Statistics
| Branch: | Revision:

root / vl.c @ 83f64091

History | View | Annotate | Download (159.5 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2005 Fabrice Bellard
5
 * 
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "vl.h"
25

    
26
#include <unistd.h>
27
#include <fcntl.h>
28
#include <signal.h>
29
#include <time.h>
30
#include <errno.h>
31
#include <sys/time.h>
32

    
33
#ifndef _WIN32
34
#include <sys/times.h>
35
#include <sys/wait.h>
36
#include <termios.h>
37
#include <sys/poll.h>
38
#include <sys/mman.h>
39
#include <sys/ioctl.h>
40
#include <sys/socket.h>
41
#include <netinet/in.h>
42
#include <dirent.h>
43
#include <netdb.h>
44
#ifdef _BSD
45
#include <sys/stat.h>
46
#ifndef __APPLE__
47
#include <libutil.h>
48
#endif
49
#else
50
#ifndef __sun__
51
#include <linux/if.h>
52
#include <linux/if_tun.h>
53
#include <pty.h>
54
#include <malloc.h>
55
#include <linux/rtc.h>
56
#include <linux/ppdev.h>
57
#endif
58
#endif
59
#endif
60

    
61
#if defined(CONFIG_SLIRP)
62
#include "libslirp.h"
63
#endif
64

    
65
#ifdef _WIN32
66
#include <malloc.h>
67
#include <sys/timeb.h>
68
#include <windows.h>
69
#define getopt_long_only getopt_long
70
#define memalign(align, size) malloc(size)
71
#endif
72

    
73
#include "qemu_socket.h"
74

    
75
#ifdef CONFIG_SDL
76
#ifdef __APPLE__
77
#include <SDL/SDL.h>
78
#endif
79
#endif /* CONFIG_SDL */
80

    
81
#ifdef CONFIG_COCOA
82
#undef main
83
#define main qemu_main
84
#endif /* CONFIG_COCOA */
85

    
86
#include "disas.h"
87

    
88
#include "exec-all.h"
89

    
90
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
91

    
92
//#define DEBUG_UNUSED_IOPORT
93
//#define DEBUG_IOPORT
94

    
95
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
96

    
97
#ifdef TARGET_PPC
98
#define DEFAULT_RAM_SIZE 144
99
#else
100
#define DEFAULT_RAM_SIZE 128
101
#endif
102
/* in ms */
103
#define GUI_REFRESH_INTERVAL 30
104

    
105
/* Max number of USB devices that can be specified on the commandline.  */
106
#define MAX_USB_CMDLINE 8
107

    
108
/* XXX: use a two level table to limit memory usage */
109
#define MAX_IOPORTS 65536
110

    
111
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
112
char phys_ram_file[1024];
113
void *ioport_opaque[MAX_IOPORTS];
114
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
115
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
116
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
117
int vga_ram_size;
118
int bios_size;
119
static DisplayState display_state;
120
int nographic;
121
const char* keyboard_layout = NULL;
122
int64_t ticks_per_sec;
123
int boot_device = 'c';
124
int ram_size;
125
int pit_min_timer_count = 0;
126
int nb_nics;
127
NICInfo nd_table[MAX_NICS];
128
QEMUTimer *gui_timer;
129
int vm_running;
130
int rtc_utc = 1;
131
int cirrus_vga_enabled = 1;
132
#ifdef TARGET_SPARC
133
int graphic_width = 1024;
134
int graphic_height = 768;
135
#else
136
int graphic_width = 800;
137
int graphic_height = 600;
138
#endif
139
int graphic_depth = 15;
140
int full_screen = 0;
141
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
142
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
143
#ifdef TARGET_I386
144
int win2k_install_hack = 0;
145
#endif
146
int usb_enabled = 0;
147
static VLANState *first_vlan;
148
int smp_cpus = 1;
149
int vnc_display = -1;
150
#if defined(TARGET_SPARC)
151
#define MAX_CPUS 16
152
#elif defined(TARGET_I386)
153
#define MAX_CPUS 255
154
#else
155
#define MAX_CPUS 1
156
#endif
157
int acpi_enabled = 1;
158
int fd_bootchk = 1;
159

    
160
/***********************************************************/
161
/* x86 ISA bus support */
162

    
163
target_phys_addr_t isa_mem_base = 0;
164
PicState2 *isa_pic;
165

    
166
uint32_t default_ioport_readb(void *opaque, uint32_t address)
167
{
168
#ifdef DEBUG_UNUSED_IOPORT
169
    fprintf(stderr, "inb: port=0x%04x\n", address);
170
#endif
171
    return 0xff;
172
}
173

    
174
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
175
{
176
#ifdef DEBUG_UNUSED_IOPORT
177
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
178
#endif
179
}
180

    
181
/* default is to make two byte accesses */
182
uint32_t default_ioport_readw(void *opaque, uint32_t address)
183
{
184
    uint32_t data;
185
    data = ioport_read_table[0][address](ioport_opaque[address], address);
186
    address = (address + 1) & (MAX_IOPORTS - 1);
187
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
188
    return data;
189
}
190

    
191
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
192
{
193
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
194
    address = (address + 1) & (MAX_IOPORTS - 1);
195
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
196
}
197

    
198
uint32_t default_ioport_readl(void *opaque, uint32_t address)
199
{
200
#ifdef DEBUG_UNUSED_IOPORT
201
    fprintf(stderr, "inl: port=0x%04x\n", address);
202
#endif
203
    return 0xffffffff;
204
}
205

    
206
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
207
{
208
#ifdef DEBUG_UNUSED_IOPORT
209
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
210
#endif
211
}
212

    
213
void init_ioports(void)
214
{
215
    int i;
216

    
217
    for(i = 0; i < MAX_IOPORTS; i++) {
218
        ioport_read_table[0][i] = default_ioport_readb;
219
        ioport_write_table[0][i] = default_ioport_writeb;
220
        ioport_read_table[1][i] = default_ioport_readw;
221
        ioport_write_table[1][i] = default_ioport_writew;
222
        ioport_read_table[2][i] = default_ioport_readl;
223
        ioport_write_table[2][i] = default_ioport_writel;
224
    }
225
}
226

    
227
/* size is the word size in byte */
228
int register_ioport_read(int start, int length, int size, 
229
                         IOPortReadFunc *func, void *opaque)
230
{
231
    int i, bsize;
232

    
233
    if (size == 1) {
234
        bsize = 0;
235
    } else if (size == 2) {
236
        bsize = 1;
237
    } else if (size == 4) {
238
        bsize = 2;
239
    } else {
240
        hw_error("register_ioport_read: invalid size");
241
        return -1;
242
    }
243
    for(i = start; i < start + length; i += size) {
244
        ioport_read_table[bsize][i] = func;
245
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
246
            hw_error("register_ioport_read: invalid opaque");
247
        ioport_opaque[i] = opaque;
248
    }
249
    return 0;
250
}
251

    
252
/* size is the word size in byte */
253
int register_ioport_write(int start, int length, int size, 
254
                          IOPortWriteFunc *func, void *opaque)
255
{
256
    int i, bsize;
257

    
258
    if (size == 1) {
259
        bsize = 0;
260
    } else if (size == 2) {
261
        bsize = 1;
262
    } else if (size == 4) {
263
        bsize = 2;
264
    } else {
265
        hw_error("register_ioport_write: invalid size");
266
        return -1;
267
    }
268
    for(i = start; i < start + length; i += size) {
269
        ioport_write_table[bsize][i] = func;
270
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
271
            hw_error("register_ioport_read: invalid opaque");
272
        ioport_opaque[i] = opaque;
273
    }
274
    return 0;
275
}
276

    
277
void isa_unassign_ioport(int start, int length)
278
{
279
    int i;
280

    
281
    for(i = start; i < start + length; i++) {
282
        ioport_read_table[0][i] = default_ioport_readb;
283
        ioport_read_table[1][i] = default_ioport_readw;
284
        ioport_read_table[2][i] = default_ioport_readl;
285

    
286
        ioport_write_table[0][i] = default_ioport_writeb;
287
        ioport_write_table[1][i] = default_ioport_writew;
288
        ioport_write_table[2][i] = default_ioport_writel;
289
    }
290
}
291

    
292
/***********************************************************/
293

    
294
void pstrcpy(char *buf, int buf_size, const char *str)
295
{
296
    int c;
297
    char *q = buf;
298

    
299
    if (buf_size <= 0)
300
        return;
301

    
302
    for(;;) {
303
        c = *str++;
304
        if (c == 0 || q >= buf + buf_size - 1)
305
            break;
306
        *q++ = c;
307
    }
308
    *q = '\0';
309
}
310

    
311
/* strcat and truncate. */
312
char *pstrcat(char *buf, int buf_size, const char *s)
313
{
314
    int len;
315
    len = strlen(buf);
316
    if (len < buf_size) 
317
        pstrcpy(buf + len, buf_size - len, s);
318
    return buf;
319
}
320

    
321
int strstart(const char *str, const char *val, const char **ptr)
322
{
323
    const char *p, *q;
324
    p = str;
325
    q = val;
326
    while (*q != '\0') {
327
        if (*p != *q)
328
            return 0;
329
        p++;
330
        q++;
331
    }
332
    if (ptr)
333
        *ptr = p;
334
    return 1;
335
}
336

    
337
void cpu_outb(CPUState *env, int addr, int val)
338
{
339
#ifdef DEBUG_IOPORT
340
    if (loglevel & CPU_LOG_IOPORT)
341
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
342
#endif    
343
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
344
#ifdef USE_KQEMU
345
    if (env)
346
        env->last_io_time = cpu_get_time_fast();
347
#endif
348
}
349

    
350
void cpu_outw(CPUState *env, int addr, int val)
351
{
352
#ifdef DEBUG_IOPORT
353
    if (loglevel & CPU_LOG_IOPORT)
354
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
355
#endif    
356
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
357
#ifdef USE_KQEMU
358
    if (env)
359
        env->last_io_time = cpu_get_time_fast();
360
#endif
361
}
362

    
363
void cpu_outl(CPUState *env, int addr, int val)
364
{
365
#ifdef DEBUG_IOPORT
366
    if (loglevel & CPU_LOG_IOPORT)
367
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
368
#endif
369
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
370
#ifdef USE_KQEMU
371
    if (env)
372
        env->last_io_time = cpu_get_time_fast();
373
#endif
374
}
375

    
376
int cpu_inb(CPUState *env, int addr)
377
{
378
    int val;
379
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
380
#ifdef DEBUG_IOPORT
381
    if (loglevel & CPU_LOG_IOPORT)
382
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
383
#endif
384
#ifdef USE_KQEMU
385
    if (env)
386
        env->last_io_time = cpu_get_time_fast();
387
#endif
388
    return val;
389
}
390

    
391
int cpu_inw(CPUState *env, int addr)
392
{
393
    int val;
394
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
395
#ifdef DEBUG_IOPORT
396
    if (loglevel & CPU_LOG_IOPORT)
397
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
398
#endif
399
#ifdef USE_KQEMU
400
    if (env)
401
        env->last_io_time = cpu_get_time_fast();
402
#endif
403
    return val;
404
}
405

    
406
int cpu_inl(CPUState *env, int addr)
407
{
408
    int val;
409
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
410
#ifdef DEBUG_IOPORT
411
    if (loglevel & CPU_LOG_IOPORT)
412
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
413
#endif
414
#ifdef USE_KQEMU
415
    if (env)
416
        env->last_io_time = cpu_get_time_fast();
417
#endif
418
    return val;
419
}
420

    
421
/***********************************************************/
422
void hw_error(const char *fmt, ...)
423
{
424
    va_list ap;
425
    CPUState *env;
426

    
427
    va_start(ap, fmt);
428
    fprintf(stderr, "qemu: hardware error: ");
429
    vfprintf(stderr, fmt, ap);
430
    fprintf(stderr, "\n");
431
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
432
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
433
#ifdef TARGET_I386
434
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
435
#else
436
        cpu_dump_state(env, stderr, fprintf, 0);
437
#endif
438
    }
439
    va_end(ap);
440
    abort();
441
}
442

    
443
/***********************************************************/
444
/* keyboard/mouse */
445

    
446
static QEMUPutKBDEvent *qemu_put_kbd_event;
447
static void *qemu_put_kbd_event_opaque;
448
static QEMUPutMouseEvent *qemu_put_mouse_event;
449
static void *qemu_put_mouse_event_opaque;
450
static int qemu_put_mouse_event_absolute;
451

    
452
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
453
{
454
    qemu_put_kbd_event_opaque = opaque;
455
    qemu_put_kbd_event = func;
456
}
457

    
458
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
459
{
460
    qemu_put_mouse_event_opaque = opaque;
461
    qemu_put_mouse_event = func;
462
    qemu_put_mouse_event_absolute = absolute;
463
}
464

    
465
void kbd_put_keycode(int keycode)
466
{
467
    if (qemu_put_kbd_event) {
468
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
469
    }
470
}
471

    
472
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
473
{
474
    if (qemu_put_mouse_event) {
475
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
476
                             dx, dy, dz, buttons_state);
477
    }
478
}
479

    
480
int kbd_mouse_is_absolute(void)
481
{
482
    return qemu_put_mouse_event_absolute;
483
}
484

    
485
/* compute with 96 bit intermediate result: (a*b)/c */
486
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
487
{
488
    union {
489
        uint64_t ll;
490
        struct {
491
#ifdef WORDS_BIGENDIAN
492
            uint32_t high, low;
493
#else
494
            uint32_t low, high;
495
#endif            
496
        } l;
497
    } u, res;
498
    uint64_t rl, rh;
499

    
500
    u.ll = a;
501
    rl = (uint64_t)u.l.low * (uint64_t)b;
502
    rh = (uint64_t)u.l.high * (uint64_t)b;
503
    rh += (rl >> 32);
504
    res.l.high = rh / c;
505
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
506
    return res.ll;
507
}
508

    
509
/***********************************************************/
510
/* real time host monotonic timer */
511

    
512
#define QEMU_TIMER_BASE 1000000000LL
513

    
514
#ifdef WIN32
515

    
516
static int64_t clock_freq;
517

    
518
static void init_get_clock(void)
519
{
520
    LARGE_INTEGER freq;
521
    int ret;
522
    ret = QueryPerformanceFrequency(&freq);
523
    if (ret == 0) {
524
        fprintf(stderr, "Could not calibrate ticks\n");
525
        exit(1);
526
    }
527
    clock_freq = freq.QuadPart;
528
}
529

    
530
static int64_t get_clock(void)
531
{
532
    LARGE_INTEGER ti;
533
    QueryPerformanceCounter(&ti);
534
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
535
}
536

    
537
#else
538

    
539
static int use_rt_clock;
540

    
541
static void init_get_clock(void)
542
{
543
    use_rt_clock = 0;
544
#if defined(__linux__)
545
    {
546
        struct timespec ts;
547
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
548
            use_rt_clock = 1;
549
        }
550
    }
551
#endif
552
}
553

    
554
static int64_t get_clock(void)
555
{
556
#if defined(__linux__)
557
    if (use_rt_clock) {
558
        struct timespec ts;
559
        clock_gettime(CLOCK_MONOTONIC, &ts);
560
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
561
    } else 
562
#endif
563
    {
564
        /* XXX: using gettimeofday leads to problems if the date
565
           changes, so it should be avoided. */
566
        struct timeval tv;
567
        gettimeofday(&tv, NULL);
568
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
569
    }
570
}
571

    
572
#endif
573

    
574
/***********************************************************/
575
/* guest cycle counter */
576

    
577
static int64_t cpu_ticks_prev;
578
static int64_t cpu_ticks_offset;
579
static int64_t cpu_clock_offset;
580
static int cpu_ticks_enabled;
581

    
582
/* return the host CPU cycle counter and handle stop/restart */
583
int64_t cpu_get_ticks(void)
584
{
585
    if (!cpu_ticks_enabled) {
586
        return cpu_ticks_offset;
587
    } else {
588
        int64_t ticks;
589
        ticks = cpu_get_real_ticks();
590
        if (cpu_ticks_prev > ticks) {
591
            /* Note: non increasing ticks may happen if the host uses
592
               software suspend */
593
            cpu_ticks_offset += cpu_ticks_prev - ticks;
594
        }
595
        cpu_ticks_prev = ticks;
596
        return ticks + cpu_ticks_offset;
597
    }
598
}
599

    
600
/* return the host CPU monotonic timer and handle stop/restart */
601
static int64_t cpu_get_clock(void)
602
{
603
    int64_t ti;
604
    if (!cpu_ticks_enabled) {
605
        return cpu_clock_offset;
606
    } else {
607
        ti = get_clock();
608
        return ti + cpu_clock_offset;
609
    }
610
}
611

    
612
/* enable cpu_get_ticks() */
613
void cpu_enable_ticks(void)
614
{
615
    if (!cpu_ticks_enabled) {
616
        cpu_ticks_offset -= cpu_get_real_ticks();
617
        cpu_clock_offset -= get_clock();
618
        cpu_ticks_enabled = 1;
619
    }
620
}
621

    
622
/* disable cpu_get_ticks() : the clock is stopped. You must not call
623
   cpu_get_ticks() after that.  */
624
void cpu_disable_ticks(void)
625
{
626
    if (cpu_ticks_enabled) {
627
        cpu_ticks_offset = cpu_get_ticks();
628
        cpu_clock_offset = cpu_get_clock();
629
        cpu_ticks_enabled = 0;
630
    }
631
}
632

    
633
/***********************************************************/
634
/* timers */
635
 
636
#define QEMU_TIMER_REALTIME 0
637
#define QEMU_TIMER_VIRTUAL  1
638

    
639
struct QEMUClock {
640
    int type;
641
    /* XXX: add frequency */
642
};
643

    
644
struct QEMUTimer {
645
    QEMUClock *clock;
646
    int64_t expire_time;
647
    QEMUTimerCB *cb;
648
    void *opaque;
649
    struct QEMUTimer *next;
650
};
651

    
652
QEMUClock *rt_clock;
653
QEMUClock *vm_clock;
654

    
655
static QEMUTimer *active_timers[2];
656
#ifdef _WIN32
657
static MMRESULT timerID;
658
static HANDLE host_alarm = NULL;
659
static unsigned int period = 1;
660
#else
661
/* frequency of the times() clock tick */
662
static int timer_freq;
663
#endif
664

    
665
QEMUClock *qemu_new_clock(int type)
666
{
667
    QEMUClock *clock;
668
    clock = qemu_mallocz(sizeof(QEMUClock));
669
    if (!clock)
670
        return NULL;
671
    clock->type = type;
672
    return clock;
673
}
674

    
675
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
676
{
677
    QEMUTimer *ts;
678

    
679
    ts = qemu_mallocz(sizeof(QEMUTimer));
680
    ts->clock = clock;
681
    ts->cb = cb;
682
    ts->opaque = opaque;
683
    return ts;
684
}
685

    
686
void qemu_free_timer(QEMUTimer *ts)
687
{
688
    qemu_free(ts);
689
}
690

    
691
/* stop a timer, but do not dealloc it */
692
void qemu_del_timer(QEMUTimer *ts)
693
{
694
    QEMUTimer **pt, *t;
695

    
696
    /* NOTE: this code must be signal safe because
697
       qemu_timer_expired() can be called from a signal. */
698
    pt = &active_timers[ts->clock->type];
699
    for(;;) {
700
        t = *pt;
701
        if (!t)
702
            break;
703
        if (t == ts) {
704
            *pt = t->next;
705
            break;
706
        }
707
        pt = &t->next;
708
    }
709
}
710

    
711
/* modify the current timer so that it will be fired when current_time
712
   >= expire_time. The corresponding callback will be called. */
713
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
714
{
715
    QEMUTimer **pt, *t;
716

    
717
    qemu_del_timer(ts);
718

    
719
    /* add the timer in the sorted list */
720
    /* NOTE: this code must be signal safe because
721
       qemu_timer_expired() can be called from a signal. */
722
    pt = &active_timers[ts->clock->type];
723
    for(;;) {
724
        t = *pt;
725
        if (!t)
726
            break;
727
        if (t->expire_time > expire_time) 
728
            break;
729
        pt = &t->next;
730
    }
731
    ts->expire_time = expire_time;
732
    ts->next = *pt;
733
    *pt = ts;
734
}
735

    
736
int qemu_timer_pending(QEMUTimer *ts)
737
{
738
    QEMUTimer *t;
739
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
740
        if (t == ts)
741
            return 1;
742
    }
743
    return 0;
744
}
745

    
746
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
747
{
748
    if (!timer_head)
749
        return 0;
750
    return (timer_head->expire_time <= current_time);
751
}
752

    
753
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
754
{
755
    QEMUTimer *ts;
756
    
757
    for(;;) {
758
        ts = *ptimer_head;
759
        if (!ts || ts->expire_time > current_time)
760
            break;
761
        /* remove timer from the list before calling the callback */
762
        *ptimer_head = ts->next;
763
        ts->next = NULL;
764
        
765
        /* run the callback (the timer list can be modified) */
766
        ts->cb(ts->opaque);
767
    }
768
}
769

    
770
int64_t qemu_get_clock(QEMUClock *clock)
771
{
772
    switch(clock->type) {
773
    case QEMU_TIMER_REALTIME:
774
        return get_clock() / 1000000;
775
    default:
776
    case QEMU_TIMER_VIRTUAL:
777
        return cpu_get_clock();
778
    }
779
}
780

    
781
static void init_timers(void)
782
{
783
    init_get_clock();
784
    ticks_per_sec = QEMU_TIMER_BASE;
785
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
786
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
787
}
788

    
789
/* save a timer */
790
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
791
{
792
    uint64_t expire_time;
793

    
794
    if (qemu_timer_pending(ts)) {
795
        expire_time = ts->expire_time;
796
    } else {
797
        expire_time = -1;
798
    }
799
    qemu_put_be64(f, expire_time);
800
}
801

    
802
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
803
{
804
    uint64_t expire_time;
805

    
806
    expire_time = qemu_get_be64(f);
807
    if (expire_time != -1) {
808
        qemu_mod_timer(ts, expire_time);
809
    } else {
810
        qemu_del_timer(ts);
811
    }
812
}
813

    
814
static void timer_save(QEMUFile *f, void *opaque)
815
{
816
    if (cpu_ticks_enabled) {
817
        hw_error("cannot save state if virtual timers are running");
818
    }
819
    qemu_put_be64s(f, &cpu_ticks_offset);
820
    qemu_put_be64s(f, &ticks_per_sec);
821
}
822

    
823
static int timer_load(QEMUFile *f, void *opaque, int version_id)
824
{
825
    if (version_id != 1)
826
        return -EINVAL;
827
    if (cpu_ticks_enabled) {
828
        return -EINVAL;
829
    }
830
    qemu_get_be64s(f, &cpu_ticks_offset);
831
    qemu_get_be64s(f, &ticks_per_sec);
832
    return 0;
833
}
834

    
835
#ifdef _WIN32
836
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
837
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
838
#else
839
static void host_alarm_handler(int host_signum)
840
#endif
841
{
842
#if 0
843
#define DISP_FREQ 1000
844
    {
845
        static int64_t delta_min = INT64_MAX;
846
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
847
        static int count;
848
        ti = qemu_get_clock(vm_clock);
849
        if (last_clock != 0) {
850
            delta = ti - last_clock;
851
            if (delta < delta_min)
852
                delta_min = delta;
853
            if (delta > delta_max)
854
                delta_max = delta;
855
            delta_cum += delta;
856
            if (++count == DISP_FREQ) {
857
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
858
                       muldiv64(delta_min, 1000000, ticks_per_sec),
859
                       muldiv64(delta_max, 1000000, ticks_per_sec),
860
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
861
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
862
                count = 0;
863
                delta_min = INT64_MAX;
864
                delta_max = 0;
865
                delta_cum = 0;
866
            }
867
        }
868
        last_clock = ti;
869
    }
870
#endif
871
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
872
                           qemu_get_clock(vm_clock)) ||
873
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
874
                           qemu_get_clock(rt_clock))) {
875
#ifdef _WIN32
876
        SetEvent(host_alarm);
877
#endif
878
        CPUState *env = cpu_single_env;
879
        if (env) {
880
            /* stop the currently executing cpu because a timer occured */
881
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
882
#ifdef USE_KQEMU
883
            if (env->kqemu_enabled) {
884
                kqemu_cpu_interrupt(env);
885
            }
886
#endif
887
        }
888
    }
889
}
890

    
891
#ifndef _WIN32
892

    
893
#if defined(__linux__)
894

    
895
#define RTC_FREQ 1024
896

    
897
static int rtc_fd;
898

    
899
static int start_rtc_timer(void)
900
{
901
    rtc_fd = open("/dev/rtc", O_RDONLY);
902
    if (rtc_fd < 0)
903
        return -1;
904
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
905
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
906
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
907
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
908
        goto fail;
909
    }
910
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
911
    fail:
912
        close(rtc_fd);
913
        return -1;
914
    }
915
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
916
    return 0;
917
}
918

    
919
#else
920

    
921
static int start_rtc_timer(void)
922
{
923
    return -1;
924
}
925

    
926
#endif /* !defined(__linux__) */
927

    
928
#endif /* !defined(_WIN32) */
929

    
930
static void init_timer_alarm(void)
931
{
932
#ifdef _WIN32
933
    {
934
        int count=0;
935
        TIMECAPS tc;
936

    
937
        ZeroMemory(&tc, sizeof(TIMECAPS));
938
        timeGetDevCaps(&tc, sizeof(TIMECAPS));
939
        if (period < tc.wPeriodMin)
940
            period = tc.wPeriodMin;
941
        timeBeginPeriod(period);
942
        timerID = timeSetEvent(1,     // interval (ms)
943
                               period,     // resolution
944
                               host_alarm_handler, // function
945
                               (DWORD)&count,  // user parameter
946
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
947
         if( !timerID ) {
948
            perror("failed timer alarm");
949
            exit(1);
950
         }
951
        host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
952
        if (!host_alarm) {
953
            perror("failed CreateEvent");
954
            exit(1);
955
        }
956
        qemu_add_wait_object(host_alarm, NULL, NULL);
957
    }
958
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
959
#else
960
    {
961
        struct sigaction act;
962
        struct itimerval itv;
963
        
964
        /* get times() syscall frequency */
965
        timer_freq = sysconf(_SC_CLK_TCK);
966
        
967
        /* timer signal */
968
        sigfillset(&act.sa_mask);
969
       act.sa_flags = 0;
970
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
971
        act.sa_flags |= SA_ONSTACK;
972
#endif
973
        act.sa_handler = host_alarm_handler;
974
        sigaction(SIGALRM, &act, NULL);
975

    
976
        itv.it_interval.tv_sec = 0;
977
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
978
        itv.it_value.tv_sec = 0;
979
        itv.it_value.tv_usec = 10 * 1000;
980
        setitimer(ITIMER_REAL, &itv, NULL);
981
        /* we probe the tick duration of the kernel to inform the user if
982
           the emulated kernel requested a too high timer frequency */
983
        getitimer(ITIMER_REAL, &itv);
984

    
985
#if defined(__linux__)
986
        /* XXX: force /dev/rtc usage because even 2.6 kernels may not
987
           have timers with 1 ms resolution. The correct solution will
988
           be to use the POSIX real time timers available in recent
989
           2.6 kernels */
990
        if (itv.it_interval.tv_usec > 1000 || 1) {
991
            /* try to use /dev/rtc to have a faster timer */
992
            if (start_rtc_timer() < 0)
993
                goto use_itimer;
994
            /* disable itimer */
995
            itv.it_interval.tv_sec = 0;
996
            itv.it_interval.tv_usec = 0;
997
            itv.it_value.tv_sec = 0;
998
            itv.it_value.tv_usec = 0;
999
            setitimer(ITIMER_REAL, &itv, NULL);
1000

    
1001
            /* use the RTC */
1002
            sigaction(SIGIO, &act, NULL);
1003
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1004
            fcntl(rtc_fd, F_SETOWN, getpid());
1005
        } else 
1006
#endif /* defined(__linux__) */
1007
        {
1008
        use_itimer:
1009
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1010
                                   PIT_FREQ) / 1000000;
1011
        }
1012
    }
1013
#endif
1014
}
1015

    
1016
void quit_timers(void)
1017
{
1018
#ifdef _WIN32
1019
    timeKillEvent(timerID);
1020
    timeEndPeriod(period);
1021
    if (host_alarm) {
1022
        CloseHandle(host_alarm);
1023
        host_alarm = NULL;
1024
    }
1025
#endif
1026
}
1027

    
1028
/***********************************************************/
1029
/* character device */
1030

    
1031
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1032
{
1033
    return s->chr_write(s, buf, len);
1034
}
1035

    
1036
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1037
{
1038
    if (!s->chr_ioctl)
1039
        return -ENOTSUP;
1040
    return s->chr_ioctl(s, cmd, arg);
1041
}
1042

    
1043
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1044
{
1045
    char buf[4096];
1046
    va_list ap;
1047
    va_start(ap, fmt);
1048
    vsnprintf(buf, sizeof(buf), fmt, ap);
1049
    qemu_chr_write(s, buf, strlen(buf));
1050
    va_end(ap);
1051
}
1052

    
1053
void qemu_chr_send_event(CharDriverState *s, int event)
1054
{
1055
    if (s->chr_send_event)
1056
        s->chr_send_event(s, event);
1057
}
1058

    
1059
void qemu_chr_add_read_handler(CharDriverState *s, 
1060
                               IOCanRWHandler *fd_can_read, 
1061
                               IOReadHandler *fd_read, void *opaque)
1062
{
1063
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1064
}
1065
             
1066
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1067
{
1068
    s->chr_event = chr_event;
1069
}
1070

    
1071
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1072
{
1073
    return len;
1074
}
1075

    
1076
static void null_chr_add_read_handler(CharDriverState *chr, 
1077
                                    IOCanRWHandler *fd_can_read, 
1078
                                    IOReadHandler *fd_read, void *opaque)
1079
{
1080
}
1081

    
1082
CharDriverState *qemu_chr_open_null(void)
1083
{
1084
    CharDriverState *chr;
1085

    
1086
    chr = qemu_mallocz(sizeof(CharDriverState));
1087
    if (!chr)
1088
        return NULL;
1089
    chr->chr_write = null_chr_write;
1090
    chr->chr_add_read_handler = null_chr_add_read_handler;
1091
    return chr;
1092
}
1093

    
1094
#ifdef _WIN32
1095

    
1096
static void socket_cleanup(void)
1097
{
1098
    WSACleanup();
1099
}
1100

    
1101
static int socket_init(void)
1102
{
1103
    WSADATA Data;
1104
    int ret, err;
1105

    
1106
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1107
    if (ret != 0) {
1108
        err = WSAGetLastError();
1109
        fprintf(stderr, "WSAStartup: %d\n", err);
1110
        return -1;
1111
    }
1112
    atexit(socket_cleanup);
1113
    return 0;
1114
}
1115

    
1116
static int send_all(int fd, const uint8_t *buf, int len1)
1117
{
1118
    int ret, len;
1119
    
1120
    len = len1;
1121
    while (len > 0) {
1122
        ret = send(fd, buf, len, 0);
1123
        if (ret < 0) {
1124
            int errno;
1125
            errno = WSAGetLastError();
1126
            if (errno != WSAEWOULDBLOCK) {
1127
                return -1;
1128
            }
1129
        } else if (ret == 0) {
1130
            break;
1131
        } else {
1132
            buf += ret;
1133
            len -= ret;
1134
        }
1135
    }
1136
    return len1 - len;
1137
}
1138

    
1139
void socket_set_nonblock(int fd)
1140
{
1141
    unsigned long opt = 1;
1142
    ioctlsocket(fd, FIONBIO, &opt);
1143
}
1144

    
1145
#else
1146

    
1147
static int unix_write(int fd, const uint8_t *buf, int len1)
1148
{
1149
    int ret, len;
1150

    
1151
    len = len1;
1152
    while (len > 0) {
1153
        ret = write(fd, buf, len);
1154
        if (ret < 0) {
1155
            if (errno != EINTR && errno != EAGAIN)
1156
                return -1;
1157
        } else if (ret == 0) {
1158
            break;
1159
        } else {
1160
            buf += ret;
1161
            len -= ret;
1162
        }
1163
    }
1164
    return len1 - len;
1165
}
1166

    
1167
static inline int send_all(int fd, const uint8_t *buf, int len1)
1168
{
1169
    return unix_write(fd, buf, len1);
1170
}
1171

    
1172
void socket_set_nonblock(int fd)
1173
{
1174
    fcntl(fd, F_SETFL, O_NONBLOCK);
1175
}
1176
#endif /* !_WIN32 */
1177

    
1178
#ifndef _WIN32
1179

    
1180
typedef struct {
1181
    int fd_in, fd_out;
1182
    IOCanRWHandler *fd_can_read; 
1183
    IOReadHandler *fd_read;
1184
    void *fd_opaque;
1185
    int max_size;
1186
} FDCharDriver;
1187

    
1188
#define STDIO_MAX_CLIENTS 2
1189

    
1190
static int stdio_nb_clients;
1191
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1192

    
1193
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1194
{
1195
    FDCharDriver *s = chr->opaque;
1196
    return unix_write(s->fd_out, buf, len);
1197
}
1198

    
1199
static int fd_chr_read_poll(void *opaque)
1200
{
1201
    CharDriverState *chr = opaque;
1202
    FDCharDriver *s = chr->opaque;
1203

    
1204
    s->max_size = s->fd_can_read(s->fd_opaque);
1205
    return s->max_size;
1206
}
1207

    
1208
static void fd_chr_read(void *opaque)
1209
{
1210
    CharDriverState *chr = opaque;
1211
    FDCharDriver *s = chr->opaque;
1212
    int size, len;
1213
    uint8_t buf[1024];
1214
    
1215
    len = sizeof(buf);
1216
    if (len > s->max_size)
1217
        len = s->max_size;
1218
    if (len == 0)
1219
        return;
1220
    size = read(s->fd_in, buf, len);
1221
    if (size > 0) {
1222
        s->fd_read(s->fd_opaque, buf, size);
1223
    }
1224
}
1225

    
1226
static void fd_chr_add_read_handler(CharDriverState *chr, 
1227
                                    IOCanRWHandler *fd_can_read, 
1228
                                    IOReadHandler *fd_read, void *opaque)
1229
{
1230
    FDCharDriver *s = chr->opaque;
1231

    
1232
    if (s->fd_in >= 0) {
1233
        s->fd_can_read = fd_can_read;
1234
        s->fd_read = fd_read;
1235
        s->fd_opaque = opaque;
1236
        if (nographic && s->fd_in == 0) {
1237
        } else {
1238
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1239
                                 fd_chr_read, NULL, chr);
1240
        }
1241
    }
1242
}
1243

    
1244
/* open a character device to a unix fd */
1245
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1246
{
1247
    CharDriverState *chr;
1248
    FDCharDriver *s;
1249

    
1250
    chr = qemu_mallocz(sizeof(CharDriverState));
1251
    if (!chr)
1252
        return NULL;
1253
    s = qemu_mallocz(sizeof(FDCharDriver));
1254
    if (!s) {
1255
        free(chr);
1256
        return NULL;
1257
    }
1258
    s->fd_in = fd_in;
1259
    s->fd_out = fd_out;
1260
    chr->opaque = s;
1261
    chr->chr_write = fd_chr_write;
1262
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1263
    return chr;
1264
}
1265

    
1266
CharDriverState *qemu_chr_open_file_out(const char *file_out)
1267
{
1268
    int fd_out;
1269

    
1270
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1271
    if (fd_out < 0)
1272
        return NULL;
1273
    return qemu_chr_open_fd(-1, fd_out);
1274
}
1275

    
1276
CharDriverState *qemu_chr_open_pipe(const char *filename)
1277
{
1278
    int fd;
1279

    
1280
    fd = open(filename, O_RDWR | O_BINARY);
1281
    if (fd < 0)
1282
        return NULL;
1283
    return qemu_chr_open_fd(fd, fd);
1284
}
1285

    
1286

    
1287
/* for STDIO, we handle the case where several clients use it
1288
   (nographic mode) */
1289

    
1290
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1291

    
1292
#define TERM_FIFO_MAX_SIZE 1
1293

    
1294
static int term_got_escape, client_index;
1295
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1296
static int term_fifo_size;
1297
static int term_timestamps;
1298
static int64_t term_timestamps_start;
1299

    
1300
void term_print_help(void)
1301
{
1302
    printf("\n"
1303
           "C-a h    print this help\n"
1304
           "C-a x    exit emulator\n"
1305
           "C-a s    save disk data back to file (if -snapshot)\n"
1306
           "C-a b    send break (magic sysrq)\n"
1307
           "C-a t    toggle console timestamps\n"
1308
           "C-a c    switch between console and monitor\n"
1309
           "C-a C-a  send C-a\n"
1310
           );
1311
}
1312

    
1313
/* called when a char is received */
1314
static void stdio_received_byte(int ch)
1315
{
1316
    if (term_got_escape) {
1317
        term_got_escape = 0;
1318
        switch(ch) {
1319
        case 'h':
1320
            term_print_help();
1321
            break;
1322
        case 'x':
1323
            exit(0);
1324
            break;
1325
        case 's': 
1326
            {
1327
                int i;
1328
                for (i = 0; i < MAX_DISKS; i++) {
1329
                    if (bs_table[i])
1330
                        bdrv_commit(bs_table[i]);
1331
                }
1332
            }
1333
            break;
1334
        case 'b':
1335
            if (client_index < stdio_nb_clients) {
1336
                CharDriverState *chr;
1337
                FDCharDriver *s;
1338

    
1339
                chr = stdio_clients[client_index];
1340
                s = chr->opaque;
1341
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1342
            }
1343
            break;
1344
        case 'c':
1345
            client_index++;
1346
            if (client_index >= stdio_nb_clients)
1347
                client_index = 0;
1348
            if (client_index == 0) {
1349
                /* send a new line in the monitor to get the prompt */
1350
                ch = '\r';
1351
                goto send_char;
1352
            }
1353
            break;
1354
        case 't':
1355
            term_timestamps = !term_timestamps;
1356
            term_timestamps_start = -1;
1357
            break;
1358
        case TERM_ESCAPE:
1359
            goto send_char;
1360
        }
1361
    } else if (ch == TERM_ESCAPE) {
1362
        term_got_escape = 1;
1363
    } else {
1364
    send_char:
1365
        if (client_index < stdio_nb_clients) {
1366
            uint8_t buf[1];
1367
            CharDriverState *chr;
1368
            FDCharDriver *s;
1369
            
1370
            chr = stdio_clients[client_index];
1371
            s = chr->opaque;
1372
            if (s->fd_can_read(s->fd_opaque) > 0) {
1373
                buf[0] = ch;
1374
                s->fd_read(s->fd_opaque, buf, 1);
1375
            } else if (term_fifo_size == 0) {
1376
                term_fifo[term_fifo_size++] = ch;
1377
            }
1378
        }
1379
    }
1380
}
1381

    
1382
static int stdio_read_poll(void *opaque)
1383
{
1384
    CharDriverState *chr;
1385
    FDCharDriver *s;
1386

    
1387
    if (client_index < stdio_nb_clients) {
1388
        chr = stdio_clients[client_index];
1389
        s = chr->opaque;
1390
        /* try to flush the queue if needed */
1391
        if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1392
            s->fd_read(s->fd_opaque, term_fifo, 1);
1393
            term_fifo_size = 0;
1394
        }
1395
        /* see if we can absorb more chars */
1396
        if (term_fifo_size == 0)
1397
            return 1;
1398
        else
1399
            return 0;
1400
    } else {
1401
        return 1;
1402
    }
1403
}
1404

    
1405
static void stdio_read(void *opaque)
1406
{
1407
    int size;
1408
    uint8_t buf[1];
1409
    
1410
    size = read(0, buf, 1);
1411
    if (size > 0)
1412
        stdio_received_byte(buf[0]);
1413
}
1414

    
1415
static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1416
{
1417
    FDCharDriver *s = chr->opaque;
1418
    if (!term_timestamps) {
1419
        return unix_write(s->fd_out, buf, len);
1420
    } else {
1421
        int i;
1422
        char buf1[64];
1423

    
1424
        for(i = 0; i < len; i++) {
1425
            unix_write(s->fd_out, buf + i, 1);
1426
            if (buf[i] == '\n') {
1427
                int64_t ti;
1428
                int secs;
1429

    
1430
                ti = get_clock();
1431
                if (term_timestamps_start == -1)
1432
                    term_timestamps_start = ti;
1433
                ti -= term_timestamps_start;
1434
                secs = ti / 1000000000;
1435
                snprintf(buf1, sizeof(buf1), 
1436
                         "[%02d:%02d:%02d.%03d] ",
1437
                         secs / 3600,
1438
                         (secs / 60) % 60,
1439
                         secs % 60,
1440
                         (int)((ti / 1000000) % 1000));
1441
                unix_write(s->fd_out, buf1, strlen(buf1));
1442
            }
1443
        }
1444
        return len;
1445
    }
1446
}
1447

    
1448
/* init terminal so that we can grab keys */
1449
static struct termios oldtty;
1450
static int old_fd0_flags;
1451

    
1452
static void term_exit(void)
1453
{
1454
    tcsetattr (0, TCSANOW, &oldtty);
1455
    fcntl(0, F_SETFL, old_fd0_flags);
1456
}
1457

    
1458
static void term_init(void)
1459
{
1460
    struct termios tty;
1461

    
1462
    tcgetattr (0, &tty);
1463
    oldtty = tty;
1464
    old_fd0_flags = fcntl(0, F_GETFL);
1465

    
1466
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1467
                          |INLCR|IGNCR|ICRNL|IXON);
1468
    tty.c_oflag |= OPOST;
1469
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1470
    /* if graphical mode, we allow Ctrl-C handling */
1471
    if (nographic)
1472
        tty.c_lflag &= ~ISIG;
1473
    tty.c_cflag &= ~(CSIZE|PARENB);
1474
    tty.c_cflag |= CS8;
1475
    tty.c_cc[VMIN] = 1;
1476
    tty.c_cc[VTIME] = 0;
1477
    
1478
    tcsetattr (0, TCSANOW, &tty);
1479

    
1480
    atexit(term_exit);
1481

    
1482
    fcntl(0, F_SETFL, O_NONBLOCK);
1483
}
1484

    
1485
CharDriverState *qemu_chr_open_stdio(void)
1486
{
1487
    CharDriverState *chr;
1488

    
1489
    if (nographic) {
1490
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1491
            return NULL;
1492
        chr = qemu_chr_open_fd(0, 1);
1493
        chr->chr_write = stdio_write;
1494
        if (stdio_nb_clients == 0)
1495
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1496
        client_index = stdio_nb_clients;
1497
    } else {
1498
        if (stdio_nb_clients != 0)
1499
            return NULL;
1500
        chr = qemu_chr_open_fd(0, 1);
1501
    }
1502
    stdio_clients[stdio_nb_clients++] = chr;
1503
    if (stdio_nb_clients == 1) {
1504
        /* set the terminal in raw mode */
1505
        term_init();
1506
    }
1507
    return chr;
1508
}
1509

    
1510
#if defined(__linux__)
1511
CharDriverState *qemu_chr_open_pty(void)
1512
{
1513
    struct termios tty;
1514
    char slave_name[1024];
1515
    int master_fd, slave_fd;
1516
    
1517
    /* Not satisfying */
1518
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1519
        return NULL;
1520
    }
1521
    
1522
    /* Disabling local echo and line-buffered output */
1523
    tcgetattr (master_fd, &tty);
1524
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1525
    tty.c_cc[VMIN] = 1;
1526
    tty.c_cc[VTIME] = 0;
1527
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1528

    
1529
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1530
    return qemu_chr_open_fd(master_fd, master_fd);
1531
}
1532

    
1533
static void tty_serial_init(int fd, int speed, 
1534
                            int parity, int data_bits, int stop_bits)
1535
{
1536
    struct termios tty;
1537
    speed_t spd;
1538

    
1539
#if 0
1540
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1541
           speed, parity, data_bits, stop_bits);
1542
#endif
1543
    tcgetattr (fd, &tty);
1544

    
1545
    switch(speed) {
1546
    case 50:
1547
        spd = B50;
1548
        break;
1549
    case 75:
1550
        spd = B75;
1551
        break;
1552
    case 300:
1553
        spd = B300;
1554
        break;
1555
    case 600:
1556
        spd = B600;
1557
        break;
1558
    case 1200:
1559
        spd = B1200;
1560
        break;
1561
    case 2400:
1562
        spd = B2400;
1563
        break;
1564
    case 4800:
1565
        spd = B4800;
1566
        break;
1567
    case 9600:
1568
        spd = B9600;
1569
        break;
1570
    case 19200:
1571
        spd = B19200;
1572
        break;
1573
    case 38400:
1574
        spd = B38400;
1575
        break;
1576
    case 57600:
1577
        spd = B57600;
1578
        break;
1579
    default:
1580
    case 115200:
1581
        spd = B115200;
1582
        break;
1583
    }
1584

    
1585
    cfsetispeed(&tty, spd);
1586
    cfsetospeed(&tty, spd);
1587

    
1588
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1589
                          |INLCR|IGNCR|ICRNL|IXON);
1590
    tty.c_oflag |= OPOST;
1591
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1592
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1593
    switch(data_bits) {
1594
    default:
1595
    case 8:
1596
        tty.c_cflag |= CS8;
1597
        break;
1598
    case 7:
1599
        tty.c_cflag |= CS7;
1600
        break;
1601
    case 6:
1602
        tty.c_cflag |= CS6;
1603
        break;
1604
    case 5:
1605
        tty.c_cflag |= CS5;
1606
        break;
1607
    }
1608
    switch(parity) {
1609
    default:
1610
    case 'N':
1611
        break;
1612
    case 'E':
1613
        tty.c_cflag |= PARENB;
1614
        break;
1615
    case 'O':
1616
        tty.c_cflag |= PARENB | PARODD;
1617
        break;
1618
    }
1619
    
1620
    tcsetattr (fd, TCSANOW, &tty);
1621
}
1622

    
1623
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1624
{
1625
    FDCharDriver *s = chr->opaque;
1626
    
1627
    switch(cmd) {
1628
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1629
        {
1630
            QEMUSerialSetParams *ssp = arg;
1631
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1632
                            ssp->data_bits, ssp->stop_bits);
1633
        }
1634
        break;
1635
    case CHR_IOCTL_SERIAL_SET_BREAK:
1636
        {
1637
            int enable = *(int *)arg;
1638
            if (enable)
1639
                tcsendbreak(s->fd_in, 1);
1640
        }
1641
        break;
1642
    default:
1643
        return -ENOTSUP;
1644
    }
1645
    return 0;
1646
}
1647

    
1648
CharDriverState *qemu_chr_open_tty(const char *filename)
1649
{
1650
    CharDriverState *chr;
1651
    int fd;
1652

    
1653
    fd = open(filename, O_RDWR | O_NONBLOCK);
1654
    if (fd < 0)
1655
        return NULL;
1656
    fcntl(fd, F_SETFL, O_NONBLOCK);
1657
    tty_serial_init(fd, 115200, 'N', 8, 1);
1658
    chr = qemu_chr_open_fd(fd, fd);
1659
    if (!chr)
1660
        return NULL;
1661
    chr->chr_ioctl = tty_serial_ioctl;
1662
    return chr;
1663
}
1664

    
1665
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1666
{
1667
    int fd = (int)chr->opaque;
1668
    uint8_t b;
1669

    
1670
    switch(cmd) {
1671
    case CHR_IOCTL_PP_READ_DATA:
1672
        if (ioctl(fd, PPRDATA, &b) < 0)
1673
            return -ENOTSUP;
1674
        *(uint8_t *)arg = b;
1675
        break;
1676
    case CHR_IOCTL_PP_WRITE_DATA:
1677
        b = *(uint8_t *)arg;
1678
        if (ioctl(fd, PPWDATA, &b) < 0)
1679
            return -ENOTSUP;
1680
        break;
1681
    case CHR_IOCTL_PP_READ_CONTROL:
1682
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1683
            return -ENOTSUP;
1684
        *(uint8_t *)arg = b;
1685
        break;
1686
    case CHR_IOCTL_PP_WRITE_CONTROL:
1687
        b = *(uint8_t *)arg;
1688
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1689
            return -ENOTSUP;
1690
        break;
1691
    case CHR_IOCTL_PP_READ_STATUS:
1692
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1693
            return -ENOTSUP;
1694
        *(uint8_t *)arg = b;
1695
        break;
1696
    default:
1697
        return -ENOTSUP;
1698
    }
1699
    return 0;
1700
}
1701

    
1702
CharDriverState *qemu_chr_open_pp(const char *filename)
1703
{
1704
    CharDriverState *chr;
1705
    int fd;
1706

    
1707
    fd = open(filename, O_RDWR);
1708
    if (fd < 0)
1709
        return NULL;
1710

    
1711
    if (ioctl(fd, PPCLAIM) < 0) {
1712
        close(fd);
1713
        return NULL;
1714
    }
1715

    
1716
    chr = qemu_mallocz(sizeof(CharDriverState));
1717
    if (!chr) {
1718
        close(fd);
1719
        return NULL;
1720
    }
1721
    chr->opaque = (void *)fd;
1722
    chr->chr_write = null_chr_write;
1723
    chr->chr_add_read_handler = null_chr_add_read_handler;
1724
    chr->chr_ioctl = pp_ioctl;
1725
    return chr;
1726
}
1727

    
1728
#else
1729
CharDriverState *qemu_chr_open_pty(void)
1730
{
1731
    return NULL;
1732
}
1733
#endif
1734

    
1735
#endif /* !defined(_WIN32) */
1736

    
1737
#ifdef _WIN32
1738
typedef struct {
1739
    IOCanRWHandler *fd_can_read; 
1740
    IOReadHandler *fd_read;
1741
    void *win_opaque;
1742
    int max_size;
1743
    HANDLE hcom, hrecv, hsend;
1744
    OVERLAPPED orecv, osend;
1745
    BOOL fpipe;
1746
    DWORD len;
1747
} WinCharState;
1748

    
1749
#define NSENDBUF 2048
1750
#define NRECVBUF 2048
1751
#define MAXCONNECT 1
1752
#define NTIMEOUT 5000
1753

    
1754
static int win_chr_poll(void *opaque);
1755
static int win_chr_pipe_poll(void *opaque);
1756

    
1757
static void win_chr_close2(WinCharState *s)
1758
{
1759
    if (s->hsend) {
1760
        CloseHandle(s->hsend);
1761
        s->hsend = NULL;
1762
    }
1763
    if (s->hrecv) {
1764
        CloseHandle(s->hrecv);
1765
        s->hrecv = NULL;
1766
    }
1767
    if (s->hcom) {
1768
        CloseHandle(s->hcom);
1769
        s->hcom = NULL;
1770
    }
1771
    if (s->fpipe)
1772
        qemu_del_polling_cb(win_chr_pipe_poll, s);
1773
    else
1774
        qemu_del_polling_cb(win_chr_poll, s);
1775
}
1776

    
1777
static void win_chr_close(CharDriverState *chr)
1778
{
1779
    WinCharState *s = chr->opaque;
1780
    win_chr_close2(s);
1781
}
1782

    
1783
static int win_chr_init(WinCharState *s, const char *filename)
1784
{
1785
    COMMCONFIG comcfg;
1786
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1787
    COMSTAT comstat;
1788
    DWORD size;
1789
    DWORD err;
1790
    
1791
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1792
    if (!s->hsend) {
1793
        fprintf(stderr, "Failed CreateEvent\n");
1794
        goto fail;
1795
    }
1796
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1797
    if (!s->hrecv) {
1798
        fprintf(stderr, "Failed CreateEvent\n");
1799
        goto fail;
1800
    }
1801

    
1802
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1803
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1804
    if (s->hcom == INVALID_HANDLE_VALUE) {
1805
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1806
        s->hcom = NULL;
1807
        goto fail;
1808
    }
1809
    
1810
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1811
        fprintf(stderr, "Failed SetupComm\n");
1812
        goto fail;
1813
    }
1814
    
1815
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1816
    size = sizeof(COMMCONFIG);
1817
    GetDefaultCommConfig(filename, &comcfg, &size);
1818
    comcfg.dcb.DCBlength = sizeof(DCB);
1819
    CommConfigDialog(filename, NULL, &comcfg);
1820

    
1821
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1822
        fprintf(stderr, "Failed SetCommState\n");
1823
        goto fail;
1824
    }
1825

    
1826
    if (!SetCommMask(s->hcom, EV_ERR)) {
1827
        fprintf(stderr, "Failed SetCommMask\n");
1828
        goto fail;
1829
    }
1830

    
1831
    cto.ReadIntervalTimeout = MAXDWORD;
1832
    if (!SetCommTimeouts(s->hcom, &cto)) {
1833
        fprintf(stderr, "Failed SetCommTimeouts\n");
1834
        goto fail;
1835
    }
1836
    
1837
    if (!ClearCommError(s->hcom, &err, &comstat)) {
1838
        fprintf(stderr, "Failed ClearCommError\n");
1839
        goto fail;
1840
    }
1841
    qemu_add_polling_cb(win_chr_poll, s);
1842
    return 0;
1843

    
1844
 fail:
1845
    win_chr_close2(s);
1846
    return -1;
1847
}
1848

    
1849
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1850
{
1851
    WinCharState *s = chr->opaque;
1852
    DWORD len, ret, size, err;
1853

    
1854
    len = len1;
1855
    ZeroMemory(&s->osend, sizeof(s->osend));
1856
    s->osend.hEvent = s->hsend;
1857
    while (len > 0) {
1858
        if (s->hsend)
1859
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1860
        else
1861
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1862
        if (!ret) {
1863
            err = GetLastError();
1864
            if (err == ERROR_IO_PENDING) {
1865
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1866
                if (ret) {
1867
                    buf += size;
1868
                    len -= size;
1869
                } else {
1870
                    break;
1871
                }
1872
            } else {
1873
                break;
1874
            }
1875
        } else {
1876
            buf += size;
1877
            len -= size;
1878
        }
1879
    }
1880
    return len1 - len;
1881
}
1882

    
1883
static int win_chr_read_poll(WinCharState *s)
1884
{
1885
    s->max_size = s->fd_can_read(s->win_opaque);
1886
    return s->max_size;
1887
}
1888
            
1889
static void win_chr_readfile(WinCharState *s)
1890
{
1891
    int ret, err;
1892
    uint8_t buf[1024];
1893
    DWORD size;
1894
    
1895
    ZeroMemory(&s->orecv, sizeof(s->orecv));
1896
    s->orecv.hEvent = s->hrecv;
1897
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1898
    if (!ret) {
1899
        err = GetLastError();
1900
        if (err == ERROR_IO_PENDING) {
1901
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1902
        }
1903
    }
1904

    
1905
    if (size > 0) {
1906
        s->fd_read(s->win_opaque, buf, size);
1907
    }
1908
}
1909

    
1910
static void win_chr_read(WinCharState *s)
1911
{
1912
    if (s->len > s->max_size)
1913
        s->len = s->max_size;
1914
    if (s->len == 0)
1915
        return;
1916
    
1917
    win_chr_readfile(s);
1918
}
1919

    
1920
static int win_chr_poll(void *opaque)
1921
{
1922
    WinCharState *s = opaque;
1923
    COMSTAT status;
1924
    DWORD comerr;
1925
    
1926
    ClearCommError(s->hcom, &comerr, &status);
1927
    if (status.cbInQue > 0) {
1928
        s->len = status.cbInQue;
1929
        win_chr_read_poll(s);
1930
        win_chr_read(s);
1931
        return 1;
1932
    }
1933
    return 0;
1934
}
1935

    
1936
static void win_chr_add_read_handler(CharDriverState *chr, 
1937
                                    IOCanRWHandler *fd_can_read, 
1938
                                    IOReadHandler *fd_read, void *opaque)
1939
{
1940
    WinCharState *s = chr->opaque;
1941

    
1942
    s->fd_can_read = fd_can_read;
1943
    s->fd_read = fd_read;
1944
    s->win_opaque = opaque;
1945
}
1946

    
1947
CharDriverState *qemu_chr_open_win(const char *filename)
1948
{
1949
    CharDriverState *chr;
1950
    WinCharState *s;
1951
    
1952
    chr = qemu_mallocz(sizeof(CharDriverState));
1953
    if (!chr)
1954
        return NULL;
1955
    s = qemu_mallocz(sizeof(WinCharState));
1956
    if (!s) {
1957
        free(chr);
1958
        return NULL;
1959
    }
1960
    chr->opaque = s;
1961
    chr->chr_write = win_chr_write;
1962
    chr->chr_add_read_handler = win_chr_add_read_handler;
1963
    chr->chr_close = win_chr_close;
1964

    
1965
    if (win_chr_init(s, filename) < 0) {
1966
        free(s);
1967
        free(chr);
1968
        return NULL;
1969
    }
1970
    return chr;
1971
}
1972

    
1973
static int win_chr_pipe_poll(void *opaque)
1974
{
1975
    WinCharState *s = opaque;
1976
    DWORD size;
1977

    
1978
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1979
    if (size > 0) {
1980
        s->len = size;
1981
        win_chr_read_poll(s);
1982
        win_chr_read(s);
1983
        return 1;
1984
    }
1985
    return 0;
1986
}
1987

    
1988
static int win_chr_pipe_init(WinCharState *s, const char *filename)
1989
{
1990
    OVERLAPPED ov;
1991
    int ret;
1992
    DWORD size;
1993
    char openname[256];
1994
    
1995
    s->fpipe = TRUE;
1996

    
1997
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1998
    if (!s->hsend) {
1999
        fprintf(stderr, "Failed CreateEvent\n");
2000
        goto fail;
2001
    }
2002
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2003
    if (!s->hrecv) {
2004
        fprintf(stderr, "Failed CreateEvent\n");
2005
        goto fail;
2006
    }
2007
    
2008
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2009
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2010
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2011
                              PIPE_WAIT,
2012
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2013
    if (s->hcom == INVALID_HANDLE_VALUE) {
2014
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2015
        s->hcom = NULL;
2016
        goto fail;
2017
    }
2018

    
2019
    ZeroMemory(&ov, sizeof(ov));
2020
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2021
    ret = ConnectNamedPipe(s->hcom, &ov);
2022
    if (ret) {
2023
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2024
        goto fail;
2025
    }
2026

    
2027
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2028
    if (!ret) {
2029
        fprintf(stderr, "Failed GetOverlappedResult\n");
2030
        if (ov.hEvent) {
2031
            CloseHandle(ov.hEvent);
2032
            ov.hEvent = NULL;
2033
        }
2034
        goto fail;
2035
    }
2036

    
2037
    if (ov.hEvent) {
2038
        CloseHandle(ov.hEvent);
2039
        ov.hEvent = NULL;
2040
    }
2041
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2042
    return 0;
2043

    
2044
 fail:
2045
    win_chr_close2(s);
2046
    return -1;
2047
}
2048

    
2049

    
2050
CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2051
{
2052
    CharDriverState *chr;
2053
    WinCharState *s;
2054

    
2055
    chr = qemu_mallocz(sizeof(CharDriverState));
2056
    if (!chr)
2057
        return NULL;
2058
    s = qemu_mallocz(sizeof(WinCharState));
2059
    if (!s) {
2060
        free(chr);
2061
        return NULL;
2062
    }
2063
    chr->opaque = s;
2064
    chr->chr_write = win_chr_write;
2065
    chr->chr_add_read_handler = win_chr_add_read_handler;
2066
    chr->chr_close = win_chr_close;
2067
    
2068
    if (win_chr_pipe_init(s, filename) < 0) {
2069
        free(s);
2070
        free(chr);
2071
        return NULL;
2072
    }
2073
    return chr;
2074
}
2075

    
2076
CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2077
{
2078
    CharDriverState *chr;
2079
    WinCharState *s;
2080

    
2081
    chr = qemu_mallocz(sizeof(CharDriverState));
2082
    if (!chr)
2083
        return NULL;
2084
    s = qemu_mallocz(sizeof(WinCharState));
2085
    if (!s) {
2086
        free(chr);
2087
        return NULL;
2088
    }
2089
    s->hcom = fd_out;
2090
    chr->opaque = s;
2091
    chr->chr_write = win_chr_write;
2092
    chr->chr_add_read_handler = win_chr_add_read_handler;
2093
    return chr;
2094
}
2095
    
2096
CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2097
{
2098
    HANDLE fd_out;
2099
    
2100
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2101
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2102
    if (fd_out == INVALID_HANDLE_VALUE)
2103
        return NULL;
2104

    
2105
    return qemu_chr_open_win_file(fd_out);
2106
}
2107
#endif
2108

    
2109
/***********************************************************/
2110
/* UDP Net console */
2111

    
2112
typedef struct {
2113
    IOCanRWHandler *fd_can_read;
2114
    IOReadHandler *fd_read;
2115
    void *fd_opaque;
2116
    int fd;
2117
    struct sockaddr_in daddr;
2118
    char buf[1024];
2119
    int bufcnt;
2120
    int bufptr;
2121
    int max_size;
2122
} NetCharDriver;
2123

    
2124
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2125
{
2126
    NetCharDriver *s = chr->opaque;
2127

    
2128
    return sendto(s->fd, buf, len, 0,
2129
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2130
}
2131

    
2132
static int udp_chr_read_poll(void *opaque)
2133
{
2134
    CharDriverState *chr = opaque;
2135
    NetCharDriver *s = chr->opaque;
2136

    
2137
    s->max_size = s->fd_can_read(s->fd_opaque);
2138

    
2139
    /* If there were any stray characters in the queue process them
2140
     * first
2141
     */
2142
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2143
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2144
        s->bufptr++;
2145
        s->max_size = s->fd_can_read(s->fd_opaque);
2146
    }
2147
    return s->max_size;
2148
}
2149

    
2150
static void udp_chr_read(void *opaque)
2151
{
2152
    CharDriverState *chr = opaque;
2153
    NetCharDriver *s = chr->opaque;
2154

    
2155
    if (s->max_size == 0)
2156
        return;
2157
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2158
    s->bufptr = s->bufcnt;
2159
    if (s->bufcnt <= 0)
2160
        return;
2161

    
2162
    s->bufptr = 0;
2163
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2164
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2165
        s->bufptr++;
2166
        s->max_size = s->fd_can_read(s->fd_opaque);
2167
    }
2168
}
2169

    
2170
static void udp_chr_add_read_handler(CharDriverState *chr,
2171
                                    IOCanRWHandler *fd_can_read,
2172
                                    IOReadHandler *fd_read, void *opaque)
2173
{
2174
    NetCharDriver *s = chr->opaque;
2175

    
2176
    if (s->fd >= 0) {
2177
        s->fd_can_read = fd_can_read;
2178
        s->fd_read = fd_read;
2179
        s->fd_opaque = opaque;
2180
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2181
                             udp_chr_read, NULL, chr);
2182
    }
2183
}
2184

    
2185
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2186
int parse_host_src_port(struct sockaddr_in *haddr,
2187
                        struct sockaddr_in *saddr,
2188
                        const char *str);
2189

    
2190
CharDriverState *qemu_chr_open_udp(const char *def)
2191
{
2192
    CharDriverState *chr = NULL;
2193
    NetCharDriver *s = NULL;
2194
    int fd = -1;
2195
    struct sockaddr_in saddr;
2196

    
2197
    chr = qemu_mallocz(sizeof(CharDriverState));
2198
    if (!chr)
2199
        goto return_err;
2200
    s = qemu_mallocz(sizeof(NetCharDriver));
2201
    if (!s)
2202
        goto return_err;
2203

    
2204
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2205
    if (fd < 0) {
2206
        perror("socket(PF_INET, SOCK_DGRAM)");
2207
        goto return_err;
2208
    }
2209

    
2210
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2211
        printf("Could not parse: %s\n", def);
2212
        goto return_err;
2213
    }
2214

    
2215
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2216
    {
2217
        perror("bind");
2218
        goto return_err;
2219
    }
2220

    
2221
    s->fd = fd;
2222
    s->bufcnt = 0;
2223
    s->bufptr = 0;
2224
    chr->opaque = s;
2225
    chr->chr_write = udp_chr_write;
2226
    chr->chr_add_read_handler = udp_chr_add_read_handler;
2227
    return chr;
2228

    
2229
return_err:
2230
    if (chr)
2231
        free(chr);
2232
    if (s)
2233
        free(s);
2234
    if (fd >= 0)
2235
        closesocket(fd);
2236
    return NULL;
2237
}
2238

    
2239
/***********************************************************/
2240
/* TCP Net console */
2241

    
2242
typedef struct {
2243
    IOCanRWHandler *fd_can_read;
2244
    IOReadHandler *fd_read;
2245
    void *fd_opaque;
2246
    int fd, listen_fd;
2247
    int connected;
2248
    int max_size;
2249
    int do_telnetopt;
2250
} TCPCharDriver;
2251

    
2252
static void tcp_chr_accept(void *opaque);
2253

    
2254
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2255
{
2256
    TCPCharDriver *s = chr->opaque;
2257
    if (s->connected) {
2258
        return send_all(s->fd, buf, len);
2259
    } else {
2260
        /* XXX: indicate an error ? */
2261
        return len;
2262
    }
2263
}
2264

    
2265
static int tcp_chr_read_poll(void *opaque)
2266
{
2267
    CharDriverState *chr = opaque;
2268
    TCPCharDriver *s = chr->opaque;
2269
    if (!s->connected)
2270
        return 0;
2271
    s->max_size = s->fd_can_read(s->fd_opaque);
2272
    return s->max_size;
2273
}
2274

    
2275
#define IAC 255
2276
#define IAC_BREAK 243
2277
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2278
                                      TCPCharDriver *s,
2279
                                      char *buf, int *size)
2280
{
2281
    /* Handle any telnet client's basic IAC options to satisfy char by
2282
     * char mode with no echo.  All IAC options will be removed from
2283
     * the buf and the do_telnetopt variable will be used to track the
2284
     * state of the width of the IAC information.
2285
     *
2286
     * IAC commands come in sets of 3 bytes with the exception of the
2287
     * "IAC BREAK" command and the double IAC.
2288
     */
2289

    
2290
    int i;
2291
    int j = 0;
2292

    
2293
    for (i = 0; i < *size; i++) {
2294
        if (s->do_telnetopt > 1) {
2295
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2296
                /* Double IAC means send an IAC */
2297
                if (j != i)
2298
                    buf[j] = buf[i];
2299
                j++;
2300
                s->do_telnetopt = 1;
2301
            } else {
2302
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2303
                    /* Handle IAC break commands by sending a serial break */
2304
                    chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2305
                    s->do_telnetopt++;
2306
                }
2307
                s->do_telnetopt++;
2308
            }
2309
            if (s->do_telnetopt >= 4) {
2310
                s->do_telnetopt = 1;
2311
            }
2312
        } else {
2313
            if ((unsigned char)buf[i] == IAC) {
2314
                s->do_telnetopt = 2;
2315
            } else {
2316
                if (j != i)
2317
                    buf[j] = buf[i];
2318
                j++;
2319
            }
2320
        }
2321
    }
2322
    *size = j;
2323
}
2324

    
2325
static void tcp_chr_read(void *opaque)
2326
{
2327
    CharDriverState *chr = opaque;
2328
    TCPCharDriver *s = chr->opaque;
2329
    uint8_t buf[1024];
2330
    int len, size;
2331

    
2332
    if (!s->connected || s->max_size <= 0)
2333
        return;
2334
    len = sizeof(buf);
2335
    if (len > s->max_size)
2336
        len = s->max_size;
2337
    size = recv(s->fd, buf, len, 0);
2338
    if (size == 0) {
2339
        /* connection closed */
2340
        s->connected = 0;
2341
        if (s->listen_fd >= 0) {
2342
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2343
        }
2344
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2345
        closesocket(s->fd);
2346
        s->fd = -1;
2347
    } else if (size > 0) {
2348
        if (s->do_telnetopt)
2349
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2350
        if (size > 0)
2351
            s->fd_read(s->fd_opaque, buf, size);
2352
    }
2353
}
2354

    
2355
static void tcp_chr_add_read_handler(CharDriverState *chr,
2356
                                     IOCanRWHandler *fd_can_read,
2357
                                    IOReadHandler *fd_read, void *opaque)
2358
{
2359
    TCPCharDriver *s = chr->opaque;
2360

    
2361
    s->fd_can_read = fd_can_read;
2362
    s->fd_read = fd_read;
2363
    s->fd_opaque = opaque;
2364
}
2365

    
2366
static void tcp_chr_connect(void *opaque)
2367
{
2368
    CharDriverState *chr = opaque;
2369
    TCPCharDriver *s = chr->opaque;
2370

    
2371
    s->connected = 1;
2372
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2373
                         tcp_chr_read, NULL, chr);
2374
}
2375

    
2376
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2377
static void tcp_chr_telnet_init(int fd)
2378
{
2379
    char buf[3];
2380
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2381
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2382
    send(fd, (char *)buf, 3, 0);
2383
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2384
    send(fd, (char *)buf, 3, 0);
2385
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2386
    send(fd, (char *)buf, 3, 0);
2387
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2388
    send(fd, (char *)buf, 3, 0);
2389
}
2390

    
2391
static void tcp_chr_accept(void *opaque)
2392
{
2393
    CharDriverState *chr = opaque;
2394
    TCPCharDriver *s = chr->opaque;
2395
    struct sockaddr_in saddr;
2396
    socklen_t len;
2397
    int fd;
2398

    
2399
    for(;;) {
2400
        len = sizeof(saddr);
2401
        fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2402
        if (fd < 0 && errno != EINTR) {
2403
            return;
2404
        } else if (fd >= 0) {
2405
            if (s->do_telnetopt)
2406
                tcp_chr_telnet_init(fd);
2407
            break;
2408
        }
2409
    }
2410
    socket_set_nonblock(fd);
2411
    s->fd = fd;
2412
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2413
    tcp_chr_connect(chr);
2414
}
2415

    
2416
static void tcp_chr_close(CharDriverState *chr)
2417
{
2418
    TCPCharDriver *s = chr->opaque;
2419
    if (s->fd >= 0)
2420
        closesocket(s->fd);
2421
    if (s->listen_fd >= 0)
2422
        closesocket(s->listen_fd);
2423
    qemu_free(s);
2424
}
2425

    
2426
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2427
                                          int is_telnet)
2428
{
2429
    CharDriverState *chr = NULL;
2430
    TCPCharDriver *s = NULL;
2431
    int fd = -1, ret, err, val;
2432
    int is_listen = 0;
2433
    int is_waitconnect = 1;
2434
    const char *ptr;
2435
    struct sockaddr_in saddr;
2436

    
2437
    if (parse_host_port(&saddr, host_str) < 0)
2438
        goto fail;
2439

    
2440
    ptr = host_str;
2441
    while((ptr = strchr(ptr,','))) {
2442
        ptr++;
2443
        if (!strncmp(ptr,"server",6)) {
2444
            is_listen = 1;
2445
        } else if (!strncmp(ptr,"nowait",6)) {
2446
            is_waitconnect = 0;
2447
        } else {
2448
            printf("Unknown option: %s\n", ptr);
2449
            goto fail;
2450
        }
2451
    }
2452
    if (!is_listen)
2453
        is_waitconnect = 0;
2454

    
2455
    chr = qemu_mallocz(sizeof(CharDriverState));
2456
    if (!chr)
2457
        goto fail;
2458
    s = qemu_mallocz(sizeof(TCPCharDriver));
2459
    if (!s)
2460
        goto fail;
2461
    
2462
    fd = socket(PF_INET, SOCK_STREAM, 0);
2463
    if (fd < 0) 
2464
        goto fail;
2465

    
2466
    if (!is_waitconnect)
2467
        socket_set_nonblock(fd);
2468

    
2469
    s->connected = 0;
2470
    s->fd = -1;
2471
    s->listen_fd = -1;
2472
    if (is_listen) {
2473
        /* allow fast reuse */
2474
        val = 1;
2475
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2476
        
2477
        ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2478
        if (ret < 0) 
2479
            goto fail;
2480
        ret = listen(fd, 0);
2481
        if (ret < 0)
2482
            goto fail;
2483
        s->listen_fd = fd;
2484
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2485
        if (is_telnet)
2486
            s->do_telnetopt = 1;
2487
    } else {
2488
        for(;;) {
2489
            ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2490
            if (ret < 0) {
2491
                err = socket_error();
2492
                if (err == EINTR || err == EWOULDBLOCK) {
2493
                } else if (err == EINPROGRESS) {
2494
                    break;
2495
                } else {
2496
                    goto fail;
2497
                }
2498
            } else {
2499
                s->connected = 1;
2500
                break;
2501
            }
2502
        }
2503
        s->fd = fd;
2504
        if (s->connected)
2505
            tcp_chr_connect(chr);
2506
        else
2507
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2508
    }
2509
    
2510
    chr->opaque = s;
2511
    chr->chr_write = tcp_chr_write;
2512
    chr->chr_add_read_handler = tcp_chr_add_read_handler;
2513
    chr->chr_close = tcp_chr_close;
2514
    if (is_listen && is_waitconnect) {
2515
        printf("QEMU waiting for connection on: %s\n", host_str);
2516
        tcp_chr_accept(chr);
2517
        socket_set_nonblock(s->listen_fd);
2518
    }
2519

    
2520
    return chr;
2521
 fail:
2522
    if (fd >= 0)
2523
        closesocket(fd);
2524
    qemu_free(s);
2525
    qemu_free(chr);
2526
    return NULL;
2527
}
2528

    
2529
CharDriverState *qemu_chr_open(const char *filename)
2530
{
2531
    const char *p;
2532

    
2533
    if (!strcmp(filename, "vc")) {
2534
        return text_console_init(&display_state);
2535
    } else if (!strcmp(filename, "null")) {
2536
        return qemu_chr_open_null();
2537
    } else 
2538
    if (strstart(filename, "tcp:", &p)) {
2539
        return qemu_chr_open_tcp(p, 0);
2540
    } else
2541
    if (strstart(filename, "telnet:", &p)) {
2542
        return qemu_chr_open_tcp(p, 1);
2543
    } else
2544
    if (strstart(filename, "udp:", &p)) {
2545
        return qemu_chr_open_udp(p);
2546
    } else
2547
#ifndef _WIN32
2548
    if (strstart(filename, "file:", &p)) {
2549
        return qemu_chr_open_file_out(p);
2550
    } else if (strstart(filename, "pipe:", &p)) {
2551
        return qemu_chr_open_pipe(p);
2552
    } else if (!strcmp(filename, "pty")) {
2553
        return qemu_chr_open_pty();
2554
    } else if (!strcmp(filename, "stdio")) {
2555
        return qemu_chr_open_stdio();
2556
    } else 
2557
#endif
2558
#if defined(__linux__)
2559
    if (strstart(filename, "/dev/parport", NULL)) {
2560
        return qemu_chr_open_pp(filename);
2561
    } else 
2562
    if (strstart(filename, "/dev/", NULL)) {
2563
        return qemu_chr_open_tty(filename);
2564
    } else 
2565
#endif
2566
#ifdef _WIN32
2567
    if (strstart(filename, "COM", NULL)) {
2568
        return qemu_chr_open_win(filename);
2569
    } else
2570
    if (strstart(filename, "pipe:", &p)) {
2571
        return qemu_chr_open_win_pipe(p);
2572
    } else
2573
    if (strstart(filename, "file:", &p)) {
2574
        return qemu_chr_open_win_file_out(p);
2575
    }
2576
#endif
2577
    {
2578
        return NULL;
2579
    }
2580
}
2581

    
2582
void qemu_chr_close(CharDriverState *chr)
2583
{
2584
    if (chr->chr_close)
2585
        chr->chr_close(chr);
2586
}
2587

    
2588
/***********************************************************/
2589
/* network device redirectors */
2590

    
2591
void hex_dump(FILE *f, const uint8_t *buf, int size)
2592
{
2593
    int len, i, j, c;
2594

    
2595
    for(i=0;i<size;i+=16) {
2596
        len = size - i;
2597
        if (len > 16)
2598
            len = 16;
2599
        fprintf(f, "%08x ", i);
2600
        for(j=0;j<16;j++) {
2601
            if (j < len)
2602
                fprintf(f, " %02x", buf[i+j]);
2603
            else
2604
                fprintf(f, "   ");
2605
        }
2606
        fprintf(f, " ");
2607
        for(j=0;j<len;j++) {
2608
            c = buf[i+j];
2609
            if (c < ' ' || c > '~')
2610
                c = '.';
2611
            fprintf(f, "%c", c);
2612
        }
2613
        fprintf(f, "\n");
2614
    }
2615
}
2616

    
2617
static int parse_macaddr(uint8_t *macaddr, const char *p)
2618
{
2619
    int i;
2620
    for(i = 0; i < 6; i++) {
2621
        macaddr[i] = strtol(p, (char **)&p, 16);
2622
        if (i == 5) {
2623
            if (*p != '\0') 
2624
                return -1;
2625
        } else {
2626
            if (*p != ':') 
2627
                return -1;
2628
            p++;
2629
        }
2630
    }
2631
    return 0;
2632
}
2633

    
2634
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2635
{
2636
    const char *p, *p1;
2637
    int len;
2638
    p = *pp;
2639
    p1 = strchr(p, sep);
2640
    if (!p1)
2641
        return -1;
2642
    len = p1 - p;
2643
    p1++;
2644
    if (buf_size > 0) {
2645
        if (len > buf_size - 1)
2646
            len = buf_size - 1;
2647
        memcpy(buf, p, len);
2648
        buf[len] = '\0';
2649
    }
2650
    *pp = p1;
2651
    return 0;
2652
}
2653

    
2654
int parse_host_src_port(struct sockaddr_in *haddr,
2655
                        struct sockaddr_in *saddr,
2656
                        const char *input_str)
2657
{
2658
    char *str = strdup(input_str);
2659
    char *host_str = str;
2660
    char *src_str;
2661
    char *ptr;
2662

    
2663
    /*
2664
     * Chop off any extra arguments at the end of the string which
2665
     * would start with a comma, then fill in the src port information
2666
     * if it was provided else use the "any address" and "any port".
2667
     */
2668
    if ((ptr = strchr(str,',')))
2669
        *ptr = '\0';
2670

    
2671
    if ((src_str = strchr(input_str,'@'))) {
2672
        *src_str = '\0';
2673
        src_str++;
2674
    }
2675

    
2676
    if (parse_host_port(haddr, host_str) < 0)
2677
        goto fail;
2678

    
2679
    if (!src_str || *src_str == '\0')
2680
        src_str = ":0";
2681

    
2682
    if (parse_host_port(saddr, src_str) < 0)
2683
        goto fail;
2684

    
2685
    free(str);
2686
    return(0);
2687

    
2688
fail:
2689
    free(str);
2690
    return -1;
2691
}
2692

    
2693
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2694
{
2695
    char buf[512];
2696
    struct hostent *he;
2697
    const char *p, *r;
2698
    int port;
2699

    
2700
    p = str;
2701
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2702
        return -1;
2703
    saddr->sin_family = AF_INET;
2704
    if (buf[0] == '\0') {
2705
        saddr->sin_addr.s_addr = 0;
2706
    } else {
2707
        if (isdigit(buf[0])) {
2708
            if (!inet_aton(buf, &saddr->sin_addr))
2709
                return -1;
2710
        } else {
2711
            if ((he = gethostbyname(buf)) == NULL)
2712
                return - 1;
2713
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2714
        }
2715
    }
2716
    port = strtol(p, (char **)&r, 0);
2717
    if (r == p)
2718
        return -1;
2719
    saddr->sin_port = htons(port);
2720
    return 0;
2721
}
2722

    
2723
/* find or alloc a new VLAN */
2724
VLANState *qemu_find_vlan(int id)
2725
{
2726
    VLANState **pvlan, *vlan;
2727
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2728
        if (vlan->id == id)
2729
            return vlan;
2730
    }
2731
    vlan = qemu_mallocz(sizeof(VLANState));
2732
    if (!vlan)
2733
        return NULL;
2734
    vlan->id = id;
2735
    vlan->next = NULL;
2736
    pvlan = &first_vlan;
2737
    while (*pvlan != NULL)
2738
        pvlan = &(*pvlan)->next;
2739
    *pvlan = vlan;
2740
    return vlan;
2741
}
2742

    
2743
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2744
                                      IOReadHandler *fd_read,
2745
                                      IOCanRWHandler *fd_can_read,
2746
                                      void *opaque)
2747
{
2748
    VLANClientState *vc, **pvc;
2749
    vc = qemu_mallocz(sizeof(VLANClientState));
2750
    if (!vc)
2751
        return NULL;
2752
    vc->fd_read = fd_read;
2753
    vc->fd_can_read = fd_can_read;
2754
    vc->opaque = opaque;
2755
    vc->vlan = vlan;
2756

    
2757
    vc->next = NULL;
2758
    pvc = &vlan->first_client;
2759
    while (*pvc != NULL)
2760
        pvc = &(*pvc)->next;
2761
    *pvc = vc;
2762
    return vc;
2763
}
2764

    
2765
int qemu_can_send_packet(VLANClientState *vc1)
2766
{
2767
    VLANState *vlan = vc1->vlan;
2768
    VLANClientState *vc;
2769

    
2770
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2771
        if (vc != vc1) {
2772
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2773
                return 0;
2774
        }
2775
    }
2776
    return 1;
2777
}
2778

    
2779
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2780
{
2781
    VLANState *vlan = vc1->vlan;
2782
    VLANClientState *vc;
2783

    
2784
#if 0
2785
    printf("vlan %d send:\n", vlan->id);
2786
    hex_dump(stdout, buf, size);
2787
#endif
2788
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2789
        if (vc != vc1) {
2790
            vc->fd_read(vc->opaque, buf, size);
2791
        }
2792
    }
2793
}
2794

    
2795
#if defined(CONFIG_SLIRP)
2796

    
2797
/* slirp network adapter */
2798

    
2799
static int slirp_inited;
2800
static VLANClientState *slirp_vc;
2801

    
2802
int slirp_can_output(void)
2803
{
2804
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
2805
}
2806

    
2807
void slirp_output(const uint8_t *pkt, int pkt_len)
2808
{
2809
#if 0
2810
    printf("slirp output:\n");
2811
    hex_dump(stdout, pkt, pkt_len);
2812
#endif
2813
    if (!slirp_vc)
2814
        return;
2815
    qemu_send_packet(slirp_vc, pkt, pkt_len);
2816
}
2817

    
2818
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2819
{
2820
#if 0
2821
    printf("slirp input:\n");
2822
    hex_dump(stdout, buf, size);
2823
#endif
2824
    slirp_input(buf, size);
2825
}
2826

    
2827
static int net_slirp_init(VLANState *vlan)
2828
{
2829
    if (!slirp_inited) {
2830
        slirp_inited = 1;
2831
        slirp_init();
2832
    }
2833
    slirp_vc = qemu_new_vlan_client(vlan, 
2834
                                    slirp_receive, NULL, NULL);
2835
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2836
    return 0;
2837
}
2838

    
2839
static void net_slirp_redir(const char *redir_str)
2840
{
2841
    int is_udp;
2842
    char buf[256], *r;
2843
    const char *p;
2844
    struct in_addr guest_addr;
2845
    int host_port, guest_port;
2846
    
2847
    if (!slirp_inited) {
2848
        slirp_inited = 1;
2849
        slirp_init();
2850
    }
2851

    
2852
    p = redir_str;
2853
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2854
        goto fail;
2855
    if (!strcmp(buf, "tcp")) {
2856
        is_udp = 0;
2857
    } else if (!strcmp(buf, "udp")) {
2858
        is_udp = 1;
2859
    } else {
2860
        goto fail;
2861
    }
2862

    
2863
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2864
        goto fail;
2865
    host_port = strtol(buf, &r, 0);
2866
    if (r == buf)
2867
        goto fail;
2868

    
2869
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2870
        goto fail;
2871
    if (buf[0] == '\0') {
2872
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
2873
    }
2874
    if (!inet_aton(buf, &guest_addr))
2875
        goto fail;
2876
    
2877
    guest_port = strtol(p, &r, 0);
2878
    if (r == p)
2879
        goto fail;
2880
    
2881
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2882
        fprintf(stderr, "qemu: could not set up redirection\n");
2883
        exit(1);
2884
    }
2885
    return;
2886
 fail:
2887
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2888
    exit(1);
2889
}
2890
    
2891
#ifndef _WIN32
2892

    
2893
char smb_dir[1024];
2894

    
2895
static void smb_exit(void)
2896
{
2897
    DIR *d;
2898
    struct dirent *de;
2899
    char filename[1024];
2900

    
2901
    /* erase all the files in the directory */
2902
    d = opendir(smb_dir);
2903
    for(;;) {
2904
        de = readdir(d);
2905
        if (!de)
2906
            break;
2907
        if (strcmp(de->d_name, ".") != 0 &&
2908
            strcmp(de->d_name, "..") != 0) {
2909
            snprintf(filename, sizeof(filename), "%s/%s", 
2910
                     smb_dir, de->d_name);
2911
            unlink(filename);
2912
        }
2913
    }
2914
    closedir(d);
2915
    rmdir(smb_dir);
2916
}
2917

    
2918
/* automatic user mode samba server configuration */
2919
void net_slirp_smb(const char *exported_dir)
2920
{
2921
    char smb_conf[1024];
2922
    char smb_cmdline[1024];
2923
    FILE *f;
2924

    
2925
    if (!slirp_inited) {
2926
        slirp_inited = 1;
2927
        slirp_init();
2928
    }
2929

    
2930
    /* XXX: better tmp dir construction */
2931
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2932
    if (mkdir(smb_dir, 0700) < 0) {
2933
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2934
        exit(1);
2935
    }
2936
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2937
    
2938
    f = fopen(smb_conf, "w");
2939
    if (!f) {
2940
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2941
        exit(1);
2942
    }
2943
    fprintf(f, 
2944
            "[global]\n"
2945
            "private dir=%s\n"
2946
            "smb ports=0\n"
2947
            "socket address=127.0.0.1\n"
2948
            "pid directory=%s\n"
2949
            "lock directory=%s\n"
2950
            "log file=%s/log.smbd\n"
2951
            "smb passwd file=%s/smbpasswd\n"
2952
            "security = share\n"
2953
            "[qemu]\n"
2954
            "path=%s\n"
2955
            "read only=no\n"
2956
            "guest ok=yes\n",
2957
            smb_dir,
2958
            smb_dir,
2959
            smb_dir,
2960
            smb_dir,
2961
            smb_dir,
2962
            exported_dir
2963
            );
2964
    fclose(f);
2965
    atexit(smb_exit);
2966

    
2967
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2968
             smb_conf);
2969
    
2970
    slirp_add_exec(0, smb_cmdline, 4, 139);
2971
}
2972

    
2973
#endif /* !defined(_WIN32) */
2974

    
2975
#endif /* CONFIG_SLIRP */
2976

    
2977
#if !defined(_WIN32)
2978

    
2979
typedef struct TAPState {
2980
    VLANClientState *vc;
2981
    int fd;
2982
} TAPState;
2983

    
2984
static void tap_receive(void *opaque, const uint8_t *buf, int size)
2985
{
2986
    TAPState *s = opaque;
2987
    int ret;
2988
    for(;;) {
2989
        ret = write(s->fd, buf, size);
2990
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2991
        } else {
2992
            break;
2993
        }
2994
    }
2995
}
2996

    
2997
static void tap_send(void *opaque)
2998
{
2999
    TAPState *s = opaque;
3000
    uint8_t buf[4096];
3001
    int size;
3002

    
3003
    size = read(s->fd, buf, sizeof(buf));
3004
    if (size > 0) {
3005
        qemu_send_packet(s->vc, buf, size);
3006
    }
3007
}
3008

    
3009
/* fd support */
3010

    
3011
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3012
{
3013
    TAPState *s;
3014

    
3015
    s = qemu_mallocz(sizeof(TAPState));
3016
    if (!s)
3017
        return NULL;
3018
    s->fd = fd;
3019
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3020
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3021
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3022
    return s;
3023
}
3024

    
3025
#ifdef _BSD
3026
static int tap_open(char *ifname, int ifname_size)
3027
{
3028
    int fd;
3029
    char *dev;
3030
    struct stat s;
3031

    
3032
    fd = open("/dev/tap", O_RDWR);
3033
    if (fd < 0) {
3034
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3035
        return -1;
3036
    }
3037

    
3038
    fstat(fd, &s);
3039
    dev = devname(s.st_rdev, S_IFCHR);
3040
    pstrcpy(ifname, ifname_size, dev);
3041

    
3042
    fcntl(fd, F_SETFL, O_NONBLOCK);
3043
    return fd;
3044
}
3045
#elif defined(__sun__)
3046
static int tap_open(char *ifname, int ifname_size)
3047
{
3048
    fprintf(stderr, "warning: tap_open not yet implemented\n");
3049
    return -1;
3050
}
3051
#else
3052
static int tap_open(char *ifname, int ifname_size)
3053
{
3054
    struct ifreq ifr;
3055
    int fd, ret;
3056
    
3057
    fd = open("/dev/net/tun", O_RDWR);
3058
    if (fd < 0) {
3059
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3060
        return -1;
3061
    }
3062
    memset(&ifr, 0, sizeof(ifr));
3063
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3064
    if (ifname[0] != '\0')
3065
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3066
    else
3067
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3068
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3069
    if (ret != 0) {
3070
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3071
        close(fd);
3072
        return -1;
3073
    }
3074
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3075
    fcntl(fd, F_SETFL, O_NONBLOCK);
3076
    return fd;
3077
}
3078
#endif
3079

    
3080
static int net_tap_init(VLANState *vlan, const char *ifname1,
3081
                        const char *setup_script)
3082
{
3083
    TAPState *s;
3084
    int pid, status, fd;
3085
    char *args[3];
3086
    char **parg;
3087
    char ifname[128];
3088

    
3089
    if (ifname1 != NULL)
3090
        pstrcpy(ifname, sizeof(ifname), ifname1);
3091
    else
3092
        ifname[0] = '\0';
3093
    fd = tap_open(ifname, sizeof(ifname));
3094
    if (fd < 0)
3095
        return -1;
3096

    
3097
    if (!setup_script)
3098
        setup_script = "";
3099
    if (setup_script[0] != '\0') {
3100
        /* try to launch network init script */
3101
        pid = fork();
3102
        if (pid >= 0) {
3103
            if (pid == 0) {
3104
                parg = args;
3105
                *parg++ = (char *)setup_script;
3106
                *parg++ = ifname;
3107
                *parg++ = NULL;
3108
                execv(setup_script, args);
3109
                _exit(1);
3110
            }
3111
            while (waitpid(pid, &status, 0) != pid);
3112
            if (!WIFEXITED(status) ||
3113
                WEXITSTATUS(status) != 0) {
3114
                fprintf(stderr, "%s: could not launch network script\n",
3115
                        setup_script);
3116
                return -1;
3117
            }
3118
        }
3119
    }
3120
    s = net_tap_fd_init(vlan, fd);
3121
    if (!s)
3122
        return -1;
3123
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3124
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3125
    return 0;
3126
}
3127

    
3128
#endif /* !_WIN32 */
3129

    
3130
/* network connection */
3131
typedef struct NetSocketState {
3132
    VLANClientState *vc;
3133
    int fd;
3134
    int state; /* 0 = getting length, 1 = getting data */
3135
    int index;
3136
    int packet_len;
3137
    uint8_t buf[4096];
3138
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3139
} NetSocketState;
3140

    
3141
typedef struct NetSocketListenState {
3142
    VLANState *vlan;
3143
    int fd;
3144
} NetSocketListenState;
3145

    
3146
/* XXX: we consider we can send the whole packet without blocking */
3147
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3148
{
3149
    NetSocketState *s = opaque;
3150
    uint32_t len;
3151
    len = htonl(size);
3152

    
3153
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3154
    send_all(s->fd, buf, size);
3155
}
3156

    
3157
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3158
{
3159
    NetSocketState *s = opaque;
3160
    sendto(s->fd, buf, size, 0, 
3161
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3162
}
3163

    
3164
static void net_socket_send(void *opaque)
3165
{
3166
    NetSocketState *s = opaque;
3167
    int l, size, err;
3168
    uint8_t buf1[4096];
3169
    const uint8_t *buf;
3170

    
3171
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3172
    if (size < 0) {
3173
        err = socket_error();
3174
        if (err != EWOULDBLOCK) 
3175
            goto eoc;
3176
    } else if (size == 0) {
3177
        /* end of connection */
3178
    eoc:
3179
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3180
        closesocket(s->fd);
3181
        return;
3182
    }
3183
    buf = buf1;
3184
    while (size > 0) {
3185
        /* reassemble a packet from the network */
3186
        switch(s->state) {
3187
        case 0:
3188
            l = 4 - s->index;
3189
            if (l > size)
3190
                l = size;
3191
            memcpy(s->buf + s->index, buf, l);
3192
            buf += l;
3193
            size -= l;
3194
            s->index += l;
3195
            if (s->index == 4) {
3196
                /* got length */
3197
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3198
                s->index = 0;
3199
                s->state = 1;
3200
            }
3201
            break;
3202
        case 1:
3203
            l = s->packet_len - s->index;
3204
            if (l > size)
3205
                l = size;
3206
            memcpy(s->buf + s->index, buf, l);
3207
            s->index += l;
3208
            buf += l;
3209
            size -= l;
3210
            if (s->index >= s->packet_len) {
3211
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3212
                s->index = 0;
3213
                s->state = 0;
3214
            }
3215
            break;
3216
        }
3217
    }
3218
}
3219

    
3220
static void net_socket_send_dgram(void *opaque)
3221
{
3222
    NetSocketState *s = opaque;
3223
    int size;
3224

    
3225
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3226
    if (size < 0) 
3227
        return;
3228
    if (size == 0) {
3229
        /* end of connection */
3230
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3231
        return;
3232
    }
3233
    qemu_send_packet(s->vc, s->buf, size);
3234
}
3235

    
3236
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3237
{
3238
    struct ip_mreq imr;
3239
    int fd;
3240
    int val, ret;
3241
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3242
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3243
                inet_ntoa(mcastaddr->sin_addr), 
3244
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3245
        return -1;
3246

    
3247
    }
3248
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3249
    if (fd < 0) {
3250
        perror("socket(PF_INET, SOCK_DGRAM)");
3251
        return -1;
3252
    }
3253

    
3254
    val = 1;
3255
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3256
                   (const char *)&val, sizeof(val));
3257
    if (ret < 0) {
3258
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3259
        goto fail;
3260
    }
3261

    
3262
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3263
    if (ret < 0) {
3264
        perror("bind");
3265
        goto fail;
3266
    }
3267
    
3268
    /* Add host to multicast group */
3269
    imr.imr_multiaddr = mcastaddr->sin_addr;
3270
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3271

    
3272
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3273
                     (const char *)&imr, sizeof(struct ip_mreq));
3274
    if (ret < 0) {
3275
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3276
        goto fail;
3277
    }
3278

    
3279
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3280
    val = 1;
3281
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3282
                   (const char *)&val, sizeof(val));
3283
    if (ret < 0) {
3284
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3285
        goto fail;
3286
    }
3287

    
3288
    socket_set_nonblock(fd);
3289
    return fd;
3290
fail:
3291
    if (fd >= 0) 
3292
        closesocket(fd);
3293
    return -1;
3294
}
3295

    
3296
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3297
                                          int is_connected)
3298
{
3299
    struct sockaddr_in saddr;
3300
    int newfd;
3301
    socklen_t saddr_len;
3302
    NetSocketState *s;
3303

    
3304
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3305
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3306
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3307
     */
3308

    
3309
    if (is_connected) {
3310
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3311
            /* must be bound */
3312
            if (saddr.sin_addr.s_addr==0) {
3313
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3314
                        fd);
3315
                return NULL;
3316
            }
3317
            /* clone dgram socket */
3318
            newfd = net_socket_mcast_create(&saddr);
3319
            if (newfd < 0) {
3320
                /* error already reported by net_socket_mcast_create() */
3321
                close(fd);
3322
                return NULL;
3323
            }
3324
            /* clone newfd to fd, close newfd */
3325
            dup2(newfd, fd);
3326
            close(newfd);
3327
        
3328
        } else {
3329
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3330
                    fd, strerror(errno));
3331
            return NULL;
3332
        }
3333
    }
3334

    
3335
    s = qemu_mallocz(sizeof(NetSocketState));
3336
    if (!s)
3337
        return NULL;
3338
    s->fd = fd;
3339

    
3340
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3341
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3342

    
3343
    /* mcast: save bound address as dst */
3344
    if (is_connected) s->dgram_dst=saddr;
3345

    
3346
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3347
            "socket: fd=%d (%s mcast=%s:%d)", 
3348
            fd, is_connected? "cloned" : "",
3349
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3350
    return s;
3351
}
3352

    
3353
static void net_socket_connect(void *opaque)
3354
{
3355
    NetSocketState *s = opaque;
3356
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3357
}
3358

    
3359
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3360
                                          int is_connected)
3361
{
3362
    NetSocketState *s;
3363
    s = qemu_mallocz(sizeof(NetSocketState));
3364
    if (!s)
3365
        return NULL;
3366
    s->fd = fd;
3367
    s->vc = qemu_new_vlan_client(vlan, 
3368
                                 net_socket_receive, NULL, s);
3369
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3370
             "socket: fd=%d", fd);
3371
    if (is_connected) {
3372
        net_socket_connect(s);
3373
    } else {
3374
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3375
    }
3376
    return s;
3377
}
3378

    
3379
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3380
                                          int is_connected)
3381
{
3382
    int so_type=-1, optlen=sizeof(so_type);
3383

    
3384
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3385
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3386
        return NULL;
3387
    }
3388
    switch(so_type) {
3389
    case SOCK_DGRAM:
3390
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3391
    case SOCK_STREAM:
3392
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3393
    default:
3394
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3395
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3396
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3397
    }
3398
    return NULL;
3399
}
3400

    
3401
static void net_socket_accept(void *opaque)
3402
{
3403
    NetSocketListenState *s = opaque;    
3404
    NetSocketState *s1;
3405
    struct sockaddr_in saddr;
3406
    socklen_t len;
3407
    int fd;
3408

    
3409
    for(;;) {
3410
        len = sizeof(saddr);
3411
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3412
        if (fd < 0 && errno != EINTR) {
3413
            return;
3414
        } else if (fd >= 0) {
3415
            break;
3416
        }
3417
    }
3418
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3419
    if (!s1) {
3420
        closesocket(fd);
3421
    } else {
3422
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3423
                 "socket: connection from %s:%d", 
3424
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3425
    }
3426
}
3427

    
3428
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3429
{
3430
    NetSocketListenState *s;
3431
    int fd, val, ret;
3432
    struct sockaddr_in saddr;
3433

    
3434
    if (parse_host_port(&saddr, host_str) < 0)
3435
        return -1;
3436
    
3437
    s = qemu_mallocz(sizeof(NetSocketListenState));
3438
    if (!s)
3439
        return -1;
3440

    
3441
    fd = socket(PF_INET, SOCK_STREAM, 0);
3442
    if (fd < 0) {
3443
        perror("socket");
3444
        return -1;
3445
    }
3446
    socket_set_nonblock(fd);
3447

    
3448
    /* allow fast reuse */
3449
    val = 1;
3450
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3451
    
3452
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3453
    if (ret < 0) {
3454
        perror("bind");
3455
        return -1;
3456
    }
3457
    ret = listen(fd, 0);
3458
    if (ret < 0) {
3459
        perror("listen");
3460
        return -1;
3461
    }
3462
    s->vlan = vlan;
3463
    s->fd = fd;
3464
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3465
    return 0;
3466
}
3467

    
3468
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3469
{
3470
    NetSocketState *s;
3471
    int fd, connected, ret, err;
3472
    struct sockaddr_in saddr;
3473

    
3474
    if (parse_host_port(&saddr, host_str) < 0)
3475
        return -1;
3476

    
3477
    fd = socket(PF_INET, SOCK_STREAM, 0);
3478
    if (fd < 0) {
3479
        perror("socket");
3480
        return -1;
3481
    }
3482
    socket_set_nonblock(fd);
3483

    
3484
    connected = 0;
3485
    for(;;) {
3486
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3487
        if (ret < 0) {
3488
            err = socket_error();
3489
            if (err == EINTR || err == EWOULDBLOCK) {
3490
            } else if (err == EINPROGRESS) {
3491
                break;
3492
            } else {
3493
                perror("connect");
3494
                closesocket(fd);
3495
                return -1;
3496
            }
3497
        } else {
3498
            connected = 1;
3499
            break;
3500
        }
3501
    }
3502
    s = net_socket_fd_init(vlan, fd, connected);
3503
    if (!s)
3504
        return -1;
3505
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3506
             "socket: connect to %s:%d", 
3507
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3508
    return 0;
3509
}
3510

    
3511
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3512
{
3513
    NetSocketState *s;
3514
    int fd;
3515
    struct sockaddr_in saddr;
3516

    
3517
    if (parse_host_port(&saddr, host_str) < 0)
3518
        return -1;
3519

    
3520

    
3521
    fd = net_socket_mcast_create(&saddr);
3522
    if (fd < 0)
3523
        return -1;
3524

    
3525
    s = net_socket_fd_init(vlan, fd, 0);
3526
    if (!s)
3527
        return -1;
3528

    
3529
    s->dgram_dst = saddr;
3530
    
3531
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3532
             "socket: mcast=%s:%d", 
3533
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3534
    return 0;
3535

    
3536
}
3537

    
3538
static int get_param_value(char *buf, int buf_size,
3539
                           const char *tag, const char *str)
3540
{
3541
    const char *p;
3542
    char *q;
3543
    char option[128];
3544

    
3545
    p = str;
3546
    for(;;) {
3547
        q = option;
3548
        while (*p != '\0' && *p != '=') {
3549
            if ((q - option) < sizeof(option) - 1)
3550
                *q++ = *p;
3551
            p++;
3552
        }
3553
        *q = '\0';
3554
        if (*p != '=')
3555
            break;
3556
        p++;
3557
        if (!strcmp(tag, option)) {
3558
            q = buf;
3559
            while (*p != '\0' && *p != ',') {
3560
                if ((q - buf) < buf_size - 1)
3561
                    *q++ = *p;
3562
                p++;
3563
            }
3564
            *q = '\0';
3565
            return q - buf;
3566
        } else {
3567
            while (*p != '\0' && *p != ',') {
3568
                p++;
3569
            }
3570
        }
3571
        if (*p != ',')
3572
            break;
3573
        p++;
3574
    }
3575
    return 0;
3576
}
3577

    
3578
int net_client_init(const char *str)
3579
{
3580
    const char *p;
3581
    char *q;
3582
    char device[64];
3583
    char buf[1024];
3584
    int vlan_id, ret;
3585
    VLANState *vlan;
3586

    
3587
    p = str;
3588
    q = device;
3589
    while (*p != '\0' && *p != ',') {
3590
        if ((q - device) < sizeof(device) - 1)
3591
            *q++ = *p;
3592
        p++;
3593
    }
3594
    *q = '\0';
3595
    if (*p == ',')
3596
        p++;
3597
    vlan_id = 0;
3598
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3599
        vlan_id = strtol(buf, NULL, 0);
3600
    }
3601
    vlan = qemu_find_vlan(vlan_id);
3602
    if (!vlan) {
3603
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3604
        return -1;
3605
    }
3606
    if (!strcmp(device, "nic")) {
3607
        NICInfo *nd;
3608
        uint8_t *macaddr;
3609

    
3610
        if (nb_nics >= MAX_NICS) {
3611
            fprintf(stderr, "Too Many NICs\n");
3612
            return -1;
3613
        }
3614
        nd = &nd_table[nb_nics];
3615
        macaddr = nd->macaddr;
3616
        macaddr[0] = 0x52;
3617
        macaddr[1] = 0x54;
3618
        macaddr[2] = 0x00;
3619
        macaddr[3] = 0x12;
3620
        macaddr[4] = 0x34;
3621
        macaddr[5] = 0x56 + nb_nics;
3622

    
3623
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3624
            if (parse_macaddr(macaddr, buf) < 0) {
3625
                fprintf(stderr, "invalid syntax for ethernet address\n");
3626
                return -1;
3627
            }
3628
        }
3629
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3630
            nd->model = strdup(buf);
3631
        }
3632
        nd->vlan = vlan;
3633
        nb_nics++;
3634
        ret = 0;
3635
    } else
3636
    if (!strcmp(device, "none")) {
3637
        /* does nothing. It is needed to signal that no network cards
3638
           are wanted */
3639
        ret = 0;
3640
    } else
3641
#ifdef CONFIG_SLIRP
3642
    if (!strcmp(device, "user")) {
3643
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3644
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3645
        }
3646
        ret = net_slirp_init(vlan);
3647
    } else
3648
#endif
3649
#ifdef _WIN32
3650
    if (!strcmp(device, "tap")) {
3651
        char ifname[64];
3652
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3653
            fprintf(stderr, "tap: no interface name\n");
3654
            return -1;
3655
        }
3656
        ret = tap_win32_init(vlan, ifname);
3657
    } else
3658
#else
3659
    if (!strcmp(device, "tap")) {
3660
        char ifname[64];
3661
        char setup_script[1024];
3662
        int fd;
3663
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3664
            fd = strtol(buf, NULL, 0);
3665
            ret = -1;
3666
            if (net_tap_fd_init(vlan, fd))
3667
                ret = 0;
3668
        } else {
3669
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3670
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3671
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3672
            }
3673
            ret = net_tap_init(vlan, ifname, setup_script);
3674
        }
3675
    } else
3676
#endif
3677
    if (!strcmp(device, "socket")) {
3678
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3679
            int fd;
3680
            fd = strtol(buf, NULL, 0);
3681
            ret = -1;
3682
            if (net_socket_fd_init(vlan, fd, 1))
3683
                ret = 0;
3684
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3685
            ret = net_socket_listen_init(vlan, buf);
3686
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3687
            ret = net_socket_connect_init(vlan, buf);
3688
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3689
            ret = net_socket_mcast_init(vlan, buf);
3690
        } else {
3691
            fprintf(stderr, "Unknown socket options: %s\n", p);
3692
            return -1;
3693
        }
3694
    } else
3695
    {
3696
        fprintf(stderr, "Unknown network device: %s\n", device);
3697
        return -1;
3698
    }
3699
    if (ret < 0) {
3700
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3701
    }
3702
    
3703
    return ret;
3704
}
3705

    
3706
void do_info_network(void)
3707
{
3708
    VLANState *vlan;
3709
    VLANClientState *vc;
3710

    
3711
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3712
        term_printf("VLAN %d devices:\n", vlan->id);
3713
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3714
            term_printf("  %s\n", vc->info_str);
3715
    }
3716
}
3717
 
3718
/***********************************************************/
3719
/* USB devices */
3720

    
3721
static USBPort *used_usb_ports;
3722
static USBPort *free_usb_ports;
3723

    
3724
/* ??? Maybe change this to register a hub to keep track of the topology.  */
3725
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3726
                            usb_attachfn attach)
3727
{
3728
    port->opaque = opaque;
3729
    port->index = index;
3730
    port->attach = attach;
3731
    port->next = free_usb_ports;
3732
    free_usb_ports = port;
3733
}
3734

    
3735
static int usb_device_add(const char *devname)
3736
{
3737
    const char *p;
3738
    USBDevice *dev;
3739
    USBPort *port;
3740

    
3741
    if (!free_usb_ports)
3742
        return -1;
3743

    
3744
    if (strstart(devname, "host:", &p)) {
3745
        dev = usb_host_device_open(p);
3746
    } else if (!strcmp(devname, "mouse")) {
3747
        dev = usb_mouse_init();
3748
    } else if (!strcmp(devname, "tablet")) {
3749
        dev = usb_tablet_init();
3750
    } else if (strstart(devname, "disk:", &p)) {
3751
        dev = usb_msd_init(p);
3752
    } else {
3753
        return -1;
3754
    }
3755
    if (!dev)
3756
        return -1;
3757

    
3758
    /* Find a USB port to add the device to.  */
3759
    port = free_usb_ports;
3760
    if (!port->next) {
3761
        USBDevice *hub;
3762

    
3763
        /* Create a new hub and chain it on.  */
3764
        free_usb_ports = NULL;
3765
        port->next = used_usb_ports;
3766
        used_usb_ports = port;
3767

    
3768
        hub = usb_hub_init(VM_USB_HUB_SIZE);
3769
        usb_attach(port, hub);
3770
        port = free_usb_ports;
3771
    }
3772

    
3773
    free_usb_ports = port->next;
3774
    port->next = used_usb_ports;
3775
    used_usb_ports = port;
3776
    usb_attach(port, dev);
3777
    return 0;
3778
}
3779

    
3780
static int usb_device_del(const char *devname)
3781
{
3782
    USBPort *port;
3783
    USBPort **lastp;
3784
    USBDevice *dev;
3785
    int bus_num, addr;
3786
    const char *p;
3787

    
3788
    if (!used_usb_ports)
3789
        return -1;
3790

    
3791
    p = strchr(devname, '.');
3792
    if (!p) 
3793
        return -1;
3794
    bus_num = strtoul(devname, NULL, 0);
3795
    addr = strtoul(p + 1, NULL, 0);
3796
    if (bus_num != 0)
3797
        return -1;
3798

    
3799
    lastp = &used_usb_ports;
3800
    port = used_usb_ports;
3801
    while (port && port->dev->addr != addr) {
3802
        lastp = &port->next;
3803
        port = port->next;
3804
    }
3805

    
3806
    if (!port)
3807
        return -1;
3808

    
3809
    dev = port->dev;
3810
    *lastp = port->next;
3811
    usb_attach(port, NULL);
3812
    dev->handle_destroy(dev);
3813
    port->next = free_usb_ports;
3814
    free_usb_ports = port;
3815
    return 0;
3816
}
3817

    
3818
void do_usb_add(const char *devname)
3819
{
3820
    int ret;
3821
    ret = usb_device_add(devname);
3822
    if (ret < 0) 
3823
        term_printf("Could not add USB device '%s'\n", devname);
3824
}
3825

    
3826
void do_usb_del(const char *devname)
3827
{
3828
    int ret;
3829
    ret = usb_device_del(devname);
3830
    if (ret < 0) 
3831
        term_printf("Could not remove USB device '%s'\n", devname);
3832
}
3833

    
3834
void usb_info(void)
3835
{
3836
    USBDevice *dev;
3837
    USBPort *port;
3838
    const char *speed_str;
3839

    
3840
    if (!usb_enabled) {
3841
        term_printf("USB support not enabled\n");
3842
        return;
3843
    }
3844

    
3845
    for (port = used_usb_ports; port; port = port->next) {
3846
        dev = port->dev;
3847
        if (!dev)
3848
            continue;
3849
        switch(dev->speed) {
3850
        case USB_SPEED_LOW: 
3851
            speed_str = "1.5"; 
3852
            break;
3853
        case USB_SPEED_FULL: 
3854
            speed_str = "12"; 
3855
            break;
3856
        case USB_SPEED_HIGH: 
3857
            speed_str = "480"; 
3858
            break;
3859
        default:
3860
            speed_str = "?"; 
3861
            break;
3862
        }
3863
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
3864
                    0, dev->addr, speed_str, dev->devname);
3865
    }
3866
}
3867

    
3868
/***********************************************************/
3869
/* pid file */
3870

    
3871
static char *pid_filename;
3872

    
3873
/* Remove PID file. Called on normal exit */
3874

    
3875
static void remove_pidfile(void) 
3876
{
3877
    unlink (pid_filename);
3878
}
3879

    
3880
static void create_pidfile(const char *filename)
3881
{
3882
    struct stat pidstat;
3883
    FILE *f;
3884

    
3885
    /* Try to write our PID to the named file */
3886
    if (stat(filename, &pidstat) < 0) {
3887
        if (errno == ENOENT) {
3888
            if ((f = fopen (filename, "w")) == NULL) {
3889
                perror("Opening pidfile");
3890
                exit(1);
3891
            }
3892
            fprintf(f, "%d\n", getpid());
3893
            fclose(f);
3894
            pid_filename = qemu_strdup(filename);
3895
            if (!pid_filename) {
3896
                fprintf(stderr, "Could not save PID filename");
3897
                exit(1);
3898
            }
3899
            atexit(remove_pidfile);
3900
        }
3901
    } else {
3902
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
3903
                filename);
3904
        exit(1);
3905
    }
3906
}
3907

    
3908
/***********************************************************/
3909
/* dumb display */
3910

    
3911
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3912
{
3913
}
3914

    
3915
static void dumb_resize(DisplayState *ds, int w, int h)
3916
{
3917
}
3918

    
3919
static void dumb_refresh(DisplayState *ds)
3920
{
3921
    vga_hw_update();
3922
}
3923

    
3924
void dumb_display_init(DisplayState *ds)
3925
{
3926
    ds->data = NULL;
3927
    ds->linesize = 0;
3928
    ds->depth = 0;
3929
    ds->dpy_update = dumb_update;
3930
    ds->dpy_resize = dumb_resize;
3931
    ds->dpy_refresh = dumb_refresh;
3932
}
3933

    
3934
/***********************************************************/
3935
/* I/O handling */
3936

    
3937
#define MAX_IO_HANDLERS 64
3938

    
3939
typedef struct IOHandlerRecord {
3940
    int fd;
3941
    IOCanRWHandler *fd_read_poll;
3942
    IOHandler *fd_read;
3943
    IOHandler *fd_write;
3944
    void *opaque;
3945
    /* temporary data */
3946
    struct pollfd *ufd;
3947
    struct IOHandlerRecord *next;
3948
} IOHandlerRecord;
3949

    
3950
static IOHandlerRecord *first_io_handler;
3951

    
3952
/* XXX: fd_read_poll should be suppressed, but an API change is
3953
   necessary in the character devices to suppress fd_can_read(). */
3954
int qemu_set_fd_handler2(int fd, 
3955
                         IOCanRWHandler *fd_read_poll, 
3956
                         IOHandler *fd_read, 
3957
                         IOHandler *fd_write, 
3958
                         void *opaque)
3959
{
3960
    IOHandlerRecord **pioh, *ioh;
3961

    
3962
    if (!fd_read && !fd_write) {
3963
        pioh = &first_io_handler;
3964
        for(;;) {
3965
            ioh = *pioh;
3966
            if (ioh == NULL)
3967
                break;
3968
            if (ioh->fd == fd) {
3969
                *pioh = ioh->next;
3970
                qemu_free(ioh);
3971
                break;
3972
            }
3973
            pioh = &ioh->next;
3974
        }
3975
    } else {
3976
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3977
            if (ioh->fd == fd)
3978
                goto found;
3979
        }
3980
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3981
        if (!ioh)
3982
            return -1;
3983
        ioh->next = first_io_handler;
3984
        first_io_handler = ioh;
3985
    found:
3986
        ioh->fd = fd;
3987
        ioh->fd_read_poll = fd_read_poll;
3988
        ioh->fd_read = fd_read;
3989
        ioh->fd_write = fd_write;
3990
        ioh->opaque = opaque;
3991
    }
3992
    return 0;
3993
}
3994

    
3995
int qemu_set_fd_handler(int fd, 
3996
                        IOHandler *fd_read, 
3997
                        IOHandler *fd_write, 
3998
                        void *opaque)
3999
{
4000
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4001
}
4002

    
4003
/***********************************************************/
4004
/* Polling handling */
4005

    
4006
typedef struct PollingEntry {
4007
    PollingFunc *func;
4008
    void *opaque;
4009
    struct PollingEntry *next;
4010
} PollingEntry;
4011

    
4012
static PollingEntry *first_polling_entry;
4013

    
4014
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4015
{
4016
    PollingEntry **ppe, *pe;
4017
    pe = qemu_mallocz(sizeof(PollingEntry));
4018
    if (!pe)
4019
        return -1;
4020
    pe->func = func;
4021
    pe->opaque = opaque;
4022
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4023
    *ppe = pe;
4024
    return 0;
4025
}
4026

    
4027
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4028
{
4029
    PollingEntry **ppe, *pe;
4030
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4031
        pe = *ppe;
4032
        if (pe->func == func && pe->opaque == opaque) {
4033
            *ppe = pe->next;
4034
            qemu_free(pe);
4035
            break;
4036
        }
4037
    }
4038
}
4039

    
4040
#ifdef _WIN32
4041
/***********************************************************/
4042
/* Wait objects support */
4043
typedef struct WaitObjects {
4044
    int num;
4045
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4046
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4047
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4048
} WaitObjects;
4049

    
4050
static WaitObjects wait_objects = {0};
4051
    
4052
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4053
{
4054
    WaitObjects *w = &wait_objects;
4055

    
4056
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4057
        return -1;
4058
    w->events[w->num] = handle;
4059
    w->func[w->num] = func;
4060
    w->opaque[w->num] = opaque;
4061
    w->num++;
4062
    return 0;
4063
}
4064

    
4065
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4066
{
4067
    int i, found;
4068
    WaitObjects *w = &wait_objects;
4069

    
4070
    found = 0;
4071
    for (i = 0; i < w->num; i++) {
4072
        if (w->events[i] == handle)
4073
            found = 1;
4074
        if (found) {
4075
            w->events[i] = w->events[i + 1];
4076
            w->func[i] = w->func[i + 1];
4077
            w->opaque[i] = w->opaque[i + 1];
4078
        }            
4079
    }
4080
    if (found)
4081
        w->num--;
4082
}
4083
#endif
4084

    
4085
/***********************************************************/
4086
/* savevm/loadvm support */
4087

    
4088
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4089
{
4090
    fwrite(buf, 1, size, f);
4091
}
4092

    
4093
void qemu_put_byte(QEMUFile *f, int v)
4094
{
4095
    fputc(v, f);
4096
}
4097

    
4098
void qemu_put_be16(QEMUFile *f, unsigned int v)
4099
{
4100
    qemu_put_byte(f, v >> 8);
4101
    qemu_put_byte(f, v);
4102
}
4103

    
4104
void qemu_put_be32(QEMUFile *f, unsigned int v)
4105
{
4106
    qemu_put_byte(f, v >> 24);
4107
    qemu_put_byte(f, v >> 16);
4108
    qemu_put_byte(f, v >> 8);
4109
    qemu_put_byte(f, v);
4110
}
4111

    
4112
void qemu_put_be64(QEMUFile *f, uint64_t v)
4113
{
4114
    qemu_put_be32(f, v >> 32);
4115
    qemu_put_be32(f, v);
4116
}
4117

    
4118
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4119
{
4120
    return fread(buf, 1, size, f);
4121
}
4122

    
4123
int qemu_get_byte(QEMUFile *f)
4124
{
4125
    int v;
4126
    v = fgetc(f);
4127
    if (v == EOF)
4128
        return 0;
4129
    else
4130
        return v;
4131
}
4132

    
4133
unsigned int qemu_get_be16(QEMUFile *f)
4134
{
4135
    unsigned int v;
4136
    v = qemu_get_byte(f) << 8;
4137
    v |= qemu_get_byte(f);
4138
    return v;
4139
}
4140

    
4141
unsigned int qemu_get_be32(QEMUFile *f)
4142
{
4143
    unsigned int v;
4144
    v = qemu_get_byte(f) << 24;
4145
    v |= qemu_get_byte(f) << 16;
4146
    v |= qemu_get_byte(f) << 8;
4147
    v |= qemu_get_byte(f);
4148
    return v;
4149
}
4150

    
4151
uint64_t qemu_get_be64(QEMUFile *f)
4152
{
4153
    uint64_t v;
4154
    v = (uint64_t)qemu_get_be32(f) << 32;
4155
    v |= qemu_get_be32(f);
4156
    return v;
4157
}
4158

    
4159
int64_t qemu_ftell(QEMUFile *f)
4160
{
4161
    return ftell(f);
4162
}
4163

    
4164
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4165
{
4166
    if (fseek(f, pos, whence) < 0)
4167
        return -1;
4168
    return ftell(f);
4169
}
4170

    
4171
typedef struct SaveStateEntry {
4172
    char idstr[256];
4173
    int instance_id;
4174
    int version_id;
4175
    SaveStateHandler *save_state;
4176
    LoadStateHandler *load_state;
4177
    void *opaque;
4178
    struct SaveStateEntry *next;
4179
} SaveStateEntry;
4180

    
4181
static SaveStateEntry *first_se;
4182

    
4183
int register_savevm(const char *idstr, 
4184
                    int instance_id, 
4185
                    int version_id,
4186
                    SaveStateHandler *save_state,
4187
                    LoadStateHandler *load_state,
4188
                    void *opaque)
4189
{
4190
    SaveStateEntry *se, **pse;
4191

    
4192
    se = qemu_malloc(sizeof(SaveStateEntry));
4193
    if (!se)
4194
        return -1;
4195
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4196
    se->instance_id = instance_id;
4197
    se->version_id = version_id;
4198
    se->save_state = save_state;
4199
    se->load_state = load_state;
4200
    se->opaque = opaque;
4201
    se->next = NULL;
4202

    
4203
    /* add at the end of list */
4204
    pse = &first_se;
4205
    while (*pse != NULL)
4206
        pse = &(*pse)->next;
4207
    *pse = se;
4208
    return 0;
4209
}
4210

    
4211
#define QEMU_VM_FILE_MAGIC   0x5145564d
4212
#define QEMU_VM_FILE_VERSION 0x00000001
4213

    
4214
int qemu_savevm(const char *filename)
4215
{
4216
    SaveStateEntry *se;
4217
    QEMUFile *f;
4218
    int len, len_pos, cur_pos, saved_vm_running, ret;
4219

    
4220
    saved_vm_running = vm_running;
4221
    vm_stop(0);
4222

    
4223
    f = fopen(filename, "wb");
4224
    if (!f) {
4225
        ret = -1;
4226
        goto the_end;
4227
    }
4228

    
4229
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4230
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4231

    
4232
    for(se = first_se; se != NULL; se = se->next) {
4233
        /* ID string */
4234
        len = strlen(se->idstr);
4235
        qemu_put_byte(f, len);
4236
        qemu_put_buffer(f, se->idstr, len);
4237

    
4238
        qemu_put_be32(f, se->instance_id);
4239
        qemu_put_be32(f, se->version_id);
4240

    
4241
        /* record size: filled later */
4242
        len_pos = ftell(f);
4243
        qemu_put_be32(f, 0);
4244
        
4245
        se->save_state(f, se->opaque);
4246

    
4247
        /* fill record size */
4248
        cur_pos = ftell(f);
4249
        len = ftell(f) - len_pos - 4;
4250
        fseek(f, len_pos, SEEK_SET);
4251
        qemu_put_be32(f, len);
4252
        fseek(f, cur_pos, SEEK_SET);
4253
    }
4254

    
4255
    fclose(f);
4256
    ret = 0;
4257
 the_end:
4258
    if (saved_vm_running)
4259
        vm_start();
4260
    return ret;
4261
}
4262

    
4263
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4264
{
4265
    SaveStateEntry *se;
4266

    
4267
    for(se = first_se; se != NULL; se = se->next) {
4268
        if (!strcmp(se->idstr, idstr) && 
4269
            instance_id == se->instance_id)
4270
            return se;
4271
    }
4272
    return NULL;
4273
}
4274

    
4275
int qemu_loadvm(const char *filename)
4276
{
4277
    SaveStateEntry *se;
4278
    QEMUFile *f;
4279
    int len, cur_pos, ret, instance_id, record_len, version_id;
4280
    int saved_vm_running;
4281
    unsigned int v;
4282
    char idstr[256];
4283
    
4284
    saved_vm_running = vm_running;
4285
    vm_stop(0);
4286

    
4287
    f = fopen(filename, "rb");
4288
    if (!f) {
4289
        ret = -1;
4290
        goto the_end;
4291
    }
4292

    
4293
    v = qemu_get_be32(f);
4294
    if (v != QEMU_VM_FILE_MAGIC)
4295
        goto fail;
4296
    v = qemu_get_be32(f);
4297
    if (v != QEMU_VM_FILE_VERSION) {
4298
    fail:
4299
        fclose(f);
4300
        ret = -1;
4301
        goto the_end;
4302
    }
4303
    for(;;) {
4304
        len = qemu_get_byte(f);
4305
        if (feof(f))
4306
            break;
4307
        qemu_get_buffer(f, idstr, len);
4308
        idstr[len] = '\0';
4309
        instance_id = qemu_get_be32(f);
4310
        version_id = qemu_get_be32(f);
4311
        record_len = qemu_get_be32(f);
4312
#if 0
4313
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4314
               idstr, instance_id, version_id, record_len);
4315
#endif
4316
        cur_pos = ftell(f);
4317
        se = find_se(idstr, instance_id);
4318
        if (!se) {
4319
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4320
                    instance_id, idstr);
4321
        } else {
4322
            ret = se->load_state(f, se->opaque, version_id);
4323
            if (ret < 0) {
4324
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4325
                        instance_id, idstr);
4326
            }
4327
        }
4328
        /* always seek to exact end of record */
4329
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4330
    }
4331
    fclose(f);
4332
    ret = 0;
4333
 the_end:
4334
    if (saved_vm_running)
4335
        vm_start();
4336
    return ret;
4337
}
4338

    
4339
/***********************************************************/
4340
/* cpu save/restore */
4341

    
4342
#if defined(TARGET_I386)
4343

    
4344
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4345
{
4346
    qemu_put_be32(f, dt->selector);
4347
    qemu_put_betl(f, dt->base);
4348
    qemu_put_be32(f, dt->limit);
4349
    qemu_put_be32(f, dt->flags);
4350
}
4351

    
4352
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4353
{
4354
    dt->selector = qemu_get_be32(f);
4355
    dt->base = qemu_get_betl(f);
4356
    dt->limit = qemu_get_be32(f);
4357
    dt->flags = qemu_get_be32(f);
4358
}
4359

    
4360
void cpu_save(QEMUFile *f, void *opaque)
4361
{
4362
    CPUState *env = opaque;
4363
    uint16_t fptag, fpus, fpuc, fpregs_format;
4364
    uint32_t hflags;
4365
    int i;
4366
    
4367
    for(i = 0; i < CPU_NB_REGS; i++)
4368
        qemu_put_betls(f, &env->regs[i]);
4369
    qemu_put_betls(f, &env->eip);
4370
    qemu_put_betls(f, &env->eflags);
4371
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4372
    qemu_put_be32s(f, &hflags);
4373
    
4374
    /* FPU */
4375
    fpuc = env->fpuc;
4376
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4377
    fptag = 0;
4378
    for(i = 0; i < 8; i++) {
4379
        fptag |= ((!env->fptags[i]) << i);
4380
    }
4381
    
4382
    qemu_put_be16s(f, &fpuc);
4383
    qemu_put_be16s(f, &fpus);
4384
    qemu_put_be16s(f, &fptag);
4385

    
4386
#ifdef USE_X86LDOUBLE
4387
    fpregs_format = 0;
4388
#else
4389
    fpregs_format = 1;
4390
#endif
4391
    qemu_put_be16s(f, &fpregs_format);
4392
    
4393
    for(i = 0; i < 8; i++) {
4394
#ifdef USE_X86LDOUBLE
4395
        {
4396
            uint64_t mant;
4397
            uint16_t exp;
4398
            /* we save the real CPU data (in case of MMX usage only 'mant'
4399
               contains the MMX register */
4400
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4401
            qemu_put_be64(f, mant);
4402
            qemu_put_be16(f, exp);
4403
        }
4404
#else
4405
        /* if we use doubles for float emulation, we save the doubles to
4406
           avoid losing information in case of MMX usage. It can give
4407
           problems if the image is restored on a CPU where long
4408
           doubles are used instead. */
4409
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4410
#endif
4411
    }
4412

    
4413
    for(i = 0; i < 6; i++)
4414
        cpu_put_seg(f, &env->segs[i]);
4415
    cpu_put_seg(f, &env->ldt);
4416
    cpu_put_seg(f, &env->tr);
4417
    cpu_put_seg(f, &env->gdt);
4418
    cpu_put_seg(f, &env->idt);
4419
    
4420
    qemu_put_be32s(f, &env->sysenter_cs);
4421
    qemu_put_be32s(f, &env->sysenter_esp);
4422
    qemu_put_be32s(f, &env->sysenter_eip);
4423
    
4424
    qemu_put_betls(f, &env->cr[0]);
4425
    qemu_put_betls(f, &env->cr[2]);
4426
    qemu_put_betls(f, &env->cr[3]);
4427
    qemu_put_betls(f, &env->cr[4]);
4428
    
4429
    for(i = 0; i < 8; i++)
4430
        qemu_put_betls(f, &env->dr[i]);
4431

    
4432
    /* MMU */
4433
    qemu_put_be32s(f, &env->a20_mask);
4434

    
4435
    /* XMM */
4436
    qemu_put_be32s(f, &env->mxcsr);
4437
    for(i = 0; i < CPU_NB_REGS; i++) {
4438
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4439
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4440
    }
4441

    
4442
#ifdef TARGET_X86_64
4443
    qemu_put_be64s(f, &env->efer);
4444
    qemu_put_be64s(f, &env->star);
4445
    qemu_put_be64s(f, &env->lstar);
4446
    qemu_put_be64s(f, &env->cstar);
4447
    qemu_put_be64s(f, &env->fmask);
4448
    qemu_put_be64s(f, &env->kernelgsbase);
4449
#endif
4450
}
4451

    
4452
#ifdef USE_X86LDOUBLE
4453
/* XXX: add that in a FPU generic layer */
4454
union x86_longdouble {
4455
    uint64_t mant;
4456
    uint16_t exp;
4457
};
4458

    
4459
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
4460
#define EXPBIAS1 1023
4461
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
4462
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
4463

    
4464
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4465
{
4466
    int e;
4467
    /* mantissa */
4468
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4469
    /* exponent + sign */
4470
    e = EXPD1(temp) - EXPBIAS1 + 16383;
4471
    e |= SIGND1(temp) >> 16;
4472
    p->exp = e;
4473
}
4474
#endif
4475

    
4476
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4477
{
4478
    CPUState *env = opaque;
4479
    int i, guess_mmx;
4480
    uint32_t hflags;
4481
    uint16_t fpus, fpuc, fptag, fpregs_format;
4482

    
4483
    if (version_id != 3)
4484
        return -EINVAL;
4485
    for(i = 0; i < CPU_NB_REGS; i++)
4486
        qemu_get_betls(f, &env->regs[i]);
4487
    qemu_get_betls(f, &env->eip);
4488
    qemu_get_betls(f, &env->eflags);
4489
    qemu_get_be32s(f, &hflags);
4490

    
4491
    qemu_get_be16s(f, &fpuc);
4492
    qemu_get_be16s(f, &fpus);
4493
    qemu_get_be16s(f, &fptag);
4494
    qemu_get_be16s(f, &fpregs_format);
4495
    
4496
    /* NOTE: we cannot always restore the FPU state if the image come
4497
       from a host with a different 'USE_X86LDOUBLE' define. We guess
4498
       if we are in an MMX state to restore correctly in that case. */
4499
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4500
    for(i = 0; i < 8; i++) {
4501
        uint64_t mant;
4502
        uint16_t exp;
4503
        
4504
        switch(fpregs_format) {
4505
        case 0:
4506
            mant = qemu_get_be64(f);
4507
            exp = qemu_get_be16(f);
4508
#ifdef USE_X86LDOUBLE
4509
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
4510
#else
4511
            /* difficult case */
4512
            if (guess_mmx)
4513
                env->fpregs[i].mmx.MMX_Q(0) = mant;
4514
            else
4515
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
4516
#endif
4517
            break;
4518
        case 1:
4519
            mant = qemu_get_be64(f);
4520
#ifdef USE_X86LDOUBLE
4521
            {
4522
                union x86_longdouble *p;
4523
                /* difficult case */
4524
                p = (void *)&env->fpregs[i];
4525
                if (guess_mmx) {
4526
                    p->mant = mant;
4527
                    p->exp = 0xffff;
4528
                } else {
4529
                    fp64_to_fp80(p, mant);
4530
                }
4531
            }
4532
#else
4533
            env->fpregs[i].mmx.MMX_Q(0) = mant;
4534
#endif            
4535
            break;
4536
        default:
4537
            return -EINVAL;
4538
        }
4539
    }
4540

    
4541
    env->fpuc = fpuc;
4542
    /* XXX: restore FPU round state */
4543
    env->fpstt = (fpus >> 11) & 7;
4544
    env->fpus = fpus & ~0x3800;
4545
    fptag ^= 0xff;
4546
    for(i = 0; i < 8; i++) {
4547
        env->fptags[i] = (fptag >> i) & 1;
4548
    }
4549
    
4550
    for(i = 0; i < 6; i++)
4551
        cpu_get_seg(f, &env->segs[i]);
4552
    cpu_get_seg(f, &env->ldt);
4553
    cpu_get_seg(f, &env->tr);
4554
    cpu_get_seg(f, &env->gdt);
4555
    cpu_get_seg(f, &env->idt);
4556
    
4557
    qemu_get_be32s(f, &env->sysenter_cs);
4558
    qemu_get_be32s(f, &env->sysenter_esp);
4559
    qemu_get_be32s(f, &env->sysenter_eip);
4560
    
4561
    qemu_get_betls(f, &env->cr[0]);
4562
    qemu_get_betls(f, &env->cr[2]);
4563
    qemu_get_betls(f, &env->cr[3]);
4564
    qemu_get_betls(f, &env->cr[4]);
4565
    
4566
    for(i = 0; i < 8; i++)
4567
        qemu_get_betls(f, &env->dr[i]);
4568

    
4569
    /* MMU */
4570
    qemu_get_be32s(f, &env->a20_mask);
4571

    
4572
    qemu_get_be32s(f, &env->mxcsr);
4573
    for(i = 0; i < CPU_NB_REGS; i++) {
4574
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4575
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4576
    }
4577

    
4578
#ifdef TARGET_X86_64
4579
    qemu_get_be64s(f, &env->efer);
4580
    qemu_get_be64s(f, &env->star);
4581
    qemu_get_be64s(f, &env->lstar);
4582
    qemu_get_be64s(f, &env->cstar);
4583
    qemu_get_be64s(f, &env->fmask);
4584
    qemu_get_be64s(f, &env->kernelgsbase);
4585
#endif
4586

    
4587
    /* XXX: compute hflags from scratch, except for CPL and IIF */
4588
    env->hflags = hflags;
4589
    tlb_flush(env, 1);
4590
    return 0;
4591
}
4592

    
4593
#elif defined(TARGET_PPC)
4594
void cpu_save(QEMUFile *f, void *opaque)
4595
{
4596
}
4597

    
4598
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4599
{
4600
    return 0;
4601
}
4602

    
4603
#elif defined(TARGET_MIPS)
4604
void cpu_save(QEMUFile *f, void *opaque)
4605
{
4606
}
4607

    
4608
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4609
{
4610
    return 0;
4611
}
4612

    
4613
#elif defined(TARGET_SPARC)
4614
void cpu_save(QEMUFile *f, void *opaque)
4615
{
4616
    CPUState *env = opaque;
4617
    int i;
4618
    uint32_t tmp;
4619

    
4620
    for(i = 0; i < 8; i++)
4621
        qemu_put_betls(f, &env->gregs[i]);
4622
    for(i = 0; i < NWINDOWS * 16; i++)
4623
        qemu_put_betls(f, &env->regbase[i]);
4624

    
4625
    /* FPU */
4626
    for(i = 0; i < TARGET_FPREGS; i++) {
4627
        union {
4628
            float32 f;
4629
            uint32_t i;
4630
        } u;
4631
        u.f = env->fpr[i];
4632
        qemu_put_be32(f, u.i);
4633
    }
4634

    
4635
    qemu_put_betls(f, &env->pc);
4636
    qemu_put_betls(f, &env->npc);
4637
    qemu_put_betls(f, &env->y);
4638
    tmp = GET_PSR(env);
4639
    qemu_put_be32(f, tmp);
4640
    qemu_put_betls(f, &env->fsr);
4641
    qemu_put_betls(f, &env->tbr);
4642
#ifndef TARGET_SPARC64
4643
    qemu_put_be32s(f, &env->wim);
4644
    /* MMU */
4645
    for(i = 0; i < 16; i++)
4646
        qemu_put_be32s(f, &env->mmuregs[i]);
4647
#endif
4648
}
4649

    
4650
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4651
{
4652
    CPUState *env = opaque;
4653
    int i;
4654
    uint32_t tmp;
4655

    
4656
    for(i = 0; i < 8; i++)
4657
        qemu_get_betls(f, &env->gregs[i]);
4658
    for(i = 0; i < NWINDOWS * 16; i++)
4659
        qemu_get_betls(f, &env->regbase[i]);
4660

    
4661
    /* FPU */
4662
    for(i = 0; i < TARGET_FPREGS; i++) {
4663
        union {
4664
            float32 f;
4665
            uint32_t i;
4666
        } u;
4667
        u.i = qemu_get_be32(f);
4668
        env->fpr[i] = u.f;
4669
    }
4670

    
4671
    qemu_get_betls(f, &env->pc);
4672
    qemu_get_betls(f, &env->npc);
4673
    qemu_get_betls(f, &env->y);
4674
    tmp = qemu_get_be32(f);
4675
    env->cwp = 0; /* needed to ensure that the wrapping registers are
4676
                     correctly updated */
4677
    PUT_PSR(env, tmp);
4678
    qemu_get_betls(f, &env->fsr);
4679
    qemu_get_betls(f, &env->tbr);
4680
#ifndef TARGET_SPARC64
4681
    qemu_get_be32s(f, &env->wim);
4682
    /* MMU */
4683
    for(i = 0; i < 16; i++)
4684
        qemu_get_be32s(f, &env->mmuregs[i]);
4685
#endif
4686
    tlb_flush(env, 1);
4687
    return 0;
4688
}
4689

    
4690
#elif defined(TARGET_ARM)
4691

    
4692
/* ??? Need to implement these.  */
4693
void cpu_save(QEMUFile *f, void *opaque)
4694
{
4695
}
4696

    
4697
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4698
{
4699
    return 0;
4700
}
4701

    
4702
#else
4703

    
4704
#warning No CPU save/restore functions
4705

    
4706
#endif
4707

    
4708
/***********************************************************/
4709
/* ram save/restore */
4710

    
4711
/* we just avoid storing empty pages */
4712
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4713
{
4714
    int i, v;
4715

    
4716
    v = buf[0];
4717
    for(i = 1; i < len; i++) {
4718
        if (buf[i] != v)
4719
            goto normal_save;
4720
    }
4721
    qemu_put_byte(f, 1);
4722
    qemu_put_byte(f, v);
4723
    return;
4724
 normal_save:
4725
    qemu_put_byte(f, 0); 
4726
    qemu_put_buffer(f, buf, len);
4727
}
4728

    
4729
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4730
{
4731
    int v;
4732

    
4733
    v = qemu_get_byte(f);
4734
    switch(v) {
4735
    case 0:
4736
        if (qemu_get_buffer(f, buf, len) != len)
4737
            return -EIO;
4738
        break;
4739
    case 1:
4740
        v = qemu_get_byte(f);
4741
        memset(buf, v, len);
4742
        break;
4743
    default:
4744
        return -EINVAL;
4745
    }
4746
    return 0;
4747
}
4748

    
4749
static void ram_save(QEMUFile *f, void *opaque)
4750
{
4751
    int i;
4752
    qemu_put_be32(f, phys_ram_size);
4753
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4754
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4755
    }
4756
}
4757

    
4758
static int ram_load(QEMUFile *f, void *opaque, int version_id)
4759
{
4760
    int i, ret;
4761

    
4762
    if (version_id != 1)
4763
        return -EINVAL;
4764
    if (qemu_get_be32(f) != phys_ram_size)
4765
        return -EINVAL;
4766
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4767
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4768
        if (ret)
4769
            return ret;
4770
    }
4771
    return 0;
4772
}
4773

    
4774
/***********************************************************/
4775
/* bottom halves (can be seen as timers which expire ASAP) */
4776

    
4777
struct QEMUBH {
4778
    QEMUBHFunc *cb;
4779
    void *opaque;
4780
    int scheduled;
4781
    QEMUBH *next;
4782
};
4783

    
4784
static QEMUBH *first_bh = NULL;
4785

    
4786
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4787
{
4788
    QEMUBH *bh;
4789
    bh = qemu_mallocz(sizeof(QEMUBH));
4790
    if (!bh)
4791
        return NULL;
4792
    bh->cb = cb;
4793
    bh->opaque = opaque;
4794
    return bh;
4795
}
4796

    
4797
void qemu_bh_poll(void)
4798
{
4799
    QEMUBH *bh, **pbh;
4800

    
4801
    for(;;) {
4802
        pbh = &first_bh;
4803
        bh = *pbh;
4804
        if (!bh)
4805
            break;
4806
        *pbh = bh->next;
4807
        bh->scheduled = 0;
4808
        bh->cb(bh->opaque);
4809
    }
4810
}
4811

    
4812
void qemu_bh_schedule(QEMUBH *bh)
4813
{
4814
    CPUState *env = cpu_single_env;
4815
    if (bh->scheduled)
4816
        return;
4817
    bh->scheduled = 1;
4818
    bh->next = first_bh;
4819
    first_bh = bh;
4820

    
4821
    /* stop the currently executing CPU to execute the BH ASAP */
4822
    if (env) {
4823
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4824
    }
4825
}
4826

    
4827
void qemu_bh_cancel(QEMUBH *bh)
4828
{
4829
    QEMUBH **pbh;
4830
    if (bh->scheduled) {
4831
        pbh = &first_bh;
4832
        while (*pbh != bh)
4833
            pbh = &(*pbh)->next;
4834
        *pbh = bh->next;
4835
        bh->scheduled = 0;
4836
    }
4837
}
4838

    
4839
void qemu_bh_delete(QEMUBH *bh)
4840
{
4841
    qemu_bh_cancel(bh);
4842
    qemu_free(bh);
4843
}
4844

    
4845
/***********************************************************/
4846
/* machine registration */
4847

    
4848
QEMUMachine *first_machine = NULL;
4849

    
4850
int qemu_register_machine(QEMUMachine *m)
4851
{
4852
    QEMUMachine **pm;
4853
    pm = &first_machine;
4854
    while (*pm != NULL)
4855
        pm = &(*pm)->next;
4856
    m->next = NULL;
4857
    *pm = m;
4858
    return 0;
4859
}
4860

    
4861
QEMUMachine *find_machine(const char *name)
4862
{
4863
    QEMUMachine *m;
4864

    
4865
    for(m = first_machine; m != NULL; m = m->next) {
4866
        if (!strcmp(m->name, name))
4867
            return m;
4868
    }
4869
    return NULL;
4870
}
4871

    
4872
/***********************************************************/
4873
/* main execution loop */
4874

    
4875
void gui_update(void *opaque)
4876
{
4877
    display_state.dpy_refresh(&display_state);
4878
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4879
}
4880

    
4881
struct vm_change_state_entry {
4882
    VMChangeStateHandler *cb;
4883
    void *opaque;
4884
    LIST_ENTRY (vm_change_state_entry) entries;
4885
};
4886

    
4887
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4888

    
4889
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4890
                                                     void *opaque)
4891
{
4892
    VMChangeStateEntry *e;
4893

    
4894
    e = qemu_mallocz(sizeof (*e));
4895
    if (!e)
4896
        return NULL;
4897

    
4898
    e->cb = cb;
4899
    e->opaque = opaque;
4900
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4901
    return e;
4902
}
4903

    
4904
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4905
{
4906
    LIST_REMOVE (e, entries);
4907
    qemu_free (e);
4908
}
4909

    
4910
static void vm_state_notify(int running)
4911
{
4912
    VMChangeStateEntry *e;
4913

    
4914
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4915
        e->cb(e->opaque, running);
4916
    }
4917
}
4918

    
4919
/* XXX: support several handlers */
4920
static VMStopHandler *vm_stop_cb;
4921
static void *vm_stop_opaque;
4922

    
4923
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4924
{
4925
    vm_stop_cb = cb;
4926
    vm_stop_opaque = opaque;
4927
    return 0;
4928
}
4929

    
4930
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4931
{
4932
    vm_stop_cb = NULL;
4933
}
4934

    
4935
void vm_start(void)
4936
{
4937
    if (!vm_running) {
4938
        cpu_enable_ticks();
4939
        vm_running = 1;
4940
        vm_state_notify(1);
4941
    }
4942
}
4943

    
4944
void vm_stop(int reason) 
4945
{
4946
    if (vm_running) {
4947
        cpu_disable_ticks();
4948
        vm_running = 0;
4949
        if (reason != 0) {
4950
            if (vm_stop_cb) {
4951
                vm_stop_cb(vm_stop_opaque, reason);
4952
            }
4953
        }
4954
        vm_state_notify(0);
4955
    }
4956
}
4957

    
4958
/* reset/shutdown handler */
4959

    
4960
typedef struct QEMUResetEntry {
4961
    QEMUResetHandler *func;
4962
    void *opaque;
4963
    struct QEMUResetEntry *next;
4964
} QEMUResetEntry;
4965

    
4966
static QEMUResetEntry *first_reset_entry;
4967
static int reset_requested;
4968
static int shutdown_requested;
4969
static int powerdown_requested;
4970

    
4971
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4972
{
4973
    QEMUResetEntry **pre, *re;
4974

    
4975
    pre = &first_reset_entry;
4976
    while (*pre != NULL)
4977
        pre = &(*pre)->next;
4978
    re = qemu_mallocz(sizeof(QEMUResetEntry));
4979
    re->func = func;
4980
    re->opaque = opaque;
4981
    re->next = NULL;
4982
    *pre = re;
4983
}
4984

    
4985
void qemu_system_reset(void)
4986
{
4987
    QEMUResetEntry *re;
4988

    
4989
    /* reset all devices */
4990
    for(re = first_reset_entry; re != NULL; re = re->next) {
4991
        re->func(re->opaque);
4992
    }
4993
}
4994

    
4995
void qemu_system_reset_request(void)
4996
{
4997
    reset_requested = 1;
4998
    if (cpu_single_env)
4999
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5000
}
5001

    
5002
void qemu_system_shutdown_request(void)
5003
{
5004
    shutdown_requested = 1;
5005
    if (cpu_single_env)
5006
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5007
}
5008

    
5009
void qemu_system_powerdown_request(void)
5010
{
5011
    powerdown_requested = 1;
5012
    if (cpu_single_env)
5013
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5014
}
5015

    
5016
void main_loop_wait(int timeout)
5017
{
5018
    IOHandlerRecord *ioh, *ioh_next;
5019
    fd_set rfds, wfds, xfds;
5020
    int ret, nfds;
5021
    struct timeval tv;
5022
    PollingEntry *pe;
5023

    
5024

    
5025
    /* XXX: need to suppress polling by better using win32 events */
5026
    ret = 0;
5027
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5028
        ret |= pe->func(pe->opaque);
5029
    }
5030
#ifdef _WIN32
5031
    if (ret == 0 && timeout > 0) {
5032
        int err;
5033
        WaitObjects *w = &wait_objects;
5034
        
5035
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5036
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5037
            if (w->func[ret - WAIT_OBJECT_0])
5038
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5039
        } else if (ret == WAIT_TIMEOUT) {
5040
        } else {
5041
            err = GetLastError();
5042
            fprintf(stderr, "Wait error %d %d\n", ret, err);
5043
        }
5044
    }
5045
#endif
5046
    /* poll any events */
5047
    /* XXX: separate device handlers from system ones */
5048
    nfds = -1;
5049
    FD_ZERO(&rfds);
5050
    FD_ZERO(&wfds);
5051
    FD_ZERO(&xfds);
5052
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5053
        if (ioh->fd_read &&
5054
            (!ioh->fd_read_poll ||
5055
             ioh->fd_read_poll(ioh->opaque) != 0)) {
5056
            FD_SET(ioh->fd, &rfds);
5057