Statistics
| Branch: | Revision:

root / vl.c @ ba3c64fb

History | View | Annotate | Download (123.3 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
#include <linux/if.h>
51
#include <linux/if_tun.h>
52
#include <pty.h>
53
#include <malloc.h>
54
#include <linux/rtc.h>
55
#include <linux/ppdev.h>
56
#endif
57
#endif
58

    
59
#if defined(CONFIG_SLIRP)
60
#include "libslirp.h"
61
#endif
62

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

    
71
#ifdef CONFIG_SDL
72
#ifdef __APPLE__
73
#include <SDL/SDL.h>
74
#endif
75
#endif /* CONFIG_SDL */
76

    
77
#ifdef CONFIG_COCOA
78
#undef main
79
#define main qemu_main
80
#endif /* CONFIG_COCOA */
81

    
82
#include "disas.h"
83

    
84
#include "exec-all.h"
85

    
86
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
87

    
88
//#define DEBUG_UNUSED_IOPORT
89
//#define DEBUG_IOPORT
90

    
91
#if !defined(CONFIG_SOFTMMU)
92
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
93
#else
94
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
95
#endif
96

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

    
105
/* XXX: use a two level table to limit memory usage */
106
#define MAX_IOPORTS 65536
107

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
294
/***********************************************************/
295

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

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

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

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

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

    
339
/* return the size or -1 if error */
340
int get_image_size(const char *filename)
341
{
342
    int fd, size;
343
    fd = open(filename, O_RDONLY | O_BINARY);
344
    if (fd < 0)
345
        return -1;
346
    size = lseek(fd, 0, SEEK_END);
347
    close(fd);
348
    return size;
349
}
350

    
351
/* return the size or -1 if error */
352
int load_image(const char *filename, uint8_t *addr)
353
{
354
    int fd, size;
355
    fd = open(filename, O_RDONLY | O_BINARY);
356
    if (fd < 0)
357
        return -1;
358
    size = lseek(fd, 0, SEEK_END);
359
    lseek(fd, 0, SEEK_SET);
360
    if (read(fd, addr, size) != size) {
361
        close(fd);
362
        return -1;
363
    }
364
    close(fd);
365
    return size;
366
}
367

    
368
void cpu_outb(CPUState *env, int addr, int val)
369
{
370
#ifdef DEBUG_IOPORT
371
    if (loglevel & CPU_LOG_IOPORT)
372
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
373
#endif    
374
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
375
}
376

    
377
void cpu_outw(CPUState *env, int addr, int val)
378
{
379
#ifdef DEBUG_IOPORT
380
    if (loglevel & CPU_LOG_IOPORT)
381
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
382
#endif    
383
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
384
}
385

    
386
void cpu_outl(CPUState *env, int addr, int val)
387
{
388
#ifdef DEBUG_IOPORT
389
    if (loglevel & CPU_LOG_IOPORT)
390
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
391
#endif
392
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
393
}
394

    
395
int cpu_inb(CPUState *env, int addr)
396
{
397
    int val;
398
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
399
#ifdef DEBUG_IOPORT
400
    if (loglevel & CPU_LOG_IOPORT)
401
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
402
#endif
403
    return val;
404
}
405

    
406
int cpu_inw(CPUState *env, int addr)
407
{
408
    int val;
409
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
410
#ifdef DEBUG_IOPORT
411
    if (loglevel & CPU_LOG_IOPORT)
412
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
413
#endif
414
    return val;
415
}
416

    
417
int cpu_inl(CPUState *env, int addr)
418
{
419
    int val;
420
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
421
#ifdef DEBUG_IOPORT
422
    if (loglevel & CPU_LOG_IOPORT)
423
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
424
#endif
425
    return val;
426
}
427

    
428
/***********************************************************/
429
void hw_error(const char *fmt, ...)
430
{
431
    va_list ap;
432
    CPUState *env;
433

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

    
450
/***********************************************************/
451
/* keyboard/mouse */
452

    
453
static QEMUPutKBDEvent *qemu_put_kbd_event;
454
static void *qemu_put_kbd_event_opaque;
455
static QEMUPutMouseEvent *qemu_put_mouse_event;
456
static void *qemu_put_mouse_event_opaque;
457

    
458
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
459
{
460
    qemu_put_kbd_event_opaque = opaque;
461
    qemu_put_kbd_event = func;
462
}
463

    
464
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
465
{
466
    qemu_put_mouse_event_opaque = opaque;
467
    qemu_put_mouse_event = func;
468
}
469

    
470
void kbd_put_keycode(int keycode)
471
{
472
    if (qemu_put_kbd_event) {
473
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
474
    }
475
}
476

    
477
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
478
{
479
    if (qemu_put_mouse_event) {
480
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
481
                             dx, dy, dz, buttons_state);
482
    }
483
}
484

    
485
/***********************************************************/
486
/* timers */
487

    
488
#if defined(__powerpc__)
489

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

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

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

    
516
#elif defined(__i386__)
517

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

    
525
#elif defined(__x86_64__)
526

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

    
538
#elif defined(__ia64)
539

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

    
547
#elif defined(__s390__)
548

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

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

    
560
static int64_t cpu_ticks_offset;
561
static int cpu_ticks_enabled;
562

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

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

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

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

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

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

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

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

    
644
#define QEMU_TIMER_REALTIME 0
645
#define QEMU_TIMER_VIRTUAL  1
646

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

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

    
660
QEMUClock *rt_clock;
661
QEMUClock *vm_clock;
662

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

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

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

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

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

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

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

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

    
723
    qemu_del_timer(ts);
724

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

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

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

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

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

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

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

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

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

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

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

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

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

    
901
#ifndef _WIN32
902

    
903
#if defined(__linux__)
904

    
905
#define RTC_FREQ 1024
906

    
907
static int rtc_fd;
908

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

    
929
#else
930

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

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

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

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

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

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

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

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

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

    
1019
/***********************************************************/
1020
/* character device */
1021

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

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

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

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

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

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

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

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

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

    
1085
#ifndef _WIN32
1086

    
1087
typedef struct {
1088
    int fd_in, fd_out;
1089
    IOCanRWHandler *fd_can_read; 
1090
    IOReadHandler *fd_read;
1091
    void *fd_opaque;
1092
    int max_size;
1093
} FDCharDriver;
1094

    
1095
#define STDIO_MAX_CLIENTS 2
1096

    
1097
static int stdio_nb_clients;
1098
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1099

    
1100
static int unix_write(int fd, const uint8_t *buf, int len1)
1101
{
1102
    int ret, len;
1103

    
1104
    len = len1;
1105
    while (len > 0) {
1106
        ret = write(fd, buf, len);
1107
        if (ret < 0) {
1108
            if (errno != EINTR && errno != EAGAIN)
1109
                return -1;
1110
        } else if (ret == 0) {
1111
            break;
1112
        } else {
1113
            buf += ret;
1114
            len -= ret;
1115
        }
1116
    }
1117
    return len1 - len;
1118
}
1119

    
1120
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1121
{
1122
    FDCharDriver *s = chr->opaque;
1123
    return unix_write(s->fd_out, buf, len);
1124
}
1125

    
1126
static int fd_chr_read_poll(void *opaque)
1127
{
1128
    CharDriverState *chr = opaque;
1129
    FDCharDriver *s = chr->opaque;
1130

    
1131
    s->max_size = s->fd_can_read(s->fd_opaque);
1132
    return s->max_size;
1133
}
1134

    
1135
static void fd_chr_read(void *opaque)
1136
{
1137
    CharDriverState *chr = opaque;
1138
    FDCharDriver *s = chr->opaque;
1139
    int size, len;
1140
    uint8_t buf[1024];
1141
    
1142
    len = sizeof(buf);
1143
    if (len > s->max_size)
1144
        len = s->max_size;
1145
    if (len == 0)
1146
        return;
1147
    size = read(s->fd_in, buf, len);
1148
    if (size > 0) {
1149
        s->fd_read(s->fd_opaque, buf, size);
1150
    }
1151
}
1152

    
1153
static void fd_chr_add_read_handler(CharDriverState *chr, 
1154
                                    IOCanRWHandler *fd_can_read, 
1155
                                    IOReadHandler *fd_read, void *opaque)
1156
{
1157
    FDCharDriver *s = chr->opaque;
1158

    
1159
    if (s->fd_in >= 0) {
1160
        s->fd_can_read = fd_can_read;
1161
        s->fd_read = fd_read;
1162
        s->fd_opaque = opaque;
1163
        if (nographic && s->fd_in == 0) {
1164
        } else {
1165
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1166
                                 fd_chr_read, NULL, chr);
1167
        }
1168
    }
1169
}
1170

    
1171
/* open a character device to a unix fd */
1172
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1173
{
1174
    CharDriverState *chr;
1175
    FDCharDriver *s;
1176

    
1177
    chr = qemu_mallocz(sizeof(CharDriverState));
1178
    if (!chr)
1179
        return NULL;
1180
    s = qemu_mallocz(sizeof(FDCharDriver));
1181
    if (!s) {
1182
        free(chr);
1183
        return NULL;
1184
    }
1185
    s->fd_in = fd_in;
1186
    s->fd_out = fd_out;
1187
    chr->opaque = s;
1188
    chr->chr_write = fd_chr_write;
1189
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1190
    return chr;
1191
}
1192

    
1193
CharDriverState *qemu_chr_open_file_out(const char *file_out)
1194
{
1195
    int fd_out;
1196

    
1197
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1198
    if (fd_out < 0)
1199
        return NULL;
1200
    return qemu_chr_open_fd(-1, fd_out);
1201
}
1202

    
1203
CharDriverState *qemu_chr_open_pipe(const char *filename)
1204
{
1205
    int fd;
1206

    
1207
    fd = open(filename, O_RDWR | O_BINARY);
1208
    if (fd < 0)
1209
        return NULL;
1210
    return qemu_chr_open_fd(fd, fd);
1211
}
1212

    
1213

    
1214
/* for STDIO, we handle the case where several clients use it
1215
   (nographic mode) */
1216

    
1217
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1218

    
1219
#define TERM_FIFO_MAX_SIZE 1
1220

    
1221
static int term_got_escape, client_index;
1222
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1223
int term_fifo_size;
1224

    
1225
void term_print_help(void)
1226
{
1227
    printf("\n"
1228
           "C-a h    print this help\n"
1229
           "C-a x    exit emulator\n"
1230
           "C-a s    save disk data back to file (if -snapshot)\n"
1231
           "C-a b    send break (magic sysrq)\n"
1232
           "C-a c    switch between console and monitor\n"
1233
           "C-a C-a  send C-a\n"
1234
           );
1235
}
1236

    
1237
/* called when a char is received */
1238
static void stdio_received_byte(int ch)
1239
{
1240
    if (term_got_escape) {
1241
        term_got_escape = 0;
1242
        switch(ch) {
1243
        case 'h':
1244
            term_print_help();
1245
            break;
1246
        case 'x':
1247
            exit(0);
1248
            break;
1249
        case 's': 
1250
            {
1251
                int i;
1252
                for (i = 0; i < MAX_DISKS; i++) {
1253
                    if (bs_table[i])
1254
                        bdrv_commit(bs_table[i]);
1255
                }
1256
            }
1257
            break;
1258
        case 'b':
1259
            if (client_index < stdio_nb_clients) {
1260
                CharDriverState *chr;
1261
                FDCharDriver *s;
1262

    
1263
                chr = stdio_clients[client_index];
1264
                s = chr->opaque;
1265
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1266
            }
1267
            break;
1268
        case 'c':
1269
            client_index++;
1270
            if (client_index >= stdio_nb_clients)
1271
                client_index = 0;
1272
            if (client_index == 0) {
1273
                /* send a new line in the monitor to get the prompt */
1274
                ch = '\r';
1275
                goto send_char;
1276
            }
1277
            break;
1278
        case TERM_ESCAPE:
1279
            goto send_char;
1280
        }
1281
    } else if (ch == TERM_ESCAPE) {
1282
        term_got_escape = 1;
1283
    } else {
1284
    send_char:
1285
        if (client_index < stdio_nb_clients) {
1286
            uint8_t buf[1];
1287
            CharDriverState *chr;
1288
            FDCharDriver *s;
1289
            
1290
            chr = stdio_clients[client_index];
1291
            s = chr->opaque;
1292
            if (s->fd_can_read(s->fd_opaque) > 0) {
1293
                buf[0] = ch;
1294
                s->fd_read(s->fd_opaque, buf, 1);
1295
            } else if (term_fifo_size == 0) {
1296
                term_fifo[term_fifo_size++] = ch;
1297
            }
1298
        }
1299
    }
1300
}
1301

    
1302
static int stdio_read_poll(void *opaque)
1303
{
1304
    CharDriverState *chr;
1305
    FDCharDriver *s;
1306

    
1307
    if (client_index < stdio_nb_clients) {
1308
        chr = stdio_clients[client_index];
1309
        s = chr->opaque;
1310
        /* try to flush the queue if needed */
1311
        if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1312
            s->fd_read(s->fd_opaque, term_fifo, 1);
1313
            term_fifo_size = 0;
1314
        }
1315
        /* see if we can absorb more chars */
1316
        if (term_fifo_size == 0)
1317
            return 1;
1318
        else
1319
            return 0;
1320
    } else {
1321
        return 1;
1322
    }
1323
}
1324

    
1325
static void stdio_read(void *opaque)
1326
{
1327
    int size;
1328
    uint8_t buf[1];
1329
    
1330
    size = read(0, buf, 1);
1331
    if (size > 0)
1332
        stdio_received_byte(buf[0]);
1333
}
1334

    
1335
/* init terminal so that we can grab keys */
1336
static struct termios oldtty;
1337
static int old_fd0_flags;
1338

    
1339
static void term_exit(void)
1340
{
1341
    tcsetattr (0, TCSANOW, &oldtty);
1342
    fcntl(0, F_SETFL, old_fd0_flags);
1343
}
1344

    
1345
static void term_init(void)
1346
{
1347
    struct termios tty;
1348

    
1349
    tcgetattr (0, &tty);
1350
    oldtty = tty;
1351
    old_fd0_flags = fcntl(0, F_GETFL);
1352

    
1353
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1354
                          |INLCR|IGNCR|ICRNL|IXON);
1355
    tty.c_oflag |= OPOST;
1356
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1357
    /* if graphical mode, we allow Ctrl-C handling */
1358
    if (nographic)
1359
        tty.c_lflag &= ~ISIG;
1360
    tty.c_cflag &= ~(CSIZE|PARENB);
1361
    tty.c_cflag |= CS8;
1362
    tty.c_cc[VMIN] = 1;
1363
    tty.c_cc[VTIME] = 0;
1364
    
1365
    tcsetattr (0, TCSANOW, &tty);
1366

    
1367
    atexit(term_exit);
1368

    
1369
    fcntl(0, F_SETFL, O_NONBLOCK);
1370
}
1371

    
1372
CharDriverState *qemu_chr_open_stdio(void)
1373
{
1374
    CharDriverState *chr;
1375

    
1376
    if (nographic) {
1377
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1378
            return NULL;
1379
        chr = qemu_chr_open_fd(0, 1);
1380
        if (stdio_nb_clients == 0)
1381
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1382
        client_index = stdio_nb_clients;
1383
    } else {
1384
        if (stdio_nb_clients != 0)
1385
            return NULL;
1386
        chr = qemu_chr_open_fd(0, 1);
1387
    }
1388
    stdio_clients[stdio_nb_clients++] = chr;
1389
    if (stdio_nb_clients == 1) {
1390
        /* set the terminal in raw mode */
1391
        term_init();
1392
    }
1393
    return chr;
1394
}
1395

    
1396
#if defined(__linux__)
1397
CharDriverState *qemu_chr_open_pty(void)
1398
{
1399
    char slave_name[1024];
1400
    int master_fd, slave_fd;
1401
    
1402
    /* Not satisfying */
1403
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1404
        return NULL;
1405
    }
1406
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1407
    return qemu_chr_open_fd(master_fd, master_fd);
1408
}
1409

    
1410
static void tty_serial_init(int fd, int speed, 
1411
                            int parity, int data_bits, int stop_bits)
1412
{
1413
    struct termios tty;
1414
    speed_t spd;
1415

    
1416
#if 0
1417
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1418
           speed, parity, data_bits, stop_bits);
1419
#endif
1420
    tcgetattr (fd, &tty);
1421

    
1422
    switch(speed) {
1423
    case 50:
1424
        spd = B50;
1425
        break;
1426
    case 75:
1427
        spd = B75;
1428
        break;
1429
    case 300:
1430
        spd = B300;
1431
        break;
1432
    case 600:
1433
        spd = B600;
1434
        break;
1435
    case 1200:
1436
        spd = B1200;
1437
        break;
1438
    case 2400:
1439
        spd = B2400;
1440
        break;
1441
    case 4800:
1442
        spd = B4800;
1443
        break;
1444
    case 9600:
1445
        spd = B9600;
1446
        break;
1447
    case 19200:
1448
        spd = B19200;
1449
        break;
1450
    case 38400:
1451
        spd = B38400;
1452
        break;
1453
    case 57600:
1454
        spd = B57600;
1455
        break;
1456
    default:
1457
    case 115200:
1458
        spd = B115200;
1459
        break;
1460
    }
1461

    
1462
    cfsetispeed(&tty, spd);
1463
    cfsetospeed(&tty, spd);
1464

    
1465
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1466
                          |INLCR|IGNCR|ICRNL|IXON);
1467
    tty.c_oflag |= OPOST;
1468
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1469
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1470
    switch(data_bits) {
1471
    default:
1472
    case 8:
1473
        tty.c_cflag |= CS8;
1474
        break;
1475
    case 7:
1476
        tty.c_cflag |= CS7;
1477
        break;
1478
    case 6:
1479
        tty.c_cflag |= CS6;
1480
        break;
1481
    case 5:
1482
        tty.c_cflag |= CS5;
1483
        break;
1484
    }
1485
    switch(parity) {
1486
    default:
1487
    case 'N':
1488
        break;
1489
    case 'E':
1490
        tty.c_cflag |= PARENB;
1491
        break;
1492
    case 'O':
1493
        tty.c_cflag |= PARENB | PARODD;
1494
        break;
1495
    }
1496
    
1497
    tcsetattr (fd, TCSANOW, &tty);
1498
}
1499

    
1500
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1501
{
1502
    FDCharDriver *s = chr->opaque;
1503
    
1504
    switch(cmd) {
1505
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1506
        {
1507
            QEMUSerialSetParams *ssp = arg;
1508
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1509
                            ssp->data_bits, ssp->stop_bits);
1510
        }
1511
        break;
1512
    case CHR_IOCTL_SERIAL_SET_BREAK:
1513
        {
1514
            int enable = *(int *)arg;
1515
            if (enable)
1516
                tcsendbreak(s->fd_in, 1);
1517
        }
1518
        break;
1519
    default:
1520
        return -ENOTSUP;
1521
    }
1522
    return 0;
1523
}
1524

    
1525
CharDriverState *qemu_chr_open_tty(const char *filename)
1526
{
1527
    CharDriverState *chr;
1528
    int fd;
1529

    
1530
    fd = open(filename, O_RDWR | O_NONBLOCK);
1531
    if (fd < 0)
1532
        return NULL;
1533
    fcntl(fd, F_SETFL, O_NONBLOCK);
1534
    tty_serial_init(fd, 115200, 'N', 8, 1);
1535
    chr = qemu_chr_open_fd(fd, fd);
1536
    if (!chr)
1537
        return NULL;
1538
    chr->chr_ioctl = tty_serial_ioctl;
1539
    return chr;
1540
}
1541

    
1542
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1543
{
1544
    int fd = (int)chr->opaque;
1545
    uint8_t b;
1546

    
1547
    switch(cmd) {
1548
    case CHR_IOCTL_PP_READ_DATA:
1549
        if (ioctl(fd, PPRDATA, &b) < 0)
1550
            return -ENOTSUP;
1551
        *(uint8_t *)arg = b;
1552
        break;
1553
    case CHR_IOCTL_PP_WRITE_DATA:
1554
        b = *(uint8_t *)arg;
1555
        if (ioctl(fd, PPWDATA, &b) < 0)
1556
            return -ENOTSUP;
1557
        break;
1558
    case CHR_IOCTL_PP_READ_CONTROL:
1559
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1560
            return -ENOTSUP;
1561
        *(uint8_t *)arg = b;
1562
        break;
1563
    case CHR_IOCTL_PP_WRITE_CONTROL:
1564
        b = *(uint8_t *)arg;
1565
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1566
            return -ENOTSUP;
1567
        break;
1568
    case CHR_IOCTL_PP_READ_STATUS:
1569
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1570
            return -ENOTSUP;
1571
        *(uint8_t *)arg = b;
1572
        break;
1573
    default:
1574
        return -ENOTSUP;
1575
    }
1576
    return 0;
1577
}
1578

    
1579
CharDriverState *qemu_chr_open_pp(const char *filename)
1580
{
1581
    CharDriverState *chr;
1582
    int fd;
1583

    
1584
    fd = open(filename, O_RDWR);
1585
    if (fd < 0)
1586
        return NULL;
1587

    
1588
    if (ioctl(fd, PPCLAIM) < 0) {
1589
        close(fd);
1590
        return NULL;
1591
    }
1592

    
1593
    chr = qemu_mallocz(sizeof(CharDriverState));
1594
    if (!chr) {
1595
        close(fd);
1596
        return NULL;
1597
    }
1598
    chr->opaque = (void *)fd;
1599
    chr->chr_write = null_chr_write;
1600
    chr->chr_add_read_handler = null_chr_add_read_handler;
1601
    chr->chr_ioctl = pp_ioctl;
1602
    return chr;
1603
}
1604

    
1605
#else
1606
CharDriverState *qemu_chr_open_pty(void)
1607
{
1608
    return NULL;
1609
}
1610
#endif
1611

    
1612
#endif /* !defined(_WIN32) */
1613

    
1614
CharDriverState *qemu_chr_open(const char *filename)
1615
{
1616
    const char *p;
1617
    if (!strcmp(filename, "vc")) {
1618
        return text_console_init(&display_state);
1619
    } else if (!strcmp(filename, "null")) {
1620
        return qemu_chr_open_null();
1621
    } else 
1622
#ifndef _WIN32
1623
    if (strstart(filename, "file:", &p)) {
1624
        return qemu_chr_open_file_out(p);
1625
    } else if (strstart(filename, "pipe:", &p)) {
1626
        return qemu_chr_open_pipe(p);
1627
    } else if (!strcmp(filename, "pty")) {
1628
        return qemu_chr_open_pty();
1629
    } else if (!strcmp(filename, "stdio")) {
1630
        return qemu_chr_open_stdio();
1631
    } else 
1632
#endif
1633
#if defined(__linux__)
1634
    if (strstart(filename, "/dev/parport", NULL)) {
1635
        return qemu_chr_open_pp(filename);
1636
    } else 
1637
    if (strstart(filename, "/dev/", NULL)) {
1638
        return qemu_chr_open_tty(filename);
1639
    } else 
1640
#endif
1641
    {
1642
        return NULL;
1643
    }
1644
}
1645

    
1646
/***********************************************************/
1647
/* network device redirectors */
1648

    
1649
void hex_dump(FILE *f, const uint8_t *buf, int size)
1650
{
1651
    int len, i, j, c;
1652

    
1653
    for(i=0;i<size;i+=16) {
1654
        len = size - i;
1655
        if (len > 16)
1656
            len = 16;
1657
        fprintf(f, "%08x ", i);
1658
        for(j=0;j<16;j++) {
1659
            if (j < len)
1660
                fprintf(f, " %02x", buf[i+j]);
1661
            else
1662
                fprintf(f, "   ");
1663
        }
1664
        fprintf(f, " ");
1665
        for(j=0;j<len;j++) {
1666
            c = buf[i+j];
1667
            if (c < ' ' || c > '~')
1668
                c = '.';
1669
            fprintf(f, "%c", c);
1670
        }
1671
        fprintf(f, "\n");
1672
    }
1673
}
1674

    
1675
static int parse_macaddr(uint8_t *macaddr, const char *p)
1676
{
1677
    int i;
1678
    for(i = 0; i < 6; i++) {
1679
        macaddr[i] = strtol(p, (char **)&p, 16);
1680
        if (i == 5) {
1681
            if (*p != '\0') 
1682
                return -1;
1683
        } else {
1684
            if (*p != ':') 
1685
                return -1;
1686
            p++;
1687
        }
1688
    }
1689
    return 0;
1690
}
1691

    
1692
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1693
{
1694
    const char *p, *p1;
1695
    int len;
1696
    p = *pp;
1697
    p1 = strchr(p, sep);
1698
    if (!p1)
1699
        return -1;
1700
    len = p1 - p;
1701
    p1++;
1702
    if (buf_size > 0) {
1703
        if (len > buf_size - 1)
1704
            len = buf_size - 1;
1705
        memcpy(buf, p, len);
1706
        buf[len] = '\0';
1707
    }
1708
    *pp = p1;
1709
    return 0;
1710
}
1711

    
1712
int parse_host_port(struct sockaddr_in *saddr, const char *str)
1713
{
1714
    char buf[512];
1715
    struct hostent *he;
1716
    const char *p, *r;
1717
    int port;
1718

    
1719
    p = str;
1720
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1721
        return -1;
1722
    saddr->sin_family = AF_INET;
1723
    if (buf[0] == '\0') {
1724
        saddr->sin_addr.s_addr = 0;
1725
    } else {
1726
        if (isdigit(buf[0])) {
1727
            if (!inet_aton(buf, &saddr->sin_addr))
1728
                return -1;
1729
        } else {
1730
#ifdef _WIN32
1731
            return -1;
1732
#else
1733
            if ((he = gethostbyname(buf)) == NULL)
1734
                return - 1;
1735
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
1736
#endif
1737
        }
1738
    }
1739
    port = strtol(p, (char **)&r, 0);
1740
    if (r == p)
1741
        return -1;
1742
    saddr->sin_port = htons(port);
1743
    return 0;
1744
}
1745

    
1746
/* find or alloc a new VLAN */
1747
VLANState *qemu_find_vlan(int id)
1748
{
1749
    VLANState **pvlan, *vlan;
1750
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1751
        if (vlan->id == id)
1752
            return vlan;
1753
    }
1754
    vlan = qemu_mallocz(sizeof(VLANState));
1755
    if (!vlan)
1756
        return NULL;
1757
    vlan->id = id;
1758
    vlan->next = NULL;
1759
    pvlan = &first_vlan;
1760
    while (*pvlan != NULL)
1761
        pvlan = &(*pvlan)->next;
1762
    *pvlan = vlan;
1763
    return vlan;
1764
}
1765

    
1766
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1767
                                      IOReadHandler *fd_read, void *opaque)
1768
{
1769
    VLANClientState *vc, **pvc;
1770
    vc = qemu_mallocz(sizeof(VLANClientState));
1771
    if (!vc)
1772
        return NULL;
1773
    vc->fd_read = fd_read;
1774
    vc->opaque = opaque;
1775
    vc->vlan = vlan;
1776

    
1777
    vc->next = NULL;
1778
    pvc = &vlan->first_client;
1779
    while (*pvc != NULL)
1780
        pvc = &(*pvc)->next;
1781
    *pvc = vc;
1782
    return vc;
1783
}
1784

    
1785
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1786
{
1787
    VLANState *vlan = vc1->vlan;
1788
    VLANClientState *vc;
1789

    
1790
#if 0
1791
    printf("vlan %d send:\n", vlan->id);
1792
    hex_dump(stdout, buf, size);
1793
#endif
1794
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1795
        if (vc != vc1) {
1796
            vc->fd_read(vc->opaque, buf, size);
1797
        }
1798
    }
1799
}
1800

    
1801
#if defined(CONFIG_SLIRP)
1802

    
1803
/* slirp network adapter */
1804

    
1805
static int slirp_inited;
1806
static VLANClientState *slirp_vc;
1807

    
1808
int slirp_can_output(void)
1809
{
1810
    return 1;
1811
}
1812

    
1813
void slirp_output(const uint8_t *pkt, int pkt_len)
1814
{
1815
#if 0
1816
    printf("slirp output:\n");
1817
    hex_dump(stdout, pkt, pkt_len);
1818
#endif
1819
    qemu_send_packet(slirp_vc, pkt, pkt_len);
1820
}
1821

    
1822
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1823
{
1824
#if 0
1825
    printf("slirp input:\n");
1826
    hex_dump(stdout, buf, size);
1827
#endif
1828
    slirp_input(buf, size);
1829
}
1830

    
1831
static int net_slirp_init(VLANState *vlan)
1832
{
1833
    if (!slirp_inited) {
1834
        slirp_inited = 1;
1835
        slirp_init();
1836
    }
1837
    slirp_vc = qemu_new_vlan_client(vlan, 
1838
                                    slirp_receive, NULL);
1839
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1840
    return 0;
1841
}
1842

    
1843
static void net_slirp_redir(const char *redir_str)
1844
{
1845
    int is_udp;
1846
    char buf[256], *r;
1847
    const char *p;
1848
    struct in_addr guest_addr;
1849
    int host_port, guest_port;
1850
    
1851
    if (!slirp_inited) {
1852
        slirp_inited = 1;
1853
        slirp_init();
1854
    }
1855

    
1856
    p = redir_str;
1857
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1858
        goto fail;
1859
    if (!strcmp(buf, "tcp")) {
1860
        is_udp = 0;
1861
    } else if (!strcmp(buf, "udp")) {
1862
        is_udp = 1;
1863
    } else {
1864
        goto fail;
1865
    }
1866

    
1867
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1868
        goto fail;
1869
    host_port = strtol(buf, &r, 0);
1870
    if (r == buf)
1871
        goto fail;
1872

    
1873
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1874
        goto fail;
1875
    if (buf[0] == '\0') {
1876
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
1877
    }
1878
    if (!inet_aton(buf, &guest_addr))
1879
        goto fail;
1880
    
1881
    guest_port = strtol(p, &r, 0);
1882
    if (r == p)
1883
        goto fail;
1884
    
1885
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1886
        fprintf(stderr, "qemu: could not set up redirection\n");
1887
        exit(1);
1888
    }
1889
    return;
1890
 fail:
1891
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1892
    exit(1);
1893
}
1894
    
1895
#ifndef _WIN32
1896

    
1897
char smb_dir[1024];
1898

    
1899
static void smb_exit(void)
1900
{
1901
    DIR *d;
1902
    struct dirent *de;
1903
    char filename[1024];
1904

    
1905
    /* erase all the files in the directory */
1906
    d = opendir(smb_dir);
1907
    for(;;) {
1908
        de = readdir(d);
1909
        if (!de)
1910
            break;
1911
        if (strcmp(de->d_name, ".") != 0 &&
1912
            strcmp(de->d_name, "..") != 0) {
1913
            snprintf(filename, sizeof(filename), "%s/%s", 
1914
                     smb_dir, de->d_name);
1915
            unlink(filename);
1916
        }
1917
    }
1918
    closedir(d);
1919
    rmdir(smb_dir);
1920
}
1921

    
1922
/* automatic user mode samba server configuration */
1923
void net_slirp_smb(const char *exported_dir)
1924
{
1925
    char smb_conf[1024];
1926
    char smb_cmdline[1024];
1927
    FILE *f;
1928

    
1929
    if (!slirp_inited) {
1930
        slirp_inited = 1;
1931
        slirp_init();
1932
    }
1933

    
1934
    /* XXX: better tmp dir construction */
1935
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1936
    if (mkdir(smb_dir, 0700) < 0) {
1937
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1938
        exit(1);
1939
    }
1940
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1941
    
1942
    f = fopen(smb_conf, "w");
1943
    if (!f) {
1944
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1945
        exit(1);
1946
    }
1947
    fprintf(f, 
1948
            "[global]\n"
1949
            "private dir=%s\n"
1950
            "smb ports=0\n"
1951
            "socket address=127.0.0.1\n"
1952
            "pid directory=%s\n"
1953
            "lock directory=%s\n"
1954
            "log file=%s/log.smbd\n"
1955
            "smb passwd file=%s/smbpasswd\n"
1956
            "security = share\n"
1957
            "[qemu]\n"
1958
            "path=%s\n"
1959
            "read only=no\n"
1960
            "guest ok=yes\n",
1961
            smb_dir,
1962
            smb_dir,
1963
            smb_dir,
1964
            smb_dir,
1965
            smb_dir,
1966
            exported_dir
1967
            );
1968
    fclose(f);
1969
    atexit(smb_exit);
1970

    
1971
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1972
             smb_conf);
1973
    
1974
    slirp_add_exec(0, smb_cmdline, 4, 139);
1975
}
1976

    
1977
#endif /* !defined(_WIN32) */
1978

    
1979
#endif /* CONFIG_SLIRP */
1980

    
1981
#if !defined(_WIN32)
1982

    
1983
typedef struct TAPState {
1984
    VLANClientState *vc;
1985
    int fd;
1986
} TAPState;
1987

    
1988
static void tap_receive(void *opaque, const uint8_t *buf, int size)
1989
{
1990
    TAPState *s = opaque;
1991
    int ret;
1992
    for(;;) {
1993
        ret = write(s->fd, buf, size);
1994
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
1995
        } else {
1996
            break;
1997
        }
1998
    }
1999
}
2000

    
2001
static void tap_send(void *opaque)
2002
{
2003
    TAPState *s = opaque;
2004
    uint8_t buf[4096];
2005
    int size;
2006

    
2007
    size = read(s->fd, buf, sizeof(buf));
2008
    if (size > 0) {
2009
        qemu_send_packet(s->vc, buf, size);
2010
    }
2011
}
2012

    
2013
/* fd support */
2014

    
2015
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2016
{
2017
    TAPState *s;
2018

    
2019
    s = qemu_mallocz(sizeof(TAPState));
2020
    if (!s)
2021
        return NULL;
2022
    s->fd = fd;
2023
    s->vc = qemu_new_vlan_client(vlan, tap_receive, s);
2024
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2025
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2026
    return s;
2027
}
2028

    
2029
#ifdef _BSD
2030
static int tap_open(char *ifname, int ifname_size)
2031
{
2032
    int fd;
2033
    char *dev;
2034
    struct stat s;
2035

    
2036
    fd = open("/dev/tap", O_RDWR);
2037
    if (fd < 0) {
2038
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2039
        return -1;
2040
    }
2041

    
2042
    fstat(fd, &s);
2043
    dev = devname(s.st_rdev, S_IFCHR);
2044
    pstrcpy(ifname, ifname_size, dev);
2045

    
2046
    fcntl(fd, F_SETFL, O_NONBLOCK);
2047
    return fd;
2048
}
2049
#else
2050
static int tap_open(char *ifname, int ifname_size)
2051
{
2052
    struct ifreq ifr;
2053
    int fd, ret;
2054
    
2055
    fd = open("/dev/net/tun", O_RDWR);
2056
    if (fd < 0) {
2057
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2058
        return -1;
2059
    }
2060
    memset(&ifr, 0, sizeof(ifr));
2061
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2062
    if (ifname[0] != '\0')
2063
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2064
    else
2065
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2066
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2067
    if (ret != 0) {
2068
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2069
        close(fd);
2070
        return -1;
2071
    }
2072
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
2073
    fcntl(fd, F_SETFL, O_NONBLOCK);
2074
    return fd;
2075
}
2076
#endif
2077

    
2078
static int net_tap_init(VLANState *vlan, const char *ifname1,
2079
                        const char *setup_script)
2080
{
2081
    TAPState *s;
2082
    int pid, status, fd;
2083
    char *args[3];
2084
    char **parg;
2085
    char ifname[128];
2086

    
2087
    if (ifname1 != NULL)
2088
        pstrcpy(ifname, sizeof(ifname), ifname1);
2089
    else
2090
        ifname[0] = '\0';
2091
    fd = tap_open(ifname, sizeof(ifname));
2092
    if (fd < 0)
2093
        return -1;
2094

    
2095
    if (!setup_script)
2096
        setup_script = "";
2097
    if (setup_script[0] != '\0') {
2098
        /* try to launch network init script */
2099
        pid = fork();
2100
        if (pid >= 0) {
2101
            if (pid == 0) {
2102
                parg = args;
2103
                *parg++ = (char *)setup_script;
2104
                *parg++ = ifname;
2105
                *parg++ = NULL;
2106
                execv(setup_script, args);
2107
                _exit(1);
2108
            }
2109
            while (waitpid(pid, &status, 0) != pid);
2110
            if (!WIFEXITED(status) ||
2111
                WEXITSTATUS(status) != 0) {
2112
                fprintf(stderr, "%s: could not launch network script\n",
2113
                        setup_script);
2114
                return -1;
2115
            }
2116
        }
2117
    }
2118
    s = net_tap_fd_init(vlan, fd);
2119
    if (!s)
2120
        return -1;
2121
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
2122
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
2123
    return 0;
2124
}
2125

    
2126
/* network connection */
2127
typedef struct NetSocketState {
2128
    VLANClientState *vc;
2129
    int fd;
2130
    int state; /* 0 = getting length, 1 = getting data */
2131
    int index;
2132
    int packet_len;
2133
    uint8_t buf[4096];
2134
} NetSocketState;
2135

    
2136
typedef struct NetSocketListenState {
2137
    VLANState *vlan;
2138
    int fd;
2139
} NetSocketListenState;
2140

    
2141
/* XXX: we consider we can send the whole packet without blocking */
2142
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2143
{
2144
    NetSocketState *s = opaque;
2145
    uint32_t len;
2146
    len = htonl(size);
2147

    
2148
    unix_write(s->fd, (const uint8_t *)&len, sizeof(len));
2149
    unix_write(s->fd, buf, size);
2150
}
2151

    
2152
static void net_socket_send(void *opaque)
2153
{
2154
    NetSocketState *s = opaque;
2155
    int l, size;
2156
    uint8_t buf1[4096];
2157
    const uint8_t *buf;
2158

    
2159
    size = read(s->fd, buf1, sizeof(buf1));
2160
    if (size < 0) 
2161
        return;
2162
    if (size == 0) {
2163
        /* end of connection */
2164
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2165
        return;
2166
    }
2167
    buf = buf1;
2168
    while (size > 0) {
2169
        /* reassemble a packet from the network */
2170
        switch(s->state) {
2171
        case 0:
2172
            l = 4 - s->index;
2173
            if (l > size)
2174
                l = size;
2175
            memcpy(s->buf + s->index, buf, l);
2176
            buf += l;
2177
            size -= l;
2178
            s->index += l;
2179
            if (s->index == 4) {
2180
                /* got length */
2181
                s->packet_len = ntohl(*(uint32_t *)s->buf);
2182
                s->index = 0;
2183
                s->state = 1;
2184
            }
2185
            break;
2186
        case 1:
2187
            l = s->packet_len - s->index;
2188
            if (l > size)
2189
                l = size;
2190
            memcpy(s->buf + s->index, buf, l);
2191
            s->index += l;
2192
            buf += l;
2193
            size -= l;
2194
            if (s->index >= s->packet_len) {
2195
                qemu_send_packet(s->vc, s->buf, s->packet_len);
2196
                s->index = 0;
2197
                s->state = 0;
2198
            }
2199
            break;
2200
        }
2201
    }
2202
}
2203

    
2204
static void net_socket_connect(void *opaque)
2205
{
2206
    NetSocketState *s = opaque;
2207
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2208
}
2209

    
2210
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
2211
                                          int is_connected)
2212
{
2213
    NetSocketState *s;
2214
    s = qemu_mallocz(sizeof(NetSocketState));
2215
    if (!s)
2216
        return NULL;
2217
    s->fd = fd;
2218
    s->vc = qemu_new_vlan_client(vlan, 
2219
                                 net_socket_receive, s);
2220
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2221
             "socket: fd=%d", fd);
2222
    if (is_connected) {
2223
        net_socket_connect(s);
2224
    } else {
2225
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2226
    }
2227
    return s;
2228
}
2229

    
2230
static void net_socket_accept(void *opaque)
2231
{
2232
    NetSocketListenState *s = opaque;    
2233
    NetSocketState *s1;
2234
    struct sockaddr_in saddr;
2235
    socklen_t len;
2236
    int fd;
2237

    
2238
    for(;;) {
2239
        len = sizeof(saddr);
2240
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2241
        if (fd < 0 && errno != EINTR) {
2242
            return;
2243
        } else if (fd >= 0) {
2244
            break;
2245
        }
2246
    }
2247
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
2248
    if (!s1) {
2249
        close(fd);
2250
    } else {
2251
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2252
                 "socket: connection from %s:%d", 
2253
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2254
    }
2255
}
2256

    
2257
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2258
{
2259
    NetSocketListenState *s;
2260
    int fd, val, ret;
2261
    struct sockaddr_in saddr;
2262

    
2263
    if (parse_host_port(&saddr, host_str) < 0)
2264
        return -1;
2265
    
2266
    s = qemu_mallocz(sizeof(NetSocketListenState));
2267
    if (!s)
2268
        return -1;
2269

    
2270
    fd = socket(PF_INET, SOCK_STREAM, 0);
2271
    if (fd < 0) {
2272
        perror("socket");
2273
        return -1;
2274
    }
2275
    fcntl(fd, F_SETFL, O_NONBLOCK);
2276

    
2277
    /* allow fast reuse */
2278
    val = 1;
2279
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2280
    
2281
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2282
    if (ret < 0) {
2283
        perror("bind");
2284
        return -1;
2285
    }
2286
    ret = listen(fd, 0);
2287
    if (ret < 0) {
2288
        perror("listen");
2289
        return -1;
2290
    }
2291
    s->vlan = vlan;
2292
    s->fd = fd;
2293
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2294
    return 0;
2295
}
2296

    
2297
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2298
{
2299
    NetSocketState *s;
2300
    int fd, connected, ret;
2301
    struct sockaddr_in saddr;
2302

    
2303
    if (parse_host_port(&saddr, host_str) < 0)
2304
        return -1;
2305

    
2306
    fd = socket(PF_INET, SOCK_STREAM, 0);
2307
    if (fd < 0) {
2308
        perror("socket");
2309
        return -1;
2310
    }
2311
    fcntl(fd, F_SETFL, O_NONBLOCK);
2312

    
2313
    connected = 0;
2314
    for(;;) {
2315
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2316
        if (ret < 0) {
2317
            if (errno == EINTR || errno == EAGAIN) {
2318
            } else if (errno == EINPROGRESS) {
2319
                break;
2320
            } else {
2321
                perror("connect");
2322
                close(fd);
2323
                return -1;
2324
            }
2325
        } else {
2326
            connected = 1;
2327
            break;
2328
        }
2329
    }
2330
    s = net_socket_fd_init(vlan, fd, connected);
2331
    if (!s)
2332
        return -1;
2333
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2334
             "socket: connect to %s:%d", 
2335
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2336
    return 0;
2337
}
2338

    
2339
#endif /* !_WIN32 */
2340

    
2341
static int get_param_value(char *buf, int buf_size,
2342
                           const char *tag, const char *str)
2343
{
2344
    const char *p;
2345
    char *q;
2346
    char option[128];
2347

    
2348
    p = str;
2349
    for(;;) {
2350
        q = option;
2351
        while (*p != '\0' && *p != '=') {
2352
            if ((q - option) < sizeof(option) - 1)
2353
                *q++ = *p;
2354
            p++;
2355
        }
2356
        *q = '\0';
2357
        if (*p != '=')
2358
            break;
2359
        p++;
2360
        if (!strcmp(tag, option)) {
2361
            q = buf;
2362
            while (*p != '\0' && *p != ',') {
2363
                if ((q - buf) < buf_size - 1)
2364
                    *q++ = *p;
2365
                p++;
2366
            }
2367
            *q = '\0';
2368
            return q - buf;
2369
        } else {
2370
            while (*p != '\0' && *p != ',') {
2371
                p++;
2372
            }
2373
        }
2374
        if (*p != ',')
2375
            break;
2376
        p++;
2377
    }
2378
    return 0;
2379
}
2380

    
2381
int net_client_init(const char *str)
2382
{
2383
    const char *p;
2384
    char *q;
2385
    char device[64];
2386
    char buf[1024];
2387
    int vlan_id, ret;
2388
    VLANState *vlan;
2389

    
2390
    p = str;
2391
    q = device;
2392
    while (*p != '\0' && *p != ',') {
2393
        if ((q - device) < sizeof(device) - 1)
2394
            *q++ = *p;
2395
        p++;
2396
    }
2397
    *q = '\0';
2398
    if (*p == ',')
2399
        p++;
2400
    vlan_id = 0;
2401
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2402
        vlan_id = strtol(buf, NULL, 0);
2403
    }
2404
    vlan = qemu_find_vlan(vlan_id);
2405
    if (!vlan) {
2406
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2407
        return -1;
2408
    }
2409
    if (!strcmp(device, "nic")) {
2410
        NICInfo *nd;
2411
        uint8_t *macaddr;
2412

    
2413
        if (nb_nics >= MAX_NICS) {
2414
            fprintf(stderr, "Too Many NICs\n");
2415
            return -1;
2416
        }
2417
        nd = &nd_table[nb_nics];
2418
        macaddr = nd->macaddr;
2419
        macaddr[0] = 0x52;
2420
        macaddr[1] = 0x54;
2421
        macaddr[2] = 0x00;
2422
        macaddr[3] = 0x12;
2423
        macaddr[4] = 0x34;
2424
        macaddr[5] = 0x56 + nb_nics;
2425

    
2426
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2427
            if (parse_macaddr(macaddr, buf) < 0) {
2428
                fprintf(stderr, "invalid syntax for ethernet address\n");
2429
                return -1;
2430
            }
2431
        }
2432
        nd->vlan = vlan;
2433
        nb_nics++;
2434
        ret = 0;
2435
    } else
2436
    if (!strcmp(device, "none")) {
2437
        /* does nothing. It is needed to signal that no network cards
2438
           are wanted */
2439
        ret = 0;
2440
    } else
2441
#ifdef CONFIG_SLIRP
2442
    if (!strcmp(device, "user")) {
2443
        ret = net_slirp_init(vlan);
2444
    } else
2445
#endif
2446
#ifndef _WIN32
2447
    if (!strcmp(device, "tap")) {
2448
        char ifname[64];
2449
        char setup_script[1024];
2450
        int fd;
2451
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2452
            fd = strtol(buf, NULL, 0);
2453
            ret = -1;
2454
            if (net_tap_fd_init(vlan, fd))
2455
                ret = 0;
2456
        } else {
2457
            get_param_value(ifname, sizeof(ifname), "ifname", p);
2458
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2459
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2460
            }
2461
            ret = net_tap_init(vlan, ifname, setup_script);
2462
        }
2463
    } else
2464
    if (!strcmp(device, "socket")) {
2465
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2466
            int fd;
2467
            fd = strtol(buf, NULL, 0);
2468
            ret = -1;
2469
            if (net_socket_fd_init(vlan, fd, 1))
2470
                ret = 0;
2471
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2472
            ret = net_socket_listen_init(vlan, buf);
2473
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2474
            ret = net_socket_connect_init(vlan, buf);
2475
        } else {
2476
            fprintf(stderr, "Unknown socket options: %s\n", p);
2477
            return -1;
2478
        }
2479
    } else
2480
#endif
2481
    {
2482
        fprintf(stderr, "Unknown network device: %s\n", device);
2483
        return -1;
2484
    }
2485
    if (ret < 0) {
2486
        fprintf(stderr, "Could not initialize device '%s'\n", device);
2487
    }
2488
    
2489
    return ret;
2490
}
2491

    
2492
void do_info_network(void)
2493
{
2494
    VLANState *vlan;
2495
    VLANClientState *vc;
2496

    
2497
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2498
        term_printf("VLAN %d devices:\n", vlan->id);
2499
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2500
            term_printf("  %s\n", vc->info_str);
2501
    }
2502
}
2503
 
2504
/***********************************************************/
2505
/* USB devices */
2506

    
2507
static int usb_device_add(const char *devname)
2508
{
2509
    const char *p;
2510
    USBDevice *dev;
2511
    int i;
2512

    
2513
    if (!vm_usb_hub)
2514
        return -1;
2515
    for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2516
        if (!vm_usb_ports[i]->dev)
2517
            break;
2518
    }
2519
    if (i == MAX_VM_USB_PORTS)
2520
        return -1;
2521

    
2522
    if (strstart(devname, "host:", &p)) {
2523
        dev = usb_host_device_open(p);
2524
        if (!dev)
2525
            return -1;
2526
    } else if (!strcmp(devname, "mouse")) {
2527
        dev = usb_mouse_init();
2528
        if (!dev)
2529
            return -1;
2530
    } else {
2531
        return -1;
2532
    }
2533
    usb_attach(vm_usb_ports[i], dev);
2534
    return 0;
2535
}
2536

    
2537
static int usb_device_del(const char *devname)
2538
{
2539
    USBDevice *dev;
2540
    int bus_num, addr, i;
2541
    const char *p;
2542

    
2543
    if (!vm_usb_hub)
2544
        return -1;
2545

    
2546
    p = strchr(devname, '.');
2547
    if (!p) 
2548
        return -1;
2549
    bus_num = strtoul(devname, NULL, 0);
2550
    addr = strtoul(p + 1, NULL, 0);
2551
    if (bus_num != 0)
2552
        return -1;
2553
    for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2554
        dev = vm_usb_ports[i]->dev;
2555
        if (dev && dev->addr == addr)
2556
            break;
2557
    }
2558
    if (i == MAX_VM_USB_PORTS)
2559
        return -1;
2560
    usb_attach(vm_usb_ports[i], NULL);
2561
    return 0;
2562
}
2563

    
2564
void do_usb_add(const char *devname)
2565
{
2566
    int ret;
2567
    ret = usb_device_add(devname);
2568
    if (ret < 0) 
2569
        term_printf("Could not add USB device '%s'\n", devname);
2570
}
2571

    
2572
void do_usb_del(const char *devname)
2573
{
2574
    int ret;
2575
    ret = usb_device_del(devname);
2576
    if (ret < 0) 
2577
        term_printf("Could not remove USB device '%s'\n", devname);
2578
}
2579

    
2580
void usb_info(void)
2581
{
2582
    USBDevice *dev;
2583
    int i;
2584
    const char *speed_str;
2585

    
2586
    if (!vm_usb_hub) {
2587
        term_printf("USB support not enabled\n");
2588
        return;
2589
    }
2590

    
2591
    for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2592
        dev = vm_usb_ports[i]->dev;
2593
        if (dev) {
2594
            term_printf("Hub port %d:\n", i);
2595
            switch(dev->speed) {
2596
            case USB_SPEED_LOW: 
2597
                speed_str = "1.5"; 
2598
                break;
2599
            case USB_SPEED_FULL: 
2600
                speed_str = "12"; 
2601
                break;
2602
            case USB_SPEED_HIGH: 
2603
                speed_str = "480"; 
2604
                break;
2605
            default:
2606
                speed_str = "?"; 
2607
                break;
2608
            }
2609
            term_printf("  Device %d.%d, speed %s Mb/s\n", 
2610
                        0, dev->addr, speed_str);
2611
        }
2612
    }
2613
}
2614

    
2615
/***********************************************************/
2616
/* pid file */
2617

    
2618
static char *pid_filename;
2619

    
2620
/* Remove PID file. Called on normal exit */
2621

    
2622
static void remove_pidfile(void) 
2623
{
2624
    unlink (pid_filename);
2625
}
2626

    
2627
static void create_pidfile(const char *filename)
2628
{
2629
    struct stat pidstat;
2630
    FILE *f;
2631

    
2632
    /* Try to write our PID to the named file */
2633
    if (stat(filename, &pidstat) < 0) {
2634
        if (errno == ENOENT) {
2635
            if ((f = fopen (filename, "w")) == NULL) {
2636
                perror("Opening pidfile");
2637
                exit(1);
2638
            }
2639
            fprintf(f, "%d\n", getpid());
2640
            fclose(f);
2641
            pid_filename = qemu_strdup(filename);
2642
            if (!pid_filename) {
2643
                fprintf(stderr, "Could not save PID filename");
2644
                exit(1);
2645
            }
2646
            atexit(remove_pidfile);
2647
        }
2648
    } else {
2649
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
2650
                filename);
2651
        exit(1);
2652
    }
2653
}
2654

    
2655
/***********************************************************/
2656
/* dumb display */
2657

    
2658
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2659
{
2660
}
2661

    
2662
static void dumb_resize(DisplayState *ds, int w, int h)
2663
{
2664
}
2665

    
2666
static void dumb_refresh(DisplayState *ds)
2667
{
2668
    vga_update_display();
2669
}
2670

    
2671
void dumb_display_init(DisplayState *ds)
2672
{
2673
    ds->data = NULL;
2674
    ds->linesize = 0;
2675
    ds->depth = 0;
2676
    ds->dpy_update = dumb_update;
2677
    ds->dpy_resize = dumb_resize;
2678
    ds->dpy_refresh = dumb_refresh;
2679
}
2680

    
2681
#if !defined(CONFIG_SOFTMMU)
2682
/***********************************************************/
2683
/* cpu signal handler */
2684
static void host_segv_handler(int host_signum, siginfo_t *info, 
2685
                              void *puc)
2686
{
2687
    if (cpu_signal_handler(host_signum, info, puc))
2688
        return;
2689
    if (stdio_nb_clients > 0)
2690
        term_exit();
2691
    abort();
2692
}
2693
#endif
2694

    
2695
/***********************************************************/
2696
/* I/O handling */
2697

    
2698
#define MAX_IO_HANDLERS 64
2699

    
2700
typedef struct IOHandlerRecord {
2701
    int fd;
2702
    IOCanRWHandler *fd_read_poll;
2703
    IOHandler *fd_read;
2704
    IOHandler *fd_write;
2705
    void *opaque;
2706
    /* temporary data */
2707
    struct pollfd *ufd;
2708
    struct IOHandlerRecord *next;
2709
} IOHandlerRecord;
2710

    
2711
static IOHandlerRecord *first_io_handler;
2712

    
2713
/* XXX: fd_read_poll should be suppressed, but an API change is
2714
   necessary in the character devices to suppress fd_can_read(). */
2715
int qemu_set_fd_handler2(int fd, 
2716
                         IOCanRWHandler *fd_read_poll, 
2717
                         IOHandler *fd_read, 
2718
                         IOHandler *fd_write, 
2719
                         void *opaque)
2720
{
2721
    IOHandlerRecord **pioh, *ioh;
2722

    
2723
    if (!fd_read && !fd_write) {
2724
        pioh = &first_io_handler;
2725
        for(;;) {
2726
            ioh = *pioh;
2727
            if (ioh == NULL)
2728
                break;
2729
            if (ioh->fd == fd) {
2730
                *pioh = ioh->next;
2731
                break;
2732
            }
2733
            pioh = &ioh->next;
2734
        }
2735
    } else {
2736
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2737
            if (ioh->fd == fd)
2738
                goto found;
2739
        }
2740
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2741
        if (!ioh)
2742
            return -1;
2743
        ioh->next = first_io_handler;
2744
        first_io_handler = ioh;
2745
    found:
2746
        ioh->fd = fd;
2747
        ioh->fd_read_poll = fd_read_poll;
2748
        ioh->fd_read = fd_read;
2749
        ioh->fd_write = fd_write;
2750
        ioh->opaque = opaque;
2751
    }
2752
    return 0;
2753
}
2754

    
2755
int qemu_set_fd_handler(int fd, 
2756
                        IOHandler *fd_read, 
2757
                        IOHandler *fd_write, 
2758
                        void *opaque)
2759
{
2760
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2761
}
2762

    
2763
/***********************************************************/
2764
/* savevm/loadvm support */
2765

    
2766
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2767
{
2768
    fwrite(buf, 1, size, f);
2769
}
2770

    
2771
void qemu_put_byte(QEMUFile *f, int v)
2772
{
2773
    fputc(v, f);
2774
}
2775

    
2776
void qemu_put_be16(QEMUFile *f, unsigned int v)
2777
{
2778
    qemu_put_byte(f, v >> 8);
2779
    qemu_put_byte(f, v);
2780
}
2781

    
2782
void qemu_put_be32(QEMUFile *f, unsigned int v)
2783
{
2784
    qemu_put_byte(f, v >> 24);
2785
    qemu_put_byte(f, v >> 16);
2786
    qemu_put_byte(f, v >> 8);
2787
    qemu_put_byte(f, v);
2788
}
2789

    
2790
void qemu_put_be64(QEMUFile *f, uint64_t v)
2791
{
2792
    qemu_put_be32(f, v >> 32);
2793
    qemu_put_be32(f, v);
2794
}
2795

    
2796
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
2797
{
2798
    return fread(buf, 1, size, f);
2799
}
2800

    
2801
int qemu_get_byte(QEMUFile *f)
2802
{
2803
    int v;
2804
    v = fgetc(f);
2805
    if (v == EOF)
2806
        return 0;
2807
    else
2808
        return v;
2809
}
2810

    
2811
unsigned int qemu_get_be16(QEMUFile *f)
2812
{
2813
    unsigned int v;
2814
    v = qemu_get_byte(f) << 8;
2815
    v |= qemu_get_byte(f);
2816
    return v;
2817
}
2818

    
2819
unsigned int qemu_get_be32(QEMUFile *f)
2820
{
2821
    unsigned int v;
2822
    v = qemu_get_byte(f) << 24;
2823
    v |= qemu_get_byte(f) << 16;
2824
    v |= qemu_get_byte(f) << 8;
2825
    v |= qemu_get_byte(f);
2826
    return v;
2827
}
2828

    
2829
uint64_t qemu_get_be64(QEMUFile *f)
2830
{
2831
    uint64_t v;
2832
    v = (uint64_t)qemu_get_be32(f) << 32;
2833
    v |= qemu_get_be32(f);
2834
    return v;
2835
}
2836

    
2837
int64_t qemu_ftell(QEMUFile *f)
2838
{
2839
    return ftell(f);
2840
}
2841

    
2842
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
2843
{
2844
    if (fseek(f, pos, whence) < 0)
2845
        return -1;
2846
    return ftell(f);
2847
}
2848

    
2849
typedef struct SaveStateEntry {
2850
    char idstr[256];
2851
    int instance_id;
2852
    int version_id;
2853
    SaveStateHandler *save_state;
2854
    LoadStateHandler *load_state;
2855
    void *opaque;
2856
    struct SaveStateEntry *next;
2857
} SaveStateEntry;
2858

    
2859
static SaveStateEntry *first_se;
2860

    
2861
int register_savevm(const char *idstr, 
2862
                    int instance_id, 
2863
                    int version_id,
2864
                    SaveStateHandler *save_state,
2865
                    LoadStateHandler *load_state,
2866
                    void *opaque)
2867
{
2868
    SaveStateEntry *se, **pse;
2869

    
2870
    se = qemu_malloc(sizeof(SaveStateEntry));
2871
    if (!se)
2872
        return -1;
2873
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
2874
    se->instance_id = instance_id;
2875
    se->version_id = version_id;
2876
    se->save_state = save_state;
2877
    se->load_state = load_state;
2878
    se->opaque = opaque;
2879
    se->next = NULL;
2880

    
2881
    /* add at the end of list */
2882
    pse = &first_se;
2883
    while (*pse != NULL)
2884
        pse = &(*pse)->next;
2885
    *pse = se;
2886
    return 0;
2887
}
2888

    
2889
#define QEMU_VM_FILE_MAGIC   0x5145564d
2890
#define QEMU_VM_FILE_VERSION 0x00000001
2891

    
2892
int qemu_savevm(const char *filename)
2893
{
2894
    SaveStateEntry *se;
2895
    QEMUFile *f;
2896
    int len, len_pos, cur_pos, saved_vm_running, ret;
2897

    
2898
    saved_vm_running = vm_running;
2899
    vm_stop(0);
2900

    
2901
    f = fopen(filename, "wb");
2902
    if (!f) {
2903
        ret = -1;
2904
        goto the_end;
2905
    }
2906

    
2907
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
2908
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
2909

    
2910
    for(se = first_se; se != NULL; se = se->next) {
2911
        /* ID string */
2912
        len = strlen(se->idstr);
2913
        qemu_put_byte(f, len);
2914
        qemu_put_buffer(f, se->idstr, len);
2915

    
2916
        qemu_put_be32(f, se->instance_id);
2917
        qemu_put_be32(f, se->version_id);
2918

    
2919
        /* record size: filled later */
2920
        len_pos = ftell(f);
2921
        qemu_put_be32(f, 0);
2922
        
2923
        se->save_state(f, se->opaque);
2924

    
2925
        /* fill record size */
2926
        cur_pos = ftell(f);
2927
        len = ftell(f) - len_pos - 4;
2928
        fseek(f, len_pos, SEEK_SET);
2929
        qemu_put_be32(f, len);
2930
        fseek(f, cur_pos, SEEK_SET);
2931
    }
2932

    
2933
    fclose(f);
2934
    ret = 0;
2935
 the_end:
2936
    if (saved_vm_running)
2937
        vm_start();
2938
    return ret;
2939
}
2940

    
2941
static SaveStateEntry *find_se(const char *idstr, int instance_id)
2942
{
2943
    SaveStateEntry *se;
2944

    
2945
    for(se = first_se; se != NULL; se = se->next) {
2946
        if (!strcmp(se->idstr, idstr) && 
2947
            instance_id == se->instance_id)
2948
            return se;
2949
    }
2950
    return NULL;
2951
}
2952

    
2953
int qemu_loadvm(const char *filename)
2954
{
2955
    SaveStateEntry *se;
2956
    QEMUFile *f;
2957
    int len, cur_pos, ret, instance_id, record_len, version_id;
2958
    int saved_vm_running;
2959
    unsigned int v;
2960
    char idstr[256];
2961
    
2962
    saved_vm_running = vm_running;
2963
    vm_stop(0);
2964

    
2965
    f = fopen(filename, "rb");
2966
    if (!f) {
2967
        ret = -1;
2968
        goto the_end;
2969
    }
2970

    
2971
    v = qemu_get_be32(f);
2972
    if (v != QEMU_VM_FILE_MAGIC)
2973
        goto fail;
2974
    v = qemu_get_be32(f);
2975
    if (v != QEMU_VM_FILE_VERSION) {
2976
    fail:
2977
        fclose(f);
2978
        ret = -1;
2979
        goto the_end;
2980
    }
2981
    for(;;) {
2982
        len = qemu_get_byte(f);
2983
        if (feof(f))
2984
            break;
2985
        qemu_get_buffer(f, idstr, len);
2986
        idstr[len] = '\0';
2987
        instance_id = qemu_get_be32(f);
2988
        version_id = qemu_get_be32(f);
2989
        record_len = qemu_get_be32(f);
2990
#if 0
2991
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
2992
               idstr, instance_id, version_id, record_len);
2993
#endif
2994
        cur_pos = ftell(f);
2995
        se = find_se(idstr, instance_id);
2996
        if (!se) {
2997
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
2998
                    instance_id, idstr);
2999
        } else {
3000
            ret = se->load_state(f, se->opaque, version_id);
3001
            if (ret < 0) {
3002
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
3003
                        instance_id, idstr);
3004
            }
3005
        }
3006
        /* always seek to exact end of record */
3007
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3008
    }
3009
    fclose(f);
3010
    ret = 0;
3011
 the_end:
3012
    if (saved_vm_running)
3013
        vm_start();
3014
    return ret;
3015
}
3016

    
3017
/***********************************************************/
3018
/* cpu save/restore */
3019

    
3020
#if defined(TARGET_I386)
3021

    
3022
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3023
{
3024
    qemu_put_be32(f, dt->selector);
3025
    qemu_put_betl(f, dt->base);
3026
    qemu_put_be32(f, dt->limit);
3027
    qemu_put_be32(f, dt->flags);
3028
}
3029

    
3030
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3031
{
3032
    dt->selector = qemu_get_be32(f);
3033
    dt->base = qemu_get_betl(f);
3034
    dt->limit = qemu_get_be32(f);
3035
    dt->flags = qemu_get_be32(f);
3036
}
3037

    
3038
void cpu_save(QEMUFile *f, void *opaque)
3039
{
3040
    CPUState *env = opaque;
3041
    uint16_t fptag, fpus, fpuc, fpregs_format;
3042
    uint32_t hflags;
3043
    int i;
3044
    
3045
    for(i = 0; i < CPU_NB_REGS; i++)
3046
        qemu_put_betls(f, &env->regs[i]);
3047
    qemu_put_betls(f, &env->eip);
3048
    qemu_put_betls(f, &env->eflags);
3049
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3050
    qemu_put_be32s(f, &hflags);
3051
    
3052
    /* FPU */
3053
    fpuc = env->fpuc;
3054
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3055
    fptag = 0;
3056
    for(i = 0; i < 8; i++) {
3057
        fptag |= ((!env->fptags[i]) << i);
3058
    }
3059
    
3060
    qemu_put_be16s(f, &fpuc);
3061
    qemu_put_be16s(f, &fpus);
3062
    qemu_put_be16s(f, &fptag);
3063

    
3064
#ifdef USE_X86LDOUBLE
3065
    fpregs_format = 0;
3066
#else
3067
    fpregs_format = 1;
3068
#endif
3069
    qemu_put_be16s(f, &fpregs_format);
3070
    
3071
    for(i = 0; i < 8; i++) {
3072
#ifdef USE_X86LDOUBLE
3073
        {
3074
            uint64_t mant;
3075
            uint16_t exp;
3076
            /* we save the real CPU data (in case of MMX usage only 'mant'
3077
               contains the MMX register */
3078
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3079
            qemu_put_be64(f, mant);
3080
            qemu_put_be16(f, exp);
3081
        }
3082
#else
3083
        /* if we use doubles for float emulation, we save the doubles to
3084
           avoid losing information in case of MMX usage. It can give
3085
           problems if the image is restored on a CPU where long
3086
           doubles are used instead. */
3087
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3088
#endif
3089
    }
3090

    
3091
    for(i = 0; i < 6; i++)
3092
        cpu_put_seg(f, &env->segs[i]);
3093
    cpu_put_seg(f, &env->ldt);
3094
    cpu_put_seg(f, &env->tr);
3095
    cpu_put_seg(f, &env->gdt);
3096
    cpu_put_seg(f, &env->idt);
3097
    
3098
    qemu_put_be32s(f, &env->sysenter_cs);
3099
    qemu_put_be32s(f, &env->sysenter_esp);
3100
    qemu_put_be32s(f, &env->sysenter_eip);
3101
    
3102
    qemu_put_betls(f, &env->cr[0]);
3103
    qemu_put_betls(f, &env->cr[2]);
3104
    qemu_put_betls(f, &env->cr[3]);
3105
    qemu_put_betls(f, &env->cr[4]);
3106
    
3107
    for(i = 0; i < 8; i++)
3108
        qemu_put_betls(f, &env->dr[i]);
3109

    
3110
    /* MMU */
3111
    qemu_put_be32s(f, &env->a20_mask);
3112

    
3113
    /* XMM */
3114
    qemu_put_be32s(f, &env->mxcsr);
3115
    for(i = 0; i < CPU_NB_REGS; i++) {
3116
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3117
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3118
    }
3119

    
3120
#ifdef TARGET_X86_64
3121
    qemu_put_be64s(f, &env->efer);
3122
    qemu_put_be64s(f, &env->star);
3123
    qemu_put_be64s(f, &env->lstar);
3124
    qemu_put_be64s(f, &env->cstar);
3125
    qemu_put_be64s(f, &env->fmask);
3126
    qemu_put_be64s(f, &env->kernelgsbase);
3127
#endif
3128
}
3129

    
3130
#ifdef USE_X86LDOUBLE
3131
/* XXX: add that in a FPU generic layer */
3132
union x86_longdouble {
3133
    uint64_t mant;
3134
    uint16_t exp;
3135
};
3136

    
3137
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
3138
#define EXPBIAS1 1023
3139
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
3140
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
3141

    
3142
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3143
{
3144
    int e;
3145
    /* mantissa */
3146
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3147
    /* exponent + sign */
3148
    e = EXPD1(temp) - EXPBIAS1 + 16383;
3149
    e |= SIGND1(temp) >> 16;
3150
    p->exp = e;
3151
}
3152
#endif
3153

    
3154
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3155
{
3156
    CPUState *env = opaque;
3157
    int i, guess_mmx;
3158
    uint32_t hflags;
3159
    uint16_t fpus, fpuc, fptag, fpregs_format;
3160

    
3161
    if (version_id != 3)
3162
        return -EINVAL;
3163
    for(i = 0; i < CPU_NB_REGS; i++)
3164
        qemu_get_betls(f, &env->regs[i]);
3165
    qemu_get_betls(f, &env->eip);
3166
    qemu_get_betls(f, &env->eflags);
3167
    qemu_get_be32s(f, &hflags);
3168

    
3169
    qemu_get_be16s(f, &fpuc);
3170
    qemu_get_be16s(f, &fpus);
3171
    qemu_get_be16s(f, &fptag);
3172
    qemu_get_be16s(f, &fpregs_format);
3173
    
3174
    /* NOTE: we cannot always restore the FPU state if the image come
3175
       from a host with a different 'USE_X86LDOUBLE' define. We guess
3176
       if we are in an MMX state to restore correctly in that case. */
3177
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3178
    for(i = 0; i < 8; i++) {
3179
        uint64_t mant;
3180
        uint16_t exp;
3181
        
3182
        switch(fpregs_format) {
3183
        case 0:
3184
            mant = qemu_get_be64(f);
3185
            exp = qemu_get_be16(f);
3186
#ifdef USE_X86LDOUBLE
3187
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
3188
#else
3189
            /* difficult case */
3190
            if (guess_mmx)
3191
                env->fpregs[i].mmx.MMX_Q(0) = mant;
3192
            else
3193
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
3194
#endif
3195
            break;
3196
        case 1:
3197
            mant = qemu_get_be64(f);
3198
#ifdef USE_X86LDOUBLE
3199
            {
3200
                union x86_longdouble *p;
3201
                /* difficult case */
3202
                p = (void *)&env->fpregs[i];
3203
                if (guess_mmx) {
3204
                    p->mant = mant;
3205
                    p->exp = 0xffff;
3206
                } else {
3207
                    fp64_to_fp80(p, mant);
3208
                }
3209
            }
3210
#else
3211
            env->fpregs[i].mmx.MMX_Q(0) = mant;
3212
#endif            
3213
            break;
3214
        default:
3215
            return -EINVAL;
3216
        }
3217
    }
3218

    
3219
    env->fpuc = fpuc;
3220
    /* XXX: restore FPU round state */
3221
    env->fpstt = (fpus >> 11) & 7;
3222
    env->fpus = fpus & ~0x3800;
3223
    fptag ^= 0xff;
3224
    for(i = 0; i < 8; i++) {
3225
        env->fptags[i] = (fptag >> i) & 1;
3226
    }
3227
    
3228
    for(i = 0; i < 6; i++)
3229
        cpu_get_seg(f, &env->segs[i]);
3230
    cpu_get_seg(f, &env->ldt);
3231
    cpu_get_seg(f, &env->tr);
3232
    cpu_get_seg(f, &env->gdt);
3233
    cpu_get_seg(f, &env->idt);
3234
    
3235
    qemu_get_be32s(f, &env->sysenter_cs);
3236
    qemu_get_be32s(f, &env->sysenter_esp);
3237
    qemu_get_be32s(f, &env->sysenter_eip);
3238
    
3239
    qemu_get_betls(f, &env->cr[0]);
3240
    qemu_get_betls(f, &env->cr[2]);
3241
    qemu_get_betls(f, &env->cr[3]);
3242
    qemu_get_betls(f, &env->cr[4]);
3243
    
3244
    for(i = 0; i < 8; i++)
3245
        qemu_get_betls(f, &env->dr[i]);
3246

    
3247
    /* MMU */
3248
    qemu_get_be32s(f, &env->a20_mask);
3249

    
3250
    qemu_get_be32s(f, &env->mxcsr);
3251
    for(i = 0; i < CPU_NB_REGS; i++) {
3252
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3253
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3254
    }
3255

    
3256
#ifdef TARGET_X86_64
3257
    qemu_get_be64s(f, &env->efer);
3258
    qemu_get_be64s(f, &env->star);
3259
    qemu_get_be64s(f, &env->lstar);
3260
    qemu_get_be64s(f, &env->cstar);
3261
    qemu_get_be64s(f, &env->fmask);
3262
    qemu_get_be64s(f, &env->kernelgsbase);
3263
#endif
3264

    
3265
    /* XXX: compute hflags from scratch, except for CPL and IIF */
3266
    env->hflags = hflags;
3267
    tlb_flush(env, 1);
3268
    return 0;
3269
}
3270

    
3271
#elif defined(TARGET_PPC)
3272
void cpu_save(QEMUFile *f, void *opaque)
3273
{
3274
}
3275

    
3276
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3277
{
3278
    return 0;
3279
}
3280

    
3281
#elif defined(TARGET_MIPS)
3282
void cpu_save(QEMUFile *f, void *opaque)
3283
{
3284
}
3285

    
3286
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3287
{
3288
    return 0;
3289
}
3290

    
3291
#elif defined(TARGET_SPARC)
3292
void cpu_save(QEMUFile *f, void *opaque)
3293
{
3294
    CPUState *env = opaque;
3295
    int i;
3296
    uint32_t tmp;
3297

    
3298
    for(i = 0; i < 8; i++)
3299
        qemu_put_betls(f, &env->gregs[i]);
3300
    for(i = 0; i < NWINDOWS * 16; i++)
3301
        qemu_put_betls(f, &env->regbase[i]);
3302

    
3303
    /* FPU */
3304
    for(i = 0; i < TARGET_FPREGS; i++) {
3305
        union {
3306
            TARGET_FPREG_T f;
3307
            target_ulong i;
3308
        } u;
3309
        u.f = env->fpr[i];
3310
        qemu_put_betl(f, u.i);
3311
    }
3312

    
3313
    qemu_put_betls(f, &env->pc);
3314
    qemu_put_betls(f, &env->npc);
3315
    qemu_put_betls(f, &env->y);
3316
    tmp = GET_PSR(env);
3317
    qemu_put_be32(f, tmp);
3318
    qemu_put_betls(f, &env->fsr);
3319
    qemu_put_betls(f, &env->tbr);
3320
#ifndef TARGET_SPARC64
3321
    qemu_put_be32s(f, &env->wim);
3322
    /* MMU */
3323
    for(i = 0; i < 16; i++)
3324
        qemu_put_be32s(f, &env->mmuregs[i]);
3325
#endif
3326
}
3327

    
3328
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3329
{
3330
    CPUState *env = opaque;
3331
    int i;
3332
    uint32_t tmp;
3333

    
3334
    for(i = 0; i < 8; i++)
3335
        qemu_get_betls(f, &env->gregs[i]);
3336
    for(i = 0; i < NWINDOWS * 16; i++)
3337
        qemu_get_betls(f, &env->regbase[i]);
3338

    
3339
    /* FPU */
3340
    for(i = 0; i < TARGET_FPREGS; i++) {
3341
        union {
3342
            TARGET_FPREG_T f;
3343
            target_ulong i;
3344
        } u;
3345
        u.i = qemu_get_betl(f);
3346
        env->fpr[i] = u.f;
3347
    }
3348

    
3349
    qemu_get_betls(f, &env->pc);
3350
    qemu_get_betls(f, &env->npc);
3351
    qemu_get_betls(f, &env->y);
3352
    tmp = qemu_get_be32(f);
3353
    env->cwp = 0; /* needed to ensure that the wrapping registers are
3354
                     correctly updated */
3355
    PUT_PSR(env, tmp);
3356
    qemu_get_betls(f, &env->fsr);
3357
    qemu_get_betls(f, &env->tbr);
3358
#ifndef TARGET_SPARC64
3359
    qemu_get_be32s(f, &env->wim);
3360
    /* MMU */
3361
    for(i = 0; i < 16; i++)
3362
        qemu_get_be32s(f, &env->mmuregs[i]);
3363
#endif
3364
    tlb_flush(env, 1);
3365
    return 0;
3366
}
3367

    
3368
#elif defined(TARGET_ARM)
3369

    
3370
/* ??? Need to implement these.  */
3371
void cpu_save(QEMUFile *f, void *opaque)
3372
{
3373
}
3374

    
3375
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3376
{
3377
    return 0;
3378
}
3379

    
3380
#else
3381

    
3382
#warning No CPU save/restore functions
3383

    
3384
#endif
3385

    
3386
/***********************************************************/
3387
/* ram save/restore */
3388

    
3389
/* we just avoid storing empty pages */
3390
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3391
{
3392
    int i, v;
3393

    
3394
    v = buf[0];
3395
    for(i = 1; i < len; i++) {
3396
        if (buf[i] != v)
3397
            goto normal_save;
3398
    }
3399
    qemu_put_byte(f, 1);
3400
    qemu_put_byte(f, v);
3401
    return;
3402
 normal_save:
3403
    qemu_put_byte(f, 0); 
3404
    qemu_put_buffer(f, buf, len);
3405
}
3406

    
3407
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3408
{
3409
    int v;
3410

    
3411
    v = qemu_get_byte(f);
3412
    switch(v) {
3413
    case 0:
3414
        if (qemu_get_buffer(f, buf, len) != len)
3415
            return -EIO;
3416
        break;
3417
    case 1:
3418
        v = qemu_get_byte(f);
3419
        memset(buf, v, len);
3420
        break;
3421
    default:
3422
        return -EINVAL;
3423
    }
3424
    return 0;
3425
}
3426

    
3427
static void ram_save(QEMUFile *f, void *opaque)
3428
{
3429
    int i;
3430
    qemu_put_be32(f, phys_ram_size);
3431
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3432
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3433
    }
3434
}
3435

    
3436
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3437
{
3438
    int i, ret;
3439

    
3440
    if (version_id != 1)
3441
        return -EINVAL;
3442
    if (qemu_get_be32(f) != phys_ram_size)
3443
        return -EINVAL;
3444
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3445
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3446
        if (ret)
3447
            return ret;
3448
    }
3449
    return 0;
3450
}
3451

    
3452
/***********************************************************/
3453
/* machine registration */
3454

    
3455
QEMUMachine *first_machine = NULL;
3456

    
3457
int qemu_register_machine(QEMUMachine *m)
3458
{
3459
    QEMUMachine **pm;
3460
    pm = &first_machine;
3461
    while (*pm != NULL)
3462
        pm = &(*pm)->next;
3463
    m->next = NULL;
3464
    *pm = m;
3465
    return 0;
3466
}
3467

    
3468
QEMUMachine *find_machine(const char *name)
3469
{
3470
    QEMUMachine *m;
3471

    
3472
    for(m = first_machine; m != NULL; m = m->next) {
3473
        if (!strcmp(m->name, name))
3474
            return m;
3475
    }
3476
    return NULL;
3477
}
3478

    
3479
/***********************************************************/
3480
/* main execution loop */
3481

    
3482
void gui_update(void *opaque)
3483
{
3484
    display_state.dpy_refresh(&display_state);
3485
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3486
}
3487

    
3488
struct vm_change_state_entry {
3489
    VMChangeStateHandler *cb;
3490
    void *opaque;
3491
    LIST_ENTRY (vm_change_state_entry) entries;
3492
};
3493

    
3494
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3495

    
3496
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3497
                                                     void *opaque)
3498
{
3499
    VMChangeStateEntry *e;
3500

    
3501
    e = qemu_mallocz(sizeof (*e));
3502
    if (!e)
3503
        return NULL;
3504

    
3505
    e->cb = cb;
3506
    e->opaque = opaque;
3507
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3508
    return e;
3509
}
3510

    
3511
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3512
{
3513
    LIST_REMOVE (e, entries);
3514
    qemu_free (e);
3515
}
3516

    
3517
static void vm_state_notify(int running)
3518
{
3519
    VMChangeStateEntry *e;
3520

    
3521
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3522
        e->cb(e->opaque, running);
3523
    }
3524
}
3525

    
3526
/* XXX: support several handlers */
3527
static VMStopHandler *vm_stop_cb;
3528
static void *vm_stop_opaque;
3529

    
3530
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3531
{
3532
    vm_stop_cb = cb;
3533
    vm_stop_opaque = opaque;
3534
    return 0;
3535
}
3536

    
3537
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3538
{
3539
    vm_stop_cb = NULL;
3540
}
3541

    
3542
void vm_start(void)
3543
{
3544
    if (!vm_running) {
3545
        cpu_enable_ticks();
3546
        vm_running = 1;
3547
        vm_state_notify(1);
3548
    }
3549
}
3550

    
3551
void vm_stop(int reason) 
3552
{
3553
    if (vm_running) {
3554
        cpu_disable_ticks();
3555
        vm_running = 0;
3556
        if (reason != 0) {
3557
            if (vm_stop_cb) {
3558
                vm_stop_cb(vm_stop_opaque, reason);
3559
            }
3560
        }
3561
        vm_state_notify(0);
3562
    }
3563
}
3564

    
3565
/* reset/shutdown handler */
3566

    
3567
typedef struct QEMUResetEntry {
3568
    QEMUResetHandler *func;
3569
    void *opaque;
3570
    struct QEMUResetEntry *next;
3571
} QEMUResetEntry;
3572

    
3573
static QEMUResetEntry *first_reset_entry;
3574
static int reset_requested;
3575
static int shutdown_requested;
3576
static int powerdown_requested;
3577

    
3578
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3579
{
3580
    QEMUResetEntry **pre, *re;
3581

    
3582
    pre = &first_reset_entry;
3583
    while (*pre != NULL)
3584
        pre = &(*pre)->next;
3585
    re = qemu_mallocz(sizeof(QEMUResetEntry));
3586
    re->func = func;
3587
    re->opaque = opaque;
3588
    re->next = NULL;
3589
    *pre = re;
3590
}
3591

    
3592
void qemu_system_reset(void)
3593
{
3594
    QEMUResetEntry *re;
3595

    
3596
    /* reset all devices */
3597
    for(re = first_reset_entry; re != NULL; re = re->next) {
3598
        re->func(re->opaque);
3599
    }
3600
}
3601

    
3602
void qemu_system_reset_request(void)
3603
{
3604
    reset_requested = 1;
3605
    if (cpu_single_env)
3606
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3607
}
3608

    
3609
void qemu_system_shutdown_request(void)
3610
{
3611
    shutdown_requested = 1;
3612
    if (cpu_single_env)
3613
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3614
}
3615

    
3616
void qemu_system_powerdown_request(void)
3617
{
3618
    powerdown_requested = 1;
3619
    if (cpu_single_env)
3620
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3621
}
3622

    
3623
void main_loop_wait(int timeout)
3624
{
3625
#ifndef _WIN32
3626
    struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
3627
    IOHandlerRecord *ioh, *ioh_next;
3628
#endif
3629
    int ret;
3630

    
3631
#ifdef _WIN32
3632
        if (timeout > 0)
3633
            Sleep(timeout);
3634
#else
3635
        /* poll any events */
3636
        /* XXX: separate device handlers from system ones */
3637
        pf = ufds;
3638
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3639
            pf->events = 0;
3640
            pf->fd = ioh->fd;
3641
            if (ioh->fd_read &&
3642
                (!ioh->fd_read_poll ||
3643
                 ioh->fd_read_poll(ioh->opaque) != 0)) {
3644
                pf->events |= POLLIN;
3645
            }
3646
            if (ioh->fd_write) {
3647
                pf->events |= POLLOUT;
3648
            }
3649
            ioh->ufd = pf;
3650
            pf++;
3651
        }
3652
        
3653
        ret = poll(ufds, pf - ufds, timeout);
3654
        if (ret > 0) {
3655
            /* XXX: better handling of removal */
3656
            for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3657
                ioh_next = ioh->next;
3658
                pf = ioh->ufd;
3659
                if (pf->revents & POLLIN) {
3660
                    ioh->fd_read(ioh->opaque);
3661
                }
3662
                if (pf->revents & POLLOUT) {
3663
                    ioh->fd_write(ioh->opaque);
3664
                }
3665
            }
3666
        }
3667
#endif /* !defined(_WIN32) */
3668
#if defined(CONFIG_SLIRP)
3669
        /* XXX: merge with poll() */
3670
        if (slirp_inited) {
3671
            fd_set rfds, wfds, xfds;
3672
            int nfds;
3673
            struct timeval tv;
3674

    
3675
            nfds = -1;
3676
            FD_ZERO(&rfds);
3677
            FD_ZERO(&wfds);
3678
            FD_ZERO(&xfds);
3679
            slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3680
            tv.tv_sec = 0;
3681
            tv.tv_usec = 0;
3682
            ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3683
            if (ret >= 0) {
3684
                slirp_select_poll(&rfds, &wfds, &xfds);
3685
            }
3686
        }
3687
#endif
3688

    
3689
        if (vm_running) {
3690
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
3691
                            qemu_get_clock(vm_clock));
3692
            /* run dma transfers, if any */
3693
            DMA_run();
3694
        }
3695

    
3696
        /* real time timers */
3697
        qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
3698
                        qemu_get_clock(rt_clock));
3699
}
3700

    
3701
static CPUState *cur_cpu;
3702

    
3703
int main_loop(void)
3704
{
3705
    int ret, timeout;
3706
    CPUState *env;
3707

    
3708
    cur_cpu = first_cpu;
3709
    for(;;) {
3710
        if (vm_running) {
3711

    
3712
            env = cur_cpu;
3713
            for(;;) {
3714
                /* get next cpu */
3715
                env = env->next_cpu;
3716
                if (!env)
3717
                    env = first_cpu;
3718
                ret = cpu_exec(env);
3719
                if (ret != EXCP_HALTED)
3720
                    break;
3721
                /* all CPUs are halted ? */
3722
                if (env == cur_cpu) {
3723
                    ret = EXCP_HLT;
3724
                    break;
3725
                }
3726
            }
3727
            cur_cpu = env;
3728

    
3729
            if (shutdown_requested) {
3730
                ret = EXCP_INTERRUPT;
3731
                break;
3732
            }
3733
            if (reset_requested) {
3734
                reset_requested = 0;
3735
                qemu_system_reset();
3736
                ret = EXCP_INTERRUPT;
3737
            }
3738
            if (powerdown_requested) {
3739
                powerdown_requested = 0;
3740
                qemu_system_powerdown();
3741
                ret = EXCP_INTERRUPT;
3742
            }
3743
            if (ret == EXCP_DEBUG) {
3744
                vm_stop(EXCP_DEBUG);
3745
            }
3746
            /* if hlt instruction, we wait until the next IRQ */
3747
            /* XXX: use timeout computed from timers */
3748
            if (ret == EXCP_HLT)
3749
                timeout = 10;
3750
            else
3751
                timeout = 0;
3752
        } else {
3753
            timeout = 10;
3754
        }
3755
        main_loop_wait(timeout);
3756
    }
3757
    cpu_disable_ticks();
3758
    return ret;
3759
}
3760

    
3761
void help(void)
3762
{
3763
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
3764
           "usage: %s [options] [disk_image]\n"
3765
           "\n"
3766
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3767
           "\n"
3768
           "Standard options:\n"
3769
           "-M machine      select emulated machine (-M ? for list)\n"
3770
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
3771
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
3772
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
3773
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3774
           "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
3775
           "-snapshot       write to temporary files instead of disk image files\n"
3776
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
3777
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
3778
#ifndef _WIN32
3779
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
3780
#endif
3781
#ifdef HAS_AUDIO
3782
           "-enable-audio   enable audio support, and all the sound cars\n"
3783
           "-audio-help     print list of audio drivers and their options\n"
3784
           "-soundhw c1,... enable audio support\n"
3785
           "                and only specified sound cards (comma separated list)\n"
3786
           "                use -soundhw ? to get the list of supported cards\n"
3787
#endif
3788
           "-localtime      set the real time clock to local time [default=utc]\n"
3789
           "-full-screen    start in full screen\n"
3790
#ifdef TARGET_I386
3791
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
3792
#endif
3793
           "-usb            enable the USB driver (will be the default soon)\n"
3794
           "-usbdevice name add the host or guest USB device 'name'\n"
3795
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
3796
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
3797
#endif
3798
           "\n"
3799
           "Network options:\n"
3800
           "-net nic[,vlan=n][,macaddr=addr]\n"
3801
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
3802
#ifdef CONFIG_SLIRP
3803
           "-net user[,vlan=n]\n"
3804
           "                connect the user mode network stack to VLAN 'n'\n"
3805
#endif
3806
#ifndef _WIN32
3807
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
3808
           "                connect the host TAP network interface to VLAN 'n' and use\n"
3809
           "                the network script 'file' (default=%s);\n"
3810
           "                use 'fd=h' to connect to an already opened TAP interface\n"
3811
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3812
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
3813
#endif
3814
           "-net none       use it alone to have zero network devices; if no -net option\n"
3815
           "                is provided, the default is '-net nic -net user'\n"
3816
           "\n"
3817
#ifdef CONFIG_SLIRP
3818
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
3819
#ifndef _WIN32
3820
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
3821
#endif
3822
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3823
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
3824
#endif
3825
           "\n"
3826
           "Linux boot specific:\n"
3827
           "-kernel bzImage use 'bzImage' as kernel image\n"
3828
           "-append cmdline use 'cmdline' as kernel command line\n"
3829
           "-initrd file    use 'file' as initial ram disk\n"
3830
           "\n"
3831
           "Debug/Expert options:\n"
3832
           "-monitor dev    redirect the monitor to char device 'dev'\n"
3833
           "-serial dev     redirect the serial port to char device 'dev'\n"
3834
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
3835
           "-pidfile file   Write PID to 'file'\n"
3836
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
3837
           "-s              wait gdb connection to port %d\n"
3838
           "-p port         change gdb connection port\n"
3839
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
3840
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
3841
           "                translation (t=none or lba) (usually qemu can guess them)\n"
3842
           "-L path         set the directory for the BIOS and VGA BIOS\n"
3843
#ifdef USE_KQEMU
3844
           "-no-kqemu       disable KQEMU kernel module usage\n"
3845
#endif
3846
#ifdef USE_CODE_COPY
3847
           "-no-code-copy   disable code copy acceleration\n"
3848
#endif
3849
#ifdef TARGET_I386
3850
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
3851
           "                (default is CL-GD5446 PCI VGA)\n"
3852
#endif
3853
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
3854
           "\n"
3855
           "During emulation, the following keys are useful:\n"
3856
           "ctrl-alt-f      toggle full screen\n"
3857
           "ctrl-alt-n      switch to virtual console 'n'\n"
3858
           "ctrl-alt        toggle mouse and keyboard grab\n"
3859
           "\n"
3860
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
3861
           ,
3862
#ifdef CONFIG_SOFTMMU
3863
           "qemu",
3864
#else
3865
           "qemu-fast",
3866
#endif
3867
           DEFAULT_RAM_SIZE,
3868
#ifndef _WIN32
3869
           DEFAULT_NETWORK_SCRIPT,
3870
#endif
3871
           DEFAULT_GDBSTUB_PORT,
3872
           "/tmp/qemu.log");
3873
#ifndef CONFIG_SOFTMMU
3874
    printf("\n"
3875
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
3876
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
3877
           "PC emulation.\n");
3878
#endif
3879
    exit(1);
3880
}
3881

    
3882
#define HAS_ARG 0x0001
3883

    
3884
enum {
3885
    QEMU_OPTION_h,
3886

    
3887
    QEMU_OPTION_M,
3888
    QEMU_OPTION_fda,
3889
    QEMU_OPTION_fdb,
3890
    QEMU_OPTION_hda,
3891
    QEMU_OPTION_hdb,
3892
    QEMU_OPTION_hdc,
3893
    QEMU_OPTION_hdd,
3894
    QEMU_OPTION_cdrom,
3895
    QEMU_OPTION_boot,
3896
    QEMU_OPTION_snapshot,
3897
    QEMU_OPTION_m,
3898
    QEMU_OPTION_nographic,
3899
#ifdef HAS_AUDIO
3900
    QEMU_OPTION_enable_audio,
3901
    QEMU_OPTION_audio_help,
3902
    QEMU_OPTION_soundhw,
3903
#endif
3904

    
3905
    QEMU_OPTION_net,
3906
    QEMU_OPTION_tftp,
3907
    QEMU_OPTION_smb,
3908
    QEMU_OPTION_redir,
3909

    
3910
    QEMU_OPTION_kernel,
3911
    QEMU_OPTION_append,
3912
    QEMU_OPTION_initrd,
3913

    
3914
    QEMU_OPTION_S,
3915
    QEMU_OPTION_s,
3916
    QEMU_OPTION_p,
3917
    QEMU_OPTION_d,
3918
    QEMU_OPTION_hdachs,
3919
    QEMU_OPTION_L,
3920
    QEMU_OPTION_no_code_copy,
3921
    QEMU_OPTION_k,
3922
    QEMU_OPTION_localtime,
3923
    QEMU_OPTION_cirrusvga,
3924
    QEMU_OPTION_g,
3925
    QEMU_OPTION_std_vga,
3926
    QEMU_OPTION_monitor,
3927
    QEMU_OPTION_serial,
3928
    QEMU_OPTION_parallel,
3929
    QEMU_OPTION_loadvm,
3930
    QEMU_OPTION_full_screen,
3931
    QEMU_OPTION_pidfile,
3932
    QEMU_OPTION_no_kqemu,
3933
    QEMU_OPTION_win2k_hack,
3934
    QEMU_OPTION_usb,
3935
    QEMU_OPTION_usbdevice,
3936
    QEMU_OPTION_smp,
3937
};
3938

    
3939
typedef struct QEMUOption {
3940
    const char *name;
3941
    int flags;
3942
    int index;
3943
} QEMUOption;
3944

    
3945
const QEMUOption qemu_options[] = {
3946
    { "h", 0, QEMU_OPTION_h },
3947

    
3948
    { "M", HAS_ARG, QEMU_OPTION_M },
3949
    { "fda", HAS_ARG, QEMU_OPTION_fda },
3950
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
3951
    { "hda", HAS_ARG, QEMU_OPTION_hda },
3952
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
3953
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
3954
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
3955
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
3956
    { "boot", HAS_ARG, QEMU_OPTION_boot },
3957
    { "snapshot", 0, QEMU_OPTION_snapshot },
3958
    { "m", HAS_ARG, QEMU_OPTION_m },
3959
    { "nographic", 0, QEMU_OPTION_nographic },
3960
    { "k", HAS_ARG, QEMU_OPTION_k },
3961
#ifdef HAS_AUDIO
3962
    { "enable-audio", 0, QEMU_OPTION_enable_audio },
3963
    { "audio-help", 0, QEMU_OPTION_audio_help },
3964
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
3965
#endif
3966

    
3967
    { "net", HAS_ARG, QEMU_OPTION_net},
3968
#ifdef CONFIG_SLIRP
3969
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
3970
#ifndef _WIN32
3971
    { "smb", HAS_ARG, QEMU_OPTION_smb },
3972
#endif
3973
    { "redir", HAS_ARG, QEMU_OPTION_redir },
3974
#endif
3975

    
3976
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
3977
    { "append", HAS_ARG, QEMU_OPTION_append },
3978
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
3979

    
3980
    { "S", 0, QEMU_OPTION_S },
3981
    { "s", 0, QEMU_OPTION_s },
3982
    { "p", HAS_ARG, QEMU_OPTION_p },
3983
    { "d", HAS_ARG, QEMU_OPTION_d },
3984
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
3985
    { "L", HAS_ARG, QEMU_OPTION_L },
3986
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
3987
#ifdef USE_KQEMU
3988
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
3989
#endif
3990
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
3991
    { "g", 1, QEMU_OPTION_g },
3992
#endif
3993
    { "localtime", 0, QEMU_OPTION_localtime },
3994
    { "std-vga", 0, QEMU_OPTION_std_vga },
3995
    { "monitor", 1, QEMU_OPTION_monitor },
3996
    { "serial", 1, QEMU_OPTION_serial },
3997
    { "parallel", 1, QEMU_OPTION_parallel },
3998
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
3999
    { "full-screen", 0, QEMU_OPTION_full_screen },
4000
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4001
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4002
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4003
    { "smp", HAS_ARG, QEMU_OPTION_smp },
4004
    
4005
    /* temporary options */
4006
    { "usb", 0, QEMU_OPTION_usb },
4007
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4008
    { NULL },
4009
};
4010

    
4011
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4012

    
4013
/* this stack is only used during signal handling */
4014
#define SIGNAL_STACK_SIZE 32768
4015

    
4016
static uint8_t *signal_stack;
4017

    
4018
#endif
4019

    
4020
/* password input */
4021

    
4022
static BlockDriverState *get_bdrv(int index)
4023
{
4024
    BlockDriverState *bs;
4025

    
4026
    if (index < 4) {
4027
        bs = bs_table[index];
4028
    } else if (index < 6) {
4029
        bs = fd_table[index - 4];
4030
    } else {
4031
        bs = NULL;
4032
    }
4033
    return bs;
4034
}
4035

    
4036
static void read_passwords(void)
4037
{
4038
    BlockDriverState *bs;
4039
    int i, j;
4040
    char password[256];
4041

    
4042
    for(i = 0; i < 6; i++) {
4043
        bs = get_bdrv(i);
4044
        if (bs && bdrv_is_encrypted(bs)) {
4045
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4046
            for(j = 0; j < 3; j++) {
4047
                monitor_readline("Password: ", 
4048
                                 1, password, sizeof(password));
4049
                if (bdrv_set_key(bs, password) == 0)
4050
                    break;
4051
                term_printf("invalid password\n");
4052
            }
4053
        }
4054
    }
4055
}
4056

    
4057
/* XXX: currently we cannot use simultaneously different CPUs */
4058
void register_machines(void)
4059
{
4060
#if defined(TARGET_I386)
4061
    qemu_register_machine(&pc_machine);
4062
    qemu_register_machine(&isapc_machine);
4063
#elif defined(TARGET_PPC)
4064
    qemu_register_machine(&heathrow_machine);
4065
    qemu_register_machine(&core99_machine);
4066
    qemu_register_machine(&prep_machine);
4067
#elif defined(TARGET_MIPS)
4068
    qemu_register_machine(&mips_machine);
4069
#elif defined(TARGET_SPARC)
4070
#ifdef TARGET_SPARC64
4071
    qemu_register_machine(&sun4u_machine);
4072
#else
4073
    qemu_register_machine(&sun4m_machine);
4074
#endif
4075
#elif defined(TARGET_ARM)
4076
    qemu_register_machine(&integratorcp_machine);
4077
#else
4078
#error unsupported CPU
4079
#endif
4080
}
4081

    
4082
#ifdef HAS_AUDIO
4083
static void select_soundhw (const char *optarg)
4084
{
4085
    if (*optarg == '?') {
4086
    show_valid_cards:
4087
        printf ("Valid sound card names (comma separated):\n");
4088
        printf ("sb16       Creative Sound Blaster 16\n");
4089
#ifdef CONFIG_ADLIB
4090
#ifdef HAS_YMF262
4091
        printf ("adlib      Yamaha YMF262 (OPL3)\n");
4092
#else
4093
        printf ("adlib      Yamaha YM3812 (OPL2)\n");
4094
#endif
4095
#endif
4096
#ifdef CONFIG_GUS
4097
        printf ("gus        Gravis Ultrasound GF1\n");
4098
#endif
4099
        printf ("es1370     ENSONIQ AudioPCI ES1370\n");
4100
        exit (*optarg != '?');
4101
    }
4102
    else {
4103
        struct {
4104
            char *name;
4105
            int *enabledp;
4106
        } soundhw_tab[] = {
4107
            { "sb16", &sb16_enabled },
4108
#ifdef CONFIG_ADLIB
4109
            { "adlib", &adlib_enabled },
4110
#endif
4111
#ifdef CONFIG_GUS
4112
            { "gus", &gus_enabled },
4113
#endif
4114
            { "es1370", &es1370_enabled },
4115
        };
4116
        size_t tablen, l, i;
4117
        const char *p;
4118
        char *e;
4119
        int bad_card = 0;
4120

    
4121
        p = optarg;
4122
        tablen = sizeof (soundhw_tab) / sizeof (soundhw_tab[0]);
4123

    
4124
        while (*p) {
4125
            e = strchr (p, ',');
4126
            l = !e ? strlen (p) : (size_t) (e - p);
4127
            for (i = 0; i < tablen; ++i) {
4128
                if (!strncmp (soundhw_tab[i].name, p, l)) {
4129
                    audio_enabled = 1;
4130
                    *soundhw_tab[i].enabledp = 1;
4131
                    break;
4132
                }
4133
            }
4134
            if (i == tablen) {
4135
                if (l > 80) {
4136
                    fprintf (stderr,
4137
                             "Unknown sound card name (too big to show)\n");
4138
                }
4139
                else {
4140
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4141
                             (int) l, p);
4142
                }
4143
                bad_card = 1;
4144
            }
4145
            p += l + (e != NULL);
4146
        }
4147

    
4148
        if (bad_card)
4149
            goto show_valid_cards;
4150
    }
4151
}
4152
#endif
4153

    
4154
#define MAX_NET_CLIENTS 32
4155

    
4156
int main(int argc, char **argv)
4157
{
4158
#ifdef CONFIG_GDBSTUB
4159
    int use_gdbstub, gdbstub_port;
4160
#endif
4161
    int i, cdrom_index;
4162
    int snapshot, linux_boot;
4163
    const char *initrd_filename;
4164
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4165
    const char *kernel_filename, *kernel_cmdline;
4166
    DisplayState *ds = &display_state;
4167
    int cyls, heads, secs, translation;
4168
    int start_emulation = 1;
4169
    char net_clients[MAX_NET_CLIENTS][256];
4170
    int nb_net_clients;
4171
    int optind;
4172
    const char *r, *optarg;
4173
    CharDriverState *monitor_hd;
4174
    char monitor_device[128];
4175
    char serial_devices[MAX_SERIAL_PORTS][128];
4176
    int serial_device_index;
4177
    char parallel_devices[MAX_PARALLEL_PORTS][128];
4178
    int parallel_device_index;
4179
    const char *loadvm = NULL;
4180
    QEMUMachine *machine;
4181
    char usb_devices[MAX_VM_USB_PORTS][128];
4182
    int usb_devices_index;
4183

    
4184
    LIST_INIT (&vm_change_state_head);
4185
#if !defined(CONFIG_SOFTMMU)
4186
    /* we never want that malloc() uses mmap() */
4187
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4188
#endif
4189
    register_machines();
4190
    machine = first_machine;
4191
    initrd_filename = NULL;
4192
    for(i = 0; i < MAX_FD; i++)
4193
        fd_filename[i] = NULL;
4194
    for(i = 0; i < MAX_DISKS; i++)
4195
        hd_filename[i] = NULL;
4196
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4197
    vga_ram_size = VGA_RAM_SIZE;
4198
    bios_size = BIOS_SIZE;
4199
#ifdef CONFIG_GDBSTUB
4200
    use_gdbstub = 0;
4201
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
4202
#endif
4203
    snapshot = 0;
4204
    nographic = 0;
4205
    kernel_filename = NULL;
4206
    kernel_cmdline = "";
4207
#ifdef TARGET_PPC
4208
    cdrom_index = 1;
4209
#else
4210
    cdrom_index = 2;
4211
#endif
4212
    cyls = heads = secs = 0;
4213
    translation = BIOS_ATA_TRANSLATION_AUTO;
4214
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4215

    
4216
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4217
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4218
        serial_devices[i][0] = '\0';
4219
    serial_device_index = 0;
4220
    
4221
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4222
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4223
        parallel_devices[i][0] = '\0';
4224
    parallel_device_index = 0;
4225
    
4226
    usb_devices_index = 0;
4227
    
4228
    nb_net_clients = 0;
4229

    
4230
    nb_nics = 0;
4231
    /* default mac address of the first network interface */
4232
    
4233
    optind = 1;
4234
    for(;;) {
4235
        if (optind >= argc)
4236
            break;
4237
        r = argv[optind];
4238
        if (r[0] != '-') {
4239
            hd_filename[0] = argv[optind++];
4240
        } else {
4241
            const QEMUOption *popt;
4242

    
4243
            optind++;
4244
            popt = qemu_options;
4245
            for(;;) {
4246
                if (!popt->name) {
4247
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
4248
                            argv[0], r);
4249
                    exit(1);
4250
                }
4251
                if (!strcmp(popt->name, r + 1))
4252
                    break;
4253
                popt++;
4254
            }
4255
            if (popt->flags & HAS_ARG) {
4256
                if (optind >= argc) {
4257
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
4258
                            argv[0], r);
4259
                    exit(1);
4260
                }
4261
                optarg = argv[optind++];
4262
            } else {
4263
                optarg = NULL;
4264
            }
4265

    
4266
            switch(popt->index) {
4267
            case QEMU_OPTION_M:
4268
                machine = find_machine(optarg);
4269
                if (!machine) {
4270
                    QEMUMachine *m;
4271
                    printf("Supported machines are:\n");
4272
                    for(m = first_machine; m != NULL; m = m->next) {
4273
                        printf("%-10s %s%s\n",
4274
                               m->name, m->desc, 
4275
                               m == first_machine ? " (default)" : "");
4276
                    }
4277
                    exit(1);
4278
                }
4279
                break;
4280
            case QEMU_OPTION_initrd:
4281
                initrd_filename = optarg;
4282
                break;
4283
            case QEMU_OPTION_hda:
4284
            case QEMU_OPTION_hdb:
4285
            case QEMU_OPTION_hdc:
4286
            case QEMU_OPTION_hdd:
4287
                {
4288
                    int hd_index;
4289
                    hd_index = popt->index - QEMU_OPTION_hda;
4290
                    hd_filename[hd_index] = optarg;
4291
                    if (hd_index == cdrom_index)
4292
                        cdrom_index = -1;
4293
                }
4294
                break;
4295
            case QEMU_OPTION_snapshot:
4296
                snapshot = 1;
4297
                break;
4298
            case QEMU_OPTION_hdachs:
4299
                {
4300
                    const char *p;
4301
                    p = optarg;
4302
                    cyls = strtol(p, (char **)&p, 0);
4303
                    if (cyls < 1 || cyls > 16383)
4304
                        goto chs_fail;
4305
                    if (*p != ',')
4306
                        goto chs_fail;
4307
                    p++;
4308
                    heads = strtol(p, (char **)&p, 0);
4309
                    if (heads < 1 || heads > 16)
4310
                        goto chs_fail;
4311
                    if (*p != ',')
4312
                        goto chs_fail;
4313
                    p++;
4314
                    secs = strtol(p, (char **)&p, 0);
4315
                    if (secs < 1 || secs > 63)
4316
                        goto chs_fail;
4317
                    if (*p == ',') {
4318
                        p++;
4319
                        if (!strcmp(p, "none"))
4320
                            translation = BIOS_ATA_TRANSLATION_NONE;
4321
                        else if (!strcmp(p, "lba"))
4322
                            translation = BIOS_ATA_TRANSLATION_LBA;
4323
                        else if (!strcmp(p, "auto"))
4324
                            translation = BIOS_ATA_TRANSLATION_AUTO;
4325
                        else
4326
                            goto chs_fail;
4327
                    } else if (*p != '\0') {
4328
                    chs_fail:
4329
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
4330
                        exit(1);
4331
                    }
4332
                }
4333
                break;
4334
            case QEMU_OPTION_nographic:
4335
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4336
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4337
                nographic = 1;
4338
                break;
4339
            case QEMU_OPTION_kernel:
4340
                kernel_filename = optarg;
4341
                break;
4342
            case QEMU_OPTION_append:
4343
                kernel_cmdline = optarg;
4344
                break;
4345
            case QEMU_OPTION_cdrom:
4346
                if (cdrom_index >= 0) {
4347
                    hd_filename[cdrom_index] = optarg;
4348
                }
4349
                break;
4350
            case QEMU_OPTION_boot:
4351
                boot_device = optarg[0];
4352
                if (boot_device != 'a' && 
4353
#ifdef TARGET_SPARC
4354
                    // Network boot
4355
                    boot_device != 'n' &&
4356
#endif
4357
                    boot_device != 'c' && boot_device != 'd') {
4358
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4359
                    exit(1);
4360
                }
4361
                break;
4362
            case QEMU_OPTION_fda:
4363
                fd_filename[0] = optarg;
4364
                break;
4365
            case QEMU_OPTION_fdb:
4366
                fd_filename[1] = optarg;
4367
                break;
4368
            case QEMU_OPTION_no_code_copy:
4369
                code_copy_enabled = 0;
4370
                break;
4371
            case QEMU_OPTION_net:
4372
                if (nb_net_clients >= MAX_NET_CLIENTS) {
4373
                    fprintf(stderr, "qemu: too many network clients\n");
4374
                    exit(1);
4375
                }
4376
                pstrcpy(net_clients[nb_net_clients],
4377
                        sizeof(net_clients[0]),
4378
                        optarg);
4379
                nb_net_clients++;
4380
                break;
4381
#ifdef CONFIG_SLIRP
4382
            case QEMU_OPTION_tftp:
4383
                tftp_prefix = optarg;
4384
                break;
4385
#ifndef _WIN32
4386
            case QEMU_OPTION_smb:
4387
                net_slirp_smb(optarg);
4388
                break;
4389
#endif
4390
            case QEMU_OPTION_redir:
4391
                net_slirp_redir(optarg);                
4392
                break;
4393
#endif
4394
#ifdef HAS_AUDIO
4395
            case QEMU_OPTION_enable_audio:
4396
                audio_enabled = 1;
4397
                sb16_enabled = 1;
4398
                adlib_enabled = 1;
4399
                gus_enabled = 1;
4400
                es1370_enabled = 1;
4401
                break;
4402
            case QEMU_OPTION_audio_help:
4403
                AUD_help ();
4404
                exit (0);
4405
                break;
4406
            case QEMU_OPTION_soundhw:
4407
                select_soundhw (optarg);
4408
                break;
4409
#endif
4410
            case QEMU_OPTION_h:
4411
                help();
4412
                break;
4413
            case QEMU_OPTION_m:
4414
                ram_size = atoi(optarg) * 1024 * 1024;
4415
                if (ram_size <= 0)
4416
                    help();
4417
                if (ram_size > PHYS_RAM_MAX_SIZE) {
4418
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4419
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
4420
                    exit(1);
4421
                }
4422
                break;
4423
            case QEMU_OPTION_d:
4424
                {
4425
                    int mask;
4426
                    CPULogItem *item;
4427
                    
4428
                    mask = cpu_str_to_log_mask(optarg);
4429
                    if (!mask) {
4430
                        printf("Log items (comma separated):\n");
4431
                    for(item = cpu_log_items; item->mask != 0; item++) {
4432
                        printf("%-10s %s\n", item->name, item->help);
4433
                    }
4434
                    exit(1);
4435
                    }
4436
                    cpu_set_log(mask);
4437
                }
4438
                break;
4439
#ifdef CONFIG_GDBSTUB
4440
            case QEMU_OPTION_s:
4441
                use_gdbstub = 1;
4442
                break;
4443
            case QEMU_OPTION_p:
4444
                gdbstub_port = atoi(optarg);
4445
                break;
4446
#endif
4447
            case QEMU_OPTION_L:
4448
                bios_dir = optarg;
4449
                break;
4450
            case QEMU_OPTION_S:
4451
                start_emulation = 0;
4452
                break;
4453
            case QEMU_OPTION_k:
4454
                keyboard_layout = optarg;
4455
                break;
4456
            case QEMU_OPTION_localtime:
4457
                rtc_utc = 0;
4458
                break;
4459
            case QEMU_OPTION_cirrusvga:
4460
                cirrus_vga_enabled = 1;
4461
                break;
4462
            case QEMU_OPTION_std_vga:
4463
                cirrus_vga_enabled = 0;
4464
                break;
4465
            case QEMU_OPTION_g:
4466
                {
4467
                    const char *p;
4468
                    int w, h, depth;
4469
                    p = optarg;
4470
                    w = strtol(p, (char **)&p, 10);
4471
                    if (w <= 0) {
4472
                    graphic_error:
4473
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
4474
                        exit(1);
4475
                    }
4476
                    if (*p != 'x')
4477
                        goto graphic_error;
4478
                    p++;
4479
                    h = strtol(p, (char **)&p, 10);
4480
                    if (h <= 0)
4481
                        goto graphic_error;
4482
                    if (*p == 'x') {
4483
                        p++;
4484
                        depth = strtol(p, (char **)&p, 10);
4485
                        if (depth != 8 && depth != 15 && depth != 16 && 
4486
                            depth != 24 && depth != 32)
4487
                            goto graphic_error;
4488
                    } else if (*p == '\0') {
4489
                        depth = graphic_depth;
4490
                    } else {
4491
                        goto graphic_error;
4492
                    }
4493
                    
4494
                    graphic_width = w;
4495
                    graphic_height = h;
4496
                    graphic_depth = depth;
4497
                }
4498
                break;
4499
            case QEMU_OPTION_monitor:
4500
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4501
                break;
4502
            case QEMU_OPTION_serial:
4503
                if (serial_device_index >= MAX_SERIAL_PORTS) {
4504
                    fprintf(stderr, "qemu: too many serial ports\n");
4505
                    exit(1);
4506
                }
4507
                pstrcpy(serial_devices[serial_device_index], 
4508
                        sizeof(serial_devices[0]), optarg);
4509
                serial_device_index++;
4510
                break;
4511
            case QEMU_OPTION_parallel:
4512
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4513
                    fprintf(stderr, "qemu: too many parallel ports\n");
4514
                    exit(1);
4515
                }
4516
                pstrcpy(parallel_devices[parallel_device_index], 
4517
                        sizeof(parallel_devices[0]), optarg);
4518
                parallel_device_index++;
4519
                break;
4520
            case QEMU_OPTION_loadvm:
4521
                loadvm = optarg;
4522
                break;
4523
            case QEMU_OPTION_full_screen:
4524
                full_screen = 1;
4525
                break;
4526
            case QEMU_OPTION_pidfile:
4527
                create_pidfile(optarg);
4528
                break;
4529
#ifdef TARGET_I386
4530
            case QEMU_OPTION_win2k_hack:
4531
                win2k_install_hack = 1;
4532
                break;
4533
#endif
4534
#ifdef USE_KQEMU
4535
            case QEMU_OPTION_no_kqemu:
4536
                kqemu_allowed = 0;
4537
                break;
4538
#endif
4539
            case QEMU_OPTION_usb:
4540
                usb_enabled = 1;
4541
                break;
4542
            case QEMU_OPTION_usbdevice:
4543
                usb_enabled = 1;
4544
                if (usb_devices_index >= MAX_VM_USB_PORTS) {
4545
                    fprintf(stderr, "Too many USB devices\n");
4546
                    exit(1);
4547
                }
4548
                pstrcpy(usb_devices[usb_devices_index],
4549
                        sizeof(usb_devices[usb_devices_index]),
4550
                        optarg);
4551
                usb_devices_index++;
4552
                break;
4553
            case QEMU_OPTION_smp:
4554
                smp_cpus = atoi(optarg);
4555
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
4556
                    fprintf(stderr, "Invalid number of CPUs\n");
4557
                    exit(1);
4558
                }
4559
                break;
4560
            }
4561
        }
4562
    }
4563

    
4564
    linux_boot = (kernel_filename != NULL);
4565
        
4566
    if (!linux_boot && 
4567
        hd_filename[0] == '\0' && 
4568
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4569
        fd_filename[0] == '\0')
4570
        help();
4571
    
4572
    /* boot to cd by default if no hard disk */
4573
    if (hd_filename[0] == '\0' && boot_device == 'c') {
4574
        if (fd_filename[0] != '\0')
4575
            boot_device = 'a';
4576
        else
4577
            boot_device = 'd';
4578
    }
4579

    
4580
#if !defined(CONFIG_SOFTMMU)
4581
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4582
    {
4583
        static uint8_t stdout_buf[4096];
4584
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4585
    }
4586
#else
4587
    setvbuf(stdout, NULL, _IOLBF, 0);
4588
#endif
4589
    
4590
    /* init network clients */
4591
    if (nb_net_clients == 0) {
4592
        /* if no clients, we use a default config */
4593
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
4594
                "nic");
4595
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
4596
                "user");
4597
        nb_net_clients = 2;
4598
    }
4599

    
4600
    for(i = 0;i < nb_net_clients; i++) {
4601
        if (net_client_init(net_clients[i]) < 0)
4602
            exit(1);
4603
    }
4604

    
4605
    /* init the memory */
4606
    phys_ram_size = ram_size + vga_ram_size + bios_size;
4607

    
4608
#ifdef CONFIG_SOFTMMU
4609
    phys_ram_base = qemu_vmalloc(phys_ram_size);
4610
    if (!phys_ram_base) {
4611
        fprintf(stderr, "Could not allocate physical memory\n");
4612
        exit(1);
4613
    }
4614
#else
4615
    /* as we must map the same page at several addresses, we must use
4616
       a fd */
4617
    {
4618
        const char *tmpdir;
4619

    
4620
        tmpdir = getenv("QEMU_TMPDIR");
4621
        if (!tmpdir)
4622
            tmpdir = "/tmp";
4623
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4624
        if (mkstemp(phys_ram_file) < 0) {
4625
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
4626
                    phys_ram_file);
4627
            exit(1);
4628
        }
4629
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4630
        if (phys_ram_fd < 0) {
4631
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
4632
                    phys_ram_file);
4633
            exit(1);
4634
        }
4635
        ftruncate(phys_ram_fd, phys_ram_size);
4636
        unlink(phys_ram_file);
4637
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
4638
                             phys_ram_size, 
4639
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
4640
                             phys_ram_fd, 0);
4641
        if (phys_ram_base == MAP_FAILED) {
4642
            fprintf(stderr, "Could not map physical memory\n");
4643
            exit(1);
4644
        }
4645
    }
4646
#endif
4647

    
4648
    /* we always create the cdrom drive, even if no disk is there */
4649
    bdrv_init();
4650
    if (cdrom_index >= 0) {
4651
        bs_table[cdrom_index] = bdrv_new("cdrom");
4652
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4653
    }
4654

    
4655
    /* open the virtual block devices */
4656
    for(i = 0; i < MAX_DISKS; i++) {
4657
        if (hd_filename[i]) {
4658
            if (!bs_table[i]) {
4659
                char buf[64];
4660
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
4661
                bs_table[i] = bdrv_new(buf);
4662
            }
4663
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
4664
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
4665
                        hd_filename[i]);
4666
                exit(1);
4667
            }
4668
            if (i == 0 && cyls != 0) {
4669
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4670
                bdrv_set_translation_hint(bs_table[i], translation);
4671
            }
4672
        }
4673
    }
4674

    
4675
    /* we always create at least one floppy disk */
4676
    fd_table[0] = bdrv_new("fda");
4677
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
4678

    
4679
    for(i = 0; i < MAX_FD; i++) {
4680
        if (fd_filename[i]) {
4681
            if (!fd_table[i]) {
4682
                char buf[64];
4683
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
4684
                fd_table[i] = bdrv_new(buf);
4685
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
4686
            }
4687
            if (fd_filename[i] != '\0') {
4688
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
4689
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
4690
                            fd_filename[i]);
4691
                    exit(1);
4692
                }
4693
            }
4694
        }
4695
    }
4696

    
4697
    /* init USB devices */
4698
    if (usb_enabled) {
4699
        vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
4700
        for(i = 0; i < usb_devices_index; i++) {
4701
            if (usb_device_add(usb_devices[i]) < 0) {
4702
                fprintf(stderr, "Warning: could not add USB device %s\n",
4703
                        usb_devices[i]);
4704
            }
4705
        }
4706
    }
4707

    
4708
    register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
4709
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
4710

    
4711
    init_ioports();
4712
    cpu_calibrate_ticks();
4713

    
4714
    /* terminal init */
4715
    if (nographic) {
4716
        dumb_display_init(ds);
4717
    } else {
4718
#if defined(CONFIG_SDL)
4719
        sdl_display_init(ds, full_screen);
4720
#elif defined(CONFIG_COCOA)
4721
        cocoa_display_init(ds, full_screen);
4722
#else
4723
        dumb_display_init(ds);
4724
#endif
4725
    }
4726

    
4727
    vga_console = graphic_console_init(ds);
4728
    
4729
    monitor_hd = qemu_chr_open(monitor_device);
4730
    if (!monitor_hd) {
4731
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
4732
        exit(1);
4733
    }
4734
    monitor_init(monitor_hd, !nographic);
4735

    
4736
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4737
        if (serial_devices[i][0] != '\0') {
4738
            serial_hds[i] = qemu_chr_open(serial_devices[i]);
4739
            if (!serial_hds[i]) {
4740
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
4741
                        serial_devices[i]);
4742
                exit(1);
4743
            }
4744
            if (!strcmp(serial_devices[i], "vc"))
4745
                qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
4746
        }
4747
    }
4748

    
4749
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4750
        if (parallel_devices[i][0] != '\0') {
4751
            parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
4752
            if (!parallel_hds[i]) {
4753
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
4754
                        parallel_devices[i]);
4755
                exit(1);
4756
            }
4757
            if (!strcmp(parallel_devices[i], "vc"))
4758
                qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
4759
        }
4760
    }
4761

    
4762
    /* setup cpu signal handlers for MMU / self modifying code handling */
4763
#if !defined(CONFIG_SOFTMMU)
4764
    
4765
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4766
    {
4767
        stack_t stk;
4768
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
4769
        stk.ss_sp = signal_stack;
4770
        stk.ss_size = SIGNAL_STACK_SIZE;
4771
        stk.ss_flags = 0;
4772

    
4773
        if (sigaltstack(&stk, NULL) < 0) {
4774
            perror("sigaltstack");
4775
            exit(1);
4776
        }
4777
    }
4778
#endif
4779
    {
4780
        struct sigaction act;
4781
        
4782
        sigfillset(&act.sa_mask);
4783
        act.sa_flags = SA_SIGINFO;
4784
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4785
        act.sa_flags |= SA_ONSTACK;
4786
#endif
4787
        act.sa_sigaction = host_segv_handler;
4788
        sigaction(SIGSEGV, &act, NULL);
4789
        sigaction(SIGBUS, &act, NULL);
4790
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4791
        sigaction(SIGFPE, &act, NULL);
4792
#endif
4793
    }
4794
#endif
4795

    
4796
#ifndef _WIN32
4797
    {
4798
        struct sigaction act;
4799
        sigfillset(&act.sa_mask);
4800
        act.sa_flags = 0;
4801
        act.sa_handler = SIG_IGN;
4802
        sigaction(SIGPIPE, &act, NULL);
4803
    }
4804
#endif
4805
    init_timers();
4806

    
4807
    machine->init(ram_size, vga_ram_size, boot_device,
4808
                  ds, fd_filename, snapshot,
4809
                  kernel_filename, kernel_cmdline, initrd_filename);
4810

    
4811
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
4812
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
4813

    
4814
#ifdef CONFIG_GDBSTUB
4815
    if (use_gdbstub) {
4816
        if (gdbserver_start(gdbstub_port) < 0) {
4817
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
4818
                    gdbstub_port);
4819
            exit(1);
4820
        } else {
4821
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
4822
        }
4823
    } else 
4824
#endif
4825
    if (loadvm)
4826
        qemu_loadvm(loadvm);
4827

    
4828
    {
4829
        /* XXX: simplify init */
4830
        read_passwords();
4831
        if (start_emulation) {
4832
            vm_start();
4833
        }
4834
    }
4835
    main_loop();
4836
    quit_timers();
4837
    return 0;
4838
}