Statistics
| Branch: | Revision:

root / vl.c @ a1968d71

History | View | Annotate | Download (72 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 0
791
#define DISP_FREQ 1000
792
    {
793
        static int64_t delta_min = INT64_MAX;
794
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
795
        static int count;
796
        ti = qemu_get_clock(vm_clock);
797
        if (last_clock != 0) {
798
            delta = ti - last_clock;
799
            if (delta < delta_min)
800
                delta_min = delta;
801
            if (delta > delta_max)
802
                delta_max = delta;
803
            delta_cum += delta;
804
            if (++count == DISP_FREQ) {
805
                printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
806
                       muldiv64(delta_min, 1000000, ticks_per_sec),
807
                       muldiv64(delta_max, 1000000, ticks_per_sec),
808
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
809
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
810
                count = 0;
811
                delta_min = INT64_MAX;
812
                delta_max = 0;
813
                delta_cum = 0;
814
            }
815
        }
816
        last_clock = ti;
817
    }
818
#endif
819
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
820
                           qemu_get_clock(vm_clock)) ||
821
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
822
                           qemu_get_clock(rt_clock))) {
823
        /* stop the cpu because a timer occured */
824
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
825
    }
826
}
827

    
828
#ifndef _WIN32
829

    
830
#if defined(__linux__)
831

    
832
#define RTC_FREQ 1024
833

    
834
static int rtc_fd;
835

    
836
static int start_rtc_timer(void)
837
{
838
    rtc_fd = open("/dev/rtc", O_RDONLY);
839
    if (rtc_fd < 0)
840
        return -1;
841
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
842
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
843
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
844
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
845
        goto fail;
846
    }
847
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
848
    fail:
849
        close(rtc_fd);
850
        return -1;
851
    }
852
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
853
    return 0;
854
}
855

    
856
#else
857

    
858
static int start_rtc_timer(void)
859
{
860
    return -1;
861
}
862

    
863
#endif /* !defined(__linux__) */
864

    
865
#endif /* !defined(_WIN32) */
866

    
867
static void init_timers(void)
868
{
869
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
870
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
871

    
872
#ifdef _WIN32
873
    {
874
        int count=0;
875
        timerID = timeSetEvent(10,    // interval (ms)
876
                               0,     // resolution
877
                               host_alarm_handler, // function
878
                               (DWORD)&count,  // user parameter
879
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
880
         if( !timerID ) {
881
            perror("failed timer alarm");
882
            exit(1);
883
         }
884
    }
885
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
886
#else
887
    {
888
        struct sigaction act;
889
        struct itimerval itv;
890
        
891
        /* get times() syscall frequency */
892
        timer_freq = sysconf(_SC_CLK_TCK);
893
        
894
        /* timer signal */
895
        sigfillset(&act.sa_mask);
896
        act.sa_flags = 0;
897
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
898
        act.sa_flags |= SA_ONSTACK;
899
#endif
900
        act.sa_handler = host_alarm_handler;
901
        sigaction(SIGALRM, &act, NULL);
902

    
903
        itv.it_interval.tv_sec = 0;
904
        itv.it_interval.tv_usec = 1000;
905
        itv.it_value.tv_sec = 0;
906
        itv.it_value.tv_usec = 10 * 1000;
907
        setitimer(ITIMER_REAL, &itv, NULL);
908
        /* we probe the tick duration of the kernel to inform the user if
909
           the emulated kernel requested a too high timer frequency */
910
        getitimer(ITIMER_REAL, &itv);
911

    
912
        if (itv.it_interval.tv_usec > 1000) {
913
            /* try to use /dev/rtc to have a faster timer */
914
            if (start_rtc_timer() < 0)
915
                goto use_itimer;
916
            /* disable itimer */
917
            itv.it_interval.tv_sec = 0;
918
            itv.it_interval.tv_usec = 0;
919
            itv.it_value.tv_sec = 0;
920
            itv.it_value.tv_usec = 0;
921
            setitimer(ITIMER_REAL, &itv, NULL);
922

    
923
            /* use the RTC */
924
            sigaction(SIGIO, &act, NULL);
925
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
926
            fcntl(rtc_fd, F_SETOWN, getpid());
927
        } else {
928
        use_itimer:
929
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
930
                                   PIT_FREQ) / 1000000;
931
        }
932
    }
933
#endif
934
}
935

    
936
void quit_timers(void)
937
{
938
#ifdef _WIN32
939
    timeKillEvent(timerID);
940
#endif
941
}
942

    
943
/***********************************************************/
944
/* serial device */
945

    
946
#ifdef _WIN32
947

    
948
int serial_open_device(void)
949
{
950
    return -1;
951
}
952

    
953
#else
954

    
955
int serial_open_device(void)
956
{
957
    char slave_name[1024];
958
    int master_fd, slave_fd;
959

    
960
    if (serial_console == NULL && nographic) {
961
        /* use console for serial port */
962
        return 0;
963
    } else {
964
#if 0
965
        /* Not satisfying */
966
        if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
967
            fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
968
            return -1;
969
        }
970
        fprintf(stderr, "Serial port redirected to %s\n", slave_name);
971
        return master_fd;
972
#else
973
        return -1;
974
#endif
975
    }
976
}
977

    
978
#endif
979

    
980
/***********************************************************/
981
/* Linux network device redirectors */
982

    
983
void hex_dump(FILE *f, const uint8_t *buf, int size)
984
{
985
    int len, i, j, c;
986

    
987
    for(i=0;i<size;i+=16) {
988
        len = size - i;
989
        if (len > 16)
990
            len = 16;
991
        fprintf(f, "%08x ", i);
992
        for(j=0;j<16;j++) {
993
            if (j < len)
994
                fprintf(f, " %02x", buf[i+j]);
995
            else
996
                fprintf(f, "   ");
997
        }
998
        fprintf(f, " ");
999
        for(j=0;j<len;j++) {
1000
            c = buf[i+j];
1001
            if (c < ' ' || c > '~')
1002
                c = '.';
1003
            fprintf(f, "%c", c);
1004
        }
1005
        fprintf(f, "\n");
1006
    }
1007
}
1008

    
1009
void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1010
{
1011
    nd->send_packet(nd, buf, size);
1012
}
1013

    
1014
void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
1015
                          IOReadHandler *fd_read, void *opaque)
1016
{
1017
    nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1018
}
1019

    
1020
/* dummy network adapter */
1021

    
1022
static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1023
{
1024
}
1025

    
1026
static void dummy_add_read_packet(NetDriverState *nd, 
1027
                                  IOCanRWHandler *fd_can_read, 
1028
                                  IOReadHandler *fd_read, void *opaque)
1029
{
1030
}
1031

    
1032
static int net_dummy_init(NetDriverState *nd)
1033
{
1034
    nd->send_packet = dummy_send_packet;
1035
    nd->add_read_packet = dummy_add_read_packet;
1036
    pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1037
    return 0;
1038
}
1039

    
1040
#if defined(CONFIG_SLIRP)
1041

    
1042
/* slirp network adapter */
1043

    
1044
static void *slirp_fd_opaque;
1045
static IOCanRWHandler *slirp_fd_can_read;
1046
static IOReadHandler *slirp_fd_read;
1047
static int slirp_inited;
1048

    
1049
int slirp_can_output(void)
1050
{
1051
    return slirp_fd_can_read(slirp_fd_opaque);
1052
}
1053

    
1054
void slirp_output(const uint8_t *pkt, int pkt_len)
1055
{
1056
#if 0
1057
    printf("output:\n");
1058
    hex_dump(stdout, pkt, pkt_len);
1059
#endif
1060
    slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1061
}
1062

    
1063
static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1064
{
1065
#if 0
1066
    printf("input:\n");
1067
    hex_dump(stdout, buf, size);
1068
#endif
1069
    slirp_input(buf, size);
1070
}
1071

    
1072
static void slirp_add_read_packet(NetDriverState *nd, 
1073
                                  IOCanRWHandler *fd_can_read, 
1074
                                  IOReadHandler *fd_read, void *opaque)
1075
{
1076
    slirp_fd_opaque = opaque;
1077
    slirp_fd_can_read = fd_can_read;
1078
    slirp_fd_read = fd_read;
1079
}
1080

    
1081
static int net_slirp_init(NetDriverState *nd)
1082
{
1083
    if (!slirp_inited) {
1084
        slirp_inited = 1;
1085
        slirp_init();
1086
    }
1087
    nd->send_packet = slirp_send_packet;
1088
    nd->add_read_packet = slirp_add_read_packet;
1089
    pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1090
    return 0;
1091
}
1092

    
1093
#endif /* CONFIG_SLIRP */
1094

    
1095
#if !defined(_WIN32)
1096
#ifdef _BSD
1097
static int tun_open(char *ifname, int ifname_size)
1098
{
1099
    int fd;
1100
    char *dev;
1101
    struct stat s;
1102

    
1103
    fd = open("/dev/tap", O_RDWR);
1104
    if (fd < 0) {
1105
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1106
        return -1;
1107
    }
1108

    
1109
    fstat(fd, &s);
1110
    dev = devname(s.st_rdev, S_IFCHR);
1111
    pstrcpy(ifname, ifname_size, dev);
1112

    
1113
    fcntl(fd, F_SETFL, O_NONBLOCK);
1114
    return fd;
1115
}
1116
#else
1117
static int tun_open(char *ifname, int ifname_size)
1118
{
1119
    struct ifreq ifr;
1120
    int fd, ret;
1121
    
1122
    fd = open("/dev/net/tun", O_RDWR);
1123
    if (fd < 0) {
1124
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1125
        return -1;
1126
    }
1127
    memset(&ifr, 0, sizeof(ifr));
1128
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1129
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1130
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1131
    if (ret != 0) {
1132
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1133
        close(fd);
1134
        return -1;
1135
    }
1136
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
1137
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
1138
    fcntl(fd, F_SETFL, O_NONBLOCK);
1139
    return fd;
1140
}
1141
#endif
1142

    
1143
static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1144
{
1145
    write(nd->fd, buf, size);
1146
}
1147

    
1148
static void tun_add_read_packet(NetDriverState *nd, 
1149
                                IOCanRWHandler *fd_can_read, 
1150
                                IOReadHandler *fd_read, void *opaque)
1151
{
1152
    qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1153
}
1154

    
1155
static int net_tun_init(NetDriverState *nd)
1156
{
1157
    int pid, status;
1158
    char *args[3];
1159
    char **parg;
1160

    
1161
    nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1162
    if (nd->fd < 0)
1163
        return -1;
1164

    
1165
    /* try to launch network init script */
1166
    pid = fork();
1167
    if (pid >= 0) {
1168
        if (pid == 0) {
1169
            parg = args;
1170
            *parg++ = network_script;
1171
            *parg++ = nd->ifname;
1172
            *parg++ = NULL;
1173
            execv(network_script, args);
1174
            exit(1);
1175
        }
1176
        while (waitpid(pid, &status, 0) != pid);
1177
        if (!WIFEXITED(status) ||
1178
            WEXITSTATUS(status) != 0) {
1179
            fprintf(stderr, "%s: could not launch network script\n",
1180
                    network_script);
1181
        }
1182
    }
1183
    nd->send_packet = tun_send_packet;
1184
    nd->add_read_packet = tun_add_read_packet;
1185
    return 0;
1186
}
1187

    
1188
static int net_fd_init(NetDriverState *nd, int fd)
1189
{
1190
    nd->fd = fd;
1191
    nd->send_packet = tun_send_packet;
1192
    nd->add_read_packet = tun_add_read_packet;
1193
    pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1194
    return 0;
1195
}
1196

    
1197
#endif /* !_WIN32 */
1198

    
1199
/***********************************************************/
1200
/* dumb display */
1201

    
1202
#ifdef _WIN32
1203

    
1204
static void term_exit(void)
1205
{
1206
}
1207

    
1208
static void term_init(void)
1209
{
1210
}
1211

    
1212
#else
1213

    
1214
/* init terminal so that we can grab keys */
1215
static struct termios oldtty;
1216
static int old_fd0_flags;
1217

    
1218
static void term_exit(void)
1219
{
1220
    tcsetattr (0, TCSANOW, &oldtty);
1221
    fcntl(0, F_SETFL, old_fd0_flags);
1222
}
1223

    
1224
static void term_init(void)
1225
{
1226
    struct termios tty;
1227

    
1228
    tcgetattr (0, &tty);
1229
    oldtty = tty;
1230
    old_fd0_flags = fcntl(0, F_GETFL);
1231

    
1232
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1233
                          |INLCR|IGNCR|ICRNL|IXON);
1234
    tty.c_oflag |= OPOST;
1235
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1236
    /* if graphical mode, we allow Ctrl-C handling */
1237
    if (nographic)
1238
        tty.c_lflag &= ~ISIG;
1239
    tty.c_cflag &= ~(CSIZE|PARENB);
1240
    tty.c_cflag |= CS8;
1241
    tty.c_cc[VMIN] = 1;
1242
    tty.c_cc[VTIME] = 0;
1243
    
1244
    tcsetattr (0, TCSANOW, &tty);
1245

    
1246
    atexit(term_exit);
1247

    
1248
    fcntl(0, F_SETFL, O_NONBLOCK);
1249
}
1250

    
1251
#endif
1252

    
1253
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1254
{
1255
}
1256

    
1257
static void dumb_resize(DisplayState *ds, int w, int h)
1258
{
1259
}
1260

    
1261
static void dumb_refresh(DisplayState *ds)
1262
{
1263
    vga_update_display();
1264
}
1265

    
1266
void dumb_display_init(DisplayState *ds)
1267
{
1268
    ds->data = NULL;
1269
    ds->linesize = 0;
1270
    ds->depth = 0;
1271
    ds->dpy_update = dumb_update;
1272
    ds->dpy_resize = dumb_resize;
1273
    ds->dpy_refresh = dumb_refresh;
1274
}
1275

    
1276
#if !defined(CONFIG_SOFTMMU)
1277
/***********************************************************/
1278
/* cpu signal handler */
1279
static void host_segv_handler(int host_signum, siginfo_t *info, 
1280
                              void *puc)
1281
{
1282
    if (cpu_signal_handler(host_signum, info, puc))
1283
        return;
1284
    term_exit();
1285
    abort();
1286
}
1287
#endif
1288

    
1289
/***********************************************************/
1290
/* I/O handling */
1291

    
1292
#define MAX_IO_HANDLERS 64
1293

    
1294
typedef struct IOHandlerRecord {
1295
    int fd;
1296
    IOCanRWHandler *fd_can_read;
1297
    IOReadHandler *fd_read;
1298
    void *opaque;
1299
    /* temporary data */
1300
    struct pollfd *ufd;
1301
    int max_size;
1302
    struct IOHandlerRecord *next;
1303
} IOHandlerRecord;
1304

    
1305
static IOHandlerRecord *first_io_handler;
1306

    
1307
int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1308
                             IOReadHandler *fd_read, void *opaque)
1309
{
1310
    IOHandlerRecord *ioh;
1311

    
1312
    ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1313
    if (!ioh)
1314
        return -1;
1315
    ioh->fd = fd;
1316
    ioh->fd_can_read = fd_can_read;
1317
    ioh->fd_read = fd_read;
1318
    ioh->opaque = opaque;
1319
    ioh->next = first_io_handler;
1320
    first_io_handler = ioh;
1321
    return 0;
1322
}
1323

    
1324
void qemu_del_fd_read_handler(int fd)
1325
{
1326
    IOHandlerRecord **pioh, *ioh;
1327

    
1328
    pioh = &first_io_handler;
1329
    for(;;) {
1330
        ioh = *pioh;
1331
        if (ioh == NULL)
1332
            break;
1333
        if (ioh->fd == fd) {
1334
            *pioh = ioh->next;
1335
            break;
1336
        }
1337
        pioh = &ioh->next;
1338
    }
1339
}
1340

    
1341
/***********************************************************/
1342
/* savevm/loadvm support */
1343

    
1344
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1345
{
1346
    fwrite(buf, 1, size, f);
1347
}
1348

    
1349
void qemu_put_byte(QEMUFile *f, int v)
1350
{
1351
    fputc(v, f);
1352
}
1353

    
1354
void qemu_put_be16(QEMUFile *f, unsigned int v)
1355
{
1356
    qemu_put_byte(f, v >> 8);
1357
    qemu_put_byte(f, v);
1358
}
1359

    
1360
void qemu_put_be32(QEMUFile *f, unsigned int v)
1361
{
1362
    qemu_put_byte(f, v >> 24);
1363
    qemu_put_byte(f, v >> 16);
1364
    qemu_put_byte(f, v >> 8);
1365
    qemu_put_byte(f, v);
1366
}
1367

    
1368
void qemu_put_be64(QEMUFile *f, uint64_t v)
1369
{
1370
    qemu_put_be32(f, v >> 32);
1371
    qemu_put_be32(f, v);
1372
}
1373

    
1374
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1375
{
1376
    return fread(buf, 1, size, f);
1377
}
1378

    
1379
int qemu_get_byte(QEMUFile *f)
1380
{
1381
    int v;
1382
    v = fgetc(f);
1383
    if (v == EOF)
1384
        return 0;
1385
    else
1386
        return v;
1387
}
1388

    
1389
unsigned int qemu_get_be16(QEMUFile *f)
1390
{
1391
    unsigned int v;
1392
    v = qemu_get_byte(f) << 8;
1393
    v |= qemu_get_byte(f);
1394
    return v;
1395
}
1396

    
1397
unsigned int qemu_get_be32(QEMUFile *f)
1398
{
1399
    unsigned int v;
1400
    v = qemu_get_byte(f) << 24;
1401
    v |= qemu_get_byte(f) << 16;
1402
    v |= qemu_get_byte(f) << 8;
1403
    v |= qemu_get_byte(f);
1404
    return v;
1405
}
1406

    
1407
uint64_t qemu_get_be64(QEMUFile *f)
1408
{
1409
    uint64_t v;
1410
    v = (uint64_t)qemu_get_be32(f) << 32;
1411
    v |= qemu_get_be32(f);
1412
    return v;
1413
}
1414

    
1415
int64_t qemu_ftell(QEMUFile *f)
1416
{
1417
    return ftell(f);
1418
}
1419

    
1420
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1421
{
1422
    if (fseek(f, pos, whence) < 0)
1423
        return -1;
1424
    return ftell(f);
1425
}
1426

    
1427
typedef struct SaveStateEntry {
1428
    char idstr[256];
1429
    int instance_id;
1430
    int version_id;
1431
    SaveStateHandler *save_state;
1432
    LoadStateHandler *load_state;
1433
    void *opaque;
1434
    struct SaveStateEntry *next;
1435
} SaveStateEntry;
1436

    
1437
static SaveStateEntry *first_se;
1438

    
1439
int register_savevm(const char *idstr, 
1440
                    int instance_id, 
1441
                    int version_id,
1442
                    SaveStateHandler *save_state,
1443
                    LoadStateHandler *load_state,
1444
                    void *opaque)
1445
{
1446
    SaveStateEntry *se, **pse;
1447

    
1448
    se = qemu_malloc(sizeof(SaveStateEntry));
1449
    if (!se)
1450
        return -1;
1451
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1452
    se->instance_id = instance_id;
1453
    se->version_id = version_id;
1454
    se->save_state = save_state;
1455
    se->load_state = load_state;
1456
    se->opaque = opaque;
1457
    se->next = NULL;
1458

    
1459
    /* add at the end of list */
1460
    pse = &first_se;
1461
    while (*pse != NULL)
1462
        pse = &(*pse)->next;
1463
    *pse = se;
1464
    return 0;
1465
}
1466

    
1467
#define QEMU_VM_FILE_MAGIC   0x5145564d
1468
#define QEMU_VM_FILE_VERSION 0x00000001
1469

    
1470
int qemu_savevm(const char *filename)
1471
{
1472
    SaveStateEntry *se;
1473
    QEMUFile *f;
1474
    int len, len_pos, cur_pos, saved_vm_running, ret;
1475

    
1476
    saved_vm_running = vm_running;
1477
    vm_stop(0);
1478

    
1479
    f = fopen(filename, "wb");
1480
    if (!f) {
1481
        ret = -1;
1482
        goto the_end;
1483
    }
1484

    
1485
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1486
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1487

    
1488
    for(se = first_se; se != NULL; se = se->next) {
1489
        /* ID string */
1490
        len = strlen(se->idstr);
1491
        qemu_put_byte(f, len);
1492
        qemu_put_buffer(f, se->idstr, len);
1493

    
1494
        qemu_put_be32(f, se->instance_id);
1495
        qemu_put_be32(f, se->version_id);
1496

    
1497
        /* record size: filled later */
1498
        len_pos = ftell(f);
1499
        qemu_put_be32(f, 0);
1500
        
1501
        se->save_state(f, se->opaque);
1502

    
1503
        /* fill record size */
1504
        cur_pos = ftell(f);
1505
        len = ftell(f) - len_pos - 4;
1506
        fseek(f, len_pos, SEEK_SET);
1507
        qemu_put_be32(f, len);
1508
        fseek(f, cur_pos, SEEK_SET);
1509
    }
1510

    
1511
    fclose(f);
1512
    ret = 0;
1513
 the_end:
1514
    if (saved_vm_running)
1515
        vm_start();
1516
    return ret;
1517
}
1518

    
1519
static SaveStateEntry *find_se(const char *idstr, int instance_id)
1520
{
1521
    SaveStateEntry *se;
1522

    
1523
    for(se = first_se; se != NULL; se = se->next) {
1524
        if (!strcmp(se->idstr, idstr) && 
1525
            instance_id == se->instance_id)
1526
            return se;
1527
    }
1528
    return NULL;
1529
}
1530

    
1531
int qemu_loadvm(const char *filename)
1532
{
1533
    SaveStateEntry *se;
1534
    QEMUFile *f;
1535
    int len, cur_pos, ret, instance_id, record_len, version_id;
1536
    int saved_vm_running;
1537
    unsigned int v;
1538
    char idstr[256];
1539
    
1540
    saved_vm_running = vm_running;
1541
    vm_stop(0);
1542

    
1543
    f = fopen(filename, "rb");
1544
    if (!f) {
1545
        ret = -1;
1546
        goto the_end;
1547
    }
1548

    
1549
    v = qemu_get_be32(f);
1550
    if (v != QEMU_VM_FILE_MAGIC)
1551
        goto fail;
1552
    v = qemu_get_be32(f);
1553
    if (v != QEMU_VM_FILE_VERSION) {
1554
    fail:
1555
        fclose(f);
1556
        ret = -1;
1557
        goto the_end;
1558
    }
1559
    for(;;) {
1560
#if defined (DO_TB_FLUSH)
1561
        tb_flush(global_env);
1562
#endif
1563
        len = qemu_get_byte(f);
1564
        if (feof(f))
1565
            break;
1566
        qemu_get_buffer(f, idstr, len);
1567
        idstr[len] = '\0';
1568
        instance_id = qemu_get_be32(f);
1569
        version_id = qemu_get_be32(f);
1570
        record_len = qemu_get_be32(f);
1571
#if 0
1572
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1573
               idstr, instance_id, version_id, record_len);
1574
#endif
1575
        cur_pos = ftell(f);
1576
        se = find_se(idstr, instance_id);
1577
        if (!se) {
1578
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1579
                    instance_id, idstr);
1580
        } else {
1581
            ret = se->load_state(f, se->opaque, version_id);
1582
            if (ret < 0) {
1583
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1584
                        instance_id, idstr);
1585
            }
1586
        }
1587
        /* always seek to exact end of record */
1588
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1589
    }
1590
    fclose(f);
1591
    ret = 0;
1592
 the_end:
1593
    if (saved_vm_running)
1594
        vm_start();
1595
    return ret;
1596
}
1597

    
1598
/***********************************************************/
1599
/* cpu save/restore */
1600

    
1601
#if defined(TARGET_I386)
1602

    
1603
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1604
{
1605
    qemu_put_be32(f, dt->selector);
1606
    qemu_put_be32(f, (uint32_t)dt->base);
1607
    qemu_put_be32(f, dt->limit);
1608
    qemu_put_be32(f, dt->flags);
1609
}
1610

    
1611
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1612
{
1613
    dt->selector = qemu_get_be32(f);
1614
    dt->base = (uint8_t *)qemu_get_be32(f);
1615
    dt->limit = qemu_get_be32(f);
1616
    dt->flags = qemu_get_be32(f);
1617
}
1618

    
1619
void cpu_save(QEMUFile *f, void *opaque)
1620
{
1621
    CPUState *env = opaque;
1622
    uint16_t fptag, fpus, fpuc;
1623
    uint32_t hflags;
1624
    int i;
1625

    
1626
    for(i = 0; i < 8; i++)
1627
        qemu_put_be32s(f, &env->regs[i]);
1628
    qemu_put_be32s(f, &env->eip);
1629
    qemu_put_be32s(f, &env->eflags);
1630
    qemu_put_be32s(f, &env->eflags);
1631
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1632
    qemu_put_be32s(f, &hflags);
1633
    
1634
    /* FPU */
1635
    fpuc = env->fpuc;
1636
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1637
    fptag = 0;
1638
    for (i=7; i>=0; i--) {
1639
        fptag <<= 2;
1640
        if (env->fptags[i]) {
1641
            fptag |= 3;
1642
        }
1643
    }
1644
    
1645
    qemu_put_be16s(f, &fpuc);
1646
    qemu_put_be16s(f, &fpus);
1647
    qemu_put_be16s(f, &fptag);
1648

    
1649
    for(i = 0; i < 8; i++) {
1650
        uint64_t mant;
1651
        uint16_t exp;
1652
        cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1653
        qemu_put_be64(f, mant);
1654
        qemu_put_be16(f, exp);
1655
    }
1656

    
1657
    for(i = 0; i < 6; i++)
1658
        cpu_put_seg(f, &env->segs[i]);
1659
    cpu_put_seg(f, &env->ldt);
1660
    cpu_put_seg(f, &env->tr);
1661
    cpu_put_seg(f, &env->gdt);
1662
    cpu_put_seg(f, &env->idt);
1663
    
1664
    qemu_put_be32s(f, &env->sysenter_cs);
1665
    qemu_put_be32s(f, &env->sysenter_esp);
1666
    qemu_put_be32s(f, &env->sysenter_eip);
1667
    
1668
    qemu_put_be32s(f, &env->cr[0]);
1669
    qemu_put_be32s(f, &env->cr[2]);
1670
    qemu_put_be32s(f, &env->cr[3]);
1671
    qemu_put_be32s(f, &env->cr[4]);
1672
    
1673
    for(i = 0; i < 8; i++)
1674
        qemu_put_be32s(f, &env->dr[i]);
1675

    
1676
    /* MMU */
1677
    qemu_put_be32s(f, &env->a20_mask);
1678
}
1679

    
1680
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1681
{
1682
    CPUState *env = opaque;
1683
    int i;
1684
    uint32_t hflags;
1685
    uint16_t fpus, fpuc, fptag;
1686

    
1687
    if (version_id != 2)
1688
        return -EINVAL;
1689
    for(i = 0; i < 8; i++)
1690
        qemu_get_be32s(f, &env->regs[i]);
1691
    qemu_get_be32s(f, &env->eip);
1692
    qemu_get_be32s(f, &env->eflags);
1693
    qemu_get_be32s(f, &env->eflags);
1694
    qemu_get_be32s(f, &hflags);
1695

    
1696
    qemu_get_be16s(f, &fpuc);
1697
    qemu_get_be16s(f, &fpus);
1698
    qemu_get_be16s(f, &fptag);
1699

    
1700
    for(i = 0; i < 8; i++) {
1701
        uint64_t mant;
1702
        uint16_t exp;
1703
        mant = qemu_get_be64(f);
1704
        exp = qemu_get_be16(f);
1705
        env->fpregs[i] = cpu_set_fp80(mant, exp);
1706
    }
1707

    
1708
    env->fpuc = fpuc;
1709
    env->fpstt = (fpus >> 11) & 7;
1710
    env->fpus = fpus & ~0x3800;
1711
    for(i = 0; i < 8; i++) {
1712
        env->fptags[i] = ((fptag & 3) == 3);
1713
        fptag >>= 2;
1714
    }
1715
    
1716
    for(i = 0; i < 6; i++)
1717
        cpu_get_seg(f, &env->segs[i]);
1718
    cpu_get_seg(f, &env->ldt);
1719
    cpu_get_seg(f, &env->tr);
1720
    cpu_get_seg(f, &env->gdt);
1721
    cpu_get_seg(f, &env->idt);
1722
    
1723
    qemu_get_be32s(f, &env->sysenter_cs);
1724
    qemu_get_be32s(f, &env->sysenter_esp);
1725
    qemu_get_be32s(f, &env->sysenter_eip);
1726
    
1727
    qemu_get_be32s(f, &env->cr[0]);
1728
    qemu_get_be32s(f, &env->cr[2]);
1729
    qemu_get_be32s(f, &env->cr[3]);
1730
    qemu_get_be32s(f, &env->cr[4]);
1731
    
1732
    for(i = 0; i < 8; i++)
1733
        qemu_get_be32s(f, &env->dr[i]);
1734

    
1735
    /* MMU */
1736
    qemu_get_be32s(f, &env->a20_mask);
1737

    
1738
    /* XXX: compute hflags from scratch, except for CPL and IIF */
1739
    env->hflags = hflags;
1740
    tlb_flush(env, 1);
1741
    return 0;
1742
}
1743

    
1744
#elif defined(TARGET_PPC)
1745
void cpu_save(QEMUFile *f, void *opaque)
1746
{
1747
}
1748

    
1749
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1750
{
1751
    return 0;
1752
}
1753
#else
1754

    
1755
#warning No CPU save/restore functions
1756

    
1757
#endif
1758

    
1759
/***********************************************************/
1760
/* ram save/restore */
1761

    
1762
/* we just avoid storing empty pages */
1763
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1764
{
1765
    int i, v;
1766

    
1767
    v = buf[0];
1768
    for(i = 1; i < len; i++) {
1769
        if (buf[i] != v)
1770
            goto normal_save;
1771
    }
1772
    qemu_put_byte(f, 1);
1773
    qemu_put_byte(f, v);
1774
    return;
1775
 normal_save:
1776
    qemu_put_byte(f, 0); 
1777
    qemu_put_buffer(f, buf, len);
1778
}
1779

    
1780
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1781
{
1782
    int v;
1783

    
1784
    v = qemu_get_byte(f);
1785
    switch(v) {
1786
    case 0:
1787
        if (qemu_get_buffer(f, buf, len) != len)
1788
            return -EIO;
1789
        break;
1790
    case 1:
1791
        v = qemu_get_byte(f);
1792
        memset(buf, v, len);
1793
        break;
1794
    default:
1795
        return -EINVAL;
1796
    }
1797
    return 0;
1798
}
1799

    
1800
static void ram_save(QEMUFile *f, void *opaque)
1801
{
1802
    int i;
1803
    qemu_put_be32(f, phys_ram_size);
1804
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1805
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1806
    }
1807
}
1808

    
1809
static int ram_load(QEMUFile *f, void *opaque, int version_id)
1810
{
1811
    int i, ret;
1812

    
1813
    if (version_id != 1)
1814
        return -EINVAL;
1815
    if (qemu_get_be32(f) != phys_ram_size)
1816
        return -EINVAL;
1817
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1818
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1819
        if (ret)
1820
            return ret;
1821
    }
1822
    return 0;
1823
}
1824

    
1825
/***********************************************************/
1826
/* main execution loop */
1827

    
1828
void gui_update(void *opaque)
1829
{
1830
    display_state.dpy_refresh(&display_state);
1831
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1832
}
1833

    
1834
/* XXX: support several handlers */
1835
VMStopHandler *vm_stop_cb;
1836
VMStopHandler *vm_stop_opaque;
1837

    
1838
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1839
{
1840
    vm_stop_cb = cb;
1841
    vm_stop_opaque = opaque;
1842
    return 0;
1843
}
1844

    
1845
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1846
{
1847
    vm_stop_cb = NULL;
1848
}
1849

    
1850
void vm_start(void)
1851
{
1852
    if (!vm_running) {
1853
        cpu_enable_ticks();
1854
        vm_running = 1;
1855
    }
1856
}
1857

    
1858
void vm_stop(int reason) 
1859
{
1860
    if (vm_running) {
1861
        cpu_disable_ticks();
1862
        vm_running = 0;
1863
        if (reason != 0) {
1864
            if (vm_stop_cb) {
1865
                vm_stop_cb(vm_stop_opaque, reason);
1866
            }
1867
        }
1868
    }
1869
}
1870

    
1871
/* reset/shutdown handler */
1872

    
1873
typedef struct QEMUResetEntry {
1874
    QEMUResetHandler *func;
1875
    void *opaque;
1876
    struct QEMUResetEntry *next;
1877
} QEMUResetEntry;
1878

    
1879
static QEMUResetEntry *first_reset_entry;
1880
static int reset_requested;
1881
static int shutdown_requested;
1882

    
1883
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1884
{
1885
    QEMUResetEntry **pre, *re;
1886

    
1887
    pre = &first_reset_entry;
1888
    while (*pre != NULL)
1889
        pre = &(*pre)->next;
1890
    re = qemu_mallocz(sizeof(QEMUResetEntry));
1891
    re->func = func;
1892
    re->opaque = opaque;
1893
    re->next = NULL;
1894
    *pre = re;
1895
}
1896

    
1897
void qemu_system_reset(void)
1898
{
1899
    QEMUResetEntry *re;
1900

    
1901
    /* reset all devices */
1902
    for(re = first_reset_entry; re != NULL; re = re->next) {
1903
        re->func(re->opaque);
1904
    }
1905
}
1906

    
1907
void qemu_system_reset_request(void)
1908
{
1909
    reset_requested = 1;
1910
    cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1911
}
1912

    
1913
void qemu_system_shutdown_request(void)
1914
{
1915
    shutdown_requested = 1;
1916
    cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1917
}
1918

    
1919
static void main_cpu_reset(void *opaque)
1920
{
1921
#ifdef TARGET_I386
1922
    CPUState *env = opaque;
1923
    cpu_reset(env);
1924
#endif
1925
}
1926

    
1927
int main_loop(void)
1928
{
1929
#ifndef _WIN32
1930
    struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1931
    IOHandlerRecord *ioh, *ioh_next;
1932
    uint8_t buf[4096];
1933
    int n, max_size;
1934
#endif
1935
    int ret, timeout;
1936
    CPUState *env = global_env;
1937

    
1938
    for(;;) {
1939
        if (vm_running) {
1940
            ret = cpu_exec(env);
1941
            if (shutdown_requested) {
1942
                ret = EXCP_INTERRUPT; 
1943
                break;
1944
            }
1945
            if (reset_requested) {
1946
                reset_requested = 0;
1947
                qemu_system_reset();
1948
                ret = EXCP_INTERRUPT; 
1949
            }
1950
            if (ret == EXCP_DEBUG) {
1951
                vm_stop(EXCP_DEBUG);
1952
            }
1953
            /* if hlt instruction, we wait until the next IRQ */
1954
            /* XXX: use timeout computed from timers */
1955
            if (ret == EXCP_HLT) 
1956
                timeout = 10;
1957
            else
1958
                timeout = 0;
1959
        } else {
1960
            timeout = 10;
1961
        }
1962

    
1963
#ifdef _WIN32
1964
        if (timeout > 0)
1965
            Sleep(timeout);
1966
#else
1967

    
1968
        /* poll any events */
1969
        /* XXX: separate device handlers from system ones */
1970
        pf = ufds;
1971
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1972
            if (!ioh->fd_can_read) {
1973
                max_size = 0;
1974
                pf->fd = ioh->fd;
1975
                pf->events = POLLIN;
1976
                ioh->ufd = pf;
1977
                pf++;
1978
            } else {
1979
                max_size = ioh->fd_can_read(ioh->opaque);
1980
                if (max_size > 0) {
1981
                    if (max_size > sizeof(buf))
1982
                        max_size = sizeof(buf);
1983
                    pf->fd = ioh->fd;
1984
                    pf->events = POLLIN;
1985
                    ioh->ufd = pf;
1986
                    pf++;
1987
                } else {
1988
                    ioh->ufd = NULL;
1989
                }
1990
            }
1991
            ioh->max_size = max_size;
1992
        }
1993
        
1994
        ret = poll(ufds, pf - ufds, timeout);
1995
        if (ret > 0) {
1996
            /* XXX: better handling of removal */
1997
            for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1998
                ioh_next = ioh->next;
1999
                pf = ioh->ufd;
2000
                if (pf) {
2001
                    if (pf->revents & POLLIN) {
2002
                        if (ioh->max_size == 0) {
2003
                            /* just a read event */
2004
                            ioh->fd_read(ioh->opaque, NULL, 0);
2005
                        } else {
2006
                            n = read(ioh->fd, buf, ioh->max_size);
2007
                            if (n >= 0) {
2008
                                ioh->fd_read(ioh->opaque, buf, n);
2009
                            } else if (errno != EAGAIN) {
2010
                                ioh->fd_read(ioh->opaque, NULL, -errno);
2011
                            }
2012
                        }
2013
                    }
2014
                }
2015
            }
2016
        }
2017

    
2018
#if defined(CONFIG_SLIRP)
2019
        /* XXX: merge with poll() */
2020
        if (slirp_inited) {
2021
            fd_set rfds, wfds, xfds;
2022
            int nfds;
2023
            struct timeval tv;
2024

    
2025
            nfds = -1;
2026
            FD_ZERO(&rfds);
2027
            FD_ZERO(&wfds);
2028
            FD_ZERO(&xfds);
2029
            slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2030
            tv.tv_sec = 0;
2031
            tv.tv_usec = 0;
2032
            ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2033
            if (ret >= 0) {
2034
                slirp_select_poll(&rfds, &wfds, &xfds);
2035
            }
2036
        }
2037
#endif
2038

    
2039
#endif
2040

    
2041
        if (vm_running) {
2042
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
2043
                            qemu_get_clock(vm_clock));
2044
            
2045
            if (audio_enabled) {
2046
                /* XXX: add explicit timer */
2047
                SB16_run();
2048
            }
2049
            
2050
            /* run dma transfers, if any */
2051
            DMA_run();
2052
        }
2053

    
2054
        /* real time timers */
2055
        qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
2056
                        qemu_get_clock(rt_clock));
2057
    }
2058
    cpu_disable_ticks();
2059
    return ret;
2060
}
2061

    
2062
void help(void)
2063
{
2064
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2065
           "usage: %s [options] [disk_image]\n"
2066
           "\n"
2067
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2068
           "\n"
2069
           "Standard options:\n"
2070
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
2071
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
2072
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
2073
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2074
           "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
2075
           "-snapshot       write to temporary files instead of disk image files\n"
2076
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
2077
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
2078
           "-enable-audio   enable audio support\n"
2079
           "-localtime      set the real time clock to local time [default=utc]\n"
2080
#ifdef TARGET_PPC
2081
           "-prep           Simulate a PREP system (default is PowerMAC)\n"
2082
           "-g WxH[xDEPTH]  Set the initial VGA graphic mode\n"
2083
#endif
2084
           "\n"
2085
           "Network options:\n"
2086
           "-nics n         simulate 'n' network cards [default=1]\n"
2087
           "-macaddr addr   set the mac address of the first interface\n"
2088
           "-n script       set tap/tun network init script [default=%s]\n"
2089
           "-tun-fd fd      use this fd as already opened tap/tun interface\n"
2090
#ifdef CONFIG_SLIRP
2091
           "-user-net       use user mode network stack [default if no tap/tun script]\n"
2092
#endif
2093
           "-dummy-net      use dummy network stack\n"
2094
           "\n"
2095
           "Linux boot specific:\n"
2096
           "-kernel bzImage use 'bzImage' as kernel image\n"
2097
           "-append cmdline use 'cmdline' as kernel command line\n"
2098
           "-initrd file    use 'file' as initial ram disk\n"
2099
           "\n"
2100
           "Debug/Expert options:\n"
2101
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
2102
           "-s              wait gdb connection to port %d\n"
2103
           "-p port         change gdb connection port\n"
2104
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
2105
           "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
2106
           "-L path         set the directory for the BIOS and VGA BIOS\n"
2107
#ifdef USE_CODE_COPY
2108
           "-no-code-copy   disable code copy acceleration\n"
2109
#endif
2110
#ifdef TARGET_I386
2111
           "-isa            simulate an ISA-only system (default is PCI system)\n"
2112
#endif
2113
           "\n"
2114
           "During emulation, use C-a h to get terminal commands:\n",
2115
#ifdef CONFIG_SOFTMMU
2116
           "qemu",
2117
#else
2118
           "qemu-fast",
2119
#endif
2120
           DEFAULT_RAM_SIZE,
2121
           DEFAULT_NETWORK_SCRIPT,
2122
           DEFAULT_GDBSTUB_PORT,
2123
           "/tmp/qemu.log");
2124
    term_print_help();
2125
#ifndef CONFIG_SOFTMMU
2126
    printf("\n"
2127
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2128
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2129
           "PC emulation.\n");
2130
#endif
2131
    exit(1);
2132
}
2133

    
2134
#define HAS_ARG 0x0001
2135

    
2136
enum {
2137
    QEMU_OPTION_h,
2138

    
2139
    QEMU_OPTION_fda,
2140
    QEMU_OPTION_fdb,
2141
    QEMU_OPTION_hda,
2142
    QEMU_OPTION_hdb,
2143
    QEMU_OPTION_hdc,
2144
    QEMU_OPTION_hdd,
2145
    QEMU_OPTION_cdrom,
2146
    QEMU_OPTION_boot,
2147
    QEMU_OPTION_snapshot,
2148
    QEMU_OPTION_m,
2149
    QEMU_OPTION_nographic,
2150
    QEMU_OPTION_enable_audio,
2151

    
2152
    QEMU_OPTION_nics,
2153
    QEMU_OPTION_macaddr,
2154
    QEMU_OPTION_n,
2155
    QEMU_OPTION_tun_fd,
2156
    QEMU_OPTION_user_net,
2157
    QEMU_OPTION_dummy_net,
2158

    
2159
    QEMU_OPTION_kernel,
2160
    QEMU_OPTION_append,
2161
    QEMU_OPTION_initrd,
2162

    
2163
    QEMU_OPTION_S,
2164
    QEMU_OPTION_s,
2165
    QEMU_OPTION_p,
2166
    QEMU_OPTION_d,
2167
    QEMU_OPTION_hdachs,
2168
    QEMU_OPTION_L,
2169
    QEMU_OPTION_no_code_copy,
2170
    QEMU_OPTION_pci,
2171
    QEMU_OPTION_isa,
2172
    QEMU_OPTION_prep,
2173
    QEMU_OPTION_localtime,
2174
    QEMU_OPTION_cirrusvga,
2175
    QEMU_OPTION_g,
2176
};
2177

    
2178
typedef struct QEMUOption {
2179
    const char *name;
2180
    int flags;
2181
    int index;
2182
} QEMUOption;
2183

    
2184
const QEMUOption qemu_options[] = {
2185
    { "h", 0, QEMU_OPTION_h },
2186

    
2187
    { "fda", HAS_ARG, QEMU_OPTION_fda },
2188
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2189
    { "hda", HAS_ARG, QEMU_OPTION_hda },
2190
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2191
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2192
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2193
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2194
    { "boot", HAS_ARG, QEMU_OPTION_boot },
2195
    { "snapshot", 0, QEMU_OPTION_snapshot },
2196
    { "m", HAS_ARG, QEMU_OPTION_m },
2197
    { "nographic", 0, QEMU_OPTION_nographic },
2198
    { "enable-audio", 0, QEMU_OPTION_enable_audio },
2199

    
2200
    { "nics", HAS_ARG, QEMU_OPTION_nics},
2201
    { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2202
    { "n", HAS_ARG, QEMU_OPTION_n },
2203
    { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2204
#ifdef CONFIG_SLIRP
2205
    { "user-net", 0, QEMU_OPTION_user_net },
2206
#endif
2207
    { "dummy-net", 0, QEMU_OPTION_dummy_net },
2208

    
2209
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2210
    { "append", HAS_ARG, QEMU_OPTION_append },
2211
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2212

    
2213
    { "S", 0, QEMU_OPTION_S },
2214
    { "s", 0, QEMU_OPTION_s },
2215
    { "p", HAS_ARG, QEMU_OPTION_p },
2216
    { "d", HAS_ARG, QEMU_OPTION_d },
2217
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2218
    { "L", HAS_ARG, QEMU_OPTION_L },
2219
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2220
#ifdef TARGET_PPC
2221
    { "prep", 0, QEMU_OPTION_prep },
2222
    { "g", 1, QEMU_OPTION_g },
2223
#endif
2224
    { "localtime", 0, QEMU_OPTION_localtime },
2225
    { "isa", 0, QEMU_OPTION_isa },
2226

    
2227
    /* temporary options */
2228
    { "pci", 0, QEMU_OPTION_pci },
2229
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2230
    { NULL },
2231
};
2232

    
2233
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2234

    
2235
/* this stack is only used during signal handling */
2236
#define SIGNAL_STACK_SIZE 32768
2237

    
2238
static uint8_t *signal_stack;
2239

    
2240
#endif
2241

    
2242
#define NET_IF_TUN   0
2243
#define NET_IF_USER  1
2244
#define NET_IF_DUMMY 2
2245

    
2246
int main(int argc, char **argv)
2247
{
2248
#ifdef CONFIG_GDBSTUB
2249
    int use_gdbstub, gdbstub_port;
2250
#endif
2251
    int i, has_cdrom;
2252
    int snapshot, linux_boot;
2253
    CPUState *env;
2254
    const char *initrd_filename;
2255
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2256
    const char *kernel_filename, *kernel_cmdline;
2257
    DisplayState *ds = &display_state;
2258
    int cyls, heads, secs;
2259
    int start_emulation = 1;
2260
    uint8_t macaddr[6];
2261
    int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2262
    int optind;
2263
    const char *r, *optarg;
2264

    
2265
#if !defined(CONFIG_SOFTMMU)
2266
    /* we never want that malloc() uses mmap() */
2267
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2268
#endif
2269
    initrd_filename = NULL;
2270
    for(i = 0; i < MAX_FD; i++)
2271
        fd_filename[i] = NULL;
2272
    for(i = 0; i < MAX_DISKS; i++)
2273
        hd_filename[i] = NULL;
2274
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2275
    vga_ram_size = VGA_RAM_SIZE;
2276
    bios_size = BIOS_SIZE;
2277
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2278
#ifdef CONFIG_GDBSTUB
2279
    use_gdbstub = 0;
2280
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
2281
#endif
2282
    snapshot = 0;
2283
    nographic = 0;
2284
    kernel_filename = NULL;
2285
    kernel_cmdline = "";
2286
    has_cdrom = 1;
2287
    cyls = heads = secs = 0;
2288

    
2289
    nb_tun_fds = 0;
2290
    net_if_type = -1;
2291
    nb_nics = 1;
2292
    /* default mac address of the first network interface */
2293
    macaddr[0] = 0x52;
2294
    macaddr[1] = 0x54;
2295
    macaddr[2] = 0x00;
2296
    macaddr[3] = 0x12;
2297
    macaddr[4] = 0x34;
2298
    macaddr[5] = 0x56;
2299

    
2300
    optind = 1;
2301
    for(;;) {
2302
        if (optind >= argc)
2303
            break;
2304
        r = argv[optind];
2305
        if (r[0] != '-') {
2306
            hd_filename[0] = argv[optind++];
2307
        } else {
2308
            const QEMUOption *popt;
2309

    
2310
            optind++;
2311
            popt = qemu_options;
2312
            for(;;) {
2313
                if (!popt->name) {
2314
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
2315
                            argv[0], r);
2316
                    exit(1);
2317
                }
2318
                if (!strcmp(popt->name, r + 1))
2319
                    break;
2320
                popt++;
2321
            }
2322
            if (popt->flags & HAS_ARG) {
2323
                if (optind >= argc) {
2324
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
2325
                            argv[0], r);
2326
                    exit(1);
2327
                }
2328
                optarg = argv[optind++];
2329
            } else {
2330
                optarg = NULL;
2331
            }
2332

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

    
2553
    linux_boot = (kernel_filename != NULL);
2554
        
2555
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2556
        fd_filename[0] == '\0')
2557
        help();
2558
    
2559
    /* boot to cd by default if no hard disk */
2560
    if (hd_filename[0] == '\0' && boot_device == 'c') {
2561
        if (fd_filename[0] != '\0')
2562
            boot_device = 'a';
2563
        else
2564
            boot_device = 'd';
2565
    }
2566

    
2567
#if !defined(CONFIG_SOFTMMU)
2568
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2569
    {
2570
        static uint8_t stdout_buf[4096];
2571
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2572
    }
2573
#else
2574
    setvbuf(stdout, NULL, _IOLBF, 0);
2575
#endif
2576

    
2577
    /* init host network redirectors */
2578
    if (net_if_type == -1) {
2579
        net_if_type = NET_IF_TUN;
2580
#if defined(CONFIG_SLIRP)
2581
        if (access(network_script, R_OK) < 0) {
2582
            net_if_type = NET_IF_USER;
2583
        }
2584
#endif
2585
    }
2586

    
2587
    for(i = 0; i < nb_nics; i++) {
2588
        NetDriverState *nd = &nd_table[i];
2589
        nd->index = i;
2590
        /* init virtual mac address */
2591
        nd->macaddr[0] = macaddr[0];
2592
        nd->macaddr[1] = macaddr[1];
2593
        nd->macaddr[2] = macaddr[2];
2594
        nd->macaddr[3] = macaddr[3];
2595
        nd->macaddr[4] = macaddr[4];
2596
        nd->macaddr[5] = macaddr[5] + i;
2597
        switch(net_if_type) {
2598
#if defined(CONFIG_SLIRP)
2599
        case NET_IF_USER:
2600
            net_slirp_init(nd);
2601
            break;
2602
#endif
2603
#if !defined(_WIN32)
2604
        case NET_IF_TUN:
2605
            if (i < nb_tun_fds) {
2606
                net_fd_init(nd, tun_fds[i]);
2607
            } else {
2608
                if (net_tun_init(nd) < 0)
2609
                    net_dummy_init(nd);
2610
            }
2611
            break;
2612
#endif
2613
        case NET_IF_DUMMY:
2614
        default:
2615
            net_dummy_init(nd);
2616
            break;
2617
        }
2618
    }
2619

    
2620
    /* init the memory */
2621
    phys_ram_size = ram_size + vga_ram_size + bios_size;
2622

    
2623
#ifdef CONFIG_SOFTMMU
2624
#ifdef _BSD
2625
    /* mallocs are always aligned on BSD. */
2626
    phys_ram_base = malloc(phys_ram_size);
2627
#else
2628
    phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2629
#endif
2630
    if (!phys_ram_base) {
2631
        fprintf(stderr, "Could not allocate physical memory\n");
2632
        exit(1);
2633
    }
2634
#else
2635
    /* as we must map the same page at several addresses, we must use
2636
       a fd */
2637
    {
2638
        const char *tmpdir;
2639

    
2640
        tmpdir = getenv("QEMU_TMPDIR");
2641
        if (!tmpdir)
2642
            tmpdir = "/tmp";
2643
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2644
        if (mkstemp(phys_ram_file) < 0) {
2645
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2646
                    phys_ram_file);
2647
            exit(1);
2648
        }
2649
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2650
        if (phys_ram_fd < 0) {
2651
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2652
                    phys_ram_file);
2653
            exit(1);
2654
        }
2655
        ftruncate(phys_ram_fd, phys_ram_size);
2656
        unlink(phys_ram_file);
2657
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2658
                             phys_ram_size, 
2659
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2660
                             phys_ram_fd, 0);
2661
        if (phys_ram_base == MAP_FAILED) {
2662
            fprintf(stderr, "Could not map physical memory\n");
2663
            exit(1);
2664
        }
2665
    }
2666
#endif
2667

    
2668
    /* we always create the cdrom drive, even if no disk is there */
2669
    if (has_cdrom) {
2670
        bs_table[2] = bdrv_new("cdrom");
2671
        bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2672
    }
2673

    
2674
    /* open the virtual block devices */
2675
    for(i = 0; i < MAX_DISKS; i++) {
2676
        if (hd_filename[i]) {
2677
            if (!bs_table[i]) {
2678
                char buf[64];
2679
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2680
                bs_table[i] = bdrv_new(buf);
2681
            }
2682
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2683
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2684
                        hd_filename[i]);
2685
                exit(1);
2686
            }
2687
            if (i == 0 && cyls != 0) 
2688
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2689
        }
2690
    }
2691

    
2692
    /* we always create at least one floppy disk */
2693
    fd_table[0] = bdrv_new("fda");
2694
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2695

    
2696
    for(i = 0; i < MAX_FD; i++) {
2697
        if (fd_filename[i]) {
2698
            if (!fd_table[i]) {
2699
                char buf[64];
2700
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2701
                fd_table[i] = bdrv_new(buf);
2702
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2703
            }
2704
            if (fd_filename[i] != '\0') {
2705
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2706
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2707
                            fd_filename[i]);
2708
                    exit(1);
2709
                }
2710
            }
2711
        }
2712
    }
2713

    
2714
    /* init CPU state */
2715
    env = cpu_init();
2716
    global_env = env;
2717
    cpu_single_env = env;
2718

    
2719
    register_savevm("timer", 0, 1, timer_save, timer_load, env);
2720
    register_savevm("cpu", 0, 2, cpu_save, cpu_load, env);
2721
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2722
    qemu_register_reset(main_cpu_reset, global_env);
2723

    
2724
    init_ioports();
2725
    cpu_calibrate_ticks();
2726

    
2727
    /* terminal init */
2728
    if (nographic) {
2729
        dumb_display_init(ds);
2730
    } else {
2731
#ifdef CONFIG_SDL
2732
        sdl_display_init(ds);
2733
#else
2734
        dumb_display_init(ds);
2735
#endif
2736
    }
2737

    
2738
    /* setup cpu signal handlers for MMU / self modifying code handling */
2739
#if !defined(CONFIG_SOFTMMU)
2740
    
2741
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2742
    {
2743
        stack_t stk;
2744
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2745
        stk.ss_sp = signal_stack;
2746
        stk.ss_size = SIGNAL_STACK_SIZE;
2747
        stk.ss_flags = 0;
2748

    
2749
        if (sigaltstack(&stk, NULL) < 0) {
2750
            perror("sigaltstack");
2751
            exit(1);
2752
        }
2753
    }
2754
#endif
2755
    {
2756
        struct sigaction act;
2757
        
2758
        sigfillset(&act.sa_mask);
2759
        act.sa_flags = SA_SIGINFO;
2760
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2761
        act.sa_flags |= SA_ONSTACK;
2762
#endif
2763
        act.sa_sigaction = host_segv_handler;
2764
        sigaction(SIGSEGV, &act, NULL);
2765
        sigaction(SIGBUS, &act, NULL);
2766
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2767
        sigaction(SIGFPE, &act, NULL);
2768
#endif
2769
    }
2770
#endif
2771

    
2772
#ifndef _WIN32
2773
    {
2774
        struct sigaction act;
2775
        sigfillset(&act.sa_mask);
2776
        act.sa_flags = 0;
2777
        act.sa_handler = SIG_IGN;
2778
        sigaction(SIGPIPE, &act, NULL);
2779
    }
2780
#endif
2781
    init_timers();
2782

    
2783
#if defined(TARGET_I386)
2784
    pc_init(ram_size, vga_ram_size, boot_device,
2785
            ds, fd_filename, snapshot,
2786
            kernel_filename, kernel_cmdline, initrd_filename);
2787
#elif defined(TARGET_PPC)
2788
    ppc_init(ram_size, vga_ram_size, boot_device,
2789
             ds, fd_filename, snapshot,
2790
             kernel_filename, kernel_cmdline, initrd_filename);
2791
#endif
2792

    
2793
    /* launched after the device init so that it can display or not a
2794
       banner */
2795
    monitor_init();
2796

    
2797
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2798
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2799

    
2800
#ifdef CONFIG_GDBSTUB
2801
    if (use_gdbstub) {
2802
        if (gdbserver_start(gdbstub_port) < 0) {
2803
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
2804
                    gdbstub_port);
2805
            exit(1);
2806
        } else {
2807
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
2808
        }
2809
    } else 
2810
#endif
2811
    if (start_emulation)
2812
    {
2813
        vm_start();
2814
    }
2815
    term_init();
2816
    main_loop();
2817
    quit_timers();
2818
    return 0;
2819
}