Statistics
| Branch: | Revision:

root / vl.c @ fd872598

History | View | Annotate | Download (61.3 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 <malloc.h>
32
#include <errno.h>
33
#include <sys/time.h>
34

    
35
#ifndef _WIN32
36
#include <sys/times.h>
37
#include <sys/wait.h>
38
#include <pty.h>
39
#include <termios.h>
40
#include <sys/poll.h>
41
#include <sys/mman.h>
42
#include <sys/ioctl.h>
43
#include <sys/socket.h>
44
#include <linux/if.h>
45
#include <linux/if_tun.h>
46
#include <linux/rtc.h>
47
#endif
48

    
49
#if defined(CONFIG_SLIRP)
50
#include "libslirp.h"
51
#endif
52

    
53
#ifdef _WIN32
54
#include <sys/timeb.h>
55
#include <windows.h>
56
#define getopt_long_only getopt_long
57
#define memalign(align, size) malloc(size)
58
#endif
59

    
60
#ifdef CONFIG_SDL
61
/* SDL use the pthreads and they modify sigaction. We don't
62
   want that. */
63
#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)
64
extern void __libc_sigaction();
65
#define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
66
#else
67
extern void __sigaction();
68
#define sigaction(sig, act, oact) __sigaction(sig, act, oact)
69
#endif
70
#endif /* CONFIG_SDL */
71

    
72
#include "disas.h"
73

    
74
#include "exec-all.h"
75

    
76
//#define DO_TB_FLUSH
77

    
78
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
79

    
80
//#define DEBUG_UNUSED_IOPORT
81
//#define DEBUG_IOPORT
82

    
83
#if !defined(CONFIG_SOFTMMU)
84
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
85
#else
86
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
87
#endif
88

    
89
/* in ms */
90
#define GUI_REFRESH_INTERVAL 30
91

    
92
/* XXX: use a two level table to limit memory usage */
93
#define MAX_IOPORTS 65536
94

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

    
118
/***********************************************************/
119
/* x86 ISA bus support */
120

    
121
target_phys_addr_t isa_mem_base = 0;
122

    
123
uint32_t default_ioport_readb(void *opaque, uint32_t address)
124
{
125
#ifdef DEBUG_UNUSED_IOPORT
126
    fprintf(stderr, "inb: port=0x%04x\n", address);
127
#endif
128
    return 0xff;
129
}
130

    
131
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
132
{
133
#ifdef DEBUG_UNUSED_IOPORT
134
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
135
#endif
136
}
137

    
138
/* default is to make two byte accesses */
139
uint32_t default_ioport_readw(void *opaque, uint32_t address)
140
{
141
    uint32_t data;
142
    data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](opaque, address);
143
    data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](opaque, address + 1) << 8;
144
    return data;
145
}
146

    
147
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
148
{
149
    ioport_write_table[0][address & (MAX_IOPORTS - 1)](opaque, address, data & 0xff);
150
    ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](opaque, address + 1, (data >> 8) & 0xff);
151
}
152

    
153
uint32_t default_ioport_readl(void *opaque, uint32_t address)
154
{
155
#ifdef DEBUG_UNUSED_IOPORT
156
    fprintf(stderr, "inl: port=0x%04x\n", address);
157
#endif
158
    return 0xffffffff;
159
}
160

    
161
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
162
{
163
#ifdef DEBUG_UNUSED_IOPORT
164
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
165
#endif
166
}
167

    
168
void init_ioports(void)
169
{
170
    int i;
171

    
172
    for(i = 0; i < MAX_IOPORTS; i++) {
173
        ioport_read_table[0][i] = default_ioport_readb;
174
        ioport_write_table[0][i] = default_ioport_writeb;
175
        ioport_read_table[1][i] = default_ioport_readw;
176
        ioport_write_table[1][i] = default_ioport_writew;
177
        ioport_read_table[2][i] = default_ioport_readl;
178
        ioport_write_table[2][i] = default_ioport_writel;
179
    }
180
}
181

    
182
/* size is the word size in byte */
183
int register_ioport_read(int start, int length, int size, 
184
                         IOPortReadFunc *func, void *opaque)
185
{
186
    int i, bsize;
187

    
188
    if (size == 1) {
189
        bsize = 0;
190
    } else if (size == 2) {
191
        bsize = 1;
192
    } else if (size == 4) {
193
        bsize = 2;
194
    } else {
195
        hw_error("register_ioport_read: invalid size");
196
        return -1;
197
    }
198
    for(i = start; i < start + length; i += size) {
199
        ioport_read_table[bsize][i] = func;
200
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
201
            hw_error("register_ioport_read: invalid opaque");
202
        ioport_opaque[i] = opaque;
203
    }
204
    return 0;
205
}
206

    
207
/* size is the word size in byte */
208
int register_ioport_write(int start, int length, int size, 
209
                          IOPortWriteFunc *func, void *opaque)
210
{
211
    int i, bsize;
212

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

    
232
void pstrcpy(char *buf, int buf_size, const char *str)
233
{
234
    int c;
235
    char *q = buf;
236

    
237
    if (buf_size <= 0)
238
        return;
239

    
240
    for(;;) {
241
        c = *str++;
242
        if (c == 0 || q >= buf + buf_size - 1)
243
            break;
244
        *q++ = c;
245
    }
246
    *q = '\0';
247
}
248

    
249
/* strcat and truncate. */
250
char *pstrcat(char *buf, int buf_size, const char *s)
251
{
252
    int len;
253
    len = strlen(buf);
254
    if (len < buf_size) 
255
        pstrcpy(buf + len, buf_size - len, s);
256
    return buf;
257
}
258

    
259
/* return the size or -1 if error */
260
int load_image(const char *filename, uint8_t *addr)
261
{
262
    int fd, size;
263
    fd = open(filename, O_RDONLY | O_BINARY);
264
    if (fd < 0)
265
        return -1;
266
    size = lseek(fd, 0, SEEK_END);
267
    lseek(fd, 0, SEEK_SET);
268
    if (read(fd, addr, size) != size) {
269
        close(fd);
270
        return -1;
271
    }
272
    close(fd);
273
    return size;
274
}
275

    
276
void cpu_outb(CPUState *env, int addr, int val)
277
{
278
    addr &= (MAX_IOPORTS - 1);
279
#ifdef DEBUG_IOPORT
280
    if (loglevel & CPU_LOG_IOPORT)
281
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
282
#endif    
283
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
284
}
285

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

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

    
306
int cpu_inb(CPUState *env, int addr)
307
{
308
    int val;
309
    addr &= (MAX_IOPORTS - 1);
310
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
311
#ifdef DEBUG_IOPORT
312
    if (loglevel & CPU_LOG_IOPORT)
313
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
314
#endif
315
    return val;
316
}
317

    
318
int cpu_inw(CPUState *env, int addr)
319
{
320
    int val;
321
    addr &= (MAX_IOPORTS - 1);
322
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
323
#ifdef DEBUG_IOPORT
324
    if (loglevel & CPU_LOG_IOPORT)
325
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
326
#endif
327
    return val;
328
}
329

    
330
int cpu_inl(CPUState *env, int addr)
331
{
332
    int val;
333
    addr &= (MAX_IOPORTS - 1);
334
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
335
#ifdef DEBUG_IOPORT
336
    if (loglevel & CPU_LOG_IOPORT)
337
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
338
#endif
339
    return val;
340
}
341

    
342
/***********************************************************/
343
void hw_error(const char *fmt, ...)
344
{
345
    va_list ap;
346

    
347
    va_start(ap, fmt);
348
    fprintf(stderr, "qemu: hardware error: ");
349
    vfprintf(stderr, fmt, ap);
350
    fprintf(stderr, "\n");
351
#ifdef TARGET_I386
352
    cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
353
#else
354
    cpu_dump_state(global_env, stderr, 0);
355
#endif
356
    va_end(ap);
357
    abort();
358
}
359

    
360
/***********************************************************/
361
/* timers */
362

    
363
#if defined(__powerpc__)
364

    
365
static inline uint32_t get_tbl(void) 
366
{
367
    uint32_t tbl;
368
    asm volatile("mftb %0" : "=r" (tbl));
369
    return tbl;
370
}
371

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

    
379
int64_t cpu_get_real_ticks(void)
380
{
381
    uint32_t l, h, h1;
382
    /* NOTE: we test if wrapping has occurred */
383
    do {
384
        h = get_tbu();
385
        l = get_tbl();
386
        h1 = get_tbu();
387
    } while (h != h1);
388
    return ((int64_t)h << 32) | l;
389
}
390

    
391
#elif defined(__i386__)
392

    
393
int64_t cpu_get_real_ticks(void)
394
{
395
    int64_t val;
396
    asm volatile ("rdtsc" : "=A" (val));
397
    return val;
398
}
399

    
400
#elif defined(__x86_64__)
401

    
402
int64_t cpu_get_real_ticks(void)
403
{
404
    uint32_t low,high;
405
    int64_t val;
406
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
407
    val = high;
408
    val <<= 32;
409
    val |= low;
410
    return val;
411
}
412

    
413
#else
414
#error unsupported CPU
415
#endif
416

    
417
static int64_t cpu_ticks_offset;
418
static int cpu_ticks_enabled;
419

    
420
static inline int64_t cpu_get_ticks(void)
421
{
422
    if (!cpu_ticks_enabled) {
423
        return cpu_ticks_offset;
424
    } else {
425
        return cpu_get_real_ticks() + cpu_ticks_offset;
426
    }
427
}
428

    
429
/* enable cpu_get_ticks() */
430
void cpu_enable_ticks(void)
431
{
432
    if (!cpu_ticks_enabled) {
433
        cpu_ticks_offset -= cpu_get_real_ticks();
434
        cpu_ticks_enabled = 1;
435
    }
436
}
437

    
438
/* disable cpu_get_ticks() : the clock is stopped. You must not call
439
   cpu_get_ticks() after that.  */
440
void cpu_disable_ticks(void)
441
{
442
    if (cpu_ticks_enabled) {
443
        cpu_ticks_offset = cpu_get_ticks();
444
        cpu_ticks_enabled = 0;
445
    }
446
}
447

    
448
static int64_t get_clock(void)
449
{
450
#ifdef _WIN32
451
    struct _timeb tb;
452
    _ftime(&tb);
453
    return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
454
#else
455
    struct timeval tv;
456
    gettimeofday(&tv, NULL);
457
    return tv.tv_sec * 1000000LL + tv.tv_usec;
458
#endif
459
}
460

    
461
void cpu_calibrate_ticks(void)
462
{
463
    int64_t usec, ticks;
464

    
465
    usec = get_clock();
466
    ticks = cpu_get_real_ticks();
467
#ifdef _WIN32
468
    Sleep(50);
469
#else
470
    usleep(50 * 1000);
471
#endif
472
    usec = get_clock() - usec;
473
    ticks = cpu_get_real_ticks() - ticks;
474
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
475
}
476

    
477
/* compute with 96 bit intermediate result: (a*b)/c */
478
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
479
{
480
    union {
481
        uint64_t ll;
482
        struct {
483
#ifdef WORDS_BIGENDIAN
484
            uint32_t high, low;
485
#else
486
            uint32_t low, high;
487
#endif            
488
        } l;
489
    } u, res;
490
    uint64_t rl, rh;
491

    
492
    u.ll = a;
493
    rl = (uint64_t)u.l.low * (uint64_t)b;
494
    rh = (uint64_t)u.l.high * (uint64_t)b;
495
    rh += (rl >> 32);
496
    res.l.high = rh / c;
497
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
498
    return res.ll;
499
}
500

    
501
#define QEMU_TIMER_REALTIME 0
502
#define QEMU_TIMER_VIRTUAL  1
503

    
504
struct QEMUClock {
505
    int type;
506
    /* XXX: add frequency */
507
};
508

    
509
struct QEMUTimer {
510
    QEMUClock *clock;
511
    int64_t expire_time;
512
    QEMUTimerCB *cb;
513
    void *opaque;
514
    struct QEMUTimer *next;
515
};
516

    
517
QEMUClock *rt_clock;
518
QEMUClock *vm_clock;
519

    
520
static QEMUTimer *active_timers[2];
521
#ifdef _WIN32
522
static MMRESULT timerID;
523
#else
524
/* frequency of the times() clock tick */
525
static int timer_freq;
526
#endif
527

    
528
QEMUClock *qemu_new_clock(int type)
529
{
530
    QEMUClock *clock;
531
    clock = qemu_mallocz(sizeof(QEMUClock));
532
    if (!clock)
533
        return NULL;
534
    clock->type = type;
535
    return clock;
536
}
537

    
538
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
539
{
540
    QEMUTimer *ts;
541

    
542
    ts = qemu_mallocz(sizeof(QEMUTimer));
543
    ts->clock = clock;
544
    ts->cb = cb;
545
    ts->opaque = opaque;
546
    return ts;
547
}
548

    
549
void qemu_free_timer(QEMUTimer *ts)
550
{
551
    qemu_free(ts);
552
}
553

    
554
/* stop a timer, but do not dealloc it */
555
void qemu_del_timer(QEMUTimer *ts)
556
{
557
    QEMUTimer **pt, *t;
558

    
559
    /* NOTE: this code must be signal safe because
560
       qemu_timer_expired() can be called from a signal. */
561
    pt = &active_timers[ts->clock->type];
562
    for(;;) {
563
        t = *pt;
564
        if (!t)
565
            break;
566
        if (t == ts) {
567
            *pt = t->next;
568
            break;
569
        }
570
        pt = &t->next;
571
    }
572
}
573

    
574
/* modify the current timer so that it will be fired when current_time
575
   >= expire_time. The corresponding callback will be called. */
576
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
577
{
578
    QEMUTimer **pt, *t;
579

    
580
    qemu_del_timer(ts);
581

    
582
    /* add the timer in the sorted list */
583
    /* NOTE: this code must be signal safe because
584
       qemu_timer_expired() can be called from a signal. */
585
    pt = &active_timers[ts->clock->type];
586
    for(;;) {
587
        t = *pt;
588
        if (!t)
589
            break;
590
        if (t->expire_time > expire_time) 
591
            break;
592
        pt = &t->next;
593
    }
594
    ts->expire_time = expire_time;
595
    ts->next = *pt;
596
    *pt = ts;
597
}
598

    
599
int qemu_timer_pending(QEMUTimer *ts)
600
{
601
    QEMUTimer *t;
602
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
603
        if (t == ts)
604
            return 1;
605
    }
606
    return 0;
607
}
608

    
609
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
610
{
611
    if (!timer_head)
612
        return 0;
613
    return (timer_head->expire_time <= current_time);
614
}
615

    
616
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
617
{
618
    QEMUTimer *ts;
619
    
620
    for(;;) {
621
        ts = *ptimer_head;
622
        if (ts->expire_time > current_time)
623
            break;
624
        /* remove timer from the list before calling the callback */
625
        *ptimer_head = ts->next;
626
        ts->next = NULL;
627
        
628
        /* run the callback (the timer list can be modified) */
629
        ts->cb(ts->opaque);
630
    }
631
}
632

    
633
int64_t qemu_get_clock(QEMUClock *clock)
634
{
635
    switch(clock->type) {
636
    case QEMU_TIMER_REALTIME:
637
#ifdef _WIN32
638
        return GetTickCount();
639
#else
640
        /* XXX: portability among Linux hosts */
641
        if (timer_freq == 100) {
642
            return times(NULL) * 10;
643
        } else {
644
            return ((int64_t)times(NULL) * 1000) / timer_freq;
645
        }
646
#endif
647
    default:
648
    case QEMU_TIMER_VIRTUAL:
649
        return cpu_get_ticks();
650
    }
651
}
652

    
653
/* save a timer */
654
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
655
{
656
    uint64_t expire_time;
657

    
658
    if (qemu_timer_pending(ts)) {
659
        expire_time = ts->expire_time;
660
    } else {
661
        expire_time = -1;
662
    }
663
    qemu_put_be64(f, expire_time);
664
}
665

    
666
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
667
{
668
    uint64_t expire_time;
669

    
670
    expire_time = qemu_get_be64(f);
671
    if (expire_time != -1) {
672
        qemu_mod_timer(ts, expire_time);
673
    } else {
674
        qemu_del_timer(ts);
675
    }
676
}
677

    
678
static void timer_save(QEMUFile *f, void *opaque)
679
{
680
    if (cpu_ticks_enabled) {
681
        hw_error("cannot save state if virtual timers are running");
682
    }
683
    qemu_put_be64s(f, &cpu_ticks_offset);
684
    qemu_put_be64s(f, &ticks_per_sec);
685
}
686

    
687
static int timer_load(QEMUFile *f, void *opaque, int version_id)
688
{
689
    if (version_id != 1)
690
        return -EINVAL;
691
    if (cpu_ticks_enabled) {
692
        return -EINVAL;
693
    }
694
    qemu_get_be64s(f, &cpu_ticks_offset);
695
    qemu_get_be64s(f, &ticks_per_sec);
696
    return 0;
697
}
698

    
699
#ifdef _WIN32
700
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
701
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
702
#else
703
static void host_alarm_handler(int host_signum)
704
#endif
705
{
706
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
707
                           qemu_get_clock(vm_clock)) ||
708
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
709
                           qemu_get_clock(rt_clock))) {
710
        /* stop the cpu because a timer occured */
711
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
712
    }
713
}
714

    
715
#ifndef _WIN32
716

    
717
#define RTC_FREQ 1024
718

    
719
static int rtc_fd;
720
    
721
static int start_rtc_timer(void)
722
{
723
    rtc_fd = open("/dev/rtc", O_RDONLY);
724
    if (rtc_fd < 0)
725
        return -1;
726
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
727
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
728
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
729
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
730
        goto fail;
731
    }
732
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
733
    fail:
734
        close(rtc_fd);
735
        return -1;
736
    }
737
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
738
    return 0;
739
}
740

    
741
#endif
742

    
743
static void init_timers(void)
744
{
745
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
746
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
747

    
748
#ifdef _WIN32
749
    {
750
        int count=0;
751
        timerID = timeSetEvent(10,    // interval (ms)
752
                               0,     // resolution
753
                               host_alarm_handler, // function
754
                               (DWORD)&count,  // user parameter
755
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
756
         if( !timerID ) {
757
            perror("failed timer alarm");
758
            exit(1);
759
         }
760
    }
761
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
762
#else
763
    {
764
        struct sigaction act;
765
        struct itimerval itv;
766
        
767
        /* get times() syscall frequency */
768
        timer_freq = sysconf(_SC_CLK_TCK);
769
        
770
        /* timer signal */
771
        sigfillset(&act.sa_mask);
772
        act.sa_flags = 0;
773
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
774
        act.sa_flags |= SA_ONSTACK;
775
#endif
776
        act.sa_handler = host_alarm_handler;
777
        sigaction(SIGALRM, &act, NULL);
778

    
779
        itv.it_interval.tv_sec = 0;
780
        itv.it_interval.tv_usec = 1000;
781
        itv.it_value.tv_sec = 0;
782
        itv.it_value.tv_usec = 10 * 1000;
783
        setitimer(ITIMER_REAL, &itv, NULL);
784
        /* we probe the tick duration of the kernel to inform the user if
785
           the emulated kernel requested a too high timer frequency */
786
        getitimer(ITIMER_REAL, &itv);
787

    
788
        if (itv.it_interval.tv_usec > 1000) {
789
            /* try to use /dev/rtc to have a faster timer */
790
            if (start_rtc_timer() < 0)
791
                goto use_itimer;
792
            /* disable itimer */
793
            itv.it_interval.tv_sec = 0;
794
            itv.it_interval.tv_usec = 0;
795
            itv.it_value.tv_sec = 0;
796
            itv.it_value.tv_usec = 0;
797
            setitimer(ITIMER_REAL, &itv, NULL);
798

    
799
            /* use the RTC */
800
            sigaction(SIGIO, &act, NULL);
801
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
802
            fcntl(rtc_fd, F_SETOWN, getpid());
803
        } else {
804
        use_itimer:
805
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
806
                                   PIT_FREQ) / 1000000;
807
        }
808
    }
809
#endif
810
}
811

    
812
void quit_timers(void)
813
{
814
#ifdef _WIN32
815
    timeKillEvent(timerID);
816
#endif
817
}
818

    
819
/***********************************************************/
820
/* serial device */
821

    
822
#ifdef _WIN32
823

    
824
int serial_open_device(void)
825
{
826
    return -1;
827
}
828

    
829
#else
830

    
831
int serial_open_device(void)
832
{
833
    char slave_name[1024];
834
    int master_fd, slave_fd;
835

    
836
    if (serial_console == NULL && nographic) {
837
        /* use console for serial port */
838
        return 0;
839
    } else {
840
        if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
841
            fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
842
            return -1;
843
        }
844
        fprintf(stderr, "Serial port redirected to %s\n", slave_name);
845
        return master_fd;
846
    }
847
}
848

    
849
#endif
850

    
851
/***********************************************************/
852
/* Linux network device redirectors */
853

    
854
void hex_dump(FILE *f, const uint8_t *buf, int size)
855
{
856
    int len, i, j, c;
857

    
858
    for(i=0;i<size;i+=16) {
859
        len = size - i;
860
        if (len > 16)
861
            len = 16;
862
        fprintf(f, "%08x ", i);
863
        for(j=0;j<16;j++) {
864
            if (j < len)
865
                fprintf(f, " %02x", buf[i+j]);
866
            else
867
                fprintf(f, "   ");
868
        }
869
        fprintf(f, " ");
870
        for(j=0;j<len;j++) {
871
            c = buf[i+j];
872
            if (c < ' ' || c > '~')
873
                c = '.';
874
            fprintf(f, "%c", c);
875
        }
876
        fprintf(f, "\n");
877
    }
878
}
879

    
880
void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
881
{
882
    nd->send_packet(nd, buf, size);
883
}
884

    
885
void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
886
                          IOReadHandler *fd_read, void *opaque)
887
{
888
    nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
889
}
890

    
891
/* dummy network adapter */
892

    
893
static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
894
{
895
}
896

    
897
static void dummy_add_read_packet(NetDriverState *nd, 
898
                                  IOCanRWHandler *fd_can_read, 
899
                                  IOReadHandler *fd_read, void *opaque)
900
{
901
}
902

    
903
static int net_dummy_init(NetDriverState *nd)
904
{
905
    nd->send_packet = dummy_send_packet;
906
    nd->add_read_packet = dummy_add_read_packet;
907
    pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
908
    return 0;
909
}
910

    
911
#if defined(CONFIG_SLIRP)
912

    
913
/* slirp network adapter */
914

    
915
static void *slirp_fd_opaque;
916
static IOCanRWHandler *slirp_fd_can_read;
917
static IOReadHandler *slirp_fd_read;
918
static int slirp_inited;
919

    
920
int slirp_can_output(void)
921
{
922
    return slirp_fd_can_read(slirp_fd_opaque);
923
}
924

    
925
void slirp_output(const uint8_t *pkt, int pkt_len)
926
{
927
#if 0
928
    printf("output:\n");
929
    hex_dump(stdout, pkt, pkt_len);
930
#endif
931
    slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
932
}
933

    
934
static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
935
{
936
#if 0
937
    printf("input:\n");
938
    hex_dump(stdout, buf, size);
939
#endif
940
    slirp_input(buf, size);
941
}
942

    
943
static void slirp_add_read_packet(NetDriverState *nd, 
944
                                  IOCanRWHandler *fd_can_read, 
945
                                  IOReadHandler *fd_read, void *opaque)
946
{
947
    slirp_fd_opaque = opaque;
948
    slirp_fd_can_read = fd_can_read;
949
    slirp_fd_read = fd_read;
950
}
951

    
952
static int net_slirp_init(NetDriverState *nd)
953
{
954
    if (!slirp_inited) {
955
        slirp_inited = 1;
956
        slirp_init();
957
    }
958
    nd->send_packet = slirp_send_packet;
959
    nd->add_read_packet = slirp_add_read_packet;
960
    pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
961
    return 0;
962
}
963

    
964
#endif /* CONFIG_SLIRP */
965

    
966
#if !defined(_WIN32)
967

    
968
static int tun_open(char *ifname, int ifname_size)
969
{
970
    struct ifreq ifr;
971
    int fd, ret;
972
    
973
    fd = open("/dev/net/tun", O_RDWR);
974
    if (fd < 0) {
975
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
976
        return -1;
977
    }
978
    memset(&ifr, 0, sizeof(ifr));
979
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
980
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
981
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
982
    if (ret != 0) {
983
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
984
        close(fd);
985
        return -1;
986
    }
987
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
988
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
989
    fcntl(fd, F_SETFL, O_NONBLOCK);
990
    return fd;
991
}
992

    
993
static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
994
{
995
    write(nd->fd, buf, size);
996
}
997

    
998
static void tun_add_read_packet(NetDriverState *nd, 
999
                                IOCanRWHandler *fd_can_read, 
1000
                                IOReadHandler *fd_read, void *opaque)
1001
{
1002
    qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1003
}
1004

    
1005
static int net_tun_init(NetDriverState *nd)
1006
{
1007
    int pid, status;
1008
    char *args[3];
1009
    char **parg;
1010

    
1011
    nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1012
    if (nd->fd < 0)
1013
        return -1;
1014

    
1015
    /* try to launch network init script */
1016
    pid = fork();
1017
    if (pid >= 0) {
1018
        if (pid == 0) {
1019
            parg = args;
1020
            *parg++ = network_script;
1021
            *parg++ = nd->ifname;
1022
            *parg++ = NULL;
1023
            execv(network_script, args);
1024
            exit(1);
1025
        }
1026
        while (waitpid(pid, &status, 0) != pid);
1027
        if (!WIFEXITED(status) ||
1028
            WEXITSTATUS(status) != 0) {
1029
            fprintf(stderr, "%s: could not launch network script\n",
1030
                    network_script);
1031
        }
1032
    }
1033
    nd->send_packet = tun_send_packet;
1034
    nd->add_read_packet = tun_add_read_packet;
1035
    return 0;
1036
}
1037

    
1038
static int net_fd_init(NetDriverState *nd, int fd)
1039
{
1040
    nd->fd = fd;
1041
    nd->send_packet = tun_send_packet;
1042
    nd->add_read_packet = tun_add_read_packet;
1043
    pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1044
    return 0;
1045
}
1046

    
1047
#endif /* !_WIN32 */
1048

    
1049
/***********************************************************/
1050
/* dumb display */
1051

    
1052
#ifdef _WIN32
1053

    
1054
static void term_exit(void)
1055
{
1056
}
1057

    
1058
static void term_init(void)
1059
{
1060
}
1061

    
1062
#else
1063

    
1064
/* init terminal so that we can grab keys */
1065
static struct termios oldtty;
1066

    
1067
static void term_exit(void)
1068
{
1069
    tcsetattr (0, TCSANOW, &oldtty);
1070
}
1071

    
1072
static void term_init(void)
1073
{
1074
    struct termios tty;
1075

    
1076
    tcgetattr (0, &tty);
1077
    oldtty = tty;
1078

    
1079
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1080
                          |INLCR|IGNCR|ICRNL|IXON);
1081
    tty.c_oflag |= OPOST;
1082
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1083
    /* if graphical mode, we allow Ctrl-C handling */
1084
    if (nographic)
1085
        tty.c_lflag &= ~ISIG;
1086
    tty.c_cflag &= ~(CSIZE|PARENB);
1087
    tty.c_cflag |= CS8;
1088
    tty.c_cc[VMIN] = 1;
1089
    tty.c_cc[VTIME] = 0;
1090
    
1091
    tcsetattr (0, TCSANOW, &tty);
1092

    
1093
    atexit(term_exit);
1094

    
1095
    fcntl(0, F_SETFL, O_NONBLOCK);
1096
}
1097

    
1098
#endif
1099

    
1100
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1101
{
1102
}
1103

    
1104
static void dumb_resize(DisplayState *ds, int w, int h)
1105
{
1106
}
1107

    
1108
static void dumb_refresh(DisplayState *ds)
1109
{
1110
    vga_update_display();
1111
}
1112

    
1113
void dumb_display_init(DisplayState *ds)
1114
{
1115
    ds->data = NULL;
1116
    ds->linesize = 0;
1117
    ds->depth = 0;
1118
    ds->dpy_update = dumb_update;
1119
    ds->dpy_resize = dumb_resize;
1120
    ds->dpy_refresh = dumb_refresh;
1121
}
1122

    
1123
#if !defined(CONFIG_SOFTMMU)
1124
/***********************************************************/
1125
/* cpu signal handler */
1126
static void host_segv_handler(int host_signum, siginfo_t *info, 
1127
                              void *puc)
1128
{
1129
    if (cpu_signal_handler(host_signum, info, puc))
1130
        return;
1131
    term_exit();
1132
    abort();
1133
}
1134
#endif
1135

    
1136
/***********************************************************/
1137
/* I/O handling */
1138

    
1139
#define MAX_IO_HANDLERS 64
1140

    
1141
typedef struct IOHandlerRecord {
1142
    int fd;
1143
    IOCanRWHandler *fd_can_read;
1144
    IOReadHandler *fd_read;
1145
    void *opaque;
1146
    /* temporary data */
1147
    struct pollfd *ufd;
1148
    int max_size;
1149
    struct IOHandlerRecord *next;
1150
} IOHandlerRecord;
1151

    
1152
static IOHandlerRecord *first_io_handler;
1153

    
1154
int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1155
                             IOReadHandler *fd_read, void *opaque)
1156
{
1157
    IOHandlerRecord *ioh;
1158

    
1159
    ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1160
    if (!ioh)
1161
        return -1;
1162
    ioh->fd = fd;
1163
    ioh->fd_can_read = fd_can_read;
1164
    ioh->fd_read = fd_read;
1165
    ioh->opaque = opaque;
1166
    ioh->next = first_io_handler;
1167
    first_io_handler = ioh;
1168
    return 0;
1169
}
1170

    
1171
void qemu_del_fd_read_handler(int fd)
1172
{
1173
    IOHandlerRecord **pioh, *ioh;
1174

    
1175
    pioh = &first_io_handler;
1176
    for(;;) {
1177
        ioh = *pioh;
1178
        if (ioh == NULL)
1179
            break;
1180
        if (ioh->fd == fd) {
1181
            *pioh = ioh->next;
1182
            break;
1183
        }
1184
        pioh = &ioh->next;
1185
    }
1186
}
1187

    
1188
/***********************************************************/
1189
/* savevm/loadvm support */
1190

    
1191
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1192
{
1193
    fwrite(buf, 1, size, f);
1194
}
1195

    
1196
void qemu_put_byte(QEMUFile *f, int v)
1197
{
1198
    fputc(v, f);
1199
}
1200

    
1201
void qemu_put_be16(QEMUFile *f, unsigned int v)
1202
{
1203
    qemu_put_byte(f, v >> 8);
1204
    qemu_put_byte(f, v);
1205
}
1206

    
1207
void qemu_put_be32(QEMUFile *f, unsigned int v)
1208
{
1209
    qemu_put_byte(f, v >> 24);
1210
    qemu_put_byte(f, v >> 16);
1211
    qemu_put_byte(f, v >> 8);
1212
    qemu_put_byte(f, v);
1213
}
1214

    
1215
void qemu_put_be64(QEMUFile *f, uint64_t v)
1216
{
1217
    qemu_put_be32(f, v >> 32);
1218
    qemu_put_be32(f, v);
1219
}
1220

    
1221
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1222
{
1223
    return fread(buf, 1, size, f);
1224
}
1225

    
1226
int qemu_get_byte(QEMUFile *f)
1227
{
1228
    int v;
1229
    v = fgetc(f);
1230
    if (v == EOF)
1231
        return 0;
1232
    else
1233
        return v;
1234
}
1235

    
1236
unsigned int qemu_get_be16(QEMUFile *f)
1237
{
1238
    unsigned int v;
1239
    v = qemu_get_byte(f) << 8;
1240
    v |= qemu_get_byte(f);
1241
    return v;
1242
}
1243

    
1244
unsigned int qemu_get_be32(QEMUFile *f)
1245
{
1246
    unsigned int v;
1247
    v = qemu_get_byte(f) << 24;
1248
    v |= qemu_get_byte(f) << 16;
1249
    v |= qemu_get_byte(f) << 8;
1250
    v |= qemu_get_byte(f);
1251
    return v;
1252
}
1253

    
1254
uint64_t qemu_get_be64(QEMUFile *f)
1255
{
1256
    uint64_t v;
1257
    v = (uint64_t)qemu_get_be32(f) << 32;
1258
    v |= qemu_get_be32(f);
1259
    return v;
1260
}
1261

    
1262
int64_t qemu_ftell(QEMUFile *f)
1263
{
1264
    return ftell(f);
1265
}
1266

    
1267
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1268
{
1269
    if (fseek(f, pos, whence) < 0)
1270
        return -1;
1271
    return ftell(f);
1272
}
1273

    
1274
typedef struct SaveStateEntry {
1275
    char idstr[256];
1276
    int instance_id;
1277
    int version_id;
1278
    SaveStateHandler *save_state;
1279
    LoadStateHandler *load_state;
1280
    void *opaque;
1281
    struct SaveStateEntry *next;
1282
} SaveStateEntry;
1283

    
1284
static SaveStateEntry *first_se;
1285

    
1286
int register_savevm(const char *idstr, 
1287
                    int instance_id, 
1288
                    int version_id,
1289
                    SaveStateHandler *save_state,
1290
                    LoadStateHandler *load_state,
1291
                    void *opaque)
1292
{
1293
    SaveStateEntry *se, **pse;
1294

    
1295
    se = qemu_malloc(sizeof(SaveStateEntry));
1296
    if (!se)
1297
        return -1;
1298
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1299
    se->instance_id = instance_id;
1300
    se->version_id = version_id;
1301
    se->save_state = save_state;
1302
    se->load_state = load_state;
1303
    se->opaque = opaque;
1304
    se->next = NULL;
1305

    
1306
    /* add at the end of list */
1307
    pse = &first_se;
1308
    while (*pse != NULL)
1309
        pse = &(*pse)->next;
1310
    *pse = se;
1311
    return 0;
1312
}
1313

    
1314
#define QEMU_VM_FILE_MAGIC   0x5145564d
1315
#define QEMU_VM_FILE_VERSION 0x00000001
1316

    
1317
int qemu_savevm(const char *filename)
1318
{
1319
    SaveStateEntry *se;
1320
    QEMUFile *f;
1321
    int len, len_pos, cur_pos, saved_vm_running, ret;
1322

    
1323
    saved_vm_running = vm_running;
1324
    vm_stop(0);
1325

    
1326
    f = fopen(filename, "wb");
1327
    if (!f) {
1328
        ret = -1;
1329
        goto the_end;
1330
    }
1331

    
1332
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1333
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1334

    
1335
    for(se = first_se; se != NULL; se = se->next) {
1336
        /* ID string */
1337
        len = strlen(se->idstr);
1338
        qemu_put_byte(f, len);
1339
        qemu_put_buffer(f, se->idstr, len);
1340

    
1341
        qemu_put_be32(f, se->instance_id);
1342
        qemu_put_be32(f, se->version_id);
1343

    
1344
        /* record size: filled later */
1345
        len_pos = ftell(f);
1346
        qemu_put_be32(f, 0);
1347
        
1348
        se->save_state(f, se->opaque);
1349

    
1350
        /* fill record size */
1351
        cur_pos = ftell(f);
1352
        len = ftell(f) - len_pos - 4;
1353
        fseek(f, len_pos, SEEK_SET);
1354
        qemu_put_be32(f, len);
1355
        fseek(f, cur_pos, SEEK_SET);
1356
    }
1357

    
1358
    fclose(f);
1359
    ret = 0;
1360
 the_end:
1361
    if (saved_vm_running)
1362
        vm_start();
1363
    return ret;
1364
}
1365

    
1366
static SaveStateEntry *find_se(const char *idstr, int instance_id)
1367
{
1368
    SaveStateEntry *se;
1369

    
1370
    for(se = first_se; se != NULL; se = se->next) {
1371
        if (!strcmp(se->idstr, idstr) && 
1372
            instance_id == se->instance_id)
1373
            return se;
1374
    }
1375
    return NULL;
1376
}
1377

    
1378
int qemu_loadvm(const char *filename)
1379
{
1380
    SaveStateEntry *se;
1381
    QEMUFile *f;
1382
    int len, cur_pos, ret, instance_id, record_len, version_id;
1383
    int saved_vm_running;
1384
    unsigned int v;
1385
    char idstr[256];
1386
    
1387
    saved_vm_running = vm_running;
1388
    vm_stop(0);
1389

    
1390
    f = fopen(filename, "rb");
1391
    if (!f) {
1392
        ret = -1;
1393
        goto the_end;
1394
    }
1395

    
1396
    v = qemu_get_be32(f);
1397
    if (v != QEMU_VM_FILE_MAGIC)
1398
        goto fail;
1399
    v = qemu_get_be32(f);
1400
    if (v != QEMU_VM_FILE_VERSION) {
1401
    fail:
1402
        fclose(f);
1403
        ret = -1;
1404
        goto the_end;
1405
    }
1406
    for(;;) {
1407
#if defined (DO_TB_FLUSH)
1408
        tb_flush(global_env);
1409
#endif
1410
        len = qemu_get_byte(f);
1411
        if (feof(f))
1412
            break;
1413
        qemu_get_buffer(f, idstr, len);
1414
        idstr[len] = '\0';
1415
        instance_id = qemu_get_be32(f);
1416
        version_id = qemu_get_be32(f);
1417
        record_len = qemu_get_be32(f);
1418
#if 0
1419
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1420
               idstr, instance_id, version_id, record_len);
1421
#endif
1422
        cur_pos = ftell(f);
1423
        se = find_se(idstr, instance_id);
1424
        if (!se) {
1425
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1426
                    instance_id, idstr);
1427
        } else {
1428
            ret = se->load_state(f, se->opaque, version_id);
1429
            if (ret < 0) {
1430
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1431
                        instance_id, idstr);
1432
            }
1433
        }
1434
        /* always seek to exact end of record */
1435
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1436
    }
1437
    fclose(f);
1438
    ret = 0;
1439
 the_end:
1440
    if (saved_vm_running)
1441
        vm_start();
1442
    return ret;
1443
}
1444

    
1445
/***********************************************************/
1446
/* cpu save/restore */
1447

    
1448
#if defined(TARGET_I386)
1449

    
1450
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1451
{
1452
    qemu_put_be32(f, (uint32_t)dt->base);
1453
    qemu_put_be32(f, dt->limit);
1454
    qemu_put_be32(f, dt->flags);
1455
}
1456

    
1457
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1458
{
1459
    dt->base = (uint8_t *)qemu_get_be32(f);
1460
    dt->limit = qemu_get_be32(f);
1461
    dt->flags = qemu_get_be32(f);
1462
}
1463

    
1464
void cpu_save(QEMUFile *f, void *opaque)
1465
{
1466
    CPUState *env = opaque;
1467
    uint16_t fptag, fpus, fpuc;
1468
    uint32_t hflags;
1469
    int i;
1470

    
1471
    for(i = 0; i < 8; i++)
1472
        qemu_put_be32s(f, &env->regs[i]);
1473
    qemu_put_be32s(f, &env->eip);
1474
    qemu_put_be32s(f, &env->eflags);
1475
    qemu_put_be32s(f, &env->eflags);
1476
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1477
    qemu_put_be32s(f, &hflags);
1478
    
1479
    /* FPU */
1480
    fpuc = env->fpuc;
1481
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1482
    fptag = 0;
1483
    for (i=7; i>=0; i--) {
1484
        fptag <<= 2;
1485
        if (env->fptags[i]) {
1486
            fptag |= 3;
1487
        }
1488
    }
1489
    
1490
    qemu_put_be16s(f, &fpuc);
1491
    qemu_put_be16s(f, &fpus);
1492
    qemu_put_be16s(f, &fptag);
1493

    
1494
    for(i = 0; i < 8; i++) {
1495
        uint64_t mant;
1496
        uint16_t exp;
1497
        cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1498
        qemu_put_be64(f, mant);
1499
        qemu_put_be16(f, exp);
1500
    }
1501

    
1502
    for(i = 0; i < 6; i++)
1503
        cpu_put_seg(f, &env->segs[i]);
1504
    cpu_put_seg(f, &env->ldt);
1505
    cpu_put_seg(f, &env->tr);
1506
    cpu_put_seg(f, &env->gdt);
1507
    cpu_put_seg(f, &env->idt);
1508
    
1509
    qemu_put_be32s(f, &env->sysenter_cs);
1510
    qemu_put_be32s(f, &env->sysenter_esp);
1511
    qemu_put_be32s(f, &env->sysenter_eip);
1512
    
1513
    qemu_put_be32s(f, &env->cr[0]);
1514
    qemu_put_be32s(f, &env->cr[2]);
1515
    qemu_put_be32s(f, &env->cr[3]);
1516
    qemu_put_be32s(f, &env->cr[4]);
1517
    
1518
    for(i = 0; i < 8; i++)
1519
        qemu_put_be32s(f, &env->dr[i]);
1520

    
1521
    /* MMU */
1522
    qemu_put_be32s(f, &env->a20_mask);
1523
}
1524

    
1525
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1526
{
1527
    CPUState *env = opaque;
1528
    int i;
1529
    uint32_t hflags;
1530
    uint16_t fpus, fpuc, fptag;
1531

    
1532
    if (version_id != 1)
1533
        return -EINVAL;
1534
    for(i = 0; i < 8; i++)
1535
        qemu_get_be32s(f, &env->regs[i]);
1536
    qemu_get_be32s(f, &env->eip);
1537
    qemu_get_be32s(f, &env->eflags);
1538
    qemu_get_be32s(f, &env->eflags);
1539
    qemu_get_be32s(f, &hflags);
1540

    
1541
    qemu_get_be16s(f, &fpuc);
1542
    qemu_get_be16s(f, &fpus);
1543
    qemu_get_be16s(f, &fptag);
1544

    
1545
    for(i = 0; i < 8; i++) {
1546
        uint64_t mant;
1547
        uint16_t exp;
1548
        mant = qemu_get_be64(f);
1549
        exp = qemu_get_be16(f);
1550
        env->fpregs[i] = cpu_set_fp80(mant, exp);
1551
    }
1552

    
1553
    env->fpuc = fpuc;
1554
    env->fpstt = (fpus >> 11) & 7;
1555
    env->fpus = fpus & ~0x3800;
1556
    for(i = 0; i < 8; i++) {
1557
        env->fptags[i] = ((fptag & 3) == 3);
1558
        fptag >>= 2;
1559
    }
1560
    
1561
    for(i = 0; i < 6; i++)
1562
        cpu_get_seg(f, &env->segs[i]);
1563
    cpu_get_seg(f, &env->ldt);
1564
    cpu_get_seg(f, &env->tr);
1565
    cpu_get_seg(f, &env->gdt);
1566
    cpu_get_seg(f, &env->idt);
1567
    
1568
    qemu_get_be32s(f, &env->sysenter_cs);
1569
    qemu_get_be32s(f, &env->sysenter_esp);
1570
    qemu_get_be32s(f, &env->sysenter_eip);
1571
    
1572
    qemu_get_be32s(f, &env->cr[0]);
1573
    qemu_get_be32s(f, &env->cr[2]);
1574
    qemu_get_be32s(f, &env->cr[3]);
1575
    qemu_get_be32s(f, &env->cr[4]);
1576
    
1577
    for(i = 0; i < 8; i++)
1578
        qemu_get_be32s(f, &env->dr[i]);
1579

    
1580
    /* MMU */
1581
    qemu_get_be32s(f, &env->a20_mask);
1582

    
1583
    /* XXX: compute hflags from scratch, except for CPL and IIF */
1584
    env->hflags = hflags;
1585
    tlb_flush(env, 1);
1586
    return 0;
1587
}
1588

    
1589
#elif defined(TARGET_PPC)
1590
void cpu_save(QEMUFile *f, void *opaque)
1591
{
1592
}
1593

    
1594
int cpu_load(QEMUFile *f, void *opaque, int version_id)
1595
{
1596
    return 0;
1597
}
1598
#else
1599

    
1600
#warning No CPU save/restore functions
1601

    
1602
#endif
1603

    
1604
/***********************************************************/
1605
/* ram save/restore */
1606

    
1607
/* we just avoid storing empty pages */
1608
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1609
{
1610
    int i, v;
1611

    
1612
    v = buf[0];
1613
    for(i = 1; i < len; i++) {
1614
        if (buf[i] != v)
1615
            goto normal_save;
1616
    }
1617
    qemu_put_byte(f, 1);
1618
    qemu_put_byte(f, v);
1619
    return;
1620
 normal_save:
1621
    qemu_put_byte(f, 0); 
1622
    qemu_put_buffer(f, buf, len);
1623
}
1624

    
1625
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1626
{
1627
    int v;
1628

    
1629
    v = qemu_get_byte(f);
1630
    switch(v) {
1631
    case 0:
1632
        if (qemu_get_buffer(f, buf, len) != len)
1633
            return -EIO;
1634
        break;
1635
    case 1:
1636
        v = qemu_get_byte(f);
1637
        memset(buf, v, len);
1638
        break;
1639
    default:
1640
        return -EINVAL;
1641
    }
1642
    return 0;
1643
}
1644

    
1645
static void ram_save(QEMUFile *f, void *opaque)
1646
{
1647
    int i;
1648
    qemu_put_be32(f, phys_ram_size);
1649
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1650
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1651
    }
1652
}
1653

    
1654
static int ram_load(QEMUFile *f, void *opaque, int version_id)
1655
{
1656
    int i, ret;
1657

    
1658
    if (version_id != 1)
1659
        return -EINVAL;
1660
    if (qemu_get_be32(f) != phys_ram_size)
1661
        return -EINVAL;
1662
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1663
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1664
        if (ret)
1665
            return ret;
1666
    }
1667
    return 0;
1668
}
1669

    
1670
/***********************************************************/
1671
/* main execution loop */
1672

    
1673
void gui_update(void *opaque)
1674
{
1675
    display_state.dpy_refresh(&display_state);
1676
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1677
}
1678

    
1679
/* XXX: support several handlers */
1680
VMStopHandler *vm_stop_cb;
1681
VMStopHandler *vm_stop_opaque;
1682

    
1683
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1684
{
1685
    vm_stop_cb = cb;
1686
    vm_stop_opaque = opaque;
1687
    return 0;
1688
}
1689

    
1690
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1691
{
1692
    vm_stop_cb = NULL;
1693
}
1694

    
1695
void vm_start(void)
1696
{
1697
    if (!vm_running) {
1698
        cpu_enable_ticks();
1699
        vm_running = 1;
1700
    }
1701
}
1702

    
1703
void vm_stop(int reason) 
1704
{
1705
    if (vm_running) {
1706
        cpu_disable_ticks();
1707
        vm_running = 0;
1708
        if (reason != 0) {
1709
            if (vm_stop_cb) {
1710
                vm_stop_cb(vm_stop_opaque, reason);
1711
            }
1712
        }
1713
    }
1714
}
1715

    
1716
int main_loop(void)
1717
{
1718
#ifndef _WIN32
1719
    struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1720
    IOHandlerRecord *ioh, *ioh_next;
1721
    uint8_t buf[4096];
1722
    int n, max_size;
1723
#endif
1724
    int ret, timeout;
1725
    CPUState *env = global_env;
1726

    
1727
    for(;;) {
1728
        if (vm_running) {
1729
            ret = cpu_exec(env);
1730
            if (reset_requested) {
1731
                ret = EXCP_INTERRUPT; 
1732
                break;
1733
            }
1734
            if (ret == EXCP_DEBUG) {
1735
                vm_stop(EXCP_DEBUG);
1736
            }
1737
            /* if hlt instruction, we wait until the next IRQ */
1738
            /* XXX: use timeout computed from timers */
1739
            if (ret == EXCP_HLT) 
1740
                timeout = 10;
1741
            else
1742
                timeout = 0;
1743
        } else {
1744
            timeout = 10;
1745
        }
1746

    
1747
#ifdef _WIN32
1748
        if (timeout > 0)
1749
            Sleep(timeout);
1750
#else
1751

    
1752
        /* poll any events */
1753
        /* XXX: separate device handlers from system ones */
1754
        pf = ufds;
1755
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1756
            if (!ioh->fd_can_read) {
1757
                max_size = 0;
1758
                pf->fd = ioh->fd;
1759
                pf->events = POLLIN;
1760
                ioh->ufd = pf;
1761
                pf++;
1762
            } else {
1763
                max_size = ioh->fd_can_read(ioh->opaque);
1764
                if (max_size > 0) {
1765
                    if (max_size > sizeof(buf))
1766
                        max_size = sizeof(buf);
1767
                    pf->fd = ioh->fd;
1768
                    pf->events = POLLIN;
1769
                    ioh->ufd = pf;
1770
                    pf++;
1771
                } else {
1772
                    ioh->ufd = NULL;
1773
                }
1774
            }
1775
            ioh->max_size = max_size;
1776
        }
1777
        
1778
        ret = poll(ufds, pf - ufds, timeout);
1779
        if (ret > 0) {
1780
            /* XXX: better handling of removal */
1781
            for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1782
                ioh_next = ioh->next;
1783
                pf = ioh->ufd;
1784
                if (pf) {
1785
                    if (pf->revents & POLLIN) {
1786
                        if (ioh->max_size == 0) {
1787
                            /* just a read event */
1788
                            ioh->fd_read(ioh->opaque, NULL, 0);
1789
                        } else {
1790
                            n = read(ioh->fd, buf, ioh->max_size);
1791
                            if (n >= 0) {
1792
                                ioh->fd_read(ioh->opaque, buf, n);
1793
                            } else if (errno != -EAGAIN) {
1794
                                ioh->fd_read(ioh->opaque, NULL, -errno);
1795
                            }
1796
                        }
1797
                    }
1798
                }
1799
            }
1800
        }
1801

    
1802
#if defined(CONFIG_SLIRP)
1803
        /* XXX: merge with poll() */
1804
        if (slirp_inited) {
1805
            fd_set rfds, wfds, xfds;
1806
            int nfds;
1807
            struct timeval tv;
1808

    
1809
            nfds = -1;
1810
            FD_ZERO(&rfds);
1811
            FD_ZERO(&wfds);
1812
            FD_ZERO(&xfds);
1813
            slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1814
            tv.tv_sec = 0;
1815
            tv.tv_usec = 0;
1816
            ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1817
            if (ret >= 0) {
1818
                slirp_select_poll(&rfds, &wfds, &xfds);
1819
            }
1820
        }
1821
#endif
1822

    
1823
#endif
1824

    
1825
        if (vm_running) {
1826
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
1827
                            qemu_get_clock(vm_clock));
1828
            
1829
            if (audio_enabled) {
1830
                /* XXX: add explicit timer */
1831
                SB16_run();
1832
            }
1833
            
1834
            /* run dma transfers, if any */
1835
            DMA_run();
1836
        }
1837

    
1838
        /* real time timers */
1839
        qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
1840
                        qemu_get_clock(rt_clock));
1841
    }
1842
    cpu_disable_ticks();
1843
    return ret;
1844
}
1845

    
1846
void help(void)
1847
{
1848
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
1849
           "usage: %s [options] [disk_image]\n"
1850
           "\n"
1851
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
1852
           "\n"
1853
           "Standard options:\n"
1854
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
1855
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
1856
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
1857
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
1858
           "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
1859
           "-snapshot       write to temporary files instead of disk image files\n"
1860
           "-m megs         set virtual RAM size to megs MB\n"
1861
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
1862
           "-enable-audio   enable audio support\n"
1863
           "\n"
1864
           "Network options:\n"
1865
           "-nics n         simulate 'n' network cards [default=1]\n"
1866
           "-macaddr addr   set the mac address of the first interface\n"
1867
           "-n script       set tap/tun network init script [default=%s]\n"
1868
           "-tun-fd fd      use this fd as already opened tap/tun interface\n"
1869
#ifdef CONFIG_SLIRP
1870
           "-user-net       use user mode network stack [default if no tap/tun script]\n"
1871
#endif
1872
           "-dummy-net      use dummy network stack\n"
1873
           "\n"
1874
           "Linux boot specific:\n"
1875
           "-kernel bzImage use 'bzImage' as kernel image\n"
1876
           "-append cmdline use 'cmdline' as kernel command line\n"
1877
           "-initrd file    use 'file' as initial ram disk\n"
1878
           "\n"
1879
           "Debug/Expert options:\n"
1880
           "-s              wait gdb connection to port %d\n"
1881
           "-p port         change gdb connection port\n"
1882
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
1883
           "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
1884
           "-L path         set the directory for the BIOS and VGA BIOS\n"
1885
#ifdef USE_CODE_COPY
1886
           "-no-code-copy   disable code copy acceleration\n"
1887
#endif
1888

    
1889
           "\n"
1890
           "During emulation, use C-a h to get terminal commands:\n",
1891
#ifdef CONFIG_SOFTMMU
1892
           "qemu",
1893
#else
1894
           "qemu-fast",
1895
#endif
1896
           DEFAULT_NETWORK_SCRIPT, 
1897
           DEFAULT_GDBSTUB_PORT,
1898
           "/tmp/qemu.log");
1899
    term_print_help();
1900
#ifndef CONFIG_SOFTMMU
1901
    printf("\n"
1902
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
1903
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
1904
           "PC emulation.\n");
1905
#endif
1906
    exit(1);
1907
}
1908

    
1909
struct option long_options[] = {
1910
    { "initrd", 1, NULL, 0, },
1911
    { "hda", 1, NULL, 0, },
1912
    { "hdb", 1, NULL, 0, },
1913
    { "snapshot", 0, NULL, 0, },
1914
    { "hdachs", 1, NULL, 0, },
1915
    { "nographic", 0, NULL, 0, },
1916
    { "kernel", 1, NULL, 0, },
1917
    { "append", 1, NULL, 0, },
1918
    { "tun-fd", 1, NULL, 0, },
1919
    { "hdc", 1, NULL, 0, },
1920
    { "hdd", 1, NULL, 0, },
1921
    { "cdrom", 1, NULL, 0, },
1922
    { "boot", 1, NULL, 0, },
1923
    { "fda", 1, NULL, 0, },
1924
    { "fdb", 1, NULL, 0, },
1925
    { "no-code-copy", 0, NULL, 0 },
1926
    { "nics", 1, NULL, 0 },
1927
    { "macaddr", 1, NULL, 0 },
1928
    { "user-net", 0, NULL, 0 },
1929
    { "dummy-net", 0, NULL, 0 },
1930
    { "enable-audio", 0, NULL, 0 },
1931
    { NULL, 0, NULL, 0 },
1932
};
1933

    
1934
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1935

    
1936
/* this stack is only used during signal handling */
1937
#define SIGNAL_STACK_SIZE 32768
1938

    
1939
static uint8_t *signal_stack;
1940

    
1941
#endif
1942

    
1943
#define NET_IF_TUN   0
1944
#define NET_IF_USER  1
1945
#define NET_IF_DUMMY 2
1946

    
1947
int main(int argc, char **argv)
1948
{
1949
#ifdef CONFIG_GDBSTUB
1950
    int use_gdbstub, gdbstub_port;
1951
#endif
1952
    int c, i, long_index, has_cdrom;
1953
    int snapshot, linux_boot;
1954
    CPUState *env;
1955
    const char *initrd_filename;
1956
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
1957
    const char *kernel_filename, *kernel_cmdline;
1958
    DisplayState *ds = &display_state;
1959
    int cyls, heads, secs;
1960
    int start_emulation = 1;
1961
    uint8_t macaddr[6];
1962
    int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
1963
    
1964
#if !defined(CONFIG_SOFTMMU)
1965
    /* we never want that malloc() uses mmap() */
1966
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
1967
#endif
1968
    initrd_filename = NULL;
1969
    for(i = 0; i < MAX_FD; i++)
1970
        fd_filename[i] = NULL;
1971
    for(i = 0; i < MAX_DISKS; i++)
1972
        hd_filename[i] = NULL;
1973
    ram_size = 32 * 1024 * 1024;
1974
    vga_ram_size = VGA_RAM_SIZE;
1975
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
1976
#ifdef CONFIG_GDBSTUB
1977
    use_gdbstub = 0;
1978
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
1979
#endif
1980
    snapshot = 0;
1981
    nographic = 0;
1982
    kernel_filename = NULL;
1983
    kernel_cmdline = "";
1984
    has_cdrom = 1;
1985
    cyls = heads = secs = 0;
1986

    
1987
    nb_tun_fds = 0;
1988
    net_if_type = -1;
1989
    nb_nics = 1;
1990
    /* default mac address of the first network interface */
1991
    macaddr[0] = 0x52;
1992
    macaddr[1] = 0x54;
1993
    macaddr[2] = 0x00;
1994
    macaddr[3] = 0x12;
1995
    macaddr[4] = 0x34;
1996
    macaddr[5] = 0x56;
1997

    
1998

    
1999
    for(;;) {
2000
        c = getopt_long_only(argc, argv, "hm:d:n:sp:L:S", long_options, &long_index);
2001
        if (c == -1)
2002
            break;
2003
        switch(c) {
2004
        case 0:
2005
            switch(long_index) {
2006
            case 0:
2007
                initrd_filename = optarg;
2008
                break;
2009
            case 1:
2010
                hd_filename[0] = optarg;
2011
                break;
2012
            case 2:
2013
                hd_filename[1] = optarg;
2014
                break;
2015
            case 3:
2016
                snapshot = 1;
2017
                break;
2018
            case 4:
2019
                {
2020
                    const char *p;
2021
                    p = optarg;
2022
                    cyls = strtol(p, (char **)&p, 0);
2023
                    if (*p != ',')
2024
                        goto chs_fail;
2025
                    p++;
2026
                    heads = strtol(p, (char **)&p, 0);
2027
                    if (*p != ',')
2028
                        goto chs_fail;
2029
                    p++;
2030
                    secs = strtol(p, (char **)&p, 0);
2031
                    if (*p != '\0') {
2032
                    chs_fail:
2033
                        cyls = 0;
2034
                    }
2035
                }
2036
                break;
2037
            case 5:
2038
                nographic = 1;
2039
                break;
2040
            case 6:
2041
                kernel_filename = optarg;
2042
                break;
2043
            case 7:
2044
                kernel_cmdline = optarg;
2045
                break;
2046
            case 8:
2047
                {
2048
                    const char *p;
2049
                    int fd;
2050
                    if (nb_tun_fds < MAX_NICS) {
2051
                        fd = strtol(optarg, (char **)&p, 0);
2052
                        if (*p != '\0') {
2053
                            fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2054
                            exit(1);
2055
                        }
2056
                        tun_fds[nb_tun_fds++] = fd;
2057
                    }
2058
                }
2059
                break;
2060
            case 9:
2061
                hd_filename[2] = optarg;
2062
                has_cdrom = 0;
2063
                break;
2064
            case 10:
2065
                hd_filename[3] = optarg;
2066
                break;
2067
            case 11:
2068
                hd_filename[2] = optarg;
2069
                has_cdrom = 1;
2070
                break;
2071
            case 12:
2072
                boot_device = optarg[0];
2073
                if (boot_device != 'a' && boot_device != 'b' &&
2074
                    boot_device != 'c' && boot_device != 'd') {
2075
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2076
                    exit(1);
2077
                }
2078
                break;
2079
            case 13:
2080
                fd_filename[0] = optarg;
2081
                break;
2082
            case 14:
2083
                fd_filename[1] = optarg;
2084
                break;
2085
            case 15:
2086
                code_copy_enabled = 0;
2087
                break;
2088
            case 16:
2089
                nb_nics = atoi(optarg);
2090
                if (nb_nics < 1 || nb_nics > MAX_NICS) {
2091
                    fprintf(stderr, "qemu: invalid number of network interfaces\n");
2092
                    exit(1);
2093
                }
2094
                break;
2095
            case 17:
2096
                {
2097
                    const char *p;
2098
                    int i;
2099
                    p = optarg;
2100
                    for(i = 0; i < 6; i++) {
2101
                        macaddr[i] = strtol(p, (char **)&p, 16);
2102
                        if (i == 5) {
2103
                            if (*p != '\0') 
2104
                                goto macaddr_error;
2105
                        } else {
2106
                            if (*p != ':') {
2107
                            macaddr_error:
2108
                                fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2109
                                exit(1);
2110
                            }
2111
                            p++;
2112
                        }
2113
                    }
2114
                }
2115
                break;
2116
            case 18:
2117
                net_if_type = NET_IF_USER;
2118
                break;
2119
            case 19:
2120
                net_if_type = NET_IF_DUMMY;
2121
                break;
2122
            case 20:
2123
                audio_enabled = 1;
2124
                break;
2125
            }
2126
            break;
2127
        case 'h':
2128
            help();
2129
            break;
2130
        case 'm':
2131
            ram_size = atoi(optarg) * 1024 * 1024;
2132
            if (ram_size <= 0)
2133
                help();
2134
            if (ram_size > PHYS_RAM_MAX_SIZE) {
2135
                fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2136
                        PHYS_RAM_MAX_SIZE / (1024 * 1024));
2137
                exit(1);
2138
            }
2139
            break;
2140
        case 'd':
2141
            {
2142
                int mask;
2143
                CPULogItem *item;
2144

    
2145
                mask = cpu_str_to_log_mask(optarg);
2146
                if (!mask) {
2147
                    printf("Log items (comma separated):\n");
2148
                    for(item = cpu_log_items; item->mask != 0; item++) {
2149
                        printf("%-10s %s\n", item->name, item->help);
2150
                    }
2151
                    exit(1);
2152
                }
2153
                cpu_set_log(mask);
2154
            }
2155
            break;
2156
        case 'n':
2157
            pstrcpy(network_script, sizeof(network_script), optarg);
2158
            break;
2159
#ifdef CONFIG_GDBSTUB
2160
        case 's':
2161
            use_gdbstub = 1;
2162
            break;
2163
        case 'p':
2164
            gdbstub_port = atoi(optarg);
2165
            break;
2166
#endif
2167
        case 'L':
2168
            bios_dir = optarg;
2169
            break;
2170
        case 'S':
2171
            start_emulation = 0;
2172
            break;
2173
        }
2174
    }
2175

    
2176
    if (optind < argc) {
2177
        hd_filename[0] = argv[optind++];
2178
    }
2179

    
2180
    linux_boot = (kernel_filename != NULL);
2181
        
2182
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2183
        fd_filename[0] == '\0')
2184
        help();
2185
    
2186
    /* boot to cd by default if no hard disk */
2187
    if (hd_filename[0] == '\0' && boot_device == 'c') {
2188
        if (fd_filename[0] != '\0')
2189
            boot_device = 'a';
2190
        else
2191
            boot_device = 'd';
2192
    }
2193

    
2194
#if !defined(CONFIG_SOFTMMU)
2195
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2196
    {
2197
        static uint8_t stdout_buf[4096];
2198
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2199
    }
2200
#else
2201
    setvbuf(stdout, NULL, _IOLBF, 0);
2202
#endif
2203

    
2204
    /* init host network redirectors */
2205
    if (net_if_type == -1) {
2206
        net_if_type = NET_IF_TUN;
2207
#if defined(CONFIG_SLIRP)
2208
        if (access(network_script, R_OK) < 0) {
2209
            net_if_type = NET_IF_USER;
2210
        }
2211
#endif
2212
    }
2213

    
2214
    for(i = 0; i < nb_nics; i++) {
2215
        NetDriverState *nd = &nd_table[i];
2216
        nd->index = i;
2217
        /* init virtual mac address */
2218
        nd->macaddr[0] = macaddr[0];
2219
        nd->macaddr[1] = macaddr[1];
2220
        nd->macaddr[2] = macaddr[2];
2221
        nd->macaddr[3] = macaddr[3];
2222
        nd->macaddr[4] = macaddr[4];
2223
        nd->macaddr[5] = macaddr[5] + i;
2224
        switch(net_if_type) {
2225
#if defined(CONFIG_SLIRP)
2226
        case NET_IF_USER:
2227
            net_slirp_init(nd);
2228
            break;
2229
#endif
2230
#if !defined(_WIN32)
2231
        case NET_IF_TUN:
2232
            if (i < nb_tun_fds) {
2233
                net_fd_init(nd, tun_fds[i]);
2234
            } else {
2235
                if (net_tun_init(nd) < 0)
2236
                    net_dummy_init(nd);
2237
            }
2238
            break;
2239
#endif
2240
        case NET_IF_DUMMY:
2241
        default:
2242
            net_dummy_init(nd);
2243
            break;
2244
        }
2245
    }
2246

    
2247
    /* init the memory */
2248
    phys_ram_size = ram_size + vga_ram_size;
2249

    
2250
#ifdef CONFIG_SOFTMMU
2251
    phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2252
    if (!phys_ram_base) {
2253
        fprintf(stderr, "Could not allocate physical memory\n");
2254
        exit(1);
2255
    }
2256
#else
2257
    /* as we must map the same page at several addresses, we must use
2258
       a fd */
2259
    {
2260
        const char *tmpdir;
2261

    
2262
        tmpdir = getenv("QEMU_TMPDIR");
2263
        if (!tmpdir)
2264
            tmpdir = "/tmp";
2265
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2266
        if (mkstemp(phys_ram_file) < 0) {
2267
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2268
                    phys_ram_file);
2269
            exit(1);
2270
        }
2271
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2272
        if (phys_ram_fd < 0) {
2273
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2274
                    phys_ram_file);
2275
            exit(1);
2276
        }
2277
        ftruncate(phys_ram_fd, phys_ram_size);
2278
        unlink(phys_ram_file);
2279
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2280
                             phys_ram_size, 
2281
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2282
                             phys_ram_fd, 0);
2283
        if (phys_ram_base == MAP_FAILED) {
2284
            fprintf(stderr, "Could not map physical memory\n");
2285
            exit(1);
2286
        }
2287
    }
2288
#endif
2289

    
2290
    /* we always create the cdrom drive, even if no disk is there */
2291
    if (has_cdrom) {
2292
        bs_table[2] = bdrv_new("cdrom");
2293
        bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2294
    }
2295

    
2296
    /* open the virtual block devices */
2297
    for(i = 0; i < MAX_DISKS; i++) {
2298
        if (hd_filename[i]) {
2299
            if (!bs_table[i]) {
2300
                char buf[64];
2301
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2302
                bs_table[i] = bdrv_new(buf);
2303
            }
2304
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2305
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2306
                        hd_filename[i]);
2307
                exit(1);
2308
            }
2309
            if (i == 0 && cyls != 0) 
2310
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2311
        }
2312
    }
2313

    
2314
    /* we always create at least one floppy disk */
2315
    fd_table[0] = bdrv_new("fda");
2316
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2317

    
2318
    for(i = 0; i < MAX_FD; i++) {
2319
        if (fd_filename[i]) {
2320
            if (!fd_table[i]) {
2321
                char buf[64];
2322
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2323
                fd_table[i] = bdrv_new(buf);
2324
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2325
            }
2326
            if (fd_filename[i] != '\0') {
2327
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2328
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2329
                            fd_filename[i]);
2330
                    exit(1);
2331
                }
2332
            }
2333
        }
2334
    }
2335

    
2336
    /* init CPU state */
2337
    env = cpu_init();
2338
    global_env = env;
2339
    cpu_single_env = env;
2340

    
2341
    register_savevm("timer", 0, 1, timer_save, timer_load, env);
2342
    register_savevm("cpu", 0, 1, cpu_save, cpu_load, env);
2343
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2344

    
2345
    init_ioports();
2346
    cpu_calibrate_ticks();
2347

    
2348
    /* terminal init */
2349
    if (nographic) {
2350
        dumb_display_init(ds);
2351
    } else {
2352
#ifdef CONFIG_SDL
2353
        sdl_display_init(ds);
2354
#else
2355
        dumb_display_init(ds);
2356
#endif
2357
    }
2358

    
2359
    /* setup cpu signal handlers for MMU / self modifying code handling */
2360
#if !defined(CONFIG_SOFTMMU)
2361
    
2362
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2363
    {
2364
        stack_t stk;
2365
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2366
        stk.ss_sp = signal_stack;
2367
        stk.ss_size = SIGNAL_STACK_SIZE;
2368
        stk.ss_flags = 0;
2369

    
2370
        if (sigaltstack(&stk, NULL) < 0) {
2371
            perror("sigaltstack");
2372
            exit(1);
2373
        }
2374
    }
2375
#endif
2376
    {
2377
        struct sigaction act;
2378
        
2379
        sigfillset(&act.sa_mask);
2380
        act.sa_flags = SA_SIGINFO;
2381
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2382
        act.sa_flags |= SA_ONSTACK;
2383
#endif
2384
        act.sa_sigaction = host_segv_handler;
2385
        sigaction(SIGSEGV, &act, NULL);
2386
        sigaction(SIGBUS, &act, NULL);
2387
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2388
        sigaction(SIGFPE, &act, NULL);
2389
#endif
2390
    }
2391
#endif
2392

    
2393
#ifndef _WIN32
2394
    {
2395
        struct sigaction act;
2396
        sigfillset(&act.sa_mask);
2397
        act.sa_flags = 0;
2398
        act.sa_handler = SIG_IGN;
2399
        sigaction(SIGPIPE, &act, NULL);
2400
    }
2401
#endif
2402
    init_timers();
2403

    
2404
#if defined(TARGET_I386)
2405
    pc_init(ram_size, vga_ram_size, boot_device,
2406
            ds, fd_filename, snapshot,
2407
            kernel_filename, kernel_cmdline, initrd_filename);
2408
#elif defined(TARGET_PPC)
2409
    ppc_init(ram_size, vga_ram_size, boot_device,
2410
             ds, fd_filename, snapshot,
2411
             kernel_filename, kernel_cmdline, initrd_filename);
2412
#endif
2413

    
2414
    /* launched after the device init so that it can display or not a
2415
       banner */
2416
    monitor_init();
2417

    
2418
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2419
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2420

    
2421
#ifdef CONFIG_GDBSTUB
2422
    if (use_gdbstub) {
2423
        if (gdbserver_start(gdbstub_port) < 0) {
2424
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
2425
                    gdbstub_port);
2426
            exit(1);
2427
        } else {
2428
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
2429
        }
2430
    } else 
2431
#endif
2432
    if (start_emulation)
2433
    {
2434
        vm_start();
2435
    }
2436
    term_init();
2437
    main_loop();
2438
    quit_timers();
2439
    return 0;
2440
}