Statistics
| Branch: | Revision:

root / vl.c @ 7d3505c5

History | View | Annotate | Download (62.2 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 <getopt.h>
27
#include <unistd.h>
28
#include <fcntl.h>
29
#include <signal.h>
30
#include <time.h>
31
#include <errno.h>
32
#include <sys/time.h>
33

    
34
#ifndef _WIN32
35
#include <sys/times.h>
36
#include <sys/wait.h>
37
#include <termios.h>
38
#include <sys/poll.h>
39
#include <sys/mman.h>
40
#include <sys/ioctl.h>
41
#include <sys/socket.h>
42
#ifdef _BSD
43
#include <sys/stat.h>
44
#include <libutil.h>
45
#else
46
#include <linux/if.h>
47
#include <linux/if_tun.h>
48
#include <pty.h>
49
#include <malloc.h>
50
#include <linux/rtc.h>
51
#endif
52
#endif
53

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

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

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

    
80
#include "disas.h"
81

    
82
#include "exec-all.h"
83

    
84
//#define DO_TB_FLUSH
85

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

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

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

    
97
/* in ms */
98
#define GUI_REFRESH_INTERVAL 30
99

    
100
/* XXX: use a two level table to limit memory usage */
101
#define MAX_IOPORTS 65536
102

    
103
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
104
char phys_ram_file[1024];
105
CPUState *global_env;
106
CPUState *cpu_single_env;
107
void *ioport_opaque[MAX_IOPORTS];
108
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
109
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
110
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
111
int vga_ram_size;
112
static DisplayState display_state;
113
int nographic;
114
int64_t ticks_per_sec;
115
int boot_device = 'c';
116
static int ram_size;
117
static char network_script[1024];
118
int pit_min_timer_count = 0;
119
int nb_nics;
120
NetDriverState nd_table[MAX_NICS];
121
SerialState *serial_console;
122
QEMUTimer *gui_timer;
123
int vm_running;
124
int audio_enabled = 0;
125

    
126
/***********************************************************/
127
/* x86 ISA bus support */
128

    
129
target_phys_addr_t isa_mem_base = 0;
130

    
131
uint32_t default_ioport_readb(void *opaque, uint32_t address)
132
{
133
#ifdef DEBUG_UNUSED_IOPORT
134
    fprintf(stderr, "inb: port=0x%04x\n", address);
135
#endif
136
    return 0xff;
137
}
138

    
139
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
140
{
141
#ifdef DEBUG_UNUSED_IOPORT
142
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
143
#endif
144
}
145

    
146
/* default is to make two byte accesses */
147
uint32_t default_ioport_readw(void *opaque, uint32_t address)
148
{
149
    uint32_t data;
150
    data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](opaque, address);
151
    data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](opaque, address + 1) << 8;
152
    return data;
153
}
154

    
155
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
156
{
157
    ioport_write_table[0][address & (MAX_IOPORTS - 1)](opaque, address, data & 0xff);
158
    ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](opaque, address + 1, (data >> 8) & 0xff);
159
}
160

    
161
uint32_t default_ioport_readl(void *opaque, uint32_t address)
162
{
163
#ifdef DEBUG_UNUSED_IOPORT
164
    fprintf(stderr, "inl: port=0x%04x\n", address);
165
#endif
166
    return 0xffffffff;
167
}
168

    
169
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
170
{
171
#ifdef DEBUG_UNUSED_IOPORT
172
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
173
#endif
174
}
175

    
176
void init_ioports(void)
177
{
178
    int i;
179

    
180
    for(i = 0; i < MAX_IOPORTS; i++) {
181
        ioport_read_table[0][i] = default_ioport_readb;
182
        ioport_write_table[0][i] = default_ioport_writeb;
183
        ioport_read_table[1][i] = default_ioport_readw;
184
        ioport_write_table[1][i] = default_ioport_writew;
185
        ioport_read_table[2][i] = default_ioport_readl;
186
        ioport_write_table[2][i] = default_ioport_writel;
187
    }
188
}
189

    
190
/* size is the word size in byte */
191
int register_ioport_read(int start, int length, int size, 
192
                         IOPortReadFunc *func, void *opaque)
193
{
194
    int i, bsize;
195

    
196
    if (size == 1) {
197
        bsize = 0;
198
    } else if (size == 2) {
199
        bsize = 1;
200
    } else if (size == 4) {
201
        bsize = 2;
202
    } else {
203
        hw_error("register_ioport_read: invalid size");
204
        return -1;
205
    }
206
    for(i = start; i < start + length; i += size) {
207
        ioport_read_table[bsize][i] = func;
208
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
209
            hw_error("register_ioport_read: invalid opaque");
210
        ioport_opaque[i] = opaque;
211
    }
212
    return 0;
213
}
214

    
215
/* size is the word size in byte */
216
int register_ioport_write(int start, int length, int size, 
217
                          IOPortWriteFunc *func, void *opaque)
218
{
219
    int i, bsize;
220

    
221
    if (size == 1) {
222
        bsize = 0;
223
    } else if (size == 2) {
224
        bsize = 1;
225
    } else if (size == 4) {
226
        bsize = 2;
227
    } else {
228
        hw_error("register_ioport_write: invalid size");
229
        return -1;
230
    }
231
    for(i = start; i < start + length; i += size) {
232
        ioport_write_table[bsize][i] = func;
233
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
234
            hw_error("register_ioport_read: invalid opaque");
235
        ioport_opaque[i] = opaque;
236
    }
237
    return 0;
238
}
239

    
240
void pstrcpy(char *buf, int buf_size, const char *str)
241
{
242
    int c;
243
    char *q = buf;
244

    
245
    if (buf_size <= 0)
246
        return;
247

    
248
    for(;;) {
249
        c = *str++;
250
        if (c == 0 || q >= buf + buf_size - 1)
251
            break;
252
        *q++ = c;
253
    }
254
    *q = '\0';
255
}
256

    
257
/* strcat and truncate. */
258
char *pstrcat(char *buf, int buf_size, const char *s)
259
{
260
    int len;
261
    len = strlen(buf);
262
    if (len < buf_size) 
263
        pstrcpy(buf + len, buf_size - len, s);
264
    return buf;
265
}
266

    
267
/* return the size or -1 if error */
268
int load_image(const char *filename, uint8_t *addr)
269
{
270
    int fd, size;
271
    fd = open(filename, O_RDONLY | O_BINARY);
272
    if (fd < 0)
273
        return -1;
274
    size = lseek(fd, 0, SEEK_END);
275
    lseek(fd, 0, SEEK_SET);
276
    if (read(fd, addr, size) != size) {
277
        close(fd);
278
        return -1;
279
    }
280
    close(fd);
281
    return size;
282
}
283

    
284
void cpu_outb(CPUState *env, int addr, int val)
285
{
286
    addr &= (MAX_IOPORTS - 1);
287
#ifdef DEBUG_IOPORT
288
    if (loglevel & CPU_LOG_IOPORT)
289
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
290
#endif    
291
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
292
}
293

    
294
void cpu_outw(CPUState *env, int addr, int val)
295
{
296
    addr &= (MAX_IOPORTS - 1);
297
#ifdef DEBUG_IOPORT
298
    if (loglevel & CPU_LOG_IOPORT)
299
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
300
#endif    
301
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
302
}
303

    
304
void cpu_outl(CPUState *env, int addr, int val)
305
{
306
    addr &= (MAX_IOPORTS - 1);
307
#ifdef DEBUG_IOPORT
308
    if (loglevel & CPU_LOG_IOPORT)
309
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
310
#endif
311
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
312
}
313

    
314
int cpu_inb(CPUState *env, int addr)
315
{
316
    int val;
317
    addr &= (MAX_IOPORTS - 1);
318
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
319
#ifdef DEBUG_IOPORT
320
    if (loglevel & CPU_LOG_IOPORT)
321
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
322
#endif
323
    return val;
324
}
325

    
326
int cpu_inw(CPUState *env, int addr)
327
{
328
    int val;
329
    addr &= (MAX_IOPORTS - 1);
330
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
331
#ifdef DEBUG_IOPORT
332
    if (loglevel & CPU_LOG_IOPORT)
333
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
334
#endif
335
    return val;
336
}
337

    
338
int cpu_inl(CPUState *env, int addr)
339
{
340
    int val;
341
    addr &= (MAX_IOPORTS - 1);
342
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
343
#ifdef DEBUG_IOPORT
344
    if (loglevel & CPU_LOG_IOPORT)
345
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
346
#endif
347
    return val;
348
}
349

    
350
/***********************************************************/
351
void hw_error(const char *fmt, ...)
352
{
353
    va_list ap;
354

    
355
    va_start(ap, fmt);
356
    fprintf(stderr, "qemu: hardware error: ");
357
    vfprintf(stderr, fmt, ap);
358
    fprintf(stderr, "\n");
359
#ifdef TARGET_I386
360
    cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
361
#else
362
    cpu_dump_state(global_env, stderr, 0);
363
#endif
364
    va_end(ap);
365
    abort();
366
}
367

    
368
/***********************************************************/
369
/* timers */
370

    
371
#if defined(__powerpc__)
372

    
373
static inline uint32_t get_tbl(void) 
374
{
375
    uint32_t tbl;
376
    asm volatile("mftb %0" : "=r" (tbl));
377
    return tbl;
378
}
379

    
380
static inline uint32_t get_tbu(void) 
381
{
382
        uint32_t tbl;
383
        asm volatile("mftbu %0" : "=r" (tbl));
384
        return tbl;
385
}
386

    
387
int64_t cpu_get_real_ticks(void)
388
{
389
    uint32_t l, h, h1;
390
    /* NOTE: we test if wrapping has occurred */
391
    do {
392
        h = get_tbu();
393
        l = get_tbl();
394
        h1 = get_tbu();
395
    } while (h != h1);
396
    return ((int64_t)h << 32) | l;
397
}
398

    
399
#elif defined(__i386__)
400

    
401
int64_t cpu_get_real_ticks(void)
402
{
403
    int64_t val;
404
    asm volatile ("rdtsc" : "=A" (val));
405
    return val;
406
}
407

    
408
#elif defined(__x86_64__)
409

    
410
int64_t cpu_get_real_ticks(void)
411
{
412
    uint32_t low,high;
413
    int64_t val;
414
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
415
    val = high;
416
    val <<= 32;
417
    val |= low;
418
    return val;
419
}
420

    
421
#else
422
#error unsupported CPU
423
#endif
424

    
425
static int64_t cpu_ticks_offset;
426
static int cpu_ticks_enabled;
427

    
428
static inline int64_t cpu_get_ticks(void)
429
{
430
    if (!cpu_ticks_enabled) {
431
        return cpu_ticks_offset;
432
    } else {
433
        return cpu_get_real_ticks() + cpu_ticks_offset;
434
    }
435
}
436

    
437
/* enable cpu_get_ticks() */
438
void cpu_enable_ticks(void)
439
{
440
    if (!cpu_ticks_enabled) {
441
        cpu_ticks_offset -= cpu_get_real_ticks();
442
        cpu_ticks_enabled = 1;
443
    }
444
}
445

    
446
/* disable cpu_get_ticks() : the clock is stopped. You must not call
447
   cpu_get_ticks() after that.  */
448
void cpu_disable_ticks(void)
449
{
450
    if (cpu_ticks_enabled) {
451
        cpu_ticks_offset = cpu_get_ticks();
452
        cpu_ticks_enabled = 0;
453
    }
454
}
455

    
456
static int64_t get_clock(void)
457
{
458
#ifdef _WIN32
459
    struct _timeb tb;
460
    _ftime(&tb);
461
    return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
462
#else
463
    struct timeval tv;
464
    gettimeofday(&tv, NULL);
465
    return tv.tv_sec * 1000000LL + tv.tv_usec;
466
#endif
467
}
468

    
469
void cpu_calibrate_ticks(void)
470
{
471
    int64_t usec, ticks;
472

    
473
    usec = get_clock();
474
    ticks = cpu_get_real_ticks();
475
#ifdef _WIN32
476
    Sleep(50);
477
#else
478
    usleep(50 * 1000);
479
#endif
480
    usec = get_clock() - usec;
481
    ticks = cpu_get_real_ticks() - ticks;
482
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
483
}
484

    
485
/* compute with 96 bit intermediate result: (a*b)/c */
486
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
487
{
488
    union {
489
        uint64_t ll;
490
        struct {
491
#ifdef WORDS_BIGENDIAN
492
            uint32_t high, low;
493
#else
494
            uint32_t low, high;
495
#endif            
496
        } l;
497
    } u, res;
498
    uint64_t rl, rh;
499

    
500
    u.ll = a;
501
    rl = (uint64_t)u.l.low * (uint64_t)b;
502
    rh = (uint64_t)u.l.high * (uint64_t)b;
503
    rh += (rl >> 32);
504
    res.l.high = rh / c;
505
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
506
    return res.ll;
507
}
508

    
509
#define QEMU_TIMER_REALTIME 0
510
#define QEMU_TIMER_VIRTUAL  1
511

    
512
struct QEMUClock {
513
    int type;
514
    /* XXX: add frequency */
515
};
516

    
517
struct QEMUTimer {
518
    QEMUClock *clock;
519
    int64_t expire_time;
520
    QEMUTimerCB *cb;
521
    void *opaque;
522
    struct QEMUTimer *next;
523
};
524

    
525
QEMUClock *rt_clock;
526
QEMUClock *vm_clock;
527

    
528
static QEMUTimer *active_timers[2];
529
#ifdef _WIN32
530
static MMRESULT timerID;
531
#else
532
/* frequency of the times() clock tick */
533
static int timer_freq;
534
#endif
535

    
536
QEMUClock *qemu_new_clock(int type)
537
{
538
    QEMUClock *clock;
539
    clock = qemu_mallocz(sizeof(QEMUClock));
540
    if (!clock)
541
        return NULL;
542
    clock->type = type;
543
    return clock;
544
}
545

    
546
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
547
{
548
    QEMUTimer *ts;
549

    
550
    ts = qemu_mallocz(sizeof(QEMUTimer));
551
    ts->clock = clock;
552
    ts->cb = cb;
553
    ts->opaque = opaque;
554
    return ts;
555
}
556

    
557
void qemu_free_timer(QEMUTimer *ts)
558
{
559
    qemu_free(ts);
560
}
561

    
562
/* stop a timer, but do not dealloc it */
563
void qemu_del_timer(QEMUTimer *ts)
564
{
565
    QEMUTimer **pt, *t;
566

    
567
    /* NOTE: this code must be signal safe because
568
       qemu_timer_expired() can be called from a signal. */
569
    pt = &active_timers[ts->clock->type];
570
    for(;;) {
571
        t = *pt;
572
        if (!t)
573
            break;
574
        if (t == ts) {
575
            *pt = t->next;
576
            break;
577
        }
578
        pt = &t->next;
579
    }
580
}
581

    
582
/* modify the current timer so that it will be fired when current_time
583
   >= expire_time. The corresponding callback will be called. */
584
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
585
{
586
    QEMUTimer **pt, *t;
587

    
588
    qemu_del_timer(ts);
589

    
590
    /* add the timer in the sorted list */
591
    /* NOTE: this code must be signal safe because
592
       qemu_timer_expired() can be called from a signal. */
593
    pt = &active_timers[ts->clock->type];
594
    for(;;) {
595
        t = *pt;
596
        if (!t)
597
            break;
598
        if (t->expire_time > expire_time) 
599
            break;
600
        pt = &t->next;
601
    }
602
    ts->expire_time = expire_time;
603
    ts->next = *pt;
604
    *pt = ts;
605
}
606

    
607
int qemu_timer_pending(QEMUTimer *ts)
608
{
609
    QEMUTimer *t;
610
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
611
        if (t == ts)
612
            return 1;
613
    }
614
    return 0;
615
}
616

    
617
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
618
{
619
    if (!timer_head)
620
        return 0;
621
    return (timer_head->expire_time <= current_time);
622
}
623

    
624
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
625
{
626
    QEMUTimer *ts;
627
    
628
    for(;;) {
629
        ts = *ptimer_head;
630
        if (ts->expire_time > current_time)
631
            break;
632
        /* remove timer from the list before calling the callback */
633
        *ptimer_head = ts->next;
634
        ts->next = NULL;
635
        
636
        /* run the callback (the timer list can be modified) */
637
        ts->cb(ts->opaque);
638
    }
639
}
640

    
641
int64_t qemu_get_clock(QEMUClock *clock)
642
{
643
    switch(clock->type) {
644
    case QEMU_TIMER_REALTIME:
645
#ifdef _WIN32
646
        return GetTickCount();
647
#else
648
        {
649
            struct tms tp;
650

    
651
            /* Note that using gettimeofday() is not a good solution
652
               for timers because its value change when the date is
653
               modified. */
654
            if (timer_freq == 100) {
655
                return times(&tp) * 10;
656
            } else {
657
                return ((int64_t)times(&tp) * 1000) / timer_freq;
658
            }
659
        }
660
#endif
661
    default:
662
    case QEMU_TIMER_VIRTUAL:
663
        return cpu_get_ticks();
664
    }
665
}
666

    
667
/* save a timer */
668
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
669
{
670
    uint64_t expire_time;
671

    
672
    if (qemu_timer_pending(ts)) {
673
        expire_time = ts->expire_time;
674
    } else {
675
        expire_time = -1;
676
    }
677
    qemu_put_be64(f, expire_time);
678
}
679

    
680
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
681
{
682
    uint64_t expire_time;
683

    
684
    expire_time = qemu_get_be64(f);
685
    if (expire_time != -1) {
686
        qemu_mod_timer(ts, expire_time);
687
    } else {
688
        qemu_del_timer(ts);
689
    }
690
}
691

    
692
static void timer_save(QEMUFile *f, void *opaque)
693
{
694
    if (cpu_ticks_enabled) {
695
        hw_error("cannot save state if virtual timers are running");
696
    }
697
    qemu_put_be64s(f, &cpu_ticks_offset);
698
    qemu_put_be64s(f, &ticks_per_sec);
699
}
700

    
701
static int timer_load(QEMUFile *f, void *opaque, int version_id)
702
{
703
    if (version_id != 1)
704
        return -EINVAL;
705
    if (cpu_ticks_enabled) {
706
        return -EINVAL;
707
    }
708
    qemu_get_be64s(f, &cpu_ticks_offset);
709
    qemu_get_be64s(f, &ticks_per_sec);
710
    return 0;
711
}
712

    
713
#ifdef _WIN32
714
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
715
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
716
#else
717
static void host_alarm_handler(int host_signum)
718
#endif
719
{
720
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
721
                           qemu_get_clock(vm_clock)) ||
722
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
723
                           qemu_get_clock(rt_clock))) {
724
        /* stop the cpu because a timer occured */
725
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
726
    }
727
}
728

    
729
#ifndef _WIN32
730

    
731
#define RTC_FREQ 1024
732

    
733
static int rtc_fd;
734
    
735
static int start_rtc_timer(void)
736
{
737
    rtc_fd = open("/dev/rtc", O_RDONLY);
738
    if (rtc_fd < 0)
739
        return -1;
740
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
741
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
742
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
743
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
744
        goto fail;
745
    }
746
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
747
    fail:
748
        close(rtc_fd);
749
        return -1;
750
    }
751
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
752
    return 0;
753
}
754

    
755
#endif
756

    
757
static void init_timers(void)
758
{
759
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
760
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
761

    
762
#ifdef _WIN32
763
    {
764
        int count=0;
765
        timerID = timeSetEvent(10,    // interval (ms)
766
                               0,     // resolution
767
                               host_alarm_handler, // function
768
                               (DWORD)&count,  // user parameter
769
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
770
         if( !timerID ) {
771
            perror("failed timer alarm");
772
            exit(1);
773
         }
774
    }
775
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
776
#else
777
    {
778
        struct sigaction act;
779
        struct itimerval itv;
780
        
781
        /* get times() syscall frequency */
782
        timer_freq = sysconf(_SC_CLK_TCK);
783
        
784
        /* timer signal */
785
        sigfillset(&act.sa_mask);
786
        act.sa_flags = 0;
787
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
788
        act.sa_flags |= SA_ONSTACK;
789
#endif
790
        act.sa_handler = host_alarm_handler;
791
        sigaction(SIGALRM, &act, NULL);
792

    
793
        itv.it_interval.tv_sec = 0;
794
        itv.it_interval.tv_usec = 1000;
795
        itv.it_value.tv_sec = 0;
796
        itv.it_value.tv_usec = 10 * 1000;
797
        setitimer(ITIMER_REAL, &itv, NULL);
798
        /* we probe the tick duration of the kernel to inform the user if
799
           the emulated kernel requested a too high timer frequency */
800
        getitimer(ITIMER_REAL, &itv);
801

    
802
        if (itv.it_interval.tv_usec > 1000) {
803
            /* try to use /dev/rtc to have a faster timer */
804
            if (start_rtc_timer() < 0)
805
                goto use_itimer;
806
            /* disable itimer */
807
            itv.it_interval.tv_sec = 0;
808
            itv.it_interval.tv_usec = 0;
809
            itv.it_value.tv_sec = 0;
810
            itv.it_value.tv_usec = 0;
811
            setitimer(ITIMER_REAL, &itv, NULL);
812

    
813
            /* use the RTC */
814
            sigaction(SIGIO, &act, NULL);
815
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
816
            fcntl(rtc_fd, F_SETOWN, getpid());
817
        } else {
818
        use_itimer:
819
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
820
                                   PIT_FREQ) / 1000000;
821
        }
822
    }
823
#endif
824
}
825

    
826
void quit_timers(void)
827
{
828
#ifdef _WIN32
829
    timeKillEvent(timerID);
830
#endif
831
}
832

    
833
/***********************************************************/
834
/* serial device */
835

    
836
#ifdef _WIN32
837

    
838
int serial_open_device(void)
839
{
840
    return -1;
841
}
842

    
843
#else
844

    
845
int serial_open_device(void)
846
{
847
    char slave_name[1024];
848
    int master_fd, slave_fd;
849

    
850
    if (serial_console == NULL && nographic) {
851
        /* use console for serial port */
852
        return 0;
853
    } else {
854
        if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
855
            fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
856
            return -1;
857
        }
858
        fprintf(stderr, "Serial port redirected to %s\n", slave_name);
859
        return master_fd;
860
    }
861
}
862

    
863
#endif
864

    
865
/***********************************************************/
866
/* Linux network device redirectors */
867

    
868
void hex_dump(FILE *f, const uint8_t *buf, int size)
869
{
870
    int len, i, j, c;
871

    
872
    for(i=0;i<size;i+=16) {
873
        len = size - i;
874
        if (len > 16)
875
            len = 16;
876
        fprintf(f, "%08x ", i);
877
        for(j=0;j<16;j++) {
878
            if (j < len)
879
                fprintf(f, " %02x", buf[i+j]);
880
            else
881
                fprintf(f, "   ");
882
        }
883
        fprintf(f, " ");
884
        for(j=0;j<len;j++) {
885
            c = buf[i+j];
886
            if (c < ' ' || c > '~')
887
                c = '.';
888
            fprintf(f, "%c", c);
889
        }
890
        fprintf(f, "\n");
891
    }
892
}
893

    
894
void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
895
{
896
    nd->send_packet(nd, buf, size);
897
}
898

    
899
void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
900
                          IOReadHandler *fd_read, void *opaque)
901
{
902
    nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
903
}
904

    
905
/* dummy network adapter */
906

    
907
static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
908
{
909
}
910

    
911
static void dummy_add_read_packet(NetDriverState *nd, 
912
                                  IOCanRWHandler *fd_can_read, 
913
                                  IOReadHandler *fd_read, void *opaque)
914
{
915
}
916

    
917
static int net_dummy_init(NetDriverState *nd)
918
{
919
    nd->send_packet = dummy_send_packet;
920
    nd->add_read_packet = dummy_add_read_packet;
921
    pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
922
    return 0;
923
}
924

    
925
#if defined(CONFIG_SLIRP)
926

    
927
/* slirp network adapter */
928

    
929
static void *slirp_fd_opaque;
930
static IOCanRWHandler *slirp_fd_can_read;
931
static IOReadHandler *slirp_fd_read;
932
static int slirp_inited;
933

    
934
int slirp_can_output(void)
935
{
936
    return slirp_fd_can_read(slirp_fd_opaque);
937
}
938

    
939
void slirp_output(const uint8_t *pkt, int pkt_len)
940
{
941
#if 0
942
    printf("output:\n");
943
    hex_dump(stdout, pkt, pkt_len);
944
#endif
945
    slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
946
}
947

    
948
static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
949
{
950
#if 0
951
    printf("input:\n");
952
    hex_dump(stdout, buf, size);
953
#endif
954
    slirp_input(buf, size);
955
}
956

    
957
static void slirp_add_read_packet(NetDriverState *nd, 
958
                                  IOCanRWHandler *fd_can_read, 
959
                                  IOReadHandler *fd_read, void *opaque)
960
{
961
    slirp_fd_opaque = opaque;
962
    slirp_fd_can_read = fd_can_read;
963
    slirp_fd_read = fd_read;
964
}
965

    
966
static int net_slirp_init(NetDriverState *nd)
967
{
968
    if (!slirp_inited) {
969
        slirp_inited = 1;
970
        slirp_init();
971
    }
972
    nd->send_packet = slirp_send_packet;
973
    nd->add_read_packet = slirp_add_read_packet;
974
    pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
975
    return 0;
976
}
977

    
978
#endif /* CONFIG_SLIRP */
979

    
980
#if !defined(_WIN32)
981
#ifdef _BSD
982
static int tun_open(char *ifname, int ifname_size)
983
{
984
    int fd;
985
    char *dev;
986
    struct stat s;
987

    
988
    fd = open("/dev/tap", O_RDWR);
989
    if (fd < 0) {
990
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
991
        return -1;
992
    }
993

    
994
    fstat(fd, &s);
995
    dev = devname(s.st_rdev, S_IFCHR);
996
    pstrcpy(ifname, ifname_size, dev);
997

    
998
    fcntl(fd, F_SETFL, O_NONBLOCK);
999
    return fd;
1000
}
1001
#else
1002
static int tun_open(char *ifname, int ifname_size)
1003
{
1004
    struct ifreq ifr;
1005
    int fd, ret;
1006
    
1007
    fd = open("/dev/net/tun", O_RDWR);
1008
    if (fd < 0) {
1009
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1010
        return -1;
1011
    }
1012
    memset(&ifr, 0, sizeof(ifr));
1013
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1014
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1015
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1016
    if (ret != 0) {
1017
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1018
        close(fd);
1019
        return -1;
1020
    }
1021
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
1022
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
1023
    fcntl(fd, F_SETFL, O_NONBLOCK);
1024
    return fd;
1025
}
1026
#endif
1027

    
1028
static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1029
{
1030
    write(nd->fd, buf, size);
1031
}
1032

    
1033
static void tun_add_read_packet(NetDriverState *nd, 
1034
                                IOCanRWHandler *fd_can_read, 
1035
                                IOReadHandler *fd_read, void *opaque)
1036
{
1037
    qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1038
}
1039

    
1040
static int net_tun_init(NetDriverState *nd)
1041
{
1042
    int pid, status;
1043
    char *args[3];
1044
    char **parg;
1045

    
1046
    nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1047
    if (nd->fd < 0)
1048
        return -1;
1049

    
1050
    /* try to launch network init script */
1051
    pid = fork();
1052
    if (pid >= 0) {
1053
        if (pid == 0) {
1054
            parg = args;
1055
            *parg++ = network_script;
1056
            *parg++ = nd->ifname;
1057
            *parg++ = NULL;
1058
            execv(network_script, args);
1059
            exit(1);
1060
        }
1061
        while (waitpid(pid, &status, 0) != pid);
1062
        if (!WIFEXITED(status) ||
1063
            WEXITSTATUS(status) != 0) {
1064
            fprintf(stderr, "%s: could not launch network script\n",
1065
                    network_script);
1066
        }
1067
    }
1068
    nd->send_packet = tun_send_packet;
1069
    nd->add_read_packet = tun_add_read_packet;
1070
    return 0;
1071
}
1072

    
1073
static int net_fd_init(NetDriverState *nd, int fd)
1074
{
1075
    nd->fd = fd;
1076
    nd->send_packet = tun_send_packet;
1077
    nd->add_read_packet = tun_add_read_packet;
1078
    pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1079
    return 0;
1080
}
1081

    
1082
#endif /* !_WIN32 */
1083

    
1084
/***********************************************************/
1085
/* dumb display */
1086

    
1087
#ifdef _WIN32
1088

    
1089
static void term_exit(void)
1090
{
1091
}
1092

    
1093
static void term_init(void)
1094
{
1095
}
1096

    
1097
#else
1098

    
1099
/* init terminal so that we can grab keys */
1100
static struct termios oldtty;
1101

    
1102
static void term_exit(void)
1103
{
1104
    tcsetattr (0, TCSANOW, &oldtty);
1105
}
1106

    
1107
static void term_init(void)
1108
{
1109
    struct termios tty;
1110

    
1111
    tcgetattr (0, &tty);
1112
    oldtty = tty;
1113

    
1114
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1115
                          |INLCR|IGNCR|ICRNL|IXON);
1116
    tty.c_oflag |= OPOST;
1117
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1118
    /* if graphical mode, we allow Ctrl-C handling */
1119
    if (nographic)
1120
        tty.c_lflag &= ~ISIG;
1121
    tty.c_cflag &= ~(CSIZE|PARENB);
1122
    tty.c_cflag |= CS8;
1123
    tty.c_cc[VMIN] = 1;
1124
    tty.c_cc[VTIME] = 0;
1125
    
1126
    tcsetattr (0, TCSANOW, &tty);
1127

    
1128
    atexit(term_exit);
1129

    
1130
    fcntl(0, F_SETFL, O_NONBLOCK);
1131
}
1132

    
1133
#endif
1134

    
1135
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1136
{
1137
}
1138

    
1139
static void dumb_resize(DisplayState *ds, int w, int h)
1140
{
1141
}
1142

    
1143
static void dumb_refresh(DisplayState *ds)
1144
{
1145
    vga_update_display();
1146
}
1147

    
1148
void dumb_display_init(DisplayState *ds)
1149
{
1150
    ds->data = NULL;
1151
    ds->linesize = 0;
1152
    ds->depth = 0;
1153
    ds->dpy_update = dumb_update;
1154
    ds->dpy_resize = dumb_resize;
1155
    ds->dpy_refresh = dumb_refresh;
1156
}
1157

    
1158
#if !defined(CONFIG_SOFTMMU)
1159
/***********************************************************/
1160
/* cpu signal handler */
1161
static void host_segv_handler(int host_signum, siginfo_t *info, 
1162
                              void *puc)
1163
{
1164
    if (cpu_signal_handler(host_signum, info, puc))
1165
        return;
1166
    term_exit();
1167
    abort();
1168
}
1169
#endif
1170

    
1171
/***********************************************************/
1172
/* I/O handling */
1173

    
1174
#define MAX_IO_HANDLERS 64
1175

    
1176
typedef struct IOHandlerRecord {
1177
    int fd;
1178
    IOCanRWHandler *fd_can_read;
1179
    IOReadHandler *fd_read;
1180
    void *opaque;
1181
    /* temporary data */
1182
    struct pollfd *ufd;
1183
    int max_size;
1184
    struct IOHandlerRecord *next;
1185
} IOHandlerRecord;
1186

    
1187
static IOHandlerRecord *first_io_handler;
1188

    
1189
int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1190
                             IOReadHandler *fd_read, void *opaque)
1191
{
1192
    IOHandlerRecord *ioh;
1193

    
1194
    ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1195
    if (!ioh)
1196
        return -1;
1197
    ioh->fd = fd;
1198
    ioh->fd_can_read = fd_can_read;
1199
    ioh->fd_read = fd_read;
1200
    ioh->opaque = opaque;
1201
    ioh->next = first_io_handler;
1202
    first_io_handler = ioh;
1203
    return 0;
1204
}
1205

    
1206
void qemu_del_fd_read_handler(int fd)
1207
{
1208
    IOHandlerRecord **pioh, *ioh;
1209

    
1210
    pioh = &first_io_handler;
1211
    for(;;) {
1212
        ioh = *pioh;
1213
        if (ioh == NULL)
1214
            break;
1215
        if (ioh->fd == fd) {
1216
            *pioh = ioh->next;
1217
            break;
1218
        }
1219
        pioh = &ioh->next;
1220
    }
1221
}
1222

    
1223
/***********************************************************/
1224
/* savevm/loadvm support */
1225

    
1226
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1227
{
1228
    fwrite(buf, 1, size, f);
1229
}
1230

    
1231
void qemu_put_byte(QEMUFile *f, int v)
1232
{
1233
    fputc(v, f);
1234
}
1235

    
1236
void qemu_put_be16(QEMUFile *f, unsigned int v)
1237
{
1238
    qemu_put_byte(f, v >> 8);
1239
    qemu_put_byte(f, v);
1240
}
1241

    
1242
void qemu_put_be32(QEMUFile *f, unsigned int v)
1243
{
1244
    qemu_put_byte(f, v >> 24);
1245
    qemu_put_byte(f, v >> 16);
1246
    qemu_put_byte(f, v >> 8);
1247
    qemu_put_byte(f, v);
1248
}
1249

    
1250
void qemu_put_be64(QEMUFile *f, uint64_t v)
1251
{
1252
    qemu_put_be32(f, v >> 32);
1253
    qemu_put_be32(f, v);
1254
}
1255

    
1256
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1257
{
1258
    return fread(buf, 1, size, f);
1259
}
1260

    
1261
int qemu_get_byte(QEMUFile *f)
1262
{
1263
    int v;
1264
    v = fgetc(f);
1265
    if (v == EOF)
1266
        return 0;
1267
    else
1268
        return v;
1269
}
1270

    
1271
unsigned int qemu_get_be16(QEMUFile *f)
1272
{
1273
    unsigned int v;
1274
    v = qemu_get_byte(f) << 8;
1275
    v |= qemu_get_byte(f);
1276
    return v;
1277
}
1278

    
1279
unsigned int qemu_get_be32(QEMUFile *f)
1280
{
1281
    unsigned int v;
1282
    v = qemu_get_byte(f) << 24;
1283
    v |= qemu_get_byte(f) << 16;
1284
    v |= qemu_get_byte(f) << 8;
1285
    v |= qemu_get_byte(f);
1286
    return v;
1287
}
1288

    
1289
uint64_t qemu_get_be64(QEMUFile *f)
1290
{
1291
    uint64_t v;
1292
    v = (uint64_t)qemu_get_be32(f) << 32;
1293
    v |= qemu_get_be32(f);
1294
    return v;
1295
}
1296

    
1297
int64_t qemu_ftell(QEMUFile *f)
1298
{
1299
    return ftell(f);
1300
}
1301

    
1302
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1303
{
1304
    if (fseek(f, pos, whence) < 0)
1305
        return -1;
1306
    return ftell(f);
1307
}
1308

    
1309
typedef struct SaveStateEntry {
1310
    char idstr[256];
1311
    int instance_id;
1312
    int version_id;
1313
    SaveStateHandler *save_state;
1314
    LoadStateHandler *load_state;
1315
    void *opaque;
1316
    struct SaveStateEntry *next;
1317
} SaveStateEntry;
1318

    
1319
static SaveStateEntry *first_se;
1320

    
1321
int register_savevm(const char *idstr, 
1322
                    int instance_id, 
1323
                    int version_id,
1324
                    SaveStateHandler *save_state,
1325
                    LoadStateHandler *load_state,
1326
                    void *opaque)
1327
{
1328
    SaveStateEntry *se, **pse;
1329

    
1330
    se = qemu_malloc(sizeof(SaveStateEntry));
1331
    if (!se)
1332
        return -1;
1333
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1334
    se->instance_id = instance_id;
1335
    se->version_id = version_id;
1336
    se->save_state = save_state;
1337
    se->load_state = load_state;
1338
    se->opaque = opaque;
1339
    se->next = NULL;
1340

    
1341
    /* add at the end of list */
1342
    pse = &first_se;
1343
    while (*pse != NULL)
1344
        pse = &(*pse)->next;
1345
    *pse = se;
1346
    return 0;
1347
}
1348

    
1349
#define QEMU_VM_FILE_MAGIC   0x5145564d
1350
#define QEMU_VM_FILE_VERSION 0x00000001
1351

    
1352
int qemu_savevm(const char *filename)
1353
{
1354
    SaveStateEntry *se;
1355
    QEMUFile *f;
1356
    int len, len_pos, cur_pos, saved_vm_running, ret;
1357

    
1358
    saved_vm_running = vm_running;
1359
    vm_stop(0);
1360

    
1361
    f = fopen(filename, "wb");
1362
    if (!f) {
1363
        ret = -1;
1364
        goto the_end;
1365
    }
1366

    
1367
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1368
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1369

    
1370
    for(se = first_se; se != NULL; se = se->next) {
1371
        /* ID string */
1372
        len = strlen(se->idstr);
1373
        qemu_put_byte(f, len);
1374
        qemu_put_buffer(f, se->idstr, len);
1375

    
1376
        qemu_put_be32(f, se->instance_id);
1377
        qemu_put_be32(f, se->version_id);
1378

    
1379
        /* record size: filled later */
1380
        len_pos = ftell(f);
1381
        qemu_put_be32(f, 0);
1382
        
1383
        se->save_state(f, se->opaque);
1384

    
1385
        /* fill record size */
1386
        cur_pos = ftell(f);
1387
        len = ftell(f) - len_pos - 4;
1388
        fseek(f, len_pos, SEEK_SET);
1389
        qemu_put_be32(f, len);
1390
        fseek(f, cur_pos, SEEK_SET);
1391
    }
1392

    
1393
    fclose(f);
1394
    ret = 0;
1395
 the_end:
1396
    if (saved_vm_running)
1397
        vm_start();
1398
    return ret;
1399
}
1400

    
1401
static SaveStateEntry *find_se(const char *idstr, int instance_id)
1402
{
1403
    SaveStateEntry *se;
1404

    
1405
    for(se = first_se; se != NULL; se = se->next) {
1406
        if (!strcmp(se->idstr, idstr) && 
1407
            instance_id == se->instance_id)
1408
            return se;
1409
    }
1410
    return NULL;
1411
}
1412

    
1413
int qemu_loadvm(const char *filename)
1414
{
1415
    SaveStateEntry *se;
1416
    QEMUFile *f;
1417
    int len, cur_pos, ret, instance_id, record_len, version_id;
1418
    int saved_vm_running;
1419
    unsigned int v;
1420
    char idstr[256];
1421
    
1422
    saved_vm_running = vm_running;
1423
    vm_stop(0);
1424

    
1425
    f = fopen(filename, "rb");
1426
    if (!f) {
1427
        ret = -1;
1428
        goto the_end;
1429
    }
1430

    
1431
    v = qemu_get_be32(f);
1432
    if (v != QEMU_VM_FILE_MAGIC)
1433
        goto fail;
1434
    v = qemu_get_be32(f);
1435
    if (v != QEMU_VM_FILE_VERSION) {
1436
    fail:
1437
        fclose(f);
1438
        ret = -1;
1439
        goto the_end;
1440
    }
1441
    for(;;) {
1442
#if defined (DO_TB_FLUSH)
1443
        tb_flush(global_env);
1444
#endif
1445
        len = qemu_get_byte(f);
1446
        if (feof(f))
1447
            break;
1448
        qemu_get_buffer(f, idstr, len);
1449
        idstr[len] = '\0';
1450
        instance_id = qemu_get_be32(f);
1451
        version_id = qemu_get_be32(f);
1452
        record_len = qemu_get_be32(f);
1453
#if 0
1454
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1455
               idstr, instance_id, version_id, record_len);
1456
#endif
1457
        cur_pos = ftell(f);
1458
        se = find_se(idstr, instance_id);
1459
        if (!se) {
1460
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1461
                    instance_id, idstr);
1462
        } else {
1463
            ret = se->load_state(f, se->opaque, version_id);
1464
            if (ret < 0) {
1465
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1466
                        instance_id, idstr);
1467
            }
1468
        }
1469
        /* always seek to exact end of record */
1470
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1471
    }
1472
    fclose(f);
1473
    ret = 0;
1474
 the_end:
1475
    if (saved_vm_running)
1476
        vm_start();
1477
    return ret;
1478
}
1479

    
1480
/***********************************************************/
1481
/* cpu save/restore */
1482

    
1483
#if defined(TARGET_I386)
1484

    
1485
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1486
{
1487
    qemu_put_be32(f, (uint32_t)dt->base);
1488
    qemu_put_be32(f, dt->limit);
1489
    qemu_put_be32(f, dt->flags);
1490
}
1491

    
1492
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1493
{
1494
    dt->base = (uint8_t *)qemu_get_be32(f);
1495
    dt->limit = qemu_get_be32(f);
1496
    dt->flags = qemu_get_be32(f);
1497
}
1498

    
1499
void cpu_save(QEMUFile *f, void *opaque)
1500
{
1501
    CPUState *env = opaque;
1502
    uint16_t fptag, fpus, fpuc;
1503
    uint32_t hflags;
1504
    int i;
1505

    
1506
    for(i = 0; i < 8; i++)
1507
        qemu_put_be32s(f, &env->regs[i]);
1508
    qemu_put_be32s(f, &env->eip);
1509
    qemu_put_be32s(f, &env->eflags);
1510
    qemu_put_be32s(f, &env->eflags);
1511
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1512
    qemu_put_be32s(f, &hflags);
1513
    
1514
    /* FPU */
1515
    fpuc = env->fpuc;
1516
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1517
    fptag = 0;
1518
    for (i=7; i>=0; i--) {
1519
        fptag <<= 2;
1520
        if (env->fptags[i]) {
1521
            fptag |= 3;
1522
        }
1523
    }
1524
    
1525
    qemu_put_be16s(f, &fpuc);
1526
    qemu_put_be16s(f, &fpus);
1527
    qemu_put_be16s(f, &fptag);
1528

    
1529
    for(i = 0; i < 8; i++) {
1530
        uint64_t mant;
1531
        uint16_t exp;
1532
        cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1533
        qemu_put_be64(f, mant);
1534
        qemu_put_be16(f, exp);
1535
    }
1536

    
1537
    for(i = 0; i < 6; i++)
1538
        cpu_put_seg(f, &env->segs[i]);
1539
    cpu_put_seg(f, &env->ldt);
1540
    cpu_put_seg(f, &env->tr);
1541
    cpu_put_seg(f, &env->gdt);
1542
    cpu_put_seg(f, &env->idt);
1543
    
1544
    qemu_put_be32s(f, &env->sysenter_cs);
1545
    qemu_put_be32s(f, &env->sysenter_esp);
1546
    qemu_put_be32s(f, &env->sysenter_eip);
1547
    
1548
    qemu_put_be32s(f, &env->cr[0]);
1549
    qemu_put_be32s(f, &env->cr[2]);
1550
    qemu_put_be32s(f, &env->cr[3]);
1551
    qemu_put_be32s(f, &env->cr[4]);
1552
    
1553
    for(i = 0; i < 8; i++)
1554
        qemu_put_be32s(f, &env->dr[i]);
1555

    
1556
    /* MMU */
1557
    qemu_put_be32s(f, &env->a20_mask);
1558
}
1559

    
1560
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1561
{
1562
    CPUState *env = opaque;
1563
    int i;
1564
    uint32_t hflags;
1565
    uint16_t fpus, fpuc, fptag;
1566

    
1567
    if (version_id != 1)
1568
        return -EINVAL;
1569
    for(i = 0; i < 8; i++)
1570
        qemu_get_be32s(f, &env->regs[i]);
1571
    qemu_get_be32s(f, &env->eip);
1572
    qemu_get_be32s(f, &env->eflags);
1573
    qemu_get_be32s(f, &env->eflags);
1574
    qemu_get_be32s(f, &hflags);
1575

    
1576
    qemu_get_be16s(f, &fpuc);
1577
    qemu_get_be16s(f, &fpus);
1578
    qemu_get_be16s(f, &fptag);
1579

    
1580
    for(i = 0; i < 8; i++) {
1581
        uint64_t mant;
1582
        uint16_t exp;
1583
        mant = qemu_get_be64(f);
1584
        exp = qemu_get_be16(f);
1585
        env->fpregs[i] = cpu_set_fp80(mant, exp);
1586
    }
1587

    
1588
    env->fpuc = fpuc;
1589
    env->fpstt = (fpus >> 11) & 7;
1590
    env->fpus = fpus & ~0x3800;
1591
    for(i = 0; i < 8; i++) {
1592
        env->fptags[i] = ((fptag & 3) == 3);
1593
        fptag >>= 2;
1594
    }
1595
    
1596
    for(i = 0; i < 6; i++)
1597
        cpu_get_seg(f, &env->segs[i]);
1598
    cpu_get_seg(f, &env->ldt);
1599
    cpu_get_seg(f, &env->tr);
1600
    cpu_get_seg(f, &env->gdt);
1601
    cpu_get_seg(f, &env->idt);
1602
    
1603
    qemu_get_be32s(f, &env->sysenter_cs);
1604
    qemu_get_be32s(f, &env->sysenter_esp);
1605
    qemu_get_be32s(f, &env->sysenter_eip);
1606
    
1607
    qemu_get_be32s(f, &env->cr[0]);
1608
    qemu_get_be32s(f, &env->cr[2]);
1609
    qemu_get_be32s(f, &env->cr[3]);
1610
    qemu_get_be32s(f, &env->cr[4]);
1611
    
1612
    for(i = 0; i < 8; i++)
1613
        qemu_get_be32s(f, &env->dr[i]);
1614

    
1615
    /* MMU */
1616
    qemu_get_be32s(f, &env->a20_mask);
1617

    
1618
    /* XXX: compute hflags from scratch, except for CPL and IIF */
1619
    env->hflags = hflags;
1620
    tlb_flush(env, 1);
1621
    return 0;
1622
}
1623

    
1624
#elif defined(TARGET_PPC)
1625
void cpu_save(QEMUFile *f, void *opaque)
1626
{
1627
}
1628

    
1629
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1630
{
1631
    return 0;
1632
}
1633
#else
1634

    
1635
#warning No CPU save/restore functions
1636

    
1637
#endif
1638

    
1639
/***********************************************************/
1640
/* ram save/restore */
1641

    
1642
/* we just avoid storing empty pages */
1643
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1644
{
1645
    int i, v;
1646

    
1647
    v = buf[0];
1648
    for(i = 1; i < len; i++) {
1649
        if (buf[i] != v)
1650
            goto normal_save;
1651
    }
1652
    qemu_put_byte(f, 1);
1653
    qemu_put_byte(f, v);
1654
    return;
1655
 normal_save:
1656
    qemu_put_byte(f, 0); 
1657
    qemu_put_buffer(f, buf, len);
1658
}
1659

    
1660
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1661
{
1662
    int v;
1663

    
1664
    v = qemu_get_byte(f);
1665
    switch(v) {
1666
    case 0:
1667
        if (qemu_get_buffer(f, buf, len) != len)
1668
            return -EIO;
1669
        break;
1670
    case 1:
1671
        v = qemu_get_byte(f);
1672
        memset(buf, v, len);
1673
        break;
1674
    default:
1675
        return -EINVAL;
1676
    }
1677
    return 0;
1678
}
1679

    
1680
static void ram_save(QEMUFile *f, void *opaque)
1681
{
1682
    int i;
1683
    qemu_put_be32(f, phys_ram_size);
1684
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1685
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1686
    }
1687
}
1688

    
1689
static int ram_load(QEMUFile *f, void *opaque, int version_id)
1690
{
1691
    int i, ret;
1692

    
1693
    if (version_id != 1)
1694
        return -EINVAL;
1695
    if (qemu_get_be32(f) != phys_ram_size)
1696
        return -EINVAL;
1697
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1698
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1699
        if (ret)
1700
            return ret;
1701
    }
1702
    return 0;
1703
}
1704

    
1705
/***********************************************************/
1706
/* main execution loop */
1707

    
1708
void gui_update(void *opaque)
1709
{
1710
    display_state.dpy_refresh(&display_state);
1711
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1712
}
1713

    
1714
/* XXX: support several handlers */
1715
VMStopHandler *vm_stop_cb;
1716
VMStopHandler *vm_stop_opaque;
1717

    
1718
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1719
{
1720
    vm_stop_cb = cb;
1721
    vm_stop_opaque = opaque;
1722
    return 0;
1723
}
1724

    
1725
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1726
{
1727
    vm_stop_cb = NULL;
1728
}
1729

    
1730
void vm_start(void)
1731
{
1732
    if (!vm_running) {
1733
        cpu_enable_ticks();
1734
        vm_running = 1;
1735
    }
1736
}
1737

    
1738
void vm_stop(int reason) 
1739
{
1740
    if (vm_running) {
1741
        cpu_disable_ticks();
1742
        vm_running = 0;
1743
        if (reason != 0) {
1744
            if (vm_stop_cb) {
1745
                vm_stop_cb(vm_stop_opaque, reason);
1746
            }
1747
        }
1748
    }
1749
}
1750

    
1751
int main_loop(void)
1752
{
1753
#ifndef _WIN32
1754
    struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1755
    IOHandlerRecord *ioh, *ioh_next;
1756
    uint8_t buf[4096];
1757
    int n, max_size;
1758
#endif
1759
    int ret, timeout;
1760
    CPUState *env = global_env;
1761

    
1762
    for(;;) {
1763
        if (vm_running) {
1764
            ret = cpu_exec(env);
1765
            if (reset_requested) {
1766
                ret = EXCP_INTERRUPT; 
1767
                break;
1768
            }
1769
            if (ret == EXCP_DEBUG) {
1770
                vm_stop(EXCP_DEBUG);
1771
            }
1772
            /* if hlt instruction, we wait until the next IRQ */
1773
            /* XXX: use timeout computed from timers */
1774
            if (ret == EXCP_HLT) 
1775
                timeout = 10;
1776
            else
1777
                timeout = 0;
1778
        } else {
1779
            timeout = 10;
1780
        }
1781

    
1782
#ifdef _WIN32
1783
        if (timeout > 0)
1784
            Sleep(timeout);
1785
#else
1786

    
1787
        /* poll any events */
1788
        /* XXX: separate device handlers from system ones */
1789
        pf = ufds;
1790
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1791
            if (!ioh->fd_can_read) {
1792
                max_size = 0;
1793
                pf->fd = ioh->fd;
1794
                pf->events = POLLIN;
1795
                ioh->ufd = pf;
1796
                pf++;
1797
            } else {
1798
                max_size = ioh->fd_can_read(ioh->opaque);
1799
                if (max_size > 0) {
1800
                    if (max_size > sizeof(buf))
1801
                        max_size = sizeof(buf);
1802
                    pf->fd = ioh->fd;
1803
                    pf->events = POLLIN;
1804
                    ioh->ufd = pf;
1805
                    pf++;
1806
                } else {
1807
                    ioh->ufd = NULL;
1808
                }
1809
            }
1810
            ioh->max_size = max_size;
1811
        }
1812
        
1813
        ret = poll(ufds, pf - ufds, timeout);
1814
        if (ret > 0) {
1815
            /* XXX: better handling of removal */
1816
            for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1817
                ioh_next = ioh->next;
1818
                pf = ioh->ufd;
1819
                if (pf) {
1820
                    if (pf->revents & POLLIN) {
1821
                        if (ioh->max_size == 0) {
1822
                            /* just a read event */
1823
                            ioh->fd_read(ioh->opaque, NULL, 0);
1824
                        } else {
1825
                            n = read(ioh->fd, buf, ioh->max_size);
1826
                            if (n >= 0) {
1827
                                ioh->fd_read(ioh->opaque, buf, n);
1828
                            } else if (errno != -EAGAIN) {
1829
                                ioh->fd_read(ioh->opaque, NULL, -errno);
1830
                            }
1831
                        }
1832
                    }
1833
                }
1834
            }
1835
        }
1836

    
1837
#if defined(CONFIG_SLIRP)
1838
        /* XXX: merge with poll() */
1839
        if (slirp_inited) {
1840
            fd_set rfds, wfds, xfds;
1841
            int nfds;
1842
            struct timeval tv;
1843

    
1844
            nfds = -1;
1845
            FD_ZERO(&rfds);
1846
            FD_ZERO(&wfds);
1847
            FD_ZERO(&xfds);
1848
            slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1849
            tv.tv_sec = 0;
1850
            tv.tv_usec = 0;
1851
            ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1852
            if (ret >= 0) {
1853
                slirp_select_poll(&rfds, &wfds, &xfds);
1854
            }
1855
        }
1856
#endif
1857

    
1858
#endif
1859

    
1860
        if (vm_running) {
1861
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
1862
                            qemu_get_clock(vm_clock));
1863
            
1864
            if (audio_enabled) {
1865
                /* XXX: add explicit timer */
1866
                SB16_run();
1867
            }
1868
            
1869
            /* run dma transfers, if any */
1870
            DMA_run();
1871
        }
1872

    
1873
        /* real time timers */
1874
        qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
1875
                        qemu_get_clock(rt_clock));
1876
    }
1877
    cpu_disable_ticks();
1878
    return ret;
1879
}
1880

    
1881
void help(void)
1882
{
1883
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
1884
           "usage: %s [options] [disk_image]\n"
1885
           "\n"
1886
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
1887
           "\n"
1888
           "Standard options:\n"
1889
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
1890
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
1891
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
1892
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
1893
           "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
1894
           "-snapshot       write to temporary files instead of disk image files\n"
1895
           "-m megs         set virtual RAM size to megs MB\n"
1896
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
1897
           "-enable-audio   enable audio support\n"
1898
           "\n"
1899
           "Network options:\n"
1900
           "-nics n         simulate 'n' network cards [default=1]\n"
1901
           "-macaddr addr   set the mac address of the first interface\n"
1902
           "-n script       set tap/tun network init script [default=%s]\n"
1903
           "-tun-fd fd      use this fd as already opened tap/tun interface\n"
1904
#ifdef CONFIG_SLIRP
1905
           "-user-net       use user mode network stack [default if no tap/tun script]\n"
1906
#endif
1907
           "-dummy-net      use dummy network stack\n"
1908
           "\n"
1909
           "Linux boot specific:\n"
1910
           "-kernel bzImage use 'bzImage' as kernel image\n"
1911
           "-append cmdline use 'cmdline' as kernel command line\n"
1912
           "-initrd file    use 'file' as initial ram disk\n"
1913
           "\n"
1914
           "Debug/Expert options:\n"
1915
           "-s              wait gdb connection to port %d\n"
1916
           "-p port         change gdb connection port\n"
1917
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
1918
           "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
1919
           "-L path         set the directory for the BIOS and VGA BIOS\n"
1920
#ifdef USE_CODE_COPY
1921
           "-no-code-copy   disable code copy acceleration\n"
1922
#endif
1923

    
1924
           "\n"
1925
           "During emulation, use C-a h to get terminal commands:\n",
1926
#ifdef CONFIG_SOFTMMU
1927
           "qemu",
1928
#else
1929
           "qemu-fast",
1930
#endif
1931
           DEFAULT_NETWORK_SCRIPT, 
1932
           DEFAULT_GDBSTUB_PORT,
1933
           "/tmp/qemu.log");
1934
    term_print_help();
1935
#ifndef CONFIG_SOFTMMU
1936
    printf("\n"
1937
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
1938
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
1939
           "PC emulation.\n");
1940
#endif
1941
    exit(1);
1942
}
1943

    
1944
struct option long_options[] = {
1945
    { "initrd", 1, NULL, 0, },
1946
    { "hda", 1, NULL, 0, },
1947
    { "hdb", 1, NULL, 0, },
1948
    { "snapshot", 0, NULL, 0, },
1949
    { "hdachs", 1, NULL, 0, },
1950
    { "nographic", 0, NULL, 0, },
1951
    { "kernel", 1, NULL, 0, },
1952
    { "append", 1, NULL, 0, },
1953
    { "tun-fd", 1, NULL, 0, },
1954
    { "hdc", 1, NULL, 0, },
1955
    { "hdd", 1, NULL, 0, },
1956
    { "cdrom", 1, NULL, 0, },
1957
    { "boot", 1, NULL, 0, },
1958
    { "fda", 1, NULL, 0, },
1959
    { "fdb", 1, NULL, 0, },
1960
    { "no-code-copy", 0, NULL, 0 },
1961
    { "nics", 1, NULL, 0 },
1962
    { "macaddr", 1, NULL, 0 },
1963
    { "user-net", 0, NULL, 0 },
1964
    { "dummy-net", 0, NULL, 0 },
1965
    { "enable-audio", 0, NULL, 0 },
1966
    { NULL, 0, NULL, 0 },
1967
};
1968

    
1969
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1970

    
1971
/* this stack is only used during signal handling */
1972
#define SIGNAL_STACK_SIZE 32768
1973

    
1974
static uint8_t *signal_stack;
1975

    
1976
#endif
1977

    
1978
#define NET_IF_TUN   0
1979
#define NET_IF_USER  1
1980
#define NET_IF_DUMMY 2
1981

    
1982
int main(int argc, char **argv)
1983
{
1984
#ifdef CONFIG_GDBSTUB
1985
    int use_gdbstub, gdbstub_port;
1986
#endif
1987
    int c, i, long_index, has_cdrom;
1988
    int snapshot, linux_boot;
1989
    CPUState *env;
1990
    const char *initrd_filename;
1991
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
1992
    const char *kernel_filename, *kernel_cmdline;
1993
    DisplayState *ds = &display_state;
1994
    int cyls, heads, secs;
1995
    int start_emulation = 1;
1996
    uint8_t macaddr[6];
1997
    int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
1998
    
1999
#if !defined(CONFIG_SOFTMMU)
2000
    /* we never want that malloc() uses mmap() */
2001
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2002
#endif
2003
    initrd_filename = NULL;
2004
    for(i = 0; i < MAX_FD; i++)
2005
        fd_filename[i] = NULL;
2006
    for(i = 0; i < MAX_DISKS; i++)
2007
        hd_filename[i] = NULL;
2008
    ram_size = 32 * 1024 * 1024;
2009
    vga_ram_size = VGA_RAM_SIZE;
2010
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2011
#ifdef CONFIG_GDBSTUB
2012
    use_gdbstub = 0;
2013
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
2014
#endif
2015
    snapshot = 0;
2016
    nographic = 0;
2017
    kernel_filename = NULL;
2018
    kernel_cmdline = "";
2019
    has_cdrom = 1;
2020
    cyls = heads = secs = 0;
2021

    
2022
    nb_tun_fds = 0;
2023
    net_if_type = -1;
2024
    nb_nics = 1;
2025
    /* default mac address of the first network interface */
2026
    macaddr[0] = 0x52;
2027
    macaddr[1] = 0x54;
2028
    macaddr[2] = 0x00;
2029
    macaddr[3] = 0x12;
2030
    macaddr[4] = 0x34;
2031
    macaddr[5] = 0x56;
2032

    
2033

    
2034
    for(;;) {
2035
        c = getopt_long_only(argc, argv, "hm:d:n:sp:L:S", long_options, &long_index);
2036
        if (c == -1)
2037
            break;
2038
        switch(c) {
2039
        case 0:
2040
            switch(long_index) {
2041
            case 0:
2042
                initrd_filename = optarg;
2043
                break;
2044
            case 1:
2045
                hd_filename[0] = optarg;
2046
                break;
2047
            case 2:
2048
                hd_filename[1] = optarg;
2049
                break;
2050
            case 3:
2051
                snapshot = 1;
2052
                break;
2053
            case 4:
2054
                {
2055
                    const char *p;
2056
                    p = optarg;
2057
                    cyls = strtol(p, (char **)&p, 0);
2058
                    if (*p != ',')
2059
                        goto chs_fail;
2060
                    p++;
2061
                    heads = strtol(p, (char **)&p, 0);
2062
                    if (*p != ',')
2063
                        goto chs_fail;
2064
                    p++;
2065
                    secs = strtol(p, (char **)&p, 0);
2066
                    if (*p != '\0') {
2067
                    chs_fail:
2068
                        cyls = 0;
2069
                    }
2070
                }
2071
                break;
2072
            case 5:
2073
                nographic = 1;
2074
                break;
2075
            case 6:
2076
                kernel_filename = optarg;
2077
                break;
2078
            case 7:
2079
                kernel_cmdline = optarg;
2080
                break;
2081
            case 8:
2082
                {
2083
                    const char *p;
2084
                    int fd;
2085
                    if (nb_tun_fds < MAX_NICS) {
2086
                        fd = strtol(optarg, (char **)&p, 0);
2087
                        if (*p != '\0') {
2088
                            fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2089
                            exit(1);
2090
                        }
2091
                        tun_fds[nb_tun_fds++] = fd;
2092
                    }
2093
                }
2094
                break;
2095
            case 9:
2096
                hd_filename[2] = optarg;
2097
                has_cdrom = 0;
2098
                break;
2099
            case 10:
2100
                hd_filename[3] = optarg;
2101
                break;
2102
            case 11:
2103
                hd_filename[2] = optarg;
2104
                has_cdrom = 1;
2105
                break;
2106
            case 12:
2107
                boot_device = optarg[0];
2108
                if (boot_device != 'a' && boot_device != 'b' &&
2109
                    boot_device != 'c' && boot_device != 'd') {
2110
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2111
                    exit(1);
2112
                }
2113
                break;
2114
            case 13:
2115
                fd_filename[0] = optarg;
2116
                break;
2117
            case 14:
2118
                fd_filename[1] = optarg;
2119
                break;
2120
            case 15:
2121
                code_copy_enabled = 0;
2122
                break;
2123
            case 16:
2124
                nb_nics = atoi(optarg);
2125
                if (nb_nics < 1 || nb_nics > MAX_NICS) {
2126
                    fprintf(stderr, "qemu: invalid number of network interfaces\n");
2127
                    exit(1);
2128
                }
2129
                break;
2130
            case 17:
2131
                {
2132
                    const char *p;
2133
                    int i;
2134
                    p = optarg;
2135
                    for(i = 0; i < 6; i++) {
2136
                        macaddr[i] = strtol(p, (char **)&p, 16);
2137
                        if (i == 5) {
2138
                            if (*p != '\0') 
2139
                                goto macaddr_error;
2140
                        } else {
2141
                            if (*p != ':') {
2142
                            macaddr_error:
2143
                                fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2144
                                exit(1);
2145
                            }
2146
                            p++;
2147
                        }
2148
                    }
2149
                }
2150
                break;
2151
            case 18:
2152
                net_if_type = NET_IF_USER;
2153
                break;
2154
            case 19:
2155
                net_if_type = NET_IF_DUMMY;
2156
                break;
2157
            case 20:
2158
                audio_enabled = 1;
2159
                break;
2160
            }
2161
            break;
2162
        case 'h':
2163
            help();
2164
            break;
2165
        case 'm':
2166
            ram_size = atoi(optarg) * 1024 * 1024;
2167
            if (ram_size <= 0)
2168
                help();
2169
            if (ram_size > PHYS_RAM_MAX_SIZE) {
2170
                fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2171
                        PHYS_RAM_MAX_SIZE / (1024 * 1024));
2172
                exit(1);
2173
            }
2174
            break;
2175
        case 'd':
2176
            {
2177
                int mask;
2178
                CPULogItem *item;
2179

    
2180
                mask = cpu_str_to_log_mask(optarg);
2181
                if (!mask) {
2182
                    printf("Log items (comma separated):\n");
2183
                    for(item = cpu_log_items; item->mask != 0; item++) {
2184
                        printf("%-10s %s\n", item->name, item->help);
2185
                    }
2186
                    exit(1);
2187
                }
2188
                cpu_set_log(mask);
2189
            }
2190
            break;
2191
        case 'n':
2192
            pstrcpy(network_script, sizeof(network_script), optarg);
2193
            break;
2194
#ifdef CONFIG_GDBSTUB
2195
        case 's':
2196
            use_gdbstub = 1;
2197
            break;
2198
        case 'p':
2199
            gdbstub_port = atoi(optarg);
2200
            break;
2201
#endif
2202
        case 'L':
2203
            bios_dir = optarg;
2204
            break;
2205
        case 'S':
2206
            start_emulation = 0;
2207
            break;
2208
        }
2209
    }
2210

    
2211
    if (optind < argc) {
2212
        hd_filename[0] = argv[optind++];
2213
    }
2214

    
2215
    linux_boot = (kernel_filename != NULL);
2216
        
2217
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2218
        fd_filename[0] == '\0')
2219
        help();
2220
    
2221
    /* boot to cd by default if no hard disk */
2222
    if (hd_filename[0] == '\0' && boot_device == 'c') {
2223
        if (fd_filename[0] != '\0')
2224
            boot_device = 'a';
2225
        else
2226
            boot_device = 'd';
2227
    }
2228

    
2229
#if !defined(CONFIG_SOFTMMU)
2230
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2231
    {
2232
        static uint8_t stdout_buf[4096];
2233
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2234
    }
2235
#else
2236
    setvbuf(stdout, NULL, _IOLBF, 0);
2237
#endif
2238

    
2239
    /* init host network redirectors */
2240
    if (net_if_type == -1) {
2241
        net_if_type = NET_IF_TUN;
2242
#if defined(CONFIG_SLIRP)
2243
        if (access(network_script, R_OK) < 0) {
2244
            net_if_type = NET_IF_USER;
2245
        }
2246
#endif
2247
    }
2248

    
2249
    for(i = 0; i < nb_nics; i++) {
2250
        NetDriverState *nd = &nd_table[i];
2251
        nd->index = i;
2252
        /* init virtual mac address */
2253
        nd->macaddr[0] = macaddr[0];
2254
        nd->macaddr[1] = macaddr[1];
2255
        nd->macaddr[2] = macaddr[2];
2256
        nd->macaddr[3] = macaddr[3];
2257
        nd->macaddr[4] = macaddr[4];
2258
        nd->macaddr[5] = macaddr[5] + i;
2259
        switch(net_if_type) {
2260
#if defined(CONFIG_SLIRP)
2261
        case NET_IF_USER:
2262
            net_slirp_init(nd);
2263
            break;
2264
#endif
2265
#if !defined(_WIN32)
2266
        case NET_IF_TUN:
2267
            if (i < nb_tun_fds) {
2268
                net_fd_init(nd, tun_fds[i]);
2269
            } else {
2270
                if (net_tun_init(nd) < 0)
2271
                    net_dummy_init(nd);
2272
            }
2273
            break;
2274
#endif
2275
        case NET_IF_DUMMY:
2276
        default:
2277
            net_dummy_init(nd);
2278
            break;
2279
        }
2280
    }
2281

    
2282
    /* init the memory */
2283
    phys_ram_size = ram_size + vga_ram_size;
2284

    
2285
#ifdef CONFIG_SOFTMMU
2286
#ifdef _BSD
2287
    /* mallocs are always aligned on BSD. */
2288
    phys_ram_base = malloc(phys_ram_size);
2289
#else
2290
    phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2291
#endif
2292
    if (!phys_ram_base) {
2293
        fprintf(stderr, "Could not allocate physical memory\n");
2294
        exit(1);
2295
    }
2296
#else
2297
    /* as we must map the same page at several addresses, we must use
2298
       a fd */
2299
    {
2300
        const char *tmpdir;
2301

    
2302
        tmpdir = getenv("QEMU_TMPDIR");
2303
        if (!tmpdir)
2304
            tmpdir = "/tmp";
2305
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2306
        if (mkstemp(phys_ram_file) < 0) {
2307
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2308
                    phys_ram_file);
2309
            exit(1);
2310
        }
2311
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2312
        if (phys_ram_fd < 0) {
2313
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2314
                    phys_ram_file);
2315
            exit(1);
2316
        }
2317
        ftruncate(phys_ram_fd, phys_ram_size);
2318
        unlink(phys_ram_file);
2319
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2320
                             phys_ram_size, 
2321
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2322
                             phys_ram_fd, 0);
2323
        if (phys_ram_base == MAP_FAILED) {
2324
            fprintf(stderr, "Could not map physical memory\n");
2325
            exit(1);
2326
        }
2327
    }
2328
#endif
2329

    
2330
    /* we always create the cdrom drive, even if no disk is there */
2331
    if (has_cdrom) {
2332
        bs_table[2] = bdrv_new("cdrom");
2333
        bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2334
    }
2335

    
2336
    /* open the virtual block devices */
2337
    for(i = 0; i < MAX_DISKS; i++) {
2338
        if (hd_filename[i]) {
2339
            if (!bs_table[i]) {
2340
                char buf[64];
2341
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2342
                bs_table[i] = bdrv_new(buf);
2343
            }
2344
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2345
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2346
                        hd_filename[i]);
2347
                exit(1);
2348
            }
2349
            if (i == 0 && cyls != 0) 
2350
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2351
        }
2352
    }
2353

    
2354
    /* we always create at least one floppy disk */
2355
    fd_table[0] = bdrv_new("fda");
2356
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2357

    
2358
    for(i = 0; i < MAX_FD; i++) {
2359
        if (fd_filename[i]) {
2360
            if (!fd_table[i]) {
2361
                char buf[64];
2362
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2363
                fd_table[i] = bdrv_new(buf);
2364
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2365
            }
2366
            if (fd_filename[i] != '\0') {
2367
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2368
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2369
                            fd_filename[i]);
2370
                    exit(1);
2371
                }
2372
            }
2373
        }
2374
    }
2375

    
2376
    /* init CPU state */
2377
    env = cpu_init();
2378
    global_env = env;
2379
    cpu_single_env = env;
2380

    
2381
    register_savevm("timer", 0, 1, timer_save, timer_load, env);
2382
    register_savevm("cpu", 0, 1, cpu_save, cpu_load, env);
2383
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2384

    
2385
    init_ioports();
2386
    cpu_calibrate_ticks();
2387

    
2388
    /* terminal init */
2389
    if (nographic) {
2390
        dumb_display_init(ds);
2391
    } else {
2392
#ifdef CONFIG_SDL
2393
        sdl_display_init(ds);
2394
#else
2395
        dumb_display_init(ds);
2396
#endif
2397
    }
2398

    
2399
    /* setup cpu signal handlers for MMU / self modifying code handling */
2400
#if !defined(CONFIG_SOFTMMU)
2401
    
2402
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2403
    {
2404
        stack_t stk;
2405
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2406
        stk.ss_sp = signal_stack;
2407
        stk.ss_size = SIGNAL_STACK_SIZE;
2408
        stk.ss_flags = 0;
2409

    
2410
        if (sigaltstack(&stk, NULL) < 0) {
2411
            perror("sigaltstack");
2412
            exit(1);
2413
        }
2414
    }
2415
#endif
2416
    {
2417
        struct sigaction act;
2418
        
2419
        sigfillset(&act.sa_mask);
2420
        act.sa_flags = SA_SIGINFO;
2421
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2422
        act.sa_flags |= SA_ONSTACK;
2423
#endif
2424
        act.sa_sigaction = host_segv_handler;
2425
        sigaction(SIGSEGV, &act, NULL);
2426
        sigaction(SIGBUS, &act, NULL);
2427
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2428
        sigaction(SIGFPE, &act, NULL);
2429
#endif
2430
    }
2431
#endif
2432

    
2433
#ifndef _WIN32
2434
    {
2435
        struct sigaction act;
2436
        sigfillset(&act.sa_mask);
2437
        act.sa_flags = 0;
2438
        act.sa_handler = SIG_IGN;
2439
        sigaction(SIGPIPE, &act, NULL);
2440
    }
2441
#endif
2442
    init_timers();
2443

    
2444
#if defined(TARGET_I386)
2445
    pc_init(ram_size, vga_ram_size, boot_device,
2446
            ds, fd_filename, snapshot,
2447
            kernel_filename, kernel_cmdline, initrd_filename);
2448
#elif defined(TARGET_PPC)
2449
    ppc_init(ram_size, vga_ram_size, boot_device,
2450
             ds, fd_filename, snapshot,
2451
             kernel_filename, kernel_cmdline, initrd_filename);
2452
#endif
2453

    
2454
    /* launched after the device init so that it can display or not a
2455
       banner */
2456
    monitor_init();
2457

    
2458
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2459
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2460

    
2461
#ifdef CONFIG_GDBSTUB
2462
    if (use_gdbstub) {
2463
        if (gdbserver_start(gdbstub_port) < 0) {
2464
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
2465
                    gdbstub_port);
2466
            exit(1);
2467
        } else {
2468
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
2469
        }
2470
    } else 
2471
#endif
2472
    if (start_emulation)
2473
    {
2474
        vm_start();
2475
    }
2476
    term_init();
2477
    main_loop();
2478
    quit_timers();
2479
    return 0;
2480
}