Statistics
| Branch: | Revision:

root / vl.c @ 45a8f3ca

History | View | Annotate | Download (143.6 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
#include <winsock2.h>
70
#include <ws2tcpip.h>
71
#define getopt_long_only getopt_long
72
#define memalign(align, size) malloc(size)
73
#endif
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
#if !defined(CONFIG_SOFTMMU)
96
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
97
#else
98
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
99
#endif
100

    
101
#ifdef TARGET_PPC
102
#define DEFAULT_RAM_SIZE 144
103
#else
104
#define DEFAULT_RAM_SIZE 128
105
#endif
106
/* in ms */
107
#define GUI_REFRESH_INTERVAL 30
108

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
293
/***********************************************************/
294

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

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

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

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

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

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

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

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

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

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

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

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

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

    
444
/***********************************************************/
445
/* keyboard/mouse */
446

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

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

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

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

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

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

    
486
/***********************************************************/
487
/* timers */
488

    
489
#if defined(__powerpc__)
490

    
491
static inline uint32_t get_tbl(void) 
492
{
493
    uint32_t tbl;
494
    asm volatile("mftb %0" : "=r" (tbl));
495
    return tbl;
496
}
497

    
498
static inline uint32_t get_tbu(void) 
499
{
500
        uint32_t tbl;
501
        asm volatile("mftbu %0" : "=r" (tbl));
502
        return tbl;
503
}
504

    
505
int64_t cpu_get_real_ticks(void)
506
{
507
    uint32_t l, h, h1;
508
    /* NOTE: we test if wrapping has occurred */
509
    do {
510
        h = get_tbu();
511
        l = get_tbl();
512
        h1 = get_tbu();
513
    } while (h != h1);
514
    return ((int64_t)h << 32) | l;
515
}
516

    
517
#elif defined(__i386__)
518

    
519
int64_t cpu_get_real_ticks(void)
520
{
521
    int64_t val;
522
    asm volatile ("rdtsc" : "=A" (val));
523
    return val;
524
}
525

    
526
#elif defined(__x86_64__)
527

    
528
int64_t cpu_get_real_ticks(void)
529
{
530
    uint32_t low,high;
531
    int64_t val;
532
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
533
    val = high;
534
    val <<= 32;
535
    val |= low;
536
    return val;
537
}
538

    
539
#elif defined(__ia64)
540

    
541
int64_t cpu_get_real_ticks(void)
542
{
543
        int64_t val;
544
        asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
545
        return val;
546
}
547

    
548
#elif defined(__s390__)
549

    
550
int64_t cpu_get_real_ticks(void)
551
{
552
    int64_t val;
553
    asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
554
    return val;
555
}
556

    
557
#else
558
#error unsupported CPU
559
#endif
560

    
561
static int64_t cpu_ticks_offset;
562
static int cpu_ticks_enabled;
563

    
564
static inline int64_t cpu_get_ticks(void)
565
{
566
    if (!cpu_ticks_enabled) {
567
        return cpu_ticks_offset;
568
    } else {
569
        return cpu_get_real_ticks() + cpu_ticks_offset;
570
    }
571
}
572

    
573
/* enable cpu_get_ticks() */
574
void cpu_enable_ticks(void)
575
{
576
    if (!cpu_ticks_enabled) {
577
        cpu_ticks_offset -= cpu_get_real_ticks();
578
        cpu_ticks_enabled = 1;
579
    }
580
}
581

    
582
/* disable cpu_get_ticks() : the clock is stopped. You must not call
583
   cpu_get_ticks() after that.  */
584
void cpu_disable_ticks(void)
585
{
586
    if (cpu_ticks_enabled) {
587
        cpu_ticks_offset = cpu_get_ticks();
588
        cpu_ticks_enabled = 0;
589
    }
590
}
591

    
592
static int64_t get_clock(void)
593
{
594
#ifdef _WIN32
595
    struct _timeb tb;
596
    _ftime(&tb);
597
    return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
598
#else
599
    struct timeval tv;
600
    gettimeofday(&tv, NULL);
601
    return tv.tv_sec * 1000000LL + tv.tv_usec;
602
#endif
603
}
604

    
605
void cpu_calibrate_ticks(void)
606
{
607
    int64_t usec, ticks;
608

    
609
    usec = get_clock();
610
    ticks = cpu_get_real_ticks();
611
#ifdef _WIN32
612
    Sleep(50);
613
#else
614
    usleep(50 * 1000);
615
#endif
616
    usec = get_clock() - usec;
617
    ticks = cpu_get_real_ticks() - ticks;
618
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
619
}
620

    
621
/* compute with 96 bit intermediate result: (a*b)/c */
622
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
623
{
624
    union {
625
        uint64_t ll;
626
        struct {
627
#ifdef WORDS_BIGENDIAN
628
            uint32_t high, low;
629
#else
630
            uint32_t low, high;
631
#endif            
632
        } l;
633
    } u, res;
634
    uint64_t rl, rh;
635

    
636
    u.ll = a;
637
    rl = (uint64_t)u.l.low * (uint64_t)b;
638
    rh = (uint64_t)u.l.high * (uint64_t)b;
639
    rh += (rl >> 32);
640
    res.l.high = rh / c;
641
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
642
    return res.ll;
643
}
644

    
645
#define QEMU_TIMER_REALTIME 0
646
#define QEMU_TIMER_VIRTUAL  1
647

    
648
struct QEMUClock {
649
    int type;
650
    /* XXX: add frequency */
651
};
652

    
653
struct QEMUTimer {
654
    QEMUClock *clock;
655
    int64_t expire_time;
656
    QEMUTimerCB *cb;
657
    void *opaque;
658
    struct QEMUTimer *next;
659
};
660

    
661
QEMUClock *rt_clock;
662
QEMUClock *vm_clock;
663

    
664
static QEMUTimer *active_timers[2];
665
#ifdef _WIN32
666
static MMRESULT timerID;
667
#else
668
/* frequency of the times() clock tick */
669
static int timer_freq;
670
#endif
671

    
672
QEMUClock *qemu_new_clock(int type)
673
{
674
    QEMUClock *clock;
675
    clock = qemu_mallocz(sizeof(QEMUClock));
676
    if (!clock)
677
        return NULL;
678
    clock->type = type;
679
    return clock;
680
}
681

    
682
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
683
{
684
    QEMUTimer *ts;
685

    
686
    ts = qemu_mallocz(sizeof(QEMUTimer));
687
    ts->clock = clock;
688
    ts->cb = cb;
689
    ts->opaque = opaque;
690
    return ts;
691
}
692

    
693
void qemu_free_timer(QEMUTimer *ts)
694
{
695
    qemu_free(ts);
696
}
697

    
698
/* stop a timer, but do not dealloc it */
699
void qemu_del_timer(QEMUTimer *ts)
700
{
701
    QEMUTimer **pt, *t;
702

    
703
    /* NOTE: this code must be signal safe because
704
       qemu_timer_expired() can be called from a signal. */
705
    pt = &active_timers[ts->clock->type];
706
    for(;;) {
707
        t = *pt;
708
        if (!t)
709
            break;
710
        if (t == ts) {
711
            *pt = t->next;
712
            break;
713
        }
714
        pt = &t->next;
715
    }
716
}
717

    
718
/* modify the current timer so that it will be fired when current_time
719
   >= expire_time. The corresponding callback will be called. */
720
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
721
{
722
    QEMUTimer **pt, *t;
723

    
724
    qemu_del_timer(ts);
725

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

    
743
int qemu_timer_pending(QEMUTimer *ts)
744
{
745
    QEMUTimer *t;
746
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
747
        if (t == ts)
748
            return 1;
749
    }
750
    return 0;
751
}
752

    
753
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
754
{
755
    if (!timer_head)
756
        return 0;
757
    return (timer_head->expire_time <= current_time);
758
}
759

    
760
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
761
{
762
    QEMUTimer *ts;
763
    
764
    for(;;) {
765
        ts = *ptimer_head;
766
        if (!ts || ts->expire_time > current_time)
767
            break;
768
        /* remove timer from the list before calling the callback */
769
        *ptimer_head = ts->next;
770
        ts->next = NULL;
771
        
772
        /* run the callback (the timer list can be modified) */
773
        ts->cb(ts->opaque);
774
    }
775
}
776

    
777
int64_t qemu_get_clock(QEMUClock *clock)
778
{
779
    switch(clock->type) {
780
    case QEMU_TIMER_REALTIME:
781
#ifdef _WIN32
782
        return GetTickCount();
783
#else
784
        {
785
            struct tms tp;
786

    
787
            /* Note that using gettimeofday() is not a good solution
788
               for timers because its value change when the date is
789
               modified. */
790
            if (timer_freq == 100) {
791
                return times(&tp) * 10;
792
            } else {
793
                return ((int64_t)times(&tp) * 1000) / timer_freq;
794
            }
795
        }
796
#endif
797
    default:
798
    case QEMU_TIMER_VIRTUAL:
799
        return cpu_get_ticks();
800
    }
801
}
802

    
803
/* save a timer */
804
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
805
{
806
    uint64_t expire_time;
807

    
808
    if (qemu_timer_pending(ts)) {
809
        expire_time = ts->expire_time;
810
    } else {
811
        expire_time = -1;
812
    }
813
    qemu_put_be64(f, expire_time);
814
}
815

    
816
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
817
{
818
    uint64_t expire_time;
819

    
820
    expire_time = qemu_get_be64(f);
821
    if (expire_time != -1) {
822
        qemu_mod_timer(ts, expire_time);
823
    } else {
824
        qemu_del_timer(ts);
825
    }
826
}
827

    
828
static void timer_save(QEMUFile *f, void *opaque)
829
{
830
    if (cpu_ticks_enabled) {
831
        hw_error("cannot save state if virtual timers are running");
832
    }
833
    qemu_put_be64s(f, &cpu_ticks_offset);
834
    qemu_put_be64s(f, &ticks_per_sec);
835
}
836

    
837
static int timer_load(QEMUFile *f, void *opaque, int version_id)
838
{
839
    if (version_id != 1)
840
        return -EINVAL;
841
    if (cpu_ticks_enabled) {
842
        return -EINVAL;
843
    }
844
    qemu_get_be64s(f, &cpu_ticks_offset);
845
    qemu_get_be64s(f, &ticks_per_sec);
846
    return 0;
847
}
848

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

    
902
#ifndef _WIN32
903

    
904
#if defined(__linux__)
905

    
906
#define RTC_FREQ 1024
907

    
908
static int rtc_fd;
909

    
910
static int start_rtc_timer(void)
911
{
912
    rtc_fd = open("/dev/rtc", O_RDONLY);
913
    if (rtc_fd < 0)
914
        return -1;
915
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
916
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
917
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
918
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
919
        goto fail;
920
    }
921
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
922
    fail:
923
        close(rtc_fd);
924
        return -1;
925
    }
926
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
927
    return 0;
928
}
929

    
930
#else
931

    
932
static int start_rtc_timer(void)
933
{
934
    return -1;
935
}
936

    
937
#endif /* !defined(__linux__) */
938

    
939
#endif /* !defined(_WIN32) */
940

    
941
static void init_timers(void)
942
{
943
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
944
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
945

    
946
#ifdef _WIN32
947
    {
948
        int count=0;
949
        timerID = timeSetEvent(1,     // interval (ms)
950
                               0,     // resolution
951
                               host_alarm_handler, // function
952
                               (DWORD)&count,  // user parameter
953
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
954
         if( !timerID ) {
955
            perror("failed timer alarm");
956
            exit(1);
957
         }
958
    }
959
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
960
#else
961
    {
962
        struct sigaction act;
963
        struct itimerval itv;
964
        
965
        /* get times() syscall frequency */
966
        timer_freq = sysconf(_SC_CLK_TCK);
967
        
968
        /* timer signal */
969
        sigfillset(&act.sa_mask);
970
       act.sa_flags = 0;
971
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
972
        act.sa_flags |= SA_ONSTACK;
973
#endif
974
        act.sa_handler = host_alarm_handler;
975
        sigaction(SIGALRM, &act, NULL);
976

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

    
986
#if defined(__linux__)
987
        if (itv.it_interval.tv_usec > 1000) {
988
            /* try to use /dev/rtc to have a faster timer */
989
            if (start_rtc_timer() < 0)
990
                goto use_itimer;
991
            /* disable itimer */
992
            itv.it_interval.tv_sec = 0;
993
            itv.it_interval.tv_usec = 0;
994
            itv.it_value.tv_sec = 0;
995
            itv.it_value.tv_usec = 0;
996
            setitimer(ITIMER_REAL, &itv, NULL);
997

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

    
1013
void quit_timers(void)
1014
{
1015
#ifdef _WIN32
1016
    timeKillEvent(timerID);
1017
#endif
1018
}
1019

    
1020
/***********************************************************/
1021
/* character device */
1022

    
1023
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1024
{
1025
    return s->chr_write(s, buf, len);
1026
}
1027

    
1028
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1029
{
1030
    if (!s->chr_ioctl)
1031
        return -ENOTSUP;
1032
    return s->chr_ioctl(s, cmd, arg);
1033
}
1034

    
1035
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1036
{
1037
    char buf[4096];
1038
    va_list ap;
1039
    va_start(ap, fmt);
1040
    vsnprintf(buf, sizeof(buf), fmt, ap);
1041
    qemu_chr_write(s, buf, strlen(buf));
1042
    va_end(ap);
1043
}
1044

    
1045
void qemu_chr_send_event(CharDriverState *s, int event)
1046
{
1047
    if (s->chr_send_event)
1048
        s->chr_send_event(s, event);
1049
}
1050

    
1051
void qemu_chr_add_read_handler(CharDriverState *s, 
1052
                               IOCanRWHandler *fd_can_read, 
1053
                               IOReadHandler *fd_read, void *opaque)
1054
{
1055
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1056
}
1057
             
1058
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1059
{
1060
    s->chr_event = chr_event;
1061
}
1062

    
1063
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1064
{
1065
    return len;
1066
}
1067

    
1068
static void null_chr_add_read_handler(CharDriverState *chr, 
1069
                                    IOCanRWHandler *fd_can_read, 
1070
                                    IOReadHandler *fd_read, void *opaque)
1071
{
1072
}
1073

    
1074
CharDriverState *qemu_chr_open_null(void)
1075
{
1076
    CharDriverState *chr;
1077

    
1078
    chr = qemu_mallocz(sizeof(CharDriverState));
1079
    if (!chr)
1080
        return NULL;
1081
    chr->chr_write = null_chr_write;
1082
    chr->chr_add_read_handler = null_chr_add_read_handler;
1083
    return chr;
1084
}
1085

    
1086
#ifdef _WIN32
1087

    
1088
#define socket_error() WSAGetLastError()
1089
#undef EINTR
1090
#define EWOULDBLOCK WSAEWOULDBLOCK
1091
#define EINTR       WSAEINTR
1092
#define EINPROGRESS WSAEINPROGRESS
1093

    
1094
static void socket_cleanup(void)
1095
{
1096
    WSACleanup();
1097
}
1098

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

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

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

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

    
1143
#else
1144

    
1145
#define socket_error() errno
1146
#define closesocket(s) close(s)
1147

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

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

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

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

    
1179
#ifndef _WIN32
1180

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

    
1189
#define STDIO_MAX_CLIENTS 2
1190

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1287

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

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

    
1293
#define TERM_FIFO_MAX_SIZE 1
1294

    
1295
static int term_got_escape, client_index;
1296
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1297
int term_fifo_size;
1298

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

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

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

    
1376
static int stdio_read_poll(void *opaque)
1377
{
1378
    CharDriverState *chr;
1379
    FDCharDriver *s;
1380

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

    
1399
static void stdio_read(void *opaque)
1400
{
1401
    int size;
1402
    uint8_t buf[1];
1403
    
1404
    size = read(0, buf, 1);
1405
    if (size > 0)
1406
        stdio_received_byte(buf[0]);
1407
}
1408

    
1409
/* init terminal so that we can grab keys */
1410
static struct termios oldtty;
1411
static int old_fd0_flags;
1412

    
1413
static void term_exit(void)
1414
{
1415
    tcsetattr (0, TCSANOW, &oldtty);
1416
    fcntl(0, F_SETFL, old_fd0_flags);
1417
}
1418

    
1419
static void term_init(void)
1420
{
1421
    struct termios tty;
1422

    
1423
    tcgetattr (0, &tty);
1424
    oldtty = tty;
1425
    old_fd0_flags = fcntl(0, F_GETFL);
1426

    
1427
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1428
                          |INLCR|IGNCR|ICRNL|IXON);
1429
    tty.c_oflag |= OPOST;
1430
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1431
    /* if graphical mode, we allow Ctrl-C handling */
1432
    if (nographic)
1433
        tty.c_lflag &= ~ISIG;
1434
    tty.c_cflag &= ~(CSIZE|PARENB);
1435
    tty.c_cflag |= CS8;
1436
    tty.c_cc[VMIN] = 1;
1437
    tty.c_cc[VTIME] = 0;
1438
    
1439
    tcsetattr (0, TCSANOW, &tty);
1440

    
1441
    atexit(term_exit);
1442

    
1443
    fcntl(0, F_SETFL, O_NONBLOCK);
1444
}
1445

    
1446
CharDriverState *qemu_chr_open_stdio(void)
1447
{
1448
    CharDriverState *chr;
1449

    
1450
    if (nographic) {
1451
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1452
            return NULL;
1453
        chr = qemu_chr_open_fd(0, 1);
1454
        if (stdio_nb_clients == 0)
1455
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1456
        client_index = stdio_nb_clients;
1457
    } else {
1458
        if (stdio_nb_clients != 0)
1459
            return NULL;
1460
        chr = qemu_chr_open_fd(0, 1);
1461
    }
1462
    stdio_clients[stdio_nb_clients++] = chr;
1463
    if (stdio_nb_clients == 1) {
1464
        /* set the terminal in raw mode */
1465
        term_init();
1466
    }
1467
    return chr;
1468
}
1469

    
1470
#if defined(__linux__)
1471
CharDriverState *qemu_chr_open_pty(void)
1472
{
1473
    struct termios tty;
1474
    char slave_name[1024];
1475
    int master_fd, slave_fd;
1476
    
1477
    /* Not satisfying */
1478
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1479
        return NULL;
1480
    }
1481
    
1482
    /* Disabling local echo and line-buffered output */
1483
    tcgetattr (master_fd, &tty);
1484
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1485
    tty.c_cc[VMIN] = 1;
1486
    tty.c_cc[VTIME] = 0;
1487
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1488

    
1489
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1490
    return qemu_chr_open_fd(master_fd, master_fd);
1491
}
1492

    
1493
static void tty_serial_init(int fd, int speed, 
1494
                            int parity, int data_bits, int stop_bits)
1495
{
1496
    struct termios tty;
1497
    speed_t spd;
1498

    
1499
#if 0
1500
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1501
           speed, parity, data_bits, stop_bits);
1502
#endif
1503
    tcgetattr (fd, &tty);
1504

    
1505
    switch(speed) {
1506
    case 50:
1507
        spd = B50;
1508
        break;
1509
    case 75:
1510
        spd = B75;
1511
        break;
1512
    case 300:
1513
        spd = B300;
1514
        break;
1515
    case 600:
1516
        spd = B600;
1517
        break;
1518
    case 1200:
1519
        spd = B1200;
1520
        break;
1521
    case 2400:
1522
        spd = B2400;
1523
        break;
1524
    case 4800:
1525
        spd = B4800;
1526
        break;
1527
    case 9600:
1528
        spd = B9600;
1529
        break;
1530
    case 19200:
1531
        spd = B19200;
1532
        break;
1533
    case 38400:
1534
        spd = B38400;
1535
        break;
1536
    case 57600:
1537
        spd = B57600;
1538
        break;
1539
    default:
1540
    case 115200:
1541
        spd = B115200;
1542
        break;
1543
    }
1544

    
1545
    cfsetispeed(&tty, spd);
1546
    cfsetospeed(&tty, spd);
1547

    
1548
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1549
                          |INLCR|IGNCR|ICRNL|IXON);
1550
    tty.c_oflag |= OPOST;
1551
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1552
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1553
    switch(data_bits) {
1554
    default:
1555
    case 8:
1556
        tty.c_cflag |= CS8;
1557
        break;
1558
    case 7:
1559
        tty.c_cflag |= CS7;
1560
        break;
1561
    case 6:
1562
        tty.c_cflag |= CS6;
1563
        break;
1564
    case 5:
1565
        tty.c_cflag |= CS5;
1566
        break;
1567
    }
1568
    switch(parity) {
1569
    default:
1570
    case 'N':
1571
        break;
1572
    case 'E':
1573
        tty.c_cflag |= PARENB;
1574
        break;
1575
    case 'O':
1576
        tty.c_cflag |= PARENB | PARODD;
1577
        break;
1578
    }
1579
    
1580
    tcsetattr (fd, TCSANOW, &tty);
1581
}
1582

    
1583
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1584
{
1585
    FDCharDriver *s = chr->opaque;
1586
    
1587
    switch(cmd) {
1588
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1589
        {
1590
            QEMUSerialSetParams *ssp = arg;
1591
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1592
                            ssp->data_bits, ssp->stop_bits);
1593
        }
1594
        break;
1595
    case CHR_IOCTL_SERIAL_SET_BREAK:
1596
        {
1597
            int enable = *(int *)arg;
1598
            if (enable)
1599
                tcsendbreak(s->fd_in, 1);
1600
        }
1601
        break;
1602
    default:
1603
        return -ENOTSUP;
1604
    }
1605
    return 0;
1606
}
1607

    
1608
CharDriverState *qemu_chr_open_tty(const char *filename)
1609
{
1610
    CharDriverState *chr;
1611
    int fd;
1612

    
1613
    fd = open(filename, O_RDWR | O_NONBLOCK);
1614
    if (fd < 0)
1615
        return NULL;
1616
    fcntl(fd, F_SETFL, O_NONBLOCK);
1617
    tty_serial_init(fd, 115200, 'N', 8, 1);
1618
    chr = qemu_chr_open_fd(fd, fd);
1619
    if (!chr)
1620
        return NULL;
1621
    chr->chr_ioctl = tty_serial_ioctl;
1622
    return chr;
1623
}
1624

    
1625
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1626
{
1627
    int fd = (int)chr->opaque;
1628
    uint8_t b;
1629

    
1630
    switch(cmd) {
1631
    case CHR_IOCTL_PP_READ_DATA:
1632
        if (ioctl(fd, PPRDATA, &b) < 0)
1633
            return -ENOTSUP;
1634
        *(uint8_t *)arg = b;
1635
        break;
1636
    case CHR_IOCTL_PP_WRITE_DATA:
1637
        b = *(uint8_t *)arg;
1638
        if (ioctl(fd, PPWDATA, &b) < 0)
1639
            return -ENOTSUP;
1640
        break;
1641
    case CHR_IOCTL_PP_READ_CONTROL:
1642
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1643
            return -ENOTSUP;
1644
        *(uint8_t *)arg = b;
1645
        break;
1646
    case CHR_IOCTL_PP_WRITE_CONTROL:
1647
        b = *(uint8_t *)arg;
1648
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1649
            return -ENOTSUP;
1650
        break;
1651
    case CHR_IOCTL_PP_READ_STATUS:
1652
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1653
            return -ENOTSUP;
1654
        *(uint8_t *)arg = b;
1655
        break;
1656
    default:
1657
        return -ENOTSUP;
1658
    }
1659
    return 0;
1660
}
1661

    
1662
CharDriverState *qemu_chr_open_pp(const char *filename)
1663
{
1664
    CharDriverState *chr;
1665
    int fd;
1666

    
1667
    fd = open(filename, O_RDWR);
1668
    if (fd < 0)
1669
        return NULL;
1670

    
1671
    if (ioctl(fd, PPCLAIM) < 0) {
1672
        close(fd);
1673
        return NULL;
1674
    }
1675

    
1676
    chr = qemu_mallocz(sizeof(CharDriverState));
1677
    if (!chr) {
1678
        close(fd);
1679
        return NULL;
1680
    }
1681
    chr->opaque = (void *)fd;
1682
    chr->chr_write = null_chr_write;
1683
    chr->chr_add_read_handler = null_chr_add_read_handler;
1684
    chr->chr_ioctl = pp_ioctl;
1685
    return chr;
1686
}
1687

    
1688
#else
1689
CharDriverState *qemu_chr_open_pty(void)
1690
{
1691
    return NULL;
1692
}
1693
#endif
1694

    
1695
#endif /* !defined(_WIN32) */
1696

    
1697
#ifdef _WIN32
1698
typedef struct {
1699
    IOCanRWHandler *fd_can_read; 
1700
    IOReadHandler *fd_read;
1701
    void *win_opaque;
1702
    int max_size;
1703
    HANDLE hcom, hrecv, hsend;
1704
    OVERLAPPED orecv, osend;
1705
    BOOL fpipe;
1706
    DWORD len;
1707
} WinCharState;
1708

    
1709
#define NSENDBUF 2048
1710
#define NRECVBUF 2048
1711
#define MAXCONNECT 1
1712
#define NTIMEOUT 5000
1713

    
1714
static int win_chr_poll(void *opaque);
1715
static int win_chr_pipe_poll(void *opaque);
1716

    
1717
static void win_chr_close2(WinCharState *s)
1718
{
1719
    if (s->hsend) {
1720
        CloseHandle(s->hsend);
1721
        s->hsend = NULL;
1722
    }
1723
    if (s->hrecv) {
1724
        CloseHandle(s->hrecv);
1725
        s->hrecv = NULL;
1726
    }
1727
    if (s->hcom) {
1728
        CloseHandle(s->hcom);
1729
        s->hcom = NULL;
1730
    }
1731
    if (s->fpipe)
1732
        qemu_del_polling_cb(win_chr_pipe_poll, s);
1733
    else
1734
        qemu_del_polling_cb(win_chr_poll, s);
1735
}
1736

    
1737
static void win_chr_close(CharDriverState *chr)
1738
{
1739
    WinCharState *s = chr->opaque;
1740
    win_chr_close2(s);
1741
}
1742

    
1743
static int win_chr_init(WinCharState *s, const char *filename)
1744
{
1745
    COMMCONFIG comcfg;
1746
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1747
    COMSTAT comstat;
1748
    DWORD size;
1749
    DWORD err;
1750
    
1751
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1752
    if (!s->hsend) {
1753
        fprintf(stderr, "Failed CreateEvent\n");
1754
        goto fail;
1755
    }
1756
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1757
    if (!s->hrecv) {
1758
        fprintf(stderr, "Failed CreateEvent\n");
1759
        goto fail;
1760
    }
1761

    
1762
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1763
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1764
    if (s->hcom == INVALID_HANDLE_VALUE) {
1765
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1766
        s->hcom = NULL;
1767
        goto fail;
1768
    }
1769
    
1770
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1771
        fprintf(stderr, "Failed SetupComm\n");
1772
        goto fail;
1773
    }
1774
    
1775
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1776
    size = sizeof(COMMCONFIG);
1777
    GetDefaultCommConfig(filename, &comcfg, &size);
1778
    comcfg.dcb.DCBlength = sizeof(DCB);
1779
    CommConfigDialog(filename, NULL, &comcfg);
1780

    
1781
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1782
        fprintf(stderr, "Failed SetCommState\n");
1783
        goto fail;
1784
    }
1785

    
1786
    if (!SetCommMask(s->hcom, EV_ERR)) {
1787
        fprintf(stderr, "Failed SetCommMask\n");
1788
        goto fail;
1789
    }
1790

    
1791
    cto.ReadIntervalTimeout = MAXDWORD;
1792
    if (!SetCommTimeouts(s->hcom, &cto)) {
1793
        fprintf(stderr, "Failed SetCommTimeouts\n");
1794
        goto fail;
1795
    }
1796
    
1797
    if (!ClearCommError(s->hcom, &err, &comstat)) {
1798
        fprintf(stderr, "Failed ClearCommError\n");
1799
        goto fail;
1800
    }
1801
    qemu_add_polling_cb(win_chr_poll, s);
1802
    return 0;
1803

    
1804
 fail:
1805
    win_chr_close2(s);
1806
    return -1;
1807
}
1808

    
1809
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1810
{
1811
    WinCharState *s = chr->opaque;
1812
    DWORD len, ret, size, err;
1813

    
1814
    len = len1;
1815
    ZeroMemory(&s->osend, sizeof(s->osend));
1816
    s->osend.hEvent = s->hsend;
1817
    while (len > 0) {
1818
        if (s->hsend)
1819
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1820
        else
1821
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1822
        if (!ret) {
1823
            err = GetLastError();
1824
            if (err == ERROR_IO_PENDING) {
1825
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1826
                if (ret) {
1827
                    buf += size;
1828
                    len -= size;
1829
                } else {
1830
                    break;
1831
                }
1832
            } else {
1833
                break;
1834
            }
1835
        } else {
1836
            buf += size;
1837
            len -= size;
1838
        }
1839
    }
1840
    return len1 - len;
1841
}
1842

    
1843
static int win_chr_read_poll(WinCharState *s)
1844
{
1845
    s->max_size = s->fd_can_read(s->win_opaque);
1846
    return s->max_size;
1847
}
1848
            
1849
static void win_chr_readfile(WinCharState *s)
1850
{
1851
    int ret, err;
1852
    uint8_t buf[1024];
1853
    DWORD size;
1854
    
1855
    ZeroMemory(&s->orecv, sizeof(s->orecv));
1856
    s->orecv.hEvent = s->hrecv;
1857
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1858
    if (!ret) {
1859
        err = GetLastError();
1860
        if (err == ERROR_IO_PENDING) {
1861
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1862
        }
1863
    }
1864

    
1865
    if (size > 0) {
1866
        s->fd_read(s->win_opaque, buf, size);
1867
    }
1868
}
1869

    
1870
static void win_chr_read(WinCharState *s)
1871
{
1872
    if (s->len > s->max_size)
1873
        s->len = s->max_size;
1874
    if (s->len == 0)
1875
        return;
1876
    
1877
    win_chr_readfile(s);
1878
}
1879

    
1880
static int win_chr_poll(void *opaque)
1881
{
1882
    WinCharState *s = opaque;
1883
    COMSTAT status;
1884
    DWORD comerr;
1885
    
1886
    ClearCommError(s->hcom, &comerr, &status);
1887
    if (status.cbInQue > 0) {
1888
        s->len = status.cbInQue;
1889
        win_chr_read_poll(s);
1890
        win_chr_read(s);
1891
        return 1;
1892
    }
1893
    return 0;
1894
}
1895

    
1896
static void win_chr_add_read_handler(CharDriverState *chr, 
1897
                                    IOCanRWHandler *fd_can_read, 
1898
                                    IOReadHandler *fd_read, void *opaque)
1899
{
1900
    WinCharState *s = chr->opaque;
1901

    
1902
    s->fd_can_read = fd_can_read;
1903
    s->fd_read = fd_read;
1904
    s->win_opaque = opaque;
1905
}
1906

    
1907
CharDriverState *qemu_chr_open_win(const char *filename)
1908
{
1909
    CharDriverState *chr;
1910
    WinCharState *s;
1911
    
1912
    chr = qemu_mallocz(sizeof(CharDriverState));
1913
    if (!chr)
1914
        return NULL;
1915
    s = qemu_mallocz(sizeof(WinCharState));
1916
    if (!s) {
1917
        free(chr);
1918
        return NULL;
1919
    }
1920
    chr->opaque = s;
1921
    chr->chr_write = win_chr_write;
1922
    chr->chr_add_read_handler = win_chr_add_read_handler;
1923
    chr->chr_close = win_chr_close;
1924

    
1925
    if (win_chr_init(s, filename) < 0) {
1926
        free(s);
1927
        free(chr);
1928
        return NULL;
1929
    }
1930
    return chr;
1931
}
1932

    
1933
static int win_chr_pipe_poll(void *opaque)
1934
{
1935
    WinCharState *s = opaque;
1936
    DWORD size;
1937

    
1938
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1939
    if (size > 0) {
1940
        s->len = size;
1941
        win_chr_read_poll(s);
1942
        win_chr_read(s);
1943
        return 1;
1944
    }
1945
    return 0;
1946
}
1947

    
1948
static int win_chr_pipe_init(WinCharState *s, const char *filename)
1949
{
1950
    OVERLAPPED ov;
1951
    int ret;
1952
    DWORD size;
1953
    char openname[256];
1954
    
1955
    s->fpipe = TRUE;
1956

    
1957
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1958
    if (!s->hsend) {
1959
        fprintf(stderr, "Failed CreateEvent\n");
1960
        goto fail;
1961
    }
1962
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1963
    if (!s->hrecv) {
1964
        fprintf(stderr, "Failed CreateEvent\n");
1965
        goto fail;
1966
    }
1967
    
1968
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1969
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1970
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1971
                              PIPE_WAIT,
1972
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1973
    if (s->hcom == INVALID_HANDLE_VALUE) {
1974
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1975
        s->hcom = NULL;
1976
        goto fail;
1977
    }
1978

    
1979
    ZeroMemory(&ov, sizeof(ov));
1980
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1981
    ret = ConnectNamedPipe(s->hcom, &ov);
1982
    if (ret) {
1983
        fprintf(stderr, "Failed ConnectNamedPipe\n");
1984
        goto fail;
1985
    }
1986

    
1987
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1988
    if (!ret) {
1989
        fprintf(stderr, "Failed GetOverlappedResult\n");
1990
        if (ov.hEvent) {
1991
            CloseHandle(ov.hEvent);
1992
            ov.hEvent = NULL;
1993
        }
1994
        goto fail;
1995
    }
1996

    
1997
    if (ov.hEvent) {
1998
        CloseHandle(ov.hEvent);
1999
        ov.hEvent = NULL;
2000
    }
2001
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2002
    return 0;
2003

    
2004
 fail:
2005
    win_chr_close2(s);
2006
    return -1;
2007
}
2008

    
2009

    
2010
CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2011
{
2012
    CharDriverState *chr;
2013
    WinCharState *s;
2014

    
2015
    chr = qemu_mallocz(sizeof(CharDriverState));
2016
    if (!chr)
2017
        return NULL;
2018
    s = qemu_mallocz(sizeof(WinCharState));
2019
    if (!s) {
2020
        free(chr);
2021
        return NULL;
2022
    }
2023
    chr->opaque = s;
2024
    chr->chr_write = win_chr_write;
2025
    chr->chr_add_read_handler = win_chr_add_read_handler;
2026
    chr->chr_close = win_chr_close;
2027
    
2028
    if (win_chr_pipe_init(s, filename) < 0) {
2029
        free(s);
2030
        free(chr);
2031
        return NULL;
2032
    }
2033
    return chr;
2034
}
2035

    
2036
CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2037
{
2038
    CharDriverState *chr;
2039
    WinCharState *s;
2040

    
2041
    chr = qemu_mallocz(sizeof(CharDriverState));
2042
    if (!chr)
2043
        return NULL;
2044
    s = qemu_mallocz(sizeof(WinCharState));
2045
    if (!s) {
2046
        free(chr);
2047
        return NULL;
2048
    }
2049
    s->hcom = fd_out;
2050
    chr->opaque = s;
2051
    chr->chr_write = win_chr_write;
2052
    chr->chr_add_read_handler = win_chr_add_read_handler;
2053
    return chr;
2054
}
2055
    
2056
CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2057
{
2058
    HANDLE fd_out;
2059
    
2060
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2061
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2062
    if (fd_out == INVALID_HANDLE_VALUE)
2063
        return NULL;
2064

    
2065
    return qemu_chr_open_win_file(fd_out);
2066
}
2067
#endif
2068

    
2069
CharDriverState *qemu_chr_open(const char *filename)
2070
{
2071
    const char *p;
2072

    
2073
    if (!strcmp(filename, "vc")) {
2074
        return text_console_init(&display_state);
2075
    } else if (!strcmp(filename, "null")) {
2076
        return qemu_chr_open_null();
2077
    } else 
2078
#ifndef _WIN32
2079
    if (strstart(filename, "file:", &p)) {
2080
        return qemu_chr_open_file_out(p);
2081
    } else if (strstart(filename, "pipe:", &p)) {
2082
        return qemu_chr_open_pipe(p);
2083
    } else if (!strcmp(filename, "pty")) {
2084
        return qemu_chr_open_pty();
2085
    } else if (!strcmp(filename, "stdio")) {
2086
        return qemu_chr_open_stdio();
2087
    } else 
2088
#endif
2089
#if defined(__linux__)
2090
    if (strstart(filename, "/dev/parport", NULL)) {
2091
        return qemu_chr_open_pp(filename);
2092
    } else 
2093
    if (strstart(filename, "/dev/", NULL)) {
2094
        return qemu_chr_open_tty(filename);
2095
    } else 
2096
#endif
2097
#ifdef _WIN32
2098
    if (strstart(filename, "COM", NULL)) {
2099
        return qemu_chr_open_win(filename);
2100
    } else
2101
    if (strstart(filename, "pipe:", &p)) {
2102
        return qemu_chr_open_win_pipe(p);
2103
    } else
2104
    if (strstart(filename, "file:", &p)) {
2105
        return qemu_chr_open_win_file_out(p);
2106
    }
2107
#endif
2108
    {
2109
        return NULL;
2110
    }
2111
}
2112

    
2113
void qemu_chr_close(CharDriverState *chr)
2114
{
2115
    if (chr->chr_close)
2116
        chr->chr_close(chr);
2117
}
2118

    
2119
/***********************************************************/
2120
/* network device redirectors */
2121

    
2122
void hex_dump(FILE *f, const uint8_t *buf, int size)
2123
{
2124
    int len, i, j, c;
2125

    
2126
    for(i=0;i<size;i+=16) {
2127
        len = size - i;
2128
        if (len > 16)
2129
            len = 16;
2130
        fprintf(f, "%08x ", i);
2131
        for(j=0;j<16;j++) {
2132
            if (j < len)
2133
                fprintf(f, " %02x", buf[i+j]);
2134
            else
2135
                fprintf(f, "   ");
2136
        }
2137
        fprintf(f, " ");
2138
        for(j=0;j<len;j++) {
2139
            c = buf[i+j];
2140
            if (c < ' ' || c > '~')
2141
                c = '.';
2142
            fprintf(f, "%c", c);
2143
        }
2144
        fprintf(f, "\n");
2145
    }
2146
}
2147

    
2148
static int parse_macaddr(uint8_t *macaddr, const char *p)
2149
{
2150
    int i;
2151
    for(i = 0; i < 6; i++) {
2152
        macaddr[i] = strtol(p, (char **)&p, 16);
2153
        if (i == 5) {
2154
            if (*p != '\0') 
2155
                return -1;
2156
        } else {
2157
            if (*p != ':') 
2158
                return -1;
2159
            p++;
2160
        }
2161
    }
2162
    return 0;
2163
}
2164

    
2165
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2166
{
2167
    const char *p, *p1;
2168
    int len;
2169
    p = *pp;
2170
    p1 = strchr(p, sep);
2171
    if (!p1)
2172
        return -1;
2173
    len = p1 - p;
2174
    p1++;
2175
    if (buf_size > 0) {
2176
        if (len > buf_size - 1)
2177
            len = buf_size - 1;
2178
        memcpy(buf, p, len);
2179
        buf[len] = '\0';
2180
    }
2181
    *pp = p1;
2182
    return 0;
2183
}
2184

    
2185
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2186
{
2187
    char buf[512];
2188
    struct hostent *he;
2189
    const char *p, *r;
2190
    int port;
2191

    
2192
    p = str;
2193
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2194
        return -1;
2195
    saddr->sin_family = AF_INET;
2196
    if (buf[0] == '\0') {
2197
        saddr->sin_addr.s_addr = 0;
2198
    } else {
2199
        if (isdigit(buf[0])) {
2200
            if (!inet_aton(buf, &saddr->sin_addr))
2201
                return -1;
2202
        } else {
2203
            if ((he = gethostbyname(buf)) == NULL)
2204
                return - 1;
2205
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2206
        }
2207
    }
2208
    port = strtol(p, (char **)&r, 0);
2209
    if (r == p)
2210
        return -1;
2211
    saddr->sin_port = htons(port);
2212
    return 0;
2213
}
2214

    
2215
/* find or alloc a new VLAN */
2216
VLANState *qemu_find_vlan(int id)
2217
{
2218
    VLANState **pvlan, *vlan;
2219
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2220
        if (vlan->id == id)
2221
            return vlan;
2222
    }
2223
    vlan = qemu_mallocz(sizeof(VLANState));
2224
    if (!vlan)
2225
        return NULL;
2226
    vlan->id = id;
2227
    vlan->next = NULL;
2228
    pvlan = &first_vlan;
2229
    while (*pvlan != NULL)
2230
        pvlan = &(*pvlan)->next;
2231
    *pvlan = vlan;
2232
    return vlan;
2233
}
2234

    
2235
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2236
                                      IOReadHandler *fd_read,
2237
                                      IOCanRWHandler *fd_can_read,
2238
                                      void *opaque)
2239
{
2240
    VLANClientState *vc, **pvc;
2241
    vc = qemu_mallocz(sizeof(VLANClientState));
2242
    if (!vc)
2243
        return NULL;
2244
    vc->fd_read = fd_read;
2245
    vc->fd_can_read = fd_can_read;
2246
    vc->opaque = opaque;
2247
    vc->vlan = vlan;
2248

    
2249
    vc->next = NULL;
2250
    pvc = &vlan->first_client;
2251
    while (*pvc != NULL)
2252
        pvc = &(*pvc)->next;
2253
    *pvc = vc;
2254
    return vc;
2255
}
2256

    
2257
int qemu_can_send_packet(VLANClientState *vc1)
2258
{
2259
    VLANState *vlan = vc1->vlan;
2260
    VLANClientState *vc;
2261

    
2262
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2263
        if (vc != vc1) {
2264
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2265
                return 0;
2266
        }
2267
    }
2268
    return 1;
2269
}
2270

    
2271
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2272
{
2273
    VLANState *vlan = vc1->vlan;
2274
    VLANClientState *vc;
2275

    
2276
#if 0
2277
    printf("vlan %d send:\n", vlan->id);
2278
    hex_dump(stdout, buf, size);
2279
#endif
2280
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2281
        if (vc != vc1) {
2282
            vc->fd_read(vc->opaque, buf, size);
2283
        }
2284
    }
2285
}
2286

    
2287
#if defined(CONFIG_SLIRP)
2288

    
2289
/* slirp network adapter */
2290

    
2291
static int slirp_inited;
2292
static VLANClientState *slirp_vc;
2293

    
2294
int slirp_can_output(void)
2295
{
2296
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
2297
}
2298

    
2299
void slirp_output(const uint8_t *pkt, int pkt_len)
2300
{
2301
#if 0
2302
    printf("slirp output:\n");
2303
    hex_dump(stdout, pkt, pkt_len);
2304
#endif
2305
    if (!slirp_vc)
2306
        return;
2307
    qemu_send_packet(slirp_vc, pkt, pkt_len);
2308
}
2309

    
2310
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2311
{
2312
#if 0
2313
    printf("slirp input:\n");
2314
    hex_dump(stdout, buf, size);
2315
#endif
2316
    slirp_input(buf, size);
2317
}
2318

    
2319
static int net_slirp_init(VLANState *vlan)
2320
{
2321
    if (!slirp_inited) {
2322
        slirp_inited = 1;
2323
        slirp_init();
2324
    }
2325
    slirp_vc = qemu_new_vlan_client(vlan, 
2326
                                    slirp_receive, NULL, NULL);
2327
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2328
    return 0;
2329
}
2330

    
2331
static void net_slirp_redir(const char *redir_str)
2332
{
2333
    int is_udp;
2334
    char buf[256], *r;
2335
    const char *p;
2336
    struct in_addr guest_addr;
2337
    int host_port, guest_port;
2338
    
2339
    if (!slirp_inited) {
2340
        slirp_inited = 1;
2341
        slirp_init();
2342
    }
2343

    
2344
    p = redir_str;
2345
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2346
        goto fail;
2347
    if (!strcmp(buf, "tcp")) {
2348
        is_udp = 0;
2349
    } else if (!strcmp(buf, "udp")) {
2350
        is_udp = 1;
2351
    } else {
2352
        goto fail;
2353
    }
2354

    
2355
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2356
        goto fail;
2357
    host_port = strtol(buf, &r, 0);
2358
    if (r == buf)
2359
        goto fail;
2360

    
2361
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2362
        goto fail;
2363
    if (buf[0] == '\0') {
2364
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
2365
    }
2366
    if (!inet_aton(buf, &guest_addr))
2367
        goto fail;
2368
    
2369
    guest_port = strtol(p, &r, 0);
2370
    if (r == p)
2371
        goto fail;
2372
    
2373
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2374
        fprintf(stderr, "qemu: could not set up redirection\n");
2375
        exit(1);
2376
    }
2377
    return;
2378
 fail:
2379
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2380
    exit(1);
2381
}
2382
    
2383
#ifndef _WIN32
2384

    
2385
char smb_dir[1024];
2386

    
2387
static void smb_exit(void)
2388
{
2389
    DIR *d;
2390
    struct dirent *de;
2391
    char filename[1024];
2392

    
2393
    /* erase all the files in the directory */
2394
    d = opendir(smb_dir);
2395
    for(;;) {
2396
        de = readdir(d);
2397
        if (!de)
2398
            break;
2399
        if (strcmp(de->d_name, ".") != 0 &&
2400
            strcmp(de->d_name, "..") != 0) {
2401
            snprintf(filename, sizeof(filename), "%s/%s", 
2402
                     smb_dir, de->d_name);
2403
            unlink(filename);
2404
        }
2405
    }
2406
    closedir(d);
2407
    rmdir(smb_dir);
2408
}
2409

    
2410
/* automatic user mode samba server configuration */
2411
void net_slirp_smb(const char *exported_dir)
2412
{
2413
    char smb_conf[1024];
2414
    char smb_cmdline[1024];
2415
    FILE *f;
2416

    
2417
    if (!slirp_inited) {
2418
        slirp_inited = 1;
2419
        slirp_init();
2420
    }
2421

    
2422
    /* XXX: better tmp dir construction */
2423
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2424
    if (mkdir(smb_dir, 0700) < 0) {
2425
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2426
        exit(1);
2427
    }
2428
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2429
    
2430
    f = fopen(smb_conf, "w");
2431
    if (!f) {
2432
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2433
        exit(1);
2434
    }
2435
    fprintf(f, 
2436
            "[global]\n"
2437
            "private dir=%s\n"
2438
            "smb ports=0\n"
2439
            "socket address=127.0.0.1\n"
2440
            "pid directory=%s\n"
2441
            "lock directory=%s\n"
2442
            "log file=%s/log.smbd\n"
2443
            "smb passwd file=%s/smbpasswd\n"
2444
            "security = share\n"
2445
            "[qemu]\n"
2446
            "path=%s\n"
2447
            "read only=no\n"
2448
            "guest ok=yes\n",
2449
            smb_dir,
2450
            smb_dir,
2451
            smb_dir,
2452
            smb_dir,
2453
            smb_dir,
2454
            exported_dir
2455
            );
2456
    fclose(f);
2457
    atexit(smb_exit);
2458

    
2459
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2460
             smb_conf);
2461
    
2462
    slirp_add_exec(0, smb_cmdline, 4, 139);
2463
}
2464

    
2465
#endif /* !defined(_WIN32) */
2466

    
2467
#endif /* CONFIG_SLIRP */
2468

    
2469
#if !defined(_WIN32)
2470

    
2471
typedef struct TAPState {
2472
    VLANClientState *vc;
2473
    int fd;
2474
} TAPState;
2475

    
2476
static void tap_receive(void *opaque, const uint8_t *buf, int size)
2477
{
2478
    TAPState *s = opaque;
2479
    int ret;
2480
    for(;;) {
2481
        ret = write(s->fd, buf, size);
2482
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2483
        } else {
2484
            break;
2485
        }
2486
    }
2487
}
2488

    
2489
static void tap_send(void *opaque)
2490
{
2491
    TAPState *s = opaque;
2492
    uint8_t buf[4096];
2493
    int size;
2494

    
2495
    size = read(s->fd, buf, sizeof(buf));
2496
    if (size > 0) {
2497
        qemu_send_packet(s->vc, buf, size);
2498
    }
2499
}
2500

    
2501
/* fd support */
2502

    
2503
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2504
{
2505
    TAPState *s;
2506

    
2507
    s = qemu_mallocz(sizeof(TAPState));
2508
    if (!s)
2509
        return NULL;
2510
    s->fd = fd;
2511
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2512
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2513
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2514
    return s;
2515
}
2516

    
2517
#ifdef _BSD
2518
static int tap_open(char *ifname, int ifname_size)
2519
{
2520
    int fd;
2521
    char *dev;
2522
    struct stat s;
2523

    
2524
    fd = open("/dev/tap", O_RDWR);
2525
    if (fd < 0) {
2526
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2527
        return -1;
2528
    }
2529

    
2530
    fstat(fd, &s);
2531
    dev = devname(s.st_rdev, S_IFCHR);
2532
    pstrcpy(ifname, ifname_size, dev);
2533

    
2534
    fcntl(fd, F_SETFL, O_NONBLOCK);
2535
    return fd;
2536
}
2537
#elif defined(__sun__)
2538
static int tap_open(char *ifname, int ifname_size)
2539
{
2540
    fprintf(stderr, "warning: tap_open not yet implemented\n");
2541
    return -1;
2542
}
2543
#else
2544
static int tap_open(char *ifname, int ifname_size)
2545
{
2546
    struct ifreq ifr;
2547
    int fd, ret;
2548
    
2549
    fd = open("/dev/net/tun", O_RDWR);
2550
    if (fd < 0) {
2551
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2552
        return -1;
2553
    }
2554
    memset(&ifr, 0, sizeof(ifr));
2555
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2556
    if (ifname[0] != '\0')
2557
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2558
    else
2559
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2560
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2561
    if (ret != 0) {
2562
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2563
        close(fd);
2564
        return -1;
2565
    }
2566
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
2567
    fcntl(fd, F_SETFL, O_NONBLOCK);
2568
    return fd;
2569
}
2570
#endif
2571

    
2572
static int net_tap_init(VLANState *vlan, const char *ifname1,
2573
                        const char *setup_script)
2574
{
2575
    TAPState *s;
2576
    int pid, status, fd;
2577
    char *args[3];
2578
    char **parg;
2579
    char ifname[128];
2580

    
2581
    if (ifname1 != NULL)
2582
        pstrcpy(ifname, sizeof(ifname), ifname1);
2583
    else
2584
        ifname[0] = '\0';
2585
    fd = tap_open(ifname, sizeof(ifname));
2586
    if (fd < 0)
2587
        return -1;
2588

    
2589
    if (!setup_script)
2590
        setup_script = "";
2591
    if (setup_script[0] != '\0') {
2592
        /* try to launch network init script */
2593
        pid = fork();
2594
        if (pid >= 0) {
2595
            if (pid == 0) {
2596
                parg = args;
2597
                *parg++ = (char *)setup_script;
2598
                *parg++ = ifname;
2599
                *parg++ = NULL;
2600
                execv(setup_script, args);
2601
                _exit(1);
2602
            }
2603
            while (waitpid(pid, &status, 0) != pid);
2604
            if (!WIFEXITED(status) ||
2605
                WEXITSTATUS(status) != 0) {
2606
                fprintf(stderr, "%s: could not launch network script\n",
2607
                        setup_script);
2608
                return -1;
2609
            }
2610
        }
2611
    }
2612
    s = net_tap_fd_init(vlan, fd);
2613
    if (!s)
2614
        return -1;
2615
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
2616
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
2617
    return 0;
2618
}
2619

    
2620
#endif /* !_WIN32 */
2621

    
2622
/* network connection */
2623
typedef struct NetSocketState {
2624
    VLANClientState *vc;
2625
    int fd;
2626
    int state; /* 0 = getting length, 1 = getting data */
2627
    int index;
2628
    int packet_len;
2629
    uint8_t buf[4096];
2630
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2631
} NetSocketState;
2632

    
2633
typedef struct NetSocketListenState {
2634
    VLANState *vlan;
2635
    int fd;
2636
} NetSocketListenState;
2637

    
2638
/* XXX: we consider we can send the whole packet without blocking */
2639
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2640
{
2641
    NetSocketState *s = opaque;
2642
    uint32_t len;
2643
    len = htonl(size);
2644

    
2645
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2646
    send_all(s->fd, buf, size);
2647
}
2648

    
2649
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2650
{
2651
    NetSocketState *s = opaque;
2652
    sendto(s->fd, buf, size, 0, 
2653
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2654
}
2655

    
2656
static void net_socket_send(void *opaque)
2657
{
2658
    NetSocketState *s = opaque;
2659
    int l, size, err;
2660
    uint8_t buf1[4096];
2661
    const uint8_t *buf;
2662

    
2663
    size = recv(s->fd, buf1, sizeof(buf1), 0);
2664
    if (size < 0) {
2665
        err = socket_error();
2666
        if (err != EWOULDBLOCK) 
2667
            goto eoc;
2668
    } else if (size == 0) {
2669
        /* end of connection */
2670
    eoc:
2671
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2672
        closesocket(s->fd);
2673
        return;
2674
    }
2675
    buf = buf1;
2676
    while (size > 0) {
2677
        /* reassemble a packet from the network */
2678
        switch(s->state) {
2679
        case 0:
2680
            l = 4 - s->index;
2681
            if (l > size)
2682
                l = size;
2683
            memcpy(s->buf + s->index, buf, l);
2684
            buf += l;
2685
            size -= l;
2686
            s->index += l;
2687
            if (s->index == 4) {
2688
                /* got length */
2689
                s->packet_len = ntohl(*(uint32_t *)s->buf);
2690
                s->index = 0;
2691
                s->state = 1;
2692
            }
2693
            break;
2694
        case 1:
2695
            l = s->packet_len - s->index;
2696
            if (l > size)
2697
                l = size;
2698
            memcpy(s->buf + s->index, buf, l);
2699
            s->index += l;
2700
            buf += l;
2701
            size -= l;
2702
            if (s->index >= s->packet_len) {
2703
                qemu_send_packet(s->vc, s->buf, s->packet_len);
2704
                s->index = 0;
2705
                s->state = 0;
2706
            }
2707
            break;
2708
        }
2709
    }
2710
}
2711

    
2712
static void net_socket_send_dgram(void *opaque)
2713
{
2714
    NetSocketState *s = opaque;
2715
    int size;
2716

    
2717
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2718
    if (size < 0) 
2719
        return;
2720
    if (size == 0) {
2721
        /* end of connection */
2722
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2723
        return;
2724
    }
2725
    qemu_send_packet(s->vc, s->buf, size);
2726
}
2727

    
2728
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2729
{
2730
    struct ip_mreq imr;
2731
    int fd;
2732
    int val, ret;
2733
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2734
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2735
                inet_ntoa(mcastaddr->sin_addr), 
2736
                (int)ntohl(mcastaddr->sin_addr.s_addr));
2737
        return -1;
2738

    
2739
    }
2740
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2741
    if (fd < 0) {
2742
        perror("socket(PF_INET, SOCK_DGRAM)");
2743
        return -1;
2744
    }
2745

    
2746
    val = 1;
2747
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
2748
                   (const char *)&val, sizeof(val));
2749
    if (ret < 0) {
2750
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2751
        goto fail;
2752
    }
2753

    
2754
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2755
    if (ret < 0) {
2756
        perror("bind");
2757
        goto fail;
2758
    }
2759
    
2760
    /* Add host to multicast group */
2761
    imr.imr_multiaddr = mcastaddr->sin_addr;
2762
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
2763

    
2764
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
2765
                     (const char *)&imr, sizeof(struct ip_mreq));
2766
    if (ret < 0) {
2767
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
2768
        goto fail;
2769
    }
2770

    
2771
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2772
    val = 1;
2773
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
2774
                   (const char *)&val, sizeof(val));
2775
    if (ret < 0) {
2776
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2777
        goto fail;
2778
    }
2779

    
2780
    socket_set_nonblock(fd);
2781
    return fd;
2782
fail:
2783
    if (fd>=0) close(fd);
2784
    return -1;
2785
}
2786

    
2787
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
2788
                                          int is_connected)
2789
{
2790
    struct sockaddr_in saddr;
2791
    int newfd;
2792
    socklen_t saddr_len;
2793
    NetSocketState *s;
2794

    
2795
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2796
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
2797
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
2798
     */
2799

    
2800
    if (is_connected) {
2801
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2802
            /* must be bound */
2803
            if (saddr.sin_addr.s_addr==0) {
2804
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2805
                        fd);
2806
                return NULL;
2807
            }
2808
            /* clone dgram socket */
2809
            newfd = net_socket_mcast_create(&saddr);
2810
            if (newfd < 0) {
2811
                /* error already reported by net_socket_mcast_create() */
2812
                close(fd);
2813
                return NULL;
2814
            }
2815
            /* clone newfd to fd, close newfd */
2816
            dup2(newfd, fd);
2817
            close(newfd);
2818
        
2819
        } else {
2820
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2821
                    fd, strerror(errno));
2822
            return NULL;
2823
        }
2824
    }
2825

    
2826
    s = qemu_mallocz(sizeof(NetSocketState));
2827
    if (!s)
2828
        return NULL;
2829
    s->fd = fd;
2830

    
2831
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2832
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2833

    
2834
    /* mcast: save bound address as dst */
2835
    if (is_connected) s->dgram_dst=saddr;
2836

    
2837
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2838
            "socket: fd=%d (%s mcast=%s:%d)", 
2839
            fd, is_connected? "cloned" : "",
2840
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2841
    return s;
2842
}
2843

    
2844
static void net_socket_connect(void *opaque)
2845
{
2846
    NetSocketState *s = opaque;
2847
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2848
}
2849

    
2850
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
2851
                                          int is_connected)
2852
{
2853
    NetSocketState *s;
2854
    s = qemu_mallocz(sizeof(NetSocketState));
2855
    if (!s)
2856
        return NULL;
2857
    s->fd = fd;
2858
    s->vc = qemu_new_vlan_client(vlan, 
2859
                                 net_socket_receive, NULL, s);
2860
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2861
             "socket: fd=%d", fd);
2862
    if (is_connected) {
2863
        net_socket_connect(s);
2864
    } else {
2865
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2866
    }
2867
    return s;
2868
}
2869

    
2870
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
2871
                                          int is_connected)
2872
{
2873
    int so_type=-1, optlen=sizeof(so_type);
2874

    
2875
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2876
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2877
        return NULL;
2878
    }
2879
    switch(so_type) {
2880
    case SOCK_DGRAM:
2881
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
2882
    case SOCK_STREAM:
2883
        return net_socket_fd_init_stream(vlan, fd, is_connected);
2884
    default:
2885
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2886
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2887
        return net_socket_fd_init_stream(vlan, fd, is_connected);
2888
    }
2889
    return NULL;
2890
}
2891

    
2892
static void net_socket_accept(void *opaque)
2893
{
2894
    NetSocketListenState *s = opaque;    
2895
    NetSocketState *s1;
2896
    struct sockaddr_in saddr;
2897
    socklen_t len;
2898
    int fd;
2899

    
2900
    for(;;) {
2901
        len = sizeof(saddr);
2902
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2903
        if (fd < 0 && errno != EINTR) {
2904
            return;
2905
        } else if (fd >= 0) {
2906
            break;
2907
        }
2908
    }
2909
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
2910
    if (!s1) {
2911
        close(fd);
2912
    } else {
2913
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2914
                 "socket: connection from %s:%d", 
2915
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2916
    }
2917
}
2918

    
2919
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2920
{
2921
    NetSocketListenState *s;
2922
    int fd, val, ret;
2923
    struct sockaddr_in saddr;
2924

    
2925
    if (parse_host_port(&saddr, host_str) < 0)
2926
        return -1;
2927
    
2928
    s = qemu_mallocz(sizeof(NetSocketListenState));
2929
    if (!s)
2930
        return -1;
2931

    
2932
    fd = socket(PF_INET, SOCK_STREAM, 0);
2933
    if (fd < 0) {
2934
        perror("socket");
2935
        return -1;
2936
    }
2937
    socket_set_nonblock(fd);
2938

    
2939
    /* allow fast reuse */
2940
    val = 1;
2941
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2942
    
2943
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2944
    if (ret < 0) {
2945
        perror("bind");
2946
        return -1;
2947
    }
2948
    ret = listen(fd, 0);
2949
    if (ret < 0) {
2950
        perror("listen");
2951
        return -1;
2952
    }
2953
    s->vlan = vlan;
2954
    s->fd = fd;
2955
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2956
    return 0;
2957
}
2958

    
2959
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2960
{
2961
    NetSocketState *s;
2962
    int fd, connected, ret, err;
2963
    struct sockaddr_in saddr;
2964

    
2965
    if (parse_host_port(&saddr, host_str) < 0)
2966
        return -1;
2967

    
2968
    fd = socket(PF_INET, SOCK_STREAM, 0);
2969
    if (fd < 0) {
2970
        perror("socket");
2971
        return -1;
2972
    }
2973
    socket_set_nonblock(fd);
2974

    
2975
    connected = 0;
2976
    for(;;) {
2977
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2978
        if (ret < 0) {
2979
            err = socket_error();
2980
            if (err == EINTR || err == EWOULDBLOCK) {
2981
            } else if (err == EINPROGRESS) {
2982
                break;
2983
            } else {
2984
                perror("connect");
2985
                closesocket(fd);
2986
                return -1;
2987
            }
2988
        } else {
2989
            connected = 1;
2990
            break;
2991
        }
2992
    }
2993
    s = net_socket_fd_init(vlan, fd, connected);
2994
    if (!s)
2995
        return -1;
2996
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2997
             "socket: connect to %s:%d", 
2998
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2999
    return 0;
3000
}
3001

    
3002
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3003
{
3004
    NetSocketState *s;
3005
    int fd;
3006
    struct sockaddr_in saddr;
3007

    
3008
    if (parse_host_port(&saddr, host_str) < 0)
3009
        return -1;
3010

    
3011

    
3012
    fd = net_socket_mcast_create(&saddr);
3013
    if (fd < 0)
3014
        return -1;
3015

    
3016
    s = net_socket_fd_init(vlan, fd, 0);
3017
    if (!s)
3018
        return -1;
3019

    
3020
    s->dgram_dst = saddr;
3021
    
3022
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3023
             "socket: mcast=%s:%d", 
3024
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3025
    return 0;
3026

    
3027
}
3028

    
3029
static int get_param_value(char *buf, int buf_size,
3030
                           const char *tag, const char *str)
3031
{
3032
    const char *p;
3033
    char *q;
3034
    char option[128];
3035

    
3036
    p = str;
3037
    for(;;) {
3038
        q = option;
3039
        while (*p != '\0' && *p != '=') {
3040
            if ((q - option) < sizeof(option) - 1)
3041
                *q++ = *p;
3042
            p++;
3043
        }
3044
        *q = '\0';
3045
        if (*p != '=')
3046
            break;
3047
        p++;
3048
        if (!strcmp(tag, option)) {
3049
            q = buf;
3050
            while (*p != '\0' && *p != ',') {
3051
                if ((q - buf) < buf_size - 1)
3052
                    *q++ = *p;
3053
                p++;
3054
            }
3055
            *q = '\0';
3056
            return q - buf;
3057
        } else {
3058
            while (*p != '\0' && *p != ',') {
3059
                p++;
3060
            }
3061
        }
3062
        if (*p != ',')
3063
            break;
3064
        p++;
3065
    }
3066
    return 0;
3067
}
3068

    
3069
int net_client_init(const char *str)
3070
{
3071
    const char *p;
3072
    char *q;
3073
    char device[64];
3074
    char buf[1024];
3075
    int vlan_id, ret;
3076
    VLANState *vlan;
3077

    
3078
    p = str;
3079
    q = device;
3080
    while (*p != '\0' && *p != ',') {
3081
        if ((q - device) < sizeof(device) - 1)
3082
            *q++ = *p;
3083
        p++;
3084
    }
3085
    *q = '\0';
3086
    if (*p == ',')
3087
        p++;
3088
    vlan_id = 0;
3089
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3090
        vlan_id = strtol(buf, NULL, 0);
3091
    }
3092
    vlan = qemu_find_vlan(vlan_id);
3093
    if (!vlan) {
3094
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3095
        return -1;
3096
    }
3097
    if (!strcmp(device, "nic")) {
3098
        NICInfo *nd;
3099
        uint8_t *macaddr;
3100

    
3101
        if (nb_nics >= MAX_NICS) {
3102
            fprintf(stderr, "Too Many NICs\n");
3103
            return -1;
3104
        }
3105
        nd = &nd_table[nb_nics];
3106
        macaddr = nd->macaddr;
3107
        macaddr[0] = 0x52;
3108
        macaddr[1] = 0x54;
3109
        macaddr[2] = 0x00;
3110
        macaddr[3] = 0x12;
3111
        macaddr[4] = 0x34;
3112
        macaddr[5] = 0x56 + nb_nics;
3113

    
3114
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3115
            if (parse_macaddr(macaddr, buf) < 0) {
3116
                fprintf(stderr, "invalid syntax for ethernet address\n");
3117
                return -1;
3118
            }
3119
        }
3120
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3121
            nd->model = strdup(buf);
3122
        }
3123
        nd->vlan = vlan;
3124
        nb_nics++;
3125
        ret = 0;
3126
    } else
3127
    if (!strcmp(device, "none")) {
3128
        /* does nothing. It is needed to signal that no network cards
3129
           are wanted */
3130
        ret = 0;
3131
    } else
3132
#ifdef CONFIG_SLIRP
3133
    if (!strcmp(device, "user")) {
3134
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3135
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3136
        }
3137
        ret = net_slirp_init(vlan);
3138
    } else
3139
#endif
3140
#ifdef _WIN32
3141
    if (!strcmp(device, "tap")) {
3142
        char ifname[64];
3143
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3144
            fprintf(stderr, "tap: no interface name\n");
3145
            return -1;
3146
        }
3147
        ret = tap_win32_init(vlan, ifname);
3148
    } else
3149
#else
3150
    if (!strcmp(device, "tap")) {
3151
        char ifname[64];
3152
        char setup_script[1024];
3153
        int fd;
3154
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3155
            fd = strtol(buf, NULL, 0);
3156
            ret = -1;
3157
            if (net_tap_fd_init(vlan, fd))
3158
                ret = 0;
3159
        } else {
3160
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3161
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3162
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3163
            }
3164
            ret = net_tap_init(vlan, ifname, setup_script);
3165
        }
3166
    } else
3167
#endif
3168
    if (!strcmp(device, "socket")) {
3169
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3170
            int fd;
3171
            fd = strtol(buf, NULL, 0);
3172
            ret = -1;
3173
            if (net_socket_fd_init(vlan, fd, 1))
3174
                ret = 0;
3175
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3176
            ret = net_socket_listen_init(vlan, buf);
3177
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3178
            ret = net_socket_connect_init(vlan, buf);
3179
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3180
            ret = net_socket_mcast_init(vlan, buf);
3181
        } else {
3182
            fprintf(stderr, "Unknown socket options: %s\n", p);
3183
            return -1;
3184
        }
3185
    } else
3186
    {
3187
        fprintf(stderr, "Unknown network device: %s\n", device);
3188
        return -1;
3189
    }
3190
    if (ret < 0) {
3191
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3192
    }
3193
    
3194
    return ret;
3195
}
3196

    
3197
void do_info_network(void)
3198
{
3199
    VLANState *vlan;
3200
    VLANClientState *vc;
3201

    
3202
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3203
        term_printf("VLAN %d devices:\n", vlan->id);
3204
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3205
            term_printf("  %s\n", vc->info_str);
3206
    }
3207
}
3208
 
3209
/***********************************************************/
3210
/* USB devices */
3211

    
3212
static int usb_device_add(const char *devname)
3213
{
3214
    const char *p;
3215
    USBDevice *dev;
3216
    int i;
3217

    
3218
    if (!vm_usb_hub)
3219
        return -1;
3220
    for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3221
        if (!vm_usb_ports[i]->dev)
3222
            break;
3223
    }
3224
    if (i == MAX_VM_USB_PORTS)
3225
        return -1;
3226

    
3227
    if (strstart(devname, "host:", &p)) {
3228
        dev = usb_host_device_open(p);
3229
        if (!dev)
3230
            return -1;
3231
    } else if (!strcmp(devname, "mouse")) {
3232
        dev = usb_mouse_init();
3233
        if (!dev)
3234
            return -1;
3235
    } else if (!strcmp(devname, "tablet")) {
3236
        dev = usb_tablet_init();
3237
        if (!dev)
3238
            return -1;
3239
    } else {
3240
        return -1;
3241
    }
3242
    usb_attach(vm_usb_ports[i], dev);
3243
    return 0;
3244
}
3245

    
3246
static int usb_device_del(const char *devname)
3247
{
3248
    USBDevice *dev;
3249
    int bus_num, addr, i;
3250
    const char *p;
3251

    
3252
    if (!vm_usb_hub)
3253
        return -1;
3254

    
3255
    p = strchr(devname, '.');
3256
    if (!p) 
3257
        return -1;
3258
    bus_num = strtoul(devname, NULL, 0);
3259
    addr = strtoul(p + 1, NULL, 0);
3260
    if (bus_num != 0)
3261
        return -1;
3262
    for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3263
        dev = vm_usb_ports[i]->dev;
3264
        if (dev && dev->addr == addr)
3265
            break;
3266
    }
3267
    if (i == MAX_VM_USB_PORTS)
3268
        return -1;
3269
    usb_attach(vm_usb_ports[i], NULL);
3270
    return 0;
3271
}
3272

    
3273
void do_usb_add(const char *devname)
3274
{
3275
    int ret;
3276
    ret = usb_device_add(devname);
3277
    if (ret < 0) 
3278
        term_printf("Could not add USB device '%s'\n", devname);
3279
}
3280

    
3281
void do_usb_del(const char *devname)
3282
{
3283
    int ret;
3284
    ret = usb_device_del(devname);
3285
    if (ret < 0) 
3286
        term_printf("Could not remove USB device '%s'\n", devname);
3287
}
3288

    
3289
void usb_info(void)
3290
{
3291
    USBDevice *dev;
3292
    int i;
3293
    const char *speed_str;
3294

    
3295
    if (!vm_usb_hub) {
3296
        term_printf("USB support not enabled\n");
3297
        return;
3298
    }
3299

    
3300
    for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3301
        dev = vm_usb_ports[i]->dev;
3302
        if (dev) {
3303
            term_printf("Hub port %d:\n", i);
3304
            switch(dev->speed) {
3305
            case USB_SPEED_LOW: 
3306
                speed_str = "1.5"; 
3307
                break;
3308
            case USB_SPEED_FULL: 
3309
                speed_str = "12"; 
3310
                break;
3311
            case USB_SPEED_HIGH: 
3312
                speed_str = "480"; 
3313
                break;
3314
            default:
3315
                speed_str = "?"; 
3316
                break;
3317
            }
3318
            term_printf("  Device %d.%d, speed %s Mb/s\n", 
3319
                        0, dev->addr, speed_str);
3320
        }
3321
    }
3322
}
3323

    
3324
/***********************************************************/
3325
/* pid file */
3326

    
3327
static char *pid_filename;
3328

    
3329
/* Remove PID file. Called on normal exit */
3330

    
3331
static void remove_pidfile(void) 
3332
{
3333
    unlink (pid_filename);
3334
}
3335

    
3336
static void create_pidfile(const char *filename)
3337
{
3338
    struct stat pidstat;
3339
    FILE *f;
3340

    
3341
    /* Try to write our PID to the named file */
3342
    if (stat(filename, &pidstat) < 0) {
3343
        if (errno == ENOENT) {
3344
            if ((f = fopen (filename, "w")) == NULL) {
3345
                perror("Opening pidfile");
3346
                exit(1);
3347
            }
3348
            fprintf(f, "%d\n", getpid());
3349
            fclose(f);
3350
            pid_filename = qemu_strdup(filename);
3351
            if (!pid_filename) {
3352
                fprintf(stderr, "Could not save PID filename");
3353
                exit(1);
3354
            }
3355
            atexit(remove_pidfile);
3356
        }
3357
    } else {
3358
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
3359
                filename);
3360
        exit(1);
3361
    }
3362
}
3363

    
3364
/***********************************************************/
3365
/* dumb display */
3366

    
3367
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3368
{
3369
}
3370

    
3371
static void dumb_resize(DisplayState *ds, int w, int h)
3372
{
3373
}
3374

    
3375
static void dumb_refresh(DisplayState *ds)
3376
{
3377
    vga_hw_update();
3378
}
3379

    
3380
void dumb_display_init(DisplayState *ds)
3381
{
3382
    ds->data = NULL;
3383
    ds->linesize = 0;
3384
    ds->depth = 0;
3385
    ds->dpy_update = dumb_update;
3386
    ds->dpy_resize = dumb_resize;
3387
    ds->dpy_refresh = dumb_refresh;
3388
}
3389

    
3390
#if !defined(CONFIG_SOFTMMU)
3391
/***********************************************************/
3392
/* cpu signal handler */
3393
static void host_segv_handler(int host_signum, siginfo_t *info, 
3394
                              void *puc)
3395
{
3396
    if (cpu_signal_handler(host_signum, info, puc))
3397
        return;
3398
    if (stdio_nb_clients > 0)
3399
        term_exit();
3400
    abort();
3401
}
3402
#endif
3403

    
3404
/***********************************************************/
3405
/* I/O handling */
3406

    
3407
#define MAX_IO_HANDLERS 64
3408

    
3409
typedef struct IOHandlerRecord {
3410
    int fd;
3411
    IOCanRWHandler *fd_read_poll;
3412
    IOHandler *fd_read;
3413
    IOHandler *fd_write;
3414
    void *opaque;
3415
    /* temporary data */
3416
    struct pollfd *ufd;
3417
    struct IOHandlerRecord *next;
3418
} IOHandlerRecord;
3419

    
3420
static IOHandlerRecord *first_io_handler;
3421

    
3422
/* XXX: fd_read_poll should be suppressed, but an API change is
3423
   necessary in the character devices to suppress fd_can_read(). */
3424
int qemu_set_fd_handler2(int fd, 
3425
                         IOCanRWHandler *fd_read_poll, 
3426
                         IOHandler *fd_read, 
3427
                         IOHandler *fd_write, 
3428
                         void *opaque)
3429
{
3430
    IOHandlerRecord **pioh, *ioh;
3431

    
3432
    if (!fd_read && !fd_write) {
3433
        pioh = &first_io_handler;
3434
        for(;;) {
3435
            ioh = *pioh;
3436
            if (ioh == NULL)
3437
                break;
3438
            if (ioh->fd == fd) {
3439
                *pioh = ioh->next;
3440
                qemu_free(ioh);
3441
                break;
3442
            }
3443
            pioh = &ioh->next;
3444
        }
3445
    } else {
3446
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3447
            if (ioh->fd == fd)
3448
                goto found;
3449
        }
3450
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3451
        if (!ioh)
3452
            return -1;
3453
        ioh->next = first_io_handler;
3454
        first_io_handler = ioh;
3455
    found:
3456
        ioh->fd = fd;
3457
        ioh->fd_read_poll = fd_read_poll;
3458
        ioh->fd_read = fd_read;
3459
        ioh->fd_write = fd_write;
3460
        ioh->opaque = opaque;
3461
    }
3462
    return 0;
3463
}
3464

    
3465
int qemu_set_fd_handler(int fd, 
3466
                        IOHandler *fd_read, 
3467
                        IOHandler *fd_write, 
3468
                        void *opaque)
3469
{
3470
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3471
}
3472

    
3473
/***********************************************************/
3474
/* Polling handling */
3475

    
3476
typedef struct PollingEntry {
3477
    PollingFunc *func;
3478
    void *opaque;
3479
    struct PollingEntry *next;
3480
} PollingEntry;
3481

    
3482
static PollingEntry *first_polling_entry;
3483

    
3484
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3485
{
3486
    PollingEntry **ppe, *pe;
3487
    pe = qemu_mallocz(sizeof(PollingEntry));
3488
    if (!pe)
3489
        return -1;
3490
    pe->func = func;
3491
    pe->opaque = opaque;
3492
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3493
    *ppe = pe;
3494
    return 0;
3495
}
3496

    
3497
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3498
{
3499
    PollingEntry **ppe, *pe;
3500
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3501
        pe = *ppe;
3502
        if (pe->func == func && pe->opaque == opaque) {
3503
            *ppe = pe->next;
3504
            qemu_free(pe);
3505
            break;
3506
        }
3507
    }
3508
}
3509

    
3510
/***********************************************************/
3511
/* savevm/loadvm support */
3512

    
3513
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3514
{
3515
    fwrite(buf, 1, size, f);
3516
}
3517

    
3518
void qemu_put_byte(QEMUFile *f, int v)
3519
{
3520
    fputc(v, f);
3521
}
3522

    
3523
void qemu_put_be16(QEMUFile *f, unsigned int v)
3524
{
3525
    qemu_put_byte(f, v >> 8);
3526
    qemu_put_byte(f, v);
3527
}
3528

    
3529
void qemu_put_be32(QEMUFile *f, unsigned int v)
3530
{
3531
    qemu_put_byte(f, v >> 24);
3532
    qemu_put_byte(f, v >> 16);
3533
    qemu_put_byte(f, v >> 8);
3534
    qemu_put_byte(f, v);
3535
}
3536

    
3537
void qemu_put_be64(QEMUFile *f, uint64_t v)
3538
{
3539
    qemu_put_be32(f, v >> 32);
3540
    qemu_put_be32(f, v);
3541
}
3542

    
3543
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3544
{
3545
    return fread(buf, 1, size, f);
3546
}
3547

    
3548
int qemu_get_byte(QEMUFile *f)
3549
{
3550
    int v;
3551
    v = fgetc(f);
3552
    if (v == EOF)
3553
        return 0;
3554
    else
3555
        return v;
3556
}
3557

    
3558
unsigned int qemu_get_be16(QEMUFile *f)
3559
{
3560
    unsigned int v;
3561
    v = qemu_get_byte(f) << 8;
3562
    v |= qemu_get_byte(f);
3563
    return v;
3564
}
3565

    
3566
unsigned int qemu_get_be32(QEMUFile *f)
3567
{
3568
    unsigned int v;
3569
    v = qemu_get_byte(f) << 24;
3570
    v |= qemu_get_byte(f) << 16;
3571
    v |= qemu_get_byte(f) << 8;
3572
    v |= qemu_get_byte(f);
3573
    return v;
3574
}
3575

    
3576
uint64_t qemu_get_be64(QEMUFile *f)
3577
{
3578
    uint64_t v;
3579
    v = (uint64_t)qemu_get_be32(f) << 32;
3580
    v |= qemu_get_be32(f);
3581
    return v;
3582
}
3583

    
3584
int64_t qemu_ftell(QEMUFile *f)
3585
{
3586
    return ftell(f);
3587
}
3588

    
3589
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3590
{
3591
    if (fseek(f, pos, whence) < 0)
3592
        return -1;
3593
    return ftell(f);
3594
}
3595

    
3596
typedef struct SaveStateEntry {
3597
    char idstr[256];
3598
    int instance_id;
3599
    int version_id;
3600
    SaveStateHandler *save_state;
3601
    LoadStateHandler *load_state;
3602
    void *opaque;
3603
    struct SaveStateEntry *next;
3604
} SaveStateEntry;
3605

    
3606
static SaveStateEntry *first_se;
3607

    
3608
int register_savevm(const char *idstr, 
3609
                    int instance_id, 
3610
                    int version_id,
3611
                    SaveStateHandler *save_state,
3612
                    LoadStateHandler *load_state,
3613
                    void *opaque)
3614
{
3615
    SaveStateEntry *se, **pse;
3616

    
3617
    se = qemu_malloc(sizeof(SaveStateEntry));
3618
    if (!se)
3619
        return -1;
3620
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3621
    se->instance_id = instance_id;
3622
    se->version_id = version_id;
3623
    se->save_state = save_state;
3624
    se->load_state = load_state;
3625
    se->opaque = opaque;
3626
    se->next = NULL;
3627

    
3628
    /* add at the end of list */
3629
    pse = &first_se;
3630
    while (*pse != NULL)
3631
        pse = &(*pse)->next;
3632
    *pse = se;
3633
    return 0;
3634
}
3635

    
3636
#define QEMU_VM_FILE_MAGIC   0x5145564d
3637
#define QEMU_VM_FILE_VERSION 0x00000001
3638

    
3639
int qemu_savevm(const char *filename)
3640
{
3641
    SaveStateEntry *se;
3642
    QEMUFile *f;
3643
    int len, len_pos, cur_pos, saved_vm_running, ret;
3644

    
3645
    saved_vm_running = vm_running;
3646
    vm_stop(0);
3647

    
3648
    f = fopen(filename, "wb");
3649
    if (!f) {
3650
        ret = -1;
3651
        goto the_end;
3652
    }
3653

    
3654
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3655
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3656

    
3657
    for(se = first_se; se != NULL; se = se->next) {
3658
        /* ID string */
3659
        len = strlen(se->idstr);
3660
        qemu_put_byte(f, len);
3661
        qemu_put_buffer(f, se->idstr, len);
3662

    
3663
        qemu_put_be32(f, se->instance_id);
3664
        qemu_put_be32(f, se->version_id);
3665

    
3666
        /* record size: filled later */
3667
        len_pos = ftell(f);
3668
        qemu_put_be32(f, 0);
3669
        
3670
        se->save_state(f, se->opaque);
3671

    
3672
        /* fill record size */
3673
        cur_pos = ftell(f);
3674
        len = ftell(f) - len_pos - 4;
3675
        fseek(f, len_pos, SEEK_SET);
3676
        qemu_put_be32(f, len);
3677
        fseek(f, cur_pos, SEEK_SET);
3678
    }
3679

    
3680
    fclose(f);
3681
    ret = 0;
3682
 the_end:
3683
    if (saved_vm_running)
3684
        vm_start();
3685
    return ret;
3686
}
3687

    
3688
static SaveStateEntry *find_se(const char *idstr, int instance_id)
3689
{
3690
    SaveStateEntry *se;
3691

    
3692
    for(se = first_se; se != NULL; se = se->next) {
3693
        if (!strcmp(se->idstr, idstr) && 
3694
            instance_id == se->instance_id)
3695
            return se;
3696
    }
3697
    return NULL;
3698
}
3699

    
3700
int qemu_loadvm(const char *filename)
3701
{
3702
    SaveStateEntry *se;
3703
    QEMUFile *f;
3704
    int len, cur_pos, ret, instance_id, record_len, version_id;
3705
    int saved_vm_running;
3706
    unsigned int v;
3707
    char idstr[256];
3708
    
3709
    saved_vm_running = vm_running;
3710
    vm_stop(0);
3711

    
3712
    f = fopen(filename, "rb");
3713
    if (!f) {
3714
        ret = -1;
3715
        goto the_end;
3716
    }
3717

    
3718
    v = qemu_get_be32(f);
3719
    if (v != QEMU_VM_FILE_MAGIC)
3720
        goto fail;
3721
    v = qemu_get_be32(f);
3722
    if (v != QEMU_VM_FILE_VERSION) {
3723
    fail:
3724
        fclose(f);
3725
        ret = -1;
3726
        goto the_end;
3727
    }
3728
    for(;;) {
3729
        len = qemu_get_byte(f);
3730
        if (feof(f))
3731
            break;
3732
        qemu_get_buffer(f, idstr, len);
3733
        idstr[len] = '\0';
3734
        instance_id = qemu_get_be32(f);
3735
        version_id = qemu_get_be32(f);
3736
        record_len = qemu_get_be32(f);
3737
#if 0
3738
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
3739
               idstr, instance_id, version_id, record_len);
3740
#endif
3741
        cur_pos = ftell(f);
3742
        se = find_se(idstr, instance_id);
3743
        if (!se) {
3744
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
3745
                    instance_id, idstr);
3746
        } else {
3747
            ret = se->load_state(f, se->opaque, version_id);
3748
            if (ret < 0) {
3749
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
3750
                        instance_id, idstr);
3751
            }
3752
        }
3753
        /* always seek to exact end of record */
3754
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3755
    }
3756
    fclose(f);
3757
    ret = 0;
3758
 the_end:
3759
    if (saved_vm_running)
3760
        vm_start();
3761
    return ret;
3762
}
3763

    
3764
/***********************************************************/
3765
/* cpu save/restore */
3766

    
3767
#if defined(TARGET_I386)
3768

    
3769
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3770
{
3771
    qemu_put_be32(f, dt->selector);
3772
    qemu_put_betl(f, dt->base);
3773
    qemu_put_be32(f, dt->limit);
3774
    qemu_put_be32(f, dt->flags);
3775
}
3776

    
3777
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3778
{
3779
    dt->selector = qemu_get_be32(f);
3780
    dt->base = qemu_get_betl(f);
3781
    dt->limit = qemu_get_be32(f);
3782
    dt->flags = qemu_get_be32(f);
3783
}
3784

    
3785
void cpu_save(QEMUFile *f, void *opaque)
3786
{
3787
    CPUState *env = opaque;
3788
    uint16_t fptag, fpus, fpuc, fpregs_format;
3789
    uint32_t hflags;
3790
    int i;
3791
    
3792
    for(i = 0; i < CPU_NB_REGS; i++)
3793
        qemu_put_betls(f, &env->regs[i]);
3794
    qemu_put_betls(f, &env->eip);
3795
    qemu_put_betls(f, &env->eflags);
3796
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3797
    qemu_put_be32s(f, &hflags);
3798
    
3799
    /* FPU */
3800
    fpuc = env->fpuc;
3801
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3802
    fptag = 0;
3803
    for(i = 0; i < 8; i++) {
3804
        fptag |= ((!env->fptags[i]) << i);
3805
    }
3806
    
3807
    qemu_put_be16s(f, &fpuc);
3808
    qemu_put_be16s(f, &fpus);
3809
    qemu_put_be16s(f, &fptag);
3810

    
3811
#ifdef USE_X86LDOUBLE
3812
    fpregs_format = 0;
3813
#else
3814
    fpregs_format = 1;
3815
#endif
3816
    qemu_put_be16s(f, &fpregs_format);
3817
    
3818
    for(i = 0; i < 8; i++) {
3819
#ifdef USE_X86LDOUBLE
3820
        {
3821
            uint64_t mant;
3822
            uint16_t exp;
3823
            /* we save the real CPU data (in case of MMX usage only 'mant'
3824
               contains the MMX register */
3825
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3826
            qemu_put_be64(f, mant);
3827
            qemu_put_be16(f, exp);
3828
        }
3829
#else
3830
        /* if we use doubles for float emulation, we save the doubles to
3831
           avoid losing information in case of MMX usage. It can give
3832
           problems if the image is restored on a CPU where long
3833
           doubles are used instead. */
3834
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3835
#endif
3836
    }
3837

    
3838
    for(i = 0; i < 6; i++)
3839
        cpu_put_seg(f, &env->segs[i]);
3840
    cpu_put_seg(f, &env->ldt);
3841
    cpu_put_seg(f, &env->tr);
3842
    cpu_put_seg(f, &env->gdt);
3843
    cpu_put_seg(f, &env->idt);
3844
    
3845
    qemu_put_be32s(f, &env->sysenter_cs);
3846
    qemu_put_be32s(f, &env->sysenter_esp);
3847
    qemu_put_be32s(f, &env->sysenter_eip);
3848
    
3849
    qemu_put_betls(f, &env->cr[0]);
3850
    qemu_put_betls(f, &env->cr[2]);
3851
    qemu_put_betls(f, &env->cr[3]);
3852
    qemu_put_betls(f, &env->cr[4]);
3853
    
3854
    for(i = 0; i < 8; i++)
3855
        qemu_put_betls(f, &env->dr[i]);
3856

    
3857
    /* MMU */
3858
    qemu_put_be32s(f, &env->a20_mask);
3859

    
3860
    /* XMM */
3861
    qemu_put_be32s(f, &env->mxcsr);
3862
    for(i = 0; i < CPU_NB_REGS; i++) {
3863
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3864
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3865
    }
3866

    
3867
#ifdef TARGET_X86_64
3868
    qemu_put_be64s(f, &env->efer);
3869
    qemu_put_be64s(f, &env->star);
3870
    qemu_put_be64s(f, &env->lstar);
3871
    qemu_put_be64s(f, &env->cstar);
3872
    qemu_put_be64s(f, &env->fmask);
3873
    qemu_put_be64s(f, &env->kernelgsbase);
3874
#endif
3875
}
3876

    
3877
#ifdef USE_X86LDOUBLE
3878
/* XXX: add that in a FPU generic layer */
3879
union x86_longdouble {
3880
    uint64_t mant;
3881
    uint16_t exp;
3882
};
3883

    
3884
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
3885
#define EXPBIAS1 1023
3886
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
3887
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
3888

    
3889
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3890
{
3891
    int e;
3892
    /* mantissa */
3893
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3894
    /* exponent + sign */
3895
    e = EXPD1(temp) - EXPBIAS1 + 16383;
3896
    e |= SIGND1(temp) >> 16;
3897
    p->exp = e;
3898
}
3899
#endif
3900

    
3901
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3902
{
3903
    CPUState *env = opaque;
3904
    int i, guess_mmx;
3905
    uint32_t hflags;
3906
    uint16_t fpus, fpuc, fptag, fpregs_format;
3907

    
3908
    if (version_id != 3)
3909
        return -EINVAL;
3910
    for(i = 0; i < CPU_NB_REGS; i++)
3911
        qemu_get_betls(f, &env->regs[i]);
3912
    qemu_get_betls(f, &env->eip);
3913
    qemu_get_betls(f, &env->eflags);
3914
    qemu_get_be32s(f, &hflags);
3915

    
3916
    qemu_get_be16s(f, &fpuc);
3917
    qemu_get_be16s(f, &fpus);
3918
    qemu_get_be16s(f, &fptag);
3919
    qemu_get_be16s(f, &fpregs_format);
3920
    
3921
    /* NOTE: we cannot always restore the FPU state if the image come
3922
       from a host with a different 'USE_X86LDOUBLE' define. We guess
3923
       if we are in an MMX state to restore correctly in that case. */
3924
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3925
    for(i = 0; i < 8; i++) {
3926
        uint64_t mant;
3927
        uint16_t exp;
3928
        
3929
        switch(fpregs_format) {
3930
        case 0:
3931
            mant = qemu_get_be64(f);
3932
            exp = qemu_get_be16(f);
3933
#ifdef USE_X86LDOUBLE
3934
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
3935
#else
3936
            /* difficult case */
3937
            if (guess_mmx)
3938
                env->fpregs[i].mmx.MMX_Q(0) = mant;
3939
            else
3940
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
3941
#endif
3942
            break;
3943
        case 1:
3944
            mant = qemu_get_be64(f);
3945
#ifdef USE_X86LDOUBLE
3946
            {
3947
                union x86_longdouble *p;
3948
                /* difficult case */
3949
                p = (void *)&env->fpregs[i];
3950
                if (guess_mmx) {
3951
                    p->mant = mant;
3952
                    p->exp = 0xffff;
3953
                } else {
3954
                    fp64_to_fp80(p, mant);
3955
                }
3956
            }
3957
#else
3958
            env->fpregs[i].mmx.MMX_Q(0) = mant;
3959
#endif            
3960
            break;
3961
        default:
3962
            return -EINVAL;
3963
        }
3964
    }
3965

    
3966
    env->fpuc = fpuc;
3967
    /* XXX: restore FPU round state */
3968
    env->fpstt = (fpus >> 11) & 7;
3969
    env->fpus = fpus & ~0x3800;
3970
    fptag ^= 0xff;
3971
    for(i = 0; i < 8; i++) {
3972
        env->fptags[i] = (fptag >> i) & 1;
3973
    }
3974
    
3975
    for(i = 0; i < 6; i++)
3976
        cpu_get_seg(f, &env->segs[i]);
3977
    cpu_get_seg(f, &env->ldt);
3978
    cpu_get_seg(f, &env->tr);
3979
    cpu_get_seg(f, &env->gdt);
3980
    cpu_get_seg(f, &env->idt);
3981
    
3982
    qemu_get_be32s(f, &env->sysenter_cs);
3983
    qemu_get_be32s(f, &env->sysenter_esp);
3984
    qemu_get_be32s(f, &env->sysenter_eip);
3985
    
3986
    qemu_get_betls(f, &env->cr[0]);
3987
    qemu_get_betls(f, &env->cr[2]);
3988
    qemu_get_betls(f, &env->cr[3]);
3989
    qemu_get_betls(f, &env->cr[4]);
3990
    
3991
    for(i = 0; i < 8; i++)
3992
        qemu_get_betls(f, &env->dr[i]);
3993

    
3994
    /* MMU */
3995
    qemu_get_be32s(f, &env->a20_mask);
3996

    
3997
    qemu_get_be32s(f, &env->mxcsr);
3998
    for(i = 0; i < CPU_NB_REGS; i++) {
3999
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4000
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4001
    }
4002

    
4003
#ifdef TARGET_X86_64
4004
    qemu_get_be64s(f, &env->efer);
4005
    qemu_get_be64s(f, &env->star);
4006
    qemu_get_be64s(f, &env->lstar);
4007
    qemu_get_be64s(f, &env->cstar);
4008
    qemu_get_be64s(f, &env->fmask);
4009
    qemu_get_be64s(f, &env->kernelgsbase);
4010
#endif
4011

    
4012
    /* XXX: compute hflags from scratch, except for CPL and IIF */
4013
    env->hflags = hflags;
4014
    tlb_flush(env, 1);
4015
    return 0;
4016
}
4017

    
4018
#elif defined(TARGET_PPC)
4019
void cpu_save(QEMUFile *f, void *opaque)
4020
{
4021
}
4022

    
4023
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4024
{
4025
    return 0;
4026
}
4027

    
4028
#elif defined(TARGET_MIPS)
4029
void cpu_save(QEMUFile *f, void *opaque)
4030
{
4031
}
4032

    
4033
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4034
{
4035
    return 0;
4036
}
4037

    
4038
#elif defined(TARGET_SPARC)
4039
void cpu_save(QEMUFile *f, void *opaque)
4040
{
4041
    CPUState *env = opaque;
4042
    int i;
4043
    uint32_t tmp;
4044

    
4045
    for(i = 0; i < 8; i++)
4046
        qemu_put_betls(f, &env->gregs[i]);
4047
    for(i = 0; i < NWINDOWS * 16; i++)
4048
        qemu_put_betls(f, &env->regbase[i]);
4049

    
4050
    /* FPU */
4051
    for(i = 0; i < TARGET_FPREGS; i++) {
4052
        union {
4053
            TARGET_FPREG_T f;
4054
            target_ulong i;
4055
        } u;
4056
        u.f = env->fpr[i];
4057
        qemu_put_betl(f, u.i);
4058
    }
4059

    
4060
    qemu_put_betls(f, &env->pc);
4061
    qemu_put_betls(f, &env->npc);
4062
    qemu_put_betls(f, &env->y);
4063
    tmp = GET_PSR(env);
4064
    qemu_put_be32(f, tmp);
4065
    qemu_put_betls(f, &env->fsr);
4066
    qemu_put_betls(f, &env->tbr);
4067
#ifndef TARGET_SPARC64
4068
    qemu_put_be32s(f, &env->wim);
4069
    /* MMU */
4070
    for(i = 0; i < 16; i++)
4071
        qemu_put_be32s(f, &env->mmuregs[i]);
4072
#endif
4073
}
4074

    
4075
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4076
{
4077
    CPUState *env = opaque;
4078
    int i;
4079
    uint32_t tmp;
4080

    
4081
    for(i = 0; i < 8; i++)
4082
        qemu_get_betls(f, &env->gregs[i]);
4083
    for(i = 0; i < NWINDOWS * 16; i++)
4084
        qemu_get_betls(f, &env->regbase[i]);
4085

    
4086
    /* FPU */
4087
    for(i = 0; i < TARGET_FPREGS; i++) {
4088
        union {
4089
            TARGET_FPREG_T f;
4090
            target_ulong i;
4091
        } u;
4092
        u.i = qemu_get_betl(f);
4093
        env->fpr[i] = u.f;
4094
    }
4095

    
4096
    qemu_get_betls(f, &env->pc);
4097
    qemu_get_betls(f, &env->npc);
4098
    qemu_get_betls(f, &env->y);
4099
    tmp = qemu_get_be32(f);
4100
    env->cwp = 0; /* needed to ensure that the wrapping registers are
4101
                     correctly updated */
4102
    PUT_PSR(env, tmp);
4103
    qemu_get_betls(f, &env->fsr);
4104
    qemu_get_betls(f, &env->tbr);
4105
#ifndef TARGET_SPARC64
4106
    qemu_get_be32s(f, &env->wim);
4107
    /* MMU */
4108
    for(i = 0; i < 16; i++)
4109
        qemu_get_be32s(f, &env->mmuregs[i]);
4110
#endif
4111
    tlb_flush(env, 1);
4112
    return 0;
4113
}
4114

    
4115
#elif defined(TARGET_ARM)
4116

    
4117
/* ??? Need to implement these.  */
4118
void cpu_save(QEMUFile *f, void *opaque)
4119
{
4120
}
4121

    
4122
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4123
{
4124
    return 0;
4125
}
4126

    
4127
#else
4128

    
4129
#warning No CPU save/restore functions
4130

    
4131
#endif
4132

    
4133
/***********************************************************/
4134
/* ram save/restore */
4135

    
4136
/* we just avoid storing empty pages */
4137
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4138
{
4139
    int i, v;
4140

    
4141
    v = buf[0];
4142
    for(i = 1; i < len; i++) {
4143
        if (buf[i] != v)
4144
            goto normal_save;
4145
    }
4146
    qemu_put_byte(f, 1);
4147
    qemu_put_byte(f, v);
4148
    return;
4149
 normal_save:
4150
    qemu_put_byte(f, 0); 
4151
    qemu_put_buffer(f, buf, len);
4152
}
4153

    
4154
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4155
{
4156
    int v;
4157

    
4158
    v = qemu_get_byte(f);
4159
    switch(v) {
4160
    case 0:
4161
        if (qemu_get_buffer(f, buf, len) != len)
4162
            return -EIO;
4163
        break;
4164
    case 1:
4165
        v = qemu_get_byte(f);
4166
        memset(buf, v, len);
4167
        break;
4168
    default:
4169
        return -EINVAL;
4170
    }
4171
    return 0;
4172
}
4173

    
4174
static void ram_save(QEMUFile *f, void *opaque)
4175
{
4176
    int i;
4177
    qemu_put_be32(f, phys_ram_size);
4178
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4179
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4180
    }
4181
}
4182

    
4183
static int ram_load(QEMUFile *f, void *opaque, int version_id)
4184
{
4185
    int i, ret;
4186

    
4187
    if (version_id != 1)
4188
        return -EINVAL;
4189
    if (qemu_get_be32(f) != phys_ram_size)
4190
        return -EINVAL;
4191
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4192
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4193
        if (ret)
4194
            return ret;
4195
    }
4196
    return 0;
4197
}
4198

    
4199
/***********************************************************/
4200
/* machine registration */
4201

    
4202
QEMUMachine *first_machine = NULL;
4203

    
4204
int qemu_register_machine(QEMUMachine *m)
4205
{
4206
    QEMUMachine **pm;
4207
    pm = &first_machine;
4208
    while (*pm != NULL)
4209
        pm = &(*pm)->next;
4210
    m->next = NULL;
4211
    *pm = m;
4212
    return 0;
4213
}
4214

    
4215
QEMUMachine *find_machine(const char *name)
4216
{
4217
    QEMUMachine *m;
4218

    
4219
    for(m = first_machine; m != NULL; m = m->next) {
4220
        if (!strcmp(m->name, name))
4221
            return m;
4222
    }
4223
    return NULL;
4224
}
4225

    
4226
/***********************************************************/
4227
/* main execution loop */
4228

    
4229
void gui_update(void *opaque)
4230
{
4231
    display_state.dpy_refresh(&display_state);
4232
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4233
}
4234

    
4235
struct vm_change_state_entry {
4236
    VMChangeStateHandler *cb;
4237
    void *opaque;
4238
    LIST_ENTRY (vm_change_state_entry) entries;
4239
};
4240

    
4241
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4242

    
4243
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4244
                                                     void *opaque)
4245
{
4246
    VMChangeStateEntry *e;
4247

    
4248
    e = qemu_mallocz(sizeof (*e));
4249
    if (!e)
4250
        return NULL;
4251

    
4252
    e->cb = cb;
4253
    e->opaque = opaque;
4254
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4255
    return e;
4256
}
4257

    
4258
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4259
{
4260
    LIST_REMOVE (e, entries);
4261
    qemu_free (e);
4262
}
4263

    
4264
static void vm_state_notify(int running)
4265
{
4266
    VMChangeStateEntry *e;
4267

    
4268
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4269
        e->cb(e->opaque, running);
4270
    }
4271
}
4272

    
4273
/* XXX: support several handlers */
4274
static VMStopHandler *vm_stop_cb;
4275
static void *vm_stop_opaque;
4276

    
4277
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4278
{
4279
    vm_stop_cb = cb;
4280
    vm_stop_opaque = opaque;
4281
    return 0;
4282
}
4283

    
4284
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4285
{
4286
    vm_stop_cb = NULL;
4287
}
4288

    
4289
void vm_start(void)
4290
{
4291
    if (!vm_running) {
4292
        cpu_enable_ticks();
4293
        vm_running = 1;
4294
        vm_state_notify(1);
4295
    }
4296
}
4297

    
4298
void vm_stop(int reason) 
4299
{
4300
    if (vm_running) {
4301
        cpu_disable_ticks();
4302
        vm_running = 0;
4303
        if (reason != 0) {
4304
            if (vm_stop_cb) {
4305
                vm_stop_cb(vm_stop_opaque, reason);
4306
            }
4307
        }
4308
        vm_state_notify(0);
4309
    }
4310
}
4311

    
4312
/* reset/shutdown handler */
4313

    
4314
typedef struct QEMUResetEntry {
4315
    QEMUResetHandler *func;
4316
    void *opaque;
4317
    struct QEMUResetEntry *next;
4318
} QEMUResetEntry;
4319

    
4320
static QEMUResetEntry *first_reset_entry;
4321
static int reset_requested;
4322
static int shutdown_requested;
4323
static int powerdown_requested;
4324

    
4325
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4326
{
4327
    QEMUResetEntry **pre, *re;
4328

    
4329
    pre = &first_reset_entry;
4330
    while (*pre != NULL)
4331
        pre = &(*pre)->next;
4332
    re = qemu_mallocz(sizeof(QEMUResetEntry));
4333
    re->func = func;
4334
    re->opaque = opaque;
4335
    re->next = NULL;
4336
    *pre = re;
4337
}
4338

    
4339
void qemu_system_reset(void)
4340
{
4341
    QEMUResetEntry *re;
4342

    
4343
    /* reset all devices */
4344
    for(re = first_reset_entry; re != NULL; re = re->next) {
4345
        re->func(re->opaque);
4346
    }
4347
}
4348

    
4349
void qemu_system_reset_request(void)
4350
{
4351
    reset_requested = 1;
4352
    if (cpu_single_env)
4353
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4354
}
4355

    
4356
void qemu_system_shutdown_request(void)
4357
{
4358
    shutdown_requested = 1;
4359
    if (cpu_single_env)
4360
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4361
}
4362

    
4363
void qemu_system_powerdown_request(void)
4364
{
4365
    powerdown_requested = 1;
4366
    if (cpu_single_env)
4367
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4368
}
4369

    
4370
void main_loop_wait(int timeout)
4371
{
4372
    IOHandlerRecord *ioh, *ioh_next;
4373
    fd_set rfds, wfds;
4374
    int ret, nfds;
4375
    struct timeval tv;
4376
    PollingEntry *pe;
4377

    
4378

    
4379
    /* XXX: need to suppress polling by better using win32 events */
4380
    ret = 0;
4381
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4382
        ret |= pe->func(pe->opaque);
4383
    }
4384
#ifdef _WIN32
4385
    if (ret == 0 && timeout > 0) {
4386
        Sleep(timeout);
4387
    }
4388
#endif
4389
    /* poll any events */
4390
    /* XXX: separate device handlers from system ones */
4391
    nfds = -1;
4392
    FD_ZERO(&rfds);
4393
    FD_ZERO(&wfds);
4394
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4395
        if (ioh->fd_read &&
4396
            (!ioh->fd_read_poll ||
4397
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4398
            FD_SET(ioh->fd, &rfds);
4399
            if (ioh->fd > nfds)
4400
                nfds = ioh->fd;
4401
        }
4402
        if (ioh->fd_write) {
4403
            FD_SET(ioh->fd, &wfds);
4404
            if (ioh->fd > nfds)
4405
                nfds = ioh->fd;
4406
        }
4407
    }
4408
    
4409
    tv.tv_sec = 0;
4410
#ifdef _WIN32
4411
    tv.tv_usec = 0;
4412
#else
4413
    tv.tv_usec = timeout * 1000;
4414
#endif
4415
    ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4416
    if (ret > 0) {
4417
        /* XXX: better handling of removal */
4418
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4419
            ioh_next = ioh->next;
4420
            if (FD_ISSET(ioh->fd, &rfds)) {
4421
                ioh->fd_read(ioh->opaque);
4422
            }
4423
            if (FD_ISSET(ioh->fd, &wfds)) {
4424
                ioh->fd_write(ioh->opaque);
4425
            }
4426
        }
4427
    }
4428
#ifdef _WIN32
4429
    tap_win32_poll();
4430
#endif
4431

    
4432
#if defined(CONFIG_SLIRP)
4433
    /* XXX: merge with the previous select() */
4434
    if (slirp_inited) {
4435
        fd_set rfds, wfds, xfds;
4436
        int nfds;
4437
        struct timeval tv;
4438
        
4439
        nfds = -1;
4440
        FD_ZERO(&rfds);
4441
        FD_ZERO(&wfds);
4442
        FD_ZERO(&xfds);
4443
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4444
        tv.tv_sec = 0;
4445
        tv.tv_usec = 0;
4446
        ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4447
        if (ret >= 0) {
4448
            slirp_select_poll(&rfds, &wfds, &xfds);
4449
        }
4450
    }
4451
#endif
4452

    
4453
    if (vm_running) {
4454
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
4455
                        qemu_get_clock(vm_clock));
4456
        /* run dma transfers, if any */
4457
        DMA_run();
4458
    }
4459
    
4460
    /* real time timers */
4461
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
4462
                    qemu_get_clock(rt_clock));
4463
}
4464

    
4465
static CPUState *cur_cpu;
4466

    
4467
int main_loop(void)
4468
{
4469
    int ret, timeout;
4470
#ifdef CONFIG_PROFILER
4471
    int64_t ti;
4472
#endif
4473
    CPUState *env;
4474

    
4475
    cur_cpu = first_cpu;
4476
    for(;;) {
4477
        if (vm_running) {
4478

    
4479
            env = cur_cpu;
4480
            for(;;) {
4481
                /* get next cpu */
4482
                env = env->next_cpu;
4483
                if (!env)
4484
                    env = first_cpu;
4485
#ifdef CONFIG_PROFILER
4486
                ti = profile_getclock();
4487
#endif
4488
                ret = cpu_exec(env);
4489
#ifdef CONFIG_PROFILER
4490
                qemu_time += profile_getclock() - ti;
4491
#endif
4492
                if (ret != EXCP_HALTED)
4493
                    break;
4494
                /* all CPUs are halted ? */
4495
                if (env == cur_cpu) {
4496
                    ret = EXCP_HLT;
4497
                    break;
4498
                }
4499
            }
4500
            cur_cpu = env;
4501

    
4502
            if (shutdown_requested) {
4503
                ret = EXCP_INTERRUPT;
4504
                break;
4505
            }
4506
            if (reset_requested) {
4507
                reset_requested = 0;
4508
                qemu_system_reset();
4509
                ret = EXCP_INTERRUPT;
4510
            }
4511
            if (powerdown_requested) {
4512
                powerdown_requested = 0;
4513
                qemu_system_powerdown();
4514
                ret = EXCP_INTERRUPT;
4515
            }
4516
            if (ret == EXCP_DEBUG) {
4517
                vm_stop(EXCP_DEBUG);
4518
            }
4519
            /* if hlt instruction, we wait until the next IRQ */
4520
            /* XXX: use timeout computed from timers */
4521
            if (ret == EXCP_HLT)
4522
                timeout = 10;
4523
            else
4524
                timeout = 0;
4525
        } else {
4526
            timeout = 10;
4527
        }
4528
#ifdef CONFIG_PROFILER
4529
        ti = profile_getclock();
4530
#endif
4531
        main_loop_wait(timeout);
4532
#ifdef CONFIG_PROFILER
4533
        dev_time += profile_getclock() - ti;
4534
#endif
4535
    }
4536
    cpu_disable_ticks();
4537
    return ret;
4538
}
4539

    
4540
void help(void)
4541
{
4542
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4543
           "usage: %s [options] [disk_image]\n"
4544
           "\n"
4545
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4546
           "\n"
4547
           "Standard options:\n"
4548
           "-M machine      select emulated machine (-M ? for list)\n"
4549
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
4550
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
4551
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
4552
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4553
           "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4554
           "-snapshot       write to temporary files instead of disk image files\n"
4555
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
4556
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
4557
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
4558
#ifndef _WIN32
4559
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
4560
#endif
4561
#ifdef HAS_AUDIO
4562
           "-audio-help     print list of audio drivers and their options\n"
4563
           "-soundhw c1,... enable audio support\n"
4564
           "                and only specified sound cards (comma separated list)\n"
4565
           "                use -soundhw ? to get the list of supported cards\n"
4566
           "                use -soundhw all to enable all of them\n"
4567
#endif
4568
           "-localtime      set the real time clock to local time [default=utc]\n"
4569
           "-full-screen    start in full screen\n"
4570
#ifdef TARGET_I386
4571
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
4572
#endif
4573
           "-usb            enable the USB driver (will be the default soon)\n"
4574
           "-usbdevice name add the host or guest USB device 'name'\n"
4575
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4576
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
4577
#endif
4578
           "\n"
4579
           "Network options:\n"
4580
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4581
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
4582
#ifdef CONFIG_SLIRP
4583
           "-net user[,vlan=n][,hostname=host]\n"
4584
           "                connect the user mode network stack to VLAN 'n' and send\n"
4585
           "                hostname 'host' to DHCP clients\n"
4586
#endif
4587
#ifdef _WIN32
4588
           "-net tap[,vlan=n],ifname=name\n"
4589
           "                connect the host TAP network interface to VLAN 'n'\n"
4590
#else
4591
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4592
           "                connect the host TAP network interface to VLAN 'n' and use\n"
4593
           "                the network script 'file' (default=%s);\n"
4594
           "                use 'fd=h' to connect to an already opened TAP interface\n"
4595
#endif
4596
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4597
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
4598
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4599
           "                connect the vlan 'n' to multicast maddr and port\n"
4600
           "-net none       use it alone to have zero network devices; if no -net option\n"
4601
           "                is provided, the default is '-net nic -net user'\n"
4602
           "\n"
4603
#ifdef CONFIG_SLIRP
4604
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
4605
#ifndef _WIN32
4606
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
4607
#endif
4608
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4609
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
4610
#endif
4611
           "\n"
4612
           "Linux boot specific:\n"
4613
           "-kernel bzImage use 'bzImage' as kernel image\n"
4614
           "-append cmdline use 'cmdline' as kernel command line\n"
4615
           "-initrd file    use 'file' as initial ram disk\n"
4616
           "\n"
4617
           "Debug/Expert options:\n"
4618
           "-monitor dev    redirect the monitor to char device 'dev'\n"
4619
           "-serial dev     redirect the serial port to char device 'dev'\n"
4620
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
4621
           "-pidfile file   Write PID to 'file'\n"
4622
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
4623
           "-s              wait gdb connection to port %d\n"
4624
           "-p port         change gdb connection port\n"
4625
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
4626
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
4627
           "                translation (t=none or lba) (usually qemu can guess them)\n"
4628
           "-L path         set the directory for the BIOS and VGA BIOS\n"
4629
#ifdef USE_KQEMU
4630
           "-no-kqemu       disable KQEMU kernel module usage\n"
4631
#endif
4632
#ifdef USE_CODE_COPY
4633
           "-no-code-copy   disable code copy acceleration\n"
4634
#endif
4635
#ifdef TARGET_I386
4636
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
4637
           "                (default is CL-GD5446 PCI VGA)\n"
4638
#endif
4639
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
4640
           "-vnc display    start a VNC server on display\n"
4641
           "\n"
4642
           "During emulation, the following keys are useful:\n"
4643
           "ctrl-alt-f      toggle full screen\n"
4644
           "ctrl-alt-n      switch to virtual console 'n'\n"
4645
           "ctrl-alt        toggle mouse and keyboard grab\n"
4646
           "\n"
4647
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4648
           ,
4649
#ifdef CONFIG_SOFTMMU
4650
           "qemu",
4651
#else
4652
           "qemu-fast",
4653
#endif
4654
           DEFAULT_RAM_SIZE,
4655
#ifndef _WIN32
4656
           DEFAULT_NETWORK_SCRIPT,
4657
#endif
4658
           DEFAULT_GDBSTUB_PORT,
4659
           "/tmp/qemu.log");
4660
#ifndef CONFIG_SOFTMMU
4661
    printf("\n"
4662
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4663
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4664
           "PC emulation.\n");
4665
#endif
4666
    exit(1);
4667
}
4668

    
4669
#define HAS_ARG 0x0001
4670

    
4671
enum {
4672
    QEMU_OPTION_h,
4673

    
4674
    QEMU_OPTION_M,
4675
    QEMU_OPTION_fda,
4676
    QEMU_OPTION_fdb,
4677
    QEMU_OPTION_hda,
4678
    QEMU_OPTION_hdb,
4679
    QEMU_OPTION_hdc,
4680
    QEMU_OPTION_hdd,
4681
    QEMU_OPTION_cdrom,
4682
    QEMU_OPTION_boot,
4683
    QEMU_OPTION_snapshot,
4684
    QEMU_OPTION_m,
4685
    QEMU_OPTION_nographic,
4686
#ifdef HAS_AUDIO
4687
    QEMU_OPTION_audio_help,
4688
    QEMU_OPTION_soundhw,
4689
#endif
4690

    
4691
    QEMU_OPTION_net,
4692
    QEMU_OPTION_tftp,
4693
    QEMU_OPTION_smb,
4694
    QEMU_OPTION_redir,
4695

    
4696
    QEMU_OPTION_kernel,
4697
    QEMU_OPTION_append,
4698
    QEMU_OPTION_initrd,
4699

    
4700
    QEMU_OPTION_S,
4701
    QEMU_OPTION_s,
4702
    QEMU_OPTION_p,
4703
    QEMU_OPTION_d,
4704
    QEMU_OPTION_hdachs,
4705
    QEMU_OPTION_L,
4706
    QEMU_OPTION_no_code_copy,
4707
    QEMU_OPTION_k,
4708
    QEMU_OPTION_localtime,
4709
    QEMU_OPTION_cirrusvga,
4710
    QEMU_OPTION_g,
4711
    QEMU_OPTION_std_vga,
4712
    QEMU_OPTION_monitor,
4713
    QEMU_OPTION_serial,
4714
    QEMU_OPTION_parallel,
4715
    QEMU_OPTION_loadvm,
4716
    QEMU_OPTION_full_screen,
4717
    QEMU_OPTION_pidfile,
4718
    QEMU_OPTION_no_kqemu,
4719
    QEMU_OPTION_kernel_kqemu,
4720
    QEMU_OPTION_win2k_hack,
4721
    QEMU_OPTION_usb,
4722
    QEMU_OPTION_usbdevice,
4723
    QEMU_OPTION_smp,
4724
    QEMU_OPTION_vnc,
4725
};
4726

    
4727
typedef struct QEMUOption {
4728
    const char *name;
4729
    int flags;
4730
    int index;
4731
} QEMUOption;
4732

    
4733
const QEMUOption qemu_options[] = {
4734
    { "h", 0, QEMU_OPTION_h },
4735

    
4736
    { "M", HAS_ARG, QEMU_OPTION_M },
4737
    { "fda", HAS_ARG, QEMU_OPTION_fda },
4738
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4739
    { "hda", HAS_ARG, QEMU_OPTION_hda },
4740
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4741
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4742
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4743
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4744
    { "boot", HAS_ARG, QEMU_OPTION_boot },
4745
    { "snapshot", 0, QEMU_OPTION_snapshot },
4746
    { "m", HAS_ARG, QEMU_OPTION_m },
4747
    { "nographic", 0, QEMU_OPTION_nographic },
4748
    { "k", HAS_ARG, QEMU_OPTION_k },
4749
#ifdef HAS_AUDIO
4750
    { "audio-help", 0, QEMU_OPTION_audio_help },
4751
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4752
#endif
4753

    
4754
    { "net", HAS_ARG, QEMU_OPTION_net},
4755
#ifdef CONFIG_SLIRP
4756
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4757
#ifndef _WIN32
4758
    { "smb", HAS_ARG, QEMU_OPTION_smb },
4759
#endif
4760
    { "redir", HAS_ARG, QEMU_OPTION_redir },
4761
#endif
4762

    
4763
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4764
    { "append", HAS_ARG, QEMU_OPTION_append },
4765
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4766

    
4767
    { "S", 0, QEMU_OPTION_S },
4768
    { "s", 0, QEMU_OPTION_s },
4769
    { "p", HAS_ARG, QEMU_OPTION_p },
4770
    { "d", HAS_ARG, QEMU_OPTION_d },
4771
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4772
    { "L", HAS_ARG, QEMU_OPTION_L },
4773
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4774
#ifdef USE_KQEMU
4775
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4776
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4777
#endif
4778
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4779
    { "g", 1, QEMU_OPTION_g },
4780
#endif
4781
    { "localtime", 0, QEMU_OPTION_localtime },
4782
    { "std-vga", 0, QEMU_OPTION_std_vga },
4783
    { "monitor", 1, QEMU_OPTION_monitor },
4784
    { "serial", 1, QEMU_OPTION_serial },
4785
    { "parallel", 1, QEMU_OPTION_parallel },
4786
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4787
    { "full-screen", 0, QEMU_OPTION_full_screen },
4788
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4789
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4790
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4791
    { "smp", HAS_ARG, QEMU_OPTION_smp },
4792
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4793
    
4794
    /* temporary options */
4795
    { "usb", 0, QEMU_OPTION_usb },
4796
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4797
    { NULL },
4798
};
4799

    
4800
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4801

    
4802
/* this stack is only used during signal handling */
4803
#define SIGNAL_STACK_SIZE 32768
4804

    
4805
static uint8_t *signal_stack;
4806

    
4807
#endif
4808

    
4809
/* password input */
4810

    
4811
static BlockDriverState *get_bdrv(int index)
4812
{
4813
    BlockDriverState *bs;
4814

    
4815
    if (index < 4) {
4816
        bs = bs_table[index];
4817
    } else if (index < 6) {
4818
        bs = fd_table[index - 4];
4819
    } else {
4820
        bs = NULL;
4821
    }
4822
    return bs;
4823
}
4824

    
4825
static void read_passwords(void)
4826
{
4827
    BlockDriverState *bs;
4828
    int i, j;
4829
    char password[256];
4830

    
4831
    for(i = 0; i < 6; i++) {
4832
        bs = get_bdrv(i);
4833
        if (bs && bdrv_is_encrypted(bs)) {
4834
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4835
            for(j = 0; j < 3; j++) {
4836
                monitor_readline("Password: ", 
4837
                                 1, password, sizeof(password));
4838
                if (bdrv_set_key(bs, password) == 0)
4839
                    break;
4840
                term_printf("invalid password\n");
4841
            }
4842
        }
4843
    }
4844
}
4845

    
4846
/* XXX: currently we cannot use simultaneously different CPUs */
4847
void register_machines(void)
4848
{
4849
#if defined(TARGET_I386)
4850
    qemu_register_machine(&pc_machine);
4851
    qemu_register_machine(&isapc_machine);
4852
#elif defined(TARGET_PPC)
4853
    qemu_register_machine(&heathrow_machine);
4854
    qemu_register_machine(&core99_machine);
4855
    qemu_register_machine(&prep_machine);
4856
#elif defined(TARGET_MIPS)
4857
    qemu_register_machine(&mips_machine);
4858
#elif defined(TARGET_SPARC)
4859
#ifdef TARGET_SPARC64
4860
    qemu_register_machine(&sun4u_machine);
4861
#else
4862
    qemu_register_machine(&sun4m_machine);
4863
#endif
4864
#elif defined(TARGET_ARM)
4865
    qemu_register_machine(&integratorcp926_machine);
4866
    qemu_register_machine(&integratorcp1026_machine);
4867
    qemu_register_machine(&versatilepb_machine);
4868
    qemu_register_machine(&versatileab_machine);
4869
#elif defined(TARGET_SH4)
4870
    qemu_register_machine(&shix_machine);
4871
#else
4872
#error unsupported CPU
4873
#endif
4874
}
4875

    
4876
#ifdef HAS_AUDIO
4877
struct soundhw soundhw[] = {
4878
#ifdef TARGET_I386
4879
    {
4880
        "pcspk",
4881
        "PC speaker",
4882
        0,
4883
        1,
4884
        { .init_isa = pcspk_audio_init }
4885
    },
4886
#endif
4887
    {
4888
        "sb16",
4889
        "Creative Sound Blaster 16",
4890
        0,
4891
        1,
4892
        { .init_isa = SB16_init }
4893
    },
4894

    
4895
#ifdef CONFIG_ADLIB
4896
    {
4897
        "adlib",
4898
#ifdef HAS_YMF262
4899
        "Yamaha YMF262 (OPL3)",
4900
#else
4901
        "Yamaha YM3812 (OPL2)",
4902
#endif
4903
        0,
4904
        1,
4905
        { .init_isa = Adlib_init }
4906
    },
4907
#endif
4908

    
4909
#ifdef CONFIG_GUS
4910
    {
4911
        "gus",
4912
        "Gravis Ultrasound GF1",
4913
        0,
4914
        1,
4915
        { .init_isa = GUS_init }
4916
    },
4917
#endif
4918

    
4919
    {
4920
        "es1370",
4921
        "ENSONIQ AudioPCI ES1370",
4922
        0,
4923
        0,
4924
        { .init_pci = es1370_init }
4925
    },
4926

    
4927
    { NULL, NULL, 0, 0, { NULL } }
4928
};
4929

    
4930
static void select_soundhw (const char *optarg)
4931
{
4932
    struct soundhw *c;
4933

    
4934
    if (*optarg == '?') {
4935
    show_valid_cards:
4936

    
4937
        printf ("Valid sound card names (comma separated):\n");
4938
        for (c = soundhw; c->name; ++c) {
4939
            printf ("%-11s %s\n", c->name, c->descr);
4940
        }
4941
        printf ("\n-soundhw all will enable all of the above\n");
4942
        exit (*optarg != '?');
4943
    }
4944
    else {
4945
        size_t l;
4946
        const char *p;
4947
        char *e;
4948
        int bad_card = 0;
4949

    
4950
        if (!strcmp (optarg, "all")) {
4951
            for (c = soundhw; c->name; ++c) {
4952
                c->enabled = 1;
4953
            }
4954
            return;
4955
        }
4956

    
4957
        p = optarg;
4958
        while (*p) {
4959
            e = strchr (p, ',');
4960
            l = !e ? strlen (p) : (size_t) (e - p);
4961

    
4962
            for (c = soundhw; c->name; ++c) {
4963
                if (!strncmp (c->name, p, l)) {
4964
                    c->enabled = 1;
4965
                    break;
4966
                }
4967
            }
4968

    
4969
            if (!c->name) {
4970
                if (l > 80) {
4971
                    fprintf (stderr,
4972
                             "Unknown sound card name (too big to show)\n");
4973
                }
4974
                else {
4975
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4976
                             (int) l, p);
4977
                }
4978
                bad_card = 1;
4979
            }
4980
            p += l + (e != NULL);
4981
        }
4982

    
4983
        if (bad_card)
4984
            goto show_valid_cards;
4985
    }
4986
}
4987
#endif
4988

    
4989
#define MAX_NET_CLIENTS 32
4990

    
4991
int main(int argc, char **argv)
4992
{
4993
#ifdef CONFIG_GDBSTUB
4994
    int use_gdbstub, gdbstub_port;
4995
#endif
4996
    int i, cdrom_index;
4997
    int snapshot, linux_boot;
4998
    const char *initrd_filename;
4999
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5000
    const char *kernel_filename, *kernel_cmdline;
5001
    DisplayState *ds = &display_state;
5002
    int cyls, heads, secs, translation;
5003
    int start_emulation = 1;
5004
    char net_clients[MAX_NET_CLIENTS][256];
5005
    int nb_net_clients;
5006
    int optind;
5007
    const char *r, *optarg;
5008
    CharDriverState *monitor_hd;
5009
    char monitor_device[128];
5010
    char serial_devices[MAX_SERIAL_PORTS][128];
5011
    int serial_device_index;
5012
    char parallel_devices[MAX_PARALLEL_PORTS][128];
5013
    int parallel_device_index;
5014
    const char *loadvm = NULL;
5015
    QEMUMachine *machine;
5016
    char usb_devices[MAX_VM_USB_PORTS][128];
5017
    int usb_devices_index;
5018

    
5019
    LIST_INIT (&vm_change_state_head);
5020
#if !defined(CONFIG_SOFTMMU)
5021
    /* we never want that malloc() uses mmap() */
5022
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5023
#endif
5024
    register_machines();
5025
    machine = first_machine;
5026
    initrd_filename = NULL;
5027
    for(i = 0; i < MAX_FD; i++)
5028
        fd_filename[i] = NULL;
5029
    for(i = 0; i < MAX_DISKS; i++)
5030
        hd_filename[i] = NULL;
5031
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5032
    vga_ram_size = VGA_RAM_SIZE;
5033
    bios_size = BIOS_SIZE;
5034
#ifdef CONFIG_GDBSTUB
5035
    use_gdbstub = 0;
5036
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
5037
#endif
5038
    snapshot = 0;
5039
    nographic = 0;
5040
    kernel_filename = NULL;
5041
    kernel_cmdline = "";
5042
#ifdef TARGET_PPC
5043
    cdrom_index = 1;
5044
#else
5045
    cdrom_index = 2;
5046
#endif
5047
    cyls = heads = secs = 0;
5048
    translation = BIOS_ATA_TRANSLATION_AUTO;
5049
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5050

    
5051
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5052
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
5053
        serial_devices[i][0] = '\0';
5054
    serial_device_index = 0;
5055
    
5056
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5057
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5058
        parallel_devices[i][0] = '\0';
5059
    parallel_device_index = 0;
5060
    
5061
    usb_devices_index = 0;
5062
    
5063
    nb_net_clients = 0;
5064

    
5065
    nb_nics = 0;
5066
    /* default mac address of the first network interface */
5067
    
5068
    optind = 1;
5069
    for(;;) {
5070
        if (optind >= argc)
5071
            break;
5072
        r = argv[optind];
5073
        if (r[0] != '-') {
5074
            hd_filename[0] = argv[optind++];
5075
        } else {
5076
            const QEMUOption *popt;
5077

    
5078
            optind++;
5079
            popt = qemu_options;
5080
            for(;;) {
5081
                if (!popt->name) {
5082
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
5083
                            argv[0], r);
5084
                    exit(1);
5085
                }
5086
                if (!strcmp(popt->name, r + 1))
5087
                    break;
5088
                popt++;
5089
            }
5090
            if (popt->flags & HAS_ARG) {
5091
                if (optind >= argc) {
5092
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
5093
                            argv[0], r);
5094
                    exit(1);
5095
                }
5096
                optarg = argv[optind++];
5097
            } else {
5098
                optarg = NULL;
5099
            }
5100

    
5101
            switch(popt->index) {
5102
            case QEMU_OPTION_M:
5103
                machine = find_machine(optarg);
5104
                if (!machine) {
5105
                    QEMUMachine *m;
5106
                    printf("Supported machines are:\n");
5107
                    for(m = first_machine; m != NULL; m = m->next) {
5108
                        printf("%-10s %s%s\n",
5109
                               m->name, m->desc, 
5110
                               m == first_machine ? " (default)" : "");
5111
                    }
5112
                    exit(1);
5113
                }
5114
                break;
5115
            case QEMU_OPTION_initrd:
5116
                initrd_filename = optarg;
5117
                break;
5118
            case QEMU_OPTION_hda:
5119
            case QEMU_OPTION_hdb:
5120
            case QEMU_OPTION_hdc:
5121
            case QEMU_OPTION_hdd:
5122
                {
5123
                    int hd_index;
5124
                    hd_index = popt->index - QEMU_OPTION_hda;
5125
                    hd_filename[hd_index] = optarg;
5126
                    if (hd_index == cdrom_index)
5127
                        cdrom_index = -1;
5128
                }
5129
                break;
5130
            case QEMU_OPTION_snapshot:
5131
                snapshot = 1;
5132
                break;
5133
            case QEMU_OPTION_hdachs:
5134
                {
5135
                    const char *p;
5136
                    p = optarg;
5137
                    cyls = strtol(p, (char **)&p, 0);
5138
                    if (cyls < 1 || cyls > 16383)
5139
                        goto chs_fail;
5140
                    if (*p != ',')
5141
                        goto chs_fail;
5142
                    p++;
5143
                    heads = strtol(p, (char **)&p, 0);
5144
                    if (heads < 1 || heads > 16)
5145
                        goto chs_fail;
5146
                    if (*p != ',')
5147
                        goto chs_fail;
5148
                    p++;
5149
                    secs = strtol(p, (char **)&p, 0);
5150
                    if (secs < 1 || secs > 63)
5151
                        goto chs_fail;
5152
                    if (*p == ',') {
5153
                        p++;
5154
                        if (!strcmp(p, "none"))
5155
                            translation = BIOS_ATA_TRANSLATION_NONE;
5156
                        else if (!strcmp(p, "lba"))
5157
                            translation = BIOS_ATA_TRANSLATION_LBA;
5158
                        else if (!strcmp(p, "auto"))
5159
                            translation = BIOS_ATA_TRANSLATION_AUTO;
5160
                        else
5161
                            goto chs_fail;
5162
                    } else if (*p != '\0') {
5163
                    chs_fail:
5164
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
5165
                        exit(1);
5166
                    }
5167
                }
5168
                break;
5169
            case QEMU_OPTION_nographic:
5170
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5171
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5172
                nographic = 1;
5173
                break;
5174
            case QEMU_OPTION_kernel:
5175
                kernel_filename = optarg;
5176
                break;
5177
            case QEMU_OPTION_append:
5178
                kernel_cmdline = optarg;
5179
                break;
5180
            case QEMU_OPTION_cdrom:
5181
                if (cdrom_index >= 0) {
5182
                    hd_filename[cdrom_index] = optarg;
5183
                }
5184
                break;
5185
            case QEMU_OPTION_boot:
5186
                boot_device = optarg[0];
5187
                if (boot_device != 'a' && 
5188
#ifdef TARGET_SPARC
5189
                    // Network boot
5190
                    boot_device != 'n' &&
5191
#endif
5192
                    boot_device != 'c' && boot_device != 'd') {
5193
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5194
                    exit(1);
5195
                }
5196
                break;
5197
            case QEMU_OPTION_fda:
5198
                fd_filename[0] = optarg;
5199
                break;
5200
            case QEMU_OPTION_fdb:
5201
                fd_filename[1] = optarg;
5202
                break;
5203
            case QEMU_OPTION_no_code_copy:
5204
                code_copy_enabled = 0;
5205
                break;
5206
            case QEMU_OPTION_net:
5207
                if (nb_net_clients >= MAX_NET_CLIENTS) {
5208
                    fprintf(stderr, "qemu: too many network clients\n");
5209
                    exit(1);
5210
                }
5211
                pstrcpy(net_clients[nb_net_clients],
5212
                        sizeof(net_clients[0]),
5213
                        optarg);
5214
                nb_net_clients++;
5215
                break;
5216
#ifdef CONFIG_SLIRP
5217
            case QEMU_OPTION_tftp:
5218
                tftp_prefix = optarg;
5219
                break;
5220
#ifndef _WIN32
5221
            case QEMU_OPTION_smb:
5222
                net_slirp_smb(optarg);
5223
                break;
5224
#endif
5225
            case QEMU_OPTION_redir:
5226
                net_slirp_redir(optarg);                
5227
                break;
5228
#endif
5229
#ifdef HAS_AUDIO
5230
            case QEMU_OPTION_audio_help:
5231
                AUD_help ();
5232
                exit (0);
5233
                break;
5234
            case QEMU_OPTION_soundhw:
5235
                select_soundhw (optarg);
5236
                break;
5237
#endif
5238
            case QEMU_OPTION_h:
5239
                help();
5240
                break;
5241
            case QEMU_OPTION_m:
5242
                ram_size = atoi(optarg) * 1024 * 1024;
5243
                if (ram_size <= 0)
5244
                    help();
5245
                if (ram_size > PHYS_RAM_MAX_SIZE) {
5246
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5247
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
5248
                    exit(1);
5249
                }
5250
                break;
5251
            case QEMU_OPTION_d:
5252
                {
5253
                    int mask;
5254
                    CPULogItem *item;
5255
                    
5256
                    mask = cpu_str_to_log_mask(optarg);
5257
                    if (!mask) {
5258
                        printf("Log items (comma separated):\n");
5259
                    for(item = cpu_log_items; item->mask != 0; item++) {
5260
                        printf("%-10s %s\n", item->name, item->help);
5261
                    }
5262
                    exit(1);
5263
                    }
5264
                    cpu_set_log(mask);
5265
                }
5266
                break;
5267
#ifdef CONFIG_GDBSTUB
5268
            case QEMU_OPTION_s:
5269
                use_gdbstub = 1;
5270
                break;
5271
            case QEMU_OPTION_p:
5272
                gdbstub_port = atoi(optarg);
5273
                break;
5274
#endif
5275
            case QEMU_OPTION_L:
5276
                bios_dir = optarg;
5277
                break;
5278
            case QEMU_OPTION_S:
5279
                start_emulation = 0;
5280
                break;
5281
            case QEMU_OPTION_k:
5282
                keyboard_layout = optarg;
5283
                break;
5284
            case QEMU_OPTION_localtime:
5285
                rtc_utc = 0;
5286
                break;
5287
            case QEMU_OPTION_cirrusvga:
5288
                cirrus_vga_enabled = 1;
5289
                break;
5290
            case QEMU_OPTION_std_vga:
5291
                cirrus_vga_enabled = 0;
5292
                break;
5293
            case QEMU_OPTION_g:
5294
                {
5295
                    const char *p;
5296
                    int w, h, depth;
5297
                    p = optarg;
5298
                    w = strtol(p, (char **)&p, 10);
5299
                    if (w <= 0) {
5300
                    graphic_error:
5301
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5302
                        exit(1);
5303
                    }
5304
                    if (*p != 'x')
5305
                        goto graphic_error;
5306
                    p++;
5307
                    h = strtol(p, (char **)&p, 10);
5308
                    if (h <= 0)
5309
                        goto graphic_error;
5310
                    if (*p == 'x') {
5311
                        p++;
5312
                        depth = strtol(p, (char **)&p, 10);
5313
                        if (depth != 8 && depth != 15 && depth != 16 && 
5314
                            depth != 24 && depth != 32)
5315
                            goto graphic_error;
5316
                    } else if (*p == '\0') {
5317
                        depth = graphic_depth;
5318
                    } else {
5319
                        goto graphic_error;
5320
                    }
5321
                    
5322
                    graphic_width = w;
5323
                    graphic_height = h;
5324
                    graphic_depth = depth;
5325
                }
5326
                break;
5327
            case QEMU_OPTION_monitor:
5328
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5329
                break;
5330
            case QEMU_OPTION_serial:
5331
                if (serial_device_index >= MAX_SERIAL_PORTS) {
5332
                    fprintf(stderr, "qemu: too many serial ports\n");
5333
                    exit(1);
5334
                }
5335
                pstrcpy(serial_devices[serial_device_index], 
5336
                        sizeof(serial_devices[0]), optarg);
5337
                serial_device_index++;
5338
                break;
5339
            case QEMU_OPTION_parallel:
5340
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5341
                    fprintf(stderr, "qemu: too many parallel ports\n");
5342
                    exit(1);
5343
                }
5344
                pstrcpy(parallel_devices[parallel_device_index], 
5345
                        sizeof(parallel_devices[0]), optarg);
5346
                parallel_device_index++;
5347
                break;
5348
            case QEMU_OPTION_loadvm:
5349
                loadvm = optarg;
5350
                break;
5351
            case QEMU_OPTION_full_screen:
5352
                full_screen = 1;
5353
                break;
5354
            case QEMU_OPTION_pidfile:
5355
                create_pidfile(optarg);
5356
                break;
5357
#ifdef TARGET_I386
5358
            case QEMU_OPTION_win2k_hack:
5359
                win2k_install_hack = 1;
5360
                break;
5361
#endif
5362
#ifdef USE_KQEMU
5363
            case QEMU_OPTION_no_kqemu:
5364
                kqemu_allowed = 0;
5365
                break;
5366
            case QEMU_OPTION_kernel_kqemu:
5367
                kqemu_allowed = 2;
5368
                break;
5369
#endif
5370
            case QEMU_OPTION_usb:
5371
                usb_enabled = 1;
5372
                break;
5373
            case QEMU_OPTION_usbdevice:
5374
                usb_enabled = 1;
5375
                if (usb_devices_index >= MAX_VM_USB_PORTS) {
5376
                    fprintf(stderr, "Too many USB devices\n");
5377
                    exit(1);
5378
                }
5379
                pstrcpy(usb_devices[usb_devices_index],
5380
                        sizeof(usb_devices[usb_devices_index]),
5381
                        optarg);
5382
                usb_devices_index++;
5383
                break;
5384
            case QEMU_OPTION_smp:
5385
                smp_cpus = atoi(optarg);
5386
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5387
                    fprintf(stderr, "Invalid number of CPUs\n");
5388
                    exit(1);
5389
                }
5390
                break;
5391
            case QEMU_OPTION_vnc:
5392
                vnc_display = atoi(optarg);
5393
                if (vnc_display < 0) {
5394
                    fprintf(stderr, "Invalid VNC display\n");
5395
                    exit(1);
5396
                }
5397
                break;
5398
            }
5399
        }
5400
    }
5401

    
5402
#ifdef USE_KQEMU
5403
    if (smp_cpus > 1)
5404
        kqemu_allowed = 0;
5405
#endif
5406
    linux_boot = (kernel_filename != NULL);
5407
        
5408
    if (!linux_boot && 
5409
        hd_filename[0] == '\0' && 
5410
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5411
        fd_filename[0] == '\0')
5412
        help();
5413
    
5414
    /* boot to cd by default if no hard disk */
5415
    if (hd_filename[0] == '\0' && boot_device == 'c') {
5416
        if (fd_filename[0] != '\0')
5417
            boot_device = 'a';
5418
        else
5419
            boot_device = 'd';
5420
    }
5421

    
5422
#if !defined(CONFIG_SOFTMMU)
5423
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5424
    {
5425
        static uint8_t stdout_buf[4096];
5426
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5427
    }
5428
#else
5429
    setvbuf(stdout, NULL, _IOLBF, 0);
5430
#endif
5431
    
5432
#ifdef _WIN32
5433
    socket_init();
5434
#endif
5435

    
5436
    /* init network clients */
5437
    if (nb_net_clients == 0) {
5438
        /* if no clients, we use a default config */
5439
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
5440
                "nic");
5441
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
5442
                "user");
5443
        nb_net_clients = 2;
5444
    }
5445

    
5446
    for(i = 0;i < nb_net_clients; i++) {
5447
        if (net_client_init(net_clients[i]) < 0)
5448
            exit(1);
5449
    }
5450

    
5451
    /* init the memory */
5452
    phys_ram_size = ram_size + vga_ram_size + bios_size;
5453

    
5454
#ifdef CONFIG_SOFTMMU
5455
    phys_ram_base = qemu_vmalloc(phys_ram_size);
5456
    if (!phys_ram_base) {
5457
        fprintf(stderr, "Could not allocate physical memory\n");
5458
        exit(1);
5459
    }
5460
#else
5461
    /* as we must map the same page at several addresses, we must use
5462
       a fd */
5463
    {
5464
        const char *tmpdir;
5465

    
5466
        tmpdir = getenv("QEMU_TMPDIR");
5467
        if (!tmpdir)
5468
            tmpdir = "/tmp";
5469
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5470
        if (mkstemp(phys_ram_file) < 0) {
5471
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
5472
                    phys_ram_file);
5473
            exit(1);
5474
        }
5475
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5476
        if (phys_ram_fd < 0) {
5477
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
5478
                    phys_ram_file);
5479
            exit(1);
5480
        }
5481
        ftruncate(phys_ram_fd, phys_ram_size);
5482
        unlink(phys_ram_file);
5483
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
5484
                             phys_ram_size, 
5485
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
5486
                             phys_ram_fd, 0);
5487
        if (phys_ram_base == MAP_FAILED) {
5488
            fprintf(stderr, "Could not map physical memory\n");
5489
            exit(1);
5490
        }
5491
    }
5492
#endif
5493

    
5494
    /* we always create the cdrom drive, even if no disk is there */
5495
    bdrv_init();
5496
    if (cdrom_index >= 0) {
5497
        bs_table[cdrom_index] = bdrv_new("cdrom");
5498
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5499
    }
5500

    
5501
    /* open the virtual block devices */
5502
    for(i = 0; i < MAX_DISKS; i++) {
5503
        if (hd_filename[i]) {
5504
            if (!bs_table[i]) {
5505
                char buf[64];
5506
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5507
                bs_table[i] = bdrv_new(buf);
5508
            }
5509
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5510
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5511
                        hd_filename[i]);
5512
                exit(1);
5513
            }
5514
            if (i == 0 && cyls != 0) {
5515
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5516
                bdrv_set_translation_hint(bs_table[i], translation);
5517
            }
5518
        }
5519
    }
5520

    
5521
    /* we always create at least one floppy disk */
5522
    fd_table[0] = bdrv_new("fda");
5523
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5524

    
5525
    for(i = 0; i < MAX_FD; i++) {
5526
        if (fd_filename[i]) {
5527
            if (!fd_table[i]) {
5528
                char buf[64];
5529
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5530
                fd_table[i] = bdrv_new(buf);
5531
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5532
            }
5533
            if (fd_filename[i] != '\0') {
5534
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5535
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5536
                            fd_filename[i]);
5537
                    exit(1);
5538
                }
5539
            }
5540
        }
5541
    }
5542

    
5543
    /* init USB devices */
5544
    if (usb_enabled) {
5545
        vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5546
        for(i = 0; i < usb_devices_index; i++) {
5547
            if (usb_device_add(usb_devices[i]) < 0) {
5548
                fprintf(stderr, "Warning: could not add USB device %s\n",
5549
                        usb_devices[i]);
5550
            }
5551
        }
5552
    }
5553

    
5554
    register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5555
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5556

    
5557
    init_ioports();
5558
    cpu_calibrate_ticks();
5559

    
5560
    /* terminal init */
5561
    if (nographic) {
5562
        dumb_display_init(ds);
5563
    } else if (vnc_display != -1) {
5564
        vnc_display_init(ds, vnc_display);
5565
    } else {
5566
#if defined(CONFIG_SDL)
5567
        sdl_display_init(ds, full_screen);
5568
#elif defined(CONFIG_COCOA)
5569
        cocoa_display_init(ds, full_screen);
5570
#else
5571
        dumb_display_init(ds);
5572
#endif
5573
    }
5574

    
5575
    monitor_hd = qemu_chr_open(monitor_device);
5576
    if (!monitor_hd) {
5577
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5578
        exit(1);
5579
    }
5580
    monitor_init(monitor_hd, !nographic);
5581

    
5582
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5583
        if (serial_devices[i][0] != '\0') {
5584
            serial_hds[i] = qemu_chr_open(serial_devices[i]);
5585
            if (!serial_hds[i]) {
5586
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
5587
                        serial_devices[i]);
5588
                exit(1);
5589
            }
5590
            if (!strcmp(serial_devices[i], "vc"))
5591
                qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5592
        }
5593
    }
5594

    
5595
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5596
        if (parallel_devices[i][0] != '\0') {
5597
            parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5598
            if (!parallel_hds[i]) {
5599
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
5600
                        parallel_devices[i]);
5601
                exit(1);
5602
            }
5603
            if (!strcmp(parallel_devices[i], "vc"))
5604
                qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5605
        }
5606
    }
5607

    
5608
    /* setup cpu signal handlers for MMU / self modifying code handling */
5609
#if !defined(CONFIG_SOFTMMU)
5610
    
5611
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5612
    {
5613
        stack_t stk;
5614
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5615
        stk.ss_sp = signal_stack;
5616
        stk.ss_size = SIGNAL_STACK_SIZE;
5617
        stk.ss_flags = 0;
5618

    
5619
        if (sigaltstack(&stk, NULL) < 0) {
5620
            perror("sigaltstack");
5621
            exit(1);
5622
        }
5623
    }
5624
#endif
5625
    {
5626
        struct sigaction act;
5627
        
5628
        sigfillset(&act.sa_mask);
5629
        act.sa_flags = SA_SIGINFO;
5630
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5631
        act.sa_flags |= SA_ONSTACK;
5632
#endif
5633
        act.sa_sigaction = host_segv_handler;
5634
        sigaction(SIGSEGV, &act, NULL);
5635
        sigaction(SIGBUS, &act, NULL);
5636
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5637
        sigaction(SIGFPE, &act, NULL);
5638
#endif
5639
    }
5640
#endif
5641

    
5642
#ifndef _WIN32
5643
    {
5644
        struct sigaction act;
5645
        sigfillset(&act.sa_mask);
5646
        act.sa_flags = 0;
5647
        act.sa_handler = SIG_IGN;
5648
        sigaction(SIGPIPE, &act, NULL);
5649
    }
5650
#endif
5651
    init_timers();
5652

    
5653
    machine->init(ram_size, vga_ram_size, boot_device,
5654
                  ds, fd_filename, snapshot,
5655
                  kernel_filename, kernel_cmdline, initrd_filename);
5656

    
5657
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5658
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5659

    
5660
#ifdef CONFIG_GDBSTUB
5661
    if (use_gdbstub) {
5662
        if (gdbserver_start(gdbstub_port) < 0) {
5663
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
5664
                    gdbstub_port);
5665
            exit(1);
5666
        } else {
5667
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
5668
        }
5669
    } else 
5670
#endif
5671
    if (loadvm)
5672
        qemu_loadvm(loadvm);
5673

    
5674
    {
5675
        /* XXX: simplify init */
5676
        read_passwords();
5677
        if (start_emulation) {
5678
            vm_start();
5679
        }
5680
    }
5681
    main_loop();
5682
    quit_timers();
5683
    return 0;
5684
}