Statistics
| Branch: | Revision:

root / vl.c @ 3b6304f7

History | View | Annotate | Download (129.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 CONFIG_BSD etc. */
33
#include "config-host.h"
34

    
35
#ifndef _WIN32
36
#include <libgen.h>
37
#include <pwd.h>
38
#include <sys/times.h>
39
#include <sys/wait.h>
40
#include <termios.h>
41
#include <sys/mman.h>
42
#include <sys/ioctl.h>
43
#include <sys/resource.h>
44
#include <sys/socket.h>
45
#include <netinet/in.h>
46
#include <net/if.h>
47
#include <arpa/inet.h>
48
#include <dirent.h>
49
#include <netdb.h>
50
#include <sys/select.h>
51
#ifdef CONFIG_BSD
52
#include <sys/stat.h>
53
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54
#include <libutil.h>
55
#else
56
#include <util.h>
57
#endif
58
#else
59
#ifdef __linux__
60
#include <pty.h>
61
#include <malloc.h>
62
#include <sys/prctl.h>
63

    
64
#include <linux/ppdev.h>
65
#include <linux/parport.h>
66
#endif
67
#ifdef __sun__
68
#include <sys/stat.h>
69
#include <sys/ethernet.h>
70
#include <sys/sockio.h>
71
#include <netinet/arp.h>
72
#include <netinet/in.h>
73
#include <netinet/in_systm.h>
74
#include <netinet/ip.h>
75
#include <netinet/ip_icmp.h> // must come after ip.h
76
#include <netinet/udp.h>
77
#include <netinet/tcp.h>
78
#include <net/if.h>
79
#include <syslog.h>
80
#include <stropts.h>
81
/* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
82
   discussion about Solaris header problems */
83
extern int madvise(caddr_t, size_t, int);
84
#endif
85
#endif
86
#endif
87

    
88
#if defined(__OpenBSD__)
89
#include <util.h>
90
#endif
91

    
92
#if defined(CONFIG_VDE)
93
#include <libvdeplug.h>
94
#endif
95

    
96
#ifdef _WIN32
97
#include <windows.h>
98
#endif
99

    
100
#ifdef CONFIG_SDL
101
#if defined(__APPLE__) || defined(main)
102
#include <SDL.h>
103
int qemu_main(int argc, char **argv, char **envp);
104
int main(int argc, char **argv)
105
{
106
    return qemu_main(argc, argv, NULL);
107
}
108
#undef main
109
#define main qemu_main
110
#endif
111
#endif /* CONFIG_SDL */
112

    
113
#ifdef CONFIG_COCOA
114
#undef main
115
#define main qemu_main
116
#endif /* CONFIG_COCOA */
117

    
118
#include "hw/hw.h"
119
#include "hw/boards.h"
120
#include "hw/usb.h"
121
#include "hw/pcmcia.h"
122
#include "hw/pc.h"
123
#include "hw/audiodev.h"
124
#include "hw/isa.h"
125
#include "hw/baum.h"
126
#include "hw/bt.h"
127
#include "hw/watchdog.h"
128
#include "hw/smbios.h"
129
#include "hw/xen.h"
130
#include "hw/qdev.h"
131
#include "hw/loader.h"
132
#include "bt-host.h"
133
#include "net.h"
134
#include "net/slirp.h"
135
#include "monitor.h"
136
#include "console.h"
137
#include "sysemu.h"
138
#include "gdbstub.h"
139
#include "qemu-timer.h"
140
#include "qemu-char.h"
141
#include "cache-utils.h"
142
#include "block.h"
143
#include "block_int.h"
144
#include "block-migration.h"
145
#include "dma.h"
146
#include "audio/audio.h"
147
#include "migration.h"
148
#include "kvm.h"
149
#include "balloon.h"
150
#include "qemu-option.h"
151
#include "qemu-config.h"
152
#include "qemu-objects.h"
153
#include "notify.h"
154

    
155
#include "disas.h"
156

    
157
#include "exec-all.h"
158

    
159
#include "qemu_socket.h"
160

    
161
#include "slirp/libslirp.h"
162

    
163
#include "qemu-queue.h"
164

    
165
//#define DEBUG_NET
166
//#define DEBUG_SLIRP
167

    
168
#define DEFAULT_RAM_SIZE 128
169

    
170
#define MAX_VIRTIO_CONSOLES 1
171

    
172
static const char *data_dir;
173
const char *bios_name = NULL;
174
/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
175
   to store the VM snapshots */
176
struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
177
struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
178
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
179
DisplayType display_type = DT_DEFAULT;
180
const char* keyboard_layout = NULL;
181
ram_addr_t ram_size;
182
const char *mem_path = NULL;
183
#ifdef MAP_POPULATE
184
int mem_prealloc = 0; /* force preallocation of physical target memory */
185
#endif
186
int nb_nics;
187
NICInfo nd_table[MAX_NICS];
188
int vm_running;
189
int autostart;
190
static int rtc_utc = 1;
191
static int rtc_date_offset = -1; /* -1 means no change */
192
QEMUClock *rtc_clock;
193
int vga_interface_type = VGA_NONE;
194
#ifdef TARGET_SPARC
195
int graphic_width = 1024;
196
int graphic_height = 768;
197
int graphic_depth = 8;
198
#else
199
int graphic_width = 800;
200
int graphic_height = 600;
201
int graphic_depth = 15;
202
#endif
203
static int full_screen = 0;
204
#ifdef CONFIG_SDL
205
static int no_frame = 0;
206
#endif
207
int no_quit = 0;
208
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
209
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
210
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
211
#ifdef TARGET_I386
212
int win2k_install_hack = 0;
213
int rtc_td_hack = 0;
214
#endif
215
int usb_enabled = 0;
216
int singlestep = 0;
217
int smp_cpus = 1;
218
int max_cpus = 0;
219
int smp_cores = 1;
220
int smp_threads = 1;
221
const char *vnc_display;
222
int acpi_enabled = 1;
223
int no_hpet = 0;
224
int fd_bootchk = 1;
225
int no_reboot = 0;
226
int no_shutdown = 0;
227
int cursor_hide = 1;
228
int graphic_rotate = 0;
229
uint8_t irq0override = 1;
230
#ifndef _WIN32
231
int daemonize = 0;
232
#endif
233
const char *watchdog;
234
const char *option_rom[MAX_OPTION_ROMS];
235
int nb_option_roms;
236
int semihosting_enabled = 0;
237
#ifdef TARGET_ARM
238
int old_param = 0;
239
#endif
240
const char *qemu_name;
241
int alt_grab = 0;
242
int ctrl_grab = 0;
243
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
244
unsigned int nb_prom_envs = 0;
245
const char *prom_envs[MAX_PROM_ENVS];
246
#endif
247
int boot_menu;
248

    
249
int nb_numa_nodes;
250
uint64_t node_mem[MAX_NODES];
251
uint64_t node_cpumask[MAX_NODES];
252

    
253
static CPUState *cur_cpu;
254
static CPUState *next_cpu;
255
static QEMUTimer *nographic_timer;
256

    
257
uint8_t qemu_uuid[16];
258

    
259
static QEMUBootSetHandler *boot_set_handler;
260
static void *boot_set_opaque;
261

    
262
#ifdef SIGRTMIN
263
#define SIG_IPI (SIGRTMIN+4)
264
#else
265
#define SIG_IPI SIGUSR1
266
#endif
267

    
268
static int default_serial = 1;
269
static int default_parallel = 1;
270
static int default_virtcon = 1;
271
static int default_monitor = 1;
272
static int default_vga = 1;
273
static int default_floppy = 1;
274
static int default_cdrom = 1;
275
static int default_sdcard = 1;
276

    
277
static struct {
278
    const char *driver;
279
    int *flag;
280
} default_list[] = {
281
    { .driver = "isa-serial",           .flag = &default_serial    },
282
    { .driver = "isa-parallel",         .flag = &default_parallel  },
283
    { .driver = "isa-fdc",              .flag = &default_floppy    },
284
    { .driver = "ide-drive",            .flag = &default_cdrom     },
285
    { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
286
    { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
287
    { .driver = "virtio-serial",        .flag = &default_virtcon   },
288
    { .driver = "VGA",                  .flag = &default_vga       },
289
    { .driver = "cirrus-vga",           .flag = &default_vga       },
290
    { .driver = "vmware-svga",          .flag = &default_vga       },
291
};
292

    
293
static int default_driver_check(QemuOpts *opts, void *opaque)
294
{
295
    const char *driver = qemu_opt_get(opts, "driver");
296
    int i;
297

    
298
    if (!driver)
299
        return 0;
300
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
301
        if (strcmp(default_list[i].driver, driver) != 0)
302
            continue;
303
        *(default_list[i].flag) = 0;
304
    }
305
    return 0;
306
}
307

    
308
/***********************************************************/
309
/* x86 ISA bus support */
310

    
311
target_phys_addr_t isa_mem_base = 0;
312
PicState2 *isa_pic;
313

    
314
/***********************************************************/
315
void hw_error(const char *fmt, ...)
316
{
317
    va_list ap;
318
    CPUState *env;
319

    
320
    va_start(ap, fmt);
321
    fprintf(stderr, "qemu: hardware error: ");
322
    vfprintf(stderr, fmt, ap);
323
    fprintf(stderr, "\n");
324
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
325
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
326
#ifdef TARGET_I386
327
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
328
#else
329
        cpu_dump_state(env, stderr, fprintf, 0);
330
#endif
331
    }
332
    va_end(ap);
333
    abort();
334
}
335

    
336
static void set_proc_name(const char *s)
337
{
338
#if defined(__linux__) && defined(PR_SET_NAME)
339
    char name[16];
340
    if (!s)
341
        return;
342
    name[sizeof(name) - 1] = 0;
343
    strncpy(name, s, sizeof(name));
344
    /* Could rewrite argv[0] too, but that's a bit more complicated.
345
       This simple way is enough for `top'. */
346
    prctl(PR_SET_NAME, name);
347
#endif            
348
}
349
 
350
/***************/
351
/* ballooning */
352

    
353
static QEMUBalloonEvent *qemu_balloon_event;
354
void *qemu_balloon_event_opaque;
355

    
356
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
357
{
358
    qemu_balloon_event = func;
359
    qemu_balloon_event_opaque = opaque;
360
}
361

    
362
int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
363
{
364
    if (qemu_balloon_event) {
365
        qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
366
        return 1;
367
    } else {
368
        return 0;
369
    }
370
}
371

    
372
int qemu_balloon_status(MonitorCompletion cb, void *opaque)
373
{
374
    if (qemu_balloon_event) {
375
        qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
376
        return 1;
377
    } else {
378
        return 0;
379
    }
380
}
381

    
382

    
383
/***********************************************************/
384
/* real time host monotonic timer */
385

    
386
/* compute with 96 bit intermediate result: (a*b)/c */
387
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
388
{
389
    union {
390
        uint64_t ll;
391
        struct {
392
#ifdef HOST_WORDS_BIGENDIAN
393
            uint32_t high, low;
394
#else
395
            uint32_t low, high;
396
#endif
397
        } l;
398
    } u, res;
399
    uint64_t rl, rh;
400

    
401
    u.ll = a;
402
    rl = (uint64_t)u.l.low * (uint64_t)b;
403
    rh = (uint64_t)u.l.high * (uint64_t)b;
404
    rh += (rl >> 32);
405
    res.l.high = rh / c;
406
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
407
    return res.ll;
408
}
409

    
410
/***********************************************************/
411
/* host time/date access */
412
void qemu_get_timedate(struct tm *tm, int offset)
413
{
414
    time_t ti;
415
    struct tm *ret;
416

    
417
    time(&ti);
418
    ti += offset;
419
    if (rtc_date_offset == -1) {
420
        if (rtc_utc)
421
            ret = gmtime(&ti);
422
        else
423
            ret = localtime(&ti);
424
    } else {
425
        ti -= rtc_date_offset;
426
        ret = gmtime(&ti);
427
    }
428

    
429
    memcpy(tm, ret, sizeof(struct tm));
430
}
431

    
432
int qemu_timedate_diff(struct tm *tm)
433
{
434
    time_t seconds;
435

    
436
    if (rtc_date_offset == -1)
437
        if (rtc_utc)
438
            seconds = mktimegm(tm);
439
        else
440
            seconds = mktime(tm);
441
    else
442
        seconds = mktimegm(tm) + rtc_date_offset;
443

    
444
    return seconds - time(NULL);
445
}
446

    
447
void rtc_change_mon_event(struct tm *tm)
448
{
449
    QObject *data;
450

    
451
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
452
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
453
    qobject_decref(data);
454
}
455

    
456
static void configure_rtc_date_offset(const char *startdate, int legacy)
457
{
458
    time_t rtc_start_date;
459
    struct tm tm;
460

    
461
    if (!strcmp(startdate, "now") && legacy) {
462
        rtc_date_offset = -1;
463
    } else {
464
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
465
                   &tm.tm_year,
466
                   &tm.tm_mon,
467
                   &tm.tm_mday,
468
                   &tm.tm_hour,
469
                   &tm.tm_min,
470
                   &tm.tm_sec) == 6) {
471
            /* OK */
472
        } else if (sscanf(startdate, "%d-%d-%d",
473
                          &tm.tm_year,
474
                          &tm.tm_mon,
475
                          &tm.tm_mday) == 3) {
476
            tm.tm_hour = 0;
477
            tm.tm_min = 0;
478
            tm.tm_sec = 0;
479
        } else {
480
            goto date_fail;
481
        }
482
        tm.tm_year -= 1900;
483
        tm.tm_mon--;
484
        rtc_start_date = mktimegm(&tm);
485
        if (rtc_start_date == -1) {
486
        date_fail:
487
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
488
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
489
            exit(1);
490
        }
491
        rtc_date_offset = time(NULL) - rtc_start_date;
492
    }
493
}
494

    
495
static void configure_rtc(QemuOpts *opts)
496
{
497
    const char *value;
498

    
499
    value = qemu_opt_get(opts, "base");
500
    if (value) {
501
        if (!strcmp(value, "utc")) {
502
            rtc_utc = 1;
503
        } else if (!strcmp(value, "localtime")) {
504
            rtc_utc = 0;
505
        } else {
506
            configure_rtc_date_offset(value, 0);
507
        }
508
    }
509
    value = qemu_opt_get(opts, "clock");
510
    if (value) {
511
        if (!strcmp(value, "host")) {
512
            rtc_clock = host_clock;
513
        } else if (!strcmp(value, "vm")) {
514
            rtc_clock = vm_clock;
515
        } else {
516
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
517
            exit(1);
518
        }
519
    }
520
#ifdef CONFIG_TARGET_I386
521
    value = qemu_opt_get(opts, "driftfix");
522
    if (value) {
523
        if (!strcmp(buf, "slew")) {
524
            rtc_td_hack = 1;
525
        } else if (!strcmp(buf, "none")) {
526
            rtc_td_hack = 0;
527
        } else {
528
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
529
            exit(1);
530
        }
531
    }
532
#endif
533
}
534

    
535
#ifdef _WIN32
536
static void socket_cleanup(void)
537
{
538
    WSACleanup();
539
}
540

    
541
static int socket_init(void)
542
{
543
    WSADATA Data;
544
    int ret, err;
545

    
546
    ret = WSAStartup(MAKEWORD(2,2), &Data);
547
    if (ret != 0) {
548
        err = WSAGetLastError();
549
        fprintf(stderr, "WSAStartup: %d\n", err);
550
        return -1;
551
    }
552
    atexit(socket_cleanup);
553
    return 0;
554
}
555
#endif
556

    
557
/*********************/
558
/* Exit notifiers    */
559
/*********************/
560

    
561
static NotifierList exit_notifiers = NOTIFIER_LIST_INITIALIZER(exit_notifiers);
562

    
563
void exit_notifier_add(Notifier *notifier)
564
{
565
    notifier_list_add(&exit_notifiers, notifier);
566
}
567

    
568
void exit_notifier_remove(Notifier *notifier)
569
{
570
    notifier_list_remove(&exit_notifiers, notifier);
571
}
572

    
573
static void exit_notifier_notify(void)
574
{
575
    notifier_list_notify(&exit_notifiers);
576
}
577

    
578
static void exit_notifier_init(void)
579
{
580
    atexit(exit_notifier_notify);
581
}
582

    
583
/***********************************************************/
584
/* Bluetooth support */
585
static int nb_hcis;
586
static int cur_hci;
587
static struct HCIInfo *hci_table[MAX_NICS];
588

    
589
static struct bt_vlan_s {
590
    struct bt_scatternet_s net;
591
    int id;
592
    struct bt_vlan_s *next;
593
} *first_bt_vlan;
594

    
595
/* find or alloc a new bluetooth "VLAN" */
596
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
597
{
598
    struct bt_vlan_s **pvlan, *vlan;
599
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
600
        if (vlan->id == id)
601
            return &vlan->net;
602
    }
603
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
604
    vlan->id = id;
605
    pvlan = &first_bt_vlan;
606
    while (*pvlan != NULL)
607
        pvlan = &(*pvlan)->next;
608
    *pvlan = vlan;
609
    return &vlan->net;
610
}
611

    
612
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
613
{
614
}
615

    
616
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
617
{
618
    return -ENOTSUP;
619
}
620

    
621
static struct HCIInfo null_hci = {
622
    .cmd_send = null_hci_send,
623
    .sco_send = null_hci_send,
624
    .acl_send = null_hci_send,
625
    .bdaddr_set = null_hci_addr_set,
626
};
627

    
628
struct HCIInfo *qemu_next_hci(void)
629
{
630
    if (cur_hci == nb_hcis)
631
        return &null_hci;
632

    
633
    return hci_table[cur_hci++];
634
}
635

    
636
static struct HCIInfo *hci_init(const char *str)
637
{
638
    char *endp;
639
    struct bt_scatternet_s *vlan = 0;
640

    
641
    if (!strcmp(str, "null"))
642
        /* null */
643
        return &null_hci;
644
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
645
        /* host[:hciN] */
646
        return bt_host_hci(str[4] ? str + 5 : "hci0");
647
    else if (!strncmp(str, "hci", 3)) {
648
        /* hci[,vlan=n] */
649
        if (str[3]) {
650
            if (!strncmp(str + 3, ",vlan=", 6)) {
651
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
652
                if (*endp)
653
                    vlan = 0;
654
            }
655
        } else
656
            vlan = qemu_find_bt_vlan(0);
657
        if (vlan)
658
           return bt_new_hci(vlan);
659
    }
660

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

    
663
    return 0;
664
}
665

    
666
static int bt_hci_parse(const char *str)
667
{
668
    struct HCIInfo *hci;
669
    bdaddr_t bdaddr;
670

    
671
    if (nb_hcis >= MAX_NICS) {
672
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
673
        return -1;
674
    }
675

    
676
    hci = hci_init(str);
677
    if (!hci)
678
        return -1;
679

    
680
    bdaddr.b[0] = 0x52;
681
    bdaddr.b[1] = 0x54;
682
    bdaddr.b[2] = 0x00;
683
    bdaddr.b[3] = 0x12;
684
    bdaddr.b[4] = 0x34;
685
    bdaddr.b[5] = 0x56 + nb_hcis;
686
    hci->bdaddr_set(hci, bdaddr.b);
687

    
688
    hci_table[nb_hcis++] = hci;
689

    
690
    return 0;
691
}
692

    
693
static void bt_vhci_add(int vlan_id)
694
{
695
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
696

    
697
    if (!vlan->slave)
698
        fprintf(stderr, "qemu: warning: adding a VHCI to "
699
                        "an empty scatternet %i\n", vlan_id);
700

    
701
    bt_vhci_init(bt_new_hci(vlan));
702
}
703

    
704
static struct bt_device_s *bt_device_add(const char *opt)
705
{
706
    struct bt_scatternet_s *vlan;
707
    int vlan_id = 0;
708
    char *endp = strstr(opt, ",vlan=");
709
    int len = (endp ? endp - opt : strlen(opt)) + 1;
710
    char devname[10];
711

    
712
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
713

    
714
    if (endp) {
715
        vlan_id = strtol(endp + 6, &endp, 0);
716
        if (*endp) {
717
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
718
            return 0;
719
        }
720
    }
721

    
722
    vlan = qemu_find_bt_vlan(vlan_id);
723

    
724
    if (!vlan->slave)
725
        fprintf(stderr, "qemu: warning: adding a slave device to "
726
                        "an empty scatternet %i\n", vlan_id);
727

    
728
    if (!strcmp(devname, "keyboard"))
729
        return bt_keyboard_init(vlan);
730

    
731
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
732
    return 0;
733
}
734

    
735
static int bt_parse(const char *opt)
736
{
737
    const char *endp, *p;
738
    int vlan;
739

    
740
    if (strstart(opt, "hci", &endp)) {
741
        if (!*endp || *endp == ',') {
742
            if (*endp)
743
                if (!strstart(endp, ",vlan=", 0))
744
                    opt = endp + 1;
745

    
746
            return bt_hci_parse(opt);
747
       }
748
    } else if (strstart(opt, "vhci", &endp)) {
749
        if (!*endp || *endp == ',') {
750
            if (*endp) {
751
                if (strstart(endp, ",vlan=", &p)) {
752
                    vlan = strtol(p, (char **) &endp, 0);
753
                    if (*endp) {
754
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
755
                        return 1;
756
                    }
757
                } else {
758
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
759
                    return 1;
760
                }
761
            } else
762
                vlan = 0;
763

    
764
            bt_vhci_add(vlan);
765
            return 0;
766
        }
767
    } else if (strstart(opt, "device:", &endp))
768
        return !bt_device_add(endp);
769

    
770
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
771
    return 1;
772
}
773

    
774
/***********************************************************/
775
/* QEMU Block devices */
776

    
777
#define HD_ALIAS "index=%d,media=disk"
778
#define CDROM_ALIAS "index=2,media=cdrom"
779
#define FD_ALIAS "index=%d,if=floppy"
780
#define PFLASH_ALIAS "if=pflash"
781
#define MTD_ALIAS "if=mtd"
782
#define SD_ALIAS "index=0,if=sd"
783

    
784
QemuOpts *drive_add(const char *file, const char *fmt, ...)
785
{
786
    va_list ap;
787
    char optstr[1024];
788
    QemuOpts *opts;
789

    
790
    va_start(ap, fmt);
791
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
792
    va_end(ap);
793

    
794
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
795
    if (!opts) {
796
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
797
                __FUNCTION__, optstr);
798
        return NULL;
799
    }
800
    if (file)
801
        qemu_opt_set(opts, "file", file);
802
    return opts;
803
}
804

    
805
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
806
{
807
    DriveInfo *dinfo;
808

    
809
    /* seek interface, bus and unit */
810

    
811
    QTAILQ_FOREACH(dinfo, &drives, next) {
812
        if (dinfo->type == type &&
813
            dinfo->bus == bus &&
814
            dinfo->unit == unit)
815
            return dinfo;
816
    }
817

    
818
    return NULL;
819
}
820

    
821
DriveInfo *drive_get_by_id(const char *id)
822
{
823
    DriveInfo *dinfo;
824

    
825
    QTAILQ_FOREACH(dinfo, &drives, next) {
826
        if (strcmp(id, dinfo->id))
827
            continue;
828
        return dinfo;
829
    }
830
    return NULL;
831
}
832

    
833
int drive_get_max_bus(BlockInterfaceType type)
834
{
835
    int max_bus;
836
    DriveInfo *dinfo;
837

    
838
    max_bus = -1;
839
    QTAILQ_FOREACH(dinfo, &drives, next) {
840
        if(dinfo->type == type &&
841
           dinfo->bus > max_bus)
842
            max_bus = dinfo->bus;
843
    }
844
    return max_bus;
845
}
846

    
847
const char *drive_get_serial(BlockDriverState *bdrv)
848
{
849
    DriveInfo *dinfo;
850

    
851
    QTAILQ_FOREACH(dinfo, &drives, next) {
852
        if (dinfo->bdrv == bdrv)
853
            return dinfo->serial;
854
    }
855

    
856
    return "\0";
857
}
858

    
859
BlockInterfaceErrorAction drive_get_on_error(
860
    BlockDriverState *bdrv, int is_read)
861
{
862
    DriveInfo *dinfo;
863

    
864
    QTAILQ_FOREACH(dinfo, &drives, next) {
865
        if (dinfo->bdrv == bdrv)
866
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
867
    }
868

    
869
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
870
}
871

    
872
static void bdrv_format_print(void *opaque, const char *name)
873
{
874
    fprintf(stderr, " %s", name);
875
}
876

    
877
void drive_uninit(DriveInfo *dinfo)
878
{
879
    qemu_opts_del(dinfo->opts);
880
    bdrv_delete(dinfo->bdrv);
881
    QTAILQ_REMOVE(&drives, dinfo, next);
882
    qemu_free(dinfo);
883
}
884

    
885
static int parse_block_error_action(const char *buf, int is_read)
886
{
887
    if (!strcmp(buf, "ignore")) {
888
        return BLOCK_ERR_IGNORE;
889
    } else if (!is_read && !strcmp(buf, "enospc")) {
890
        return BLOCK_ERR_STOP_ENOSPC;
891
    } else if (!strcmp(buf, "stop")) {
892
        return BLOCK_ERR_STOP_ANY;
893
    } else if (!strcmp(buf, "report")) {
894
        return BLOCK_ERR_REPORT;
895
    } else {
896
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
897
            buf, is_read ? "read" : "write");
898
        return -1;
899
    }
900
}
901

    
902
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
903
                      int *fatal_error)
904
{
905
    const char *buf;
906
    const char *file = NULL;
907
    char devname[128];
908
    const char *serial;
909
    const char *mediastr = "";
910
    BlockInterfaceType type;
911
    enum { MEDIA_DISK, MEDIA_CDROM } media;
912
    int bus_id, unit_id;
913
    int cyls, heads, secs, translation;
914
    BlockDriver *drv = NULL;
915
    QEMUMachine *machine = opaque;
916
    int max_devs;
917
    int index;
918
    int cache;
919
    int aio = 0;
920
    int ro = 0;
921
    int bdrv_flags;
922
    int on_read_error, on_write_error;
923
    const char *devaddr;
924
    DriveInfo *dinfo;
925
    int snapshot = 0;
926

    
927
    *fatal_error = 1;
928

    
929
    translation = BIOS_ATA_TRANSLATION_AUTO;
930
    cache = 1;
931

    
932
    if (machine && machine->use_scsi) {
933
        type = IF_SCSI;
934
        max_devs = MAX_SCSI_DEVS;
935
        pstrcpy(devname, sizeof(devname), "scsi");
936
    } else {
937
        type = IF_IDE;
938
        max_devs = MAX_IDE_DEVS;
939
        pstrcpy(devname, sizeof(devname), "ide");
940
    }
941
    media = MEDIA_DISK;
942

    
943
    /* extract parameters */
944
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
945
    unit_id = qemu_opt_get_number(opts, "unit", -1);
946
    index   = qemu_opt_get_number(opts, "index", -1);
947

    
948
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
949
    heads = qemu_opt_get_number(opts, "heads", 0);
950
    secs  = qemu_opt_get_number(opts, "secs", 0);
951

    
952
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
953
    ro = qemu_opt_get_bool(opts, "readonly", 0);
954

    
955
    file = qemu_opt_get(opts, "file");
956
    serial = qemu_opt_get(opts, "serial");
957

    
958
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
959
        pstrcpy(devname, sizeof(devname), buf);
960
        if (!strcmp(buf, "ide")) {
961
            type = IF_IDE;
962
            max_devs = MAX_IDE_DEVS;
963
        } else if (!strcmp(buf, "scsi")) {
964
            type = IF_SCSI;
965
            max_devs = MAX_SCSI_DEVS;
966
        } else if (!strcmp(buf, "floppy")) {
967
            type = IF_FLOPPY;
968
            max_devs = 0;
969
        } else if (!strcmp(buf, "pflash")) {
970
            type = IF_PFLASH;
971
            max_devs = 0;
972
        } else if (!strcmp(buf, "mtd")) {
973
            type = IF_MTD;
974
            max_devs = 0;
975
        } else if (!strcmp(buf, "sd")) {
976
            type = IF_SD;
977
            max_devs = 0;
978
        } else if (!strcmp(buf, "virtio")) {
979
            type = IF_VIRTIO;
980
            max_devs = 0;
981
        } else if (!strcmp(buf, "xen")) {
982
            type = IF_XEN;
983
            max_devs = 0;
984
        } else if (!strcmp(buf, "none")) {
985
            type = IF_NONE;
986
            max_devs = 0;
987
        } else {
988
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
989
            return NULL;
990
        }
991
    }
992

    
993
    if (cyls || heads || secs) {
994
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
995
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
996
            return NULL;
997
        }
998
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
999
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1000
            return NULL;
1001
        }
1002
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
1003
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1004
            return NULL;
1005
        }
1006
    }
1007

    
1008
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1009
        if (!cyls) {
1010
            fprintf(stderr,
1011
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
1012
                    buf);
1013
            return NULL;
1014
        }
1015
        if (!strcmp(buf, "none"))
1016
            translation = BIOS_ATA_TRANSLATION_NONE;
1017
        else if (!strcmp(buf, "lba"))
1018
            translation = BIOS_ATA_TRANSLATION_LBA;
1019
        else if (!strcmp(buf, "auto"))
1020
            translation = BIOS_ATA_TRANSLATION_AUTO;
1021
        else {
1022
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
1023
            return NULL;
1024
        }
1025
    }
1026

    
1027
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1028
        if (!strcmp(buf, "disk")) {
1029
            media = MEDIA_DISK;
1030
        } else if (!strcmp(buf, "cdrom")) {
1031
            if (cyls || secs || heads) {
1032
                fprintf(stderr,
1033
                        "qemu: '%s' invalid physical CHS format\n", buf);
1034
                return NULL;
1035
            }
1036
            media = MEDIA_CDROM;
1037
        } else {
1038
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1039
            return NULL;
1040
        }
1041
    }
1042

    
1043
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1044
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1045
            cache = 0;
1046
        else if (!strcmp(buf, "writethrough"))
1047
            cache = 1;
1048
        else if (!strcmp(buf, "writeback"))
1049
            cache = 2;
1050
        else {
1051
           fprintf(stderr, "qemu: invalid cache option\n");
1052
           return NULL;
1053
        }
1054
    }
1055

    
1056
#ifdef CONFIG_LINUX_AIO
1057
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1058
        if (!strcmp(buf, "threads"))
1059
            aio = 0;
1060
        else if (!strcmp(buf, "native"))
1061
            aio = 1;
1062
        else {
1063
           fprintf(stderr, "qemu: invalid aio option\n");
1064
           return NULL;
1065
        }
1066
    }
1067
#endif
1068

    
1069
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1070
       if (strcmp(buf, "?") == 0) {
1071
            fprintf(stderr, "qemu: Supported formats:");
1072
            bdrv_iterate_format(bdrv_format_print, NULL);
1073
            fprintf(stderr, "\n");
1074
            return NULL;
1075
        }
1076
        drv = bdrv_find_whitelisted_format(buf);
1077
        if (!drv) {
1078
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1079
            return NULL;
1080
        }
1081
    }
1082

    
1083
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
1084
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1085
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1086
            fprintf(stderr, "werror is no supported by this format\n");
1087
            return NULL;
1088
        }
1089

    
1090
        on_write_error = parse_block_error_action(buf, 0);
1091
        if (on_write_error < 0) {
1092
            return NULL;
1093
        }
1094
    }
1095

    
1096
    on_read_error = BLOCK_ERR_REPORT;
1097
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1098
        if (type != IF_IDE && type != IF_VIRTIO) {
1099
            fprintf(stderr, "rerror is no supported by this format\n");
1100
            return NULL;
1101
        }
1102

    
1103
        on_read_error = parse_block_error_action(buf, 1);
1104
        if (on_read_error < 0) {
1105
            return NULL;
1106
        }
1107
    }
1108

    
1109
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1110
        if (type != IF_VIRTIO) {
1111
            fprintf(stderr, "addr is not supported\n");
1112
            return NULL;
1113
        }
1114
    }
1115

    
1116
    /* compute bus and unit according index */
1117

    
1118
    if (index != -1) {
1119
        if (bus_id != 0 || unit_id != -1) {
1120
            fprintf(stderr,
1121
                    "qemu: index cannot be used with bus and unit\n");
1122
            return NULL;
1123
        }
1124
        if (max_devs == 0)
1125
        {
1126
            unit_id = index;
1127
            bus_id = 0;
1128
        } else {
1129
            unit_id = index % max_devs;
1130
            bus_id = index / max_devs;
1131
        }
1132
    }
1133

    
1134
    /* if user doesn't specify a unit_id,
1135
     * try to find the first free
1136
     */
1137

    
1138
    if (unit_id == -1) {
1139
       unit_id = 0;
1140
       while (drive_get(type, bus_id, unit_id) != NULL) {
1141
           unit_id++;
1142
           if (max_devs && unit_id >= max_devs) {
1143
               unit_id -= max_devs;
1144
               bus_id++;
1145
           }
1146
       }
1147
    }
1148

    
1149
    /* check unit id */
1150

    
1151
    if (max_devs && unit_id >= max_devs) {
1152
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1153
                unit_id, max_devs - 1);
1154
        return NULL;
1155
    }
1156

    
1157
    /*
1158
     * ignore multiple definitions
1159
     */
1160

    
1161
    if (drive_get(type, bus_id, unit_id) != NULL) {
1162
        *fatal_error = 0;
1163
        return NULL;
1164
    }
1165

    
1166
    /* init */
1167

    
1168
    dinfo = qemu_mallocz(sizeof(*dinfo));
1169
    if ((buf = qemu_opts_id(opts)) != NULL) {
1170
        dinfo->id = qemu_strdup(buf);
1171
    } else {
1172
        /* no id supplied -> create one */
1173
        dinfo->id = qemu_mallocz(32);
1174
        if (type == IF_IDE || type == IF_SCSI)
1175
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1176
        if (max_devs)
1177
            snprintf(dinfo->id, 32, "%s%i%s%i",
1178
                     devname, bus_id, mediastr, unit_id);
1179
        else
1180
            snprintf(dinfo->id, 32, "%s%s%i",
1181
                     devname, mediastr, unit_id);
1182
    }
1183
    dinfo->bdrv = bdrv_new(dinfo->id);
1184
    dinfo->devaddr = devaddr;
1185
    dinfo->type = type;
1186
    dinfo->bus = bus_id;
1187
    dinfo->unit = unit_id;
1188
    dinfo->on_read_error = on_read_error;
1189
    dinfo->on_write_error = on_write_error;
1190
    dinfo->opts = opts;
1191
    if (serial)
1192
        strncpy(dinfo->serial, serial, sizeof(serial));
1193
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1194

    
1195
    switch(type) {
1196
    case IF_IDE:
1197
    case IF_SCSI:
1198
    case IF_XEN:
1199
    case IF_NONE:
1200
        switch(media) {
1201
        case MEDIA_DISK:
1202
            if (cyls != 0) {
1203
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1204
                bdrv_set_translation_hint(dinfo->bdrv, translation);
1205
            }
1206
            break;
1207
        case MEDIA_CDROM:
1208
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1209
            break;
1210
        }
1211
        break;
1212
    case IF_SD:
1213
        /* FIXME: This isn't really a floppy, but it's a reasonable
1214
           approximation.  */
1215
    case IF_FLOPPY:
1216
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1217
        break;
1218
    case IF_PFLASH:
1219
    case IF_MTD:
1220
        break;
1221
    case IF_VIRTIO:
1222
        /* add virtio block device */
1223
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1224
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
1225
        qemu_opt_set(opts, "drive", dinfo->id);
1226
        if (devaddr)
1227
            qemu_opt_set(opts, "addr", devaddr);
1228
        break;
1229
    case IF_COUNT:
1230
        abort();
1231
    }
1232
    if (!file) {
1233
        *fatal_error = 0;
1234
        return NULL;
1235
    }
1236
    bdrv_flags = 0;
1237
    if (snapshot) {
1238
        bdrv_flags |= BDRV_O_SNAPSHOT;
1239
        cache = 2; /* always use write-back with snapshot */
1240
    }
1241
    if (cache == 0) /* no caching */
1242
        bdrv_flags |= BDRV_O_NOCACHE;
1243
    else if (cache == 2) /* write-back */
1244
        bdrv_flags |= BDRV_O_CACHE_WB;
1245

    
1246
    if (aio == 1) {
1247
        bdrv_flags |= BDRV_O_NATIVE_AIO;
1248
    } else {
1249
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1250
    }
1251

    
1252
    if (ro == 1) {
1253
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1254
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1255
            return NULL;
1256
        }
1257
    }
1258
    /* 
1259
     * cdrom is read-only. Set it now, after above interface checking
1260
     * since readonly attribute not explicitly required, so no error.
1261
     */
1262
    if (media == MEDIA_CDROM) {
1263
        ro = 1;
1264
    }
1265
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1266

    
1267
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1268
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1269
                        file, strerror(errno));
1270
        return NULL;
1271
    }
1272

    
1273
    if (bdrv_key_required(dinfo->bdrv))
1274
        autostart = 0;
1275
    *fatal_error = 0;
1276
    return dinfo;
1277
}
1278

    
1279
static int drive_init_func(QemuOpts *opts, void *opaque)
1280
{
1281
    QEMUMachine *machine = opaque;
1282
    int fatal_error = 0;
1283

    
1284
    if (drive_init(opts, machine, &fatal_error) == NULL) {
1285
        if (fatal_error)
1286
            return 1;
1287
    }
1288
    return 0;
1289
}
1290

    
1291
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1292
{
1293
    if (NULL == qemu_opt_get(opts, "snapshot")) {
1294
        qemu_opt_set(opts, "snapshot", "on");
1295
    }
1296
    return 0;
1297
}
1298

    
1299
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1300
{
1301
    boot_set_handler = func;
1302
    boot_set_opaque = opaque;
1303
}
1304

    
1305
int qemu_boot_set(const char *boot_devices)
1306
{
1307
    if (!boot_set_handler) {
1308
        return -EINVAL;
1309
    }
1310
    return boot_set_handler(boot_set_opaque, boot_devices);
1311
}
1312

    
1313
static int parse_bootdevices(char *devices)
1314
{
1315
    /* We just do some generic consistency checks */
1316
    const char *p;
1317
    int bitmap = 0;
1318

    
1319
    for (p = devices; *p != '\0'; p++) {
1320
        /* Allowed boot devices are:
1321
         * a-b: floppy disk drives
1322
         * c-f: IDE disk drives
1323
         * g-m: machine implementation dependant drives
1324
         * n-p: network devices
1325
         * It's up to each machine implementation to check if the given boot
1326
         * devices match the actual hardware implementation and firmware
1327
         * features.
1328
         */
1329
        if (*p < 'a' || *p > 'p') {
1330
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
1331
            exit(1);
1332
        }
1333
        if (bitmap & (1 << (*p - 'a'))) {
1334
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1335
            exit(1);
1336
        }
1337
        bitmap |= 1 << (*p - 'a');
1338
    }
1339
    return bitmap;
1340
}
1341

    
1342
static void restore_boot_devices(void *opaque)
1343
{
1344
    char *standard_boot_devices = opaque;
1345

    
1346
    qemu_boot_set(standard_boot_devices);
1347

    
1348
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1349
    qemu_free(standard_boot_devices);
1350
}
1351

    
1352
static void numa_add(const char *optarg)
1353
{
1354
    char option[128];
1355
    char *endptr;
1356
    unsigned long long value, endvalue;
1357
    int nodenr;
1358

    
1359
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
1360
    if (!strcmp(option, "node")) {
1361
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1362
            nodenr = nb_numa_nodes;
1363
        } else {
1364
            nodenr = strtoull(option, NULL, 10);
1365
        }
1366

    
1367
        if (get_param_value(option, 128, "mem", optarg) == 0) {
1368
            node_mem[nodenr] = 0;
1369
        } else {
1370
            value = strtoull(option, &endptr, 0);
1371
            switch (*endptr) {
1372
            case 0: case 'M': case 'm':
1373
                value <<= 20;
1374
                break;
1375
            case 'G': case 'g':
1376
                value <<= 30;
1377
                break;
1378
            }
1379
            node_mem[nodenr] = value;
1380
        }
1381
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
1382
            node_cpumask[nodenr] = 0;
1383
        } else {
1384
            value = strtoull(option, &endptr, 10);
1385
            if (value >= 64) {
1386
                value = 63;
1387
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1388
            } else {
1389
                if (*endptr == '-') {
1390
                    endvalue = strtoull(endptr+1, &endptr, 10);
1391
                    if (endvalue >= 63) {
1392
                        endvalue = 62;
1393
                        fprintf(stderr,
1394
                            "only 63 CPUs in NUMA mode supported.\n");
1395
                    }
1396
                    value = (2ULL << endvalue) - (1ULL << value);
1397
                } else {
1398
                    value = 1ULL << value;
1399
                }
1400
            }
1401
            node_cpumask[nodenr] = value;
1402
        }
1403
        nb_numa_nodes++;
1404
    }
1405
    return;
1406
}
1407

    
1408
static void smp_parse(const char *optarg)
1409
{
1410
    int smp, sockets = 0, threads = 0, cores = 0;
1411
    char *endptr;
1412
    char option[128];
1413

    
1414
    smp = strtoul(optarg, &endptr, 10);
1415
    if (endptr != optarg) {
1416
        if (*endptr == ',') {
1417
            endptr++;
1418
        }
1419
    }
1420
    if (get_param_value(option, 128, "sockets", endptr) != 0)
1421
        sockets = strtoull(option, NULL, 10);
1422
    if (get_param_value(option, 128, "cores", endptr) != 0)
1423
        cores = strtoull(option, NULL, 10);
1424
    if (get_param_value(option, 128, "threads", endptr) != 0)
1425
        threads = strtoull(option, NULL, 10);
1426
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1427
        max_cpus = strtoull(option, NULL, 10);
1428

    
1429
    /* compute missing values, prefer sockets over cores over threads */
1430
    if (smp == 0 || sockets == 0) {
1431
        sockets = sockets > 0 ? sockets : 1;
1432
        cores = cores > 0 ? cores : 1;
1433
        threads = threads > 0 ? threads : 1;
1434
        if (smp == 0) {
1435
            smp = cores * threads * sockets;
1436
        }
1437
    } else {
1438
        if (cores == 0) {
1439
            threads = threads > 0 ? threads : 1;
1440
            cores = smp / (sockets * threads);
1441
        } else {
1442
            if (sockets) {
1443
                threads = smp / (cores * sockets);
1444
            }
1445
        }
1446
    }
1447
    smp_cpus = smp;
1448
    smp_cores = cores > 0 ? cores : 1;
1449
    smp_threads = threads > 0 ? threads : 1;
1450
    if (max_cpus == 0)
1451
        max_cpus = smp_cpus;
1452
}
1453

    
1454
/***********************************************************/
1455
/* USB devices */
1456

    
1457
static int usb_device_add(const char *devname, int is_hotplug)
1458
{
1459
    const char *p;
1460
    USBDevice *dev = NULL;
1461

    
1462
    if (!usb_enabled)
1463
        return -1;
1464

    
1465
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1466
    dev = usbdevice_create(devname);
1467
    if (dev)
1468
        goto done;
1469

    
1470
    /* the other ones */
1471
    if (strstart(devname, "host:", &p)) {
1472
        dev = usb_host_device_open(p);
1473
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1474
        dev = usb_bt_init(devname[2] ? hci_init(p) :
1475
                        bt_new_hci(qemu_find_bt_vlan(0)));
1476
    } else {
1477
        return -1;
1478
    }
1479
    if (!dev)
1480
        return -1;
1481

    
1482
done:
1483
    return 0;
1484
}
1485

    
1486
static int usb_device_del(const char *devname)
1487
{
1488
    int bus_num, addr;
1489
    const char *p;
1490

    
1491
    if (strstart(devname, "host:", &p))
1492
        return usb_host_device_close(p);
1493

    
1494
    if (!usb_enabled)
1495
        return -1;
1496

    
1497
    p = strchr(devname, '.');
1498
    if (!p)
1499
        return -1;
1500
    bus_num = strtoul(devname, NULL, 0);
1501
    addr = strtoul(p + 1, NULL, 0);
1502

    
1503
    return usb_device_delete_addr(bus_num, addr);
1504
}
1505

    
1506
static int usb_parse(const char *cmdline)
1507
{
1508
    int r;
1509
    r = usb_device_add(cmdline, 0);
1510
    if (r < 0) {
1511
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1512
    }
1513
    return r;
1514
}
1515

    
1516
void do_usb_add(Monitor *mon, const QDict *qdict)
1517
{
1518
    const char *devname = qdict_get_str(qdict, "devname");
1519
    if (usb_device_add(devname, 1) < 0) {
1520
        error_report("could not add USB device '%s'", devname);
1521
    }
1522
}
1523

    
1524
void do_usb_del(Monitor *mon, const QDict *qdict)
1525
{
1526
    const char *devname = qdict_get_str(qdict, "devname");
1527
    if (usb_device_del(devname) < 0) {
1528
        error_report("could not delete USB device '%s'", devname);
1529
    }
1530
}
1531

    
1532
/***********************************************************/
1533
/* PCMCIA/Cardbus */
1534

    
1535
static struct pcmcia_socket_entry_s {
1536
    PCMCIASocket *socket;
1537
    struct pcmcia_socket_entry_s *next;
1538
} *pcmcia_sockets = 0;
1539

    
1540
void pcmcia_socket_register(PCMCIASocket *socket)
1541
{
1542
    struct pcmcia_socket_entry_s *entry;
1543

    
1544
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1545
    entry->socket = socket;
1546
    entry->next = pcmcia_sockets;
1547
    pcmcia_sockets = entry;
1548
}
1549

    
1550
void pcmcia_socket_unregister(PCMCIASocket *socket)
1551
{
1552
    struct pcmcia_socket_entry_s *entry, **ptr;
1553

    
1554
    ptr = &pcmcia_sockets;
1555
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1556
        if (entry->socket == socket) {
1557
            *ptr = entry->next;
1558
            qemu_free(entry);
1559
        }
1560
}
1561

    
1562
void pcmcia_info(Monitor *mon)
1563
{
1564
    struct pcmcia_socket_entry_s *iter;
1565

    
1566
    if (!pcmcia_sockets)
1567
        monitor_printf(mon, "No PCMCIA sockets\n");
1568

    
1569
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1570
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1571
                       iter->socket->attached ? iter->socket->card_string :
1572
                       "Empty");
1573
}
1574

    
1575
/***********************************************************/
1576
/* I/O handling */
1577

    
1578
typedef struct IOHandlerRecord {
1579
    int fd;
1580
    IOCanReadHandler *fd_read_poll;
1581
    IOHandler *fd_read;
1582
    IOHandler *fd_write;
1583
    int deleted;
1584
    void *opaque;
1585
    /* temporary data */
1586
    struct pollfd *ufd;
1587
    QLIST_ENTRY(IOHandlerRecord) next;
1588
} IOHandlerRecord;
1589

    
1590
static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1591
    QLIST_HEAD_INITIALIZER(io_handlers);
1592

    
1593

    
1594
/* XXX: fd_read_poll should be suppressed, but an API change is
1595
   necessary in the character devices to suppress fd_can_read(). */
1596
int qemu_set_fd_handler2(int fd,
1597
                         IOCanReadHandler *fd_read_poll,
1598
                         IOHandler *fd_read,
1599
                         IOHandler *fd_write,
1600
                         void *opaque)
1601
{
1602
    IOHandlerRecord *ioh;
1603

    
1604
    if (!fd_read && !fd_write) {
1605
        QLIST_FOREACH(ioh, &io_handlers, next) {
1606
            if (ioh->fd == fd) {
1607
                ioh->deleted = 1;
1608
                break;
1609
            }
1610
        }
1611
    } else {
1612
        QLIST_FOREACH(ioh, &io_handlers, next) {
1613
            if (ioh->fd == fd)
1614
                goto found;
1615
        }
1616
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1617
        QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1618
    found:
1619
        ioh->fd = fd;
1620
        ioh->fd_read_poll = fd_read_poll;
1621
        ioh->fd_read = fd_read;
1622
        ioh->fd_write = fd_write;
1623
        ioh->opaque = opaque;
1624
        ioh->deleted = 0;
1625
    }
1626
    return 0;
1627
}
1628

    
1629
int qemu_set_fd_handler(int fd,
1630
                        IOHandler *fd_read,
1631
                        IOHandler *fd_write,
1632
                        void *opaque)
1633
{
1634
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1635
}
1636

    
1637
#ifdef _WIN32
1638
/***********************************************************/
1639
/* Polling handling */
1640

    
1641
typedef struct PollingEntry {
1642
    PollingFunc *func;
1643
    void *opaque;
1644
    struct PollingEntry *next;
1645
} PollingEntry;
1646

    
1647
static PollingEntry *first_polling_entry;
1648

    
1649
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1650
{
1651
    PollingEntry **ppe, *pe;
1652
    pe = qemu_mallocz(sizeof(PollingEntry));
1653
    pe->func = func;
1654
    pe->opaque = opaque;
1655
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1656
    *ppe = pe;
1657
    return 0;
1658
}
1659

    
1660
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1661
{
1662
    PollingEntry **ppe, *pe;
1663
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1664
        pe = *ppe;
1665
        if (pe->func == func && pe->opaque == opaque) {
1666
            *ppe = pe->next;
1667
            qemu_free(pe);
1668
            break;
1669
        }
1670
    }
1671
}
1672

    
1673
/***********************************************************/
1674
/* Wait objects support */
1675
typedef struct WaitObjects {
1676
    int num;
1677
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1678
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1679
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1680
} WaitObjects;
1681

    
1682
static WaitObjects wait_objects = {0};
1683

    
1684
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1685
{
1686
    WaitObjects *w = &wait_objects;
1687

    
1688
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
1689
        return -1;
1690
    w->events[w->num] = handle;
1691
    w->func[w->num] = func;
1692
    w->opaque[w->num] = opaque;
1693
    w->num++;
1694
    return 0;
1695
}
1696

    
1697
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1698
{
1699
    int i, found;
1700
    WaitObjects *w = &wait_objects;
1701

    
1702
    found = 0;
1703
    for (i = 0; i < w->num; i++) {
1704
        if (w->events[i] == handle)
1705
            found = 1;
1706
        if (found) {
1707
            w->events[i] = w->events[i + 1];
1708
            w->func[i] = w->func[i + 1];
1709
            w->opaque[i] = w->opaque[i + 1];
1710
        }
1711
    }
1712
    if (found)
1713
        w->num--;
1714
}
1715
#endif
1716

    
1717
/***********************************************************/
1718
/* ram save/restore */
1719

    
1720
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
1721
#define RAM_SAVE_FLAG_COMPRESS        0x02
1722
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
1723
#define RAM_SAVE_FLAG_PAGE        0x08
1724
#define RAM_SAVE_FLAG_EOS        0x10
1725

    
1726
static int is_dup_page(uint8_t *page, uint8_t ch)
1727
{
1728
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1729
    uint32_t *array = (uint32_t *)page;
1730
    int i;
1731

    
1732
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1733
        if (array[i] != val)
1734
            return 0;
1735
    }
1736

    
1737
    return 1;
1738
}
1739

    
1740
static int ram_save_block(QEMUFile *f)
1741
{
1742
    static ram_addr_t current_addr = 0;
1743
    ram_addr_t saved_addr = current_addr;
1744
    ram_addr_t addr = 0;
1745
    int found = 0;
1746

    
1747
    while (addr < last_ram_offset) {
1748
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1749
            uint8_t *p;
1750

    
1751
            cpu_physical_memory_reset_dirty(current_addr,
1752
                                            current_addr + TARGET_PAGE_SIZE,
1753
                                            MIGRATION_DIRTY_FLAG);
1754

    
1755
            p = qemu_get_ram_ptr(current_addr);
1756

    
1757
            if (is_dup_page(p, *p)) {
1758
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1759
                qemu_put_byte(f, *p);
1760
            } else {
1761
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1762
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1763
            }
1764

    
1765
            found = 1;
1766
            break;
1767
        }
1768
        addr += TARGET_PAGE_SIZE;
1769
        current_addr = (saved_addr + addr) % last_ram_offset;
1770
    }
1771

    
1772
    return found;
1773
}
1774

    
1775
static uint64_t bytes_transferred;
1776

    
1777
static ram_addr_t ram_save_remaining(void)
1778
{
1779
    ram_addr_t addr;
1780
    ram_addr_t count = 0;
1781

    
1782
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1783
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1784
            count++;
1785
    }
1786

    
1787
    return count;
1788
}
1789

    
1790
uint64_t ram_bytes_remaining(void)
1791
{
1792
    return ram_save_remaining() * TARGET_PAGE_SIZE;
1793
}
1794

    
1795
uint64_t ram_bytes_transferred(void)
1796
{
1797
    return bytes_transferred;
1798
}
1799

    
1800
uint64_t ram_bytes_total(void)
1801
{
1802
    return last_ram_offset;
1803
}
1804

    
1805
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1806
{
1807
    ram_addr_t addr;
1808
    uint64_t bytes_transferred_last;
1809
    double bwidth = 0;
1810
    uint64_t expected_time = 0;
1811

    
1812
    if (stage < 0) {
1813
        cpu_physical_memory_set_dirty_tracking(0);
1814
        return 0;
1815
    }
1816

    
1817
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1818
        qemu_file_set_error(f);
1819
        return 0;
1820
    }
1821

    
1822
    if (stage == 1) {
1823
        bytes_transferred = 0;
1824

    
1825
        /* Make sure all dirty bits are set */
1826
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1827
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1828
                cpu_physical_memory_set_dirty(addr);
1829
        }
1830

    
1831
        /* Enable dirty memory tracking */
1832
        cpu_physical_memory_set_dirty_tracking(1);
1833

    
1834
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1835
    }
1836

    
1837
    bytes_transferred_last = bytes_transferred;
1838
    bwidth = qemu_get_clock_ns(rt_clock);
1839

    
1840
    while (!qemu_file_rate_limit(f)) {
1841
        int ret;
1842

    
1843
        ret = ram_save_block(f);
1844
        bytes_transferred += ret * TARGET_PAGE_SIZE;
1845
        if (ret == 0) /* no more blocks */
1846
            break;
1847
    }
1848

    
1849
    bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1850
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1851

    
1852
    /* if we haven't transferred anything this round, force expected_time to a
1853
     * a very high value, but without crashing */
1854
    if (bwidth == 0)
1855
        bwidth = 0.000001;
1856

    
1857
    /* try transferring iterative blocks of memory */
1858
    if (stage == 3) {
1859
        /* flush all remaining blocks regardless of rate limiting */
1860
        while (ram_save_block(f) != 0) {
1861
            bytes_transferred += TARGET_PAGE_SIZE;
1862
        }
1863
        cpu_physical_memory_set_dirty_tracking(0);
1864
    }
1865

    
1866
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1867

    
1868
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1869

    
1870
    return (stage == 2) && (expected_time <= migrate_max_downtime());
1871
}
1872

    
1873
static int ram_load(QEMUFile *f, void *opaque, int version_id)
1874
{
1875
    ram_addr_t addr;
1876
    int flags;
1877

    
1878
    if (version_id != 3)
1879
        return -EINVAL;
1880

    
1881
    do {
1882
        addr = qemu_get_be64(f);
1883

    
1884
        flags = addr & ~TARGET_PAGE_MASK;
1885
        addr &= TARGET_PAGE_MASK;
1886

    
1887
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1888
            if (addr != last_ram_offset)
1889
                return -EINVAL;
1890
        }
1891

    
1892
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
1893
            uint8_t ch = qemu_get_byte(f);
1894
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1895
#ifndef _WIN32
1896
            if (ch == 0 &&
1897
                (!kvm_enabled() || kvm_has_sync_mmu())) {
1898
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1899
            }
1900
#endif
1901
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
1902
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1903
        }
1904
        if (qemu_file_has_error(f)) {
1905
            return -EIO;
1906
        }
1907
    } while (!(flags & RAM_SAVE_FLAG_EOS));
1908

    
1909
    return 0;
1910
}
1911

    
1912
void qemu_service_io(void)
1913
{
1914
    qemu_notify_event();
1915
}
1916

    
1917
/***********************************************************/
1918
/* machine registration */
1919

    
1920
static QEMUMachine *first_machine = NULL;
1921
QEMUMachine *current_machine = NULL;
1922

    
1923
int qemu_register_machine(QEMUMachine *m)
1924
{
1925
    QEMUMachine **pm;
1926
    pm = &first_machine;
1927
    while (*pm != NULL)
1928
        pm = &(*pm)->next;
1929
    m->next = NULL;
1930
    *pm = m;
1931
    return 0;
1932
}
1933

    
1934
static QEMUMachine *find_machine(const char *name)
1935
{
1936
    QEMUMachine *m;
1937

    
1938
    for(m = first_machine; m != NULL; m = m->next) {
1939
        if (!strcmp(m->name, name))
1940
            return m;
1941
        if (m->alias && !strcmp(m->alias, name))
1942
            return m;
1943
    }
1944
    return NULL;
1945
}
1946

    
1947
static QEMUMachine *find_default_machine(void)
1948
{
1949
    QEMUMachine *m;
1950

    
1951
    for(m = first_machine; m != NULL; m = m->next) {
1952
        if (m->is_default) {
1953
            return m;
1954
        }
1955
    }
1956
    return NULL;
1957
}
1958

    
1959
/***********************************************************/
1960
/* main execution loop */
1961

    
1962
static void gui_update(void *opaque)
1963
{
1964
    uint64_t interval = GUI_REFRESH_INTERVAL;
1965
    DisplayState *ds = opaque;
1966
    DisplayChangeListener *dcl = ds->listeners;
1967

    
1968
    qemu_flush_coalesced_mmio_buffer();
1969
    dpy_refresh(ds);
1970

    
1971
    while (dcl != NULL) {
1972
        if (dcl->gui_timer_interval &&
1973
            dcl->gui_timer_interval < interval)
1974
            interval = dcl->gui_timer_interval;
1975
        dcl = dcl->next;
1976
    }
1977
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1978
}
1979

    
1980
static void nographic_update(void *opaque)
1981
{
1982
    uint64_t interval = GUI_REFRESH_INTERVAL;
1983

    
1984
    qemu_flush_coalesced_mmio_buffer();
1985
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1986
}
1987

    
1988
void cpu_synchronize_all_states(void)
1989
{
1990
    CPUState *cpu;
1991

    
1992
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1993
        cpu_synchronize_state(cpu);
1994
    }
1995
}
1996

    
1997
void cpu_synchronize_all_post_reset(void)
1998
{
1999
    CPUState *cpu;
2000

    
2001
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2002
        cpu_synchronize_post_reset(cpu);
2003
    }
2004
}
2005

    
2006
void cpu_synchronize_all_post_init(void)
2007
{
2008
    CPUState *cpu;
2009

    
2010
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
2011
        cpu_synchronize_post_init(cpu);
2012
    }
2013
}
2014

    
2015
struct vm_change_state_entry {
2016
    VMChangeStateHandler *cb;
2017
    void *opaque;
2018
    QLIST_ENTRY (vm_change_state_entry) entries;
2019
};
2020

    
2021
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
2022

    
2023
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2024
                                                     void *opaque)
2025
{
2026
    VMChangeStateEntry *e;
2027

    
2028
    e = qemu_mallocz(sizeof (*e));
2029

    
2030
    e->cb = cb;
2031
    e->opaque = opaque;
2032
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2033
    return e;
2034
}
2035

    
2036
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2037
{
2038
    QLIST_REMOVE (e, entries);
2039
    qemu_free (e);
2040
}
2041

    
2042
static void vm_state_notify(int running, int reason)
2043
{
2044
    VMChangeStateEntry *e;
2045

    
2046
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2047
        e->cb(e->opaque, running, reason);
2048
    }
2049
}
2050

    
2051
static void resume_all_vcpus(void);
2052
static void pause_all_vcpus(void);
2053

    
2054
void vm_start(void)
2055
{
2056
    if (!vm_running) {
2057
        cpu_enable_ticks();
2058
        vm_running = 1;
2059
        vm_state_notify(1, 0);
2060
        resume_all_vcpus();
2061
    }
2062
}
2063

    
2064
/* reset/shutdown handler */
2065

    
2066
typedef struct QEMUResetEntry {
2067
    QTAILQ_ENTRY(QEMUResetEntry) entry;
2068
    QEMUResetHandler *func;
2069
    void *opaque;
2070
} QEMUResetEntry;
2071

    
2072
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2073
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
2074
static int reset_requested;
2075
static int shutdown_requested;
2076
static int powerdown_requested;
2077
static int debug_requested;
2078
static int vmstop_requested;
2079

    
2080
int qemu_shutdown_requested(void)
2081
{
2082
    int r = shutdown_requested;
2083
    shutdown_requested = 0;
2084
    return r;
2085
}
2086

    
2087
int qemu_reset_requested(void)
2088
{
2089
    int r = reset_requested;
2090
    reset_requested = 0;
2091
    return r;
2092
}
2093

    
2094
int qemu_powerdown_requested(void)
2095
{
2096
    int r = powerdown_requested;
2097
    powerdown_requested = 0;
2098
    return r;
2099
}
2100

    
2101
static int qemu_debug_requested(void)
2102
{
2103
    int r = debug_requested;
2104
    debug_requested = 0;
2105
    return r;
2106
}
2107

    
2108
static int qemu_vmstop_requested(void)
2109
{
2110
    int r = vmstop_requested;
2111
    vmstop_requested = 0;
2112
    return r;
2113
}
2114

    
2115
static void do_vm_stop(int reason)
2116
{
2117
    if (vm_running) {
2118
        cpu_disable_ticks();
2119
        vm_running = 0;
2120
        pause_all_vcpus();
2121
        vm_state_notify(0, reason);
2122
        monitor_protocol_event(QEVENT_STOP, NULL);
2123
    }
2124
}
2125

    
2126
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2127
{
2128
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2129

    
2130
    re->func = func;
2131
    re->opaque = opaque;
2132
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2133
}
2134

    
2135
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2136
{
2137
    QEMUResetEntry *re;
2138

    
2139
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
2140
        if (re->func == func && re->opaque == opaque) {
2141
            QTAILQ_REMOVE(&reset_handlers, re, entry);
2142
            qemu_free(re);
2143
            return;
2144
        }
2145
    }
2146
}
2147

    
2148
void qemu_system_reset(void)
2149
{
2150
    QEMUResetEntry *re, *nre;
2151

    
2152
    /* reset all devices */
2153
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2154
        re->func(re->opaque);
2155
    }
2156
    monitor_protocol_event(QEVENT_RESET, NULL);
2157
    cpu_synchronize_all_post_reset();
2158
}
2159

    
2160
void qemu_system_reset_request(void)
2161
{
2162
    if (no_reboot) {
2163
        shutdown_requested = 1;
2164
    } else {
2165
        reset_requested = 1;
2166
    }
2167
    qemu_notify_event();
2168
}
2169

    
2170
void qemu_system_shutdown_request(void)
2171
{
2172
    shutdown_requested = 1;
2173
    qemu_notify_event();
2174
}
2175

    
2176
void qemu_system_powerdown_request(void)
2177
{
2178
    powerdown_requested = 1;
2179
    qemu_notify_event();
2180
}
2181

    
2182
static int cpu_can_run(CPUState *env)
2183
{
2184
    if (env->stop)
2185
        return 0;
2186
    if (env->stopped)
2187
        return 0;
2188
    if (!vm_running)
2189
        return 0;
2190
    return 1;
2191
}
2192

    
2193
static int cpu_has_work(CPUState *env)
2194
{
2195
    if (env->stop)
2196
        return 1;
2197
    if (env->stopped)
2198
        return 0;
2199
    if (!env->halted)
2200
        return 1;
2201
    if (qemu_cpu_has_work(env))
2202
        return 1;
2203
    return 0;
2204
}
2205

    
2206
static int tcg_has_work(void)
2207
{
2208
    CPUState *env;
2209

    
2210
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2211
        if (cpu_has_work(env))
2212
            return 1;
2213
    return 0;
2214
}
2215

    
2216
#ifndef _WIN32
2217
static int io_thread_fd = -1;
2218

    
2219
static void qemu_event_increment(void)
2220
{
2221
    /* Write 8 bytes to be compatible with eventfd.  */
2222
    static uint64_t val = 1;
2223
    ssize_t ret;
2224

    
2225
    if (io_thread_fd == -1)
2226
        return;
2227

    
2228
    do {
2229
        ret = write(io_thread_fd, &val, sizeof(val));
2230
    } while (ret < 0 && errno == EINTR);
2231

    
2232
    /* EAGAIN is fine, a read must be pending.  */
2233
    if (ret < 0 && errno != EAGAIN) {
2234
        fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2235
                strerror(errno));
2236
        exit (1);
2237
    }
2238
}
2239

    
2240
static void qemu_event_read(void *opaque)
2241
{
2242
    int fd = (unsigned long)opaque;
2243
    ssize_t len;
2244
    char buffer[512];
2245

    
2246
    /* Drain the notify pipe.  For eventfd, only 8 bytes will be read.  */
2247
    do {
2248
        len = read(fd, buffer, sizeof(buffer));
2249
    } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2250
}
2251

    
2252
static int qemu_event_init(void)
2253
{
2254
    int err;
2255
    int fds[2];
2256

    
2257
    err = qemu_eventfd(fds);
2258
    if (err == -1)
2259
        return -errno;
2260

    
2261
    err = fcntl_setfl(fds[0], O_NONBLOCK);
2262
    if (err < 0)
2263
        goto fail;
2264

    
2265
    err = fcntl_setfl(fds[1], O_NONBLOCK);
2266
    if (err < 0)
2267
        goto fail;
2268

    
2269
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2270
                         (void *)(unsigned long)fds[0]);
2271

    
2272
    io_thread_fd = fds[1];
2273
    return 0;
2274

    
2275
fail:
2276
    close(fds[0]);
2277
    close(fds[1]);
2278
    return err;
2279
}
2280
#else
2281
HANDLE qemu_event_handle;
2282

    
2283
static void dummy_event_handler(void *opaque)
2284
{
2285
}
2286

    
2287
static int qemu_event_init(void)
2288
{
2289
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2290
    if (!qemu_event_handle) {
2291
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2292
        return -1;
2293
    }
2294
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2295
    return 0;
2296
}
2297

    
2298
static void qemu_event_increment(void)
2299
{
2300
    if (!SetEvent(qemu_event_handle)) {
2301
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2302
                GetLastError());
2303
        exit (1);
2304
    }
2305
}
2306
#endif
2307

    
2308
#ifndef CONFIG_IOTHREAD
2309
static int qemu_init_main_loop(void)
2310
{
2311
    return qemu_event_init();
2312
}
2313

    
2314
void qemu_init_vcpu(void *_env)
2315
{
2316
    CPUState *env = _env;
2317

    
2318
    env->nr_cores = smp_cores;
2319
    env->nr_threads = smp_threads;
2320
    if (kvm_enabled())
2321
        kvm_init_vcpu(env);
2322
    return;
2323
}
2324

    
2325
int qemu_cpu_self(void *env)
2326
{
2327
    return 1;
2328
}
2329

    
2330
static void resume_all_vcpus(void)
2331
{
2332
}
2333

    
2334
static void pause_all_vcpus(void)
2335
{
2336
}
2337

    
2338
void qemu_cpu_kick(void *env)
2339
{
2340
    return;
2341
}
2342

    
2343
void qemu_notify_event(void)
2344
{
2345
    CPUState *env = cpu_single_env;
2346

    
2347
    qemu_event_increment ();
2348
    if (env) {
2349
        cpu_exit(env);
2350
    }
2351
    if (next_cpu && env != next_cpu) {
2352
        cpu_exit(next_cpu);
2353
    }
2354
}
2355

    
2356
void qemu_mutex_lock_iothread(void) {}
2357
void qemu_mutex_unlock_iothread(void) {}
2358

    
2359
void vm_stop(int reason)
2360
{
2361
    do_vm_stop(reason);
2362
}
2363

    
2364
#else /* CONFIG_IOTHREAD */
2365

    
2366
#include "qemu-thread.h"
2367

    
2368
QemuMutex qemu_global_mutex;
2369
static QemuMutex qemu_fair_mutex;
2370

    
2371
static QemuThread io_thread;
2372

    
2373
static QemuThread *tcg_cpu_thread;
2374
static QemuCond *tcg_halt_cond;
2375

    
2376
static int qemu_system_ready;
2377
/* cpu creation */
2378
static QemuCond qemu_cpu_cond;
2379
/* system init */
2380
static QemuCond qemu_system_cond;
2381
static QemuCond qemu_pause_cond;
2382

    
2383
static void tcg_block_io_signals(void);
2384
static void kvm_block_io_signals(CPUState *env);
2385
static void unblock_io_signals(void);
2386

    
2387
static int qemu_init_main_loop(void)
2388
{
2389
    int ret;
2390

    
2391
    ret = qemu_event_init();
2392
    if (ret)
2393
        return ret;
2394

    
2395
    qemu_cond_init(&qemu_pause_cond);
2396
    qemu_mutex_init(&qemu_fair_mutex);
2397
    qemu_mutex_init(&qemu_global_mutex);
2398
    qemu_mutex_lock(&qemu_global_mutex);
2399

    
2400
    unblock_io_signals();
2401
    qemu_thread_self(&io_thread);
2402

    
2403
    return 0;
2404
}
2405

    
2406
static void qemu_wait_io_event_common(CPUState *env)
2407
{
2408
    if (env->stop) {
2409
        env->stop = 0;
2410
        env->stopped = 1;
2411
        qemu_cond_signal(&qemu_pause_cond);
2412
    }
2413
}
2414

    
2415
static void qemu_wait_io_event(CPUState *env)
2416
{
2417
    while (!tcg_has_work())
2418
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2419

    
2420
    qemu_mutex_unlock(&qemu_global_mutex);
2421

    
2422
    /*
2423
     * Users of qemu_global_mutex can be starved, having no chance
2424
     * to acquire it since this path will get to it first.
2425
     * So use another lock to provide fairness.
2426
     */
2427
    qemu_mutex_lock(&qemu_fair_mutex);
2428
    qemu_mutex_unlock(&qemu_fair_mutex);
2429

    
2430
    qemu_mutex_lock(&qemu_global_mutex);
2431
    qemu_wait_io_event_common(env);
2432
}
2433

    
2434
static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2435
{
2436
    struct timespec ts;
2437
    int r, e;
2438
    siginfo_t siginfo;
2439
    sigset_t waitset;
2440

    
2441
    ts.tv_sec = timeout / 1000;
2442
    ts.tv_nsec = (timeout % 1000) * 1000000;
2443

    
2444
    sigemptyset(&waitset);
2445
    sigaddset(&waitset, SIG_IPI);
2446

    
2447
    qemu_mutex_unlock(&qemu_global_mutex);
2448
    r = sigtimedwait(&waitset, &siginfo, &ts);
2449
    e = errno;
2450
    qemu_mutex_lock(&qemu_global_mutex);
2451

    
2452
    if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2453
        fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2454
        exit(1);
2455
    }
2456
}
2457

    
2458
static void qemu_kvm_wait_io_event(CPUState *env)
2459
{
2460
    while (!cpu_has_work(env))
2461
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2462

    
2463
    qemu_kvm_eat_signal(env, 0);
2464
    qemu_wait_io_event_common(env);
2465
}
2466

    
2467
static int qemu_cpu_exec(CPUState *env);
2468

    
2469
static void *kvm_cpu_thread_fn(void *arg)
2470
{
2471
    CPUState *env = arg;
2472

    
2473
    qemu_thread_self(env->thread);
2474
    if (kvm_enabled())
2475
        kvm_init_vcpu(env);
2476

    
2477
    kvm_block_io_signals(env);
2478

    
2479
    /* signal CPU creation */
2480
    qemu_mutex_lock(&qemu_global_mutex);
2481
    env->created = 1;
2482
    qemu_cond_signal(&qemu_cpu_cond);
2483

    
2484
    /* and wait for machine initialization */
2485
    while (!qemu_system_ready)
2486
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2487

    
2488
    while (1) {
2489
        if (cpu_can_run(env))
2490
            qemu_cpu_exec(env);
2491
        qemu_kvm_wait_io_event(env);
2492
    }
2493

    
2494
    return NULL;
2495
}
2496

    
2497
static bool tcg_cpu_exec(void);
2498

    
2499
static void *tcg_cpu_thread_fn(void *arg)
2500
{
2501
    CPUState *env = arg;
2502

    
2503
    tcg_block_io_signals();
2504
    qemu_thread_self(env->thread);
2505

    
2506
    /* signal CPU creation */
2507
    qemu_mutex_lock(&qemu_global_mutex);
2508
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2509
        env->created = 1;
2510
    qemu_cond_signal(&qemu_cpu_cond);
2511

    
2512
    /* and wait for machine initialization */
2513
    while (!qemu_system_ready)
2514
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2515

    
2516
    while (1) {
2517
        tcg_cpu_exec();
2518
        qemu_wait_io_event(cur_cpu);
2519
    }
2520

    
2521
    return NULL;
2522
}
2523

    
2524
void qemu_cpu_kick(void *_env)
2525
{
2526
    CPUState *env = _env;
2527
    qemu_cond_broadcast(env->halt_cond);
2528
    if (kvm_enabled())
2529
        qemu_thread_signal(env->thread, SIG_IPI);
2530
}
2531

    
2532
int qemu_cpu_self(void *_env)
2533
{
2534
    CPUState *env = _env;
2535
    QemuThread this;
2536
 
2537
    qemu_thread_self(&this);
2538
 
2539
    return qemu_thread_equal(&this, env->thread);
2540
}
2541

    
2542
static void cpu_signal(int sig)
2543
{
2544
    if (cpu_single_env)
2545
        cpu_exit(cpu_single_env);
2546
}
2547

    
2548
static void tcg_block_io_signals(void)
2549
{
2550
    sigset_t set;
2551
    struct sigaction sigact;
2552

    
2553
    sigemptyset(&set);
2554
    sigaddset(&set, SIGUSR2);
2555
    sigaddset(&set, SIGIO);
2556
    sigaddset(&set, SIGALRM);
2557
    sigaddset(&set, SIGCHLD);
2558
    pthread_sigmask(SIG_BLOCK, &set, NULL);
2559

    
2560
    sigemptyset(&set);
2561
    sigaddset(&set, SIG_IPI);
2562
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2563

    
2564
    memset(&sigact, 0, sizeof(sigact));
2565
    sigact.sa_handler = cpu_signal;
2566
    sigaction(SIG_IPI, &sigact, NULL);
2567
}
2568

    
2569
static void dummy_signal(int sig)
2570
{
2571
}
2572

    
2573
static void kvm_block_io_signals(CPUState *env)
2574
{
2575
    int r;
2576
    sigset_t set;
2577
    struct sigaction sigact;
2578

    
2579
    sigemptyset(&set);
2580
    sigaddset(&set, SIGUSR2);
2581
    sigaddset(&set, SIGIO);
2582
    sigaddset(&set, SIGALRM);
2583
    sigaddset(&set, SIGCHLD);
2584
    sigaddset(&set, SIG_IPI);
2585
    pthread_sigmask(SIG_BLOCK, &set, NULL);
2586

    
2587
    pthread_sigmask(SIG_BLOCK, NULL, &set);
2588
    sigdelset(&set, SIG_IPI);
2589

    
2590
    memset(&sigact, 0, sizeof(sigact));
2591
    sigact.sa_handler = dummy_signal;
2592
    sigaction(SIG_IPI, &sigact, NULL);
2593

    
2594
    r = kvm_set_signal_mask(env, &set);
2595
    if (r) {
2596
        fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2597
        exit(1);
2598
    }
2599
}
2600

    
2601
static void unblock_io_signals(void)
2602
{
2603
    sigset_t set;
2604

    
2605
    sigemptyset(&set);
2606
    sigaddset(&set, SIGUSR2);
2607
    sigaddset(&set, SIGIO);
2608
    sigaddset(&set, SIGALRM);
2609
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2610

    
2611
    sigemptyset(&set);
2612
    sigaddset(&set, SIG_IPI);
2613
    pthread_sigmask(SIG_BLOCK, &set, NULL);
2614
}
2615

    
2616
static void qemu_signal_lock(unsigned int msecs)
2617
{
2618
    qemu_mutex_lock(&qemu_fair_mutex);
2619

    
2620
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
2621
        qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2622
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2623
            break;
2624
    }
2625
    qemu_mutex_unlock(&qemu_fair_mutex);
2626
}
2627

    
2628
void qemu_mutex_lock_iothread(void)
2629
{
2630
    if (kvm_enabled()) {
2631
        qemu_mutex_lock(&qemu_fair_mutex);
2632
        qemu_mutex_lock(&qemu_global_mutex);
2633
        qemu_mutex_unlock(&qemu_fair_mutex);
2634
    } else
2635
        qemu_signal_lock(100);
2636
}
2637

    
2638
void qemu_mutex_unlock_iothread(void)
2639
{
2640
    qemu_mutex_unlock(&qemu_global_mutex);
2641
}
2642

    
2643
static int all_vcpus_paused(void)
2644
{
2645
    CPUState *penv = first_cpu;
2646

    
2647
    while (penv) {
2648
        if (!penv->stopped)
2649
            return 0;
2650
        penv = (CPUState *)penv->next_cpu;
2651
    }
2652

    
2653
    return 1;
2654
}
2655

    
2656
static void pause_all_vcpus(void)
2657
{
2658
    CPUState *penv = first_cpu;
2659

    
2660
    while (penv) {
2661
        penv->stop = 1;
2662
        qemu_thread_signal(penv->thread, SIG_IPI);
2663
        qemu_cpu_kick(penv);
2664
        penv = (CPUState *)penv->next_cpu;
2665
    }
2666

    
2667
    while (!all_vcpus_paused()) {
2668
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2669
        penv = first_cpu;
2670
        while (penv) {
2671
            qemu_thread_signal(penv->thread, SIG_IPI);
2672
            penv = (CPUState *)penv->next_cpu;
2673
        }
2674
    }
2675
}
2676

    
2677
static void resume_all_vcpus(void)
2678
{
2679
    CPUState *penv = first_cpu;
2680

    
2681
    while (penv) {
2682
        penv->stop = 0;
2683
        penv->stopped = 0;
2684
        qemu_thread_signal(penv->thread, SIG_IPI);
2685
        qemu_cpu_kick(penv);
2686
        penv = (CPUState *)penv->next_cpu;
2687
    }
2688
}
2689

    
2690
static void tcg_init_vcpu(void *_env)
2691
{
2692
    CPUState *env = _env;
2693
    /* share a single thread for all cpus with TCG */
2694
    if (!tcg_cpu_thread) {
2695
        env->thread = qemu_mallocz(sizeof(QemuThread));
2696
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2697
        qemu_cond_init(env->halt_cond);
2698
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2699
        while (env->created == 0)
2700
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2701
        tcg_cpu_thread = env->thread;
2702
        tcg_halt_cond = env->halt_cond;
2703
    } else {
2704
        env->thread = tcg_cpu_thread;
2705
        env->halt_cond = tcg_halt_cond;
2706
    }
2707
}
2708

    
2709
static void kvm_start_vcpu(CPUState *env)
2710
{
2711
    env->thread = qemu_mallocz(sizeof(QemuThread));
2712
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2713
    qemu_cond_init(env->halt_cond);
2714
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2715
    while (env->created == 0)
2716
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2717
}
2718

    
2719
void qemu_init_vcpu(void *_env)
2720
{
2721
    CPUState *env = _env;
2722

    
2723
    env->nr_cores = smp_cores;
2724
    env->nr_threads = smp_threads;
2725
    if (kvm_enabled())
2726
        kvm_start_vcpu(env);
2727
    else
2728
        tcg_init_vcpu(env);
2729
}
2730

    
2731
void qemu_notify_event(void)
2732
{
2733
    qemu_event_increment();
2734
}
2735

    
2736
static void qemu_system_vmstop_request(int reason)
2737
{
2738
    vmstop_requested = reason;
2739
    qemu_notify_event();
2740
}
2741

    
2742
void vm_stop(int reason)
2743
{
2744
    QemuThread me;
2745
    qemu_thread_self(&me);
2746

    
2747
    if (!qemu_thread_equal(&me, &io_thread)) {
2748
        qemu_system_vmstop_request(reason);
2749
        /*
2750
         * FIXME: should not return to device code in case
2751
         * vm_stop() has been requested.
2752
         */
2753
        if (cpu_single_env) {
2754
            cpu_exit(cpu_single_env);
2755
            cpu_single_env->stop = 1;
2756
        }
2757
        return;
2758
    }
2759
    do_vm_stop(reason);
2760
}
2761

    
2762
#endif
2763

    
2764

    
2765
#ifdef _WIN32
2766
static void host_main_loop_wait(int *timeout)
2767
{
2768
    int ret, ret2, i;
2769
    PollingEntry *pe;
2770

    
2771

    
2772
    /* XXX: need to suppress polling by better using win32 events */
2773
    ret = 0;
2774
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2775
        ret |= pe->func(pe->opaque);
2776
    }
2777
    if (ret == 0) {
2778
        int err;
2779
        WaitObjects *w = &wait_objects;
2780

    
2781
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2782
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2783
            if (w->func[ret - WAIT_OBJECT_0])
2784
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2785

    
2786
            /* Check for additional signaled events */
2787
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2788

    
2789
                /* Check if event is signaled */
2790
                ret2 = WaitForSingleObject(w->events[i], 0);
2791
                if(ret2 == WAIT_OBJECT_0) {
2792
                    if (w->func[i])
2793
                        w->func[i](w->opaque[i]);
2794
                } else if (ret2 == WAIT_TIMEOUT) {
2795
                } else {
2796
                    err = GetLastError();
2797
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2798
                }
2799
            }
2800
        } else if (ret == WAIT_TIMEOUT) {
2801
        } else {
2802
            err = GetLastError();
2803
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2804
        }
2805
    }
2806

    
2807
    *timeout = 0;
2808
}
2809
#else
2810
static void host_main_loop_wait(int *timeout)
2811
{
2812
}
2813
#endif
2814

    
2815
void main_loop_wait(int nonblocking)
2816
{
2817
    IOHandlerRecord *ioh;
2818
    fd_set rfds, wfds, xfds;
2819
    int ret, nfds;
2820
    struct timeval tv;
2821
    int timeout;
2822

    
2823
    if (nonblocking)
2824
        timeout = 0;
2825
    else {
2826
        timeout = qemu_calculate_timeout();
2827
        qemu_bh_update_timeout(&timeout);
2828
    }
2829

    
2830
    host_main_loop_wait(&timeout);
2831

    
2832
    /* poll any events */
2833
    /* XXX: separate device handlers from system ones */
2834
    nfds = -1;
2835
    FD_ZERO(&rfds);
2836
    FD_ZERO(&wfds);
2837
    FD_ZERO(&xfds);
2838
    QLIST_FOREACH(ioh, &io_handlers, next) {
2839
        if (ioh->deleted)
2840
            continue;
2841
        if (ioh->fd_read &&
2842
            (!ioh->fd_read_poll ||
2843
             ioh->fd_read_poll(ioh->opaque) != 0)) {
2844
            FD_SET(ioh->fd, &rfds);
2845
            if (ioh->fd > nfds)
2846
                nfds = ioh->fd;
2847
        }
2848
        if (ioh->fd_write) {
2849
            FD_SET(ioh->fd, &wfds);
2850
            if (ioh->fd > nfds)
2851
                nfds = ioh->fd;
2852
        }
2853
    }
2854

    
2855
    tv.tv_sec = timeout / 1000;
2856
    tv.tv_usec = (timeout % 1000) * 1000;
2857

    
2858
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2859

    
2860
    qemu_mutex_unlock_iothread();
2861
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2862
    qemu_mutex_lock_iothread();
2863
    if (ret > 0) {
2864
        IOHandlerRecord *pioh;
2865

    
2866
        QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2867
            if (ioh->deleted) {
2868
                QLIST_REMOVE(ioh, next);
2869
                qemu_free(ioh);
2870
                continue;
2871
            }
2872
            if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2873
                ioh->fd_read(ioh->opaque);
2874
            }
2875
            if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2876
                ioh->fd_write(ioh->opaque);
2877
            }
2878
        }
2879
    }
2880

    
2881
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2882

    
2883
    qemu_run_all_timers();
2884

    
2885
    /* Check bottom-halves last in case any of the earlier events triggered
2886
       them.  */
2887
    qemu_bh_poll();
2888

    
2889
}
2890

    
2891
static int qemu_cpu_exec(CPUState *env)
2892
{
2893
    int ret;
2894
#ifdef CONFIG_PROFILER
2895
    int64_t ti;
2896
#endif
2897

    
2898
#ifdef CONFIG_PROFILER
2899
    ti = profile_getclock();
2900
#endif
2901
    if (use_icount) {
2902
        int64_t count;
2903
        int decr;
2904
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2905
        env->icount_decr.u16.low = 0;
2906
        env->icount_extra = 0;
2907
        count = qemu_icount_round (qemu_next_deadline());
2908
        qemu_icount += count;
2909
        decr = (count > 0xffff) ? 0xffff : count;
2910
        count -= decr;
2911
        env->icount_decr.u16.low = decr;
2912
        env->icount_extra = count;
2913
    }
2914
    ret = cpu_exec(env);
2915
#ifdef CONFIG_PROFILER
2916
    qemu_time += profile_getclock() - ti;
2917
#endif
2918
    if (use_icount) {
2919
        /* Fold pending instructions back into the
2920
           instruction counter, and clear the interrupt flag.  */
2921
        qemu_icount -= (env->icount_decr.u16.low
2922
                        + env->icount_extra);
2923
        env->icount_decr.u32 = 0;
2924
        env->icount_extra = 0;
2925
    }
2926
    return ret;
2927
}
2928

    
2929
static bool tcg_cpu_exec(void)
2930
{
2931
    int ret = 0;
2932

    
2933
    if (next_cpu == NULL)
2934
        next_cpu = first_cpu;
2935
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2936
        CPUState *env = cur_cpu = next_cpu;
2937

    
2938
        qemu_clock_enable(vm_clock,
2939
                          (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2940

    
2941
        if (qemu_alarm_pending())
2942
            break;
2943
        if (cpu_can_run(env))
2944
            ret = qemu_cpu_exec(env);
2945
        else if (env->stop)
2946
            break;
2947

    
2948
        if (ret == EXCP_DEBUG) {
2949
            gdb_set_stop_cpu(env);
2950
            debug_requested = 1;
2951
            break;
2952
        }
2953
    }
2954
    return tcg_has_work();
2955
}
2956

    
2957
static int vm_can_run(void)
2958
{
2959
    if (powerdown_requested)
2960
        return 0;
2961
    if (reset_requested)
2962
        return 0;
2963
    if (shutdown_requested)
2964
        return 0;
2965
    if (debug_requested)
2966
        return 0;
2967
    return 1;
2968
}
2969

    
2970
qemu_irq qemu_system_powerdown;
2971

    
2972
static void main_loop(void)
2973
{
2974
    int r;
2975

    
2976
#ifdef CONFIG_IOTHREAD
2977
    qemu_system_ready = 1;
2978
    qemu_cond_broadcast(&qemu_system_cond);
2979
#endif
2980

    
2981
    for (;;) {
2982
        do {
2983
            bool nonblocking = false;
2984
#ifdef CONFIG_PROFILER
2985
            int64_t ti;
2986
#endif
2987
#ifndef CONFIG_IOTHREAD
2988
            nonblocking = tcg_cpu_exec();
2989
#endif
2990
#ifdef CONFIG_PROFILER
2991
            ti = profile_getclock();
2992
#endif
2993
            main_loop_wait(nonblocking);
2994
#ifdef CONFIG_PROFILER
2995
            dev_time += profile_getclock() - ti;
2996
#endif
2997
        } while (vm_can_run());
2998

    
2999
        if (qemu_debug_requested()) {
3000
            vm_stop(EXCP_DEBUG);
3001
        }
3002
        if (qemu_shutdown_requested()) {
3003
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3004
            if (no_shutdown) {
3005
                vm_stop(0);
3006
                no_shutdown = 0;
3007
            } else
3008
                break;
3009
        }
3010
        if (qemu_reset_requested()) {
3011
            pause_all_vcpus();
3012
            qemu_system_reset();
3013
            resume_all_vcpus();
3014
        }
3015
        if (qemu_powerdown_requested()) {
3016
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3017
            qemu_irq_raise(qemu_system_powerdown);
3018
        }
3019
        if ((r = qemu_vmstop_requested())) {
3020
            vm_stop(r);
3021
        }
3022
    }
3023
    pause_all_vcpus();
3024
}
3025

    
3026
static void version(void)
3027
{
3028
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3029
}
3030

    
3031
static void help(int exitcode)
3032
{
3033
    const char *options_help =
3034
#define DEF(option, opt_arg, opt_enum, opt_help)        \
3035
           opt_help
3036
#define DEFHEADING(text) stringify(text) "\n"
3037
#include "qemu-options.h"
3038
#undef DEF
3039
#undef DEFHEADING
3040
#undef GEN_DOCS
3041
        ;
3042
    version();
3043
    printf("usage: %s [options] [disk_image]\n"
3044
           "\n"
3045
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3046
           "\n"
3047
           "%s\n"
3048
           "During emulation, the following keys are useful:\n"
3049
           "ctrl-alt-f      toggle full screen\n"
3050
           "ctrl-alt-n      switch to virtual console 'n'\n"
3051
           "ctrl-alt        toggle mouse and keyboard grab\n"
3052
           "\n"
3053
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
3054
           "qemu",
3055
           options_help);
3056
    exit(exitcode);
3057
}
3058

    
3059
#define HAS_ARG 0x0001
3060

    
3061
enum {
3062
#define DEF(option, opt_arg, opt_enum, opt_help)        \
3063
    opt_enum,
3064
#define DEFHEADING(text)
3065
#include "qemu-options.h"
3066
#undef DEF
3067
#undef DEFHEADING
3068
#undef GEN_DOCS
3069
};
3070

    
3071
typedef struct QEMUOption {
3072
    const char *name;
3073
    int flags;
3074
    int index;
3075
} QEMUOption;
3076

    
3077
static const QEMUOption qemu_options[] = {
3078
    { "h", 0, QEMU_OPTION_h },
3079
#define DEF(option, opt_arg, opt_enum, opt_help)        \
3080
    { option, opt_arg, opt_enum },
3081
#define DEFHEADING(text)
3082
#include "qemu-options.h"
3083
#undef DEF
3084
#undef DEFHEADING
3085
#undef GEN_DOCS
3086
    { NULL },
3087
};
3088

    
3089
#ifdef HAS_AUDIO
3090
struct soundhw soundhw[] = {
3091
#ifdef HAS_AUDIO_CHOICE
3092
#if defined(TARGET_I386) || defined(TARGET_MIPS)
3093
    {
3094
        "pcspk",
3095
        "PC speaker",
3096
        0,
3097
        1,
3098
        { .init_isa = pcspk_audio_init }
3099
    },
3100
#endif
3101

    
3102
#ifdef CONFIG_SB16
3103
    {
3104
        "sb16",
3105
        "Creative Sound Blaster 16",
3106
        0,
3107
        1,
3108
        { .init_isa = SB16_init }
3109
    },
3110
#endif
3111

    
3112
#ifdef CONFIG_CS4231A
3113
    {
3114
        "cs4231a",
3115
        "CS4231A",
3116
        0,
3117
        1,
3118
        { .init_isa = cs4231a_init }
3119
    },
3120
#endif
3121

    
3122
#ifdef CONFIG_ADLIB
3123
    {
3124
        "adlib",
3125
#ifdef HAS_YMF262
3126
        "Yamaha YMF262 (OPL3)",
3127
#else
3128
        "Yamaha YM3812 (OPL2)",
3129
#endif
3130
        0,
3131
        1,
3132
        { .init_isa = Adlib_init }
3133
    },
3134
#endif
3135

    
3136
#ifdef CONFIG_GUS
3137
    {
3138
        "gus",
3139
        "Gravis Ultrasound GF1",
3140
        0,
3141
        1,
3142
        { .init_isa = GUS_init }
3143
    },
3144
#endif
3145

    
3146
#ifdef CONFIG_AC97
3147
    {
3148
        "ac97",
3149
        "Intel 82801AA AC97 Audio",
3150
        0,
3151
        0,
3152
        { .init_pci = ac97_init }
3153
    },
3154
#endif
3155

    
3156
#ifdef CONFIG_ES1370
3157
    {
3158
        "es1370",
3159
        "ENSONIQ AudioPCI ES1370",
3160
        0,
3161
        0,
3162
        { .init_pci = es1370_init }
3163
    },
3164
#endif
3165

    
3166
#endif /* HAS_AUDIO_CHOICE */
3167

    
3168
    { NULL, NULL, 0, 0, { NULL } }
3169
};
3170

    
3171
static void select_soundhw (const char *optarg)
3172
{
3173
    struct soundhw *c;
3174

    
3175
    if (*optarg == '?') {
3176
    show_valid_cards:
3177

    
3178
        printf ("Valid sound card names (comma separated):\n");
3179
        for (c = soundhw; c->name; ++c) {
3180
            printf ("%-11s %s\n", c->name, c->descr);
3181
        }
3182
        printf ("\n-soundhw all will enable all of the above\n");
3183
        exit (*optarg != '?');
3184
    }
3185
    else {
3186
        size_t l;
3187
        const char *p;
3188
        char *e;
3189
        int bad_card = 0;
3190

    
3191
        if (!strcmp (optarg, "all")) {
3192
            for (c = soundhw; c->name; ++c) {
3193
                c->enabled = 1;
3194
            }
3195
            return;
3196
        }
3197

    
3198
        p = optarg;
3199
        while (*p) {
3200
            e = strchr (p, ',');
3201
            l = !e ? strlen (p) : (size_t) (e - p);
3202

    
3203
            for (c = soundhw; c->name; ++c) {
3204
                if (!strncmp (c->name, p, l) && !c->name[l]) {
3205
                    c->enabled = 1;
3206
                    break;
3207
                }
3208
            }
3209

    
3210
            if (!c->name) {
3211
                if (l > 80) {
3212
                    fprintf (stderr,
3213
                             "Unknown sound card name (too big to show)\n");
3214
                }
3215
                else {
3216
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
3217
                             (int) l, p);
3218
                }
3219
                bad_card = 1;
3220
            }
3221
            p += l + (e != NULL);
3222
        }
3223

    
3224
        if (bad_card)
3225
            goto show_valid_cards;
3226
    }
3227
}
3228
#endif
3229

    
3230
static void select_vgahw (const char *p)
3231
{
3232
    const char *opts;
3233

    
3234
    default_vga = 0;
3235
    vga_interface_type = VGA_NONE;
3236
    if (strstart(p, "std", &opts)) {
3237
        vga_interface_type = VGA_STD;
3238
    } else if (strstart(p, "cirrus", &opts)) {
3239
        vga_interface_type = VGA_CIRRUS;
3240
    } else if (strstart(p, "vmware", &opts)) {
3241
        vga_interface_type = VGA_VMWARE;
3242
    } else if (strstart(p, "xenfb", &opts)) {
3243
        vga_interface_type = VGA_XENFB;
3244
    } else if (!strstart(p, "none", &opts)) {
3245
    invalid_vga:
3246
        fprintf(stderr, "Unknown vga type: %s\n", p);
3247
        exit(1);
3248
    }
3249
    while (*opts) {
3250
        const char *nextopt;
3251

    
3252
        if (strstart(opts, ",retrace=", &nextopt)) {
3253
            opts = nextopt;
3254
            if (strstart(opts, "dumb", &nextopt))
3255
                vga_retrace_method = VGA_RETRACE_DUMB;
3256
            else if (strstart(opts, "precise", &nextopt))
3257
                vga_retrace_method = VGA_RETRACE_PRECISE;
3258
            else goto invalid_vga;
3259
        } else goto invalid_vga;
3260
        opts = nextopt;
3261
    }
3262
}
3263

    
3264
#ifdef TARGET_I386
3265
static int balloon_parse(const char *arg)
3266
{
3267
    QemuOpts *opts;
3268

    
3269
    if (strcmp(arg, "none") == 0) {
3270
        return 0;
3271
    }
3272

    
3273
    if (!strncmp(arg, "virtio", 6)) {
3274
        if (arg[6] == ',') {
3275
            /* have params -> parse them */
3276
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3277
            if (!opts)
3278
                return  -1;
3279
        } else {
3280
            /* create empty opts */
3281
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3282
        }
3283
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3284
        return 0;
3285
    }
3286

    
3287
    return -1;
3288
}
3289
#endif
3290

    
3291
#ifdef _WIN32
3292
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3293
{
3294
    exit(STATUS_CONTROL_C_EXIT);
3295
    return TRUE;
3296
}
3297
#endif
3298

    
3299
int qemu_uuid_parse(const char *str, uint8_t *uuid)
3300
{
3301
    int ret;
3302

    
3303
    if(strlen(str) != 36)
3304
        return -1;
3305

    
3306
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3307
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3308
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3309

    
3310
    if(ret != 16)
3311
        return -1;
3312

    
3313
#ifdef TARGET_I386
3314
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3315
#endif
3316

    
3317
    return 0;
3318
}
3319

    
3320
#ifndef _WIN32
3321

    
3322
static void termsig_handler(int signal)
3323
{
3324
    qemu_system_shutdown_request();
3325
}
3326

    
3327
static void sigchld_handler(int signal)
3328
{
3329
    waitpid(-1, NULL, WNOHANG);
3330
}
3331

    
3332
static void sighandler_setup(void)
3333
{
3334
    struct sigaction act;
3335

    
3336
    memset(&act, 0, sizeof(act));
3337
    act.sa_handler = termsig_handler;
3338
    sigaction(SIGINT,  &act, NULL);
3339
    sigaction(SIGHUP,  &act, NULL);
3340
    sigaction(SIGTERM, &act, NULL);
3341

    
3342
    act.sa_handler = sigchld_handler;
3343
    act.sa_flags = SA_NOCLDSTOP;
3344
    sigaction(SIGCHLD, &act, NULL);
3345
}
3346

    
3347
#endif
3348

    
3349
#ifdef _WIN32
3350
/* Look for support files in the same directory as the executable.  */
3351
static char *find_datadir(const char *argv0)
3352
{
3353
    char *p;
3354
    char buf[MAX_PATH];
3355
    DWORD len;
3356

    
3357
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3358
    if (len == 0) {
3359
        return NULL;
3360
    }
3361

    
3362
    buf[len] = 0;
3363
    p = buf + len - 1;
3364
    while (p != buf && *p != '\\')
3365
        p--;
3366
    *p = 0;
3367
    if (access(buf, R_OK) == 0) {
3368
        return qemu_strdup(buf);
3369
    }
3370
    return NULL;
3371
}
3372
#else /* !_WIN32 */
3373

    
3374
/* Find a likely location for support files using the location of the binary.
3375
   For installed binaries this will be "$bindir/../share/qemu".  When
3376
   running from the build tree this will be "$bindir/../pc-bios".  */
3377
#define SHARE_SUFFIX "/share/qemu"
3378
#define BUILD_SUFFIX "/pc-bios"
3379
static char *find_datadir(const char *argv0)
3380
{
3381
    char *dir;
3382
    char *p = NULL;
3383
    char *res;
3384
    char buf[PATH_MAX];
3385
    size_t max_len;
3386

    
3387
#if defined(__linux__)
3388
    {
3389
        int len;
3390
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3391
        if (len > 0) {
3392
            buf[len] = 0;
3393
            p = buf;
3394
        }
3395
    }
3396
#elif defined(__FreeBSD__)
3397
    {
3398
        int len;
3399
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3400
        if (len > 0) {
3401
            buf[len] = 0;
3402
            p = buf;
3403
        }
3404
    }
3405
#endif
3406
    /* If we don't have any way of figuring out the actual executable
3407
       location then try argv[0].  */
3408
    if (!p) {
3409
        p = realpath(argv0, buf);
3410
        if (!p) {
3411
            return NULL;
3412
        }
3413
    }
3414
    dir = dirname(p);
3415
    dir = dirname(dir);
3416

    
3417
    max_len = strlen(dir) +
3418
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3419
    res = qemu_mallocz(max_len);
3420
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3421
    if (access(res, R_OK)) {
3422
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3423
        if (access(res, R_OK)) {
3424
            qemu_free(res);
3425
            res = NULL;
3426
        }
3427
    }
3428

    
3429
    return res;
3430
}
3431
#undef SHARE_SUFFIX
3432
#undef BUILD_SUFFIX
3433
#endif
3434

    
3435
char *qemu_find_file(int type, const char *name)
3436
{
3437
    int len;
3438
    const char *subdir;
3439
    char *buf;
3440

    
3441
    /* If name contains path separators then try it as a straight path.  */
3442
    if ((strchr(name, '/') || strchr(name, '\\'))
3443
        && access(name, R_OK) == 0) {
3444
        return qemu_strdup(name);
3445
    }
3446
    switch (type) {
3447
    case QEMU_FILE_TYPE_BIOS:
3448
        subdir = "";
3449
        break;
3450
    case QEMU_FILE_TYPE_KEYMAP:
3451
        subdir = "keymaps/";
3452
        break;
3453
    default:
3454
        abort();
3455
    }
3456
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3457
    buf = qemu_mallocz(len);
3458
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3459
    if (access(buf, R_OK)) {
3460
        qemu_free(buf);
3461
        return NULL;
3462
    }
3463
    return buf;
3464
}
3465

    
3466
static int device_help_func(QemuOpts *opts, void *opaque)
3467
{
3468
    return qdev_device_help(opts);
3469
}
3470

    
3471
static int device_init_func(QemuOpts *opts, void *opaque)
3472
{
3473
    DeviceState *dev;
3474

    
3475
    dev = qdev_device_add(opts);
3476
    if (!dev)
3477
        return -1;
3478
    return 0;
3479
}
3480

    
3481
static int chardev_init_func(QemuOpts *opts, void *opaque)
3482
{
3483
    CharDriverState *chr;
3484

    
3485
    chr = qemu_chr_open_opts(opts, NULL);
3486
    if (!chr)
3487
        return -1;
3488
    return 0;
3489
}
3490

    
3491
static int mon_init_func(QemuOpts *opts, void *opaque)
3492
{
3493
    CharDriverState *chr;
3494
    const char *chardev;
3495
    const char *mode;
3496
    int flags;
3497

    
3498
    mode = qemu_opt_get(opts, "mode");
3499
    if (mode == NULL) {
3500
        mode = "readline";
3501
    }
3502
    if (strcmp(mode, "readline") == 0) {
3503
        flags = MONITOR_USE_READLINE;
3504
    } else if (strcmp(mode, "control") == 0) {
3505
        flags = MONITOR_USE_CONTROL;
3506
    } else {
3507
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3508
        exit(1);
3509
    }
3510

    
3511
    if (qemu_opt_get_bool(opts, "default", 0))
3512
        flags |= MONITOR_IS_DEFAULT;
3513

    
3514
    chardev = qemu_opt_get(opts, "chardev");
3515
    chr = qemu_chr_find(chardev);
3516
    if (chr == NULL) {
3517
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3518
        exit(1);
3519
    }
3520

    
3521
    monitor_init(chr, flags);
3522
    return 0;
3523
}
3524

    
3525
static void monitor_parse(const char *optarg, const char *mode)
3526
{
3527
    static int monitor_device_index = 0;
3528
    QemuOpts *opts;
3529
    const char *p;
3530
    char label[32];
3531
    int def = 0;
3532

    
3533
    if (strstart(optarg, "chardev:", &p)) {
3534
        snprintf(label, sizeof(label), "%s", p);
3535
    } else {
3536
        if (monitor_device_index) {
3537
            snprintf(label, sizeof(label), "monitor%d",
3538
                     monitor_device_index);
3539
        } else {
3540
            snprintf(label, sizeof(label), "monitor");
3541
            def = 1;
3542
        }
3543
        opts = qemu_chr_parse_compat(label, optarg);
3544
        if (!opts) {
3545
            fprintf(stderr, "parse error: %s\n", optarg);
3546
            exit(1);
3547
        }
3548
    }
3549

    
3550
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3551
    if (!opts) {
3552
        fprintf(stderr, "duplicate chardev: %s\n", label);
3553
        exit(1);
3554
    }
3555
    qemu_opt_set(opts, "mode", mode);
3556
    qemu_opt_set(opts, "chardev", label);
3557
    if (def)
3558
        qemu_opt_set(opts, "default", "on");
3559
    monitor_device_index++;
3560
}
3561

    
3562
struct device_config {
3563
    enum {
3564
        DEV_USB,       /* -usbdevice     */
3565
        DEV_BT,        /* -bt            */
3566
        DEV_SERIAL,    /* -serial        */
3567
        DEV_PARALLEL,  /* -parallel      */
3568
        DEV_VIRTCON,   /* -virtioconsole */
3569
        DEV_DEBUGCON,  /* -debugcon */
3570
    } type;
3571
    const char *cmdline;
3572
    QTAILQ_ENTRY(device_config) next;
3573
};
3574
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3575

    
3576
static void add_device_config(int type, const char *cmdline)
3577
{
3578
    struct device_config *conf;
3579

    
3580
    conf = qemu_mallocz(sizeof(*conf));
3581
    conf->type = type;
3582
    conf->cmdline = cmdline;
3583
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3584
}
3585

    
3586
static int foreach_device_config(int type, int (*func)(const char *cmdline))
3587
{
3588
    struct device_config *conf;
3589
    int rc;
3590

    
3591
    QTAILQ_FOREACH(conf, &device_configs, next) {
3592
        if (conf->type != type)
3593
            continue;
3594
        rc = func(conf->cmdline);
3595
        if (0 != rc)
3596
            return rc;
3597
    }
3598
    return 0;
3599
}
3600

    
3601
static int serial_parse(const char *devname)
3602
{
3603
    static int index = 0;
3604
    char label[32];
3605

    
3606
    if (strcmp(devname, "none") == 0)
3607
        return 0;
3608
    if (index == MAX_SERIAL_PORTS) {
3609
        fprintf(stderr, "qemu: too many serial ports\n");
3610
        exit(1);
3611
    }
3612
    snprintf(label, sizeof(label), "serial%d", index);
3613
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
3614
    if (!serial_hds[index]) {
3615
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3616
                devname, strerror(errno));
3617
        return -1;
3618
    }
3619
    index++;
3620
    return 0;
3621
}
3622

    
3623
static int parallel_parse(const char *devname)
3624
{
3625
    static int index = 0;
3626
    char label[32];
3627

    
3628
    if (strcmp(devname, "none") == 0)
3629
        return 0;
3630
    if (index == MAX_PARALLEL_PORTS) {
3631
        fprintf(stderr, "qemu: too many parallel ports\n");
3632
        exit(1);
3633
    }
3634
    snprintf(label, sizeof(label), "parallel%d", index);
3635
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3636
    if (!parallel_hds[index]) {
3637
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3638
                devname, strerror(errno));
3639
        return -1;
3640
    }
3641
    index++;
3642
    return 0;
3643
}
3644

    
3645
static int virtcon_parse(const char *devname)
3646
{
3647
    static int index = 0;
3648
    char label[32];
3649
    QemuOpts *bus_opts, *dev_opts;
3650

    
3651
    if (strcmp(devname, "none") == 0)
3652
        return 0;
3653
    if (index == MAX_VIRTIO_CONSOLES) {
3654
        fprintf(stderr, "qemu: too many virtio consoles\n");
3655
        exit(1);
3656
    }
3657

    
3658
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3659
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
3660

    
3661
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3662
    qemu_opt_set(dev_opts, "driver", "virtconsole");
3663

    
3664
    snprintf(label, sizeof(label), "virtcon%d", index);
3665
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3666
    if (!virtcon_hds[index]) {
3667
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3668
                devname, strerror(errno));
3669
        return -1;
3670
    }
3671
    qemu_opt_set(dev_opts, "chardev", label);
3672

    
3673
    index++;
3674
    return 0;
3675
}
3676

    
3677
static int debugcon_parse(const char *devname)
3678
{   
3679
    QemuOpts *opts;
3680

    
3681
    if (!qemu_chr_open("debugcon", devname, NULL)) {
3682
        exit(1);
3683
    }
3684
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3685
    if (!opts) {
3686
        fprintf(stderr, "qemu: already have a debugcon device\n");
3687
        exit(1);
3688
    }
3689
    qemu_opt_set(opts, "driver", "isa-debugcon");
3690
    qemu_opt_set(opts, "chardev", "debugcon");
3691
    return 0;
3692
}
3693

    
3694
static const QEMUOption *lookup_opt(int argc, char **argv,
3695
                                    const char **poptarg, int *poptind)
3696
{
3697
    const QEMUOption *popt;
3698
    int optind = *poptind;
3699
    char *r = argv[optind];
3700
    const char *optarg;
3701

    
3702
    loc_set_cmdline(argv, optind, 1);
3703
    optind++;
3704
    /* Treat --foo the same as -foo.  */
3705
    if (r[1] == '-')
3706
        r++;
3707
    popt = qemu_options;
3708
    for(;;) {
3709
        if (!popt->name) {
3710
            error_report("invalid option");
3711
            exit(1);
3712
        }
3713
        if (!strcmp(popt->name, r + 1))
3714
            break;
3715
        popt++;
3716
    }
3717
    if (popt->flags & HAS_ARG) {
3718
        if (optind >= argc) {
3719
            error_report("requires an argument");
3720
            exit(1);
3721
        }
3722
        optarg = argv[optind++];
3723
        loc_set_cmdline(argv, optind - 2, 2);
3724
    } else {
3725
        optarg = NULL;
3726
    }
3727

    
3728
    *poptarg = optarg;
3729
    *poptind = optind;
3730

    
3731
    return popt;
3732
}
3733

    
3734
int main(int argc, char **argv, char **envp)
3735
{
3736
    const char *gdbstub_dev = NULL;
3737
    uint32_t boot_devices_bitmap = 0;
3738
    int i;
3739
    int snapshot, linux_boot, net_boot;
3740
    const char *icount_option = NULL;
3741
    const char *initrd_filename;
3742
    const char *kernel_filename, *kernel_cmdline;
3743
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3744
    DisplayState *ds;
3745
    DisplayChangeListener *dcl;
3746
    int cyls, heads, secs, translation;
3747
    QemuOpts *hda_opts = NULL, *opts;
3748
    int optind;
3749
    const char *optarg;
3750
    const char *loadvm = NULL;
3751
    QEMUMachine *machine;
3752
    const char *cpu_model;
3753
#ifndef _WIN32
3754
    int fds[2];
3755
#endif
3756
    int tb_size;
3757
    const char *pid_file = NULL;
3758
    const char *incoming = NULL;
3759
#ifndef _WIN32
3760
    int fd = 0;
3761
    struct passwd *pwd = NULL;
3762
    const char *chroot_dir = NULL;
3763
    const char *run_as = NULL;
3764
#endif
3765
    CPUState *env;
3766
    int show_vnc_port = 0;
3767
    int defconfig = 1;
3768

    
3769
    error_set_progname(argv[0]);
3770

    
3771
    init_clocks();
3772

    
3773
    qemu_cache_utils_init(envp);
3774

    
3775
    QLIST_INIT (&vm_change_state_head);
3776
#ifndef _WIN32
3777
    {
3778
        struct sigaction act;
3779
        sigfillset(&act.sa_mask);
3780
        act.sa_flags = 0;
3781
        act.sa_handler = SIG_IGN;
3782
        sigaction(SIGPIPE, &act, NULL);
3783
    }
3784
#else
3785
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3786
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
3787
       QEMU to run on a single CPU */
3788
    {
3789
        HANDLE h;
3790
        DWORD mask, smask;
3791
        int i;
3792
        h = GetCurrentProcess();
3793
        if (GetProcessAffinityMask(h, &mask, &smask)) {
3794
            for(i = 0; i < 32; i++) {
3795
                if (mask & (1 << i))
3796
                    break;
3797
            }
3798
            if (i != 32) {
3799
                mask = 1 << i;
3800
                SetProcessAffinityMask(h, mask);
3801
            }
3802
        }
3803
    }
3804
#endif
3805

    
3806
    module_call_init(MODULE_INIT_MACHINE);
3807
    machine = find_default_machine();
3808
    cpu_model = NULL;
3809
    initrd_filename = NULL;
3810
    ram_size = 0;
3811
    snapshot = 0;
3812
    kernel_filename = NULL;
3813
    kernel_cmdline = "";
3814
    cyls = heads = secs = 0;
3815
    translation = BIOS_ATA_TRANSLATION_AUTO;
3816

    
3817
    for (i = 0; i < MAX_NODES; i++) {
3818
        node_mem[i] = 0;
3819
        node_cpumask[i] = 0;
3820
    }
3821

    
3822
    nb_numa_nodes = 0;
3823
    nb_nics = 0;
3824

    
3825
    tb_size = 0;
3826
    autostart= 1;
3827

    
3828
    /* first pass of option parsing */
3829
    optind = 1;
3830
    while (optind < argc) {
3831
        if (argv[optind][0] != '-') {
3832
            /* disk image */
3833
            optind++;
3834
            continue;
3835
        } else {
3836
            const QEMUOption *popt;
3837

    
3838
            popt = lookup_opt(argc, argv, &optarg, &optind);
3839
            switch (popt->index) {
3840
            case QEMU_OPTION_nodefconfig:
3841
                defconfig=0;
3842
                break;
3843
            }
3844
        }
3845
    }
3846

    
3847
    if (defconfig) {
3848
        const char *fname;
3849
        FILE *fp;
3850

    
3851
        fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3852
        fp = fopen(fname, "r");
3853
        if (fp) {
3854
            if (qemu_config_parse(fp, fname) != 0) {
3855
                exit(1);
3856
            }
3857
            fclose(fp);
3858
        }
3859

    
3860
        fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3861
        fp = fopen(fname, "r");
3862
        if (fp) {
3863
            if (qemu_config_parse(fp, fname) != 0) {
3864
                exit(1);
3865
            }
3866
            fclose(fp);
3867
        }
3868
    }
3869
#if defined(cpudef_setup)
3870
    cpudef_setup(); /* parse cpu definitions in target config file */
3871
#endif
3872

    
3873
    /* second pass of option parsing */
3874
    optind = 1;
3875
    for(;;) {
3876
        if (optind >= argc)
3877
            break;
3878
        if (argv[optind][0] != '-') {
3879
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3880
        } else {
3881
            const QEMUOption *popt;
3882

    
3883
            popt = lookup_opt(argc, argv, &optarg, &optind);
3884
            switch(popt->index) {
3885
            case QEMU_OPTION_M:
3886
                machine = find_machine(optarg);
3887
                if (!machine) {
3888
                    QEMUMachine *m;
3889
                    printf("Supported machines are:\n");
3890
                    for(m = first_machine; m != NULL; m = m->next) {
3891
                        if (m->alias)
3892
                            printf("%-10s %s (alias of %s)\n",
3893
                                   m->alias, m->desc, m->name);
3894
                        printf("%-10s %s%s\n",
3895
                               m->name, m->desc,
3896
                               m->is_default ? " (default)" : "");
3897
                    }
3898
                    exit(*optarg != '?');
3899
                }
3900
                break;
3901
            case QEMU_OPTION_cpu:
3902
                /* hw initialization will check this */
3903
                if (*optarg == '?') {
3904
/* XXX: implement xxx_cpu_list for targets that still miss it */
3905
#if defined(cpu_list_id)
3906
                    cpu_list_id(stdout, &fprintf, optarg);
3907
#elif defined(cpu_list)
3908
                    cpu_list(stdout, &fprintf);                /* deprecated */
3909
#endif
3910
                    exit(0);
3911
                } else {
3912
                    cpu_model = optarg;
3913
                }
3914
                break;
3915
            case QEMU_OPTION_initrd:
3916
                initrd_filename = optarg;
3917
                break;
3918
            case QEMU_OPTION_hda:
3919
                if (cyls == 0)
3920
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
3921
                else
3922
                    hda_opts = drive_add(optarg, HD_ALIAS
3923
                             ",cyls=%d,heads=%d,secs=%d%s",
3924
                             0, cyls, heads, secs,
3925
                             translation == BIOS_ATA_TRANSLATION_LBA ?
3926
                                 ",trans=lba" :
3927
                             translation == BIOS_ATA_TRANSLATION_NONE ?
3928
                                 ",trans=none" : "");
3929
                 break;
3930
            case QEMU_OPTION_hdb:
3931
            case QEMU_OPTION_hdc:
3932
            case QEMU_OPTION_hdd:
3933
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3934
                break;
3935
            case QEMU_OPTION_drive:
3936
                drive_add(NULL, "%s", optarg);
3937
                break;
3938
            case QEMU_OPTION_set:
3939
                if (qemu_set_option(optarg) != 0)
3940
                    exit(1);
3941
                break;
3942
            case QEMU_OPTION_global:
3943
                if (qemu_global_option(optarg) != 0)
3944
                    exit(1);
3945
                break;
3946
            case QEMU_OPTION_mtdblock:
3947
                drive_add(optarg, MTD_ALIAS);
3948
                break;
3949
            case QEMU_OPTION_sd:
3950
                drive_add(optarg, SD_ALIAS);
3951
                break;
3952
            case QEMU_OPTION_pflash:
3953
                drive_add(optarg, PFLASH_ALIAS);
3954
                break;
3955
            case QEMU_OPTION_snapshot:
3956
                snapshot = 1;
3957
                break;
3958
            case QEMU_OPTION_hdachs:
3959
                {
3960
                    const char *p;
3961
                    p = optarg;
3962
                    cyls = strtol(p, (char **)&p, 0);
3963
                    if (cyls < 1 || cyls > 16383)
3964
                        goto chs_fail;
3965
                    if (*p != ',')
3966
                        goto chs_fail;
3967
                    p++;
3968
                    heads = strtol(p, (char **)&p, 0);
3969
                    if (heads < 1 || heads > 16)
3970
                        goto chs_fail;
3971
                    if (*p != ',')
3972
                        goto chs_fail;
3973
                    p++;
3974
                    secs = strtol(p, (char **)&p, 0);
3975
                    if (secs < 1 || secs > 63)
3976
                        goto chs_fail;
3977
                    if (*p == ',') {
3978
                        p++;
3979
                        if (!strcmp(p, "none"))
3980
                            translation = BIOS_ATA_TRANSLATION_NONE;
3981
                        else if (!strcmp(p, "lba"))
3982
                            translation = BIOS_ATA_TRANSLATION_LBA;
3983
                        else if (!strcmp(p, "auto"))
3984
                            translation = BIOS_ATA_TRANSLATION_AUTO;
3985
                        else
3986
                            goto chs_fail;
3987
                    } else if (*p != '\0') {
3988
                    chs_fail:
3989
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
3990
                        exit(1);
3991
                    }
3992
                    if (hda_opts != NULL) {
3993
                        char num[16];
3994
                        snprintf(num, sizeof(num), "%d", cyls);
3995
                        qemu_opt_set(hda_opts, "cyls", num);
3996
                        snprintf(num, sizeof(num), "%d", heads);
3997
                        qemu_opt_set(hda_opts, "heads", num);
3998
                        snprintf(num, sizeof(num), "%d", secs);
3999
                        qemu_opt_set(hda_opts, "secs", num);
4000
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
4001
                            qemu_opt_set(hda_opts, "trans", "lba");
4002
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
4003
                            qemu_opt_set(hda_opts, "trans", "none");
4004
                    }
4005
                }
4006
                break;
4007
            case QEMU_OPTION_numa:
4008
                if (nb_numa_nodes >= MAX_NODES) {
4009
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
4010
                    exit(1);
4011
                }
4012
                numa_add(optarg);
4013
                break;
4014
            case QEMU_OPTION_nographic:
4015
                display_type = DT_NOGRAPHIC;
4016
                break;
4017
#ifdef CONFIG_CURSES
4018
            case QEMU_OPTION_curses:
4019
                display_type = DT_CURSES;
4020
                break;
4021
#endif
4022
            case QEMU_OPTION_portrait:
4023
                graphic_rotate = 1;
4024
                break;
4025
            case QEMU_OPTION_kernel:
4026
                kernel_filename = optarg;
4027
                break;
4028
            case QEMU_OPTION_append:
4029
                kernel_cmdline = optarg;
4030
                break;
4031
            case QEMU_OPTION_cdrom:
4032
                drive_add(optarg, CDROM_ALIAS);
4033
                break;
4034
            case QEMU_OPTION_boot:
4035
                {
4036
                    static const char * const params[] = {
4037
                        "order", "once", "menu", NULL
4038
                    };
4039
                    char buf[sizeof(boot_devices)];
4040
                    char *standard_boot_devices;
4041
                    int legacy = 0;
4042

    
4043
                    if (!strchr(optarg, '=')) {
4044
                        legacy = 1;
4045
                        pstrcpy(buf, sizeof(buf), optarg);
4046
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4047
                        fprintf(stderr,
4048
                                "qemu: unknown boot parameter '%s' in '%s'\n",
4049
                                buf, optarg);
4050
                        exit(1);
4051
                    }
4052

    
4053
                    if (legacy ||
4054
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
4055
                        boot_devices_bitmap = parse_bootdevices(buf);
4056
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
4057
                    }
4058
                    if (!legacy) {
4059
                        if (get_param_value(buf, sizeof(buf),
4060
                                            "once", optarg)) {
4061
                            boot_devices_bitmap |= parse_bootdevices(buf);
4062
                            standard_boot_devices = qemu_strdup(boot_devices);
4063
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
4064
                            qemu_register_reset(restore_boot_devices,
4065
                                                standard_boot_devices);
4066
                        }
4067
                        if (get_param_value(buf, sizeof(buf),
4068
                                            "menu", optarg)) {
4069
                            if (!strcmp(buf, "on")) {
4070
                                boot_menu = 1;
4071
                            } else if (!strcmp(buf, "off")) {
4072
                                boot_menu = 0;
4073
                            } else {
4074
                                fprintf(stderr,
4075
                                        "qemu: invalid option value '%s'\n",
4076
                                        buf);
4077
                                exit(1);
4078
                            }
4079
                        }
4080
                    }
4081
                }
4082
                break;
4083
            case QEMU_OPTION_fda:
4084
            case QEMU_OPTION_fdb:
4085
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4086
                break;
4087
#ifdef TARGET_I386
4088
            case QEMU_OPTION_no_fd_bootchk:
4089
                fd_bootchk = 0;
4090
                break;
4091
#endif
4092
            case QEMU_OPTION_netdev:
4093
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4094
                    exit(1);
4095
                }
4096
                break;
4097
            case QEMU_OPTION_net:
4098
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4099
                    exit(1);
4100
                }
4101
                break;
4102
#ifdef CONFIG_SLIRP
4103
            case QEMU_OPTION_tftp:
4104
                legacy_tftp_prefix = optarg;
4105
                break;
4106
            case QEMU_OPTION_bootp:
4107
                legacy_bootp_filename = optarg;
4108
                break;
4109
#ifndef _WIN32
4110
            case QEMU_OPTION_smb:
4111
                if (net_slirp_smb(optarg) < 0)
4112
                    exit(1);
4113
                break;
4114
#endif
4115
            case QEMU_OPTION_redir:
4116
                if (net_slirp_redir(optarg) < 0)
4117
                    exit(1);
4118
                break;
4119
#endif
4120
            case QEMU_OPTION_bt:
4121
                add_device_config(DEV_BT, optarg);
4122
                break;
4123
#ifdef HAS_AUDIO
4124
            case QEMU_OPTION_audio_help:
4125
                AUD_help ();
4126
                exit (0);
4127
                break;
4128
            case QEMU_OPTION_soundhw:
4129
                select_soundhw (optarg);
4130
                break;
4131
#endif
4132
            case QEMU_OPTION_h:
4133
                help(0);
4134
                break;
4135
            case QEMU_OPTION_version:
4136
                version();
4137
                exit(0);
4138
                break;
4139
            case QEMU_OPTION_m: {
4140
                uint64_t value;
4141
                char *ptr;
4142

    
4143
                value = strtoul(optarg, &ptr, 10);
4144
                switch (*ptr) {
4145
                case 0: case 'M': case 'm':
4146
                    value <<= 20;
4147
                    break;
4148
                case 'G': case 'g':
4149
                    value <<= 30;
4150
                    break;
4151
                default:
4152
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4153
                    exit(1);
4154
                }
4155

    
4156
                /* On 32-bit hosts, QEMU is limited by virtual address space */
4157
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4158
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4159
                    exit(1);
4160
                }
4161
                if (value != (uint64_t)(ram_addr_t)value) {
4162
                    fprintf(stderr, "qemu: ram size too large\n");
4163
                    exit(1);
4164
                }
4165
                ram_size = value;
4166
                break;
4167
            }
4168
            case QEMU_OPTION_mempath:
4169
                mem_path = optarg;
4170
                break;
4171
#ifdef MAP_POPULATE
4172
            case QEMU_OPTION_mem_prealloc:
4173
                mem_prealloc = 1;
4174
                break;
4175
#endif
4176
            case QEMU_OPTION_d:
4177
                {
4178
                    int mask;
4179
                    const CPULogItem *item;
4180

    
4181
                    mask = cpu_str_to_log_mask(optarg);
4182
                    if (!mask) {
4183
                        printf("Log items (comma separated):\n");
4184
                    for(item = cpu_log_items; item->mask != 0; item++) {
4185
                        printf("%-10s %s\n", item->name, item->help);
4186
                    }
4187
                    exit(1);
4188
                    }
4189
                    cpu_set_log(mask);
4190
                }
4191
                break;
4192
            case QEMU_OPTION_s:
4193
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4194
                break;
4195
            case QEMU_OPTION_gdb:
4196
                gdbstub_dev = optarg;
4197
                break;
4198
            case QEMU_OPTION_L:
4199
                data_dir = optarg;
4200
                break;
4201
            case QEMU_OPTION_bios:
4202
                bios_name = optarg;
4203
                break;
4204
            case QEMU_OPTION_singlestep:
4205
                singlestep = 1;
4206
                break;
4207
            case QEMU_OPTION_S:
4208
                autostart = 0;
4209
                break;
4210
            case QEMU_OPTION_k:
4211
                keyboard_layout = optarg;
4212
                break;
4213
            case QEMU_OPTION_localtime:
4214
                rtc_utc = 0;
4215
                break;
4216
            case QEMU_OPTION_vga:
4217
                select_vgahw (optarg);
4218
                break;
4219
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4220
            case QEMU_OPTION_g:
4221
                {
4222
                    const char *p;
4223
                    int w, h, depth;
4224
                    p = optarg;
4225
                    w = strtol(p, (char **)&p, 10);
4226
                    if (w <= 0) {
4227
                    graphic_error:
4228
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
4229
                        exit(1);
4230
                    }
4231
                    if (*p != 'x')
4232
                        goto graphic_error;
4233
                    p++;
4234
                    h = strtol(p, (char **)&p, 10);
4235
                    if (h <= 0)
4236
                        goto graphic_error;
4237
                    if (*p == 'x') {
4238
                        p++;
4239
                        depth = strtol(p, (char **)&p, 10);
4240
                        if (depth != 8 && depth != 15 && depth != 16 &&
4241
                            depth != 24 && depth != 32)
4242
                            goto graphic_error;
4243
                    } else if (*p == '\0') {
4244
                        depth = graphic_depth;
4245
                    } else {
4246
                        goto graphic_error;
4247
                    }
4248

    
4249
                    graphic_width = w;
4250
                    graphic_height = h;
4251
                    graphic_depth = depth;
4252
                }
4253
                break;
4254
#endif
4255
            case QEMU_OPTION_echr:
4256
                {
4257
                    char *r;
4258
                    term_escape_char = strtol(optarg, &r, 0);
4259
                    if (r == optarg)
4260
                        printf("Bad argument to echr\n");
4261
                    break;
4262
                }
4263
            case QEMU_OPTION_monitor:
4264
                monitor_parse(optarg, "readline");
4265
                default_monitor = 0;
4266
                break;
4267
            case QEMU_OPTION_qmp:
4268
                monitor_parse(optarg, "control");
4269
                default_monitor = 0;
4270
                break;
4271
            case QEMU_OPTION_mon:
4272
                opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4273
                if (!opts) {
4274
                    fprintf(stderr, "parse error: %s\n", optarg);
4275
                    exit(1);
4276
                }
4277
                default_monitor = 0;
4278
                break;
4279
            case QEMU_OPTION_chardev:
4280
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4281
                if (!opts) {
4282
                    fprintf(stderr, "parse error: %s\n", optarg);
4283
                    exit(1);
4284
                }
4285
                break;
4286
            case QEMU_OPTION_serial:
4287
                add_device_config(DEV_SERIAL, optarg);
4288
                default_serial = 0;
4289
                if (strncmp(optarg, "mon:", 4) == 0) {
4290
                    default_monitor = 0;
4291
                }
4292
                break;
4293
            case QEMU_OPTION_watchdog:
4294
                if (watchdog) {
4295
                    fprintf(stderr,
4296
                            "qemu: only one watchdog option may be given\n");
4297
                    return 1;
4298
                }
4299
                watchdog = optarg;
4300
                break;
4301
            case QEMU_OPTION_watchdog_action:
4302
                if (select_watchdog_action(optarg) == -1) {
4303
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
4304
                    exit(1);
4305
                }
4306
                break;
4307
            case QEMU_OPTION_virtiocon:
4308
                add_device_config(DEV_VIRTCON, optarg);
4309
                default_virtcon = 0;
4310
                if (strncmp(optarg, "mon:", 4) == 0) {
4311
                    default_monitor = 0;
4312
                }
4313
                break;
4314
            case QEMU_OPTION_parallel:
4315
                add_device_config(DEV_PARALLEL, optarg);
4316
                default_parallel = 0;
4317
                if (strncmp(optarg, "mon:", 4) == 0) {
4318
                    default_monitor = 0;
4319
                }
4320
                break;
4321
            case QEMU_OPTION_debugcon:
4322
                add_device_config(DEV_DEBUGCON, optarg);
4323
                break;
4324
            case QEMU_OPTION_loadvm:
4325
                loadvm = optarg;
4326
                break;
4327
            case QEMU_OPTION_full_screen:
4328
                full_screen = 1;
4329
                break;
4330
#ifdef CONFIG_SDL
4331
            case QEMU_OPTION_no_frame:
4332
                no_frame = 1;
4333
                break;
4334
            case QEMU_OPTION_alt_grab:
4335
                alt_grab = 1;
4336
                break;
4337
            case QEMU_OPTION_ctrl_grab:
4338
                ctrl_grab = 1;
4339
                break;
4340
            case QEMU_OPTION_no_quit:
4341
                no_quit = 1;
4342
                break;
4343
            case QEMU_OPTION_sdl:
4344
                display_type = DT_SDL;
4345
                break;
4346
#endif
4347
            case QEMU_OPTION_pidfile:
4348
                pid_file = optarg;
4349
                break;
4350
#ifdef TARGET_I386
4351
            case QEMU_OPTION_win2k_hack:
4352
                win2k_install_hack = 1;
4353
                break;
4354
            case QEMU_OPTION_rtc_td_hack:
4355
                rtc_td_hack = 1;
4356
                break;
4357
            case QEMU_OPTION_acpitable:
4358
                if(acpi_table_add(optarg) < 0) {
4359
                    fprintf(stderr, "Wrong acpi table provided\n");
4360
                    exit(1);
4361
                }
4362
                break;
4363
            case QEMU_OPTION_smbios:
4364
                if(smbios_entry_add(optarg) < 0) {
4365
                    fprintf(stderr, "Wrong smbios provided\n");
4366
                    exit(1);
4367
                }
4368
                break;
4369
#endif
4370
#ifdef CONFIG_KVM
4371
            case QEMU_OPTION_enable_kvm:
4372
                kvm_allowed = 1;
4373
                break;
4374
#endif
4375
            case QEMU_OPTION_usb:
4376
                usb_enabled = 1;
4377
                break;
4378
            case QEMU_OPTION_usbdevice:
4379
                usb_enabled = 1;
4380
                add_device_config(DEV_USB, optarg);
4381
                break;
4382
            case QEMU_OPTION_device:
4383
                if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4384
                    exit(1);
4385
                }
4386
                break;
4387
            case QEMU_OPTION_smp:
4388
                smp_parse(optarg);
4389
                if (smp_cpus < 1) {
4390
                    fprintf(stderr, "Invalid number of CPUs\n");
4391
                    exit(1);
4392
                }
4393
                if (max_cpus < smp_cpus) {
4394
                    fprintf(stderr, "maxcpus must be equal to or greater than "
4395
                            "smp\n");
4396
                    exit(1);
4397
                }
4398
                if (max_cpus > 255) {
4399
                    fprintf(stderr, "Unsupported number of maxcpus\n");
4400
                    exit(1);
4401
                }
4402
                break;
4403
            case QEMU_OPTION_vnc:
4404
                display_type = DT_VNC;
4405
                vnc_display = optarg;
4406
                break;
4407
#ifdef TARGET_I386
4408
            case QEMU_OPTION_no_acpi:
4409
                acpi_enabled = 0;
4410
                break;
4411
            case QEMU_OPTION_no_hpet:
4412
                no_hpet = 1;
4413
                break;
4414
            case QEMU_OPTION_balloon:
4415
                if (balloon_parse(optarg) < 0) {
4416
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4417
                    exit(1);
4418
                }
4419
                break;
4420
#endif
4421
            case QEMU_OPTION_no_reboot:
4422
                no_reboot = 1;
4423
                break;
4424
            case QEMU_OPTION_no_shutdown:
4425
                no_shutdown = 1;
4426
                break;
4427
            case QEMU_OPTION_show_cursor:
4428
                cursor_hide = 0;
4429
                break;
4430
            case QEMU_OPTION_uuid:
4431
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4432
                    fprintf(stderr, "Fail to parse UUID string."
4433
                            " Wrong format.\n");
4434
                    exit(1);
4435
                }
4436
                break;
4437
#ifndef _WIN32
4438
            case QEMU_OPTION_daemonize:
4439
                daemonize = 1;
4440
                break;
4441
#endif
4442
            case QEMU_OPTION_option_rom:
4443
                if (nb_option_roms >= MAX_OPTION_ROMS) {
4444
                    fprintf(stderr, "Too many option ROMs\n");
4445
                    exit(1);
4446
                }
4447
                option_rom[nb_option_roms] = optarg;
4448
                nb_option_roms++;
4449
                break;
4450
#if defined(TARGET_ARM) || defined(TARGET_M68K)
4451
            case QEMU_OPTION_semihosting:
4452
                semihosting_enabled = 1;
4453
                break;
4454
#endif
4455
            case QEMU_OPTION_name:
4456
                qemu_name = qemu_strdup(optarg);
4457
                 {
4458
                     char *p = strchr(qemu_name, ',');
4459
                     if (p != NULL) {
4460
                        *p++ = 0;
4461
                        if (strncmp(p, "process=", 8)) {
4462
                            fprintf(stderr, "Unknown subargument %s to -name", p);
4463
                            exit(1);
4464
                        }
4465
                        p += 8;
4466
                        set_proc_name(p);
4467
                     }        
4468
                 }        
4469
                break;
4470
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
4471
            case QEMU_OPTION_prom_env:
4472
                if (nb_prom_envs >= MAX_PROM_ENVS) {
4473
                    fprintf(stderr, "Too many prom variables\n");
4474
                    exit(1);
4475
                }
4476
                prom_envs[nb_prom_envs] = optarg;
4477
                nb_prom_envs++;
4478
                break;
4479
#endif
4480
#ifdef TARGET_ARM
4481
            case QEMU_OPTION_old_param:
4482
                old_param = 1;
4483
                break;
4484
#endif
4485
            case QEMU_OPTION_clock:
4486
                configure_alarms(optarg);
4487
                break;
4488
            case QEMU_OPTION_startdate:
4489
                configure_rtc_date_offset(optarg, 1);
4490
                break;
4491
            case QEMU_OPTION_rtc:
4492
                opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4493
                if (!opts) {
4494
                    fprintf(stderr, "parse error: %s\n", optarg);
4495
                    exit(1);
4496
                }
4497
                configure_rtc(opts);
4498
                break;
4499
            case QEMU_OPTION_tb_size:
4500
                tb_size = strtol(optarg, NULL, 0);
4501
                if (tb_size < 0)
4502
                    tb_size = 0;
4503
                break;
4504
            case QEMU_OPTION_icount:
4505
                icount_option = optarg;
4506
                break;
4507
            case QEMU_OPTION_incoming:
4508
                incoming = optarg;
4509
                break;
4510
            case QEMU_OPTION_nodefaults:
4511
                default_serial = 0;
4512
                default_parallel = 0;
4513
                default_virtcon = 0;
4514
                default_monitor = 0;
4515
                default_vga = 0;
4516
                default_net = 0;
4517
                default_floppy = 0;
4518
                default_cdrom = 0;
4519
                default_sdcard = 0;
4520
                break;
4521
#ifndef _WIN32
4522
            case QEMU_OPTION_chroot:
4523
                chroot_dir = optarg;
4524
                break;
4525
            case QEMU_OPTION_runas:
4526
                run_as = optarg;
4527
                break;
4528
#endif
4529
#ifdef CONFIG_XEN
4530
            case QEMU_OPTION_xen_domid:
4531
                xen_domid = atoi(optarg);
4532
                break;
4533
            case QEMU_OPTION_xen_create:
4534
                xen_mode = XEN_CREATE;
4535
                break;
4536
            case QEMU_OPTION_xen_attach:
4537
                xen_mode = XEN_ATTACH;
4538
                break;
4539
#endif
4540
            case QEMU_OPTION_readconfig:
4541
                {
4542
                    FILE *fp;
4543
                    fp = fopen(optarg, "r");
4544
                    if (fp == NULL) {
4545
                        fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4546
                        exit(1);
4547
                    }
4548
                    if (qemu_config_parse(fp, optarg) != 0) {
4549
                        exit(1);
4550
                    }
4551
                    fclose(fp);
4552
                    break;
4553
                }
4554
            case QEMU_OPTION_writeconfig:
4555
                {
4556
                    FILE *fp;
4557
                    if (strcmp(optarg, "-") == 0) {
4558
                        fp = stdout;
4559
                    } else {
4560
                        fp = fopen(optarg, "w");
4561
                        if (fp == NULL) {
4562
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4563
                            exit(1);
4564
                        }
4565
                    }
4566
                    qemu_config_write(fp);
4567
                    fclose(fp);
4568
                    break;
4569
                }
4570
            }
4571
        }
4572
    }
4573
    loc_set_none();
4574

    
4575
    /* If no data_dir is specified then try to find it relative to the
4576
       executable path.  */
4577
    if (!data_dir) {
4578
        data_dir = find_datadir(argv[0]);
4579
    }
4580
    /* If all else fails use the install patch specified when building.  */
4581
    if (!data_dir) {
4582
        data_dir = CONFIG_QEMU_SHAREDIR;
4583
    }
4584

    
4585
    /*
4586
     * Default to max_cpus = smp_cpus, in case the user doesn't
4587
     * specify a max_cpus value.
4588
     */
4589
    if (!max_cpus)
4590
        max_cpus = smp_cpus;
4591

    
4592
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4593
    if (smp_cpus > machine->max_cpus) {
4594
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4595
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
4596
                machine->max_cpus);
4597
        exit(1);
4598
    }
4599

    
4600
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4601
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4602

    
4603
    if (machine->no_serial) {
4604
        default_serial = 0;
4605
    }
4606
    if (machine->no_parallel) {
4607
        default_parallel = 0;
4608
    }
4609
    if (!machine->use_virtcon) {
4610
        default_virtcon = 0;
4611
    }
4612
    if (machine->no_vga) {
4613
        default_vga = 0;
4614
    }
4615
    if (machine->no_floppy) {
4616
        default_floppy = 0;
4617
    }
4618
    if (machine->no_cdrom) {
4619
        default_cdrom = 0;
4620
    }
4621
    if (machine->no_sdcard) {
4622
        default_sdcard = 0;
4623
    }
4624

    
4625
    if (display_type == DT_NOGRAPHIC) {
4626
        if (default_parallel)
4627
            add_device_config(DEV_PARALLEL, "null");
4628
        if (default_serial && default_monitor) {
4629
            add_device_config(DEV_SERIAL, "mon:stdio");
4630
        } else if (default_virtcon && default_monitor) {
4631
            add_device_config(DEV_VIRTCON, "mon:stdio");
4632
        } else {
4633
            if (default_serial)
4634
                add_device_config(DEV_SERIAL, "stdio");
4635
            if (default_virtcon)
4636
                add_device_config(DEV_VIRTCON, "stdio");
4637
            if (default_monitor)
4638
                monitor_parse("stdio", "readline");
4639
        }
4640
    } else {
4641
        if (default_serial)
4642
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
4643
        if (default_parallel)
4644
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4645
        if (default_monitor)
4646
            monitor_parse("vc:80Cx24C", "readline");
4647
        if (default_virtcon)
4648
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4649
    }
4650
    if (default_vga)
4651
        vga_interface_type = VGA_CIRRUS;
4652

    
4653
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4654
        exit(1);
4655

    
4656
#ifndef _WIN32
4657
    if (daemonize) {
4658
        pid_t pid;
4659

    
4660
        if (pipe(fds) == -1)
4661
            exit(1);
4662

    
4663
        pid = fork();
4664
        if (pid > 0) {
4665
            uint8_t status;
4666
            ssize_t len;
4667

    
4668
            close(fds[1]);
4669

    
4670
        again:
4671
            len = read(fds[0], &status, 1);
4672
            if (len == -1 && (errno == EINTR))
4673
                goto again;
4674

    
4675
            if (len != 1)
4676
                exit(1);
4677
            else if (status == 1) {
4678
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4679
                exit(1);
4680
            } else
4681
                exit(0);
4682
        } else if (pid < 0)
4683
            exit(1);
4684

    
4685
        close(fds[0]);
4686
        qemu_set_cloexec(fds[1]);
4687

    
4688
        setsid();
4689

    
4690
        pid = fork();
4691
        if (pid > 0)
4692
            exit(0);
4693
        else if (pid < 0)
4694
            exit(1);
4695

    
4696
        umask(027);
4697

    
4698
        signal(SIGTSTP, SIG_IGN);
4699
        signal(SIGTTOU, SIG_IGN);
4700
        signal(SIGTTIN, SIG_IGN);
4701
    }
4702
#endif
4703

    
4704
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4705
#ifndef _WIN32
4706
        if (daemonize) {
4707
            uint8_t status = 1;
4708
            if (write(fds[1], &status, 1) != 1) {
4709
                perror("daemonize. Writing to pipe\n");
4710
            }
4711
        } else
4712
#endif
4713
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4714
        exit(1);
4715
    }
4716

    
4717
    if (kvm_enabled()) {
4718
        int ret;
4719

    
4720
        ret = kvm_init(smp_cpus);
4721
        if (ret < 0) {
4722
            fprintf(stderr, "failed to initialize KVM\n");
4723
            exit(1);
4724
        }
4725
    }
4726

    
4727
    if (qemu_init_main_loop()) {
4728
        fprintf(stderr, "qemu_init_main_loop failed\n");
4729
        exit(1);
4730
    }
4731
    linux_boot = (kernel_filename != NULL);
4732

    
4733
    if (!linux_boot && *kernel_cmdline != '\0') {
4734
        fprintf(stderr, "-append only allowed with -kernel option\n");
4735
        exit(1);
4736
    }
4737

    
4738
    if (!linux_boot && initrd_filename != NULL) {
4739
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
4740
        exit(1);
4741
    }
4742

    
4743
#ifndef _WIN32
4744
    /* Win32 doesn't support line-buffering and requires size >= 2 */
4745
    setvbuf(stdout, NULL, _IOLBF, 0);
4746
#endif
4747

    
4748
    if (init_timer_alarm() < 0) {
4749
        fprintf(stderr, "could not initialize alarm timer\n");
4750
        exit(1);
4751
    }
4752
    configure_icount(icount_option);
4753

    
4754
#ifdef _WIN32
4755
    socket_init();
4756
#endif
4757

    
4758
    if (net_init_clients() < 0) {
4759
        exit(1);
4760
    }
4761

    
4762
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4763
    net_set_boot_mask(net_boot);
4764

    
4765
    /* init the bluetooth world */
4766
    if (foreach_device_config(DEV_BT, bt_parse))
4767
        exit(1);
4768

    
4769
    /* init the memory */
4770
    if (ram_size == 0)
4771
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4772

    
4773
    /* init the dynamic translator */
4774
    cpu_exec_init_all(tb_size * 1024 * 1024);
4775

    
4776
    bdrv_init_with_whitelist();
4777

    
4778
    blk_mig_init();
4779

    
4780
    if (default_cdrom) {
4781
        /* we always create the cdrom drive, even if no disk is there */
4782
        drive_add(NULL, CDROM_ALIAS);
4783
    }
4784

    
4785
    if (default_floppy) {
4786
        /* we always create at least one floppy */
4787
        drive_add(NULL, FD_ALIAS, 0);
4788
    }
4789

    
4790
    if (default_sdcard) {
4791
        /* we always create one sd slot, even if no card is in it */
4792
        drive_add(NULL, SD_ALIAS);
4793
    }
4794

    
4795
    /* open the virtual block devices */
4796
    if (snapshot)
4797
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4798
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4799
        exit(1);
4800

    
4801
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
4802
                         ram_load, NULL);
4803

    
4804
    if (nb_numa_nodes > 0) {
4805
        int i;
4806

    
4807
        if (nb_numa_nodes > smp_cpus) {
4808
            nb_numa_nodes = smp_cpus;
4809
        }
4810

    
4811
        /* If no memory size if given for any node, assume the default case
4812
         * and distribute the available memory equally across all nodes
4813
         */
4814
        for (i = 0; i < nb_numa_nodes; i++) {
4815
            if (node_mem[i] != 0)
4816
                break;
4817
        }
4818
        if (i == nb_numa_nodes) {
4819
            uint64_t usedmem = 0;
4820

    
4821
            /* On Linux, the each node's border has to be 8MB aligned,
4822
             * the final node gets the rest.
4823
             */
4824
            for (i = 0; i < nb_numa_nodes - 1; i++) {
4825
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4826
                usedmem += node_mem[i];
4827
            }
4828
            node_mem[i] = ram_size - usedmem;
4829
        }
4830

    
4831
        for (i = 0; i < nb_numa_nodes; i++) {
4832
            if (node_cpumask[i] != 0)
4833
                break;
4834
        }
4835
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
4836
         * must cope with this anyway, because there are BIOSes out there in
4837
         * real machines which also use this scheme.
4838
         */
4839
        if (i == nb_numa_nodes) {
4840
            for (i = 0; i < smp_cpus; i++) {
4841
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
4842
            }
4843
        }
4844
    }
4845

    
4846
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4847
        exit(1);
4848
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4849
        exit(1);
4850
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4851
        exit(1);
4852
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4853
        exit(1);
4854

    
4855
    module_call_init(MODULE_INIT_DEVICE);
4856

    
4857
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4858
        exit(0);
4859

    
4860
    if (watchdog) {
4861
        i = select_watchdog(watchdog);
4862
        if (i > 0)
4863
            exit (i == 1 ? 1 : 0);
4864
    }
4865

    
4866
    if (machine->compat_props) {
4867
        qdev_prop_register_global_list(machine->compat_props);
4868
    }
4869
    qemu_add_globals();
4870

    
4871
    machine->init(ram_size, boot_devices,
4872
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);