Statistics
| Branch: | Revision:

root / vl.c @ 829309c7

History | View | Annotate | Download (65.6 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2004 Fabrice Bellard
5
 * 
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "vl.h"
25

    
26
#include <unistd.h>
27
#include <fcntl.h>
28
#include <signal.h>
29
#include <time.h>
30
#include <errno.h>
31
#include <sys/time.h>
32

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

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

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

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

    
79
#include "disas.h"
80

    
81
#include "exec-all.h"
82

    
83
//#define DO_TB_FLUSH
84

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

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

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

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

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

    
102
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
103
char phys_ram_file[1024];
104
CPUState *global_env;
105
CPUState *cpu_single_env;
106
void *ioport_opaque[MAX_IOPORTS];
107
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
108
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
109
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
110
int vga_ram_size;
111
static DisplayState display_state;
112
int nographic;
113
int64_t ticks_per_sec;
114
int boot_device = 'c';
115
static int ram_size;
116
static char network_script[1024];
117
int pit_min_timer_count = 0;
118
int nb_nics;
119
NetDriverState nd_table[MAX_NICS];
120
SerialState *serial_console;
121
QEMUTimer *gui_timer;
122
int vm_running;
123
int audio_enabled = 0;
124
int pci_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](ioport_opaque[address], address);
151
    address = (address + 1) & (MAX_IOPORTS - 1);
152
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
153
    return data;
154
}
155

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

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

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

    
178
void init_ioports(void)
179
{
180
    int i;
181

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

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

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

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

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

    
242
void isa_unassign_ioport(int start, int length)
243
{
244
    int i;
245

    
246
    for(i = start; i < start + length; i++) {
247
        ioport_read_table[0][i] = default_ioport_readb;
248
        ioport_read_table[1][i] = default_ioport_readw;
249
        ioport_read_table[2][i] = default_ioport_readl;
250

    
251
        ioport_write_table[0][i] = default_ioport_writeb;
252
        ioport_write_table[1][i] = default_ioport_writew;
253
        ioport_write_table[2][i] = default_ioport_writel;
254
    }
255
}
256

    
257
void pstrcpy(char *buf, int buf_size, const char *str)
258
{
259
    int c;
260
    char *q = buf;
261

    
262
    if (buf_size <= 0)
263
        return;
264

    
265
    for(;;) {
266
        c = *str++;
267
        if (c == 0 || q >= buf + buf_size - 1)
268
            break;
269
        *q++ = c;
270
    }
271
    *q = '\0';
272
}
273

    
274
/* strcat and truncate. */
275
char *pstrcat(char *buf, int buf_size, const char *s)
276
{
277
    int len;
278
    len = strlen(buf);
279
    if (len < buf_size) 
280
        pstrcpy(buf + len, buf_size - len, s);
281
    return buf;
282
}
283

    
284
/* return the size or -1 if error */
285
int load_image(const char *filename, uint8_t *addr)
286
{
287
    int fd, size;
288
    fd = open(filename, O_RDONLY | O_BINARY);
289
    if (fd < 0)
290
        return -1;
291
    size = lseek(fd, 0, SEEK_END);
292
    lseek(fd, 0, SEEK_SET);
293
    if (read(fd, addr, size) != size) {
294
        close(fd);
295
        return -1;
296
    }
297
    close(fd);
298
    return size;
299
}
300

    
301
void cpu_outb(CPUState *env, int addr, int val)
302
{
303
#ifdef DEBUG_IOPORT
304
    if (loglevel & CPU_LOG_IOPORT)
305
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
306
#endif    
307
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
308
}
309

    
310
void cpu_outw(CPUState *env, int addr, int val)
311
{
312
#ifdef DEBUG_IOPORT
313
    if (loglevel & CPU_LOG_IOPORT)
314
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
315
#endif    
316
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
317
}
318

    
319
void cpu_outl(CPUState *env, int addr, int val)
320
{
321
#ifdef DEBUG_IOPORT
322
    if (loglevel & CPU_LOG_IOPORT)
323
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
324
#endif
325
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
326
}
327

    
328
int cpu_inb(CPUState *env, int addr)
329
{
330
    int val;
331
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
332
#ifdef DEBUG_IOPORT
333
    if (loglevel & CPU_LOG_IOPORT)
334
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
335
#endif
336
    return val;
337
}
338

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

    
350
int cpu_inl(CPUState *env, int addr)
351
{
352
    int val;
353
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
354
#ifdef DEBUG_IOPORT
355
    if (loglevel & CPU_LOG_IOPORT)
356
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
357
#endif
358
    return val;
359
}
360

    
361
/***********************************************************/
362
void hw_error(const char *fmt, ...)
363
{
364
    va_list ap;
365

    
366
    va_start(ap, fmt);
367
    fprintf(stderr, "qemu: hardware error: ");
368
    vfprintf(stderr, fmt, ap);
369
    fprintf(stderr, "\n");
370
#ifdef TARGET_I386
371
    cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
372
#else
373
    cpu_dump_state(global_env, stderr, 0);
374
#endif
375
    va_end(ap);
376
    abort();
377
}
378

    
379
/***********************************************************/
380
/* timers */
381

    
382
#if defined(__powerpc__)
383

    
384
static inline uint32_t get_tbl(void) 
385
{
386
    uint32_t tbl;
387
    asm volatile("mftb %0" : "=r" (tbl));
388
    return tbl;
389
}
390

    
391
static inline uint32_t get_tbu(void) 
392
{
393
        uint32_t tbl;
394
        asm volatile("mftbu %0" : "=r" (tbl));
395
        return tbl;
396
}
397

    
398
int64_t cpu_get_real_ticks(void)
399
{
400
    uint32_t l, h, h1;
401
    /* NOTE: we test if wrapping has occurred */
402
    do {
403
        h = get_tbu();
404
        l = get_tbl();
405
        h1 = get_tbu();
406
    } while (h != h1);
407
    return ((int64_t)h << 32) | l;
408
}
409

    
410
#elif defined(__i386__)
411

    
412
int64_t cpu_get_real_ticks(void)
413
{
414
    int64_t val;
415
    asm volatile ("rdtsc" : "=A" (val));
416
    return val;
417
}
418

    
419
#elif defined(__x86_64__)
420

    
421
int64_t cpu_get_real_ticks(void)
422
{
423
    uint32_t low,high;
424
    int64_t val;
425
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
426
    val = high;
427
    val <<= 32;
428
    val |= low;
429
    return val;
430
}
431

    
432
#else
433
#error unsupported CPU
434
#endif
435

    
436
static int64_t cpu_ticks_offset;
437
static int cpu_ticks_enabled;
438

    
439
static inline int64_t cpu_get_ticks(void)
440
{
441
    if (!cpu_ticks_enabled) {
442
        return cpu_ticks_offset;
443
    } else {
444
        return cpu_get_real_ticks() + cpu_ticks_offset;
445
    }
446
}
447

    
448
/* enable cpu_get_ticks() */
449
void cpu_enable_ticks(void)
450
{
451
    if (!cpu_ticks_enabled) {
452
        cpu_ticks_offset -= cpu_get_real_ticks();
453
        cpu_ticks_enabled = 1;
454
    }
455
}
456

    
457
/* disable cpu_get_ticks() : the clock is stopped. You must not call
458
   cpu_get_ticks() after that.  */
459
void cpu_disable_ticks(void)
460
{
461
    if (cpu_ticks_enabled) {
462
        cpu_ticks_offset = cpu_get_ticks();
463
        cpu_ticks_enabled = 0;
464
    }
465
}
466

    
467
static int64_t get_clock(void)
468
{
469
#ifdef _WIN32
470
    struct _timeb tb;
471
    _ftime(&tb);
472
    return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
473
#else
474
    struct timeval tv;
475
    gettimeofday(&tv, NULL);
476
    return tv.tv_sec * 1000000LL + tv.tv_usec;
477
#endif
478
}
479

    
480
void cpu_calibrate_ticks(void)
481
{
482
    int64_t usec, ticks;
483

    
484
    usec = get_clock();
485
    ticks = cpu_get_real_ticks();
486
#ifdef _WIN32
487
    Sleep(50);
488
#else
489
    usleep(50 * 1000);
490
#endif
491
    usec = get_clock() - usec;
492
    ticks = cpu_get_real_ticks() - ticks;
493
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
494
}
495

    
496
/* compute with 96 bit intermediate result: (a*b)/c */
497
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
498
{
499
    union {
500
        uint64_t ll;
501
        struct {
502
#ifdef WORDS_BIGENDIAN
503
            uint32_t high, low;
504
#else
505
            uint32_t low, high;
506
#endif            
507
        } l;
508
    } u, res;
509
    uint64_t rl, rh;
510

    
511
    u.ll = a;
512
    rl = (uint64_t)u.l.low * (uint64_t)b;
513
    rh = (uint64_t)u.l.high * (uint64_t)b;
514
    rh += (rl >> 32);
515
    res.l.high = rh / c;
516
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
517
    return res.ll;
518
}
519

    
520
#define QEMU_TIMER_REALTIME 0
521
#define QEMU_TIMER_VIRTUAL  1
522

    
523
struct QEMUClock {
524
    int type;
525
    /* XXX: add frequency */
526
};
527

    
528
struct QEMUTimer {
529
    QEMUClock *clock;
530
    int64_t expire_time;
531
    QEMUTimerCB *cb;
532
    void *opaque;
533
    struct QEMUTimer *next;
534
};
535

    
536
QEMUClock *rt_clock;
537
QEMUClock *vm_clock;
538

    
539
static QEMUTimer *active_timers[2];
540
#ifdef _WIN32
541
static MMRESULT timerID;
542
#else
543
/* frequency of the times() clock tick */
544
static int timer_freq;
545
#endif
546

    
547
QEMUClock *qemu_new_clock(int type)
548
{
549
    QEMUClock *clock;
550
    clock = qemu_mallocz(sizeof(QEMUClock));
551
    if (!clock)
552
        return NULL;
553
    clock->type = type;
554
    return clock;
555
}
556

    
557
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
558
{
559
    QEMUTimer *ts;
560

    
561
    ts = qemu_mallocz(sizeof(QEMUTimer));
562
    ts->clock = clock;
563
    ts->cb = cb;
564
    ts->opaque = opaque;
565
    return ts;
566
}
567

    
568
void qemu_free_timer(QEMUTimer *ts)
569
{
570
    qemu_free(ts);
571
}
572

    
573
/* stop a timer, but do not dealloc it */
574
void qemu_del_timer(QEMUTimer *ts)
575
{
576
    QEMUTimer **pt, *t;
577

    
578
    /* NOTE: this code must be signal safe because
579
       qemu_timer_expired() can be called from a signal. */
580
    pt = &active_timers[ts->clock->type];
581
    for(;;) {
582
        t = *pt;
583
        if (!t)
584
            break;
585
        if (t == ts) {
586
            *pt = t->next;
587
            break;
588
        }
589
        pt = &t->next;
590
    }
591
}
592

    
593
/* modify the current timer so that it will be fired when current_time
594
   >= expire_time. The corresponding callback will be called. */
595
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
596
{
597
    QEMUTimer **pt, *t;
598

    
599
    qemu_del_timer(ts);
600

    
601
    /* add the timer in the sorted list */
602
    /* NOTE: this code must be signal safe because
603
       qemu_timer_expired() can be called from a signal. */
604
    pt = &active_timers[ts->clock->type];
605
    for(;;) {
606
        t = *pt;
607
        if (!t)
608
            break;
609
        if (t->expire_time > expire_time) 
610
            break;
611
        pt = &t->next;
612
    }
613
    ts->expire_time = expire_time;
614
    ts->next = *pt;
615
    *pt = ts;
616
}
617

    
618
int qemu_timer_pending(QEMUTimer *ts)
619
{
620
    QEMUTimer *t;
621
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
622
        if (t == ts)
623
            return 1;
624
    }
625
    return 0;
626
}
627

    
628
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
629
{
630
    if (!timer_head)
631
        return 0;
632
    return (timer_head->expire_time <= current_time);
633
}
634

    
635
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
636
{
637
    QEMUTimer *ts;
638
    
639
    for(;;) {
640
        ts = *ptimer_head;
641
        if (ts->expire_time > current_time)
642
            break;
643
        /* remove timer from the list before calling the callback */
644
        *ptimer_head = ts->next;
645
        ts->next = NULL;
646
        
647
        /* run the callback (the timer list can be modified) */
648
        ts->cb(ts->opaque);
649
    }
650
}
651

    
652
int64_t qemu_get_clock(QEMUClock *clock)
653
{
654
    switch(clock->type) {
655
    case QEMU_TIMER_REALTIME:
656
#ifdef _WIN32
657
        return GetTickCount();
658
#else
659
        {
660
            struct tms tp;
661

    
662
            /* Note that using gettimeofday() is not a good solution
663
               for timers because its value change when the date is
664
               modified. */
665
            if (timer_freq == 100) {
666
                return times(&tp) * 10;
667
            } else {
668
                return ((int64_t)times(&tp) * 1000) / timer_freq;
669
            }
670
        }
671
#endif
672
    default:
673
    case QEMU_TIMER_VIRTUAL:
674
        return cpu_get_ticks();
675
    }
676
}
677

    
678
/* save a timer */
679
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
680
{
681
    uint64_t expire_time;
682

    
683
    if (qemu_timer_pending(ts)) {
684
        expire_time = ts->expire_time;
685
    } else {
686
        expire_time = -1;
687
    }
688
    qemu_put_be64(f, expire_time);
689
}
690

    
691
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
692
{
693
    uint64_t expire_time;
694

    
695
    expire_time = qemu_get_be64(f);
696
    if (expire_time != -1) {
697
        qemu_mod_timer(ts, expire_time);
698
    } else {
699
        qemu_del_timer(ts);
700
    }
701
}
702

    
703
static void timer_save(QEMUFile *f, void *opaque)
704
{
705
    if (cpu_ticks_enabled) {
706
        hw_error("cannot save state if virtual timers are running");
707
    }
708
    qemu_put_be64s(f, &cpu_ticks_offset);
709
    qemu_put_be64s(f, &ticks_per_sec);
710
}
711

    
712
static int timer_load(QEMUFile *f, void *opaque, int version_id)
713
{
714
    if (version_id != 1)
715
        return -EINVAL;
716
    if (cpu_ticks_enabled) {
717
        return -EINVAL;
718
    }
719
    qemu_get_be64s(f, &cpu_ticks_offset);
720
    qemu_get_be64s(f, &ticks_per_sec);
721
    return 0;
722
}
723

    
724
#ifdef _WIN32
725
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
726
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
727
#else
728
static void host_alarm_handler(int host_signum)
729
#endif
730
{
731
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
732
                           qemu_get_clock(vm_clock)) ||
733
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
734
                           qemu_get_clock(rt_clock))) {
735
        /* stop the cpu because a timer occured */
736
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
737
    }
738
}
739

    
740
#ifndef _WIN32
741

    
742
#if defined(__linux__)
743

    
744
#define RTC_FREQ 1024
745

    
746
static int rtc_fd;
747

    
748
static int start_rtc_timer(void)
749
{
750
    rtc_fd = open("/dev/rtc", O_RDONLY);
751
    if (rtc_fd < 0)
752
        return -1;
753
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
754
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
755
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
756
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
757
        goto fail;
758
    }
759
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
760
    fail:
761
        close(rtc_fd);
762
        return -1;
763
    }
764
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
765
    return 0;
766
}
767

    
768
#else
769

    
770
static int start_rtc_timer(void)
771
{
772
    return -1;
773
}
774

    
775
#endif /* !defined(__linux__) */
776

    
777
#endif /* !defined(_WIN32) */
778

    
779
static void init_timers(void)
780
{
781
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
782
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
783

    
784
#ifdef _WIN32
785
    {
786
        int count=0;
787
        timerID = timeSetEvent(10,    // interval (ms)
788
                               0,     // resolution
789
                               host_alarm_handler, // function
790
                               (DWORD)&count,  // user parameter
791
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
792
         if( !timerID ) {
793
            perror("failed timer alarm");
794
            exit(1);
795
         }
796
    }
797
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
798
#else
799
    {
800
        struct sigaction act;
801
        struct itimerval itv;
802
        
803
        /* get times() syscall frequency */
804
        timer_freq = sysconf(_SC_CLK_TCK);
805
        
806
        /* timer signal */
807
        sigfillset(&act.sa_mask);
808
        act.sa_flags = 0;
809
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
810
        act.sa_flags |= SA_ONSTACK;
811
#endif
812
        act.sa_handler = host_alarm_handler;
813
        sigaction(SIGALRM, &act, NULL);
814

    
815
        itv.it_interval.tv_sec = 0;
816
        itv.it_interval.tv_usec = 1000;
817
        itv.it_value.tv_sec = 0;
818
        itv.it_value.tv_usec = 10 * 1000;
819
        setitimer(ITIMER_REAL, &itv, NULL);
820
        /* we probe the tick duration of the kernel to inform the user if
821
           the emulated kernel requested a too high timer frequency */
822
        getitimer(ITIMER_REAL, &itv);
823

    
824
        if (itv.it_interval.tv_usec > 1000) {
825
            /* try to use /dev/rtc to have a faster timer */
826
            if (start_rtc_timer() < 0)
827
                goto use_itimer;
828
            /* disable itimer */
829
            itv.it_interval.tv_sec = 0;
830
            itv.it_interval.tv_usec = 0;
831
            itv.it_value.tv_sec = 0;
832
            itv.it_value.tv_usec = 0;
833
            setitimer(ITIMER_REAL, &itv, NULL);
834

    
835
            /* use the RTC */
836
            sigaction(SIGIO, &act, NULL);
837
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
838
            fcntl(rtc_fd, F_SETOWN, getpid());
839
        } else {
840
        use_itimer:
841
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
842
                                   PIT_FREQ) / 1000000;
843
        }
844
    }
845
#endif
846
}
847

    
848
void quit_timers(void)
849
{
850
#ifdef _WIN32
851
    timeKillEvent(timerID);
852
#endif
853
}
854

    
855
/***********************************************************/
856
/* serial device */
857

    
858
#ifdef _WIN32
859

    
860
int serial_open_device(void)
861
{
862
    return -1;
863
}
864

    
865
#else
866

    
867
int serial_open_device(void)
868
{
869
    char slave_name[1024];
870
    int master_fd, slave_fd;
871

    
872
    if (serial_console == NULL && nographic) {
873
        /* use console for serial port */
874
        return 0;
875
    } else {
876
        if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
877
            fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
878
            return -1;
879
        }
880
        fprintf(stderr, "Serial port redirected to %s\n", slave_name);
881
        return master_fd;
882
    }
883
}
884

    
885
#endif
886

    
887
/***********************************************************/
888
/* Linux network device redirectors */
889

    
890
void hex_dump(FILE *f, const uint8_t *buf, int size)
891
{
892
    int len, i, j, c;
893

    
894
    for(i=0;i<size;i+=16) {
895
        len = size - i;
896
        if (len > 16)
897
            len = 16;
898
        fprintf(f, "%08x ", i);
899
        for(j=0;j<16;j++) {
900
            if (j < len)
901
                fprintf(f, " %02x", buf[i+j]);
902
            else
903
                fprintf(f, "   ");
904
        }
905
        fprintf(f, " ");
906
        for(j=0;j<len;j++) {
907
            c = buf[i+j];
908
            if (c < ' ' || c > '~')
909
                c = '.';
910
            fprintf(f, "%c", c);
911
        }
912
        fprintf(f, "\n");
913
    }
914
}
915

    
916
void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
917
{
918
    nd->send_packet(nd, buf, size);
919
}
920

    
921
void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
922
                          IOReadHandler *fd_read, void *opaque)
923
{
924
    nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
925
}
926

    
927
/* dummy network adapter */
928

    
929
static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
930
{
931
}
932

    
933
static void dummy_add_read_packet(NetDriverState *nd, 
934
                                  IOCanRWHandler *fd_can_read, 
935
                                  IOReadHandler *fd_read, void *opaque)
936
{
937
}
938

    
939
static int net_dummy_init(NetDriverState *nd)
940
{
941
    nd->send_packet = dummy_send_packet;
942
    nd->add_read_packet = dummy_add_read_packet;
943
    pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
944
    return 0;
945
}
946

    
947
#if defined(CONFIG_SLIRP)
948

    
949
/* slirp network adapter */
950

    
951
static void *slirp_fd_opaque;
952
static IOCanRWHandler *slirp_fd_can_read;
953
static IOReadHandler *slirp_fd_read;
954
static int slirp_inited;
955

    
956
int slirp_can_output(void)
957
{
958
    return slirp_fd_can_read(slirp_fd_opaque);
959
}
960

    
961
void slirp_output(const uint8_t *pkt, int pkt_len)
962
{
963
#if 0
964
    printf("output:\n");
965
    hex_dump(stdout, pkt, pkt_len);
966
#endif
967
    slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
968
}
969

    
970
static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
971
{
972
#if 0
973
    printf("input:\n");
974
    hex_dump(stdout, buf, size);
975
#endif
976
    slirp_input(buf, size);
977
}
978

    
979
static void slirp_add_read_packet(NetDriverState *nd, 
980
                                  IOCanRWHandler *fd_can_read, 
981
                                  IOReadHandler *fd_read, void *opaque)
982
{
983
    slirp_fd_opaque = opaque;
984
    slirp_fd_can_read = fd_can_read;
985
    slirp_fd_read = fd_read;
986
}
987

    
988
static int net_slirp_init(NetDriverState *nd)
989
{
990
    if (!slirp_inited) {
991
        slirp_inited = 1;
992
        slirp_init();
993
    }
994
    nd->send_packet = slirp_send_packet;
995
    nd->add_read_packet = slirp_add_read_packet;
996
    pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
997
    return 0;
998
}
999

    
1000
#endif /* CONFIG_SLIRP */
1001

    
1002
#if !defined(_WIN32)
1003
#ifdef _BSD
1004
static int tun_open(char *ifname, int ifname_size)
1005
{
1006
    int fd;
1007
    char *dev;
1008
    struct stat s;
1009

    
1010
    fd = open("/dev/tap", O_RDWR);
1011
    if (fd < 0) {
1012
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1013
        return -1;
1014
    }
1015

    
1016
    fstat(fd, &s);
1017
    dev = devname(s.st_rdev, S_IFCHR);
1018
    pstrcpy(ifname, ifname_size, dev);
1019

    
1020
    fcntl(fd, F_SETFL, O_NONBLOCK);
1021
    return fd;
1022
}
1023
#else
1024
static int tun_open(char *ifname, int ifname_size)
1025
{
1026
    struct ifreq ifr;
1027
    int fd, ret;
1028
    
1029
    fd = open("/dev/net/tun", O_RDWR);
1030
    if (fd < 0) {
1031
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1032
        return -1;
1033
    }
1034
    memset(&ifr, 0, sizeof(ifr));
1035
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1036
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1037
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1038
    if (ret != 0) {
1039
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1040
        close(fd);
1041
        return -1;
1042
    }
1043
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
1044
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
1045
    fcntl(fd, F_SETFL, O_NONBLOCK);
1046
    return fd;
1047
}
1048
#endif
1049

    
1050
static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1051
{
1052
    write(nd->fd, buf, size);
1053
}
1054

    
1055
static void tun_add_read_packet(NetDriverState *nd, 
1056
                                IOCanRWHandler *fd_can_read, 
1057
                                IOReadHandler *fd_read, void *opaque)
1058
{
1059
    qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1060
}
1061

    
1062
static int net_tun_init(NetDriverState *nd)
1063
{
1064
    int pid, status;
1065
    char *args[3];
1066
    char **parg;
1067

    
1068
    nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1069
    if (nd->fd < 0)
1070
        return -1;
1071

    
1072
    /* try to launch network init script */
1073
    pid = fork();
1074
    if (pid >= 0) {
1075
        if (pid == 0) {
1076
            parg = args;
1077
            *parg++ = network_script;
1078
            *parg++ = nd->ifname;
1079
            *parg++ = NULL;
1080
            execv(network_script, args);
1081
            exit(1);
1082
        }
1083
        while (waitpid(pid, &status, 0) != pid);
1084
        if (!WIFEXITED(status) ||
1085
            WEXITSTATUS(status) != 0) {
1086
            fprintf(stderr, "%s: could not launch network script\n",
1087
                    network_script);
1088
        }
1089
    }
1090
    nd->send_packet = tun_send_packet;
1091
    nd->add_read_packet = tun_add_read_packet;
1092
    return 0;
1093
}
1094

    
1095
static int net_fd_init(NetDriverState *nd, int fd)
1096
{
1097
    nd->fd = fd;
1098
    nd->send_packet = tun_send_packet;
1099
    nd->add_read_packet = tun_add_read_packet;
1100
    pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1101
    return 0;
1102
}
1103

    
1104
#endif /* !_WIN32 */
1105

    
1106
/***********************************************************/
1107
/* dumb display */
1108

    
1109
#ifdef _WIN32
1110

    
1111
static void term_exit(void)
1112
{
1113
}
1114

    
1115
static void term_init(void)
1116
{
1117
}
1118

    
1119
#else
1120

    
1121
/* init terminal so that we can grab keys */
1122
static struct termios oldtty;
1123

    
1124
static void term_exit(void)
1125
{
1126
    tcsetattr (0, TCSANOW, &oldtty);
1127
}
1128

    
1129
static void term_init(void)
1130
{
1131
    struct termios tty;
1132

    
1133
    tcgetattr (0, &tty);
1134
    oldtty = tty;
1135

    
1136
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1137
                          |INLCR|IGNCR|ICRNL|IXON);
1138
    tty.c_oflag |= OPOST;
1139
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1140
    /* if graphical mode, we allow Ctrl-C handling */
1141
    if (nographic)
1142
        tty.c_lflag &= ~ISIG;
1143
    tty.c_cflag &= ~(CSIZE|PARENB);
1144
    tty.c_cflag |= CS8;
1145
    tty.c_cc[VMIN] = 1;
1146
    tty.c_cc[VTIME] = 0;
1147
    
1148
    tcsetattr (0, TCSANOW, &tty);
1149

    
1150
    atexit(term_exit);
1151

    
1152
    fcntl(0, F_SETFL, O_NONBLOCK);
1153
}
1154

    
1155
#endif
1156

    
1157
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1158
{
1159
}
1160

    
1161
static void dumb_resize(DisplayState *ds, int w, int h)
1162
{
1163
}
1164

    
1165
static void dumb_refresh(DisplayState *ds)
1166
{
1167
    vga_update_display();
1168
}
1169

    
1170
void dumb_display_init(DisplayState *ds)
1171
{
1172
    ds->data = NULL;
1173
    ds->linesize = 0;
1174
    ds->depth = 0;
1175
    ds->dpy_update = dumb_update;
1176
    ds->dpy_resize = dumb_resize;
1177
    ds->dpy_refresh = dumb_refresh;
1178
}
1179

    
1180
#if !defined(CONFIG_SOFTMMU)
1181
/***********************************************************/
1182
/* cpu signal handler */
1183
static void host_segv_handler(int host_signum, siginfo_t *info, 
1184
                              void *puc)
1185
{
1186
    if (cpu_signal_handler(host_signum, info, puc))
1187
        return;
1188
    term_exit();
1189
    abort();
1190
}
1191
#endif
1192

    
1193
/***********************************************************/
1194
/* I/O handling */
1195

    
1196
#define MAX_IO_HANDLERS 64
1197

    
1198
typedef struct IOHandlerRecord {
1199
    int fd;
1200
    IOCanRWHandler *fd_can_read;
1201
    IOReadHandler *fd_read;
1202
    void *opaque;
1203
    /* temporary data */
1204
    struct pollfd *ufd;
1205
    int max_size;
1206
    struct IOHandlerRecord *next;
1207
} IOHandlerRecord;
1208

    
1209
static IOHandlerRecord *first_io_handler;
1210

    
1211
int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1212
                             IOReadHandler *fd_read, void *opaque)
1213
{
1214
    IOHandlerRecord *ioh;
1215

    
1216
    ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1217
    if (!ioh)
1218
        return -1;
1219
    ioh->fd = fd;
1220
    ioh->fd_can_read = fd_can_read;
1221
    ioh->fd_read = fd_read;
1222
    ioh->opaque = opaque;
1223
    ioh->next = first_io_handler;
1224
    first_io_handler = ioh;
1225
    return 0;
1226
}
1227

    
1228
void qemu_del_fd_read_handler(int fd)
1229
{
1230
    IOHandlerRecord **pioh, *ioh;
1231

    
1232
    pioh = &first_io_handler;
1233
    for(;;) {
1234
        ioh = *pioh;
1235
        if (ioh == NULL)
1236
            break;
1237
        if (ioh->fd == fd) {
1238
            *pioh = ioh->next;
1239
            break;
1240
        }
1241
        pioh = &ioh->next;
1242
    }
1243
}
1244

    
1245
/***********************************************************/
1246
/* savevm/loadvm support */
1247

    
1248
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1249
{
1250
    fwrite(buf, 1, size, f);
1251
}
1252

    
1253
void qemu_put_byte(QEMUFile *f, int v)
1254
{
1255
    fputc(v, f);
1256
}
1257

    
1258
void qemu_put_be16(QEMUFile *f, unsigned int v)
1259
{
1260
    qemu_put_byte(f, v >> 8);
1261
    qemu_put_byte(f, v);
1262
}
1263

    
1264
void qemu_put_be32(QEMUFile *f, unsigned int v)
1265
{
1266
    qemu_put_byte(f, v >> 24);
1267
    qemu_put_byte(f, v >> 16);
1268
    qemu_put_byte(f, v >> 8);
1269
    qemu_put_byte(f, v);
1270
}
1271

    
1272
void qemu_put_be64(QEMUFile *f, uint64_t v)
1273
{
1274
    qemu_put_be32(f, v >> 32);
1275
    qemu_put_be32(f, v);
1276
}
1277

    
1278
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1279
{
1280
    return fread(buf, 1, size, f);
1281
}
1282

    
1283
int qemu_get_byte(QEMUFile *f)
1284
{
1285
    int v;
1286
    v = fgetc(f);
1287
    if (v == EOF)
1288
        return 0;
1289
    else
1290
        return v;
1291
}
1292

    
1293
unsigned int qemu_get_be16(QEMUFile *f)
1294
{
1295
    unsigned int v;
1296
    v = qemu_get_byte(f) << 8;
1297
    v |= qemu_get_byte(f);
1298
    return v;
1299
}
1300

    
1301
unsigned int qemu_get_be32(QEMUFile *f)
1302
{
1303
    unsigned int v;
1304
    v = qemu_get_byte(f) << 24;
1305
    v |= qemu_get_byte(f) << 16;
1306
    v |= qemu_get_byte(f) << 8;
1307
    v |= qemu_get_byte(f);
1308
    return v;
1309
}
1310

    
1311
uint64_t qemu_get_be64(QEMUFile *f)
1312
{
1313
    uint64_t v;
1314
    v = (uint64_t)qemu_get_be32(f) << 32;
1315
    v |= qemu_get_be32(f);
1316
    return v;
1317
}
1318

    
1319
int64_t qemu_ftell(QEMUFile *f)
1320
{
1321
    return ftell(f);
1322
}
1323

    
1324
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1325
{
1326
    if (fseek(f, pos, whence) < 0)
1327
        return -1;
1328
    return ftell(f);
1329
}
1330

    
1331
typedef struct SaveStateEntry {
1332
    char idstr[256];
1333
    int instance_id;
1334
    int version_id;
1335
    SaveStateHandler *save_state;
1336
    LoadStateHandler *load_state;
1337
    void *opaque;
1338
    struct SaveStateEntry *next;
1339
} SaveStateEntry;
1340

    
1341
static SaveStateEntry *first_se;
1342

    
1343
int register_savevm(const char *idstr, 
1344
                    int instance_id, 
1345
                    int version_id,
1346
                    SaveStateHandler *save_state,
1347
                    LoadStateHandler *load_state,
1348
                    void *opaque)
1349
{
1350
    SaveStateEntry *se, **pse;
1351

    
1352
    se = qemu_malloc(sizeof(SaveStateEntry));
1353
    if (!se)
1354
        return -1;
1355
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1356
    se->instance_id = instance_id;
1357
    se->version_id = version_id;
1358
    se->save_state = save_state;
1359
    se->load_state = load_state;
1360
    se->opaque = opaque;
1361
    se->next = NULL;
1362

    
1363
    /* add at the end of list */
1364
    pse = &first_se;
1365
    while (*pse != NULL)
1366
        pse = &(*pse)->next;
1367
    *pse = se;
1368
    return 0;
1369
}
1370

    
1371
#define QEMU_VM_FILE_MAGIC   0x5145564d
1372
#define QEMU_VM_FILE_VERSION 0x00000001
1373

    
1374
int qemu_savevm(const char *filename)
1375
{
1376
    SaveStateEntry *se;
1377
    QEMUFile *f;
1378
    int len, len_pos, cur_pos, saved_vm_running, ret;
1379

    
1380
    saved_vm_running = vm_running;
1381
    vm_stop(0);
1382

    
1383
    f = fopen(filename, "wb");
1384
    if (!f) {
1385
        ret = -1;
1386
        goto the_end;
1387
    }
1388

    
1389
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1390
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1391

    
1392
    for(se = first_se; se != NULL; se = se->next) {
1393
        /* ID string */
1394
        len = strlen(se->idstr);
1395
        qemu_put_byte(f, len);
1396
        qemu_put_buffer(f, se->idstr, len);
1397

    
1398
        qemu_put_be32(f, se->instance_id);
1399
        qemu_put_be32(f, se->version_id);
1400

    
1401
        /* record size: filled later */
1402
        len_pos = ftell(f);
1403
        qemu_put_be32(f, 0);
1404
        
1405
        se->save_state(f, se->opaque);
1406

    
1407
        /* fill record size */
1408
        cur_pos = ftell(f);
1409
        len = ftell(f) - len_pos - 4;
1410
        fseek(f, len_pos, SEEK_SET);
1411
        qemu_put_be32(f, len);
1412
        fseek(f, cur_pos, SEEK_SET);
1413
    }
1414

    
1415
    fclose(f);
1416
    ret = 0;
1417
 the_end:
1418
    if (saved_vm_running)
1419
        vm_start();
1420
    return ret;
1421
}
1422

    
1423
static SaveStateEntry *find_se(const char *idstr, int instance_id)
1424
{
1425
    SaveStateEntry *se;
1426

    
1427
    for(se = first_se; se != NULL; se = se->next) {
1428
        if (!strcmp(se->idstr, idstr) && 
1429
            instance_id == se->instance_id)
1430
            return se;
1431
    }
1432
    return NULL;
1433
}
1434

    
1435
int qemu_loadvm(const char *filename)
1436
{
1437
    SaveStateEntry *se;
1438
    QEMUFile *f;
1439
    int len, cur_pos, ret, instance_id, record_len, version_id;
1440
    int saved_vm_running;
1441
    unsigned int v;
1442
    char idstr[256];
1443
    
1444
    saved_vm_running = vm_running;
1445
    vm_stop(0);
1446

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

    
1453
    v = qemu_get_be32(f);
1454
    if (v != QEMU_VM_FILE_MAGIC)
1455
        goto fail;
1456
    v = qemu_get_be32(f);
1457
    if (v != QEMU_VM_FILE_VERSION) {
1458
    fail:
1459
        fclose(f);
1460
        ret = -1;
1461
        goto the_end;
1462
    }
1463
    for(;;) {
1464
#if defined (DO_TB_FLUSH)
1465
        tb_flush(global_env);
1466
#endif
1467
        len = qemu_get_byte(f);
1468
        if (feof(f))
1469
            break;
1470
        qemu_get_buffer(f, idstr, len);
1471
        idstr[len] = '\0';
1472
        instance_id = qemu_get_be32(f);
1473
        version_id = qemu_get_be32(f);
1474
        record_len = qemu_get_be32(f);
1475
#if 0
1476
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1477
               idstr, instance_id, version_id, record_len);
1478
#endif
1479
        cur_pos = ftell(f);
1480
        se = find_se(idstr, instance_id);
1481
        if (!se) {
1482
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1483
                    instance_id, idstr);
1484
        } else {
1485
            ret = se->load_state(f, se->opaque, version_id);
1486
            if (ret < 0) {
1487
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1488
                        instance_id, idstr);
1489
            }
1490
        }
1491
        /* always seek to exact end of record */
1492
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1493
    }
1494
    fclose(f);
1495
    ret = 0;
1496
 the_end:
1497
    if (saved_vm_running)
1498
        vm_start();
1499
    return ret;
1500
}
1501

    
1502
/***********************************************************/
1503
/* cpu save/restore */
1504

    
1505
#if defined(TARGET_I386)
1506

    
1507
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1508
{
1509
    qemu_put_be32(f, (uint32_t)dt->base);
1510
    qemu_put_be32(f, dt->limit);
1511
    qemu_put_be32(f, dt->flags);
1512
}
1513

    
1514
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1515
{
1516
    dt->base = (uint8_t *)qemu_get_be32(f);
1517
    dt->limit = qemu_get_be32(f);
1518
    dt->flags = qemu_get_be32(f);
1519
}
1520

    
1521
void cpu_save(QEMUFile *f, void *opaque)
1522
{
1523
    CPUState *env = opaque;
1524
    uint16_t fptag, fpus, fpuc;
1525
    uint32_t hflags;
1526
    int i;
1527

    
1528
    for(i = 0; i < 8; i++)
1529
        qemu_put_be32s(f, &env->regs[i]);
1530
    qemu_put_be32s(f, &env->eip);
1531
    qemu_put_be32s(f, &env->eflags);
1532
    qemu_put_be32s(f, &env->eflags);
1533
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1534
    qemu_put_be32s(f, &hflags);
1535
    
1536
    /* FPU */
1537
    fpuc = env->fpuc;
1538
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1539
    fptag = 0;
1540
    for (i=7; i>=0; i--) {
1541
        fptag <<= 2;
1542
        if (env->fptags[i]) {
1543
            fptag |= 3;
1544
        }
1545
    }
1546
    
1547
    qemu_put_be16s(f, &fpuc);
1548
    qemu_put_be16s(f, &fpus);
1549
    qemu_put_be16s(f, &fptag);
1550

    
1551
    for(i = 0; i < 8; i++) {
1552
        uint64_t mant;
1553
        uint16_t exp;
1554
        cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1555
        qemu_put_be64(f, mant);
1556
        qemu_put_be16(f, exp);
1557
    }
1558

    
1559
    for(i = 0; i < 6; i++)
1560
        cpu_put_seg(f, &env->segs[i]);
1561
    cpu_put_seg(f, &env->ldt);
1562
    cpu_put_seg(f, &env->tr);
1563
    cpu_put_seg(f, &env->gdt);
1564
    cpu_put_seg(f, &env->idt);
1565
    
1566
    qemu_put_be32s(f, &env->sysenter_cs);
1567
    qemu_put_be32s(f, &env->sysenter_esp);
1568
    qemu_put_be32s(f, &env->sysenter_eip);
1569
    
1570
    qemu_put_be32s(f, &env->cr[0]);
1571
    qemu_put_be32s(f, &env->cr[2]);
1572
    qemu_put_be32s(f, &env->cr[3]);
1573
    qemu_put_be32s(f, &env->cr[4]);
1574
    
1575
    for(i = 0; i < 8; i++)
1576
        qemu_put_be32s(f, &env->dr[i]);
1577

    
1578
    /* MMU */
1579
    qemu_put_be32s(f, &env->a20_mask);
1580
}
1581

    
1582
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1583
{
1584
    CPUState *env = opaque;
1585
    int i;
1586
    uint32_t hflags;
1587
    uint16_t fpus, fpuc, fptag;
1588

    
1589
    if (version_id != 1)
1590
        return -EINVAL;
1591
    for(i = 0; i < 8; i++)
1592
        qemu_get_be32s(f, &env->regs[i]);
1593
    qemu_get_be32s(f, &env->eip);
1594
    qemu_get_be32s(f, &env->eflags);
1595
    qemu_get_be32s(f, &env->eflags);
1596
    qemu_get_be32s(f, &hflags);
1597

    
1598
    qemu_get_be16s(f, &fpuc);
1599
    qemu_get_be16s(f, &fpus);
1600
    qemu_get_be16s(f, &fptag);
1601

    
1602
    for(i = 0; i < 8; i++) {
1603
        uint64_t mant;
1604
        uint16_t exp;
1605
        mant = qemu_get_be64(f);
1606
        exp = qemu_get_be16(f);
1607
        env->fpregs[i] = cpu_set_fp80(mant, exp);
1608
    }
1609

    
1610
    env->fpuc = fpuc;
1611
    env->fpstt = (fpus >> 11) & 7;
1612
    env->fpus = fpus & ~0x3800;
1613
    for(i = 0; i < 8; i++) {
1614
        env->fptags[i] = ((fptag & 3) == 3);
1615
        fptag >>= 2;
1616
    }
1617
    
1618
    for(i = 0; i < 6; i++)
1619
        cpu_get_seg(f, &env->segs[i]);
1620
    cpu_get_seg(f, &env->ldt);
1621
    cpu_get_seg(f, &env->tr);
1622
    cpu_get_seg(f, &env->gdt);
1623
    cpu_get_seg(f, &env->idt);
1624
    
1625
    qemu_get_be32s(f, &env->sysenter_cs);
1626
    qemu_get_be32s(f, &env->sysenter_esp);
1627
    qemu_get_be32s(f, &env->sysenter_eip);
1628
    
1629
    qemu_get_be32s(f, &env->cr[0]);
1630
    qemu_get_be32s(f, &env->cr[2]);
1631
    qemu_get_be32s(f, &env->cr[3]);
1632
    qemu_get_be32s(f, &env->cr[4]);
1633
    
1634
    for(i = 0; i < 8; i++)
1635
        qemu_get_be32s(f, &env->dr[i]);
1636

    
1637
    /* MMU */
1638
    qemu_get_be32s(f, &env->a20_mask);
1639

    
1640
    /* XXX: compute hflags from scratch, except for CPL and IIF */
1641
    env->hflags = hflags;
1642
    tlb_flush(env, 1);
1643
    return 0;
1644
}
1645

    
1646
#elif defined(TARGET_PPC)
1647
void cpu_save(QEMUFile *f, void *opaque)
1648
{
1649
}
1650

    
1651
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1652
{
1653
    return 0;
1654
}
1655
#else
1656

    
1657
#warning No CPU save/restore functions
1658

    
1659
#endif
1660

    
1661
/***********************************************************/
1662
/* ram save/restore */
1663

    
1664
/* we just avoid storing empty pages */
1665
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1666
{
1667
    int i, v;
1668

    
1669
    v = buf[0];
1670
    for(i = 1; i < len; i++) {
1671
        if (buf[i] != v)
1672
            goto normal_save;
1673
    }
1674
    qemu_put_byte(f, 1);
1675
    qemu_put_byte(f, v);
1676
    return;
1677
 normal_save:
1678
    qemu_put_byte(f, 0); 
1679
    qemu_put_buffer(f, buf, len);
1680
}
1681

    
1682
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1683
{
1684
    int v;
1685

    
1686
    v = qemu_get_byte(f);
1687
    switch(v) {
1688
    case 0:
1689
        if (qemu_get_buffer(f, buf, len) != len)
1690
            return -EIO;
1691
        break;
1692
    case 1:
1693
        v = qemu_get_byte(f);
1694
        memset(buf, v, len);
1695
        break;
1696
    default:
1697
        return -EINVAL;
1698
    }
1699
    return 0;
1700
}
1701

    
1702
static void ram_save(QEMUFile *f, void *opaque)
1703
{
1704
    int i;
1705
    qemu_put_be32(f, phys_ram_size);
1706
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1707
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1708
    }
1709
}
1710

    
1711
static int ram_load(QEMUFile *f, void *opaque, int version_id)
1712
{
1713
    int i, ret;
1714

    
1715
    if (version_id != 1)
1716
        return -EINVAL;
1717
    if (qemu_get_be32(f) != phys_ram_size)
1718
        return -EINVAL;
1719
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1720
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1721
        if (ret)
1722
            return ret;
1723
    }
1724
    return 0;
1725
}
1726

    
1727
/***********************************************************/
1728
/* main execution loop */
1729

    
1730
void gui_update(void *opaque)
1731
{
1732
    display_state.dpy_refresh(&display_state);
1733
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1734
}
1735

    
1736
/* XXX: support several handlers */
1737
VMStopHandler *vm_stop_cb;
1738
VMStopHandler *vm_stop_opaque;
1739

    
1740
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1741
{
1742
    vm_stop_cb = cb;
1743
    vm_stop_opaque = opaque;
1744
    return 0;
1745
}
1746

    
1747
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1748
{
1749
    vm_stop_cb = NULL;
1750
}
1751

    
1752
void vm_start(void)
1753
{
1754
    if (!vm_running) {
1755
        cpu_enable_ticks();
1756
        vm_running = 1;
1757
    }
1758
}
1759

    
1760
void vm_stop(int reason) 
1761
{
1762
    if (vm_running) {
1763
        cpu_disable_ticks();
1764
        vm_running = 0;
1765
        if (reason != 0) {
1766
            if (vm_stop_cb) {
1767
                vm_stop_cb(vm_stop_opaque, reason);
1768
            }
1769
        }
1770
    }
1771
}
1772

    
1773
int main_loop(void)
1774
{
1775
#ifndef _WIN32
1776
    struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1777
    IOHandlerRecord *ioh, *ioh_next;
1778
    uint8_t buf[4096];
1779
    int n, max_size;
1780
#endif
1781
    int ret, timeout;
1782
    CPUState *env = global_env;
1783

    
1784
    for(;;) {
1785
        if (vm_running) {
1786
            ret = cpu_exec(env);
1787
            if (reset_requested) {
1788
                ret = EXCP_INTERRUPT; 
1789
                break;
1790
            }
1791
            if (ret == EXCP_DEBUG) {
1792
                vm_stop(EXCP_DEBUG);
1793
            }
1794
            /* if hlt instruction, we wait until the next IRQ */
1795
            /* XXX: use timeout computed from timers */
1796
            if (ret == EXCP_HLT) 
1797
                timeout = 10;
1798
            else
1799
                timeout = 0;
1800
        } else {
1801
            timeout = 10;
1802
        }
1803

    
1804
#ifdef _WIN32
1805
        if (timeout > 0)
1806
            Sleep(timeout);
1807
#else
1808

    
1809
        /* poll any events */
1810
        /* XXX: separate device handlers from system ones */
1811
        pf = ufds;
1812
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1813
            if (!ioh->fd_can_read) {
1814
                max_size = 0;
1815
                pf->fd = ioh->fd;
1816
                pf->events = POLLIN;
1817
                ioh->ufd = pf;
1818
                pf++;
1819
            } else {
1820
                max_size = ioh->fd_can_read(ioh->opaque);
1821
                if (max_size > 0) {
1822
                    if (max_size > sizeof(buf))
1823
                        max_size = sizeof(buf);
1824
                    pf->fd = ioh->fd;
1825
                    pf->events = POLLIN;
1826
                    ioh->ufd = pf;
1827
                    pf++;
1828
                } else {
1829
                    ioh->ufd = NULL;
1830
                }
1831
            }
1832
            ioh->max_size = max_size;
1833
        }
1834
        
1835
        ret = poll(ufds, pf - ufds, timeout);
1836
        if (ret > 0) {
1837
            /* XXX: better handling of removal */
1838
            for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1839
                ioh_next = ioh->next;
1840
                pf = ioh->ufd;
1841
                if (pf) {
1842
                    if (pf->revents & POLLIN) {
1843
                        if (ioh->max_size == 0) {
1844
                            /* just a read event */
1845
                            ioh->fd_read(ioh->opaque, NULL, 0);
1846
                        } else {
1847
                            n = read(ioh->fd, buf, ioh->max_size);
1848
                            if (n >= 0) {
1849
                                ioh->fd_read(ioh->opaque, buf, n);
1850
                            } else if (errno != EAGAIN) {
1851
                                ioh->fd_read(ioh->opaque, NULL, -errno);
1852
                            }
1853
                        }
1854
                    }
1855
                }
1856
            }
1857
        }
1858

    
1859
#if defined(CONFIG_SLIRP)
1860
        /* XXX: merge with poll() */
1861
        if (slirp_inited) {
1862
            fd_set rfds, wfds, xfds;
1863
            int nfds;
1864
            struct timeval tv;
1865

    
1866
            nfds = -1;
1867
            FD_ZERO(&rfds);
1868
            FD_ZERO(&wfds);
1869
            FD_ZERO(&xfds);
1870
            slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1871
            tv.tv_sec = 0;
1872
            tv.tv_usec = 0;
1873
            ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1874
            if (ret >= 0) {
1875
                slirp_select_poll(&rfds, &wfds, &xfds);
1876
            }
1877
        }
1878
#endif
1879

    
1880
#endif
1881

    
1882
        if (vm_running) {
1883
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
1884
                            qemu_get_clock(vm_clock));
1885
            
1886
            if (audio_enabled) {
1887
                /* XXX: add explicit timer */
1888
                SB16_run();
1889
            }
1890
            
1891
            /* run dma transfers, if any */
1892
            DMA_run();
1893
        }
1894

    
1895
        /* real time timers */
1896
        qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
1897
                        qemu_get_clock(rt_clock));
1898
    }
1899
    cpu_disable_ticks();
1900
    return ret;
1901
}
1902

    
1903
void help(void)
1904
{
1905
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
1906
           "usage: %s [options] [disk_image]\n"
1907
           "\n"
1908
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
1909
           "\n"
1910
           "Standard options:\n"
1911
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
1912
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
1913
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
1914
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
1915
           "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
1916
           "-snapshot       write to temporary files instead of disk image files\n"
1917
           "-m megs         set virtual RAM size to megs MB\n"
1918
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
1919
           "-enable-audio   enable audio support\n"
1920
           "\n"
1921
           "Network options:\n"
1922
           "-nics n         simulate 'n' network cards [default=1]\n"
1923
           "-macaddr addr   set the mac address of the first interface\n"
1924
           "-n script       set tap/tun network init script [default=%s]\n"
1925
           "-tun-fd fd      use this fd as already opened tap/tun interface\n"
1926
#ifdef CONFIG_SLIRP
1927
           "-user-net       use user mode network stack [default if no tap/tun script]\n"
1928
#endif
1929
           "-dummy-net      use dummy network stack\n"
1930
           "\n"
1931
           "Linux boot specific:\n"
1932
           "-kernel bzImage use 'bzImage' as kernel image\n"
1933
           "-append cmdline use 'cmdline' as kernel command line\n"
1934
           "-initrd file    use 'file' as initial ram disk\n"
1935
           "\n"
1936
           "Debug/Expert options:\n"
1937
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
1938
           "-s              wait gdb connection to port %d\n"
1939
           "-p port         change gdb connection port\n"
1940
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
1941
           "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
1942
           "-L path         set the directory for the BIOS and VGA BIOS\n"
1943
#ifdef USE_CODE_COPY
1944
           "-no-code-copy   disable code copy acceleration\n"
1945
#endif
1946

    
1947
           "\n"
1948
           "During emulation, use C-a h to get terminal commands:\n",
1949
#ifdef CONFIG_SOFTMMU
1950
           "qemu",
1951
#else
1952
           "qemu-fast",
1953
#endif
1954
           DEFAULT_NETWORK_SCRIPT, 
1955
           DEFAULT_GDBSTUB_PORT,
1956
           "/tmp/qemu.log");
1957
    term_print_help();
1958
#ifndef CONFIG_SOFTMMU
1959
    printf("\n"
1960
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
1961
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
1962
           "PC emulation.\n");
1963
#endif
1964
    exit(1);
1965
}
1966

    
1967
#define HAS_ARG 0x0001
1968

    
1969
enum {
1970
    QEMU_OPTION_h,
1971

    
1972
    QEMU_OPTION_fda,
1973
    QEMU_OPTION_fdb,
1974
    QEMU_OPTION_hda,
1975
    QEMU_OPTION_hdb,
1976
    QEMU_OPTION_hdc,
1977
    QEMU_OPTION_hdd,
1978
    QEMU_OPTION_cdrom,
1979
    QEMU_OPTION_boot,
1980
    QEMU_OPTION_snapshot,
1981
    QEMU_OPTION_m,
1982
    QEMU_OPTION_nographic,
1983
    QEMU_OPTION_enable_audio,
1984

    
1985
    QEMU_OPTION_nics,
1986
    QEMU_OPTION_macaddr,
1987
    QEMU_OPTION_n,
1988
    QEMU_OPTION_tun_fd,
1989
    QEMU_OPTION_user_net,
1990
    QEMU_OPTION_dummy_net,
1991

    
1992
    QEMU_OPTION_kernel,
1993
    QEMU_OPTION_append,
1994
    QEMU_OPTION_initrd,
1995

    
1996
    QEMU_OPTION_S,
1997
    QEMU_OPTION_s,
1998
    QEMU_OPTION_p,
1999
    QEMU_OPTION_d,
2000
    QEMU_OPTION_hdachs,
2001
    QEMU_OPTION_L,
2002
    QEMU_OPTION_no_code_copy,
2003
    QEMU_OPTION_pci,
2004
};
2005

    
2006
typedef struct QEMUOption {
2007
    const char *name;
2008
    int flags;
2009
    int index;
2010
} QEMUOption;
2011

    
2012
const QEMUOption qemu_options[] = {
2013
    { "h", 0, QEMU_OPTION_h },
2014

    
2015
    { "fda", HAS_ARG, QEMU_OPTION_fda },
2016
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2017
    { "hda", HAS_ARG, QEMU_OPTION_hda },
2018
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2019
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2020
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2021
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2022
    { "boot", HAS_ARG, QEMU_OPTION_boot },
2023
    { "snapshot", 0, QEMU_OPTION_snapshot },
2024
    { "m", HAS_ARG, QEMU_OPTION_m },
2025
    { "nographic", 0, QEMU_OPTION_nographic },
2026
    { "enable-audio", 0, QEMU_OPTION_enable_audio },
2027

    
2028
    { "nics", HAS_ARG, QEMU_OPTION_nics},
2029
    { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2030
    { "n", HAS_ARG, QEMU_OPTION_n },
2031
    { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2032
#ifdef CONFIG_SLIRP
2033
    { "user-net", 0, QEMU_OPTION_user_net },
2034
#endif
2035
    { "dummy-net", 0, QEMU_OPTION_dummy_net },
2036

    
2037
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2038
    { "append", HAS_ARG, QEMU_OPTION_append },
2039
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2040

    
2041
    { "S", 0, QEMU_OPTION_S },
2042
    { "s", 0, QEMU_OPTION_s },
2043
    { "p", HAS_ARG, QEMU_OPTION_p },
2044
    { "d", HAS_ARG, QEMU_OPTION_d },
2045
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2046
    { "L", HAS_ARG, QEMU_OPTION_L },
2047
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2048
    { "pci", 0, QEMU_OPTION_pci },
2049
    { NULL },
2050
};
2051

    
2052
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2053

    
2054
/* this stack is only used during signal handling */
2055
#define SIGNAL_STACK_SIZE 32768
2056

    
2057
static uint8_t *signal_stack;
2058

    
2059
#endif
2060

    
2061
#define NET_IF_TUN   0
2062
#define NET_IF_USER  1
2063
#define NET_IF_DUMMY 2
2064

    
2065
int main(int argc, char **argv)
2066
{
2067
#ifdef CONFIG_GDBSTUB
2068
    int use_gdbstub, gdbstub_port;
2069
#endif
2070
    int i, has_cdrom;
2071
    int snapshot, linux_boot;
2072
    CPUState *env;
2073
    const char *initrd_filename;
2074
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2075
    const char *kernel_filename, *kernel_cmdline;
2076
    DisplayState *ds = &display_state;
2077
    int cyls, heads, secs;
2078
    int start_emulation = 1;
2079
    uint8_t macaddr[6];
2080
    int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2081
    int optind;
2082
    const char *r, *optarg;
2083

    
2084
#if !defined(CONFIG_SOFTMMU)
2085
    /* we never want that malloc() uses mmap() */
2086
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2087
#endif
2088
    initrd_filename = NULL;
2089
    for(i = 0; i < MAX_FD; i++)
2090
        fd_filename[i] = NULL;
2091
    for(i = 0; i < MAX_DISKS; i++)
2092
        hd_filename[i] = NULL;
2093
    ram_size = 32 * 1024 * 1024;
2094
    vga_ram_size = VGA_RAM_SIZE;
2095
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2096
#ifdef CONFIG_GDBSTUB
2097
    use_gdbstub = 0;
2098
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
2099
#endif
2100
    snapshot = 0;
2101
    nographic = 0;
2102
    kernel_filename = NULL;
2103
    kernel_cmdline = "";
2104
    has_cdrom = 1;
2105
    cyls = heads = secs = 0;
2106

    
2107
    nb_tun_fds = 0;
2108
    net_if_type = -1;
2109
    nb_nics = 1;
2110
    /* default mac address of the first network interface */
2111
    macaddr[0] = 0x52;
2112
    macaddr[1] = 0x54;
2113
    macaddr[2] = 0x00;
2114
    macaddr[3] = 0x12;
2115
    macaddr[4] = 0x34;
2116
    macaddr[5] = 0x56;
2117

    
2118
    optind = 1;
2119
    for(;;) {
2120
        if (optind >= argc)
2121
            break;
2122
        r = argv[optind];
2123
        if (r[0] != '-') {
2124
            hd_filename[0] = argv[optind++];
2125
        } else {
2126
            const QEMUOption *popt;
2127

    
2128
            optind++;
2129
            popt = qemu_options;
2130
            for(;;) {
2131
                if (!popt->name) {
2132
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
2133
                            argv[0], r);
2134
                    exit(1);
2135
                }
2136
                if (!strcmp(popt->name, r + 1))
2137
                    break;
2138
                popt++;
2139
            }
2140
            if (popt->flags & HAS_ARG) {
2141
                if (optind >= argc) {
2142
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
2143
                            argv[0], r);
2144
                    exit(1);
2145
                }
2146
                optarg = argv[optind++];
2147
            } else {
2148
                optarg = NULL;
2149
            }
2150

    
2151
            switch(popt->index) {
2152
            case QEMU_OPTION_initrd:
2153
                initrd_filename = optarg;
2154
                break;
2155
            case QEMU_OPTION_hda:
2156
                hd_filename[0] = optarg;
2157
                break;
2158
            case QEMU_OPTION_hdb:
2159
                hd_filename[1] = optarg;
2160
                break;
2161
            case QEMU_OPTION_snapshot:
2162
                snapshot = 1;
2163
                break;
2164
            case QEMU_OPTION_hdachs:
2165
                {
2166
                    const char *p;
2167
                    p = optarg;
2168
                    cyls = strtol(p, (char **)&p, 0);
2169
                    if (*p != ',')
2170
                        goto chs_fail;
2171
                    p++;
2172
                    heads = strtol(p, (char **)&p, 0);
2173
                    if (*p != ',')
2174
                        goto chs_fail;
2175
                    p++;
2176
                    secs = strtol(p, (char **)&p, 0);
2177
                    if (*p != '\0') {
2178
                    chs_fail:
2179
                        cyls = 0;
2180
                    }
2181
                }
2182
                break;
2183
            case QEMU_OPTION_nographic:
2184
                nographic = 1;
2185
                break;
2186
            case QEMU_OPTION_kernel:
2187
                kernel_filename = optarg;
2188
                break;
2189
            case QEMU_OPTION_append:
2190
                kernel_cmdline = optarg;
2191
                break;
2192
            case QEMU_OPTION_tun_fd:
2193
                {
2194
                    const char *p;
2195
                    int fd;
2196
                    net_if_type = NET_IF_TUN;
2197
                    if (nb_tun_fds < MAX_NICS) {
2198
                        fd = strtol(optarg, (char **)&p, 0);
2199
                        if (*p != '\0') {
2200
                            fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2201
                            exit(1);
2202
                        }
2203
                        tun_fds[nb_tun_fds++] = fd;
2204
                    }
2205
                }
2206
                break;
2207
            case QEMU_OPTION_hdc:
2208
                hd_filename[2] = optarg;
2209
                has_cdrom = 0;
2210
                break;
2211
            case QEMU_OPTION_hdd:
2212
                hd_filename[3] = optarg;
2213
                break;
2214
            case QEMU_OPTION_cdrom:
2215
                hd_filename[2] = optarg;
2216
                has_cdrom = 1;
2217
                break;
2218
            case QEMU_OPTION_boot:
2219
                boot_device = optarg[0];
2220
                if (boot_device != 'a' && boot_device != 'b' &&
2221
                    boot_device != 'c' && boot_device != 'd') {
2222
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2223
                    exit(1);
2224
                }
2225
                break;
2226
            case QEMU_OPTION_fda:
2227
                fd_filename[0] = optarg;
2228
                break;
2229
            case QEMU_OPTION_fdb:
2230
                fd_filename[1] = optarg;
2231
                break;
2232
            case QEMU_OPTION_no_code_copy:
2233
                code_copy_enabled = 0;
2234
                break;
2235
            case QEMU_OPTION_nics:
2236
                nb_nics = atoi(optarg);
2237
                if (nb_nics < 0 || nb_nics > MAX_NICS) {
2238
                    fprintf(stderr, "qemu: invalid number of network interfaces\n");
2239
                    exit(1);
2240
                }
2241
                break;
2242
            case QEMU_OPTION_macaddr:
2243
                {
2244
                    const char *p;
2245
                    int i;
2246
                    p = optarg;
2247
                    for(i = 0; i < 6; i++) {
2248
                        macaddr[i] = strtol(p, (char **)&p, 16);
2249
                        if (i == 5) {
2250
                            if (*p != '\0') 
2251
                                goto macaddr_error;
2252
                        } else {
2253
                            if (*p != ':') {
2254
                            macaddr_error:
2255
                                fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2256
                                exit(1);
2257
                            }
2258
                            p++;
2259
                        }
2260
                    }
2261
                }
2262
                break;
2263
            case QEMU_OPTION_user_net:
2264
                net_if_type = NET_IF_USER;
2265
                break;
2266
            case QEMU_OPTION_dummy_net:
2267
                net_if_type = NET_IF_DUMMY;
2268
                break;
2269
            case QEMU_OPTION_enable_audio:
2270
                audio_enabled = 1;
2271
                break;
2272
            case QEMU_OPTION_h:
2273
                help();
2274
                break;
2275
            case QEMU_OPTION_m:
2276
                ram_size = atoi(optarg) * 1024 * 1024;
2277
                if (ram_size <= 0)
2278
                    help();
2279
                if (ram_size > PHYS_RAM_MAX_SIZE) {
2280
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2281
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
2282
                    exit(1);
2283
                }
2284
                break;
2285
            case QEMU_OPTION_d:
2286
                {
2287
                    int mask;
2288
                    CPULogItem *item;
2289
                    
2290
                    mask = cpu_str_to_log_mask(optarg);
2291
                    if (!mask) {
2292
                        printf("Log items (comma separated):\n");
2293
                    for(item = cpu_log_items; item->mask != 0; item++) {
2294
                        printf("%-10s %s\n", item->name, item->help);
2295
                    }
2296
                    exit(1);
2297
                    }
2298
                    cpu_set_log(mask);
2299
                }
2300
                break;
2301
            case QEMU_OPTION_n:
2302
                pstrcpy(network_script, sizeof(network_script), optarg);
2303
                break;
2304
#ifdef CONFIG_GDBSTUB
2305
            case QEMU_OPTION_s:
2306
                use_gdbstub = 1;
2307
                break;
2308
            case QEMU_OPTION_p:
2309
                gdbstub_port = atoi(optarg);
2310
                break;
2311
#endif
2312
            case QEMU_OPTION_L:
2313
                bios_dir = optarg;
2314
                break;
2315
            case QEMU_OPTION_S:
2316
                start_emulation = 0;
2317
                break;
2318
            case QEMU_OPTION_pci:
2319
                pci_enabled = 1;
2320
                break;
2321
            }
2322
        }
2323
    }
2324

    
2325
    linux_boot = (kernel_filename != NULL);
2326
        
2327
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2328
        fd_filename[0] == '\0')
2329
        help();
2330
    
2331
    /* boot to cd by default if no hard disk */
2332
    if (hd_filename[0] == '\0' && boot_device == 'c') {
2333
        if (fd_filename[0] != '\0')
2334
            boot_device = 'a';
2335
        else
2336
            boot_device = 'd';
2337
    }
2338

    
2339
#if !defined(CONFIG_SOFTMMU)
2340
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2341
    {
2342
        static uint8_t stdout_buf[4096];
2343
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2344
    }
2345
#else
2346
    setvbuf(stdout, NULL, _IOLBF, 0);
2347
#endif
2348

    
2349
    /* init host network redirectors */
2350
    if (net_if_type == -1) {
2351
        net_if_type = NET_IF_TUN;
2352
#if defined(CONFIG_SLIRP)
2353
        if (access(network_script, R_OK) < 0) {
2354
            net_if_type = NET_IF_USER;
2355
        }
2356
#endif
2357
    }
2358

    
2359
    for(i = 0; i < nb_nics; i++) {
2360
        NetDriverState *nd = &nd_table[i];
2361
        nd->index = i;
2362
        /* init virtual mac address */
2363
        nd->macaddr[0] = macaddr[0];
2364
        nd->macaddr[1] = macaddr[1];
2365
        nd->macaddr[2] = macaddr[2];
2366
        nd->macaddr[3] = macaddr[3];
2367
        nd->macaddr[4] = macaddr[4];
2368
        nd->macaddr[5] = macaddr[5] + i;
2369
        switch(net_if_type) {
2370
#if defined(CONFIG_SLIRP)
2371
        case NET_IF_USER:
2372
            net_slirp_init(nd);
2373
            break;
2374
#endif
2375
#if !defined(_WIN32)
2376
        case NET_IF_TUN:
2377
            if (i < nb_tun_fds) {
2378
                net_fd_init(nd, tun_fds[i]);
2379
            } else {
2380
                if (net_tun_init(nd) < 0)
2381
                    net_dummy_init(nd);
2382
            }
2383
            break;
2384
#endif
2385
        case NET_IF_DUMMY:
2386
        default:
2387
            net_dummy_init(nd);
2388
            break;
2389
        }
2390
    }
2391

    
2392
    /* init the memory */
2393
    phys_ram_size = ram_size + vga_ram_size;
2394

    
2395
#ifdef CONFIG_SOFTMMU
2396
#ifdef _BSD
2397
    /* mallocs are always aligned on BSD. */
2398
    phys_ram_base = malloc(phys_ram_size);
2399
#else
2400
    phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2401
#endif
2402
    if (!phys_ram_base) {
2403
        fprintf(stderr, "Could not allocate physical memory\n");
2404
        exit(1);
2405
    }
2406
#else
2407
    /* as we must map the same page at several addresses, we must use
2408
       a fd */
2409
    {
2410
        const char *tmpdir;
2411

    
2412
        tmpdir = getenv("QEMU_TMPDIR");
2413
        if (!tmpdir)
2414
            tmpdir = "/tmp";
2415
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2416
        if (mkstemp(phys_ram_file) < 0) {
2417
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2418
                    phys_ram_file);
2419
            exit(1);
2420
        }
2421
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2422
        if (phys_ram_fd < 0) {
2423
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2424
                    phys_ram_file);
2425
            exit(1);
2426
        }
2427
        ftruncate(phys_ram_fd, phys_ram_size);
2428
        unlink(phys_ram_file);
2429
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2430
                             phys_ram_size, 
2431
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2432
                             phys_ram_fd, 0);
2433
        if (phys_ram_base == MAP_FAILED) {
2434
            fprintf(stderr, "Could not map physical memory\n");
2435
            exit(1);
2436
        }
2437
    }
2438
#endif
2439

    
2440
    /* we always create the cdrom drive, even if no disk is there */
2441
    if (has_cdrom) {
2442
        bs_table[2] = bdrv_new("cdrom");
2443
        bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2444
    }
2445

    
2446
    /* open the virtual block devices */
2447
    for(i = 0; i < MAX_DISKS; i++) {
2448
        if (hd_filename[i]) {
2449
            if (!bs_table[i]) {
2450
                char buf[64];
2451
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2452
                bs_table[i] = bdrv_new(buf);
2453
            }
2454
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2455
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2456
                        hd_filename[i]);
2457
                exit(1);
2458
            }
2459
            if (i == 0 && cyls != 0) 
2460
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2461
        }
2462
    }
2463

    
2464
    /* we always create at least one floppy disk */
2465
    fd_table[0] = bdrv_new("fda");
2466
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2467

    
2468
    for(i = 0; i < MAX_FD; i++) {
2469
        if (fd_filename[i]) {
2470
            if (!fd_table[i]) {
2471
                char buf[64];
2472
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2473
                fd_table[i] = bdrv_new(buf);
2474
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2475
            }
2476
            if (fd_filename[i] != '\0') {
2477
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2478
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2479
                            fd_filename[i]);
2480
                    exit(1);
2481
                }
2482
            }
2483
        }
2484
    }
2485

    
2486
    /* init CPU state */
2487
    env = cpu_init();
2488
    global_env = env;
2489
    cpu_single_env = env;
2490

    
2491
    register_savevm("timer", 0, 1, timer_save, timer_load, env);
2492
    register_savevm("cpu", 0, 1, cpu_save, cpu_load, env);
2493
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2494

    
2495
    init_ioports();
2496
    cpu_calibrate_ticks();
2497

    
2498
    /* terminal init */
2499
    if (nographic) {
2500
        dumb_display_init(ds);
2501
    } else {
2502
#ifdef CONFIG_SDL
2503
        sdl_display_init(ds);
2504
#else
2505
        dumb_display_init(ds);
2506
#endif
2507
    }
2508

    
2509
    /* setup cpu signal handlers for MMU / self modifying code handling */
2510
#if !defined(CONFIG_SOFTMMU)
2511
    
2512
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2513
    {
2514
        stack_t stk;
2515
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2516
        stk.ss_sp = signal_stack;
2517
        stk.ss_size = SIGNAL_STACK_SIZE;
2518
        stk.ss_flags = 0;
2519

    
2520
        if (sigaltstack(&stk, NULL) < 0) {
2521
            perror("sigaltstack");
2522
            exit(1);
2523
        }
2524
    }
2525
#endif
2526
    {
2527
        struct sigaction act;
2528
        
2529
        sigfillset(&act.sa_mask);
2530
        act.sa_flags = SA_SIGINFO;
2531
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2532
        act.sa_flags |= SA_ONSTACK;
2533
#endif
2534
        act.sa_sigaction = host_segv_handler;
2535
        sigaction(SIGSEGV, &act, NULL);
2536
        sigaction(SIGBUS, &act, NULL);
2537
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2538
        sigaction(SIGFPE, &act, NULL);
2539
#endif
2540
    }
2541
#endif
2542

    
2543
#ifndef _WIN32
2544
    {
2545
        struct sigaction act;
2546
        sigfillset(&act.sa_mask);
2547
        act.sa_flags = 0;
2548
        act.sa_handler = SIG_IGN;
2549
        sigaction(SIGPIPE, &act, NULL);
2550
    }
2551
#endif
2552
    init_timers();
2553

    
2554
#if defined(TARGET_I386)
2555
    pc_init(ram_size, vga_ram_size, boot_device,
2556
            ds, fd_filename, snapshot,
2557
            kernel_filename, kernel_cmdline, initrd_filename);
2558
#elif defined(TARGET_PPC)
2559
    ppc_init(ram_size, vga_ram_size, boot_device,
2560
             ds, fd_filename, snapshot,
2561
             kernel_filename, kernel_cmdline, initrd_filename);
2562
#endif
2563

    
2564
    /* launched after the device init so that it can display or not a
2565
       banner */
2566
    monitor_init();
2567

    
2568
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2569
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2570

    
2571
#ifdef CONFIG_GDBSTUB
2572
    if (use_gdbstub) {
2573
        if (gdbserver_start(gdbstub_port) < 0) {
2574
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
2575
                    gdbstub_port);
2576
            exit(1);
2577
        } else {
2578
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
2579
        }
2580
    } else 
2581
#endif
2582
    if (start_emulation)
2583
    {
2584
        vm_start();
2585
    }
2586
    term_init();
2587
    main_loop();
2588
    quit_timers();
2589
    return 0;
2590
}