Statistics
| Branch: | Revision:

root / vl.c @ 02536f8b

History | View | Annotate | Download (92.5 kB)

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

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

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

    
57
#if defined(CONFIG_SLIRP)
58
#include "libslirp.h"
59
#endif
60

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

    
69
#ifdef CONFIG_SDL
70
#ifdef __APPLE__
71
#include <SDL/SDL.h>
72
#endif
73
#endif /* CONFIG_SDL */
74

    
75
#include "disas.h"
76

    
77
#include "exec-all.h"
78

    
79
//#define DO_TB_FLUSH
80

    
81
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
82

    
83
//#define DEBUG_UNUSED_IOPORT
84
//#define DEBUG_IOPORT
85

    
86
#if !defined(CONFIG_SOFTMMU)
87
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
88
#else
89
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
90
#endif
91

    
92
#ifdef TARGET_PPC
93
#define DEFAULT_RAM_SIZE 144
94
#else
95
#define DEFAULT_RAM_SIZE 128
96
#endif
97
/* in ms */
98
#define GUI_REFRESH_INTERVAL 30
99

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

    
103
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
104
char phys_ram_file[1024];
105
CPUState *global_env;
106
CPUState *cpu_single_env;
107
void *ioport_opaque[MAX_IOPORTS];
108
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
109
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
110
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
111
int vga_ram_size;
112
int bios_size;
113
static DisplayState display_state;
114
int nographic;
115
const char* keyboard_layout = NULL;
116
int64_t ticks_per_sec;
117
int boot_device = 'c';
118
int ram_size;
119
static char network_script[1024];
120
int pit_min_timer_count = 0;
121
int nb_nics;
122
NetDriverState nd_table[MAX_NICS];
123
QEMUTimer *gui_timer;
124
int vm_running;
125
int audio_enabled = 0;
126
int sb16_enabled = 1;
127
int adlib_enabled = 1;
128
int gus_enabled = 1;
129
int pci_enabled = 1;
130
int prep_enabled = 0;
131
int rtc_utc = 1;
132
int cirrus_vga_enabled = 1;
133
int graphic_width = 800;
134
int graphic_height = 600;
135
int graphic_depth = 15;
136
int full_screen = 0;
137
TextConsole *vga_console;
138
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
139

    
140
/***********************************************************/
141
/* x86 ISA bus support */
142

    
143
target_phys_addr_t isa_mem_base = 0;
144

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

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

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

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

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

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

    
192
void init_ioports(void)
193
{
194
    int i;
195

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

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

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

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

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

    
256
void isa_unassign_ioport(int start, int length)
257
{
258
    int i;
259

    
260
    for(i = start; i < start + length; i++) {
261
        ioport_read_table[0][i] = default_ioport_readb;
262
        ioport_read_table[1][i] = default_ioport_readw;
263
        ioport_read_table[2][i] = default_ioport_readl;
264

    
265
        ioport_write_table[0][i] = default_ioport_writeb;
266
        ioport_write_table[1][i] = default_ioport_writew;
267
        ioport_write_table[2][i] = default_ioport_writel;
268
    }
269
}
270

    
271
/***********************************************************/
272

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

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

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

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

    
300
int strstart(const char *str, const char *val, const char **ptr)
301
{
302
    const char *p, *q;
303
    p = str;
304
    q = val;
305
    while (*q != '\0') {
306
        if (*p != *q)
307
            return 0;
308
        p++;
309
        q++;
310
    }
311
    if (ptr)
312
        *ptr = p;
313
    return 1;
314
}
315

    
316
/* return the size or -1 if error */
317
int get_image_size(const char *filename)
318
{
319
    int fd, size;
320
    fd = open(filename, O_RDONLY | O_BINARY);
321
    if (fd < 0)
322
        return -1;
323
    size = lseek(fd, 0, SEEK_END);
324
    close(fd);
325
    return size;
326
}
327

    
328
/* return the size or -1 if error */
329
int load_image(const char *filename, uint8_t *addr)
330
{
331
    int fd, size;
332
    fd = open(filename, O_RDONLY | O_BINARY);
333
    if (fd < 0)
334
        return -1;
335
    size = lseek(fd, 0, SEEK_END);
336
    lseek(fd, 0, SEEK_SET);
337
    if (read(fd, addr, size) != size) {
338
        close(fd);
339
        return -1;
340
    }
341
    close(fd);
342
    return size;
343
}
344

    
345
void cpu_outb(CPUState *env, int addr, int val)
346
{
347
#ifdef DEBUG_IOPORT
348
    if (loglevel & CPU_LOG_IOPORT)
349
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
350
#endif    
351
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
352
}
353

    
354
void cpu_outw(CPUState *env, int addr, int val)
355
{
356
#ifdef DEBUG_IOPORT
357
    if (loglevel & CPU_LOG_IOPORT)
358
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
359
#endif    
360
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
361
}
362

    
363
void cpu_outl(CPUState *env, int addr, int val)
364
{
365
#ifdef DEBUG_IOPORT
366
    if (loglevel & CPU_LOG_IOPORT)
367
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
368
#endif
369
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
370
}
371

    
372
int cpu_inb(CPUState *env, int addr)
373
{
374
    int val;
375
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
376
#ifdef DEBUG_IOPORT
377
    if (loglevel & CPU_LOG_IOPORT)
378
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
379
#endif
380
    return val;
381
}
382

    
383
int cpu_inw(CPUState *env, int addr)
384
{
385
    int val;
386
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
387
#ifdef DEBUG_IOPORT
388
    if (loglevel & CPU_LOG_IOPORT)
389
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
390
#endif
391
    return val;
392
}
393

    
394
int cpu_inl(CPUState *env, int addr)
395
{
396
    int val;
397
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
398
#ifdef DEBUG_IOPORT
399
    if (loglevel & CPU_LOG_IOPORT)
400
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
401
#endif
402
    return val;
403
}
404

    
405
/***********************************************************/
406
void hw_error(const char *fmt, ...)
407
{
408
    va_list ap;
409

    
410
    va_start(ap, fmt);
411
    fprintf(stderr, "qemu: hardware error: ");
412
    vfprintf(stderr, fmt, ap);
413
    fprintf(stderr, "\n");
414
#ifdef TARGET_I386
415
    cpu_dump_state(global_env, stderr, fprintf, X86_DUMP_FPU | X86_DUMP_CCOP);
416
#else
417
    cpu_dump_state(global_env, stderr, fprintf, 0);
418
#endif
419
    va_end(ap);
420
    abort();
421
}
422

    
423
/***********************************************************/
424
/* keyboard/mouse */
425

    
426
static QEMUPutKBDEvent *qemu_put_kbd_event;
427
static void *qemu_put_kbd_event_opaque;
428
static QEMUPutMouseEvent *qemu_put_mouse_event;
429
static void *qemu_put_mouse_event_opaque;
430

    
431
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
432
{
433
    qemu_put_kbd_event_opaque = opaque;
434
    qemu_put_kbd_event = func;
435
}
436

    
437
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
438
{
439
    qemu_put_mouse_event_opaque = opaque;
440
    qemu_put_mouse_event = func;
441
}
442

    
443
void kbd_put_keycode(int keycode)
444
{
445
    if (qemu_put_kbd_event) {
446
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
447
    }
448
}
449

    
450
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
451
{
452
    if (qemu_put_mouse_event) {
453
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
454
                             dx, dy, dz, buttons_state);
455
    }
456
}
457

    
458
/***********************************************************/
459
/* timers */
460

    
461
#if defined(__powerpc__)
462

    
463
static inline uint32_t get_tbl(void) 
464
{
465
    uint32_t tbl;
466
    asm volatile("mftb %0" : "=r" (tbl));
467
    return tbl;
468
}
469

    
470
static inline uint32_t get_tbu(void) 
471
{
472
        uint32_t tbl;
473
        asm volatile("mftbu %0" : "=r" (tbl));
474
        return tbl;
475
}
476

    
477
int64_t cpu_get_real_ticks(void)
478
{
479
    uint32_t l, h, h1;
480
    /* NOTE: we test if wrapping has occurred */
481
    do {
482
        h = get_tbu();
483
        l = get_tbl();
484
        h1 = get_tbu();
485
    } while (h != h1);
486
    return ((int64_t)h << 32) | l;
487
}
488

    
489
#elif defined(__i386__)
490

    
491
int64_t cpu_get_real_ticks(void)
492
{
493
    int64_t val;
494
    asm volatile ("rdtsc" : "=A" (val));
495
    return val;
496
}
497

    
498
#elif defined(__x86_64__)
499

    
500
int64_t cpu_get_real_ticks(void)
501
{
502
    uint32_t low,high;
503
    int64_t val;
504
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
505
    val = high;
506
    val <<= 32;
507
    val |= low;
508
    return val;
509
}
510

    
511
#else
512
#error unsupported CPU
513
#endif
514

    
515
static int64_t cpu_ticks_offset;
516
static int cpu_ticks_enabled;
517

    
518
static inline int64_t cpu_get_ticks(void)
519
{
520
    if (!cpu_ticks_enabled) {
521
        return cpu_ticks_offset;
522
    } else {
523
        return cpu_get_real_ticks() + cpu_ticks_offset;
524
    }
525
}
526

    
527
/* enable cpu_get_ticks() */
528
void cpu_enable_ticks(void)
529
{
530
    if (!cpu_ticks_enabled) {
531
        cpu_ticks_offset -= cpu_get_real_ticks();
532
        cpu_ticks_enabled = 1;
533
    }
534
}
535

    
536
/* disable cpu_get_ticks() : the clock is stopped. You must not call
537
   cpu_get_ticks() after that.  */
538
void cpu_disable_ticks(void)
539
{
540
    if (cpu_ticks_enabled) {
541
        cpu_ticks_offset = cpu_get_ticks();
542
        cpu_ticks_enabled = 0;
543
    }
544
}
545

    
546
static int64_t get_clock(void)
547
{
548
#ifdef _WIN32
549
    struct _timeb tb;
550
    _ftime(&tb);
551
    return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
552
#else
553
    struct timeval tv;
554
    gettimeofday(&tv, NULL);
555
    return tv.tv_sec * 1000000LL + tv.tv_usec;
556
#endif
557
}
558

    
559
void cpu_calibrate_ticks(void)
560
{
561
    int64_t usec, ticks;
562

    
563
    usec = get_clock();
564
    ticks = cpu_get_real_ticks();
565
#ifdef _WIN32
566
    Sleep(50);
567
#else
568
    usleep(50 * 1000);
569
#endif
570
    usec = get_clock() - usec;
571
    ticks = cpu_get_real_ticks() - ticks;
572
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
573
}
574

    
575
/* compute with 96 bit intermediate result: (a*b)/c */
576
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
577
{
578
    union {
579
        uint64_t ll;
580
        struct {
581
#ifdef WORDS_BIGENDIAN
582
            uint32_t high, low;
583
#else
584
            uint32_t low, high;
585
#endif            
586
        } l;
587
    } u, res;
588
    uint64_t rl, rh;
589

    
590
    u.ll = a;
591
    rl = (uint64_t)u.l.low * (uint64_t)b;
592
    rh = (uint64_t)u.l.high * (uint64_t)b;
593
    rh += (rl >> 32);
594
    res.l.high = rh / c;
595
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
596
    return res.ll;
597
}
598

    
599
#define QEMU_TIMER_REALTIME 0
600
#define QEMU_TIMER_VIRTUAL  1
601

    
602
struct QEMUClock {
603
    int type;
604
    /* XXX: add frequency */
605
};
606

    
607
struct QEMUTimer {
608
    QEMUClock *clock;
609
    int64_t expire_time;
610
    QEMUTimerCB *cb;
611
    void *opaque;
612
    struct QEMUTimer *next;
613
};
614

    
615
QEMUClock *rt_clock;
616
QEMUClock *vm_clock;
617

    
618
static QEMUTimer *active_timers[2];
619
#ifdef _WIN32
620
static MMRESULT timerID;
621
#else
622
/* frequency of the times() clock tick */
623
static int timer_freq;
624
#endif
625

    
626
QEMUClock *qemu_new_clock(int type)
627
{
628
    QEMUClock *clock;
629
    clock = qemu_mallocz(sizeof(QEMUClock));
630
    if (!clock)
631
        return NULL;
632
    clock->type = type;
633
    return clock;
634
}
635

    
636
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
637
{
638
    QEMUTimer *ts;
639

    
640
    ts = qemu_mallocz(sizeof(QEMUTimer));
641
    ts->clock = clock;
642
    ts->cb = cb;
643
    ts->opaque = opaque;
644
    return ts;
645
}
646

    
647
void qemu_free_timer(QEMUTimer *ts)
648
{
649
    qemu_free(ts);
650
}
651

    
652
/* stop a timer, but do not dealloc it */
653
void qemu_del_timer(QEMUTimer *ts)
654
{
655
    QEMUTimer **pt, *t;
656

    
657
    /* NOTE: this code must be signal safe because
658
       qemu_timer_expired() can be called from a signal. */
659
    pt = &active_timers[ts->clock->type];
660
    for(;;) {
661
        t = *pt;
662
        if (!t)
663
            break;
664
        if (t == ts) {
665
            *pt = t->next;
666
            break;
667
        }
668
        pt = &t->next;
669
    }
670
}
671

    
672
/* modify the current timer so that it will be fired when current_time
673
   >= expire_time. The corresponding callback will be called. */
674
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
675
{
676
    QEMUTimer **pt, *t;
677

    
678
    qemu_del_timer(ts);
679

    
680
    /* add the timer in the sorted list */
681
    /* NOTE: this code must be signal safe because
682
       qemu_timer_expired() can be called from a signal. */
683
    pt = &active_timers[ts->clock->type];
684
    for(;;) {
685
        t = *pt;
686
        if (!t)
687
            break;
688
        if (t->expire_time > expire_time) 
689
            break;
690
        pt = &t->next;
691
    }
692
    ts->expire_time = expire_time;
693
    ts->next = *pt;
694
    *pt = ts;
695
}
696

    
697
int qemu_timer_pending(QEMUTimer *ts)
698
{
699
    QEMUTimer *t;
700
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
701
        if (t == ts)
702
            return 1;
703
    }
704
    return 0;
705
}
706

    
707
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
708
{
709
    if (!timer_head)
710
        return 0;
711
    return (timer_head->expire_time <= current_time);
712
}
713

    
714
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
715
{
716
    QEMUTimer *ts;
717
    
718
    for(;;) {
719
        ts = *ptimer_head;
720
        if (!ts || ts->expire_time > current_time)
721
            break;
722
        /* remove timer from the list before calling the callback */
723
        *ptimer_head = ts->next;
724
        ts->next = NULL;
725
        
726
        /* run the callback (the timer list can be modified) */
727
        ts->cb(ts->opaque);
728
    }
729
}
730

    
731
int64_t qemu_get_clock(QEMUClock *clock)
732
{
733
    switch(clock->type) {
734
    case QEMU_TIMER_REALTIME:
735
#ifdef _WIN32
736
        return GetTickCount();
737
#else
738
        {
739
            struct tms tp;
740

    
741
            /* Note that using gettimeofday() is not a good solution
742
               for timers because its value change when the date is
743
               modified. */
744
            if (timer_freq == 100) {
745
                return times(&tp) * 10;
746
            } else {
747
                return ((int64_t)times(&tp) * 1000) / timer_freq;
748
            }
749
        }
750
#endif
751
    default:
752
    case QEMU_TIMER_VIRTUAL:
753
        return cpu_get_ticks();
754
    }
755
}
756

    
757
/* save a timer */
758
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
759
{
760
    uint64_t expire_time;
761

    
762
    if (qemu_timer_pending(ts)) {
763
        expire_time = ts->expire_time;
764
    } else {
765
        expire_time = -1;
766
    }
767
    qemu_put_be64(f, expire_time);
768
}
769

    
770
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
771
{
772
    uint64_t expire_time;
773

    
774
    expire_time = qemu_get_be64(f);
775
    if (expire_time != -1) {
776
        qemu_mod_timer(ts, expire_time);
777
    } else {
778
        qemu_del_timer(ts);
779
    }
780
}
781

    
782
static void timer_save(QEMUFile *f, void *opaque)
783
{
784
    if (cpu_ticks_enabled) {
785
        hw_error("cannot save state if virtual timers are running");
786
    }
787
    qemu_put_be64s(f, &cpu_ticks_offset);
788
    qemu_put_be64s(f, &ticks_per_sec);
789
}
790

    
791
static int timer_load(QEMUFile *f, void *opaque, int version_id)
792
{
793
    if (version_id != 1)
794
        return -EINVAL;
795
    if (cpu_ticks_enabled) {
796
        return -EINVAL;
797
    }
798
    qemu_get_be64s(f, &cpu_ticks_offset);
799
    qemu_get_be64s(f, &ticks_per_sec);
800
    return 0;
801
}
802

    
803
#ifdef _WIN32
804
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
805
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
806
#else
807
static void host_alarm_handler(int host_signum)
808
#endif
809
{
810
#if 0
811
#define DISP_FREQ 1000
812
    {
813
        static int64_t delta_min = INT64_MAX;
814
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
815
        static int count;
816
        ti = qemu_get_clock(vm_clock);
817
        if (last_clock != 0) {
818
            delta = ti - last_clock;
819
            if (delta < delta_min)
820
                delta_min = delta;
821
            if (delta > delta_max)
822
                delta_max = delta;
823
            delta_cum += delta;
824
            if (++count == DISP_FREQ) {
825
                printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
826
                       muldiv64(delta_min, 1000000, ticks_per_sec),
827
                       muldiv64(delta_max, 1000000, ticks_per_sec),
828
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
829
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
830
                count = 0;
831
                delta_min = INT64_MAX;
832
                delta_max = 0;
833
                delta_cum = 0;
834
            }
835
        }
836
        last_clock = ti;
837
    }
838
#endif
839
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
840
                           qemu_get_clock(vm_clock)) ||
841
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
842
                           qemu_get_clock(rt_clock))) {
843
        /* stop the cpu because a timer occured */
844
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
845
    }
846
}
847

    
848
#ifndef _WIN32
849

    
850
#if defined(__linux__)
851

    
852
#define RTC_FREQ 1024
853

    
854
static int rtc_fd;
855

    
856
static int start_rtc_timer(void)
857
{
858
    rtc_fd = open("/dev/rtc", O_RDONLY);
859
    if (rtc_fd < 0)
860
        return -1;
861
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
862
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
863
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
864
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
865
        goto fail;
866
    }
867
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
868
    fail:
869
        close(rtc_fd);
870
        return -1;
871
    }
872
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
873
    return 0;
874
}
875

    
876
#else
877

    
878
static int start_rtc_timer(void)
879
{
880
    return -1;
881
}
882

    
883
#endif /* !defined(__linux__) */
884

    
885
#endif /* !defined(_WIN32) */
886

    
887
static void init_timers(void)
888
{
889
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
890
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
891

    
892
#ifdef _WIN32
893
    {
894
        int count=0;
895
        timerID = timeSetEvent(10,    // interval (ms)
896
                               0,     // resolution
897
                               host_alarm_handler, // function
898
                               (DWORD)&count,  // user parameter
899
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
900
         if( !timerID ) {
901
            perror("failed timer alarm");
902
            exit(1);
903
         }
904
    }
905
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
906
#else
907
    {
908
        struct sigaction act;
909
        struct itimerval itv;
910
        
911
        /* get times() syscall frequency */
912
        timer_freq = sysconf(_SC_CLK_TCK);
913
        
914
        /* timer signal */
915
        sigfillset(&act.sa_mask);
916
        act.sa_flags = 0;
917
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
918
        act.sa_flags |= SA_ONSTACK;
919
#endif
920
        act.sa_handler = host_alarm_handler;
921
        sigaction(SIGALRM, &act, NULL);
922

    
923
        itv.it_interval.tv_sec = 0;
924
        itv.it_interval.tv_usec = 1000;
925
        itv.it_value.tv_sec = 0;
926
        itv.it_value.tv_usec = 10 * 1000;
927
        setitimer(ITIMER_REAL, &itv, NULL);
928
        /* we probe the tick duration of the kernel to inform the user if
929
           the emulated kernel requested a too high timer frequency */
930
        getitimer(ITIMER_REAL, &itv);
931

    
932
#if defined(__linux__)
933
        if (itv.it_interval.tv_usec > 1000) {
934
            /* try to use /dev/rtc to have a faster timer */
935
            if (start_rtc_timer() < 0)
936
                goto use_itimer;
937
            /* disable itimer */
938
            itv.it_interval.tv_sec = 0;
939
            itv.it_interval.tv_usec = 0;
940
            itv.it_value.tv_sec = 0;
941
            itv.it_value.tv_usec = 0;
942
            setitimer(ITIMER_REAL, &itv, NULL);
943

    
944
            /* use the RTC */
945
            sigaction(SIGIO, &act, NULL);
946
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
947
            fcntl(rtc_fd, F_SETOWN, getpid());
948
        } else 
949
#endif /* defined(__linux__) */
950
        {
951
        use_itimer:
952
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
953
                                   PIT_FREQ) / 1000000;
954
        }
955
    }
956
#endif
957
}
958

    
959
void quit_timers(void)
960
{
961
#ifdef _WIN32
962
    timeKillEvent(timerID);
963
#endif
964
}
965

    
966
/***********************************************************/
967
/* character device */
968

    
969
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
970
{
971
    return s->chr_write(s, buf, len);
972
}
973

    
974
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
975
{
976
    char buf[4096];
977
    va_list ap;
978
    va_start(ap, fmt);
979
    vsnprintf(buf, sizeof(buf), fmt, ap);
980
    qemu_chr_write(s, buf, strlen(buf));
981
    va_end(ap);
982
}
983

    
984
void qemu_chr_send_event(CharDriverState *s, int event)
985
{
986
    if (s->chr_send_event)
987
        s->chr_send_event(s, event);
988
}
989

    
990
void qemu_chr_add_read_handler(CharDriverState *s, 
991
                               IOCanRWHandler *fd_can_read, 
992
                               IOReadHandler *fd_read, void *opaque)
993
{
994
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
995
}
996
             
997
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
998
{
999
    s->chr_event = chr_event;
1000
}
1001

    
1002
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1003
{
1004
    return len;
1005
}
1006

    
1007
static void null_chr_add_read_handler(CharDriverState *chr, 
1008
                                    IOCanRWHandler *fd_can_read, 
1009
                                    IOReadHandler *fd_read, void *opaque)
1010
{
1011
}
1012

    
1013
CharDriverState *qemu_chr_open_null(void)
1014
{
1015
    CharDriverState *chr;
1016

    
1017
    chr = qemu_mallocz(sizeof(CharDriverState));
1018
    if (!chr)
1019
        return NULL;
1020
    chr->chr_write = null_chr_write;
1021
    chr->chr_add_read_handler = null_chr_add_read_handler;
1022
    return chr;
1023
}
1024

    
1025
#ifndef _WIN32
1026

    
1027
typedef struct {
1028
    int fd_in, fd_out;
1029
    /* for nographic stdio only */
1030
    IOCanRWHandler *fd_can_read; 
1031
    IOReadHandler *fd_read;
1032
    void *fd_opaque;
1033
} FDCharDriver;
1034

    
1035
#define STDIO_MAX_CLIENTS 2
1036

    
1037
static int stdio_nb_clients;
1038
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1039

    
1040
static int unix_write(int fd, const uint8_t *buf, int len1)
1041
{
1042
    int ret, len;
1043

    
1044
    len = len1;
1045
    while (len > 0) {
1046
        ret = write(fd, buf, len);
1047
        if (ret < 0) {
1048
            if (errno != EINTR && errno != EAGAIN)
1049
                return -1;
1050
        } else if (ret == 0) {
1051
            break;
1052
        } else {
1053
            buf += ret;
1054
            len -= ret;
1055
        }
1056
    }
1057
    return len1 - len;
1058
}
1059

    
1060
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1061
{
1062
    FDCharDriver *s = chr->opaque;
1063
    return unix_write(s->fd_out, buf, len);
1064
}
1065

    
1066
static void fd_chr_add_read_handler(CharDriverState *chr, 
1067
                                    IOCanRWHandler *fd_can_read, 
1068
                                    IOReadHandler *fd_read, void *opaque)
1069
{
1070
    FDCharDriver *s = chr->opaque;
1071

    
1072
    if (nographic && s->fd_in == 0) {
1073
        s->fd_can_read = fd_can_read;
1074
        s->fd_read = fd_read;
1075
        s->fd_opaque = opaque;
1076
    } else {
1077
        qemu_add_fd_read_handler(s->fd_in, fd_can_read, fd_read, opaque);
1078
    }
1079
}
1080

    
1081
/* open a character device to a unix fd */
1082
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1083
{
1084
    CharDriverState *chr;
1085
    FDCharDriver *s;
1086

    
1087
    chr = qemu_mallocz(sizeof(CharDriverState));
1088
    if (!chr)
1089
        return NULL;
1090
    s = qemu_mallocz(sizeof(FDCharDriver));
1091
    if (!s) {
1092
        free(chr);
1093
        return NULL;
1094
    }
1095
    s->fd_in = fd_in;
1096
    s->fd_out = fd_out;
1097
    chr->opaque = s;
1098
    chr->chr_write = fd_chr_write;
1099
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1100
    return chr;
1101
}
1102

    
1103
/* for STDIO, we handle the case where several clients use it
1104
   (nographic mode) */
1105

    
1106
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1107

    
1108
static int term_got_escape, client_index;
1109

    
1110
void term_print_help(void)
1111
{
1112
    printf("\n"
1113
           "C-a h    print this help\n"
1114
           "C-a x    exit emulator\n"
1115
           "C-a s    save disk data back to file (if -snapshot)\n"
1116
           "C-a b    send break (magic sysrq)\n"
1117
           "C-a c    switch between console and monitor\n"
1118
           "C-a C-a  send C-a\n"
1119
           );
1120
}
1121

    
1122
/* called when a char is received */
1123
static void stdio_received_byte(int ch)
1124
{
1125
    if (term_got_escape) {
1126
        term_got_escape = 0;
1127
        switch(ch) {
1128
        case 'h':
1129
            term_print_help();
1130
            break;
1131
        case 'x':
1132
            exit(0);
1133
            break;
1134
        case 's': 
1135
            {
1136
                int i;
1137
                for (i = 0; i < MAX_DISKS; i++) {
1138
                    if (bs_table[i])
1139
                        bdrv_commit(bs_table[i]);
1140
                }
1141
            }
1142
            break;
1143
        case 'b':
1144
            if (client_index < stdio_nb_clients) {
1145
                CharDriverState *chr;
1146
                FDCharDriver *s;
1147

    
1148
                chr = stdio_clients[client_index];
1149
                s = chr->opaque;
1150
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1151
            }
1152
            break;
1153
        case 'c':
1154
            client_index++;
1155
            if (client_index >= stdio_nb_clients)
1156
                client_index = 0;
1157
            if (client_index == 0) {
1158
                /* send a new line in the monitor to get the prompt */
1159
                ch = '\r';
1160
                goto send_char;
1161
            }
1162
            break;
1163
        case TERM_ESCAPE:
1164
            goto send_char;
1165
        }
1166
    } else if (ch == TERM_ESCAPE) {
1167
        term_got_escape = 1;
1168
    } else {
1169
    send_char:
1170
        if (client_index < stdio_nb_clients) {
1171
            uint8_t buf[1];
1172
            CharDriverState *chr;
1173
            FDCharDriver *s;
1174
            
1175
            chr = stdio_clients[client_index];
1176
            s = chr->opaque;
1177
            buf[0] = ch;
1178
            /* XXX: should queue the char if the device is not
1179
               ready */
1180
            if (s->fd_can_read(s->fd_opaque) > 0) 
1181
                s->fd_read(s->fd_opaque, buf, 1);
1182
        }
1183
    }
1184
}
1185

    
1186
static int stdio_can_read(void *opaque)
1187
{
1188
    /* XXX: not strictly correct */
1189
    return 1;
1190
}
1191

    
1192
static void stdio_read(void *opaque, const uint8_t *buf, int size)
1193
{
1194
    int i;
1195
    for(i = 0; i < size; i++)
1196
        stdio_received_byte(buf[i]);
1197
}
1198

    
1199
/* init terminal so that we can grab keys */
1200
static struct termios oldtty;
1201
static int old_fd0_flags;
1202

    
1203
static void term_exit(void)
1204
{
1205
    tcsetattr (0, TCSANOW, &oldtty);
1206
    fcntl(0, F_SETFL, old_fd0_flags);
1207
}
1208

    
1209
static void term_init(void)
1210
{
1211
    struct termios tty;
1212

    
1213
    tcgetattr (0, &tty);
1214
    oldtty = tty;
1215
    old_fd0_flags = fcntl(0, F_GETFL);
1216

    
1217
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1218
                          |INLCR|IGNCR|ICRNL|IXON);
1219
    tty.c_oflag |= OPOST;
1220
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1221
    /* if graphical mode, we allow Ctrl-C handling */
1222
    if (nographic)
1223
        tty.c_lflag &= ~ISIG;
1224
    tty.c_cflag &= ~(CSIZE|PARENB);
1225
    tty.c_cflag |= CS8;
1226
    tty.c_cc[VMIN] = 1;
1227
    tty.c_cc[VTIME] = 0;
1228
    
1229
    tcsetattr (0, TCSANOW, &tty);
1230

    
1231
    atexit(term_exit);
1232

    
1233
    fcntl(0, F_SETFL, O_NONBLOCK);
1234
}
1235

    
1236
CharDriverState *qemu_chr_open_stdio(void)
1237
{
1238
    CharDriverState *chr;
1239

    
1240
    if (nographic) {
1241
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1242
            return NULL;
1243
        chr = qemu_chr_open_fd(0, 1);
1244
        if (stdio_nb_clients == 0)
1245
            qemu_add_fd_read_handler(0, stdio_can_read, stdio_read, NULL);
1246
        client_index = stdio_nb_clients;
1247
    } else {
1248
        if (stdio_nb_clients != 0)
1249
            return NULL;
1250
        chr = qemu_chr_open_fd(0, 1);
1251
    }
1252
    stdio_clients[stdio_nb_clients++] = chr;
1253
    if (stdio_nb_clients == 1) {
1254
        /* set the terminal in raw mode */
1255
        term_init();
1256
    }
1257
    return chr;
1258
}
1259

    
1260
#if defined(__linux__)
1261
CharDriverState *qemu_chr_open_pty(void)
1262
{
1263
    char slave_name[1024];
1264
    int master_fd, slave_fd;
1265
    
1266
    /* Not satisfying */
1267
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1268
        return NULL;
1269
    }
1270
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1271
    return qemu_chr_open_fd(master_fd, master_fd);
1272
}
1273
#else
1274
CharDriverState *qemu_chr_open_pty(void)
1275
{
1276
    return NULL;
1277
}
1278
#endif
1279

    
1280
#endif /* !defined(_WIN32) */
1281

    
1282
CharDriverState *qemu_chr_open(const char *filename)
1283
{
1284
    if (!strcmp(filename, "vc")) {
1285
        return text_console_init(&display_state);
1286
    } else if (!strcmp(filename, "null")) {
1287
        return qemu_chr_open_null();
1288
    } else 
1289
#ifndef _WIN32
1290
    if (!strcmp(filename, "pty")) {
1291
        return qemu_chr_open_pty();
1292
    } else if (!strcmp(filename, "stdio")) {
1293
        return qemu_chr_open_stdio();
1294
    } else 
1295
#endif
1296
    {
1297
        return NULL;
1298
    }
1299
}
1300

    
1301
/***********************************************************/
1302
/* Linux network device redirectors */
1303

    
1304
void hex_dump(FILE *f, const uint8_t *buf, int size)
1305
{
1306
    int len, i, j, c;
1307

    
1308
    for(i=0;i<size;i+=16) {
1309
        len = size - i;
1310
        if (len > 16)
1311
            len = 16;
1312
        fprintf(f, "%08x ", i);
1313
        for(j=0;j<16;j++) {
1314
            if (j < len)
1315
                fprintf(f, " %02x", buf[i+j]);
1316
            else
1317
                fprintf(f, "   ");
1318
        }
1319
        fprintf(f, " ");
1320
        for(j=0;j<len;j++) {
1321
            c = buf[i+j];
1322
            if (c < ' ' || c > '~')
1323
                c = '.';
1324
            fprintf(f, "%c", c);
1325
        }
1326
        fprintf(f, "\n");
1327
    }
1328
}
1329

    
1330
void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1331
{
1332
    nd->send_packet(nd, buf, size);
1333
}
1334

    
1335
void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
1336
                          IOReadHandler *fd_read, void *opaque)
1337
{
1338
    nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
1339
}
1340

    
1341
/* dummy network adapter */
1342

    
1343
static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1344
{
1345
}
1346

    
1347
static void dummy_add_read_packet(NetDriverState *nd, 
1348
                                  IOCanRWHandler *fd_can_read, 
1349
                                  IOReadHandler *fd_read, void *opaque)
1350
{
1351
}
1352

    
1353
static int net_dummy_init(NetDriverState *nd)
1354
{
1355
    nd->send_packet = dummy_send_packet;
1356
    nd->add_read_packet = dummy_add_read_packet;
1357
    pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
1358
    return 0;
1359
}
1360

    
1361
#if defined(CONFIG_SLIRP)
1362

    
1363
/* slirp network adapter */
1364

    
1365
static void *slirp_fd_opaque;
1366
static IOCanRWHandler *slirp_fd_can_read;
1367
static IOReadHandler *slirp_fd_read;
1368
static int slirp_inited;
1369

    
1370
int slirp_can_output(void)
1371
{
1372
    return slirp_fd_can_read(slirp_fd_opaque);
1373
}
1374

    
1375
void slirp_output(const uint8_t *pkt, int pkt_len)
1376
{
1377
#if 0
1378
    printf("output:\n");
1379
    hex_dump(stdout, pkt, pkt_len);
1380
#endif
1381
    slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
1382
}
1383

    
1384
static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1385
{
1386
#if 0
1387
    printf("input:\n");
1388
    hex_dump(stdout, buf, size);
1389
#endif
1390
    slirp_input(buf, size);
1391
}
1392

    
1393
static void slirp_add_read_packet(NetDriverState *nd, 
1394
                                  IOCanRWHandler *fd_can_read, 
1395
                                  IOReadHandler *fd_read, void *opaque)
1396
{
1397
    slirp_fd_opaque = opaque;
1398
    slirp_fd_can_read = fd_can_read;
1399
    slirp_fd_read = fd_read;
1400
}
1401

    
1402
static int net_slirp_init(NetDriverState *nd)
1403
{
1404
    if (!slirp_inited) {
1405
        slirp_inited = 1;
1406
        slirp_init();
1407
    }
1408
    nd->send_packet = slirp_send_packet;
1409
    nd->add_read_packet = slirp_add_read_packet;
1410
    pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1411
    return 0;
1412
}
1413

    
1414
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1415
{
1416
    const char *p, *p1;
1417
    int len;
1418
    p = *pp;
1419
    p1 = strchr(p, sep);
1420
    if (!p1)
1421
        return -1;
1422
    len = p1 - p;
1423
    p1++;
1424
    if (buf_size > 0) {
1425
        if (len > buf_size - 1)
1426
            len = buf_size - 1;
1427
        memcpy(buf, p, len);
1428
        buf[len] = '\0';
1429
    }
1430
    *pp = p1;
1431
    return 0;
1432
}
1433

    
1434
static void net_slirp_redir(const char *redir_str)
1435
{
1436
    int is_udp;
1437
    char buf[256], *r;
1438
    const char *p;
1439
    struct in_addr guest_addr;
1440
    int host_port, guest_port;
1441
    
1442
    if (!slirp_inited) {
1443
        slirp_inited = 1;
1444
        slirp_init();
1445
    }
1446

    
1447
    p = redir_str;
1448
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1449
        goto fail;
1450
    if (!strcmp(buf, "tcp")) {
1451
        is_udp = 0;
1452
    } else if (!strcmp(buf, "udp")) {
1453
        is_udp = 1;
1454
    } else {
1455
        goto fail;
1456
    }
1457

    
1458
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1459
        goto fail;
1460
    host_port = strtol(buf, &r, 0);
1461
    if (r == buf)
1462
        goto fail;
1463

    
1464
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1465
        goto fail;
1466
    if (buf[0] == '\0') {
1467
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
1468
    }
1469
    if (!inet_aton(buf, &guest_addr))
1470
        goto fail;
1471
    
1472
    guest_port = strtol(p, &r, 0);
1473
    if (r == p)
1474
        goto fail;
1475
    
1476
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1477
        fprintf(stderr, "qemu: could not set up redirection\n");
1478
        exit(1);
1479
    }
1480
    return;
1481
 fail:
1482
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1483
    exit(1);
1484
}
1485
    
1486
#ifndef _WIN32
1487

    
1488
char smb_dir[1024];
1489

    
1490
static void smb_exit(void)
1491
{
1492
    DIR *d;
1493
    struct dirent *de;
1494
    char filename[1024];
1495

    
1496
    /* erase all the files in the directory */
1497
    d = opendir(smb_dir);
1498
    for(;;) {
1499
        de = readdir(d);
1500
        if (!de)
1501
            break;
1502
        if (strcmp(de->d_name, ".") != 0 &&
1503
            strcmp(de->d_name, "..") != 0) {
1504
            snprintf(filename, sizeof(filename), "%s/%s", 
1505
                     smb_dir, de->d_name);
1506
            unlink(filename);
1507
        }
1508
    }
1509
    closedir(d);
1510
    rmdir(smb_dir);
1511
}
1512

    
1513
/* automatic user mode samba server configuration */
1514
void net_slirp_smb(const char *exported_dir)
1515
{
1516
    char smb_conf[1024];
1517
    char smb_cmdline[1024];
1518
    FILE *f;
1519

    
1520
    if (!slirp_inited) {
1521
        slirp_inited = 1;
1522
        slirp_init();
1523
    }
1524

    
1525
    /* XXX: better tmp dir construction */
1526
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1527
    if (mkdir(smb_dir, 0700) < 0) {
1528
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1529
        exit(1);
1530
    }
1531
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1532
    
1533
    f = fopen(smb_conf, "w");
1534
    if (!f) {
1535
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1536
        exit(1);
1537
    }
1538
    fprintf(f, 
1539
            "[global]\n"
1540
            "pid directory=%s\n"
1541
            "lock directory=%s\n"
1542
            "log file=%s/log.smbd\n"
1543
            "smb passwd file=%s/smbpasswd\n"
1544
            "security = share\n"
1545
            "[qemu]\n"
1546
            "path=%s\n"
1547
            "read only=no\n"
1548
            "guest ok=yes\n",
1549
            smb_dir,
1550
            smb_dir,
1551
            smb_dir,
1552
            smb_dir,
1553
            exported_dir
1554
            );
1555
    fclose(f);
1556
    atexit(smb_exit);
1557

    
1558
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1559
             smb_conf);
1560
    
1561
    slirp_add_exec(0, smb_cmdline, 4, 139);
1562
}
1563

    
1564
#endif /* !defined(_WIN32) */
1565

    
1566
#endif /* CONFIG_SLIRP */
1567

    
1568
#if !defined(_WIN32)
1569
#ifdef _BSD
1570
static int tun_open(char *ifname, int ifname_size)
1571
{
1572
    int fd;
1573
    char *dev;
1574
    struct stat s;
1575

    
1576
    fd = open("/dev/tap", O_RDWR);
1577
    if (fd < 0) {
1578
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1579
        return -1;
1580
    }
1581

    
1582
    fstat(fd, &s);
1583
    dev = devname(s.st_rdev, S_IFCHR);
1584
    pstrcpy(ifname, ifname_size, dev);
1585

    
1586
    fcntl(fd, F_SETFL, O_NONBLOCK);
1587
    return fd;
1588
}
1589
#else
1590
static int tun_open(char *ifname, int ifname_size)
1591
{
1592
    struct ifreq ifr;
1593
    int fd, ret;
1594
    
1595
    fd = open("/dev/net/tun", O_RDWR);
1596
    if (fd < 0) {
1597
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1598
        return -1;
1599
    }
1600
    memset(&ifr, 0, sizeof(ifr));
1601
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1602
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1603
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1604
    if (ret != 0) {
1605
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1606
        close(fd);
1607
        return -1;
1608
    }
1609
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
1610
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
1611
    fcntl(fd, F_SETFL, O_NONBLOCK);
1612
    return fd;
1613
}
1614
#endif
1615

    
1616
static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1617
{
1618
    write(nd->fd, buf, size);
1619
}
1620

    
1621
static void tun_add_read_packet(NetDriverState *nd, 
1622
                                IOCanRWHandler *fd_can_read, 
1623
                                IOReadHandler *fd_read, void *opaque)
1624
{
1625
    qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1626
}
1627

    
1628
static int net_tun_init(NetDriverState *nd)
1629
{
1630
    int pid, status;
1631
    char *args[3];
1632
    char **parg;
1633

    
1634
    nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1635
    if (nd->fd < 0)
1636
        return -1;
1637

    
1638
    /* try to launch network init script */
1639
    pid = fork();
1640
    if (pid >= 0) {
1641
        if (pid == 0) {
1642
            parg = args;
1643
            *parg++ = network_script;
1644
            *parg++ = nd->ifname;
1645
            *parg++ = NULL;
1646
            execv(network_script, args);
1647
            exit(1);
1648
        }
1649
        while (waitpid(pid, &status, 0) != pid);
1650
        if (!WIFEXITED(status) ||
1651
            WEXITSTATUS(status) != 0) {
1652
            fprintf(stderr, "%s: could not launch network script\n",
1653
                    network_script);
1654
        }
1655
    }
1656
    nd->send_packet = tun_send_packet;
1657
    nd->add_read_packet = tun_add_read_packet;
1658
    return 0;
1659
}
1660

    
1661
static int net_fd_init(NetDriverState *nd, int fd)
1662
{
1663
    nd->fd = fd;
1664
    nd->send_packet = tun_send_packet;
1665
    nd->add_read_packet = tun_add_read_packet;
1666
    pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1667
    return 0;
1668
}
1669

    
1670
#endif /* !_WIN32 */
1671

    
1672
/***********************************************************/
1673
/* pid file */
1674

    
1675
static char *pid_filename;
1676

    
1677
/* Remove PID file. Called on normal exit */
1678

    
1679
static void remove_pidfile(void) 
1680
{
1681
    unlink (pid_filename);
1682
}
1683

    
1684
static void create_pidfile(const char *filename)
1685
{
1686
    struct stat pidstat;
1687
    FILE *f;
1688

    
1689
    /* Try to write our PID to the named file */
1690
    if (stat(filename, &pidstat) < 0) {
1691
        if (errno == ENOENT) {
1692
            if ((f = fopen (filename, "w")) == NULL) {
1693
                perror("Opening pidfile");
1694
                exit(1);
1695
            }
1696
            fprintf(f, "%d\n", getpid());
1697
            fclose(f);
1698
            pid_filename = qemu_strdup(filename);
1699
            if (!pid_filename) {
1700
                fprintf(stderr, "Could not save PID filename");
1701
                exit(1);
1702
            }
1703
            atexit(remove_pidfile);
1704
        }
1705
    } else {
1706
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
1707
                filename);
1708
        exit(1);
1709
    }
1710
}
1711

    
1712
/***********************************************************/
1713
/* dumb display */
1714

    
1715
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1716
{
1717
}
1718

    
1719
static void dumb_resize(DisplayState *ds, int w, int h)
1720
{
1721
}
1722

    
1723
static void dumb_refresh(DisplayState *ds)
1724
{
1725
    vga_update_display();
1726
}
1727

    
1728
void dumb_display_init(DisplayState *ds)
1729
{
1730
    ds->data = NULL;
1731
    ds->linesize = 0;
1732
    ds->depth = 0;
1733
    ds->dpy_update = dumb_update;
1734
    ds->dpy_resize = dumb_resize;
1735
    ds->dpy_refresh = dumb_refresh;
1736
}
1737

    
1738
#if !defined(CONFIG_SOFTMMU)
1739
/***********************************************************/
1740
/* cpu signal handler */
1741
static void host_segv_handler(int host_signum, siginfo_t *info, 
1742
                              void *puc)
1743
{
1744
    if (cpu_signal_handler(host_signum, info, puc))
1745
        return;
1746
    if (stdio_nb_clients > 0)
1747
        term_exit();
1748
    abort();
1749
}
1750
#endif
1751

    
1752
/***********************************************************/
1753
/* I/O handling */
1754

    
1755
#define MAX_IO_HANDLERS 64
1756

    
1757
typedef struct IOHandlerRecord {
1758
    int fd;
1759
    IOCanRWHandler *fd_can_read;
1760
    IOReadHandler *fd_read;
1761
    void *opaque;
1762
    /* temporary data */
1763
    struct pollfd *ufd;
1764
    int max_size;
1765
    struct IOHandlerRecord *next;
1766
} IOHandlerRecord;
1767

    
1768
static IOHandlerRecord *first_io_handler;
1769

    
1770
int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1771
                             IOReadHandler *fd_read, void *opaque)
1772
{
1773
    IOHandlerRecord *ioh;
1774

    
1775
    ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1776
    if (!ioh)
1777
        return -1;
1778
    ioh->fd = fd;
1779
    ioh->fd_can_read = fd_can_read;
1780
    ioh->fd_read = fd_read;
1781
    ioh->opaque = opaque;
1782
    ioh->next = first_io_handler;
1783
    first_io_handler = ioh;
1784
    return 0;
1785
}
1786

    
1787
void qemu_del_fd_read_handler(int fd)
1788
{
1789
    IOHandlerRecord **pioh, *ioh;
1790

    
1791
    pioh = &first_io_handler;
1792
    for(;;) {
1793
        ioh = *pioh;
1794
        if (ioh == NULL)
1795
            break;
1796
        if (ioh->fd == fd) {
1797
            *pioh = ioh->next;
1798
            break;
1799
        }
1800
        pioh = &ioh->next;
1801
    }
1802
}
1803

    
1804
/***********************************************************/
1805
/* savevm/loadvm support */
1806

    
1807
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1808
{
1809
    fwrite(buf, 1, size, f);
1810
}
1811

    
1812
void qemu_put_byte(QEMUFile *f, int v)
1813
{
1814
    fputc(v, f);
1815
}
1816

    
1817
void qemu_put_be16(QEMUFile *f, unsigned int v)
1818
{
1819
    qemu_put_byte(f, v >> 8);
1820
    qemu_put_byte(f, v);
1821
}
1822

    
1823
void qemu_put_be32(QEMUFile *f, unsigned int v)
1824
{
1825
    qemu_put_byte(f, v >> 24);
1826
    qemu_put_byte(f, v >> 16);
1827
    qemu_put_byte(f, v >> 8);
1828
    qemu_put_byte(f, v);
1829
}
1830

    
1831
void qemu_put_be64(QEMUFile *f, uint64_t v)
1832
{
1833
    qemu_put_be32(f, v >> 32);
1834
    qemu_put_be32(f, v);
1835
}
1836

    
1837
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1838
{
1839
    return fread(buf, 1, size, f);
1840
}
1841

    
1842
int qemu_get_byte(QEMUFile *f)
1843
{
1844
    int v;
1845
    v = fgetc(f);
1846
    if (v == EOF)
1847
        return 0;
1848
    else
1849
        return v;
1850
}
1851

    
1852
unsigned int qemu_get_be16(QEMUFile *f)
1853
{
1854
    unsigned int v;
1855
    v = qemu_get_byte(f) << 8;
1856
    v |= qemu_get_byte(f);
1857
    return v;
1858
}
1859

    
1860
unsigned int qemu_get_be32(QEMUFile *f)
1861
{
1862
    unsigned int v;
1863
    v = qemu_get_byte(f) << 24;
1864
    v |= qemu_get_byte(f) << 16;
1865
    v |= qemu_get_byte(f) << 8;
1866
    v |= qemu_get_byte(f);
1867
    return v;
1868
}
1869

    
1870
uint64_t qemu_get_be64(QEMUFile *f)
1871
{
1872
    uint64_t v;
1873
    v = (uint64_t)qemu_get_be32(f) << 32;
1874
    v |= qemu_get_be32(f);
1875
    return v;
1876
}
1877

    
1878
int64_t qemu_ftell(QEMUFile *f)
1879
{
1880
    return ftell(f);
1881
}
1882

    
1883
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1884
{
1885
    if (fseek(f, pos, whence) < 0)
1886
        return -1;
1887
    return ftell(f);
1888
}
1889

    
1890
typedef struct SaveStateEntry {
1891
    char idstr[256];
1892
    int instance_id;
1893
    int version_id;
1894
    SaveStateHandler *save_state;
1895
    LoadStateHandler *load_state;
1896
    void *opaque;
1897
    struct SaveStateEntry *next;
1898
} SaveStateEntry;
1899

    
1900
static SaveStateEntry *first_se;
1901

    
1902
int register_savevm(const char *idstr, 
1903
                    int instance_id, 
1904
                    int version_id,
1905
                    SaveStateHandler *save_state,
1906
                    LoadStateHandler *load_state,
1907
                    void *opaque)
1908
{
1909
    SaveStateEntry *se, **pse;
1910

    
1911
    se = qemu_malloc(sizeof(SaveStateEntry));
1912
    if (!se)
1913
        return -1;
1914
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1915
    se->instance_id = instance_id;
1916
    se->version_id = version_id;
1917
    se->save_state = save_state;
1918
    se->load_state = load_state;
1919
    se->opaque = opaque;
1920
    se->next = NULL;
1921

    
1922
    /* add at the end of list */
1923
    pse = &first_se;
1924
    while (*pse != NULL)
1925
        pse = &(*pse)->next;
1926
    *pse = se;
1927
    return 0;
1928
}
1929

    
1930
#define QEMU_VM_FILE_MAGIC   0x5145564d
1931
#define QEMU_VM_FILE_VERSION 0x00000001
1932

    
1933
int qemu_savevm(const char *filename)
1934
{
1935
    SaveStateEntry *se;
1936
    QEMUFile *f;
1937
    int len, len_pos, cur_pos, saved_vm_running, ret;
1938

    
1939
    saved_vm_running = vm_running;
1940
    vm_stop(0);
1941

    
1942
    f = fopen(filename, "wb");
1943
    if (!f) {
1944
        ret = -1;
1945
        goto the_end;
1946
    }
1947

    
1948
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1949
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1950

    
1951
    for(se = first_se; se != NULL; se = se->next) {
1952
        /* ID string */
1953
        len = strlen(se->idstr);
1954
        qemu_put_byte(f, len);
1955
        qemu_put_buffer(f, se->idstr, len);
1956

    
1957
        qemu_put_be32(f, se->instance_id);
1958
        qemu_put_be32(f, se->version_id);
1959

    
1960
        /* record size: filled later */
1961
        len_pos = ftell(f);
1962
        qemu_put_be32(f, 0);
1963
        
1964
        se->save_state(f, se->opaque);
1965

    
1966
        /* fill record size */
1967
        cur_pos = ftell(f);
1968
        len = ftell(f) - len_pos - 4;
1969
        fseek(f, len_pos, SEEK_SET);
1970
        qemu_put_be32(f, len);
1971
        fseek(f, cur_pos, SEEK_SET);
1972
    }
1973

    
1974
    fclose(f);
1975
    ret = 0;
1976
 the_end:
1977
    if (saved_vm_running)
1978
        vm_start();
1979
    return ret;
1980
}
1981

    
1982
static SaveStateEntry *find_se(const char *idstr, int instance_id)
1983
{
1984
    SaveStateEntry *se;
1985

    
1986
    for(se = first_se; se != NULL; se = se->next) {
1987
        if (!strcmp(se->idstr, idstr) && 
1988
            instance_id == se->instance_id)
1989
            return se;
1990
    }
1991
    return NULL;
1992
}
1993

    
1994
int qemu_loadvm(const char *filename)
1995
{
1996
    SaveStateEntry *se;
1997
    QEMUFile *f;
1998
    int len, cur_pos, ret, instance_id, record_len, version_id;
1999
    int saved_vm_running;
2000
    unsigned int v;
2001
    char idstr[256];
2002
    
2003
    saved_vm_running = vm_running;
2004
    vm_stop(0);
2005

    
2006
    f = fopen(filename, "rb");
2007
    if (!f) {
2008
        ret = -1;
2009
        goto the_end;
2010
    }
2011

    
2012
    v = qemu_get_be32(f);
2013
    if (v != QEMU_VM_FILE_MAGIC)
2014
        goto fail;
2015
    v = qemu_get_be32(f);
2016
    if (v != QEMU_VM_FILE_VERSION) {
2017
    fail:
2018
        fclose(f);
2019
        ret = -1;
2020
        goto the_end;
2021
    }
2022
    for(;;) {
2023
#if defined (DO_TB_FLUSH)
2024
        tb_flush(global_env);
2025
#endif
2026
        len = qemu_get_byte(f);
2027
        if (feof(f))
2028
            break;
2029
        qemu_get_buffer(f, idstr, len);
2030
        idstr[len] = '\0';
2031
        instance_id = qemu_get_be32(f);
2032
        version_id = qemu_get_be32(f);
2033
        record_len = qemu_get_be32(f);
2034
#if 0
2035
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
2036
               idstr, instance_id, version_id, record_len);
2037
#endif
2038
        cur_pos = ftell(f);
2039
        se = find_se(idstr, instance_id);
2040
        if (!se) {
2041
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
2042
                    instance_id, idstr);
2043
        } else {
2044
            ret = se->load_state(f, se->opaque, version_id);
2045
            if (ret < 0) {
2046
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
2047
                        instance_id, idstr);
2048
            }
2049
        }
2050
        /* always seek to exact end of record */
2051
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
2052
    }
2053
    fclose(f);
2054
    ret = 0;
2055
 the_end:
2056
    if (saved_vm_running)
2057
        vm_start();
2058
    return ret;
2059
}
2060

    
2061
/***********************************************************/
2062
/* cpu save/restore */
2063

    
2064
#if defined(TARGET_I386)
2065

    
2066
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
2067
{
2068
    qemu_put_be32(f, dt->selector);
2069
    qemu_put_betl(f, dt->base);
2070
    qemu_put_be32(f, dt->limit);
2071
    qemu_put_be32(f, dt->flags);
2072
}
2073

    
2074
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
2075
{
2076
    dt->selector = qemu_get_be32(f);
2077
    dt->base = qemu_get_betl(f);
2078
    dt->limit = qemu_get_be32(f);
2079
    dt->flags = qemu_get_be32(f);
2080
}
2081

    
2082
void cpu_save(QEMUFile *f, void *opaque)
2083
{
2084
    CPUState *env = opaque;
2085
    uint16_t fptag, fpus, fpuc;
2086
    uint32_t hflags;
2087
    int i;
2088

    
2089
    for(i = 0; i < CPU_NB_REGS; i++)
2090
        qemu_put_betls(f, &env->regs[i]);
2091
    qemu_put_betls(f, &env->eip);
2092
    qemu_put_betls(f, &env->eflags);
2093
    qemu_put_betl(f, 0); /* XXX: suppress that */
2094
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
2095
    qemu_put_be32s(f, &hflags);
2096
    
2097
    /* FPU */
2098
    fpuc = env->fpuc;
2099
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
2100
    fptag = 0;
2101
    for (i=7; i>=0; i--) {
2102
        fptag <<= 2;
2103
        if (env->fptags[i]) {
2104
            fptag |= 3;
2105
        }
2106
    }
2107
    
2108
    qemu_put_be16s(f, &fpuc);
2109
    qemu_put_be16s(f, &fpus);
2110
    qemu_put_be16s(f, &fptag);
2111

    
2112
    for(i = 0; i < 8; i++) {
2113
        uint64_t mant;
2114
        uint16_t exp;
2115
        cpu_get_fp80(&mant, &exp, env->fpregs[i]);
2116
        qemu_put_be64(f, mant);
2117
        qemu_put_be16(f, exp);
2118
    }
2119

    
2120
    for(i = 0; i < 6; i++)
2121
        cpu_put_seg(f, &env->segs[i]);
2122
    cpu_put_seg(f, &env->ldt);
2123
    cpu_put_seg(f, &env->tr);
2124
    cpu_put_seg(f, &env->gdt);
2125
    cpu_put_seg(f, &env->idt);
2126
    
2127
    qemu_put_be32s(f, &env->sysenter_cs);
2128
    qemu_put_be32s(f, &env->sysenter_esp);
2129
    qemu_put_be32s(f, &env->sysenter_eip);
2130
    
2131
    qemu_put_betls(f, &env->cr[0]);
2132
    qemu_put_betls(f, &env->cr[2]);
2133
    qemu_put_betls(f, &env->cr[3]);
2134
    qemu_put_betls(f, &env->cr[4]);
2135
    
2136
    for(i = 0; i < 8; i++)
2137
        qemu_put_betls(f, &env->dr[i]);
2138

    
2139
    /* MMU */
2140
    qemu_put_be32s(f, &env->a20_mask);
2141

    
2142
#ifdef TARGET_X86_64
2143
    for(i = 0; i < CPU_NB_REGS; i++) {
2144
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2145
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2146
    }
2147

    
2148
    qemu_put_be64s(f, &env->efer);
2149
    qemu_put_be64s(f, &env->star);
2150
    qemu_put_be64s(f, &env->lstar);
2151
    qemu_put_be64s(f, &env->cstar);
2152
    qemu_put_be64s(f, &env->fmask);
2153
    qemu_put_be64s(f, &env->kernelgsbase);
2154
#endif
2155
}
2156

    
2157
int cpu_load(QEMUFile *f, void *opaque, int version_id)
2158
{
2159
    CPUState *env = opaque;
2160
    int i;
2161
    uint32_t hflags;
2162
    uint16_t fpus, fpuc, fptag;
2163

    
2164
    if (version_id != 2)
2165
        return -EINVAL;
2166
    for(i = 0; i < CPU_NB_REGS; i++)
2167
        qemu_get_betls(f, &env->regs[i]);
2168
    qemu_get_betls(f, &env->eip);
2169
    qemu_get_betls(f, &env->eflags);
2170
    qemu_get_betl(f); /* XXX: suppress that */
2171
    qemu_get_be32s(f, &hflags);
2172

    
2173
    qemu_get_be16s(f, &fpuc);
2174
    qemu_get_be16s(f, &fpus);
2175
    qemu_get_be16s(f, &fptag);
2176

    
2177
    for(i = 0; i < 8; i++) {
2178
        uint64_t mant;
2179
        uint16_t exp;
2180
        mant = qemu_get_be64(f);
2181
        exp = qemu_get_be16(f);
2182
        env->fpregs[i] = cpu_set_fp80(mant, exp);
2183
    }
2184

    
2185
    env->fpuc = fpuc;
2186
    env->fpstt = (fpus >> 11) & 7;
2187
    env->fpus = fpus & ~0x3800;
2188
    for(i = 0; i < 8; i++) {
2189
        env->fptags[i] = ((fptag & 3) == 3);
2190
        fptag >>= 2;
2191
    }
2192
    
2193
    for(i = 0; i < 6; i++)
2194
        cpu_get_seg(f, &env->segs[i]);
2195
    cpu_get_seg(f, &env->ldt);
2196
    cpu_get_seg(f, &env->tr);
2197
    cpu_get_seg(f, &env->gdt);
2198
    cpu_get_seg(f, &env->idt);
2199
    
2200
    qemu_get_be32s(f, &env->sysenter_cs);
2201
    qemu_get_be32s(f, &env->sysenter_esp);
2202
    qemu_get_be32s(f, &env->sysenter_eip);
2203
    
2204
    qemu_get_betls(f, &env->cr[0]);
2205
    qemu_get_betls(f, &env->cr[2]);
2206
    qemu_get_betls(f, &env->cr[3]);
2207
    qemu_get_betls(f, &env->cr[4]);
2208
    
2209
    for(i = 0; i < 8; i++)
2210
        qemu_get_betls(f, &env->dr[i]);
2211

    
2212
    /* MMU */
2213
    qemu_get_be32s(f, &env->a20_mask);
2214

    
2215
#ifdef TARGET_X86_64
2216
    for(i = 0; i < CPU_NB_REGS; i++) {
2217
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
2218
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
2219
    }
2220

    
2221
    qemu_get_be64s(f, &env->efer);
2222
    qemu_get_be64s(f, &env->star);
2223
    qemu_get_be64s(f, &env->lstar);
2224
    qemu_get_be64s(f, &env->cstar);
2225
    qemu_get_be64s(f, &env->fmask);
2226
    qemu_get_be64s(f, &env->kernelgsbase);
2227
#endif
2228

    
2229
    /* XXX: compute hflags from scratch, except for CPL and IIF */
2230
    env->hflags = hflags;
2231
    tlb_flush(env, 1);
2232
    return 0;
2233
}
2234

    
2235
#elif defined(TARGET_PPC)
2236
void cpu_save(QEMUFile *f, void *opaque)
2237
{
2238
}
2239

    
2240
int cpu_load(QEMUFile *f, void *opaque, int version_id)
2241
{
2242
    return 0;
2243
}
2244
#elif defined(TARGET_SPARC)
2245
void cpu_save(QEMUFile *f, void *opaque)
2246
{
2247
    CPUState *env = opaque;
2248
    int i;
2249
    uint32_t tmp;
2250

    
2251
    for(i = 1; i < 8; i++)
2252
        qemu_put_be32s(f, &env->gregs[i]);
2253
    tmp = env->regwptr - env->regbase;
2254
    qemu_put_be32s(f, &tmp);
2255
    for(i = 1; i < NWINDOWS * 16 + 8; i++)
2256
        qemu_put_be32s(f, &env->regbase[i]);
2257

    
2258
    /* FPU */
2259
    for(i = 0; i < 32; i++) {
2260
        uint64_t mant;
2261
        uint16_t exp;
2262
        cpu_get_fp64(&mant, &exp, env->fpr[i]);
2263
        qemu_put_be64(f, mant);
2264
        qemu_put_be16(f, exp);
2265
    }
2266
    qemu_put_be32s(f, &env->pc);
2267
    qemu_put_be32s(f, &env->npc);
2268
    qemu_put_be32s(f, &env->y);
2269
    tmp = GET_PSR(env);
2270
    qemu_put_be32s(f, &tmp);
2271
    qemu_put_be32s(f, &env->fsr);
2272
    qemu_put_be32s(f, &env->cwp);
2273
    qemu_put_be32s(f, &env->wim);
2274
    qemu_put_be32s(f, &env->tbr);
2275
    /* MMU */
2276
    for(i = 0; i < 16; i++)
2277
        qemu_put_be32s(f, &env->mmuregs[i]);
2278
}
2279

    
2280
int cpu_load(QEMUFile *f, void *opaque, int version_id)
2281
{
2282
    CPUState *env = opaque;
2283
    int i;
2284
    uint32_t tmp;
2285

    
2286
    for(i = 1; i < 8; i++)
2287
        qemu_get_be32s(f, &env->gregs[i]);
2288
    qemu_get_be32s(f, &tmp);
2289
    env->regwptr = env->regbase + tmp;
2290
    for(i = 1; i < NWINDOWS * 16 + 8; i++)
2291
        qemu_get_be32s(f, &env->regbase[i]);
2292

    
2293
    /* FPU */
2294
    for(i = 0; i < 32; i++) {
2295
        uint64_t mant;
2296
        uint16_t exp;
2297

    
2298
        qemu_get_be64s(f, &mant);
2299
        qemu_get_be16s(f, &exp);
2300
        env->fpr[i] = cpu_put_fp64(mant, exp);
2301
    }
2302
    qemu_get_be32s(f, &env->pc);
2303
    qemu_get_be32s(f, &env->npc);
2304
    qemu_get_be32s(f, &env->y);
2305
    qemu_get_be32s(f, &tmp);
2306
    PUT_PSR(env, tmp);
2307
    qemu_get_be32s(f, &env->fsr);
2308
    qemu_get_be32s(f, &env->cwp);
2309
    qemu_get_be32s(f, &env->wim);
2310
    qemu_get_be32s(f, &env->tbr);
2311
    /* MMU */
2312
    for(i = 0; i < 16; i++)
2313
        qemu_get_be32s(f, &env->mmuregs[i]);
2314
    tlb_flush(env, 1);
2315
    return 0;
2316
}
2317
#else
2318

    
2319
#warning No CPU save/restore functions
2320

    
2321
#endif
2322

    
2323
/***********************************************************/
2324
/* ram save/restore */
2325

    
2326
/* we just avoid storing empty pages */
2327
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
2328
{
2329
    int i, v;
2330

    
2331
    v = buf[0];
2332
    for(i = 1; i < len; i++) {
2333
        if (buf[i] != v)
2334
            goto normal_save;
2335
    }
2336
    qemu_put_byte(f, 1);
2337
    qemu_put_byte(f, v);
2338
    return;
2339
 normal_save:
2340
    qemu_put_byte(f, 0); 
2341
    qemu_put_buffer(f, buf, len);
2342
}
2343

    
2344
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2345
{
2346
    int v;
2347

    
2348
    v = qemu_get_byte(f);
2349
    switch(v) {
2350
    case 0:
2351
        if (qemu_get_buffer(f, buf, len) != len)
2352
            return -EIO;
2353
        break;
2354
    case 1:
2355
        v = qemu_get_byte(f);
2356
        memset(buf, v, len);
2357
        break;
2358
    default:
2359
        return -EINVAL;
2360
    }
2361
    return 0;
2362
}
2363

    
2364
static void ram_save(QEMUFile *f, void *opaque)
2365
{
2366
    int i;
2367
    qemu_put_be32(f, phys_ram_size);
2368
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2369
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2370
    }
2371
}
2372

    
2373
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2374
{
2375
    int i, ret;
2376

    
2377
    if (version_id != 1)
2378
        return -EINVAL;
2379
    if (qemu_get_be32(f) != phys_ram_size)
2380
        return -EINVAL;
2381
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2382
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2383
        if (ret)
2384
            return ret;
2385
    }
2386
    return 0;
2387
}
2388

    
2389
/***********************************************************/
2390
/* main execution loop */
2391

    
2392
void gui_update(void *opaque)
2393
{
2394
    display_state.dpy_refresh(&display_state);
2395
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
2396
}
2397

    
2398
/* XXX: support several handlers */
2399
VMStopHandler *vm_stop_cb;
2400
VMStopHandler *vm_stop_opaque;
2401

    
2402
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
2403
{
2404
    vm_stop_cb = cb;
2405
    vm_stop_opaque = opaque;
2406
    return 0;
2407
}
2408

    
2409
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
2410
{
2411
    vm_stop_cb = NULL;
2412
}
2413

    
2414
void vm_start(void)
2415
{
2416
    if (!vm_running) {
2417
        cpu_enable_ticks();
2418
        vm_running = 1;
2419
    }
2420
}
2421

    
2422
void vm_stop(int reason) 
2423
{
2424
    if (vm_running) {
2425
        cpu_disable_ticks();
2426
        vm_running = 0;
2427
        if (reason != 0) {
2428
            if (vm_stop_cb) {
2429
                vm_stop_cb(vm_stop_opaque, reason);
2430
            }
2431
        }
2432
    }
2433
}
2434

    
2435
/* reset/shutdown handler */
2436

    
2437
typedef struct QEMUResetEntry {
2438
    QEMUResetHandler *func;
2439
    void *opaque;
2440
    struct QEMUResetEntry *next;
2441
} QEMUResetEntry;
2442

    
2443
static QEMUResetEntry *first_reset_entry;
2444
static int reset_requested;
2445
static int shutdown_requested;
2446

    
2447
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2448
{
2449
    QEMUResetEntry **pre, *re;
2450

    
2451
    pre = &first_reset_entry;
2452
    while (*pre != NULL)
2453
        pre = &(*pre)->next;
2454
    re = qemu_mallocz(sizeof(QEMUResetEntry));
2455
    re->func = func;
2456
    re->opaque = opaque;
2457
    re->next = NULL;
2458
    *pre = re;
2459
}
2460

    
2461
void qemu_system_reset(void)
2462
{
2463
    QEMUResetEntry *re;
2464

    
2465
    /* reset all devices */
2466
    for(re = first_reset_entry; re != NULL; re = re->next) {
2467
        re->func(re->opaque);
2468
    }
2469
}
2470

    
2471
void qemu_system_reset_request(void)
2472
{
2473
    reset_requested = 1;
2474
    cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2475
}
2476

    
2477
void qemu_system_shutdown_request(void)
2478
{
2479
    shutdown_requested = 1;
2480
    cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
2481
}
2482

    
2483
static void main_cpu_reset(void *opaque)
2484
{
2485
#if defined(TARGET_I386) || defined(TARGET_SPARC)
2486
    CPUState *env = opaque;
2487
    cpu_reset(env);
2488
#endif
2489
}
2490

    
2491
void main_loop_wait(int timeout)
2492
{
2493
#ifndef _WIN32
2494
    struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
2495
    IOHandlerRecord *ioh, *ioh_next;
2496
    uint8_t buf[4096];
2497
    int n, max_size;
2498
#endif
2499
    int ret;
2500

    
2501
#ifdef _WIN32
2502
        if (timeout > 0)
2503
            Sleep(timeout);
2504
#else
2505
        /* poll any events */
2506
        /* XXX: separate device handlers from system ones */
2507
        pf = ufds;
2508
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2509
            if (!ioh->fd_can_read) {
2510
                max_size = 0;
2511
                pf->fd = ioh->fd;
2512
                pf->events = POLLIN;
2513
                ioh->ufd = pf;
2514
                pf++;
2515
            } else {
2516
                max_size = ioh->fd_can_read(ioh->opaque);
2517
                if (max_size > 0) {
2518
                    if (max_size > sizeof(buf))
2519
                        max_size = sizeof(buf);
2520
                    pf->fd = ioh->fd;
2521
                    pf->events = POLLIN;
2522
                    ioh->ufd = pf;
2523
                    pf++;
2524
                } else {
2525
                    ioh->ufd = NULL;
2526
                }
2527
            }
2528
            ioh->max_size = max_size;
2529
        }
2530
        
2531
        ret = poll(ufds, pf - ufds, timeout);
2532
        if (ret > 0) {
2533
            /* XXX: better handling of removal */
2534
            for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
2535
                ioh_next = ioh->next;
2536
                pf = ioh->ufd;
2537
                if (pf) {
2538
                    if (pf->revents & POLLIN) {
2539
                        if (ioh->max_size == 0) {
2540
                            /* just a read event */
2541
                            ioh->fd_read(ioh->opaque, NULL, 0);
2542
                        } else {
2543
                            n = read(ioh->fd, buf, ioh->max_size);
2544
                            if (n >= 0) {
2545
                                ioh->fd_read(ioh->opaque, buf, n);
2546
                            } else if (errno != EAGAIN) {
2547
                                ioh->fd_read(ioh->opaque, NULL, -errno);
2548
                            }
2549
                        }
2550
                    }
2551
                }
2552
            }
2553
        }
2554
#endif /* !defined(_WIN32) */
2555
#if defined(CONFIG_SLIRP)
2556
        /* XXX: merge with poll() */
2557
        if (slirp_inited) {
2558
            fd_set rfds, wfds, xfds;
2559
            int nfds;
2560
            struct timeval tv;
2561

    
2562
            nfds = -1;
2563
            FD_ZERO(&rfds);
2564
            FD_ZERO(&wfds);
2565
            FD_ZERO(&xfds);
2566
            slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2567
            tv.tv_sec = 0;
2568
            tv.tv_usec = 0;
2569
            ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2570
            if (ret >= 0) {
2571
                slirp_select_poll(&rfds, &wfds, &xfds);
2572
            }
2573
        }
2574
#endif
2575

    
2576
        if (vm_running) {
2577
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
2578
                            qemu_get_clock(vm_clock));
2579
            /* run dma transfers, if any */
2580
            DMA_run();
2581
        }
2582

    
2583
        /* real time timers */
2584
        qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
2585
                        qemu_get_clock(rt_clock));
2586
}
2587

    
2588
int main_loop(void)
2589
{
2590
    int ret, timeout;
2591
    CPUState *env = global_env;
2592

    
2593
    for(;;) {
2594
        if (vm_running) {
2595
            ret = cpu_exec(env);
2596
            if (shutdown_requested) {
2597
                ret = EXCP_INTERRUPT; 
2598
                break;
2599
            }
2600
            if (reset_requested) {
2601
                reset_requested = 0;
2602
                qemu_system_reset();
2603
                ret = EXCP_INTERRUPT; 
2604
            }
2605
            if (ret == EXCP_DEBUG) {
2606
                vm_stop(EXCP_DEBUG);
2607
            }
2608
            /* if hlt instruction, we wait until the next IRQ */
2609
            /* XXX: use timeout computed from timers */
2610
            if (ret == EXCP_HLT) 
2611
                timeout = 10;
2612
            else
2613
                timeout = 0;
2614
        } else {
2615
            timeout = 10;
2616
        }
2617
        main_loop_wait(timeout);
2618
    }
2619
    cpu_disable_ticks();
2620
    return ret;
2621
}
2622

    
2623
void help(void)
2624
{
2625
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
2626
           "usage: %s [options] [disk_image]\n"
2627
           "\n"
2628
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2629
           "\n"
2630
           "Standard options:\n"
2631
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
2632
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
2633
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
2634
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
2635
           "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
2636
           "-snapshot       write to temporary files instead of disk image files\n"
2637
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
2638
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
2639
#ifndef _WIN32
2640
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
2641
#endif
2642
           "-enable-audio   enable audio support\n"
2643
           "-localtime      set the real time clock to local time [default=utc]\n"
2644
           "-full-screen    start in full screen\n"
2645
#ifdef TARGET_PPC
2646
           "-prep           Simulate a PREP system (default is PowerMAC)\n"
2647
           "-g WxH[xDEPTH]  Set the initial VGA graphic mode\n"
2648
#endif
2649
           "\n"
2650
           "Network options:\n"
2651
           "-nics n         simulate 'n' network cards [default=1]\n"
2652
           "-macaddr addr   set the mac address of the first interface\n"
2653
           "-n script       set tap/tun network init script [default=%s]\n"
2654
           "-tun-fd fd      use this fd as already opened tap/tun interface\n"
2655
#ifdef CONFIG_SLIRP
2656
           "-user-net       use user mode network stack [default if no tap/tun script]\n"
2657
           "-tftp prefix    allow tftp access to files starting with prefix [-user-net]\n"
2658
#ifndef _WIN32
2659
           "-smb dir        allow SMB access to files in 'dir' [-user-net]\n"
2660
#endif
2661
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
2662
           "                redirect TCP or UDP connections from host to guest [-user-net]\n"
2663
#endif
2664
           "-dummy-net      use dummy network stack\n"
2665
           "\n"
2666
           "Linux boot specific:\n"
2667
           "-kernel bzImage use 'bzImage' as kernel image\n"
2668
           "-append cmdline use 'cmdline' as kernel command line\n"
2669
           "-initrd file    use 'file' as initial ram disk\n"
2670
           "\n"
2671
           "Debug/Expert options:\n"
2672
           "-monitor dev    redirect the monitor to char device 'dev'\n"
2673
           "-serial dev     redirect the serial port to char device 'dev'\n"
2674
           "-pidfile file   Write PID to 'file'\n"
2675
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
2676
           "-s              wait gdb connection to port %d\n"
2677
           "-p port         change gdb connection port\n"
2678
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
2679
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
2680
           "                translation (t=none or lba) (usually qemu can guess them)\n"
2681
           "-L path         set the directory for the BIOS and VGA BIOS\n"
2682
#ifdef USE_CODE_COPY
2683
           "-no-code-copy   disable code copy acceleration\n"
2684
#endif
2685
#ifdef TARGET_I386
2686
           "-isa            simulate an ISA-only system (default is PCI system)\n"
2687
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
2688
           "                (default is CL-GD5446 PCI VGA)\n"
2689
#endif
2690
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
2691
           "\n"
2692
           "During emulation, the following keys are useful:\n"
2693
           "ctrl-alt-f      toggle full screen\n"
2694
           "ctrl-alt-n      switch to virtual console 'n'\n"
2695
           "ctrl-alt        toggle mouse and keyboard grab\n"
2696
           "\n"
2697
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
2698
           ,
2699
#ifdef CONFIG_SOFTMMU
2700
           "qemu",
2701
#else
2702
           "qemu-fast",
2703
#endif
2704
           DEFAULT_RAM_SIZE,
2705
           DEFAULT_NETWORK_SCRIPT,
2706
           DEFAULT_GDBSTUB_PORT,
2707
           "/tmp/qemu.log");
2708
#ifndef CONFIG_SOFTMMU
2709
    printf("\n"
2710
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2711
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2712
           "PC emulation.\n");
2713
#endif
2714
    exit(1);
2715
}
2716

    
2717
#define HAS_ARG 0x0001
2718

    
2719
enum {
2720
    QEMU_OPTION_h,
2721

    
2722
    QEMU_OPTION_fda,
2723
    QEMU_OPTION_fdb,
2724
    QEMU_OPTION_hda,
2725
    QEMU_OPTION_hdb,
2726
    QEMU_OPTION_hdc,
2727
    QEMU_OPTION_hdd,
2728
    QEMU_OPTION_cdrom,
2729
    QEMU_OPTION_boot,
2730
    QEMU_OPTION_snapshot,
2731
    QEMU_OPTION_m,
2732
    QEMU_OPTION_nographic,
2733
    QEMU_OPTION_enable_audio,
2734

    
2735
    QEMU_OPTION_nics,
2736
    QEMU_OPTION_macaddr,
2737
    QEMU_OPTION_n,
2738
    QEMU_OPTION_tun_fd,
2739
    QEMU_OPTION_user_net,
2740
    QEMU_OPTION_tftp,
2741
    QEMU_OPTION_smb,
2742
    QEMU_OPTION_redir,
2743
    QEMU_OPTION_dummy_net,
2744

    
2745
    QEMU_OPTION_kernel,
2746
    QEMU_OPTION_append,
2747
    QEMU_OPTION_initrd,
2748

    
2749
    QEMU_OPTION_S,
2750
    QEMU_OPTION_s,
2751
    QEMU_OPTION_p,
2752
    QEMU_OPTION_d,
2753
    QEMU_OPTION_hdachs,
2754
    QEMU_OPTION_L,
2755
    QEMU_OPTION_no_code_copy,
2756
    QEMU_OPTION_pci,
2757
    QEMU_OPTION_isa,
2758
    QEMU_OPTION_prep,
2759
    QEMU_OPTION_k,
2760
    QEMU_OPTION_localtime,
2761
    QEMU_OPTION_cirrusvga,
2762
    QEMU_OPTION_g,
2763
    QEMU_OPTION_std_vga,
2764
    QEMU_OPTION_monitor,
2765
    QEMU_OPTION_serial,
2766
    QEMU_OPTION_loadvm,
2767
    QEMU_OPTION_full_screen,
2768
    QEMU_OPTION_pidfile,
2769
};
2770

    
2771
typedef struct QEMUOption {
2772
    const char *name;
2773
    int flags;
2774
    int index;
2775
} QEMUOption;
2776

    
2777
const QEMUOption qemu_options[] = {
2778
    { "h", 0, QEMU_OPTION_h },
2779

    
2780
    { "fda", HAS_ARG, QEMU_OPTION_fda },
2781
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2782
    { "hda", HAS_ARG, QEMU_OPTION_hda },
2783
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2784
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2785
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2786
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2787
    { "boot", HAS_ARG, QEMU_OPTION_boot },
2788
    { "snapshot", 0, QEMU_OPTION_snapshot },
2789
    { "m", HAS_ARG, QEMU_OPTION_m },
2790
    { "nographic", 0, QEMU_OPTION_nographic },
2791
    { "k", HAS_ARG, QEMU_OPTION_k },
2792
    { "enable-audio", 0, QEMU_OPTION_enable_audio },
2793

    
2794
    { "nics", HAS_ARG, QEMU_OPTION_nics},
2795
    { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2796
    { "n", HAS_ARG, QEMU_OPTION_n },
2797
    { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2798
#ifdef CONFIG_SLIRP
2799
    { "user-net", 0, QEMU_OPTION_user_net },
2800
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
2801
#ifndef _WIN32
2802
    { "smb", HAS_ARG, QEMU_OPTION_smb },
2803
#endif
2804
    { "redir", HAS_ARG, QEMU_OPTION_redir },
2805
#endif
2806
    { "dummy-net", 0, QEMU_OPTION_dummy_net },
2807

    
2808
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2809
    { "append", HAS_ARG, QEMU_OPTION_append },
2810
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2811

    
2812
    { "S", 0, QEMU_OPTION_S },
2813
    { "s", 0, QEMU_OPTION_s },
2814
    { "p", HAS_ARG, QEMU_OPTION_p },
2815
    { "d", HAS_ARG, QEMU_OPTION_d },
2816
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2817
    { "L", HAS_ARG, QEMU_OPTION_L },
2818
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2819
#ifdef TARGET_PPC
2820
    { "prep", 0, QEMU_OPTION_prep },
2821
    { "g", 1, QEMU_OPTION_g },
2822
#endif
2823
    { "localtime", 0, QEMU_OPTION_localtime },
2824
    { "isa", 0, QEMU_OPTION_isa },
2825
    { "std-vga", 0, QEMU_OPTION_std_vga },
2826
    { "monitor", 1, QEMU_OPTION_monitor },
2827
    { "serial", 1, QEMU_OPTION_serial },
2828
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
2829
    { "full-screen", 0, QEMU_OPTION_full_screen },
2830
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
2831

    
2832
    /* temporary options */
2833
    { "pci", 0, QEMU_OPTION_pci },
2834
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
2835
    { NULL },
2836
};
2837

    
2838
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
2839

    
2840
/* this stack is only used during signal handling */
2841
#define SIGNAL_STACK_SIZE 32768
2842

    
2843
static uint8_t *signal_stack;
2844

    
2845
#endif
2846

    
2847
/* password input */
2848

    
2849
static BlockDriverState *get_bdrv(int index)
2850
{
2851
    BlockDriverState *bs;
2852

    
2853
    if (index < 4) {
2854
        bs = bs_table[index];
2855
    } else if (index < 6) {
2856
        bs = fd_table[index - 4];
2857
    } else {
2858
        bs = NULL;
2859
    }
2860
    return bs;
2861
}
2862

    
2863
static void read_passwords(void)
2864
{
2865
    BlockDriverState *bs;
2866
    int i, j;
2867
    char password[256];
2868

    
2869
    for(i = 0; i < 6; i++) {
2870
        bs = get_bdrv(i);
2871
        if (bs && bdrv_is_encrypted(bs)) {
2872
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
2873
            for(j = 0; j < 3; j++) {
2874
                monitor_readline("Password: ", 
2875
                                 1, password, sizeof(password));
2876
                if (bdrv_set_key(bs, password) == 0)
2877
                    break;
2878
                term_printf("invalid password\n");
2879
            }
2880
        }
2881
    }
2882
}
2883

    
2884
#define NET_IF_TUN   0
2885
#define NET_IF_USER  1
2886
#define NET_IF_DUMMY 2
2887

    
2888
int main(int argc, char **argv)
2889
{
2890
#ifdef CONFIG_GDBSTUB
2891
    int use_gdbstub, gdbstub_port;
2892
#endif
2893
    int i, has_cdrom;
2894
    int snapshot, linux_boot;
2895
    CPUState *env;
2896
    const char *initrd_filename;
2897
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2898
    const char *kernel_filename, *kernel_cmdline;
2899
    DisplayState *ds = &display_state;
2900
    int cyls, heads, secs, translation;
2901
    int start_emulation = 1;
2902
    uint8_t macaddr[6];
2903
    int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2904
    int optind;
2905
    const char *r, *optarg;
2906
    CharDriverState *monitor_hd;
2907
    char monitor_device[128];
2908
    char serial_devices[MAX_SERIAL_PORTS][128];
2909
    int serial_device_index;
2910
    const char *loadvm = NULL;
2911
    
2912
#if !defined(CONFIG_SOFTMMU)
2913
    /* we never want that malloc() uses mmap() */
2914
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2915
#endif
2916
    initrd_filename = NULL;
2917
    for(i = 0; i < MAX_FD; i++)
2918
        fd_filename[i] = NULL;
2919
    for(i = 0; i < MAX_DISKS; i++)
2920
        hd_filename[i] = NULL;
2921
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2922
    vga_ram_size = VGA_RAM_SIZE;
2923
    bios_size = BIOS_SIZE;
2924
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2925
#ifdef CONFIG_GDBSTUB
2926
    use_gdbstub = 0;
2927
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
2928
#endif
2929
    snapshot = 0;
2930
    nographic = 0;
2931
    kernel_filename = NULL;
2932
    kernel_cmdline = "";
2933
    has_cdrom = 1;
2934
    cyls = heads = secs = 0;
2935
    translation = BIOS_ATA_TRANSLATION_AUTO;
2936
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
2937

    
2938
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
2939
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
2940
        serial_devices[i][0] = '\0';
2941
    serial_device_index = 0;
2942
    
2943
    nb_tun_fds = 0;
2944
    net_if_type = -1;
2945
    nb_nics = 1;
2946
    /* default mac address of the first network interface */
2947
    macaddr[0] = 0x52;
2948
    macaddr[1] = 0x54;
2949
    macaddr[2] = 0x00;
2950
    macaddr[3] = 0x12;
2951
    macaddr[4] = 0x34;
2952
    macaddr[5] = 0x56;
2953
    
2954
    optind = 1;
2955
    for(;;) {
2956
        if (optind >= argc)
2957
            break;
2958
        r = argv[optind];
2959
        if (r[0] != '-') {
2960
            hd_filename[0] = argv[optind++];
2961
        } else {
2962
            const QEMUOption *popt;
2963

    
2964
            optind++;
2965
            popt = qemu_options;
2966
            for(;;) {
2967
                if (!popt->name) {
2968
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
2969
                            argv[0], r);
2970
                    exit(1);
2971
                }
2972
                if (!strcmp(popt->name, r + 1))
2973
                    break;
2974
                popt++;
2975
            }
2976
            if (popt->flags & HAS_ARG) {
2977
                if (optind >= argc) {
2978
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
2979
                            argv[0], r);
2980
                    exit(1);
2981
                }
2982
                optarg = argv[optind++];
2983
            } else {
2984
                optarg = NULL;
2985
            }
2986

    
2987
            switch(popt->index) {
2988
            case QEMU_OPTION_initrd:
2989
                initrd_filename = optarg;
2990
                break;
2991
            case QEMU_OPTION_hda:
2992
                hd_filename[0] = optarg;
2993
                break;
2994
            case QEMU_OPTION_hdb:
2995
                hd_filename[1] = optarg;
2996
                break;
2997
            case QEMU_OPTION_snapshot:
2998
                snapshot = 1;
2999
                break;
3000
            case QEMU_OPTION_hdachs:
3001
                {
3002
                    const char *p;
3003
                    p = optarg;
3004
                    cyls = strtol(p, (char **)&p, 0);
3005
                    if (cyls < 1 || cyls > 16383)
3006
                        goto chs_fail;
3007
                    if (*p != ',')
3008
                        goto chs_fail;
3009
                    p++;
3010
                    heads = strtol(p, (char **)&p, 0);
3011
                    if (heads < 1 || heads > 16)
3012
                        goto chs_fail;
3013
                    if (*p != ',')
3014
                        goto chs_fail;
3015
                    p++;
3016
                    secs = strtol(p, (char **)&p, 0);
3017
                    if (secs < 1 || secs > 63)
3018
                        goto chs_fail;
3019
                    if (*p == ',') {
3020
                        p++;
3021
                        if (!strcmp(p, "none"))
3022
                            translation = BIOS_ATA_TRANSLATION_NONE;
3023
                        else if (!strcmp(p, "lba"))
3024
                            translation = BIOS_ATA_TRANSLATION_LBA;
3025
                        else if (!strcmp(p, "auto"))
3026
                            translation = BIOS_ATA_TRANSLATION_AUTO;
3027
                        else
3028
                            goto chs_fail;
3029
                    } else if (*p != '\0') {
3030
                    chs_fail:
3031
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
3032
                        exit(1);
3033
                    }
3034
                }
3035
                break;
3036
            case QEMU_OPTION_nographic:
3037
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
3038
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
3039
                nographic = 1;
3040
                break;
3041
            case QEMU_OPTION_kernel:
3042
                kernel_filename = optarg;
3043
                break;
3044
            case QEMU_OPTION_append:
3045
                kernel_cmdline = optarg;
3046
                break;
3047
            case QEMU_OPTION_tun_fd:
3048
                {
3049
                    const char *p;
3050
                    int fd;
3051
                    net_if_type = NET_IF_TUN;
3052
                    if (nb_tun_fds < MAX_NICS) {
3053
                        fd = strtol(optarg, (char **)&p, 0);
3054
                        if (*p != '\0') {
3055
                            fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
3056
                            exit(1);
3057
                        }
3058
                        tun_fds[nb_tun_fds++] = fd;
3059
                    }
3060
                }
3061
                break;
3062
            case QEMU_OPTION_hdc:
3063
                hd_filename[2] = optarg;
3064
                has_cdrom = 0;
3065
                break;
3066
            case QEMU_OPTION_hdd:
3067
                hd_filename[3] = optarg;
3068
                break;
3069
            case QEMU_OPTION_cdrom:
3070
                hd_filename[2] = optarg;
3071
                has_cdrom = 1;
3072
                break;
3073
            case QEMU_OPTION_boot:
3074
                boot_device = optarg[0];
3075
                if (boot_device != 'a' && 
3076
                    boot_device != 'c' && boot_device != 'd') {
3077
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3078
                    exit(1);
3079
                }
3080
                break;
3081
            case QEMU_OPTION_fda:
3082
                fd_filename[0] = optarg;
3083
                break;
3084
            case QEMU_OPTION_fdb:
3085
                fd_filename[1] = optarg;
3086
                break;
3087
            case QEMU_OPTION_no_code_copy:
3088
                code_copy_enabled = 0;
3089
                break;
3090
            case QEMU_OPTION_nics:
3091
                nb_nics = atoi(optarg);
3092
                if (nb_nics < 0 || nb_nics > MAX_NICS) {
3093
                    fprintf(stderr, "qemu: invalid number of network interfaces\n");
3094
                    exit(1);
3095
                }
3096
                break;
3097
            case QEMU_OPTION_macaddr:
3098
                {
3099
                    const char *p;
3100
                    int i;
3101
                    p = optarg;
3102
                    for(i = 0; i < 6; i++) {
3103
                        macaddr[i] = strtol(p, (char **)&p, 16);
3104
                        if (i == 5) {
3105
                            if (*p != '\0') 
3106
                                goto macaddr_error;
3107
                        } else {
3108
                            if (*p != ':') {
3109
                            macaddr_error:
3110
                                fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
3111
                                exit(1);
3112
                            }
3113
                            p++;
3114
                        }
3115
                    }
3116
                }
3117
                break;
3118
#ifdef CONFIG_SLIRP
3119
            case QEMU_OPTION_tftp:
3120
                tftp_prefix = optarg;
3121
                break;
3122
#ifndef _WIN32
3123
            case QEMU_OPTION_smb:
3124
                net_slirp_smb(optarg);
3125
                break;
3126
#endif
3127
            case QEMU_OPTION_user_net:
3128
                net_if_type = NET_IF_USER;
3129
                break;
3130
            case QEMU_OPTION_redir:
3131
                net_slirp_redir(optarg);                
3132
                break;
3133
#endif
3134
            case QEMU_OPTION_dummy_net:
3135
                net_if_type = NET_IF_DUMMY;
3136
                break;
3137
            case QEMU_OPTION_enable_audio:
3138
                audio_enabled = 1;
3139
                break;
3140
            case QEMU_OPTION_h:
3141
                help();
3142
                break;
3143
            case QEMU_OPTION_m:
3144
                ram_size = atoi(optarg) * 1024 * 1024;
3145
                if (ram_size <= 0)
3146
                    help();
3147
                if (ram_size > PHYS_RAM_MAX_SIZE) {
3148
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3149
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
3150
                    exit(1);
3151
                }
3152
                break;
3153
            case QEMU_OPTION_d:
3154
                {
3155
                    int mask;
3156
                    CPULogItem *item;
3157
                    
3158
                    mask = cpu_str_to_log_mask(optarg);
3159
                    if (!mask) {
3160
                        printf("Log items (comma separated):\n");
3161
                    for(item = cpu_log_items; item->mask != 0; item++) {
3162
                        printf("%-10s %s\n", item->name, item->help);
3163
                    }
3164
                    exit(1);
3165
                    }
3166
                    cpu_set_log(mask);
3167
                }
3168
                break;
3169
            case QEMU_OPTION_n:
3170
                pstrcpy(network_script, sizeof(network_script), optarg);
3171
                break;
3172
#ifdef CONFIG_GDBSTUB
3173
            case QEMU_OPTION_s:
3174
                use_gdbstub = 1;
3175
                break;
3176
            case QEMU_OPTION_p:
3177
                gdbstub_port = atoi(optarg);
3178
                break;
3179
#endif
3180
            case QEMU_OPTION_L:
3181
                bios_dir = optarg;
3182
                break;
3183
            case QEMU_OPTION_S:
3184
                start_emulation = 0;
3185
                break;
3186
            case QEMU_OPTION_pci:
3187
                pci_enabled = 1;
3188
                break;
3189
            case QEMU_OPTION_isa:
3190
                pci_enabled = 0;
3191
                break;
3192
            case QEMU_OPTION_prep:
3193
                prep_enabled = 1;
3194
                break;
3195
            case QEMU_OPTION_k:
3196
                keyboard_layout = optarg;
3197
                break;
3198
            case QEMU_OPTION_localtime:
3199
                rtc_utc = 0;
3200
                break;
3201
            case QEMU_OPTION_cirrusvga:
3202
                cirrus_vga_enabled = 1;
3203
                break;
3204
            case QEMU_OPTION_std_vga:
3205
                cirrus_vga_enabled = 0;
3206
                break;
3207
            case QEMU_OPTION_g:
3208
                {
3209
                    const char *p;
3210
                    int w, h, depth;
3211
                    p = optarg;
3212
                    w = strtol(p, (char **)&p, 10);
3213
                    if (w <= 0) {
3214
                    graphic_error:
3215
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
3216
                        exit(1);
3217
                    }
3218
                    if (*p != 'x')
3219
                        goto graphic_error;
3220
                    p++;
3221
                    h = strtol(p, (char **)&p, 10);
3222
                    if (h <= 0)
3223
                        goto graphic_error;
3224
                    if (*p == 'x') {
3225
                        p++;
3226
                        depth = strtol(p, (char **)&p, 10);
3227
                        if (depth != 8 && depth != 15 && depth != 16 && 
3228
                            depth != 24 && depth != 32)
3229
                            goto graphic_error;
3230
                    } else if (*p == '\0') {
3231
                        depth = graphic_depth;
3232
                    } else {
3233
                        goto graphic_error;
3234
                    }
3235
                    
3236
                    graphic_width = w;
3237
                    graphic_height = h;
3238
                    graphic_depth = depth;
3239
                }
3240
                break;
3241
            case QEMU_OPTION_monitor:
3242
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
3243
                break;
3244
            case QEMU_OPTION_serial:
3245
                if (serial_device_index >= MAX_SERIAL_PORTS) {
3246
                    fprintf(stderr, "qemu: too many serial ports\n");
3247
                    exit(1);
3248
                }
3249
                pstrcpy(serial_devices[serial_device_index], 
3250
                        sizeof(serial_devices[0]), optarg);
3251
                serial_device_index++;
3252
                break;
3253
            case QEMU_OPTION_loadvm:
3254
                loadvm = optarg;
3255
                break;
3256
            case QEMU_OPTION_full_screen:
3257
                full_screen = 1;
3258
                break;
3259
            case QEMU_OPTION_pidfile:
3260
                create_pidfile(optarg);
3261
                break;
3262
            }
3263
        }
3264
    }
3265

    
3266
    linux_boot = (kernel_filename != NULL);
3267
        
3268
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
3269
        fd_filename[0] == '\0')
3270
        help();
3271
    
3272
    /* boot to cd by default if no hard disk */
3273
    if (hd_filename[0] == '\0' && boot_device == 'c') {
3274
        if (fd_filename[0] != '\0')
3275
            boot_device = 'a';
3276
        else
3277
            boot_device = 'd';
3278
    }
3279

    
3280
#if !defined(CONFIG_SOFTMMU)
3281
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3282
    {
3283
        static uint8_t stdout_buf[4096];
3284
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3285
    }
3286
#else
3287
    setvbuf(stdout, NULL, _IOLBF, 0);
3288
#endif
3289

    
3290
    /* init host network redirectors */
3291
    if (net_if_type == -1) {
3292
        net_if_type = NET_IF_TUN;
3293
#if defined(CONFIG_SLIRP)
3294
        if (access(network_script, R_OK) < 0) {
3295
            net_if_type = NET_IF_USER;
3296
        }
3297
#endif
3298
    }
3299

    
3300
    for(i = 0; i < nb_nics; i++) {
3301
        NetDriverState *nd = &nd_table[i];
3302
        nd->index = i;
3303
        /* init virtual mac address */
3304
        nd->macaddr[0] = macaddr[0];
3305
        nd->macaddr[1] = macaddr[1];
3306
        nd->macaddr[2] = macaddr[2];
3307
        nd->macaddr[3] = macaddr[3];
3308
        nd->macaddr[4] = macaddr[4];
3309
        nd->macaddr[5] = macaddr[5] + i;
3310
        switch(net_if_type) {
3311
#if defined(CONFIG_SLIRP)
3312
        case NET_IF_USER:
3313
            net_slirp_init(nd);
3314
            break;
3315
#endif
3316
#if !defined(_WIN32)
3317
        case NET_IF_TUN:
3318
            if (i < nb_tun_fds) {
3319
                net_fd_init(nd, tun_fds[i]);
3320
            } else {
3321
                if (net_tun_init(nd) < 0)
3322
                    net_dummy_init(nd);
3323
            }
3324
            break;
3325
#endif
3326
        case NET_IF_DUMMY:
3327
        default:
3328
            net_dummy_init(nd);
3329
            break;
3330
        }
3331
    }
3332

    
3333
    /* init the memory */
3334
    phys_ram_size = ram_size + vga_ram_size + bios_size;
3335

    
3336
#ifdef CONFIG_SOFTMMU
3337
#ifdef _BSD
3338
    /* mallocs are always aligned on BSD. valloc is better for correctness */
3339
    phys_ram_base = valloc(phys_ram_size);
3340
#else
3341
    phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
3342
#endif
3343
    if (!phys_ram_base) {
3344
        fprintf(stderr, "Could not allocate physical memory\n");
3345
        exit(1);
3346
    }
3347
#else
3348
    /* as we must map the same page at several addresses, we must use
3349
       a fd */
3350
    {
3351
        const char *tmpdir;
3352

    
3353
        tmpdir = getenv("QEMU_TMPDIR");
3354
        if (!tmpdir)
3355
            tmpdir = "/tmp";
3356
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3357
        if (mkstemp(phys_ram_file) < 0) {
3358
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
3359
                    phys_ram_file);
3360
            exit(1);
3361
        }
3362
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3363
        if (phys_ram_fd < 0) {
3364
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
3365
                    phys_ram_file);
3366
            exit(1);
3367
        }
3368
        ftruncate(phys_ram_fd, phys_ram_size);
3369
        unlink(phys_ram_file);
3370
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
3371
                             phys_ram_size, 
3372
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
3373
                             phys_ram_fd, 0);
3374
        if (phys_ram_base == MAP_FAILED) {
3375
            fprintf(stderr, "Could not map physical memory\n");
3376
            exit(1);
3377
        }
3378
    }
3379
#endif
3380

    
3381
    /* we always create the cdrom drive, even if no disk is there */
3382
    bdrv_init();
3383
    if (has_cdrom) {
3384
        bs_table[2] = bdrv_new("cdrom");
3385
        bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
3386
    }
3387

    
3388
    /* open the virtual block devices */
3389
    for(i = 0; i < MAX_DISKS; i++) {
3390
        if (hd_filename[i]) {
3391
            if (!bs_table[i]) {
3392
                char buf[64];
3393
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
3394
                bs_table[i] = bdrv_new(buf);
3395
            }
3396
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
3397
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
3398
                        hd_filename[i]);
3399
                exit(1);
3400
            }
3401
            if (i == 0 && cyls != 0) {
3402
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3403
                bdrv_set_translation_hint(bs_table[i], translation);
3404
            }
3405
        }
3406
    }
3407

    
3408
    /* we always create at least one floppy disk */
3409
    fd_table[0] = bdrv_new("fda");
3410
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
3411

    
3412
    for(i = 0; i < MAX_FD; i++) {
3413
        if (fd_filename[i]) {
3414
            if (!fd_table[i]) {
3415
                char buf[64];
3416
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
3417
                fd_table[i] = bdrv_new(buf);
3418
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
3419
            }
3420
            if (fd_filename[i] != '\0') {
3421
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
3422
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
3423
                            fd_filename[i]);
3424
                    exit(1);
3425
                }
3426
            }
3427
        }
3428
    }
3429

    
3430
    /* init CPU state */
3431
    env = cpu_init();
3432
    global_env = env;
3433
    cpu_single_env = env;
3434

    
3435
    register_savevm("timer", 0, 1, timer_save, timer_load, env);
3436
    register_savevm("cpu", 0, 2, cpu_save, cpu_load, env);
3437
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
3438
    qemu_register_reset(main_cpu_reset, global_env);
3439

    
3440
    init_ioports();
3441
    cpu_calibrate_ticks();
3442

    
3443
    /* terminal init */
3444
    if (nographic) {
3445
        dumb_display_init(ds);
3446
    } else {
3447
#ifdef CONFIG_SDL
3448
        sdl_display_init(ds, full_screen);
3449
#else
3450
        dumb_display_init(ds);
3451
#endif
3452
    }
3453

    
3454
    vga_console = graphic_console_init(ds);
3455
    
3456
    monitor_hd = qemu_chr_open(monitor_device);
3457
    if (!monitor_hd) {
3458
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
3459
        exit(1);
3460
    }
3461
    monitor_init(monitor_hd, !nographic);
3462

    
3463
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
3464
        if (serial_devices[i][0] != '\0') {
3465
            serial_hds[i] = qemu_chr_open(serial_devices[i]);
3466
            if (!serial_hds[i]) {
3467
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
3468
                        serial_devices[i]);
3469
                exit(1);
3470
            }
3471
            if (!strcmp(serial_devices[i], "vc"))
3472
                qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
3473
        }
3474
    }
3475

    
3476
    /* setup cpu signal handlers for MMU / self modifying code handling */
3477
#if !defined(CONFIG_SOFTMMU)
3478
    
3479
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
3480
    {
3481
        stack_t stk;
3482
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
3483
        stk.ss_sp = signal_stack;
3484
        stk.ss_size = SIGNAL_STACK_SIZE;
3485
        stk.ss_flags = 0;
3486

    
3487
        if (sigaltstack(&stk, NULL) < 0) {
3488
            perror("sigaltstack");
3489
            exit(1);
3490
        }
3491
    }
3492
#endif
3493
    {
3494
        struct sigaction act;
3495
        
3496
        sigfillset(&act.sa_mask);
3497
        act.sa_flags = SA_SIGINFO;
3498
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
3499
        act.sa_flags |= SA_ONSTACK;
3500
#endif
3501
        act.sa_sigaction = host_segv_handler;
3502
        sigaction(SIGSEGV, &act, NULL);
3503
        sigaction(SIGBUS, &act, NULL);
3504
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
3505
        sigaction(SIGFPE, &act, NULL);
3506
#endif
3507
    }
3508
#endif
3509

    
3510
#ifndef _WIN32
3511
    {
3512
        struct sigaction act;
3513
        sigfillset(&act.sa_mask);
3514
        act.sa_flags = 0;
3515
        act.sa_handler = SIG_IGN;
3516
        sigaction(SIGPIPE, &act, NULL);
3517
    }
3518
#endif
3519
    init_timers();
3520

    
3521
#if defined(TARGET_I386)
3522
    pc_init(ram_size, vga_ram_size, boot_device,
3523
            ds, fd_filename, snapshot,
3524
            kernel_filename, kernel_cmdline, initrd_filename);
3525
#elif defined(TARGET_PPC)
3526
    ppc_init(ram_size, vga_ram_size, boot_device,
3527
             ds, fd_filename, snapshot,
3528
             kernel_filename, kernel_cmdline, initrd_filename);
3529
#elif defined(TARGET_SPARC)
3530
    sun4m_init(ram_size, vga_ram_size, boot_device,
3531
            ds, fd_filename, snapshot,
3532
            kernel_filename, kernel_cmdline, initrd_filename);
3533
#endif
3534

    
3535
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
3536
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
3537

    
3538
#ifdef CONFIG_GDBSTUB
3539
    if (use_gdbstub) {
3540
        if (gdbserver_start(gdbstub_port) < 0) {
3541
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
3542
                    gdbstub_port);
3543
            exit(1);
3544
        } else {
3545
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
3546
        }
3547
    } else 
3548
#endif
3549
    if (loadvm)
3550
        qemu_loadvm(loadvm);
3551

    
3552
    {
3553
        /* XXX: simplify init */
3554
        read_passwords();
3555
        if (start_emulation) {
3556
            vm_start();
3557
        }
3558
    }
3559
    main_loop();
3560
    quit_timers();
3561
    return 0;
3562
}