Statistics
| Branch: | Revision:

root / vl.c @ d1d9f421

History | View | Annotate | Download (72.5 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
#ifndef __APPLE__
44
#include <libutil.h>
45
#endif
46
#else
47
#include <linux/if.h>
48
#include <linux/if_tun.h>
49
#include <pty.h>
50
#include <malloc.h>
51
#include <linux/rtc.h>
52
#endif
53
#endif
54

    
55
#if defined(CONFIG_SLIRP)
56
#include "libslirp.h"
57
#endif
58

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

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

    
84
#include "disas.h"
85

    
86
#include "exec-all.h"
87

    
88
//#define DO_TB_FLUSH
89

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

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

    
95
#if !defined(CONFIG_SOFTMMU)
96
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
97
#else
98
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
99
#endif
100

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

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

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

    
143
/***********************************************************/
144
/* x86 ISA bus support */
145

    
146
target_phys_addr_t isa_mem_base = 0;
147

    
148
uint32_t default_ioport_readb(void *opaque, uint32_t address)
149
{
150
#ifdef DEBUG_UNUSED_IOPORT
151
    fprintf(stderr, "inb: port=0x%04x\n", address);
152
#endif
153
    return 0xff;
154
}
155

    
156
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
157
{
158
#ifdef DEBUG_UNUSED_IOPORT
159
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
160
#endif
161
}
162

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

    
173
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
174
{
175
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
176
    address = (address + 1) & (MAX_IOPORTS - 1);
177
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
178
}
179

    
180
uint32_t default_ioport_readl(void *opaque, uint32_t address)
181
{
182
#ifdef DEBUG_UNUSED_IOPORT
183
    fprintf(stderr, "inl: port=0x%04x\n", address);
184
#endif
185
    return 0xffffffff;
186
}
187

    
188
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
189
{
190
#ifdef DEBUG_UNUSED_IOPORT
191
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
192
#endif
193
}
194

    
195
void init_ioports(void)
196
{
197
    int i;
198

    
199
    for(i = 0; i < MAX_IOPORTS; i++) {
200
        ioport_read_table[0][i] = default_ioport_readb;
201
        ioport_write_table[0][i] = default_ioport_writeb;
202
        ioport_read_table[1][i] = default_ioport_readw;
203
        ioport_write_table[1][i] = default_ioport_writew;
204
        ioport_read_table[2][i] = default_ioport_readl;
205
        ioport_write_table[2][i] = default_ioport_writel;
206
    }
207
}
208

    
209
/* size is the word size in byte */
210
int register_ioport_read(int start, int length, int size, 
211
                         IOPortReadFunc *func, void *opaque)
212
{
213
    int i, bsize;
214

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

    
234
/* size is the word size in byte */
235
int register_ioport_write(int start, int length, int size, 
236
                          IOPortWriteFunc *func, void *opaque)
237
{
238
    int i, bsize;
239

    
240
    if (size == 1) {
241
        bsize = 0;
242
    } else if (size == 2) {
243
        bsize = 1;
244
    } else if (size == 4) {
245
        bsize = 2;
246
    } else {
247
        hw_error("register_ioport_write: invalid size");
248
        return -1;
249
    }
250
    for(i = start; i < start + length; i += size) {
251
        ioport_write_table[bsize][i] = func;
252
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
253
            hw_error("register_ioport_read: invalid opaque");
254
        ioport_opaque[i] = opaque;
255
    }
256
    return 0;
257
}
258

    
259
void isa_unassign_ioport(int start, int length)
260
{
261
    int i;
262

    
263
    for(i = start; i < start + length; i++) {
264
        ioport_read_table[0][i] = default_ioport_readb;
265
        ioport_read_table[1][i] = default_ioport_readw;
266
        ioport_read_table[2][i] = default_ioport_readl;
267

    
268
        ioport_write_table[0][i] = default_ioport_writeb;
269
        ioport_write_table[1][i] = default_ioport_writew;
270
        ioport_write_table[2][i] = default_ioport_writel;
271
    }
272
}
273

    
274
void pstrcpy(char *buf, int buf_size, const char *str)
275
{
276
    int c;
277
    char *q = buf;
278

    
279
    if (buf_size <= 0)
280
        return;
281

    
282
    for(;;) {
283
        c = *str++;
284
        if (c == 0 || q >= buf + buf_size - 1)
285
            break;
286
        *q++ = c;
287
    }
288
    *q = '\0';
289
}
290

    
291
/* strcat and truncate. */
292
char *pstrcat(char *buf, int buf_size, const char *s)
293
{
294
    int len;
295
    len = strlen(buf);
296
    if (len < buf_size) 
297
        pstrcpy(buf + len, buf_size - len, s);
298
    return buf;
299
}
300

    
301
/* return the size or -1 if error */
302
int get_image_size(const char *filename)
303
{
304
    int fd, size;
305
    fd = open(filename, O_RDONLY | O_BINARY);
306
    if (fd < 0)
307
        return -1;
308
    size = lseek(fd, 0, SEEK_END);
309
    close(fd);
310
    return size;
311
}
312

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

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

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

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

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

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

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

    
390
/***********************************************************/
391
void hw_error(const char *fmt, ...)
392
{
393
    va_list ap;
394

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

    
408
/***********************************************************/
409
/* keyboard/mouse */
410

    
411
static QEMUPutKBDEvent *qemu_put_kbd_event;
412
static void *qemu_put_kbd_event_opaque;
413
static QEMUPutMouseEvent *qemu_put_mouse_event;
414
static void *qemu_put_mouse_event_opaque;
415

    
416
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
417
{
418
    qemu_put_kbd_event_opaque = opaque;
419
    qemu_put_kbd_event = func;
420
}
421

    
422
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
423
{
424
    qemu_put_mouse_event_opaque = opaque;
425
    qemu_put_mouse_event = func;
426
}
427

    
428
void kbd_put_keycode(int keycode)
429
{
430
    if (qemu_put_kbd_event) {
431
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
432
    }
433
}
434

    
435
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
436
{
437
    if (qemu_put_mouse_event) {
438
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
439
                             dx, dy, dz, buttons_state);
440
    }
441
}
442

    
443
/***********************************************************/
444
/* timers */
445

    
446
#if defined(__powerpc__)
447

    
448
static inline uint32_t get_tbl(void) 
449
{
450
    uint32_t tbl;
451
    asm volatile("mftb %0" : "=r" (tbl));
452
    return tbl;
453
}
454

    
455
static inline uint32_t get_tbu(void) 
456
{
457
        uint32_t tbl;
458
        asm volatile("mftbu %0" : "=r" (tbl));
459
        return tbl;
460
}
461

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

    
474
#elif defined(__i386__)
475

    
476
int64_t cpu_get_real_ticks(void)
477
{
478
    int64_t val;
479
    asm volatile ("rdtsc" : "=A" (val));
480
    return val;
481
}
482

    
483
#elif defined(__x86_64__)
484

    
485
int64_t cpu_get_real_ticks(void)
486
{
487
    uint32_t low,high;
488
    int64_t val;
489
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
490
    val = high;
491
    val <<= 32;
492
    val |= low;
493
    return val;
494
}
495

    
496
#else
497
#error unsupported CPU
498
#endif
499

    
500
static int64_t cpu_ticks_offset;
501
static int cpu_ticks_enabled;
502

    
503
static inline int64_t cpu_get_ticks(void)
504
{
505
    if (!cpu_ticks_enabled) {
506
        return cpu_ticks_offset;
507
    } else {
508
        return cpu_get_real_ticks() + cpu_ticks_offset;
509
    }
510
}
511

    
512
/* enable cpu_get_ticks() */
513
void cpu_enable_ticks(void)
514
{
515
    if (!cpu_ticks_enabled) {
516
        cpu_ticks_offset -= cpu_get_real_ticks();
517
        cpu_ticks_enabled = 1;
518
    }
519
}
520

    
521
/* disable cpu_get_ticks() : the clock is stopped. You must not call
522
   cpu_get_ticks() after that.  */
523
void cpu_disable_ticks(void)
524
{
525
    if (cpu_ticks_enabled) {
526
        cpu_ticks_offset = cpu_get_ticks();
527
        cpu_ticks_enabled = 0;
528
    }
529
}
530

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

    
544
void cpu_calibrate_ticks(void)
545
{
546
    int64_t usec, ticks;
547

    
548
    usec = get_clock();
549
    ticks = cpu_get_real_ticks();
550
#ifdef _WIN32
551
    Sleep(50);
552
#else
553
    usleep(50 * 1000);
554
#endif
555
    usec = get_clock() - usec;
556
    ticks = cpu_get_real_ticks() - ticks;
557
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
558
}
559

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

    
575
    u.ll = a;
576
    rl = (uint64_t)u.l.low * (uint64_t)b;
577
    rh = (uint64_t)u.l.high * (uint64_t)b;
578
    rh += (rl >> 32);
579
    res.l.high = rh / c;
580
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
581
    return res.ll;
582
}
583

    
584
#define QEMU_TIMER_REALTIME 0
585
#define QEMU_TIMER_VIRTUAL  1
586

    
587
struct QEMUClock {
588
    int type;
589
    /* XXX: add frequency */
590
};
591

    
592
struct QEMUTimer {
593
    QEMUClock *clock;
594
    int64_t expire_time;
595
    QEMUTimerCB *cb;
596
    void *opaque;
597
    struct QEMUTimer *next;
598
};
599

    
600
QEMUClock *rt_clock;
601
QEMUClock *vm_clock;
602

    
603
static QEMUTimer *active_timers[2];
604
#ifdef _WIN32
605
static MMRESULT timerID;
606
#else
607
/* frequency of the times() clock tick */
608
static int timer_freq;
609
#endif
610

    
611
QEMUClock *qemu_new_clock(int type)
612
{
613
    QEMUClock *clock;
614
    clock = qemu_mallocz(sizeof(QEMUClock));
615
    if (!clock)
616
        return NULL;
617
    clock->type = type;
618
    return clock;
619
}
620

    
621
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
622
{
623
    QEMUTimer *ts;
624

    
625
    ts = qemu_mallocz(sizeof(QEMUTimer));
626
    ts->clock = clock;
627
    ts->cb = cb;
628
    ts->opaque = opaque;
629
    return ts;
630
}
631

    
632
void qemu_free_timer(QEMUTimer *ts)
633
{
634
    qemu_free(ts);
635
}
636

    
637
/* stop a timer, but do not dealloc it */
638
void qemu_del_timer(QEMUTimer *ts)
639
{
640
    QEMUTimer **pt, *t;
641

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

    
657
/* modify the current timer so that it will be fired when current_time
658
   >= expire_time. The corresponding callback will be called. */
659
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
660
{
661
    QEMUTimer **pt, *t;
662

    
663
    qemu_del_timer(ts);
664

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

    
682
int qemu_timer_pending(QEMUTimer *ts)
683
{
684
    QEMUTimer *t;
685
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
686
        if (t == ts)
687
            return 1;
688
    }
689
    return 0;
690
}
691

    
692
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
693
{
694
    if (!timer_head)
695
        return 0;
696
    return (timer_head->expire_time <= current_time);
697
}
698

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

    
716
int64_t qemu_get_clock(QEMUClock *clock)
717
{
718
    switch(clock->type) {
719
    case QEMU_TIMER_REALTIME:
720
#ifdef _WIN32
721
        return GetTickCount();
722
#else
723
        {
724
            struct tms tp;
725

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

    
742
/* save a timer */
743
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
744
{
745
    uint64_t expire_time;
746

    
747
    if (qemu_timer_pending(ts)) {
748
        expire_time = ts->expire_time;
749
    } else {
750
        expire_time = -1;
751
    }
752
    qemu_put_be64(f, expire_time);
753
}
754

    
755
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
756
{
757
    uint64_t expire_time;
758

    
759
    expire_time = qemu_get_be64(f);
760
    if (expire_time != -1) {
761
        qemu_mod_timer(ts, expire_time);
762
    } else {
763
        qemu_del_timer(ts);
764
    }
765
}
766

    
767
static void timer_save(QEMUFile *f, void *opaque)
768
{
769
    if (cpu_ticks_enabled) {
770
        hw_error("cannot save state if virtual timers are running");
771
    }
772
    qemu_put_be64s(f, &cpu_ticks_offset);
773
    qemu_put_be64s(f, &ticks_per_sec);
774
}
775

    
776
static int timer_load(QEMUFile *f, void *opaque, int version_id)
777
{
778
    if (version_id != 1)
779
        return -EINVAL;
780
    if (cpu_ticks_enabled) {
781
        return -EINVAL;
782
    }
783
    qemu_get_be64s(f, &cpu_ticks_offset);
784
    qemu_get_be64s(f, &ticks_per_sec);
785
    return 0;
786
}
787

    
788
#ifdef _WIN32
789
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
790
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
791
#else
792
static void host_alarm_handler(int host_signum)
793
#endif
794
{
795
#if 0
796
#define DISP_FREQ 1000
797
    {
798
        static int64_t delta_min = INT64_MAX;
799
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
800
        static int count;
801
        ti = qemu_get_clock(vm_clock);
802
        if (last_clock != 0) {
803
            delta = ti - last_clock;
804
            if (delta < delta_min)
805
                delta_min = delta;
806
            if (delta > delta_max)
807
                delta_max = delta;
808
            delta_cum += delta;
809
            if (++count == DISP_FREQ) {
810
                printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
811
                       muldiv64(delta_min, 1000000, ticks_per_sec),
812
                       muldiv64(delta_max, 1000000, ticks_per_sec),
813
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
814
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
815
                count = 0;
816
                delta_min = INT64_MAX;
817
                delta_max = 0;
818
                delta_cum = 0;
819
            }
820
        }
821
        last_clock = ti;
822
    }
823
#endif
824
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
825
                           qemu_get_clock(vm_clock)) ||
826
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
827
                           qemu_get_clock(rt_clock))) {
828
        /* stop the cpu because a timer occured */
829
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
830
    }
831
}
832

    
833
#ifndef _WIN32
834

    
835
#if defined(__linux__)
836

    
837
#define RTC_FREQ 1024
838

    
839
static int rtc_fd;
840

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

    
861
#else
862

    
863
static int start_rtc_timer(void)
864
{
865
    return -1;
866
}
867

    
868
#endif /* !defined(__linux__) */
869

    
870
#endif /* !defined(_WIN32) */
871

    
872
static void init_timers(void)
873
{
874
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
875
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
876

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

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

    
917
#if defined(__linux__)
918
        if (itv.it_interval.tv_usec > 1000) {
919
            /* try to use /dev/rtc to have a faster timer */
920
            if (start_rtc_timer() < 0)
921
                goto use_itimer;
922
            /* disable itimer */
923
            itv.it_interval.tv_sec = 0;
924
            itv.it_interval.tv_usec = 0;
925
            itv.it_value.tv_sec = 0;
926
            itv.it_value.tv_usec = 0;
927
            setitimer(ITIMER_REAL, &itv, NULL);
928

    
929
            /* use the RTC */
930
            sigaction(SIGIO, &act, NULL);
931
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
932
            fcntl(rtc_fd, F_SETOWN, getpid());
933
        } else 
934
#endif /* defined(__linux__) */
935
        {
936
        use_itimer:
937
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
938
                                   PIT_FREQ) / 1000000;
939
        }
940
    }
941
#endif
942
}
943

    
944
void quit_timers(void)
945
{
946
#ifdef _WIN32
947
    timeKillEvent(timerID);
948
#endif
949
}
950

    
951
/***********************************************************/
952
/* serial device */
953

    
954
#ifdef _WIN32
955

    
956
int serial_open_device(void)
957
{
958
    return -1;
959
}
960

    
961
#else
962

    
963
int serial_open_device(void)
964
{
965
    if (serial_console == NULL && nographic) {
966
        /* use console for serial port */
967
        return 0;
968
    } else {
969
#if 0
970
        char slave_name[1024];
971
        int master_fd, slave_fd;
972
        
973
        /* Not satisfying */
974
        if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
975
            fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
976
            return -1;
977
        }
978
        fprintf(stderr, "Serial port redirected to %s\n", slave_name);
979
        return master_fd;
980
#else
981
        return -1;
982
#endif
983
    }
984
}
985

    
986
#endif
987

    
988
/***********************************************************/
989
/* Linux network device redirectors */
990

    
991
void hex_dump(FILE *f, const uint8_t *buf, int size)
992
{
993
    int len, i, j, c;
994

    
995
    for(i=0;i<size;i+=16) {
996
        len = size - i;
997
        if (len > 16)
998
            len = 16;
999
        fprintf(f, "%08x ", i);
1000
        for(j=0;j<16;j++) {
1001
            if (j < len)
1002
                fprintf(f, " %02x", buf[i+j]);
1003
            else
1004
                fprintf(f, "   ");
1005
        }
1006
        fprintf(f, " ");
1007
        for(j=0;j<len;j++) {
1008
            c = buf[i+j];
1009
            if (c < ' ' || c > '~')
1010
                c = '.';
1011
            fprintf(f, "%c", c);
1012
        }
1013
        fprintf(f, "\n");
1014
    }
1015
}
1016

    
1017
void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1018
{
1019
    nd->send_packet(nd, buf, size);
1020
}
1021

    
1022
void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
1023
                          IOReadHandler *fd_read, void *opaque)
1024
{
1025
    nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1026
}
1027

    
1028
/* dummy network adapter */
1029

    
1030
static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1031
{
1032
}
1033

    
1034
static void dummy_add_read_packet(NetDriverState *nd, 
1035
                                  IOCanRWHandler *fd_can_read, 
1036
                                  IOReadHandler *fd_read, void *opaque)
1037
{
1038
}
1039

    
1040
static int net_dummy_init(NetDriverState *nd)
1041
{
1042
    nd->send_packet = dummy_send_packet;
1043
    nd->add_read_packet = dummy_add_read_packet;
1044
    pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1045
    return 0;
1046
}
1047

    
1048
#if defined(CONFIG_SLIRP)
1049

    
1050
/* slirp network adapter */
1051

    
1052
static void *slirp_fd_opaque;
1053
static IOCanRWHandler *slirp_fd_can_read;
1054
static IOReadHandler *slirp_fd_read;
1055
static int slirp_inited;
1056

    
1057
int slirp_can_output(void)
1058
{
1059
    return slirp_fd_can_read(slirp_fd_opaque);
1060
}
1061

    
1062
void slirp_output(const uint8_t *pkt, int pkt_len)
1063
{
1064
#if 0
1065
    printf("output:\n");
1066
    hex_dump(stdout, pkt, pkt_len);
1067
#endif
1068
    slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1069
}
1070

    
1071
static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1072
{
1073
#if 0
1074
    printf("input:\n");
1075
    hex_dump(stdout, buf, size);
1076
#endif
1077
    slirp_input(buf, size);
1078
}
1079

    
1080
static void slirp_add_read_packet(NetDriverState *nd, 
1081
                                  IOCanRWHandler *fd_can_read, 
1082
                                  IOReadHandler *fd_read, void *opaque)
1083
{
1084
    slirp_fd_opaque = opaque;
1085
    slirp_fd_can_read = fd_can_read;
1086
    slirp_fd_read = fd_read;
1087
}
1088

    
1089
static int net_slirp_init(NetDriverState *nd)
1090
{
1091
    if (!slirp_inited) {
1092
        slirp_inited = 1;
1093
        slirp_init();
1094
    }
1095
    nd->send_packet = slirp_send_packet;
1096
    nd->add_read_packet = slirp_add_read_packet;
1097
    pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1098
    return 0;
1099
}
1100

    
1101
#endif /* CONFIG_SLIRP */
1102

    
1103
#if !defined(_WIN32)
1104
#ifdef _BSD
1105
static int tun_open(char *ifname, int ifname_size)
1106
{
1107
    int fd;
1108
    char *dev;
1109
    struct stat s;
1110

    
1111
    fd = open("/dev/tap", O_RDWR);
1112
    if (fd < 0) {
1113
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1114
        return -1;
1115
    }
1116

    
1117
    fstat(fd, &s);
1118
    dev = devname(s.st_rdev, S_IFCHR);
1119
    pstrcpy(ifname, ifname_size, dev);
1120

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

    
1151
static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1152
{
1153
    write(nd->fd, buf, size);
1154
}
1155

    
1156
static void tun_add_read_packet(NetDriverState *nd, 
1157
                                IOCanRWHandler *fd_can_read, 
1158
                                IOReadHandler *fd_read, void *opaque)
1159
{
1160
    qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1161
}
1162

    
1163
static int net_tun_init(NetDriverState *nd)
1164
{
1165
    int pid, status;
1166
    char *args[3];
1167
    char **parg;
1168

    
1169
    nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1170
    if (nd->fd < 0)
1171
        return -1;
1172

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

    
1196
static int net_fd_init(NetDriverState *nd, int fd)
1197
{
1198
    nd->fd = fd;
1199
    nd->send_packet = tun_send_packet;
1200
    nd->add_read_packet = tun_add_read_packet;
1201
    pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1202
    return 0;
1203
}
1204

    
1205
#endif /* !_WIN32 */
1206

    
1207
/***********************************************************/
1208
/* dumb display */
1209

    
1210
#ifdef _WIN32
1211

    
1212
static void term_exit(void)
1213
{
1214
}
1215

    
1216
static void term_init(void)
1217
{
1218
}
1219

    
1220
#else
1221

    
1222
/* init terminal so that we can grab keys */
1223
static struct termios oldtty;
1224
static int old_fd0_flags;
1225

    
1226
static void term_exit(void)
1227
{
1228
    tcsetattr (0, TCSANOW, &oldtty);
1229
    fcntl(0, F_SETFL, old_fd0_flags);
1230
}
1231

    
1232
static void term_init(void)
1233
{
1234
    struct termios tty;
1235

    
1236
    tcgetattr (0, &tty);
1237
    oldtty = tty;
1238
    old_fd0_flags = fcntl(0, F_GETFL);
1239

    
1240
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1241
                          |INLCR|IGNCR|ICRNL|IXON);
1242
    tty.c_oflag |= OPOST;
1243
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1244
    /* if graphical mode, we allow Ctrl-C handling */
1245
    if (nographic)
1246
        tty.c_lflag &= ~ISIG;
1247
    tty.c_cflag &= ~(CSIZE|PARENB);
1248
    tty.c_cflag |= CS8;
1249
    tty.c_cc[VMIN] = 1;
1250
    tty.c_cc[VTIME] = 0;
1251
    
1252
    tcsetattr (0, TCSANOW, &tty);
1253

    
1254
    atexit(term_exit);
1255

    
1256
    fcntl(0, F_SETFL, O_NONBLOCK);
1257
}
1258

    
1259
#endif
1260

    
1261
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1262
{
1263
}
1264

    
1265
static void dumb_resize(DisplayState *ds, int w, int h)
1266
{
1267
}
1268

    
1269
static void dumb_refresh(DisplayState *ds)
1270
{
1271
    vga_update_display();
1272
}
1273

    
1274
void dumb_display_init(DisplayState *ds)
1275
{
1276
    ds->data = NULL;
1277
    ds->linesize = 0;
1278
    ds->depth = 0;
1279
    ds->dpy_update = dumb_update;
1280
    ds->dpy_resize = dumb_resize;
1281
    ds->dpy_refresh = dumb_refresh;
1282
}
1283

    
1284
#if !defined(CONFIG_SOFTMMU)
1285
/***********************************************************/
1286
/* cpu signal handler */
1287
static void host_segv_handler(int host_signum, siginfo_t *info, 
1288
                              void *puc)
1289
{
1290
    if (cpu_signal_handler(host_signum, info, puc))
1291
        return;
1292
    term_exit();
1293
    abort();
1294
}
1295
#endif
1296

    
1297
/***********************************************************/
1298
/* I/O handling */
1299

    
1300
#define MAX_IO_HANDLERS 64
1301

    
1302
typedef struct IOHandlerRecord {
1303
    int fd;
1304
    IOCanRWHandler *fd_can_read;
1305
    IOReadHandler *fd_read;
1306
    void *opaque;
1307
    /* temporary data */
1308
    struct pollfd *ufd;
1309
    int max_size;
1310
    struct IOHandlerRecord *next;
1311
} IOHandlerRecord;
1312

    
1313
static IOHandlerRecord *first_io_handler;
1314

    
1315
int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1316
                             IOReadHandler *fd_read, void *opaque)
1317
{
1318
    IOHandlerRecord *ioh;
1319

    
1320
    ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1321
    if (!ioh)
1322
        return -1;
1323
    ioh->fd = fd;
1324
    ioh->fd_can_read = fd_can_read;
1325
    ioh->fd_read = fd_read;
1326
    ioh->opaque = opaque;
1327
    ioh->next = first_io_handler;
1328
    first_io_handler = ioh;
1329
    return 0;
1330
}
1331

    
1332
void qemu_del_fd_read_handler(int fd)
1333
{
1334
    IOHandlerRecord **pioh, *ioh;
1335

    
1336
    pioh = &first_io_handler;
1337
    for(;;) {
1338
        ioh = *pioh;
1339
        if (ioh == NULL)
1340
            break;
1341
        if (ioh->fd == fd) {
1342
            *pioh = ioh->next;
1343
            break;
1344
        }
1345
        pioh = &ioh->next;
1346
    }
1347
}
1348

    
1349
/***********************************************************/
1350
/* savevm/loadvm support */
1351

    
1352
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1353
{
1354
    fwrite(buf, 1, size, f);
1355
}
1356

    
1357
void qemu_put_byte(QEMUFile *f, int v)
1358
{
1359
    fputc(v, f);
1360
}
1361

    
1362
void qemu_put_be16(QEMUFile *f, unsigned int v)
1363
{
1364
    qemu_put_byte(f, v >> 8);
1365
    qemu_put_byte(f, v);
1366
}
1367

    
1368
void qemu_put_be32(QEMUFile *f, unsigned int v)
1369
{
1370
    qemu_put_byte(f, v >> 24);
1371
    qemu_put_byte(f, v >> 16);
1372
    qemu_put_byte(f, v >> 8);
1373
    qemu_put_byte(f, v);
1374
}
1375

    
1376
void qemu_put_be64(QEMUFile *f, uint64_t v)
1377
{
1378
    qemu_put_be32(f, v >> 32);
1379
    qemu_put_be32(f, v);
1380
}
1381

    
1382
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1383
{
1384
    return fread(buf, 1, size, f);
1385
}
1386

    
1387
int qemu_get_byte(QEMUFile *f)
1388
{
1389
    int v;
1390
    v = fgetc(f);
1391
    if (v == EOF)
1392
        return 0;
1393
    else
1394
        return v;
1395
}
1396

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

    
1405
unsigned int qemu_get_be32(QEMUFile *f)
1406
{
1407
    unsigned int v;
1408
    v = qemu_get_byte(f) << 24;
1409
    v |= qemu_get_byte(f) << 16;
1410
    v |= qemu_get_byte(f) << 8;
1411
    v |= qemu_get_byte(f);
1412
    return v;
1413
}
1414

    
1415
uint64_t qemu_get_be64(QEMUFile *f)
1416
{
1417
    uint64_t v;
1418
    v = (uint64_t)qemu_get_be32(f) << 32;
1419
    v |= qemu_get_be32(f);
1420
    return v;
1421
}
1422

    
1423
int64_t qemu_ftell(QEMUFile *f)
1424
{
1425
    return ftell(f);
1426
}
1427

    
1428
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1429
{
1430
    if (fseek(f, pos, whence) < 0)
1431
        return -1;
1432
    return ftell(f);
1433
}
1434

    
1435
typedef struct SaveStateEntry {
1436
    char idstr[256];
1437
    int instance_id;
1438
    int version_id;
1439
    SaveStateHandler *save_state;
1440
    LoadStateHandler *load_state;
1441
    void *opaque;
1442
    struct SaveStateEntry *next;
1443
} SaveStateEntry;
1444

    
1445
static SaveStateEntry *first_se;
1446

    
1447
int register_savevm(const char *idstr, 
1448
                    int instance_id, 
1449
                    int version_id,
1450
                    SaveStateHandler *save_state,
1451
                    LoadStateHandler *load_state,
1452
                    void *opaque)
1453
{
1454
    SaveStateEntry *se, **pse;
1455

    
1456
    se = qemu_malloc(sizeof(SaveStateEntry));
1457
    if (!se)
1458
        return -1;
1459
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1460
    se->instance_id = instance_id;
1461
    se->version_id = version_id;
1462
    se->save_state = save_state;
1463
    se->load_state = load_state;
1464
    se->opaque = opaque;
1465
    se->next = NULL;
1466

    
1467
    /* add at the end of list */
1468
    pse = &first_se;
1469
    while (*pse != NULL)
1470
        pse = &(*pse)->next;
1471
    *pse = se;
1472
    return 0;
1473
}
1474

    
1475
#define QEMU_VM_FILE_MAGIC   0x5145564d
1476
#define QEMU_VM_FILE_VERSION 0x00000001
1477

    
1478
int qemu_savevm(const char *filename)
1479
{
1480
    SaveStateEntry *se;
1481
    QEMUFile *f;
1482
    int len, len_pos, cur_pos, saved_vm_running, ret;
1483

    
1484
    saved_vm_running = vm_running;
1485
    vm_stop(0);
1486

    
1487
    f = fopen(filename, "wb");
1488
    if (!f) {
1489
        ret = -1;
1490
        goto the_end;
1491
    }
1492

    
1493
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1494
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1495

    
1496
    for(se = first_se; se != NULL; se = se->next) {
1497
        /* ID string */
1498
        len = strlen(se->idstr);
1499
        qemu_put_byte(f, len);
1500
        qemu_put_buffer(f, se->idstr, len);
1501

    
1502
        qemu_put_be32(f, se->instance_id);
1503
        qemu_put_be32(f, se->version_id);
1504

    
1505
        /* record size: filled later */
1506
        len_pos = ftell(f);
1507
        qemu_put_be32(f, 0);
1508
        
1509
        se->save_state(f, se->opaque);
1510

    
1511
        /* fill record size */
1512
        cur_pos = ftell(f);
1513
        len = ftell(f) - len_pos - 4;
1514
        fseek(f, len_pos, SEEK_SET);
1515
        qemu_put_be32(f, len);
1516
        fseek(f, cur_pos, SEEK_SET);
1517
    }
1518

    
1519
    fclose(f);
1520
    ret = 0;
1521
 the_end:
1522
    if (saved_vm_running)
1523
        vm_start();
1524
    return ret;
1525
}
1526

    
1527
static SaveStateEntry *find_se(const char *idstr, int instance_id)
1528
{
1529
    SaveStateEntry *se;
1530

    
1531
    for(se = first_se; se != NULL; se = se->next) {
1532
        if (!strcmp(se->idstr, idstr) && 
1533
            instance_id == se->instance_id)
1534
            return se;
1535
    }
1536
    return NULL;
1537
}
1538

    
1539
int qemu_loadvm(const char *filename)
1540
{
1541
    SaveStateEntry *se;
1542
    QEMUFile *f;
1543
    int len, cur_pos, ret, instance_id, record_len, version_id;
1544
    int saved_vm_running;
1545
    unsigned int v;
1546
    char idstr[256];
1547
    
1548
    saved_vm_running = vm_running;
1549
    vm_stop(0);
1550

    
1551
    f = fopen(filename, "rb");
1552
    if (!f) {
1553
        ret = -1;
1554
        goto the_end;
1555
    }
1556

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

    
1606
/***********************************************************/
1607
/* cpu save/restore */
1608

    
1609
#if defined(TARGET_I386)
1610

    
1611
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1612
{
1613
    qemu_put_be32(f, dt->selector);
1614
    qemu_put_be32(f, (uint32_t)dt->base);
1615
    qemu_put_be32(f, dt->limit);
1616
    qemu_put_be32(f, dt->flags);
1617
}
1618

    
1619
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1620
{
1621
    dt->selector = qemu_get_be32(f);
1622
    dt->base = (uint8_t *)qemu_get_be32(f);
1623
    dt->limit = qemu_get_be32(f);
1624
    dt->flags = qemu_get_be32(f);
1625
}
1626

    
1627
void cpu_save(QEMUFile *f, void *opaque)
1628
{
1629
    CPUState *env = opaque;
1630
    uint16_t fptag, fpus, fpuc;
1631
    uint32_t hflags;
1632
    int i;
1633

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

    
1657
    for(i = 0; i < 8; i++) {
1658
        uint64_t mant;
1659
        uint16_t exp;
1660
        cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1661
        qemu_put_be64(f, mant);
1662
        qemu_put_be16(f, exp);
1663
    }
1664

    
1665
    for(i = 0; i < 6; i++)
1666
        cpu_put_seg(f, &env->segs[i]);
1667
    cpu_put_seg(f, &env->ldt);
1668
    cpu_put_seg(f, &env->tr);
1669
    cpu_put_seg(f, &env->gdt);
1670
    cpu_put_seg(f, &env->idt);
1671
    
1672
    qemu_put_be32s(f, &env->sysenter_cs);
1673
    qemu_put_be32s(f, &env->sysenter_esp);
1674
    qemu_put_be32s(f, &env->sysenter_eip);
1675
    
1676
    qemu_put_be32s(f, &env->cr[0]);
1677
    qemu_put_be32s(f, &env->cr[2]);
1678
    qemu_put_be32s(f, &env->cr[3]);
1679
    qemu_put_be32s(f, &env->cr[4]);
1680
    
1681
    for(i = 0; i < 8; i++)
1682
        qemu_put_be32s(f, &env->dr[i]);
1683

    
1684
    /* MMU */
1685
    qemu_put_be32s(f, &env->a20_mask);
1686
}
1687

    
1688
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1689
{
1690
    CPUState *env = opaque;
1691
    int i;
1692
    uint32_t hflags;
1693
    uint16_t fpus, fpuc, fptag;
1694

    
1695
    if (version_id != 2)
1696
        return -EINVAL;
1697
    for(i = 0; i < 8; i++)
1698
        qemu_get_be32s(f, &env->regs[i]);
1699
    qemu_get_be32s(f, &env->eip);
1700
    qemu_get_be32s(f, &env->eflags);
1701
    qemu_get_be32s(f, &env->eflags);
1702
    qemu_get_be32s(f, &hflags);
1703

    
1704
    qemu_get_be16s(f, &fpuc);
1705
    qemu_get_be16s(f, &fpus);
1706
    qemu_get_be16s(f, &fptag);
1707

    
1708
    for(i = 0; i < 8; i++) {
1709
        uint64_t mant;
1710
        uint16_t exp;
1711
        mant = qemu_get_be64(f);
1712
        exp = qemu_get_be16(f);
1713
        env->fpregs[i] = cpu_set_fp80(mant, exp);
1714
    }
1715

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

    
1743
    /* MMU */
1744
    qemu_get_be32s(f, &env->a20_mask);
1745

    
1746
    /* XXX: compute hflags from scratch, except for CPL and IIF */
1747
    env->hflags = hflags;
1748
    tlb_flush(env, 1);
1749
    return 0;
1750
}
1751

    
1752
#elif defined(TARGET_PPC)
1753
void cpu_save(QEMUFile *f, void *opaque)
1754
{
1755
}
1756

    
1757
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1758
{
1759
    return 0;
1760
}
1761
#else
1762

    
1763
#warning No CPU save/restore functions
1764

    
1765
#endif
1766

    
1767
/***********************************************************/
1768
/* ram save/restore */
1769

    
1770
/* we just avoid storing empty pages */
1771
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1772
{
1773
    int i, v;
1774

    
1775
    v = buf[0];
1776
    for(i = 1; i < len; i++) {
1777
        if (buf[i] != v)
1778
            goto normal_save;
1779
    }
1780
    qemu_put_byte(f, 1);
1781
    qemu_put_byte(f, v);
1782
    return;
1783
 normal_save:
1784
    qemu_put_byte(f, 0); 
1785
    qemu_put_buffer(f, buf, len);
1786
}
1787

    
1788
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1789
{
1790
    int v;
1791

    
1792
    v = qemu_get_byte(f);
1793
    switch(v) {
1794
    case 0:
1795
        if (qemu_get_buffer(f, buf, len) != len)
1796
            return -EIO;
1797
        break;
1798
    case 1:
1799
        v = qemu_get_byte(f);
1800
        memset(buf, v, len);
1801
        break;
1802
    default:
1803
        return -EINVAL;
1804
    }
1805
    return 0;
1806
}
1807

    
1808
static void ram_save(QEMUFile *f, void *opaque)
1809
{
1810
    int i;
1811
    qemu_put_be32(f, phys_ram_size);
1812
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1813
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1814
    }
1815
}
1816

    
1817
static int ram_load(QEMUFile *f, void *opaque, int version_id)
1818
{
1819
    int i, ret;
1820

    
1821
    if (version_id != 1)
1822
        return -EINVAL;
1823
    if (qemu_get_be32(f) != phys_ram_size)
1824
        return -EINVAL;
1825
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1826
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1827
        if (ret)
1828
            return ret;
1829
    }
1830
    return 0;
1831
}
1832

    
1833
/***********************************************************/
1834
/* main execution loop */
1835

    
1836
void gui_update(void *opaque)
1837
{
1838
    display_state.dpy_refresh(&display_state);
1839
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1840
}
1841

    
1842
/* XXX: support several handlers */
1843
VMStopHandler *vm_stop_cb;
1844
VMStopHandler *vm_stop_opaque;
1845

    
1846
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1847
{
1848
    vm_stop_cb = cb;
1849
    vm_stop_opaque = opaque;
1850
    return 0;
1851
}
1852

    
1853
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1854
{
1855
    vm_stop_cb = NULL;
1856
}
1857

    
1858
void vm_start(void)
1859
{
1860
    if (!vm_running) {
1861
        cpu_enable_ticks();
1862
        vm_running = 1;
1863
    }
1864
}
1865

    
1866
void vm_stop(int reason) 
1867
{
1868
    if (vm_running) {
1869
        cpu_disable_ticks();
1870
        vm_running = 0;
1871
        if (reason != 0) {
1872
            if (vm_stop_cb) {
1873
                vm_stop_cb(vm_stop_opaque, reason);
1874
            }
1875
        }
1876
    }
1877
}
1878

    
1879
/* reset/shutdown handler */
1880

    
1881
typedef struct QEMUResetEntry {
1882
    QEMUResetHandler *func;
1883
    void *opaque;
1884
    struct QEMUResetEntry *next;
1885
} QEMUResetEntry;
1886

    
1887
static QEMUResetEntry *first_reset_entry;
1888
static int reset_requested;
1889
static int shutdown_requested;
1890

    
1891
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1892
{
1893
    QEMUResetEntry **pre, *re;
1894

    
1895
    pre = &first_reset_entry;
1896
    while (*pre != NULL)
1897
        pre = &(*pre)->next;
1898
    re = qemu_mallocz(sizeof(QEMUResetEntry));
1899
    re->func = func;
1900
    re->opaque = opaque;
1901
    re->next = NULL;
1902
    *pre = re;
1903
}
1904

    
1905
void qemu_system_reset(void)
1906
{
1907
    QEMUResetEntry *re;
1908

    
1909
    /* reset all devices */
1910
    for(re = first_reset_entry; re != NULL; re = re->next) {
1911
        re->func(re->opaque);
1912
    }
1913
}
1914

    
1915
void qemu_system_reset_request(void)
1916
{
1917
    reset_requested = 1;
1918
    cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1919
}
1920

    
1921
void qemu_system_shutdown_request(void)
1922
{
1923
    shutdown_requested = 1;
1924
    cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1925
}
1926

    
1927
static void main_cpu_reset(void *opaque)
1928
{
1929
#ifdef TARGET_I386
1930
    CPUState *env = opaque;
1931
    cpu_reset(env);
1932
#endif
1933
}
1934

    
1935
int main_loop(void)
1936
{
1937
#ifndef _WIN32
1938
    struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1939
    IOHandlerRecord *ioh, *ioh_next;
1940
    uint8_t buf[4096];
1941
    int n, max_size;
1942
#endif
1943
    int ret, timeout;
1944
    CPUState *env = global_env;
1945

    
1946
    for(;;) {
1947
        if (vm_running) {
1948
            ret = cpu_exec(env);
1949
            if (shutdown_requested) {
1950
                ret = EXCP_INTERRUPT; 
1951
                break;
1952
            }
1953
            if (reset_requested) {
1954
                reset_requested = 0;
1955
                qemu_system_reset();
1956
                ret = EXCP_INTERRUPT; 
1957
            }
1958
            if (ret == EXCP_DEBUG) {
1959
                vm_stop(EXCP_DEBUG);
1960
            }
1961
            /* if hlt instruction, we wait until the next IRQ */
1962
            /* XXX: use timeout computed from timers */
1963
            if (ret == EXCP_HLT) 
1964
                timeout = 10;
1965
            else
1966
                timeout = 0;
1967
        } else {
1968
            timeout = 10;
1969
        }
1970

    
1971
#ifdef _WIN32
1972
        if (timeout > 0)
1973
            Sleep(timeout);
1974
#else
1975

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

    
2026
#if defined(CONFIG_SLIRP)
2027
        /* XXX: merge with poll() */
2028
        if (slirp_inited) {
2029
            fd_set rfds, wfds, xfds;
2030
            int nfds;
2031
            struct timeval tv;
2032

    
2033
            nfds = -1;
2034
            FD_ZERO(&rfds);
2035
            FD_ZERO(&wfds);
2036
            FD_ZERO(&xfds);
2037
            slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2038
            tv.tv_sec = 0;
2039
            tv.tv_usec = 0;
2040
            ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2041
            if (ret >= 0) {
2042
                slirp_select_poll(&rfds, &wfds, &xfds);
2043
            }
2044
        }
2045
#endif
2046

    
2047
#endif
2048

    
2049
        if (vm_running) {
2050
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
2051
                            qemu_get_clock(vm_clock));
2052
            
2053
            if (audio_enabled) {
2054
                /* XXX: add explicit timer */
2055
                SB16_run();
2056
            }
2057
            
2058
            /* run dma transfers, if any */
2059
            DMA_run();
2060
        }
2061

    
2062
        /* real time timers */
2063
        qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
2064
                        qemu_get_clock(rt_clock));
2065
    }
2066
    cpu_disable_ticks();
2067
    return ret;
2068
}
2069

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

    
2144
#define HAS_ARG 0x0001
2145

    
2146
enum {
2147
    QEMU_OPTION_h,
2148

    
2149
    QEMU_OPTION_fda,
2150
    QEMU_OPTION_fdb,
2151
    QEMU_OPTION_hda,
2152
    QEMU_OPTION_hdb,
2153
    QEMU_OPTION_hdc,
2154
    QEMU_OPTION_hdd,
2155
    QEMU_OPTION_cdrom,
2156
    QEMU_OPTION_boot,
2157
    QEMU_OPTION_snapshot,
2158
    QEMU_OPTION_m,
2159
    QEMU_OPTION_nographic,
2160
    QEMU_OPTION_enable_audio,
2161

    
2162
    QEMU_OPTION_nics,
2163
    QEMU_OPTION_macaddr,
2164
    QEMU_OPTION_n,
2165
    QEMU_OPTION_tun_fd,
2166
    QEMU_OPTION_user_net,
2167
    QEMU_OPTION_dummy_net,
2168

    
2169
    QEMU_OPTION_kernel,
2170
    QEMU_OPTION_append,
2171
    QEMU_OPTION_initrd,
2172

    
2173
    QEMU_OPTION_S,
2174
    QEMU_OPTION_s,
2175
    QEMU_OPTION_p,
2176
    QEMU_OPTION_d,
2177
    QEMU_OPTION_hdachs,
2178
    QEMU_OPTION_L,
2179
    QEMU_OPTION_no_code_copy,
2180
    QEMU_OPTION_pci,
2181
    QEMU_OPTION_isa,
2182
    QEMU_OPTION_prep,
2183
    QEMU_OPTION_localtime,
2184
    QEMU_OPTION_cirrusvga,
2185
    QEMU_OPTION_g,
2186
    QEMU_OPTION_std_vga,
2187
};
2188

    
2189
typedef struct QEMUOption {
2190
    const char *name;
2191
    int flags;
2192
    int index;
2193
} QEMUOption;
2194

    
2195
const QEMUOption qemu_options[] = {
2196
    { "h", 0, QEMU_OPTION_h },
2197

    
2198
    { "fda", HAS_ARG, QEMU_OPTION_fda },
2199
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2200
    { "hda", HAS_ARG, QEMU_OPTION_hda },
2201
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2202
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2203
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2204
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2205
    { "boot", HAS_ARG, QEMU_OPTION_boot },
2206
    { "snapshot", 0, QEMU_OPTION_snapshot },
2207
    { "m", HAS_ARG, QEMU_OPTION_m },
2208
    { "nographic", 0, QEMU_OPTION_nographic },
2209
    { "enable-audio", 0, QEMU_OPTION_enable_audio },
2210

    
2211
    { "nics", HAS_ARG, QEMU_OPTION_nics},
2212
    { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2213
    { "n", HAS_ARG, QEMU_OPTION_n },
2214
    { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2215
#ifdef CONFIG_SLIRP
2216
    { "user-net", 0, QEMU_OPTION_user_net },
2217
#endif
2218
    { "dummy-net", 0, QEMU_OPTION_dummy_net },
2219

    
2220
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2221
    { "append", HAS_ARG, QEMU_OPTION_append },
2222
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2223

    
2224
    { "S", 0, QEMU_OPTION_S },
2225
    { "s", 0, QEMU_OPTION_s },
2226
    { "p", HAS_ARG, QEMU_OPTION_p },
2227
    { "d", HAS_ARG, QEMU_OPTION_d },
2228
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2229
    { "L", HAS_ARG, QEMU_OPTION_L },
2230
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2231
#ifdef TARGET_PPC
2232
    { "prep", 0, QEMU_OPTION_prep },
2233
    { "g", 1, QEMU_OPTION_g },
2234
#endif
2235
    { "localtime", 0, QEMU_OPTION_localtime },
2236
    { "isa", 0, QEMU_OPTION_isa },
2237
    { "std-vga", 0, QEMU_OPTION_std_vga },
2238

    
2239
    /* temporary options */
2240
    { "pci", 0, QEMU_OPTION_pci },
2241
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2242
    { NULL },
2243
};
2244

    
2245
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2246

    
2247
/* this stack is only used during signal handling */
2248
#define SIGNAL_STACK_SIZE 32768
2249

    
2250
static uint8_t *signal_stack;
2251

    
2252
#endif
2253

    
2254
#define NET_IF_TUN   0
2255
#define NET_IF_USER  1
2256
#define NET_IF_DUMMY 2
2257

    
2258
int main(int argc, char **argv)
2259
{
2260
#ifdef CONFIG_GDBSTUB
2261
    int use_gdbstub, gdbstub_port;
2262
#endif
2263
    int i, has_cdrom;
2264
    int snapshot, linux_boot;
2265
    CPUState *env;
2266
    const char *initrd_filename;
2267
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2268
    const char *kernel_filename, *kernel_cmdline;
2269
    DisplayState *ds = &display_state;
2270
    int cyls, heads, secs;
2271
    int start_emulation = 1;
2272
    uint8_t macaddr[6];
2273
    int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2274
    int optind;
2275
    const char *r, *optarg;
2276

    
2277
#if !defined(CONFIG_SOFTMMU)
2278
    /* we never want that malloc() uses mmap() */
2279
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2280
#endif
2281
    initrd_filename = NULL;
2282
    for(i = 0; i < MAX_FD; i++)
2283
        fd_filename[i] = NULL;
2284
    for(i = 0; i < MAX_DISKS; i++)
2285
        hd_filename[i] = NULL;
2286
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2287
    vga_ram_size = VGA_RAM_SIZE;
2288
    bios_size = BIOS_SIZE;
2289
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2290
#ifdef CONFIG_GDBSTUB
2291
    use_gdbstub = 0;
2292
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
2293
#endif
2294
    snapshot = 0;
2295
    nographic = 0;
2296
    kernel_filename = NULL;
2297
    kernel_cmdline = "";
2298
    has_cdrom = 1;
2299
    cyls = heads = secs = 0;
2300

    
2301
    nb_tun_fds = 0;
2302
    net_if_type = -1;
2303
    nb_nics = 1;
2304
    /* default mac address of the first network interface */
2305
    macaddr[0] = 0x52;
2306
    macaddr[1] = 0x54;
2307
    macaddr[2] = 0x00;
2308
    macaddr[3] = 0x12;
2309
    macaddr[4] = 0x34;
2310
    macaddr[5] = 0x56;
2311

    
2312
    optind = 1;
2313
    for(;;) {
2314
        if (optind >= argc)
2315
            break;
2316
        r = argv[optind];
2317
        if (r[0] != '-') {
2318
            hd_filename[0] = argv[optind++];
2319
        } else {
2320
            const QEMUOption *popt;
2321

    
2322
            optind++;
2323
            popt = qemu_options;
2324
            for(;;) {
2325
                if (!popt->name) {
2326
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
2327
                            argv[0], r);
2328
                    exit(1);
2329
                }
2330
                if (!strcmp(popt->name, r + 1))
2331
                    break;
2332
                popt++;
2333
            }
2334
            if (popt->flags & HAS_ARG) {
2335
                if (optind >= argc) {
2336
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
2337
                            argv[0], r);
2338
                    exit(1);
2339
                }
2340
                optarg = argv[optind++];
2341
            } else {
2342
                optarg = NULL;
2343
            }
2344

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

    
2568
    linux_boot = (kernel_filename != NULL);
2569
        
2570
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2571
        fd_filename[0] == '\0')
2572
        help();
2573
    
2574
    /* boot to cd by default if no hard disk */
2575
    if (hd_filename[0] == '\0' && boot_device == 'c') {
2576
        if (fd_filename[0] != '\0')
2577
            boot_device = 'a';
2578
        else
2579
            boot_device = 'd';
2580
    }
2581

    
2582
#if !defined(CONFIG_SOFTMMU)
2583
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2584
    {
2585
        static uint8_t stdout_buf[4096];
2586
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2587
    }
2588
#else
2589
    setvbuf(stdout, NULL, _IOLBF, 0);
2590
#endif
2591

    
2592
    /* init host network redirectors */
2593
    if (net_if_type == -1) {
2594
        net_if_type = NET_IF_TUN;
2595
#if defined(CONFIG_SLIRP)
2596
        if (access(network_script, R_OK) < 0) {
2597
            net_if_type = NET_IF_USER;
2598
        }
2599
#endif
2600
    }
2601

    
2602
    for(i = 0; i < nb_nics; i++) {
2603
        NetDriverState *nd = &nd_table[i];
2604
        nd->index = i;
2605
        /* init virtual mac address */
2606
        nd->macaddr[0] = macaddr[0];
2607
        nd->macaddr[1] = macaddr[1];
2608
        nd->macaddr[2] = macaddr[2];
2609
        nd->macaddr[3] = macaddr[3];
2610
        nd->macaddr[4] = macaddr[4];
2611
        nd->macaddr[5] = macaddr[5] + i;
2612
        switch(net_if_type) {
2613
#if defined(CONFIG_SLIRP)
2614
        case NET_IF_USER:
2615
            net_slirp_init(nd);
2616
            break;
2617
#endif
2618
#if !defined(_WIN32)
2619
        case NET_IF_TUN:
2620
            if (i < nb_tun_fds) {
2621
                net_fd_init(nd, tun_fds[i]);
2622
            } else {
2623
                if (net_tun_init(nd) < 0)
2624
                    net_dummy_init(nd);
2625
            }
2626
            break;
2627
#endif
2628
        case NET_IF_DUMMY:
2629
        default:
2630
            net_dummy_init(nd);
2631
            break;
2632
        }
2633
    }
2634

    
2635
    /* init the memory */
2636
    phys_ram_size = ram_size + vga_ram_size + bios_size;
2637

    
2638
#ifdef CONFIG_SOFTMMU
2639
#ifdef _BSD
2640
    /* mallocs are always aligned on BSD. valloc is better for correctness */
2641
    phys_ram_base = valloc(phys_ram_size);
2642
#else
2643
    phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2644
#endif
2645
    if (!phys_ram_base) {
2646
        fprintf(stderr, "Could not allocate physical memory\n");
2647
        exit(1);
2648
    }
2649
#else
2650
    /* as we must map the same page at several addresses, we must use
2651
       a fd */
2652
    {
2653
        const char *tmpdir;
2654

    
2655
        tmpdir = getenv("QEMU_TMPDIR");
2656
        if (!tmpdir)
2657
            tmpdir = "/tmp";
2658
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2659
        if (mkstemp(phys_ram_file) < 0) {
2660
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2661
                    phys_ram_file);
2662
            exit(1);
2663
        }
2664
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2665
        if (phys_ram_fd < 0) {
2666
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2667
                    phys_ram_file);
2668
            exit(1);
2669
        }
2670
        ftruncate(phys_ram_fd, phys_ram_size);
2671
        unlink(phys_ram_file);
2672
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2673
                             phys_ram_size, 
2674
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2675
                             phys_ram_fd, 0);
2676
        if (phys_ram_base == MAP_FAILED) {
2677
            fprintf(stderr, "Could not map physical memory\n");
2678
            exit(1);
2679
        }
2680
    }
2681
#endif
2682

    
2683
    /* we always create the cdrom drive, even if no disk is there */
2684
    if (has_cdrom) {
2685
        bs_table[2] = bdrv_new("cdrom");
2686
        bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2687
    }
2688

    
2689
    /* open the virtual block devices */
2690
    for(i = 0; i < MAX_DISKS; i++) {
2691
        if (hd_filename[i]) {
2692
            if (!bs_table[i]) {
2693
                char buf[64];
2694
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2695
                bs_table[i] = bdrv_new(buf);
2696
            }
2697
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2698
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2699
                        hd_filename[i]);
2700
                exit(1);
2701
            }
2702
            if (i == 0 && cyls != 0) 
2703
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2704
        }
2705
    }
2706

    
2707
    /* we always create at least one floppy disk */
2708
    fd_table[0] = bdrv_new("fda");
2709
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2710

    
2711
    for(i = 0; i < MAX_FD; i++) {
2712
        if (fd_filename[i]) {
2713
            if (!fd_table[i]) {
2714
                char buf[64];
2715
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2716
                fd_table[i] = bdrv_new(buf);
2717
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2718
            }
2719
            if (fd_filename[i] != '\0') {
2720
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2721
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2722
                            fd_filename[i]);
2723
                    exit(1);
2724
                }
2725
            }
2726
        }
2727
    }
2728

    
2729
    /* init CPU state */
2730
    env = cpu_init();
2731
    global_env = env;
2732
    cpu_single_env = env;
2733

    
2734
    register_savevm("timer", 0, 1, timer_save, timer_load, env);
2735
    register_savevm("cpu", 0, 2, cpu_save, cpu_load, env);
2736
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2737
    qemu_register_reset(main_cpu_reset, global_env);
2738

    
2739
    init_ioports();
2740
    cpu_calibrate_ticks();
2741

    
2742
    /* terminal init */
2743
    if (nographic) {
2744
        dumb_display_init(ds);
2745
    } else {
2746
#ifdef CONFIG_SDL
2747
        sdl_display_init(ds);
2748
#else
2749
        dumb_display_init(ds);
2750
#endif
2751
    }
2752

    
2753
    /* setup cpu signal handlers for MMU / self modifying code handling */
2754
#if !defined(CONFIG_SOFTMMU)
2755
    
2756
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2757
    {
2758
        stack_t stk;
2759
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2760
        stk.ss_sp = signal_stack;
2761
        stk.ss_size = SIGNAL_STACK_SIZE;
2762
        stk.ss_flags = 0;
2763

    
2764
        if (sigaltstack(&stk, NULL) < 0) {
2765
            perror("sigaltstack");
2766
            exit(1);
2767
        }
2768
    }
2769
#endif
2770
    {
2771
        struct sigaction act;
2772
        
2773
        sigfillset(&act.sa_mask);
2774
        act.sa_flags = SA_SIGINFO;
2775
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2776
        act.sa_flags |= SA_ONSTACK;
2777
#endif
2778
        act.sa_sigaction = host_segv_handler;
2779
        sigaction(SIGSEGV, &act, NULL);
2780
        sigaction(SIGBUS, &act, NULL);
2781
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2782
        sigaction(SIGFPE, &act, NULL);
2783
#endif
2784
    }
2785
#endif
2786

    
2787
#ifndef _WIN32
2788
    {
2789
        struct sigaction act;
2790
        sigfillset(&act.sa_mask);
2791
        act.sa_flags = 0;
2792
        act.sa_handler = SIG_IGN;
2793
        sigaction(SIGPIPE, &act, NULL);
2794
    }
2795
#endif
2796
    init_timers();
2797

    
2798
#if defined(TARGET_I386)
2799
    pc_init(ram_size, vga_ram_size, boot_device,
2800
            ds, fd_filename, snapshot,
2801
            kernel_filename, kernel_cmdline, initrd_filename);
2802
#elif defined(TARGET_PPC)
2803
    ppc_init(ram_size, vga_ram_size, boot_device,
2804
             ds, fd_filename, snapshot,
2805
             kernel_filename, kernel_cmdline, initrd_filename);
2806
#endif
2807

    
2808
    /* launched after the device init so that it can display or not a
2809
       banner */
2810
    monitor_init();
2811

    
2812
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2813
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2814

    
2815
#ifdef CONFIG_GDBSTUB
2816
    if (use_gdbstub) {
2817
        if (gdbserver_start(gdbstub_port) < 0) {
2818
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
2819
                    gdbstub_port);
2820
            exit(1);
2821
        } else {
2822
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
2823
        }
2824
    } else 
2825
#endif
2826
    if (start_emulation)
2827
    {
2828
        vm_start();
2829
    }
2830
    term_init();
2831
    main_loop();
2832
    quit_timers();
2833
    return 0;
2834
}