Statistics
| Branch: | Revision:

root / vl.c @ e9b137c2

History | View | Annotate | Download (70.8 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2004 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
#ifdef _BSD
42
#include <sys/stat.h>
43
#include <libutil.h>
44
#else
45
#include <linux/if.h>
46
#include <linux/if_tun.h>
47
#include <pty.h>
48
#include <malloc.h>
49
#include <linux/rtc.h>
50
#endif
51
#endif
52

    
53
#if defined(CONFIG_SLIRP)
54
#include "libslirp.h"
55
#endif
56

    
57
#ifdef _WIN32
58
#include <malloc.h>
59
#include <sys/timeb.h>
60
#include <windows.h>
61
#define getopt_long_only getopt_long
62
#define memalign(align, size) malloc(size)
63
#endif
64

    
65
#ifdef CONFIG_SDL
66
#if defined(__linux__)
67
/* SDL use the pthreads and they modify sigaction. We don't
68
   want that. */
69
#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
70
extern void __libc_sigaction();
71
#define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
72
#else
73
extern void __sigaction();
74
#define sigaction(sig, act, oact) __sigaction(sig, act, oact)
75
#endif
76
#endif /* __linux__ */
77
#endif /* CONFIG_SDL */
78

    
79
#include "disas.h"
80

    
81
#include "exec-all.h"
82

    
83
//#define DO_TB_FLUSH
84

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

    
87
//#define DEBUG_UNUSED_IOPORT
88
//#define DEBUG_IOPORT
89

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

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

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

    
107
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
108
char phys_ram_file[1024];
109
CPUState *global_env;
110
CPUState *cpu_single_env;
111
void *ioport_opaque[MAX_IOPORTS];
112
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
113
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
114
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
115
int vga_ram_size;
116
int bios_size;
117
static DisplayState display_state;
118
int nographic;
119
int64_t ticks_per_sec;
120
int boot_device = 'c';
121
int ram_size;
122
static char network_script[1024];
123
int pit_min_timer_count = 0;
124
int nb_nics;
125
NetDriverState nd_table[MAX_NICS];
126
SerialState *serial_console;
127
QEMUTimer *gui_timer;
128
int vm_running;
129
int audio_enabled = 0;
130
int pci_enabled = 1;
131
int prep_enabled = 0;
132
int rtc_utc = 1;
133
int cirrus_vga_enabled = 0;
134
int graphic_width = 640;
135
int graphic_height = 480;
136
int graphic_depth = 15;
137

    
138
/***********************************************************/
139
/* x86 ISA bus support */
140

    
141
target_phys_addr_t isa_mem_base = 0;
142

    
143
uint32_t default_ioport_readb(void *opaque, uint32_t address)
144
{
145
#ifdef DEBUG_UNUSED_IOPORT
146
    fprintf(stderr, "inb: port=0x%04x\n", address);
147
#endif
148
    return 0xff;
149
}
150

    
151
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
152
{
153
#ifdef DEBUG_UNUSED_IOPORT
154
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
155
#endif
156
}
157

    
158
/* default is to make two byte accesses */
159
uint32_t default_ioport_readw(void *opaque, uint32_t address)
160
{
161
    uint32_t data;
162
    data = ioport_read_table[0][address](ioport_opaque[address], address);
163
    address = (address + 1) & (MAX_IOPORTS - 1);
164
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
165
    return data;
166
}
167

    
168
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
169
{
170
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
171
    address = (address + 1) & (MAX_IOPORTS - 1);
172
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
173
}
174

    
175
uint32_t default_ioport_readl(void *opaque, uint32_t address)
176
{
177
#ifdef DEBUG_UNUSED_IOPORT
178
    fprintf(stderr, "inl: port=0x%04x\n", address);
179
#endif
180
    return 0xffffffff;
181
}
182

    
183
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
184
{
185
#ifdef DEBUG_UNUSED_IOPORT
186
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
187
#endif
188
}
189

    
190
void init_ioports(void)
191
{
192
    int i;
193

    
194
    for(i = 0; i < MAX_IOPORTS; i++) {
195
        ioport_read_table[0][i] = default_ioport_readb;
196
        ioport_write_table[0][i] = default_ioport_writeb;
197
        ioport_read_table[1][i] = default_ioport_readw;
198
        ioport_write_table[1][i] = default_ioport_writew;
199
        ioport_read_table[2][i] = default_ioport_readl;
200
        ioport_write_table[2][i] = default_ioport_writel;
201
    }
202
}
203

    
204
/* size is the word size in byte */
205
int register_ioport_read(int start, int length, int size, 
206
                         IOPortReadFunc *func, void *opaque)
207
{
208
    int i, bsize;
209

    
210
    if (size == 1) {
211
        bsize = 0;
212
    } else if (size == 2) {
213
        bsize = 1;
214
    } else if (size == 4) {
215
        bsize = 2;
216
    } else {
217
        hw_error("register_ioport_read: invalid size");
218
        return -1;
219
    }
220
    for(i = start; i < start + length; i += size) {
221
        ioport_read_table[bsize][i] = func;
222
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
223
            hw_error("register_ioport_read: invalid opaque");
224
        ioport_opaque[i] = opaque;
225
    }
226
    return 0;
227
}
228

    
229
/* size is the word size in byte */
230
int register_ioport_write(int start, int length, int size, 
231
                          IOPortWriteFunc *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_write: invalid size");
243
        return -1;
244
    }
245
    for(i = start; i < start + length; i += size) {
246
        ioport_write_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
void isa_unassign_ioport(int start, int length)
255
{
256
    int i;
257

    
258
    for(i = start; i < start + length; i++) {
259
        ioport_read_table[0][i] = default_ioport_readb;
260
        ioport_read_table[1][i] = default_ioport_readw;
261
        ioport_read_table[2][i] = default_ioport_readl;
262

    
263
        ioport_write_table[0][i] = default_ioport_writeb;
264
        ioport_write_table[1][i] = default_ioport_writew;
265
        ioport_write_table[2][i] = default_ioport_writel;
266
    }
267
}
268

    
269
void pstrcpy(char *buf, int buf_size, const char *str)
270
{
271
    int c;
272
    char *q = buf;
273

    
274
    if (buf_size <= 0)
275
        return;
276

    
277
    for(;;) {
278
        c = *str++;
279
        if (c == 0 || q >= buf + buf_size - 1)
280
            break;
281
        *q++ = c;
282
    }
283
    *q = '\0';
284
}
285

    
286
/* strcat and truncate. */
287
char *pstrcat(char *buf, int buf_size, const char *s)
288
{
289
    int len;
290
    len = strlen(buf);
291
    if (len < buf_size) 
292
        pstrcpy(buf + len, buf_size - len, s);
293
    return buf;
294
}
295

    
296
/* return the size or -1 if error */
297
int get_image_size(const char *filename)
298
{
299
    int fd, size;
300
    fd = open(filename, O_RDONLY | O_BINARY);
301
    if (fd < 0)
302
        return -1;
303
    size = lseek(fd, 0, SEEK_END);
304
    close(fd);
305
    return size;
306
}
307

    
308
/* return the size or -1 if error */
309
int load_image(const char *filename, uint8_t *addr)
310
{
311
    int fd, size;
312
    fd = open(filename, O_RDONLY | O_BINARY);
313
    if (fd < 0)
314
        return -1;
315
    size = lseek(fd, 0, SEEK_END);
316
    lseek(fd, 0, SEEK_SET);
317
    if (read(fd, addr, size) != size) {
318
        close(fd);
319
        return -1;
320
    }
321
    close(fd);
322
    return size;
323
}
324

    
325
void cpu_outb(CPUState *env, int addr, int val)
326
{
327
#ifdef DEBUG_IOPORT
328
    if (loglevel & CPU_LOG_IOPORT)
329
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
330
#endif    
331
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
332
}
333

    
334
void cpu_outw(CPUState *env, int addr, int val)
335
{
336
#ifdef DEBUG_IOPORT
337
    if (loglevel & CPU_LOG_IOPORT)
338
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
339
#endif    
340
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
341
}
342

    
343
void cpu_outl(CPUState *env, int addr, int val)
344
{
345
#ifdef DEBUG_IOPORT
346
    if (loglevel & CPU_LOG_IOPORT)
347
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
348
#endif
349
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
350
}
351

    
352
int cpu_inb(CPUState *env, int addr)
353
{
354
    int val;
355
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
356
#ifdef DEBUG_IOPORT
357
    if (loglevel & CPU_LOG_IOPORT)
358
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
359
#endif
360
    return val;
361
}
362

    
363
int cpu_inw(CPUState *env, int addr)
364
{
365
    int val;
366
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
367
#ifdef DEBUG_IOPORT
368
    if (loglevel & CPU_LOG_IOPORT)
369
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
370
#endif
371
    return val;
372
}
373

    
374
int cpu_inl(CPUState *env, int addr)
375
{
376
    int val;
377
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
378
#ifdef DEBUG_IOPORT
379
    if (loglevel & CPU_LOG_IOPORT)
380
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
381
#endif
382
    return val;
383
}
384

    
385
/***********************************************************/
386
void hw_error(const char *fmt, ...)
387
{
388
    va_list ap;
389

    
390
    va_start(ap, fmt);
391
    fprintf(stderr, "qemu: hardware error: ");
392
    vfprintf(stderr, fmt, ap);
393
    fprintf(stderr, "\n");
394
#ifdef TARGET_I386
395
    cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
396
#else
397
    cpu_dump_state(global_env, stderr, 0);
398
#endif
399
    va_end(ap);
400
    abort();
401
}
402

    
403
/***********************************************************/
404
/* keyboard/mouse */
405

    
406
static QEMUPutKBDEvent *qemu_put_kbd_event;
407
static void *qemu_put_kbd_event_opaque;
408
static QEMUPutMouseEvent *qemu_put_mouse_event;
409
static void *qemu_put_mouse_event_opaque;
410

    
411
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
412
{
413
    qemu_put_kbd_event_opaque = opaque;
414
    qemu_put_kbd_event = func;
415
}
416

    
417
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
418
{
419
    qemu_put_mouse_event_opaque = opaque;
420
    qemu_put_mouse_event = func;
421
}
422

    
423
void kbd_put_keycode(int keycode)
424
{
425
    if (qemu_put_kbd_event) {
426
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
427
    }
428
}
429

    
430
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
431
{
432
    if (qemu_put_mouse_event) {
433
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
434
                             dx, dy, dz, buttons_state);
435
    }
436
}
437

    
438
/***********************************************************/
439
/* timers */
440

    
441
#if defined(__powerpc__)
442

    
443
static inline uint32_t get_tbl(void) 
444
{
445
    uint32_t tbl;
446
    asm volatile("mftb %0" : "=r" (tbl));
447
    return tbl;
448
}
449

    
450
static inline uint32_t get_tbu(void) 
451
{
452
        uint32_t tbl;
453
        asm volatile("mftbu %0" : "=r" (tbl));
454
        return tbl;
455
}
456

    
457
int64_t cpu_get_real_ticks(void)
458
{
459
    uint32_t l, h, h1;
460
    /* NOTE: we test if wrapping has occurred */
461
    do {
462
        h = get_tbu();
463
        l = get_tbl();
464
        h1 = get_tbu();
465
    } while (h != h1);
466
    return ((int64_t)h << 32) | l;
467
}
468

    
469
#elif defined(__i386__)
470

    
471
int64_t cpu_get_real_ticks(void)
472
{
473
    int64_t val;
474
    asm volatile ("rdtsc" : "=A" (val));
475
    return val;
476
}
477

    
478
#elif defined(__x86_64__)
479

    
480
int64_t cpu_get_real_ticks(void)
481
{
482
    uint32_t low,high;
483
    int64_t val;
484
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
485
    val = high;
486
    val <<= 32;
487
    val |= low;
488
    return val;
489
}
490

    
491
#else
492
#error unsupported CPU
493
#endif
494

    
495
static int64_t cpu_ticks_offset;
496
static int cpu_ticks_enabled;
497

    
498
static inline int64_t cpu_get_ticks(void)
499
{
500
    if (!cpu_ticks_enabled) {
501
        return cpu_ticks_offset;
502
    } else {
503
        return cpu_get_real_ticks() + cpu_ticks_offset;
504
    }
505
}
506

    
507
/* enable cpu_get_ticks() */
508
void cpu_enable_ticks(void)
509
{
510
    if (!cpu_ticks_enabled) {
511
        cpu_ticks_offset -= cpu_get_real_ticks();
512
        cpu_ticks_enabled = 1;
513
    }
514
}
515

    
516
/* disable cpu_get_ticks() : the clock is stopped. You must not call
517
   cpu_get_ticks() after that.  */
518
void cpu_disable_ticks(void)
519
{
520
    if (cpu_ticks_enabled) {
521
        cpu_ticks_offset = cpu_get_ticks();
522
        cpu_ticks_enabled = 0;
523
    }
524
}
525

    
526
static int64_t get_clock(void)
527
{
528
#ifdef _WIN32
529
    struct _timeb tb;
530
    _ftime(&tb);
531
    return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
532
#else
533
    struct timeval tv;
534
    gettimeofday(&tv, NULL);
535
    return tv.tv_sec * 1000000LL + tv.tv_usec;
536
#endif
537
}
538

    
539
void cpu_calibrate_ticks(void)
540
{
541
    int64_t usec, ticks;
542

    
543
    usec = get_clock();
544
    ticks = cpu_get_real_ticks();
545
#ifdef _WIN32
546
    Sleep(50);
547
#else
548
    usleep(50 * 1000);
549
#endif
550
    usec = get_clock() - usec;
551
    ticks = cpu_get_real_ticks() - ticks;
552
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
553
}
554

    
555
/* compute with 96 bit intermediate result: (a*b)/c */
556
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
557
{
558
    union {
559
        uint64_t ll;
560
        struct {
561
#ifdef WORDS_BIGENDIAN
562
            uint32_t high, low;
563
#else
564
            uint32_t low, high;
565
#endif            
566
        } l;
567
    } u, res;
568
    uint64_t rl, rh;
569

    
570
    u.ll = a;
571
    rl = (uint64_t)u.l.low * (uint64_t)b;
572
    rh = (uint64_t)u.l.high * (uint64_t)b;
573
    rh += (rl >> 32);
574
    res.l.high = rh / c;
575
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
576
    return res.ll;
577
}
578

    
579
#define QEMU_TIMER_REALTIME 0
580
#define QEMU_TIMER_VIRTUAL  1
581

    
582
struct QEMUClock {
583
    int type;
584
    /* XXX: add frequency */
585
};
586

    
587
struct QEMUTimer {
588
    QEMUClock *clock;
589
    int64_t expire_time;
590
    QEMUTimerCB *cb;
591
    void *opaque;
592
    struct QEMUTimer *next;
593
};
594

    
595
QEMUClock *rt_clock;
596
QEMUClock *vm_clock;
597

    
598
static QEMUTimer *active_timers[2];
599
#ifdef _WIN32
600
static MMRESULT timerID;
601
#else
602
/* frequency of the times() clock tick */
603
static int timer_freq;
604
#endif
605

    
606
QEMUClock *qemu_new_clock(int type)
607
{
608
    QEMUClock *clock;
609
    clock = qemu_mallocz(sizeof(QEMUClock));
610
    if (!clock)
611
        return NULL;
612
    clock->type = type;
613
    return clock;
614
}
615

    
616
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
617
{
618
    QEMUTimer *ts;
619

    
620
    ts = qemu_mallocz(sizeof(QEMUTimer));
621
    ts->clock = clock;
622
    ts->cb = cb;
623
    ts->opaque = opaque;
624
    return ts;
625
}
626

    
627
void qemu_free_timer(QEMUTimer *ts)
628
{
629
    qemu_free(ts);
630
}
631

    
632
/* stop a timer, but do not dealloc it */
633
void qemu_del_timer(QEMUTimer *ts)
634
{
635
    QEMUTimer **pt, *t;
636

    
637
    /* NOTE: this code must be signal safe because
638
       qemu_timer_expired() can be called from a signal. */
639
    pt = &active_timers[ts->clock->type];
640
    for(;;) {
641
        t = *pt;
642
        if (!t)
643
            break;
644
        if (t == ts) {
645
            *pt = t->next;
646
            break;
647
        }
648
        pt = &t->next;
649
    }
650
}
651

    
652
/* modify the current timer so that it will be fired when current_time
653
   >= expire_time. The corresponding callback will be called. */
654
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
655
{
656
    QEMUTimer **pt, *t;
657

    
658
    qemu_del_timer(ts);
659

    
660
    /* add the timer in the sorted list */
661
    /* NOTE: this code must be signal safe because
662
       qemu_timer_expired() can be called from a signal. */
663
    pt = &active_timers[ts->clock->type];
664
    for(;;) {
665
        t = *pt;
666
        if (!t)
667
            break;
668
        if (t->expire_time > expire_time) 
669
            break;
670
        pt = &t->next;
671
    }
672
    ts->expire_time = expire_time;
673
    ts->next = *pt;
674
    *pt = ts;
675
}
676

    
677
int qemu_timer_pending(QEMUTimer *ts)
678
{
679
    QEMUTimer *t;
680
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
681
        if (t == ts)
682
            return 1;
683
    }
684
    return 0;
685
}
686

    
687
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
688
{
689
    if (!timer_head)
690
        return 0;
691
    return (timer_head->expire_time <= current_time);
692
}
693

    
694
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
695
{
696
    QEMUTimer *ts;
697
    
698
    for(;;) {
699
        ts = *ptimer_head;
700
        if (ts->expire_time > current_time)
701
            break;
702
        /* remove timer from the list before calling the callback */
703
        *ptimer_head = ts->next;
704
        ts->next = NULL;
705
        
706
        /* run the callback (the timer list can be modified) */
707
        ts->cb(ts->opaque);
708
    }
709
}
710

    
711
int64_t qemu_get_clock(QEMUClock *clock)
712
{
713
    switch(clock->type) {
714
    case QEMU_TIMER_REALTIME:
715
#ifdef _WIN32
716
        return GetTickCount();
717
#else
718
        {
719
            struct tms tp;
720

    
721
            /* Note that using gettimeofday() is not a good solution
722
               for timers because its value change when the date is
723
               modified. */
724
            if (timer_freq == 100) {
725
                return times(&tp) * 10;
726
            } else {
727
                return ((int64_t)times(&tp) * 1000) / timer_freq;
728
            }
729
        }
730
#endif
731
    default:
732
    case QEMU_TIMER_VIRTUAL:
733
        return cpu_get_ticks();
734
    }
735
}
736

    
737
/* save a timer */
738
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
739
{
740
    uint64_t expire_time;
741

    
742
    if (qemu_timer_pending(ts)) {
743
        expire_time = ts->expire_time;
744
    } else {
745
        expire_time = -1;
746
    }
747
    qemu_put_be64(f, expire_time);
748
}
749

    
750
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
751
{
752
    uint64_t expire_time;
753

    
754
    expire_time = qemu_get_be64(f);
755
    if (expire_time != -1) {
756
        qemu_mod_timer(ts, expire_time);
757
    } else {
758
        qemu_del_timer(ts);
759
    }
760
}
761

    
762
static void timer_save(QEMUFile *f, void *opaque)
763
{
764
    if (cpu_ticks_enabled) {
765
        hw_error("cannot save state if virtual timers are running");
766
    }
767
    qemu_put_be64s(f, &cpu_ticks_offset);
768
    qemu_put_be64s(f, &ticks_per_sec);
769
}
770

    
771
static int timer_load(QEMUFile *f, void *opaque, int version_id)
772
{
773
    if (version_id != 1)
774
        return -EINVAL;
775
    if (cpu_ticks_enabled) {
776
        return -EINVAL;
777
    }
778
    qemu_get_be64s(f, &cpu_ticks_offset);
779
    qemu_get_be64s(f, &ticks_per_sec);
780
    return 0;
781
}
782

    
783
#ifdef _WIN32
784
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
785
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
786
#else
787
static void host_alarm_handler(int host_signum)
788
#endif
789
{
790
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
791
                           qemu_get_clock(vm_clock)) ||
792
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
793
                           qemu_get_clock(rt_clock))) {
794
        /* stop the cpu because a timer occured */
795
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
796
    }
797
}
798

    
799
#ifndef _WIN32
800

    
801
#if defined(__linux__)
802

    
803
#define RTC_FREQ 1024
804

    
805
static int rtc_fd;
806

    
807
static int start_rtc_timer(void)
808
{
809
    rtc_fd = open("/dev/rtc", O_RDONLY);
810
    if (rtc_fd < 0)
811
        return -1;
812
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
813
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
814
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
815
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
816
        goto fail;
817
    }
818
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
819
    fail:
820
        close(rtc_fd);
821
        return -1;
822
    }
823
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
824
    return 0;
825
}
826

    
827
#else
828

    
829
static int start_rtc_timer(void)
830
{
831
    return -1;
832
}
833

    
834
#endif /* !defined(__linux__) */
835

    
836
#endif /* !defined(_WIN32) */
837

    
838
static void init_timers(void)
839
{
840
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
841
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
842

    
843
#ifdef _WIN32
844
    {
845
        int count=0;
846
        timerID = timeSetEvent(10,    // interval (ms)
847
                               0,     // resolution
848
                               host_alarm_handler, // function
849
                               (DWORD)&count,  // user parameter
850
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
851
         if( !timerID ) {
852
            perror("failed timer alarm");
853
            exit(1);
854
         }
855
    }
856
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
857
#else
858
    {
859
        struct sigaction act;
860
        struct itimerval itv;
861
        
862
        /* get times() syscall frequency */
863
        timer_freq = sysconf(_SC_CLK_TCK);
864
        
865
        /* timer signal */
866
        sigfillset(&act.sa_mask);
867
        act.sa_flags = 0;
868
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
869
        act.sa_flags |= SA_ONSTACK;
870
#endif
871
        act.sa_handler = host_alarm_handler;
872
        sigaction(SIGALRM, &act, NULL);
873

    
874
        itv.it_interval.tv_sec = 0;
875
        itv.it_interval.tv_usec = 1000;
876
        itv.it_value.tv_sec = 0;
877
        itv.it_value.tv_usec = 10 * 1000;
878
        setitimer(ITIMER_REAL, &itv, NULL);
879
        /* we probe the tick duration of the kernel to inform the user if
880
           the emulated kernel requested a too high timer frequency */
881
        getitimer(ITIMER_REAL, &itv);
882

    
883
        if (itv.it_interval.tv_usec > 1000) {
884
            /* try to use /dev/rtc to have a faster timer */
885
            if (start_rtc_timer() < 0)
886
                goto use_itimer;
887
            /* disable itimer */
888
            itv.it_interval.tv_sec = 0;
889
            itv.it_interval.tv_usec = 0;
890
            itv.it_value.tv_sec = 0;
891
            itv.it_value.tv_usec = 0;
892
            setitimer(ITIMER_REAL, &itv, NULL);
893

    
894
            /* use the RTC */
895
            sigaction(SIGIO, &act, NULL);
896
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
897
            fcntl(rtc_fd, F_SETOWN, getpid());
898
        } else {
899
        use_itimer:
900
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
901
                                   PIT_FREQ) / 1000000;
902
        }
903
    }
904
#endif
905
}
906

    
907
void quit_timers(void)
908
{
909
#ifdef _WIN32
910
    timeKillEvent(timerID);
911
#endif
912
}
913

    
914
/***********************************************************/
915
/* serial device */
916

    
917
#ifdef _WIN32
918

    
919
int serial_open_device(void)
920
{
921
    return -1;
922
}
923

    
924
#else
925

    
926
int serial_open_device(void)
927
{
928
    char slave_name[1024];
929
    int master_fd, slave_fd;
930

    
931
    if (serial_console == NULL && nographic) {
932
        /* use console for serial port */
933
        return 0;
934
    } else {
935
#if 0
936
        /* Not satisfying */
937
        if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
938
            fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
939
            return -1;
940
        }
941
        fprintf(stderr, "Serial port redirected to %s\n", slave_name);
942
        return master_fd;
943
#else
944
        return -1;
945
#endif
946
    }
947
}
948

    
949
#endif
950

    
951
/***********************************************************/
952
/* Linux network device redirectors */
953

    
954
void hex_dump(FILE *f, const uint8_t *buf, int size)
955
{
956
    int len, i, j, c;
957

    
958
    for(i=0;i<size;i+=16) {
959
        len = size - i;
960
        if (len > 16)
961
            len = 16;
962
        fprintf(f, "%08x ", i);
963
        for(j=0;j<16;j++) {
964
            if (j < len)
965
                fprintf(f, " %02x", buf[i+j]);
966
            else
967
                fprintf(f, "   ");
968
        }
969
        fprintf(f, " ");
970
        for(j=0;j<len;j++) {
971
            c = buf[i+j];
972
            if (c < ' ' || c > '~')
973
                c = '.';
974
            fprintf(f, "%c", c);
975
        }
976
        fprintf(f, "\n");
977
    }
978
}
979

    
980
void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
981
{
982
    nd->send_packet(nd, buf, size);
983
}
984

    
985
void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
986
                          IOReadHandler *fd_read, void *opaque)
987
{
988
    nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
989
}
990

    
991
/* dummy network adapter */
992

    
993
static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
994
{
995
}
996

    
997
static void dummy_add_read_packet(NetDriverState *nd, 
998
                                  IOCanRWHandler *fd_can_read, 
999
                                  IOReadHandler *fd_read, void *opaque)
1000
{
1001
}
1002

    
1003
static int net_dummy_init(NetDriverState *nd)
1004
{
1005
    nd->send_packet = dummy_send_packet;
1006
    nd->add_read_packet = dummy_add_read_packet;
1007
    pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1008
    return 0;
1009
}
1010

    
1011
#if defined(CONFIG_SLIRP)
1012

    
1013
/* slirp network adapter */
1014

    
1015
static void *slirp_fd_opaque;
1016
static IOCanRWHandler *slirp_fd_can_read;
1017
static IOReadHandler *slirp_fd_read;
1018
static int slirp_inited;
1019

    
1020
int slirp_can_output(void)
1021
{
1022
    return slirp_fd_can_read(slirp_fd_opaque);
1023
}
1024

    
1025
void slirp_output(const uint8_t *pkt, int pkt_len)
1026
{
1027
#if 0
1028
    printf("output:\n");
1029
    hex_dump(stdout, pkt, pkt_len);
1030
#endif
1031
    slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1032
}
1033

    
1034
static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1035
{
1036
#if 0
1037
    printf("input:\n");
1038
    hex_dump(stdout, buf, size);
1039
#endif
1040
    slirp_input(buf, size);
1041
}
1042

    
1043
static void slirp_add_read_packet(NetDriverState *nd, 
1044
                                  IOCanRWHandler *fd_can_read, 
1045
                                  IOReadHandler *fd_read, void *opaque)
1046
{
1047
    slirp_fd_opaque = opaque;
1048
    slirp_fd_can_read = fd_can_read;
1049
    slirp_fd_read = fd_read;
1050
}
1051

    
1052
static int net_slirp_init(NetDriverState *nd)
1053
{
1054
    if (!slirp_inited) {
1055
        slirp_inited = 1;
1056
        slirp_init();
1057
    }
1058
    nd->send_packet = slirp_send_packet;
1059
    nd->add_read_packet = slirp_add_read_packet;
1060
    pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1061
    return 0;
1062
}
1063

    
1064
#endif /* CONFIG_SLIRP */
1065

    
1066
#if !defined(_WIN32)
1067
#ifdef _BSD
1068
static int tun_open(char *ifname, int ifname_size)
1069
{
1070
    int fd;
1071
    char *dev;
1072
    struct stat s;
1073

    
1074
    fd = open("/dev/tap", O_RDWR);
1075
    if (fd < 0) {
1076
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1077
        return -1;
1078
    }
1079

    
1080
    fstat(fd, &s);
1081
    dev = devname(s.st_rdev, S_IFCHR);
1082
    pstrcpy(ifname, ifname_size, dev);
1083

    
1084
    fcntl(fd, F_SETFL, O_NONBLOCK);
1085
    return fd;
1086
}
1087
#else
1088
static int tun_open(char *ifname, int ifname_size)
1089
{
1090
    struct ifreq ifr;
1091
    int fd, ret;
1092
    
1093
    fd = open("/dev/net/tun", O_RDWR);
1094
    if (fd < 0) {
1095
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1096
        return -1;
1097
    }
1098
    memset(&ifr, 0, sizeof(ifr));
1099
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1100
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1101
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1102
    if (ret != 0) {
1103
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1104
        close(fd);
1105
        return -1;
1106
    }
1107
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
1108
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
1109
    fcntl(fd, F_SETFL, O_NONBLOCK);
1110
    return fd;
1111
}
1112
#endif
1113

    
1114
static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1115
{
1116
    write(nd->fd, buf, size);
1117
}
1118

    
1119
static void tun_add_read_packet(NetDriverState *nd, 
1120
                                IOCanRWHandler *fd_can_read, 
1121
                                IOReadHandler *fd_read, void *opaque)
1122
{
1123
    qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1124
}
1125

    
1126
static int net_tun_init(NetDriverState *nd)
1127
{
1128
    int pid, status;
1129
    char *args[3];
1130
    char **parg;
1131

    
1132
    nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1133
    if (nd->fd < 0)
1134
        return -1;
1135

    
1136
    /* try to launch network init script */
1137
    pid = fork();
1138
    if (pid >= 0) {
1139
        if (pid == 0) {
1140
            parg = args;
1141
            *parg++ = network_script;
1142
            *parg++ = nd->ifname;
1143
            *parg++ = NULL;
1144
            execv(network_script, args);
1145
            exit(1);
1146
        }
1147
        while (waitpid(pid, &status, 0) != pid);
1148
        if (!WIFEXITED(status) ||
1149
            WEXITSTATUS(status) != 0) {
1150
            fprintf(stderr, "%s: could not launch network script\n",
1151
                    network_script);
1152
        }
1153
    }
1154
    nd->send_packet = tun_send_packet;
1155
    nd->add_read_packet = tun_add_read_packet;
1156
    return 0;
1157
}
1158

    
1159
static int net_fd_init(NetDriverState *nd, int fd)
1160
{
1161
    nd->fd = fd;
1162
    nd->send_packet = tun_send_packet;
1163
    nd->add_read_packet = tun_add_read_packet;
1164
    pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1165
    return 0;
1166
}
1167

    
1168
#endif /* !_WIN32 */
1169

    
1170
/***********************************************************/
1171
/* dumb display */
1172

    
1173
#ifdef _WIN32
1174

    
1175
static void term_exit(void)
1176
{
1177
}
1178

    
1179
static void term_init(void)
1180
{
1181
}
1182

    
1183
#else
1184

    
1185
/* init terminal so that we can grab keys */
1186
static struct termios oldtty;
1187

    
1188
static void term_exit(void)
1189
{
1190
    tcsetattr (0, TCSANOW, &oldtty);
1191
}
1192

    
1193
static void term_init(void)
1194
{
1195
    struct termios tty;
1196

    
1197
    tcgetattr (0, &tty);
1198
    oldtty = tty;
1199

    
1200
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1201
                          |INLCR|IGNCR|ICRNL|IXON);
1202
    tty.c_oflag |= OPOST;
1203
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1204
    /* if graphical mode, we allow Ctrl-C handling */
1205
    if (nographic)
1206
        tty.c_lflag &= ~ISIG;
1207
    tty.c_cflag &= ~(CSIZE|PARENB);
1208
    tty.c_cflag |= CS8;
1209
    tty.c_cc[VMIN] = 1;
1210
    tty.c_cc[VTIME] = 0;
1211
    
1212
    tcsetattr (0, TCSANOW, &tty);
1213

    
1214
    atexit(term_exit);
1215

    
1216
    fcntl(0, F_SETFL, O_NONBLOCK);
1217
}
1218

    
1219
#endif
1220

    
1221
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1222
{
1223
}
1224

    
1225
static void dumb_resize(DisplayState *ds, int w, int h)
1226
{
1227
}
1228

    
1229
static void dumb_refresh(DisplayState *ds)
1230
{
1231
    vga_update_display();
1232
}
1233

    
1234
void dumb_display_init(DisplayState *ds)
1235
{
1236
    ds->data = NULL;
1237
    ds->linesize = 0;
1238
    ds->depth = 0;
1239
    ds->dpy_update = dumb_update;
1240
    ds->dpy_resize = dumb_resize;
1241
    ds->dpy_refresh = dumb_refresh;
1242
}
1243

    
1244
#if !defined(CONFIG_SOFTMMU)
1245
/***********************************************************/
1246
/* cpu signal handler */
1247
static void host_segv_handler(int host_signum, siginfo_t *info, 
1248
                              void *puc)
1249
{
1250
    if (cpu_signal_handler(host_signum, info, puc))
1251
        return;
1252
    term_exit();
1253
    abort();
1254
}
1255
#endif
1256

    
1257
/***********************************************************/
1258
/* I/O handling */
1259

    
1260
#define MAX_IO_HANDLERS 64
1261

    
1262
typedef struct IOHandlerRecord {
1263
    int fd;
1264
    IOCanRWHandler *fd_can_read;
1265
    IOReadHandler *fd_read;
1266
    void *opaque;
1267
    /* temporary data */
1268
    struct pollfd *ufd;
1269
    int max_size;
1270
    struct IOHandlerRecord *next;
1271
} IOHandlerRecord;
1272

    
1273
static IOHandlerRecord *first_io_handler;
1274

    
1275
int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1276
                             IOReadHandler *fd_read, void *opaque)
1277
{
1278
    IOHandlerRecord *ioh;
1279

    
1280
    ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1281
    if (!ioh)
1282
        return -1;
1283
    ioh->fd = fd;
1284
    ioh->fd_can_read = fd_can_read;
1285
    ioh->fd_read = fd_read;
1286
    ioh->opaque = opaque;
1287
    ioh->next = first_io_handler;
1288
    first_io_handler = ioh;
1289
    return 0;
1290
}
1291

    
1292
void qemu_del_fd_read_handler(int fd)
1293
{
1294
    IOHandlerRecord **pioh, *ioh;
1295

    
1296
    pioh = &first_io_handler;
1297
    for(;;) {
1298
        ioh = *pioh;
1299
        if (ioh == NULL)
1300
            break;
1301
        if (ioh->fd == fd) {
1302
            *pioh = ioh->next;
1303
            break;
1304
        }
1305
        pioh = &ioh->next;
1306
    }
1307
}
1308

    
1309
/***********************************************************/
1310
/* savevm/loadvm support */
1311

    
1312
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1313
{
1314
    fwrite(buf, 1, size, f);
1315
}
1316

    
1317
void qemu_put_byte(QEMUFile *f, int v)
1318
{
1319
    fputc(v, f);
1320
}
1321

    
1322
void qemu_put_be16(QEMUFile *f, unsigned int v)
1323
{
1324
    qemu_put_byte(f, v >> 8);
1325
    qemu_put_byte(f, v);
1326
}
1327

    
1328
void qemu_put_be32(QEMUFile *f, unsigned int v)
1329
{
1330
    qemu_put_byte(f, v >> 24);
1331
    qemu_put_byte(f, v >> 16);
1332
    qemu_put_byte(f, v >> 8);
1333
    qemu_put_byte(f, v);
1334
}
1335

    
1336
void qemu_put_be64(QEMUFile *f, uint64_t v)
1337
{
1338
    qemu_put_be32(f, v >> 32);
1339
    qemu_put_be32(f, v);
1340
}
1341

    
1342
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1343
{
1344
    return fread(buf, 1, size, f);
1345
}
1346

    
1347
int qemu_get_byte(QEMUFile *f)
1348
{
1349
    int v;
1350
    v = fgetc(f);
1351
    if (v == EOF)
1352
        return 0;
1353
    else
1354
        return v;
1355
}
1356

    
1357
unsigned int qemu_get_be16(QEMUFile *f)
1358
{
1359
    unsigned int v;
1360
    v = qemu_get_byte(f) << 8;
1361
    v |= qemu_get_byte(f);
1362
    return v;
1363
}
1364

    
1365
unsigned int qemu_get_be32(QEMUFile *f)
1366
{
1367
    unsigned int v;
1368
    v = qemu_get_byte(f) << 24;
1369
    v |= qemu_get_byte(f) << 16;
1370
    v |= qemu_get_byte(f) << 8;
1371
    v |= qemu_get_byte(f);
1372
    return v;
1373
}
1374

    
1375
uint64_t qemu_get_be64(QEMUFile *f)
1376
{
1377
    uint64_t v;
1378
    v = (uint64_t)qemu_get_be32(f) << 32;
1379
    v |= qemu_get_be32(f);
1380
    return v;
1381
}
1382

    
1383
int64_t qemu_ftell(QEMUFile *f)
1384
{
1385
    return ftell(f);
1386
}
1387

    
1388
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1389
{
1390
    if (fseek(f, pos, whence) < 0)
1391
        return -1;
1392
    return ftell(f);
1393
}
1394

    
1395
typedef struct SaveStateEntry {
1396
    char idstr[256];
1397
    int instance_id;
1398
    int version_id;
1399
    SaveStateHandler *save_state;
1400
    LoadStateHandler *load_state;
1401
    void *opaque;
1402
    struct SaveStateEntry *next;
1403
} SaveStateEntry;
1404

    
1405
static SaveStateEntry *first_se;
1406

    
1407
int register_savevm(const char *idstr, 
1408
                    int instance_id, 
1409
                    int version_id,
1410
                    SaveStateHandler *save_state,
1411
                    LoadStateHandler *load_state,
1412
                    void *opaque)
1413
{
1414
    SaveStateEntry *se, **pse;
1415

    
1416
    se = qemu_malloc(sizeof(SaveStateEntry));
1417
    if (!se)
1418
        return -1;
1419
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1420
    se->instance_id = instance_id;
1421
    se->version_id = version_id;
1422
    se->save_state = save_state;
1423
    se->load_state = load_state;
1424
    se->opaque = opaque;
1425
    se->next = NULL;
1426

    
1427
    /* add at the end of list */
1428
    pse = &first_se;
1429
    while (*pse != NULL)
1430
        pse = &(*pse)->next;
1431
    *pse = se;
1432
    return 0;
1433
}
1434

    
1435
#define QEMU_VM_FILE_MAGIC   0x5145564d
1436
#define QEMU_VM_FILE_VERSION 0x00000001
1437

    
1438
int qemu_savevm(const char *filename)
1439
{
1440
    SaveStateEntry *se;
1441
    QEMUFile *f;
1442
    int len, len_pos, cur_pos, saved_vm_running, ret;
1443

    
1444
    saved_vm_running = vm_running;
1445
    vm_stop(0);
1446

    
1447
    f = fopen(filename, "wb");
1448
    if (!f) {
1449
        ret = -1;
1450
        goto the_end;
1451
    }
1452

    
1453
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1454
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1455

    
1456
    for(se = first_se; se != NULL; se = se->next) {
1457
        /* ID string */
1458
        len = strlen(se->idstr);
1459
        qemu_put_byte(f, len);
1460
        qemu_put_buffer(f, se->idstr, len);
1461

    
1462
        qemu_put_be32(f, se->instance_id);
1463
        qemu_put_be32(f, se->version_id);
1464

    
1465
        /* record size: filled later */
1466
        len_pos = ftell(f);
1467
        qemu_put_be32(f, 0);
1468
        
1469
        se->save_state(f, se->opaque);
1470

    
1471
        /* fill record size */
1472
        cur_pos = ftell(f);
1473
        len = ftell(f) - len_pos - 4;
1474
        fseek(f, len_pos, SEEK_SET);
1475
        qemu_put_be32(f, len);
1476
        fseek(f, cur_pos, SEEK_SET);
1477
    }
1478

    
1479
    fclose(f);
1480
    ret = 0;
1481
 the_end:
1482
    if (saved_vm_running)
1483
        vm_start();
1484
    return ret;
1485
}
1486

    
1487
static SaveStateEntry *find_se(const char *idstr, int instance_id)
1488
{
1489
    SaveStateEntry *se;
1490

    
1491
    for(se = first_se; se != NULL; se = se->next) {
1492
        if (!strcmp(se->idstr, idstr) && 
1493
            instance_id == se->instance_id)
1494
            return se;
1495
    }
1496
    return NULL;
1497
}
1498

    
1499
int qemu_loadvm(const char *filename)
1500
{
1501
    SaveStateEntry *se;
1502
    QEMUFile *f;
1503
    int len, cur_pos, ret, instance_id, record_len, version_id;
1504
    int saved_vm_running;
1505
    unsigned int v;
1506
    char idstr[256];
1507
    
1508
    saved_vm_running = vm_running;
1509
    vm_stop(0);
1510

    
1511
    f = fopen(filename, "rb");
1512
    if (!f) {
1513
        ret = -1;
1514
        goto the_end;
1515
    }
1516

    
1517
    v = qemu_get_be32(f);
1518
    if (v != QEMU_VM_FILE_MAGIC)
1519
        goto fail;
1520
    v = qemu_get_be32(f);
1521
    if (v != QEMU_VM_FILE_VERSION) {
1522
    fail:
1523
        fclose(f);
1524
        ret = -1;
1525
        goto the_end;
1526
    }
1527
    for(;;) {
1528
#if defined (DO_TB_FLUSH)
1529
        tb_flush(global_env);
1530
#endif
1531
        len = qemu_get_byte(f);
1532
        if (feof(f))
1533
            break;
1534
        qemu_get_buffer(f, idstr, len);
1535
        idstr[len] = '\0';
1536
        instance_id = qemu_get_be32(f);
1537
        version_id = qemu_get_be32(f);
1538
        record_len = qemu_get_be32(f);
1539
#if 0
1540
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1541
               idstr, instance_id, version_id, record_len);
1542
#endif
1543
        cur_pos = ftell(f);
1544
        se = find_se(idstr, instance_id);
1545
        if (!se) {
1546
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1547
                    instance_id, idstr);
1548
        } else {
1549
            ret = se->load_state(f, se->opaque, version_id);
1550
            if (ret < 0) {
1551
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1552
                        instance_id, idstr);
1553
            }
1554
        }
1555
        /* always seek to exact end of record */
1556
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1557
    }
1558
    fclose(f);
1559
    ret = 0;
1560
 the_end:
1561
    if (saved_vm_running)
1562
        vm_start();
1563
    return ret;
1564
}
1565

    
1566
/***********************************************************/
1567
/* cpu save/restore */
1568

    
1569
#if defined(TARGET_I386)
1570

    
1571
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1572
{
1573
    qemu_put_be32(f, (uint32_t)dt->base);
1574
    qemu_put_be32(f, dt->limit);
1575
    qemu_put_be32(f, dt->flags);
1576
}
1577

    
1578
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1579
{
1580
    dt->base = (uint8_t *)qemu_get_be32(f);
1581
    dt->limit = qemu_get_be32(f);
1582
    dt->flags = qemu_get_be32(f);
1583
}
1584

    
1585
void cpu_save(QEMUFile *f, void *opaque)
1586
{
1587
    CPUState *env = opaque;
1588
    uint16_t fptag, fpus, fpuc;
1589
    uint32_t hflags;
1590
    int i;
1591

    
1592
    for(i = 0; i < 8; i++)
1593
        qemu_put_be32s(f, &env->regs[i]);
1594
    qemu_put_be32s(f, &env->eip);
1595
    qemu_put_be32s(f, &env->eflags);
1596
    qemu_put_be32s(f, &env->eflags);
1597
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1598
    qemu_put_be32s(f, &hflags);
1599
    
1600
    /* FPU */
1601
    fpuc = env->fpuc;
1602
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1603
    fptag = 0;
1604
    for (i=7; i>=0; i--) {
1605
        fptag <<= 2;
1606
        if (env->fptags[i]) {
1607
            fptag |= 3;
1608
        }
1609
    }
1610
    
1611
    qemu_put_be16s(f, &fpuc);
1612
    qemu_put_be16s(f, &fpus);
1613
    qemu_put_be16s(f, &fptag);
1614

    
1615
    for(i = 0; i < 8; i++) {
1616
        uint64_t mant;
1617
        uint16_t exp;
1618
        cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1619
        qemu_put_be64(f, mant);
1620
        qemu_put_be16(f, exp);
1621
    }
1622

    
1623
    for(i = 0; i < 6; i++)
1624
        cpu_put_seg(f, &env->segs[i]);
1625
    cpu_put_seg(f, &env->ldt);
1626
    cpu_put_seg(f, &env->tr);
1627
    cpu_put_seg(f, &env->gdt);
1628
    cpu_put_seg(f, &env->idt);
1629
    
1630
    qemu_put_be32s(f, &env->sysenter_cs);
1631
    qemu_put_be32s(f, &env->sysenter_esp);
1632
    qemu_put_be32s(f, &env->sysenter_eip);
1633
    
1634
    qemu_put_be32s(f, &env->cr[0]);
1635
    qemu_put_be32s(f, &env->cr[2]);
1636
    qemu_put_be32s(f, &env->cr[3]);
1637
    qemu_put_be32s(f, &env->cr[4]);
1638
    
1639
    for(i = 0; i < 8; i++)
1640
        qemu_put_be32s(f, &env->dr[i]);
1641

    
1642
    /* MMU */
1643
    qemu_put_be32s(f, &env->a20_mask);
1644
}
1645

    
1646
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1647
{
1648
    CPUState *env = opaque;
1649
    int i;
1650
    uint32_t hflags;
1651
    uint16_t fpus, fpuc, fptag;
1652

    
1653
    if (version_id != 1)
1654
        return -EINVAL;
1655
    for(i = 0; i < 8; i++)
1656
        qemu_get_be32s(f, &env->regs[i]);
1657
    qemu_get_be32s(f, &env->eip);
1658
    qemu_get_be32s(f, &env->eflags);
1659
    qemu_get_be32s(f, &env->eflags);
1660
    qemu_get_be32s(f, &hflags);
1661

    
1662
    qemu_get_be16s(f, &fpuc);
1663
    qemu_get_be16s(f, &fpus);
1664
    qemu_get_be16s(f, &fptag);
1665

    
1666
    for(i = 0; i < 8; i++) {
1667
        uint64_t mant;
1668
        uint16_t exp;
1669
        mant = qemu_get_be64(f);
1670
        exp = qemu_get_be16(f);
1671
        env->fpregs[i] = cpu_set_fp80(mant, exp);
1672
    }
1673

    
1674
    env->fpuc = fpuc;
1675
    env->fpstt = (fpus >> 11) & 7;
1676
    env->fpus = fpus & ~0x3800;
1677
    for(i = 0; i < 8; i++) {
1678
        env->fptags[i] = ((fptag & 3) == 3);
1679
        fptag >>= 2;
1680
    }
1681
    
1682
    for(i = 0; i < 6; i++)
1683
        cpu_get_seg(f, &env->segs[i]);
1684
    cpu_get_seg(f, &env->ldt);
1685
    cpu_get_seg(f, &env->tr);
1686
    cpu_get_seg(f, &env->gdt);
1687
    cpu_get_seg(f, &env->idt);
1688
    
1689
    qemu_get_be32s(f, &env->sysenter_cs);
1690
    qemu_get_be32s(f, &env->sysenter_esp);
1691
    qemu_get_be32s(f, &env->sysenter_eip);
1692
    
1693
    qemu_get_be32s(f, &env->cr[0]);
1694
    qemu_get_be32s(f, &env->cr[2]);
1695
    qemu_get_be32s(f, &env->cr[3]);
1696
    qemu_get_be32s(f, &env->cr[4]);
1697
    
1698
    for(i = 0; i < 8; i++)
1699
        qemu_get_be32s(f, &env->dr[i]);
1700

    
1701
    /* MMU */
1702
    qemu_get_be32s(f, &env->a20_mask);
1703

    
1704
    /* XXX: compute hflags from scratch, except for CPL and IIF */
1705
    env->hflags = hflags;
1706
    tlb_flush(env, 1);
1707
    return 0;
1708
}
1709

    
1710
#elif defined(TARGET_PPC)
1711
void cpu_save(QEMUFile *f, void *opaque)
1712
{
1713
}
1714

    
1715
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1716
{
1717
    return 0;
1718
}
1719
#else
1720

    
1721
#warning No CPU save/restore functions
1722

    
1723
#endif
1724

    
1725
/***********************************************************/
1726
/* ram save/restore */
1727

    
1728
/* we just avoid storing empty pages */
1729
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1730
{
1731
    int i, v;
1732

    
1733
    v = buf[0];
1734
    for(i = 1; i < len; i++) {
1735
        if (buf[i] != v)
1736
            goto normal_save;
1737
    }
1738
    qemu_put_byte(f, 1);
1739
    qemu_put_byte(f, v);
1740
    return;
1741
 normal_save:
1742
    qemu_put_byte(f, 0); 
1743
    qemu_put_buffer(f, buf, len);
1744
}
1745

    
1746
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1747
{
1748
    int v;
1749

    
1750
    v = qemu_get_byte(f);
1751
    switch(v) {
1752
    case 0:
1753
        if (qemu_get_buffer(f, buf, len) != len)
1754
            return -EIO;
1755
        break;
1756
    case 1:
1757
        v = qemu_get_byte(f);
1758
        memset(buf, v, len);
1759
        break;
1760
    default:
1761
        return -EINVAL;
1762
    }
1763
    return 0;
1764
}
1765

    
1766
static void ram_save(QEMUFile *f, void *opaque)
1767
{
1768
    int i;
1769
    qemu_put_be32(f, phys_ram_size);
1770
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1771
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1772
    }
1773
}
1774

    
1775
static int ram_load(QEMUFile *f, void *opaque, int version_id)
1776
{
1777
    int i, ret;
1778

    
1779
    if (version_id != 1)
1780
        return -EINVAL;
1781
    if (qemu_get_be32(f) != phys_ram_size)
1782
        return -EINVAL;
1783
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1784
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1785
        if (ret)
1786
            return ret;
1787
    }
1788
    return 0;
1789
}
1790

    
1791
/***********************************************************/
1792
/* main execution loop */
1793

    
1794
void gui_update(void *opaque)
1795
{
1796
    display_state.dpy_refresh(&display_state);
1797
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1798
}
1799

    
1800
/* XXX: support several handlers */
1801
VMStopHandler *vm_stop_cb;
1802
VMStopHandler *vm_stop_opaque;
1803

    
1804
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1805
{
1806
    vm_stop_cb = cb;
1807
    vm_stop_opaque = opaque;
1808
    return 0;
1809
}
1810

    
1811
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1812
{
1813
    vm_stop_cb = NULL;
1814
}
1815

    
1816
void vm_start(void)
1817
{
1818
    if (!vm_running) {
1819
        cpu_enable_ticks();
1820
        vm_running = 1;
1821
    }
1822
}
1823

    
1824
void vm_stop(int reason) 
1825
{
1826
    if (vm_running) {
1827
        cpu_disable_ticks();
1828
        vm_running = 0;
1829
        if (reason != 0) {
1830
            if (vm_stop_cb) {
1831
                vm_stop_cb(vm_stop_opaque, reason);
1832
            }
1833
        }
1834
    }
1835
}
1836

    
1837
/* reset/shutdown handler */
1838

    
1839
typedef struct QEMUResetEntry {
1840
    QEMUResetHandler *func;
1841
    void *opaque;
1842
    struct QEMUResetEntry *next;
1843
} QEMUResetEntry;
1844

    
1845
static QEMUResetEntry *first_reset_entry;
1846
static int reset_requested;
1847
static int shutdown_requested;
1848

    
1849
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1850
{
1851
    QEMUResetEntry **pre, *re;
1852

    
1853
    pre = &first_reset_entry;
1854
    while (*pre != NULL)
1855
        pre = &(*pre)->next;
1856
    re = qemu_mallocz(sizeof(QEMUResetEntry));
1857
    re->func = func;
1858
    re->opaque = opaque;
1859
    re->next = NULL;
1860
    *pre = re;
1861
}
1862

    
1863
void qemu_system_reset(void)
1864
{
1865
    QEMUResetEntry *re;
1866

    
1867
    /* reset all devices */
1868
    for(re = first_reset_entry; re != NULL; re = re->next) {
1869
        re->func(re->opaque);
1870
    }
1871
}
1872

    
1873
void qemu_system_reset_request(void)
1874
{
1875
    reset_requested = 1;
1876
    cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1877
}
1878

    
1879
void qemu_system_shutdown_request(void)
1880
{
1881
    shutdown_requested = 1;
1882
    cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1883
}
1884

    
1885
static void main_cpu_reset(void *opaque)
1886
{
1887
#ifdef TARGET_I386
1888
    CPUState *env = opaque;
1889
    cpu_reset(env);
1890
#endif
1891
}
1892

    
1893
int main_loop(void)
1894
{
1895
#ifndef _WIN32
1896
    struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1897
    IOHandlerRecord *ioh, *ioh_next;
1898
    uint8_t buf[4096];
1899
    int n, max_size;
1900
#endif
1901
    int ret, timeout;
1902
    CPUState *env = global_env;
1903

    
1904
    for(;;) {
1905
        if (vm_running) {
1906
            ret = cpu_exec(env);
1907
            if (shutdown_requested) {
1908
                ret = EXCP_INTERRUPT; 
1909
                break;
1910
            }
1911
            if (reset_requested) {
1912
                reset_requested = 0;
1913
                qemu_system_reset();
1914
                ret = EXCP_INTERRUPT; 
1915
            }
1916
            if (ret == EXCP_DEBUG) {
1917
                vm_stop(EXCP_DEBUG);
1918
            }
1919
            /* if hlt instruction, we wait until the next IRQ */
1920
            /* XXX: use timeout computed from timers */
1921
            if (ret == EXCP_HLT) 
1922
                timeout = 10;
1923
            else
1924
                timeout = 0;
1925
        } else {
1926
            timeout = 10;
1927
        }
1928

    
1929
#ifdef _WIN32
1930
        if (timeout > 0)
1931
            Sleep(timeout);
1932
#else
1933

    
1934
        /* poll any events */
1935
        /* XXX: separate device handlers from system ones */
1936
        pf = ufds;
1937
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1938
            if (!ioh->fd_can_read) {
1939
                max_size = 0;
1940
                pf->fd = ioh->fd;
1941
                pf->events = POLLIN;
1942
                ioh->ufd = pf;
1943
                pf++;
1944
            } else {
1945
                max_size = ioh->fd_can_read(ioh->opaque);
1946
                if (max_size > 0) {
1947
                    if (max_size > sizeof(buf))
1948
                        max_size = sizeof(buf);
1949
                    pf->fd = ioh->fd;
1950
                    pf->events = POLLIN;
1951
                    ioh->ufd = pf;
1952
                    pf++;
1953
                } else {
1954
                    ioh->ufd = NULL;
1955
                }
1956
            }
1957
            ioh->max_size = max_size;
1958
        }
1959
        
1960
        ret = poll(ufds, pf - ufds, timeout);
1961
        if (ret > 0) {
1962
            /* XXX: better handling of removal */
1963
            for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1964
                ioh_next = ioh->next;
1965
                pf = ioh->ufd;
1966
                if (pf) {
1967
                    if (pf->revents & POLLIN) {
1968
                        if (ioh->max_size == 0) {
1969
                            /* just a read event */
1970
                            ioh->fd_read(ioh->opaque, NULL, 0);
1971
                        } else {
1972
                            n = read(ioh->fd, buf, ioh->max_size);
1973
                            if (n >= 0) {
1974
                                ioh->fd_read(ioh->opaque, buf, n);
1975
                            } else if (errno != EAGAIN) {
1976
                                ioh->fd_read(ioh->opaque, NULL, -errno);
1977
                            }
1978
                        }
1979
                    }
1980
                }
1981
            }
1982
        }
1983

    
1984
#if defined(CONFIG_SLIRP)
1985
        /* XXX: merge with poll() */
1986
        if (slirp_inited) {
1987
            fd_set rfds, wfds, xfds;
1988
            int nfds;
1989
            struct timeval tv;
1990

    
1991
            nfds = -1;
1992
            FD_ZERO(&rfds);
1993
            FD_ZERO(&wfds);
1994
            FD_ZERO(&xfds);
1995
            slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1996
            tv.tv_sec = 0;
1997
            tv.tv_usec = 0;
1998
            ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1999
            if (ret >= 0) {
2000
                slirp_select_poll(&rfds, &wfds, &xfds);
2001
            }
2002
        }
2003
#endif
2004

    
2005
#endif
2006

    
2007
        if (vm_running) {
2008
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
2009
                            qemu_get_clock(vm_clock));
2010
            
2011
            if (audio_enabled) {
2012
                /* XXX: add explicit timer */
2013
                SB16_run();
2014
            }
2015
            
2016
            /* run dma transfers, if any */
2017
            DMA_run();
2018
        }
2019

    
2020
        /* real time timers */
2021
        qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
2022
                        qemu_get_clock(rt_clock));
2023
    }
2024
    cpu_disable_ticks();
2025
    return ret;
2026
}
2027

    
2028
void help(void)
2029
{
2030
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2031
           "usage: %s [options] [disk_image]\n"
2032
           "\n"
2033
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2034
           "\n"
2035
           "Standard options:\n"
2036
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
2037
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
2038
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
2039
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2040
           "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
2041
           "-snapshot       write to temporary files instead of disk image files\n"
2042
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
2043
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
2044
           "-enable-audio   enable audio support\n"
2045
           "-localtime      set the real time clock to local time [default=utc]\n"
2046
#ifdef TARGET_PPC
2047
           "-prep           Simulate a PREP system (default is PowerMAC)\n"
2048
           "-g WxH[xDEPTH]  Set the initial VGA graphic mode\n"
2049
#endif
2050
           "\n"
2051
           "Network options:\n"
2052
           "-nics n         simulate 'n' network cards [default=1]\n"
2053
           "-macaddr addr   set the mac address of the first interface\n"
2054
           "-n script       set tap/tun network init script [default=%s]\n"
2055
           "-tun-fd fd      use this fd as already opened tap/tun interface\n"
2056
#ifdef CONFIG_SLIRP
2057
           "-user-net       use user mode network stack [default if no tap/tun script]\n"
2058
#endif
2059
           "-dummy-net      use dummy network stack\n"
2060
           "\n"
2061
           "Linux boot specific:\n"
2062
           "-kernel bzImage use 'bzImage' as kernel image\n"
2063
           "-append cmdline use 'cmdline' as kernel command line\n"
2064
           "-initrd file    use 'file' as initial ram disk\n"
2065
           "\n"
2066
           "Debug/Expert options:\n"
2067
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
2068
           "-s              wait gdb connection to port %d\n"
2069
           "-p port         change gdb connection port\n"
2070
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
2071
           "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
2072
           "-L path         set the directory for the BIOS and VGA BIOS\n"
2073
#ifdef USE_CODE_COPY
2074
           "-no-code-copy   disable code copy acceleration\n"
2075
#endif
2076
#ifdef TARGET_I386
2077
           "-isa            simulate an ISA-only system (default is PCI system)\n"
2078
#endif
2079
           "\n"
2080
           "During emulation, use C-a h to get terminal commands:\n",
2081
#ifdef CONFIG_SOFTMMU
2082
           "qemu",
2083
#else
2084
           "qemu-fast",
2085
#endif
2086
           DEFAULT_RAM_SIZE,
2087
           DEFAULT_NETWORK_SCRIPT,
2088
           DEFAULT_GDBSTUB_PORT,
2089
           "/tmp/qemu.log");
2090
    term_print_help();
2091
#ifndef CONFIG_SOFTMMU
2092
    printf("\n"
2093
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2094
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2095
           "PC emulation.\n");
2096
#endif
2097
    exit(1);
2098
}
2099

    
2100
#define HAS_ARG 0x0001
2101

    
2102
enum {
2103
    QEMU_OPTION_h,
2104

    
2105
    QEMU_OPTION_fda,
2106
    QEMU_OPTION_fdb,
2107
    QEMU_OPTION_hda,
2108
    QEMU_OPTION_hdb,
2109
    QEMU_OPTION_hdc,
2110
    QEMU_OPTION_hdd,
2111
    QEMU_OPTION_cdrom,
2112
    QEMU_OPTION_boot,
2113
    QEMU_OPTION_snapshot,
2114
    QEMU_OPTION_m,
2115
    QEMU_OPTION_nographic,
2116
    QEMU_OPTION_enable_audio,
2117

    
2118
    QEMU_OPTION_nics,
2119
    QEMU_OPTION_macaddr,
2120
    QEMU_OPTION_n,
2121
    QEMU_OPTION_tun_fd,
2122
    QEMU_OPTION_user_net,
2123
    QEMU_OPTION_dummy_net,
2124

    
2125
    QEMU_OPTION_kernel,
2126
    QEMU_OPTION_append,
2127
    QEMU_OPTION_initrd,
2128

    
2129
    QEMU_OPTION_S,
2130
    QEMU_OPTION_s,
2131
    QEMU_OPTION_p,
2132
    QEMU_OPTION_d,
2133
    QEMU_OPTION_hdachs,
2134
    QEMU_OPTION_L,
2135
    QEMU_OPTION_no_code_copy,
2136
    QEMU_OPTION_pci,
2137
    QEMU_OPTION_isa,
2138
    QEMU_OPTION_prep,
2139
    QEMU_OPTION_localtime,
2140
    QEMU_OPTION_cirrusvga,
2141
    QEMU_OPTION_g,
2142
};
2143

    
2144
typedef struct QEMUOption {
2145
    const char *name;
2146
    int flags;
2147
    int index;
2148
} QEMUOption;
2149

    
2150
const QEMUOption qemu_options[] = {
2151
    { "h", 0, QEMU_OPTION_h },
2152

    
2153
    { "fda", HAS_ARG, QEMU_OPTION_fda },
2154
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2155
    { "hda", HAS_ARG, QEMU_OPTION_hda },
2156
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2157
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2158
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2159
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2160
    { "boot", HAS_ARG, QEMU_OPTION_boot },
2161
    { "snapshot", 0, QEMU_OPTION_snapshot },
2162
    { "m", HAS_ARG, QEMU_OPTION_m },
2163
    { "nographic", 0, QEMU_OPTION_nographic },
2164
    { "enable-audio", 0, QEMU_OPTION_enable_audio },
2165

    
2166
    { "nics", HAS_ARG, QEMU_OPTION_nics},
2167
    { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2168
    { "n", HAS_ARG, QEMU_OPTION_n },
2169
    { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2170
#ifdef CONFIG_SLIRP
2171
    { "user-net", 0, QEMU_OPTION_user_net },
2172
#endif
2173
    { "dummy-net", 0, QEMU_OPTION_dummy_net },
2174

    
2175
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2176
    { "append", HAS_ARG, QEMU_OPTION_append },
2177
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2178

    
2179
    { "S", 0, QEMU_OPTION_S },
2180
    { "s", 0, QEMU_OPTION_s },
2181
    { "p", HAS_ARG, QEMU_OPTION_p },
2182
    { "d", HAS_ARG, QEMU_OPTION_d },
2183
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2184
    { "L", HAS_ARG, QEMU_OPTION_L },
2185
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2186
#ifdef TARGET_PPC
2187
    { "prep", 0, QEMU_OPTION_prep },
2188
    { "g", 1, QEMU_OPTION_g },
2189
#endif
2190
    { "localtime", 0, QEMU_OPTION_localtime },
2191
    { "isa", 0, QEMU_OPTION_isa },
2192

    
2193
    /* temporary options */
2194
    { "pci", 0, QEMU_OPTION_pci },
2195
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2196
    { NULL },
2197
};
2198

    
2199
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2200

    
2201
/* this stack is only used during signal handling */
2202
#define SIGNAL_STACK_SIZE 32768
2203

    
2204
static uint8_t *signal_stack;
2205

    
2206
#endif
2207

    
2208
#define NET_IF_TUN   0
2209
#define NET_IF_USER  1
2210
#define NET_IF_DUMMY 2
2211

    
2212
int main(int argc, char **argv)
2213
{
2214
#ifdef CONFIG_GDBSTUB
2215
    int use_gdbstub, gdbstub_port;
2216
#endif
2217
    int i, has_cdrom;
2218
    int snapshot, linux_boot;
2219
    CPUState *env;
2220
    const char *initrd_filename;
2221
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2222
    const char *kernel_filename, *kernel_cmdline;
2223
    DisplayState *ds = &display_state;
2224
    int cyls, heads, secs;
2225
    int start_emulation = 1;
2226
    uint8_t macaddr[6];
2227
    int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2228
    int optind;
2229
    const char *r, *optarg;
2230

    
2231
#if !defined(CONFIG_SOFTMMU)
2232
    /* we never want that malloc() uses mmap() */
2233
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2234
#endif
2235
    initrd_filename = NULL;
2236
    for(i = 0; i < MAX_FD; i++)
2237
        fd_filename[i] = NULL;
2238
    for(i = 0; i < MAX_DISKS; i++)
2239
        hd_filename[i] = NULL;
2240
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2241
    vga_ram_size = VGA_RAM_SIZE;
2242
    bios_size = BIOS_SIZE;
2243
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2244
#ifdef CONFIG_GDBSTUB
2245
    use_gdbstub = 0;
2246
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
2247
#endif
2248
    snapshot = 0;
2249
    nographic = 0;
2250
    kernel_filename = NULL;
2251
    kernel_cmdline = "";
2252
    has_cdrom = 1;
2253
    cyls = heads = secs = 0;
2254

    
2255
    nb_tun_fds = 0;
2256
    net_if_type = -1;
2257
    nb_nics = 1;
2258
    /* default mac address of the first network interface */
2259
    macaddr[0] = 0x52;
2260
    macaddr[1] = 0x54;
2261
    macaddr[2] = 0x00;
2262
    macaddr[3] = 0x12;
2263
    macaddr[4] = 0x34;
2264
    macaddr[5] = 0x56;
2265

    
2266
    optind = 1;
2267
    for(;;) {
2268
        if (optind >= argc)
2269
            break;
2270
        r = argv[optind];
2271
        if (r[0] != '-') {
2272
            hd_filename[0] = argv[optind++];
2273
        } else {
2274
            const QEMUOption *popt;
2275

    
2276
            optind++;
2277
            popt = qemu_options;
2278
            for(;;) {
2279
                if (!popt->name) {
2280
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
2281
                            argv[0], r);
2282
                    exit(1);
2283
                }
2284
                if (!strcmp(popt->name, r + 1))
2285
                    break;
2286
                popt++;
2287
            }
2288
            if (popt->flags & HAS_ARG) {
2289
                if (optind >= argc) {
2290
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
2291
                            argv[0], r);
2292
                    exit(1);
2293
                }
2294
                optarg = argv[optind++];
2295
            } else {
2296
                optarg = NULL;
2297
            }
2298

    
2299
            switch(popt->index) {
2300
            case QEMU_OPTION_initrd:
2301
                initrd_filename = optarg;
2302
                break;
2303
            case QEMU_OPTION_hda:
2304
                hd_filename[0] = optarg;
2305
                break;
2306
            case QEMU_OPTION_hdb:
2307
                hd_filename[1] = optarg;
2308
                break;
2309
            case QEMU_OPTION_snapshot:
2310
                snapshot = 1;
2311
                break;
2312
            case QEMU_OPTION_hdachs:
2313
                {
2314
                    const char *p;
2315
                    p = optarg;
2316
                    cyls = strtol(p, (char **)&p, 0);
2317
                    if (*p != ',')
2318
                        goto chs_fail;
2319
                    p++;
2320
                    heads = strtol(p, (char **)&p, 0);
2321
                    if (*p != ',')
2322
                        goto chs_fail;
2323
                    p++;
2324
                    secs = strtol(p, (char **)&p, 0);
2325
                    if (*p != '\0') {
2326
                    chs_fail:
2327
                        cyls = 0;
2328
                    }
2329
                }
2330
                break;
2331
            case QEMU_OPTION_nographic:
2332
                nographic = 1;
2333
                break;
2334
            case QEMU_OPTION_kernel:
2335
                kernel_filename = optarg;
2336
                break;
2337
            case QEMU_OPTION_append:
2338
                kernel_cmdline = optarg;
2339
                break;
2340
            case QEMU_OPTION_tun_fd:
2341
                {
2342
                    const char *p;
2343
                    int fd;
2344
                    net_if_type = NET_IF_TUN;
2345
                    if (nb_tun_fds < MAX_NICS) {
2346
                        fd = strtol(optarg, (char **)&p, 0);
2347
                        if (*p != '\0') {
2348
                            fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2349
                            exit(1);
2350
                        }
2351
                        tun_fds[nb_tun_fds++] = fd;
2352
                    }
2353
                }
2354
                break;
2355
            case QEMU_OPTION_hdc:
2356
                hd_filename[2] = optarg;
2357
                has_cdrom = 0;
2358
                break;
2359
            case QEMU_OPTION_hdd:
2360
                hd_filename[3] = optarg;
2361
                break;
2362
            case QEMU_OPTION_cdrom:
2363
                hd_filename[2] = optarg;
2364
                has_cdrom = 1;
2365
                break;
2366
            case QEMU_OPTION_boot:
2367
                boot_device = optarg[0];
2368
                if (boot_device != 'a' && boot_device != 'b' &&
2369
                    boot_device != 'c' && boot_device != 'd') {
2370
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2371
                    exit(1);
2372
                }
2373
                break;
2374
            case QEMU_OPTION_fda:
2375
                fd_filename[0] = optarg;
2376
                break;
2377
            case QEMU_OPTION_fdb:
2378
                fd_filename[1] = optarg;
2379
                break;
2380
            case QEMU_OPTION_no_code_copy:
2381
                code_copy_enabled = 0;
2382
                break;
2383
            case QEMU_OPTION_nics:
2384
                nb_nics = atoi(optarg);
2385
                if (nb_nics < 0 || nb_nics > MAX_NICS) {
2386
                    fprintf(stderr, "qemu: invalid number of network interfaces\n");
2387
                    exit(1);
2388
                }
2389
                break;
2390
            case QEMU_OPTION_macaddr:
2391
                {
2392
                    const char *p;
2393
                    int i;
2394
                    p = optarg;
2395
                    for(i = 0; i < 6; i++) {
2396
                        macaddr[i] = strtol(p, (char **)&p, 16);
2397
                        if (i == 5) {
2398
                            if (*p != '\0') 
2399
                                goto macaddr_error;
2400
                        } else {
2401
                            if (*p != ':') {
2402
                            macaddr_error:
2403
                                fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2404
                                exit(1);
2405
                            }
2406
                            p++;
2407
                        }
2408
                    }
2409
                }
2410
                break;
2411
            case QEMU_OPTION_user_net:
2412
                net_if_type = NET_IF_USER;
2413
                break;
2414
            case QEMU_OPTION_dummy_net:
2415
                net_if_type = NET_IF_DUMMY;
2416
                break;
2417
            case QEMU_OPTION_enable_audio:
2418
                audio_enabled = 1;
2419
                break;
2420
            case QEMU_OPTION_h:
2421
                help();
2422
                break;
2423
            case QEMU_OPTION_m:
2424
                ram_size = atoi(optarg) * 1024 * 1024;
2425
                if (ram_size <= 0)
2426
                    help();
2427
                if (ram_size > PHYS_RAM_MAX_SIZE) {
2428
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2429
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
2430
                    exit(1);
2431
                }
2432
                break;
2433
            case QEMU_OPTION_d:
2434
                {
2435
                    int mask;
2436
                    CPULogItem *item;
2437
                    
2438
                    mask = cpu_str_to_log_mask(optarg);
2439
                    if (!mask) {
2440
                        printf("Log items (comma separated):\n");
2441
                    for(item = cpu_log_items; item->mask != 0; item++) {
2442
                        printf("%-10s %s\n", item->name, item->help);
2443
                    }
2444
                    exit(1);
2445
                    }
2446
                    cpu_set_log(mask);
2447
                }
2448
                break;
2449
            case QEMU_OPTION_n:
2450
                pstrcpy(network_script, sizeof(network_script), optarg);
2451
                break;
2452
#ifdef CONFIG_GDBSTUB
2453
            case QEMU_OPTION_s:
2454
                use_gdbstub = 1;
2455
                break;
2456
            case QEMU_OPTION_p:
2457
                gdbstub_port = atoi(optarg);
2458
                break;
2459
#endif
2460
            case QEMU_OPTION_L:
2461
                bios_dir = optarg;
2462
                break;
2463
            case QEMU_OPTION_S:
2464
                start_emulation = 0;
2465
                break;
2466
            case QEMU_OPTION_pci:
2467
                pci_enabled = 1;
2468
                break;
2469
            case QEMU_OPTION_isa:
2470
                pci_enabled = 0;
2471
                break;
2472
            case QEMU_OPTION_prep:
2473
                prep_enabled = 1;
2474
                break;
2475
            case QEMU_OPTION_localtime:
2476
                rtc_utc = 0;
2477
                break;
2478
            case QEMU_OPTION_cirrusvga:
2479
                cirrus_vga_enabled = 1;
2480
                break;
2481
            case QEMU_OPTION_g:
2482
                {
2483
                    const char *p;
2484
                    int w, h, depth;
2485
                    p = optarg;
2486
                    w = strtol(p, (char **)&p, 10);
2487
                    if (w <= 0) {
2488
                    graphic_error:
2489
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
2490
                        exit(1);
2491
                    }
2492
                    if (*p != 'x')
2493
                        goto graphic_error;
2494
                    p++;
2495
                    h = strtol(p, (char **)&p, 10);
2496
                    if (h <= 0)
2497
                        goto graphic_error;
2498
                    if (*p == 'x') {
2499
                        p++;
2500
                        depth = strtol(p, (char **)&p, 10);
2501
                        if (depth != 8 && depth != 15 && depth != 16 && 
2502
                            depth != 24 && depth != 32)
2503
                            goto graphic_error;
2504
                    } else if (*p == '\0') {
2505
                        depth = graphic_depth;
2506
                    } else {
2507
                        goto graphic_error;
2508
                    }
2509
                    
2510
                    graphic_width = w;
2511
                    graphic_height = h;
2512
                    graphic_depth = depth;
2513
                }
2514
                break;
2515
            }
2516
        }
2517
    }
2518

    
2519
    linux_boot = (kernel_filename != NULL);
2520
        
2521
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2522
        fd_filename[0] == '\0')
2523
        help();
2524
    
2525
    /* boot to cd by default if no hard disk */
2526
    if (hd_filename[0] == '\0' && boot_device == 'c') {
2527
        if (fd_filename[0] != '\0')
2528
            boot_device = 'a';
2529
        else
2530
            boot_device = 'd';
2531
    }
2532

    
2533
#if !defined(CONFIG_SOFTMMU)
2534
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2535
    {
2536
        static uint8_t stdout_buf[4096];
2537
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2538
    }
2539
#else
2540
    setvbuf(stdout, NULL, _IOLBF, 0);
2541
#endif
2542

    
2543
    /* init host network redirectors */
2544
    if (net_if_type == -1) {
2545
        net_if_type = NET_IF_TUN;
2546
#if defined(CONFIG_SLIRP)
2547
        if (access(network_script, R_OK) < 0) {
2548
            net_if_type = NET_IF_USER;
2549
        }
2550
#endif
2551
    }
2552

    
2553
    for(i = 0; i < nb_nics; i++) {
2554
        NetDriverState *nd = &nd_table[i];
2555
        nd->index = i;
2556
        /* init virtual mac address */
2557
        nd->macaddr[0] = macaddr[0];
2558
        nd->macaddr[1] = macaddr[1];
2559
        nd->macaddr[2] = macaddr[2];
2560
        nd->macaddr[3] = macaddr[3];
2561
        nd->macaddr[4] = macaddr[4];
2562
        nd->macaddr[5] = macaddr[5] + i;
2563
        switch(net_if_type) {
2564
#if defined(CONFIG_SLIRP)
2565
        case NET_IF_USER:
2566
            net_slirp_init(nd);
2567
            break;
2568
#endif
2569
#if !defined(_WIN32)
2570
        case NET_IF_TUN:
2571
            if (i < nb_tun_fds) {
2572
                net_fd_init(nd, tun_fds[i]);
2573
            } else {
2574
                if (net_tun_init(nd) < 0)
2575
                    net_dummy_init(nd);
2576
            }
2577
            break;
2578
#endif
2579
        case NET_IF_DUMMY:
2580
        default:
2581
            net_dummy_init(nd);
2582
            break;
2583
        }
2584
    }
2585

    
2586
    /* init the memory */
2587
    phys_ram_size = ram_size + vga_ram_size + bios_size;
2588

    
2589
#ifdef CONFIG_SOFTMMU
2590
#ifdef _BSD
2591
    /* mallocs are always aligned on BSD. */
2592
    phys_ram_base = malloc(phys_ram_size);
2593
#else
2594
    phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2595
#endif
2596
    if (!phys_ram_base) {
2597
        fprintf(stderr, "Could not allocate physical memory\n");
2598
        exit(1);
2599
    }
2600
#else
2601
    /* as we must map the same page at several addresses, we must use
2602
       a fd */
2603
    {
2604
        const char *tmpdir;
2605

    
2606
        tmpdir = getenv("QEMU_TMPDIR");
2607
        if (!tmpdir)
2608
            tmpdir = "/tmp";
2609
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2610
        if (mkstemp(phys_ram_file) < 0) {
2611
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2612
                    phys_ram_file);
2613
            exit(1);
2614
        }
2615
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2616
        if (phys_ram_fd < 0) {
2617
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2618
                    phys_ram_file);
2619
            exit(1);
2620
        }
2621
        ftruncate(phys_ram_fd, phys_ram_size);
2622
        unlink(phys_ram_file);
2623
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2624
                             phys_ram_size, 
2625
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2626
                             phys_ram_fd, 0);
2627
        if (phys_ram_base == MAP_FAILED) {
2628
            fprintf(stderr, "Could not map physical memory\n");
2629
            exit(1);
2630
        }
2631
    }
2632
#endif
2633

    
2634
    /* we always create the cdrom drive, even if no disk is there */
2635
    if (has_cdrom) {
2636
        bs_table[2] = bdrv_new("cdrom");
2637
        bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2638
    }
2639

    
2640
    /* open the virtual block devices */
2641
    for(i = 0; i < MAX_DISKS; i++) {
2642
        if (hd_filename[i]) {
2643
            if (!bs_table[i]) {
2644
                char buf[64];
2645
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2646
                bs_table[i] = bdrv_new(buf);
2647
            }
2648
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2649
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2650
                        hd_filename[i]);
2651
                exit(1);
2652
            }
2653
            if (i == 0 && cyls != 0) 
2654
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2655
        }
2656
    }
2657

    
2658
    /* we always create at least one floppy disk */
2659
    fd_table[0] = bdrv_new("fda");
2660
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2661

    
2662
    for(i = 0; i < MAX_FD; i++) {
2663
        if (fd_filename[i]) {
2664
            if (!fd_table[i]) {
2665
                char buf[64];
2666
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2667
                fd_table[i] = bdrv_new(buf);
2668
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2669
            }
2670
            if (fd_filename[i] != '\0') {
2671
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2672
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2673
                            fd_filename[i]);
2674
                    exit(1);
2675
                }
2676
            }
2677
        }
2678
    }
2679

    
2680
    /* init CPU state */
2681
    env = cpu_init();
2682
    global_env = env;
2683
    cpu_single_env = env;
2684

    
2685
    register_savevm("timer", 0, 1, timer_save, timer_load, env);
2686
    register_savevm("cpu", 0, 1, cpu_save, cpu_load, env);
2687
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2688
    qemu_register_reset(main_cpu_reset, global_env);
2689

    
2690
    init_ioports();
2691
    cpu_calibrate_ticks();
2692

    
2693
    /* terminal init */
2694
    if (nographic) {
2695
        dumb_display_init(ds);
2696
    } else {
2697
#ifdef CONFIG_SDL
2698
        sdl_display_init(ds);
2699
#else
2700
        dumb_display_init(ds);
2701
#endif
2702
    }
2703

    
2704
    /* setup cpu signal handlers for MMU / self modifying code handling */
2705
#if !defined(CONFIG_SOFTMMU)
2706
    
2707
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2708
    {
2709
        stack_t stk;
2710
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2711
        stk.ss_sp = signal_stack;
2712
        stk.ss_size = SIGNAL_STACK_SIZE;
2713
        stk.ss_flags = 0;
2714

    
2715
        if (sigaltstack(&stk, NULL) < 0) {
2716
            perror("sigaltstack");
2717
            exit(1);
2718
        }
2719
    }
2720
#endif
2721
    {
2722
        struct sigaction act;
2723
        
2724
        sigfillset(&act.sa_mask);
2725
        act.sa_flags = SA_SIGINFO;
2726
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2727
        act.sa_flags |= SA_ONSTACK;
2728
#endif
2729
        act.sa_sigaction = host_segv_handler;
2730
        sigaction(SIGSEGV, &act, NULL);
2731
        sigaction(SIGBUS, &act, NULL);
2732
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2733
        sigaction(SIGFPE, &act, NULL);
2734
#endif
2735
    }
2736
#endif
2737

    
2738
#ifndef _WIN32
2739
    {
2740
        struct sigaction act;
2741
        sigfillset(&act.sa_mask);
2742
        act.sa_flags = 0;
2743
        act.sa_handler = SIG_IGN;
2744
        sigaction(SIGPIPE, &act, NULL);
2745
    }
2746
#endif
2747
    init_timers();
2748

    
2749
#if defined(TARGET_I386)
2750
    pc_init(ram_size, vga_ram_size, boot_device,
2751
            ds, fd_filename, snapshot,
2752
            kernel_filename, kernel_cmdline, initrd_filename);
2753
#elif defined(TARGET_PPC)
2754
    ppc_init(ram_size, vga_ram_size, boot_device,
2755
             ds, fd_filename, snapshot,
2756
             kernel_filename, kernel_cmdline, initrd_filename);
2757
#endif
2758

    
2759
    /* launched after the device init so that it can display or not a
2760
       banner */
2761
    monitor_init();
2762

    
2763
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2764
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2765

    
2766
#ifdef CONFIG_GDBSTUB
2767
    if (use_gdbstub) {
2768
        if (gdbserver_start(gdbstub_port) < 0) {
2769
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
2770
                    gdbstub_port);
2771
            exit(1);
2772
        } else {
2773
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
2774
        }
2775
    } else 
2776
#endif
2777
    if (start_emulation)
2778
    {
2779
        vm_start();
2780
    }
2781
    term_init();
2782
    main_loop();
2783
    quit_timers();
2784
    return 0;
2785
}