Statistics
| Branch: | Revision:

root / vl.c @ 09b26c5e

History | View | Annotate | Download (143.2 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
/* return the size or -1 if error */
336
int get_image_size(const char *filename)
337
{
338
    int fd, size;
339
    fd = open(filename, O_RDONLY | O_BINARY);
340
    if (fd < 0)
341
        return -1;
342
    size = lseek(fd, 0, SEEK_END);
343
    close(fd);
344
    return size;
345
}
346

    
347
/* return the size or -1 if error */
348
int load_image(const char *filename, uint8_t *addr)
349
{
350
    int fd, size;
351
    fd = open(filename, O_RDONLY | O_BINARY);
352
    if (fd < 0)
353
        return -1;
354
    size = lseek(fd, 0, SEEK_END);
355
    lseek(fd, 0, SEEK_SET);
356
    if (read(fd, addr, size) != size) {
357
        close(fd);
358
        return -1;
359
    }
360
    close(fd);
361
    return size;
362
}
363

    
364
void cpu_outb(CPUState *env, int addr, int val)
365
{
366
#ifdef DEBUG_IOPORT
367
    if (loglevel & CPU_LOG_IOPORT)
368
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
369
#endif    
370
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
371
#ifdef USE_KQEMU
372
    if (env)
373
        env->last_io_time = cpu_get_time_fast();
374
#endif
375
}
376

    
377
void cpu_outw(CPUState *env, int addr, int val)
378
{
379
#ifdef DEBUG_IOPORT
380
    if (loglevel & CPU_LOG_IOPORT)
381
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
382
#endif    
383
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
384
#ifdef USE_KQEMU
385
    if (env)
386
        env->last_io_time = cpu_get_time_fast();
387
#endif
388
}
389

    
390
void cpu_outl(CPUState *env, int addr, int val)
391
{
392
#ifdef DEBUG_IOPORT
393
    if (loglevel & CPU_LOG_IOPORT)
394
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
395
#endif
396
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
397
#ifdef USE_KQEMU
398
    if (env)
399
        env->last_io_time = cpu_get_time_fast();
400
#endif
401
}
402

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

    
418
int cpu_inw(CPUState *env, int addr)
419
{
420
    int val;
421
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
422
#ifdef DEBUG_IOPORT
423
    if (loglevel & CPU_LOG_IOPORT)
424
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
425
#endif
426
#ifdef USE_KQEMU
427
    if (env)
428
        env->last_io_time = cpu_get_time_fast();
429
#endif
430
    return val;
431
}
432

    
433
int cpu_inl(CPUState *env, int addr)
434
{
435
    int val;
436
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
437
#ifdef DEBUG_IOPORT
438
    if (loglevel & CPU_LOG_IOPORT)
439
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
440
#endif
441
#ifdef USE_KQEMU
442
    if (env)
443
        env->last_io_time = cpu_get_time_fast();
444
#endif
445
    return val;
446
}
447

    
448
/***********************************************************/
449
void hw_error(const char *fmt, ...)
450
{
451
    va_list ap;
452
    CPUState *env;
453

    
454
    va_start(ap, fmt);
455
    fprintf(stderr, "qemu: hardware error: ");
456
    vfprintf(stderr, fmt, ap);
457
    fprintf(stderr, "\n");
458
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
459
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
460
#ifdef TARGET_I386
461
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
462
#else
463
        cpu_dump_state(env, stderr, fprintf, 0);
464
#endif
465
    }
466
    va_end(ap);
467
    abort();
468
}
469

    
470
/***********************************************************/
471
/* keyboard/mouse */
472

    
473
static QEMUPutKBDEvent *qemu_put_kbd_event;
474
static void *qemu_put_kbd_event_opaque;
475
static QEMUPutMouseEvent *qemu_put_mouse_event;
476
static void *qemu_put_mouse_event_opaque;
477
static int qemu_put_mouse_event_absolute;
478

    
479
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
480
{
481
    qemu_put_kbd_event_opaque = opaque;
482
    qemu_put_kbd_event = func;
483
}
484

    
485
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
486
{
487
    qemu_put_mouse_event_opaque = opaque;
488
    qemu_put_mouse_event = func;
489
    qemu_put_mouse_event_absolute = absolute;
490
}
491

    
492
void kbd_put_keycode(int keycode)
493
{
494
    if (qemu_put_kbd_event) {
495
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
496
    }
497
}
498

    
499
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
500
{
501
    if (qemu_put_mouse_event) {
502
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
503
                             dx, dy, dz, buttons_state);
504
    }
505
}
506

    
507
int kbd_mouse_is_absolute(void)
508
{
509
    return qemu_put_mouse_event_absolute;
510
}
511

    
512
/***********************************************************/
513
/* timers */
514

    
515
#if defined(__powerpc__)
516

    
517
static inline uint32_t get_tbl(void) 
518
{
519
    uint32_t tbl;
520
    asm volatile("mftb %0" : "=r" (tbl));
521
    return tbl;
522
}
523

    
524
static inline uint32_t get_tbu(void) 
525
{
526
        uint32_t tbl;
527
        asm volatile("mftbu %0" : "=r" (tbl));
528
        return tbl;
529
}
530

    
531
int64_t cpu_get_real_ticks(void)
532
{
533
    uint32_t l, h, h1;
534
    /* NOTE: we test if wrapping has occurred */
535
    do {
536
        h = get_tbu();
537
        l = get_tbl();
538
        h1 = get_tbu();
539
    } while (h != h1);
540
    return ((int64_t)h << 32) | l;
541
}
542

    
543
#elif defined(__i386__)
544

    
545
int64_t cpu_get_real_ticks(void)
546
{
547
    int64_t val;
548
    asm volatile ("rdtsc" : "=A" (val));
549
    return val;
550
}
551

    
552
#elif defined(__x86_64__)
553

    
554
int64_t cpu_get_real_ticks(void)
555
{
556
    uint32_t low,high;
557
    int64_t val;
558
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
559
    val = high;
560
    val <<= 32;
561
    val |= low;
562
    return val;
563
}
564

    
565
#elif defined(__ia64)
566

    
567
int64_t cpu_get_real_ticks(void)
568
{
569
        int64_t val;
570
        asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
571
        return val;
572
}
573

    
574
#elif defined(__s390__)
575

    
576
int64_t cpu_get_real_ticks(void)
577
{
578
    int64_t val;
579
    asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
580
    return val;
581
}
582

    
583
#else
584
#error unsupported CPU
585
#endif
586

    
587
static int64_t cpu_ticks_offset;
588
static int cpu_ticks_enabled;
589

    
590
static inline int64_t cpu_get_ticks(void)
591
{
592
    if (!cpu_ticks_enabled) {
593
        return cpu_ticks_offset;
594
    } else {
595
        return cpu_get_real_ticks() + cpu_ticks_offset;
596
    }
597
}
598

    
599
/* enable cpu_get_ticks() */
600
void cpu_enable_ticks(void)
601
{
602
    if (!cpu_ticks_enabled) {
603
        cpu_ticks_offset -= cpu_get_real_ticks();
604
        cpu_ticks_enabled = 1;
605
    }
606
}
607

    
608
/* disable cpu_get_ticks() : the clock is stopped. You must not call
609
   cpu_get_ticks() after that.  */
610
void cpu_disable_ticks(void)
611
{
612
    if (cpu_ticks_enabled) {
613
        cpu_ticks_offset = cpu_get_ticks();
614
        cpu_ticks_enabled = 0;
615
    }
616
}
617

    
618
static int64_t get_clock(void)
619
{
620
#ifdef _WIN32
621
    struct _timeb tb;
622
    _ftime(&tb);
623
    return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
624
#else
625
    struct timeval tv;
626
    gettimeofday(&tv, NULL);
627
    return tv.tv_sec * 1000000LL + tv.tv_usec;
628
#endif
629
}
630

    
631
void cpu_calibrate_ticks(void)
632
{
633
    int64_t usec, ticks;
634

    
635
    usec = get_clock();
636
    ticks = cpu_get_real_ticks();
637
#ifdef _WIN32
638
    Sleep(50);
639
#else
640
    usleep(50 * 1000);
641
#endif
642
    usec = get_clock() - usec;
643
    ticks = cpu_get_real_ticks() - ticks;
644
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
645
}
646

    
647
/* compute with 96 bit intermediate result: (a*b)/c */
648
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
649
{
650
    union {
651
        uint64_t ll;
652
        struct {
653
#ifdef WORDS_BIGENDIAN
654
            uint32_t high, low;
655
#else
656
            uint32_t low, high;
657
#endif            
658
        } l;
659
    } u, res;
660
    uint64_t rl, rh;
661

    
662
    u.ll = a;
663
    rl = (uint64_t)u.l.low * (uint64_t)b;
664
    rh = (uint64_t)u.l.high * (uint64_t)b;
665
    rh += (rl >> 32);
666
    res.l.high = rh / c;
667
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
668
    return res.ll;
669
}
670

    
671
#define QEMU_TIMER_REALTIME 0
672
#define QEMU_TIMER_VIRTUAL  1
673

    
674
struct QEMUClock {
675
    int type;
676
    /* XXX: add frequency */
677
};
678

    
679
struct QEMUTimer {
680
    QEMUClock *clock;
681
    int64_t expire_time;
682
    QEMUTimerCB *cb;
683
    void *opaque;
684
    struct QEMUTimer *next;
685
};
686

    
687
QEMUClock *rt_clock;
688
QEMUClock *vm_clock;
689

    
690
static QEMUTimer *active_timers[2];
691
#ifdef _WIN32
692
static MMRESULT timerID;
693
#else
694
/* frequency of the times() clock tick */
695
static int timer_freq;
696
#endif
697

    
698
QEMUClock *qemu_new_clock(int type)
699
{
700
    QEMUClock *clock;
701
    clock = qemu_mallocz(sizeof(QEMUClock));
702
    if (!clock)
703
        return NULL;
704
    clock->type = type;
705
    return clock;
706
}
707

    
708
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
709
{
710
    QEMUTimer *ts;
711

    
712
    ts = qemu_mallocz(sizeof(QEMUTimer));
713
    ts->clock = clock;
714
    ts->cb = cb;
715
    ts->opaque = opaque;
716
    return ts;
717
}
718

    
719
void qemu_free_timer(QEMUTimer *ts)
720
{
721
    qemu_free(ts);
722
}
723

    
724
/* stop a timer, but do not dealloc it */
725
void qemu_del_timer(QEMUTimer *ts)
726
{
727
    QEMUTimer **pt, *t;
728

    
729
    /* NOTE: this code must be signal safe because
730
       qemu_timer_expired() can be called from a signal. */
731
    pt = &active_timers[ts->clock->type];
732
    for(;;) {
733
        t = *pt;
734
        if (!t)
735
            break;
736
        if (t == ts) {
737
            *pt = t->next;
738
            break;
739
        }
740
        pt = &t->next;
741
    }
742
}
743

    
744
/* modify the current timer so that it will be fired when current_time
745
   >= expire_time. The corresponding callback will be called. */
746
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
747
{
748
    QEMUTimer **pt, *t;
749

    
750
    qemu_del_timer(ts);
751

    
752
    /* add the timer in the sorted list */
753
    /* NOTE: this code must be signal safe because
754
       qemu_timer_expired() can be called from a signal. */
755
    pt = &active_timers[ts->clock->type];
756
    for(;;) {
757
        t = *pt;
758
        if (!t)
759
            break;
760
        if (t->expire_time > expire_time) 
761
            break;
762
        pt = &t->next;
763
    }
764
    ts->expire_time = expire_time;
765
    ts->next = *pt;
766
    *pt = ts;
767
}
768

    
769
int qemu_timer_pending(QEMUTimer *ts)
770
{
771
    QEMUTimer *t;
772
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
773
        if (t == ts)
774
            return 1;
775
    }
776
    return 0;
777
}
778

    
779
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
780
{
781
    if (!timer_head)
782
        return 0;
783
    return (timer_head->expire_time <= current_time);
784
}
785

    
786
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
787
{
788
    QEMUTimer *ts;
789
    
790
    for(;;) {
791
        ts = *ptimer_head;
792
        if (!ts || ts->expire_time > current_time)
793
            break;
794
        /* remove timer from the list before calling the callback */
795
        *ptimer_head = ts->next;
796
        ts->next = NULL;
797
        
798
        /* run the callback (the timer list can be modified) */
799
        ts->cb(ts->opaque);
800
    }
801
}
802

    
803
int64_t qemu_get_clock(QEMUClock *clock)
804
{
805
    switch(clock->type) {
806
    case QEMU_TIMER_REALTIME:
807
#ifdef _WIN32
808
        return GetTickCount();
809
#else
810
        {
811
            struct tms tp;
812

    
813
            /* Note that using gettimeofday() is not a good solution
814
               for timers because its value change when the date is
815
               modified. */
816
            if (timer_freq == 100) {
817
                return times(&tp) * 10;
818
            } else {
819
                return ((int64_t)times(&tp) * 1000) / timer_freq;
820
            }
821
        }
822
#endif
823
    default:
824
    case QEMU_TIMER_VIRTUAL:
825
        return cpu_get_ticks();
826
    }
827
}
828

    
829
/* save a timer */
830
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
831
{
832
    uint64_t expire_time;
833

    
834
    if (qemu_timer_pending(ts)) {
835
        expire_time = ts->expire_time;
836
    } else {
837
        expire_time = -1;
838
    }
839
    qemu_put_be64(f, expire_time);
840
}
841

    
842
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
843
{
844
    uint64_t expire_time;
845

    
846
    expire_time = qemu_get_be64(f);
847
    if (expire_time != -1) {
848
        qemu_mod_timer(ts, expire_time);
849
    } else {
850
        qemu_del_timer(ts);
851
    }
852
}
853

    
854
static void timer_save(QEMUFile *f, void *opaque)
855
{
856
    if (cpu_ticks_enabled) {
857
        hw_error("cannot save state if virtual timers are running");
858
    }
859
    qemu_put_be64s(f, &cpu_ticks_offset);
860
    qemu_put_be64s(f, &ticks_per_sec);
861
}
862

    
863
static int timer_load(QEMUFile *f, void *opaque, int version_id)
864
{
865
    if (version_id != 1)
866
        return -EINVAL;
867
    if (cpu_ticks_enabled) {
868
        return -EINVAL;
869
    }
870
    qemu_get_be64s(f, &cpu_ticks_offset);
871
    qemu_get_be64s(f, &ticks_per_sec);
872
    return 0;
873
}
874

    
875
#ifdef _WIN32
876
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
877
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
878
#else
879
static void host_alarm_handler(int host_signum)
880
#endif
881
{
882
#if 0
883
#define DISP_FREQ 1000
884
    {
885
        static int64_t delta_min = INT64_MAX;
886
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
887
        static int count;
888
        ti = qemu_get_clock(vm_clock);
889
        if (last_clock != 0) {
890
            delta = ti - last_clock;
891
            if (delta < delta_min)
892
                delta_min = delta;
893
            if (delta > delta_max)
894
                delta_max = delta;
895
            delta_cum += delta;
896
            if (++count == DISP_FREQ) {
897
                printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
898
                       muldiv64(delta_min, 1000000, ticks_per_sec),
899
                       muldiv64(delta_max, 1000000, ticks_per_sec),
900
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
901
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
902
                count = 0;
903
                delta_min = INT64_MAX;
904
                delta_max = 0;
905
                delta_cum = 0;
906
            }
907
        }
908
        last_clock = ti;
909
    }
910
#endif
911
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
912
                           qemu_get_clock(vm_clock)) ||
913
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
914
                           qemu_get_clock(rt_clock))) {
915
        CPUState *env = cpu_single_env;
916
        if (env) {
917
            /* stop the currently executing cpu because a timer occured */
918
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
919
#ifdef USE_KQEMU
920
            if (env->kqemu_enabled) {
921
                kqemu_cpu_interrupt(env);
922
            }
923
#endif
924
        }
925
    }
926
}
927

    
928
#ifndef _WIN32
929

    
930
#if defined(__linux__)
931

    
932
#define RTC_FREQ 1024
933

    
934
static int rtc_fd;
935

    
936
static int start_rtc_timer(void)
937
{
938
    rtc_fd = open("/dev/rtc", O_RDONLY);
939
    if (rtc_fd < 0)
940
        return -1;
941
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
942
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
943
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
944
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
945
        goto fail;
946
    }
947
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
948
    fail:
949
        close(rtc_fd);
950
        return -1;
951
    }
952
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
953
    return 0;
954
}
955

    
956
#else
957

    
958
static int start_rtc_timer(void)
959
{
960
    return -1;
961
}
962

    
963
#endif /* !defined(__linux__) */
964

    
965
#endif /* !defined(_WIN32) */
966

    
967
static void init_timers(void)
968
{
969
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
970
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
971

    
972
#ifdef _WIN32
973
    {
974
        int count=0;
975
        timerID = timeSetEvent(1,     // interval (ms)
976
                               0,     // resolution
977
                               host_alarm_handler, // function
978
                               (DWORD)&count,  // user parameter
979
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
980
         if( !timerID ) {
981
            perror("failed timer alarm");
982
            exit(1);
983
         }
984
    }
985
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
986
#else
987
    {
988
        struct sigaction act;
989
        struct itimerval itv;
990
        
991
        /* get times() syscall frequency */
992
        timer_freq = sysconf(_SC_CLK_TCK);
993
        
994
        /* timer signal */
995
        sigfillset(&act.sa_mask);
996
       act.sa_flags = 0;
997
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
998
        act.sa_flags |= SA_ONSTACK;
999
#endif
1000
        act.sa_handler = host_alarm_handler;
1001
        sigaction(SIGALRM, &act, NULL);
1002

    
1003
        itv.it_interval.tv_sec = 0;
1004
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1005
        itv.it_value.tv_sec = 0;
1006
        itv.it_value.tv_usec = 10 * 1000;
1007
        setitimer(ITIMER_REAL, &itv, NULL);
1008
        /* we probe the tick duration of the kernel to inform the user if
1009
           the emulated kernel requested a too high timer frequency */
1010
        getitimer(ITIMER_REAL, &itv);
1011

    
1012
#if defined(__linux__)
1013
        if (itv.it_interval.tv_usec > 1000) {
1014
            /* try to use /dev/rtc to have a faster timer */
1015
            if (start_rtc_timer() < 0)
1016
                goto use_itimer;
1017
            /* disable itimer */
1018
            itv.it_interval.tv_sec = 0;
1019
            itv.it_interval.tv_usec = 0;
1020
            itv.it_value.tv_sec = 0;
1021
            itv.it_value.tv_usec = 0;
1022
            setitimer(ITIMER_REAL, &itv, NULL);
1023

    
1024
            /* use the RTC */
1025
            sigaction(SIGIO, &act, NULL);
1026
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1027
            fcntl(rtc_fd, F_SETOWN, getpid());
1028
        } else 
1029
#endif /* defined(__linux__) */
1030
        {
1031
        use_itimer:
1032
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1033
                                   PIT_FREQ) / 1000000;
1034
        }
1035
    }
1036
#endif
1037
}
1038

    
1039
void quit_timers(void)
1040
{
1041
#ifdef _WIN32
1042
    timeKillEvent(timerID);
1043
#endif
1044
}
1045

    
1046
/***********************************************************/
1047
/* character device */
1048

    
1049
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1050
{
1051
    return s->chr_write(s, buf, len);
1052
}
1053

    
1054
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1055
{
1056
    if (!s->chr_ioctl)
1057
        return -ENOTSUP;
1058
    return s->chr_ioctl(s, cmd, arg);
1059
}
1060

    
1061
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1062
{
1063
    char buf[4096];
1064
    va_list ap;
1065
    va_start(ap, fmt);
1066
    vsnprintf(buf, sizeof(buf), fmt, ap);
1067
    qemu_chr_write(s, buf, strlen(buf));
1068
    va_end(ap);
1069
}
1070

    
1071
void qemu_chr_send_event(CharDriverState *s, int event)
1072
{
1073
    if (s->chr_send_event)
1074
        s->chr_send_event(s, event);
1075
}
1076

    
1077
void qemu_chr_add_read_handler(CharDriverState *s, 
1078
                               IOCanRWHandler *fd_can_read, 
1079
                               IOReadHandler *fd_read, void *opaque)
1080
{
1081
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1082
}
1083
             
1084
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1085
{
1086
    s->chr_event = chr_event;
1087
}
1088

    
1089
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1090
{
1091
    return len;
1092
}
1093

    
1094
static void null_chr_add_read_handler(CharDriverState *chr, 
1095
                                    IOCanRWHandler *fd_can_read, 
1096
                                    IOReadHandler *fd_read, void *opaque)
1097
{
1098
}
1099

    
1100
CharDriverState *qemu_chr_open_null(void)
1101
{
1102
    CharDriverState *chr;
1103

    
1104
    chr = qemu_mallocz(sizeof(CharDriverState));
1105
    if (!chr)
1106
        return NULL;
1107
    chr->chr_write = null_chr_write;
1108
    chr->chr_add_read_handler = null_chr_add_read_handler;
1109
    return chr;
1110
}
1111

    
1112
#ifdef _WIN32
1113

    
1114
#define socket_error() WSAGetLastError()
1115
#undef EINTR
1116
#define EWOULDBLOCK WSAEWOULDBLOCK
1117
#define EINTR       WSAEINTR
1118
#define EINPROGRESS WSAEINPROGRESS
1119

    
1120
static void socket_cleanup(void)
1121
{
1122
    WSACleanup();
1123
}
1124

    
1125
static int socket_init(void)
1126
{
1127
    WSADATA Data;
1128
    int ret, err;
1129

    
1130
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1131
    if (ret != 0) {
1132
        err = WSAGetLastError();
1133
        fprintf(stderr, "WSAStartup: %d\n", err);
1134
        return -1;
1135
    }
1136
    atexit(socket_cleanup);
1137
    return 0;
1138
}
1139

    
1140
static int send_all(int fd, const uint8_t *buf, int len1)
1141
{
1142
    int ret, len;
1143
    
1144
    len = len1;
1145
    while (len > 0) {
1146
        ret = send(fd, buf, len, 0);
1147
        if (ret < 0) {
1148
            int errno;
1149
            errno = WSAGetLastError();
1150
            if (errno != WSAEWOULDBLOCK) {
1151
                return -1;
1152
            }
1153
        } else if (ret == 0) {
1154
            break;
1155
        } else {
1156
            buf += ret;
1157
            len -= ret;
1158
        }
1159
    }
1160
    return len1 - len;
1161
}
1162

    
1163
void socket_set_nonblock(int fd)
1164
{
1165
    unsigned long opt = 1;
1166
    ioctlsocket(fd, FIONBIO, &opt);
1167
}
1168

    
1169
#else
1170

    
1171
#define socket_error() errno
1172
#define closesocket(s) close(s)
1173

    
1174
static int unix_write(int fd, const uint8_t *buf, int len1)
1175
{
1176
    int ret, len;
1177

    
1178
    len = len1;
1179
    while (len > 0) {
1180
        ret = write(fd, buf, len);
1181
        if (ret < 0) {
1182
            if (errno != EINTR && errno != EAGAIN)
1183
                return -1;
1184
        } else if (ret == 0) {
1185
            break;
1186
        } else {
1187
            buf += ret;
1188
            len -= ret;
1189
        }
1190
    }
1191
    return len1 - len;
1192
}
1193

    
1194
static inline int send_all(int fd, const uint8_t *buf, int len1)
1195
{
1196
    return unix_write(fd, buf, len1);
1197
}
1198

    
1199
void socket_set_nonblock(int fd)
1200
{
1201
    fcntl(fd, F_SETFL, O_NONBLOCK);
1202
}
1203
#endif /* !_WIN32 */
1204

    
1205
#ifndef _WIN32
1206

    
1207
typedef struct {
1208
    int fd_in, fd_out;
1209
    IOCanRWHandler *fd_can_read; 
1210
    IOReadHandler *fd_read;
1211
    void *fd_opaque;
1212
    int max_size;
1213
} FDCharDriver;
1214

    
1215
#define STDIO_MAX_CLIENTS 2
1216

    
1217
static int stdio_nb_clients;
1218
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1219

    
1220
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1221
{
1222
    FDCharDriver *s = chr->opaque;
1223
    return unix_write(s->fd_out, buf, len);
1224
}
1225

    
1226
static int fd_chr_read_poll(void *opaque)
1227
{
1228
    CharDriverState *chr = opaque;
1229
    FDCharDriver *s = chr->opaque;
1230

    
1231
    s->max_size = s->fd_can_read(s->fd_opaque);
1232
    return s->max_size;
1233
}
1234

    
1235
static void fd_chr_read(void *opaque)
1236
{
1237
    CharDriverState *chr = opaque;
1238
    FDCharDriver *s = chr->opaque;
1239
    int size, len;
1240
    uint8_t buf[1024];
1241
    
1242
    len = sizeof(buf);
1243
    if (len > s->max_size)
1244
        len = s->max_size;
1245
    if (len == 0)
1246
        return;
1247
    size = read(s->fd_in, buf, len);
1248
    if (size > 0) {
1249
        s->fd_read(s->fd_opaque, buf, size);
1250
    }
1251
}
1252

    
1253
static void fd_chr_add_read_handler(CharDriverState *chr, 
1254
                                    IOCanRWHandler *fd_can_read, 
1255
                                    IOReadHandler *fd_read, void *opaque)
1256
{
1257
    FDCharDriver *s = chr->opaque;
1258

    
1259
    if (s->fd_in >= 0) {
1260
        s->fd_can_read = fd_can_read;
1261
        s->fd_read = fd_read;
1262
        s->fd_opaque = opaque;
1263
        if (nographic && s->fd_in == 0) {
1264
        } else {
1265
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1266
                                 fd_chr_read, NULL, chr);
1267
        }
1268
    }
1269
}
1270

    
1271
/* open a character device to a unix fd */
1272
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1273
{
1274
    CharDriverState *chr;
1275
    FDCharDriver *s;
1276

    
1277
    chr = qemu_mallocz(sizeof(CharDriverState));
1278
    if (!chr)
1279
        return NULL;
1280
    s = qemu_mallocz(sizeof(FDCharDriver));
1281
    if (!s) {
1282
        free(chr);
1283
        return NULL;
1284
    }
1285
    s->fd_in = fd_in;
1286
    s->fd_out = fd_out;
1287
    chr->opaque = s;
1288
    chr->chr_write = fd_chr_write;
1289
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1290
    return chr;
1291
}
1292

    
1293
CharDriverState *qemu_chr_open_file_out(const char *file_out)
1294
{
1295
    int fd_out;
1296

    
1297
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1298
    if (fd_out < 0)
1299
        return NULL;
1300
    return qemu_chr_open_fd(-1, fd_out);
1301
}
1302

    
1303
CharDriverState *qemu_chr_open_pipe(const char *filename)
1304
{
1305
    int fd;
1306

    
1307
    fd = open(filename, O_RDWR | O_BINARY);
1308
    if (fd < 0)
1309
        return NULL;
1310
    return qemu_chr_open_fd(fd, fd);
1311
}
1312

    
1313

    
1314
/* for STDIO, we handle the case where several clients use it
1315
   (nographic mode) */
1316

    
1317
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1318

    
1319
#define TERM_FIFO_MAX_SIZE 1
1320

    
1321
static int term_got_escape, client_index;
1322
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1323
int term_fifo_size;
1324

    
1325
void term_print_help(void)
1326
{
1327
    printf("\n"
1328
           "C-a h    print this help\n"
1329
           "C-a x    exit emulator\n"
1330
           "C-a s    save disk data back to file (if -snapshot)\n"
1331
           "C-a b    send break (magic sysrq)\n"
1332
           "C-a c    switch between console and monitor\n"
1333
           "C-a C-a  send C-a\n"
1334
           );
1335
}
1336

    
1337
/* called when a char is received */
1338
static void stdio_received_byte(int ch)
1339
{
1340
    if (term_got_escape) {
1341
        term_got_escape = 0;
1342
        switch(ch) {
1343
        case 'h':
1344
            term_print_help();
1345
            break;
1346
        case 'x':
1347
            exit(0);
1348
            break;
1349
        case 's': 
1350
            {
1351
                int i;
1352
                for (i = 0; i < MAX_DISKS; i++) {
1353
                    if (bs_table[i])
1354
                        bdrv_commit(bs_table[i]);
1355
                }
1356
            }
1357
            break;
1358
        case 'b':
1359
            if (client_index < stdio_nb_clients) {
1360
                CharDriverState *chr;
1361
                FDCharDriver *s;
1362

    
1363
                chr = stdio_clients[client_index];
1364
                s = chr->opaque;
1365
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1366
            }
1367
            break;
1368
        case 'c':
1369
            client_index++;
1370
            if (client_index >= stdio_nb_clients)
1371
                client_index = 0;
1372
            if (client_index == 0) {
1373
                /* send a new line in the monitor to get the prompt */
1374
                ch = '\r';
1375
                goto send_char;
1376
            }
1377
            break;
1378
        case TERM_ESCAPE:
1379
            goto send_char;
1380
        }
1381
    } else if (ch == TERM_ESCAPE) {
1382
        term_got_escape = 1;
1383
    } else {
1384
    send_char:
1385
        if (client_index < stdio_nb_clients) {
1386
            uint8_t buf[1];
1387
            CharDriverState *chr;
1388
            FDCharDriver *s;
1389
            
1390
            chr = stdio_clients[client_index];
1391
            s = chr->opaque;
1392
            if (s->fd_can_read(s->fd_opaque) > 0) {
1393
                buf[0] = ch;
1394
                s->fd_read(s->fd_opaque, buf, 1);
1395
            } else if (term_fifo_size == 0) {
1396
                term_fifo[term_fifo_size++] = ch;
1397
            }
1398
        }
1399
    }
1400
}
1401

    
1402
static int stdio_read_poll(void *opaque)
1403
{
1404
    CharDriverState *chr;
1405
    FDCharDriver *s;
1406

    
1407
    if (client_index < stdio_nb_clients) {
1408
        chr = stdio_clients[client_index];
1409
        s = chr->opaque;
1410
        /* try to flush the queue if needed */
1411
        if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1412
            s->fd_read(s->fd_opaque, term_fifo, 1);
1413
            term_fifo_size = 0;
1414
        }
1415
        /* see if we can absorb more chars */
1416
        if (term_fifo_size == 0)
1417
            return 1;
1418
        else
1419
            return 0;
1420
    } else {
1421
        return 1;
1422
    }
1423
}
1424

    
1425
static void stdio_read(void *opaque)
1426
{
1427
    int size;
1428
    uint8_t buf[1];
1429
    
1430
    size = read(0, buf, 1);
1431
    if (size > 0)
1432
        stdio_received_byte(buf[0]);
1433
}
1434

    
1435
/* init terminal so that we can grab keys */
1436
static struct termios oldtty;
1437
static int old_fd0_flags;
1438

    
1439
static void term_exit(void)
1440
{
1441
    tcsetattr (0, TCSANOW, &oldtty);
1442
    fcntl(0, F_SETFL, old_fd0_flags);
1443
}
1444

    
1445
static void term_init(void)
1446
{
1447
    struct termios tty;
1448

    
1449
    tcgetattr (0, &tty);
1450
    oldtty = tty;
1451
    old_fd0_flags = fcntl(0, F_GETFL);
1452

    
1453
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1454
                          |INLCR|IGNCR|ICRNL|IXON);
1455
    tty.c_oflag |= OPOST;
1456
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1457
    /* if graphical mode, we allow Ctrl-C handling */
1458
    if (nographic)
1459
        tty.c_lflag &= ~ISIG;
1460
    tty.c_cflag &= ~(CSIZE|PARENB);
1461
    tty.c_cflag |= CS8;
1462
    tty.c_cc[VMIN] = 1;
1463
    tty.c_cc[VTIME] = 0;
1464
    
1465
    tcsetattr (0, TCSANOW, &tty);
1466

    
1467
    atexit(term_exit);
1468

    
1469
    fcntl(0, F_SETFL, O_NONBLOCK);
1470
}
1471

    
1472
CharDriverState *qemu_chr_open_stdio(void)
1473
{
1474
    CharDriverState *chr;
1475

    
1476
    if (nographic) {
1477
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1478
            return NULL;
1479
        chr = qemu_chr_open_fd(0, 1);
1480
        if (stdio_nb_clients == 0)
1481
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1482
        client_index = stdio_nb_clients;
1483
    } else {
1484
        if (stdio_nb_clients != 0)
1485
            return NULL;
1486
        chr = qemu_chr_open_fd(0, 1);
1487
    }
1488
    stdio_clients[stdio_nb_clients++] = chr;
1489
    if (stdio_nb_clients == 1) {
1490
        /* set the terminal in raw mode */
1491
        term_init();
1492
    }
1493
    return chr;
1494
}
1495

    
1496
#if defined(__linux__)
1497
CharDriverState *qemu_chr_open_pty(void)
1498
{
1499
    struct termios tty;
1500
    char slave_name[1024];
1501
    int master_fd, slave_fd;
1502
    
1503
    /* Not satisfying */
1504
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1505
        return NULL;
1506
    }
1507
    
1508
    /* Disabling local echo and line-buffered output */
1509
    tcgetattr (master_fd, &tty);
1510
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1511
    tty.c_cc[VMIN] = 1;
1512
    tty.c_cc[VTIME] = 0;
1513
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1514

    
1515
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1516
    return qemu_chr_open_fd(master_fd, master_fd);
1517
}
1518

    
1519
static void tty_serial_init(int fd, int speed, 
1520
                            int parity, int data_bits, int stop_bits)
1521
{
1522
    struct termios tty;
1523
    speed_t spd;
1524

    
1525
#if 0
1526
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1527
           speed, parity, data_bits, stop_bits);
1528
#endif
1529
    tcgetattr (fd, &tty);
1530

    
1531
    switch(speed) {
1532
    case 50:
1533
        spd = B50;
1534
        break;
1535
    case 75:
1536
        spd = B75;
1537
        break;
1538
    case 300:
1539
        spd = B300;
1540
        break;
1541
    case 600:
1542
        spd = B600;
1543
        break;
1544
    case 1200:
1545
        spd = B1200;
1546
        break;
1547
    case 2400:
1548
        spd = B2400;
1549
        break;
1550
    case 4800:
1551
        spd = B4800;
1552
        break;
1553
    case 9600:
1554
        spd = B9600;
1555
        break;
1556
    case 19200:
1557
        spd = B19200;
1558
        break;
1559
    case 38400:
1560
        spd = B38400;
1561
        break;
1562
    case 57600:
1563
        spd = B57600;
1564
        break;
1565
    default:
1566
    case 115200:
1567
        spd = B115200;
1568
        break;
1569
    }
1570

    
1571
    cfsetispeed(&tty, spd);
1572
    cfsetospeed(&tty, spd);
1573

    
1574
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1575
                          |INLCR|IGNCR|ICRNL|IXON);
1576
    tty.c_oflag |= OPOST;
1577
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1578
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1579
    switch(data_bits) {
1580
    default:
1581
    case 8:
1582
        tty.c_cflag |= CS8;
1583
        break;
1584
    case 7:
1585
        tty.c_cflag |= CS7;
1586
        break;
1587
    case 6:
1588
        tty.c_cflag |= CS6;
1589
        break;
1590
    case 5:
1591
        tty.c_cflag |= CS5;
1592
        break;
1593
    }
1594
    switch(parity) {
1595
    default:
1596
    case 'N':
1597
        break;
1598
    case 'E':
1599
        tty.c_cflag |= PARENB;
1600
        break;
1601
    case 'O':
1602
        tty.c_cflag |= PARENB | PARODD;
1603
        break;
1604
    }
1605
    
1606
    tcsetattr (fd, TCSANOW, &tty);
1607
}
1608

    
1609
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1610
{
1611
    FDCharDriver *s = chr->opaque;
1612
    
1613
    switch(cmd) {
1614
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1615
        {
1616
            QEMUSerialSetParams *ssp = arg;
1617
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1618
                            ssp->data_bits, ssp->stop_bits);
1619
        }
1620
        break;
1621
    case CHR_IOCTL_SERIAL_SET_BREAK:
1622
        {
1623
            int enable = *(int *)arg;
1624
            if (enable)
1625
                tcsendbreak(s->fd_in, 1);
1626
        }
1627
        break;
1628
    default:
1629
        return -ENOTSUP;
1630
    }
1631
    return 0;
1632
}
1633

    
1634
CharDriverState *qemu_chr_open_tty(const char *filename)
1635
{
1636
    CharDriverState *chr;
1637
    int fd;
1638

    
1639
    fd = open(filename, O_RDWR | O_NONBLOCK);
1640
    if (fd < 0)
1641
        return NULL;
1642
    fcntl(fd, F_SETFL, O_NONBLOCK);
1643
    tty_serial_init(fd, 115200, 'N', 8, 1);
1644
    chr = qemu_chr_open_fd(fd, fd);
1645
    if (!chr)
1646
        return NULL;
1647
    chr->chr_ioctl = tty_serial_ioctl;
1648
    return chr;
1649
}
1650

    
1651
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1652
{
1653
    int fd = (int)chr->opaque;
1654
    uint8_t b;
1655

    
1656
    switch(cmd) {
1657
    case CHR_IOCTL_PP_READ_DATA:
1658
        if (ioctl(fd, PPRDATA, &b) < 0)
1659
            return -ENOTSUP;
1660
        *(uint8_t *)arg = b;
1661
        break;
1662
    case CHR_IOCTL_PP_WRITE_DATA:
1663
        b = *(uint8_t *)arg;
1664
        if (ioctl(fd, PPWDATA, &b) < 0)
1665
            return -ENOTSUP;
1666
        break;
1667
    case CHR_IOCTL_PP_READ_CONTROL:
1668
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1669
            return -ENOTSUP;
1670
        *(uint8_t *)arg = b;
1671
        break;
1672
    case CHR_IOCTL_PP_WRITE_CONTROL:
1673
        b = *(uint8_t *)arg;
1674
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1675
            return -ENOTSUP;
1676
        break;
1677
    case CHR_IOCTL_PP_READ_STATUS:
1678
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1679
            return -ENOTSUP;
1680
        *(uint8_t *)arg = b;
1681
        break;
1682
    default:
1683
        return -ENOTSUP;
1684
    }
1685
    return 0;
1686
}
1687

    
1688
CharDriverState *qemu_chr_open_pp(const char *filename)
1689
{
1690
    CharDriverState *chr;
1691
    int fd;
1692

    
1693
    fd = open(filename, O_RDWR);
1694
    if (fd < 0)
1695
        return NULL;
1696

    
1697
    if (ioctl(fd, PPCLAIM) < 0) {
1698
        close(fd);
1699
        return NULL;
1700
    }
1701

    
1702
    chr = qemu_mallocz(sizeof(CharDriverState));
1703
    if (!chr) {
1704
        close(fd);
1705
        return NULL;
1706
    }
1707
    chr->opaque = (void *)fd;
1708
    chr->chr_write = null_chr_write;
1709
    chr->chr_add_read_handler = null_chr_add_read_handler;
1710
    chr->chr_ioctl = pp_ioctl;
1711
    return chr;
1712
}
1713

    
1714
#else
1715
CharDriverState *qemu_chr_open_pty(void)
1716
{
1717
    return NULL;
1718
}
1719
#endif
1720

    
1721
#endif /* !defined(_WIN32) */
1722

    
1723
#ifdef _WIN32
1724
typedef struct {
1725
    IOCanRWHandler *fd_can_read; 
1726
    IOReadHandler *fd_read;
1727
    void *win_opaque;
1728
    int max_size;
1729
    HANDLE hcom, hrecv, hsend;
1730
    OVERLAPPED orecv, osend;
1731
    BOOL fpipe;
1732
    DWORD len;
1733
} WinCharState;
1734

    
1735
#define NSENDBUF 2048
1736
#define NRECVBUF 2048
1737
#define MAXCONNECT 1
1738
#define NTIMEOUT 5000
1739

    
1740
static int win_chr_poll(void *opaque);
1741
static int win_chr_pipe_poll(void *opaque);
1742

    
1743
static void win_chr_close2(WinCharState *s)
1744
{
1745
    if (s->hsend) {
1746
        CloseHandle(s->hsend);
1747
        s->hsend = NULL;
1748
    }
1749
    if (s->hrecv) {
1750
        CloseHandle(s->hrecv);
1751
        s->hrecv = NULL;
1752
    }
1753
    if (s->hcom) {
1754
        CloseHandle(s->hcom);
1755
        s->hcom = NULL;
1756
    }
1757
    if (s->fpipe)
1758
        qemu_del_polling_cb(win_chr_pipe_poll, s);
1759
    else
1760
        qemu_del_polling_cb(win_chr_poll, s);
1761
}
1762

    
1763
static void win_chr_close(CharDriverState *chr)
1764
{
1765
    WinCharState *s = chr->opaque;
1766
    win_chr_close2(s);
1767
}
1768

    
1769
static int win_chr_init(WinCharState *s, const char *filename)
1770
{
1771
    COMMCONFIG comcfg;
1772
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1773
    COMSTAT comstat;
1774
    DWORD size;
1775
    DWORD err;
1776
    
1777
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1778
    if (!s->hsend) {
1779
        fprintf(stderr, "Failed CreateEvent\n");
1780
        goto fail;
1781
    }
1782
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1783
    if (!s->hrecv) {
1784
        fprintf(stderr, "Failed CreateEvent\n");
1785
        goto fail;
1786
    }
1787

    
1788
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1789
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1790
    if (s->hcom == INVALID_HANDLE_VALUE) {
1791
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1792
        s->hcom = NULL;
1793
        goto fail;
1794
    }
1795
    
1796
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1797
        fprintf(stderr, "Failed SetupComm\n");
1798
        goto fail;
1799
    }
1800
    
1801
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1802
    size = sizeof(COMMCONFIG);
1803
    GetDefaultCommConfig(filename, &comcfg, &size);
1804
    comcfg.dcb.DCBlength = sizeof(DCB);
1805
    CommConfigDialog(filename, NULL, &comcfg);
1806

    
1807
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1808
        fprintf(stderr, "Failed SetCommState\n");
1809
        goto fail;
1810
    }
1811

    
1812
    if (!SetCommMask(s->hcom, EV_ERR)) {
1813
        fprintf(stderr, "Failed SetCommMask\n");
1814
        goto fail;
1815
    }
1816

    
1817
    cto.ReadIntervalTimeout = MAXDWORD;
1818
    if (!SetCommTimeouts(s->hcom, &cto)) {
1819
        fprintf(stderr, "Failed SetCommTimeouts\n");
1820
        goto fail;
1821
    }
1822
    
1823
    if (!ClearCommError(s->hcom, &err, &comstat)) {
1824
        fprintf(stderr, "Failed ClearCommError\n");
1825
        goto fail;
1826
    }
1827
    qemu_add_polling_cb(win_chr_poll, s);
1828
    return 0;
1829

    
1830
 fail:
1831
    win_chr_close2(s);
1832
    return -1;
1833
}
1834

    
1835
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1836
{
1837
    WinCharState *s = chr->opaque;
1838
    DWORD len, ret, size, err;
1839

    
1840
    len = len1;
1841
    ZeroMemory(&s->osend, sizeof(s->osend));
1842
    s->osend.hEvent = s->hsend;
1843
    while (len > 0) {
1844
        if (s->hsend)
1845
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1846
        else
1847
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1848
        if (!ret) {
1849
            err = GetLastError();
1850
            if (err == ERROR_IO_PENDING) {
1851
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1852
                if (ret) {
1853
                    buf += size;
1854
                    len -= size;
1855
                } else {
1856
                    break;
1857
                }
1858
            } else {
1859
                break;
1860
            }
1861
        } else {
1862
            buf += size;
1863
            len -= size;
1864
        }
1865
    }
1866
    return len1 - len;
1867
}
1868

    
1869
static int win_chr_read_poll(WinCharState *s)
1870
{
1871
    s->max_size = s->fd_can_read(s->win_opaque);
1872
    return s->max_size;
1873
}
1874
            
1875
static void win_chr_readfile(WinCharState *s)
1876
{
1877
    int ret, err;
1878
    uint8_t buf[1024];
1879
    DWORD size;
1880
    
1881
    ZeroMemory(&s->orecv, sizeof(s->orecv));
1882
    s->orecv.hEvent = s->hrecv;
1883
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1884
    if (!ret) {
1885
        err = GetLastError();
1886
        if (err == ERROR_IO_PENDING) {
1887
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1888
        }
1889
    }
1890

    
1891
    if (size > 0) {
1892
        s->fd_read(s->win_opaque, buf, size);
1893
    }
1894
}
1895

    
1896
static void win_chr_read(WinCharState *s)
1897
{
1898
    if (s->len > s->max_size)
1899
        s->len = s->max_size;
1900
    if (s->len == 0)
1901
        return;
1902
    
1903
    win_chr_readfile(s);
1904
}
1905

    
1906
static int win_chr_poll(void *opaque)
1907
{
1908
    WinCharState *s = opaque;
1909
    COMSTAT status;
1910
    DWORD comerr;
1911
    
1912
    ClearCommError(s->hcom, &comerr, &status);
1913
    if (status.cbInQue > 0) {
1914
        s->len = status.cbInQue;
1915
        win_chr_read_poll(s);
1916
        win_chr_read(s);
1917
        return 1;
1918
    }
1919
    return 0;
1920
}
1921

    
1922
static void win_chr_add_read_handler(CharDriverState *chr, 
1923
                                    IOCanRWHandler *fd_can_read, 
1924
                                    IOReadHandler *fd_read, void *opaque)
1925
{
1926
    WinCharState *s = chr->opaque;
1927

    
1928
    s->fd_can_read = fd_can_read;
1929
    s->fd_read = fd_read;
1930
    s->win_opaque = opaque;
1931
}
1932

    
1933
CharDriverState *qemu_chr_open_win(const char *filename)
1934
{
1935
    CharDriverState *chr;
1936
    WinCharState *s;
1937
    
1938
    chr = qemu_mallocz(sizeof(CharDriverState));
1939
    if (!chr)
1940
        return NULL;
1941
    s = qemu_mallocz(sizeof(WinCharState));
1942
    if (!s) {
1943
        free(chr);
1944
        return NULL;
1945
    }
1946
    chr->opaque = s;
1947
    chr->chr_write = win_chr_write;
1948
    chr->chr_add_read_handler = win_chr_add_read_handler;
1949
    chr->chr_close = win_chr_close;
1950

    
1951
    if (win_chr_init(s, filename) < 0) {
1952
        free(s);
1953
        free(chr);
1954
        return NULL;
1955
    }
1956
    return chr;
1957
}
1958

    
1959
static int win_chr_pipe_poll(void *opaque)
1960
{
1961
    WinCharState *s = opaque;
1962
    DWORD size;
1963

    
1964
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1965
    if (size > 0) {
1966
        s->len = size;
1967
        win_chr_read_poll(s);
1968
        win_chr_read(s);
1969
        return 1;
1970
    }
1971
    return 0;
1972
}
1973

    
1974
static int win_chr_pipe_init(WinCharState *s, const char *filename)
1975
{
1976
    OVERLAPPED ov;
1977
    int ret;
1978
    DWORD size;
1979
    char openname[256];
1980
    
1981
    s->fpipe = TRUE;
1982

    
1983
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1984
    if (!s->hsend) {
1985
        fprintf(stderr, "Failed CreateEvent\n");
1986
        goto fail;
1987
    }
1988
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1989
    if (!s->hrecv) {
1990
        fprintf(stderr, "Failed CreateEvent\n");
1991
        goto fail;
1992
    }
1993
    
1994
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1995
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1996
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1997
                              PIPE_WAIT,
1998
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1999
    if (s->hcom == INVALID_HANDLE_VALUE) {
2000
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2001
        s->hcom = NULL;
2002
        goto fail;
2003
    }
2004

    
2005
    ZeroMemory(&ov, sizeof(ov));
2006
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2007
    ret = ConnectNamedPipe(s->hcom, &ov);
2008
    if (ret) {
2009
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2010
        goto fail;
2011
    }
2012

    
2013
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2014
    if (!ret) {
2015
        fprintf(stderr, "Failed GetOverlappedResult\n");
2016
        if (ov.hEvent) {
2017
            CloseHandle(ov.hEvent);
2018
            ov.hEvent = NULL;
2019
        }
2020
        goto fail;
2021
    }
2022

    
2023
    if (ov.hEvent) {
2024
        CloseHandle(ov.hEvent);
2025
        ov.hEvent = NULL;
2026
    }
2027
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2028
    return 0;
2029

    
2030
 fail:
2031
    win_chr_close2(s);
2032
    return -1;
2033
}
2034

    
2035

    
2036
CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2037
{
2038
    CharDriverState *chr;
2039
    WinCharState *s;
2040

    
2041
    chr = qemu_mallocz(sizeof(CharDriverState));
2042
    if (!chr)
2043
        return NULL;
2044
    s = qemu_mallocz(sizeof(WinCharState));
2045
    if (!s) {
2046
        free(chr);
2047
        return NULL;
2048
    }
2049
    chr->opaque = s;
2050
    chr->chr_write = win_chr_write;
2051
    chr->chr_add_read_handler = win_chr_add_read_handler;
2052
    chr->chr_close = win_chr_close;
2053
    
2054
    if (win_chr_pipe_init(s, filename) < 0) {
2055
        free(s);
2056
        free(chr);
2057
        return NULL;
2058
    }
2059
    return chr;
2060
}
2061

    
2062
CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2063
{
2064
    CharDriverState *chr;
2065
    WinCharState *s;
2066

    
2067
    chr = qemu_mallocz(sizeof(CharDriverState));
2068
    if (!chr)
2069
        return NULL;
2070
    s = qemu_mallocz(sizeof(WinCharState));
2071
    if (!s) {
2072
        free(chr);
2073
        return NULL;
2074
    }
2075
    s->hcom = fd_out;
2076
    chr->opaque = s;
2077
    chr->chr_write = win_chr_write;
2078
    chr->chr_add_read_handler = win_chr_add_read_handler;
2079
    return chr;
2080
}
2081
    
2082
CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2083
{
2084
    HANDLE fd_out;
2085
    
2086
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2087
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2088
    if (fd_out == INVALID_HANDLE_VALUE)
2089
        return NULL;
2090

    
2091
    return qemu_chr_open_win_file(fd_out);
2092
}
2093
#endif
2094

    
2095
CharDriverState *qemu_chr_open(const char *filename)
2096
{
2097
    const char *p;
2098

    
2099
    if (!strcmp(filename, "vc")) {
2100
        return text_console_init(&display_state);
2101
    } else if (!strcmp(filename, "null")) {
2102
        return qemu_chr_open_null();
2103
    } else 
2104
#ifndef _WIN32
2105
    if (strstart(filename, "file:", &p)) {
2106
        return qemu_chr_open_file_out(p);
2107
    } else if (strstart(filename, "pipe:", &p)) {
2108
        return qemu_chr_open_pipe(p);
2109
    } else if (!strcmp(filename, "pty")) {
2110
        return qemu_chr_open_pty();
2111
    } else if (!strcmp(filename, "stdio")) {
2112
        return qemu_chr_open_stdio();
2113
    } else 
2114
#endif
2115
#if defined(__linux__)
2116
    if (strstart(filename, "/dev/parport", NULL)) {
2117
        return qemu_chr_open_pp(filename);
2118
    } else 
2119
    if (strstart(filename, "/dev/", NULL)) {
2120
        return qemu_chr_open_tty(filename);
2121
    } else 
2122
#endif
2123
#ifdef _WIN32
2124
    if (strstart(filename, "COM", NULL)) {
2125
        return qemu_chr_open_win(filename);
2126
    } else
2127
    if (strstart(filename, "pipe:", &p)) {
2128
        return qemu_chr_open_win_pipe(p);
2129
    } else
2130
    if (strstart(filename, "file:", &p)) {
2131
        return qemu_chr_open_win_file_out(p);
2132
    }
2133
#endif
2134
    {
2135
        return NULL;
2136
    }
2137
}
2138

    
2139
void qemu_chr_close(CharDriverState *chr)
2140
{
2141
    if (chr->chr_close)
2142
        chr->chr_close(chr);
2143
}
2144

    
2145
/***********************************************************/
2146
/* network device redirectors */
2147

    
2148
void hex_dump(FILE *f, const uint8_t *buf, int size)
2149
{
2150
    int len, i, j, c;
2151

    
2152
    for(i=0;i<size;i+=16) {
2153
        len = size - i;
2154
        if (len > 16)
2155
            len = 16;
2156
        fprintf(f, "%08x ", i);
2157
        for(j=0;j<16;j++) {
2158
            if (j < len)
2159
                fprintf(f, " %02x", buf[i+j]);
2160
            else
2161
                fprintf(f, "   ");
2162
        }
2163
        fprintf(f, " ");
2164
        for(j=0;j<len;j++) {
2165
            c = buf[i+j];
2166
            if (c < ' ' || c > '~')
2167
                c = '.';
2168
            fprintf(f, "%c", c);
2169
        }
2170
        fprintf(f, "\n");
2171
    }
2172
}
2173

    
2174
static int parse_macaddr(uint8_t *macaddr, const char *p)
2175
{
2176
    int i;
2177
    for(i = 0; i < 6; i++) {
2178
        macaddr[i] = strtol(p, (char **)&p, 16);
2179
        if (i == 5) {
2180
            if (*p != '\0') 
2181
                return -1;
2182
        } else {
2183
            if (*p != ':') 
2184
                return -1;
2185
            p++;
2186
        }
2187
    }
2188
    return 0;
2189
}
2190

    
2191
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2192
{
2193
    const char *p, *p1;
2194
    int len;
2195
    p = *pp;
2196
    p1 = strchr(p, sep);
2197
    if (!p1)
2198
        return -1;
2199
    len = p1 - p;
2200
    p1++;
2201
    if (buf_size > 0) {
2202
        if (len > buf_size - 1)
2203
            len = buf_size - 1;
2204
        memcpy(buf, p, len);
2205
        buf[len] = '\0';
2206
    }
2207
    *pp = p1;
2208
    return 0;
2209
}
2210

    
2211
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2212
{
2213
    char buf[512];
2214
    struct hostent *he;
2215
    const char *p, *r;
2216
    int port;
2217

    
2218
    p = str;
2219
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2220
        return -1;
2221
    saddr->sin_family = AF_INET;
2222
    if (buf[0] == '\0') {
2223
        saddr->sin_addr.s_addr = 0;
2224
    } else {
2225
        if (isdigit(buf[0])) {
2226
            if (!inet_aton(buf, &saddr->sin_addr))
2227
                return -1;
2228
        } else {
2229
            if ((he = gethostbyname(buf)) == NULL)
2230
                return - 1;
2231
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2232
        }
2233
    }
2234
    port = strtol(p, (char **)&r, 0);
2235
    if (r == p)
2236
        return -1;
2237
    saddr->sin_port = htons(port);
2238
    return 0;
2239
}
2240

    
2241
/* find or alloc a new VLAN */
2242
VLANState *qemu_find_vlan(int id)
2243
{
2244
    VLANState **pvlan, *vlan;
2245
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2246
        if (vlan->id == id)
2247
            return vlan;
2248
    }
2249
    vlan = qemu_mallocz(sizeof(VLANState));
2250
    if (!vlan)
2251
        return NULL;
2252
    vlan->id = id;
2253
    vlan->next = NULL;
2254
    pvlan = &first_vlan;
2255
    while (*pvlan != NULL)
2256
        pvlan = &(*pvlan)->next;
2257
    *pvlan = vlan;
2258
    return vlan;
2259
}
2260

    
2261
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2262
                                      IOReadHandler *fd_read,
2263
                                      IOCanRWHandler *fd_can_read,
2264
                                      void *opaque)
2265
{
2266
    VLANClientState *vc, **pvc;
2267
    vc = qemu_mallocz(sizeof(VLANClientState));
2268
    if (!vc)
2269
        return NULL;
2270
    vc->fd_read = fd_read;
2271
    vc->fd_can_read = fd_can_read;
2272
    vc->opaque = opaque;
2273
    vc->vlan = vlan;
2274

    
2275
    vc->next = NULL;
2276
    pvc = &vlan->first_client;
2277
    while (*pvc != NULL)
2278
        pvc = &(*pvc)->next;
2279
    *pvc = vc;
2280
    return vc;
2281
}
2282

    
2283
int qemu_can_send_packet(VLANClientState *vc1)
2284
{
2285
    VLANState *vlan = vc1->vlan;
2286
    VLANClientState *vc;
2287

    
2288
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2289
        if (vc != vc1) {
2290
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2291
                return 0;
2292
        }
2293
    }
2294
    return 1;
2295
}
2296

    
2297
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2298
{
2299
    VLANState *vlan = vc1->vlan;
2300
    VLANClientState *vc;
2301

    
2302
#if 0
2303
    printf("vlan %d send:\n", vlan->id);
2304
    hex_dump(stdout, buf, size);
2305
#endif
2306
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2307
        if (vc != vc1) {
2308
            vc->fd_read(vc->opaque, buf, size);
2309
        }
2310
    }
2311
}
2312

    
2313
#if defined(CONFIG_SLIRP)
2314

    
2315
/* slirp network adapter */
2316

    
2317
static int slirp_inited;
2318
static VLANClientState *slirp_vc;
2319

    
2320
int slirp_can_output(void)
2321
{
2322
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
2323
}
2324

    
2325
void slirp_output(const uint8_t *pkt, int pkt_len)
2326
{
2327
#if 0
2328
    printf("slirp output:\n");
2329
    hex_dump(stdout, pkt, pkt_len);
2330
#endif
2331
    if (!slirp_vc)
2332
        return;
2333
    qemu_send_packet(slirp_vc, pkt, pkt_len);
2334
}
2335

    
2336
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2337
{
2338
#if 0
2339
    printf("slirp input:\n");
2340
    hex_dump(stdout, buf, size);
2341
#endif
2342
    slirp_input(buf, size);
2343
}
2344

    
2345
static int net_slirp_init(VLANState *vlan)
2346
{
2347
    if (!slirp_inited) {
2348
        slirp_inited = 1;
2349
        slirp_init();
2350
    }
2351
    slirp_vc = qemu_new_vlan_client(vlan, 
2352
                                    slirp_receive, NULL, NULL);
2353
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2354
    return 0;
2355
}
2356

    
2357
static void net_slirp_redir(const char *redir_str)
2358
{
2359
    int is_udp;
2360
    char buf[256], *r;
2361
    const char *p;
2362
    struct in_addr guest_addr;
2363
    int host_port, guest_port;
2364
    
2365
    if (!slirp_inited) {
2366
        slirp_inited = 1;
2367
        slirp_init();
2368
    }
2369

    
2370
    p = redir_str;
2371
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2372
        goto fail;
2373
    if (!strcmp(buf, "tcp")) {
2374
        is_udp = 0;
2375
    } else if (!strcmp(buf, "udp")) {
2376
        is_udp = 1;
2377
    } else {
2378
        goto fail;
2379
    }
2380

    
2381
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2382
        goto fail;
2383
    host_port = strtol(buf, &r, 0);
2384
    if (r == buf)
2385
        goto fail;
2386

    
2387
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2388
        goto fail;
2389
    if (buf[0] == '\0') {
2390
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
2391
    }
2392
    if (!inet_aton(buf, &guest_addr))
2393
        goto fail;
2394
    
2395
    guest_port = strtol(p, &r, 0);
2396
    if (r == p)
2397
        goto fail;
2398
    
2399
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2400
        fprintf(stderr, "qemu: could not set up redirection\n");
2401
        exit(1);
2402
    }
2403
    return;
2404
 fail:
2405
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2406
    exit(1);
2407
}
2408
    
2409
#ifndef _WIN32
2410

    
2411
char smb_dir[1024];
2412

    
2413
static void smb_exit(void)
2414
{
2415
    DIR *d;
2416
    struct dirent *de;
2417
    char filename[1024];
2418

    
2419
    /* erase all the files in the directory */
2420
    d = opendir(smb_dir);
2421
    for(;;) {
2422
        de = readdir(d);
2423
        if (!de)
2424
            break;
2425
        if (strcmp(de->d_name, ".") != 0 &&
2426
            strcmp(de->d_name, "..") != 0) {
2427
            snprintf(filename, sizeof(filename), "%s/%s", 
2428
                     smb_dir, de->d_name);
2429
            unlink(filename);
2430
        }
2431
    }
2432
    closedir(d);
2433
    rmdir(smb_dir);
2434
}
2435

    
2436
/* automatic user mode samba server configuration */
2437
void net_slirp_smb(const char *exported_dir)
2438
{
2439
    char smb_conf[1024];
2440
    char smb_cmdline[1024];
2441
    FILE *f;
2442

    
2443
    if (!slirp_inited) {
2444
        slirp_inited = 1;
2445
        slirp_init();
2446
    }
2447

    
2448
    /* XXX: better tmp dir construction */
2449
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2450
    if (mkdir(smb_dir, 0700) < 0) {
2451
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2452
        exit(1);
2453
    }
2454
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2455
    
2456
    f = fopen(smb_conf, "w");
2457
    if (!f) {
2458
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2459
        exit(1);
2460
    }
2461
    fprintf(f, 
2462
            "[global]\n"
2463
            "private dir=%s\n"
2464
            "smb ports=0\n"
2465
            "socket address=127.0.0.1\n"
2466
            "pid directory=%s\n"
2467
            "lock directory=%s\n"
2468
            "log file=%s/log.smbd\n"
2469
            "smb passwd file=%s/smbpasswd\n"
2470
            "security = share\n"
2471
            "[qemu]\n"
2472
            "path=%s\n"
2473
            "read only=no\n"
2474
            "guest ok=yes\n",
2475
            smb_dir,
2476
            smb_dir,
2477
            smb_dir,
2478
            smb_dir,
2479
            smb_dir,
2480
            exported_dir
2481
            );
2482
    fclose(f);
2483
    atexit(smb_exit);
2484

    
2485
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2486
             smb_conf);
2487
    
2488
    slirp_add_exec(0, smb_cmdline, 4, 139);
2489
}
2490

    
2491
#endif /* !defined(_WIN32) */
2492

    
2493
#endif /* CONFIG_SLIRP */
2494

    
2495
#if !defined(_WIN32)
2496

    
2497
typedef struct TAPState {
2498
    VLANClientState *vc;
2499
    int fd;
2500
} TAPState;
2501

    
2502
static void tap_receive(void *opaque, const uint8_t *buf, int size)
2503
{
2504
    TAPState *s = opaque;
2505
    int ret;
2506
    for(;;) {
2507
        ret = write(s->fd, buf, size);
2508
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2509
        } else {
2510
            break;
2511
        }
2512
    }
2513
}
2514

    
2515
static void tap_send(void *opaque)
2516
{
2517
    TAPState *s = opaque;
2518
    uint8_t buf[4096];
2519
    int size;
2520

    
2521
    size = read(s->fd, buf, sizeof(buf));
2522
    if (size > 0) {
2523
        qemu_send_packet(s->vc, buf, size);
2524
    }
2525
}
2526

    
2527
/* fd support */
2528

    
2529
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2530
{
2531
    TAPState *s;
2532

    
2533
    s = qemu_mallocz(sizeof(TAPState));
2534
    if (!s)
2535
        return NULL;
2536
    s->fd = fd;
2537
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2538
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2539
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2540
    return s;
2541
}
2542

    
2543
#ifdef _BSD
2544
static int tap_open(char *ifname, int ifname_size)
2545
{
2546
    int fd;
2547
    char *dev;
2548
    struct stat s;
2549

    
2550
    fd = open("/dev/tap", O_RDWR);
2551
    if (fd < 0) {
2552
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2553
        return -1;
2554
    }
2555

    
2556
    fstat(fd, &s);
2557
    dev = devname(s.st_rdev, S_IFCHR);
2558
    pstrcpy(ifname, ifname_size, dev);
2559

    
2560
    fcntl(fd, F_SETFL, O_NONBLOCK);
2561
    return fd;
2562
}
2563
#else
2564
static int tap_open(char *ifname, int ifname_size)
2565
{
2566
    struct ifreq ifr;
2567
    int fd, ret;
2568
    
2569
    fd = open("/dev/net/tun", O_RDWR);
2570
    if (fd < 0) {
2571
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2572
        return -1;
2573
    }
2574
    memset(&ifr, 0, sizeof(ifr));
2575
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2576
    if (ifname[0] != '\0')
2577
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2578
    else
2579
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2580
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2581
    if (ret != 0) {
2582
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2583
        close(fd);
2584
        return -1;
2585
    }
2586
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
2587
    fcntl(fd, F_SETFL, O_NONBLOCK);
2588
    return fd;
2589
}
2590
#endif
2591

    
2592
static int net_tap_init(VLANState *vlan, const char *ifname1,
2593
                        const char *setup_script)
2594
{
2595
    TAPState *s;
2596
    int pid, status, fd;
2597
    char *args[3];
2598
    char **parg;
2599
    char ifname[128];
2600

    
2601
    if (ifname1 != NULL)
2602
        pstrcpy(ifname, sizeof(ifname), ifname1);
2603
    else
2604
        ifname[0] = '\0';
2605
    fd = tap_open(ifname, sizeof(ifname));
2606
    if (fd < 0)
2607
        return -1;
2608

    
2609
    if (!setup_script)
2610
        setup_script = "";
2611
    if (setup_script[0] != '\0') {
2612
        /* try to launch network init script */
2613
        pid = fork();
2614
        if (pid >= 0) {
2615
            if (pid == 0) {
2616
                parg = args;
2617
                *parg++ = (char *)setup_script;
2618
                *parg++ = ifname;
2619
                *parg++ = NULL;
2620
                execv(setup_script, args);
2621
                _exit(1);
2622
            }
2623
            while (waitpid(pid, &status, 0) != pid);
2624
            if (!WIFEXITED(status) ||
2625
                WEXITSTATUS(status) != 0) {
2626
                fprintf(stderr, "%s: could not launch network script\n",
2627
                        setup_script);
2628
                return -1;
2629
            }
2630
        }
2631
    }
2632
    s = net_tap_fd_init(vlan, fd);
2633
    if (!s)
2634
        return -1;
2635
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
2636
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
2637
    return 0;
2638
}
2639

    
2640
#endif /* !_WIN32 */
2641

    
2642
/* network connection */
2643
typedef struct NetSocketState {
2644
    VLANClientState *vc;
2645
    int fd;
2646
    int state; /* 0 = getting length, 1 = getting data */
2647
    int index;
2648
    int packet_len;
2649
    uint8_t buf[4096];
2650
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2651
} NetSocketState;
2652

    
2653
typedef struct NetSocketListenState {
2654
    VLANState *vlan;
2655
    int fd;
2656
} NetSocketListenState;
2657

    
2658
/* XXX: we consider we can send the whole packet without blocking */
2659
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2660
{
2661
    NetSocketState *s = opaque;
2662
    uint32_t len;
2663
    len = htonl(size);
2664

    
2665
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2666
    send_all(s->fd, buf, size);
2667
}
2668

    
2669
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2670
{
2671
    NetSocketState *s = opaque;
2672
    sendto(s->fd, buf, size, 0, 
2673
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2674
}
2675

    
2676
static void net_socket_send(void *opaque)
2677
{
2678
    NetSocketState *s = opaque;
2679
    int l, size, err;
2680
    uint8_t buf1[4096];
2681
    const uint8_t *buf;
2682

    
2683
    size = recv(s->fd, buf1, sizeof(buf1), 0);
2684
    if (size < 0) {
2685
        err = socket_error();
2686
        if (err != EWOULDBLOCK) 
2687
            goto eoc;
2688
    } else if (size == 0) {
2689
        /* end of connection */
2690
    eoc:
2691
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2692
        closesocket(s->fd);
2693
        return;
2694
    }
2695
    buf = buf1;
2696
    while (size > 0) {
2697
        /* reassemble a packet from the network */
2698
        switch(s->state) {
2699
        case 0:
2700
            l = 4 - s->index;
2701
            if (l > size)
2702
                l = size;
2703
            memcpy(s->buf + s->index, buf, l);
2704
            buf += l;
2705
            size -= l;
2706
            s->index += l;
2707
            if (s->index == 4) {
2708
                /* got length */
2709
                s->packet_len = ntohl(*(uint32_t *)s->buf);
2710
                s->index = 0;
2711
                s->state = 1;
2712
            }
2713
            break;
2714
        case 1:
2715
            l = s->packet_len - s->index;
2716
            if (l > size)
2717
                l = size;
2718
            memcpy(s->buf + s->index, buf, l);
2719
            s->index += l;
2720
            buf += l;
2721
            size -= l;
2722
            if (s->index >= s->packet_len) {
2723
                qemu_send_packet(s->vc, s->buf, s->packet_len);
2724
                s->index = 0;
2725
                s->state = 0;
2726
            }
2727
            break;
2728
        }
2729
    }
2730
}
2731

    
2732
static void net_socket_send_dgram(void *opaque)
2733
{
2734
    NetSocketState *s = opaque;
2735
    int size;
2736

    
2737
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2738
    if (size < 0) 
2739
        return;
2740
    if (size == 0) {
2741
        /* end of connection */
2742
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2743
        return;
2744
    }
2745
    qemu_send_packet(s->vc, s->buf, size);
2746
}
2747

    
2748
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2749
{
2750
    struct ip_mreq imr;
2751
    int fd;
2752
    int val, ret;
2753
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2754
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2755
                inet_ntoa(mcastaddr->sin_addr), 
2756
                (int)ntohl(mcastaddr->sin_addr.s_addr));
2757
        return -1;
2758

    
2759
    }
2760
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2761
    if (fd < 0) {
2762
        perror("socket(PF_INET, SOCK_DGRAM)");
2763
        return -1;
2764
    }
2765

    
2766
    val = 1;
2767
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
2768
                   (const char *)&val, sizeof(val));
2769
    if (ret < 0) {
2770
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2771
        goto fail;
2772
    }
2773

    
2774
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2775
    if (ret < 0) {
2776
        perror("bind");
2777
        goto fail;
2778
    }
2779
    
2780
    /* Add host to multicast group */
2781
    imr.imr_multiaddr = mcastaddr->sin_addr;
2782
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
2783

    
2784
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
2785
                     (const char *)&imr, sizeof(struct ip_mreq));
2786
    if (ret < 0) {
2787
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
2788
        goto fail;
2789
    }
2790

    
2791
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2792
    val = 1;
2793
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
2794
                   (const char *)&val, sizeof(val));
2795
    if (ret < 0) {
2796
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2797
        goto fail;
2798
    }
2799

    
2800
    socket_set_nonblock(fd);
2801
    return fd;
2802
fail:
2803
    if (fd>=0) close(fd);
2804
    return -1;
2805
}
2806

    
2807
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
2808
                                          int is_connected)
2809
{
2810
    struct sockaddr_in saddr;
2811
    int newfd;
2812
    socklen_t saddr_len;
2813
    NetSocketState *s;
2814

    
2815
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2816
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
2817
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
2818
     */
2819

    
2820
    if (is_connected) {
2821
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2822
            /* must be bound */
2823
            if (saddr.sin_addr.s_addr==0) {
2824
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2825
                        fd);
2826
                return NULL;
2827
            }
2828
            /* clone dgram socket */
2829
            newfd = net_socket_mcast_create(&saddr);
2830
            if (newfd < 0) {
2831
                /* error already reported by net_socket_mcast_create() */
2832
                close(fd);
2833
                return NULL;
2834
            }
2835
            /* clone newfd to fd, close newfd */
2836
            dup2(newfd, fd);
2837
            close(newfd);
2838
        
2839
        } else {
2840
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2841
                    fd, strerror(errno));
2842
            return NULL;
2843
        }
2844
    }
2845

    
2846
    s = qemu_mallocz(sizeof(NetSocketState));
2847
    if (!s)
2848
        return NULL;
2849
    s->fd = fd;
2850

    
2851
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2852
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2853

    
2854
    /* mcast: save bound address as dst */
2855
    if (is_connected) s->dgram_dst=saddr;
2856

    
2857
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2858
            "socket: fd=%d (%s mcast=%s:%d)", 
2859
            fd, is_connected? "cloned" : "",
2860
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2861
    return s;
2862
}
2863

    
2864
static void net_socket_connect(void *opaque)
2865
{
2866
    NetSocketState *s = opaque;
2867
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2868
}
2869

    
2870
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
2871
                                          int is_connected)
2872
{
2873
    NetSocketState *s;
2874
    s = qemu_mallocz(sizeof(NetSocketState));
2875
    if (!s)
2876
        return NULL;
2877
    s->fd = fd;
2878
    s->vc = qemu_new_vlan_client(vlan, 
2879
                                 net_socket_receive, NULL, s);
2880
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2881
             "socket: fd=%d", fd);
2882
    if (is_connected) {
2883
        net_socket_connect(s);
2884
    } else {
2885
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2886
    }
2887
    return s;
2888
}
2889

    
2890
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
2891
                                          int is_connected)
2892
{
2893
    int so_type=-1, optlen=sizeof(so_type);
2894

    
2895
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2896
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2897
        return NULL;
2898
    }
2899
    switch(so_type) {
2900
    case SOCK_DGRAM:
2901
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
2902
    case SOCK_STREAM:
2903
        return net_socket_fd_init_stream(vlan, fd, is_connected);
2904
    default:
2905
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2906
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2907
        return net_socket_fd_init_stream(vlan, fd, is_connected);
2908
    }
2909
    return NULL;
2910
}
2911

    
2912
static void net_socket_accept(void *opaque)
2913
{
2914
    NetSocketListenState *s = opaque;    
2915
    NetSocketState *s1;
2916
    struct sockaddr_in saddr;
2917
    socklen_t len;
2918
    int fd;
2919

    
2920
    for(;;) {
2921
        len = sizeof(saddr);
2922
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2923
        if (fd < 0 && errno != EINTR) {
2924
            return;
2925
        } else if (fd >= 0) {
2926
            break;
2927
        }
2928
    }
2929
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
2930
    if (!s1) {
2931
        close(fd);
2932
    } else {
2933
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2934
                 "socket: connection from %s:%d", 
2935
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2936
    }
2937
}
2938

    
2939
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2940
{
2941
    NetSocketListenState *s;
2942
    int fd, val, ret;
2943
    struct sockaddr_in saddr;
2944

    
2945
    if (parse_host_port(&saddr, host_str) < 0)
2946
        return -1;
2947
    
2948
    s = qemu_mallocz(sizeof(NetSocketListenState));
2949
    if (!s)
2950
        return -1;
2951

    
2952
    fd = socket(PF_INET, SOCK_STREAM, 0);
2953
    if (fd < 0) {
2954
        perror("socket");
2955
        return -1;
2956
    }
2957
    socket_set_nonblock(fd);
2958

    
2959
    /* allow fast reuse */
2960
    val = 1;
2961
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2962
    
2963
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2964
    if (ret < 0) {
2965
        perror("bind");
2966
        return -1;
2967
    }
2968
    ret = listen(fd, 0);
2969
    if (ret < 0) {
2970
        perror("listen");
2971
        return -1;
2972
    }
2973
    s->vlan = vlan;
2974
    s->fd = fd;
2975
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2976
    return 0;
2977
}
2978

    
2979
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2980
{
2981
    NetSocketState *s;
2982
    int fd, connected, ret, err;
2983
    struct sockaddr_in saddr;
2984

    
2985
    if (parse_host_port(&saddr, host_str) < 0)
2986
        return -1;
2987

    
2988
    fd = socket(PF_INET, SOCK_STREAM, 0);
2989
    if (fd < 0) {
2990
        perror("socket");
2991
        return -1;
2992
    }
2993
    socket_set_nonblock(fd);
2994

    
2995
    connected = 0;
2996
    for(;;) {
2997
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2998
        if (ret < 0) {
2999
            err = socket_error();
3000
            if (err == EINTR || err == EWOULDBLOCK) {
3001
            } else if (err == EINPROGRESS) {
3002
                break;
3003
            } else {
3004
                perror("connect");
3005
                closesocket(fd);
3006
                return -1;
3007
            }
3008
        } else {
3009
            connected = 1;
3010
            break;
3011
        }
3012
    }
3013
    s = net_socket_fd_init(vlan, fd, connected);
3014
    if (!s)
3015
        return -1;
3016
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3017
             "socket: connect to %s:%d", 
3018
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3019
    return 0;
3020
}
3021

    
3022
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3023
{
3024
    NetSocketState *s;
3025
    int fd;
3026
    struct sockaddr_in saddr;
3027

    
3028
    if (parse_host_port(&saddr, host_str) < 0)
3029
        return -1;
3030

    
3031

    
3032
    fd = net_socket_mcast_create(&saddr);
3033
    if (fd < 0)
3034
        return -1;
3035

    
3036
    s = net_socket_fd_init(vlan, fd, 0);
3037
    if (!s)
3038
        return -1;
3039

    
3040
    s->dgram_dst = saddr;
3041
    
3042
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3043
             "socket: mcast=%s:%d", 
3044
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3045
    return 0;
3046

    
3047
}
3048

    
3049
static int get_param_value(char *buf, int buf_size,
3050
                           const char *tag, const char *str)
3051
{
3052
    const char *p;
3053
    char *q;
3054
    char option[128];
3055

    
3056
    p = str;
3057
    for(;;) {
3058
        q = option;
3059
        while (*p != '\0' && *p != '=') {
3060
            if ((q - option) < sizeof(option) - 1)
3061
                *q++ = *p;
3062
            p++;
3063
        }
3064
        *q = '\0';
3065
        if (*p != '=')
3066
            break;
3067
        p++;
3068
        if (!strcmp(tag, option)) {
3069
            q = buf;
3070
            while (*p != '\0' && *p != ',') {
3071
                if ((q - buf) < buf_size - 1)
3072
                    *q++ = *p;
3073
                p++;
3074
            }
3075
            *q = '\0';
3076
            return q - buf;
3077
        } else {
3078
            while (*p != '\0' && *p != ',') {
3079
                p++;
3080
            }
3081
        }
3082
        if (*p != ',')
3083
            break;
3084
        p++;
3085
    }
3086
    return 0;
3087
}
3088

    
3089
int net_client_init(const char *str)
3090
{
3091
    const char *p;
3092
    char *q;
3093
    char device[64];
3094
    char buf[1024];
3095
    int vlan_id, ret;
3096
    VLANState *vlan;
3097

    
3098
    p = str;
3099
    q = device;
3100
    while (*p != '\0' && *p != ',') {
3101
        if ((q - device) < sizeof(device) - 1)
3102
            *q++ = *p;
3103
        p++;
3104
    }
3105
    *q = '\0';
3106
    if (*p == ',')
3107
        p++;
3108
    vlan_id = 0;
3109
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3110
        vlan_id = strtol(buf, NULL, 0);
3111
    }
3112
    vlan = qemu_find_vlan(vlan_id);
3113
    if (!vlan) {
3114
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3115
        return -1;
3116
    }
3117
    if (!strcmp(device, "nic")) {
3118
        NICInfo *nd;
3119
        uint8_t *macaddr;
3120

    
3121
        if (nb_nics >= MAX_NICS) {
3122
            fprintf(stderr, "Too Many NICs\n");
3123
            return -1;
3124
        }
3125
        nd = &nd_table[nb_nics];
3126
        macaddr = nd->macaddr;
3127
        macaddr[0] = 0x52;
3128
        macaddr[1] = 0x54;
3129
        macaddr[2] = 0x00;
3130
        macaddr[3] = 0x12;
3131
        macaddr[4] = 0x34;
3132
        macaddr[5] = 0x56 + nb_nics;
3133

    
3134
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3135
            if (parse_macaddr(macaddr, buf) < 0) {
3136
                fprintf(stderr, "invalid syntax for ethernet address\n");
3137
                return -1;
3138
            }
3139
        }
3140
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3141
            nd->model = strdup(buf);
3142
        }
3143
        nd->vlan = vlan;
3144
        nb_nics++;
3145
        ret = 0;
3146
    } else
3147
    if (!strcmp(device, "none")) {
3148
        /* does nothing. It is needed to signal that no network cards
3149
           are wanted */
3150
        ret = 0;
3151
    } else
3152
#ifdef CONFIG_SLIRP
3153
    if (!strcmp(device, "user")) {
3154
        ret = net_slirp_init(vlan);
3155
    } else
3156
#endif
3157
#ifdef _WIN32
3158
    if (!strcmp(device, "tap")) {
3159
        char ifname[64];
3160
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3161
            fprintf(stderr, "tap: no interface name\n");
3162
            return -1;
3163
        }
3164
        ret = tap_win32_init(vlan, ifname);
3165
    } else
3166
#else
3167
    if (!strcmp(device, "tap")) {
3168
        char ifname[64];
3169
        char setup_script[1024];
3170
        int fd;
3171
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3172
            fd = strtol(buf, NULL, 0);
3173
            ret = -1;
3174
            if (net_tap_fd_init(vlan, fd))
3175
                ret = 0;
3176
        } else {
3177
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3178
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3179
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3180
            }
3181
            ret = net_tap_init(vlan, ifname, setup_script);
3182
        }
3183
    } else
3184
#endif
3185
    if (!strcmp(device, "socket")) {
3186
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3187
            int fd;
3188
            fd = strtol(buf, NULL, 0);
3189
            ret = -1;
3190
            if (net_socket_fd_init(vlan, fd, 1))
3191
                ret = 0;
3192
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3193
            ret = net_socket_listen_init(vlan, buf);
3194
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3195
            ret = net_socket_connect_init(vlan, buf);
3196
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3197
            ret = net_socket_mcast_init(vlan, buf);
3198
        } else {
3199
            fprintf(stderr, "Unknown socket options: %s\n", p);
3200
            return -1;
3201
        }
3202
    } else
3203
    {
3204
        fprintf(stderr, "Unknown network device: %s\n", device);
3205
        return -1;
3206
    }
3207
    if (ret < 0) {
3208
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3209
    }
3210
    
3211
    return ret;
3212
}
3213

    
3214
void do_info_network(void)
3215
{
3216
    VLANState *vlan;
3217
    VLANClientState *vc;
3218

    
3219
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3220
        term_printf("VLAN %d devices:\n", vlan->id);
3221
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3222
            term_printf("  %s\n", vc->info_str);
3223
    }
3224
}
3225
 
3226
/***********************************************************/
3227
/* USB devices */
3228

    
3229
static int usb_device_add(const char *devname)
3230
{
3231
    const char *p;
3232
    USBDevice *dev;
3233
    int i;
3234

    
3235
    if (!vm_usb_hub)
3236
        return -1;
3237
    for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3238
        if (!vm_usb_ports[i]->dev)
3239
            break;
3240
    }
3241
    if (i == MAX_VM_USB_PORTS)
3242
        return -1;
3243

    
3244
    if (strstart(devname, "host:", &p)) {
3245
        dev = usb_host_device_open(p);
3246
        if (!dev)
3247
            return -1;
3248
    } else if (!strcmp(devname, "mouse")) {
3249
        dev = usb_mouse_init();
3250
        if (!dev)
3251
            return -1;
3252
    } else if (!strcmp(devname, "tablet")) {
3253
        dev = usb_tablet_init();
3254
        if (!dev)
3255
            return -1;
3256
    } else {
3257
        return -1;
3258
    }
3259
    usb_attach(vm_usb_ports[i], dev);
3260
    return 0;
3261
}
3262

    
3263
static int usb_device_del(const char *devname)
3264
{
3265
    USBDevice *dev;
3266
    int bus_num, addr, i;
3267
    const char *p;
3268

    
3269
    if (!vm_usb_hub)
3270
        return -1;
3271

    
3272
    p = strchr(devname, '.');
3273
    if (!p) 
3274
        return -1;
3275
    bus_num = strtoul(devname, NULL, 0);
3276
    addr = strtoul(p + 1, NULL, 0);
3277
    if (bus_num != 0)
3278
        return -1;
3279
    for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3280
        dev = vm_usb_ports[i]->dev;
3281
        if (dev && dev->addr == addr)
3282
            break;
3283
    }
3284
    if (i == MAX_VM_USB_PORTS)
3285
        return -1;
3286
    usb_attach(vm_usb_ports[i], NULL);
3287
    return 0;
3288
}
3289

    
3290
void do_usb_add(const char *devname)
3291
{
3292
    int ret;
3293
    ret = usb_device_add(devname);
3294
    if (ret < 0) 
3295
        term_printf("Could not add USB device '%s'\n", devname);
3296
}
3297

    
3298
void do_usb_del(const char *devname)
3299
{
3300
    int ret;
3301
    ret = usb_device_del(devname);
3302
    if (ret < 0) 
3303
        term_printf("Could not remove USB device '%s'\n", devname);
3304
}
3305

    
3306
void usb_info(void)
3307
{
3308
    USBDevice *dev;
3309
    int i;
3310
    const char *speed_str;
3311

    
3312
    if (!vm_usb_hub) {
3313
        term_printf("USB support not enabled\n");
3314
        return;
3315
    }
3316

    
3317
    for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3318
        dev = vm_usb_ports[i]->dev;
3319
        if (dev) {
3320
            term_printf("Hub port %d:\n", i);
3321
            switch(dev->speed) {
3322
            case USB_SPEED_LOW: 
3323
                speed_str = "1.5"; 
3324
                break;
3325
            case USB_SPEED_FULL: 
3326
                speed_str = "12"; 
3327
                break;
3328
            case USB_SPEED_HIGH: 
3329
                speed_str = "480"; 
3330
                break;
3331
            default:
3332
                speed_str = "?"; 
3333
                break;
3334
            }
3335
            term_printf("  Device %d.%d, speed %s Mb/s\n", 
3336
                        0, dev->addr, speed_str);
3337
        }
3338
    }
3339
}
3340

    
3341
/***********************************************************/
3342
/* pid file */
3343

    
3344
static char *pid_filename;
3345

    
3346
/* Remove PID file. Called on normal exit */
3347

    
3348
static void remove_pidfile(void) 
3349
{
3350
    unlink (pid_filename);
3351
}
3352

    
3353
static void create_pidfile(const char *filename)
3354
{
3355
    struct stat pidstat;
3356
    FILE *f;
3357

    
3358
    /* Try to write our PID to the named file */
3359
    if (stat(filename, &pidstat) < 0) {
3360
        if (errno == ENOENT) {
3361
            if ((f = fopen (filename, "w")) == NULL) {
3362
                perror("Opening pidfile");
3363
                exit(1);
3364
            }
3365
            fprintf(f, "%d\n", getpid());
3366
            fclose(f);
3367
            pid_filename = qemu_strdup(filename);
3368
            if (!pid_filename) {
3369
                fprintf(stderr, "Could not save PID filename");
3370
                exit(1);
3371
            }
3372
            atexit(remove_pidfile);
3373
        }
3374
    } else {
3375
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
3376
                filename);
3377
        exit(1);
3378
    }
3379
}
3380

    
3381
/***********************************************************/
3382
/* dumb display */
3383

    
3384
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3385
{
3386
}
3387

    
3388
static void dumb_resize(DisplayState *ds, int w, int h)
3389
{
3390
}
3391

    
3392
static void dumb_refresh(DisplayState *ds)
3393
{
3394
    vga_hw_update();
3395
}
3396

    
3397
void dumb_display_init(DisplayState *ds)
3398
{
3399
    ds->data = NULL;
3400
    ds->linesize = 0;
3401
    ds->depth = 0;
3402
    ds->dpy_update = dumb_update;
3403
    ds->dpy_resize = dumb_resize;
3404
    ds->dpy_refresh = dumb_refresh;
3405
}
3406

    
3407
#if !defined(CONFIG_SOFTMMU)
3408
/***********************************************************/
3409
/* cpu signal handler */
3410
static void host_segv_handler(int host_signum, siginfo_t *info, 
3411
                              void *puc)
3412
{
3413
    if (cpu_signal_handler(host_signum, info, puc))
3414
        return;
3415
    if (stdio_nb_clients > 0)
3416
        term_exit();
3417
    abort();
3418
}
3419
#endif
3420

    
3421
/***********************************************************/
3422
/* I/O handling */
3423

    
3424
#define MAX_IO_HANDLERS 64
3425

    
3426
typedef struct IOHandlerRecord {
3427
    int fd;
3428
    IOCanRWHandler *fd_read_poll;
3429
    IOHandler *fd_read;
3430
    IOHandler *fd_write;
3431
    void *opaque;
3432
    /* temporary data */
3433
    struct pollfd *ufd;
3434
    struct IOHandlerRecord *next;
3435
} IOHandlerRecord;
3436

    
3437
static IOHandlerRecord *first_io_handler;
3438

    
3439
/* XXX: fd_read_poll should be suppressed, but an API change is
3440
   necessary in the character devices to suppress fd_can_read(). */
3441
int qemu_set_fd_handler2(int fd, 
3442
                         IOCanRWHandler *fd_read_poll, 
3443
                         IOHandler *fd_read, 
3444
                         IOHandler *fd_write, 
3445
                         void *opaque)
3446
{
3447
    IOHandlerRecord **pioh, *ioh;
3448

    
3449
    if (!fd_read && !fd_write) {
3450
        pioh = &first_io_handler;
3451
        for(;;) {
3452
            ioh = *pioh;
3453
            if (ioh == NULL)
3454
                break;
3455
            if (ioh->fd == fd) {
3456
                *pioh = ioh->next;
3457
                qemu_free(ioh);
3458
                break;
3459
            }
3460
            pioh = &ioh->next;
3461
        }
3462
    } else {
3463
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3464
            if (ioh->fd == fd)
3465
                goto found;
3466
        }
3467
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3468
        if (!ioh)
3469
            return -1;
3470
        ioh->next = first_io_handler;
3471
        first_io_handler = ioh;
3472
    found:
3473
        ioh->fd = fd;
3474
        ioh->fd_read_poll = fd_read_poll;
3475
        ioh->fd_read = fd_read;
3476
        ioh->fd_write = fd_write;
3477
        ioh->opaque = opaque;
3478
    }
3479
    return 0;
3480
}
3481

    
3482
int qemu_set_fd_handler(int fd, 
3483
                        IOHandler *fd_read, 
3484
                        IOHandler *fd_write, 
3485
                        void *opaque)
3486
{
3487
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3488
}
3489

    
3490
/***********************************************************/
3491
/* Polling handling */
3492

    
3493
typedef struct PollingEntry {
3494
    PollingFunc *func;
3495
    void *opaque;
3496
    struct PollingEntry *next;
3497
} PollingEntry;
3498

    
3499
static PollingEntry *first_polling_entry;
3500

    
3501
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3502
{
3503
    PollingEntry **ppe, *pe;
3504
    pe = qemu_mallocz(sizeof(PollingEntry));
3505
    if (!pe)
3506
        return -1;
3507
    pe->func = func;
3508
    pe->opaque = opaque;
3509
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3510
    *ppe = pe;
3511
    return 0;
3512
}
3513

    
3514
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3515
{
3516
    PollingEntry **ppe, *pe;
3517
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3518
        pe = *ppe;
3519
        if (pe->func == func && pe->opaque == opaque) {
3520
            *ppe = pe->next;
3521
            qemu_free(pe);
3522
            break;
3523
        }
3524
    }
3525
}
3526

    
3527
/***********************************************************/
3528
/* savevm/loadvm support */
3529

    
3530
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3531
{
3532
    fwrite(buf, 1, size, f);
3533
}
3534

    
3535
void qemu_put_byte(QEMUFile *f, int v)
3536
{
3537
    fputc(v, f);
3538
}
3539

    
3540
void qemu_put_be16(QEMUFile *f, unsigned int v)
3541
{
3542
    qemu_put_byte(f, v >> 8);
3543
    qemu_put_byte(f, v);
3544
}
3545

    
3546
void qemu_put_be32(QEMUFile *f, unsigned int v)
3547
{
3548
    qemu_put_byte(f, v >> 24);
3549
    qemu_put_byte(f, v >> 16);
3550
    qemu_put_byte(f, v >> 8);
3551
    qemu_put_byte(f, v);
3552
}
3553

    
3554
void qemu_put_be64(QEMUFile *f, uint64_t v)
3555
{
3556
    qemu_put_be32(f, v >> 32);
3557
    qemu_put_be32(f, v);
3558
}
3559

    
3560
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3561
{
3562
    return fread(buf, 1, size, f);
3563
}
3564

    
3565
int qemu_get_byte(QEMUFile *f)
3566
{
3567
    int v;
3568
    v = fgetc(f);
3569
    if (v == EOF)
3570
        return 0;
3571
    else
3572
        return v;
3573
}
3574

    
3575
unsigned int qemu_get_be16(QEMUFile *f)
3576
{
3577
    unsigned int v;
3578
    v = qemu_get_byte(f) << 8;
3579
    v |= qemu_get_byte(f);
3580
    return v;
3581
}
3582

    
3583
unsigned int qemu_get_be32(QEMUFile *f)
3584
{
3585
    unsigned int v;
3586
    v = qemu_get_byte(f) << 24;
3587
    v |= qemu_get_byte(f) << 16;
3588
    v |= qemu_get_byte(f) << 8;
3589
    v |= qemu_get_byte(f);
3590
    return v;
3591
}
3592

    
3593
uint64_t qemu_get_be64(QEMUFile *f)
3594
{
3595
    uint64_t v;
3596
    v = (uint64_t)qemu_get_be32(f) << 32;
3597
    v |= qemu_get_be32(f);
3598
    return v;
3599
}
3600

    
3601
int64_t qemu_ftell(QEMUFile *f)
3602
{
3603
    return ftell(f);
3604
}
3605

    
3606
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3607
{
3608
    if (fseek(f, pos, whence) < 0)
3609
        return -1;
3610
    return ftell(f);
3611
}
3612

    
3613
typedef struct SaveStateEntry {
3614
    char idstr[256];
3615
    int instance_id;
3616
    int version_id;
3617
    SaveStateHandler *save_state;
3618
    LoadStateHandler *load_state;
3619
    void *opaque;
3620
    struct SaveStateEntry *next;
3621
} SaveStateEntry;
3622

    
3623
static SaveStateEntry *first_se;
3624

    
3625
int register_savevm(const char *idstr, 
3626
                    int instance_id, 
3627
                    int version_id,
3628
                    SaveStateHandler *save_state,
3629
                    LoadStateHandler *load_state,
3630
                    void *opaque)
3631
{
3632
    SaveStateEntry *se, **pse;
3633

    
3634
    se = qemu_malloc(sizeof(SaveStateEntry));
3635
    if (!se)
3636
        return -1;
3637
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3638
    se->instance_id = instance_id;
3639
    se->version_id = version_id;
3640
    se->save_state = save_state;
3641
    se->load_state = load_state;
3642
    se->opaque = opaque;
3643
    se->next = NULL;
3644

    
3645
    /* add at the end of list */
3646
    pse = &first_se;
3647
    while (*pse != NULL)
3648
        pse = &(*pse)->next;
3649
    *pse = se;
3650
    return 0;
3651
}
3652

    
3653
#define QEMU_VM_FILE_MAGIC   0x5145564d
3654
#define QEMU_VM_FILE_VERSION 0x00000001
3655

    
3656
int qemu_savevm(const char *filename)
3657
{
3658
    SaveStateEntry *se;
3659
    QEMUFile *f;
3660
    int len, len_pos, cur_pos, saved_vm_running, ret;
3661

    
3662
    saved_vm_running = vm_running;
3663
    vm_stop(0);
3664

    
3665
    f = fopen(filename, "wb");
3666
    if (!f) {
3667
        ret = -1;
3668
        goto the_end;
3669
    }
3670

    
3671
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3672
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3673

    
3674
    for(se = first_se; se != NULL; se = se->next) {
3675
        /* ID string */
3676
        len = strlen(se->idstr);
3677
        qemu_put_byte(f, len);
3678
        qemu_put_buffer(f, se->idstr, len);
3679

    
3680
        qemu_put_be32(f, se->instance_id);
3681
        qemu_put_be32(f, se->version_id);
3682

    
3683
        /* record size: filled later */
3684
        len_pos = ftell(f);
3685
        qemu_put_be32(f, 0);
3686
        
3687
        se->save_state(f, se->opaque);
3688

    
3689
        /* fill record size */
3690
        cur_pos = ftell(f);
3691
        len = ftell(f) - len_pos - 4;
3692
        fseek(f, len_pos, SEEK_SET);
3693
        qemu_put_be32(f, len);
3694
        fseek(f, cur_pos, SEEK_SET);
3695
    }
3696

    
3697
    fclose(f);
3698
    ret = 0;
3699
 the_end:
3700
    if (saved_vm_running)
3701
        vm_start();
3702
    return ret;
3703
}
3704

    
3705
static SaveStateEntry *find_se(const char *idstr, int instance_id)
3706
{
3707
    SaveStateEntry *se;
3708

    
3709
    for(se = first_se; se != NULL; se = se->next) {
3710
        if (!strcmp(se->idstr, idstr) && 
3711
            instance_id == se->instance_id)
3712
            return se;
3713
    }
3714
    return NULL;
3715
}
3716

    
3717
int qemu_loadvm(const char *filename)
3718
{
3719
    SaveStateEntry *se;
3720
    QEMUFile *f;
3721
    int len, cur_pos, ret, instance_id, record_len, version_id;
3722
    int saved_vm_running;
3723
    unsigned int v;
3724
    char idstr[256];
3725
    
3726
    saved_vm_running = vm_running;
3727
    vm_stop(0);
3728

    
3729
    f = fopen(filename, "rb");
3730
    if (!f) {
3731
        ret = -1;
3732
        goto the_end;
3733
    }
3734

    
3735
    v = qemu_get_be32(f);
3736
    if (v != QEMU_VM_FILE_MAGIC)
3737
        goto fail;
3738
    v = qemu_get_be32(f);
3739
    if (v != QEMU_VM_FILE_VERSION) {
3740
    fail:
3741
        fclose(f);
3742
        ret = -1;
3743
        goto the_end;
3744
    }
3745
    for(;;) {
3746
        len = qemu_get_byte(f);
3747
        if (feof(f))
3748
            break;
3749
        qemu_get_buffer(f, idstr, len);
3750
        idstr[len] = '\0';
3751
        instance_id = qemu_get_be32(f);
3752
        version_id = qemu_get_be32(f);
3753
        record_len = qemu_get_be32(f);
3754
#if 0
3755
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
3756
               idstr, instance_id, version_id, record_len);
3757
#endif
3758
        cur_pos = ftell(f);
3759
        se = find_se(idstr, instance_id);
3760
        if (!se) {
3761
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
3762
                    instance_id, idstr);
3763
        } else {
3764
            ret = se->load_state(f, se->opaque, version_id);
3765
            if (ret < 0) {
3766
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
3767
                        instance_id, idstr);
3768
            }
3769
        }
3770
        /* always seek to exact end of record */
3771
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3772
    }
3773
    fclose(f);
3774
    ret = 0;
3775
 the_end:
3776
    if (saved_vm_running)
3777
        vm_start();
3778
    return ret;
3779
}
3780

    
3781
/***********************************************************/
3782
/* cpu save/restore */
3783

    
3784
#if defined(TARGET_I386)
3785

    
3786
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3787
{
3788
    qemu_put_be32(f, dt->selector);
3789
    qemu_put_betl(f, dt->base);
3790
    qemu_put_be32(f, dt->limit);
3791
    qemu_put_be32(f, dt->flags);
3792
}
3793

    
3794
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3795
{
3796
    dt->selector = qemu_get_be32(f);
3797
    dt->base = qemu_get_betl(f);
3798
    dt->limit = qemu_get_be32(f);
3799
    dt->flags = qemu_get_be32(f);
3800
}
3801

    
3802
void cpu_save(QEMUFile *f, void *opaque)
3803
{
3804
    CPUState *env = opaque;
3805
    uint16_t fptag, fpus, fpuc, fpregs_format;
3806
    uint32_t hflags;
3807
    int i;
3808
    
3809
    for(i = 0; i < CPU_NB_REGS; i++)
3810
        qemu_put_betls(f, &env->regs[i]);
3811
    qemu_put_betls(f, &env->eip);
3812
    qemu_put_betls(f, &env->eflags);
3813
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3814
    qemu_put_be32s(f, &hflags);
3815
    
3816
    /* FPU */
3817
    fpuc = env->fpuc;
3818
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3819
    fptag = 0;
3820
    for(i = 0; i < 8; i++) {
3821
        fptag |= ((!env->fptags[i]) << i);
3822
    }
3823
    
3824
    qemu_put_be16s(f, &fpuc);
3825
    qemu_put_be16s(f, &fpus);
3826
    qemu_put_be16s(f, &fptag);
3827

    
3828
#ifdef USE_X86LDOUBLE
3829
    fpregs_format = 0;
3830
#else
3831
    fpregs_format = 1;
3832
#endif
3833
    qemu_put_be16s(f, &fpregs_format);
3834
    
3835
    for(i = 0; i < 8; i++) {
3836
#ifdef USE_X86LDOUBLE
3837
        {
3838
            uint64_t mant;
3839
            uint16_t exp;
3840
            /* we save the real CPU data (in case of MMX usage only 'mant'
3841
               contains the MMX register */
3842
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3843
            qemu_put_be64(f, mant);
3844
            qemu_put_be16(f, exp);
3845
        }
3846
#else
3847
        /* if we use doubles for float emulation, we save the doubles to
3848
           avoid losing information in case of MMX usage. It can give
3849
           problems if the image is restored on a CPU where long
3850
           doubles are used instead. */
3851
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3852
#endif
3853
    }
3854

    
3855
    for(i = 0; i < 6; i++)
3856
        cpu_put_seg(f, &env->segs[i]);
3857
    cpu_put_seg(f, &env->ldt);
3858
    cpu_put_seg(f, &env->tr);
3859
    cpu_put_seg(f, &env->gdt);
3860
    cpu_put_seg(f, &env->idt);
3861
    
3862
    qemu_put_be32s(f, &env->sysenter_cs);
3863
    qemu_put_be32s(f, &env->sysenter_esp);
3864
    qemu_put_be32s(f, &env->sysenter_eip);
3865
    
3866
    qemu_put_betls(f, &env->cr[0]);
3867
    qemu_put_betls(f, &env->cr[2]);
3868
    qemu_put_betls(f, &env->cr[3]);
3869
    qemu_put_betls(f, &env->cr[4]);
3870
    
3871
    for(i = 0; i < 8; i++)
3872
        qemu_put_betls(f, &env->dr[i]);
3873

    
3874
    /* MMU */
3875
    qemu_put_be32s(f, &env->a20_mask);
3876

    
3877
    /* XMM */
3878
    qemu_put_be32s(f, &env->mxcsr);
3879
    for(i = 0; i < CPU_NB_REGS; i++) {
3880
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3881
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3882
    }
3883

    
3884
#ifdef TARGET_X86_64
3885
    qemu_put_be64s(f, &env->efer);
3886
    qemu_put_be64s(f, &env->star);
3887
    qemu_put_be64s(f, &env->lstar);
3888
    qemu_put_be64s(f, &env->cstar);
3889
    qemu_put_be64s(f, &env->fmask);
3890
    qemu_put_be64s(f, &env->kernelgsbase);
3891
#endif
3892
}
3893

    
3894
#ifdef USE_X86LDOUBLE
3895
/* XXX: add that in a FPU generic layer */
3896
union x86_longdouble {
3897
    uint64_t mant;
3898
    uint16_t exp;
3899
};
3900

    
3901
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
3902
#define EXPBIAS1 1023
3903
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
3904
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
3905

    
3906
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3907
{
3908
    int e;
3909
    /* mantissa */
3910
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3911
    /* exponent + sign */
3912
    e = EXPD1(temp) - EXPBIAS1 + 16383;
3913
    e |= SIGND1(temp) >> 16;
3914
    p->exp = e;
3915
}
3916
#endif
3917

    
3918
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3919
{
3920
    CPUState *env = opaque;
3921
    int i, guess_mmx;
3922
    uint32_t hflags;
3923
    uint16_t fpus, fpuc, fptag, fpregs_format;
3924

    
3925
    if (version_id != 3)
3926
        return -EINVAL;
3927
    for(i = 0; i < CPU_NB_REGS; i++)
3928
        qemu_get_betls(f, &env->regs[i]);
3929
    qemu_get_betls(f, &env->eip);
3930
    qemu_get_betls(f, &env->eflags);
3931
    qemu_get_be32s(f, &hflags);
3932

    
3933
    qemu_get_be16s(f, &fpuc);
3934
    qemu_get_be16s(f, &fpus);
3935
    qemu_get_be16s(f, &fptag);
3936
    qemu_get_be16s(f, &fpregs_format);
3937
    
3938
    /* NOTE: we cannot always restore the FPU state if the image come
3939
       from a host with a different 'USE_X86LDOUBLE' define. We guess
3940
       if we are in an MMX state to restore correctly in that case. */
3941
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3942
    for(i = 0; i < 8; i++) {
3943
        uint64_t mant;
3944
        uint16_t exp;
3945
        
3946
        switch(fpregs_format) {
3947
        case 0:
3948
            mant = qemu_get_be64(f);
3949
            exp = qemu_get_be16(f);
3950
#ifdef USE_X86LDOUBLE
3951
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
3952
#else
3953
            /* difficult case */
3954
            if (guess_mmx)
3955
                env->fpregs[i].mmx.MMX_Q(0) = mant;
3956
            else
3957
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
3958
#endif
3959
            break;
3960
        case 1:
3961
            mant = qemu_get_be64(f);
3962
#ifdef USE_X86LDOUBLE
3963
            {
3964
                union x86_longdouble *p;
3965
                /* difficult case */
3966
                p = (void *)&env->fpregs[i];
3967
                if (guess_mmx) {
3968
                    p->mant = mant;
3969
                    p->exp = 0xffff;
3970
                } else {
3971
                    fp64_to_fp80(p, mant);
3972
                }
3973
            }
3974
#else
3975
            env->fpregs[i].mmx.MMX_Q(0) = mant;
3976
#endif            
3977
            break;
3978
        default:
3979
            return -EINVAL;
3980
        }
3981
    }
3982

    
3983
    env->fpuc = fpuc;
3984
    /* XXX: restore FPU round state */
3985
    env->fpstt = (fpus >> 11) & 7;
3986
    env->fpus = fpus & ~0x3800;
3987
    fptag ^= 0xff;
3988
    for(i = 0; i < 8; i++) {
3989
        env->fptags[i] = (fptag >> i) & 1;
3990
    }
3991
    
3992
    for(i = 0; i < 6; i++)
3993
        cpu_get_seg(f, &env->segs[i]);
3994
    cpu_get_seg(f, &env->ldt);
3995
    cpu_get_seg(f, &env->tr);
3996
    cpu_get_seg(f, &env->gdt);
3997
    cpu_get_seg(f, &env->idt);
3998
    
3999
    qemu_get_be32s(f, &env->sysenter_cs);
4000
    qemu_get_be32s(f, &env->sysenter_esp);
4001
    qemu_get_be32s(f, &env->sysenter_eip);
4002
    
4003
    qemu_get_betls(f, &env->cr[0]);
4004
    qemu_get_betls(f, &env->cr[2]);
4005
    qemu_get_betls(f, &env->cr[3]);
4006
    qemu_get_betls(f, &env->cr[4]);
4007
    
4008
    for(i = 0; i < 8; i++)
4009
        qemu_get_betls(f, &env->dr[i]);
4010

    
4011
    /* MMU */
4012
    qemu_get_be32s(f, &env->a20_mask);
4013

    
4014
    qemu_get_be32s(f, &env->mxcsr);
4015
    for(i = 0; i < CPU_NB_REGS; i++) {
4016
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4017
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4018
    }
4019

    
4020
#ifdef TARGET_X86_64
4021
    qemu_get_be64s(f, &env->efer);
4022
    qemu_get_be64s(f, &env->star);
4023
    qemu_get_be64s(f, &env->lstar);
4024
    qemu_get_be64s(f, &env->cstar);
4025
    qemu_get_be64s(f, &env->fmask);
4026
    qemu_get_be64s(f, &env->kernelgsbase);
4027
#endif
4028

    
4029
    /* XXX: compute hflags from scratch, except for CPL and IIF */
4030
    env->hflags = hflags;
4031
    tlb_flush(env, 1);
4032
    return 0;
4033
}
4034

    
4035
#elif defined(TARGET_PPC)
4036
void cpu_save(QEMUFile *f, void *opaque)
4037
{
4038
}
4039

    
4040
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4041
{
4042
    return 0;
4043
}
4044

    
4045
#elif defined(TARGET_MIPS)
4046
void cpu_save(QEMUFile *f, void *opaque)
4047
{
4048
}
4049

    
4050
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4051
{
4052
    return 0;
4053
}
4054

    
4055
#elif defined(TARGET_SPARC)
4056
void cpu_save(QEMUFile *f, void *opaque)
4057
{
4058
    CPUState *env = opaque;
4059
    int i;
4060
    uint32_t tmp;
4061

    
4062
    for(i = 0; i < 8; i++)
4063
        qemu_put_betls(f, &env->gregs[i]);
4064
    for(i = 0; i < NWINDOWS * 16; i++)
4065
        qemu_put_betls(f, &env->regbase[i]);
4066

    
4067
    /* FPU */
4068
    for(i = 0; i < TARGET_FPREGS; i++) {
4069
        union {
4070
            TARGET_FPREG_T f;
4071
            target_ulong i;
4072
        } u;
4073
        u.f = env->fpr[i];
4074
        qemu_put_betl(f, u.i);
4075
    }
4076

    
4077
    qemu_put_betls(f, &env->pc);
4078
    qemu_put_betls(f, &env->npc);
4079
    qemu_put_betls(f, &env->y);
4080
    tmp = GET_PSR(env);
4081
    qemu_put_be32(f, tmp);
4082
    qemu_put_betls(f, &env->fsr);
4083
    qemu_put_betls(f, &env->tbr);
4084
#ifndef TARGET_SPARC64
4085
    qemu_put_be32s(f, &env->wim);
4086
    /* MMU */
4087
    for(i = 0; i < 16; i++)
4088
        qemu_put_be32s(f, &env->mmuregs[i]);
4089
#endif
4090
}
4091

    
4092
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4093
{
4094
    CPUState *env = opaque;
4095
    int i;
4096
    uint32_t tmp;
4097

    
4098
    for(i = 0; i < 8; i++)
4099
        qemu_get_betls(f, &env->gregs[i]);
4100
    for(i = 0; i < NWINDOWS * 16; i++)
4101
        qemu_get_betls(f, &env->regbase[i]);
4102

    
4103
    /* FPU */
4104
    for(i = 0; i < TARGET_FPREGS; i++) {
4105
        union {
4106
            TARGET_FPREG_T f;
4107
            target_ulong i;
4108
        } u;
4109
        u.i = qemu_get_betl(f);
4110
        env->fpr[i] = u.f;
4111
    }
4112

    
4113
    qemu_get_betls(f, &env->pc);
4114
    qemu_get_betls(f, &env->npc);
4115
    qemu_get_betls(f, &env->y);
4116
    tmp = qemu_get_be32(f);
4117
    env->cwp = 0; /* needed to ensure that the wrapping registers are
4118
                     correctly updated */
4119
    PUT_PSR(env, tmp);
4120
    qemu_get_betls(f, &env->fsr);
4121
    qemu_get_betls(f, &env->tbr);
4122
#ifndef TARGET_SPARC64
4123
    qemu_get_be32s(f, &env->wim);
4124
    /* MMU */
4125
    for(i = 0; i < 16; i++)
4126
        qemu_get_be32s(f, &env->mmuregs[i]);
4127
#endif
4128
    tlb_flush(env, 1);
4129
    return 0;
4130
}
4131

    
4132
#elif defined(TARGET_ARM)
4133

    
4134
/* ??? Need to implement these.  */
4135
void cpu_save(QEMUFile *f, void *opaque)
4136
{
4137
}
4138

    
4139
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4140
{
4141
    return 0;
4142
}
4143

    
4144
#else
4145

    
4146
#warning No CPU save/restore functions
4147

    
4148
#endif
4149

    
4150
/***********************************************************/
4151
/* ram save/restore */
4152

    
4153
/* we just avoid storing empty pages */
4154
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4155
{
4156
    int i, v;
4157

    
4158
    v = buf[0];
4159
    for(i = 1; i < len; i++) {
4160
        if (buf[i] != v)
4161
            goto normal_save;
4162
    }
4163
    qemu_put_byte(f, 1);
4164
    qemu_put_byte(f, v);
4165
    return;
4166
 normal_save:
4167
    qemu_put_byte(f, 0); 
4168
    qemu_put_buffer(f, buf, len);
4169
}
4170

    
4171
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4172
{
4173
    int v;
4174

    
4175
    v = qemu_get_byte(f);
4176
    switch(v) {
4177
    case 0:
4178
        if (qemu_get_buffer(f, buf, len) != len)
4179
            return -EIO;
4180
        break;
4181
    case 1:
4182
        v = qemu_get_byte(f);
4183
        memset(buf, v, len);
4184
        break;
4185
    default:
4186
        return -EINVAL;
4187
    }
4188
    return 0;
4189
}
4190

    
4191
static void ram_save(QEMUFile *f, void *opaque)
4192
{
4193
    int i;
4194
    qemu_put_be32(f, phys_ram_size);
4195
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4196
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4197
    }
4198
}
4199

    
4200
static int ram_load(QEMUFile *f, void *opaque, int version_id)
4201
{
4202
    int i, ret;
4203

    
4204
    if (version_id != 1)
4205
        return -EINVAL;
4206
    if (qemu_get_be32(f) != phys_ram_size)
4207
        return -EINVAL;
4208
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4209
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4210
        if (ret)
4211
            return ret;
4212
    }
4213
    return 0;
4214
}
4215

    
4216
/***********************************************************/
4217
/* machine registration */
4218

    
4219
QEMUMachine *first_machine = NULL;
4220

    
4221
int qemu_register_machine(QEMUMachine *m)
4222
{
4223
    QEMUMachine **pm;
4224
    pm = &first_machine;
4225
    while (*pm != NULL)
4226
        pm = &(*pm)->next;
4227
    m->next = NULL;
4228
    *pm = m;
4229
    return 0;
4230
}
4231

    
4232
QEMUMachine *find_machine(const char *name)
4233
{
4234
    QEMUMachine *m;
4235

    
4236
    for(m = first_machine; m != NULL; m = m->next) {
4237
        if (!strcmp(m->name, name))
4238
            return m;
4239
    }
4240
    return NULL;
4241
}
4242

    
4243
/***********************************************************/
4244
/* main execution loop */
4245

    
4246
void gui_update(void *opaque)
4247
{
4248
    display_state.dpy_refresh(&display_state);
4249
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4250
}
4251

    
4252
struct vm_change_state_entry {
4253
    VMChangeStateHandler *cb;
4254
    void *opaque;
4255
    LIST_ENTRY (vm_change_state_entry) entries;
4256
};
4257

    
4258
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4259

    
4260
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4261
                                                     void *opaque)
4262
{
4263
    VMChangeStateEntry *e;
4264

    
4265
    e = qemu_mallocz(sizeof (*e));
4266
    if (!e)
4267
        return NULL;
4268

    
4269
    e->cb = cb;
4270
    e->opaque = opaque;
4271
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4272
    return e;
4273
}
4274

    
4275
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4276
{
4277
    LIST_REMOVE (e, entries);
4278
    qemu_free (e);
4279
}
4280

    
4281
static void vm_state_notify(int running)
4282
{
4283
    VMChangeStateEntry *e;
4284

    
4285
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4286
        e->cb(e->opaque, running);
4287
    }
4288
}
4289

    
4290
/* XXX: support several handlers */
4291
static VMStopHandler *vm_stop_cb;
4292
static void *vm_stop_opaque;
4293

    
4294
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4295
{
4296
    vm_stop_cb = cb;
4297
    vm_stop_opaque = opaque;
4298
    return 0;
4299
}
4300

    
4301
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4302
{
4303
    vm_stop_cb = NULL;
4304
}
4305

    
4306
void vm_start(void)
4307
{
4308
    if (!vm_running) {
4309
        cpu_enable_ticks();
4310
        vm_running = 1;
4311
        vm_state_notify(1);
4312
    }
4313
}
4314

    
4315
void vm_stop(int reason) 
4316
{
4317
    if (vm_running) {
4318
        cpu_disable_ticks();
4319
        vm_running = 0;
4320
        if (reason != 0) {
4321
            if (vm_stop_cb) {
4322
                vm_stop_cb(vm_stop_opaque, reason);
4323
            }
4324
        }
4325
        vm_state_notify(0);
4326
    }
4327
}
4328

    
4329
/* reset/shutdown handler */
4330

    
4331
typedef struct QEMUResetEntry {
4332
    QEMUResetHandler *func;
4333
    void *opaque;
4334
    struct QEMUResetEntry *next;
4335
} QEMUResetEntry;
4336

    
4337
static QEMUResetEntry *first_reset_entry;
4338
static int reset_requested;
4339
static int shutdown_requested;
4340
static int powerdown_requested;
4341

    
4342
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4343
{
4344
    QEMUResetEntry **pre, *re;
4345

    
4346
    pre = &first_reset_entry;
4347
    while (*pre != NULL)
4348
        pre = &(*pre)->next;
4349
    re = qemu_mallocz(sizeof(QEMUResetEntry));
4350
    re->func = func;
4351
    re->opaque = opaque;
4352
    re->next = NULL;
4353
    *pre = re;
4354
}
4355

    
4356
void qemu_system_reset(void)
4357
{
4358
    QEMUResetEntry *re;
4359

    
4360
    /* reset all devices */
4361
    for(re = first_reset_entry; re != NULL; re = re->next) {
4362
        re->func(re->opaque);
4363
    }
4364
}
4365

    
4366
void qemu_system_reset_request(void)
4367
{
4368
    reset_requested = 1;
4369
    if (cpu_single_env)
4370
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4371
}
4372

    
4373
void qemu_system_shutdown_request(void)
4374
{
4375
    shutdown_requested = 1;
4376
    if (cpu_single_env)
4377
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4378
}
4379

    
4380
void qemu_system_powerdown_request(void)
4381
{
4382
    powerdown_requested = 1;
4383
    if (cpu_single_env)
4384
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4385
}
4386

    
4387
void main_loop_wait(int timeout)
4388
{
4389
    IOHandlerRecord *ioh, *ioh_next;
4390
    fd_set rfds, wfds;
4391
    int ret, nfds;
4392
    struct timeval tv;
4393
    PollingEntry *pe;
4394

    
4395

    
4396
    /* XXX: need to suppress polling by better using win32 events */
4397
    ret = 0;
4398
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4399
        ret |= pe->func(pe->opaque);
4400
    }
4401
#ifdef _WIN32
4402
    if (ret == 0 && timeout > 0) {
4403
        Sleep(timeout);
4404
    }
4405
#endif
4406
    /* poll any events */
4407
    /* XXX: separate device handlers from system ones */
4408
    nfds = -1;
4409
    FD_ZERO(&rfds);
4410
    FD_ZERO(&wfds);
4411
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4412
        if (ioh->fd_read &&
4413
            (!ioh->fd_read_poll ||
4414
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4415
            FD_SET(ioh->fd, &rfds);
4416
            if (ioh->fd > nfds)
4417
                nfds = ioh->fd;
4418
        }
4419
        if (ioh->fd_write) {
4420
            FD_SET(ioh->fd, &wfds);
4421
            if (ioh->fd > nfds)
4422
                nfds = ioh->fd;
4423
        }
4424
    }
4425
    
4426
    tv.tv_sec = 0;
4427
#ifdef _WIN32
4428
    tv.tv_usec = 0;
4429
#else
4430
    tv.tv_usec = timeout * 1000;
4431
#endif
4432
    ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4433
    if (ret > 0) {
4434
        /* XXX: better handling of removal */
4435
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4436
            ioh_next = ioh->next;
4437
            if (FD_ISSET(ioh->fd, &rfds)) {
4438
                ioh->fd_read(ioh->opaque);
4439
            }
4440
            if (FD_ISSET(ioh->fd, &wfds)) {
4441
                ioh->fd_write(ioh->opaque);
4442
            }
4443
        }
4444
    }
4445
#ifdef _WIN32
4446
    tap_win32_poll();
4447
#endif
4448

    
4449
#if defined(CONFIG_SLIRP)
4450
    /* XXX: merge with the previous select() */
4451
    if (slirp_inited) {
4452
        fd_set rfds, wfds, xfds;
4453
        int nfds;
4454
        struct timeval tv;
4455
        
4456
        nfds = -1;
4457
        FD_ZERO(&rfds);
4458
        FD_ZERO(&wfds);
4459
        FD_ZERO(&xfds);
4460
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4461
        tv.tv_sec = 0;
4462
        tv.tv_usec = 0;
4463
        ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4464
        if (ret >= 0) {
4465
            slirp_select_poll(&rfds, &wfds, &xfds);
4466
        }
4467
    }
4468
#endif
4469

    
4470
    if (vm_running) {
4471
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
4472
                        qemu_get_clock(vm_clock));
4473
        /* run dma transfers, if any */
4474
        DMA_run();
4475
    }
4476
    
4477
    /* real time timers */
4478
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
4479
                    qemu_get_clock(rt_clock));
4480
}
4481

    
4482
static CPUState *cur_cpu;
4483

    
4484
int main_loop(void)
4485
{
4486
    int ret, timeout;
4487
#ifdef CONFIG_PROFILER
4488
    int64_t ti;
4489
#endif
4490
    CPUState *env;
4491

    
4492
    cur_cpu = first_cpu;
4493
    for(;;) {
4494
        if (vm_running) {
4495

    
4496
            env = cur_cpu;
4497
            for(;;) {
4498
                /* get next cpu */
4499
                env = env->next_cpu;
4500
                if (!env)
4501
                    env = first_cpu;
4502
#ifdef CONFIG_PROFILER
4503
                ti = profile_getclock();
4504
#endif
4505
                ret = cpu_exec(env);
4506
#ifdef CONFIG_PROFILER
4507
                qemu_time += profile_getclock() - ti;
4508
#endif
4509
                if (ret != EXCP_HALTED)
4510
                    break;
4511
                /* all CPUs are halted ? */
4512
                if (env == cur_cpu) {
4513
                    ret = EXCP_HLT;
4514
                    break;
4515
                }
4516
            }
4517
            cur_cpu = env;
4518

    
4519
            if (shutdown_requested) {
4520
                ret = EXCP_INTERRUPT;
4521
                break;
4522
            }
4523
            if (reset_requested) {
4524
                reset_requested = 0;
4525
                qemu_system_reset();
4526
                ret = EXCP_INTERRUPT;
4527
            }
4528
            if (powerdown_requested) {
4529
                powerdown_requested = 0;
4530
                qemu_system_powerdown();
4531
                ret = EXCP_INTERRUPT;
4532
            }
4533
            if (ret == EXCP_DEBUG) {
4534
                vm_stop(EXCP_DEBUG);
4535
            }
4536
            /* if hlt instruction, we wait until the next IRQ */
4537
            /* XXX: use timeout computed from timers */
4538
            if (ret == EXCP_HLT)
4539
                timeout = 10;
4540
            else
4541
                timeout = 0;
4542
        } else {
4543
            timeout = 10;
4544
        }
4545
#ifdef CONFIG_PROFILER
4546
        ti = profile_getclock();
4547
#endif
4548
        main_loop_wait(timeout);
4549
#ifdef CONFIG_PROFILER
4550
        dev_time += profile_getclock() - ti;
4551
#endif
4552
    }
4553
    cpu_disable_ticks();
4554
    return ret;
4555
}
4556

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

    
4684
#define HAS_ARG 0x0001
4685

    
4686
enum {
4687
    QEMU_OPTION_h,
4688

    
4689
    QEMU_OPTION_M,
4690
    QEMU_OPTION_fda,
4691
    QEMU_OPTION_fdb,
4692
    QEMU_OPTION_hda,
4693
    QEMU_OPTION_hdb,
4694
    QEMU_OPTION_hdc,
4695
    QEMU_OPTION_hdd,
4696
    QEMU_OPTION_cdrom,
4697
    QEMU_OPTION_boot,
4698
    QEMU_OPTION_snapshot,
4699
    QEMU_OPTION_m,
4700
    QEMU_OPTION_nographic,
4701
#ifdef HAS_AUDIO
4702
    QEMU_OPTION_audio_help,
4703
    QEMU_OPTION_soundhw,
4704
#endif
4705

    
4706
    QEMU_OPTION_net,
4707
    QEMU_OPTION_tftp,
4708
    QEMU_OPTION_smb,
4709
    QEMU_OPTION_redir,
4710

    
4711
    QEMU_OPTION_kernel,
4712
    QEMU_OPTION_append,
4713
    QEMU_OPTION_initrd,
4714

    
4715
    QEMU_OPTION_S,
4716
    QEMU_OPTION_s,
4717
    QEMU_OPTION_p,
4718
    QEMU_OPTION_d,
4719
    QEMU_OPTION_hdachs,
4720
    QEMU_OPTION_L,
4721
    QEMU_OPTION_no_code_copy,
4722
    QEMU_OPTION_k,
4723
    QEMU_OPTION_localtime,
4724
    QEMU_OPTION_cirrusvga,
4725
    QEMU_OPTION_g,
4726
    QEMU_OPTION_std_vga,
4727
    QEMU_OPTION_monitor,
4728
    QEMU_OPTION_serial,
4729
    QEMU_OPTION_parallel,
4730
    QEMU_OPTION_loadvm,
4731
    QEMU_OPTION_full_screen,
4732
    QEMU_OPTION_pidfile,
4733
    QEMU_OPTION_no_kqemu,
4734
    QEMU_OPTION_kernel_kqemu,
4735
    QEMU_OPTION_win2k_hack,
4736
    QEMU_OPTION_usb,
4737
    QEMU_OPTION_usbdevice,
4738
    QEMU_OPTION_smp,
4739
};
4740

    
4741
typedef struct QEMUOption {
4742
    const char *name;
4743
    int flags;
4744
    int index;
4745
} QEMUOption;
4746

    
4747
const QEMUOption qemu_options[] = {
4748
    { "h", 0, QEMU_OPTION_h },
4749

    
4750
    { "M", HAS_ARG, QEMU_OPTION_M },
4751
    { "fda", HAS_ARG, QEMU_OPTION_fda },
4752
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4753
    { "hda", HAS_ARG, QEMU_OPTION_hda },
4754
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4755
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4756
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4757
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4758
    { "boot", HAS_ARG, QEMU_OPTION_boot },
4759
    { "snapshot", 0, QEMU_OPTION_snapshot },
4760
    { "m", HAS_ARG, QEMU_OPTION_m },
4761
    { "nographic", 0, QEMU_OPTION_nographic },
4762
    { "k", HAS_ARG, QEMU_OPTION_k },
4763
#ifdef HAS_AUDIO
4764
    { "audio-help", 0, QEMU_OPTION_audio_help },
4765
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4766
#endif
4767

    
4768
    { "net", HAS_ARG, QEMU_OPTION_net},
4769
#ifdef CONFIG_SLIRP
4770
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4771
#ifndef _WIN32
4772
    { "smb", HAS_ARG, QEMU_OPTION_smb },
4773
#endif
4774
    { "redir", HAS_ARG, QEMU_OPTION_redir },
4775
#endif
4776

    
4777
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4778
    { "append", HAS_ARG, QEMU_OPTION_append },
4779
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4780

    
4781
    { "S", 0, QEMU_OPTION_S },
4782
    { "s", 0, QEMU_OPTION_s },
4783
    { "p", HAS_ARG, QEMU_OPTION_p },
4784
    { "d", HAS_ARG, QEMU_OPTION_d },
4785
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4786
    { "L", HAS_ARG, QEMU_OPTION_L },
4787
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4788
#ifdef USE_KQEMU
4789
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4790
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4791
#endif
4792
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4793
    { "g", 1, QEMU_OPTION_g },
4794
#endif
4795
    { "localtime", 0, QEMU_OPTION_localtime },
4796
    { "std-vga", 0, QEMU_OPTION_std_vga },
4797
    { "monitor", 1, QEMU_OPTION_monitor },
4798
    { "serial", 1, QEMU_OPTION_serial },
4799
    { "parallel", 1, QEMU_OPTION_parallel },
4800
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4801
    { "full-screen", 0, QEMU_OPTION_full_screen },
4802
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4803
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4804
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4805
    { "smp", HAS_ARG, QEMU_OPTION_smp },
4806
    
4807
    /* temporary options */
4808
    { "usb", 0, QEMU_OPTION_usb },
4809
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4810
    { NULL },
4811
};
4812

    
4813
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4814

    
4815
/* this stack is only used during signal handling */
4816
#define SIGNAL_STACK_SIZE 32768
4817

    
4818
static uint8_t *signal_stack;
4819

    
4820
#endif
4821

    
4822
/* password input */
4823

    
4824
static BlockDriverState *get_bdrv(int index)
4825
{
4826
    BlockDriverState *bs;
4827

    
4828
    if (index < 4) {
4829
        bs = bs_table[index];
4830
    } else if (index < 6) {
4831
        bs = fd_table[index - 4];
4832
    } else {
4833
        bs = NULL;
4834
    }
4835
    return bs;
4836
}
4837

    
4838
static void read_passwords(void)
4839
{
4840
    BlockDriverState *bs;
4841
    int i, j;
4842
    char password[256];
4843

    
4844
    for(i = 0; i < 6; i++) {
4845
        bs = get_bdrv(i);
4846
        if (bs && bdrv_is_encrypted(bs)) {
4847
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4848
            for(j = 0; j < 3; j++) {
4849
                monitor_readline("Password: ", 
4850
                                 1, password, sizeof(password));
4851
                if (bdrv_set_key(bs, password) == 0)
4852
                    break;
4853
                term_printf("invalid password\n");
4854
            }
4855
        }
4856
    }
4857
}
4858

    
4859
/* XXX: currently we cannot use simultaneously different CPUs */
4860
void register_machines(void)
4861
{
4862
#if defined(TARGET_I386)
4863
    qemu_register_machine(&pc_machine);
4864
    qemu_register_machine(&isapc_machine);
4865
#elif defined(TARGET_PPC)
4866
    qemu_register_machine(&heathrow_machine);
4867
    qemu_register_machine(&core99_machine);
4868
    qemu_register_machine(&prep_machine);
4869
#elif defined(TARGET_MIPS)
4870
    qemu_register_machine(&mips_machine);
4871
#elif defined(TARGET_SPARC)
4872
#ifdef TARGET_SPARC64
4873
    qemu_register_machine(&sun4u_machine);
4874
#else
4875
    qemu_register_machine(&sun4m_machine);
4876
#endif
4877
#elif defined(TARGET_ARM)
4878
    qemu_register_machine(&integratorcp926_machine);
4879
    qemu_register_machine(&integratorcp1026_machine);
4880
    qemu_register_machine(&versatilepb_machine);
4881
#else
4882
#error unsupported CPU
4883
#endif
4884
}
4885

    
4886
#ifdef HAS_AUDIO
4887
struct soundhw soundhw[] = {
4888
    {
4889
        "sb16",
4890
        "Creative Sound Blaster 16",
4891
        0,
4892
        1,
4893
        { .init_isa = SB16_init }
4894
    },
4895

    
4896
#ifdef CONFIG_ADLIB
4897
    {
4898
        "adlib",
4899
#ifdef HAS_YMF262
4900
        "Yamaha YMF262 (OPL3)",
4901
#else
4902
        "Yamaha YM3812 (OPL2)",
4903
#endif
4904
        0,
4905
        1,
4906
        { .init_isa = Adlib_init }
4907
    },
4908
#endif
4909

    
4910
#ifdef CONFIG_GUS
4911
    {
4912
        "gus",
4913
        "Gravis Ultrasound GF1",
4914
        0,
4915
        1,
4916
        { .init_isa = GUS_init }
4917
    },
4918
#endif
4919

    
4920
    {
4921
        "es1370",
4922
        "ENSONIQ AudioPCI ES1370",
4923
        0,
4924
        0,
4925
        { .init_pci = es1370_init }
4926
    },
4927

    
4928
    { NULL, NULL, 0, 0, { NULL } }
4929
};
4930

    
4931
static void select_soundhw (const char *optarg)
4932
{
4933
    struct soundhw *c;
4934

    
4935
    if (*optarg == '?') {
4936
    show_valid_cards:
4937

    
4938
        printf ("Valid sound card names (comma separated):\n");
4939
        for (c = soundhw; c->name; ++c) {
4940
            printf ("%-11s %s\n", c->name, c->descr);
4941
        }
4942
        printf ("\n-soundhw all will enable all of the above\n");
4943
        exit (*optarg != '?');
4944
    }
4945
    else {
4946
        size_t l;
4947
        const char *p;
4948
        char *e;
4949
        int bad_card = 0;
4950

    
4951
        if (!strcmp (optarg, "all")) {
4952
            for (c = soundhw; c->name; ++c) {
4953
                c->enabled = 1;
4954
            }
4955
            return;
4956
        }
4957

    
4958
        p = optarg;
4959
        while (*p) {
4960
            e = strchr (p, ',');
4961
            l = !e ? strlen (p) : (size_t) (e - p);
4962

    
4963
            for (c = soundhw; c->name; ++c) {
4964
                if (!strncmp (c->name, p, l)) {
4965
                    c->enabled = 1;
4966
                    break;
4967
                }
4968
            }
4969

    
4970
            if (!c->name) {
4971
                if (l > 80) {