Statistics
| Branch: | Revision:

root / vl.c @ fd06c375

History | View | Annotate | Download (143 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2005 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
#include <netdb.h>
44
#ifdef _BSD
45
#include <sys/stat.h>
46
#ifndef __APPLE__
47
#include <libutil.h>
48
#endif
49
#else
50
#include <linux/if.h>
51
#include <linux/if_tun.h>
52
#include <pty.h>
53
#include <malloc.h>
54
#include <linux/rtc.h>
55
#include <linux/ppdev.h>
56
#endif
57
#endif
58

    
59
#if defined(CONFIG_SLIRP)
60
#include "libslirp.h"
61
#endif
62

    
63
#ifdef _WIN32
64
#include <malloc.h>
65
#include <sys/timeb.h>
66
#include <windows.h>
67
#include <winsock2.h>
68
#include <ws2tcpip.h>
69
#define getopt_long_only getopt_long
70
#define memalign(align, size) malloc(size)
71
#endif
72

    
73
#ifdef CONFIG_SDL
74
#ifdef __APPLE__
75
#include <SDL/SDL.h>
76
#endif
77
#endif /* CONFIG_SDL */
78

    
79
#ifdef CONFIG_COCOA
80
#undef main
81
#define main qemu_main
82
#endif /* CONFIG_COCOA */
83

    
84
#include "disas.h"
85

    
86
#include "exec-all.h"
87

    
88
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
89

    
90
//#define DEBUG_UNUSED_IOPORT
91
//#define DEBUG_IOPORT
92

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

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

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

    
110
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
111
char phys_ram_file[1024];
112
void *ioport_opaque[MAX_IOPORTS];
113
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
114
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
115
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
116
int vga_ram_size;
117
int bios_size;
118
static DisplayState display_state;
119
int nographic;
120
const char* keyboard_layout = NULL;
121
int64_t ticks_per_sec;
122
int boot_device = 'c';
123
int ram_size;
124
int pit_min_timer_count = 0;
125
int nb_nics;
126
NICInfo nd_table[MAX_NICS];
127
QEMUTimer *gui_timer;
128
int vm_running;
129
int rtc_utc = 1;
130
int cirrus_vga_enabled = 1;
131
#ifdef TARGET_SPARC
132
int graphic_width = 1024;
133
int graphic_height = 768;
134
#else
135
int graphic_width = 800;
136
int graphic_height = 600;
137
#endif
138
int graphic_depth = 15;
139
int full_screen = 0;
140
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
141
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
142
#ifdef TARGET_I386
143
int win2k_install_hack = 0;
144
#endif
145
int usb_enabled = 0;
146
USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
147
USBDevice *vm_usb_hub;
148
static VLANState *first_vlan;
149
int smp_cpus = 1;
150
#if defined(TARGET_SPARC)
151
#define MAX_CPUS 16
152
#elif defined(TARGET_I386)
153
#define MAX_CPUS 255
154
#else
155
#define MAX_CPUS 1
156
#endif
157

    
158
/***********************************************************/
159
/* x86 ISA bus support */
160

    
161
target_phys_addr_t isa_mem_base = 0;
162
PicState2 *isa_pic;
163

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

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

    
179
/* default is to make two byte accesses */
180
uint32_t default_ioport_readw(void *opaque, uint32_t address)
181
{
182
    uint32_t data;
183
    data = ioport_read_table[0][address](ioport_opaque[address], address);
184
    address = (address + 1) & (MAX_IOPORTS - 1);
185
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
186
    return data;
187
}
188

    
189
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
190
{
191
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
192
    address = (address + 1) & (MAX_IOPORTS - 1);
193
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
194
}
195

    
196
uint32_t default_ioport_readl(void *opaque, uint32_t address)
197
{
198
#ifdef DEBUG_UNUSED_IOPORT
199
    fprintf(stderr, "inl: port=0x%04x\n", address);
200
#endif
201
    return 0xffffffff;
202
}
203

    
204
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
205
{
206
#ifdef DEBUG_UNUSED_IOPORT
207
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
208
#endif
209
}
210

    
211
void init_ioports(void)
212
{
213
    int i;
214

    
215
    for(i = 0; i < MAX_IOPORTS; i++) {
216
        ioport_read_table[0][i] = default_ioport_readb;
217
        ioport_write_table[0][i] = default_ioport_writeb;
218
        ioport_read_table[1][i] = default_ioport_readw;
219
        ioport_write_table[1][i] = default_ioport_writew;
220
        ioport_read_table[2][i] = default_ioport_readl;
221
        ioport_write_table[2][i] = default_ioport_writel;
222
    }
223
}
224

    
225
/* size is the word size in byte */
226
int register_ioport_read(int start, int length, int size, 
227
                         IOPortReadFunc *func, void *opaque)
228
{
229
    int i, bsize;
230

    
231
    if (size == 1) {
232
        bsize = 0;
233
    } else if (size == 2) {
234
        bsize = 1;
235
    } else if (size == 4) {
236
        bsize = 2;
237
    } else {
238
        hw_error("register_ioport_read: invalid size");
239
        return -1;
240
    }
241
    for(i = start; i < start + length; i += size) {
242
        ioport_read_table[bsize][i] = func;
243
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
244
            hw_error("register_ioport_read: invalid opaque");
245
        ioport_opaque[i] = opaque;
246
    }
247
    return 0;
248
}
249

    
250
/* size is the word size in byte */
251
int register_ioport_write(int start, int length, int size, 
252
                          IOPortWriteFunc *func, void *opaque)
253
{
254
    int i, bsize;
255

    
256
    if (size == 1) {
257
        bsize = 0;
258
    } else if (size == 2) {
259
        bsize = 1;
260
    } else if (size == 4) {
261
        bsize = 2;
262
    } else {
263
        hw_error("register_ioport_write: invalid size");
264
        return -1;
265
    }
266
    for(i = start; i < start + length; i += size) {
267
        ioport_write_table[bsize][i] = func;
268
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
269
            hw_error("register_ioport_read: invalid opaque");
270
        ioport_opaque[i] = opaque;
271
    }
272
    return 0;
273
}
274

    
275
void isa_unassign_ioport(int start, int length)
276
{
277
    int i;
278

    
279
    for(i = start; i < start + length; i++) {
280
        ioport_read_table[0][i] = default_ioport_readb;
281
        ioport_read_table[1][i] = default_ioport_readw;
282
        ioport_read_table[2][i] = default_ioport_readl;
283

    
284
        ioport_write_table[0][i] = default_ioport_writeb;
285
        ioport_write_table[1][i] = default_ioport_writew;
286
        ioport_write_table[2][i] = default_ioport_writel;
287
    }
288
}
289

    
290
/***********************************************************/
291

    
292
void pstrcpy(char *buf, int buf_size, const char *str)
293
{
294
    int c;
295
    char *q = buf;
296

    
297
    if (buf_size <= 0)
298
        return;
299

    
300
    for(;;) {
301
        c = *str++;
302
        if (c == 0 || q >= buf + buf_size - 1)
303
            break;
304
        *q++ = c;
305
    }
306
    *q = '\0';
307
}
308

    
309
/* strcat and truncate. */
310
char *pstrcat(char *buf, int buf_size, const char *s)
311
{
312
    int len;
313
    len = strlen(buf);
314
    if (len < buf_size) 
315
        pstrcpy(buf + len, buf_size - len, s);
316
    return buf;
317
}
318

    
319
int strstart(const char *str, const char *val, const char **ptr)
320
{
321
    const char *p, *q;
322
    p = str;
323
    q = val;
324
    while (*q != '\0') {
325
        if (*p != *q)
326
            return 0;
327
        p++;
328
        q++;
329
    }
330
    if (ptr)
331
        *ptr = p;
332
    return 1;
333
}
334

    
335
void cpu_outb(CPUState *env, int addr, int val)
336
{
337
#ifdef DEBUG_IOPORT
338
    if (loglevel & CPU_LOG_IOPORT)
339
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
340
#endif    
341
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
342
#ifdef USE_KQEMU
343
    if (env)
344
        env->last_io_time = cpu_get_time_fast();
345
#endif
346
}
347

    
348
void cpu_outw(CPUState *env, int addr, int val)
349
{
350
#ifdef DEBUG_IOPORT
351
    if (loglevel & CPU_LOG_IOPORT)
352
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
353
#endif    
354
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
355
#ifdef USE_KQEMU
356
    if (env)
357
        env->last_io_time = cpu_get_time_fast();
358
#endif
359
}
360

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

    
374
int cpu_inb(CPUState *env, int addr)
375
{
376
    int val;
377
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
378
#ifdef DEBUG_IOPORT
379
    if (loglevel & CPU_LOG_IOPORT)
380
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
381
#endif
382
#ifdef USE_KQEMU
383
    if (env)
384
        env->last_io_time = cpu_get_time_fast();
385
#endif
386
    return val;
387
}
388

    
389
int cpu_inw(CPUState *env, int addr)
390
{
391
    int val;
392
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
393
#ifdef DEBUG_IOPORT
394
    if (loglevel & CPU_LOG_IOPORT)
395
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
396
#endif
397
#ifdef USE_KQEMU
398
    if (env)
399
        env->last_io_time = cpu_get_time_fast();
400
#endif
401
    return val;
402
}
403

    
404
int cpu_inl(CPUState *env, int addr)
405
{
406
    int val;
407
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
408
#ifdef DEBUG_IOPORT
409
    if (loglevel & CPU_LOG_IOPORT)
410
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
411
#endif
412
#ifdef USE_KQEMU
413
    if (env)
414
        env->last_io_time = cpu_get_time_fast();
415
#endif
416
    return val;
417
}
418

    
419
/***********************************************************/
420
void hw_error(const char *fmt, ...)
421
{
422
    va_list ap;
423
    CPUState *env;
424

    
425
    va_start(ap, fmt);
426
    fprintf(stderr, "qemu: hardware error: ");
427
    vfprintf(stderr, fmt, ap);
428
    fprintf(stderr, "\n");
429
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
430
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
431
#ifdef TARGET_I386
432
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
433
#else
434
        cpu_dump_state(env, stderr, fprintf, 0);
435
#endif
436
    }
437
    va_end(ap);
438
    abort();
439
}
440

    
441
/***********************************************************/
442
/* keyboard/mouse */
443

    
444
static QEMUPutKBDEvent *qemu_put_kbd_event;
445
static void *qemu_put_kbd_event_opaque;
446
static QEMUPutMouseEvent *qemu_put_mouse_event;
447
static void *qemu_put_mouse_event_opaque;
448
static int qemu_put_mouse_event_absolute;
449

    
450
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
451
{
452
    qemu_put_kbd_event_opaque = opaque;
453
    qemu_put_kbd_event = func;
454
}
455

    
456
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
457
{
458
    qemu_put_mouse_event_opaque = opaque;
459
    qemu_put_mouse_event = func;
460
    qemu_put_mouse_event_absolute = absolute;
461
}
462

    
463
void kbd_put_keycode(int keycode)
464
{
465
    if (qemu_put_kbd_event) {
466
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
467
    }
468
}
469

    
470
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
471
{
472
    if (qemu_put_mouse_event) {
473
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
474
                             dx, dy, dz, buttons_state);
475
    }
476
}
477

    
478
int kbd_mouse_is_absolute(void)
479
{
480
    return qemu_put_mouse_event_absolute;
481
}
482

    
483
/***********************************************************/
484
/* timers */
485

    
486
#if defined(__powerpc__)
487

    
488
static inline uint32_t get_tbl(void) 
489
{
490
    uint32_t tbl;
491
    asm volatile("mftb %0" : "=r" (tbl));
492
    return tbl;
493
}
494

    
495
static inline uint32_t get_tbu(void) 
496
{
497
        uint32_t tbl;
498
        asm volatile("mftbu %0" : "=r" (tbl));
499
        return tbl;
500
}
501

    
502
int64_t cpu_get_real_ticks(void)
503
{
504
    uint32_t l, h, h1;
505
    /* NOTE: we test if wrapping has occurred */
506
    do {
507
        h = get_tbu();
508
        l = get_tbl();
509
        h1 = get_tbu();
510
    } while (h != h1);
511
    return ((int64_t)h << 32) | l;
512
}
513

    
514
#elif defined(__i386__)
515

    
516
int64_t cpu_get_real_ticks(void)
517
{
518
    int64_t val;
519
    asm volatile ("rdtsc" : "=A" (val));
520
    return val;
521
}
522

    
523
#elif defined(__x86_64__)
524

    
525
int64_t cpu_get_real_ticks(void)
526
{
527
    uint32_t low,high;
528
    int64_t val;
529
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
530
    val = high;
531
    val <<= 32;
532
    val |= low;
533
    return val;
534
}
535

    
536
#elif defined(__ia64)
537

    
538
int64_t cpu_get_real_ticks(void)
539
{
540
        int64_t val;
541
        asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
542
        return val;
543
}
544

    
545
#elif defined(__s390__)
546

    
547
int64_t cpu_get_real_ticks(void)
548
{
549
    int64_t val;
550
    asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
551
    return val;
552
}
553

    
554
#else
555
#error unsupported CPU
556
#endif
557

    
558
static int64_t cpu_ticks_offset;
559
static int cpu_ticks_enabled;
560

    
561
static inline int64_t cpu_get_ticks(void)
562
{
563
    if (!cpu_ticks_enabled) {
564
        return cpu_ticks_offset;
565
    } else {
566
        return cpu_get_real_ticks() + cpu_ticks_offset;
567
    }
568
}
569

    
570
/* enable cpu_get_ticks() */
571
void cpu_enable_ticks(void)
572
{
573
    if (!cpu_ticks_enabled) {
574
        cpu_ticks_offset -= cpu_get_real_ticks();
575
        cpu_ticks_enabled = 1;
576
    }
577
}
578

    
579
/* disable cpu_get_ticks() : the clock is stopped. You must not call
580
   cpu_get_ticks() after that.  */
581
void cpu_disable_ticks(void)
582
{
583
    if (cpu_ticks_enabled) {
584
        cpu_ticks_offset = cpu_get_ticks();
585
        cpu_ticks_enabled = 0;
586
    }
587
}
588

    
589
static int64_t get_clock(void)
590
{
591
#ifdef _WIN32
592
    struct _timeb tb;
593
    _ftime(&tb);
594
    return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
595
#else
596
    struct timeval tv;
597
    gettimeofday(&tv, NULL);
598
    return tv.tv_sec * 1000000LL + tv.tv_usec;
599
#endif
600
}
601

    
602
void cpu_calibrate_ticks(void)
603
{
604
    int64_t usec, ticks;
605

    
606
    usec = get_clock();
607
    ticks = cpu_get_real_ticks();
608
#ifdef _WIN32
609
    Sleep(50);
610
#else
611
    usleep(50 * 1000);
612
#endif
613
    usec = get_clock() - usec;
614
    ticks = cpu_get_real_ticks() - ticks;
615
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
616
}
617

    
618
/* compute with 96 bit intermediate result: (a*b)/c */
619
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
620
{
621
    union {
622
        uint64_t ll;
623
        struct {
624
#ifdef WORDS_BIGENDIAN
625
            uint32_t high, low;
626
#else
627
            uint32_t low, high;
628
#endif            
629
        } l;
630
    } u, res;
631
    uint64_t rl, rh;
632

    
633
    u.ll = a;
634
    rl = (uint64_t)u.l.low * (uint64_t)b;
635
    rh = (uint64_t)u.l.high * (uint64_t)b;
636
    rh += (rl >> 32);
637
    res.l.high = rh / c;
638
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
639
    return res.ll;
640
}
641

    
642
#define QEMU_TIMER_REALTIME 0
643
#define QEMU_TIMER_VIRTUAL  1
644

    
645
struct QEMUClock {
646
    int type;
647
    /* XXX: add frequency */
648
};
649

    
650
struct QEMUTimer {
651
    QEMUClock *clock;
652
    int64_t expire_time;
653
    QEMUTimerCB *cb;
654
    void *opaque;
655
    struct QEMUTimer *next;
656
};
657

    
658
QEMUClock *rt_clock;
659
QEMUClock *vm_clock;
660

    
661
static QEMUTimer *active_timers[2];
662
#ifdef _WIN32
663
static MMRESULT timerID;
664
#else
665
/* frequency of the times() clock tick */
666
static int timer_freq;
667
#endif
668

    
669
QEMUClock *qemu_new_clock(int type)
670
{
671
    QEMUClock *clock;
672
    clock = qemu_mallocz(sizeof(QEMUClock));
673
    if (!clock)
674
        return NULL;
675
    clock->type = type;
676
    return clock;
677
}
678

    
679
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
680
{
681
    QEMUTimer *ts;
682

    
683
    ts = qemu_mallocz(sizeof(QEMUTimer));
684
    ts->clock = clock;
685
    ts->cb = cb;
686
    ts->opaque = opaque;
687
    return ts;
688
}
689

    
690
void qemu_free_timer(QEMUTimer *ts)
691
{
692
    qemu_free(ts);
693
}
694

    
695
/* stop a timer, but do not dealloc it */
696
void qemu_del_timer(QEMUTimer *ts)
697
{
698
    QEMUTimer **pt, *t;
699

    
700
    /* NOTE: this code must be signal safe because
701
       qemu_timer_expired() can be called from a signal. */
702
    pt = &active_timers[ts->clock->type];
703
    for(;;) {
704
        t = *pt;
705
        if (!t)
706
            break;
707
        if (t == ts) {
708
            *pt = t->next;
709
            break;
710
        }
711
        pt = &t->next;
712
    }
713
}
714

    
715
/* modify the current timer so that it will be fired when current_time
716
   >= expire_time. The corresponding callback will be called. */
717
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
718
{
719
    QEMUTimer **pt, *t;
720

    
721
    qemu_del_timer(ts);
722

    
723
    /* add the timer in the sorted list */
724
    /* NOTE: this code must be signal safe because
725
       qemu_timer_expired() can be called from a signal. */
726
    pt = &active_timers[ts->clock->type];
727
    for(;;) {
728
        t = *pt;
729
        if (!t)
730
            break;
731
        if (t->expire_time > expire_time) 
732
            break;
733
        pt = &t->next;
734
    }
735
    ts->expire_time = expire_time;
736
    ts->next = *pt;
737
    *pt = ts;
738
}
739

    
740
int qemu_timer_pending(QEMUTimer *ts)
741
{
742
    QEMUTimer *t;
743
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
744
        if (t == ts)
745
            return 1;
746
    }
747
    return 0;
748
}
749

    
750
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
751
{
752
    if (!timer_head)
753
        return 0;
754
    return (timer_head->expire_time <= current_time);
755
}
756

    
757
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
758
{
759
    QEMUTimer *ts;
760
    
761
    for(;;) {
762
        ts = *ptimer_head;
763
        if (!ts || ts->expire_time > current_time)
764
            break;
765
        /* remove timer from the list before calling the callback */
766
        *ptimer_head = ts->next;
767
        ts->next = NULL;
768
        
769
        /* run the callback (the timer list can be modified) */
770
        ts->cb(ts->opaque);
771
    }
772
}
773

    
774
int64_t qemu_get_clock(QEMUClock *clock)
775
{
776
    switch(clock->type) {
777
    case QEMU_TIMER_REALTIME:
778
#ifdef _WIN32
779
        return GetTickCount();
780
#else
781
        {
782
            struct tms tp;
783

    
784
            /* Note that using gettimeofday() is not a good solution
785
               for timers because its value change when the date is
786
               modified. */
787
            if (timer_freq == 100) {
788
                return times(&tp) * 10;
789
            } else {
790
                return ((int64_t)times(&tp) * 1000) / timer_freq;
791
            }
792
        }
793
#endif
794
    default:
795
    case QEMU_TIMER_VIRTUAL:
796
        return cpu_get_ticks();
797
    }
798
}
799

    
800
/* save a timer */
801
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
802
{
803
    uint64_t expire_time;
804

    
805
    if (qemu_timer_pending(ts)) {
806
        expire_time = ts->expire_time;
807
    } else {
808
        expire_time = -1;
809
    }
810
    qemu_put_be64(f, expire_time);
811
}
812

    
813
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
814
{
815
    uint64_t expire_time;
816

    
817
    expire_time = qemu_get_be64(f);
818
    if (expire_time != -1) {
819
        qemu_mod_timer(ts, expire_time);
820
    } else {
821
        qemu_del_timer(ts);
822
    }
823
}
824

    
825
static void timer_save(QEMUFile *f, void *opaque)
826
{
827
    if (cpu_ticks_enabled) {
828
        hw_error("cannot save state if virtual timers are running");
829
    }
830
    qemu_put_be64s(f, &cpu_ticks_offset);
831
    qemu_put_be64s(f, &ticks_per_sec);
832
}
833

    
834
static int timer_load(QEMUFile *f, void *opaque, int version_id)
835
{
836
    if (version_id != 1)
837
        return -EINVAL;
838
    if (cpu_ticks_enabled) {
839
        return -EINVAL;
840
    }
841
    qemu_get_be64s(f, &cpu_ticks_offset);
842
    qemu_get_be64s(f, &ticks_per_sec);
843
    return 0;
844
}
845

    
846
#ifdef _WIN32
847
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
848
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
849
#else
850
static void host_alarm_handler(int host_signum)
851
#endif
852
{
853
#if 0
854
#define DISP_FREQ 1000
855
    {
856
        static int64_t delta_min = INT64_MAX;
857
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
858
        static int count;
859
        ti = qemu_get_clock(vm_clock);
860
        if (last_clock != 0) {
861
            delta = ti - last_clock;
862
            if (delta < delta_min)
863
                delta_min = delta;
864
            if (delta > delta_max)
865
                delta_max = delta;
866
            delta_cum += delta;
867
            if (++count == DISP_FREQ) {
868
                printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
869
                       muldiv64(delta_min, 1000000, ticks_per_sec),
870
                       muldiv64(delta_max, 1000000, ticks_per_sec),
871
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
872
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
873
                count = 0;
874
                delta_min = INT64_MAX;
875
                delta_max = 0;
876
                delta_cum = 0;
877
            }
878
        }
879
        last_clock = ti;
880
    }
881
#endif
882
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
883
                           qemu_get_clock(vm_clock)) ||
884
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
885
                           qemu_get_clock(rt_clock))) {
886
        CPUState *env = cpu_single_env;
887
        if (env) {
888
            /* stop the currently executing cpu because a timer occured */
889
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
890
#ifdef USE_KQEMU
891
            if (env->kqemu_enabled) {
892
                kqemu_cpu_interrupt(env);
893
            }
894
#endif
895
        }
896
    }
897
}
898

    
899
#ifndef _WIN32
900

    
901
#if defined(__linux__)
902

    
903
#define RTC_FREQ 1024
904

    
905
static int rtc_fd;
906

    
907
static int start_rtc_timer(void)
908
{
909
    rtc_fd = open("/dev/rtc", O_RDONLY);
910
    if (rtc_fd < 0)
911
        return -1;
912
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
913
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
914
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
915
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
916
        goto fail;
917
    }
918
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
919
    fail:
920
        close(rtc_fd);
921
        return -1;
922
    }
923
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
924
    return 0;
925
}
926

    
927
#else
928

    
929
static int start_rtc_timer(void)
930
{
931
    return -1;
932
}
933

    
934
#endif /* !defined(__linux__) */
935

    
936
#endif /* !defined(_WIN32) */
937

    
938
static void init_timers(void)
939
{
940
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
941
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
942

    
943
#ifdef _WIN32
944
    {
945
        int count=0;
946
        timerID = timeSetEvent(1,     // interval (ms)
947
                               0,     // resolution
948
                               host_alarm_handler, // function
949
                               (DWORD)&count,  // user parameter
950
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
951
         if( !timerID ) {
952
            perror("failed timer alarm");
953
            exit(1);
954
         }
955
    }
956
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
957
#else
958
    {
959
        struct sigaction act;
960
        struct itimerval itv;
961
        
962
        /* get times() syscall frequency */
963
        timer_freq = sysconf(_SC_CLK_TCK);
964
        
965
        /* timer signal */
966
        sigfillset(&act.sa_mask);
967
       act.sa_flags = 0;
968
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
969
        act.sa_flags |= SA_ONSTACK;
970
#endif
971
        act.sa_handler = host_alarm_handler;
972
        sigaction(SIGALRM, &act, NULL);
973

    
974
        itv.it_interval.tv_sec = 0;
975
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
976
        itv.it_value.tv_sec = 0;
977
        itv.it_value.tv_usec = 10 * 1000;
978
        setitimer(ITIMER_REAL, &itv, NULL);
979
        /* we probe the tick duration of the kernel to inform the user if
980
           the emulated kernel requested a too high timer frequency */
981
        getitimer(ITIMER_REAL, &itv);
982

    
983
#if defined(__linux__)
984
        if (itv.it_interval.tv_usec > 1000) {
985
            /* try to use /dev/rtc to have a faster timer */
986
            if (start_rtc_timer() < 0)
987
                goto use_itimer;
988
            /* disable itimer */
989
            itv.it_interval.tv_sec = 0;
990
            itv.it_interval.tv_usec = 0;
991
            itv.it_value.tv_sec = 0;
992
            itv.it_value.tv_usec = 0;
993
            setitimer(ITIMER_REAL, &itv, NULL);
994

    
995
            /* use the RTC */
996
            sigaction(SIGIO, &act, NULL);
997
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
998
            fcntl(rtc_fd, F_SETOWN, getpid());
999
        } else 
1000
#endif /* defined(__linux__) */
1001
        {
1002
        use_itimer:
1003
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1004
                                   PIT_FREQ) / 1000000;
1005
        }
1006
    }
1007
#endif
1008
}
1009

    
1010
void quit_timers(void)
1011
{
1012
#ifdef _WIN32
1013
    timeKillEvent(timerID);
1014
#endif
1015
}
1016

    
1017
/***********************************************************/
1018
/* character device */
1019

    
1020
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1021
{
1022
    return s->chr_write(s, buf, len);
1023
}
1024

    
1025
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1026
{
1027
    if (!s->chr_ioctl)
1028
        return -ENOTSUP;
1029
    return s->chr_ioctl(s, cmd, arg);
1030
}
1031

    
1032
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1033
{
1034
    char buf[4096];
1035
    va_list ap;
1036
    va_start(ap, fmt);
1037
    vsnprintf(buf, sizeof(buf), fmt, ap);
1038
    qemu_chr_write(s, buf, strlen(buf));
1039
    va_end(ap);
1040
}
1041

    
1042
void qemu_chr_send_event(CharDriverState *s, int event)
1043
{
1044
    if (s->chr_send_event)
1045
        s->chr_send_event(s, event);
1046
}
1047

    
1048
void qemu_chr_add_read_handler(CharDriverState *s, 
1049
                               IOCanRWHandler *fd_can_read, 
1050
                               IOReadHandler *fd_read, void *opaque)
1051
{
1052
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1053
}
1054
             
1055
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1056
{
1057
    s->chr_event = chr_event;
1058
}
1059

    
1060
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1061
{
1062
    return len;
1063
}
1064

    
1065
static void null_chr_add_read_handler(CharDriverState *chr, 
1066
                                    IOCanRWHandler *fd_can_read, 
1067
                                    IOReadHandler *fd_read, void *opaque)
1068
{
1069
}
1070

    
1071
CharDriverState *qemu_chr_open_null(void)
1072
{
1073
    CharDriverState *chr;
1074

    
1075
    chr = qemu_mallocz(sizeof(CharDriverState));
1076
    if (!chr)
1077
        return NULL;
1078
    chr->chr_write = null_chr_write;
1079
    chr->chr_add_read_handler = null_chr_add_read_handler;
1080
    return chr;
1081
}
1082

    
1083
#ifdef _WIN32
1084

    
1085
#define socket_error() WSAGetLastError()
1086
#undef EINTR
1087
#define EWOULDBLOCK WSAEWOULDBLOCK
1088
#define EINTR       WSAEINTR
1089
#define EINPROGRESS WSAEINPROGRESS
1090

    
1091
static void socket_cleanup(void)
1092
{
1093
    WSACleanup();
1094
}
1095

    
1096
static int socket_init(void)
1097
{
1098
    WSADATA Data;
1099
    int ret, err;
1100

    
1101
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1102
    if (ret != 0) {
1103
        err = WSAGetLastError();
1104
        fprintf(stderr, "WSAStartup: %d\n", err);
1105
        return -1;
1106
    }
1107
    atexit(socket_cleanup);
1108
    return 0;
1109
}
1110

    
1111
static int send_all(int fd, const uint8_t *buf, int len1)
1112
{
1113
    int ret, len;
1114
    
1115
    len = len1;
1116
    while (len > 0) {
1117
        ret = send(fd, buf, len, 0);
1118
        if (ret < 0) {
1119
            int errno;
1120
            errno = WSAGetLastError();
1121
            if (errno != WSAEWOULDBLOCK) {
1122
                return -1;
1123
            }
1124
        } else if (ret == 0) {
1125
            break;
1126
        } else {
1127
            buf += ret;
1128
            len -= ret;
1129
        }
1130
    }
1131
    return len1 - len;
1132
}
1133

    
1134
void socket_set_nonblock(int fd)
1135
{
1136
    unsigned long opt = 1;
1137
    ioctlsocket(fd, FIONBIO, &opt);
1138
}
1139

    
1140
#else
1141

    
1142
#define socket_error() errno
1143
#define closesocket(s) close(s)
1144

    
1145
static int unix_write(int fd, const uint8_t *buf, int len1)
1146
{
1147
    int ret, len;
1148

    
1149
    len = len1;
1150
    while (len > 0) {
1151
        ret = write(fd, buf, len);
1152
        if (ret < 0) {
1153
            if (errno != EINTR && errno != EAGAIN)
1154
                return -1;
1155
        } else if (ret == 0) {
1156
            break;
1157
        } else {
1158
            buf += ret;
1159
            len -= ret;
1160
        }
1161
    }
1162
    return len1 - len;
1163
}
1164

    
1165
static inline int send_all(int fd, const uint8_t *buf, int len1)
1166
{
1167
    return unix_write(fd, buf, len1);
1168
}
1169

    
1170
void socket_set_nonblock(int fd)
1171
{
1172
    fcntl(fd, F_SETFL, O_NONBLOCK);
1173
}
1174
#endif /* !_WIN32 */
1175

    
1176
#ifndef _WIN32
1177

    
1178
typedef struct {
1179
    int fd_in, fd_out;
1180
    IOCanRWHandler *fd_can_read; 
1181
    IOReadHandler *fd_read;
1182
    void *fd_opaque;
1183
    int max_size;
1184
} FDCharDriver;
1185

    
1186
#define STDIO_MAX_CLIENTS 2
1187

    
1188
static int stdio_nb_clients;
1189
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1190

    
1191
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1192
{
1193
    FDCharDriver *s = chr->opaque;
1194
    return unix_write(s->fd_out, buf, len);
1195
}
1196

    
1197
static int fd_chr_read_poll(void *opaque)
1198
{
1199
    CharDriverState *chr = opaque;
1200
    FDCharDriver *s = chr->opaque;
1201

    
1202
    s->max_size = s->fd_can_read(s->fd_opaque);
1203
    return s->max_size;
1204
}
1205

    
1206
static void fd_chr_read(void *opaque)
1207
{
1208
    CharDriverState *chr = opaque;
1209
    FDCharDriver *s = chr->opaque;
1210
    int size, len;
1211
    uint8_t buf[1024];
1212
    
1213
    len = sizeof(buf);
1214
    if (len > s->max_size)
1215
        len = s->max_size;
1216
    if (len == 0)
1217
        return;
1218
    size = read(s->fd_in, buf, len);
1219
    if (size > 0) {
1220
        s->fd_read(s->fd_opaque, buf, size);
1221
    }
1222
}
1223

    
1224
static void fd_chr_add_read_handler(CharDriverState *chr, 
1225
                                    IOCanRWHandler *fd_can_read, 
1226
                                    IOReadHandler *fd_read, void *opaque)
1227
{
1228
    FDCharDriver *s = chr->opaque;
1229

    
1230
    if (s->fd_in >= 0) {
1231
        s->fd_can_read = fd_can_read;
1232
        s->fd_read = fd_read;
1233
        s->fd_opaque = opaque;
1234
        if (nographic && s->fd_in == 0) {
1235
        } else {
1236
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1237
                                 fd_chr_read, NULL, chr);
1238
        }
1239
    }
1240
}
1241

    
1242
/* open a character device to a unix fd */
1243
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1244
{
1245
    CharDriverState *chr;
1246
    FDCharDriver *s;
1247

    
1248
    chr = qemu_mallocz(sizeof(CharDriverState));
1249
    if (!chr)
1250
        return NULL;
1251
    s = qemu_mallocz(sizeof(FDCharDriver));
1252
    if (!s) {
1253
        free(chr);
1254
        return NULL;
1255
    }
1256
    s->fd_in = fd_in;
1257
    s->fd_out = fd_out;
1258
    chr->opaque = s;
1259
    chr->chr_write = fd_chr_write;
1260
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1261
    return chr;
1262
}
1263

    
1264
CharDriverState *qemu_chr_open_file_out(const char *file_out)
1265
{
1266
    int fd_out;
1267

    
1268
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1269
    if (fd_out < 0)
1270
        return NULL;
1271
    return qemu_chr_open_fd(-1, fd_out);
1272
}
1273

    
1274
CharDriverState *qemu_chr_open_pipe(const char *filename)
1275
{
1276
    int fd;
1277

    
1278
    fd = open(filename, O_RDWR | O_BINARY);
1279
    if (fd < 0)
1280
        return NULL;
1281
    return qemu_chr_open_fd(fd, fd);
1282
}
1283

    
1284

    
1285
/* for STDIO, we handle the case where several clients use it
1286
   (nographic mode) */
1287

    
1288
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1289

    
1290
#define TERM_FIFO_MAX_SIZE 1
1291

    
1292
static int term_got_escape, client_index;
1293
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1294
int term_fifo_size;
1295

    
1296
void term_print_help(void)
1297
{
1298
    printf("\n"
1299
           "C-a h    print this help\n"
1300
           "C-a x    exit emulator\n"
1301
           "C-a s    save disk data back to file (if -snapshot)\n"
1302
           "C-a b    send break (magic sysrq)\n"
1303
           "C-a c    switch between console and monitor\n"
1304
           "C-a C-a  send C-a\n"
1305
           );
1306
}
1307

    
1308
/* called when a char is received */
1309
static void stdio_received_byte(int ch)
1310
{
1311
    if (term_got_escape) {
1312
        term_got_escape = 0;
1313
        switch(ch) {
1314
        case 'h':
1315
            term_print_help();
1316
            break;
1317
        case 'x':
1318
            exit(0);
1319
            break;
1320
        case 's': 
1321
            {
1322
                int i;
1323
                for (i = 0; i < MAX_DISKS; i++) {
1324
                    if (bs_table[i])
1325
                        bdrv_commit(bs_table[i]);
1326
                }
1327
            }
1328
            break;
1329
        case 'b':
1330
            if (client_index < stdio_nb_clients) {
1331
                CharDriverState *chr;
1332
                FDCharDriver *s;
1333

    
1334
                chr = stdio_clients[client_index];
1335
                s = chr->opaque;
1336
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1337
            }
1338
            break;
1339
        case 'c':
1340
            client_index++;
1341
            if (client_index >= stdio_nb_clients)
1342
                client_index = 0;
1343
            if (client_index == 0) {
1344
                /* send a new line in the monitor to get the prompt */
1345
                ch = '\r';
1346
                goto send_char;
1347
            }
1348
            break;
1349
        case TERM_ESCAPE:
1350
            goto send_char;
1351
        }
1352
    } else if (ch == TERM_ESCAPE) {
1353
        term_got_escape = 1;
1354
    } else {
1355
    send_char:
1356
        if (client_index < stdio_nb_clients) {
1357
            uint8_t buf[1];
1358
            CharDriverState *chr;
1359
            FDCharDriver *s;
1360
            
1361
            chr = stdio_clients[client_index];
1362
            s = chr->opaque;
1363
            if (s->fd_can_read(s->fd_opaque) > 0) {
1364
                buf[0] = ch;
1365
                s->fd_read(s->fd_opaque, buf, 1);
1366
            } else if (term_fifo_size == 0) {
1367
                term_fifo[term_fifo_size++] = ch;
1368
            }
1369
        }
1370
    }
1371
}
1372

    
1373
static int stdio_read_poll(void *opaque)
1374
{
1375
    CharDriverState *chr;
1376
    FDCharDriver *s;
1377

    
1378
    if (client_index < stdio_nb_clients) {
1379
        chr = stdio_clients[client_index];
1380
        s = chr->opaque;
1381
        /* try to flush the queue if needed */
1382
        if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1383
            s->fd_read(s->fd_opaque, term_fifo, 1);
1384
            term_fifo_size = 0;
1385
        }
1386
        /* see if we can absorb more chars */
1387
        if (term_fifo_size == 0)
1388
            return 1;
1389
        else
1390
            return 0;
1391
    } else {
1392
        return 1;
1393
    }
1394
}
1395

    
1396
static void stdio_read(void *opaque)
1397
{
1398
    int size;
1399
    uint8_t buf[1];
1400
    
1401
    size = read(0, buf, 1);
1402
    if (size > 0)
1403
        stdio_received_byte(buf[0]);
1404
}
1405

    
1406
/* init terminal so that we can grab keys */
1407
static struct termios oldtty;
1408
static int old_fd0_flags;
1409

    
1410
static void term_exit(void)
1411
{
1412
    tcsetattr (0, TCSANOW, &oldtty);
1413
    fcntl(0, F_SETFL, old_fd0_flags);
1414
}
1415

    
1416
static void term_init(void)
1417
{
1418
    struct termios tty;
1419

    
1420
    tcgetattr (0, &tty);
1421
    oldtty = tty;
1422
    old_fd0_flags = fcntl(0, F_GETFL);
1423

    
1424
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1425
                          |INLCR|IGNCR|ICRNL|IXON);
1426
    tty.c_oflag |= OPOST;
1427
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1428
    /* if graphical mode, we allow Ctrl-C handling */
1429
    if (nographic)
1430
        tty.c_lflag &= ~ISIG;
1431
    tty.c_cflag &= ~(CSIZE|PARENB);
1432
    tty.c_cflag |= CS8;
1433
    tty.c_cc[VMIN] = 1;
1434
    tty.c_cc[VTIME] = 0;
1435
    
1436
    tcsetattr (0, TCSANOW, &tty);
1437

    
1438
    atexit(term_exit);
1439

    
1440
    fcntl(0, F_SETFL, O_NONBLOCK);
1441
}
1442

    
1443
CharDriverState *qemu_chr_open_stdio(void)
1444
{
1445
    CharDriverState *chr;
1446

    
1447
    if (nographic) {
1448
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1449
            return NULL;
1450
        chr = qemu_chr_open_fd(0, 1);
1451
        if (stdio_nb_clients == 0)
1452
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1453
        client_index = stdio_nb_clients;
1454
    } else {
1455
        if (stdio_nb_clients != 0)
1456
            return NULL;
1457
        chr = qemu_chr_open_fd(0, 1);
1458
    }
1459
    stdio_clients[stdio_nb_clients++] = chr;
1460
    if (stdio_nb_clients == 1) {
1461
        /* set the terminal in raw mode */
1462
        term_init();
1463
    }
1464
    return chr;
1465
}
1466

    
1467
#if defined(__linux__)
1468
CharDriverState *qemu_chr_open_pty(void)
1469
{
1470
    struct termios tty;
1471
    char slave_name[1024];
1472
    int master_fd, slave_fd;
1473
    
1474
    /* Not satisfying */
1475
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1476
        return NULL;
1477
    }
1478
    
1479
    /* Disabling local echo and line-buffered output */
1480
    tcgetattr (master_fd, &tty);
1481
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1482
    tty.c_cc[VMIN] = 1;
1483
    tty.c_cc[VTIME] = 0;
1484
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1485

    
1486
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1487
    return qemu_chr_open_fd(master_fd, master_fd);
1488
}
1489

    
1490
static void tty_serial_init(int fd, int speed, 
1491
                            int parity, int data_bits, int stop_bits)
1492
{
1493
    struct termios tty;
1494
    speed_t spd;
1495

    
1496
#if 0
1497
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1498
           speed, parity, data_bits, stop_bits);
1499
#endif
1500
    tcgetattr (fd, &tty);
1501

    
1502
    switch(speed) {
1503
    case 50:
1504
        spd = B50;
1505
        break;
1506
    case 75:
1507
        spd = B75;
1508
        break;
1509
    case 300:
1510
        spd = B300;
1511
        break;
1512
    case 600:
1513
        spd = B600;
1514
        break;
1515
    case 1200:
1516
        spd = B1200;
1517
        break;
1518
    case 2400:
1519
        spd = B2400;
1520
        break;
1521
    case 4800:
1522
        spd = B4800;
1523
        break;
1524
    case 9600:
1525
        spd = B9600;
1526
        break;
1527
    case 19200:
1528
        spd = B19200;
1529
        break;
1530
    case 38400:
1531
        spd = B38400;
1532
        break;
1533
    case 57600:
1534
        spd = B57600;
1535
        break;
1536
    default:
1537
    case 115200:
1538
        spd = B115200;
1539
        break;
1540
    }
1541

    
1542
    cfsetispeed(&tty, spd);
1543
    cfsetospeed(&tty, spd);
1544

    
1545
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1546
                          |INLCR|IGNCR|ICRNL|IXON);
1547
    tty.c_oflag |= OPOST;
1548
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1549
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1550
    switch(data_bits) {
1551
    default:
1552
    case 8:
1553
        tty.c_cflag |= CS8;
1554
        break;
1555
    case 7:
1556
        tty.c_cflag |= CS7;
1557
        break;
1558
    case 6:
1559
        tty.c_cflag |= CS6;
1560
        break;
1561
    case 5:
1562
        tty.c_cflag |= CS5;
1563
        break;
1564
    }
1565
    switch(parity) {
1566
    default:
1567
    case 'N':
1568
        break;
1569
    case 'E':
1570
        tty.c_cflag |= PARENB;
1571
        break;
1572
    case 'O':
1573
        tty.c_cflag |= PARENB | PARODD;
1574
        break;
1575
    }
1576
    
1577
    tcsetattr (fd, TCSANOW, &tty);
1578
}
1579

    
1580
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1581
{
1582
    FDCharDriver *s = chr->opaque;
1583
    
1584
    switch(cmd) {
1585
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1586
        {
1587
            QEMUSerialSetParams *ssp = arg;
1588
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1589
                            ssp->data_bits, ssp->stop_bits);
1590
        }
1591
        break;
1592
    case CHR_IOCTL_SERIAL_SET_BREAK:
1593
        {
1594
            int enable = *(int *)arg;
1595
            if (enable)
1596
                tcsendbreak(s->fd_in, 1);
1597
        }
1598
        break;
1599
    default:
1600
        return -ENOTSUP;
1601
    }
1602
    return 0;
1603
}
1604

    
1605
CharDriverState *qemu_chr_open_tty(const char *filename)
1606
{
1607
    CharDriverState *chr;
1608
    int fd;
1609

    
1610
    fd = open(filename, O_RDWR | O_NONBLOCK);
1611
    if (fd < 0)
1612
        return NULL;
1613
    fcntl(fd, F_SETFL, O_NONBLOCK);
1614
    tty_serial_init(fd, 115200, 'N', 8, 1);
1615
    chr = qemu_chr_open_fd(fd, fd);
1616
    if (!chr)
1617
        return NULL;
1618
    chr->chr_ioctl = tty_serial_ioctl;
1619
    return chr;
1620
}
1621

    
1622
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1623
{
1624
    int fd = (int)chr->opaque;
1625
    uint8_t b;
1626

    
1627
    switch(cmd) {
1628
    case CHR_IOCTL_PP_READ_DATA:
1629
        if (ioctl(fd, PPRDATA, &b) < 0)
1630
            return -ENOTSUP;
1631
        *(uint8_t *)arg = b;
1632
        break;
1633
    case CHR_IOCTL_PP_WRITE_DATA:
1634
        b = *(uint8_t *)arg;
1635
        if (ioctl(fd, PPWDATA, &b) < 0)
1636
            return -ENOTSUP;
1637
        break;
1638
    case CHR_IOCTL_PP_READ_CONTROL:
1639
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1640
            return -ENOTSUP;
1641
        *(uint8_t *)arg = b;
1642
        break;
1643
    case CHR_IOCTL_PP_WRITE_CONTROL:
1644
        b = *(uint8_t *)arg;
1645
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1646
            return -ENOTSUP;
1647
        break;
1648
    case CHR_IOCTL_PP_READ_STATUS:
1649
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1650
            return -ENOTSUP;
1651
        *(uint8_t *)arg = b;
1652
        break;
1653
    default:
1654
        return -ENOTSUP;
1655
    }
1656
    return 0;
1657
}
1658

    
1659
CharDriverState *qemu_chr_open_pp(const char *filename)
1660
{
1661
    CharDriverState *chr;
1662
    int fd;
1663

    
1664
    fd = open(filename, O_RDWR);
1665
    if (fd < 0)
1666
        return NULL;
1667

    
1668
    if (ioctl(fd, PPCLAIM) < 0) {
1669
        close(fd);
1670
        return NULL;
1671
    }
1672

    
1673
    chr = qemu_mallocz(sizeof(CharDriverState));
1674
    if (!chr) {
1675
        close(fd);
1676
        return NULL;
1677
    }
1678
    chr->opaque = (void *)fd;
1679
    chr->chr_write = null_chr_write;
1680
    chr->chr_add_read_handler = null_chr_add_read_handler;
1681
    chr->chr_ioctl = pp_ioctl;
1682
    return chr;
1683
}
1684

    
1685
#else
1686
CharDriverState *qemu_chr_open_pty(void)
1687
{
1688
    return NULL;
1689
}
1690
#endif
1691

    
1692
#endif /* !defined(_WIN32) */
1693

    
1694
#ifdef _WIN32
1695
typedef struct {
1696
    IOCanRWHandler *fd_can_read; 
1697
    IOReadHandler *fd_read;
1698
    void *win_opaque;
1699
    int max_size;
1700
    HANDLE hcom, hrecv, hsend;
1701
    OVERLAPPED orecv, osend;
1702
    BOOL fpipe;
1703
    DWORD len;
1704
} WinCharState;
1705

    
1706
#define NSENDBUF 2048
1707
#define NRECVBUF 2048
1708
#define MAXCONNECT 1
1709
#define NTIMEOUT 5000
1710

    
1711
static int win_chr_poll(void *opaque);
1712
static int win_chr_pipe_poll(void *opaque);
1713

    
1714
static void win_chr_close2(WinCharState *s)
1715
{
1716
    if (s->hsend) {
1717
        CloseHandle(s->hsend);
1718
        s->hsend = NULL;
1719
    }
1720
    if (s->hrecv) {
1721
        CloseHandle(s->hrecv);
1722
        s->hrecv = NULL;
1723
    }
1724
    if (s->hcom) {
1725
        CloseHandle(s->hcom);
1726
        s->hcom = NULL;
1727
    }
1728
    if (s->fpipe)
1729
        qemu_del_polling_cb(win_chr_pipe_poll, s);
1730
    else
1731
        qemu_del_polling_cb(win_chr_poll, s);
1732
}
1733

    
1734
static void win_chr_close(CharDriverState *chr)
1735
{
1736
    WinCharState *s = chr->opaque;
1737
    win_chr_close2(s);
1738
}
1739

    
1740
static int win_chr_init(WinCharState *s, const char *filename)
1741
{
1742
    COMMCONFIG comcfg;
1743
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1744
    COMSTAT comstat;
1745
    DWORD size;
1746
    DWORD err;
1747
    
1748
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1749
    if (!s->hsend) {
1750
        fprintf(stderr, "Failed CreateEvent\n");
1751
        goto fail;
1752
    }
1753
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1754
    if (!s->hrecv) {
1755
        fprintf(stderr, "Failed CreateEvent\n");
1756
        goto fail;
1757
    }
1758

    
1759
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1760
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1761
    if (s->hcom == INVALID_HANDLE_VALUE) {
1762
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1763
        s->hcom = NULL;
1764
        goto fail;
1765
    }
1766
    
1767
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1768
        fprintf(stderr, "Failed SetupComm\n");
1769
        goto fail;
1770
    }
1771
    
1772
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1773
    size = sizeof(COMMCONFIG);
1774
    GetDefaultCommConfig(filename, &comcfg, &size);
1775
    comcfg.dcb.DCBlength = sizeof(DCB);
1776
    CommConfigDialog(filename, NULL, &comcfg);
1777

    
1778
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1779
        fprintf(stderr, "Failed SetCommState\n");
1780
        goto fail;
1781
    }
1782

    
1783
    if (!SetCommMask(s->hcom, EV_ERR)) {
1784
        fprintf(stderr, "Failed SetCommMask\n");
1785
        goto fail;
1786
    }
1787

    
1788
    cto.ReadIntervalTimeout = MAXDWORD;
1789
    if (!SetCommTimeouts(s->hcom, &cto)) {
1790
        fprintf(stderr, "Failed SetCommTimeouts\n");
1791
        goto fail;
1792
    }
1793
    
1794
    if (!ClearCommError(s->hcom, &err, &comstat)) {
1795
        fprintf(stderr, "Failed ClearCommError\n");
1796
        goto fail;
1797
    }
1798
    qemu_add_polling_cb(win_chr_poll, s);
1799
    return 0;
1800

    
1801
 fail:
1802
    win_chr_close2(s);
1803
    return -1;
1804
}
1805

    
1806
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1807
{
1808
    WinCharState *s = chr->opaque;
1809
    DWORD len, ret, size, err;
1810

    
1811
    len = len1;
1812
    ZeroMemory(&s->osend, sizeof(s->osend));
1813
    s->osend.hEvent = s->hsend;
1814
    while (len > 0) {
1815
        if (s->hsend)
1816
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1817
        else
1818
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1819
        if (!ret) {
1820
            err = GetLastError();
1821
            if (err == ERROR_IO_PENDING) {
1822
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1823
                if (ret) {
1824
                    buf += size;
1825
                    len -= size;
1826
                } else {
1827
                    break;
1828
                }
1829
            } else {
1830
                break;
1831
            }
1832
        } else {
1833
            buf += size;
1834
            len -= size;
1835
        }
1836
    }
1837
    return len1 - len;
1838
}
1839

    
1840
static int win_chr_read_poll(WinCharState *s)
1841
{
1842
    s->max_size = s->fd_can_read(s->win_opaque);
1843
    return s->max_size;
1844
}
1845
            
1846
static void win_chr_readfile(WinCharState *s)
1847
{
1848
    int ret, err;
1849
    uint8_t buf[1024];
1850
    DWORD size;
1851
    
1852
    ZeroMemory(&s->orecv, sizeof(s->orecv));
1853
    s->orecv.hEvent = s->hrecv;
1854
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1855
    if (!ret) {
1856
        err = GetLastError();
1857
        if (err == ERROR_IO_PENDING) {
1858
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1859
        }
1860
    }
1861

    
1862
    if (size > 0) {
1863
        s->fd_read(s->win_opaque, buf, size);
1864
    }
1865
}
1866

    
1867
static void win_chr_read(WinCharState *s)
1868
{
1869
    if (s->len > s->max_size)
1870
        s->len = s->max_size;
1871
    if (s->len == 0)
1872
        return;
1873
    
1874
    win_chr_readfile(s);
1875
}
1876

    
1877
static int win_chr_poll(void *opaque)
1878
{
1879
    WinCharState *s = opaque;
1880
    COMSTAT status;
1881
    DWORD comerr;
1882
    
1883
    ClearCommError(s->hcom, &comerr, &status);
1884
    if (status.cbInQue > 0) {
1885
        s->len = status.cbInQue;
1886
        win_chr_read_poll(s);
1887
        win_chr_read(s);
1888
        return 1;
1889
    }
1890
    return 0;
1891
}
1892

    
1893
static void win_chr_add_read_handler(CharDriverState *chr, 
1894
                                    IOCanRWHandler *fd_can_read, 
1895
                                    IOReadHandler *fd_read, void *opaque)
1896
{
1897
    WinCharState *s = chr->opaque;
1898

    
1899
    s->fd_can_read = fd_can_read;
1900
    s->fd_read = fd_read;
1901
    s->win_opaque = opaque;
1902
}
1903

    
1904
CharDriverState *qemu_chr_open_win(const char *filename)
1905
{
1906
    CharDriverState *chr;
1907
    WinCharState *s;
1908
    
1909
    chr = qemu_mallocz(sizeof(CharDriverState));
1910
    if (!chr)
1911
        return NULL;
1912
    s = qemu_mallocz(sizeof(WinCharState));
1913
    if (!s) {
1914
        free(chr);
1915
        return NULL;
1916
    }
1917
    chr->opaque = s;
1918
    chr->chr_write = win_chr_write;
1919
    chr->chr_add_read_handler = win_chr_add_read_handler;
1920
    chr->chr_close = win_chr_close;
1921

    
1922
    if (win_chr_init(s, filename) < 0) {
1923
        free(s);
1924
        free(chr);
1925
        return NULL;
1926
    }
1927
    return chr;
1928
}
1929

    
1930
static int win_chr_pipe_poll(void *opaque)
1931
{
1932
    WinCharState *s = opaque;
1933
    DWORD size;
1934

    
1935
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1936
    if (size > 0) {
1937
        s->len = size;
1938
        win_chr_read_poll(s);
1939
        win_chr_read(s);
1940
        return 1;
1941
    }
1942
    return 0;
1943
}
1944

    
1945
static int win_chr_pipe_init(WinCharState *s, const char *filename)
1946
{
1947
    OVERLAPPED ov;
1948
    int ret;
1949
    DWORD size;
1950
    char openname[256];
1951
    
1952
    s->fpipe = TRUE;
1953

    
1954
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1955
    if (!s->hsend) {
1956
        fprintf(stderr, "Failed CreateEvent\n");
1957
        goto fail;
1958
    }
1959
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1960
    if (!s->hrecv) {
1961
        fprintf(stderr, "Failed CreateEvent\n");
1962
        goto fail;
1963
    }
1964
    
1965
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1966
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1967
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1968
                              PIPE_WAIT,
1969
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1970
    if (s->hcom == INVALID_HANDLE_VALUE) {
1971
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1972
        s->hcom = NULL;
1973
        goto fail;
1974
    }
1975

    
1976
    ZeroMemory(&ov, sizeof(ov));
1977
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1978
    ret = ConnectNamedPipe(s->hcom, &ov);
1979
    if (ret) {
1980
        fprintf(stderr, "Failed ConnectNamedPipe\n");
1981
        goto fail;
1982
    }
1983

    
1984
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1985
    if (!ret) {
1986
        fprintf(stderr, "Failed GetOverlappedResult\n");
1987
        if (ov.hEvent) {
1988
            CloseHandle(ov.hEvent);
1989
            ov.hEvent = NULL;
1990
        }
1991
        goto fail;
1992
    }
1993

    
1994
    if (ov.hEvent) {
1995
        CloseHandle(ov.hEvent);
1996
        ov.hEvent = NULL;
1997
    }
1998
    qemu_add_polling_cb(win_chr_pipe_poll, s);
1999
    return 0;
2000

    
2001
 fail:
2002
    win_chr_close2(s);
2003
    return -1;
2004
}
2005

    
2006

    
2007
CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2008
{
2009
    CharDriverState *chr;
2010
    WinCharState *s;
2011

    
2012
    chr = qemu_mallocz(sizeof(CharDriverState));
2013
    if (!chr)
2014
        return NULL;
2015
    s = qemu_mallocz(sizeof(WinCharState));
2016
    if (!s) {
2017
        free(chr);
2018
        return NULL;
2019
    }
2020
    chr->opaque = s;
2021
    chr->chr_write = win_chr_write;
2022
    chr->chr_add_read_handler = win_chr_add_read_handler;
2023
    chr->chr_close = win_chr_close;
2024
    
2025
    if (win_chr_pipe_init(s, filename) < 0) {
2026
        free(s);
2027
        free(chr);
2028
        return NULL;
2029
    }
2030
    return chr;
2031
}
2032

    
2033
CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2034
{
2035
    CharDriverState *chr;
2036
    WinCharState *s;
2037

    
2038
    chr = qemu_mallocz(sizeof(CharDriverState));
2039
    if (!chr)
2040
        return NULL;
2041
    s = qemu_mallocz(sizeof(WinCharState));
2042
    if (!s) {
2043
        free(chr);
2044
        return NULL;
2045
    }
2046
    s->hcom = fd_out;
2047
    chr->opaque = s;
2048
    chr->chr_write = win_chr_write;
2049
    chr->chr_add_read_handler = win_chr_add_read_handler;
2050
    return chr;
2051
}
2052
    
2053
CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2054
{
2055
    HANDLE fd_out;
2056
    
2057
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2058
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2059
    if (fd_out == INVALID_HANDLE_VALUE)
2060
        return NULL;
2061

    
2062
    return qemu_chr_open_win_file(fd_out);
2063
}
2064
#endif
2065

    
2066
CharDriverState *qemu_chr_open(const char *filename)
2067
{
2068
    const char *p;
2069

    
2070
    if (!strcmp(filename, "vc")) {
2071
        return text_console_init(&display_state);
2072
    } else if (!strcmp(filename, "null")) {
2073
        return qemu_chr_open_null();
2074
    } else 
2075
#ifndef _WIN32
2076
    if (strstart(filename, "file:", &p)) {
2077
        return qemu_chr_open_file_out(p);
2078
    } else if (strstart(filename, "pipe:", &p)) {
2079
        return qemu_chr_open_pipe(p);
2080
    } else if (!strcmp(filename, "pty")) {
2081
        return qemu_chr_open_pty();
2082
    } else if (!strcmp(filename, "stdio")) {
2083
        return qemu_chr_open_stdio();
2084
    } else 
2085
#endif
2086
#if defined(__linux__)
2087
    if (strstart(filename, "/dev/parport", NULL)) {
2088
        return qemu_chr_open_pp(filename);
2089
    } else 
2090
    if (strstart(filename, "/dev/", NULL)) {
2091
        return qemu_chr_open_tty(filename);
2092
    } else 
2093
#endif
2094
#ifdef _WIN32
2095
    if (strstart(filename, "COM", NULL)) {
2096
        return qemu_chr_open_win(filename);
2097
    } else
2098
    if (strstart(filename, "pipe:", &p)) {
2099
        return qemu_chr_open_win_pipe(p);
2100
    } else
2101
    if (strstart(filename, "file:", &p)) {
2102
        return qemu_chr_open_win_file_out(p);
2103
    }
2104
#endif
2105
    {
2106
        return NULL;
2107
    }
2108
}
2109

    
2110
void qemu_chr_close(CharDriverState *chr)
2111
{
2112
    if (chr->chr_close)
2113
        chr->chr_close(chr);
2114
}
2115

    
2116
/***********************************************************/
2117
/* network device redirectors */
2118

    
2119
void hex_dump(FILE *f, const uint8_t *buf, int size)
2120
{
2121
    int len, i, j, c;
2122

    
2123
    for(i=0;i<size;i+=16) {
2124
        len = size - i;
2125
        if (len > 16)
2126
            len = 16;
2127
        fprintf(f, "%08x ", i);
2128
        for(j=0;j<16;j++) {
2129
            if (j < len)
2130
                fprintf(f, " %02x", buf[i+j]);
2131
            else
2132
                fprintf(f, "   ");
2133
        }
2134
        fprintf(f, " ");
2135
        for(j=0;j<len;j++) {
2136
            c = buf[i+j];
2137
            if (c < ' ' || c > '~')
2138
                c = '.';
2139
            fprintf(f, "%c", c);
2140
        }
2141
        fprintf(f, "\n");
2142
    }
2143
}
2144

    
2145
static int parse_macaddr(uint8_t *macaddr, const char *p)
2146
{
2147
    int i;
2148
    for(i = 0; i < 6; i++) {
2149
        macaddr[i] = strtol(p, (char **)&p, 16);
2150
        if (i == 5) {
2151
            if (*p != '\0') 
2152
                return -1;
2153
        } else {
2154
            if (*p != ':') 
2155
                return -1;
2156
            p++;
2157
        }
2158
    }
2159
    return 0;
2160
}
2161

    
2162
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2163
{
2164
    const char *p, *p1;
2165
    int len;
2166
    p = *pp;
2167
    p1 = strchr(p, sep);
2168
    if (!p1)
2169
        return -1;
2170
    len = p1 - p;
2171
    p1++;
2172
    if (buf_size > 0) {
2173
        if (len > buf_size - 1)
2174
            len = buf_size - 1;
2175
        memcpy(buf, p, len);
2176
        buf[len] = '\0';
2177
    }
2178
    *pp = p1;
2179
    return 0;
2180
}
2181

    
2182
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2183
{
2184
    char buf[512];
2185
    struct hostent *he;
2186
    const char *p, *r;
2187
    int port;
2188

    
2189
    p = str;
2190
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2191
        return -1;
2192
    saddr->sin_family = AF_INET;
2193
    if (buf[0] == '\0') {
2194
        saddr->sin_addr.s_addr = 0;
2195
    } else {
2196
        if (isdigit(buf[0])) {
2197
            if (!inet_aton(buf, &saddr->sin_addr))
2198
                return -1;
2199
        } else {
2200
            if ((he = gethostbyname(buf)) == NULL)
2201
                return - 1;
2202
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2203
        }
2204
    }
2205
    port = strtol(p, (char **)&r, 0);
2206
    if (r == p)
2207
        return -1;
2208
    saddr->sin_port = htons(port);
2209
    return 0;
2210
}
2211

    
2212
/* find or alloc a new VLAN */
2213
VLANState *qemu_find_vlan(int id)
2214
{
2215
    VLANState **pvlan, *vlan;
2216
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2217
        if (vlan->id == id)
2218
            return vlan;
2219
    }
2220
    vlan = qemu_mallocz(sizeof(VLANState));
2221
    if (!vlan)
2222
        return NULL;
2223
    vlan->id = id;
2224
    vlan->next = NULL;
2225
    pvlan = &first_vlan;
2226
    while (*pvlan != NULL)
2227
        pvlan = &(*pvlan)->next;
2228
    *pvlan = vlan;
2229
    return vlan;
2230
}
2231

    
2232
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2233
                                      IOReadHandler *fd_read,
2234
                                      IOCanRWHandler *fd_can_read,
2235
                                      void *opaque)
2236
{
2237
    VLANClientState *vc, **pvc;
2238
    vc = qemu_mallocz(sizeof(VLANClientState));
2239
    if (!vc)
2240
        return NULL;
2241
    vc->fd_read = fd_read;
2242
    vc->fd_can_read = fd_can_read;
2243
    vc->opaque = opaque;
2244
    vc->vlan = vlan;
2245

    
2246
    vc->next = NULL;
2247
    pvc = &vlan->first_client;
2248
    while (*pvc != NULL)
2249
        pvc = &(*pvc)->next;
2250
    *pvc = vc;
2251
    return vc;
2252
}
2253

    
2254
int qemu_can_send_packet(VLANClientState *vc1)
2255
{
2256
    VLANState *vlan = vc1->vlan;
2257
    VLANClientState *vc;
2258

    
2259
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2260
        if (vc != vc1) {
2261
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2262
                return 0;
2263
        }
2264
    }
2265
    return 1;
2266
}
2267

    
2268
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2269
{
2270
    VLANState *vlan = vc1->vlan;
2271
    VLANClientState *vc;
2272

    
2273
#if 0
2274
    printf("vlan %d send:\n", vlan->id);
2275
    hex_dump(stdout, buf, size);
2276
#endif
2277
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2278
        if (vc != vc1) {
2279
            vc->fd_read(vc->opaque, buf, size);
2280
        }
2281
    }
2282
}
2283

    
2284
#if defined(CONFIG_SLIRP)
2285

    
2286
/* slirp network adapter */
2287

    
2288
static int slirp_inited;
2289
static VLANClientState *slirp_vc;
2290

    
2291
int slirp_can_output(void)
2292
{
2293
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
2294
}
2295

    
2296
void slirp_output(const uint8_t *pkt, int pkt_len)
2297
{
2298
#if 0
2299
    printf("slirp output:\n");
2300
    hex_dump(stdout, pkt, pkt_len);
2301
#endif
2302
    if (!slirp_vc)
2303
        return;
2304
    qemu_send_packet(slirp_vc, pkt, pkt_len);
2305
}
2306

    
2307
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2308
{
2309
#if 0
2310
    printf("slirp input:\n");
2311
    hex_dump(stdout, buf, size);
2312
#endif
2313
    slirp_input(buf, size);
2314
}
2315

    
2316
static int net_slirp_init(VLANState *vlan)
2317
{
2318
    if (!slirp_inited) {
2319
        slirp_inited = 1;
2320
        slirp_init();
2321
    }
2322
    slirp_vc = qemu_new_vlan_client(vlan, 
2323
                                    slirp_receive, NULL, NULL);
2324
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2325
    return 0;
2326
}
2327

    
2328
static void net_slirp_redir(const char *redir_str)
2329
{
2330
    int is_udp;
2331
    char buf[256], *r;
2332
    const char *p;
2333
    struct in_addr guest_addr;
2334
    int host_port, guest_port;
2335
    
2336
    if (!slirp_inited) {
2337
        slirp_inited = 1;
2338
        slirp_init();
2339
    }
2340

    
2341
    p = redir_str;
2342
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2343
        goto fail;
2344
    if (!strcmp(buf, "tcp")) {
2345
        is_udp = 0;
2346
    } else if (!strcmp(buf, "udp")) {
2347
        is_udp = 1;
2348
    } else {
2349
        goto fail;
2350
    }
2351

    
2352
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2353
        goto fail;
2354
    host_port = strtol(buf, &r, 0);
2355
    if (r == buf)
2356
        goto fail;
2357

    
2358
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2359
        goto fail;
2360
    if (buf[0] == '\0') {
2361
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
2362
    }
2363
    if (!inet_aton(buf, &guest_addr))
2364
        goto fail;
2365
    
2366
    guest_port = strtol(p, &r, 0);
2367
    if (r == p)
2368
        goto fail;
2369
    
2370
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2371
        fprintf(stderr, "qemu: could not set up redirection\n");
2372
        exit(1);
2373
    }
2374
    return;
2375
 fail:
2376
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2377
    exit(1);
2378
}
2379
    
2380
#ifndef _WIN32
2381

    
2382
char smb_dir[1024];
2383

    
2384
static void smb_exit(void)
2385
{
2386
    DIR *d;
2387
    struct dirent *de;
2388
    char filename[1024];
2389

    
2390
    /* erase all the files in the directory */
2391
    d = opendir(smb_dir);
2392
    for(;;) {
2393
        de = readdir(d);
2394
        if (!de)
2395
            break;
2396
        if (strcmp(de->d_name, ".") != 0 &&
2397
            strcmp(de->d_name, "..") != 0) {
2398
            snprintf(filename, sizeof(filename), "%s/%s", 
2399
                     smb_dir, de->d_name);
2400
            unlink(filename);
2401
        }
2402
    }
2403
    closedir(d);
2404
    rmdir(smb_dir);
2405
}
2406

    
2407
/* automatic user mode samba server configuration */
2408
void net_slirp_smb(const char *exported_dir)
2409
{
2410
    char smb_conf[1024];
2411
    char smb_cmdline[1024];
2412
    FILE *f;
2413

    
2414
    if (!slirp_inited) {
2415
        slirp_inited = 1;
2416
        slirp_init();
2417
    }
2418

    
2419
    /* XXX: better tmp dir construction */
2420
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2421
    if (mkdir(smb_dir, 0700) < 0) {
2422
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2423
        exit(1);
2424
    }
2425
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2426
    
2427
    f = fopen(smb_conf, "w");
2428
    if (!f) {
2429
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2430
        exit(1);
2431
    }
2432
    fprintf(f, 
2433
            "[global]\n"
2434
            "private dir=%s\n"
2435
            "smb ports=0\n"
2436
            "socket address=127.0.0.1\n"
2437
            "pid directory=%s\n"
2438
            "lock directory=%s\n"
2439
            "log file=%s/log.smbd\n"
2440
            "smb passwd file=%s/smbpasswd\n"
2441
            "security = share\n"
2442
            "[qemu]\n"
2443
            "path=%s\n"
2444
            "read only=no\n"
2445
            "guest ok=yes\n",
2446
            smb_dir,
2447
            smb_dir,
2448
            smb_dir,
2449
            smb_dir,
2450
            smb_dir,
2451
            exported_dir
2452
            );
2453
    fclose(f);
2454
    atexit(smb_exit);
2455

    
2456
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2457
             smb_conf);
2458
    
2459
    slirp_add_exec(0, smb_cmdline, 4, 139);
2460
}
2461

    
2462
#endif /* !defined(_WIN32) */
2463

    
2464
#endif /* CONFIG_SLIRP */
2465

    
2466
#if !defined(_WIN32)
2467

    
2468
typedef struct TAPState {
2469
    VLANClientState *vc;
2470
    int fd;
2471
} TAPState;
2472

    
2473
static void tap_receive(void *opaque, const uint8_t *buf, int size)
2474
{
2475
    TAPState *s = opaque;
2476
    int ret;
2477
    for(;;) {
2478
        ret = write(s->fd, buf, size);
2479
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2480
        } else {
2481
            break;
2482
        }
2483
    }
2484
}
2485

    
2486
static void tap_send(void *opaque)
2487
{
2488
    TAPState *s = opaque;
2489
    uint8_t buf[4096];
2490
    int size;
2491

    
2492
    size = read(s->fd, buf, sizeof(buf));
2493
    if (size > 0) {
2494
        qemu_send_packet(s->vc, buf, size);
2495
    }
2496
}
2497

    
2498
/* fd support */
2499

    
2500
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2501
{
2502
    TAPState *s;
2503

    
2504
    s = qemu_mallocz(sizeof(TAPState));
2505
    if (!s)
2506
        return NULL;
2507
    s->fd = fd;
2508
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2509
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2510
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2511
    return s;
2512
}
2513

    
2514
#ifdef _BSD
2515
static int tap_open(char *ifname, int ifname_size)
2516
{
2517
    int fd;
2518
    char *dev;
2519
    struct stat s;
2520

    
2521
    fd = open("/dev/tap", O_RDWR);
2522
    if (fd < 0) {
2523
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2524
        return -1;
2525
    }
2526

    
2527
    fstat(fd, &s);
2528
    dev = devname(s.st_rdev, S_IFCHR);
2529
    pstrcpy(ifname, ifname_size, dev);
2530

    
2531
    fcntl(fd, F_SETFL, O_NONBLOCK);
2532
    return fd;
2533
}
2534
#else
2535
static int tap_open(char *ifname, int ifname_size)
2536
{
2537
    struct ifreq ifr;
2538
    int fd, ret;
2539
    
2540
    fd = open("/dev/net/tun", O_RDWR);
2541
    if (fd < 0) {
2542
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2543
        return -1;
2544
    }
2545
    memset(&ifr, 0, sizeof(ifr));
2546
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2547
    if (ifname[0] != '\0')
2548
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2549
    else
2550
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2551
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2552
    if (ret != 0) {
2553
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2554
        close(fd);
2555
        return -1;
2556
    }
2557
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
2558
    fcntl(fd, F_SETFL, O_NONBLOCK);
2559
    return fd;
2560
}
2561
#endif
2562

    
2563
static int net_tap_init(VLANState *vlan, const char *ifname1,
2564
                        const char *setup_script)
2565
{
2566
    TAPState *s;
2567
    int pid, status, fd;
2568
    char *args[3];
2569
    char **parg;
2570
    char ifname[128];
2571

    
2572
    if (ifname1 != NULL)
2573
        pstrcpy(ifname, sizeof(ifname), ifname1);
2574
    else
2575
        ifname[0] = '\0';
2576
    fd = tap_open(ifname, sizeof(ifname));
2577
    if (fd < 0)
2578
        return -1;
2579

    
2580
    if (!setup_script)
2581
        setup_script = "";
2582
    if (setup_script[0] != '\0') {
2583
        /* try to launch network init script */
2584
        pid = fork();
2585
        if (pid >= 0) {
2586
            if (pid == 0) {
2587
                parg = args;
2588
                *parg++ = (char *)setup_script;
2589
                *parg++ = ifname;
2590
                *parg++ = NULL;
2591
                execv(setup_script, args);
2592
                _exit(1);
2593
            }
2594
            while (waitpid(pid, &status, 0) != pid);
2595
            if (!WIFEXITED(status) ||
2596
                WEXITSTATUS(status) != 0) {
2597
                fprintf(stderr, "%s: could not launch network script\n",
2598
                        setup_script);
2599
                return -1;
2600
            }
2601
        }
2602
    }
2603
    s = net_tap_fd_init(vlan, fd);
2604
    if (!s)
2605
        return -1;
2606
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
2607
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
2608
    return 0;
2609
}
2610

    
2611
#endif /* !_WIN32 */
2612

    
2613
/* network connection */
2614
typedef struct NetSocketState {
2615
    VLANClientState *vc;
2616
    int fd;
2617
    int state; /* 0 = getting length, 1 = getting data */
2618
    int index;
2619
    int packet_len;
2620
    uint8_t buf[4096];
2621
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2622
} NetSocketState;
2623

    
2624
typedef struct NetSocketListenState {
2625
    VLANState *vlan;
2626
    int fd;
2627
} NetSocketListenState;
2628

    
2629
/* XXX: we consider we can send the whole packet without blocking */
2630
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2631
{
2632
    NetSocketState *s = opaque;
2633
    uint32_t len;
2634
    len = htonl(size);
2635

    
2636
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2637
    send_all(s->fd, buf, size);
2638
}
2639

    
2640
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2641
{
2642
    NetSocketState *s = opaque;
2643
    sendto(s->fd, buf, size, 0, 
2644
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2645
}
2646

    
2647
static void net_socket_send(void *opaque)
2648
{
2649
    NetSocketState *s = opaque;
2650
    int l, size, err;
2651
    uint8_t buf1[4096];
2652
    const uint8_t *buf;
2653

    
2654
    size = recv(s->fd, buf1, sizeof(buf1), 0);
2655
    if (size < 0) {
2656
        err = socket_error();
2657
        if (err != EWOULDBLOCK) 
2658
            goto eoc;
2659
    } else if (size == 0) {
2660
        /* end of connection */
2661
    eoc:
2662
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2663
        closesocket(s->fd);
2664
        return;
2665
    }
2666
    buf = buf1;
2667
    while (size > 0) {
2668
        /* reassemble a packet from the network */
2669
        switch(s->state) {
2670
        case 0:
2671
            l = 4 - s->index;
2672
            if (l > size)
2673
                l = size;
2674
            memcpy(s->buf + s->index, buf, l);
2675
            buf += l;
2676
            size -= l;
2677
            s->index += l;
2678
            if (s->index == 4) {
2679
                /* got length */
2680
                s->packet_len = ntohl(*(uint32_t *)s->buf);
2681
                s->index = 0;
2682
                s->state = 1;
2683
            }
2684
            break;
2685
        case 1:
2686
            l = s->packet_len - s->index;
2687
            if (l > size)
2688
                l = size;
2689
            memcpy(s->buf + s->index, buf, l);
2690
            s->index += l;
2691
            buf += l;
2692
            size -= l;
2693
            if (s->index >= s->packet_len) {
2694
                qemu_send_packet(s->vc, s->buf, s->packet_len);
2695
                s->index = 0;
2696
                s->state = 0;
2697
            }
2698
            break;
2699
        }
2700
    }
2701
}
2702

    
2703
static void net_socket_send_dgram(void *opaque)
2704
{
2705
    NetSocketState *s = opaque;
2706
    int size;
2707

    
2708
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2709
    if (size < 0) 
2710
        return;
2711
    if (size == 0) {
2712
        /* end of connection */
2713
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2714
        return;
2715
    }
2716
    qemu_send_packet(s->vc, s->buf, size);
2717
}
2718

    
2719
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2720
{
2721
    struct ip_mreq imr;
2722
    int fd;
2723
    int val, ret;
2724
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2725
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2726
                inet_ntoa(mcastaddr->sin_addr), 
2727
                (int)ntohl(mcastaddr->sin_addr.s_addr));
2728
        return -1;
2729

    
2730
    }
2731
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2732
    if (fd < 0) {
2733
        perror("socket(PF_INET, SOCK_DGRAM)");
2734
        return -1;
2735
    }
2736

    
2737
    val = 1;
2738
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
2739
                   (const char *)&val, sizeof(val));
2740
    if (ret < 0) {
2741
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2742
        goto fail;
2743
    }
2744

    
2745
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2746
    if (ret < 0) {
2747
        perror("bind");
2748
        goto fail;
2749
    }
2750
    
2751
    /* Add host to multicast group */
2752
    imr.imr_multiaddr = mcastaddr->sin_addr;
2753
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
2754

    
2755
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
2756
                     (const char *)&imr, sizeof(struct ip_mreq));
2757
    if (ret < 0) {
2758
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
2759
        goto fail;
2760
    }
2761

    
2762
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2763
    val = 1;
2764
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
2765
                   (const char *)&val, sizeof(val));
2766
    if (ret < 0) {
2767
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2768
        goto fail;
2769
    }
2770

    
2771
    socket_set_nonblock(fd);
2772
    return fd;
2773
fail:
2774
    if (fd>=0) close(fd);
2775
    return -1;
2776
}
2777

    
2778
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
2779
                                          int is_connected)
2780
{
2781
    struct sockaddr_in saddr;
2782
    int newfd;
2783
    socklen_t saddr_len;
2784
    NetSocketState *s;
2785

    
2786
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2787
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
2788
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
2789
     */
2790

    
2791
    if (is_connected) {
2792
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2793
            /* must be bound */
2794
            if (saddr.sin_addr.s_addr==0) {
2795
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2796
                        fd);
2797
                return NULL;
2798
            }
2799
            /* clone dgram socket */
2800
            newfd = net_socket_mcast_create(&saddr);
2801
            if (newfd < 0) {
2802
                /* error already reported by net_socket_mcast_create() */
2803
                close(fd);
2804
                return NULL;
2805
            }
2806
            /* clone newfd to fd, close newfd */
2807
            dup2(newfd, fd);
2808
            close(newfd);
2809
        
2810
        } else {
2811
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2812
                    fd, strerror(errno));
2813
            return NULL;
2814
        }
2815
    }
2816

    
2817
    s = qemu_mallocz(sizeof(NetSocketState));
2818
    if (!s)
2819
        return NULL;
2820
    s->fd = fd;
2821

    
2822
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2823
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2824

    
2825
    /* mcast: save bound address as dst */
2826
    if (is_connected) s->dgram_dst=saddr;
2827

    
2828
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2829
            "socket: fd=%d (%s mcast=%s:%d)", 
2830
            fd, is_connected? "cloned" : "",
2831
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2832
    return s;
2833
}
2834

    
2835
static void net_socket_connect(void *opaque)
2836
{
2837
    NetSocketState *s = opaque;
2838
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2839
}
2840

    
2841
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
2842
                                          int is_connected)
2843
{
2844
    NetSocketState *s;
2845
    s = qemu_mallocz(sizeof(NetSocketState));
2846
    if (!s)
2847
        return NULL;
2848
    s->fd = fd;
2849
    s->vc = qemu_new_vlan_client(vlan, 
2850
                                 net_socket_receive, NULL, s);
2851
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2852
             "socket: fd=%d", fd);
2853
    if (is_connected) {
2854
        net_socket_connect(s);
2855
    } else {
2856
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2857
    }
2858
    return s;
2859
}
2860

    
2861
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
2862
                                          int is_connected)
2863
{
2864
    int so_type=-1, optlen=sizeof(so_type);
2865

    
2866
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2867
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2868
        return NULL;
2869
    }
2870
    switch(so_type) {
2871
    case SOCK_DGRAM:
2872
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
2873
    case SOCK_STREAM:
2874
        return net_socket_fd_init_stream(vlan, fd, is_connected);
2875
    default:
2876
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2877
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2878
        return net_socket_fd_init_stream(vlan, fd, is_connected);
2879
    }
2880
    return NULL;
2881
}
2882

    
2883
static void net_socket_accept(void *opaque)
2884
{
2885
    NetSocketListenState *s = opaque;    
2886
    NetSocketState *s1;
2887
    struct sockaddr_in saddr;
2888
    socklen_t len;
2889
    int fd;
2890

    
2891
    for(;;) {
2892
        len = sizeof(saddr);
2893
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2894
        if (fd < 0 && errno != EINTR) {
2895
            return;
2896
        } else if (fd >= 0) {
2897
            break;
2898
        }
2899
    }
2900
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
2901
    if (!s1) {
2902
        close(fd);
2903
    } else {
2904
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2905
                 "socket: connection from %s:%d", 
2906
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2907
    }
2908
}
2909

    
2910
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2911
{
2912
    NetSocketListenState *s;
2913
    int fd, val, ret;
2914
    struct sockaddr_in saddr;
2915

    
2916
    if (parse_host_port(&saddr, host_str) < 0)
2917
        return -1;
2918
    
2919
    s = qemu_mallocz(sizeof(NetSocketListenState));
2920
    if (!s)
2921
        return -1;
2922

    
2923
    fd = socket(PF_INET, SOCK_STREAM, 0);
2924
    if (fd < 0) {
2925
        perror("socket");
2926
        return -1;
2927
    }
2928
    socket_set_nonblock(fd);
2929

    
2930
    /* allow fast reuse */
2931
    val = 1;
2932
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2933
    
2934
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2935
    if (ret < 0) {
2936
        perror("bind");
2937
        return -1;
2938
    }
2939
    ret = listen(fd, 0);
2940
    if (ret < 0) {
2941
        perror("listen");
2942
        return -1;
2943
    }
2944
    s->vlan = vlan;
2945
    s->fd = fd;
2946
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2947
    return 0;
2948
}
2949

    
2950
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2951
{
2952
    NetSocketState *s;
2953
    int fd, connected, ret, err;
2954
    struct sockaddr_in saddr;
2955

    
2956
    if (parse_host_port(&saddr, host_str) < 0)
2957
        return -1;
2958

    
2959
    fd = socket(PF_INET, SOCK_STREAM, 0);
2960
    if (fd < 0) {
2961
        perror("socket");
2962
        return -1;
2963
    }
2964
    socket_set_nonblock(fd);
2965

    
2966
    connected = 0;
2967
    for(;;) {
2968
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2969
        if (ret < 0) {
2970
            err = socket_error();
2971
            if (err == EINTR || err == EWOULDBLOCK) {
2972
            } else if (err == EINPROGRESS) {
2973
                break;
2974
            } else {
2975
                perror("connect");
2976
                closesocket(fd);
2977
                return -1;
2978
            }
2979
        } else {
2980
            connected = 1;
2981
            break;
2982
        }
2983
    }
2984
    s = net_socket_fd_init(vlan, fd, connected);
2985
    if (!s)
2986
        return -1;
2987
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2988
             "socket: connect to %s:%d", 
2989
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2990
    return 0;
2991
}
2992

    
2993
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
2994
{
2995
    NetSocketState *s;
2996
    int fd;
2997
    struct sockaddr_in saddr;
2998

    
2999
    if (parse_host_port(&saddr, host_str) < 0)
3000
        return -1;
3001

    
3002

    
3003
    fd = net_socket_mcast_create(&saddr);
3004
    if (fd < 0)
3005
        return -1;
3006

    
3007
    s = net_socket_fd_init(vlan, fd, 0);
3008
    if (!s)
3009
        return -1;
3010

    
3011
    s->dgram_dst = saddr;
3012
    
3013
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3014
             "socket: mcast=%s:%d", 
3015
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3016
    return 0;
3017

    
3018
}
3019

    
3020
static int get_param_value(char *buf, int buf_size,
3021
                           const char *tag, const char *str)
3022
{
3023
    const char *p;
3024
    char *q;
3025
    char option[128];
3026

    
3027
    p = str;
3028
    for(;;) {
3029
        q = option;
3030
        while (*p != '\0' && *p != '=') {
3031
            if ((q - option) < sizeof(option) - 1)
3032
                *q++ = *p;
3033
            p++;
3034
        }
3035
        *q = '\0';
3036
        if (*p != '=')
3037
            break;
3038
        p++;
3039
        if (!strcmp(tag, option)) {
3040
            q = buf;
3041
            while (*p != '\0' && *p != ',') {
3042
                if ((q - buf) < buf_size - 1)
3043
                    *q++ = *p;
3044
                p++;
3045
            }
3046
            *q = '\0';
3047
            return q - buf;
3048
        } else {
3049
            while (*p != '\0' && *p != ',') {
3050
                p++;
3051
            }
3052
        }
3053
        if (*p != ',')
3054
            break;
3055
        p++;
3056
    }
3057
    return 0;
3058
}
3059

    
3060
int net_client_init(const char *str)
3061
{
3062
    const char *p;
3063
    char *q;
3064
    char device[64];
3065
    char buf[1024];
3066
    int vlan_id, ret;
3067
    VLANState *vlan;
3068

    
3069
    p = str;
3070
    q = device;
3071
    while (*p != '\0' && *p != ',') {
3072
        if ((q - device) < sizeof(device) - 1)
3073
            *q++ = *p;
3074
        p++;
3075
    }
3076
    *q = '\0';
3077
    if (*p == ',')
3078
        p++;
3079
    vlan_id = 0;
3080
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3081
        vlan_id = strtol(buf, NULL, 0);
3082
    }
3083
    vlan = qemu_find_vlan(vlan_id);
3084
    if (!vlan) {
3085
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3086
        return -1;
3087
    }
3088
    if (!strcmp(device, "nic")) {
3089
        NICInfo *nd;
3090
        uint8_t *macaddr;
3091

    
3092
        if (nb_nics >= MAX_NICS) {
3093
            fprintf(stderr, "Too Many NICs\n");
3094
            return -1;
3095
        }
3096
        nd = &nd_table[nb_nics];
3097
        macaddr = nd->macaddr;
3098
        macaddr[0] = 0x52;
3099
        macaddr[1] = 0x54;
3100
        macaddr[2] = 0x00;
3101
        macaddr[3] = 0x12;
3102
        macaddr[4] = 0x34;
3103
        macaddr[5] = 0x56 + nb_nics;
3104

    
3105
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3106
            if (parse_macaddr(macaddr, buf) < 0) {
3107
                fprintf(stderr, "invalid syntax for ethernet address\n");
3108
                return -1;
3109
            }
3110
        }
3111
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3112
            nd->model = strdup(buf);
3113
        }
3114
        nd->vlan = vlan;
3115
        nb_nics++;
3116
        ret = 0;
3117
    } else
3118
    if (!strcmp(device, "none")) {
3119
        /* does nothing. It is needed to signal that no network cards
3120
           are wanted */
3121
        ret = 0;
3122
    } else
3123
#ifdef CONFIG_SLIRP
3124
    if (!strcmp(device, "user")) {
3125
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3126
            if (strlen(buf) > 32)
3127
              buf[32] = 0;
3128
            strcpy(slirp_hostname, buf);
3129
        }
3130
        ret = net_slirp_init(vlan);
3131
    } else
3132
#endif
3133
#ifdef _WIN32
3134
    if (!strcmp(device, "tap")) {
3135
        char ifname[64];
3136
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3137
            fprintf(stderr, "tap: no interface name\n");
3138
            return -1;
3139
        }
3140
        ret = tap_win32_init(vlan, ifname);
3141
    } else
3142
#else
3143
    if (!strcmp(device, "tap")) {
3144
        char ifname[64];
3145
        char setup_script[1024];
3146
        int fd;
3147
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3148
            fd = strtol(buf, NULL, 0);
3149
            ret = -1;
3150
            if (net_tap_fd_init(vlan, fd))
3151
                ret = 0;
3152
        } else {
3153
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3154
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3155
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3156
            }
3157
            ret = net_tap_init(vlan, ifname, setup_script);
3158
        }
3159
    } else
3160
#endif
3161
    if (!strcmp(device, "socket")) {
3162
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3163
            int fd;
3164
            fd = strtol(buf, NULL, 0);
3165
            ret = -1;
3166
            if (net_socket_fd_init(vlan, fd, 1))
3167
                ret = 0;
3168
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3169
            ret = net_socket_listen_init(vlan, buf);
3170
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3171
            ret = net_socket_connect_init(vlan, buf);
3172
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3173
            ret = net_socket_mcast_init(vlan, buf);
3174
        } else {
3175
            fprintf(stderr, "Unknown socket options: %s\n", p);
3176
            return -1;
3177
        }
3178
    } else
3179
    {
3180
        fprintf(stderr, "Unknown network device: %s\n", device);
3181
        return -1;
3182
    }
3183
    if (ret < 0) {
3184
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3185
    }
3186
    
3187
    return ret;
3188
}
3189

    
3190
void do_info_network(void)
3191
{
3192
    VLANState *vlan;
3193
    VLANClientState *vc;
3194

    
3195
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3196
        term_printf("VLAN %d devices:\n", vlan->id);
3197
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3198
            term_printf("  %s\n", vc->info_str);
3199
    }
3200
}
3201
 
3202
/***********************************************************/
3203
/* USB devices */
3204

    
3205
static int usb_device_add(const char *devname)
3206
{
3207
    const char *p;
3208
    USBDevice *dev;
3209
    int i;
3210

    
3211
    if (!vm_usb_hub)
3212
        return -1;
3213
    for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3214
        if (!vm_usb_ports[i]->dev)
3215
            break;
3216
    }
3217
    if (i == MAX_VM_USB_PORTS)
3218
        return -1;
3219

    
3220
    if (strstart(devname, "host:", &p)) {
3221
        dev = usb_host_device_open(p);
3222
        if (!dev)
3223
            return -1;
3224
    } else if (!strcmp(devname, "mouse")) {
3225
        dev = usb_mouse_init();
3226
        if (!dev)
3227
            return -1;
3228
    } else if (!strcmp(devname, "tablet")) {
3229
        dev = usb_tablet_init();
3230
        if (!dev)
3231
            return -1;
3232
    } else {
3233
        return -1;
3234
    }
3235
    usb_attach(vm_usb_ports[i], dev);
3236
    return 0;
3237
}
3238

    
3239
static int usb_device_del(const char *devname)
3240
{
3241
    USBDevice *dev;
3242
    int bus_num, addr, i;
3243
    const char *p;
3244

    
3245
    if (!vm_usb_hub)
3246
        return -1;
3247

    
3248
    p = strchr(devname, '.');
3249
    if (!p) 
3250
        return -1;
3251
    bus_num = strtoul(devname, NULL, 0);
3252
    addr = strtoul(p + 1, NULL, 0);
3253
    if (bus_num != 0)
3254
        return -1;
3255
    for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3256
        dev = vm_usb_ports[i]->dev;
3257
        if (dev && dev->addr == addr)
3258
            break;
3259
    }
3260
    if (i == MAX_VM_USB_PORTS)
3261
        return -1;
3262
    usb_attach(vm_usb_ports[i], NULL);
3263
    return 0;
3264
}
3265

    
3266
void do_usb_add(const char *devname)
3267
{
3268
    int ret;
3269
    ret = usb_device_add(devname);
3270
    if (ret < 0) 
3271
        term_printf("Could not add USB device '%s'\n", devname);
3272
}
3273

    
3274
void do_usb_del(const char *devname)
3275
{
3276
    int ret;
3277
    ret = usb_device_del(devname);
3278
    if (ret < 0) 
3279
        term_printf("Could not remove USB device '%s'\n", devname);
3280
}
3281

    
3282
void usb_info(void)
3283
{
3284
    USBDevice *dev;
3285
    int i;
3286
    const char *speed_str;
3287

    
3288
    if (!vm_usb_hub) {
3289
        term_printf("USB support not enabled\n");
3290
        return;
3291
    }
3292

    
3293
    for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3294
        dev = vm_usb_ports[i]->dev;
3295
        if (dev) {
3296
            term_printf("Hub port %d:\n", i);
3297
            switch(dev->speed) {
3298
            case USB_SPEED_LOW: 
3299
                speed_str = "1.5"; 
3300
                break;
3301
            case USB_SPEED_FULL: 
3302
                speed_str = "12"; 
3303
                break;
3304
            case USB_SPEED_HIGH: 
3305
                speed_str = "480"; 
3306
                break;
3307
            default:
3308
                speed_str = "?"; 
3309
                break;
3310
            }
3311
            term_printf("  Device %d.%d, speed %s Mb/s\n", 
3312
                        0, dev->addr, speed_str);
3313
        }
3314
    }
3315
}
3316

    
3317
/***********************************************************/
3318
/* pid file */
3319

    
3320
static char *pid_filename;
3321

    
3322
/* Remove PID file. Called on normal exit */
3323

    
3324
static void remove_pidfile(void) 
3325
{
3326
    unlink (pid_filename);
3327
}
3328

    
3329
static void create_pidfile(const char *filename)
3330
{
3331
    struct stat pidstat;
3332
    FILE *f;
3333

    
3334
    /* Try to write our PID to the named file */
3335
    if (stat(filename, &pidstat) < 0) {
3336
        if (errno == ENOENT) {
3337
            if ((f = fopen (filename, "w")) == NULL) {
3338
                perror("Opening pidfile");
3339
                exit(1);
3340
            }
3341
            fprintf(f, "%d\n", getpid());
3342
            fclose(f);
3343
            pid_filename = qemu_strdup(filename);
3344
            if (!pid_filename) {
3345
                fprintf(stderr, "Could not save PID filename");
3346
                exit(1);
3347
            }
3348
            atexit(remove_pidfile);
3349
        }
3350
    } else {
3351
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
3352
                filename);
3353
        exit(1);
3354
    }
3355
}
3356

    
3357
/***********************************************************/
3358
/* dumb display */
3359

    
3360
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3361
{
3362
}
3363

    
3364
static void dumb_resize(DisplayState *ds, int w, int h)
3365
{
3366
}
3367

    
3368
static void dumb_refresh(DisplayState *ds)
3369
{
3370
    vga_hw_update();
3371
}
3372

    
3373
void dumb_display_init(DisplayState *ds)
3374
{
3375
    ds->data = NULL;
3376
    ds->linesize = 0;
3377
    ds->depth = 0;
3378
    ds->dpy_update = dumb_update;
3379
    ds->dpy_resize = dumb_resize;
3380
    ds->dpy_refresh = dumb_refresh;
3381
}
3382

    
3383
#if !defined(CONFIG_SOFTMMU)
3384
/***********************************************************/
3385
/* cpu signal handler */
3386
static void host_segv_handler(int host_signum, siginfo_t *info, 
3387
                              void *puc)
3388
{
3389
    if (cpu_signal_handler(host_signum, info, puc))
3390
        return;
3391
    if (stdio_nb_clients > 0)
3392
        term_exit();
3393
    abort();
3394
}
3395
#endif
3396

    
3397
/***********************************************************/
3398
/* I/O handling */
3399

    
3400
#define MAX_IO_HANDLERS 64
3401

    
3402
typedef struct IOHandlerRecord {
3403
    int fd;
3404
    IOCanRWHandler *fd_read_poll;
3405
    IOHandler *fd_read;
3406
    IOHandler *fd_write;
3407
    void *opaque;
3408
    /* temporary data */
3409
    struct pollfd *ufd;
3410
    struct IOHandlerRecord *next;
3411
} IOHandlerRecord;
3412

    
3413
static IOHandlerRecord *first_io_handler;
3414

    
3415
/* XXX: fd_read_poll should be suppressed, but an API change is
3416
   necessary in the character devices to suppress fd_can_read(). */
3417
int qemu_set_fd_handler2(int fd, 
3418
                         IOCanRWHandler *fd_read_poll, 
3419
                         IOHandler *fd_read, 
3420
                         IOHandler *fd_write, 
3421
                         void *opaque)
3422
{
3423
    IOHandlerRecord **pioh, *ioh;
3424

    
3425
    if (!fd_read && !fd_write) {
3426
        pioh = &first_io_handler;
3427
        for(;;) {
3428
            ioh = *pioh;
3429
            if (ioh == NULL)
3430
                break;
3431
            if (ioh->fd == fd) {
3432
                *pioh = ioh->next;
3433
                qemu_free(ioh);
3434
                break;
3435
            }
3436
            pioh = &ioh->next;
3437
        }
3438
    } else {
3439
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3440
            if (ioh->fd == fd)
3441
                goto found;
3442
        }
3443
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3444
        if (!ioh)
3445
            return -1;
3446
        ioh->next = first_io_handler;
3447
        first_io_handler = ioh;
3448
    found:
3449
        ioh->fd = fd;
3450
        ioh->fd_read_poll = fd_read_poll;
3451
        ioh->fd_read = fd_read;
3452
        ioh->fd_write = fd_write;
3453
        ioh->opaque = opaque;
3454
    }
3455
    return 0;
3456
}
3457

    
3458
int qemu_set_fd_handler(int fd, 
3459
                        IOHandler *fd_read, 
3460
                        IOHandler *fd_write, 
3461
                        void *opaque)
3462
{
3463
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3464
}
3465

    
3466
/***********************************************************/
3467
/* Polling handling */
3468

    
3469
typedef struct PollingEntry {
3470
    PollingFunc *func;
3471
    void *opaque;
3472
    struct PollingEntry *next;
3473
} PollingEntry;
3474

    
3475
static PollingEntry *first_polling_entry;
3476

    
3477
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3478
{
3479
    PollingEntry **ppe, *pe;
3480
    pe = qemu_mallocz(sizeof(PollingEntry));
3481
    if (!pe)
3482
        return -1;
3483
    pe->func = func;
3484
    pe->opaque = opaque;
3485
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3486
    *ppe = pe;
3487
    return 0;
3488
}
3489

    
3490
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3491
{
3492
    PollingEntry **ppe, *pe;
3493
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3494
        pe = *ppe;
3495
        if (pe->func == func && pe->opaque == opaque) {
3496
            *ppe = pe->next;
3497
            qemu_free(pe);
3498
            break;
3499
        }
3500
    }
3501
}
3502

    
3503
/***********************************************************/
3504
/* savevm/loadvm support */
3505

    
3506
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3507
{
3508
    fwrite(buf, 1, size, f);
3509
}
3510

    
3511
void qemu_put_byte(QEMUFile *f, int v)
3512
{
3513
    fputc(v, f);
3514
}
3515

    
3516
void qemu_put_be16(QEMUFile *f, unsigned int v)
3517
{
3518
    qemu_put_byte(f, v >> 8);
3519
    qemu_put_byte(f, v);
3520
}
3521

    
3522
void qemu_put_be32(QEMUFile *f, unsigned int v)
3523
{
3524
    qemu_put_byte(f, v >> 24);
3525
    qemu_put_byte(f, v >> 16);
3526
    qemu_put_byte(f, v >> 8);
3527
    qemu_put_byte(f, v);
3528
}
3529

    
3530
void qemu_put_be64(QEMUFile *f, uint64_t v)
3531
{
3532
    qemu_put_be32(f, v >> 32);
3533
    qemu_put_be32(f, v);
3534
}
3535

    
3536
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3537
{
3538
    return fread(buf, 1, size, f);
3539
}
3540

    
3541
int qemu_get_byte(QEMUFile *f)
3542
{
3543
    int v;
3544
    v = fgetc(f);
3545
    if (v == EOF)
3546
        return 0;
3547
    else
3548
        return v;
3549
}
3550

    
3551
unsigned int qemu_get_be16(QEMUFile *f)
3552
{
3553
    unsigned int v;
3554
    v = qemu_get_byte(f) << 8;
3555
    v |= qemu_get_byte(f);
3556
    return v;
3557
}
3558

    
3559
unsigned int qemu_get_be32(QEMUFile *f)
3560
{
3561
    unsigned int v;
3562
    v = qemu_get_byte(f) << 24;
3563
    v |= qemu_get_byte(f) << 16;
3564
    v |= qemu_get_byte(f) << 8;
3565
    v |= qemu_get_byte(f);
3566
    return v;
3567
}
3568

    
3569
uint64_t qemu_get_be64(QEMUFile *f)
3570
{
3571
    uint64_t v;
3572
    v = (uint64_t)qemu_get_be32(f) << 32;
3573
    v |= qemu_get_be32(f);
3574
    return v;
3575
}
3576

    
3577
int64_t qemu_ftell(QEMUFile *f)
3578
{
3579
    return ftell(f);
3580
}
3581

    
3582
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3583
{
3584
    if (fseek(f, pos, whence) < 0)
3585
        return -1;
3586
    return ftell(f);
3587
}
3588

    
3589
typedef struct SaveStateEntry {
3590
    char idstr[256];
3591
    int instance_id;
3592
    int version_id;
3593
    SaveStateHandler *save_state;
3594
    LoadStateHandler *load_state;
3595
    void *opaque;
3596
    struct SaveStateEntry *next;
3597
} SaveStateEntry;
3598

    
3599
static SaveStateEntry *first_se;
3600

    
3601
int register_savevm(const char *idstr, 
3602
                    int instance_id, 
3603
                    int version_id,
3604
                    SaveStateHandler *save_state,
3605
                    LoadStateHandler *load_state,
3606
                    void *opaque)
3607
{
3608
    SaveStateEntry *se, **pse;
3609

    
3610
    se = qemu_malloc(sizeof(SaveStateEntry));
3611
    if (!se)
3612
        return -1;
3613
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3614
    se->instance_id = instance_id;
3615
    se->version_id = version_id;
3616
    se->save_state = save_state;
3617
    se->load_state = load_state;
3618
    se->opaque = opaque;
3619
    se->next = NULL;
3620

    
3621
    /* add at the end of list */
3622
    pse = &first_se;
3623
    while (*pse != NULL)
3624
        pse = &(*pse)->next;
3625
    *pse = se;
3626
    return 0;
3627
}
3628

    
3629
#define QEMU_VM_FILE_MAGIC   0x5145564d
3630
#define QEMU_VM_FILE_VERSION 0x00000001
3631

    
3632
int qemu_savevm(const char *filename)
3633
{
3634
    SaveStateEntry *se;
3635
    QEMUFile *f;
3636
    int len, len_pos, cur_pos, saved_vm_running, ret;
3637

    
3638
    saved_vm_running = vm_running;
3639
    vm_stop(0);
3640

    
3641
    f = fopen(filename, "wb");
3642
    if (!f) {
3643
        ret = -1;
3644
        goto the_end;
3645
    }
3646

    
3647
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3648
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3649

    
3650
    for(se = first_se; se != NULL; se = se->next) {
3651
        /* ID string */
3652
        len = strlen(se->idstr);
3653
        qemu_put_byte(f, len);
3654
        qemu_put_buffer(f, se->idstr, len);
3655

    
3656
        qemu_put_be32(f, se->instance_id);
3657
        qemu_put_be32(f, se->version_id);
3658

    
3659
        /* record size: filled later */
3660
        len_pos = ftell(f);
3661
        qemu_put_be32(f, 0);
3662
        
3663
        se->save_state(f, se->opaque);
3664

    
3665
        /* fill record size */
3666
        cur_pos = ftell(f);
3667
        len = ftell(f) - len_pos - 4;
3668
        fseek(f, len_pos, SEEK_SET);
3669
        qemu_put_be32(f, len);
3670
        fseek(f, cur_pos, SEEK_SET);
3671
    }
3672

    
3673
    fclose(f);
3674
    ret = 0;
3675
 the_end:
3676
    if (saved_vm_running)
3677
        vm_start();
3678
    return ret;
3679
}
3680

    
3681
static SaveStateEntry *find_se(const char *idstr, int instance_id)
3682
{
3683
    SaveStateEntry *se;
3684

    
3685
    for(se = first_se; se != NULL; se = se->next) {
3686
        if (!strcmp(se->idstr, idstr) && 
3687
            instance_id == se->instance_id)
3688
            return se;
3689
    }
3690
    return NULL;
3691
}
3692

    
3693
int qemu_loadvm(const char *filename)
3694
{
3695
    SaveStateEntry *se;
3696
    QEMUFile *f;
3697
    int len, cur_pos, ret, instance_id, record_len, version_id;
3698
    int saved_vm_running;
3699
    unsigned int v;
3700
    char idstr[256];
3701
    
3702
    saved_vm_running = vm_running;
3703
    vm_stop(0);
3704

    
3705
    f = fopen(filename, "rb");
3706
    if (!f) {
3707
        ret = -1;
3708
        goto the_end;
3709
    }
3710

    
3711
    v = qemu_get_be32(f);
3712
    if (v != QEMU_VM_FILE_MAGIC)
3713
        goto fail;
3714
    v = qemu_get_be32(f);
3715
    if (v != QEMU_VM_FILE_VERSION) {
3716
    fail:
3717
        fclose(f);
3718
        ret = -1;
3719
        goto the_end;
3720
    }
3721
    for(;;) {
3722
        len = qemu_get_byte(f);
3723
        if (feof(f))
3724
            break;
3725
        qemu_get_buffer(f, idstr, len);
3726
        idstr[len] = '\0';
3727
        instance_id = qemu_get_be32(f);
3728
        version_id = qemu_get_be32(f);
3729
        record_len = qemu_get_be32(f);
3730
#if 0
3731
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
3732
               idstr, instance_id, version_id, record_len);
3733
#endif
3734
        cur_pos = ftell(f);
3735
        se = find_se(idstr, instance_id);
3736
        if (!se) {
3737
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
3738
                    instance_id, idstr);
3739
        } else {
3740
            ret = se->load_state(f, se->opaque, version_id);
3741
            if (ret < 0) {
3742
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
3743
                        instance_id, idstr);
3744
            }
3745
        }
3746
        /* always seek to exact end of record */
3747
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3748
    }
3749
    fclose(f);
3750
    ret = 0;
3751
 the_end:
3752
    if (saved_vm_running)
3753
        vm_start();
3754
    return ret;
3755
}
3756

    
3757
/***********************************************************/
3758
/* cpu save/restore */
3759

    
3760
#if defined(TARGET_I386)
3761

    
3762
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3763
{
3764
    qemu_put_be32(f, dt->selector);
3765
    qemu_put_betl(f, dt->base);
3766
    qemu_put_be32(f, dt->limit);
3767
    qemu_put_be32(f, dt->flags);
3768
}
3769

    
3770
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3771
{
3772
    dt->selector = qemu_get_be32(f);
3773
    dt->base = qemu_get_betl(f);
3774
    dt->limit = qemu_get_be32(f);
3775
    dt->flags = qemu_get_be32(f);
3776
}
3777

    
3778
void cpu_save(QEMUFile *f, void *opaque)
3779
{
3780
    CPUState *env = opaque;
3781
    uint16_t fptag, fpus, fpuc, fpregs_format;
3782
    uint32_t hflags;
3783
    int i;
3784
    
3785
    for(i = 0; i < CPU_NB_REGS; i++)
3786
        qemu_put_betls(f, &env->regs[i]);
3787
    qemu_put_betls(f, &env->eip);
3788
    qemu_put_betls(f, &env->eflags);
3789
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3790
    qemu_put_be32s(f, &hflags);
3791
    
3792
    /* FPU */
3793
    fpuc = env->fpuc;
3794
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3795
    fptag = 0;
3796
    for(i = 0; i < 8; i++) {
3797
        fptag |= ((!env->fptags[i]) << i);
3798
    }
3799
    
3800
    qemu_put_be16s(f, &fpuc);
3801
    qemu_put_be16s(f, &fpus);
3802
    qemu_put_be16s(f, &fptag);
3803

    
3804
#ifdef USE_X86LDOUBLE
3805
    fpregs_format = 0;
3806
#else
3807
    fpregs_format = 1;
3808
#endif
3809
    qemu_put_be16s(f, &fpregs_format);
3810
    
3811
    for(i = 0; i < 8; i++) {
3812
#ifdef USE_X86LDOUBLE
3813
        {
3814
            uint64_t mant;
3815
            uint16_t exp;
3816
            /* we save the real CPU data (in case of MMX usage only 'mant'
3817
               contains the MMX register */
3818
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3819
            qemu_put_be64(f, mant);
3820
            qemu_put_be16(f, exp);
3821
        }
3822
#else
3823
        /* if we use doubles for float emulation, we save the doubles to
3824
           avoid losing information in case of MMX usage. It can give
3825
           problems if the image is restored on a CPU where long
3826
           doubles are used instead. */
3827
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3828
#endif
3829
    }
3830

    
3831
    for(i = 0; i < 6; i++)
3832
        cpu_put_seg(f, &env->segs[i]);
3833
    cpu_put_seg(f, &env->ldt);
3834
    cpu_put_seg(f, &env->tr);
3835
    cpu_put_seg(f, &env->gdt);
3836
    cpu_put_seg(f, &env->idt);
3837
    
3838
    qemu_put_be32s(f, &env->sysenter_cs);
3839
    qemu_put_be32s(f, &env->sysenter_esp);
3840
    qemu_put_be32s(f, &env->sysenter_eip);
3841
    
3842
    qemu_put_betls(f, &env->cr[0]);
3843
    qemu_put_betls(f, &env->cr[2]);
3844
    qemu_put_betls(f, &env->cr[3]);
3845
    qemu_put_betls(f, &env->cr[4]);
3846
    
3847
    for(i = 0; i < 8; i++)
3848
        qemu_put_betls(f, &env->dr[i]);
3849

    
3850
    /* MMU */
3851
    qemu_put_be32s(f, &env->a20_mask);
3852

    
3853
    /* XMM */
3854
    qemu_put_be32s(f, &env->mxcsr);
3855
    for(i = 0; i < CPU_NB_REGS; i++) {
3856
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3857
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3858
    }
3859

    
3860
#ifdef TARGET_X86_64
3861
    qemu_put_be64s(f, &env->efer);
3862
    qemu_put_be64s(f, &env->star);
3863
    qemu_put_be64s(f, &env->lstar);
3864
    qemu_put_be64s(f, &env->cstar);
3865
    qemu_put_be64s(f, &env->fmask);
3866
    qemu_put_be64s(f, &env->kernelgsbase);
3867
#endif
3868
}
3869

    
3870
#ifdef USE_X86LDOUBLE
3871
/* XXX: add that in a FPU generic layer */
3872
union x86_longdouble {
3873
    uint64_t mant;
3874
    uint16_t exp;
3875
};
3876

    
3877
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
3878
#define EXPBIAS1 1023
3879
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
3880
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
3881

    
3882
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3883
{
3884
    int e;
3885
    /* mantissa */
3886
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3887
    /* exponent + sign */
3888
    e = EXPD1(temp) - EXPBIAS1 + 16383;
3889
    e |= SIGND1(temp) >> 16;
3890
    p->exp = e;
3891
}
3892
#endif
3893

    
3894
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3895
{
3896
    CPUState *env = opaque;
3897
    int i, guess_mmx;
3898
    uint32_t hflags;
3899
    uint16_t fpus, fpuc, fptag, fpregs_format;
3900

    
3901
    if (version_id != 3)
3902
        return -EINVAL;
3903
    for(i = 0; i < CPU_NB_REGS; i++)
3904
        qemu_get_betls(f, &env->regs[i]);
3905
    qemu_get_betls(f, &env->eip);
3906
    qemu_get_betls(f, &env->eflags);
3907
    qemu_get_be32s(f, &hflags);
3908

    
3909
    qemu_get_be16s(f, &fpuc);
3910
    qemu_get_be16s(f, &fpus);
3911
    qemu_get_be16s(f, &fptag);
3912
    qemu_get_be16s(f, &fpregs_format);
3913
    
3914
    /* NOTE: we cannot always restore the FPU state if the image come
3915
       from a host with a different 'USE_X86LDOUBLE' define. We guess
3916
       if we are in an MMX state to restore correctly in that case. */
3917
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3918
    for(i = 0; i < 8; i++) {
3919
        uint64_t mant;
3920
        uint16_t exp;
3921
        
3922
        switch(fpregs_format) {
3923
        case 0:
3924
            mant = qemu_get_be64(f);
3925
            exp = qemu_get_be16(f);
3926
#ifdef USE_X86LDOUBLE
3927
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
3928
#else
3929
            /* difficult case */
3930
            if (guess_mmx)
3931
                env->fpregs[i].mmx.MMX_Q(0) = mant;
3932
            else
3933
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
3934
#endif
3935
            break;
3936
        case 1:
3937
            mant = qemu_get_be64(f);
3938
#ifdef USE_X86LDOUBLE
3939
            {
3940
                union x86_longdouble *p;
3941
                /* difficult case */
3942
                p = (void *)&env->fpregs[i];
3943
                if (guess_mmx) {
3944
                    p->mant = mant;
3945
                    p->exp = 0xffff;
3946
                } else {
3947
                    fp64_to_fp80(p, mant);
3948
                }
3949
            }
3950
#else
3951
            env->fpregs[i].mmx.MMX_Q(0) = mant;
3952
#endif            
3953
            break;
3954
        default:
3955
            return -EINVAL;
3956
        }
3957
    }
3958

    
3959
    env->fpuc = fpuc;
3960
    /* XXX: restore FPU round state */
3961
    env->fpstt = (fpus >> 11) & 7;
3962
    env->fpus = fpus & ~0x3800;
3963
    fptag ^= 0xff;
3964
    for(i = 0; i < 8; i++) {
3965
        env->fptags[i] = (fptag >> i) & 1;
3966
    }
3967
    
3968
    for(i = 0; i < 6; i++)
3969
        cpu_get_seg(f, &env->segs[i]);
3970
    cpu_get_seg(f, &env->ldt);
3971
    cpu_get_seg(f, &env->tr);
3972
    cpu_get_seg(f, &env->gdt);
3973
    cpu_get_seg(f, &env->idt);
3974
    
3975
    qemu_get_be32s(f, &env->sysenter_cs);
3976
    qemu_get_be32s(f, &env->sysenter_esp);
3977
    qemu_get_be32s(f, &env->sysenter_eip);
3978
    
3979
    qemu_get_betls(f, &env->cr[0]);
3980
    qemu_get_betls(f, &env->cr[2]);
3981
    qemu_get_betls(f, &env->cr[3]);
3982
    qemu_get_betls(f, &env->cr[4]);
3983
    
3984
    for(i = 0; i < 8; i++)
3985
        qemu_get_betls(f, &env->dr[i]);
3986

    
3987
    /* MMU */
3988
    qemu_get_be32s(f, &env->a20_mask);
3989

    
3990
    qemu_get_be32s(f, &env->mxcsr);
3991
    for(i = 0; i < CPU_NB_REGS; i++) {
3992
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3993
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3994
    }
3995

    
3996
#ifdef TARGET_X86_64
3997
    qemu_get_be64s(f, &env->efer);
3998
    qemu_get_be64s(f, &env->star);
3999
    qemu_get_be64s(f, &env->lstar);
4000
    qemu_get_be64s(f, &env->cstar);
4001
    qemu_get_be64s(f, &env->fmask);
4002
    qemu_get_be64s(f, &env->kernelgsbase);
4003
#endif
4004

    
4005
    /* XXX: compute hflags from scratch, except for CPL and IIF */
4006
    env->hflags = hflags;
4007
    tlb_flush(env, 1);
4008
    return 0;
4009
}
4010

    
4011
#elif defined(TARGET_PPC)
4012
void cpu_save(QEMUFile *f, void *opaque)
4013
{
4014
}
4015

    
4016
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4017
{
4018
    return 0;
4019
}
4020

    
4021
#elif defined(TARGET_MIPS)
4022
void cpu_save(QEMUFile *f, void *opaque)
4023
{
4024
}
4025

    
4026
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4027
{
4028
    return 0;
4029
}
4030

    
4031
#elif defined(TARGET_SPARC)
4032
void cpu_save(QEMUFile *f, void *opaque)
4033
{
4034
    CPUState *env = opaque;
4035
    int i;
4036
    uint32_t tmp;
4037

    
4038
    for(i = 0; i < 8; i++)
4039
        qemu_put_betls(f, &env->gregs[i]);
4040
    for(i = 0; i < NWINDOWS * 16; i++)
4041
        qemu_put_betls(f, &env->regbase[i]);
4042

    
4043
    /* FPU */
4044
    for(i = 0; i < TARGET_FPREGS; i++) {
4045
        union {
4046
            TARGET_FPREG_T f;
4047
            target_ulong i;
4048
        } u;
4049
        u.f = env->fpr[i];
4050
        qemu_put_betl(f, u.i);
4051
    }
4052

    
4053
    qemu_put_betls(f, &env->pc);
4054
    qemu_put_betls(f, &env->npc);
4055
    qemu_put_betls(f, &env->y);
4056
    tmp = GET_PSR(env);
4057
    qemu_put_be32(f, tmp);
4058
    qemu_put_betls(f, &env->fsr);
4059
    qemu_put_betls(f, &env->tbr);
4060
#ifndef TARGET_SPARC64
4061
    qemu_put_be32s(f, &env->wim);
4062
    /* MMU */
4063
    for(i = 0; i < 16; i++)
4064
        qemu_put_be32s(f, &env->mmuregs[i]);
4065
#endif
4066
}
4067

    
4068
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4069
{
4070
    CPUState *env = opaque;
4071
    int i;
4072
    uint32_t tmp;
4073

    
4074
    for(i = 0; i < 8; i++)
4075
        qemu_get_betls(f, &env->gregs[i]);
4076
    for(i = 0; i < NWINDOWS * 16; i++)
4077
        qemu_get_betls(f, &env->regbase[i]);
4078

    
4079
    /* FPU */
4080
    for(i = 0; i < TARGET_FPREGS; i++) {
4081
        union {
4082
            TARGET_FPREG_T f;
4083
            target_ulong i;
4084
        } u;
4085
        u.i = qemu_get_betl(f);
4086
        env->fpr[i] = u.f;
4087
    }
4088

    
4089
    qemu_get_betls(f, &env->pc);
4090
    qemu_get_betls(f, &env->npc);
4091
    qemu_get_betls(f, &env->y);
4092
    tmp = qemu_get_be32(f);
4093
    env->cwp = 0; /* needed to ensure that the wrapping registers are
4094
                     correctly updated */
4095
    PUT_PSR(env, tmp);
4096
    qemu_get_betls(f, &env->fsr);
4097
    qemu_get_betls(f, &env->tbr);
4098
#ifndef TARGET_SPARC64
4099
    qemu_get_be32s(f, &env->wim);
4100
    /* MMU */
4101
    for(i = 0; i < 16; i++)
4102
        qemu_get_be32s(f, &env->mmuregs[i]);
4103
#endif
4104
    tlb_flush(env, 1);
4105
    return 0;
4106
}
4107

    
4108
#elif defined(TARGET_ARM)
4109

    
4110
/* ??? Need to implement these.  */
4111
void cpu_save(QEMUFile *f, void *opaque)
4112
{
4113
}
4114

    
4115
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4116
{
4117
    return 0;
4118
}
4119

    
4120
#else
4121

    
4122
#warning No CPU save/restore functions
4123

    
4124
#endif
4125

    
4126
/***********************************************************/
4127
/* ram save/restore */
4128

    
4129
/* we just avoid storing empty pages */
4130
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4131
{
4132
    int i, v;
4133

    
4134
    v = buf[0];
4135
    for(i = 1; i < len; i++) {
4136
        if (buf[i] != v)
4137
            goto normal_save;
4138
    }
4139
    qemu_put_byte(f, 1);
4140
    qemu_put_byte(f, v);
4141
    return;
4142
 normal_save:
4143
    qemu_put_byte(f, 0); 
4144
    qemu_put_buffer(f, buf, len);
4145
}
4146

    
4147
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4148
{
4149
    int v;
4150

    
4151
    v = qemu_get_byte(f);
4152
    switch(v) {
4153
    case 0:
4154
        if (qemu_get_buffer(f, buf, len) != len)
4155
            return -EIO;
4156
        break;
4157
    case 1:
4158
        v = qemu_get_byte(f);
4159
        memset(buf, v, len);
4160
        break;
4161
    default:
4162
        return -EINVAL;
4163
    }
4164
    return 0;
4165
}
4166

    
4167
static void ram_save(QEMUFile *f, void *opaque)
4168
{
4169
    int i;
4170
    qemu_put_be32(f, phys_ram_size);
4171
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4172
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4173
    }
4174
}
4175

    
4176
static int ram_load(QEMUFile *f, void *opaque, int version_id)
4177
{
4178
    int i, ret;
4179

    
4180
    if (version_id != 1)
4181
        return -EINVAL;
4182
    if (qemu_get_be32(f) != phys_ram_size)
4183
        return -EINVAL;
4184
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4185
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4186
        if (ret)
4187
            return ret;
4188
    }
4189
    return 0;
4190
}
4191

    
4192
/***********************************************************/
4193
/* machine registration */
4194

    
4195
QEMUMachine *first_machine = NULL;
4196

    
4197
int qemu_register_machine(QEMUMachine *m)
4198
{
4199
    QEMUMachine **pm;
4200
    pm = &first_machine;
4201
    while (*pm != NULL)
4202
        pm = &(*pm)->next;
4203
    m->next = NULL;
4204
    *pm = m;
4205
    return 0;
4206
}
4207

    
4208
QEMUMachine *find_machine(const char *name)
4209
{
4210
    QEMUMachine *m;
4211

    
4212
    for(m = first_machine; m != NULL; m = m->next) {
4213
        if (!strcmp(m->name, name))
4214
            return m;
4215
    }
4216
    return NULL;
4217
}
4218

    
4219
/***********************************************************/
4220
/* main execution loop */
4221

    
4222
void gui_update(void *opaque)
4223
{
4224
    display_state.dpy_refresh(&display_state);
4225
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4226
}
4227

    
4228
struct vm_change_state_entry {
4229
    VMChangeStateHandler *cb;
4230
    void *opaque;
4231
    LIST_ENTRY (vm_change_state_entry) entries;
4232
};
4233

    
4234
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4235

    
4236
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4237
                                                     void *opaque)
4238
{
4239
    VMChangeStateEntry *e;
4240

    
4241
    e = qemu_mallocz(sizeof (*e));
4242
    if (!e)
4243
        return NULL;
4244

    
4245
    e->cb = cb;
4246
    e->opaque = opaque;
4247
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4248
    return e;
4249
}
4250

    
4251
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4252
{
4253
    LIST_REMOVE (e, entries);
4254
    qemu_free (e);
4255
}
4256

    
4257
static void vm_state_notify(int running)
4258
{
4259
    VMChangeStateEntry *e;
4260

    
4261
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4262
        e->cb(e->opaque, running);
4263
    }
4264
}
4265

    
4266
/* XXX: support several handlers */
4267
static VMStopHandler *vm_stop_cb;
4268
static void *vm_stop_opaque;
4269

    
4270
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4271
{
4272
    vm_stop_cb = cb;
4273
    vm_stop_opaque = opaque;
4274
    return 0;
4275
}
4276

    
4277
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4278
{
4279
    vm_stop_cb = NULL;
4280
}
4281

    
4282
void vm_start(void)
4283
{
4284
    if (!vm_running) {
4285
        cpu_enable_ticks();
4286
        vm_running = 1;
4287
        vm_state_notify(1);
4288
    }
4289
}
4290

    
4291
void vm_stop(int reason) 
4292
{
4293
    if (vm_running) {
4294
        cpu_disable_ticks();
4295
        vm_running = 0;
4296
        if (reason != 0) {
4297
            if (vm_stop_cb) {
4298
                vm_stop_cb(vm_stop_opaque, reason);
4299
            }
4300
        }
4301
        vm_state_notify(0);
4302
    }
4303
}
4304

    
4305
/* reset/shutdown handler */
4306

    
4307
typedef struct QEMUResetEntry {
4308
    QEMUResetHandler *func;
4309
    void *opaque;
4310
    struct QEMUResetEntry *next;
4311
} QEMUResetEntry;
4312

    
4313
static QEMUResetEntry *first_reset_entry;
4314
static int reset_requested;
4315
static int shutdown_requested;
4316
static int powerdown_requested;
4317

    
4318
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4319
{
4320
    QEMUResetEntry **pre, *re;
4321

    
4322
    pre = &first_reset_entry;
4323
    while (*pre != NULL)
4324
        pre = &(*pre)->next;
4325
    re = qemu_mallocz(sizeof(QEMUResetEntry));
4326
    re->func = func;
4327
    re->opaque = opaque;
4328
    re->next = NULL;
4329
    *pre = re;
4330
}
4331

    
4332
void qemu_system_reset(void)
4333
{
4334
    QEMUResetEntry *re;
4335

    
4336
    /* reset all devices */
4337
    for(re = first_reset_entry; re != NULL; re = re->next) {
4338
        re->func(re->opaque);
4339
    }
4340
}
4341

    
4342
void qemu_system_reset_request(void)
4343
{
4344
    reset_requested = 1;
4345
    if (cpu_single_env)
4346
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4347
}
4348

    
4349
void qemu_system_shutdown_request(void)
4350
{
4351
    shutdown_requested = 1;
4352
    if (cpu_single_env)
4353
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4354
}
4355

    
4356
void qemu_system_powerdown_request(void)
4357
{
4358
    powerdown_requested = 1;
4359
    if (cpu_single_env)
4360
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4361
}
4362

    
4363
void main_loop_wait(int timeout)
4364
{
4365
    IOHandlerRecord *ioh, *ioh_next;
4366
    fd_set rfds, wfds;
4367
    int ret, nfds;
4368
    struct timeval tv;
4369
    PollingEntry *pe;
4370

    
4371

    
4372
    /* XXX: need to suppress polling by better using win32 events */
4373
    ret = 0;
4374
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4375
        ret |= pe->func(pe->opaque);
4376
    }
4377
#ifdef _WIN32
4378
    if (ret == 0 && timeout > 0) {
4379
        Sleep(timeout);
4380
    }
4381
#endif
4382
    /* poll any events */
4383
    /* XXX: separate device handlers from system ones */
4384
    nfds = -1;
4385
    FD_ZERO(&rfds);
4386
    FD_ZERO(&wfds);
4387
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4388
        if (ioh->fd_read &&
4389
            (!ioh->fd_read_poll ||
4390
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4391
            FD_SET(ioh->fd, &rfds);
4392
            if (ioh->fd > nfds)
4393
                nfds = ioh->fd;
4394
        }
4395
        if (ioh->fd_write) {
4396
            FD_SET(ioh->fd, &wfds);
4397
            if (ioh->fd > nfds)
4398
                nfds = ioh->fd;
4399
        }
4400
    }
4401
    
4402
    tv.tv_sec = 0;
4403
#ifdef _WIN32
4404
    tv.tv_usec = 0;
4405
#else
4406
    tv.tv_usec = timeout * 1000;
4407
#endif
4408
    ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4409
    if (ret > 0) {
4410
        /* XXX: better handling of removal */
4411
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4412
            ioh_next = ioh->next;
4413
            if (FD_ISSET(ioh->fd, &rfds)) {
4414
                ioh->fd_read(ioh->opaque);
4415
            }
4416
            if (FD_ISSET(ioh->fd, &wfds)) {
4417
                ioh->fd_write(ioh->opaque);
4418
            }
4419
        }
4420
    }
4421
#ifdef _WIN32
4422
    tap_win32_poll();
4423
#endif
4424

    
4425
#if defined(CONFIG_SLIRP)
4426
    /* XXX: merge with the previous select() */
4427
    if (slirp_inited) {
4428
        fd_set rfds, wfds, xfds;
4429
        int nfds;
4430
        struct timeval tv;
4431
        
4432
        nfds = -1;
4433
        FD_ZERO(&rfds);
4434
        FD_ZERO(&wfds);
4435
        FD_ZERO(&xfds);
4436
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4437
        tv.tv_sec = 0;
4438
        tv.tv_usec = 0;
4439
        ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4440
        if (ret >= 0) {
4441
            slirp_select_poll(&rfds, &wfds, &xfds);
4442
        }
4443
    }
4444
#endif
4445

    
4446
    if (vm_running) {
4447
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
4448
                        qemu_get_clock(vm_clock));
4449
        /* run dma transfers, if any */
4450
        DMA_run();
4451
    }
4452
    
4453
    /* real time timers */
4454
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
4455
                    qemu_get_clock(rt_clock));
4456
}
4457

    
4458
static CPUState *cur_cpu;
4459

    
4460
int main_loop(void)
4461
{
4462
    int ret, timeout;
4463
#ifdef CONFIG_PROFILER
4464
    int64_t ti;
4465
#endif
4466
    CPUState *env;
4467

    
4468
    cur_cpu = first_cpu;
4469
    for(;;) {
4470
        if (vm_running) {
4471

    
4472
            env = cur_cpu;
4473
            for(;;) {
4474
                /* get next cpu */
4475
                env = env->next_cpu;
4476
                if (!env)
4477
                    env = first_cpu;
4478
#ifdef CONFIG_PROFILER
4479
                ti = profile_getclock();
4480
#endif
4481
                ret = cpu_exec(env);
4482
#ifdef CONFIG_PROFILER
4483
                qemu_time += profile_getclock() - ti;
4484
#endif
4485
                if (ret != EXCP_HALTED)
4486
                    break;
4487
                /* all CPUs are halted ? */
4488
                if (env == cur_cpu) {
4489
                    ret = EXCP_HLT;
4490
                    break;
4491
                }
4492
            }
4493
            cur_cpu = env;
4494

    
4495
            if (shutdown_requested) {
4496
                ret = EXCP_INTERRUPT;
4497
                break;
4498
            }
4499
            if (reset_requested) {
4500
                reset_requested = 0;
4501
                qemu_system_reset();
4502
                ret = EXCP_INTERRUPT;
4503
            }
4504
            if (powerdown_requested) {
4505
                powerdown_requested = 0;
4506
                qemu_system_powerdown();
4507
                ret = EXCP_INTERRUPT;
4508
            }
4509
            if (ret == EXCP_DEBUG) {
4510
                vm_stop(EXCP_DEBUG);
4511
            }
4512
            /* if hlt instruction, we wait until the next IRQ */
4513
            /* XXX: use timeout computed from timers */
4514
            if (ret == EXCP_HLT)
4515
                timeout = 10;
4516
            else
4517
                timeout = 0;
4518
        } else {
4519
            timeout = 10;
4520
        }
4521
#ifdef CONFIG_PROFILER
4522
        ti = profile_getclock();
4523
#endif
4524
        main_loop_wait(timeout);
4525
#ifdef CONFIG_PROFILER
4526
        dev_time += profile_getclock() - ti;
4527
#endif
4528
    }
4529
    cpu_disable_ticks();
4530
    return ret;
4531
}
4532

    
4533
void help(void)
4534
{
4535
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4536
           "usage: %s [options] [disk_image]\n"
4537
           "\n"
4538
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4539
           "\n"
4540
           "Standard options:\n"
4541
           "-M machine      select emulated machine (-M ? for list)\n"
4542
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
4543
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
4544
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
4545
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4546
           "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4547
           "-snapshot       write to temporary files instead of disk image files\n"
4548
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
4549
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
4550
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
4551
#ifndef _WIN32
4552
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
4553
#endif
4554
#ifdef HAS_AUDIO
4555
           "-audio-help     print list of audio drivers and their options\n"
4556
           "-soundhw c1,... enable audio support\n"
4557
           "                and only specified sound cards (comma separated list)\n"
4558
           "                use -soundhw ? to get the list of supported cards\n"
4559
           "                use -soundhw all to enable all of them\n"
4560
#endif
4561
           "-localtime      set the real time clock to local time [default=utc]\n"
4562
           "-full-screen    start in full screen\n"
4563
#ifdef TARGET_I386
4564
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
4565
#endif
4566
           "-usb            enable the USB driver (will be the default soon)\n"
4567
           "-usbdevice name add the host or guest USB device 'name'\n"
4568
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4569
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
4570
#endif
4571
           "\n"
4572
           "Network options:\n"
4573
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4574
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
4575
#ifdef CONFIG_SLIRP
4576
           "-net user[,vlan=n][,hostname=host]\n"
4577
           "                connect the user mode network stack to VLAN 'n' and send\n"
4578
           "                hostname 'host' to DHCP clients\n"
4579
#endif
4580
#ifdef _WIN32
4581
           "-net tap[,vlan=n],ifname=name\n"
4582
           "                connect the host TAP network interface to VLAN 'n'\n"
4583
#else
4584
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4585
           "                connect the host TAP network interface to VLAN 'n' and use\n"
4586
           "                the network script 'file' (default=%s);\n"
4587
           "                use 'fd=h' to connect to an already opened TAP interface\n"
4588
#endif
4589
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4590
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
4591
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4592
           "                connect the vlan 'n' to multicast maddr and port\n"
4593
           "-net none       use it alone to have zero network devices; if no -net option\n"
4594
           "                is provided, the default is '-net nic -net user'\n"
4595
           "\n"
4596
#ifdef CONFIG_SLIRP
4597
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
4598
#ifndef _WIN32
4599
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
4600
#endif
4601
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4602
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
4603
#endif
4604
           "\n"
4605
           "Linux boot specific:\n"
4606
           "-kernel bzImage use 'bzImage' as kernel image\n"
4607
           "-append cmdline use 'cmdline' as kernel command line\n"
4608
           "-initrd file    use 'file' as initial ram disk\n"
4609
           "\n"
4610
           "Debug/Expert options:\n"
4611
           "-monitor dev    redirect the monitor to char device 'dev'\n"
4612
           "-serial dev     redirect the serial port to char device 'dev'\n"
4613
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
4614
           "-pidfile file   Write PID to 'file'\n"
4615
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
4616
           "-s              wait gdb connection to port %d\n"
4617
           "-p port         change gdb connection port\n"
4618
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
4619
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
4620
           "                translation (t=none or lba) (usually qemu can guess them)\n"
4621
           "-L path         set the directory for the BIOS and VGA BIOS\n"
4622
#ifdef USE_KQEMU
4623
           "-no-kqemu       disable KQEMU kernel module usage\n"
4624
#endif
4625
#ifdef USE_CODE_COPY
4626
           "-no-code-copy   disable code copy acceleration\n"
4627
#endif
4628
#ifdef TARGET_I386
4629
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
4630
           "                (default is CL-GD5446 PCI VGA)\n"
4631
#endif
4632
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
4633
           "\n"
4634
           "During emulation, the following keys are useful:\n"
4635
           "ctrl-alt-f      toggle full screen\n"
4636
           "ctrl-alt-n      switch to virtual console 'n'\n"
4637
           "ctrl-alt        toggle mouse and keyboard grab\n"
4638
           "\n"
4639
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4640
           ,
4641
#ifdef CONFIG_SOFTMMU
4642
           "qemu",
4643
#else
4644
           "qemu-fast",
4645
#endif
4646
           DEFAULT_RAM_SIZE,
4647
#ifndef _WIN32
4648
           DEFAULT_NETWORK_SCRIPT,
4649
#endif
4650
           DEFAULT_GDBSTUB_PORT,
4651
           "/tmp/qemu.log");
4652
#ifndef CONFIG_SOFTMMU
4653
    printf("\n"
4654
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4655
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4656
           "PC emulation.\n");
4657
#endif
4658
    exit(1);
4659
}
4660

    
4661
#define HAS_ARG 0x0001
4662

    
4663
enum {
4664
    QEMU_OPTION_h,
4665

    
4666
    QEMU_OPTION_M,
4667
    QEMU_OPTION_fda,
4668
    QEMU_OPTION_fdb,
4669
    QEMU_OPTION_hda,
4670
    QEMU_OPTION_hdb,
4671
    QEMU_OPTION_hdc,
4672
    QEMU_OPTION_hdd,
4673
    QEMU_OPTION_cdrom,
4674
    QEMU_OPTION_boot,
4675
    QEMU_OPTION_snapshot,
4676
    QEMU_OPTION_m,
4677
    QEMU_OPTION_nographic,
4678
#ifdef HAS_AUDIO
4679
    QEMU_OPTION_audio_help,
4680
    QEMU_OPTION_soundhw,
4681
#endif
4682

    
4683
    QEMU_OPTION_net,
4684
    QEMU_OPTION_tftp,
4685
    QEMU_OPTION_smb,
4686
    QEMU_OPTION_redir,
4687

    
4688
    QEMU_OPTION_kernel,
4689
    QEMU_OPTION_append,
4690
    QEMU_OPTION_initrd,
4691

    
4692
    QEMU_OPTION_S,
4693
    QEMU_OPTION_s,
4694
    QEMU_OPTION_p,
4695
    QEMU_OPTION_d,
4696
    QEMU_OPTION_hdachs,
4697
    QEMU_OPTION_L,
4698
    QEMU_OPTION_no_code_copy,
4699
    QEMU_OPTION_k,
4700
    QEMU_OPTION_localtime,
4701
    QEMU_OPTION_cirrusvga,
4702
    QEMU_OPTION_g,
4703
    QEMU_OPTION_std_vga,
4704
    QEMU_OPTION_monitor,
4705
    QEMU_OPTION_serial,
4706
    QEMU_OPTION_parallel,
4707
    QEMU_OPTION_loadvm,
4708
    QEMU_OPTION_full_screen,
4709
    QEMU_OPTION_pidfile,
4710
    QEMU_OPTION_no_kqemu,
4711
    QEMU_OPTION_kernel_kqemu,
4712
    QEMU_OPTION_win2k_hack,
4713
    QEMU_OPTION_usb,
4714
    QEMU_OPTION_usbdevice,
4715
    QEMU_OPTION_smp,
4716
};
4717

    
4718
typedef struct QEMUOption {
4719
    const char *name;
4720
    int flags;
4721
    int index;
4722
} QEMUOption;
4723

    
4724
const QEMUOption qemu_options[] = {
4725
    { "h", 0, QEMU_OPTION_h },
4726

    
4727
    { "M", HAS_ARG, QEMU_OPTION_M },
4728
    { "fda", HAS_ARG, QEMU_OPTION_fda },
4729
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4730
    { "hda", HAS_ARG, QEMU_OPTION_hda },
4731
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4732
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4733
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4734
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4735
    { "boot", HAS_ARG, QEMU_OPTION_boot },
4736
    { "snapshot", 0, QEMU_OPTION_snapshot },
4737
    { "m", HAS_ARG, QEMU_OPTION_m },
4738
    { "nographic", 0, QEMU_OPTION_nographic },
4739
    { "k", HAS_ARG, QEMU_OPTION_k },
4740
#ifdef HAS_AUDIO
4741
    { "audio-help", 0, QEMU_OPTION_audio_help },
4742
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4743
#endif
4744

    
4745
    { "net", HAS_ARG, QEMU_OPTION_net},
4746
#ifdef CONFIG_SLIRP
4747
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4748
#ifndef _WIN32
4749
    { "smb", HAS_ARG, QEMU_OPTION_smb },
4750
#endif
4751
    { "redir", HAS_ARG, QEMU_OPTION_redir },
4752
#endif
4753

    
4754
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4755
    { "append", HAS_ARG, QEMU_OPTION_append },
4756
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4757

    
4758
    { "S", 0, QEMU_OPTION_S },
4759
    { "s", 0, QEMU_OPTION_s },
4760
    { "p", HAS_ARG, QEMU_OPTION_p },
4761
    { "d", HAS_ARG, QEMU_OPTION_d },
4762
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4763
    { "L", HAS_ARG, QEMU_OPTION_L },
4764
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4765
#ifdef USE_KQEMU
4766
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4767
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4768
#endif
4769
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4770
    { "g", 1, QEMU_OPTION_g },
4771
#endif
4772
    { "localtime", 0, QEMU_OPTION_localtime },
4773
    { "std-vga", 0, QEMU_OPTION_std_vga },
4774
    { "monitor", 1, QEMU_OPTION_monitor },
4775
    { "serial", 1, QEMU_OPTION_serial },
4776
    { "parallel", 1, QEMU_OPTION_parallel },
4777
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4778
    { "full-screen", 0, QEMU_OPTION_full_screen },
4779
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4780
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4781
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4782
    { "smp", HAS_ARG, QEMU_OPTION_smp },
4783
    
4784
    /* temporary options */
4785
    { "usb", 0, QEMU_OPTION_usb },
4786
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4787
    { NULL },
4788
};
4789

    
4790
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4791

    
4792
/* this stack is only used during signal handling */
4793
#define SIGNAL_STACK_SIZE 32768
4794

    
4795
static uint8_t *signal_stack;
4796

    
4797
#endif
4798

    
4799
/* password input */
4800

    
4801
static BlockDriverState *get_bdrv(int index)
4802
{
4803
    BlockDriverState *bs;
4804

    
4805
    if (index < 4) {
4806
        bs = bs_table[index];
4807
    } else if (index < 6) {
4808
        bs = fd_table[index - 4];
4809
    } else {
4810
        bs = NULL;
4811
    }
4812
    return bs;
4813
}
4814

    
4815
static void read_passwords(void)
4816
{
4817
    BlockDriverState *bs;
4818
    int i, j;
4819
    char password[256];
4820

    
4821
    for(i = 0; i < 6; i++) {
4822
        bs = get_bdrv(i);
4823
        if (bs && bdrv_is_encrypted(bs)) {
4824
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4825
            for(j = 0; j < 3; j++) {
4826
                monitor_readline("Password: ", 
4827
                                 1, password, sizeof(password));
4828
                if (bdrv_set_key(bs, password) == 0)
4829
                    break;
4830
                term_printf("invalid password\n");
4831
            }
4832
        }
4833
    }
4834
}
4835

    
4836
/* XXX: currently we cannot use simultaneously different CPUs */
4837
void register_machines(void)
4838
{
4839
#if defined(TARGET_I386)
4840
    qemu_register_machine(&pc_machine);
4841
    qemu_register_machine(&isapc_machine);
4842
#elif defined(TARGET_PPC)
4843
    qemu_register_machine(&heathrow_machine);
4844
    qemu_register_machine(&core99_machine);
4845
    qemu_register_machine(&prep_machine);
4846
#elif defined(TARGET_MIPS)
4847
    qemu_register_machine(&mips_machine);
4848
#elif defined(TARGET_SPARC)
4849
#ifdef TARGET_SPARC64
4850
    qemu_register_machine(&sun4u_machine);
4851
#else
4852
    qemu_register_machine(&sun4m_machine);
4853
#endif
4854
#elif defined(TARGET_ARM)
4855
    qemu_register_machine(&integratorcp926_machine);
4856
    qemu_register_machine(&integratorcp1026_machine);
4857
    qemu_register_machine(&versatilepb_machine);
4858
#else
4859
#error unsupported CPU
4860
#endif
4861
}
4862

    
4863
#ifdef HAS_AUDIO
4864
struct soundhw soundhw[] = {
4865
#ifdef TARGET_I386
4866
    {
4867
        "pcspk",
4868
        "PC speaker",
4869
        0,
4870
        1,
4871
        { .init_isa = pcspk_audio_init }
4872
    },
4873
#endif
4874
    {
4875
        "sb16",
4876
        "Creative Sound Blaster 16",
4877
        0,
4878
        1,
4879
        { .init_isa = SB16_init }
4880
    },
4881

    
4882
#ifdef CONFIG_ADLIB
4883
    {
4884
        "adlib",
4885
#ifdef HAS_YMF262
4886
        "Yamaha YMF262 (OPL3)",
4887
#else
4888
        "Yamaha YM3812 (OPL2)",
4889
#endif
4890
        0,
4891
        1,
4892
        { .init_isa = Adlib_init }
4893
    },
4894
#endif
4895

    
4896
#ifdef CONFIG_GUS
4897
    {
4898
        "gus",
4899
        "Gravis Ultrasound GF1",
4900
        0,
4901
        1,
4902
        { .init_isa = GUS_init }
4903
    },
4904
#endif
4905

    
4906
    {
4907
        "es1370",
4908
        "ENSONIQ AudioPCI ES1370",
4909
        0,
4910
        0,
4911
        { .init_pci = es1370_init }
4912
    },
4913

    
4914
    { NULL, NULL, 0, 0, { NULL } }
4915
};
4916

    
4917
static void select_soundhw (const char *optarg)
4918
{
4919
    struct soundhw *c;
4920

    
4921
    if (*optarg == '?') {
4922
    show_valid_cards:
4923

    
4924
        printf ("Valid sound card names (comma separated):\n");
4925
        for (c = soundhw; c->name; ++c) {
4926
            printf ("%-11s %s\n", c->name, c->descr);
4927
        }
4928
        printf ("\n-soundhw all will enable all of the above\n");
4929
        exit (*optarg != '?');
4930
    }
4931
    else {
4932
        size_t l;
4933
        const char *p;
4934
        char *e;
4935
        int bad_card = 0;
4936

    
4937
        if (!strcmp (optarg, "all")) {
4938
            for (c = soundhw; c->name; ++c) {
4939
                c->enabled = 1;
4940
            }
4941
            return;
4942
        }
4943

    
4944
        p = optarg;
4945
        while (*p) {
4946
            e = strchr (p, ',');
4947
            l = !e ? strlen (p) : (size_t) (e - p);
4948

    
4949
            for (c = soundhw; c->name; ++c) {
4950
                if (!strncmp (c->name, p, l)) {
4951
                    c->enabled = 1;
4952
                    break;
4953
                }
4954
            }
4955

    
4956
            if (!c->name) {
4957
                if (l > 80) {
4958
                    fprintf (stderr,
4959
                             "Unknown sound card name (too big to show)\n");
4960
                }
4961
                else {
4962
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4963
                             (int) l, p);
4964
                }
4965
                bad_card = 1;
4966
            }
4967
            p += l + (e != NULL);
4968
        }
4969

    
4970
        if (bad_card)
4971
            goto show_valid_cards;
4972
    }
4973
}
4974
#endif
4975

    
4976
#define MAX_NET_CLIENTS 32
4977

    
4978
int main(int argc, char **argv)
4979
{
4980
#ifdef CONFIG_GDBSTUB
4981
    int use_gdbstub, gdbstub_port;
4982
#endif
4983
    int i, cdrom_index;
4984
    int snapshot, linux_boot;
4985
    const char *initrd_filename;
4986
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4987
    const char *kernel_filename, *kernel_cmdline;
4988
    DisplayState *ds = &display_state;
4989
    int cyls, heads, secs, translation;
4990
    int start_emulation = 1;
4991
    char net_clients[MAX_NET_CLIENTS][256];
4992
    int nb_net_clients;
4993
    int optind;
4994
    const char *r, *optarg;
4995
    CharDriverState *monitor_hd;
4996
    char monitor_device[128];
4997
    char serial_devices[MAX_SERIAL_PORTS][128];
4998
    int serial_device_index;
4999
    char parallel_devices[MAX_PARALLEL_PORTS][128];
5000
    int parallel_device_index;
5001
    const char *loadvm = NULL;
5002
    QEMUMachine *machine;
5003
    char usb_devices[MAX_VM_USB_PORTS][128];
5004
    int usb_devices_index;
5005

    
5006
    LIST_INIT (&vm_change_state_head);
5007
#if !defined(CONFIG_SOFTMMU)
5008
    /* we never want that malloc() uses mmap() */
5009
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5010
#endif
5011
    register_machines();
5012
    machine = first_machine;
5013
    initrd_filename = NULL;
5014
    for(i = 0; i < MAX_FD; i++)
5015
        fd_filename[i] = NULL;
5016
    for(i = 0; i < MAX_DISKS; i++)
5017
        hd_filename[i] = NULL;
5018
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5019
    vga_ram_size = VGA_RAM_SIZE;
5020
    bios_size = BIOS_SIZE;
5021
#ifdef CONFIG_GDBSTUB
5022
    use_gdbstub = 0;
5023
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
5024
#endif
5025
    snapshot = 0;
5026
    nographic = 0;
5027
    kernel_filename = NULL;
5028
    kernel_cmdline = "";
5029
#ifdef TARGET_PPC
5030
    cdrom_index = 1;
5031
#else
5032
    cdrom_index = 2;
5033
#endif
5034
    cyls = heads = secs = 0;
5035
    translation = BIOS_ATA_TRANSLATION_AUTO;
5036
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5037

    
5038
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5039
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
5040
        serial_devices[i][0] = '\0';
5041
    serial_device_index = 0;
5042
    
5043
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5044
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5045
        parallel_devices[i][0] = '\0';
5046
    parallel_device_index = 0;
5047
    
5048
    usb_devices_index = 0;
5049
    
5050
    nb_net_clients = 0;
5051

    
5052
    nb_nics = 0;
5053
    /* default mac address of the first network interface */
5054
    
5055
    optind = 1;
5056
    for(;;) {
5057
        if (optind >= argc)
5058
            break;
5059
        r = argv[optind];
5060
        if (r[0] != '-') {
5061
            hd_filename[0] = argv[optind++];
5062
        } else {
5063
            const QEMUOption *popt;
5064

    
5065
            optind++;
5066
            popt = qemu_options;
5067
            for(;;) {
5068
                if (!popt->name) {
5069
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
5070
                            argv[0], r);
5071
                    exit(1);
5072
                }
5073
                if (!strcmp(popt->name, r + 1))
5074
                    break;
5075
                popt++;
5076
            }
5077
            if (popt->flags & HAS_ARG) {
5078
                if (optind >= argc) {
5079
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
5080
                            argv[0], r);
5081
                    exit(1);
5082
                }
5083
                optarg = argv[optind++];
5084
            } else {
5085
                optarg = NULL;
5086
            }
5087

    
5088
            switch(popt->index) {
5089
            case QEMU_OPTION_M:
5090
                machine = find_machine(optarg);
5091
                if (!machine) {
5092
                    QEMUMachine *m;
5093
                    printf("Supported machines are:\n");
5094
                    for(m = first_machine; m != NULL; m = m->next) {
5095
                        printf("%-10s %s%s\n",
5096
                               m->name, m->desc, 
5097
                               m == first_machine ? " (default)" : "");
5098
                    }
5099
                    exit(1);
5100
                }
5101
                break;
5102
            case QEMU_OPTION_initrd:
5103
                initrd_filename = optarg;
5104
                break;
5105
            case QEMU_OPTION_hda:
5106
            case QEMU_OPTION_hdb:
5107
            case QEMU_OPTION_hdc:
5108
            case QEMU_OPTION_hdd:
5109
                {
5110
                    int hd_index;
5111
                    hd_index = popt->index - QEMU_OPTION_hda;
5112
                    hd_filename[hd_index] = optarg;
5113
                    if (hd_index == cdrom_index)
5114
                        cdrom_index = -1;
5115
                }
5116
                break;
5117
            case QEMU_OPTION_snapshot:
5118
                snapshot = 1;
5119
                break;
5120
            case QEMU_OPTION_hdachs:
5121
                {
5122
                    const char *p;
5123
                    p = optarg;
5124
                    cyls = strtol(p, (char **)&p, 0);
5125
                    if (cyls < 1 || cyls > 16383)
5126
                        goto chs_fail;
5127
                    if (*p != ',')
5128
                        goto chs_fail;
5129
                    p++;
5130
                    heads = strtol(p, (char **)&p, 0);
5131
                    if (heads < 1 || heads > 16)
5132
                        goto chs_fail;
5133
                    if (*p != ',')
5134
                        goto chs_fail;
5135
                    p++;
5136
                    secs = strtol(p, (char **)&p, 0);
5137
                    if (secs < 1 || secs > 63)
5138
                        goto chs_fail;
5139
                    if (*p == ',') {
5140
                        p++;
5141
                        if (!strcmp(p, "none"))
5142
                            translation = BIOS_ATA_TRANSLATION_NONE;
5143
                        else if (!strcmp(p, "lba"))
5144
                            translation = BIOS_ATA_TRANSLATION_LBA;
5145
                        else if (!strcmp(p, "auto"))
5146
                            translation = BIOS_ATA_TRANSLATION_AUTO;
5147
                        else
5148
                            goto chs_fail;
5149
                    } else if (*p != '\0') {
5150
                    chs_fail:
5151
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
5152
                        exit(1);
5153
                    }
5154
                }
5155
                break;
5156
            case QEMU_OPTION_nographic:
5157
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5158
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5159
                nographic = 1;
5160
                break;
5161
            case QEMU_OPTION_kernel:
5162
                kernel_filename = optarg;
5163
                break;
5164
            case QEMU_OPTION_append:
5165
                kernel_cmdline = optarg;
5166
                break;
5167
            case QEMU_OPTION_cdrom:
5168
                if (cdrom_index >= 0) {
5169
                    hd_filename[cdrom_index] = optarg;
5170
                }
5171
                break;
5172
            case QEMU_OPTION_boot:
5173
                boot_device = optarg[0];
5174
                if (boot_device != 'a' && 
5175
#ifdef TARGET_SPARC
5176
                    // Network boot
5177
                    boot_device != 'n' &&
5178
#endif
5179
                    boot_device != 'c' && boot_device != 'd') {
5180
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5181
                    exit(1);
5182
                }
5183
                break;
5184
            case QEMU_OPTION_fda:
5185
                fd_filename[0] = optarg;
5186
                break;
5187
            case QEMU_OPTION_fdb:
5188
                fd_filename[1] = optarg;
5189
                break;
5190
            case QEMU_OPTION_no_code_copy:
5191
                code_copy_enabled = 0;
5192
                break;
5193
            case QEMU_OPTION_net:
5194
                if (nb_net_clients >= MAX_NET_CLIENTS) {
5195
                    fprintf(stderr, "qemu: too many network clients\n");
5196
                    exit(1);
5197
                }
5198
                pstrcpy(net_clients[nb_net_clients],
5199
                        sizeof(net_clients[0]),
5200
                        optarg);
5201
                nb_net_clients++;
5202
                break;
5203
#ifdef CONFIG_SLIRP
5204
            case QEMU_OPTION_tftp:
5205
                tftp_prefix = optarg;
5206
                break;
5207
#ifndef _WIN32
5208
            case QEMU_OPTION_smb:
5209
                net_slirp_smb(optarg);
5210
                break;
5211
#endif
5212
            case QEMU_OPTION_redir:
5213
                net_slirp_redir(optarg);                
5214
                break;
5215
#endif
5216
#ifdef HAS_AUDIO
5217
            case QEMU_OPTION_audio_help:
5218
                AUD_help ();
5219
                exit (0);
5220
                break;
5221
            case QEMU_OPTION_soundhw:
5222
                select_soundhw (optarg);
5223
                break;
5224
#endif
5225
            case QEMU_OPTION_h:
5226
                help();
5227
                break;
5228
            case QEMU_OPTION_m:
5229
                ram_size = atoi(optarg) * 1024 * 1024;
5230
                if (ram_size <= 0)
5231
                    help();
5232
                if (ram_size > PHYS_RAM_MAX_SIZE) {
5233
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5234
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
5235
                    exit(1);
5236
                }
5237
                break;
5238
            case QEMU_OPTION_d:
5239
                {
5240
                    int mask;
5241
                    CPULogItem *item;
5242
                    
5243
                    mask = cpu_str_to_log_mask(optarg);
5244
                    if (!mask) {
5245
                        printf("Log items (comma separated):\n");
5246
                    for(item = cpu_log_items; item->mask != 0; item++) {
5247
                        printf("%-10s %s\n", item->name, item->help);
5248
                    }
5249
                    exit(1);
5250
                    }
5251
                    cpu_set_log(mask);
5252
                }
5253
                break;
5254
#ifdef CONFIG_GDBSTUB
5255
            case QEMU_OPTION_s:
5256
                use_gdbstub = 1;
5257
                break;
5258
            case QEMU_OPTION_p:
5259
                gdbstub_port = atoi(optarg);
5260
                break;
5261
#endif
5262
            case QEMU_OPTION_L:
5263
                bios_dir = optarg;
5264
                break;
5265
            case QEMU_OPTION_S:
5266
                start_emulation = 0;
5267
                break;
5268
            case QEMU_OPTION_k:
5269
                keyboard_layout = optarg;
5270
                break;
5271
            case QEMU_OPTION_localtime:
5272
                rtc_utc = 0;
5273
                break;
5274
            case QEMU_OPTION_cirrusvga:
5275
                cirrus_vga_enabled = 1;
5276
                break;
5277
            case QEMU_OPTION_std_vga:
5278
                cirrus_vga_enabled = 0;
5279
                break;
5280
            case QEMU_OPTION_g:
5281
                {
5282
                    const char *p;
5283
                    int w, h, depth;
5284
                    p = optarg;
5285
                    w = strtol(p, (char **)&p, 10);
5286
                    if (w <= 0) {
5287
                    graphic_error:
5288
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5289
                        exit(1);
5290
                    }
5291
                    if (*p != 'x')
5292
                        goto graphic_error;
5293
                    p++;
5294
                    h = strtol(p, (char **)&p, 10);
5295
                    if (h <= 0)
5296
                        goto graphic_error;
5297
                    if (*p == 'x') {
5298
                        p++;
5299
                        depth = strtol(p, (char **)&p, 10);
5300
                        if (depth != 8 && depth != 15 && depth != 16 && 
5301
                            depth != 24 && depth != 32)
5302
                            goto graphic_error;
5303
                    } else if (*p == '\0') {
5304
                        depth = graphic_depth;
5305
                    } else {
5306
                        goto graphic_error;
5307
                    }
5308
                    
5309
                    graphic_width = w;
5310
                    graphic_height = h;
5311
                    graphic_depth = depth;
5312
                }
5313
                break;
5314
            case QEMU_OPTION_monitor:
5315
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5316
                break;
5317
            case QEMU_OPTION_serial:
5318
                if (serial_device_index >= MAX_SERIAL_PORTS) {
5319
                    fprintf(stderr, "qemu: too many serial ports\n");
5320
                    exit(1);
5321
                }
5322
                pstrcpy(serial_devices[serial_device_index], 
5323
                        sizeof(serial_devices[0]), optarg);
5324
                serial_device_index++;
5325
                break;
5326
            case QEMU_OPTION_parallel:
5327
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5328
                    fprintf(stderr, "qemu: too many parallel ports\n");
5329
                    exit(1);
5330
                }
5331
                pstrcpy(parallel_devices[parallel_device_index], 
5332
                        sizeof(parallel_devices[0]), optarg);
5333
                parallel_device_index++;
5334
                break;
5335
            case QEMU_OPTION_loadvm:
5336
                loadvm = optarg;
5337
                break;
5338
            case QEMU_OPTION_full_screen:
5339
                full_screen = 1;
5340
                break;
5341
            case QEMU_OPTION_pidfile:
5342
                create_pidfile(optarg);
5343
                break;
5344
#ifdef TARGET_I386
5345
            case QEMU_OPTION_win2k_hack:
5346
                win2k_install_hack = 1;
5347
                break;
5348
#endif
5349
#ifdef USE_KQEMU
5350
            case QEMU_OPTION_no_kqemu:
5351
                kqemu_allowed = 0;
5352
                break;
5353
            case QEMU_OPTION_kernel_kqemu:
5354
                kqemu_allowed = 2;
5355
                break;
5356
#endif
5357
            case QEMU_OPTION_usb:
5358
                usb_enabled = 1;
5359
                break;
5360
            case QEMU_OPTION_usbdevice:
5361
                usb_enabled = 1;
5362
                if (usb_devices_index >= MAX_VM_USB_PORTS) {
5363
                    fprintf(stderr, "Too many USB devices\n");
5364
                    exit(1);
5365
                }
5366
                pstrcpy(usb_devices[usb_devices_index],
5367
                        sizeof(usb_devices[usb_devices_index]),
5368
                        optarg);
5369
                usb_devices_index++;
5370
                break;
5371
            case QEMU_OPTION_smp:
5372
                smp_cpus = atoi(optarg);
5373
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5374
                    fprintf(stderr, "Invalid number of CPUs\n");
5375
                    exit(1);
5376
                }
5377
                break;
5378
            }
5379
        }
5380
    }
5381

    
5382
#ifdef USE_KQEMU
5383
    if (smp_cpus > 1)
5384
        kqemu_allowed = 0;
5385
#endif
5386
    linux_boot = (kernel_filename != NULL);
5387
        
5388
    if (!linux_boot && 
5389
        hd_filename[0] == '\0' && 
5390
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5391
        fd_filename[0] == '\0')
5392
        help();
5393
    
5394
    /* boot to cd by default if no hard disk */
5395
    if (hd_filename[0] == '\0' && boot_device == 'c') {
5396
        if (fd_filename[0] != '\0')
5397
            boot_device = 'a';
5398
        else
5399
            boot_device = 'd';
5400
    }
5401

    
5402
#if !defined(CONFIG_SOFTMMU)
5403
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5404
    {
5405
        static uint8_t stdout_buf[4096];
5406
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5407
    }
5408
#else
5409
    setvbuf(stdout, NULL, _IOLBF, 0);
5410
#endif
5411
    
5412
#ifdef _WIN32
5413
    socket_init();
5414
#endif
5415

    
5416
    /* init network clients */
5417
    if (nb_net_clients == 0) {
5418
        /* if no clients, we use a default config */
5419
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
5420
                "nic");
5421
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
5422
                "user");
5423
        nb_net_clients = 2;
5424
    }
5425

    
5426
    for(i = 0;i < nb_net_clients; i++) {
5427
        if (net_client_init(net_clients[i]) < 0)
5428
            exit(1);
5429
    }
5430

    
5431
    /* init the memory */
5432
    phys_ram_size = ram_size + vga_ram_size + bios_size;
5433

    
5434
#ifdef CONFIG_SOFTMMU
5435
    phys_ram_base = qemu_vmalloc(phys_ram_size);
5436
    if (!phys_ram_base) {
5437
        fprintf(stderr, "Could not allocate physical memory\n");
5438
        exit(1);
5439
    }
5440
#else
5441
    /* as we must map the same page at several addresses, we must use
5442
       a fd */
5443
    {
5444
        const char *tmpdir;
5445

    
5446
        tmpdir = getenv("QEMU_TMPDIR");
5447
        if (!tmpdir)
5448
            tmpdir = "/tmp";
5449
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5450
        if (mkstemp(phys_ram_file) < 0) {
5451
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
5452
                    phys_ram_file);
5453
            exit(1);
5454
        }
5455
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5456
        if (phys_ram_fd < 0) {
5457
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
5458
                    phys_ram_file);
5459
            exit(1);
5460
        }
5461
        ftruncate(phys_ram_fd, phys_ram_size);
5462
        unlink(phys_ram_file);
5463
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
5464
                             phys_ram_size, 
5465
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
5466
                             phys_ram_fd, 0);
5467
        if (phys_ram_base == MAP_FAILED) {
5468
            fprintf(stderr, "Could not map physical memory\n");
5469
            exit(1);
5470
        }
5471
    }
5472
#endif
5473

    
5474
    /* we always create the cdrom drive, even if no disk is there */
5475
    bdrv_init();
5476
    if (cdrom_index >= 0) {
5477
        bs_table[cdrom_index] = bdrv_new("cdrom");
5478
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5479
    }
5480

    
5481
    /* open the virtual block devices */
5482
    for(i = 0; i < MAX_DISKS; i++) {
5483
        if (hd_filename[i]) {
5484
            if (!bs_table[i]) {
5485
                char buf[64];
5486
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5487
                bs_table[i] = bdrv_new(buf);
5488
            }
5489
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5490
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5491
                        hd_filename[i]);
5492
                exit(1);
5493
            }
5494
            if (i == 0 && cyls != 0) {
5495
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5496
                bdrv_set_translation_hint(bs_table[i], translation);
5497
            }
5498
        }
5499
    }
5500

    
5501
    /* we always create at least one floppy disk */
5502
    fd_table[0] = bdrv_new("fda");
5503
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5504

    
5505
    for(i = 0; i < MAX_FD; i++) {
5506
        if (fd_filename[i]) {
5507
            if (!fd_table[i]) {
5508
                char buf[64];
5509
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5510
                fd_table[i] = bdrv_new(buf);
5511
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5512
            }
5513
            if (fd_filename[i] != '\0') {
5514
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5515
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5516
                            fd_filename[i]);
5517
                    exit(1);
5518
                }
5519
            }
5520
        }
5521
    }
5522

    
5523
    /* init USB devices */
5524
    if (usb_enabled) {
5525
        vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5526
        for(i = 0; i < usb_devices_index; i++) {
5527
            if (usb_device_add(usb_devices[i]) < 0) {
5528
                fprintf(stderr, "Warning: could not add USB device %s\n",
5529
                        usb_devices[i]);
5530
            }
5531
        }
5532
    }
5533

    
5534
    register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5535
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5536

    
5537
    init_ioports();
5538
    cpu_calibrate_ticks();
5539

    
5540
    /* terminal init */
5541
    if (nographic) {
5542
        dumb_display_init(ds);
5543
    } else {
5544
#if defined(CONFIG_SDL)
5545
        sdl_display_init(ds, full_screen);
5546
#elif defined(CONFIG_COCOA)
5547
        cocoa_display_init(ds, full_screen);
5548
#else
5549
        dumb_display_init(ds);
5550
#endif
5551
    }
5552

    
5553
    monitor_hd = qemu_chr_open(monitor_device);
5554
    if (!monitor_hd) {
5555
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5556
        exit(1);
5557
    }
5558
    monitor_init(monitor_hd, !nographic);
5559

    
5560
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5561
        if (serial_devices[i][0] != '\0') {
5562
            serial_hds[i] = qemu_chr_open(serial_devices[i]);
5563
            if (!serial_hds[i]) {
5564
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
5565
                        serial_devices[i]);
5566
                exit(1);
5567
            }
5568
            if (!strcmp(serial_devices[i], "vc"))
5569
                qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5570
        }
5571
    }
5572

    
5573
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5574
        if (parallel_devices[i][0] != '\0') {
5575
            parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5576
            if (!parallel_hds[i]) {
5577
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
5578
                        parallel_devices[i]);
5579
                exit(1);
5580
            }
5581
            if (!strcmp(parallel_devices[i], "vc"))
5582
                qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5583
        }
5584
    }
5585

    
5586
    /* setup cpu signal handlers for MMU / self modifying code handling */
5587
#if !defined(CONFIG_SOFTMMU)
5588
    
5589
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5590
    {
5591
        stack_t stk;
5592
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5593
        stk.ss_sp = signal_stack;
5594
        stk.ss_size = SIGNAL_STACK_SIZE;
5595
        stk.ss_flags = 0;
5596

    
5597
        if (sigaltstack(&stk, NULL) < 0) {
5598
            perror("sigaltstack");
5599
            exit(1);
5600
        }
5601
    }
5602
#endif
5603
    {
5604
        struct sigaction act;
5605
        
5606
        sigfillset(&act.sa_mask);
5607
        act.sa_flags = SA_SIGINFO;
5608
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5609
        act.sa_flags |= SA_ONSTACK;
5610
#endif
5611
        act.sa_sigaction = host_segv_handler;
5612
        sigaction(SIGSEGV, &act, NULL);
5613
        sigaction(SIGBUS, &act, NULL);
5614
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5615
        sigaction(SIGFPE, &act, NULL);
5616
#endif
5617
    }
5618
#endif
5619

    
5620
#ifndef _WIN32
5621
    {
5622
        struct sigaction act;
5623
        sigfillset(&act.sa_mask);
5624
        act.sa_flags = 0;
5625
        act.sa_handler = SIG_IGN;
5626
        sigaction(SIGPIPE, &act, NULL);
5627
    }
5628
#endif
5629
    init_timers();
5630

    
5631
    machine->init(ram_size, vga_ram_size, boot_device,
5632
                  ds, fd_filename, snapshot,
5633
                  kernel_filename, kernel_cmdline, initrd_filename);
5634

    
5635
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5636
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5637

    
5638
#ifdef CONFIG_GDBSTUB
5639
    if (use_gdbstub) {
5640
        if (gdbserver_start(gdbstub_port) < 0) {
5641
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
5642
                    gdbstub_port);
5643
            exit(1);
5644
        } else {
5645
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
5646
        }
5647
    } else 
5648
#endif
5649
    if (loadvm)
5650
        qemu_loadvm(loadvm);
5651

    
5652
    {
5653
        /* XXX: simplify init */
5654
        read_passwords();
5655
        if (start_emulation) {
5656
            vm_start();
5657
        }
5658
    }
5659
    main_loop();
5660
    quit_timers();
5661
    return 0;
5662
}