Statistics
| Branch: | Revision:

root / vl.c @ 62d23efa

History | View | Annotate | Download (145.3 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 <unistd.h>
25
#include <fcntl.h>
26
#include <signal.h>
27
#include <time.h>
28
#include <errno.h>
29
#include <sys/time.h>
30
#include <zlib.h>
31

    
32
/* Needed early for HOST_BSD etc. */
33
#include "config-host.h"
34

    
35
#ifndef _WIN32
36
#include <pwd.h>
37
#include <sys/times.h>
38
#include <sys/wait.h>
39
#include <termios.h>
40
#include <sys/mman.h>
41
#include <sys/ioctl.h>
42
#include <sys/resource.h>
43
#include <sys/socket.h>
44
#include <netinet/in.h>
45
#include <net/if.h>
46
#if defined(__NetBSD__)
47
#include <net/if_tap.h>
48
#endif
49
#ifdef __linux__
50
#include <linux/if_tun.h>
51
#endif
52
#include <arpa/inet.h>
53
#include <dirent.h>
54
#include <netdb.h>
55
#include <sys/select.h>
56
#ifdef HOST_BSD
57
#include <sys/stat.h>
58
#if defined(__FreeBSD__) || defined(__DragonFly__)
59
#include <libutil.h>
60
#else
61
#include <util.h>
62
#endif
63
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
64
#include <freebsd/stdlib.h>
65
#else
66
#ifdef __linux__
67
#include <pty.h>
68
#include <malloc.h>
69
#include <linux/rtc.h>
70

    
71
/* For the benefit of older linux systems which don't supply it,
72
   we use a local copy of hpet.h. */
73
/* #include <linux/hpet.h> */
74
#include "hpet.h"
75

    
76
#include <linux/ppdev.h>
77
#include <linux/parport.h>
78
#endif
79
#ifdef __sun__
80
#include <sys/stat.h>
81
#include <sys/ethernet.h>
82
#include <sys/sockio.h>
83
#include <netinet/arp.h>
84
#include <netinet/in.h>
85
#include <netinet/in_systm.h>
86
#include <netinet/ip.h>
87
#include <netinet/ip_icmp.h> // must come after ip.h
88
#include <netinet/udp.h>
89
#include <netinet/tcp.h>
90
#include <net/if.h>
91
#include <syslog.h>
92
#include <stropts.h>
93
#endif
94
#endif
95
#endif
96

    
97
#if defined(__OpenBSD__)
98
#include <util.h>
99
#endif
100

    
101
#if defined(CONFIG_VDE)
102
#include <libvdeplug.h>
103
#endif
104

    
105
#ifdef _WIN32
106
#include <windows.h>
107
#include <malloc.h>
108
#include <sys/timeb.h>
109
#include <mmsystem.h>
110
#define getopt_long_only getopt_long
111
#define memalign(align, size) malloc(size)
112
#endif
113

    
114
#ifdef CONFIG_SDL
115
#ifdef __APPLE__
116
#include <SDL/SDL.h>
117
int qemu_main(int argc, char **argv, char **envp);
118
int main(int argc, char **argv)
119
{
120
    qemu_main(argc, argv, NULL);
121
}
122
#undef main
123
#define main qemu_main
124
#endif
125
#endif /* CONFIG_SDL */
126

    
127
#ifdef CONFIG_COCOA
128
#undef main
129
#define main qemu_main
130
#endif /* CONFIG_COCOA */
131

    
132
#include "hw/hw.h"
133
#include "hw/boards.h"
134
#include "hw/usb.h"
135
#include "hw/pcmcia.h"
136
#include "hw/pc.h"
137
#include "hw/audiodev.h"
138
#include "hw/isa.h"
139
#include "hw/baum.h"
140
#include "hw/bt.h"
141
#include "hw/smbios.h"
142
#include "hw/xen.h"
143
#include "bt-host.h"
144
#include "net.h"
145
#include "monitor.h"
146
#include "console.h"
147
#include "sysemu.h"
148
#include "gdbstub.h"
149
#include "qemu-timer.h"
150
#include "qemu-char.h"
151
#include "cache-utils.h"
152
#include "block.h"
153
#include "dma.h"
154
#include "audio/audio.h"
155
#include "migration.h"
156
#include "kvm.h"
157
#include "balloon.h"
158

    
159
#include "disas.h"
160

    
161
#include "exec-all.h"
162

    
163
#include "qemu_socket.h"
164

    
165
#if defined(CONFIG_SLIRP)
166
#include "libslirp.h"
167
#endif
168

    
169
//#define DEBUG_UNUSED_IOPORT
170
//#define DEBUG_IOPORT
171
//#define DEBUG_NET
172
//#define DEBUG_SLIRP
173

    
174

    
175
#ifdef DEBUG_IOPORT
176
#  define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
177
#else
178
#  define LOG_IOPORT(...) do { } while (0)
179
#endif
180

    
181
#define DEFAULT_RAM_SIZE 128
182

    
183
/* Max number of USB devices that can be specified on the commandline.  */
184
#define MAX_USB_CMDLINE 8
185

    
186
/* Max number of bluetooth switches on the commandline.  */
187
#define MAX_BT_CMDLINE 10
188

    
189
/* XXX: use a two level table to limit memory usage */
190
#define MAX_IOPORTS 65536
191

    
192
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
193
const char *bios_name = NULL;
194
static void *ioport_opaque[MAX_IOPORTS];
195
static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
196
static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
197
/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
198
   to store the VM snapshots */
199
DriveInfo drives_table[MAX_DRIVES+1];
200
int nb_drives;
201
static int vga_ram_size;
202
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
203
static DisplayState *display_state;
204
int nographic;
205
static int curses;
206
static int sdl;
207
const char* keyboard_layout = NULL;
208
int64_t ticks_per_sec;
209
ram_addr_t ram_size;
210
int nb_nics;
211
NICInfo nd_table[MAX_NICS];
212
int vm_running;
213
static int autostart;
214
static int rtc_utc = 1;
215
static int rtc_date_offset = -1; /* -1 means no change */
216
int cirrus_vga_enabled = 1;
217
int std_vga_enabled = 0;
218
int vmsvga_enabled = 0;
219
#ifdef TARGET_SPARC
220
int graphic_width = 1024;
221
int graphic_height = 768;
222
int graphic_depth = 8;
223
#else
224
int graphic_width = 800;
225
int graphic_height = 600;
226
int graphic_depth = 15;
227
#endif
228
static int full_screen = 0;
229
#ifdef CONFIG_SDL
230
static int no_frame = 0;
231
#endif
232
int no_quit = 0;
233
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
234
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
235
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
236
#ifdef TARGET_I386
237
int win2k_install_hack = 0;
238
int rtc_td_hack = 0;
239
#endif
240
int usb_enabled = 0;
241
int singlestep = 0;
242
int smp_cpus = 1;
243
const char *vnc_display;
244
int acpi_enabled = 1;
245
int no_hpet = 0;
246
int fd_bootchk = 1;
247
int no_reboot = 0;
248
int no_shutdown = 0;
249
int cursor_hide = 1;
250
int graphic_rotate = 0;
251
#ifndef _WIN32
252
int daemonize = 0;
253
#endif
254
const char *option_rom[MAX_OPTION_ROMS];
255
int nb_option_roms;
256
int semihosting_enabled = 0;
257
#ifdef TARGET_ARM
258
int old_param = 0;
259
#endif
260
const char *qemu_name;
261
int alt_grab = 0;
262
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
263
unsigned int nb_prom_envs = 0;
264
const char *prom_envs[MAX_PROM_ENVS];
265
#endif
266
int nb_drives_opt;
267
struct drive_opt drives_opt[MAX_DRIVES];
268

    
269
int nb_numa_nodes;
270
uint64_t node_mem[MAX_NODES];
271
uint64_t node_cpumask[MAX_NODES];
272

    
273
static CPUState *cur_cpu;
274
static CPUState *next_cpu;
275
static int event_pending = 1;
276
/* Conversion factor from emulated instructions to virtual clock ticks.  */
277
static int icount_time_shift;
278
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
279
#define MAX_ICOUNT_SHIFT 10
280
/* Compensate for varying guest execution speed.  */
281
static int64_t qemu_icount_bias;
282
static QEMUTimer *icount_rt_timer;
283
static QEMUTimer *icount_vm_timer;
284
static QEMUTimer *nographic_timer;
285

    
286
uint8_t qemu_uuid[16];
287

    
288
/***********************************************************/
289
/* x86 ISA bus support */
290

    
291
target_phys_addr_t isa_mem_base = 0;
292
PicState2 *isa_pic;
293

    
294
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
295
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
296

    
297
static uint32_t ioport_read(int index, uint32_t address)
298
{
299
    static IOPortReadFunc *default_func[3] = {
300
        default_ioport_readb,
301
        default_ioport_readw,
302
        default_ioport_readl
303
    };
304
    IOPortReadFunc *func = ioport_read_table[index][address];
305
    if (!func)
306
        func = default_func[index];
307
    return func(ioport_opaque[address], address);
308
}
309

    
310
static void ioport_write(int index, uint32_t address, uint32_t data)
311
{
312
    static IOPortWriteFunc *default_func[3] = {
313
        default_ioport_writeb,
314
        default_ioport_writew,
315
        default_ioport_writel
316
    };
317
    IOPortWriteFunc *func = ioport_write_table[index][address];
318
    if (!func)
319
        func = default_func[index];
320
    func(ioport_opaque[address], address, data);
321
}
322

    
323
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
324
{
325
#ifdef DEBUG_UNUSED_IOPORT
326
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
327
#endif
328
    return 0xff;
329
}
330

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

    
338
/* default is to make two byte accesses */
339
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
340
{
341
    uint32_t data;
342
    data = ioport_read(0, address);
343
    address = (address + 1) & (MAX_IOPORTS - 1);
344
    data |= ioport_read(0, address) << 8;
345
    return data;
346
}
347

    
348
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
349
{
350
    ioport_write(0, address, data & 0xff);
351
    address = (address + 1) & (MAX_IOPORTS - 1);
352
    ioport_write(0, address, (data >> 8) & 0xff);
353
}
354

    
355
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
356
{
357
#ifdef DEBUG_UNUSED_IOPORT
358
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
359
#endif
360
    return 0xffffffff;
361
}
362

    
363
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
364
{
365
#ifdef DEBUG_UNUSED_IOPORT
366
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
367
#endif
368
}
369

    
370
/* size is the word size in byte */
371
int register_ioport_read(int start, int length, int size,
372
                         IOPortReadFunc *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_read: invalid size");
384
        return -1;
385
    }
386
    for(i = start; i < start + length; i += size) {
387
        ioport_read_table[bsize][i] = func;
388
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
389
            hw_error("register_ioport_read: invalid opaque");
390
        ioport_opaque[i] = opaque;
391
    }
392
    return 0;
393
}
394

    
395
/* size is the word size in byte */
396
int register_ioport_write(int start, int length, int size,
397
                          IOPortWriteFunc *func, void *opaque)
398
{
399
    int i, bsize;
400

    
401
    if (size == 1) {
402
        bsize = 0;
403
    } else if (size == 2) {
404
        bsize = 1;
405
    } else if (size == 4) {
406
        bsize = 2;
407
    } else {
408
        hw_error("register_ioport_write: invalid size");
409
        return -1;
410
    }
411
    for(i = start; i < start + length; i += size) {
412
        ioport_write_table[bsize][i] = func;
413
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
414
            hw_error("register_ioport_write: invalid opaque");
415
        ioport_opaque[i] = opaque;
416
    }
417
    return 0;
418
}
419

    
420
void isa_unassign_ioport(int start, int length)
421
{
422
    int i;
423

    
424
    for(i = start; i < start + length; i++) {
425
        ioport_read_table[0][i] = default_ioport_readb;
426
        ioport_read_table[1][i] = default_ioport_readw;
427
        ioport_read_table[2][i] = default_ioport_readl;
428

    
429
        ioport_write_table[0][i] = default_ioport_writeb;
430
        ioport_write_table[1][i] = default_ioport_writew;
431
        ioport_write_table[2][i] = default_ioport_writel;
432

    
433
        ioport_opaque[i] = NULL;
434
    }
435
}
436

    
437
/***********************************************************/
438

    
439
void cpu_outb(CPUState *env, int addr, int val)
440
{
441
    LOG_IOPORT("outb: %04x %02x\n", addr, val);
442
    ioport_write(0, addr, val);
443
#ifdef CONFIG_KQEMU
444
    if (env)
445
        env->last_io_time = cpu_get_time_fast();
446
#endif
447
}
448

    
449
void cpu_outw(CPUState *env, int addr, int val)
450
{
451
    LOG_IOPORT("outw: %04x %04x\n", addr, val);
452
    ioport_write(1, addr, val);
453
#ifdef CONFIG_KQEMU
454
    if (env)
455
        env->last_io_time = cpu_get_time_fast();
456
#endif
457
}
458

    
459
void cpu_outl(CPUState *env, int addr, int val)
460
{
461
    LOG_IOPORT("outl: %04x %08x\n", addr, val);
462
    ioport_write(2, addr, val);
463
#ifdef CONFIG_KQEMU
464
    if (env)
465
        env->last_io_time = cpu_get_time_fast();
466
#endif
467
}
468

    
469
int cpu_inb(CPUState *env, int addr)
470
{
471
    int val;
472
    val = ioport_read(0, addr);
473
    LOG_IOPORT("inb : %04x %02x\n", addr, val);
474
#ifdef CONFIG_KQEMU
475
    if (env)
476
        env->last_io_time = cpu_get_time_fast();
477
#endif
478
    return val;
479
}
480

    
481
int cpu_inw(CPUState *env, int addr)
482
{
483
    int val;
484
    val = ioport_read(1, addr);
485
    LOG_IOPORT("inw : %04x %04x\n", addr, val);
486
#ifdef CONFIG_KQEMU
487
    if (env)
488
        env->last_io_time = cpu_get_time_fast();
489
#endif
490
    return val;
491
}
492

    
493
int cpu_inl(CPUState *env, int addr)
494
{
495
    int val;
496
    val = ioport_read(2, addr);
497
    LOG_IOPORT("inl : %04x %08x\n", addr, val);
498
#ifdef CONFIG_KQEMU
499
    if (env)
500
        env->last_io_time = cpu_get_time_fast();
501
#endif
502
    return val;
503
}
504

    
505
/***********************************************************/
506
void hw_error(const char *fmt, ...)
507
{
508
    va_list ap;
509
    CPUState *env;
510

    
511
    va_start(ap, fmt);
512
    fprintf(stderr, "qemu: hardware error: ");
513
    vfprintf(stderr, fmt, ap);
514
    fprintf(stderr, "\n");
515
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
516
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
517
#ifdef TARGET_I386
518
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
519
#else
520
        cpu_dump_state(env, stderr, fprintf, 0);
521
#endif
522
    }
523
    va_end(ap);
524
    abort();
525
}
526
 
527
/***************/
528
/* ballooning */
529

    
530
static QEMUBalloonEvent *qemu_balloon_event;
531
void *qemu_balloon_event_opaque;
532

    
533
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
534
{
535
    qemu_balloon_event = func;
536
    qemu_balloon_event_opaque = opaque;
537
}
538

    
539
void qemu_balloon(ram_addr_t target)
540
{
541
    if (qemu_balloon_event)
542
        qemu_balloon_event(qemu_balloon_event_opaque, target);
543
}
544

    
545
ram_addr_t qemu_balloon_status(void)
546
{
547
    if (qemu_balloon_event)
548
        return qemu_balloon_event(qemu_balloon_event_opaque, 0);
549
    return 0;
550
}
551

    
552
/***********************************************************/
553
/* keyboard/mouse */
554

    
555
static QEMUPutKBDEvent *qemu_put_kbd_event;
556
static void *qemu_put_kbd_event_opaque;
557
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
558
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
559

    
560
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
561
{
562
    qemu_put_kbd_event_opaque = opaque;
563
    qemu_put_kbd_event = func;
564
}
565

    
566
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
567
                                                void *opaque, int absolute,
568
                                                const char *name)
569
{
570
    QEMUPutMouseEntry *s, *cursor;
571

    
572
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
573

    
574
    s->qemu_put_mouse_event = func;
575
    s->qemu_put_mouse_event_opaque = opaque;
576
    s->qemu_put_mouse_event_absolute = absolute;
577
    s->qemu_put_mouse_event_name = qemu_strdup(name);
578
    s->next = NULL;
579

    
580
    if (!qemu_put_mouse_event_head) {
581
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
582
        return s;
583
    }
584

    
585
    cursor = qemu_put_mouse_event_head;
586
    while (cursor->next != NULL)
587
        cursor = cursor->next;
588

    
589
    cursor->next = s;
590
    qemu_put_mouse_event_current = s;
591

    
592
    return s;
593
}
594

    
595
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
596
{
597
    QEMUPutMouseEntry *prev = NULL, *cursor;
598

    
599
    if (!qemu_put_mouse_event_head || entry == NULL)
600
        return;
601

    
602
    cursor = qemu_put_mouse_event_head;
603
    while (cursor != NULL && cursor != entry) {
604
        prev = cursor;
605
        cursor = cursor->next;
606
    }
607

    
608
    if (cursor == NULL) // does not exist or list empty
609
        return;
610
    else if (prev == NULL) { // entry is head
611
        qemu_put_mouse_event_head = cursor->next;
612
        if (qemu_put_mouse_event_current == entry)
613
            qemu_put_mouse_event_current = cursor->next;
614
        qemu_free(entry->qemu_put_mouse_event_name);
615
        qemu_free(entry);
616
        return;
617
    }
618

    
619
    prev->next = entry->next;
620

    
621
    if (qemu_put_mouse_event_current == entry)
622
        qemu_put_mouse_event_current = prev;
623

    
624
    qemu_free(entry->qemu_put_mouse_event_name);
625
    qemu_free(entry);
626
}
627

    
628
void kbd_put_keycode(int keycode)
629
{
630
    if (qemu_put_kbd_event) {
631
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
632
    }
633
}
634

    
635
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
636
{
637
    QEMUPutMouseEvent *mouse_event;
638
    void *mouse_event_opaque;
639
    int width;
640

    
641
    if (!qemu_put_mouse_event_current) {
642
        return;
643
    }
644

    
645
    mouse_event =
646
        qemu_put_mouse_event_current->qemu_put_mouse_event;
647
    mouse_event_opaque =
648
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
649

    
650
    if (mouse_event) {
651
        if (graphic_rotate) {
652
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
653
                width = 0x7fff;
654
            else
655
                width = graphic_width - 1;
656
            mouse_event(mouse_event_opaque,
657
                                 width - dy, dx, dz, buttons_state);
658
        } else
659
            mouse_event(mouse_event_opaque,
660
                                 dx, dy, dz, buttons_state);
661
    }
662
}
663

    
664
int kbd_mouse_is_absolute(void)
665
{
666
    if (!qemu_put_mouse_event_current)
667
        return 0;
668

    
669
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
670
}
671

    
672
void do_info_mice(Monitor *mon)
673
{
674
    QEMUPutMouseEntry *cursor;
675
    int index = 0;
676

    
677
    if (!qemu_put_mouse_event_head) {
678
        monitor_printf(mon, "No mouse devices connected\n");
679
        return;
680
    }
681

    
682
    monitor_printf(mon, "Mouse devices available:\n");
683
    cursor = qemu_put_mouse_event_head;
684
    while (cursor != NULL) {
685
        monitor_printf(mon, "%c Mouse #%d: %s\n",
686
                       (cursor == qemu_put_mouse_event_current ? '*' : ' '),
687
                       index, cursor->qemu_put_mouse_event_name);
688
        index++;
689
        cursor = cursor->next;
690
    }
691
}
692

    
693
void do_mouse_set(Monitor *mon, int index)
694
{
695
    QEMUPutMouseEntry *cursor;
696
    int i = 0;
697

    
698
    if (!qemu_put_mouse_event_head) {
699
        monitor_printf(mon, "No mouse devices connected\n");
700
        return;
701
    }
702

    
703
    cursor = qemu_put_mouse_event_head;
704
    while (cursor != NULL && index != i) {
705
        i++;
706
        cursor = cursor->next;
707
    }
708

    
709
    if (cursor != NULL)
710
        qemu_put_mouse_event_current = cursor;
711
    else
712
        monitor_printf(mon, "Mouse at given index not found\n");
713
}
714

    
715
/* compute with 96 bit intermediate result: (a*b)/c */
716
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
717
{
718
    union {
719
        uint64_t ll;
720
        struct {
721
#ifdef WORDS_BIGENDIAN
722
            uint32_t high, low;
723
#else
724
            uint32_t low, high;
725
#endif
726
        } l;
727
    } u, res;
728
    uint64_t rl, rh;
729

    
730
    u.ll = a;
731
    rl = (uint64_t)u.l.low * (uint64_t)b;
732
    rh = (uint64_t)u.l.high * (uint64_t)b;
733
    rh += (rl >> 32);
734
    res.l.high = rh / c;
735
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
736
    return res.ll;
737
}
738

    
739
/***********************************************************/
740
/* real time host monotonic timer */
741

    
742
#define QEMU_TIMER_BASE 1000000000LL
743

    
744
#ifdef WIN32
745

    
746
static int64_t clock_freq;
747

    
748
static void init_get_clock(void)
749
{
750
    LARGE_INTEGER freq;
751
    int ret;
752
    ret = QueryPerformanceFrequency(&freq);
753
    if (ret == 0) {
754
        fprintf(stderr, "Could not calibrate ticks\n");
755
        exit(1);
756
    }
757
    clock_freq = freq.QuadPart;
758
}
759

    
760
static int64_t get_clock(void)
761
{
762
    LARGE_INTEGER ti;
763
    QueryPerformanceCounter(&ti);
764
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
765
}
766

    
767
#else
768

    
769
static int use_rt_clock;
770

    
771
static void init_get_clock(void)
772
{
773
    use_rt_clock = 0;
774
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
775
    || defined(__DragonFly__)
776
    {
777
        struct timespec ts;
778
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
779
            use_rt_clock = 1;
780
        }
781
    }
782
#endif
783
}
784

    
785
static int64_t get_clock(void)
786
{
787
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
788
        || defined(__DragonFly__)
789
    if (use_rt_clock) {
790
        struct timespec ts;
791
        clock_gettime(CLOCK_MONOTONIC, &ts);
792
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
793
    } else
794
#endif
795
    {
796
        /* XXX: using gettimeofday leads to problems if the date
797
           changes, so it should be avoided. */
798
        struct timeval tv;
799
        gettimeofday(&tv, NULL);
800
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
801
    }
802
}
803
#endif
804

    
805
/* Return the virtual CPU time, based on the instruction counter.  */
806
static int64_t cpu_get_icount(void)
807
{
808
    int64_t icount;
809
    CPUState *env = cpu_single_env;;
810
    icount = qemu_icount;
811
    if (env) {
812
        if (!can_do_io(env))
813
            fprintf(stderr, "Bad clock read\n");
814
        icount -= (env->icount_decr.u16.low + env->icount_extra);
815
    }
816
    return qemu_icount_bias + (icount << icount_time_shift);
817
}
818

    
819
/***********************************************************/
820
/* guest cycle counter */
821

    
822
static int64_t cpu_ticks_prev;
823
static int64_t cpu_ticks_offset;
824
static int64_t cpu_clock_offset;
825
static int cpu_ticks_enabled;
826

    
827
/* return the host CPU cycle counter and handle stop/restart */
828
int64_t cpu_get_ticks(void)
829
{
830
    if (use_icount) {
831
        return cpu_get_icount();
832
    }
833
    if (!cpu_ticks_enabled) {
834
        return cpu_ticks_offset;
835
    } else {
836
        int64_t ticks;
837
        ticks = cpu_get_real_ticks();
838
        if (cpu_ticks_prev > ticks) {
839
            /* Note: non increasing ticks may happen if the host uses
840
               software suspend */
841
            cpu_ticks_offset += cpu_ticks_prev - ticks;
842
        }
843
        cpu_ticks_prev = ticks;
844
        return ticks + cpu_ticks_offset;
845
    }
846
}
847

    
848
/* return the host CPU monotonic timer and handle stop/restart */
849
static int64_t cpu_get_clock(void)
850
{
851
    int64_t ti;
852
    if (!cpu_ticks_enabled) {
853
        return cpu_clock_offset;
854
    } else {
855
        ti = get_clock();
856
        return ti + cpu_clock_offset;
857
    }
858
}
859

    
860
/* enable cpu_get_ticks() */
861
void cpu_enable_ticks(void)
862
{
863
    if (!cpu_ticks_enabled) {
864
        cpu_ticks_offset -= cpu_get_real_ticks();
865
        cpu_clock_offset -= get_clock();
866
        cpu_ticks_enabled = 1;
867
    }
868
}
869

    
870
/* disable cpu_get_ticks() : the clock is stopped. You must not call
871
   cpu_get_ticks() after that.  */
872
void cpu_disable_ticks(void)
873
{
874
    if (cpu_ticks_enabled) {
875
        cpu_ticks_offset = cpu_get_ticks();
876
        cpu_clock_offset = cpu_get_clock();
877
        cpu_ticks_enabled = 0;
878
    }
879
}
880

    
881
/***********************************************************/
882
/* timers */
883

    
884
#define QEMU_TIMER_REALTIME 0
885
#define QEMU_TIMER_VIRTUAL  1
886

    
887
struct QEMUClock {
888
    int type;
889
    /* XXX: add frequency */
890
};
891

    
892
struct QEMUTimer {
893
    QEMUClock *clock;
894
    int64_t expire_time;
895
    QEMUTimerCB *cb;
896
    void *opaque;
897
    struct QEMUTimer *next;
898
};
899

    
900
struct qemu_alarm_timer {
901
    char const *name;
902
    unsigned int flags;
903

    
904
    int (*start)(struct qemu_alarm_timer *t);
905
    void (*stop)(struct qemu_alarm_timer *t);
906
    void (*rearm)(struct qemu_alarm_timer *t);
907
    void *priv;
908
};
909

    
910
#define ALARM_FLAG_DYNTICKS  0x1
911
#define ALARM_FLAG_EXPIRED   0x2
912

    
913
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
914
{
915
    return t->flags & ALARM_FLAG_DYNTICKS;
916
}
917

    
918
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
919
{
920
    if (!alarm_has_dynticks(t))
921
        return;
922

    
923
    t->rearm(t);
924
}
925

    
926
/* TODO: MIN_TIMER_REARM_US should be optimized */
927
#define MIN_TIMER_REARM_US 250
928

    
929
static struct qemu_alarm_timer *alarm_timer;
930
#ifndef _WIN32
931
static int alarm_timer_rfd, alarm_timer_wfd;
932
#endif
933

    
934
#ifdef _WIN32
935

    
936
struct qemu_alarm_win32 {
937
    MMRESULT timerId;
938
    HANDLE host_alarm;
939
    unsigned int period;
940
} alarm_win32_data = {0, NULL, -1};
941

    
942
static int win32_start_timer(struct qemu_alarm_timer *t);
943
static void win32_stop_timer(struct qemu_alarm_timer *t);
944
static void win32_rearm_timer(struct qemu_alarm_timer *t);
945

    
946
#else
947

    
948
static int unix_start_timer(struct qemu_alarm_timer *t);
949
static void unix_stop_timer(struct qemu_alarm_timer *t);
950

    
951
#ifdef __linux__
952

    
953
static int dynticks_start_timer(struct qemu_alarm_timer *t);
954
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
955
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
956

    
957
static int hpet_start_timer(struct qemu_alarm_timer *t);
958
static void hpet_stop_timer(struct qemu_alarm_timer *t);
959

    
960
static int rtc_start_timer(struct qemu_alarm_timer *t);
961
static void rtc_stop_timer(struct qemu_alarm_timer *t);
962

    
963
#endif /* __linux__ */
964

    
965
#endif /* _WIN32 */
966

    
967
/* Correlation between real and virtual time is always going to be
968
   fairly approximate, so ignore small variation.
969
   When the guest is idle real and virtual time will be aligned in
970
   the IO wait loop.  */
971
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
972

    
973
static void icount_adjust(void)
974
{
975
    int64_t cur_time;
976
    int64_t cur_icount;
977
    int64_t delta;
978
    static int64_t last_delta;
979
    /* If the VM is not running, then do nothing.  */
980
    if (!vm_running)
981
        return;
982

    
983
    cur_time = cpu_get_clock();
984
    cur_icount = qemu_get_clock(vm_clock);
985
    delta = cur_icount - cur_time;
986
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
987
    if (delta > 0
988
        && last_delta + ICOUNT_WOBBLE < delta * 2
989
        && icount_time_shift > 0) {
990
        /* The guest is getting too far ahead.  Slow time down.  */
991
        icount_time_shift--;
992
    }
993
    if (delta < 0
994
        && last_delta - ICOUNT_WOBBLE > delta * 2
995
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
996
        /* The guest is getting too far behind.  Speed time up.  */
997
        icount_time_shift++;
998
    }
999
    last_delta = delta;
1000
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1001
}
1002

    
1003
static void icount_adjust_rt(void * opaque)
1004
{
1005
    qemu_mod_timer(icount_rt_timer,
1006
                   qemu_get_clock(rt_clock) + 1000);
1007
    icount_adjust();
1008
}
1009

    
1010
static void icount_adjust_vm(void * opaque)
1011
{
1012
    qemu_mod_timer(icount_vm_timer,
1013
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1014
    icount_adjust();
1015
}
1016

    
1017
static void init_icount_adjust(void)
1018
{
1019
    /* Have both realtime and virtual time triggers for speed adjustment.
1020
       The realtime trigger catches emulated time passing too slowly,
1021
       the virtual time trigger catches emulated time passing too fast.
1022
       Realtime triggers occur even when idle, so use them less frequently
1023
       than VM triggers.  */
1024
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1025
    qemu_mod_timer(icount_rt_timer,
1026
                   qemu_get_clock(rt_clock) + 1000);
1027
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1028
    qemu_mod_timer(icount_vm_timer,
1029
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1030
}
1031

    
1032
static struct qemu_alarm_timer alarm_timers[] = {
1033
#ifndef _WIN32
1034
#ifdef __linux__
1035
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1036
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
1037
    /* HPET - if available - is preferred */
1038
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1039
    /* ...otherwise try RTC */
1040
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1041
#endif
1042
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1043
#else
1044
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1045
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1046
    {"win32", 0, win32_start_timer,
1047
     win32_stop_timer, NULL, &alarm_win32_data},
1048
#endif
1049
    {NULL, }
1050
};
1051

    
1052
static void show_available_alarms(void)
1053
{
1054
    int i;
1055

    
1056
    printf("Available alarm timers, in order of precedence:\n");
1057
    for (i = 0; alarm_timers[i].name; i++)
1058
        printf("%s\n", alarm_timers[i].name);
1059
}
1060

    
1061
static void configure_alarms(char const *opt)
1062
{
1063
    int i;
1064
    int cur = 0;
1065
    int count = ARRAY_SIZE(alarm_timers) - 1;
1066
    char *arg;
1067
    char *name;
1068
    struct qemu_alarm_timer tmp;
1069

    
1070
    if (!strcmp(opt, "?")) {
1071
        show_available_alarms();
1072
        exit(0);
1073
    }
1074

    
1075
    arg = strdup(opt);
1076

    
1077
    /* Reorder the array */
1078
    name = strtok(arg, ",");
1079
    while (name) {
1080
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1081
            if (!strcmp(alarm_timers[i].name, name))
1082
                break;
1083
        }
1084

    
1085
        if (i == count) {
1086
            fprintf(stderr, "Unknown clock %s\n", name);
1087
            goto next;
1088
        }
1089

    
1090
        if (i < cur)
1091
            /* Ignore */
1092
            goto next;
1093

    
1094
        /* Swap */
1095
        tmp = alarm_timers[i];
1096
        alarm_timers[i] = alarm_timers[cur];
1097
        alarm_timers[cur] = tmp;
1098

    
1099
        cur++;
1100
next:
1101
        name = strtok(NULL, ",");
1102
    }
1103

    
1104
    free(arg);
1105

    
1106
    if (cur) {
1107
        /* Disable remaining timers */
1108
        for (i = cur; i < count; i++)
1109
            alarm_timers[i].name = NULL;
1110
    } else {
1111
        show_available_alarms();
1112
        exit(1);
1113
    }
1114
}
1115

    
1116
QEMUClock *rt_clock;
1117
QEMUClock *vm_clock;
1118

    
1119
static QEMUTimer *active_timers[2];
1120

    
1121
static QEMUClock *qemu_new_clock(int type)
1122
{
1123
    QEMUClock *clock;
1124
    clock = qemu_mallocz(sizeof(QEMUClock));
1125
    clock->type = type;
1126
    return clock;
1127
}
1128

    
1129
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1130
{
1131
    QEMUTimer *ts;
1132

    
1133
    ts = qemu_mallocz(sizeof(QEMUTimer));
1134
    ts->clock = clock;
1135
    ts->cb = cb;
1136
    ts->opaque = opaque;
1137
    return ts;
1138
}
1139

    
1140
void qemu_free_timer(QEMUTimer *ts)
1141
{
1142
    qemu_free(ts);
1143
}
1144

    
1145
/* stop a timer, but do not dealloc it */
1146
void qemu_del_timer(QEMUTimer *ts)
1147
{
1148
    QEMUTimer **pt, *t;
1149

    
1150
    /* NOTE: this code must be signal safe because
1151
       qemu_timer_expired() can be called from a signal. */
1152
    pt = &active_timers[ts->clock->type];
1153
    for(;;) {
1154
        t = *pt;
1155
        if (!t)
1156
            break;
1157
        if (t == ts) {
1158
            *pt = t->next;
1159
            break;
1160
        }
1161
        pt = &t->next;
1162
    }
1163
}
1164

    
1165
/* modify the current timer so that it will be fired when current_time
1166
   >= expire_time. The corresponding callback will be called. */
1167
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1168
{
1169
    QEMUTimer **pt, *t;
1170

    
1171
    qemu_del_timer(ts);
1172

    
1173
    /* add the timer in the sorted list */
1174
    /* NOTE: this code must be signal safe because
1175
       qemu_timer_expired() can be called from a signal. */
1176
    pt = &active_timers[ts->clock->type];
1177
    for(;;) {
1178
        t = *pt;
1179
        if (!t)
1180
            break;
1181
        if (t->expire_time > expire_time)
1182
            break;
1183
        pt = &t->next;
1184
    }
1185
    ts->expire_time = expire_time;
1186
    ts->next = *pt;
1187
    *pt = ts;
1188

    
1189
    /* Rearm if necessary  */
1190
    if (pt == &active_timers[ts->clock->type]) {
1191
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1192
            qemu_rearm_alarm_timer(alarm_timer);
1193
        }
1194
        /* Interrupt execution to force deadline recalculation.  */
1195
        if (use_icount && cpu_single_env) {
1196
            cpu_exit(cpu_single_env);
1197
        }
1198
    }
1199
}
1200

    
1201
int qemu_timer_pending(QEMUTimer *ts)
1202
{
1203
    QEMUTimer *t;
1204
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1205
        if (t == ts)
1206
            return 1;
1207
    }
1208
    return 0;
1209
}
1210

    
1211
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1212
{
1213
    if (!timer_head)
1214
        return 0;
1215
    return (timer_head->expire_time <= current_time);
1216
}
1217

    
1218
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1219
{
1220
    QEMUTimer *ts;
1221

    
1222
    for(;;) {
1223
        ts = *ptimer_head;
1224
        if (!ts || ts->expire_time > current_time)
1225
            break;
1226
        /* remove timer from the list before calling the callback */
1227
        *ptimer_head = ts->next;
1228
        ts->next = NULL;
1229

    
1230
        /* run the callback (the timer list can be modified) */
1231
        ts->cb(ts->opaque);
1232
    }
1233
}
1234

    
1235
int64_t qemu_get_clock(QEMUClock *clock)
1236
{
1237
    switch(clock->type) {
1238
    case QEMU_TIMER_REALTIME:
1239
        return get_clock() / 1000000;
1240
    default:
1241
    case QEMU_TIMER_VIRTUAL:
1242
        if (use_icount) {
1243
            return cpu_get_icount();
1244
        } else {
1245
            return cpu_get_clock();
1246
        }
1247
    }
1248
}
1249

    
1250
static void init_timers(void)
1251
{
1252
    init_get_clock();
1253
    ticks_per_sec = QEMU_TIMER_BASE;
1254
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1255
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1256
}
1257

    
1258
/* save a timer */
1259
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1260
{
1261
    uint64_t expire_time;
1262

    
1263
    if (qemu_timer_pending(ts)) {
1264
        expire_time = ts->expire_time;
1265
    } else {
1266
        expire_time = -1;
1267
    }
1268
    qemu_put_be64(f, expire_time);
1269
}
1270

    
1271
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1272
{
1273
    uint64_t expire_time;
1274

    
1275
    expire_time = qemu_get_be64(f);
1276
    if (expire_time != -1) {
1277
        qemu_mod_timer(ts, expire_time);
1278
    } else {
1279
        qemu_del_timer(ts);
1280
    }
1281
}
1282

    
1283
static void timer_save(QEMUFile *f, void *opaque)
1284
{
1285
    if (cpu_ticks_enabled) {
1286
        hw_error("cannot save state if virtual timers are running");
1287
    }
1288
    qemu_put_be64(f, cpu_ticks_offset);
1289
    qemu_put_be64(f, ticks_per_sec);
1290
    qemu_put_be64(f, cpu_clock_offset);
1291
}
1292

    
1293
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1294
{
1295
    if (version_id != 1 && version_id != 2)
1296
        return -EINVAL;
1297
    if (cpu_ticks_enabled) {
1298
        return -EINVAL;
1299
    }
1300
    cpu_ticks_offset=qemu_get_be64(f);
1301
    ticks_per_sec=qemu_get_be64(f);
1302
    if (version_id == 2) {
1303
        cpu_clock_offset=qemu_get_be64(f);
1304
    }
1305
    return 0;
1306
}
1307

    
1308
#ifdef _WIN32
1309
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1310
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
1311
                                        DWORD_PTR dw2)
1312
#else
1313
static void host_alarm_handler(int host_signum)
1314
#endif
1315
{
1316
#if 0
1317
#define DISP_FREQ 1000
1318
    {
1319
        static int64_t delta_min = INT64_MAX;
1320
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1321
        static int count;
1322
        ti = qemu_get_clock(vm_clock);
1323
        if (last_clock != 0) {
1324
            delta = ti - last_clock;
1325
            if (delta < delta_min)
1326
                delta_min = delta;
1327
            if (delta > delta_max)
1328
                delta_max = delta;
1329
            delta_cum += delta;
1330
            if (++count == DISP_FREQ) {
1331
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1332
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1333
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1334
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1335
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1336
                count = 0;
1337
                delta_min = INT64_MAX;
1338
                delta_max = 0;
1339
                delta_cum = 0;
1340
            }
1341
        }
1342
        last_clock = ti;
1343
    }
1344
#endif
1345
    if (alarm_has_dynticks(alarm_timer) ||
1346
        (!use_icount &&
1347
            qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1348
                               qemu_get_clock(vm_clock))) ||
1349
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1350
                           qemu_get_clock(rt_clock))) {
1351
        CPUState *env = next_cpu;
1352

    
1353
#ifdef _WIN32
1354
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1355
        SetEvent(data->host_alarm);
1356
#else
1357
        static const char byte = 0;
1358
        write(alarm_timer_wfd, &byte, sizeof(byte));
1359
#endif
1360
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1361

    
1362
        if (env) {
1363
            /* stop the currently executing cpu because a timer occured */
1364
            cpu_exit(env);
1365
#ifdef CONFIG_KQEMU
1366
            if (env->kqemu_enabled) {
1367
                kqemu_cpu_interrupt(env);
1368
            }
1369
#endif
1370
        }
1371
        event_pending = 1;
1372
    }
1373
}
1374

    
1375
static int64_t qemu_next_deadline(void)
1376
{
1377
    int64_t delta;
1378

    
1379
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1380
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1381
                     qemu_get_clock(vm_clock);
1382
    } else {
1383
        /* To avoid problems with overflow limit this to 2^32.  */
1384
        delta = INT32_MAX;
1385
    }
1386

    
1387
    if (delta < 0)
1388
        delta = 0;
1389

    
1390
    return delta;
1391
}
1392

    
1393
#if defined(__linux__) || defined(_WIN32)
1394
static uint64_t qemu_next_deadline_dyntick(void)
1395
{
1396
    int64_t delta;
1397
    int64_t rtdelta;
1398

    
1399
    if (use_icount)
1400
        delta = INT32_MAX;
1401
    else
1402
        delta = (qemu_next_deadline() + 999) / 1000;
1403

    
1404
    if (active_timers[QEMU_TIMER_REALTIME]) {
1405
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1406
                 qemu_get_clock(rt_clock))*1000;
1407
        if (rtdelta < delta)
1408
            delta = rtdelta;
1409
    }
1410

    
1411
    if (delta < MIN_TIMER_REARM_US)
1412
        delta = MIN_TIMER_REARM_US;
1413

    
1414
    return delta;
1415
}
1416
#endif
1417

    
1418
#ifndef _WIN32
1419

    
1420
/* Sets a specific flag */
1421
static int fcntl_setfl(int fd, int flag)
1422
{
1423
    int flags;
1424

    
1425
    flags = fcntl(fd, F_GETFL);
1426
    if (flags == -1)
1427
        return -errno;
1428

    
1429
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1430
        return -errno;
1431

    
1432
    return 0;
1433
}
1434

    
1435
#if defined(__linux__)
1436

    
1437
#define RTC_FREQ 1024
1438

    
1439
static void enable_sigio_timer(int fd)
1440
{
1441
    struct sigaction act;
1442

    
1443
    /* timer signal */
1444
    sigfillset(&act.sa_mask);
1445
    act.sa_flags = 0;
1446
    act.sa_handler = host_alarm_handler;
1447

    
1448
    sigaction(SIGIO, &act, NULL);
1449
    fcntl_setfl(fd, O_ASYNC);
1450
    fcntl(fd, F_SETOWN, getpid());
1451
}
1452

    
1453
static int hpet_start_timer(struct qemu_alarm_timer *t)
1454
{
1455
    struct hpet_info info;
1456
    int r, fd;
1457

    
1458
    fd = open("/dev/hpet", O_RDONLY);
1459
    if (fd < 0)
1460
        return -1;
1461

    
1462
    /* Set frequency */
1463
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1464
    if (r < 0) {
1465
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1466
                "error, but for better emulation accuracy type:\n"
1467
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1468
        goto fail;
1469
    }
1470

    
1471
    /* Check capabilities */
1472
    r = ioctl(fd, HPET_INFO, &info);
1473
    if (r < 0)
1474
        goto fail;
1475

    
1476
    /* Enable periodic mode */
1477
    r = ioctl(fd, HPET_EPI, 0);
1478
    if (info.hi_flags && (r < 0))
1479
        goto fail;
1480

    
1481
    /* Enable interrupt */
1482
    r = ioctl(fd, HPET_IE_ON, 0);
1483
    if (r < 0)
1484
        goto fail;
1485

    
1486
    enable_sigio_timer(fd);
1487
    t->priv = (void *)(long)fd;
1488

    
1489
    return 0;
1490
fail:
1491
    close(fd);
1492
    return -1;
1493
}
1494

    
1495
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1496
{
1497
    int fd = (long)t->priv;
1498

    
1499
    close(fd);
1500
}
1501

    
1502
static int rtc_start_timer(struct qemu_alarm_timer *t)
1503
{
1504
    int rtc_fd;
1505
    unsigned long current_rtc_freq = 0;
1506

    
1507
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1508
    if (rtc_fd < 0)
1509
        return -1;
1510
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1511
    if (current_rtc_freq != RTC_FREQ &&
1512
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1513
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1514
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1515
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1516
        goto fail;
1517
    }
1518
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1519
    fail:
1520
        close(rtc_fd);
1521
        return -1;
1522
    }
1523

    
1524
    enable_sigio_timer(rtc_fd);
1525

    
1526
    t->priv = (void *)(long)rtc_fd;
1527

    
1528
    return 0;
1529
}
1530

    
1531
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1532
{
1533
    int rtc_fd = (long)t->priv;
1534

    
1535
    close(rtc_fd);
1536
}
1537

    
1538
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1539
{
1540
    struct sigevent ev;
1541
    timer_t host_timer;
1542
    struct sigaction act;
1543

    
1544
    sigfillset(&act.sa_mask);
1545
    act.sa_flags = 0;
1546
    act.sa_handler = host_alarm_handler;
1547

    
1548
    sigaction(SIGALRM, &act, NULL);
1549

    
1550
    ev.sigev_value.sival_int = 0;
1551
    ev.sigev_notify = SIGEV_SIGNAL;
1552
    ev.sigev_signo = SIGALRM;
1553

    
1554
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1555
        perror("timer_create");
1556

    
1557
        /* disable dynticks */
1558
        fprintf(stderr, "Dynamic Ticks disabled\n");
1559

    
1560
        return -1;
1561
    }
1562

    
1563
    t->priv = (void *)(long)host_timer;
1564

    
1565
    return 0;
1566
}
1567

    
1568
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1569
{
1570
    timer_t host_timer = (timer_t)(long)t->priv;
1571

    
1572
    timer_delete(host_timer);
1573
}
1574

    
1575
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1576
{
1577
    timer_t host_timer = (timer_t)(long)t->priv;
1578
    struct itimerspec timeout;
1579
    int64_t nearest_delta_us = INT64_MAX;
1580
    int64_t current_us;
1581

    
1582
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1583
                !active_timers[QEMU_TIMER_VIRTUAL])
1584
        return;
1585

    
1586
    nearest_delta_us = qemu_next_deadline_dyntick();
1587

    
1588
    /* check whether a timer is already running */
1589
    if (timer_gettime(host_timer, &timeout)) {
1590
        perror("gettime");
1591
        fprintf(stderr, "Internal timer error: aborting\n");
1592
        exit(1);
1593
    }
1594
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1595
    if (current_us && current_us <= nearest_delta_us)
1596
        return;
1597

    
1598
    timeout.it_interval.tv_sec = 0;
1599
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1600
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1601
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1602
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1603
        perror("settime");
1604
        fprintf(stderr, "Internal timer error: aborting\n");
1605
        exit(1);
1606
    }
1607
}
1608

    
1609
#endif /* defined(__linux__) */
1610

    
1611
static int unix_start_timer(struct qemu_alarm_timer *t)
1612
{
1613
    struct sigaction act;
1614
    struct itimerval itv;
1615
    int err;
1616

    
1617
    /* timer signal */
1618
    sigfillset(&act.sa_mask);
1619
    act.sa_flags = 0;
1620
    act.sa_handler = host_alarm_handler;
1621

    
1622
    sigaction(SIGALRM, &act, NULL);
1623

    
1624
    itv.it_interval.tv_sec = 0;
1625
    /* for i386 kernel 2.6 to get 1 ms */
1626
    itv.it_interval.tv_usec = 999;
1627
    itv.it_value.tv_sec = 0;
1628
    itv.it_value.tv_usec = 10 * 1000;
1629

    
1630
    err = setitimer(ITIMER_REAL, &itv, NULL);
1631
    if (err)
1632
        return -1;
1633

    
1634
    return 0;
1635
}
1636

    
1637
static void unix_stop_timer(struct qemu_alarm_timer *t)
1638
{
1639
    struct itimerval itv;
1640

    
1641
    memset(&itv, 0, sizeof(itv));
1642
    setitimer(ITIMER_REAL, &itv, NULL);
1643
}
1644

    
1645
#endif /* !defined(_WIN32) */
1646

    
1647
static void try_to_rearm_timer(void *opaque)
1648
{
1649
    struct qemu_alarm_timer *t = opaque;
1650
#ifndef _WIN32
1651
    ssize_t len;
1652

    
1653
    /* Drain the notify pipe */
1654
    do {
1655
        char buffer[512];
1656
        len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1657
    } while ((len == -1 && errno == EINTR) || len > 0);
1658
#endif
1659

    
1660
    if (t->flags & ALARM_FLAG_EXPIRED) {
1661
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1662
        qemu_rearm_alarm_timer(alarm_timer);
1663
    }
1664
}
1665

    
1666
#ifdef _WIN32
1667

    
1668
static int win32_start_timer(struct qemu_alarm_timer *t)
1669
{
1670
    TIMECAPS tc;
1671
    struct qemu_alarm_win32 *data = t->priv;
1672
    UINT flags;
1673

    
1674
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1675
    if (!data->host_alarm) {
1676
        perror("Failed CreateEvent");
1677
        return -1;
1678
    }
1679

    
1680
    memset(&tc, 0, sizeof(tc));
1681
    timeGetDevCaps(&tc, sizeof(tc));
1682

    
1683
    if (data->period < tc.wPeriodMin)
1684
        data->period = tc.wPeriodMin;
1685

    
1686
    timeBeginPeriod(data->period);
1687

    
1688
    flags = TIME_CALLBACK_FUNCTION;
1689
    if (alarm_has_dynticks(t))
1690
        flags |= TIME_ONESHOT;
1691
    else
1692
        flags |= TIME_PERIODIC;
1693

    
1694
    data->timerId = timeSetEvent(1,         // interval (ms)
1695
                        data->period,       // resolution
1696
                        host_alarm_handler, // function
1697
                        (DWORD)t,           // parameter
1698
                        flags);
1699

    
1700
    if (!data->timerId) {
1701
        perror("Failed to initialize win32 alarm timer");
1702

    
1703
        timeEndPeriod(data->period);
1704
        CloseHandle(data->host_alarm);
1705
        return -1;
1706
    }
1707

    
1708
    qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1709

    
1710
    return 0;
1711
}
1712

    
1713
static void win32_stop_timer(struct qemu_alarm_timer *t)
1714
{
1715
    struct qemu_alarm_win32 *data = t->priv;
1716

    
1717
    timeKillEvent(data->timerId);
1718
    timeEndPeriod(data->period);
1719

    
1720
    CloseHandle(data->host_alarm);
1721
}
1722

    
1723
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1724
{
1725
    struct qemu_alarm_win32 *data = t->priv;
1726
    uint64_t nearest_delta_us;
1727

    
1728
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1729
                !active_timers[QEMU_TIMER_VIRTUAL])
1730
        return;
1731

    
1732
    nearest_delta_us = qemu_next_deadline_dyntick();
1733
    nearest_delta_us /= 1000;
1734

    
1735
    timeKillEvent(data->timerId);
1736

    
1737
    data->timerId = timeSetEvent(1,
1738
                        data->period,
1739
                        host_alarm_handler,
1740
                        (DWORD)t,
1741
                        TIME_ONESHOT | TIME_PERIODIC);
1742

    
1743
    if (!data->timerId) {
1744
        perror("Failed to re-arm win32 alarm timer");
1745

    
1746
        timeEndPeriod(data->period);
1747
        CloseHandle(data->host_alarm);
1748
        exit(1);
1749
    }
1750
}
1751

    
1752
#endif /* _WIN32 */
1753

    
1754
static int init_timer_alarm(void)
1755
{
1756
    struct qemu_alarm_timer *t = NULL;
1757
    int i, err = -1;
1758

    
1759
#ifndef _WIN32
1760
    int fds[2];
1761

    
1762
    err = pipe(fds);
1763
    if (err == -1)
1764
        return -errno;
1765

    
1766
    err = fcntl_setfl(fds[0], O_NONBLOCK);
1767
    if (err < 0)
1768
        goto fail;
1769

    
1770
    err = fcntl_setfl(fds[1], O_NONBLOCK);
1771
    if (err < 0)
1772
        goto fail;
1773

    
1774
    alarm_timer_rfd = fds[0];
1775
    alarm_timer_wfd = fds[1];
1776
#endif
1777

    
1778
    for (i = 0; alarm_timers[i].name; i++) {
1779
        t = &alarm_timers[i];
1780

    
1781
        err = t->start(t);
1782
        if (!err)
1783
            break;
1784
    }
1785

    
1786
    if (err) {
1787
        err = -ENOENT;
1788
        goto fail;
1789
    }
1790

    
1791
#ifndef _WIN32
1792
    qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1793
                         try_to_rearm_timer, NULL, t);
1794
#endif
1795

    
1796
    alarm_timer = t;
1797

    
1798
    return 0;
1799

    
1800
fail:
1801
#ifndef _WIN32
1802
    close(fds[0]);
1803
    close(fds[1]);
1804
#endif
1805
    return err;
1806
}
1807

    
1808
static void quit_timers(void)
1809
{
1810
    alarm_timer->stop(alarm_timer);
1811
    alarm_timer = NULL;
1812
}
1813

    
1814
/***********************************************************/
1815
/* host time/date access */
1816
void qemu_get_timedate(struct tm *tm, int offset)
1817
{
1818
    time_t ti;
1819
    struct tm *ret;
1820

    
1821
    time(&ti);
1822
    ti += offset;
1823
    if (rtc_date_offset == -1) {
1824
        if (rtc_utc)
1825
            ret = gmtime(&ti);
1826
        else
1827
            ret = localtime(&ti);
1828
    } else {
1829
        ti -= rtc_date_offset;
1830
        ret = gmtime(&ti);
1831
    }
1832

    
1833
    memcpy(tm, ret, sizeof(struct tm));
1834
}
1835

    
1836
int qemu_timedate_diff(struct tm *tm)
1837
{
1838
    time_t seconds;
1839

    
1840
    if (rtc_date_offset == -1)
1841
        if (rtc_utc)
1842
            seconds = mktimegm(tm);
1843
        else
1844
            seconds = mktime(tm);
1845
    else
1846
        seconds = mktimegm(tm) + rtc_date_offset;
1847

    
1848
    return seconds - time(NULL);
1849
}
1850

    
1851
#ifdef _WIN32
1852
static void socket_cleanup(void)
1853
{
1854
    WSACleanup();
1855
}
1856

    
1857
static int socket_init(void)
1858
{
1859
    WSADATA Data;
1860
    int ret, err;
1861

    
1862
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1863
    if (ret != 0) {
1864
        err = WSAGetLastError();
1865
        fprintf(stderr, "WSAStartup: %d\n", err);
1866
        return -1;
1867
    }
1868
    atexit(socket_cleanup);
1869
    return 0;
1870
}
1871
#endif
1872

    
1873
const char *get_opt_name(char *buf, int buf_size, const char *p, char delim)
1874
{
1875
    char *q;
1876

    
1877
    q = buf;
1878
    while (*p != '\0' && *p != delim) {
1879
        if (q && (q - buf) < buf_size - 1)
1880
            *q++ = *p;
1881
        p++;
1882
    }
1883
    if (q)
1884
        *q = '\0';
1885

    
1886
    return p;
1887
}
1888

    
1889
const char *get_opt_value(char *buf, int buf_size, const char *p)
1890
{
1891
    char *q;
1892

    
1893
    q = buf;
1894
    while (*p != '\0') {
1895
        if (*p == ',') {
1896
            if (*(p + 1) != ',')
1897
                break;
1898
            p++;
1899
        }
1900
        if (q && (q - buf) < buf_size - 1)
1901
            *q++ = *p;
1902
        p++;
1903
    }
1904
    if (q)
1905
        *q = '\0';
1906

    
1907
    return p;
1908
}
1909

    
1910
int get_param_value(char *buf, int buf_size,
1911
                    const char *tag, const char *str)
1912
{
1913
    const char *p;
1914
    char option[128];
1915

    
1916
    p = str;
1917
    for(;;) {
1918
        p = get_opt_name(option, sizeof(option), p, '=');
1919
        if (*p != '=')
1920
            break;
1921
        p++;
1922
        if (!strcmp(tag, option)) {
1923
            (void)get_opt_value(buf, buf_size, p);
1924
            return strlen(buf);
1925
        } else {
1926
            p = get_opt_value(NULL, 0, p);
1927
        }
1928
        if (*p != ',')
1929
            break;
1930
        p++;
1931
    }
1932
    return 0;
1933
}
1934

    
1935
int check_params(char *buf, int buf_size,
1936
                 const char * const *params, const char *str)
1937
{
1938
    const char *p;
1939
    int i;
1940

    
1941
    p = str;
1942
    while (*p != '\0') {
1943
        p = get_opt_name(buf, buf_size, p, '=');
1944
        if (*p != '=')
1945
            return -1;
1946
        p++;
1947
        for(i = 0; params[i] != NULL; i++)
1948
            if (!strcmp(params[i], buf))
1949
                break;
1950
        if (params[i] == NULL)
1951
            return -1;
1952
        p = get_opt_value(NULL, 0, p);
1953
        if (*p != ',')
1954
            break;
1955
        p++;
1956
    }
1957
    return 0;
1958
}
1959

    
1960
/***********************************************************/
1961
/* Bluetooth support */
1962
static int nb_hcis;
1963
static int cur_hci;
1964
static struct HCIInfo *hci_table[MAX_NICS];
1965

    
1966
static struct bt_vlan_s {
1967
    struct bt_scatternet_s net;
1968
    int id;
1969
    struct bt_vlan_s *next;
1970
} *first_bt_vlan;
1971

    
1972
/* find or alloc a new bluetooth "VLAN" */
1973
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1974
{
1975
    struct bt_vlan_s **pvlan, *vlan;
1976
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1977
        if (vlan->id == id)
1978
            return &vlan->net;
1979
    }
1980
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1981
    vlan->id = id;
1982
    pvlan = &first_bt_vlan;
1983
    while (*pvlan != NULL)
1984
        pvlan = &(*pvlan)->next;
1985
    *pvlan = vlan;
1986
    return &vlan->net;
1987
}
1988

    
1989
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1990
{
1991
}
1992

    
1993
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1994
{
1995
    return -ENOTSUP;
1996
}
1997

    
1998
static struct HCIInfo null_hci = {
1999
    .cmd_send = null_hci_send,
2000
    .sco_send = null_hci_send,
2001
    .acl_send = null_hci_send,
2002
    .bdaddr_set = null_hci_addr_set,
2003
};
2004

    
2005
struct HCIInfo *qemu_next_hci(void)
2006
{
2007
    if (cur_hci == nb_hcis)
2008
        return &null_hci;
2009

    
2010
    return hci_table[cur_hci++];
2011
}
2012

    
2013
static struct HCIInfo *hci_init(const char *str)
2014
{
2015
    char *endp;
2016
    struct bt_scatternet_s *vlan = 0;
2017

    
2018
    if (!strcmp(str, "null"))
2019
        /* null */
2020
        return &null_hci;
2021
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2022
        /* host[:hciN] */
2023
        return bt_host_hci(str[4] ? str + 5 : "hci0");
2024
    else if (!strncmp(str, "hci", 3)) {
2025
        /* hci[,vlan=n] */
2026
        if (str[3]) {
2027
            if (!strncmp(str + 3, ",vlan=", 6)) {
2028
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2029
                if (*endp)
2030
                    vlan = 0;
2031
            }
2032
        } else
2033
            vlan = qemu_find_bt_vlan(0);
2034
        if (vlan)
2035
           return bt_new_hci(vlan);
2036
    }
2037

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

    
2040
    return 0;
2041
}
2042

    
2043
static int bt_hci_parse(const char *str)
2044
{
2045
    struct HCIInfo *hci;
2046
    bdaddr_t bdaddr;
2047

    
2048
    if (nb_hcis >= MAX_NICS) {
2049
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2050
        return -1;
2051
    }
2052

    
2053
    hci = hci_init(str);
2054
    if (!hci)
2055
        return -1;
2056

    
2057
    bdaddr.b[0] = 0x52;
2058
    bdaddr.b[1] = 0x54;
2059
    bdaddr.b[2] = 0x00;
2060
    bdaddr.b[3] = 0x12;
2061
    bdaddr.b[4] = 0x34;
2062
    bdaddr.b[5] = 0x56 + nb_hcis;
2063
    hci->bdaddr_set(hci, bdaddr.b);
2064

    
2065
    hci_table[nb_hcis++] = hci;
2066

    
2067
    return 0;
2068
}
2069

    
2070
static void bt_vhci_add(int vlan_id)
2071
{
2072
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2073

    
2074
    if (!vlan->slave)
2075
        fprintf(stderr, "qemu: warning: adding a VHCI to "
2076
                        "an empty scatternet %i\n", vlan_id);
2077

    
2078
    bt_vhci_init(bt_new_hci(vlan));
2079
}
2080

    
2081
static struct bt_device_s *bt_device_add(const char *opt)
2082
{
2083
    struct bt_scatternet_s *vlan;
2084
    int vlan_id = 0;
2085
    char *endp = strstr(opt, ",vlan=");
2086
    int len = (endp ? endp - opt : strlen(opt)) + 1;
2087
    char devname[10];
2088

    
2089
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
2090

    
2091
    if (endp) {
2092
        vlan_id = strtol(endp + 6, &endp, 0);
2093
        if (*endp) {
2094
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2095
            return 0;
2096
        }
2097
    }
2098

    
2099
    vlan = qemu_find_bt_vlan(vlan_id);
2100

    
2101
    if (!vlan->slave)
2102
        fprintf(stderr, "qemu: warning: adding a slave device to "
2103
                        "an empty scatternet %i\n", vlan_id);
2104

    
2105
    if (!strcmp(devname, "keyboard"))
2106
        return bt_keyboard_init(vlan);
2107

    
2108
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2109
    return 0;
2110
}
2111

    
2112
static int bt_parse(const char *opt)
2113
{
2114
    const char *endp, *p;
2115
    int vlan;
2116

    
2117
    if (strstart(opt, "hci", &endp)) {
2118
        if (!*endp || *endp == ',') {
2119
            if (*endp)
2120
                if (!strstart(endp, ",vlan=", 0))
2121
                    opt = endp + 1;
2122

    
2123
            return bt_hci_parse(opt);
2124
       }
2125
    } else if (strstart(opt, "vhci", &endp)) {
2126
        if (!*endp || *endp == ',') {
2127
            if (*endp) {
2128
                if (strstart(endp, ",vlan=", &p)) {
2129
                    vlan = strtol(p, (char **) &endp, 0);
2130
                    if (*endp) {
2131
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2132
                        return 1;
2133
                    }
2134
                } else {
2135
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2136
                    return 1;
2137
                }
2138
            } else
2139
                vlan = 0;
2140

    
2141
            bt_vhci_add(vlan);
2142
            return 0;
2143
        }
2144
    } else if (strstart(opt, "device:", &endp))
2145
        return !bt_device_add(endp);
2146

    
2147
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2148
    return 1;
2149
}
2150

    
2151
/***********************************************************/
2152
/* QEMU Block devices */
2153

    
2154
#define HD_ALIAS "index=%d,media=disk"
2155
#define CDROM_ALIAS "index=2,media=cdrom"
2156
#define FD_ALIAS "index=%d,if=floppy"
2157
#define PFLASH_ALIAS "if=pflash"
2158
#define MTD_ALIAS "if=mtd"
2159
#define SD_ALIAS "index=0,if=sd"
2160

    
2161
static int drive_opt_get_free_idx(void)
2162
{
2163
    int index;
2164

    
2165
    for (index = 0; index < MAX_DRIVES; index++)
2166
        if (!drives_opt[index].used) {
2167
            drives_opt[index].used = 1;
2168
            return index;
2169
        }
2170

    
2171
    return -1;
2172
}
2173

    
2174
static int drive_get_free_idx(void)
2175
{
2176
    int index;
2177

    
2178
    for (index = 0; index < MAX_DRIVES; index++)
2179
        if (!drives_table[index].used) {
2180
            drives_table[index].used = 1;
2181
            return index;
2182
        }
2183

    
2184
    return -1;
2185
}
2186

    
2187
int drive_add(const char *file, const char *fmt, ...)
2188
{
2189
    va_list ap;
2190
    int index = drive_opt_get_free_idx();
2191

    
2192
    if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2193
        fprintf(stderr, "qemu: too many drives\n");
2194
        return -1;
2195
    }
2196

    
2197
    drives_opt[index].file = file;
2198
    va_start(ap, fmt);
2199
    vsnprintf(drives_opt[index].opt,
2200
              sizeof(drives_opt[0].opt), fmt, ap);
2201
    va_end(ap);
2202

    
2203
    nb_drives_opt++;
2204
    return index;
2205
}
2206

    
2207
void drive_remove(int index)
2208
{
2209
    drives_opt[index].used = 0;
2210
    nb_drives_opt--;
2211
}
2212

    
2213
int drive_get_index(BlockInterfaceType type, int bus, int unit)
2214
{
2215
    int index;
2216

    
2217
    /* seek interface, bus and unit */
2218

    
2219
    for (index = 0; index < MAX_DRIVES; index++)
2220
        if (drives_table[index].type == type &&
2221
            drives_table[index].bus == bus &&
2222
            drives_table[index].unit == unit &&
2223
            drives_table[index].used)
2224
        return index;
2225

    
2226
    return -1;
2227
}
2228

    
2229
int drive_get_max_bus(BlockInterfaceType type)
2230
{
2231
    int max_bus;
2232
    int index;
2233

    
2234
    max_bus = -1;
2235
    for (index = 0; index < nb_drives; index++) {
2236
        if(drives_table[index].type == type &&
2237
           drives_table[index].bus > max_bus)
2238
            max_bus = drives_table[index].bus;
2239
    }
2240
    return max_bus;
2241
}
2242

    
2243
const char *drive_get_serial(BlockDriverState *bdrv)
2244
{
2245
    int index;
2246

    
2247
    for (index = 0; index < nb_drives; index++)
2248
        if (drives_table[index].bdrv == bdrv)
2249
            return drives_table[index].serial;
2250

    
2251
    return "\0";
2252
}
2253

    
2254
BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2255
{
2256
    int index;
2257

    
2258
    for (index = 0; index < nb_drives; index++)
2259
        if (drives_table[index].bdrv == bdrv)
2260
            return drives_table[index].onerror;
2261

    
2262
    return BLOCK_ERR_STOP_ENOSPC;
2263
}
2264

    
2265
static void bdrv_format_print(void *opaque, const char *name)
2266
{
2267
    fprintf(stderr, " %s", name);
2268
}
2269

    
2270
void drive_uninit(BlockDriverState *bdrv)
2271
{
2272
    int i;
2273

    
2274
    for (i = 0; i < MAX_DRIVES; i++)
2275
        if (drives_table[i].bdrv == bdrv) {
2276
            drives_table[i].bdrv = NULL;
2277
            drives_table[i].used = 0;
2278
            drive_remove(drives_table[i].drive_opt_idx);
2279
            nb_drives--;
2280
            break;
2281
        }
2282
}
2283

    
2284
int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2285
{
2286
    char buf[128];
2287
    char file[1024];
2288
    char devname[128];
2289
    char serial[21];
2290
    const char *mediastr = "";
2291
    BlockInterfaceType type;
2292
    enum { MEDIA_DISK, MEDIA_CDROM } media;
2293
    int bus_id, unit_id;
2294
    int cyls, heads, secs, translation;
2295
    BlockDriverState *bdrv;
2296
    BlockDriver *drv = NULL;
2297
    QEMUMachine *machine = opaque;
2298
    int max_devs;
2299
    int index;
2300
    int cache;
2301
    int bdrv_flags, onerror;
2302
    int drives_table_idx;
2303
    char *str = arg->opt;
2304
    static const char * const params[] = { "bus", "unit", "if", "index",
2305
                                           "cyls", "heads", "secs", "trans",
2306
                                           "media", "snapshot", "file",
2307
                                           "cache", "format", "serial", "werror",
2308
                                           NULL };
2309

    
2310
    if (check_params(buf, sizeof(buf), params, str) < 0) {
2311
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2312
                         buf, str);
2313
         return -1;
2314
    }
2315

    
2316
    file[0] = 0;
2317
    cyls = heads = secs = 0;
2318
    bus_id = 0;
2319
    unit_id = -1;
2320
    translation = BIOS_ATA_TRANSLATION_AUTO;
2321
    index = -1;
2322
    cache = 3;
2323

    
2324
    if (machine->use_scsi) {
2325
        type = IF_SCSI;
2326
        max_devs = MAX_SCSI_DEVS;
2327
        pstrcpy(devname, sizeof(devname), "scsi");
2328
    } else {
2329
        type = IF_IDE;
2330
        max_devs = MAX_IDE_DEVS;
2331
        pstrcpy(devname, sizeof(devname), "ide");
2332
    }
2333
    media = MEDIA_DISK;
2334

    
2335
    /* extract parameters */
2336

    
2337
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
2338
        bus_id = strtol(buf, NULL, 0);
2339
        if (bus_id < 0) {
2340
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2341
            return -1;
2342
        }
2343
    }
2344

    
2345
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
2346
        unit_id = strtol(buf, NULL, 0);
2347
        if (unit_id < 0) {
2348
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2349
            return -1;
2350
        }
2351
    }
2352

    
2353
    if (get_param_value(buf, sizeof(buf), "if", str)) {
2354
        pstrcpy(devname, sizeof(devname), buf);
2355
        if (!strcmp(buf, "ide")) {
2356
            type = IF_IDE;
2357
            max_devs = MAX_IDE_DEVS;
2358
        } else if (!strcmp(buf, "scsi")) {
2359
            type = IF_SCSI;
2360
            max_devs = MAX_SCSI_DEVS;
2361
        } else if (!strcmp(buf, "floppy")) {
2362
            type = IF_FLOPPY;
2363
            max_devs = 0;
2364
        } else if (!strcmp(buf, "pflash")) {
2365
            type = IF_PFLASH;
2366
            max_devs = 0;
2367
        } else if (!strcmp(buf, "mtd")) {
2368
            type = IF_MTD;
2369
            max_devs = 0;
2370
        } else if (!strcmp(buf, "sd")) {
2371
            type = IF_SD;
2372
            max_devs = 0;
2373
        } else if (!strcmp(buf, "virtio")) {
2374
            type = IF_VIRTIO;
2375
            max_devs = 0;
2376
        } else if (!strcmp(buf, "xen")) {
2377
            type = IF_XEN;
2378
            max_devs = 0;
2379
        } else {
2380
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2381
            return -1;
2382
        }
2383
    }
2384

    
2385
    if (get_param_value(buf, sizeof(buf), "index", str)) {
2386
        index = strtol(buf, NULL, 0);
2387
        if (index < 0) {
2388
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
2389
            return -1;
2390
        }
2391
    }
2392

    
2393
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2394
        cyls = strtol(buf, NULL, 0);
2395
    }
2396

    
2397
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
2398
        heads = strtol(buf, NULL, 0);
2399
    }
2400

    
2401
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
2402
        secs = strtol(buf, NULL, 0);
2403
    }
2404

    
2405
    if (cyls || heads || secs) {
2406
        if (cyls < 1 || cyls > 16383) {
2407
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2408
            return -1;
2409
        }
2410
        if (heads < 1 || heads > 16) {
2411
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2412
            return -1;
2413
        }
2414
        if (secs < 1 || secs > 63) {
2415
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2416
            return -1;
2417
        }
2418
    }
2419

    
2420
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
2421
        if (!cyls) {
2422
            fprintf(stderr,
2423
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2424
                    str);
2425
            return -1;
2426
        }
2427
        if (!strcmp(buf, "none"))
2428
            translation = BIOS_ATA_TRANSLATION_NONE;
2429
        else if (!strcmp(buf, "lba"))
2430
            translation = BIOS_ATA_TRANSLATION_LBA;
2431
        else if (!strcmp(buf, "auto"))
2432
            translation = BIOS_ATA_TRANSLATION_AUTO;
2433
        else {
2434
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2435
            return -1;
2436
        }
2437
    }
2438

    
2439
    if (get_param_value(buf, sizeof(buf), "media", str)) {
2440
        if (!strcmp(buf, "disk")) {
2441
            media = MEDIA_DISK;
2442
        } else if (!strcmp(buf, "cdrom")) {
2443
            if (cyls || secs || heads) {
2444
                fprintf(stderr,
2445
                        "qemu: '%s' invalid physical CHS format\n", str);
2446
                return -1;
2447
            }
2448
            media = MEDIA_CDROM;
2449
        } else {
2450
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
2451
            return -1;
2452
        }
2453
    }
2454

    
2455
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2456
        if (!strcmp(buf, "on"))
2457
            snapshot = 1;
2458
        else if (!strcmp(buf, "off"))
2459
            snapshot = 0;
2460
        else {
2461
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2462
            return -1;
2463
        }
2464
    }
2465

    
2466
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
2467
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2468
            cache = 0;
2469
        else if (!strcmp(buf, "writethrough"))
2470
            cache = 1;
2471
        else if (!strcmp(buf, "writeback"))
2472
            cache = 2;
2473
        else {
2474
           fprintf(stderr, "qemu: invalid cache option\n");
2475
           return -1;
2476
        }
2477
    }
2478

    
2479
    if (get_param_value(buf, sizeof(buf), "format", str)) {
2480
       if (strcmp(buf, "?") == 0) {
2481
            fprintf(stderr, "qemu: Supported formats:");
2482
            bdrv_iterate_format(bdrv_format_print, NULL);
2483
            fprintf(stderr, "\n");
2484
            return -1;
2485
        }
2486
        drv = bdrv_find_format(buf);
2487
        if (!drv) {
2488
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2489
            return -1;
2490
        }
2491
    }
2492

    
2493
    if (arg->file == NULL)
2494
        get_param_value(file, sizeof(file), "file", str);
2495
    else
2496
        pstrcpy(file, sizeof(file), arg->file);
2497

    
2498
    if (!get_param_value(serial, sizeof(serial), "serial", str))
2499
            memset(serial, 0,  sizeof(serial));
2500

    
2501
    onerror = BLOCK_ERR_STOP_ENOSPC;
2502
    if (get_param_value(buf, sizeof(serial), "werror", str)) {
2503
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2504
            fprintf(stderr, "werror is no supported by this format\n");
2505
            return -1;
2506
        }
2507
        if (!strcmp(buf, "ignore"))
2508
            onerror = BLOCK_ERR_IGNORE;
2509
        else if (!strcmp(buf, "enospc"))
2510
            onerror = BLOCK_ERR_STOP_ENOSPC;
2511
        else if (!strcmp(buf, "stop"))
2512
            onerror = BLOCK_ERR_STOP_ANY;
2513
        else if (!strcmp(buf, "report"))
2514
            onerror = BLOCK_ERR_REPORT;
2515
        else {
2516
            fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2517
            return -1;
2518
        }
2519
    }
2520

    
2521
    /* compute bus and unit according index */
2522

    
2523
    if (index != -1) {
2524
        if (bus_id != 0 || unit_id != -1) {
2525
            fprintf(stderr,
2526
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
2527
            return -1;
2528
        }
2529
        if (max_devs == 0)
2530
        {
2531
            unit_id = index;
2532
            bus_id = 0;
2533
        } else {
2534
            unit_id = index % max_devs;
2535
            bus_id = index / max_devs;
2536
        }
2537
    }
2538

    
2539
    /* if user doesn't specify a unit_id,
2540
     * try to find the first free
2541
     */
2542

    
2543
    if (unit_id == -1) {
2544
       unit_id = 0;
2545
       while (drive_get_index(type, bus_id, unit_id) != -1) {
2546
           unit_id++;
2547
           if (max_devs && unit_id >= max_devs) {
2548
               unit_id -= max_devs;
2549
               bus_id++;
2550
           }
2551
       }
2552
    }
2553

    
2554
    /* check unit id */
2555

    
2556
    if (max_devs && unit_id >= max_devs) {
2557
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2558
                        str, unit_id, max_devs - 1);
2559
        return -1;
2560
    }
2561

    
2562
    /*
2563
     * ignore multiple definitions
2564
     */
2565

    
2566
    if (drive_get_index(type, bus_id, unit_id) != -1)
2567
        return -2;
2568

    
2569
    /* init */
2570

    
2571
    if (type == IF_IDE || type == IF_SCSI)
2572
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2573
    if (max_devs)
2574
        snprintf(buf, sizeof(buf), "%s%i%s%i",
2575
                 devname, bus_id, mediastr, unit_id);
2576
    else
2577
        snprintf(buf, sizeof(buf), "%s%s%i",
2578
                 devname, mediastr, unit_id);
2579
    bdrv = bdrv_new(buf);
2580
    drives_table_idx = drive_get_free_idx();
2581
    drives_table[drives_table_idx].bdrv = bdrv;
2582
    drives_table[drives_table_idx].type = type;
2583
    drives_table[drives_table_idx].bus = bus_id;
2584
    drives_table[drives_table_idx].unit = unit_id;
2585
    drives_table[drives_table_idx].onerror = onerror;
2586
    drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2587
    strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2588
    nb_drives++;
2589

    
2590
    switch(type) {
2591
    case IF_IDE:
2592
    case IF_SCSI:
2593
    case IF_XEN:
2594
        switch(media) {
2595
        case MEDIA_DISK:
2596
            if (cyls != 0) {
2597
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2598
                bdrv_set_translation_hint(bdrv, translation);
2599
            }
2600
            break;
2601
        case MEDIA_CDROM:
2602
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2603
            break;
2604
        }
2605
        break;
2606
    case IF_SD:
2607
        /* FIXME: This isn't really a floppy, but it's a reasonable
2608
           approximation.  */
2609
    case IF_FLOPPY:
2610
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2611
        break;
2612
    case IF_PFLASH:
2613
    case IF_MTD:
2614
    case IF_VIRTIO:
2615
        break;
2616
    }
2617
    if (!file[0])
2618
        return -2;
2619
    bdrv_flags = 0;
2620
    if (snapshot) {
2621
        bdrv_flags |= BDRV_O_SNAPSHOT;
2622
        cache = 2; /* always use write-back with snapshot */
2623
    }
2624
    if (cache == 0) /* no caching */
2625
        bdrv_flags |= BDRV_O_NOCACHE;
2626
    else if (cache == 2) /* write-back */
2627
        bdrv_flags |= BDRV_O_CACHE_WB;
2628
    else if (cache == 3) /* not specified */
2629
        bdrv_flags |= BDRV_O_CACHE_DEF;
2630
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2631
        fprintf(stderr, "qemu: could not open disk image %s\n",
2632
                        file);
2633
        return -1;
2634
    }
2635
    if (bdrv_key_required(bdrv))
2636
        autostart = 0;
2637
    return drives_table_idx;
2638
}
2639

    
2640
static void numa_add(const char *optarg)
2641
{
2642
    char option[128];
2643
    char *endptr;
2644
    unsigned long long value, endvalue;
2645
    int nodenr;
2646

    
2647
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2648
    if (!strcmp(option, "node")) {
2649
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2650
            nodenr = nb_numa_nodes;
2651
        } else {
2652
            nodenr = strtoull(option, NULL, 10);
2653
        }
2654

    
2655
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2656
            node_mem[nodenr] = 0;
2657
        } else {
2658
            value = strtoull(option, &endptr, 0);
2659
            switch (*endptr) {
2660
            case 0: case 'M': case 'm':
2661
                value <<= 20;
2662
                break;
2663
            case 'G': case 'g':
2664
                value <<= 30;
2665
                break;
2666
            }
2667
            node_mem[nodenr] = value;
2668
        }
2669
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2670
            node_cpumask[nodenr] = 0;
2671
        } else {
2672
            value = strtoull(option, &endptr, 10);
2673
            if (value >= 64) {
2674
                value = 63;
2675
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2676
            } else {
2677
                if (*endptr == '-') {
2678
                    endvalue = strtoull(endptr+1, &endptr, 10);
2679
                    if (endvalue >= 63) {
2680
                        endvalue = 62;
2681
                        fprintf(stderr,
2682
                            "only 63 CPUs in NUMA mode supported.\n");
2683
                    }
2684
                    value = (1 << (endvalue + 1)) - (1 << value);
2685
                } else {
2686
                    value = 1 << value;
2687
                }
2688
            }
2689
            node_cpumask[nodenr] = value;
2690
        }
2691
        nb_numa_nodes++;
2692
    }
2693
    return;
2694
}
2695

    
2696
/***********************************************************/
2697
/* USB devices */
2698

    
2699
static USBPort *used_usb_ports;
2700
static USBPort *free_usb_ports;
2701

    
2702
/* ??? Maybe change this to register a hub to keep track of the topology.  */
2703
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2704
                            usb_attachfn attach)
2705
{
2706
    port->opaque = opaque;
2707
    port->index = index;
2708
    port->attach = attach;
2709
    port->next = free_usb_ports;
2710
    free_usb_ports = port;
2711
}
2712

    
2713
int usb_device_add_dev(USBDevice *dev)
2714
{
2715
    USBPort *port;
2716

    
2717
    /* Find a USB port to add the device to.  */
2718
    port = free_usb_ports;
2719
    if (!port->next) {
2720
        USBDevice *hub;
2721

    
2722
        /* Create a new hub and chain it on.  */
2723
        free_usb_ports = NULL;
2724
        port->next = used_usb_ports;
2725
        used_usb_ports = port;
2726

    
2727
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2728
        usb_attach(port, hub);
2729
        port = free_usb_ports;
2730
    }
2731

    
2732
    free_usb_ports = port->next;
2733
    port->next = used_usb_ports;
2734
    used_usb_ports = port;
2735
    usb_attach(port, dev);
2736
    return 0;
2737
}
2738

    
2739
static void usb_msd_password_cb(void *opaque, int err)
2740
{
2741
    USBDevice *dev = opaque;
2742

    
2743
    if (!err)
2744
        usb_device_add_dev(dev);
2745
    else
2746
        dev->handle_destroy(dev);
2747
}
2748

    
2749
static int usb_device_add(const char *devname, int is_hotplug)
2750
{
2751
    const char *p;
2752
    USBDevice *dev;
2753

    
2754
    if (!free_usb_ports)
2755
        return -1;
2756

    
2757
    if (strstart(devname, "host:", &p)) {
2758
        dev = usb_host_device_open(p);
2759
    } else if (!strcmp(devname, "mouse")) {
2760
        dev = usb_mouse_init();
2761
    } else if (!strcmp(devname, "tablet")) {
2762
        dev = usb_tablet_init();
2763
    } else if (!strcmp(devname, "keyboard")) {
2764
        dev = usb_keyboard_init();
2765
    } else if (strstart(devname, "disk:", &p)) {
2766
        BlockDriverState *bs;
2767

    
2768
        dev = usb_msd_init(p);
2769
        if (!dev)
2770
            return -1;
2771
        bs = usb_msd_get_bdrv(dev);
2772
        if (bdrv_key_required(bs)) {
2773
            autostart = 0;
2774
            if (is_hotplug) {
2775
                monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2776
                                            dev);
2777
                return 0;
2778
            }
2779
        }
2780
    } else if (!strcmp(devname, "wacom-tablet")) {
2781
        dev = usb_wacom_init();
2782
    } else if (strstart(devname, "serial:", &p)) {
2783
        dev = usb_serial_init(p);
2784
#ifdef CONFIG_BRLAPI
2785
    } else if (!strcmp(devname, "braille")) {
2786
        dev = usb_baum_init();
2787
#endif
2788
    } else if (strstart(devname, "net:", &p)) {
2789
        int nic = nb_nics;
2790

    
2791
        if (net_client_init("nic", p) < 0)
2792
            return -1;
2793
        nd_table[nic].model = "usb";
2794
        dev = usb_net_init(&nd_table[nic]);
2795
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2796
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2797
                        bt_new_hci(qemu_find_bt_vlan(0)));
2798
    } else {
2799
        return -1;
2800
    }
2801
    if (!dev)
2802
        return -1;
2803

    
2804
    return usb_device_add_dev(dev);
2805
}
2806

    
2807
int usb_device_del_addr(int bus_num, int addr)
2808
{
2809
    USBPort *port;
2810
    USBPort **lastp;
2811
    USBDevice *dev;
2812

    
2813
    if (!used_usb_ports)
2814
        return -1;
2815

    
2816
    if (bus_num != 0)
2817
        return -1;
2818

    
2819
    lastp = &used_usb_ports;
2820
    port = used_usb_ports;
2821
    while (port && port->dev->addr != addr) {
2822
        lastp = &port->next;
2823
        port = port->next;
2824
    }
2825

    
2826
    if (!port)
2827
        return -1;
2828

    
2829
    dev = port->dev;
2830
    *lastp = port->next;
2831
    usb_attach(port, NULL);
2832
    dev->handle_destroy(dev);
2833
    port->next = free_usb_ports;
2834
    free_usb_ports = port;
2835
    return 0;
2836
}
2837

    
2838
static int usb_device_del(const char *devname)
2839
{
2840
    int bus_num, addr;
2841
    const char *p;
2842

    
2843
    if (strstart(devname, "host:", &p))
2844
        return usb_host_device_close(p);
2845

    
2846
    if (!used_usb_ports)
2847
        return -1;
2848

    
2849
    p = strchr(devname, '.');
2850
    if (!p)
2851
        return -1;
2852
    bus_num = strtoul(devname, NULL, 0);
2853
    addr = strtoul(p + 1, NULL, 0);
2854

    
2855
    return usb_device_del_addr(bus_num, addr);
2856
}
2857

    
2858
void do_usb_add(Monitor *mon, const char *devname)
2859
{
2860
    usb_device_add(devname, 1);
2861
}
2862

    
2863
void do_usb_del(Monitor *mon, const char *devname)
2864
{
2865
    usb_device_del(devname);
2866
}
2867

    
2868
void usb_info(Monitor *mon)
2869
{
2870
    USBDevice *dev;
2871
    USBPort *port;
2872
    const char *speed_str;
2873

    
2874
    if (!usb_enabled) {
2875
        monitor_printf(mon, "USB support not enabled\n");
2876
        return;
2877
    }
2878

    
2879
    for (port = used_usb_ports; port; port = port->next) {
2880
        dev = port->dev;
2881
        if (!dev)
2882
            continue;
2883
        switch(dev->speed) {
2884
        case USB_SPEED_LOW:
2885
            speed_str = "1.5";
2886
            break;
2887
        case USB_SPEED_FULL:
2888
            speed_str = "12";
2889
            break;
2890
        case USB_SPEED_HIGH:
2891
            speed_str = "480";
2892
            break;
2893
        default:
2894
            speed_str = "?";
2895
            break;
2896
        }
2897
        monitor_printf(mon, "  Device %d.%d, Speed %s Mb/s, Product %s\n",
2898
                       0, dev->addr, speed_str, dev->devname);
2899
    }
2900
}
2901

    
2902
/***********************************************************/
2903
/* PCMCIA/Cardbus */
2904

    
2905
static struct pcmcia_socket_entry_s {
2906
    struct pcmcia_socket_s *socket;
2907
    struct pcmcia_socket_entry_s *next;
2908
} *pcmcia_sockets = 0;
2909

    
2910
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2911
{
2912
    struct pcmcia_socket_entry_s *entry;
2913

    
2914
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2915
    entry->socket = socket;
2916
    entry->next = pcmcia_sockets;
2917
    pcmcia_sockets = entry;
2918
}
2919

    
2920
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2921
{
2922
    struct pcmcia_socket_entry_s *entry, **ptr;
2923

    
2924
    ptr = &pcmcia_sockets;
2925
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2926
        if (entry->socket == socket) {
2927
            *ptr = entry->next;
2928
            qemu_free(entry);
2929
        }
2930
}
2931

    
2932
void pcmcia_info(Monitor *mon)
2933
{
2934
    struct pcmcia_socket_entry_s *iter;
2935

    
2936
    if (!pcmcia_sockets)
2937
        monitor_printf(mon, "No PCMCIA sockets\n");
2938

    
2939
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2940
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2941
                       iter->socket->attached ? iter->socket->card_string :
2942
                       "Empty");
2943
}
2944

    
2945
/***********************************************************/
2946
/* register display */
2947

    
2948
struct DisplayAllocator default_allocator = {
2949
    defaultallocator_create_displaysurface,
2950
    defaultallocator_resize_displaysurface,
2951
    defaultallocator_free_displaysurface
2952
};
2953

    
2954
void register_displaystate(DisplayState *ds)
2955
{
2956
    DisplayState **s;
2957
    s = &display_state;
2958
    while (*s != NULL)
2959
        s = &(*s)->next;
2960
    ds->next = NULL;
2961
    *s = ds;
2962
}
2963

    
2964
DisplayState *get_displaystate(void)
2965
{
2966
    return display_state;
2967
}
2968

    
2969
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2970
{
2971
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2972
    return ds->allocator;
2973
}
2974

    
2975
/* dumb display */
2976

    
2977
static void dumb_display_init(void)
2978
{
2979
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2980
    ds->allocator = &default_allocator;
2981
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2982
    register_displaystate(ds);
2983
}
2984

    
2985
/***********************************************************/
2986
/* I/O handling */
2987

    
2988
typedef struct IOHandlerRecord {
2989
    int fd;
2990
    IOCanRWHandler *fd_read_poll;
2991
    IOHandler *fd_read;
2992
    IOHandler *fd_write;
2993
    int deleted;
2994
    void *opaque;
2995
    /* temporary data */
2996
    struct pollfd *ufd;
2997
    struct IOHandlerRecord *next;
2998
} IOHandlerRecord;
2999

    
3000
static IOHandlerRecord *first_io_handler;
3001

    
3002
/* XXX: fd_read_poll should be suppressed, but an API change is
3003
   necessary in the character devices to suppress fd_can_read(). */
3004
int qemu_set_fd_handler2(int fd,
3005
                         IOCanRWHandler *fd_read_poll,
3006
                         IOHandler *fd_read,
3007
                         IOHandler *fd_write,
3008
                         void *opaque)
3009
{
3010
    IOHandlerRecord **pioh, *ioh;
3011

    
3012
    if (!fd_read && !fd_write) {
3013
        pioh = &first_io_handler;
3014
        for(;;) {
3015
            ioh = *pioh;
3016
            if (ioh == NULL)
3017
                break;
3018
            if (ioh->fd == fd) {
3019
                ioh->deleted = 1;
3020
                break;
3021
            }
3022
            pioh = &ioh->next;
3023
        }
3024
    } else {
3025
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3026
            if (ioh->fd == fd)
3027
                goto found;
3028
        }
3029
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3030
        ioh->next = first_io_handler;
3031
        first_io_handler = ioh;
3032
    found:
3033
        ioh->fd = fd;
3034
        ioh->fd_read_poll = fd_read_poll;
3035
        ioh->fd_read = fd_read;
3036
        ioh->fd_write = fd_write;
3037
        ioh->opaque = opaque;
3038
        ioh->deleted = 0;
3039
    }
3040
    return 0;
3041
}
3042

    
3043
int qemu_set_fd_handler(int fd,
3044
                        IOHandler *fd_read,
3045
                        IOHandler *fd_write,
3046
                        void *opaque)
3047
{
3048
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3049
}
3050

    
3051
#ifdef _WIN32
3052
/***********************************************************/
3053
/* Polling handling */
3054

    
3055
typedef struct PollingEntry {
3056
    PollingFunc *func;
3057
    void *opaque;
3058
    struct PollingEntry *next;
3059
} PollingEntry;
3060

    
3061
static PollingEntry *first_polling_entry;
3062

    
3063
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3064
{
3065
    PollingEntry **ppe, *pe;
3066
    pe = qemu_mallocz(sizeof(PollingEntry));
3067
    pe->func = func;
3068
    pe->opaque = opaque;
3069
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3070
    *ppe = pe;
3071
    return 0;
3072
}
3073

    
3074
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3075
{
3076
    PollingEntry **ppe, *pe;
3077
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3078
        pe = *ppe;
3079
        if (pe->func == func && pe->opaque == opaque) {
3080
            *ppe = pe->next;
3081
            qemu_free(pe);
3082
            break;
3083
        }
3084
    }
3085
}
3086

    
3087
/***********************************************************/
3088
/* Wait objects support */
3089
typedef struct WaitObjects {
3090
    int num;
3091
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3092
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3093
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3094
} WaitObjects;
3095

    
3096
static WaitObjects wait_objects = {0};
3097

    
3098
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3099
{
3100
    WaitObjects *w = &wait_objects;
3101

    
3102
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
3103
        return -1;
3104
    w->events[w->num] = handle;
3105
    w->func[w->num] = func;
3106
    w->opaque[w->num] = opaque;
3107
    w->num++;
3108
    return 0;
3109
}
3110

    
3111
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3112
{
3113
    int i, found;
3114
    WaitObjects *w = &wait_objects;
3115

    
3116
    found = 0;
3117
    for (i = 0; i < w->num; i++) {
3118
        if (w->events[i] == handle)
3119
            found = 1;
3120
        if (found) {
3121
            w->events[i] = w->events[i + 1];
3122
            w->func[i] = w->func[i + 1];
3123
            w->opaque[i] = w->opaque[i + 1];
3124
        }
3125
    }
3126
    if (found)
3127
        w->num--;
3128
}
3129
#endif
3130

    
3131
/***********************************************************/
3132
/* ram save/restore */
3133

    
3134
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3135
{
3136
    int v;
3137

    
3138
    v = qemu_get_byte(f);
3139
    switch(v) {
3140
    case 0:
3141
        if (qemu_get_buffer(f, buf, len) != len)
3142
            return -EIO;
3143
        break;
3144
    case 1:
3145
        v = qemu_get_byte(f);
3146
        memset(buf, v, len);
3147
        break;
3148
    default:
3149
        return -EINVAL;
3150
    }
3151

    
3152
    if (qemu_file_has_error(f))
3153
        return -EIO;
3154

    
3155
    return 0;
3156
}
3157

    
3158
static int ram_load_v1(QEMUFile *f, void *opaque)
3159
{
3160
    int ret;
3161
    ram_addr_t i;
3162

    
3163
    if (qemu_get_be32(f) != last_ram_offset)
3164
        return -EINVAL;
3165
    for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3166
        ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3167
        if (ret)
3168
            return ret;
3169
    }
3170
    return 0;
3171
}
3172

    
3173
#define BDRV_HASH_BLOCK_SIZE 1024
3174
#define IOBUF_SIZE 4096
3175
#define RAM_CBLOCK_MAGIC 0xfabe
3176

    
3177
typedef struct RamDecompressState {
3178
    z_stream zstream;
3179
    QEMUFile *f;
3180
    uint8_t buf[IOBUF_SIZE];
3181
} RamDecompressState;
3182

    
3183
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3184
{
3185
    int ret;
3186
    memset(s, 0, sizeof(*s));
3187
    s->f = f;
3188
    ret = inflateInit(&s->zstream);
3189
    if (ret != Z_OK)
3190
        return -1;
3191
    return 0;
3192
}
3193

    
3194
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3195
{
3196
    int ret, clen;
3197

    
3198
    s->zstream.avail_out = len;
3199
    s->zstream.next_out = buf;
3200
    while (s->zstream.avail_out > 0) {
3201
        if (s->zstream.avail_in == 0) {
3202
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3203
                return -1;
3204
            clen = qemu_get_be16(s->f);
3205
            if (clen > IOBUF_SIZE)
3206
                return -1;
3207
            qemu_get_buffer(s->f, s->buf, clen);
3208
            s->zstream.avail_in = clen;
3209
            s->zstream.next_in = s->buf;
3210
        }
3211
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3212
        if (ret != Z_OK && ret != Z_STREAM_END) {
3213
            return -1;
3214
        }
3215
    }
3216
    return 0;
3217
}
3218

    
3219
static void ram_decompress_close(RamDecompressState *s)
3220
{
3221
    inflateEnd(&s->zstream);
3222
}
3223

    
3224
#define RAM_SAVE_FLAG_FULL        0x01
3225
#define RAM_SAVE_FLAG_COMPRESS        0x02
3226
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
3227
#define RAM_SAVE_FLAG_PAGE        0x08
3228
#define RAM_SAVE_FLAG_EOS        0x10
3229

    
3230
static int is_dup_page(uint8_t *page, uint8_t ch)
3231
{
3232
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3233
    uint32_t *array = (uint32_t *)page;
3234
    int i;
3235

    
3236
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3237
        if (array[i] != val)
3238
            return 0;
3239
    }
3240

    
3241
    return 1;
3242
}
3243

    
3244
static int ram_save_block(QEMUFile *f)
3245
{
3246
    static ram_addr_t current_addr = 0;
3247
    ram_addr_t saved_addr = current_addr;
3248
    ram_addr_t addr = 0;
3249
    int found = 0;
3250

    
3251
    while (addr < last_ram_offset) {
3252
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3253
            uint8_t *p;
3254

    
3255
            cpu_physical_memory_reset_dirty(current_addr,
3256
                                            current_addr + TARGET_PAGE_SIZE,
3257
                                            MIGRATION_DIRTY_FLAG);
3258

    
3259
            p = qemu_get_ram_ptr(current_addr);
3260

    
3261
            if (is_dup_page(p, *p)) {
3262
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3263
                qemu_put_byte(f, *p);
3264
            } else {
3265
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3266
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3267
            }
3268

    
3269
            found = 1;
3270
            break;
3271
        }
3272
        addr += TARGET_PAGE_SIZE;
3273
        current_addr = (saved_addr + addr) % last_ram_offset;
3274
    }
3275

    
3276
    return found;
3277
}
3278

    
3279
static ram_addr_t ram_save_threshold = 10;
3280

    
3281
static ram_addr_t ram_save_remaining(void)
3282
{
3283
    ram_addr_t addr;
3284
    ram_addr_t count = 0;
3285

    
3286
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3287
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3288
            count++;
3289
    }
3290

    
3291
    return count;
3292
}
3293

    
3294
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3295
{
3296
    ram_addr_t addr;
3297

    
3298
    if (stage == 1) {
3299
        /* Make sure all dirty bits are set */
3300
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3301
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3302
                cpu_physical_memory_set_dirty(addr);
3303
        }
3304
        
3305
        /* Enable dirty memory tracking */
3306
        cpu_physical_memory_set_dirty_tracking(1);
3307

    
3308
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3309
    }
3310

    
3311
    while (!qemu_file_rate_limit(f)) {
3312
        int ret;
3313

    
3314
        ret = ram_save_block(f);
3315
        if (ret == 0) /* no more blocks */
3316
            break;
3317
    }
3318

    
3319
    /* try transferring iterative blocks of memory */
3320

    
3321
    if (stage == 3) {
3322

    
3323
        /* flush all remaining blocks regardless of rate limiting */
3324
        while (ram_save_block(f) != 0);
3325
        cpu_physical_memory_set_dirty_tracking(0);
3326
    }
3327

    
3328
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3329

    
3330
    return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3331
}
3332

    
3333
static int ram_load_dead(QEMUFile *f, void *opaque)
3334
{
3335
    RamDecompressState s1, *s = &s1;
3336
    uint8_t buf[10];
3337
    ram_addr_t i;
3338

    
3339
    if (ram_decompress_open(s, f) < 0)
3340
        return -EINVAL;
3341
    for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3342
        if (ram_decompress_buf(s, buf, 1) < 0) {
3343
            fprintf(stderr, "Error while reading ram block header\n");
3344
            goto error;
3345
        }
3346
        if (buf[0] == 0) {
3347
            if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3348
                                   BDRV_HASH_BLOCK_SIZE) < 0) {
3349
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3350
                goto error;
3351
            }
3352
        } else {
3353
        error:
3354
            printf("Error block header\n");
3355
            return -EINVAL;
3356
        }
3357
    }
3358
    ram_decompress_close(s);
3359

    
3360
    return 0;
3361
}
3362

    
3363
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3364
{
3365
    ram_addr_t addr;
3366
    int flags;
3367

    
3368
    if (version_id == 1)
3369
        return ram_load_v1(f, opaque);
3370

    
3371
    if (version_id == 2) {
3372
        if (qemu_get_be32(f) != last_ram_offset)
3373
            return -EINVAL;
3374
        return ram_load_dead(f, opaque);
3375
    }
3376

    
3377
    if (version_id != 3)
3378
        return -EINVAL;
3379

    
3380
    do {
3381
        addr = qemu_get_be64(f);
3382

    
3383
        flags = addr & ~TARGET_PAGE_MASK;
3384
        addr &= TARGET_PAGE_MASK;
3385

    
3386
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3387
            if (addr != last_ram_offset)
3388
                return -EINVAL;
3389
        }
3390

    
3391
        if (flags & RAM_SAVE_FLAG_FULL) {
3392
            if (ram_load_dead(f, opaque) < 0)
3393
                return -EINVAL;
3394
        }
3395
        
3396
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
3397
            uint8_t ch = qemu_get_byte(f);
3398
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3399
        } else if (flags & RAM_SAVE_FLAG_PAGE)
3400
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3401
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3402

    
3403
    return 0;
3404
}
3405

    
3406
void qemu_service_io(void)
3407
{
3408
    CPUState *env = cpu_single_env;
3409
    if (env) {
3410
        cpu_exit(env);
3411
#ifdef CONFIG_KQEMU
3412
        if (env->kqemu_enabled) {
3413
            kqemu_cpu_interrupt(env);
3414
        }
3415
#endif
3416
    }
3417
}
3418

    
3419
/***********************************************************/
3420
/* bottom halves (can be seen as timers which expire ASAP) */
3421

    
3422
struct QEMUBH {
3423
    QEMUBHFunc *cb;
3424
    void *opaque;
3425
    int scheduled;
3426
    int idle;
3427
    int deleted;
3428
    QEMUBH *next;
3429
};
3430

    
3431
static QEMUBH *first_bh = NULL;
3432

    
3433
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3434
{
3435
    QEMUBH *bh;
3436
    bh = qemu_mallocz(sizeof(QEMUBH));
3437
    bh->cb = cb;
3438
    bh->opaque = opaque;
3439
    bh->next = first_bh;
3440
    first_bh = bh;
3441
    return bh;
3442
}
3443

    
3444
int qemu_bh_poll(void)
3445
{
3446
    QEMUBH *bh, **bhp;
3447
    int ret;
3448

    
3449
    ret = 0;
3450
    for (bh = first_bh; bh; bh = bh->next) {
3451
        if (!bh->deleted && bh->scheduled) {
3452
            bh->scheduled = 0;
3453
            if (!bh->idle)
3454
                ret = 1;
3455
            bh->idle = 0;
3456
            bh->cb(bh->opaque);
3457
        }
3458
    }
3459

    
3460
    /* remove deleted bhs */
3461
    bhp = &first_bh;
3462
    while (*bhp) {
3463
        bh = *bhp;
3464
        if (bh->deleted) {
3465
            *bhp = bh->next;
3466
            qemu_free(bh);
3467
        } else
3468
            bhp = &bh->next;
3469
    }
3470

    
3471
    return ret;
3472
}
3473

    
3474
void qemu_bh_schedule_idle(QEMUBH *bh)
3475
{
3476
    if (bh->scheduled)
3477
        return;
3478
    bh->scheduled = 1;
3479
    bh->idle = 1;
3480
}
3481

    
3482
void qemu_bh_schedule(QEMUBH *bh)
3483
{
3484
    CPUState *env = cpu_single_env;
3485
    if (bh->scheduled)
3486
        return;
3487
    bh->scheduled = 1;
3488
    bh->idle = 0;
3489
    /* stop the currently executing CPU to execute the BH ASAP */
3490
    if (env) {
3491
        cpu_exit(env);
3492
    }
3493
}
3494

    
3495
void qemu_bh_cancel(QEMUBH *bh)
3496
{
3497
    bh->scheduled = 0;
3498
}
3499

    
3500
void qemu_bh_delete(QEMUBH *bh)
3501
{
3502
    bh->scheduled = 0;
3503
    bh->deleted = 1;
3504
}
3505

    
3506
static void qemu_bh_update_timeout(int *timeout)
3507
{
3508
    QEMUBH *bh;
3509

    
3510
    for (bh = first_bh; bh; bh = bh->next) {
3511
        if (!bh->deleted && bh->scheduled) {
3512
            if (bh->idle) {
3513
                /* idle bottom halves will be polled at least
3514
                 * every 10ms */
3515
                *timeout = MIN(10, *timeout);
3516
            } else {
3517
                /* non-idle bottom halves will be executed
3518
                 * immediately */
3519
                *timeout = 0;
3520
                break;
3521
            }
3522
        }
3523
    }
3524
}
3525

    
3526
/***********************************************************/
3527
/* machine registration */
3528

    
3529
static QEMUMachine *first_machine = NULL;
3530
QEMUMachine *current_machine = NULL;
3531

    
3532
int qemu_register_machine(QEMUMachine *m)
3533
{
3534
    QEMUMachine **pm;
3535
    pm = &first_machine;
3536
    while (*pm != NULL)
3537
        pm = &(*pm)->next;
3538
    m->next = NULL;
3539
    *pm = m;
3540
    return 0;
3541
}
3542

    
3543
static QEMUMachine *find_machine(const char *name)
3544
{
3545
    QEMUMachine *m;
3546

    
3547
    for(m = first_machine; m != NULL; m = m->next) {
3548
        if (!strcmp(m->name, name))
3549
            return m;
3550
    }
3551
    return NULL;
3552
}
3553

    
3554
/***********************************************************/
3555
/* main execution loop */
3556

    
3557
static void gui_update(void *opaque)
3558
{
3559
    uint64_t interval = GUI_REFRESH_INTERVAL;
3560
    DisplayState *ds = opaque;
3561
    DisplayChangeListener *dcl = ds->listeners;
3562

    
3563
    dpy_refresh(ds);
3564

    
3565
    while (dcl != NULL) {
3566
        if (dcl->gui_timer_interval &&
3567
            dcl->gui_timer_interval < interval)
3568
            interval = dcl->gui_timer_interval;
3569
        dcl = dcl->next;
3570
    }
3571
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3572
}
3573

    
3574
static void nographic_update(void *opaque)
3575
{
3576
    uint64_t interval = GUI_REFRESH_INTERVAL;
3577

    
3578
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3579
}
3580

    
3581
struct vm_change_state_entry {
3582
    VMChangeStateHandler *cb;
3583
    void *opaque;
3584
    LIST_ENTRY (vm_change_state_entry) entries;
3585
};
3586

    
3587
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3588

    
3589
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3590
                                                     void *opaque)
3591
{
3592
    VMChangeStateEntry *e;
3593

    
3594
    e = qemu_mallocz(sizeof (*e));
3595

    
3596
    e->cb = cb;
3597
    e->opaque = opaque;
3598
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3599
    return e;
3600
}
3601

    
3602
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3603
{
3604
    LIST_REMOVE (e, entries);
3605
    qemu_free (e);
3606
}
3607

    
3608
static void vm_state_notify(int running, int reason)
3609
{
3610
    VMChangeStateEntry *e;
3611

    
3612
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3613
        e->cb(e->opaque, running, reason);
3614
    }
3615
}
3616

    
3617
void vm_start(void)
3618
{
3619
    if (!vm_running) {
3620
        cpu_enable_ticks();
3621
        vm_running = 1;
3622
        vm_state_notify(1, 0);
3623
        qemu_rearm_alarm_timer(alarm_timer);
3624
    }
3625
}
3626

    
3627
void vm_stop(int reason)
3628
{
3629
    if (vm_running) {
3630
        cpu_disable_ticks();
3631
        vm_running = 0;
3632
        vm_state_notify(0, reason);
3633
    }
3634
}
3635

    
3636
/* reset/shutdown handler */
3637

    
3638
typedef struct QEMUResetEntry {
3639
    QEMUResetHandler *func;
3640
    void *opaque;
3641
    struct QEMUResetEntry *next;
3642
} QEMUResetEntry;
3643

    
3644
static QEMUResetEntry *first_reset_entry;
3645
static int reset_requested;
3646
static int shutdown_requested;
3647
static int powerdown_requested;
3648

    
3649
int qemu_shutdown_requested(void)
3650
{
3651
    int r = shutdown_requested;
3652
    shutdown_requested = 0;
3653
    return r;
3654
}
3655

    
3656
int qemu_reset_requested(void)
3657
{
3658
    int r = reset_requested;
3659
    reset_requested = 0;
3660
    return r;
3661
}
3662

    
3663
int qemu_powerdown_requested(void)
3664
{
3665
    int r = powerdown_requested;
3666
    powerdown_requested = 0;
3667
    return r;
3668
}
3669

    
3670
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3671
{
3672
    QEMUResetEntry **pre, *re;
3673

    
3674
    pre = &first_reset_entry;
3675
    while (*pre != NULL)
3676
        pre = &(*pre)->next;
3677
    re = qemu_mallocz(sizeof(QEMUResetEntry));
3678
    re->func = func;
3679
    re->opaque = opaque;
3680
    re->next = NULL;
3681
    *pre = re;
3682
}
3683

    
3684
void qemu_system_reset(void)
3685
{
3686
    QEMUResetEntry *re;
3687

    
3688
    /* reset all devices */
3689
    for(re = first_reset_entry; re != NULL; re = re->next) {
3690
        re->func(re->opaque);
3691
    }
3692
    if (kvm_enabled())
3693
        kvm_sync_vcpus();
3694
}
3695

    
3696
void qemu_system_reset_request(void)
3697
{
3698
    if (no_reboot) {
3699
        shutdown_requested = 1;
3700
    } else {
3701
        reset_requested = 1;
3702
    }
3703
    if (cpu_single_env)
3704
        cpu_exit(cpu_single_env);
3705
}
3706

    
3707
void qemu_system_shutdown_request(void)
3708
{
3709
    shutdown_requested = 1;
3710
    if (cpu_single_env)
3711
        cpu_exit(cpu_single_env);
3712
}
3713

    
3714
void qemu_system_powerdown_request(void)
3715
{
3716
    powerdown_requested = 1;
3717
    if (cpu_single_env)
3718
        cpu_exit(cpu_single_env);
3719
}
3720

    
3721
#ifdef _WIN32
3722
static void host_main_loop_wait(int *timeout)
3723
{
3724
    int ret, ret2, i;
3725
    PollingEntry *pe;
3726

    
3727

    
3728
    /* XXX: need to suppress polling by better using win32 events */
3729
    ret = 0;
3730
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3731
        ret |= pe->func(pe->opaque);
3732
    }
3733
    if (ret == 0) {
3734
        int err;
3735
        WaitObjects *w = &wait_objects;
3736

    
3737
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3738
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3739
            if (w->func[ret - WAIT_OBJECT_0])
3740
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3741

    
3742
            /* Check for additional signaled events */
3743
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3744

    
3745
                /* Check if event is signaled */
3746
                ret2 = WaitForSingleObject(w->events[i], 0);
3747
                if(ret2 == WAIT_OBJECT_0) {
3748
                    if (w->func[i])
3749
                        w->func[i](w->opaque[i]);
3750
                } else if (ret2 == WAIT_TIMEOUT) {
3751
                } else {
3752
                    err = GetLastError();
3753
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3754
                }
3755
            }
3756
        } else if (ret == WAIT_TIMEOUT) {
3757
        } else {
3758
            err = GetLastError();
3759
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3760
        }
3761
    }
3762

    
3763
    *timeout = 0;
3764
}
3765
#else
3766
static void host_main_loop_wait(int *timeout)
3767
{
3768
}
3769
#endif
3770

    
3771
void main_loop_wait(int timeout)
3772
{
3773
    IOHandlerRecord *ioh;
3774
    fd_set rfds, wfds, xfds;
3775
    int ret, nfds;
3776
    struct timeval tv;
3777

    
3778
    qemu_bh_update_timeout(&timeout);
3779

    
3780
    host_main_loop_wait(&timeout);
3781

    
3782
    /* poll any events */
3783
    /* XXX: separate device handlers from system ones */
3784
    nfds = -1;
3785
    FD_ZERO(&rfds);
3786
    FD_ZERO(&wfds);
3787
    FD_ZERO(&xfds);
3788
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3789
        if (ioh->deleted)
3790
            continue;
3791
        if (ioh->fd_read &&
3792
            (!ioh->fd_read_poll ||
3793
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3794
            FD_SET(ioh->fd, &rfds);
3795
            if (ioh->fd > nfds)
3796
                nfds = ioh->fd;
3797
        }
3798
        if (ioh->fd_write) {
3799
            FD_SET(ioh->fd, &wfds);
3800
            if (ioh->fd > nfds)
3801
                nfds = ioh->fd;
3802
        }
3803
    }
3804

    
3805
    tv.tv_sec = timeout / 1000;
3806
    tv.tv_usec = (timeout % 1000) * 1000;
3807

    
3808
#if defined(CONFIG_SLIRP)
3809
    if (slirp_is_inited()) {
3810
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3811
    }
3812
#endif
3813
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3814
    if (ret > 0) {
3815
        IOHandlerRecord **pioh;
3816

    
3817
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3818
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3819
                ioh->fd_read(ioh->opaque);
3820
            }
3821
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3822
                ioh->fd_write(ioh->opaque);
3823
            }
3824
        }
3825

    
3826
        /* remove deleted IO handlers */
3827
        pioh = &first_io_handler;
3828
        while (*pioh) {
3829
            ioh = *pioh;
3830
            if (ioh->deleted) {
3831
                *pioh = ioh->next;
3832
                qemu_free(ioh);
3833
            } else
3834
                pioh = &ioh->next;
3835
        }
3836
    }
3837
#if defined(CONFIG_SLIRP)
3838
    if (slirp_is_inited()) {
3839
        if (ret < 0) {
3840
            FD_ZERO(&rfds);
3841
            FD_ZERO(&wfds);
3842
            FD_ZERO(&xfds);
3843
        }
3844
        slirp_select_poll(&rfds, &wfds, &xfds);
3845
    }
3846
#endif
3847

    
3848
    /* vm time timers */
3849
    if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3850
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3851
                        qemu_get_clock(vm_clock));
3852

    
3853
    /* real time timers */
3854
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3855
                    qemu_get_clock(rt_clock));
3856

    
3857
    /* Check bottom-halves last in case any of the earlier events triggered
3858
       them.  */
3859
    qemu_bh_poll();
3860

    
3861
}
3862

    
3863
static int main_loop(void)
3864
{
3865
    int ret, timeout;
3866
#ifdef CONFIG_PROFILER
3867
    int64_t ti;
3868
#endif
3869
    CPUState *env;
3870

    
3871
    cur_cpu = first_cpu;
3872
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
3873
    for(;;) {
3874
        if (vm_running) {
3875

    
3876
            for(;;) {
3877
                /* get next cpu */
3878
                env = next_cpu;
3879
#ifdef CONFIG_PROFILER
3880
                ti = profile_getclock();
3881
#endif
3882
                if (use_icount) {
3883
                    int64_t count;
3884
                    int decr;
3885
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3886
                    env->icount_decr.u16.low = 0;
3887
                    env->icount_extra = 0;
3888
                    count = qemu_next_deadline();
3889
                    count = (count + (1 << icount_time_shift) - 1)
3890
                            >> icount_time_shift;
3891
                    qemu_icount += count;
3892
                    decr = (count > 0xffff) ? 0xffff : count;
3893
                    count -= decr;
3894
                    env->icount_decr.u16.low = decr;
3895
                    env->icount_extra = count;
3896
                }
3897
                ret = cpu_exec(env);
3898
#ifdef CONFIG_PROFILER
3899
                qemu_time += profile_getclock() - ti;
3900
#endif
3901
                if (use_icount) {
3902
                    /* Fold pending instructions back into the
3903
                       instruction counter, and clear the interrupt flag.  */
3904
                    qemu_icount -= (env->icount_decr.u16.low
3905
                                    + env->icount_extra);
3906
                    env->icount_decr.u32 = 0;
3907
                    env->icount_extra = 0;
3908
                }
3909
                next_cpu = env->next_cpu ?: first_cpu;
3910
                if (event_pending && likely(ret != EXCP_DEBUG)) {
3911
                    ret = EXCP_INTERRUPT;
3912
                    event_pending = 0;
3913
                    break;
3914
                }
3915
                if (ret == EXCP_HLT) {
3916
                    /* Give the next CPU a chance to run.  */
3917
                    cur_cpu = env;
3918
                    continue;
3919
                }
3920
                if (ret != EXCP_HALTED)
3921
                    break;
3922
                /* all CPUs are halted ? */
3923
                if (env == cur_cpu)
3924
                    break;
3925
            }
3926
            cur_cpu = env;
3927

    
3928
            if (shutdown_requested) {
3929
                ret = EXCP_INTERRUPT;
3930
                if (no_shutdown) {
3931
                    vm_stop(0);
3932
                    no_shutdown = 0;
3933
                }
3934
                else
3935
                    break;
3936
            }
3937
            if (reset_requested) {
3938
                reset_requested = 0;
3939
                qemu_system_reset();
3940
                ret = EXCP_INTERRUPT;
3941
            }
3942
            if (powerdown_requested) {
3943
                powerdown_requested = 0;
3944
                qemu_system_powerdown();
3945
                ret = EXCP_INTERRUPT;
3946
            }
3947
            if (unlikely(ret == EXCP_DEBUG)) {
3948
                gdb_set_stop_cpu(cur_cpu);
3949
                vm_stop(EXCP_DEBUG);
3950
            }
3951
            /* If all cpus are halted then wait until the next IRQ */
3952
            /* XXX: use timeout computed from timers */
3953
            if (ret == EXCP_HALTED) {
3954
                if (use_icount) {
3955
                    int64_t add;
3956
                    int64_t delta;
3957
                    /* Advance virtual time to the next event.  */
3958
                    if (use_icount == 1) {
3959
                        /* When not using an adaptive execution frequency
3960
                           we tend to get badly out of sync with real time,
3961
                           so just delay for a reasonable amount of time.  */
3962
                        delta = 0;
3963
                    } else {
3964
                        delta = cpu_get_icount() - cpu_get_clock();
3965
                    }
3966
                    if (delta > 0) {
3967
                        /* If virtual time is ahead of real time then just
3968
                           wait for IO.  */
3969
                        timeout = (delta / 1000000) + 1;
3970
                    } else {
3971
                        /* Wait for either IO to occur or the next
3972
                           timer event.  */
3973
                        add = qemu_next_deadline();
3974
                        /* We advance the timer before checking for IO.
3975
                           Limit the amount we advance so that early IO
3976
                           activity won't get the guest too far ahead.  */
3977
                        if (add > 10000000)
3978
                            add = 10000000;
3979
                        delta += add;
3980
                        add = (add + (1 << icount_time_shift) - 1)
3981
                              >> icount_time_shift;
3982
                        qemu_icount += add;
3983
                        timeout = delta / 1000000;
3984
                        if (timeout < 0)
3985
                            timeout = 0;
3986
                    }
3987
                } else {
3988
                    timeout = 5000;
3989
                }
3990
            } else {
3991
                timeout = 0;
3992
            }
3993
        } else {
3994
            if (shutdown_requested) {
3995
                ret = EXCP_INTERRUPT;
3996
                break;
3997
            }
3998
            timeout = 5000;
3999
        }
4000
#ifdef CONFIG_PROFILER
4001
        ti = profile_getclock();
4002
#endif
4003
        main_loop_wait(timeout);
4004
#ifdef CONFIG_PROFILER
4005
        dev_time += profile_getclock() - ti;
4006
#endif
4007
    }
4008
    cpu_disable_ticks();
4009
    return ret;
4010
}
4011

    
4012
static void version(void)
4013
{
4014
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4015
}
4016

    
4017
static void help(int exitcode)
4018
{
4019
    version();
4020
    printf("usage: %s [options] [disk_image]\n"
4021
           "\n"
4022
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4023
           "\n"
4024
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4025
           opt_help
4026
#define DEFHEADING(text) stringify(text) "\n"
4027
#include "qemu-options.h"
4028
#undef DEF
4029
#undef DEFHEADING
4030
#undef GEN_DOCS
4031
           "\n"
4032
           "During emulation, the following keys are useful:\n"
4033
           "ctrl-alt-f      toggle full screen\n"
4034
           "ctrl-alt-n      switch to virtual console 'n'\n"
4035
           "ctrl-alt        toggle mouse and keyboard grab\n"
4036
           "\n"
4037
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4038
           ,
4039
           "qemu",
4040
           DEFAULT_RAM_SIZE,
4041
#ifndef _WIN32
4042
           DEFAULT_NETWORK_SCRIPT,
4043
           DEFAULT_NETWORK_DOWN_SCRIPT,
4044
#endif
4045
           DEFAULT_GDBSTUB_PORT,
4046
           "/tmp/qemu.log");
4047
    exit(exitcode);
4048
}
4049

    
4050
#define HAS_ARG 0x0001
4051

    
4052
enum {
4053
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4054
    opt_enum,
4055
#define DEFHEADING(text)
4056
#include "qemu-options.h"
4057
#undef DEF
4058
#undef DEFHEADING
4059
#undef GEN_DOCS
4060
};
4061

    
4062
typedef struct QEMUOption {
4063
    const char *name;
4064
    int flags;
4065
    int index;
4066
} QEMUOption;
4067

    
4068
static const QEMUOption qemu_options[] = {
4069
    { "h", 0, QEMU_OPTION_h },
4070
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4071
    { option, opt_arg, opt_enum },
4072
#define DEFHEADING(text)
4073
#include "qemu-options.h"
4074
#undef DEF
4075
#undef DEFHEADING
4076
#undef GEN_DOCS
4077
    { NULL },
4078
};
4079

    
4080
#ifdef HAS_AUDIO
4081
struct soundhw soundhw[] = {
4082
#ifdef HAS_AUDIO_CHOICE
4083
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4084
    {
4085
        "pcspk",
4086
        "PC speaker",
4087
        0,
4088
        1,
4089
        { .init_isa = pcspk_audio_init }
4090
    },
4091
#endif
4092

    
4093
#ifdef CONFIG_SB16
4094
    {
4095
        "sb16",
4096
        "Creative Sound Blaster 16",
4097
        0,
4098
        1,
4099
        { .init_isa = SB16_init }
4100
    },
4101
#endif
4102

    
4103
#ifdef CONFIG_CS4231A
4104
    {
4105
        "cs4231a",
4106
        "CS4231A",
4107
        0,
4108
        1,
4109
        { .init_isa = cs4231a_init }
4110
    },
4111
#endif
4112

    
4113
#ifdef CONFIG_ADLIB
4114
    {
4115
        "adlib",
4116
#ifdef HAS_YMF262
4117
        "Yamaha YMF262 (OPL3)",
4118
#else
4119
        "Yamaha YM3812 (OPL2)",
4120
#endif
4121
        0,
4122
        1,
4123
        { .init_isa = Adlib_init }
4124
    },
4125
#endif
4126

    
4127
#ifdef CONFIG_GUS
4128
    {
4129
        "gus",
4130
        "Gravis Ultrasound GF1",
4131
        0,
4132
        1,
4133
        { .init_isa = GUS_init }
4134
    },
4135
#endif
4136

    
4137
#ifdef CONFIG_AC97
4138
    {
4139
        "ac97",
4140
        "Intel 82801AA AC97 Audio",
4141
        0,
4142
        0,
4143
        { .init_pci = ac97_init }
4144
    },
4145
#endif
4146

    
4147
#ifdef CONFIG_ES1370
4148
    {
4149
        "es1370",
4150
        "ENSONIQ AudioPCI ES1370",
4151
        0,
4152
        0,
4153
        { .init_pci = es1370_init }
4154
    },
4155
#endif
4156

    
4157
#endif /* HAS_AUDIO_CHOICE */
4158

    
4159
    { NULL, NULL, 0, 0, { NULL } }
4160
};
4161

    
4162
static void select_soundhw (const char *optarg)
4163
{
4164
    struct soundhw *c;
4165

    
4166
    if (*optarg == '?') {
4167
    show_valid_cards:
4168

    
4169
        printf ("Valid sound card names (comma separated):\n");
4170
        for (c = soundhw; c->name; ++c) {
4171
            printf ("%-11s %s\n", c->name, c->descr);
4172
        }
4173
        printf ("\n-soundhw all will enable all of the above\n");
4174
        exit (*optarg != '?');
4175
    }
4176
    else {
4177
        size_t l;
4178
        const char *p;
4179
        char *e;
4180
        int bad_card = 0;
4181

    
4182
        if (!strcmp (optarg, "all")) {
4183
            for (c = soundhw; c->name; ++c) {
4184
                c->enabled = 1;
4185
            }
4186
            return;
4187
        }
4188

    
4189
        p = optarg;
4190
        while (*p) {
4191
            e = strchr (p, ',');
4192
            l = !e ? strlen (p) : (size_t) (e - p);
4193

    
4194
            for (c = soundhw; c->name; ++c) {
4195
                if (!strncmp (c->name, p, l)) {
4196
                    c->enabled = 1;
4197
                    break;
4198
                }
4199
            }
4200

    
4201
            if (!c->name) {
4202
                if (l > 80) {
4203
                    fprintf (stderr,
4204
                             "Unknown sound card name (too big to show)\n");
4205
                }
4206
                else {
4207
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4208
                             (int) l, p);
4209
                }
4210
                bad_card = 1;
4211
            }
4212
            p += l + (e != NULL);
4213
        }
4214

    
4215
        if (bad_card)
4216
            goto show_valid_cards;
4217
    }
4218
}
4219
#endif
4220

    
4221
static void select_vgahw (const char *p)
4222
{
4223
    const char *opts;
4224

    
4225
    if (strstart(p, "std", &opts)) {
4226
        std_vga_enabled = 1;
4227
        cirrus_vga_enabled = 0;
4228
        vmsvga_enabled = 0;
4229
    } else if (strstart(p, "cirrus", &opts)) {
4230
        cirrus_vga_enabled = 1;
4231
        std_vga_enabled = 0;
4232
        vmsvga_enabled = 0;
4233
    } else if (strstart(p, "vmware", &opts)) {
4234
        cirrus_vga_enabled = 0;
4235
        std_vga_enabled = 0;
4236
        vmsvga_enabled = 1;
4237
    } else if (strstart(p, "none", &opts)) {
4238
        cirrus_vga_enabled = 0;
4239
        std_vga_enabled = 0;
4240
        vmsvga_enabled = 0;
4241
    } else {
4242
    invalid_vga:
4243
        fprintf(stderr, "Unknown vga type: %s\n", p);
4244
        exit(1);
4245
    }
4246
    while (*opts) {
4247
        const char *nextopt;
4248

    
4249
        if (strstart(opts, ",retrace=", &nextopt)) {
4250
            opts = nextopt;
4251
            if (strstart(opts, "dumb", &nextopt))
4252
                vga_retrace_method = VGA_RETRACE_DUMB;
4253
            else if (strstart(opts, "precise", &nextopt))
4254
                vga_retrace_method = VGA_RETRACE_PRECISE;
4255
            else goto invalid_vga;
4256
        } else goto invalid_vga;
4257
        opts = nextopt;
4258
    }
4259
}
4260

    
4261
#ifdef _WIN32
4262
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4263
{
4264
    exit(STATUS_CONTROL_C_EXIT);
4265
    return TRUE;
4266
}
4267
#endif
4268

    
4269
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4270
{
4271
    int ret;
4272

    
4273
    if(strlen(str) != 36)
4274
        return -1;
4275

    
4276
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4277
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4278
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4279

    
4280
    if(ret != 16)
4281
        return -1;
4282

    
4283
#ifdef TARGET_I386
4284
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4285
#endif
4286

    
4287
    return 0;
4288
}
4289

    
4290
#define MAX_NET_CLIENTS 32
4291

    
4292
#ifndef _WIN32
4293

    
4294
static void termsig_handler(int signal)
4295
{
4296
    qemu_system_shutdown_request();
4297
}
4298

    
4299
static void termsig_setup(void)
4300
{
4301
    struct sigaction act;
4302

    
4303
    memset(&act, 0, sizeof(act));
4304
    act.sa_handler = termsig_handler;
4305
    sigaction(SIGINT,  &act, NULL);
4306
    sigaction(SIGHUP,  &act, NULL);
4307
    sigaction(SIGTERM, &act, NULL);
4308
}
4309

    
4310
#endif
4311

    
4312
int main(int argc, char **argv, char **envp)
4313
{
4314
#ifdef CONFIG_GDBSTUB
4315
    const char *gdbstub_dev = NULL;
4316
#endif
4317
    uint32_t boot_devices_bitmap = 0;
4318
    int i;
4319
    int snapshot, linux_boot, net_boot;
4320
    const char *initrd_filename;
4321
    const char *kernel_filename, *kernel_cmdline;
4322
    const char *boot_devices = "";
4323
    DisplayState *ds;
4324
    DisplayChangeListener *dcl;
4325
    int cyls, heads, secs, translation;
4326
    const char *net_clients[MAX_NET_CLIENTS];
4327
    int nb_net_clients;
4328
    const char *bt_opts[MAX_BT_CMDLINE];
4329
    int nb_bt_opts;
4330
    int hda_index;
4331
    int optind;
4332
    const char *r, *optarg;
4333
    CharDriverState *monitor_hd = NULL;
4334
    const char *monitor_device;
4335
    const char *serial_devices[MAX_SERIAL_PORTS];
4336
    int serial_device_index;
4337
    const char *parallel_devices[MAX_PARALLEL_PORTS];
4338
    int parallel_device_index;
4339
    const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4340
    int virtio_console_index;
4341
    const char *loadvm = NULL;
4342
    QEMUMachine *machine;
4343
    const char *cpu_model;
4344
    const char *usb_devices[MAX_USB_CMDLINE];
4345
    int usb_devices_index;
4346
#ifndef _WIN32
4347
    int fds[2];
4348
#endif
4349
    int tb_size;
4350
    const char *pid_file = NULL;
4351
    const char *incoming = NULL;
4352
#ifndef _WIN32
4353
    int fd = 0;
4354
    struct passwd *pwd = NULL;
4355
    const char *chroot_dir = NULL;
4356
    const char *run_as = NULL;
4357
#endif
4358
    CPUState *env;
4359

    
4360
    qemu_cache_utils_init(envp);
4361

    
4362
    LIST_INIT (&vm_change_state_head);
4363
#ifndef _WIN32
4364
    {
4365
        struct sigaction act;
4366
        sigfillset(&act.sa_mask);
4367
        act.sa_flags = 0;
4368
        act.sa_handler = SIG_IGN;
4369
        sigaction(SIGPIPE, &act, NULL);
4370
    }
4371
#else
4372
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4373
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4374
       QEMU to run on a single CPU */
4375
    {
4376
        HANDLE h;
4377
        DWORD mask, smask;
4378
        int i;
4379
        h = GetCurrentProcess();
4380
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4381
            for(i = 0; i < 32; i++) {
4382
                if (mask & (1 << i))
4383
                    break;
4384
            }
4385
            if (i != 32) {
4386
                mask = 1 << i;
4387
                SetProcessAffinityMask(h, mask);
4388
            }
4389
        }
4390
    }
4391
#endif
4392

    
4393
    register_machines();
4394
    machine = first_machine;
4395
    cpu_model = NULL;
4396
    initrd_filename = NULL;
4397
    ram_size = 0;
4398
    vga_ram_size = VGA_RAM_SIZE;
4399
    snapshot = 0;
4400
    nographic = 0;
4401
    curses = 0;
4402
    kernel_filename = NULL;
4403
    kernel_cmdline = "";
4404
    cyls = heads = secs = 0;
4405
    translation = BIOS_ATA_TRANSLATION_AUTO;
4406
    monitor_device = "vc:80Cx24C";
4407

    
4408
    serial_devices[0] = "vc:80Cx24C";
4409
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4410
        serial_devices[i] = NULL;
4411
    serial_device_index = 0;
4412

    
4413
    parallel_devices[0] = "vc:80Cx24C";
4414
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4415
        parallel_devices[i] = NULL;
4416
    parallel_device_index = 0;
4417

    
4418
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4419
        virtio_consoles[i] = NULL;
4420
    virtio_console_index = 0;
4421

    
4422
    for (i = 0; i < MAX_NODES; i++) {
4423
        node_mem[i] = 0;
4424
        node_cpumask[i] = 0;
4425
    }
4426

    
4427
    usb_devices_index = 0;
4428

    
4429
    nb_net_clients = 0;
4430
    nb_bt_opts = 0;
4431
    nb_drives = 0;
4432
    nb_drives_opt = 0;
4433
    nb_numa_nodes = 0;
4434
    hda_index = -1;
4435

    
4436
    nb_nics = 0;
4437

    
4438
    tb_size = 0;
4439
    autostart= 1;
4440

    
4441
    optind = 1;
4442
    for(;;) {
4443
        if (optind >= argc)
4444
            break;
4445
        r = argv[optind];
4446
        if (r[0] != '-') {
4447
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4448
        } else {
4449
            const QEMUOption *popt;
4450

    
4451
            optind++;
4452
            /* Treat --foo the same as -foo.  */
4453
            if (r[1] == '-')
4454
                r++;
4455
            popt = qemu_options;
4456
            for(;;) {
4457
                if (!popt->name) {
4458
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
4459
                            argv[0], r);
4460
                    exit(1);
4461
                }
4462
                if (!strcmp(popt->name, r + 1))
4463
                    break;
4464
                popt++;
4465
            }
4466
            if (popt->flags & HAS_ARG) {
4467
                if (optind >= argc) {
4468
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
4469
                            argv[0], r);
4470
                    exit(1);
4471
                }
4472
                optarg = argv[optind++];
4473
            } else {
4474
                optarg = NULL;
4475
            }
4476

    
4477
            switch(popt->index) {
4478
            case QEMU_OPTION_M:
4479
                machine = find_machine(optarg);
4480
                if (!machine) {
4481
                    QEMUMachine *m;
4482
                    printf("Supported machines are:\n");
4483
                    for(m = first_machine; m != NULL; m = m->next) {
4484
                        printf("%-10s %s%s\n",
4485
                               m->name, m->desc,
4486
                               m == first_machine ? " (default)" : "");
4487
                    }
4488
                    exit(*optarg != '?');
4489
                }
4490
                break;
4491
            case QEMU_OPTION_cpu:
4492
                /* hw initialization will check this */
4493
                if (*optarg == '?') {
4494
/* XXX: implement xxx_cpu_list for targets that still miss it */
4495
#if defined(cpu_list)
4496
                    cpu_list(stdout, &fprintf);
4497
#endif
4498
                    exit(0);
4499
                } else {
4500
                    cpu_model = optarg;
4501
                }
4502
                break;
4503
            case QEMU_OPTION_initrd:
4504
                initrd_filename = optarg;
4505
                break;
4506
            case QEMU_OPTION_hda:
4507
                if (cyls == 0)
4508
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
4509
                else
4510
                    hda_index = drive_add(optarg, HD_ALIAS
4511
                             ",cyls=%d,heads=%d,secs=%d%s",
4512
                             0, cyls, heads, secs,
4513
                             translation == BIOS_ATA_TRANSLATION_LBA ?
4514
                                 ",trans=lba" :
4515
                             translation == BIOS_ATA_TRANSLATION_NONE ?
4516
                                 ",trans=none" : "");
4517
                 break;
4518
            case QEMU_OPTION_hdb:
4519
            case QEMU_OPTION_hdc:
4520
            case QEMU_OPTION_hdd:
4521
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4522
                break;
4523
            case QEMU_OPTION_drive:
4524
                drive_add(NULL, "%s", optarg);
4525
                break;
4526
            case QEMU_OPTION_mtdblock:
4527
                drive_add(optarg, MTD_ALIAS);
4528
                break;
4529
            case QEMU_OPTION_sd:
4530
                drive_add(optarg, SD_ALIAS);
4531
                break;
4532
            case QEMU_OPTION_pflash:
4533
                drive_add(optarg, PFLASH_ALIAS);
4534
                break;
4535
            case QEMU_OPTION_snapshot:
4536
                snapshot = 1;
4537
                break;
4538
            case QEMU_OPTION_hdachs:
4539
                {
4540
                    const char *p;
4541
                    p = optarg;
4542
                    cyls = strtol(p, (char **)&p, 0);
4543
                    if (cyls < 1 || cyls > 16383)
4544
                        goto chs_fail;
4545
                    if (*p != ',')
4546
                        goto chs_fail;
4547
                    p++;
4548
                    heads = strtol(p, (char **)&p, 0);
4549
                    if (heads < 1 || heads > 16)
4550
                        goto chs_fail;
4551
                    if (*p != ',')
4552
                        goto chs_fail;
4553
                    p++;
4554
                    secs = strtol(p, (char **)&p, 0);
4555
                    if (secs < 1 || secs > 63)
4556
                        goto chs_fail;
4557
                    if (*p == ',') {
4558
                        p++;
4559
                        if (!strcmp(p, "none"))
4560
                            translation = BIOS_ATA_TRANSLATION_NONE;
4561
                        else if (!strcmp(p, "lba"))
4562
                            translation = BIOS_ATA_TRANSLATION_LBA;
4563
                        else if (!strcmp(p, "auto"))
4564
                            translation = BIOS_ATA_TRANSLATION_AUTO;
4565
                        else
4566
                            goto chs_fail;
4567
                    } else if (*p != '\0') {
4568
                    chs_fail:
4569
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
4570
                        exit(1);
4571
                    }
4572
                    if (hda_index != -1)
4573
                        snprintf(drives_opt[hda_index].opt,
4574
                                 sizeof(drives_opt[hda_index].opt),
4575
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4576
                                 0, cyls, heads, secs,
4577
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
4578
                                         ",trans=lba" :
4579
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
4580
                                     ",trans=none" : "");
4581
                }
4582
                break;
4583
            case QEMU_OPTION_numa:
4584
                if (nb_numa_nodes >= MAX_NODES) {
4585
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
4586
                    exit(1);
4587
                }
4588
                numa_add(optarg);
4589
                break;
4590
            case QEMU_OPTION_nographic:
4591
                nographic = 1;
4592
                break;
4593
#ifdef CONFIG_CURSES
4594
            case QEMU_OPTION_curses:
4595
                curses = 1;
4596
                break;
4597
#endif
4598
            case QEMU_OPTION_portrait:
4599
                graphic_rotate = 1;
4600
                break;
4601
            case QEMU_OPTION_kernel:
4602
                kernel_filename = optarg;
4603
                break;
4604
            case QEMU_OPTION_append:
4605
                kernel_cmdline = optarg;
4606
                break;
4607
            case QEMU_OPTION_cdrom:
4608
                drive_add(optarg, CDROM_ALIAS);
4609
                break;
4610
            case QEMU_OPTION_boot:
4611
                boot_devices = optarg;
4612
                /* We just do some generic consistency checks */
4613
                {
4614
                    /* Could easily be extended to 64 devices if needed */
4615
                    const char *p;
4616
                    
4617
                    boot_devices_bitmap = 0;
4618
                    for (p = boot_devices; *p != '\0'; p++) {
4619
                        /* Allowed boot devices are:
4620
                         * a b     : floppy disk drives
4621
                         * c ... f : IDE disk drives
4622
                         * g ... m : machine implementation dependant drives
4623
                         * n ... p : network devices
4624
                         * It's up to each machine implementation to check
4625
                         * if the given boot devices match the actual hardware
4626
                         * implementation and firmware features.
4627
                         */
4628
                        if (*p < 'a' || *p > 'q') {
4629
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
4630
                            exit(1);
4631
                        }
4632
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4633
                            fprintf(stderr,
4634
                                    "Boot device '%c' was given twice\n",*p);
4635
                            exit(1);
4636
                        }
4637
                        boot_devices_bitmap |= 1 << (*p - 'a');
4638
                    }
4639
                }
4640
                break;
4641
            case QEMU_OPTION_fda:
4642
            case QEMU_OPTION_fdb:
4643
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4644
                break;
4645
#ifdef TARGET_I386
4646
            case QEMU_OPTION_no_fd_bootchk:
4647
                fd_bootchk = 0;
4648
                break;
4649
#endif
4650
            case QEMU_OPTION_net:
4651
                if (nb_net_clients >= MAX_NET_CLIENTS) {
4652
                    fprintf(stderr, "qemu: too many network clients\n");
4653
                    exit(1);
4654
                }
4655
                net_clients[nb_net_clients] = optarg;
4656
                nb_net_clients++;
4657
                break;
4658
#ifdef CONFIG_SLIRP
4659
            case QEMU_OPTION_tftp:
4660
                tftp_prefix = optarg;
4661
                break;
4662
            case QEMU_OPTION_bootp:
4663
                bootp_filename = optarg;
4664
                break;
4665
#ifndef _WIN32
4666
            case QEMU_OPTION_smb:
4667
                net_slirp_smb(optarg);
4668
                break;
4669
#endif
4670
            case QEMU_OPTION_redir:
4671
                net_slirp_redir(NULL, optarg);
4672
                break;
4673
#endif
4674
            case QEMU_OPTION_bt:
4675
                if (nb_bt_opts >= MAX_BT_CMDLINE) {
4676
                    fprintf(stderr, "qemu: too many bluetooth options\n");
4677
                    exit(1);
4678
                }
4679
                bt_opts[nb_bt_opts++] = optarg;
4680
                break;
4681
#ifdef HAS_AUDIO
4682
            case QEMU_OPTION_audio_help:
4683
                AUD_help ();
4684
                exit (0);
4685
                break;
4686
            case QEMU_OPTION_soundhw:
4687
                select_soundhw (optarg);
4688
                break;
4689
#endif
4690
            case QEMU_OPTION_h:
4691
                help(0);
4692
                break;
4693
            case QEMU_OPTION_version:
4694
                version();
4695
                exit(0);
4696
                break;
4697
            case QEMU_OPTION_m: {
4698
                uint64_t value;
4699
                char *ptr;
4700

    
4701
                value = strtoul(optarg, &ptr, 10);
4702
                switch (*ptr) {
4703
                case 0: case 'M': case 'm':
4704
                    value <<= 20;
4705
                    break;
4706
                case 'G': case 'g':
4707
                    value <<= 30;
4708
                    break;
4709
                default:
4710
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4711
                    exit(1);
4712
                }
4713

    
4714
                /* On 32-bit hosts, QEMU is limited by virtual address space */
4715
                if (value > (2047 << 20)
4716
#ifndef CONFIG_KQEMU
4717
                    && HOST_LONG_BITS == 32
4718
#endif
4719
                    ) {
4720
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4721
                    exit(1);
4722
                }
4723
                if (value != (uint64_t)(ram_addr_t)value) {
4724
                    fprintf(stderr, "qemu: ram size too large\n");
4725
                    exit(1);
4726
                }
4727
                ram_size = value;
4728
                break;
4729
            }
4730
            case QEMU_OPTION_d:
4731
                {
4732
                    int mask;
4733
                    const CPULogItem *item;
4734

    
4735
                    mask = cpu_str_to_log_mask(optarg);
4736
                    if (!mask) {
4737
                        printf("Log items (comma separated):\n");
4738
                    for(item = cpu_log_items; item->mask != 0; item++) {
4739
                        printf("%-10s %s\n", item->name, item->help);
4740
                    }
4741
                    exit(1);
4742
                    }
4743
                    cpu_set_log(mask);
4744
                }
4745
                break;
4746
#ifdef CONFIG_GDBSTUB
4747
            case QEMU_OPTION_s:
4748
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4749
                break;
4750
            case QEMU_OPTION_gdb:
4751
                gdbstub_dev = optarg;
4752
                break;
4753
#endif
4754
            case QEMU_OPTION_L:
4755
                bios_dir = optarg;
4756
                break;
4757
            case QEMU_OPTION_bios:
4758
                bios_name = optarg;
4759
                break;
4760
            case QEMU_OPTION_singlestep:
4761
                singlestep = 1;
4762
                break;
4763
            case QEMU_OPTION_S:
4764
                autostart = 0;
4765
                break;
4766
#ifndef _WIN32
4767
            case QEMU_OPTION_k:
4768
                keyboard_layout = optarg;
4769
                break;
4770
#endif
4771
            case QEMU_OPTION_localtime:
4772
                rtc_utc = 0;
4773
                break;
4774
            case QEMU_OPTION_vga:
4775
                select_vgahw (optarg);
4776
                break;
4777
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4778
            case QEMU_OPTION_g:
4779
                {
4780
                    const char *p;
4781
                    int w, h, depth;
4782
                    p = optarg;
4783
                    w = strtol(p, (char **)&p, 10);
4784
                    if (w <= 0) {
4785
                    graphic_error:
4786
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
4787
                        exit(1);
4788
                    }
4789
                    if (*p != 'x')
4790
                        goto graphic_error;
4791
                    p++;
4792
                    h = strtol(p, (char **)&p, 10);
4793
                    if (h <= 0)
4794
                        goto graphic_error;
4795
                    if (*p == 'x') {
4796
                        p++;
4797
                        depth = strtol(p, (char **)&p, 10);
4798
                        if (depth != 8 && depth != 15 && depth != 16 &&
4799
                            depth != 24 && depth != 32)
4800
                            goto graphic_error;
4801
                    } else if (*p == '\0') {
4802
                        depth = graphic_depth;
4803
                    } else {
4804
                        goto graphic_error;
4805
                    }
4806

    
4807
                    graphic_width = w;
4808
                    graphic_height = h;
4809
                    graphic_depth = depth;
4810
                }
4811
                break;
4812
#endif
4813
            case QEMU_OPTION_echr:
4814
                {
4815
                    char *r;
4816
                    term_escape_char = strtol(optarg, &r, 0);
4817
                    if (r == optarg)
4818
                        printf("Bad argument to echr\n");
4819
                    break;
4820
                }
4821
            case QEMU_OPTION_monitor:
4822
                monitor_device = optarg;
4823
                break;
4824
            case QEMU_OPTION_serial:
4825
                if (serial_device_index >= MAX_SERIAL_PORTS) {
4826
                    fprintf(stderr, "qemu: too many serial ports\n");
4827
                    exit(1);
4828
                }
4829
                serial_devices[serial_device_index] = optarg;
4830
                serial_device_index++;
4831
                break;
4832
            case QEMU_OPTION_virtiocon:
4833
                if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4834
                    fprintf(stderr, "qemu: too many virtio consoles\n");
4835
                    exit(1);
4836
                }
4837
                virtio_consoles[virtio_console_index] = optarg;
4838
                virtio_console_index++;
4839
                break;
4840
            case QEMU_OPTION_parallel:
4841
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4842
                    fprintf(stderr, "qemu: too many parallel ports\n");
4843
                    exit(1);
4844
                }
4845
                parallel_devices[parallel_device_index] = optarg;
4846
                parallel_device_index++;
4847
                break;
4848
            case QEMU_OPTION_loadvm:
4849
                loadvm = optarg;
4850
                break;
4851
            case QEMU_OPTION_full_screen:
4852
                full_screen = 1;
4853
                break;
4854
#ifdef CONFIG_SDL
4855
            case QEMU_OPTION_no_frame:
4856
                no_frame = 1;
4857
                break;
4858
            case QEMU_OPTION_alt_grab:
4859
                alt_grab = 1;
4860
                break;
4861
            case QEMU_OPTION_no_quit:
4862
                no_quit = 1;
4863
                break;
4864
            case QEMU_OPTION_sdl:
4865
                sdl = 1;
4866
                break;
4867
#endif
4868
            case QEMU_OPTION_pidfile:
4869
                pid_file = optarg;
4870
                break;
4871
#ifdef TARGET_I386
4872
            case QEMU_OPTION_win2k_hack:
4873
                win2k_install_hack = 1;
4874
                break;
4875
            case QEMU_OPTION_rtc_td_hack:
4876
                rtc_td_hack = 1;
4877
                break;
4878
            case QEMU_OPTION_acpitable:
4879
                if(acpi_table_add(optarg) < 0) {
4880
                    fprintf(stderr, "Wrong acpi table provided\n");
4881
                    exit(1);
4882
                }
4883
                break;
4884
            case QEMU_OPTION_smbios:
4885
                if(smbios_entry_add(optarg) < 0) {
4886
                    fprintf(stderr, "Wrong smbios provided\n");
4887
                    exit(1);
4888
                }
4889
                break;
4890
#endif
4891
#ifdef CONFIG_KQEMU
4892
            case QEMU_OPTION_no_kqemu:
4893
                kqemu_allowed = 0;
4894
                break;
4895
            case QEMU_OPTION_kernel_kqemu:
4896
                kqemu_allowed = 2;
4897
                break;
4898
#endif
4899
#ifdef CONFIG_KVM
4900
            case QEMU_OPTION_enable_kvm:
4901
                kvm_allowed = 1;
4902
#ifdef CONFIG_KQEMU
4903
                kqemu_allowed = 0;
4904
#endif
4905
                break;
4906
#endif
4907
            case QEMU_OPTION_usb:
4908
                usb_enabled = 1;
4909
                break;
4910
            case QEMU_OPTION_usbdevice:
4911
                usb_enabled = 1;
4912
                if (usb_devices_index >= MAX_USB_CMDLINE) {
4913
                    fprintf(stderr, "Too many USB devices\n");
4914
                    exit(1);
4915
                }
4916
                usb_devices[usb_devices_index] = optarg;
4917
                usb_devices_index++;
4918
                break;
4919
            case QEMU_OPTION_smp:
4920
                smp_cpus = atoi(optarg);
4921
                if (smp_cpus < 1) {
4922
                    fprintf(stderr, "Invalid number of CPUs\n");
4923
                    exit(1);
4924
                }
4925
                break;
4926
            case QEMU_OPTION_vnc:
4927
                vnc_display = optarg;
4928
                break;
4929
#ifdef TARGET_I386
4930
            case QEMU_OPTION_no_acpi:
4931
                acpi_enabled = 0;
4932
                break;
4933
            case QEMU_OPTION_no_hpet:
4934
                no_hpet = 1;
4935
                break;
4936
#endif
4937
            case QEMU_OPTION_no_reboot:
4938
                no_reboot = 1;
4939
                break;
4940
            case QEMU_OPTION_no_shutdown:
4941
                no_shutdown = 1;
4942
                break;
4943
            case QEMU_OPTION_show_cursor:
4944
                cursor_hide = 0;
4945
                break;
4946
            case QEMU_OPTION_uuid:
4947
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4948
                    fprintf(stderr, "Fail to parse UUID string."
4949
                            " Wrong format.\n");
4950
                    exit(1);
4951
                }
4952
                break;
4953
#ifndef _WIN32
4954
            case QEMU_OPTION_daemonize:
4955
                daemonize = 1;
4956
                break;
4957
#endif
4958
            case QEMU_OPTION_option_rom:
4959
                if (nb_option_roms >= MAX_OPTION_ROMS) {
4960
                    fprintf(stderr, "Too many option ROMs\n");
4961
                    exit(1);
4962
                }
4963
                option_rom[nb_option_roms] = optarg;
4964
                nb_option_roms++;
4965
                break;
4966
#if defined(TARGET_ARM) || defined(TARGET_M68K)
4967
            case QEMU_OPTION_semihosting:
4968
                semihosting_enabled = 1;
4969
                break;
4970
#endif
4971
            case QEMU_OPTION_name:
4972
                qemu_name = optarg;
4973
                break;
4974
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
4975
            case QEMU_OPTION_prom_env:
4976
                if (nb_prom_envs >= MAX_PROM_ENVS) {
4977
                    fprintf(stderr, "Too many prom variables\n");
4978
                    exit(1);
4979
                }
4980
                prom_envs[nb_prom_envs] = optarg;
4981
                nb_prom_envs++;
4982
                break;
4983
#endif
4984
#ifdef TARGET_ARM
4985
            case QEMU_OPTION_old_param:
4986
                old_param = 1;
4987
                break;
4988
#endif
4989
            case QEMU_OPTION_clock:
4990
                configure_alarms(optarg);
4991
                break;
4992
            case QEMU_OPTION_startdate:
4993
                {
4994
                    struct tm tm;
4995
                    time_t rtc_start_date;
4996
                    if (!strcmp(optarg, "now")) {
4997
                        rtc_date_offset = -1;
4998
                    } else {
4999
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5000
                               &tm.tm_year,
5001
                               &tm.tm_mon,
5002
                               &tm.tm_mday,
5003
                               &tm.tm_hour,
5004
                               &tm.tm_min,
5005
                               &tm.tm_sec) == 6) {
5006
                            /* OK */
5007
                        } else if (sscanf(optarg, "%d-%d-%d",
5008
                                          &tm.tm_year,
5009
                                          &tm.tm_mon,
5010
                                          &tm.tm_mday) == 3) {
5011
                            tm.tm_hour = 0;
5012
                            tm.tm_min = 0;
5013
                            tm.tm_sec = 0;
5014
                        } else {
5015
                            goto date_fail;
5016
                        }
5017
                        tm.tm_year -= 1900;
5018
                        tm.tm_mon--;
5019
                        rtc_start_date = mktimegm(&tm);
5020
                        if (rtc_start_date == -1) {
5021
                        date_fail:
5022
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
5023
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5024
                            exit(1);
5025
                        }
5026
                        rtc_date_offset = time(NULL) - rtc_start_date;
5027
                    }
5028
                }
5029
                break;
5030
            case QEMU_OPTION_tb_size:
5031
                tb_size = strtol(optarg, NULL, 0);
5032
                if (tb_size < 0)
5033
                    tb_size = 0;
5034
                break;
5035
            case QEMU_OPTION_icount:
5036
                use_icount = 1;
5037
                if (strcmp(optarg, "auto") == 0) {
5038
                    icount_time_shift = -1;
5039
                } else {
5040
                    icount_time_shift = strtol(optarg, NULL, 0);
5041
                }
5042
                break;
5043
            case QEMU_OPTION_incoming:
5044
                incoming = optarg;
5045
                break;
5046
#ifndef _WIN32
5047
            case QEMU_OPTION_chroot:
5048
                chroot_dir = optarg;
5049
                break;
5050
            case QEMU_OPTION_runas:
5051
                run_as = optarg;
5052
                break;
5053
#endif
5054
#ifdef CONFIG_XEN
5055
            case QEMU_OPTION_xen_domid:
5056
                xen_domid = atoi(optarg);
5057
                break;
5058
            case QEMU_OPTION_xen_create:
5059
                xen_mode = XEN_CREATE;
5060
                break;
5061
            case QEMU_OPTION_xen_attach:
5062
                xen_mode = XEN_ATTACH;
5063
                break;
5064
#endif
5065
            }
5066
        }
5067
    }
5068

    
5069
#if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5070
    if (kvm_allowed && kqemu_allowed) {
5071
        fprintf(stderr,
5072
                "You can not enable both KVM and kqemu at the same time\n");
5073
        exit(1);
5074
    }
5075
#endif
5076

    
5077
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5078
    if (smp_cpus > machine->max_cpus) {
5079
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5080
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5081
                machine->max_cpus);
5082
        exit(1);
5083
    }
5084

    
5085
    if (nographic) {
5086
       if (serial_device_index == 0)
5087
           serial_devices[0] = "stdio";
5088
       if (parallel_device_index == 0)
5089
           parallel_devices[0] = "null";
5090
       if (strncmp(monitor_device, "vc", 2) == 0)
5091
           monitor_device = "stdio";
5092
    }
5093

    
5094
#ifndef _WIN32
5095
    if (daemonize) {
5096
        pid_t pid;
5097

    
5098
        if (pipe(fds) == -1)
5099
            exit(1);
5100

    
5101
        pid = fork();
5102
        if (pid > 0) {
5103
            uint8_t status;
5104
            ssize_t len;
5105

    
5106
            close(fds[1]);
5107

    
5108
        again:
5109
            len = read(fds[0], &status, 1);
5110
            if (len == -1 && (errno == EINTR))
5111
                goto again;
5112

    
5113
            if (len != 1)
5114
                exit(1);
5115
            else if (status == 1) {
5116
                fprintf(stderr, "Could not acquire pidfile\n");
5117
                exit(1);
5118
            } else
5119
                exit(0);
5120
        } else if (pid < 0)
5121
            exit(1);
5122

    
5123
        setsid();
5124

    
5125
        pid = fork();
5126
        if (pid > 0)
5127
            exit(0);
5128
        else if (pid < 0)
5129
            exit(1);
5130

    
5131
        umask(027);
5132

    
5133
        signal(SIGTSTP, SIG_IGN);
5134
        signal(SIGTTOU, SIG_IGN);
5135
        signal(SIGTTIN, SIG_IGN);
5136
    }
5137

    
5138
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5139
        if (daemonize) {
5140
            uint8_t status = 1;
5141
            write(fds[1], &status, 1);
5142
        } else
5143
            fprintf(stderr, "Could not acquire pid file\n");
5144
        exit(1);
5145
    }
5146
#endif
5147

    
5148
#ifdef CONFIG_KQEMU
5149
    if (smp_cpus > 1)
5150
        kqemu_allowed = 0;
5151
#endif
5152
    linux_boot = (kernel_filename != NULL);
5153
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5154

    
5155
    if (!linux_boot && *kernel_cmdline != '\0') {
5156
        fprintf(stderr, "-append only allowed with -kernel option\n");
5157
        exit(1);
5158
    }
5159

    
5160
    if (!linux_boot && initrd_filename != NULL) {
5161
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5162
        exit(1);
5163
    }
5164

    
5165
    /* boot to floppy or the default cd if no hard disk defined yet */
5166
    if (!boot_devices[0]) {
5167
        boot_devices = "cad";
5168
    }
5169
    setvbuf(stdout, NULL, _IOLBF, 0);
5170

    
5171
    init_timers();
5172
    if (init_timer_alarm() < 0) {
5173
        fprintf(stderr, "could not initialize alarm timer\n");
5174
        exit(1);
5175
    }
5176
    if (use_icount && icount_time_shift < 0) {
5177
        use_icount = 2;
5178
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5179
           It will be corrected fairly quickly anyway.  */
5180
        icount_time_shift = 3;
5181
        init_icount_adjust();
5182
    }
5183

    
5184
#ifdef _WIN32
5185
    socket_init();
5186
#endif
5187

    
5188
    /* init network clients */
5189
    if (nb_net_clients == 0) {
5190
        /* if no clients, we use a default config */
5191
        net_clients[nb_net_clients++] = "nic";
5192
#ifdef CONFIG_SLIRP
5193
        net_clients[nb_net_clients++] = "user";
5194
#endif
5195
    }
5196

    
5197
    for(i = 0;i < nb_net_clients; i++) {
5198
        if (net_client_parse(net_clients[i]) < 0)
5199
            exit(1);
5200
    }
5201
    net_client_check();
5202

    
5203
#ifdef TARGET_I386
5204
    /* XXX: this should be moved in the PC machine instantiation code */
5205
    if (net_boot != 0) {
5206
        int netroms = 0;
5207
        for (i = 0; i < nb_nics && i < 4; i++) {
5208
            const char *model = nd_table[i].model;
5209
            char buf[1024];
5210
            if (net_boot & (1 << i)) {
5211
                if (model == NULL)
5212
                    model = "ne2k_pci";
5213
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5214
                if (get_image_size(buf) > 0) {
5215
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
5216
                        fprintf(stderr, "Too many option ROMs\n");
5217
                        exit(1);
5218
                    }
5219
                    option_rom[nb_option_roms] = strdup(buf);
5220
                    nb_option_roms++;
5221
                    netroms++;
5222
                }
5223
            }
5224
        }
5225
        if (netroms == 0) {
5226
            fprintf(stderr, "No valid PXE rom found for network device\n");
5227
            exit(1);
5228
        }
5229
    }
5230
#endif
5231

    
5232
    /* init the bluetooth world */
5233
    for (i = 0; i < nb_bt_opts; i++)
5234
        if (bt_parse(bt_opts[i]))
5235
            exit(1);
5236

    
5237
    /* init the memory */
5238
    if (ram_size == 0)
5239
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5240

    
5241
#ifdef CONFIG_KQEMU
5242
    /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5243
       guest ram allocation.  It needs to go away.  */
5244
    if (kqemu_allowed) {
5245
        kqemu_phys_ram_size = ram_size + VGA_RAM_SIZE + 4 * 1024 * 1024;
5246
        kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5247
        if (!kqemu_phys_ram_base) {
5248
            fprintf(stderr, "Could not allocate physical memory\n");
5249
            exit(1);
5250
        }
5251
    }
5252
#endif
5253

    
5254
    /* init the dynamic translator */
5255
    cpu_exec_init_all(tb_size * 1024 * 1024);
5256

    
5257
    bdrv_init();
5258
    dma_helper_init();
5259

    
5260
    /* we always create the cdrom drive, even if no disk is there */
5261

    
5262
    if (nb_drives_opt < MAX_DRIVES)
5263
        drive_add(NULL, CDROM_ALIAS);
5264

    
5265
    /* we always create at least one floppy */
5266

    
5267
    if (nb_drives_opt < MAX_DRIVES)
5268
        drive_add(NULL, FD_ALIAS, 0);
5269

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

    
5272
    if (nb_drives_opt < MAX_DRIVES)
5273
        drive_add(NULL, SD_ALIAS);
5274

    
5275
    /* open the virtual block devices */
5276

    
5277
    for(i = 0; i < nb_drives_opt; i++)
5278
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5279
            exit(1);
5280

    
5281
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5282
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5283

    
5284
#ifndef _WIN32
5285
    /* must be after terminal init, SDL library changes signal handlers */
5286
    termsig_setup();
5287
#endif
5288

    
5289
    /* Maintain compatibility with multiple stdio monitors */
5290
    if (!strcmp(monitor_device,"stdio")) {
5291
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5292
            const char *devname = serial_devices[i];
5293
            if (devname && !strcmp(devname,"mon:stdio")) {
5294
                monitor_device = NULL;
5295
                break;
5296
            } else if (devname && !strcmp(devname,"stdio")) {
5297
                monitor_device = NULL;
5298
                serial_devices[i] = "mon:stdio";
5299
                break;
5300
            }
5301
        }
5302
    }
5303

    
5304
    if (nb_numa_nodes > 0) {
5305
        int i;
5306

    
5307
        if (nb_numa_nodes > smp_cpus) {
5308
            nb_numa_nodes = smp_cpus;
5309
        }
5310

    
5311
        /* If no memory size if given for any node, assume the default case
5312
         * and distribute the available memory equally across all nodes
5313
         */
5314
        for (i = 0; i < nb_numa_nodes; i++) {
5315
            if (node_mem[i] != 0)
5316
                break;
5317
        }
5318
        if (i == nb_numa_nodes) {
5319
            uint64_t usedmem = 0;
5320

    
5321
            /* On Linux, the each node's border has to be 8MB aligned,
5322
             * the final node gets the rest.
5323
             */
5324
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5325
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5326
                usedmem += node_mem[i];
5327
            }
5328
            node_mem[i] = ram_size - usedmem;
5329
        }
5330

    
5331
        for (i = 0; i < nb_numa_nodes; i++) {
5332
            if (node_cpumask[i] != 0)
5333
                break;
5334
        }
5335
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5336
         * must cope with this anyway, because there are BIOSes out there in
5337
         * real machines which also use this scheme.
5338
         */
5339
        if (i == nb_numa_nodes) {
5340
            for (i = 0; i < smp_cpus; i++) {
5341
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5342
            }
5343
        }
5344
    }
5345

    
5346
    if (kvm_enabled()) {
5347
        int ret;
5348

    
5349
        ret = kvm_init(smp_cpus);
5350
        if (ret < 0) {
5351
            fprintf(stderr, "failed to initialize KVM\n");
5352
            exit(1);
5353
        }
5354
    }
5355

    
5356
    if (monitor_device) {
5357
        monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5358
        if (!monitor_hd) {
5359
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5360
            exit(1);
5361
        }
5362
    }
5363

    
5364
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5365
        const char *devname = serial_devices[i];
5366
        if (devname && strcmp(devname, "none")) {
5367
            char label[32];
5368
            snprintf(label, sizeof(label), "serial%d", i);
5369
            serial_hds[i] = qemu_chr_open(label, devname, NULL);
5370
            if (!serial_hds[i]) {
5371
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
5372
                        devname);
5373
                exit(1);
5374
            }
5375
        }
5376
    }
5377

    
5378
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5379
        const char *devname = parallel_devices[i];
5380
        if (devname && strcmp(devname, "none")) {
5381
            char label[32];
5382
            snprintf(label, sizeof(label), "parallel%d", i);
5383
            parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5384
            if (!parallel_hds[i]) {
5385
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5386
                        devname);
5387
                exit(1);
5388
            }
5389
        }
5390
    }
5391

    
5392
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5393
        const char *devname = virtio_consoles[i];
5394
        if (devname && strcmp(devname, "none")) {
5395
            char label[32];
5396
            snprintf(label, sizeof(label), "virtcon%d", i);
5397
            virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5398
            if (!virtcon_hds[i]) {
5399
                fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5400
                        devname);
5401
                exit(1);
5402
            }
5403
        }
5404
    }
5405

    
5406
    machine->init(ram_size, vga_ram_size, boot_devices,
5407
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5408

    
5409

    
5410
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5411
        for (i = 0; i < nb_numa_nodes; i++) {
5412
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5413
                env->numa_node = i;
5414
            }
5415
        }
5416
    }
5417

    
5418
    current_machine = machine;
5419

    
5420
    /* Set KVM's vcpu state to qemu's initial CPUState. */
5421
    if (kvm_enabled()) {
5422
        int ret;
5423

    
5424
        ret = kvm_sync_vcpus();
5425
        if (ret < 0) {
5426
            fprintf(stderr, "failed to initialize vcpus\n");
5427
            exit(1);
5428
        }
5429
    }
5430

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

    
5441
    if (!display_state)
5442
        dumb_display_init();
5443
    /* just use the first displaystate for the moment */
5444
    ds = display_state;
5445
    /* terminal init */
5446
    if (nographic) {
5447
        if (curses) {
5448
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5449
            exit(1);
5450
        }
5451
    } else { 
5452
#if defined(CONFIG_CURSES)
5453
            if (curses) {
5454
                /* At the moment curses cannot be used with other displays */
5455
                curses_display_init(ds, full_screen);
5456
            } else
5457
#endif
5458
            {
5459
                if (vnc_display != NULL) {
5460
                    vnc_display_init(ds);
5461
                    if (vnc_display_open(ds, vnc_display) < 0)
5462
                        exit(1);
5463
                }
5464
#if defined(CONFIG_SDL)
5465
                if (sdl || !vnc_display)
5466
                    sdl_display_init(ds, full_screen, no_frame);
5467
#elif defined(CONFIG_COCOA)
5468
                if (sdl || !vnc_display)
5469
                    cocoa_display_init(ds, full_screen);
5470
#endif
5471
            }
5472
    }
5473
    dpy_resize(ds);
5474

    
5475
    dcl = ds->listeners;
5476
    while (dcl != NULL) {
5477
        if (dcl->dpy_refresh != NULL) {
5478
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5479
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5480
        }
5481
        dcl = dcl->next;
5482
    }
5483

    
5484
    if (nographic || (vnc_display && !sdl)) {
5485
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5486
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5487
    }
5488

    
5489
    text_consoles_set_display(display_state);
5490
    qemu_chr_initial_reset();
5491

    
5492
    if (monitor_device && monitor_hd)
5493
        monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5494

    
5495
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5496
        const char *devname = serial_devices[i];
5497
        if (devname && strcmp(devname, "none")) {
5498
            char label[32];
5499
            snprintf(label, sizeof(label), "serial%d", i);
5500
            if (strstart(devname, "vc", 0))
5501
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5502
        }
5503
    }
5504

    
5505
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5506
        const char *devname = parallel_devices[i];
5507
        if (devname && strcmp(devname, "none")) {
5508
            char label[32];
5509
            snprintf(label, sizeof(label), "parallel%d", i);
5510
            if (strstart(devname, "vc", 0))
5511
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5512
        }
5513
    }
5514

    
5515
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5516
        const char *devname = virtio_consoles[i];
5517
        if (virtcon_hds[i] && devname) {
5518
            char label[32];
5519
            snprintf(label, sizeof(label), "virtcon%d", i);
5520
            if (strstart(devname, "vc", 0))
5521
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5522
        }
5523
    }
5524

    
5525
#ifdef CONFIG_GDBSTUB
5526
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5527
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5528
                gdbstub_dev);
5529
        exit(1);
5530
    }
5531
#endif
5532

    
5533
    if (loadvm)
5534
        do_loadvm(cur_mon, loadvm);
5535

    
5536
    if (incoming) {
5537
        autostart = 0; /* fixme how to deal with -daemonize */
5538
        qemu_start_incoming_migration(incoming);
5539
    }
5540

    
5541
    if (autostart)
5542
        vm_start();
5543

    
5544
#ifndef _WIN32
5545
    if (daemonize) {
5546
        uint8_t status = 0;
5547
        ssize_t len;
5548

    
5549
    again1:
5550
        len = write(fds[1], &status, 1);
5551
        if (len == -1 && (errno == EINTR))
5552
            goto again1;
5553

    
5554
        if (len != 1)
5555
            exit(1);
5556

    
5557
        chdir("/");
5558
        TFR(fd = open("/dev/null", O_RDWR));
5559
        if (fd == -1)
5560
            exit(1);
5561
    }
5562

    
5563
    if (run_as) {
5564
        pwd = getpwnam(run_as);
5565
        if (!pwd) {
5566
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5567
            exit(1);
5568
        }
5569
    }
5570

    
5571
    if (chroot_dir) {
5572
        if (chroot(chroot_dir) < 0) {
5573
            fprintf(stderr, "chroot failed\n");
5574
            exit(1);
5575
        }
5576
        chdir("/");
5577
    }
5578

    
5579
    if (run_as) {
5580
        if (setgid(pwd->pw_gid) < 0) {
5581
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5582
            exit(1);
5583
        }
5584
        if (setuid(pwd->pw_uid) < 0) {
5585
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5586
            exit(1);
5587
        }
5588
        if (setuid(0) != -1) {
5589
            fprintf(stderr, "Dropping privileges failed\n");
5590
            exit(1);
5591
        }
5592
    }
5593

    
5594
    if (daemonize) {
5595
        dup2(fd, 0);
5596
        dup2(fd, 1);
5597
        dup2(fd, 2);
5598

    
5599
        close(fd);
5600
    }
5601
#endif
5602

    
5603
    main_loop();
5604
    quit_timers();
5605
    net_cleanup();
5606

    
5607
    return 0;
5608
}