Statistics
| Branch: | Revision:

root / vl.c @ 6e02c38d

History | View | Annotate | Download (146 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2008 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 "hw/hw.h"
25
#include "hw/boards.h"
26
#include "hw/usb.h"
27
#include "hw/pcmcia.h"
28
#include "hw/pc.h"
29
#include "hw/audiodev.h"
30
#include "hw/isa.h"
31
#include "hw/baum.h"
32
#include "hw/bt.h"
33
#include "net.h"
34
#include "console.h"
35
#include "sysemu.h"
36
#include "gdbstub.h"
37
#include "qemu-timer.h"
38
#include "qemu-char.h"
39
#include "block.h"
40
#include "audio/audio.h"
41
#include "migration.h"
42
#include "kvm.h"
43

    
44
#include <unistd.h>
45
#include <fcntl.h>
46
#include <signal.h>
47
#include <time.h>
48
#include <errno.h>
49
#include <sys/time.h>
50
#include <zlib.h>
51

    
52
#ifndef _WIN32
53
#include <sys/times.h>
54
#include <sys/wait.h>
55
#include <termios.h>
56
#include <sys/mman.h>
57
#include <sys/ioctl.h>
58
#include <sys/resource.h>
59
#include <sys/socket.h>
60
#include <netinet/in.h>
61
#include <net/if.h>
62
#if defined(__NetBSD__)
63
#include <net/if_tap.h>
64
#endif
65
#ifdef __linux__
66
#include <linux/if_tun.h>
67
#endif
68
#include <arpa/inet.h>
69
#include <dirent.h>
70
#include <netdb.h>
71
#include <sys/select.h>
72
#ifdef _BSD
73
#include <sys/stat.h>
74
#ifdef __FreeBSD__
75
#include <libutil.h>
76
#else
77
#include <util.h>
78
#endif
79
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
80
#include <freebsd/stdlib.h>
81
#else
82
#ifdef __linux__
83
#include <pty.h>
84
#include <malloc.h>
85
#include <linux/rtc.h>
86

    
87
/* For the benefit of older linux systems which don't supply it,
88
   we use a local copy of hpet.h. */
89
/* #include <linux/hpet.h> */
90
#include "hpet.h"
91

    
92
#include <linux/ppdev.h>
93
#include <linux/parport.h>
94
#endif
95
#ifdef __sun__
96
#include <sys/stat.h>
97
#include <sys/ethernet.h>
98
#include <sys/sockio.h>
99
#include <netinet/arp.h>
100
#include <netinet/in.h>
101
#include <netinet/in_systm.h>
102
#include <netinet/ip.h>
103
#include <netinet/ip_icmp.h> // must come after ip.h
104
#include <netinet/udp.h>
105
#include <netinet/tcp.h>
106
#include <net/if.h>
107
#include <syslog.h>
108
#include <stropts.h>
109
#endif
110
#endif
111
#endif
112

    
113
#include "qemu_socket.h"
114

    
115
#if defined(CONFIG_SLIRP)
116
#include "libslirp.h"
117
#endif
118

    
119
#if defined(__OpenBSD__)
120
#include <util.h>
121
#endif
122

    
123
#if defined(CONFIG_VDE)
124
#include <libvdeplug.h>
125
#endif
126

    
127
#ifdef _WIN32
128
#include <malloc.h>
129
#include <sys/timeb.h>
130
#include <mmsystem.h>
131
#define getopt_long_only getopt_long
132
#define memalign(align, size) malloc(size)
133
#endif
134

    
135
#ifdef CONFIG_SDL
136
#ifdef __APPLE__
137
#include <SDL/SDL.h>
138
#endif
139
#endif /* CONFIG_SDL */
140

    
141
#ifdef CONFIG_COCOA
142
#undef main
143
#define main qemu_main
144
#endif /* CONFIG_COCOA */
145

    
146
#include "disas.h"
147

    
148
#include "exec-all.h"
149

    
150
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
151
#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
152
#ifdef __sun__
153
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
154
#else
155
#define SMBD_COMMAND "/usr/sbin/smbd"
156
#endif
157

    
158
//#define DEBUG_UNUSED_IOPORT
159
//#define DEBUG_IOPORT
160
//#define DEBUG_NET
161
//#define DEBUG_SLIRP
162

    
163
#ifdef TARGET_PPC
164
#define DEFAULT_RAM_SIZE 144
165
#else
166
#define DEFAULT_RAM_SIZE 128
167
#endif
168

    
169
/* Max number of USB devices that can be specified on the commandline.  */
170
#define MAX_USB_CMDLINE 8
171

    
172
/* Max number of bluetooth switches on the commandline.  */
173
#define MAX_BT_CMDLINE 10
174

    
175
/* XXX: use a two level table to limit memory usage */
176
#define MAX_IOPORTS 65536
177

    
178
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
179
const char *bios_name = NULL;
180
static void *ioport_opaque[MAX_IOPORTS];
181
static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
182
static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
183
/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
184
   to store the VM snapshots */
185
DriveInfo drives_table[MAX_DRIVES+1];
186
int nb_drives;
187
static int vga_ram_size;
188
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
189
DisplayState display_state;
190
int nographic;
191
static int curses;
192
const char* keyboard_layout = NULL;
193
int64_t ticks_per_sec;
194
ram_addr_t ram_size;
195
int nb_nics;
196
NICInfo nd_table[MAX_NICS];
197
int vm_running;
198
static int rtc_utc = 1;
199
static int rtc_date_offset = -1; /* -1 means no change */
200
int cirrus_vga_enabled = 1;
201
int vmsvga_enabled = 0;
202
#ifdef TARGET_SPARC
203
int graphic_width = 1024;
204
int graphic_height = 768;
205
int graphic_depth = 8;
206
#else
207
int graphic_width = 800;
208
int graphic_height = 600;
209
int graphic_depth = 15;
210
#endif
211
static int full_screen = 0;
212
#ifdef CONFIG_SDL
213
static int no_frame = 0;
214
#endif
215
int no_quit = 0;
216
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
217
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
218
#ifdef TARGET_I386
219
int win2k_install_hack = 0;
220
#endif
221
int usb_enabled = 0;
222
int smp_cpus = 1;
223
const char *vnc_display;
224
int acpi_enabled = 1;
225
int fd_bootchk = 1;
226
int no_reboot = 0;
227
int no_shutdown = 0;
228
int cursor_hide = 1;
229
int graphic_rotate = 0;
230
int daemonize = 0;
231
const char *option_rom[MAX_OPTION_ROMS];
232
int nb_option_roms;
233
int semihosting_enabled = 0;
234
#ifdef TARGET_ARM
235
int old_param = 0;
236
#endif
237
const char *qemu_name;
238
int alt_grab = 0;
239
#ifdef TARGET_SPARC
240
unsigned int nb_prom_envs = 0;
241
const char *prom_envs[MAX_PROM_ENVS];
242
#endif
243
static int nb_drives_opt;
244
static struct drive_opt {
245
    const char *file;
246
    char opt[1024];
247
} drives_opt[MAX_DRIVES];
248

    
249
static CPUState *cur_cpu;
250
static CPUState *next_cpu;
251
static int event_pending = 1;
252
/* Conversion factor from emulated instructions to virtual clock ticks.  */
253
static int icount_time_shift;
254
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
255
#define MAX_ICOUNT_SHIFT 10
256
/* Compensate for varying guest execution speed.  */
257
static int64_t qemu_icount_bias;
258
static QEMUTimer *icount_rt_timer;
259
static QEMUTimer *icount_vm_timer;
260

    
261
uint8_t qemu_uuid[16];
262

    
263
/***********************************************************/
264
/* x86 ISA bus support */
265

    
266
target_phys_addr_t isa_mem_base = 0;
267
PicState2 *isa_pic;
268

    
269
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
270
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
271

    
272
static uint32_t ioport_read(int index, uint32_t address)
273
{
274
    static IOPortReadFunc *default_func[3] = {
275
        default_ioport_readb,
276
        default_ioport_readw,
277
        default_ioport_readl
278
    };
279
    IOPortReadFunc *func = ioport_read_table[index][address];
280
    if (!func)
281
        func = default_func[index];
282
    return func(ioport_opaque[address], address);
283
}
284

    
285
static void ioport_write(int index, uint32_t address, uint32_t data)
286
{
287
    static IOPortWriteFunc *default_func[3] = {
288
        default_ioport_writeb,
289
        default_ioport_writew,
290
        default_ioport_writel
291
    };
292
    IOPortWriteFunc *func = ioport_write_table[index][address];
293
    if (!func)
294
        func = default_func[index];
295
    func(ioport_opaque[address], address, data);
296
}
297

    
298
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
299
{
300
#ifdef DEBUG_UNUSED_IOPORT
301
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
302
#endif
303
    return 0xff;
304
}
305

    
306
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
307
{
308
#ifdef DEBUG_UNUSED_IOPORT
309
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
310
#endif
311
}
312

    
313
/* default is to make two byte accesses */
314
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
315
{
316
    uint32_t data;
317
    data = ioport_read(0, address);
318
    address = (address + 1) & (MAX_IOPORTS - 1);
319
    data |= ioport_read(0, address) << 8;
320
    return data;
321
}
322

    
323
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
324
{
325
    ioport_write(0, address, data & 0xff);
326
    address = (address + 1) & (MAX_IOPORTS - 1);
327
    ioport_write(0, address, (data >> 8) & 0xff);
328
}
329

    
330
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
331
{
332
#ifdef DEBUG_UNUSED_IOPORT
333
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
334
#endif
335
    return 0xffffffff;
336
}
337

    
338
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
339
{
340
#ifdef DEBUG_UNUSED_IOPORT
341
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
342
#endif
343
}
344

    
345
/* size is the word size in byte */
346
int register_ioport_read(int start, int length, int size,
347
                         IOPortReadFunc *func, void *opaque)
348
{
349
    int i, bsize;
350

    
351
    if (size == 1) {
352
        bsize = 0;
353
    } else if (size == 2) {
354
        bsize = 1;
355
    } else if (size == 4) {
356
        bsize = 2;
357
    } else {
358
        hw_error("register_ioport_read: invalid size");
359
        return -1;
360
    }
361
    for(i = start; i < start + length; i += size) {
362
        ioport_read_table[bsize][i] = func;
363
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
364
            hw_error("register_ioport_read: invalid opaque");
365
        ioport_opaque[i] = opaque;
366
    }
367
    return 0;
368
}
369

    
370
/* size is the word size in byte */
371
int register_ioport_write(int start, int length, int size,
372
                          IOPortWriteFunc *func, void *opaque)
373
{
374
    int i, bsize;
375

    
376
    if (size == 1) {
377
        bsize = 0;
378
    } else if (size == 2) {
379
        bsize = 1;
380
    } else if (size == 4) {
381
        bsize = 2;
382
    } else {
383
        hw_error("register_ioport_write: invalid size");
384
        return -1;
385
    }
386
    for(i = start; i < start + length; i += size) {
387
        ioport_write_table[bsize][i] = func;
388
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
389
            hw_error("register_ioport_write: invalid opaque");
390
        ioport_opaque[i] = opaque;
391
    }
392
    return 0;
393
}
394

    
395
void isa_unassign_ioport(int start, int length)
396
{
397
    int i;
398

    
399
    for(i = start; i < start + length; i++) {
400
        ioport_read_table[0][i] = default_ioport_readb;
401
        ioport_read_table[1][i] = default_ioport_readw;
402
        ioport_read_table[2][i] = default_ioport_readl;
403

    
404
        ioport_write_table[0][i] = default_ioport_writeb;
405
        ioport_write_table[1][i] = default_ioport_writew;
406
        ioport_write_table[2][i] = default_ioport_writel;
407
    }
408
}
409

    
410
/***********************************************************/
411

    
412
void cpu_outb(CPUState *env, int addr, int val)
413
{
414
#ifdef DEBUG_IOPORT
415
    if (loglevel & CPU_LOG_IOPORT)
416
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
417
#endif
418
    ioport_write(0, addr, val);
419
#ifdef USE_KQEMU
420
    if (env)
421
        env->last_io_time = cpu_get_time_fast();
422
#endif
423
}
424

    
425
void cpu_outw(CPUState *env, int addr, int val)
426
{
427
#ifdef DEBUG_IOPORT
428
    if (loglevel & CPU_LOG_IOPORT)
429
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
430
#endif
431
    ioport_write(1, addr, val);
432
#ifdef USE_KQEMU
433
    if (env)
434
        env->last_io_time = cpu_get_time_fast();
435
#endif
436
}
437

    
438
void cpu_outl(CPUState *env, int addr, int val)
439
{
440
#ifdef DEBUG_IOPORT
441
    if (loglevel & CPU_LOG_IOPORT)
442
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
443
#endif
444
    ioport_write(2, addr, val);
445
#ifdef USE_KQEMU
446
    if (env)
447
        env->last_io_time = cpu_get_time_fast();
448
#endif
449
}
450

    
451
int cpu_inb(CPUState *env, int addr)
452
{
453
    int val;
454
    val = ioport_read(0, addr);
455
#ifdef DEBUG_IOPORT
456
    if (loglevel & CPU_LOG_IOPORT)
457
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
458
#endif
459
#ifdef USE_KQEMU
460
    if (env)
461
        env->last_io_time = cpu_get_time_fast();
462
#endif
463
    return val;
464
}
465

    
466
int cpu_inw(CPUState *env, int addr)
467
{
468
    int val;
469
    val = ioport_read(1, addr);
470
#ifdef DEBUG_IOPORT
471
    if (loglevel & CPU_LOG_IOPORT)
472
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
473
#endif
474
#ifdef USE_KQEMU
475
    if (env)
476
        env->last_io_time = cpu_get_time_fast();
477
#endif
478
    return val;
479
}
480

    
481
int cpu_inl(CPUState *env, int addr)
482
{
483
    int val;
484
    val = ioport_read(2, addr);
485
#ifdef DEBUG_IOPORT
486
    if (loglevel & CPU_LOG_IOPORT)
487
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
488
#endif
489
#ifdef USE_KQEMU
490
    if (env)
491
        env->last_io_time = cpu_get_time_fast();
492
#endif
493
    return val;
494
}
495

    
496
/***********************************************************/
497
void hw_error(const char *fmt, ...)
498
{
499
    va_list ap;
500
    CPUState *env;
501

    
502
    va_start(ap, fmt);
503
    fprintf(stderr, "qemu: hardware error: ");
504
    vfprintf(stderr, fmt, ap);
505
    fprintf(stderr, "\n");
506
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
507
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
508
#ifdef TARGET_I386
509
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
510
#else
511
        cpu_dump_state(env, stderr, fprintf, 0);
512
#endif
513
    }
514
    va_end(ap);
515
    abort();
516
}
517

    
518
/***********************************************************/
519
/* keyboard/mouse */
520

    
521
static QEMUPutKBDEvent *qemu_put_kbd_event;
522
static void *qemu_put_kbd_event_opaque;
523
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
524
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
525

    
526
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
527
{
528
    qemu_put_kbd_event_opaque = opaque;
529
    qemu_put_kbd_event = func;
530
}
531

    
532
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
533
                                                void *opaque, int absolute,
534
                                                const char *name)
535
{
536
    QEMUPutMouseEntry *s, *cursor;
537

    
538
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
539
    if (!s)
540
        return NULL;
541

    
542
    s->qemu_put_mouse_event = func;
543
    s->qemu_put_mouse_event_opaque = opaque;
544
    s->qemu_put_mouse_event_absolute = absolute;
545
    s->qemu_put_mouse_event_name = qemu_strdup(name);
546
    s->next = NULL;
547

    
548
    if (!qemu_put_mouse_event_head) {
549
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
550
        return s;
551
    }
552

    
553
    cursor = qemu_put_mouse_event_head;
554
    while (cursor->next != NULL)
555
        cursor = cursor->next;
556

    
557
    cursor->next = s;
558
    qemu_put_mouse_event_current = s;
559

    
560
    return s;
561
}
562

    
563
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
564
{
565
    QEMUPutMouseEntry *prev = NULL, *cursor;
566

    
567
    if (!qemu_put_mouse_event_head || entry == NULL)
568
        return;
569

    
570
    cursor = qemu_put_mouse_event_head;
571
    while (cursor != NULL && cursor != entry) {
572
        prev = cursor;
573
        cursor = cursor->next;
574
    }
575

    
576
    if (cursor == NULL) // does not exist or list empty
577
        return;
578
    else if (prev == NULL) { // entry is head
579
        qemu_put_mouse_event_head = cursor->next;
580
        if (qemu_put_mouse_event_current == entry)
581
            qemu_put_mouse_event_current = cursor->next;
582
        qemu_free(entry->qemu_put_mouse_event_name);
583
        qemu_free(entry);
584
        return;
585
    }
586

    
587
    prev->next = entry->next;
588

    
589
    if (qemu_put_mouse_event_current == entry)
590
        qemu_put_mouse_event_current = prev;
591

    
592
    qemu_free(entry->qemu_put_mouse_event_name);
593
    qemu_free(entry);
594
}
595

    
596
void kbd_put_keycode(int keycode)
597
{
598
    if (qemu_put_kbd_event) {
599
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
600
    }
601
}
602

    
603
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
604
{
605
    QEMUPutMouseEvent *mouse_event;
606
    void *mouse_event_opaque;
607
    int width;
608

    
609
    if (!qemu_put_mouse_event_current) {
610
        return;
611
    }
612

    
613
    mouse_event =
614
        qemu_put_mouse_event_current->qemu_put_mouse_event;
615
    mouse_event_opaque =
616
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
617

    
618
    if (mouse_event) {
619
        if (graphic_rotate) {
620
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
621
                width = 0x7fff;
622
            else
623
                width = graphic_width - 1;
624
            mouse_event(mouse_event_opaque,
625
                                 width - dy, dx, dz, buttons_state);
626
        } else
627
            mouse_event(mouse_event_opaque,
628
                                 dx, dy, dz, buttons_state);
629
    }
630
}
631

    
632
int kbd_mouse_is_absolute(void)
633
{
634
    if (!qemu_put_mouse_event_current)
635
        return 0;
636

    
637
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
638
}
639

    
640
void do_info_mice(void)
641
{
642
    QEMUPutMouseEntry *cursor;
643
    int index = 0;
644

    
645
    if (!qemu_put_mouse_event_head) {
646
        term_printf("No mouse devices connected\n");
647
        return;
648
    }
649

    
650
    term_printf("Mouse devices available:\n");
651
    cursor = qemu_put_mouse_event_head;
652
    while (cursor != NULL) {
653
        term_printf("%c Mouse #%d: %s\n",
654
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
655
                    index, cursor->qemu_put_mouse_event_name);
656
        index++;
657
        cursor = cursor->next;
658
    }
659
}
660

    
661
void do_mouse_set(int index)
662
{
663
    QEMUPutMouseEntry *cursor;
664
    int i = 0;
665

    
666
    if (!qemu_put_mouse_event_head) {
667
        term_printf("No mouse devices connected\n");
668
        return;
669
    }
670

    
671
    cursor = qemu_put_mouse_event_head;
672
    while (cursor != NULL && index != i) {
673
        i++;
674
        cursor = cursor->next;
675
    }
676

    
677
    if (cursor != NULL)
678
        qemu_put_mouse_event_current = cursor;
679
    else
680
        term_printf("Mouse at given index not found\n");
681
}
682

    
683
/* compute with 96 bit intermediate result: (a*b)/c */
684
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
685
{
686
    union {
687
        uint64_t ll;
688
        struct {
689
#ifdef WORDS_BIGENDIAN
690
            uint32_t high, low;
691
#else
692
            uint32_t low, high;
693
#endif
694
        } l;
695
    } u, res;
696
    uint64_t rl, rh;
697

    
698
    u.ll = a;
699
    rl = (uint64_t)u.l.low * (uint64_t)b;
700
    rh = (uint64_t)u.l.high * (uint64_t)b;
701
    rh += (rl >> 32);
702
    res.l.high = rh / c;
703
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
704
    return res.ll;
705
}
706

    
707
/***********************************************************/
708
/* real time host monotonic timer */
709

    
710
#define QEMU_TIMER_BASE 1000000000LL
711

    
712
#ifdef WIN32
713

    
714
static int64_t clock_freq;
715

    
716
static void init_get_clock(void)
717
{
718
    LARGE_INTEGER freq;
719
    int ret;
720
    ret = QueryPerformanceFrequency(&freq);
721
    if (ret == 0) {
722
        fprintf(stderr, "Could not calibrate ticks\n");
723
        exit(1);
724
    }
725
    clock_freq = freq.QuadPart;
726
}
727

    
728
static int64_t get_clock(void)
729
{
730
    LARGE_INTEGER ti;
731
    QueryPerformanceCounter(&ti);
732
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
733
}
734

    
735
#else
736

    
737
static int use_rt_clock;
738

    
739
static void init_get_clock(void)
740
{
741
    use_rt_clock = 0;
742
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
743
    {
744
        struct timespec ts;
745
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
746
            use_rt_clock = 1;
747
        }
748
    }
749
#endif
750
}
751

    
752
static int64_t get_clock(void)
753
{
754
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
755
    if (use_rt_clock) {
756
        struct timespec ts;
757
        clock_gettime(CLOCK_MONOTONIC, &ts);
758
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
759
    } else
760
#endif
761
    {
762
        /* XXX: using gettimeofday leads to problems if the date
763
           changes, so it should be avoided. */
764
        struct timeval tv;
765
        gettimeofday(&tv, NULL);
766
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
767
    }
768
}
769
#endif
770

    
771
/* Return the virtual CPU time, based on the instruction counter.  */
772
static int64_t cpu_get_icount(void)
773
{
774
    int64_t icount;
775
    CPUState *env = cpu_single_env;;
776
    icount = qemu_icount;
777
    if (env) {
778
        if (!can_do_io(env))
779
            fprintf(stderr, "Bad clock read\n");
780
        icount -= (env->icount_decr.u16.low + env->icount_extra);
781
    }
782
    return qemu_icount_bias + (icount << icount_time_shift);
783
}
784

    
785
/***********************************************************/
786
/* guest cycle counter */
787

    
788
static int64_t cpu_ticks_prev;
789
static int64_t cpu_ticks_offset;
790
static int64_t cpu_clock_offset;
791
static int cpu_ticks_enabled;
792

    
793
/* return the host CPU cycle counter and handle stop/restart */
794
int64_t cpu_get_ticks(void)
795
{
796
    if (use_icount) {
797
        return cpu_get_icount();
798
    }
799
    if (!cpu_ticks_enabled) {
800
        return cpu_ticks_offset;
801
    } else {
802
        int64_t ticks;
803
        ticks = cpu_get_real_ticks();
804
        if (cpu_ticks_prev > ticks) {
805
            /* Note: non increasing ticks may happen if the host uses
806
               software suspend */
807
            cpu_ticks_offset += cpu_ticks_prev - ticks;
808
        }
809
        cpu_ticks_prev = ticks;
810
        return ticks + cpu_ticks_offset;
811
    }
812
}
813

    
814
/* return the host CPU monotonic timer and handle stop/restart */
815
static int64_t cpu_get_clock(void)
816
{
817
    int64_t ti;
818
    if (!cpu_ticks_enabled) {
819
        return cpu_clock_offset;
820
    } else {
821
        ti = get_clock();
822
        return ti + cpu_clock_offset;
823
    }
824
}
825

    
826
/* enable cpu_get_ticks() */
827
void cpu_enable_ticks(void)
828
{
829
    if (!cpu_ticks_enabled) {
830
        cpu_ticks_offset -= cpu_get_real_ticks();
831
        cpu_clock_offset -= get_clock();
832
        cpu_ticks_enabled = 1;
833
    }
834
}
835

    
836
/* disable cpu_get_ticks() : the clock is stopped. You must not call
837
   cpu_get_ticks() after that.  */
838
void cpu_disable_ticks(void)
839
{
840
    if (cpu_ticks_enabled) {
841
        cpu_ticks_offset = cpu_get_ticks();
842
        cpu_clock_offset = cpu_get_clock();
843
        cpu_ticks_enabled = 0;
844
    }
845
}
846

    
847
/***********************************************************/
848
/* timers */
849

    
850
#define QEMU_TIMER_REALTIME 0
851
#define QEMU_TIMER_VIRTUAL  1
852

    
853
struct QEMUClock {
854
    int type;
855
    /* XXX: add frequency */
856
};
857

    
858
struct QEMUTimer {
859
    QEMUClock *clock;
860
    int64_t expire_time;
861
    QEMUTimerCB *cb;
862
    void *opaque;
863
    struct QEMUTimer *next;
864
};
865

    
866
struct qemu_alarm_timer {
867
    char const *name;
868
    unsigned int flags;
869

    
870
    int (*start)(struct qemu_alarm_timer *t);
871
    void (*stop)(struct qemu_alarm_timer *t);
872
    void (*rearm)(struct qemu_alarm_timer *t);
873
    void *priv;
874
};
875

    
876
#define ALARM_FLAG_DYNTICKS  0x1
877
#define ALARM_FLAG_EXPIRED   0x2
878

    
879
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
880
{
881
    return t->flags & ALARM_FLAG_DYNTICKS;
882
}
883

    
884
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
885
{
886
    if (!alarm_has_dynticks(t))
887
        return;
888

    
889
    t->rearm(t);
890
}
891

    
892
/* TODO: MIN_TIMER_REARM_US should be optimized */
893
#define MIN_TIMER_REARM_US 250
894

    
895
static struct qemu_alarm_timer *alarm_timer;
896
#ifndef _WIN32
897
static int alarm_timer_rfd, alarm_timer_wfd;
898
#endif
899

    
900
#ifdef _WIN32
901

    
902
struct qemu_alarm_win32 {
903
    MMRESULT timerId;
904
    HANDLE host_alarm;
905
    unsigned int period;
906
} alarm_win32_data = {0, NULL, -1};
907

    
908
static int win32_start_timer(struct qemu_alarm_timer *t);
909
static void win32_stop_timer(struct qemu_alarm_timer *t);
910
static void win32_rearm_timer(struct qemu_alarm_timer *t);
911

    
912
#else
913

    
914
static int unix_start_timer(struct qemu_alarm_timer *t);
915
static void unix_stop_timer(struct qemu_alarm_timer *t);
916

    
917
#ifdef __linux__
918

    
919
static int dynticks_start_timer(struct qemu_alarm_timer *t);
920
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
921
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
922

    
923
static int hpet_start_timer(struct qemu_alarm_timer *t);
924
static void hpet_stop_timer(struct qemu_alarm_timer *t);
925

    
926
static int rtc_start_timer(struct qemu_alarm_timer *t);
927
static void rtc_stop_timer(struct qemu_alarm_timer *t);
928

    
929
#endif /* __linux__ */
930

    
931
#endif /* _WIN32 */
932

    
933
/* Correlation between real and virtual time is always going to be
934
   fairly approximate, so ignore small variation.
935
   When the guest is idle real and virtual time will be aligned in
936
   the IO wait loop.  */
937
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
938

    
939
static void icount_adjust(void)
940
{
941
    int64_t cur_time;
942
    int64_t cur_icount;
943
    int64_t delta;
944
    static int64_t last_delta;
945
    /* If the VM is not running, then do nothing.  */
946
    if (!vm_running)
947
        return;
948

    
949
    cur_time = cpu_get_clock();
950
    cur_icount = qemu_get_clock(vm_clock);
951
    delta = cur_icount - cur_time;
952
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
953
    if (delta > 0
954
        && last_delta + ICOUNT_WOBBLE < delta * 2
955
        && icount_time_shift > 0) {
956
        /* The guest is getting too far ahead.  Slow time down.  */
957
        icount_time_shift--;
958
    }
959
    if (delta < 0
960
        && last_delta - ICOUNT_WOBBLE > delta * 2
961
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
962
        /* The guest is getting too far behind.  Speed time up.  */
963
        icount_time_shift++;
964
    }
965
    last_delta = delta;
966
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
967
}
968

    
969
static void icount_adjust_rt(void * opaque)
970
{
971
    qemu_mod_timer(icount_rt_timer,
972
                   qemu_get_clock(rt_clock) + 1000);
973
    icount_adjust();
974
}
975

    
976
static void icount_adjust_vm(void * opaque)
977
{
978
    qemu_mod_timer(icount_vm_timer,
979
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
980
    icount_adjust();
981
}
982

    
983
static void init_icount_adjust(void)
984
{
985
    /* Have both realtime and virtual time triggers for speed adjustment.
986
       The realtime trigger catches emulated time passing too slowly,
987
       the virtual time trigger catches emulated time passing too fast.
988
       Realtime triggers occur even when idle, so use them less frequently
989
       than VM triggers.  */
990
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
991
    qemu_mod_timer(icount_rt_timer,
992
                   qemu_get_clock(rt_clock) + 1000);
993
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
994
    qemu_mod_timer(icount_vm_timer,
995
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
996
}
997

    
998
static struct qemu_alarm_timer alarm_timers[] = {
999
#ifndef _WIN32
1000
#ifdef __linux__
1001
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1002
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
1003
    /* HPET - if available - is preferred */
1004
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1005
    /* ...otherwise try RTC */
1006
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1007
#endif
1008
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1009
#else
1010
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1011
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1012
    {"win32", 0, win32_start_timer,
1013
     win32_stop_timer, NULL, &alarm_win32_data},
1014
#endif
1015
    {NULL, }
1016
};
1017

    
1018
static void show_available_alarms(void)
1019
{
1020
    int i;
1021

    
1022
    printf("Available alarm timers, in order of precedence:\n");
1023
    for (i = 0; alarm_timers[i].name; i++)
1024
        printf("%s\n", alarm_timers[i].name);
1025
}
1026

    
1027
static void configure_alarms(char const *opt)
1028
{
1029
    int i;
1030
    int cur = 0;
1031
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1032
    char *arg;
1033
    char *name;
1034
    struct qemu_alarm_timer tmp;
1035

    
1036
    if (!strcmp(opt, "?")) {
1037
        show_available_alarms();
1038
        exit(0);
1039
    }
1040

    
1041
    arg = strdup(opt);
1042

    
1043
    /* Reorder the array */
1044
    name = strtok(arg, ",");
1045
    while (name) {
1046
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1047
            if (!strcmp(alarm_timers[i].name, name))
1048
                break;
1049
        }
1050

    
1051
        if (i == count) {
1052
            fprintf(stderr, "Unknown clock %s\n", name);
1053
            goto next;
1054
        }
1055

    
1056
        if (i < cur)
1057
            /* Ignore */
1058
            goto next;
1059

    
1060
        /* Swap */
1061
        tmp = alarm_timers[i];
1062
        alarm_timers[i] = alarm_timers[cur];
1063
        alarm_timers[cur] = tmp;
1064

    
1065
        cur++;
1066
next:
1067
        name = strtok(NULL, ",");
1068
    }
1069

    
1070
    free(arg);
1071

    
1072
    if (cur) {
1073
        /* Disable remaining timers */
1074
        for (i = cur; i < count; i++)
1075
            alarm_timers[i].name = NULL;
1076
    } else {
1077
        show_available_alarms();
1078
        exit(1);
1079
    }
1080
}
1081

    
1082
QEMUClock *rt_clock;
1083
QEMUClock *vm_clock;
1084

    
1085
static QEMUTimer *active_timers[2];
1086

    
1087
static QEMUClock *qemu_new_clock(int type)
1088
{
1089
    QEMUClock *clock;
1090
    clock = qemu_mallocz(sizeof(QEMUClock));
1091
    if (!clock)
1092
        return NULL;
1093
    clock->type = type;
1094
    return clock;
1095
}
1096

    
1097
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1098
{
1099
    QEMUTimer *ts;
1100

    
1101
    ts = qemu_mallocz(sizeof(QEMUTimer));
1102
    ts->clock = clock;
1103
    ts->cb = cb;
1104
    ts->opaque = opaque;
1105
    return ts;
1106
}
1107

    
1108
void qemu_free_timer(QEMUTimer *ts)
1109
{
1110
    qemu_free(ts);
1111
}
1112

    
1113
/* stop a timer, but do not dealloc it */
1114
void qemu_del_timer(QEMUTimer *ts)
1115
{
1116
    QEMUTimer **pt, *t;
1117

    
1118
    /* NOTE: this code must be signal safe because
1119
       qemu_timer_expired() can be called from a signal. */
1120
    pt = &active_timers[ts->clock->type];
1121
    for(;;) {
1122
        t = *pt;
1123
        if (!t)
1124
            break;
1125
        if (t == ts) {
1126
            *pt = t->next;
1127
            break;
1128
        }
1129
        pt = &t->next;
1130
    }
1131
}
1132

    
1133
/* modify the current timer so that it will be fired when current_time
1134
   >= expire_time. The corresponding callback will be called. */
1135
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1136
{
1137
    QEMUTimer **pt, *t;
1138

    
1139
    qemu_del_timer(ts);
1140

    
1141
    /* add the timer in the sorted list */
1142
    /* NOTE: this code must be signal safe because
1143
       qemu_timer_expired() can be called from a signal. */
1144
    pt = &active_timers[ts->clock->type];
1145
    for(;;) {
1146
        t = *pt;
1147
        if (!t)
1148
            break;
1149
        if (t->expire_time > expire_time)
1150
            break;
1151
        pt = &t->next;
1152
    }
1153
    ts->expire_time = expire_time;
1154
    ts->next = *pt;
1155
    *pt = ts;
1156

    
1157
    /* Rearm if necessary  */
1158
    if (pt == &active_timers[ts->clock->type]) {
1159
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1160
            qemu_rearm_alarm_timer(alarm_timer);
1161
        }
1162
        /* Interrupt execution to force deadline recalculation.  */
1163
        if (use_icount && cpu_single_env) {
1164
            cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1165
        }
1166
    }
1167
}
1168

    
1169
int qemu_timer_pending(QEMUTimer *ts)
1170
{
1171
    QEMUTimer *t;
1172
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1173
        if (t == ts)
1174
            return 1;
1175
    }
1176
    return 0;
1177
}
1178

    
1179
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1180
{
1181
    if (!timer_head)
1182
        return 0;
1183
    return (timer_head->expire_time <= current_time);
1184
}
1185

    
1186
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1187
{
1188
    QEMUTimer *ts;
1189

    
1190
    for(;;) {
1191
        ts = *ptimer_head;
1192
        if (!ts || ts->expire_time > current_time)
1193
            break;
1194
        /* remove timer from the list before calling the callback */
1195
        *ptimer_head = ts->next;
1196
        ts->next = NULL;
1197

    
1198
        /* run the callback (the timer list can be modified) */
1199
        ts->cb(ts->opaque);
1200
    }
1201
}
1202

    
1203
int64_t qemu_get_clock(QEMUClock *clock)
1204
{
1205
    switch(clock->type) {
1206
    case QEMU_TIMER_REALTIME:
1207
        return get_clock() / 1000000;
1208
    default:
1209
    case QEMU_TIMER_VIRTUAL:
1210
        if (use_icount) {
1211
            return cpu_get_icount();
1212
        } else {
1213
            return cpu_get_clock();
1214
        }
1215
    }
1216
}
1217

    
1218
static void init_timers(void)
1219
{
1220
    init_get_clock();
1221
    ticks_per_sec = QEMU_TIMER_BASE;
1222
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1223
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1224
}
1225

    
1226
/* save a timer */
1227
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1228
{
1229
    uint64_t expire_time;
1230

    
1231
    if (qemu_timer_pending(ts)) {
1232
        expire_time = ts->expire_time;
1233
    } else {
1234
        expire_time = -1;
1235
    }
1236
    qemu_put_be64(f, expire_time);
1237
}
1238

    
1239
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1240
{
1241
    uint64_t expire_time;
1242

    
1243
    expire_time = qemu_get_be64(f);
1244
    if (expire_time != -1) {
1245
        qemu_mod_timer(ts, expire_time);
1246
    } else {
1247
        qemu_del_timer(ts);
1248
    }
1249
}
1250

    
1251
static void timer_save(QEMUFile *f, void *opaque)
1252
{
1253
    if (cpu_ticks_enabled) {
1254
        hw_error("cannot save state if virtual timers are running");
1255
    }
1256
    qemu_put_be64(f, cpu_ticks_offset);
1257
    qemu_put_be64(f, ticks_per_sec);
1258
    qemu_put_be64(f, cpu_clock_offset);
1259
}
1260

    
1261
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1262
{
1263
    if (version_id != 1 && version_id != 2)
1264
        return -EINVAL;
1265
    if (cpu_ticks_enabled) {
1266
        return -EINVAL;
1267
    }
1268
    cpu_ticks_offset=qemu_get_be64(f);
1269
    ticks_per_sec=qemu_get_be64(f);
1270
    if (version_id == 2) {
1271
        cpu_clock_offset=qemu_get_be64(f);
1272
    }
1273
    return 0;
1274
}
1275

    
1276
#ifdef _WIN32
1277
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1278
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1279
#else
1280
static void host_alarm_handler(int host_signum)
1281
#endif
1282
{
1283
#if 0
1284
#define DISP_FREQ 1000
1285
    {
1286
        static int64_t delta_min = INT64_MAX;
1287
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1288
        static int count;
1289
        ti = qemu_get_clock(vm_clock);
1290
        if (last_clock != 0) {
1291
            delta = ti - last_clock;
1292
            if (delta < delta_min)
1293
                delta_min = delta;
1294
            if (delta > delta_max)
1295
                delta_max = delta;
1296
            delta_cum += delta;
1297
            if (++count == DISP_FREQ) {
1298
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1299
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1300
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1301
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1302
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1303
                count = 0;
1304
                delta_min = INT64_MAX;
1305
                delta_max = 0;
1306
                delta_cum = 0;
1307
            }
1308
        }
1309
        last_clock = ti;
1310
    }
1311
#endif
1312
    if (alarm_has_dynticks(alarm_timer) ||
1313
        (!use_icount &&
1314
            qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1315
                               qemu_get_clock(vm_clock))) ||
1316
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1317
                           qemu_get_clock(rt_clock))) {
1318
        CPUState *env = next_cpu;
1319

    
1320
#ifdef _WIN32
1321
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1322
        SetEvent(data->host_alarm);
1323
#else
1324
        static const char byte = 0;
1325
        write(alarm_timer_wfd, &byte, sizeof(byte));
1326
#endif
1327
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1328

    
1329
        if (env) {
1330
            /* stop the currently executing cpu because a timer occured */
1331
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1332
#ifdef USE_KQEMU
1333
            if (env->kqemu_enabled) {
1334
                kqemu_cpu_interrupt(env);
1335
            }
1336
#endif
1337
        }
1338
        event_pending = 1;
1339
    }
1340
}
1341

    
1342
static int64_t qemu_next_deadline(void)
1343
{
1344
    int64_t delta;
1345

    
1346
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1347
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1348
                     qemu_get_clock(vm_clock);
1349
    } else {
1350
        /* To avoid problems with overflow limit this to 2^32.  */
1351
        delta = INT32_MAX;
1352
    }
1353

    
1354
    if (delta < 0)
1355
        delta = 0;
1356

    
1357
    return delta;
1358
}
1359

    
1360
#if defined(__linux__) || defined(_WIN32)
1361
static uint64_t qemu_next_deadline_dyntick(void)
1362
{
1363
    int64_t delta;
1364
    int64_t rtdelta;
1365

    
1366
    if (use_icount)
1367
        delta = INT32_MAX;
1368
    else
1369
        delta = (qemu_next_deadline() + 999) / 1000;
1370

    
1371
    if (active_timers[QEMU_TIMER_REALTIME]) {
1372
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1373
                 qemu_get_clock(rt_clock))*1000;
1374
        if (rtdelta < delta)
1375
            delta = rtdelta;
1376
    }
1377

    
1378
    if (delta < MIN_TIMER_REARM_US)
1379
        delta = MIN_TIMER_REARM_US;
1380

    
1381
    return delta;
1382
}
1383
#endif
1384

    
1385
#ifndef _WIN32
1386

    
1387
/* Sets a specific flag */
1388
static int fcntl_setfl(int fd, int flag)
1389
{
1390
    int flags;
1391

    
1392
    flags = fcntl(fd, F_GETFL);
1393
    if (flags == -1)
1394
        return -errno;
1395

    
1396
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1397
        return -errno;
1398

    
1399
    return 0;
1400
}
1401

    
1402
#if defined(__linux__)
1403

    
1404
#define RTC_FREQ 1024
1405

    
1406
static void enable_sigio_timer(int fd)
1407
{
1408
    struct sigaction act;
1409

    
1410
    /* timer signal */
1411
    sigfillset(&act.sa_mask);
1412
    act.sa_flags = 0;
1413
    act.sa_handler = host_alarm_handler;
1414

    
1415
    sigaction(SIGIO, &act, NULL);
1416
    fcntl_setfl(fd, O_ASYNC);
1417
    fcntl(fd, F_SETOWN, getpid());
1418
}
1419

    
1420
static int hpet_start_timer(struct qemu_alarm_timer *t)
1421
{
1422
    struct hpet_info info;
1423
    int r, fd;
1424

    
1425
    fd = open("/dev/hpet", O_RDONLY);
1426
    if (fd < 0)
1427
        return -1;
1428

    
1429
    /* Set frequency */
1430
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1431
    if (r < 0) {
1432
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1433
                "error, but for better emulation accuracy type:\n"
1434
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1435
        goto fail;
1436
    }
1437

    
1438
    /* Check capabilities */
1439
    r = ioctl(fd, HPET_INFO, &info);
1440
    if (r < 0)
1441
        goto fail;
1442

    
1443
    /* Enable periodic mode */
1444
    r = ioctl(fd, HPET_EPI, 0);
1445
    if (info.hi_flags && (r < 0))
1446
        goto fail;
1447

    
1448
    /* Enable interrupt */
1449
    r = ioctl(fd, HPET_IE_ON, 0);
1450
    if (r < 0)
1451
        goto fail;
1452

    
1453
    enable_sigio_timer(fd);
1454
    t->priv = (void *)(long)fd;
1455

    
1456
    return 0;
1457
fail:
1458
    close(fd);
1459
    return -1;
1460
}
1461

    
1462
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1463
{
1464
    int fd = (long)t->priv;
1465

    
1466
    close(fd);
1467
}
1468

    
1469
static int rtc_start_timer(struct qemu_alarm_timer *t)
1470
{
1471
    int rtc_fd;
1472
    unsigned long current_rtc_freq = 0;
1473

    
1474
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1475
    if (rtc_fd < 0)
1476
        return -1;
1477
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1478
    if (current_rtc_freq != RTC_FREQ &&
1479
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1480
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1481
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1482
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1483
        goto fail;
1484
    }
1485
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1486
    fail:
1487
        close(rtc_fd);
1488
        return -1;
1489
    }
1490

    
1491
    enable_sigio_timer(rtc_fd);
1492

    
1493
    t->priv = (void *)(long)rtc_fd;
1494

    
1495
    return 0;
1496
}
1497

    
1498
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1499
{
1500
    int rtc_fd = (long)t->priv;
1501

    
1502
    close(rtc_fd);
1503
}
1504

    
1505
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1506
{
1507
    struct sigevent ev;
1508
    timer_t host_timer;
1509
    struct sigaction act;
1510

    
1511
    sigfillset(&act.sa_mask);
1512
    act.sa_flags = 0;
1513
    act.sa_handler = host_alarm_handler;
1514

    
1515
    sigaction(SIGALRM, &act, NULL);
1516

    
1517
    ev.sigev_value.sival_int = 0;
1518
    ev.sigev_notify = SIGEV_SIGNAL;
1519
    ev.sigev_signo = SIGALRM;
1520

    
1521
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1522
        perror("timer_create");
1523

    
1524
        /* disable dynticks */
1525
        fprintf(stderr, "Dynamic Ticks disabled\n");
1526

    
1527
        return -1;
1528
    }
1529

    
1530
    t->priv = (void *)(long)host_timer;
1531

    
1532
    return 0;
1533
}
1534

    
1535
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1536
{
1537
    timer_t host_timer = (timer_t)(long)t->priv;
1538

    
1539
    timer_delete(host_timer);
1540
}
1541

    
1542
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1543
{
1544
    timer_t host_timer = (timer_t)(long)t->priv;
1545
    struct itimerspec timeout;
1546
    int64_t nearest_delta_us = INT64_MAX;
1547
    int64_t current_us;
1548

    
1549
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1550
                !active_timers[QEMU_TIMER_VIRTUAL])
1551
        return;
1552

    
1553
    nearest_delta_us = qemu_next_deadline_dyntick();
1554

    
1555
    /* check whether a timer is already running */
1556
    if (timer_gettime(host_timer, &timeout)) {
1557
        perror("gettime");
1558
        fprintf(stderr, "Internal timer error: aborting\n");
1559
        exit(1);
1560
    }
1561
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1562
    if (current_us && current_us <= nearest_delta_us)
1563
        return;
1564

    
1565
    timeout.it_interval.tv_sec = 0;
1566
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1567
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1568
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1569
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1570
        perror("settime");
1571
        fprintf(stderr, "Internal timer error: aborting\n");
1572
        exit(1);
1573
    }
1574
}
1575

    
1576
#endif /* defined(__linux__) */
1577

    
1578
static int unix_start_timer(struct qemu_alarm_timer *t)
1579
{
1580
    struct sigaction act;
1581
    struct itimerval itv;
1582
    int err;
1583

    
1584
    /* timer signal */
1585
    sigfillset(&act.sa_mask);
1586
    act.sa_flags = 0;
1587
    act.sa_handler = host_alarm_handler;
1588

    
1589
    sigaction(SIGALRM, &act, NULL);
1590

    
1591
    itv.it_interval.tv_sec = 0;
1592
    /* for i386 kernel 2.6 to get 1 ms */
1593
    itv.it_interval.tv_usec = 999;
1594
    itv.it_value.tv_sec = 0;
1595
    itv.it_value.tv_usec = 10 * 1000;
1596

    
1597
    err = setitimer(ITIMER_REAL, &itv, NULL);
1598
    if (err)
1599
        return -1;
1600

    
1601
    return 0;
1602
}
1603

    
1604
static void unix_stop_timer(struct qemu_alarm_timer *t)
1605
{
1606
    struct itimerval itv;
1607

    
1608
    memset(&itv, 0, sizeof(itv));
1609
    setitimer(ITIMER_REAL, &itv, NULL);
1610
}
1611

    
1612
#endif /* !defined(_WIN32) */
1613

    
1614
static void try_to_rearm_timer(void *opaque)
1615
{
1616
    struct qemu_alarm_timer *t = opaque;
1617
#ifndef _WIN32
1618
    ssize_t len;
1619

    
1620
    /* Drain the notify pipe */
1621
    do {
1622
        char buffer[512];
1623
        len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1624
    } while ((len == -1 && errno == EINTR) || len > 0);
1625
#endif
1626

    
1627
    if (t->flags & ALARM_FLAG_EXPIRED) {
1628
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1629
        qemu_rearm_alarm_timer(alarm_timer);
1630
    }
1631
}
1632

    
1633
#ifdef _WIN32
1634

    
1635
static int win32_start_timer(struct qemu_alarm_timer *t)
1636
{
1637
    TIMECAPS tc;
1638
    struct qemu_alarm_win32 *data = t->priv;
1639
    UINT flags;
1640

    
1641
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1642
    if (!data->host_alarm) {
1643
        perror("Failed CreateEvent");
1644
        return -1;
1645
    }
1646

    
1647
    memset(&tc, 0, sizeof(tc));
1648
    timeGetDevCaps(&tc, sizeof(tc));
1649

    
1650
    if (data->period < tc.wPeriodMin)
1651
        data->period = tc.wPeriodMin;
1652

    
1653
    timeBeginPeriod(data->period);
1654

    
1655
    flags = TIME_CALLBACK_FUNCTION;
1656
    if (alarm_has_dynticks(t))
1657
        flags |= TIME_ONESHOT;
1658
    else
1659
        flags |= TIME_PERIODIC;
1660

    
1661
    data->timerId = timeSetEvent(1,         // interval (ms)
1662
                        data->period,       // resolution
1663
                        host_alarm_handler, // function
1664
                        (DWORD)t,           // parameter
1665
                        flags);
1666

    
1667
    if (!data->timerId) {
1668
        perror("Failed to initialize win32 alarm timer");
1669

    
1670
        timeEndPeriod(data->period);
1671
        CloseHandle(data->host_alarm);
1672
        return -1;
1673
    }
1674

    
1675
    qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1676

    
1677
    return 0;
1678
}
1679

    
1680
static void win32_stop_timer(struct qemu_alarm_timer *t)
1681
{
1682
    struct qemu_alarm_win32 *data = t->priv;
1683

    
1684
    timeKillEvent(data->timerId);
1685
    timeEndPeriod(data->period);
1686

    
1687
    CloseHandle(data->host_alarm);
1688
}
1689

    
1690
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1691
{
1692
    struct qemu_alarm_win32 *data = t->priv;
1693
    uint64_t nearest_delta_us;
1694

    
1695
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1696
                !active_timers[QEMU_TIMER_VIRTUAL])
1697
        return;
1698

    
1699
    nearest_delta_us = qemu_next_deadline_dyntick();
1700
    nearest_delta_us /= 1000;
1701

    
1702
    timeKillEvent(data->timerId);
1703

    
1704
    data->timerId = timeSetEvent(1,
1705
                        data->period,
1706
                        host_alarm_handler,
1707
                        (DWORD)t,
1708
                        TIME_ONESHOT | TIME_PERIODIC);
1709

    
1710
    if (!data->timerId) {
1711
        perror("Failed to re-arm win32 alarm timer");
1712

    
1713
        timeEndPeriod(data->period);
1714
        CloseHandle(data->host_alarm);
1715
        exit(1);
1716
    }
1717
}
1718

    
1719
#endif /* _WIN32 */
1720

    
1721
static int init_timer_alarm(void)
1722
{
1723
    struct qemu_alarm_timer *t = NULL;
1724
    int i, err = -1;
1725

    
1726
#ifndef _WIN32
1727
    int fds[2];
1728

    
1729
    err = pipe(fds);
1730
    if (err == -1)
1731
        return -errno;
1732

    
1733
    err = fcntl_setfl(fds[0], O_NONBLOCK);
1734
    if (err < 0)
1735
        goto fail;
1736

    
1737
    err = fcntl_setfl(fds[1], O_NONBLOCK);
1738
    if (err < 0)
1739
        goto fail;
1740

    
1741
    alarm_timer_rfd = fds[0];
1742
    alarm_timer_wfd = fds[1];
1743
#endif
1744

    
1745
    for (i = 0; alarm_timers[i].name; i++) {
1746
        t = &alarm_timers[i];
1747

    
1748
        err = t->start(t);
1749
        if (!err)
1750
            break;
1751
    }
1752

    
1753
    if (err) {
1754
        err = -ENOENT;
1755
        goto fail;
1756
    }
1757

    
1758
#ifndef _WIN32
1759
    qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1760
                         try_to_rearm_timer, NULL, t);
1761
#endif
1762

    
1763
    alarm_timer = t;
1764

    
1765
    return 0;
1766

    
1767
fail:
1768
#ifndef _WIN32
1769
    close(fds[0]);
1770
    close(fds[1]);
1771
#endif
1772
    return err;
1773
}
1774

    
1775
static void quit_timers(void)
1776
{
1777
    alarm_timer->stop(alarm_timer);
1778
    alarm_timer = NULL;
1779
}
1780

    
1781
/***********************************************************/
1782
/* host time/date access */
1783
void qemu_get_timedate(struct tm *tm, int offset)
1784
{
1785
    time_t ti;
1786
    struct tm *ret;
1787

    
1788
    time(&ti);
1789
    ti += offset;
1790
    if (rtc_date_offset == -1) {
1791
        if (rtc_utc)
1792
            ret = gmtime(&ti);
1793
        else
1794
            ret = localtime(&ti);
1795
    } else {
1796
        ti -= rtc_date_offset;
1797
        ret = gmtime(&ti);
1798
    }
1799

    
1800
    memcpy(tm, ret, sizeof(struct tm));
1801
}
1802

    
1803
int qemu_timedate_diff(struct tm *tm)
1804
{
1805
    time_t seconds;
1806

    
1807
    if (rtc_date_offset == -1)
1808
        if (rtc_utc)
1809
            seconds = mktimegm(tm);
1810
        else
1811
            seconds = mktime(tm);
1812
    else
1813
        seconds = mktimegm(tm) + rtc_date_offset;
1814

    
1815
    return seconds - time(NULL);
1816
}
1817

    
1818
#ifdef _WIN32
1819
static void socket_cleanup(void)
1820
{
1821
    WSACleanup();
1822
}
1823

    
1824
static int socket_init(void)
1825
{
1826
    WSADATA Data;
1827
    int ret, err;
1828

    
1829
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1830
    if (ret != 0) {
1831
        err = WSAGetLastError();
1832
        fprintf(stderr, "WSAStartup: %d\n", err);
1833
        return -1;
1834
    }
1835
    atexit(socket_cleanup);
1836
    return 0;
1837
}
1838
#endif
1839

    
1840
const char *get_opt_name(char *buf, int buf_size, const char *p)
1841
{
1842
    char *q;
1843

    
1844
    q = buf;
1845
    while (*p != '\0' && *p != '=') {
1846
        if (q && (q - buf) < buf_size - 1)
1847
            *q++ = *p;
1848
        p++;
1849
    }
1850
    if (q)
1851
        *q = '\0';
1852

    
1853
    return p;
1854
}
1855

    
1856
const char *get_opt_value(char *buf, int buf_size, const char *p)
1857
{
1858
    char *q;
1859

    
1860
    q = buf;
1861
    while (*p != '\0') {
1862
        if (*p == ',') {
1863
            if (*(p + 1) != ',')
1864
                break;
1865
            p++;
1866
        }
1867
        if (q && (q - buf) < buf_size - 1)
1868
            *q++ = *p;
1869
        p++;
1870
    }
1871
    if (q)
1872
        *q = '\0';
1873

    
1874
    return p;
1875
}
1876

    
1877
int get_param_value(char *buf, int buf_size,
1878
                    const char *tag, const char *str)
1879
{
1880
    const char *p;
1881
    char option[128];
1882

    
1883
    p = str;
1884
    for(;;) {
1885
        p = get_opt_name(option, sizeof(option), p);
1886
        if (*p != '=')
1887
            break;
1888
        p++;
1889
        if (!strcmp(tag, option)) {
1890
            (void)get_opt_value(buf, buf_size, p);
1891
            return strlen(buf);
1892
        } else {
1893
            p = get_opt_value(NULL, 0, p);
1894
        }
1895
        if (*p != ',')
1896
            break;
1897
        p++;
1898
    }
1899
    return 0;
1900
}
1901

    
1902
int check_params(char *buf, int buf_size,
1903
                 const char * const *params, const char *str)
1904
{
1905
    const char *p;
1906
    int i;
1907

    
1908
    p = str;
1909
    for(;;) {
1910
        p = get_opt_name(buf, buf_size, p);
1911
        if (*p != '=')
1912
            return -1;
1913
        p++;
1914
        for(i = 0; params[i] != NULL; i++)
1915
            if (!strcmp(params[i], buf))
1916
                break;
1917
        if (params[i] == NULL)
1918
            return -1;
1919
        p = get_opt_value(NULL, 0, p);
1920
        if (*p != ',')
1921
            break;
1922
        p++;
1923
    }
1924
    return 0;
1925
}
1926

    
1927
/***********************************************************/
1928
/* Bluetooth support */
1929
static int nb_hcis;
1930
static int cur_hci;
1931
static struct HCIInfo *hci_table[MAX_NICS];
1932

    
1933
static struct bt_vlan_s {
1934
    struct bt_scatternet_s net;
1935
    int id;
1936
    struct bt_vlan_s *next;
1937
} *first_bt_vlan;
1938

    
1939
/* find or alloc a new bluetooth "VLAN" */
1940
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1941
{
1942
    struct bt_vlan_s **pvlan, *vlan;
1943
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1944
        if (vlan->id == id)
1945
            return &vlan->net;
1946
    }
1947
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1948
    vlan->id = id;
1949
    pvlan = &first_bt_vlan;
1950
    while (*pvlan != NULL)
1951
        pvlan = &(*pvlan)->next;
1952
    *pvlan = vlan;
1953
    return &vlan->net;
1954
}
1955

    
1956
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1957
{
1958
}
1959

    
1960
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1961
{
1962
    return -ENOTSUP;
1963
}
1964

    
1965
static struct HCIInfo null_hci = {
1966
    .cmd_send = null_hci_send,
1967
    .sco_send = null_hci_send,
1968
    .acl_send = null_hci_send,
1969
    .bdaddr_set = null_hci_addr_set,
1970
};
1971

    
1972
struct HCIInfo *qemu_next_hci(void)
1973
{
1974
    if (cur_hci == nb_hcis)
1975
        return &null_hci;
1976

    
1977
    return hci_table[cur_hci++];
1978
}
1979

    
1980
static struct HCIInfo *hci_init(const char *str)
1981
{
1982
    char *endp;
1983
    struct bt_scatternet_s *vlan = 0;
1984

    
1985
    if (!strcmp(str, "null"))
1986
        /* null */
1987
        return &null_hci;
1988
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1989
        /* host[:hciN] */
1990
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1991
    else if (!strncmp(str, "hci", 3)) {
1992
        /* hci[,vlan=n] */
1993
        if (str[3]) {
1994
            if (!strncmp(str + 3, ",vlan=", 6)) {
1995
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1996
                if (*endp)
1997
                    vlan = 0;
1998
            }
1999
        } else
2000
            vlan = qemu_find_bt_vlan(0);
2001
        if (vlan)
2002
           return bt_new_hci(vlan);
2003
    }
2004

    
2005
    fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
2006

    
2007
    return 0;
2008
}
2009

    
2010
static int bt_hci_parse(const char *str)
2011
{
2012
    struct HCIInfo *hci;
2013
    bdaddr_t bdaddr;
2014

    
2015
    if (nb_hcis >= MAX_NICS) {
2016
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2017
        return -1;
2018
    }
2019

    
2020
    hci = hci_init(str);
2021
    if (!hci)
2022
        return -1;
2023

    
2024
    bdaddr.b[0] = 0x52;
2025
    bdaddr.b[1] = 0x54;
2026
    bdaddr.b[2] = 0x00;
2027
    bdaddr.b[3] = 0x12;
2028
    bdaddr.b[4] = 0x34;
2029
    bdaddr.b[5] = 0x56 + nb_hcis;
2030
    hci->bdaddr_set(hci, bdaddr.b);
2031

    
2032
    hci_table[nb_hcis++] = hci;
2033

    
2034
    return 0;
2035
}
2036

    
2037
static void bt_vhci_add(int vlan_id)
2038
{
2039
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2040

    
2041
    if (!vlan->slave)
2042
        fprintf(stderr, "qemu: warning: adding a VHCI to "
2043
                        "an empty scatternet %i\n", vlan_id);
2044

    
2045
    bt_vhci_init(bt_new_hci(vlan));
2046
}
2047

    
2048
static struct bt_device_s *bt_device_add(const char *opt)
2049
{
2050
    struct bt_scatternet_s *vlan;
2051
    int vlan_id = 0;
2052
    char *endp = strstr(opt, ",vlan=");
2053
    int len = (endp ? endp - opt : strlen(opt)) + 1;
2054
    char devname[10];
2055

    
2056
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
2057

    
2058
    if (endp) {
2059
        vlan_id = strtol(endp + 6, &endp, 0);
2060
        if (*endp) {
2061
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2062
            return 0;
2063
        }
2064
    }
2065

    
2066
    vlan = qemu_find_bt_vlan(vlan_id);
2067

    
2068
    if (!vlan->slave)
2069
        fprintf(stderr, "qemu: warning: adding a slave device to "
2070
                        "an empty scatternet %i\n", vlan_id);
2071

    
2072
    if (!strcmp(devname, "keyboard"))
2073
        return bt_keyboard_init(vlan);
2074

    
2075
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2076
    return 0;
2077
}
2078

    
2079
static int bt_parse(const char *opt)
2080
{
2081
    const char *endp, *p;
2082
    int vlan;
2083

    
2084
    if (strstart(opt, "hci", &endp)) {
2085
        if (!*endp || *endp == ',') {
2086
            if (*endp)
2087
                if (!strstart(endp, ",vlan=", 0))
2088
                    opt = endp + 1;
2089

    
2090
            return bt_hci_parse(opt);
2091
       }
2092
    } else if (strstart(opt, "vhci", &endp)) {
2093
        if (!*endp || *endp == ',') {
2094
            if (*endp) {
2095
                if (strstart(endp, ",vlan=", &p)) {
2096
                    vlan = strtol(p, (char **) &endp, 0);
2097
                    if (*endp) {
2098
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2099
                        return 1;
2100
                    }
2101
                } else {
2102
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2103
                    return 1;
2104
                }
2105
            } else
2106
                vlan = 0;
2107

    
2108
            bt_vhci_add(vlan);
2109
            return 0;
2110
        }
2111
    } else if (strstart(opt, "device:", &endp))
2112
        return !bt_device_add(endp);
2113

    
2114
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2115
    return 1;
2116
}
2117

    
2118
/***********************************************************/
2119
/* QEMU Block devices */
2120

    
2121
#define HD_ALIAS "index=%d,media=disk"
2122
#ifdef TARGET_PPC
2123
#define CDROM_ALIAS "index=1,media=cdrom"
2124
#else
2125
#define CDROM_ALIAS "index=2,media=cdrom"
2126
#endif
2127
#define FD_ALIAS "index=%d,if=floppy"
2128
#define PFLASH_ALIAS "if=pflash"
2129
#define MTD_ALIAS "if=mtd"
2130
#define SD_ALIAS "index=0,if=sd"
2131

    
2132
static int drive_add(const char *file, const char *fmt, ...)
2133
{
2134
    va_list ap;
2135

    
2136
    if (nb_drives_opt >= MAX_DRIVES) {
2137
        fprintf(stderr, "qemu: too many drives\n");
2138
        exit(1);
2139
    }
2140

    
2141
    drives_opt[nb_drives_opt].file = file;
2142
    va_start(ap, fmt);
2143
    vsnprintf(drives_opt[nb_drives_opt].opt,
2144
              sizeof(drives_opt[0].opt), fmt, ap);
2145
    va_end(ap);
2146

    
2147
    return nb_drives_opt++;
2148
}
2149

    
2150
int drive_get_index(BlockInterfaceType type, int bus, int unit)
2151
{
2152
    int index;
2153

    
2154
    /* seek interface, bus and unit */
2155

    
2156
    for (index = 0; index < nb_drives; index++)
2157
        if (drives_table[index].type == type &&
2158
            drives_table[index].bus == bus &&
2159
            drives_table[index].unit == unit)
2160
        return index;
2161

    
2162
    return -1;
2163
}
2164

    
2165
int drive_get_max_bus(BlockInterfaceType type)
2166
{
2167
    int max_bus;
2168
    int index;
2169

    
2170
    max_bus = -1;
2171
    for (index = 0; index < nb_drives; index++) {
2172
        if(drives_table[index].type == type &&
2173
           drives_table[index].bus > max_bus)
2174
            max_bus = drives_table[index].bus;
2175
    }
2176
    return max_bus;
2177
}
2178

    
2179
static void bdrv_format_print(void *opaque, const char *name)
2180
{
2181
    fprintf(stderr, " %s", name);
2182
}
2183

    
2184
static int drive_init(struct drive_opt *arg, int snapshot,
2185
                      QEMUMachine *machine)
2186
{
2187
    char buf[128];
2188
    char file[1024];
2189
    char devname[128];
2190
    const char *mediastr = "";
2191
    BlockInterfaceType type;
2192
    enum { MEDIA_DISK, MEDIA_CDROM } media;
2193
    int bus_id, unit_id;
2194
    int cyls, heads, secs, translation;
2195
    BlockDriverState *bdrv;
2196
    BlockDriver *drv = NULL;
2197
    int max_devs;
2198
    int index;
2199
    int cache;
2200
    int bdrv_flags;
2201
    char *str = arg->opt;
2202
    static const char * const params[] = { "bus", "unit", "if", "index",
2203
                                           "cyls", "heads", "secs", "trans",
2204
                                           "media", "snapshot", "file",
2205
                                           "cache", "format", NULL };
2206

    
2207
    if (check_params(buf, sizeof(buf), params, str) < 0) {
2208
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2209
                         buf, str);
2210
         return -1;
2211
    }
2212

    
2213
    file[0] = 0;
2214
    cyls = heads = secs = 0;
2215
    bus_id = 0;
2216
    unit_id = -1;
2217
    translation = BIOS_ATA_TRANSLATION_AUTO;
2218
    index = -1;
2219
    cache = 1;
2220

    
2221
    if (machine->use_scsi) {
2222
        type = IF_SCSI;
2223
        max_devs = MAX_SCSI_DEVS;
2224
        pstrcpy(devname, sizeof(devname), "scsi");
2225
    } else {
2226
        type = IF_IDE;
2227
        max_devs = MAX_IDE_DEVS;
2228
        pstrcpy(devname, sizeof(devname), "ide");
2229
    }
2230
    media = MEDIA_DISK;
2231

    
2232
    /* extract parameters */
2233

    
2234
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
2235
        bus_id = strtol(buf, NULL, 0);
2236
        if (bus_id < 0) {
2237
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2238
            return -1;
2239
        }
2240
    }
2241

    
2242
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
2243
        unit_id = strtol(buf, NULL, 0);
2244
        if (unit_id < 0) {
2245
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2246
            return -1;
2247
        }
2248
    }
2249

    
2250
    if (get_param_value(buf, sizeof(buf), "if", str)) {
2251
        pstrcpy(devname, sizeof(devname), buf);
2252
        if (!strcmp(buf, "ide")) {
2253
            type = IF_IDE;
2254
            max_devs = MAX_IDE_DEVS;
2255
        } else if (!strcmp(buf, "scsi")) {
2256
            type = IF_SCSI;
2257
            max_devs = MAX_SCSI_DEVS;
2258
        } else if (!strcmp(buf, "floppy")) {
2259
            type = IF_FLOPPY;
2260
            max_devs = 0;
2261
        } else if (!strcmp(buf, "pflash")) {
2262
            type = IF_PFLASH;
2263
            max_devs = 0;
2264
        } else if (!strcmp(buf, "mtd")) {
2265
            type = IF_MTD;
2266
            max_devs = 0;
2267
        } else if (!strcmp(buf, "sd")) {
2268
            type = IF_SD;
2269
            max_devs = 0;
2270
        } else if (!strcmp(buf, "virtio")) {
2271
            type = IF_VIRTIO;
2272
            max_devs = 0;
2273
        } else {
2274
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2275
            return -1;
2276
        }
2277
    }
2278

    
2279
    if (get_param_value(buf, sizeof(buf), "index", str)) {
2280
        index = strtol(buf, NULL, 0);
2281
        if (index < 0) {
2282
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
2283
            return -1;
2284
        }
2285
    }
2286

    
2287
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2288
        cyls = strtol(buf, NULL, 0);
2289
    }
2290

    
2291
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
2292
        heads = strtol(buf, NULL, 0);
2293
    }
2294

    
2295
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
2296
        secs = strtol(buf, NULL, 0);
2297
    }
2298

    
2299
    if (cyls || heads || secs) {
2300
        if (cyls < 1 || cyls > 16383) {
2301
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2302
            return -1;
2303
        }
2304
        if (heads < 1 || heads > 16) {
2305
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2306
            return -1;
2307
        }
2308
        if (secs < 1 || secs > 63) {
2309
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2310
            return -1;
2311
        }
2312
    }
2313

    
2314
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
2315
        if (!cyls) {
2316
            fprintf(stderr,
2317
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2318
                    str);
2319
            return -1;
2320
        }
2321
        if (!strcmp(buf, "none"))
2322
            translation = BIOS_ATA_TRANSLATION_NONE;
2323
        else if (!strcmp(buf, "lba"))
2324
            translation = BIOS_ATA_TRANSLATION_LBA;
2325
        else if (!strcmp(buf, "auto"))
2326
            translation = BIOS_ATA_TRANSLATION_AUTO;
2327
        else {
2328
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2329
            return -1;
2330
        }
2331
    }
2332

    
2333
    if (get_param_value(buf, sizeof(buf), "media", str)) {
2334
        if (!strcmp(buf, "disk")) {
2335
            media = MEDIA_DISK;
2336
        } else if (!strcmp(buf, "cdrom")) {
2337
            if (cyls || secs || heads) {
2338
                fprintf(stderr,
2339
                        "qemu: '%s' invalid physical CHS format\n", str);
2340
                return -1;
2341
            }
2342
            media = MEDIA_CDROM;
2343
        } else {
2344
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
2345
            return -1;
2346
        }
2347
    }
2348

    
2349
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2350
        if (!strcmp(buf, "on"))
2351
            snapshot = 1;
2352
        else if (!strcmp(buf, "off"))
2353
            snapshot = 0;
2354
        else {
2355
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2356
            return -1;
2357
        }
2358
    }
2359

    
2360
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
2361
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2362
            cache = 0;
2363
        else if (!strcmp(buf, "writethrough"))
2364
            cache = 1;
2365
        else if (!strcmp(buf, "writeback"))
2366
            cache = 2;
2367
        else {
2368
           fprintf(stderr, "qemu: invalid cache option\n");
2369
           return -1;
2370
        }
2371
    }
2372

    
2373
    if (get_param_value(buf, sizeof(buf), "format", str)) {
2374
       if (strcmp(buf, "?") == 0) {
2375
            fprintf(stderr, "qemu: Supported formats:");
2376
            bdrv_iterate_format(bdrv_format_print, NULL);
2377
            fprintf(stderr, "\n");
2378
            return -1;
2379
        }
2380
        drv = bdrv_find_format(buf);
2381
        if (!drv) {
2382
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2383
            return -1;
2384
        }
2385
    }
2386

    
2387
    if (arg->file == NULL)
2388
        get_param_value(file, sizeof(file), "file", str);
2389
    else
2390
        pstrcpy(file, sizeof(file), arg->file);
2391

    
2392
    /* compute bus and unit according index */
2393

    
2394
    if (index != -1) {
2395
        if (bus_id != 0 || unit_id != -1) {
2396
            fprintf(stderr,
2397
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
2398
            return -1;
2399
        }
2400
        if (max_devs == 0)
2401
        {
2402
            unit_id = index;
2403
            bus_id = 0;
2404
        } else {
2405
            unit_id = index % max_devs;
2406
            bus_id = index / max_devs;
2407
        }
2408
    }
2409

    
2410
    /* if user doesn't specify a unit_id,
2411
     * try to find the first free
2412
     */
2413

    
2414
    if (unit_id == -1) {
2415
       unit_id = 0;
2416
       while (drive_get_index(type, bus_id, unit_id) != -1) {
2417
           unit_id++;
2418
           if (max_devs && unit_id >= max_devs) {
2419
               unit_id -= max_devs;
2420
               bus_id++;
2421
           }
2422
       }
2423
    }
2424

    
2425
    /* check unit id */
2426

    
2427
    if (max_devs && unit_id >= max_devs) {
2428
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2429
                        str, unit_id, max_devs - 1);
2430
        return -1;
2431
    }
2432

    
2433
    /*
2434
     * ignore multiple definitions
2435
     */
2436

    
2437
    if (drive_get_index(type, bus_id, unit_id) != -1)
2438
        return 0;
2439

    
2440
    /* init */
2441

    
2442
    if (type == IF_IDE || type == IF_SCSI)
2443
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2444
    if (max_devs)
2445
        snprintf(buf, sizeof(buf), "%s%i%s%i",
2446
                 devname, bus_id, mediastr, unit_id);
2447
    else
2448
        snprintf(buf, sizeof(buf), "%s%s%i",
2449
                 devname, mediastr, unit_id);
2450
    bdrv = bdrv_new(buf);
2451
    drives_table[nb_drives].bdrv = bdrv;
2452
    drives_table[nb_drives].type = type;
2453
    drives_table[nb_drives].bus = bus_id;
2454
    drives_table[nb_drives].unit = unit_id;
2455
    nb_drives++;
2456

    
2457
    switch(type) {
2458
    case IF_IDE:
2459
    case IF_SCSI:
2460
        switch(media) {
2461
        case MEDIA_DISK:
2462
            if (cyls != 0) {
2463
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2464
                bdrv_set_translation_hint(bdrv, translation);
2465
            }
2466
            break;
2467
        case MEDIA_CDROM:
2468
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2469
            break;
2470
        }
2471
        break;
2472
    case IF_SD:
2473
        /* FIXME: This isn't really a floppy, but it's a reasonable
2474
           approximation.  */
2475
    case IF_FLOPPY:
2476
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2477
        break;
2478
    case IF_PFLASH:
2479
    case IF_MTD:
2480
    case IF_VIRTIO:
2481
        break;
2482
    }
2483
    if (!file[0])
2484
        return 0;
2485
    bdrv_flags = 0;
2486
    if (snapshot) {
2487
        bdrv_flags |= BDRV_O_SNAPSHOT;
2488
        cache = 2; /* always use write-back with snapshot */
2489
    }
2490
    if (cache == 0) /* no caching */
2491
        bdrv_flags |= BDRV_O_NOCACHE;
2492
    else if (cache == 2) /* write-back */
2493
        bdrv_flags |= BDRV_O_CACHE_WB;
2494
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2495
        fprintf(stderr, "qemu: could not open disk image %s\n",
2496
                        file);
2497
        return -1;
2498
    }
2499
    return 0;
2500
}
2501

    
2502
/***********************************************************/
2503
/* USB devices */
2504

    
2505
static USBPort *used_usb_ports;
2506
static USBPort *free_usb_ports;
2507

    
2508
/* ??? Maybe change this to register a hub to keep track of the topology.  */
2509
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2510
                            usb_attachfn attach)
2511
{
2512
    port->opaque = opaque;
2513
    port->index = index;
2514
    port->attach = attach;
2515
    port->next = free_usb_ports;
2516
    free_usb_ports = port;
2517
}
2518

    
2519
int usb_device_add_dev(USBDevice *dev)
2520
{
2521
    USBPort *port;
2522

    
2523
    /* Find a USB port to add the device to.  */
2524
    port = free_usb_ports;
2525
    if (!port->next) {
2526
        USBDevice *hub;
2527

    
2528
        /* Create a new hub and chain it on.  */
2529
        free_usb_ports = NULL;
2530
        port->next = used_usb_ports;
2531
        used_usb_ports = port;
2532

    
2533
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2534
        usb_attach(port, hub);
2535
        port = free_usb_ports;
2536
    }
2537

    
2538
    free_usb_ports = port->next;
2539
    port->next = used_usb_ports;
2540
    used_usb_ports = port;
2541
    usb_attach(port, dev);
2542
    return 0;
2543
}
2544

    
2545
static int usb_device_add(const char *devname)
2546
{
2547
    const char *p;
2548
    USBDevice *dev;
2549

    
2550
    if (!free_usb_ports)
2551
        return -1;
2552

    
2553
    if (strstart(devname, "host:", &p)) {
2554
        dev = usb_host_device_open(p);
2555
    } else if (!strcmp(devname, "mouse")) {
2556
        dev = usb_mouse_init();
2557
    } else if (!strcmp(devname, "tablet")) {
2558
        dev = usb_tablet_init();
2559
    } else if (!strcmp(devname, "keyboard")) {
2560
        dev = usb_keyboard_init();
2561
    } else if (strstart(devname, "disk:", &p)) {
2562
        dev = usb_msd_init(p);
2563
    } else if (!strcmp(devname, "wacom-tablet")) {
2564
        dev = usb_wacom_init();
2565
    } else if (strstart(devname, "serial:", &p)) {
2566
        dev = usb_serial_init(p);
2567
#ifdef CONFIG_BRLAPI
2568
    } else if (!strcmp(devname, "braille")) {
2569
        dev = usb_baum_init();
2570
#endif
2571
    } else if (strstart(devname, "net:", &p)) {
2572
        int nic = nb_nics;
2573

    
2574
        if (net_client_init("nic", p) < 0)
2575
            return -1;
2576
        nd_table[nic].model = "usb";
2577
        dev = usb_net_init(&nd_table[nic]);
2578
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2579
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2580
                        bt_new_hci(qemu_find_bt_vlan(0)));
2581
    } else {
2582
        return -1;
2583
    }
2584
    if (!dev)
2585
        return -1;
2586

    
2587
    return usb_device_add_dev(dev);
2588
}
2589

    
2590
int usb_device_del_addr(int bus_num, int addr)
2591
{
2592
    USBPort *port;
2593
    USBPort **lastp;
2594
    USBDevice *dev;
2595

    
2596
    if (!used_usb_ports)
2597
        return -1;
2598

    
2599
    if (bus_num != 0)
2600
        return -1;
2601

    
2602
    lastp = &used_usb_ports;
2603
    port = used_usb_ports;
2604
    while (port && port->dev->addr != addr) {
2605
        lastp = &port->next;
2606
        port = port->next;
2607
    }
2608

    
2609
    if (!port)
2610
        return -1;
2611

    
2612
    dev = port->dev;
2613
    *lastp = port->next;
2614
    usb_attach(port, NULL);
2615
    dev->handle_destroy(dev);
2616
    port->next = free_usb_ports;
2617
    free_usb_ports = port;
2618
    return 0;
2619
}
2620

    
2621
static int usb_device_del(const char *devname)
2622
{
2623
    int bus_num, addr;
2624
    const char *p;
2625

    
2626
    if (strstart(devname, "host:", &p))
2627
        return usb_host_device_close(p);
2628

    
2629
    if (!used_usb_ports)
2630
        return -1;
2631

    
2632
    p = strchr(devname, '.');
2633
    if (!p)
2634
        return -1;
2635
    bus_num = strtoul(devname, NULL, 0);
2636
    addr = strtoul(p + 1, NULL, 0);
2637

    
2638
    return usb_device_del_addr(bus_num, addr);
2639
}
2640

    
2641
void do_usb_add(const char *devname)
2642
{
2643
    usb_device_add(devname);
2644
}
2645

    
2646
void do_usb_del(const char *devname)
2647
{
2648
    usb_device_del(devname);
2649
}
2650

    
2651
void usb_info(void)
2652
{
2653
    USBDevice *dev;
2654
    USBPort *port;
2655
    const char *speed_str;
2656

    
2657
    if (!usb_enabled) {
2658
        term_printf("USB support not enabled\n");
2659
        return;
2660
    }
2661

    
2662
    for (port = used_usb_ports; port; port = port->next) {
2663
        dev = port->dev;
2664
        if (!dev)
2665
            continue;
2666
        switch(dev->speed) {
2667
        case USB_SPEED_LOW:
2668
            speed_str = "1.5";
2669
            break;
2670
        case USB_SPEED_FULL:
2671
            speed_str = "12";
2672
            break;
2673
        case USB_SPEED_HIGH:
2674
            speed_str = "480";
2675
            break;
2676
        default:
2677
            speed_str = "?";
2678
            break;
2679
        }
2680
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
2681
                    0, dev->addr, speed_str, dev->devname);
2682
    }
2683
}
2684

    
2685
/***********************************************************/
2686
/* PCMCIA/Cardbus */
2687

    
2688
static struct pcmcia_socket_entry_s {
2689
    struct pcmcia_socket_s *socket;
2690
    struct pcmcia_socket_entry_s *next;
2691
} *pcmcia_sockets = 0;
2692

    
2693
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2694
{
2695
    struct pcmcia_socket_entry_s *entry;
2696

    
2697
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2698
    entry->socket = socket;
2699
    entry->next = pcmcia_sockets;
2700
    pcmcia_sockets = entry;
2701
}
2702

    
2703
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2704
{
2705
    struct pcmcia_socket_entry_s *entry, **ptr;
2706

    
2707
    ptr = &pcmcia_sockets;
2708
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2709
        if (entry->socket == socket) {
2710
            *ptr = entry->next;
2711
            qemu_free(entry);
2712
        }
2713
}
2714

    
2715
void pcmcia_info(void)
2716
{
2717
    struct pcmcia_socket_entry_s *iter;
2718
    if (!pcmcia_sockets)
2719
        term_printf("No PCMCIA sockets\n");
2720

    
2721
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2722
        term_printf("%s: %s\n", iter->socket->slot_string,
2723
                    iter->socket->attached ? iter->socket->card_string :
2724
                    "Empty");
2725
}
2726

    
2727
/***********************************************************/
2728
/* dumb display */
2729

    
2730
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2731
{
2732
}
2733

    
2734
static void dumb_resize(DisplayState *ds, int w, int h)
2735
{
2736
}
2737

    
2738
static void dumb_display_init(DisplayState *ds)
2739
{
2740
    ds->data = NULL;
2741
    ds->linesize = 0;
2742
    ds->depth = 0;
2743
    ds->dpy_update = dumb_update;
2744
    ds->dpy_resize = dumb_resize;
2745
    ds->dpy_refresh = NULL;
2746
    ds->gui_timer_interval = 0;
2747
    ds->idle = 1;
2748
}
2749

    
2750
/***********************************************************/
2751
/* I/O handling */
2752

    
2753
#define MAX_IO_HANDLERS 64
2754

    
2755
typedef struct IOHandlerRecord {
2756
    int fd;
2757
    IOCanRWHandler *fd_read_poll;
2758
    IOHandler *fd_read;
2759
    IOHandler *fd_write;
2760
    int deleted;
2761
    void *opaque;
2762
    /* temporary data */
2763
    struct pollfd *ufd;
2764
    struct IOHandlerRecord *next;
2765
} IOHandlerRecord;
2766

    
2767
static IOHandlerRecord *first_io_handler;
2768

    
2769
/* XXX: fd_read_poll should be suppressed, but an API change is
2770
   necessary in the character devices to suppress fd_can_read(). */
2771
int qemu_set_fd_handler2(int fd,
2772
                         IOCanRWHandler *fd_read_poll,
2773
                         IOHandler *fd_read,
2774
                         IOHandler *fd_write,
2775
                         void *opaque)
2776
{
2777
    IOHandlerRecord **pioh, *ioh;
2778

    
2779
    if (!fd_read && !fd_write) {
2780
        pioh = &first_io_handler;
2781
        for(;;) {
2782
            ioh = *pioh;
2783
            if (ioh == NULL)
2784
                break;
2785
            if (ioh->fd == fd) {
2786
                ioh->deleted = 1;
2787
                break;
2788
            }
2789
            pioh = &ioh->next;
2790
        }
2791
    } else {
2792
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2793
            if (ioh->fd == fd)
2794
                goto found;
2795
        }
2796
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2797
        if (!ioh)
2798
            return -1;
2799
        ioh->next = first_io_handler;
2800
        first_io_handler = ioh;
2801
    found:
2802
        ioh->fd = fd;
2803
        ioh->fd_read_poll = fd_read_poll;
2804
        ioh->fd_read = fd_read;
2805
        ioh->fd_write = fd_write;
2806
        ioh->opaque = opaque;
2807
        ioh->deleted = 0;
2808
    }
2809
    return 0;
2810
}
2811

    
2812
int qemu_set_fd_handler(int fd,
2813
                        IOHandler *fd_read,
2814
                        IOHandler *fd_write,
2815
                        void *opaque)
2816
{
2817
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2818
}
2819

    
2820
#ifdef _WIN32
2821
/***********************************************************/
2822
/* Polling handling */
2823

    
2824
typedef struct PollingEntry {
2825
    PollingFunc *func;
2826
    void *opaque;
2827
    struct PollingEntry *next;
2828
} PollingEntry;
2829

    
2830
static PollingEntry *first_polling_entry;
2831

    
2832
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2833
{
2834
    PollingEntry **ppe, *pe;
2835
    pe = qemu_mallocz(sizeof(PollingEntry));
2836
    if (!pe)
2837
        return -1;
2838
    pe->func = func;
2839
    pe->opaque = opaque;
2840
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2841
    *ppe = pe;
2842
    return 0;
2843
}
2844

    
2845
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2846
{
2847
    PollingEntry **ppe, *pe;
2848
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2849
        pe = *ppe;
2850
        if (pe->func == func && pe->opaque == opaque) {
2851
            *ppe = pe->next;
2852
            qemu_free(pe);
2853
            break;
2854
        }
2855
    }
2856
}
2857

    
2858
/***********************************************************/
2859
/* Wait objects support */
2860
typedef struct WaitObjects {
2861
    int num;
2862
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2863
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2864
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2865
} WaitObjects;
2866

    
2867
static WaitObjects wait_objects = {0};
2868

    
2869
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2870
{
2871
    WaitObjects *w = &wait_objects;
2872

    
2873
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2874
        return -1;
2875
    w->events[w->num] = handle;
2876
    w->func[w->num] = func;
2877
    w->opaque[w->num] = opaque;
2878
    w->num++;
2879
    return 0;
2880
}
2881

    
2882
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2883
{
2884
    int i, found;
2885
    WaitObjects *w = &wait_objects;
2886

    
2887
    found = 0;
2888
    for (i = 0; i < w->num; i++) {
2889
        if (w->events[i] == handle)
2890
            found = 1;
2891
        if (found) {
2892
            w->events[i] = w->events[i + 1];
2893
            w->func[i] = w->func[i + 1];
2894
            w->opaque[i] = w->opaque[i + 1];
2895
        }
2896
    }
2897
    if (found)
2898
        w->num--;
2899
}
2900
#endif
2901

    
2902
/***********************************************************/
2903
/* ram save/restore */
2904

    
2905
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2906
{
2907
    int v;
2908

    
2909
    v = qemu_get_byte(f);
2910
    switch(v) {
2911
    case 0:
2912
        if (qemu_get_buffer(f, buf, len) != len)
2913
            return -EIO;
2914
        break;
2915
    case 1:
2916
        v = qemu_get_byte(f);
2917
        memset(buf, v, len);
2918
        break;
2919
    default:
2920
        return -EINVAL;
2921
    }
2922

    
2923
    if (qemu_file_has_error(f))
2924
        return -EIO;
2925

    
2926
    return 0;
2927
}
2928

    
2929
static int ram_load_v1(QEMUFile *f, void *opaque)
2930
{
2931
    int ret;
2932
    ram_addr_t i;
2933

    
2934
    if (qemu_get_be32(f) != phys_ram_size)
2935
        return -EINVAL;
2936
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2937
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2938
        if (ret)
2939
            return ret;
2940
    }
2941
    return 0;
2942
}
2943

    
2944
#define BDRV_HASH_BLOCK_SIZE 1024
2945
#define IOBUF_SIZE 4096
2946
#define RAM_CBLOCK_MAGIC 0xfabe
2947

    
2948
typedef struct RamDecompressState {
2949
    z_stream zstream;
2950
    QEMUFile *f;
2951
    uint8_t buf[IOBUF_SIZE];
2952
} RamDecompressState;
2953

    
2954
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2955
{
2956
    int ret;
2957
    memset(s, 0, sizeof(*s));
2958
    s->f = f;
2959
    ret = inflateInit(&s->zstream);
2960
    if (ret != Z_OK)
2961
        return -1;
2962
    return 0;
2963
}
2964

    
2965
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2966
{
2967
    int ret, clen;
2968

    
2969
    s->zstream.avail_out = len;
2970
    s->zstream.next_out = buf;
2971
    while (s->zstream.avail_out > 0) {
2972
        if (s->zstream.avail_in == 0) {
2973
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2974
                return -1;
2975
            clen = qemu_get_be16(s->f);
2976
            if (clen > IOBUF_SIZE)
2977
                return -1;
2978
            qemu_get_buffer(s->f, s->buf, clen);
2979
            s->zstream.avail_in = clen;
2980
            s->zstream.next_in = s->buf;
2981
        }
2982
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2983
        if (ret != Z_OK && ret != Z_STREAM_END) {
2984
            return -1;
2985
        }
2986
    }
2987
    return 0;
2988
}
2989

    
2990
static void ram_decompress_close(RamDecompressState *s)
2991
{
2992
    inflateEnd(&s->zstream);
2993
}
2994

    
2995
#define RAM_SAVE_FLAG_FULL        0x01
2996
#define RAM_SAVE_FLAG_COMPRESS        0x02
2997
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2998
#define RAM_SAVE_FLAG_PAGE        0x08
2999
#define RAM_SAVE_FLAG_EOS        0x10
3000

    
3001
static int is_dup_page(uint8_t *page, uint8_t ch)
3002
{
3003
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3004
    uint32_t *array = (uint32_t *)page;
3005
    int i;
3006

    
3007
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3008
        if (array[i] != val)
3009
            return 0;
3010
    }
3011

    
3012
    return 1;
3013
}
3014

    
3015
static int ram_save_block(QEMUFile *f)
3016
{
3017
    static ram_addr_t current_addr = 0;
3018
    ram_addr_t saved_addr = current_addr;
3019
    ram_addr_t addr = 0;
3020
    int found = 0;
3021

    
3022
    while (addr < phys_ram_size) {
3023
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3024
            uint8_t ch;
3025

    
3026
            cpu_physical_memory_reset_dirty(current_addr,
3027
                                            current_addr + TARGET_PAGE_SIZE,
3028
                                            MIGRATION_DIRTY_FLAG);
3029

    
3030
            ch = *(phys_ram_base + current_addr);
3031

    
3032
            if (is_dup_page(phys_ram_base + current_addr, ch)) {
3033
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3034
                qemu_put_byte(f, ch);
3035
            } else {
3036
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3037
                qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3038
            }
3039

    
3040
            found = 1;
3041
            break;
3042
        }
3043
        addr += TARGET_PAGE_SIZE;
3044
        current_addr = (saved_addr + addr) % phys_ram_size;
3045
    }
3046

    
3047
    return found;
3048
}
3049

    
3050
static ram_addr_t ram_save_threshold = 10;
3051

    
3052
static ram_addr_t ram_save_remaining(void)
3053
{
3054
    ram_addr_t addr;
3055
    ram_addr_t count = 0;
3056

    
3057
    for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3058
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3059
            count++;
3060
    }
3061

    
3062
    return count;
3063
}
3064

    
3065
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3066
{
3067
    ram_addr_t addr;
3068

    
3069
    if (stage == 1) {
3070
        /* Make sure all dirty bits are set */
3071
        for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3072
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3073
                cpu_physical_memory_set_dirty(addr);
3074
        }
3075
        
3076
        /* Enable dirty memory tracking */
3077
        cpu_physical_memory_set_dirty_tracking(1);
3078

    
3079
        qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3080
    }
3081

    
3082
    while (!qemu_file_rate_limit(f)) {
3083
        int ret;
3084

    
3085
        ret = ram_save_block(f);
3086
        if (ret == 0) /* no more blocks */
3087
            break;
3088
    }
3089

    
3090
    /* try transferring iterative blocks of memory */
3091

    
3092
    if (stage == 3) {
3093
        cpu_physical_memory_set_dirty_tracking(0);
3094

    
3095
        /* flush all remaining blocks regardless of rate limiting */
3096
        while (ram_save_block(f) != 0);
3097
    }
3098

    
3099
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3100

    
3101
    return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3102
}
3103

    
3104
static int ram_load_dead(QEMUFile *f, void *opaque)
3105
{
3106
    RamDecompressState s1, *s = &s1;
3107
    uint8_t buf[10];
3108
    ram_addr_t i;
3109

    
3110
    if (ram_decompress_open(s, f) < 0)
3111
        return -EINVAL;
3112
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3113
        if (ram_decompress_buf(s, buf, 1) < 0) {
3114
            fprintf(stderr, "Error while reading ram block header\n");
3115
            goto error;
3116
        }
3117
        if (buf[0] == 0) {
3118
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3119
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3120
                goto error;
3121
            }
3122
        } else {
3123
        error:
3124
            printf("Error block header\n");
3125
            return -EINVAL;
3126
        }
3127
    }
3128
    ram_decompress_close(s);
3129

    
3130
    return 0;
3131
}
3132

    
3133
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3134
{
3135
    ram_addr_t addr;
3136
    int flags;
3137

    
3138
    if (version_id == 1)
3139
        return ram_load_v1(f, opaque);
3140

    
3141
    if (version_id == 2) {
3142
        if (qemu_get_be32(f) != phys_ram_size)
3143
            return -EINVAL;
3144
        return ram_load_dead(f, opaque);
3145
    }
3146

    
3147
    if (version_id != 3)
3148
        return -EINVAL;
3149

    
3150
    do {
3151
        addr = qemu_get_be64(f);
3152

    
3153
        flags = addr & ~TARGET_PAGE_MASK;
3154
        addr &= TARGET_PAGE_MASK;
3155

    
3156
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3157
            if (addr != phys_ram_size)
3158
                return -EINVAL;
3159
        }
3160

    
3161
        if (flags & RAM_SAVE_FLAG_FULL) {
3162
            if (ram_load_dead(f, opaque) < 0)
3163
                return -EINVAL;
3164
        }
3165
        
3166
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
3167
            uint8_t ch = qemu_get_byte(f);
3168
            memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3169
        } else if (flags & RAM_SAVE_FLAG_PAGE)
3170
            qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3171
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3172

    
3173
    return 0;
3174
}
3175

    
3176
void qemu_service_io(void)
3177
{
3178
    CPUState *env = cpu_single_env;
3179
    if (env) {
3180
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3181
#ifdef USE_KQEMU
3182
        if (env->kqemu_enabled) {
3183
            kqemu_cpu_interrupt(env);
3184
        }
3185
#endif
3186
    }
3187
}
3188

    
3189
/***********************************************************/
3190
/* bottom halves (can be seen as timers which expire ASAP) */
3191

    
3192
struct QEMUBH {
3193
    QEMUBHFunc *cb;
3194
    void *opaque;
3195
    int scheduled;
3196
    int idle;
3197
    int deleted;
3198
    QEMUBH *next;
3199
};
3200

    
3201
static QEMUBH *first_bh = NULL;
3202

    
3203
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3204
{
3205
    QEMUBH *bh;
3206
    bh = qemu_mallocz(sizeof(QEMUBH));
3207
    if (!bh)
3208
        return NULL;
3209
    bh->cb = cb;
3210
    bh->opaque = opaque;
3211
    bh->next = first_bh;
3212
    first_bh = bh;
3213
    return bh;
3214
}
3215

    
3216
int qemu_bh_poll(void)
3217
{
3218
    QEMUBH *bh, **bhp;
3219
    int ret;
3220

    
3221
    ret = 0;
3222
    for (bh = first_bh; bh; bh = bh->next) {
3223
        if (!bh->deleted && bh->scheduled) {
3224
            bh->scheduled = 0;
3225
            if (!bh->idle)
3226
                ret = 1;
3227
            bh->idle = 0;
3228
            bh->cb(bh->opaque);
3229
        }
3230
    }
3231

    
3232
    /* remove deleted bhs */
3233
    bhp = &first_bh;
3234
    while (*bhp) {
3235
        bh = *bhp;
3236
        if (bh->deleted) {
3237
            *bhp = bh->next;
3238
            qemu_free(bh);
3239
        } else
3240
            bhp = &bh->next;
3241
    }
3242

    
3243
    return ret;
3244
}
3245

    
3246
void qemu_bh_schedule_idle(QEMUBH *bh)
3247
{
3248
    if (bh->scheduled)
3249
        return;
3250
    bh->scheduled = 1;
3251
    bh->idle = 1;
3252
}
3253

    
3254
void qemu_bh_schedule(QEMUBH *bh)
3255
{
3256
    CPUState *env = cpu_single_env;
3257
    if (bh->scheduled)
3258
        return;
3259
    bh->scheduled = 1;
3260
    bh->idle = 0;
3261
    /* stop the currently executing CPU to execute the BH ASAP */
3262
    if (env) {
3263
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3264
    }
3265
}
3266

    
3267
void qemu_bh_cancel(QEMUBH *bh)
3268
{
3269
    bh->scheduled = 0;
3270
}
3271

    
3272
void qemu_bh_delete(QEMUBH *bh)
3273
{
3274
    bh->scheduled = 0;
3275
    bh->deleted = 1;
3276
}
3277

    
3278
static void qemu_bh_update_timeout(int *timeout)
3279
{
3280
    QEMUBH *bh;
3281

    
3282
    for (bh = first_bh; bh; bh = bh->next) {
3283
        if (!bh->deleted && bh->scheduled) {
3284
            if (bh->idle) {
3285
                /* idle bottom halves will be polled at least
3286
                 * every 10ms */
3287
                *timeout = MIN(10, *timeout);
3288
            } else {
3289
                /* non-idle bottom halves will be executed
3290
                 * immediately */
3291
                *timeout = 0;
3292
                break;
3293
            }
3294
        }
3295
    }
3296
}
3297

    
3298
/***********************************************************/
3299
/* machine registration */
3300

    
3301
static QEMUMachine *first_machine = NULL;
3302

    
3303
int qemu_register_machine(QEMUMachine *m)
3304
{
3305
    QEMUMachine **pm;
3306
    pm = &first_machine;
3307
    while (*pm != NULL)
3308
        pm = &(*pm)->next;
3309
    m->next = NULL;
3310
    *pm = m;
3311
    return 0;
3312
}
3313

    
3314
static QEMUMachine *find_machine(const char *name)
3315
{
3316
    QEMUMachine *m;
3317

    
3318
    for(m = first_machine; m != NULL; m = m->next) {
3319
        if (!strcmp(m->name, name))
3320
            return m;
3321
    }
3322
    return NULL;
3323
}
3324

    
3325
/***********************************************************/
3326
/* main execution loop */
3327

    
3328
static void gui_update(void *opaque)
3329
{
3330
    DisplayState *ds = opaque;
3331
    ds->dpy_refresh(ds);
3332
    qemu_mod_timer(ds->gui_timer,
3333
        (ds->gui_timer_interval ?
3334
            ds->gui_timer_interval :
3335
            GUI_REFRESH_INTERVAL)
3336
        + qemu_get_clock(rt_clock));
3337
}
3338

    
3339
struct vm_change_state_entry {
3340
    VMChangeStateHandler *cb;
3341
    void *opaque;
3342
    LIST_ENTRY (vm_change_state_entry) entries;
3343
};
3344

    
3345
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3346

    
3347
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3348
                                                     void *opaque)
3349
{
3350
    VMChangeStateEntry *e;
3351

    
3352
    e = qemu_mallocz(sizeof (*e));
3353
    if (!e)
3354
        return NULL;
3355

    
3356
    e->cb = cb;
3357
    e->opaque = opaque;
3358
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3359
    return e;
3360
}
3361

    
3362
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3363
{
3364
    LIST_REMOVE (e, entries);
3365
    qemu_free (e);
3366
}
3367

    
3368
static void vm_state_notify(int running)
3369
{
3370
    VMChangeStateEntry *e;
3371

    
3372
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3373
        e->cb(e->opaque, running);
3374
    }
3375
}
3376

    
3377
/* XXX: support several handlers */
3378
static VMStopHandler *vm_stop_cb;
3379
static void *vm_stop_opaque;
3380

    
3381
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3382
{
3383
    vm_stop_cb = cb;
3384
    vm_stop_opaque = opaque;
3385
    return 0;
3386
}
3387

    
3388
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3389
{
3390
    vm_stop_cb = NULL;
3391
}
3392

    
3393
void vm_start(void)
3394
{
3395
    if (!vm_running) {
3396
        cpu_enable_ticks();
3397
        vm_running = 1;
3398
        vm_state_notify(1);
3399
        qemu_rearm_alarm_timer(alarm_timer);
3400
    }
3401
}
3402

    
3403
void vm_stop(int reason)
3404
{
3405
    if (vm_running) {
3406
        cpu_disable_ticks();
3407
        vm_running = 0;
3408
        if (reason != 0) {
3409
            if (vm_stop_cb) {
3410
                vm_stop_cb(vm_stop_opaque, reason);
3411
            }
3412
        }
3413
        vm_state_notify(0);
3414
    }
3415
}
3416

    
3417
/* reset/shutdown handler */
3418

    
3419
typedef struct QEMUResetEntry {
3420
    QEMUResetHandler *func;
3421
    void *opaque;
3422
    struct QEMUResetEntry *next;
3423
} QEMUResetEntry;
3424

    
3425
static QEMUResetEntry *first_reset_entry;
3426
static int reset_requested;
3427
static int shutdown_requested;
3428
static int powerdown_requested;
3429

    
3430
int qemu_shutdown_requested(void)
3431
{
3432
    int r = shutdown_requested;
3433
    shutdown_requested = 0;
3434
    return r;
3435
}
3436

    
3437
int qemu_reset_requested(void)
3438
{
3439
    int r = reset_requested;
3440
    reset_requested = 0;
3441
    return r;
3442
}
3443

    
3444
int qemu_powerdown_requested(void)
3445
{
3446
    int r = powerdown_requested;
3447
    powerdown_requested = 0;
3448
    return r;
3449
}
3450

    
3451
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3452
{
3453
    QEMUResetEntry **pre, *re;
3454

    
3455
    pre = &first_reset_entry;
3456
    while (*pre != NULL)
3457
        pre = &(*pre)->next;
3458
    re = qemu_mallocz(sizeof(QEMUResetEntry));
3459
    re->func = func;
3460
    re->opaque = opaque;
3461
    re->next = NULL;
3462
    *pre = re;
3463
}
3464

    
3465
void qemu_system_reset(void)
3466
{
3467
    QEMUResetEntry *re;
3468

    
3469
    /* reset all devices */
3470
    for(re = first_reset_entry; re != NULL; re = re->next) {
3471
        re->func(re->opaque);
3472
    }
3473
}
3474

    
3475
void qemu_system_reset_request(void)
3476
{
3477
    if (no_reboot) {
3478
        shutdown_requested = 1;
3479
    } else {
3480
        reset_requested = 1;
3481
    }
3482
    if (cpu_single_env)
3483
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3484
}
3485

    
3486
void qemu_system_shutdown_request(void)
3487
{
3488
    shutdown_requested = 1;
3489
    if (cpu_single_env)
3490
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3491
}
3492

    
3493
void qemu_system_powerdown_request(void)
3494
{
3495
    powerdown_requested = 1;
3496
    if (cpu_single_env)
3497
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3498
}
3499

    
3500
#ifdef _WIN32
3501
void host_main_loop_wait(int *timeout)
3502
{
3503
    int ret, ret2, i;
3504
    PollingEntry *pe;
3505

    
3506

    
3507
    /* XXX: need to suppress polling by better using win32 events */
3508
    ret = 0;
3509
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3510
        ret |= pe->func(pe->opaque);
3511
    }
3512
    if (ret == 0) {
3513
        int err;
3514
        WaitObjects *w = &wait_objects;
3515

    
3516
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3517
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3518
            if (w->func[ret - WAIT_OBJECT_0])
3519
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3520

    
3521
            /* Check for additional signaled events */
3522
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3523

    
3524
                /* Check if event is signaled */
3525
                ret2 = WaitForSingleObject(w->events[i], 0);
3526
                if(ret2 == WAIT_OBJECT_0) {
3527
                    if (w->func[i])
3528
                        w->func[i](w->opaque[i]);
3529
                } else if (ret2 == WAIT_TIMEOUT) {
3530
                } else {
3531
                    err = GetLastError();
3532
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3533
                }
3534
            }
3535
        } else if (ret == WAIT_TIMEOUT) {
3536
        } else {
3537
            err = GetLastError();
3538
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3539
        }
3540
    }
3541

    
3542
    *timeout = 0;
3543
}
3544
#else
3545
void host_main_loop_wait(int *timeout)
3546
{
3547
}
3548
#endif
3549

    
3550
void main_loop_wait(int timeout)
3551
{
3552
    IOHandlerRecord *ioh;
3553
    fd_set rfds, wfds, xfds;
3554
    int ret, nfds;
3555
    struct timeval tv;
3556

    
3557
    qemu_bh_update_timeout(&timeout);
3558

    
3559
    host_main_loop_wait(&timeout);
3560

    
3561
    /* poll any events */
3562
    /* XXX: separate device handlers from system ones */
3563
    nfds = -1;
3564
    FD_ZERO(&rfds);
3565
    FD_ZERO(&wfds);
3566
    FD_ZERO(&xfds);
3567
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3568
        if (ioh->deleted)
3569
            continue;
3570
        if (ioh->fd_read &&
3571
            (!ioh->fd_read_poll ||
3572
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3573
            FD_SET(ioh->fd, &rfds);
3574
            if (ioh->fd > nfds)
3575
                nfds = ioh->fd;
3576
        }
3577
        if (ioh->fd_write) {
3578
            FD_SET(ioh->fd, &wfds);
3579
            if (ioh->fd > nfds)
3580
                nfds = ioh->fd;
3581
        }
3582
    }
3583

    
3584
    tv.tv_sec = timeout / 1000;
3585
    tv.tv_usec = (timeout % 1000) * 1000;
3586

    
3587
#if defined(CONFIG_SLIRP)
3588
    if (slirp_is_inited()) {
3589
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3590
    }
3591
#endif
3592
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3593
    if (ret > 0) {
3594
        IOHandlerRecord **pioh;
3595

    
3596
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3597
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3598
                ioh->fd_read(ioh->opaque);
3599
            }
3600
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3601
                ioh->fd_write(ioh->opaque);
3602
            }
3603
        }
3604

    
3605
        /* remove deleted IO handlers */
3606
        pioh = &first_io_handler;
3607
        while (*pioh) {
3608
            ioh = *pioh;
3609
            if (ioh->deleted) {
3610
                *pioh = ioh->next;
3611
                qemu_free(ioh);
3612
            } else
3613
                pioh = &ioh->next;
3614
        }
3615
    }
3616
#if defined(CONFIG_SLIRP)
3617
    if (slirp_is_inited()) {
3618
        if (ret < 0) {
3619
            FD_ZERO(&rfds);
3620
            FD_ZERO(&wfds);
3621
            FD_ZERO(&xfds);
3622
        }
3623
        slirp_select_poll(&rfds, &wfds, &xfds);
3624
    }
3625
#endif
3626

    
3627
    /* vm time timers */
3628
    if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3629
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3630
                        qemu_get_clock(vm_clock));
3631

    
3632
    /* real time timers */
3633
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3634
                    qemu_get_clock(rt_clock));
3635

    
3636
    /* Check bottom-halves last in case any of the earlier events triggered
3637
       them.  */
3638
    qemu_bh_poll();
3639

    
3640
}
3641

    
3642
static int main_loop(void)
3643
{
3644
    int ret, timeout;
3645
#ifdef CONFIG_PROFILER
3646
    int64_t ti;
3647
#endif
3648
    CPUState *env;
3649

    
3650
    cur_cpu = first_cpu;
3651
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
3652
    for(;;) {
3653
        if (vm_running) {
3654

    
3655
            for(;;) {
3656
                /* get next cpu */
3657
                env = next_cpu;
3658
#ifdef CONFIG_PROFILER
3659
                ti = profile_getclock();
3660
#endif
3661
                if (use_icount) {
3662
                    int64_t count;
3663
                    int decr;
3664
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3665
                    env->icount_decr.u16.low = 0;
3666
                    env->icount_extra = 0;
3667
                    count = qemu_next_deadline();
3668
                    count = (count + (1 << icount_time_shift) - 1)
3669
                            >> icount_time_shift;
3670
                    qemu_icount += count;
3671
                    decr = (count > 0xffff) ? 0xffff : count;
3672
                    count -= decr;
3673
                    env->icount_decr.u16.low = decr;
3674
                    env->icount_extra = count;
3675
                }
3676
                ret = cpu_exec(env);
3677
#ifdef CONFIG_PROFILER
3678
                qemu_time += profile_getclock() - ti;
3679
#endif
3680
                if (use_icount) {
3681
                    /* Fold pending instructions back into the
3682
                       instruction counter, and clear the interrupt flag.  */
3683
                    qemu_icount -= (env->icount_decr.u16.low
3684
                                    + env->icount_extra);
3685
                    env->icount_decr.u32 = 0;
3686
                    env->icount_extra = 0;
3687
                }
3688
                next_cpu = env->next_cpu ?: first_cpu;
3689
                if (event_pending && likely(ret != EXCP_DEBUG)) {
3690
                    ret = EXCP_INTERRUPT;
3691
                    event_pending = 0;
3692
                    break;
3693
                }
3694
                if (ret == EXCP_HLT) {
3695
                    /* Give the next CPU a chance to run.  */
3696
                    cur_cpu = env;
3697
                    continue;
3698
                }
3699
                if (ret != EXCP_HALTED)
3700
                    break;
3701
                /* all CPUs are halted ? */
3702
                if (env == cur_cpu)
3703
                    break;
3704
            }
3705
            cur_cpu = env;
3706

    
3707
            if (shutdown_requested) {
3708
                ret = EXCP_INTERRUPT;
3709
                if (no_shutdown) {
3710
                    vm_stop(0);
3711
                    no_shutdown = 0;
3712
                }
3713
                else
3714
                    break;
3715
            }
3716
            if (reset_requested) {
3717
                reset_requested = 0;
3718
                qemu_system_reset();
3719
                ret = EXCP_INTERRUPT;
3720
            }
3721
            if (powerdown_requested) {
3722
                powerdown_requested = 0;
3723
                qemu_system_powerdown();
3724
                ret = EXCP_INTERRUPT;
3725
            }
3726
            if (unlikely(ret == EXCP_DEBUG)) {
3727
                gdb_set_stop_cpu(cur_cpu);
3728
                vm_stop(EXCP_DEBUG);
3729
            }
3730
            /* If all cpus are halted then wait until the next IRQ */
3731
            /* XXX: use timeout computed from timers */
3732
            if (ret == EXCP_HALTED) {
3733
                if (use_icount) {
3734
                    int64_t add;
3735
                    int64_t delta;
3736
                    /* Advance virtual time to the next event.  */
3737
                    if (use_icount == 1) {
3738
                        /* When not using an adaptive execution frequency
3739
                           we tend to get badly out of sync with real time,
3740
                           so just delay for a reasonable amount of time.  */
3741
                        delta = 0;
3742
                    } else {
3743
                        delta = cpu_get_icount() - cpu_get_clock();
3744
                    }
3745
                    if (delta > 0) {
3746
                        /* If virtual time is ahead of real time then just
3747
                           wait for IO.  */
3748
                        timeout = (delta / 1000000) + 1;
3749
                    } else {
3750
                        /* Wait for either IO to occur or the next
3751
                           timer event.  */
3752
                        add = qemu_next_deadline();
3753
                        /* We advance the timer before checking for IO.
3754
                           Limit the amount we advance so that early IO
3755
                           activity won't get the guest too far ahead.  */
3756
                        if (add > 10000000)
3757
                            add = 10000000;
3758
                        delta += add;
3759
                        add = (add + (1 << icount_time_shift) - 1)
3760
                              >> icount_time_shift;
3761
                        qemu_icount += add;
3762
                        timeout = delta / 1000000;
3763
                        if (timeout < 0)
3764
                            timeout = 0;
3765
                    }
3766
                } else {
3767
                    timeout = 5000;
3768
                }
3769
            } else {
3770
                timeout = 0;
3771
            }
3772
        } else {
3773
            if (shutdown_requested) {
3774
                ret = EXCP_INTERRUPT;
3775
                break;
3776
            }
3777
            timeout = 5000;
3778
        }
3779
#ifdef CONFIG_PROFILER
3780
        ti = profile_getclock();
3781
#endif
3782
        main_loop_wait(timeout);
3783
#ifdef CONFIG_PROFILER
3784
        dev_time += profile_getclock() - ti;
3785
#endif
3786
    }
3787
    cpu_disable_ticks();
3788
    return ret;
3789
}
3790

    
3791
static void help(int exitcode)
3792
{
3793
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3794
           "usage: %s [options] [disk_image]\n"
3795
           "\n"
3796
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3797
           "\n"
3798
           "Standard options:\n"
3799
           "-M machine      select emulated machine (-M ? for list)\n"
3800
           "-cpu cpu        select CPU (-cpu ? for list)\n"
3801
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
3802
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
3803
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
3804
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3805
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3806
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3807
           "       [,cache=writethrough|writeback|none][,format=f]\n"
3808
           "                use 'file' as a drive image\n"
3809
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
3810
           "-sd file        use 'file' as SecureDigital card image\n"
3811
           "-pflash file    use 'file' as a parallel flash image\n"
3812
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3813
           "-snapshot       write to temporary files instead of disk image files\n"
3814
#ifdef CONFIG_SDL
3815
           "-no-frame       open SDL window without a frame and window decorations\n"
3816
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3817
           "-no-quit        disable SDL window close capability\n"
3818
#endif
3819
#ifdef TARGET_I386
3820
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
3821
#endif
3822
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
3823
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
3824
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
3825
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
3826
#ifndef _WIN32
3827
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
3828
#endif
3829
#ifdef HAS_AUDIO
3830
           "-audio-help     print list of audio drivers and their options\n"
3831
           "-soundhw c1,... enable audio support\n"
3832
           "                and only specified sound cards (comma separated list)\n"
3833
           "                use -soundhw ? to get the list of supported cards\n"
3834
           "                use -soundhw all to enable all of them\n"
3835
#endif
3836
           "-vga [std|cirrus|vmware]\n"
3837
           "                select video card type\n"
3838
           "-localtime      set the real time clock to local time [default=utc]\n"
3839
           "-full-screen    start in full screen\n"
3840
#ifdef TARGET_I386
3841
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
3842
#endif
3843
           "-usb            enable the USB driver (will be the default soon)\n"
3844
           "-usbdevice name add the host or guest USB device 'name'\n"
3845
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
3846
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
3847
#endif
3848
           "-name string    set the name of the guest\n"
3849
           "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3850
           "\n"
3851
           "Network options:\n"
3852
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
3853
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
3854
#ifdef CONFIG_SLIRP
3855
           "-net user[,vlan=n][,hostname=host]\n"
3856
           "                connect the user mode network stack to VLAN 'n' and send\n"
3857
           "                hostname 'host' to DHCP clients\n"
3858
#endif
3859
#ifdef _WIN32
3860
           "-net tap[,vlan=n],ifname=name\n"
3861
           "                connect the host TAP network interface to VLAN 'n'\n"
3862
#else
3863
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3864
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
3865
           "                network scripts 'file' (default=%s)\n"
3866
           "                and 'dfile' (default=%s);\n"
3867
           "                use '[down]script=no' to disable script execution;\n"
3868
           "                use 'fd=h' to connect to an already opened TAP interface\n"
3869
#endif
3870
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3871
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
3872
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
3873
           "                connect the vlan 'n' to multicast maddr and port\n"
3874
#ifdef CONFIG_VDE
3875
           "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3876
           "                connect the vlan 'n' to port 'n' of a vde switch running\n"
3877
           "                on host and listening for incoming connections on 'socketpath'.\n"
3878
           "                Use group 'groupname' and mode 'octalmode' to change default\n"
3879
           "                ownership and permissions for communication port.\n"
3880
#endif
3881
           "-net none       use it alone to have zero network devices; if no -net option\n"
3882
           "                is provided, the default is '-net nic -net user'\n"
3883
           "\n"
3884
           "-bt hci,null    Dumb bluetooth HCI - doesn't respond to commands\n"
3885
           "-bt hci,host[:id]\n"
3886
           "                Use host's HCI with the given name\n"
3887
           "-bt hci[,vlan=n]\n"
3888
           "                Emulate a standard HCI in virtual scatternet 'n'\n"
3889
           "-bt vhci[,vlan=n]\n"
3890
           "                Add host computer to virtual scatternet 'n' using VHCI\n"
3891
           "-bt device:dev[,vlan=n]\n"
3892
           "                Emulate a bluetooth device 'dev' in scatternet 'n'\n"
3893
           "\n"
3894
#ifdef CONFIG_SLIRP
3895
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
3896
           "-bootp file     advertise file in BOOTP replies\n"
3897
#ifndef _WIN32
3898
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
3899
#endif
3900
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3901
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
3902
#endif
3903
           "\n"
3904
           "Linux boot specific:\n"
3905
           "-kernel bzImage use 'bzImage' as kernel image\n"
3906
           "-append cmdline use 'cmdline' as kernel command line\n"
3907
           "-initrd file    use 'file' as initial ram disk\n"
3908
           "\n"
3909
           "Debug/Expert options:\n"
3910
           "-monitor dev    redirect the monitor to char device 'dev'\n"
3911
           "-serial dev     redirect the serial port to char device 'dev'\n"
3912
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
3913
           "-pidfile file   Write PID to 'file'\n"
3914
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
3915
           "-s              wait gdb connection to port\n"
3916
           "-p port         set gdb connection port [default=%s]\n"
3917
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
3918
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
3919
           "                translation (t=none or lba) (usually qemu can guess them)\n"
3920
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
3921
#ifdef USE_KQEMU
3922
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
3923
           "-no-kqemu       disable KQEMU kernel module usage\n"
3924
#endif
3925
#ifdef CONFIG_KVM
3926
           "-enable-kvm     enable KVM full virtualization support\n"
3927
#endif
3928
#ifdef TARGET_I386
3929
           "-no-acpi        disable ACPI\n"
3930
#endif
3931
#ifdef CONFIG_CURSES
3932
           "-curses         use a curses/ncurses interface instead of SDL\n"
3933
#endif
3934
           "-no-reboot      exit instead of rebooting\n"
3935
           "-no-shutdown    stop before shutdown\n"
3936
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
3937
           "-vnc display    start a VNC server on display\n"
3938
#ifndef _WIN32
3939
           "-daemonize      daemonize QEMU after initializing\n"
3940
#endif
3941
           "-option-rom rom load a file, rom, into the option ROM space\n"
3942
#ifdef TARGET_SPARC
3943
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
3944
#endif
3945
           "-clock          force the use of the given methods for timer alarm.\n"
3946
           "                To see what timers are available use -clock ?\n"
3947
           "-startdate      select initial date of the clock\n"
3948
           "-icount [N|auto]\n"
3949
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
3950
           "\n"
3951
           "During emulation, the following keys are useful:\n"
3952
           "ctrl-alt-f      toggle full screen\n"
3953
           "ctrl-alt-n      switch to virtual console 'n'\n"
3954
           "ctrl-alt        toggle mouse and keyboard grab\n"
3955
           "\n"
3956
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
3957
           ,
3958
           "qemu",
3959
           DEFAULT_RAM_SIZE,
3960
#ifndef _WIN32
3961
           DEFAULT_NETWORK_SCRIPT,
3962
           DEFAULT_NETWORK_DOWN_SCRIPT,
3963
#endif
3964
           DEFAULT_GDBSTUB_PORT,
3965
           "/tmp/qemu.log");
3966
    exit(exitcode);
3967
}
3968

    
3969
#define HAS_ARG 0x0001
3970

    
3971
enum {
3972
    QEMU_OPTION_h,
3973

    
3974
    QEMU_OPTION_M,
3975
    QEMU_OPTION_cpu,
3976
    QEMU_OPTION_fda,
3977
    QEMU_OPTION_fdb,
3978
    QEMU_OPTION_hda,
3979
    QEMU_OPTION_hdb,
3980
    QEMU_OPTION_hdc,
3981
    QEMU_OPTION_hdd,
3982
    QEMU_OPTION_drive,
3983
    QEMU_OPTION_cdrom,
3984
    QEMU_OPTION_mtdblock,
3985
    QEMU_OPTION_sd,
3986
    QEMU_OPTION_pflash,
3987
    QEMU_OPTION_boot,
3988
    QEMU_OPTION_snapshot,
3989
#ifdef TARGET_I386
3990
    QEMU_OPTION_no_fd_bootchk,
3991
#endif
3992
    QEMU_OPTION_m,
3993
    QEMU_OPTION_nographic,
3994
    QEMU_OPTION_portrait,
3995
#ifdef HAS_AUDIO
3996
    QEMU_OPTION_audio_help,
3997
    QEMU_OPTION_soundhw,
3998
#endif
3999

    
4000
    QEMU_OPTION_net,
4001
    QEMU_OPTION_tftp,
4002
    QEMU_OPTION_bootp,
4003
    QEMU_OPTION_smb,
4004
    QEMU_OPTION_redir,
4005
    QEMU_OPTION_bt,
4006

    
4007
    QEMU_OPTION_kernel,
4008
    QEMU_OPTION_append,
4009
    QEMU_OPTION_initrd,
4010

    
4011
    QEMU_OPTION_S,
4012
    QEMU_OPTION_s,
4013
    QEMU_OPTION_p,
4014
    QEMU_OPTION_d,
4015
    QEMU_OPTION_hdachs,
4016
    QEMU_OPTION_L,
4017
    QEMU_OPTION_bios,
4018
    QEMU_OPTION_k,
4019
    QEMU_OPTION_localtime,
4020
    QEMU_OPTION_g,
4021
    QEMU_OPTION_vga,
4022
    QEMU_OPTION_echr,
4023
    QEMU_OPTION_monitor,
4024
    QEMU_OPTION_serial,
4025
    QEMU_OPTION_parallel,
4026
    QEMU_OPTION_loadvm,
4027
    QEMU_OPTION_full_screen,
4028
    QEMU_OPTION_no_frame,
4029
    QEMU_OPTION_alt_grab,
4030
    QEMU_OPTION_no_quit,
4031
    QEMU_OPTION_pidfile,
4032
    QEMU_OPTION_no_kqemu,
4033
    QEMU_OPTION_kernel_kqemu,
4034
    QEMU_OPTION_enable_kvm,
4035
    QEMU_OPTION_win2k_hack,
4036
    QEMU_OPTION_usb,
4037
    QEMU_OPTION_usbdevice,
4038
    QEMU_OPTION_smp,
4039
    QEMU_OPTION_vnc,
4040
    QEMU_OPTION_no_acpi,
4041
    QEMU_OPTION_curses,
4042
    QEMU_OPTION_no_reboot,
4043
    QEMU_OPTION_no_shutdown,
4044
    QEMU_OPTION_show_cursor,
4045
    QEMU_OPTION_daemonize,
4046
    QEMU_OPTION_option_rom,
4047
    QEMU_OPTION_semihosting,
4048
    QEMU_OPTION_name,
4049
    QEMU_OPTION_prom_env,
4050
    QEMU_OPTION_old_param,
4051
    QEMU_OPTION_clock,
4052
    QEMU_OPTION_startdate,
4053
    QEMU_OPTION_tb_size,
4054
    QEMU_OPTION_icount,
4055
    QEMU_OPTION_uuid,
4056
    QEMU_OPTION_incoming,
4057
};
4058

    
4059
typedef struct QEMUOption {
4060
    const char *name;
4061
    int flags;
4062
    int index;
4063
} QEMUOption;
4064

    
4065
static const QEMUOption qemu_options[] = {
4066
    { "h", 0, QEMU_OPTION_h },
4067
    { "help", 0, QEMU_OPTION_h },
4068

    
4069
    { "M", HAS_ARG, QEMU_OPTION_M },
4070
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4071
    { "fda", HAS_ARG, QEMU_OPTION_fda },
4072
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4073
    { "hda", HAS_ARG, QEMU_OPTION_hda },
4074
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4075
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4076
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4077
    { "drive", HAS_ARG, QEMU_OPTION_drive },
4078
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4079
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4080
    { "sd", HAS_ARG, QEMU_OPTION_sd },
4081
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4082
    { "boot", HAS_ARG, QEMU_OPTION_boot },
4083
    { "snapshot", 0, QEMU_OPTION_snapshot },
4084
#ifdef TARGET_I386
4085
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4086
#endif
4087
    { "m", HAS_ARG, QEMU_OPTION_m },
4088
    { "nographic", 0, QEMU_OPTION_nographic },
4089
    { "portrait", 0, QEMU_OPTION_portrait },
4090
    { "k", HAS_ARG, QEMU_OPTION_k },
4091
#ifdef HAS_AUDIO
4092
    { "audio-help", 0, QEMU_OPTION_audio_help },
4093
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4094
#endif
4095

    
4096
    { "net", HAS_ARG, QEMU_OPTION_net},
4097
#ifdef CONFIG_SLIRP
4098
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4099
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4100
#ifndef _WIN32
4101
    { "smb", HAS_ARG, QEMU_OPTION_smb },
4102
#endif
4103
    { "redir", HAS_ARG, QEMU_OPTION_redir },
4104
#endif
4105
    { "bt", HAS_ARG, QEMU_OPTION_bt },
4106

    
4107
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4108
    { "append", HAS_ARG, QEMU_OPTION_append },
4109
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4110

    
4111
    { "S", 0, QEMU_OPTION_S },
4112
    { "s", 0, QEMU_OPTION_s },
4113
    { "p", HAS_ARG, QEMU_OPTION_p },
4114
    { "d", HAS_ARG, QEMU_OPTION_d },
4115
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4116
    { "L", HAS_ARG, QEMU_OPTION_L },
4117
    { "bios", HAS_ARG, QEMU_OPTION_bios },
4118
#ifdef USE_KQEMU
4119
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4120
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4121
#endif
4122
#ifdef CONFIG_KVM
4123
    { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4124
#endif
4125
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4126
    { "g", 1, QEMU_OPTION_g },
4127
#endif
4128
    { "localtime", 0, QEMU_OPTION_localtime },
4129
    { "vga", HAS_ARG, QEMU_OPTION_vga },
4130
    { "echr", HAS_ARG, QEMU_OPTION_echr },
4131
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4132
    { "serial", HAS_ARG, QEMU_OPTION_serial },
4133
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4134
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4135
    { "full-screen", 0, QEMU_OPTION_full_screen },
4136
#ifdef CONFIG_SDL
4137
    { "no-frame", 0, QEMU_OPTION_no_frame },
4138
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
4139
    { "no-quit", 0, QEMU_OPTION_no_quit },
4140
#endif
4141
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4142
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4143
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4144
    { "smp", HAS_ARG, QEMU_OPTION_smp },
4145
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4146
#ifdef CONFIG_CURSES
4147
    { "curses", 0, QEMU_OPTION_curses },
4148
#endif
4149
    { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4150

    
4151
    /* temporary options */
4152
    { "usb", 0, QEMU_OPTION_usb },
4153
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
4154
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
4155
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4156
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
4157
    { "daemonize", 0, QEMU_OPTION_daemonize },
4158
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4159
#if defined(TARGET_ARM) || defined(TARGET_M68K)
4160
    { "semihosting", 0, QEMU_OPTION_semihosting },
4161
#endif
4162
    { "name", HAS_ARG, QEMU_OPTION_name },
4163
#if defined(TARGET_SPARC)
4164
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4165
#endif
4166
#if defined(TARGET_ARM)
4167
    { "old-param", 0, QEMU_OPTION_old_param },
4168
#endif
4169
    { "clock", HAS_ARG, QEMU_OPTION_clock },
4170
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4171
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4172
    { "icount", HAS_ARG, QEMU_OPTION_icount },
4173
    { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4174
    { NULL },
4175
};
4176

    
4177
/* password input */
4178

    
4179
int qemu_key_check(BlockDriverState *bs, const char *name)
4180
{
4181
    char password[256];
4182
    int i;
4183

    
4184
    if (!bdrv_is_encrypted(bs))
4185
        return 0;
4186

    
4187
    term_printf("%s is encrypted.\n", name);
4188
    for(i = 0; i < 3; i++) {
4189
        monitor_readline("Password: ", 1, password, sizeof(password));
4190
        if (bdrv_set_key(bs, password) == 0)
4191
            return 0;
4192
        term_printf("invalid password\n");
4193
    }
4194
    return -EPERM;
4195
}
4196

    
4197
static BlockDriverState *get_bdrv(int index)
4198
{
4199
    if (index > nb_drives)
4200
        return NULL;
4201
    return drives_table[index].bdrv;
4202
}
4203

    
4204
static void read_passwords(void)
4205
{
4206
    BlockDriverState *bs;
4207
    int i;
4208

    
4209
    for(i = 0; i < 6; i++) {
4210
        bs = get_bdrv(i);
4211
        if (bs)
4212
            qemu_key_check(bs, bdrv_get_device_name(bs));
4213
    }
4214
}
4215

    
4216
#ifdef HAS_AUDIO
4217
struct soundhw soundhw[] = {
4218
#ifdef HAS_AUDIO_CHOICE
4219
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4220
    {
4221
        "pcspk",
4222
        "PC speaker",
4223
        0,
4224
        1,
4225
        { .init_isa = pcspk_audio_init }
4226
    },
4227
#endif
4228
    {
4229
        "sb16",
4230
        "Creative Sound Blaster 16",
4231
        0,
4232
        1,
4233
        { .init_isa = SB16_init }
4234
    },
4235

    
4236
#ifdef CONFIG_CS4231A
4237
    {
4238
        "cs4231a",
4239
        "CS4231A",
4240
        0,
4241
        1,
4242
        { .init_isa = cs4231a_init }
4243
    },
4244
#endif
4245

    
4246
#ifdef CONFIG_ADLIB
4247
    {
4248
        "adlib",
4249
#ifdef HAS_YMF262
4250
        "Yamaha YMF262 (OPL3)",
4251
#else
4252
        "Yamaha YM3812 (OPL2)",
4253
#endif
4254
        0,
4255
        1,
4256
        { .init_isa = Adlib_init }
4257
    },
4258
#endif
4259

    
4260
#ifdef CONFIG_GUS
4261
    {
4262
        "gus",
4263
        "Gravis Ultrasound GF1",
4264
        0,
4265
        1,
4266
        { .init_isa = GUS_init }
4267
    },
4268
#endif
4269

    
4270
#ifdef CONFIG_AC97
4271
    {
4272
        "ac97",
4273
        "Intel 82801AA AC97 Audio",
4274
        0,
4275
        0,
4276
        { .init_pci = ac97_init }
4277
    },
4278
#endif
4279

    
4280
    {
4281
        "es1370",
4282
        "ENSONIQ AudioPCI ES1370",
4283
        0,
4284
        0,
4285
        { .init_pci = es1370_init }
4286
    },
4287
#endif
4288

    
4289
    { NULL, NULL, 0, 0, { NULL } }
4290
};
4291

    
4292
static void select_soundhw (const char *optarg)
4293
{
4294
    struct soundhw *c;
4295

    
4296
    if (*optarg == '?') {
4297
    show_valid_cards:
4298

    
4299
        printf ("Valid sound card names (comma separated):\n");
4300
        for (c = soundhw; c->name; ++c) {
4301
            printf ("%-11s %s\n", c->name, c->descr);
4302
        }
4303
        printf ("\n-soundhw all will enable all of the above\n");
4304
        exit (*optarg != '?');
4305
    }
4306
    else {
4307
        size_t l;
4308
        const char *p;
4309
        char *e;
4310
        int bad_card = 0;
4311

    
4312
        if (!strcmp (optarg, "all")) {
4313
            for (c = soundhw; c->name; ++c) {
4314
                c->enabled = 1;
4315
            }
4316
            return;
4317
        }
4318

    
4319
        p = optarg;
4320
        while (*p) {
4321
            e = strchr (p, ',');
4322
            l = !e ? strlen (p) : (size_t) (e - p);
4323

    
4324
            for (c = soundhw; c->name; ++c) {
4325
                if (!strncmp (c->name, p, l)) {
4326
                    c->enabled = 1;
4327
                    break;
4328
                }
4329
            }
4330

    
4331
            if (!c->name) {
4332
                if (l > 80) {
4333
                    fprintf (stderr,
4334
                             "Unknown sound card name (too big to show)\n");
4335
                }
4336
                else {
4337
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4338
                             (int) l, p);
4339
                }
4340
                bad_card = 1;
4341
            }
4342
            p += l + (e != NULL);
4343
        }
4344

    
4345
        if (bad_card)
4346
            goto show_valid_cards;
4347
    }
4348
}
4349
#endif
4350

    
4351
static void select_vgahw (const char *p)
4352
{
4353
    const char *opts;
4354

    
4355
    if (strstart(p, "std", &opts)) {
4356
        cirrus_vga_enabled = 0;
4357
        vmsvga_enabled = 0;
4358
    } else if (strstart(p, "cirrus", &opts)) {
4359
        cirrus_vga_enabled = 1;
4360
        vmsvga_enabled = 0;
4361
    } else if (strstart(p, "vmware", &opts)) {
4362
        cirrus_vga_enabled = 0;
4363
        vmsvga_enabled = 1;
4364
    } else {
4365
    invalid_vga:
4366
        fprintf(stderr, "Unknown vga type: %s\n", p);
4367
        exit(1);
4368
    }
4369
    while (*opts) {
4370
        const char *nextopt;
4371

    
4372
        if (strstart(opts, ",retrace=", &nextopt)) {
4373
            opts = nextopt;
4374
            if (strstart(opts, "dumb", &nextopt))
4375
                vga_retrace_method = VGA_RETRACE_DUMB;
4376
            else if (strstart(opts, "precise", &nextopt))
4377
                vga_retrace_method = VGA_RETRACE_PRECISE;
4378
            else goto invalid_vga;
4379
        } else goto invalid_vga;
4380
        opts = nextopt;
4381
    }
4382
}
4383

    
4384
#ifdef _WIN32
4385
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4386
{
4387
    exit(STATUS_CONTROL_C_EXIT);
4388
    return TRUE;
4389
}
4390
#endif
4391

    
4392
static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4393
{
4394
    int ret;
4395

    
4396
    if(strlen(str) != 36)
4397
        return -1;
4398

    
4399
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4400
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4401
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4402

    
4403
    if(ret != 16)
4404
        return -1;
4405

    
4406
    return 0;
4407
}
4408

    
4409
#define MAX_NET_CLIENTS 32
4410

    
4411
#ifndef _WIN32
4412

    
4413
static void termsig_handler(int signal)
4414
{
4415
    qemu_system_shutdown_request();
4416
}
4417

    
4418
static void termsig_setup(void)
4419
{
4420
    struct sigaction act;
4421

    
4422
    memset(&act, 0, sizeof(act));
4423
    act.sa_handler = termsig_handler;
4424
    sigaction(SIGINT,  &act, NULL);
4425
    sigaction(SIGHUP,  &act, NULL);
4426
    sigaction(SIGTERM, &act, NULL);
4427
}
4428

    
4429
#endif
4430

    
4431
int main(int argc, char **argv)
4432
{
4433
#ifdef CONFIG_GDBSTUB
4434
    int use_gdbstub;
4435
    const char *gdbstub_port;
4436
#endif
4437
    uint32_t boot_devices_bitmap = 0;
4438
    int i;
4439
    int snapshot, linux_boot, net_boot;
4440
    const char *initrd_filename;
4441
    const char *kernel_filename, *kernel_cmdline;
4442
    const char *boot_devices = "";
4443
    DisplayState *ds = &display_state;
4444
    int cyls, heads, secs, translation;
4445
    const char *net_clients[MAX_NET_CLIENTS];
4446
    int nb_net_clients;
4447
    const char *bt_opts[MAX_BT_CMDLINE];
4448
    int nb_bt_opts;
4449
    int hda_index;
4450
    int optind;
4451
    const char *r, *optarg;
4452
    CharDriverState *monitor_hd;
4453
    const char *monitor_device;
4454
    const char *serial_devices[MAX_SERIAL_PORTS];
4455
    int serial_device_index;
4456
    const char *parallel_devices[MAX_PARALLEL_PORTS];
4457
    int parallel_device_index;
4458
    const char *loadvm = NULL;
4459
    QEMUMachine *machine;
4460
    const char *cpu_model;
4461
    const char *usb_devices[MAX_USB_CMDLINE];
4462
    int usb_devices_index;
4463
    int fds[2];
4464
    int tb_size;
4465
    const char *pid_file = NULL;
4466
    int autostart;
4467
    const char *incoming = NULL;
4468

    
4469
    LIST_INIT (&vm_change_state_head);
4470
#ifndef _WIN32
4471
    {
4472
        struct sigaction act;
4473
        sigfillset(&act.sa_mask);
4474
        act.sa_flags = 0;
4475
        act.sa_handler = SIG_IGN;
4476
        sigaction(SIGPIPE, &act, NULL);
4477
    }
4478
#else
4479
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4480
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4481
       QEMU to run on a single CPU */
4482
    {
4483
        HANDLE h;
4484
        DWORD mask, smask;
4485
        int i;
4486
        h = GetCurrentProcess();
4487
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4488
            for(i = 0; i < 32; i++) {
4489
                if (mask & (1 << i))
4490
                    break;
4491
            }
4492
            if (i != 32) {
4493
                mask = 1 << i;
4494
                SetProcessAffinityMask(h, mask);
4495
            }
4496
        }
4497
    }
4498
#endif
4499

    
4500
    register_machines();
4501
    machine = first_machine;
4502
    cpu_model = NULL;
4503
    initrd_filename = NULL;
4504
    ram_size = 0;
4505
    vga_ram_size = VGA_RAM_SIZE;
4506
#ifdef CONFIG_GDBSTUB
4507
    use_gdbstub = 0;
4508
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
4509
#endif
4510
    snapshot = 0;
4511
    nographic = 0;
4512
    curses = 0;
4513
    kernel_filename = NULL;
4514
    kernel_cmdline = "";
4515
    cyls = heads = secs = 0;
4516
    translation = BIOS_ATA_TRANSLATION_AUTO;
4517
    monitor_device = "vc";
4518

    
4519
    serial_devices[0] = "vc:80Cx24C";
4520
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4521
        serial_devices[i] = NULL;
4522
    serial_device_index = 0;
4523

    
4524
    parallel_devices[0] = "vc:640x480";
4525
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4526
        parallel_devices[i] = NULL;
4527
    parallel_device_index = 0;
4528

    
4529
    usb_devices_index = 0;
4530

    
4531
    nb_net_clients = 0;
4532
    nb_bt_opts = 0;
4533
    nb_drives = 0;
4534
    nb_drives_opt = 0;
4535
    hda_index = -1;
4536

    
4537
    nb_nics = 0;
4538

    
4539
    tb_size = 0;
4540
    autostart= 1;
4541

    
4542
    optind = 1;
4543
    for(;;) {
4544
        if (optind >= argc)
4545
            break;
4546
        r = argv[optind];
4547
        if (r[0] != '-') {
4548
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4549
        } else {
4550
            const QEMUOption *popt;
4551

    
4552
            optind++;
4553
            /* Treat --foo the same as -foo.  */
4554
            if (r[1] == '-')
4555
                r++;
4556
            popt = qemu_options;
4557
            for(;;) {
4558
                if (!popt->name) {
4559
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
4560
                            argv[0], r);
4561
                    exit(1);
4562
                }
4563
                if (!strcmp(popt->name, r + 1))
4564
                    break;
4565
                popt++;
4566
            }
4567
            if (popt->flags & HAS_ARG) {
4568
                if (optind >= argc) {
4569
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
4570
                            argv[0], r);
4571
                    exit(1);
4572
                }
4573
                optarg = argv[optind++];
4574
            } else {
4575
                optarg = NULL;
4576
            }
4577

    
4578
            switch(popt->index) {
4579
            case QEMU_OPTION_M:
4580
                machine = find_machine(optarg);
4581
                if (!machine) {
4582
                    QEMUMachine *m;
4583
                    printf("Supported machines are:\n");
4584
                    for(m = first_machine; m != NULL; m = m->next) {
4585
                        printf("%-10s %s%s\n",
4586
                               m->name, m->desc,
4587
                               m == first_machine ? " (default)" : "");
4588
                    }
4589
                    exit(*optarg != '?');
4590
                }
4591
                break;
4592
            case QEMU_OPTION_cpu:
4593
                /* hw initialization will check this */
4594
                if (*optarg == '?') {
4595
/* XXX: implement xxx_cpu_list for targets that still miss it */
4596
#if defined(cpu_list)
4597
                    cpu_list(stdout, &fprintf);
4598
#endif
4599
                    exit(0);
4600
                } else {
4601
                    cpu_model = optarg;
4602
                }
4603
                break;
4604
            case QEMU_OPTION_initrd:
4605
                initrd_filename = optarg;
4606
                break;
4607
            case QEMU_OPTION_hda:
4608
                if (cyls == 0)
4609
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
4610
                else
4611
                    hda_index = drive_add(optarg, HD_ALIAS
4612
                             ",cyls=%d,heads=%d,secs=%d%s",
4613
                             0, cyls, heads, secs,
4614
                             translation == BIOS_ATA_TRANSLATION_LBA ?
4615
                                 ",trans=lba" :
4616
                             translation == BIOS_ATA_TRANSLATION_NONE ?
4617
                                 ",trans=none" : "");
4618
                 break;
4619
            case QEMU_OPTION_hdb:
4620
            case QEMU_OPTION_hdc:
4621
            case QEMU_OPTION_hdd:
4622
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4623
                break;
4624
            case QEMU_OPTION_drive:
4625
                drive_add(NULL, "%s", optarg);
4626
                break;
4627
            case QEMU_OPTION_mtdblock:
4628
                drive_add(optarg, MTD_ALIAS);
4629
                break;
4630
            case QEMU_OPTION_sd:
4631
                drive_add(optarg, SD_ALIAS);
4632
                break;
4633
            case QEMU_OPTION_pflash:
4634
                drive_add(optarg, PFLASH_ALIAS);
4635
                break;
4636
            case QEMU_OPTION_snapshot:
4637
                snapshot = 1;
4638
                break;
4639
            case QEMU_OPTION_hdachs:
4640
                {
4641
                    const char *p;
4642
                    p = optarg;
4643
                    cyls = strtol(p, (char **)&p, 0);
4644
                    if (cyls < 1 || cyls > 16383)
4645
                        goto chs_fail;
4646
                    if (*p != ',')
4647
                        goto chs_fail;
4648
                    p++;
4649
                    heads = strtol(p, (char **)&p, 0);
4650
                    if (heads < 1 || heads > 16)
4651
                        goto chs_fail;
4652
                    if (*p != ',')
4653
                        goto chs_fail;
4654
                    p++;
4655
                    secs = strtol(p, (char **)&p, 0);
4656
                    if (secs < 1 || secs > 63)
4657
                        goto chs_fail;
4658
                    if (*p == ',') {
4659
                        p++;
4660
                        if (!strcmp(p, "none"))
4661
                            translation = BIOS_ATA_TRANSLATION_NONE;
4662
                        else if (!strcmp(p, "lba"))
4663
                            translation = BIOS_ATA_TRANSLATION_LBA;
4664
                        else if (!strcmp(p, "auto"))
4665
                            translation = BIOS_ATA_TRANSLATION_AUTO;
4666
                        else
4667
                            goto chs_fail;
4668
                    } else if (*p != '\0') {
4669
                    chs_fail:
4670
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
4671
                        exit(1);
4672
                    }
4673
                    if (hda_index != -1)
4674
                        snprintf(drives_opt[hda_index].opt,
4675
                                 sizeof(drives_opt[hda_index].opt),
4676
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4677
                                 0, cyls, heads, secs,
4678
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
4679
                                         ",trans=lba" :
4680
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
4681
                                     ",trans=none" : "");
4682
                }
4683
                break;
4684
            case QEMU_OPTION_nographic:
4685
                nographic = 1;
4686
                break;
4687
#ifdef CONFIG_CURSES
4688
            case QEMU_OPTION_curses:
4689
                curses = 1;
4690
                break;
4691
#endif
4692
            case QEMU_OPTION_portrait:
4693
                graphic_rotate = 1;
4694
                break;
4695
            case QEMU_OPTION_kernel:
4696
                kernel_filename = optarg;
4697
                break;
4698
            case QEMU_OPTION_append:
4699
                kernel_cmdline = optarg;
4700
                break;
4701
            case QEMU_OPTION_cdrom:
4702
                drive_add(optarg, CDROM_ALIAS);
4703
                break;
4704
            case QEMU_OPTION_boot:
4705
                boot_devices = optarg;
4706
                /* We just do some generic consistency checks */
4707
                {
4708
                    /* Could easily be extended to 64 devices if needed */
4709
                    const char *p;
4710
                    
4711
                    boot_devices_bitmap = 0;
4712
                    for (p = boot_devices; *p != '\0'; p++) {
4713
                        /* Allowed boot devices are:
4714
                         * a b     : floppy disk drives
4715
                         * c ... f : IDE disk drives
4716
                         * g ... m : machine implementation dependant drives
4717
                         * n ... p : network devices
4718
                         * It's up to each machine implementation to check
4719
                         * if the given boot devices match the actual hardware
4720
                         * implementation and firmware features.
4721
                         */
4722
                        if (*p < 'a' || *p > 'q') {
4723
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
4724
                            exit(1);
4725
                        }
4726
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4727
                            fprintf(stderr,
4728
                                    "Boot device '%c' was given twice\n",*p);
4729
                            exit(1);
4730
                        }
4731
                        boot_devices_bitmap |= 1 << (*p - 'a');
4732
                    }
4733
                }
4734
                break;
4735
            case QEMU_OPTION_fda:
4736
            case QEMU_OPTION_fdb:
4737
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4738
                break;
4739
#ifdef TARGET_I386
4740
            case QEMU_OPTION_no_fd_bootchk:
4741
                fd_bootchk = 0;
4742
                break;
4743
#endif
4744
            case QEMU_OPTION_net:
4745
                if (nb_net_clients >= MAX_NET_CLIENTS) {
4746
                    fprintf(stderr, "qemu: too many network clients\n");
4747
                    exit(1);
4748
                }
4749
                net_clients[nb_net_clients] = optarg;
4750
                nb_net_clients++;
4751
                break;
4752
#ifdef CONFIG_SLIRP
4753
            case QEMU_OPTION_tftp:
4754
                tftp_prefix = optarg;
4755
                break;
4756
            case QEMU_OPTION_bootp:
4757
                bootp_filename = optarg;
4758
                break;
4759
#ifndef _WIN32
4760
            case QEMU_OPTION_smb:
4761
                net_slirp_smb(optarg);
4762
                break;
4763
#endif
4764
            case QEMU_OPTION_redir:
4765
                net_slirp_redir(optarg);
4766
                break;
4767
#endif
4768
            case QEMU_OPTION_bt:
4769
                if (nb_bt_opts >= MAX_BT_CMDLINE) {
4770
                    fprintf(stderr, "qemu: too many bluetooth options\n");
4771
                    exit(1);
4772
                }
4773
                bt_opts[nb_bt_opts++] = optarg;
4774
                break;
4775
#ifdef HAS_AUDIO
4776
            case QEMU_OPTION_audio_help:
4777
                AUD_help ();
4778
                exit (0);
4779
                break;
4780
            case QEMU_OPTION_soundhw:
4781
                select_soundhw (optarg);
4782
                break;
4783
#endif
4784
            case QEMU_OPTION_h:
4785
                help(0);
4786
                break;
4787
            case QEMU_OPTION_m: {
4788
                uint64_t value;
4789
                char *ptr;
4790

    
4791
                value = strtoul(optarg, &ptr, 10);
4792
                switch (*ptr) {
4793
                case 0: case 'M': case 'm':
4794
                    value <<= 20;
4795
                    break;
4796
                case 'G': case 'g':
4797
                    value <<= 30;
4798
                    break;
4799
                default:
4800
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4801
                    exit(1);
4802
                }
4803

    
4804
                /* On 32-bit hosts, QEMU is limited by virtual address space */
4805
                if (value > (2047 << 20)
4806
#ifndef USE_KQEMU
4807
                    && HOST_LONG_BITS == 32
4808
#endif
4809
                    ) {
4810
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4811
                    exit(1);
4812
                }
4813
                if (value != (uint64_t)(ram_addr_t)value) {
4814
                    fprintf(stderr, "qemu: ram size too large\n");
4815
                    exit(1);
4816
                }
4817
                ram_size = value;
4818
                break;
4819
            }
4820
            case QEMU_OPTION_d:
4821
                {
4822
                    int mask;
4823
                    const CPULogItem *item;
4824

    
4825
                    mask = cpu_str_to_log_mask(optarg);
4826
                    if (!mask) {
4827
                        printf("Log items (comma separated):\n");
4828
                    for(item = cpu_log_items; item->mask != 0; item++) {
4829
                        printf("%-10s %s\n", item->name, item->help);
4830
                    }
4831
                    exit(1);
4832
                    }
4833
                    cpu_set_log(mask);
4834
                }
4835
                break;
4836
#ifdef CONFIG_GDBSTUB
4837
            case QEMU_OPTION_s:
4838
                use_gdbstub = 1;
4839
                break;
4840
            case QEMU_OPTION_p:
4841
                gdbstub_port = optarg;
4842
                break;
4843
#endif
4844
            case QEMU_OPTION_L:
4845
                bios_dir = optarg;
4846
                break;
4847
            case QEMU_OPTION_bios:
4848
                bios_name = optarg;
4849
                break;
4850
            case QEMU_OPTION_S:
4851
                autostart = 0;
4852
                break;
4853
            case QEMU_OPTION_k:
4854
                keyboard_layout = optarg;
4855
                break;
4856
            case QEMU_OPTION_localtime:
4857
                rtc_utc = 0;
4858
                break;
4859
            case QEMU_OPTION_vga:
4860
                select_vgahw (optarg);
4861
                break;
4862
            case QEMU_OPTION_g:
4863
                {
4864
                    const char *p;
4865
                    int w, h, depth;
4866
                    p = optarg;
4867
                    w = strtol(p, (char **)&p, 10);
4868
                    if (w <= 0) {
4869
                    graphic_error:
4870
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
4871
                        exit(1);
4872
                    }
4873
                    if (*p != 'x')
4874
                        goto graphic_error;
4875
                    p++;
4876
                    h = strtol(p, (char **)&p, 10);
4877
                    if (h <= 0)
4878
                        goto graphic_error;
4879
                    if (*p == 'x') {
4880
                        p++;
4881
                        depth = strtol(p, (char **)&p, 10);
4882
                        if (depth != 8 && depth != 15 && depth != 16 &&
4883
                            depth != 24 && depth != 32)
4884
                            goto graphic_error;
4885
                    } else if (*p == '\0') {
4886
                        depth = graphic_depth;
4887
                    } else {
4888
                        goto graphic_error;
4889
                    }
4890

    
4891
                    graphic_width = w;
4892
                    graphic_height = h;
4893
                    graphic_depth = depth;
4894
                }
4895
                break;
4896
            case QEMU_OPTION_echr:
4897
                {
4898
                    char *r;
4899
                    term_escape_char = strtol(optarg, &r, 0);
4900
                    if (r == optarg)
4901
                        printf("Bad argument to echr\n");
4902
                    break;
4903
                }
4904
            case QEMU_OPTION_monitor:
4905
                monitor_device = optarg;
4906
                break;
4907
            case QEMU_OPTION_serial:
4908
                if (serial_device_index >= MAX_SERIAL_PORTS) {
4909
                    fprintf(stderr, "qemu: too many serial ports\n");
4910
                    exit(1);
4911
                }
4912
                serial_devices[serial_device_index] = optarg;
4913
                serial_device_index++;
4914
                break;
4915
            case QEMU_OPTION_parallel:
4916
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4917
                    fprintf(stderr, "qemu: too many parallel ports\n");
4918
                    exit(1);
4919
                }
4920
                parallel_devices[parallel_device_index] = optarg;
4921
                parallel_device_index++;
4922
                break;
4923
            case QEMU_OPTION_loadvm:
4924
                loadvm = optarg;
4925
                break;
4926
            case QEMU_OPTION_full_screen:
4927
                full_screen = 1;
4928
                break;
4929
#ifdef CONFIG_SDL
4930
            case QEMU_OPTION_no_frame:
4931
                no_frame = 1;
4932
                break;
4933
            case QEMU_OPTION_alt_grab:
4934
                alt_grab = 1;
4935
                break;
4936
            case QEMU_OPTION_no_quit:
4937
                no_quit = 1;
4938
                break;
4939
#endif
4940
            case QEMU_OPTION_pidfile:
4941
                pid_file = optarg;
4942
                break;
4943
#ifdef TARGET_I386
4944
            case QEMU_OPTION_win2k_hack:
4945
                win2k_install_hack = 1;
4946
                break;
4947
#endif
4948
#ifdef USE_KQEMU
4949
            case QEMU_OPTION_no_kqemu:
4950
                kqemu_allowed = 0;
4951
                break;
4952
            case QEMU_OPTION_kernel_kqemu:
4953
                kqemu_allowed = 2;
4954
                break;
4955
#endif
4956
#ifdef CONFIG_KVM
4957
            case QEMU_OPTION_enable_kvm:
4958
                kvm_allowed = 1;
4959
#ifdef USE_KQEMU
4960
                kqemu_allowed = 0;
4961
#endif
4962
                break;
4963
#endif
4964
            case QEMU_OPTION_usb:
4965
                usb_enabled = 1;
4966
                break;
4967
            case QEMU_OPTION_usbdevice:
4968
                usb_enabled = 1;
4969
                if (usb_devices_index >= MAX_USB_CMDLINE) {
4970
                    fprintf(stderr, "Too many USB devices\n");
4971
                    exit(1);
4972
                }
4973
                usb_devices[usb_devices_index] = optarg;
4974
                usb_devices_index++;
4975
                break;
4976
            case QEMU_OPTION_smp:
4977
                smp_cpus = atoi(optarg);
4978
                if (smp_cpus < 1) {
4979
                    fprintf(stderr, "Invalid number of CPUs\n");
4980
                    exit(1);
4981
                }
4982
                break;
4983
            case QEMU_OPTION_vnc:
4984
                vnc_display = optarg;
4985
                break;
4986
            case QEMU_OPTION_no_acpi:
4987
                acpi_enabled = 0;
4988
                break;
4989
            case QEMU_OPTION_no_reboot:
4990
                no_reboot = 1;
4991
                break;
4992
            case QEMU_OPTION_no_shutdown:
4993
                no_shutdown = 1;
4994
                break;
4995
            case QEMU_OPTION_show_cursor:
4996
                cursor_hide = 0;
4997
                break;
4998
            case QEMU_OPTION_uuid:
4999
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5000
                    fprintf(stderr, "Fail to parse UUID string."
5001
                            " Wrong format.\n");
5002
                    exit(1);
5003
                }
5004
                break;
5005
            case QEMU_OPTION_daemonize:
5006
                daemonize = 1;
5007
                break;
5008
            case QEMU_OPTION_option_rom:
5009
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5010
                    fprintf(stderr, "Too many option ROMs\n");
5011
                    exit(1);
5012
                }
5013
                option_rom[nb_option_roms] = optarg;
5014
                nb_option_roms++;
5015
                break;
5016
            case QEMU_OPTION_semihosting:
5017
                semihosting_enabled = 1;
5018
                break;
5019
            case QEMU_OPTION_name:
5020
                qemu_name = optarg;
5021
                break;
5022
#ifdef TARGET_SPARC
5023
            case QEMU_OPTION_prom_env:
5024
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5025
                    fprintf(stderr, "Too many prom variables\n");
5026
                    exit(1);
5027
                }
5028
                prom_envs[nb_prom_envs] = optarg;
5029
                nb_prom_envs++;
5030
                break;
5031
#endif
5032
#ifdef TARGET_ARM
5033
            case QEMU_OPTION_old_param:
5034
                old_param = 1;
5035
                break;
5036
#endif
5037
            case QEMU_OPTION_clock:
5038
                configure_alarms(optarg);
5039
                break;
5040
            case QEMU_OPTION_startdate:
5041
                {
5042
                    struct tm tm;
5043
                    time_t rtc_start_date;
5044
                    if (!strcmp(optarg, "now")) {
5045
                        rtc_date_offset = -1;
5046
                    } else {
5047
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5048
                               &tm.tm_year,
5049
                               &tm.tm_mon,
5050
                               &tm.tm_mday,
5051
                               &tm.tm_hour,
5052
                               &tm.tm_min,
5053
                               &tm.tm_sec) == 6) {
5054
                            /* OK */
5055
                        } else if (sscanf(optarg, "%d-%d-%d",
5056
                                          &tm.tm_year,
5057
                                          &tm.tm_mon,
5058
                                          &tm.tm_mday) == 3) {
5059
                            tm.tm_hour = 0;
5060
                            tm.tm_min = 0;
5061
                            tm.tm_sec = 0;
5062
                        } else {
5063
                            goto date_fail;
5064
                        }
5065
                        tm.tm_year -= 1900;
5066
                        tm.tm_mon--;
5067
                        rtc_start_date = mktimegm(&tm);
5068
                        if (rtc_start_date == -1) {
5069
                        date_fail:
5070
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
5071
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5072
                            exit(1);
5073
                        }
5074
                        rtc_date_offset = time(NULL) - rtc_start_date;
5075
                    }
5076
                }
5077
                break;
5078
            case QEMU_OPTION_tb_size:
5079
                tb_size = strtol(optarg, NULL, 0);
5080
                if (tb_size < 0)
5081
                    tb_size = 0;
5082
                break;
5083
            case QEMU_OPTION_icount:
5084
                use_icount = 1;
5085
                if (strcmp(optarg, "auto") == 0) {
5086
                    icount_time_shift = -1;
5087
                } else {
5088
                    icount_time_shift = strtol(optarg, NULL, 0);
5089
                }
5090
                break;
5091
            case QEMU_OPTION_incoming:
5092
                incoming = optarg;
5093
                break;
5094
            }
5095
        }
5096
    }
5097

    
5098
#if defined(CONFIG_KVM) && defined(USE_KQEMU)
5099
    if (kvm_allowed && kqemu_allowed) {
5100
        fprintf(stderr,
5101
                "You can not enable both KVM and kqemu at the same time\n");
5102
        exit(1);
5103
    }
5104
#endif
5105

    
5106
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5107
    if (smp_cpus > machine->max_cpus) {
5108
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5109
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5110
                machine->max_cpus);
5111
        exit(1);
5112
    }
5113

    
5114
    if (nographic) {
5115
       if (serial_device_index == 0)
5116
           serial_devices[0] = "stdio";
5117
       if (parallel_device_index == 0)
5118
           parallel_devices[0] = "null";
5119
       if (strncmp(monitor_device, "vc", 2) == 0)
5120
           monitor_device = "stdio";
5121
    }
5122

    
5123
#ifndef _WIN32
5124
    if (daemonize) {
5125
        pid_t pid;
5126

    
5127
        if (pipe(fds) == -1)
5128
            exit(1);
5129

    
5130
        pid = fork();
5131
        if (pid > 0) {
5132
            uint8_t status;
5133
            ssize_t len;
5134

    
5135
            close(fds[1]);
5136

    
5137
        again:
5138
            len = read(fds[0], &status, 1);
5139
            if (len == -1 && (errno == EINTR))
5140
                goto again;
5141

    
5142
            if (len != 1)
5143
                exit(1);
5144
            else if (status == 1) {
5145
                fprintf(stderr, "Could not acquire pidfile\n");
5146
                exit(1);
5147
            } else
5148
                exit(0);
5149
        } else if (pid < 0)
5150
            exit(1);
5151

    
5152
        setsid();
5153

    
5154
        pid = fork();
5155
        if (pid > 0)
5156
            exit(0);
5157
        else if (pid < 0)
5158
            exit(1);
5159

    
5160
        umask(027);
5161

    
5162
        signal(SIGTSTP, SIG_IGN);
5163
        signal(SIGTTOU, SIG_IGN);
5164
        signal(SIGTTIN, SIG_IGN);
5165
    }
5166
#endif
5167

    
5168
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5169
        if (daemonize) {
5170
            uint8_t status = 1;
5171
            write(fds[1], &status, 1);
5172
        } else
5173
            fprintf(stderr, "Could not acquire pid file\n");
5174
        exit(1);
5175
    }
5176

    
5177
#ifdef USE_KQEMU
5178
    if (smp_cpus > 1)
5179
        kqemu_allowed = 0;
5180
#endif
5181
    linux_boot = (kernel_filename != NULL);
5182
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5183

    
5184
    if (!linux_boot && net_boot == 0 &&
5185
        !machine->nodisk_ok && nb_drives_opt == 0)
5186
        help(1);
5187

    
5188
    if (!linux_boot && *kernel_cmdline != '\0') {
5189
        fprintf(stderr, "-append only allowed with -kernel option\n");
5190
        exit(1);
5191
    }
5192

    
5193
    if (!linux_boot && initrd_filename != NULL) {
5194
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5195
        exit(1);
5196
    }
5197

    
5198
    /* boot to floppy or the default cd if no hard disk defined yet */
5199
    if (!boot_devices[0]) {
5200
        boot_devices = "cad";
5201
    }
5202
    setvbuf(stdout, NULL, _IOLBF, 0);
5203

    
5204
    init_timers();
5205
    if (init_timer_alarm() < 0) {
5206
        fprintf(stderr, "could not initialize alarm timer\n");
5207
        exit(1);
5208
    }
5209
    if (use_icount && icount_time_shift < 0) {
5210
        use_icount = 2;
5211
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5212
           It will be corrected fairly quickly anyway.  */
5213
        icount_time_shift = 3;
5214
        init_icount_adjust();
5215
    }
5216

    
5217
#ifdef _WIN32
5218
    socket_init();
5219
#endif
5220

    
5221
    /* init network clients */
5222
    if (nb_net_clients == 0) {
5223
        /* if no clients, we use a default config */
5224
        net_clients[nb_net_clients++] = "nic";
5225
#ifdef CONFIG_SLIRP
5226
        net_clients[nb_net_clients++] = "user";
5227
#endif
5228
    }
5229

    
5230
    for(i = 0;i < nb_net_clients; i++) {
5231
        if (net_client_parse(net_clients[i]) < 0)
5232
            exit(1);
5233
    }
5234
    net_client_check();
5235

    
5236
#ifdef TARGET_I386
5237
    /* XXX: this should be moved in the PC machine instantiation code */
5238
    if (net_boot != 0) {
5239
        int netroms = 0;
5240
        for (i = 0; i < nb_nics && i < 4; i++) {
5241
            const char *model = nd_table[i].model;
5242
            char buf[1024];
5243
            if (net_boot & (1 << i)) {
5244
                if (model == NULL)
5245
                    model = "ne2k_pci";
5246
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5247
                if (get_image_size(buf) > 0) {
5248
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
5249
                        fprintf(stderr, "Too many option ROMs\n");
5250
                        exit(1);
5251
                    }
5252
                    option_rom[nb_option_roms] = strdup(buf);
5253
                    nb_option_roms++;
5254
                    netroms++;
5255
                }
5256
            }
5257
        }
5258
        if (netroms == 0) {
5259
            fprintf(stderr, "No valid PXE rom found for network device\n");
5260
            exit(1);
5261
        }
5262
    }
5263
#endif
5264

    
5265
    /* init the bluetooth world */
5266
    for (i = 0; i < nb_bt_opts; i++)
5267
        if (bt_parse(bt_opts[i]))
5268
            exit(1);
5269

    
5270
    /* init the memory */
5271
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5272

    
5273
    if (machine->ram_require & RAMSIZE_FIXED) {
5274
        if (ram_size > 0) {
5275
            if (ram_size < phys_ram_size) {
5276
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5277
                                machine->name, (unsigned long long) phys_ram_size);
5278
                exit(-1);
5279
            }
5280

    
5281
            phys_ram_size = ram_size;
5282
        } else
5283
            ram_size = phys_ram_size;
5284
    } else {
5285
        if (ram_size == 0)
5286
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5287

    
5288
        phys_ram_size += ram_size;
5289
    }
5290

    
5291
    phys_ram_base = qemu_vmalloc(phys_ram_size);
5292
    if (!phys_ram_base) {
5293
        fprintf(stderr, "Could not allocate physical memory\n");
5294
        exit(1);
5295
    }
5296

    
5297
    /* init the dynamic translator */
5298
    cpu_exec_init_all(tb_size * 1024 * 1024);
5299

    
5300
    bdrv_init();
5301

    
5302
    /* we always create the cdrom drive, even if no disk is there */
5303

    
5304
    if (nb_drives_opt < MAX_DRIVES)
5305
        drive_add(NULL, CDROM_ALIAS);
5306

    
5307
    /* we always create at least one floppy */
5308

    
5309
    if (nb_drives_opt < MAX_DRIVES)
5310
        drive_add(NULL, FD_ALIAS, 0);
5311

    
5312
    /* we always create one sd slot, even if no card is in it */
5313

    
5314
    if (nb_drives_opt < MAX_DRIVES)
5315
        drive_add(NULL, SD_ALIAS);
5316

    
5317
    /* open the virtual block devices */
5318

    
5319
    for(i = 0; i < nb_drives_opt; i++)
5320
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5321
            exit(1);
5322

    
5323
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5324
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5325

    
5326
    /* terminal init */
5327
    memset(&display_state, 0, sizeof(display_state));
5328
    if (nographic) {
5329
        if (curses) {
5330
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5331
            exit(1);
5332
        }
5333
        /* nearly nothing to do */
5334
        dumb_display_init(ds);
5335
    } else if (vnc_display != NULL) {
5336
        vnc_display_init(ds);
5337
        if (vnc_display_open(ds, vnc_display) < 0)
5338
            exit(1);
5339
    } else
5340
#if defined(CONFIG_CURSES)
5341
    if (curses) {
5342
        curses_display_init(ds, full_screen);
5343
    } else
5344
#endif
5345
    {
5346
#if defined(CONFIG_SDL)
5347
        sdl_display_init(ds, full_screen, no_frame);
5348
#elif defined(CONFIG_COCOA)
5349
        cocoa_display_init(ds, full_screen);
5350
#else
5351
        dumb_display_init(ds);
5352
#endif
5353
    }
5354

    
5355
#ifndef _WIN32
5356
    /* must be after terminal init, SDL library changes signal handlers */
5357
    termsig_setup();
5358
#endif
5359

    
5360
    /* Maintain compatibility with multiple stdio monitors */
5361
    if (!strcmp(monitor_device,"stdio")) {
5362
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5363
            const char *devname = serial_devices[i];
5364
            if (devname && !strcmp(devname,"mon:stdio")) {
5365
                monitor_device = NULL;
5366
                break;
5367
            } else if (devname && !strcmp(devname,"stdio")) {
5368
                monitor_device = NULL;
5369
                serial_devices[i] = "mon:stdio";
5370
                break;
5371
            }
5372
        }
5373
    }
5374
    if (monitor_device) {
5375
        monitor_hd = qemu_chr_open("monitor", monitor_device);
5376
        if (!monitor_hd) {
5377
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5378
            exit(1);
5379
        }
5380
        monitor_init(monitor_hd, !nographic);
5381
    }
5382

    
5383
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5384
        const char *devname = serial_devices[i];
5385
        if (devname && strcmp(devname, "none")) {
5386
            char label[32];
5387
            snprintf(label, sizeof(label), "serial%d", i);
5388
            serial_hds[i] = qemu_chr_open(label, devname);
5389
            if (!serial_hds[i]) {
5390
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
5391
                        devname);
5392
                exit(1);
5393
            }
5394
            if (strstart(devname, "vc", 0))
5395
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5396
        }
5397
    }
5398

    
5399
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5400
        const char *devname = parallel_devices[i];
5401
        if (devname && strcmp(devname, "none")) {
5402
            char label[32];
5403
            snprintf(label, sizeof(label), "parallel%d", i);
5404
            parallel_hds[i] = qemu_chr_open(label, devname);
5405
            if (!parallel_hds[i]) {
5406
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5407
                        devname);
5408
                exit(1);
5409
            }
5410
            if (strstart(devname, "vc", 0))
5411
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5412
        }
5413
    }
5414

    
5415
    if (kvm_enabled()) {
5416
        int ret;
5417

    
5418
        ret = kvm_init(smp_cpus);
5419
        if (ret < 0) {
5420
            fprintf(stderr, "failed to initialize KVM\n");
5421
            exit(1);
5422
        }
5423
    }
5424

    
5425
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
5426
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5427

    
5428
    /* init USB devices */
5429
    if (usb_enabled) {
5430
        for(i = 0; i < usb_devices_index; i++) {
5431
            if (usb_device_add(usb_devices[i]) < 0) {
5432
                fprintf(stderr, "Warning: could not add USB device %s\n",
5433
                        usb_devices[i]);
5434
            }
5435
        }
5436
    }
5437

    
5438
    if (display_state.dpy_refresh) {
5439
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5440
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5441
    }
5442

    
5443
#ifdef CONFIG_GDBSTUB
5444
    if (use_gdbstub) {
5445
        /* XXX: use standard host:port notation and modify options
5446
           accordingly. */
5447
        if (gdbserver_start(gdbstub_port) < 0) {
5448
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5449
                    gdbstub_port);
5450
            exit(1);
5451
        }
5452
    }
5453
#endif
5454

    
5455
    if (loadvm)
5456
        do_loadvm(loadvm);
5457

    
5458
    if (incoming) {
5459
        autostart = 0; /* fixme how to deal with -daemonize */
5460
        qemu_start_incoming_migration(incoming);
5461
    }
5462

    
5463
    {
5464
        /* XXX: simplify init */
5465
        read_passwords();
5466
        if (autostart) {
5467
            vm_start();
5468
        }
5469
    }
5470

    
5471
    if (daemonize) {
5472
        uint8_t status = 0;
5473
        ssize_t len;
5474
        int fd;
5475

    
5476
    again1:
5477
        len = write(fds[1], &status, 1);
5478
        if (len == -1 && (errno == EINTR))
5479
            goto again1;
5480

    
5481
        if (len != 1)
5482
            exit(1);
5483

    
5484
        chdir("/");
5485
        TFR(fd = open("/dev/null", O_RDWR));
5486
        if (fd == -1)
5487
            exit(1);
5488

    
5489
        dup2(fd, 0);
5490
        dup2(fd, 1);
5491
        dup2(fd, 2);
5492

    
5493
        close(fd);
5494
    }
5495

    
5496
    main_loop();
5497
    quit_timers();
5498
    net_cleanup();
5499

    
5500
    return 0;
5501
}