Statistics
| Branch: | Revision:

root / vl.c @ 54fc6ea9

History | View | Annotate | Download (128.8 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

    
154
#include "disas.h"
155

    
156
#include "exec-all.h"
157

    
158
#include "qemu_socket.h"
159

    
160
#include "slirp/libslirp.h"
161

    
162
#include "qemu-queue.h"
163

    
164
//#define DEBUG_NET
165
//#define DEBUG_SLIRP
166

    
167
#define DEFAULT_RAM_SIZE 128
168

    
169
#define MAX_VIRTIO_CONSOLES 1
170

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

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

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

    
256
uint8_t qemu_uuid[16];
257

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
381

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
556
/***********************************************************/
557
/* Bluetooth support */
558
static int nb_hcis;
559
static int cur_hci;
560
static struct HCIInfo *hci_table[MAX_NICS];
561

    
562
static struct bt_vlan_s {
563
    struct bt_scatternet_s net;
564
    int id;
565
    struct bt_vlan_s *next;
566
} *first_bt_vlan;
567

    
568
/* find or alloc a new bluetooth "VLAN" */
569
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
570
{
571
    struct bt_vlan_s **pvlan, *vlan;
572
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
573
        if (vlan->id == id)
574
            return &vlan->net;
575
    }
576
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
577
    vlan->id = id;
578
    pvlan = &first_bt_vlan;
579
    while (*pvlan != NULL)
580
        pvlan = &(*pvlan)->next;
581
    *pvlan = vlan;
582
    return &vlan->net;
583
}
584

    
585
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
586
{
587
}
588

    
589
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
590
{
591
    return -ENOTSUP;
592
}
593

    
594
static struct HCIInfo null_hci = {
595
    .cmd_send = null_hci_send,
596
    .sco_send = null_hci_send,
597
    .acl_send = null_hci_send,
598
    .bdaddr_set = null_hci_addr_set,
599
};
600

    
601
struct HCIInfo *qemu_next_hci(void)
602
{
603
    if (cur_hci == nb_hcis)
604
        return &null_hci;
605

    
606
    return hci_table[cur_hci++];
607
}
608

    
609
static struct HCIInfo *hci_init(const char *str)
610
{
611
    char *endp;
612
    struct bt_scatternet_s *vlan = 0;
613

    
614
    if (!strcmp(str, "null"))
615
        /* null */
616
        return &null_hci;
617
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
618
        /* host[:hciN] */
619
        return bt_host_hci(str[4] ? str + 5 : "hci0");
620
    else if (!strncmp(str, "hci", 3)) {
621
        /* hci[,vlan=n] */
622
        if (str[3]) {
623
            if (!strncmp(str + 3, ",vlan=", 6)) {
624
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
625
                if (*endp)
626
                    vlan = 0;
627
            }
628
        } else
629
            vlan = qemu_find_bt_vlan(0);
630
        if (vlan)
631
           return bt_new_hci(vlan);
632
    }
633

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

    
636
    return 0;
637
}
638

    
639
static int bt_hci_parse(const char *str)
640
{
641
    struct HCIInfo *hci;
642
    bdaddr_t bdaddr;
643

    
644
    if (nb_hcis >= MAX_NICS) {
645
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
646
        return -1;
647
    }
648

    
649
    hci = hci_init(str);
650
    if (!hci)
651
        return -1;
652

    
653
    bdaddr.b[0] = 0x52;
654
    bdaddr.b[1] = 0x54;
655
    bdaddr.b[2] = 0x00;
656
    bdaddr.b[3] = 0x12;
657
    bdaddr.b[4] = 0x34;
658
    bdaddr.b[5] = 0x56 + nb_hcis;
659
    hci->bdaddr_set(hci, bdaddr.b);
660

    
661
    hci_table[nb_hcis++] = hci;
662

    
663
    return 0;
664
}
665

    
666
static void bt_vhci_add(int vlan_id)
667
{
668
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
669

    
670
    if (!vlan->slave)
671
        fprintf(stderr, "qemu: warning: adding a VHCI to "
672
                        "an empty scatternet %i\n", vlan_id);
673

    
674
    bt_vhci_init(bt_new_hci(vlan));
675
}
676

    
677
static struct bt_device_s *bt_device_add(const char *opt)
678
{
679
    struct bt_scatternet_s *vlan;
680
    int vlan_id = 0;
681
    char *endp = strstr(opt, ",vlan=");
682
    int len = (endp ? endp - opt : strlen(opt)) + 1;
683
    char devname[10];
684

    
685
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
686

    
687
    if (endp) {
688
        vlan_id = strtol(endp + 6, &endp, 0);
689
        if (*endp) {
690
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
691
            return 0;
692
        }
693
    }
694

    
695
    vlan = qemu_find_bt_vlan(vlan_id);
696

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

    
701
    if (!strcmp(devname, "keyboard"))
702
        return bt_keyboard_init(vlan);
703

    
704
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
705
    return 0;
706
}
707

    
708
static int bt_parse(const char *opt)
709
{
710
    const char *endp, *p;
711
    int vlan;
712

    
713
    if (strstart(opt, "hci", &endp)) {
714
        if (!*endp || *endp == ',') {
715
            if (*endp)
716
                if (!strstart(endp, ",vlan=", 0))
717
                    opt = endp + 1;
718

    
719
            return bt_hci_parse(opt);
720
       }
721
    } else if (strstart(opt, "vhci", &endp)) {
722
        if (!*endp || *endp == ',') {
723
            if (*endp) {
724
                if (strstart(endp, ",vlan=", &p)) {
725
                    vlan = strtol(p, (char **) &endp, 0);
726
                    if (*endp) {
727
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
728
                        return 1;
729
                    }
730
                } else {
731
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
732
                    return 1;
733
                }
734
            } else
735
                vlan = 0;
736

    
737
            bt_vhci_add(vlan);
738
            return 0;
739
        }
740
    } else if (strstart(opt, "device:", &endp))
741
        return !bt_device_add(endp);
742

    
743
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
744
    return 1;
745
}
746

    
747
/***********************************************************/
748
/* QEMU Block devices */
749

    
750
#define HD_ALIAS "index=%d,media=disk"
751
#define CDROM_ALIAS "index=2,media=cdrom"
752
#define FD_ALIAS "index=%d,if=floppy"
753
#define PFLASH_ALIAS "if=pflash"
754
#define MTD_ALIAS "if=mtd"
755
#define SD_ALIAS "index=0,if=sd"
756

    
757
QemuOpts *drive_add(const char *file, const char *fmt, ...)
758
{
759
    va_list ap;
760
    char optstr[1024];
761
    QemuOpts *opts;
762

    
763
    va_start(ap, fmt);
764
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
765
    va_end(ap);
766

    
767
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
768
    if (!opts) {
769
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
770
                __FUNCTION__, optstr);
771
        return NULL;
772
    }
773
    if (file)
774
        qemu_opt_set(opts, "file", file);
775
    return opts;
776
}
777

    
778
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
779
{
780
    DriveInfo *dinfo;
781

    
782
    /* seek interface, bus and unit */
783

    
784
    QTAILQ_FOREACH(dinfo, &drives, next) {
785
        if (dinfo->type == type &&
786
            dinfo->bus == bus &&
787
            dinfo->unit == unit)
788
            return dinfo;
789
    }
790

    
791
    return NULL;
792
}
793

    
794
DriveInfo *drive_get_by_id(const char *id)
795
{
796
    DriveInfo *dinfo;
797

    
798
    QTAILQ_FOREACH(dinfo, &drives, next) {
799
        if (strcmp(id, dinfo->id))
800
            continue;
801
        return dinfo;
802
    }
803
    return NULL;
804
}
805

    
806
int drive_get_max_bus(BlockInterfaceType type)
807
{
808
    int max_bus;
809
    DriveInfo *dinfo;
810

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

    
820
const char *drive_get_serial(BlockDriverState *bdrv)
821
{
822
    DriveInfo *dinfo;
823

    
824
    QTAILQ_FOREACH(dinfo, &drives, next) {
825
        if (dinfo->bdrv == bdrv)
826
            return dinfo->serial;
827
    }
828

    
829
    return "\0";
830
}
831

    
832
BlockInterfaceErrorAction drive_get_on_error(
833
    BlockDriverState *bdrv, int is_read)
834
{
835
    DriveInfo *dinfo;
836

    
837
    QTAILQ_FOREACH(dinfo, &drives, next) {
838
        if (dinfo->bdrv == bdrv)
839
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
840
    }
841

    
842
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
843
}
844

    
845
static void bdrv_format_print(void *opaque, const char *name)
846
{
847
    fprintf(stderr, " %s", name);
848
}
849

    
850
void drive_uninit(DriveInfo *dinfo)
851
{
852
    qemu_opts_del(dinfo->opts);
853
    bdrv_delete(dinfo->bdrv);
854
    QTAILQ_REMOVE(&drives, dinfo, next);
855
    qemu_free(dinfo);
856
}
857

    
858
static int parse_block_error_action(const char *buf, int is_read)
859
{
860
    if (!strcmp(buf, "ignore")) {
861
        return BLOCK_ERR_IGNORE;
862
    } else if (!is_read && !strcmp(buf, "enospc")) {
863
        return BLOCK_ERR_STOP_ENOSPC;
864
    } else if (!strcmp(buf, "stop")) {
865
        return BLOCK_ERR_STOP_ANY;
866
    } else if (!strcmp(buf, "report")) {
867
        return BLOCK_ERR_REPORT;
868
    } else {
869
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
870
            buf, is_read ? "read" : "write");
871
        return -1;
872
    }
873
}
874

    
875
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
876
                      int *fatal_error)
877
{
878
    const char *buf;
879
    const char *file = NULL;
880
    char devname[128];
881
    const char *serial;
882
    const char *mediastr = "";
883
    BlockInterfaceType type;
884
    enum { MEDIA_DISK, MEDIA_CDROM } media;
885
    int bus_id, unit_id;
886
    int cyls, heads, secs, translation;
887
    BlockDriver *drv = NULL;
888
    QEMUMachine *machine = opaque;
889
    int max_devs;
890
    int index;
891
    int cache;
892
    int aio = 0;
893
    int ro = 0;
894
    int bdrv_flags;
895
    int on_read_error, on_write_error;
896
    const char *devaddr;
897
    DriveInfo *dinfo;
898
    int snapshot = 0;
899

    
900
    *fatal_error = 1;
901

    
902
    translation = BIOS_ATA_TRANSLATION_AUTO;
903
    cache = 1;
904

    
905
    if (machine && machine->use_scsi) {
906
        type = IF_SCSI;
907
        max_devs = MAX_SCSI_DEVS;
908
        pstrcpy(devname, sizeof(devname), "scsi");
909
    } else {
910
        type = IF_IDE;
911
        max_devs = MAX_IDE_DEVS;
912
        pstrcpy(devname, sizeof(devname), "ide");
913
    }
914
    media = MEDIA_DISK;
915

    
916
    /* extract parameters */
917
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
918
    unit_id = qemu_opt_get_number(opts, "unit", -1);
919
    index   = qemu_opt_get_number(opts, "index", -1);
920

    
921
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
922
    heads = qemu_opt_get_number(opts, "heads", 0);
923
    secs  = qemu_opt_get_number(opts, "secs", 0);
924

    
925
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
926
    ro = qemu_opt_get_bool(opts, "readonly", 0);
927

    
928
    file = qemu_opt_get(opts, "file");
929
    serial = qemu_opt_get(opts, "serial");
930

    
931
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
932
        pstrcpy(devname, sizeof(devname), buf);
933
        if (!strcmp(buf, "ide")) {
934
            type = IF_IDE;
935
            max_devs = MAX_IDE_DEVS;
936
        } else if (!strcmp(buf, "scsi")) {
937
            type = IF_SCSI;
938
            max_devs = MAX_SCSI_DEVS;
939
        } else if (!strcmp(buf, "floppy")) {
940
            type = IF_FLOPPY;
941
            max_devs = 0;
942
        } else if (!strcmp(buf, "pflash")) {
943
            type = IF_PFLASH;
944
            max_devs = 0;
945
        } else if (!strcmp(buf, "mtd")) {
946
            type = IF_MTD;
947
            max_devs = 0;
948
        } else if (!strcmp(buf, "sd")) {
949
            type = IF_SD;
950
            max_devs = 0;
951
        } else if (!strcmp(buf, "virtio")) {
952
            type = IF_VIRTIO;
953
            max_devs = 0;
954
        } else if (!strcmp(buf, "xen")) {
955
            type = IF_XEN;
956
            max_devs = 0;
957
        } else if (!strcmp(buf, "none")) {
958
            type = IF_NONE;
959
            max_devs = 0;
960
        } else {
961
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
962
            return NULL;
963
        }
964
    }
965

    
966
    if (cyls || heads || secs) {
967
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
968
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
969
            return NULL;
970
        }
971
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
972
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
973
            return NULL;
974
        }
975
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
976
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
977
            return NULL;
978
        }
979
    }
980

    
981
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
982
        if (!cyls) {
983
            fprintf(stderr,
984
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
985
                    buf);
986
            return NULL;
987
        }
988
        if (!strcmp(buf, "none"))
989
            translation = BIOS_ATA_TRANSLATION_NONE;
990
        else if (!strcmp(buf, "lba"))
991
            translation = BIOS_ATA_TRANSLATION_LBA;
992
        else if (!strcmp(buf, "auto"))
993
            translation = BIOS_ATA_TRANSLATION_AUTO;
994
        else {
995
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
996
            return NULL;
997
        }
998
    }
999

    
1000
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1001
        if (!strcmp(buf, "disk")) {
1002
            media = MEDIA_DISK;
1003
        } else if (!strcmp(buf, "cdrom")) {
1004
            if (cyls || secs || heads) {
1005
                fprintf(stderr,
1006
                        "qemu: '%s' invalid physical CHS format\n", buf);
1007
                return NULL;
1008
            }
1009
            media = MEDIA_CDROM;
1010
        } else {
1011
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1012
            return NULL;
1013
        }
1014
    }
1015

    
1016
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1017
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1018
            cache = 0;
1019
        else if (!strcmp(buf, "writethrough"))
1020
            cache = 1;
1021
        else if (!strcmp(buf, "writeback"))
1022
            cache = 2;
1023
        else {
1024
           fprintf(stderr, "qemu: invalid cache option\n");
1025
           return NULL;
1026
        }
1027
    }
1028

    
1029
#ifdef CONFIG_LINUX_AIO
1030
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1031
        if (!strcmp(buf, "threads"))
1032
            aio = 0;
1033
        else if (!strcmp(buf, "native"))
1034
            aio = 1;
1035
        else {
1036
           fprintf(stderr, "qemu: invalid aio option\n");
1037
           return NULL;
1038
        }
1039
    }
1040
#endif
1041

    
1042
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1043
       if (strcmp(buf, "?") == 0) {
1044
            fprintf(stderr, "qemu: Supported formats:");
1045
            bdrv_iterate_format(bdrv_format_print, NULL);
1046
            fprintf(stderr, "\n");
1047
            return NULL;
1048
        }
1049
        drv = bdrv_find_whitelisted_format(buf);
1050
        if (!drv) {
1051
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1052
            return NULL;
1053
        }
1054
    }
1055

    
1056
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
1057
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1058
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1059
            fprintf(stderr, "werror is no supported by this format\n");
1060
            return NULL;
1061
        }
1062

    
1063
        on_write_error = parse_block_error_action(buf, 0);
1064
        if (on_write_error < 0) {
1065
            return NULL;
1066
        }
1067
    }
1068

    
1069
    on_read_error = BLOCK_ERR_REPORT;
1070
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1071
        if (type != IF_IDE && type != IF_VIRTIO) {
1072
            fprintf(stderr, "rerror is no supported by this format\n");
1073
            return NULL;
1074
        }
1075

    
1076
        on_read_error = parse_block_error_action(buf, 1);
1077
        if (on_read_error < 0) {
1078
            return NULL;
1079
        }
1080
    }
1081

    
1082
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1083
        if (type != IF_VIRTIO) {
1084
            fprintf(stderr, "addr is not supported\n");
1085
            return NULL;
1086
        }
1087
    }
1088

    
1089
    /* compute bus and unit according index */
1090

    
1091
    if (index != -1) {
1092
        if (bus_id != 0 || unit_id != -1) {
1093
            fprintf(stderr,
1094
                    "qemu: index cannot be used with bus and unit\n");
1095
            return NULL;
1096
        }
1097
        if (max_devs == 0)
1098
        {
1099
            unit_id = index;
1100
            bus_id = 0;
1101
        } else {
1102
            unit_id = index % max_devs;
1103
            bus_id = index / max_devs;
1104
        }
1105
    }
1106

    
1107
    /* if user doesn't specify a unit_id,
1108
     * try to find the first free
1109
     */
1110

    
1111
    if (unit_id == -1) {
1112
       unit_id = 0;
1113
       while (drive_get(type, bus_id, unit_id) != NULL) {
1114
           unit_id++;
1115
           if (max_devs && unit_id >= max_devs) {
1116
               unit_id -= max_devs;
1117
               bus_id++;
1118
           }
1119
       }
1120
    }
1121

    
1122
    /* check unit id */
1123

    
1124
    if (max_devs && unit_id >= max_devs) {
1125
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1126
                unit_id, max_devs - 1);
1127
        return NULL;
1128
    }
1129

    
1130
    /*
1131
     * ignore multiple definitions
1132
     */
1133

    
1134
    if (drive_get(type, bus_id, unit_id) != NULL) {
1135
        *fatal_error = 0;
1136
        return NULL;
1137
    }
1138

    
1139
    /* init */
1140

    
1141
    dinfo = qemu_mallocz(sizeof(*dinfo));
1142
    if ((buf = qemu_opts_id(opts)) != NULL) {
1143
        dinfo->id = qemu_strdup(buf);
1144
    } else {
1145
        /* no id supplied -> create one */
1146
        dinfo->id = qemu_mallocz(32);
1147
        if (type == IF_IDE || type == IF_SCSI)
1148
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1149
        if (max_devs)
1150
            snprintf(dinfo->id, 32, "%s%i%s%i",
1151
                     devname, bus_id, mediastr, unit_id);
1152
        else
1153
            snprintf(dinfo->id, 32, "%s%s%i",
1154
                     devname, mediastr, unit_id);
1155
    }
1156
    dinfo->bdrv = bdrv_new(dinfo->id);
1157
    dinfo->devaddr = devaddr;
1158
    dinfo->type = type;
1159
    dinfo->bus = bus_id;
1160
    dinfo->unit = unit_id;
1161
    dinfo->on_read_error = on_read_error;
1162
    dinfo->on_write_error = on_write_error;
1163
    dinfo->opts = opts;
1164
    if (serial)
1165
        strncpy(dinfo->serial, serial, sizeof(serial));
1166
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1167

    
1168
    switch(type) {
1169
    case IF_IDE:
1170
    case IF_SCSI:
1171
    case IF_XEN:
1172
    case IF_NONE:
1173
        switch(media) {
1174
        case MEDIA_DISK:
1175
            if (cyls != 0) {
1176
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1177
                bdrv_set_translation_hint(dinfo->bdrv, translation);
1178
            }
1179
            break;
1180
        case MEDIA_CDROM:
1181
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1182
            break;
1183
        }
1184
        break;
1185
    case IF_SD:
1186
        /* FIXME: This isn't really a floppy, but it's a reasonable
1187
           approximation.  */
1188
    case IF_FLOPPY:
1189
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1190
        break;
1191
    case IF_PFLASH:
1192
    case IF_MTD:
1193
        break;
1194
    case IF_VIRTIO:
1195
        /* add virtio block device */
1196
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1197
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
1198
        qemu_opt_set(opts, "drive", dinfo->id);
1199
        if (devaddr)
1200
            qemu_opt_set(opts, "addr", devaddr);
1201
        break;
1202
    case IF_COUNT:
1203
        abort();
1204
    }
1205
    if (!file) {
1206
        *fatal_error = 0;
1207
        return NULL;
1208
    }
1209
    bdrv_flags = 0;
1210
    if (snapshot) {
1211
        bdrv_flags |= BDRV_O_SNAPSHOT;
1212
        cache = 2; /* always use write-back with snapshot */
1213
    }
1214
    if (cache == 0) /* no caching */
1215
        bdrv_flags |= BDRV_O_NOCACHE;
1216
    else if (cache == 2) /* write-back */
1217
        bdrv_flags |= BDRV_O_CACHE_WB;
1218

    
1219
    if (aio == 1) {
1220
        bdrv_flags |= BDRV_O_NATIVE_AIO;
1221
    } else {
1222
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1223
    }
1224

    
1225
    if (ro == 1) {
1226
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1227
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1228
            return NULL;
1229
        }
1230
    }
1231
    /* 
1232
     * cdrom is read-only. Set it now, after above interface checking
1233
     * since readonly attribute not explicitly required, so no error.
1234
     */
1235
    if (media == MEDIA_CDROM) {
1236
        ro = 1;
1237
    }
1238
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1239

    
1240
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1241
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1242
                        file, strerror(errno));
1243
        return NULL;
1244
    }
1245

    
1246
    if (bdrv_key_required(dinfo->bdrv))
1247
        autostart = 0;
1248
    *fatal_error = 0;
1249
    return dinfo;
1250
}
1251

    
1252
static int drive_init_func(QemuOpts *opts, void *opaque)
1253
{
1254
    QEMUMachine *machine = opaque;
1255
    int fatal_error = 0;
1256

    
1257
    if (drive_init(opts, machine, &fatal_error) == NULL) {
1258
        if (fatal_error)
1259
            return 1;
1260
    }
1261
    return 0;
1262
}
1263

    
1264
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1265
{
1266
    if (NULL == qemu_opt_get(opts, "snapshot")) {
1267
        qemu_opt_set(opts, "snapshot", "on");
1268
    }
1269
    return 0;
1270
}
1271

    
1272
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1273
{
1274
    boot_set_handler = func;
1275
    boot_set_opaque = opaque;
1276
}
1277

    
1278
int qemu_boot_set(const char *boot_devices)
1279
{
1280
    if (!boot_set_handler) {
1281
        return -EINVAL;
1282
    }
1283
    return boot_set_handler(boot_set_opaque, boot_devices);
1284
}
1285

    
1286
static int parse_bootdevices(char *devices)
1287
{
1288
    /* We just do some generic consistency checks */
1289
    const char *p;
1290
    int bitmap = 0;
1291

    
1292
    for (p = devices; *p != '\0'; p++) {
1293
        /* Allowed boot devices are:
1294
         * a-b: floppy disk drives
1295
         * c-f: IDE disk drives
1296
         * g-m: machine implementation dependant drives
1297
         * n-p: network devices
1298
         * It's up to each machine implementation to check if the given boot
1299
         * devices match the actual hardware implementation and firmware
1300
         * features.
1301
         */
1302
        if (*p < 'a' || *p > 'p') {
1303
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
1304
            exit(1);
1305
        }
1306
        if (bitmap & (1 << (*p - 'a'))) {
1307
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1308
            exit(1);
1309
        }
1310
        bitmap |= 1 << (*p - 'a');
1311
    }
1312
    return bitmap;
1313
}
1314

    
1315
static void restore_boot_devices(void *opaque)
1316
{
1317
    char *standard_boot_devices = opaque;
1318

    
1319
    qemu_boot_set(standard_boot_devices);
1320

    
1321
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1322
    qemu_free(standard_boot_devices);
1323
}
1324

    
1325
static void numa_add(const char *optarg)
1326
{
1327
    char option[128];
1328
    char *endptr;
1329
    unsigned long long value, endvalue;
1330
    int nodenr;
1331

    
1332
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
1333
    if (!strcmp(option, "node")) {
1334
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1335
            nodenr = nb_numa_nodes;
1336
        } else {
1337
            nodenr = strtoull(option, NULL, 10);
1338
        }
1339

    
1340
        if (get_param_value(option, 128, "mem", optarg) == 0) {
1341
            node_mem[nodenr] = 0;
1342
        } else {
1343
            value = strtoull(option, &endptr, 0);
1344
            switch (*endptr) {
1345
            case 0: case 'M': case 'm':
1346
                value <<= 20;
1347
                break;
1348
            case 'G': case 'g':
1349
                value <<= 30;
1350
                break;
1351
            }
1352
            node_mem[nodenr] = value;
1353
        }
1354
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
1355
            node_cpumask[nodenr] = 0;
1356
        } else {
1357
            value = strtoull(option, &endptr, 10);
1358
            if (value >= 64) {
1359
                value = 63;
1360
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1361
            } else {
1362
                if (*endptr == '-') {
1363
                    endvalue = strtoull(endptr+1, &endptr, 10);
1364
                    if (endvalue >= 63) {
1365
                        endvalue = 62;
1366
                        fprintf(stderr,
1367
                            "only 63 CPUs in NUMA mode supported.\n");
1368
                    }
1369
                    value = (2ULL << endvalue) - (1ULL << value);
1370
                } else {
1371
                    value = 1ULL << value;
1372
                }
1373
            }
1374
            node_cpumask[nodenr] = value;
1375
        }
1376
        nb_numa_nodes++;
1377
    }
1378
    return;
1379
}
1380

    
1381
static void smp_parse(const char *optarg)
1382
{
1383
    int smp, sockets = 0, threads = 0, cores = 0;
1384
    char *endptr;
1385
    char option[128];
1386

    
1387
    smp = strtoul(optarg, &endptr, 10);
1388
    if (endptr != optarg) {
1389
        if (*endptr == ',') {
1390
            endptr++;
1391
        }
1392
    }
1393
    if (get_param_value(option, 128, "sockets", endptr) != 0)
1394
        sockets = strtoull(option, NULL, 10);
1395
    if (get_param_value(option, 128, "cores", endptr) != 0)
1396
        cores = strtoull(option, NULL, 10);
1397
    if (get_param_value(option, 128, "threads", endptr) != 0)
1398
        threads = strtoull(option, NULL, 10);
1399
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1400
        max_cpus = strtoull(option, NULL, 10);
1401

    
1402
    /* compute missing values, prefer sockets over cores over threads */
1403
    if (smp == 0 || sockets == 0) {
1404
        sockets = sockets > 0 ? sockets : 1;
1405
        cores = cores > 0 ? cores : 1;
1406
        threads = threads > 0 ? threads : 1;
1407
        if (smp == 0) {
1408
            smp = cores * threads * sockets;
1409
        }
1410
    } else {
1411
        if (cores == 0) {
1412
            threads = threads > 0 ? threads : 1;
1413
            cores = smp / (sockets * threads);
1414
        } else {
1415
            if (sockets) {
1416
                threads = smp / (cores * sockets);
1417
            }
1418
        }
1419
    }
1420
    smp_cpus = smp;
1421
    smp_cores = cores > 0 ? cores : 1;
1422
    smp_threads = threads > 0 ? threads : 1;
1423
    if (max_cpus == 0)
1424
        max_cpus = smp_cpus;
1425
}
1426

    
1427
/***********************************************************/
1428
/* USB devices */
1429

    
1430
static int usb_device_add(const char *devname, int is_hotplug)
1431
{
1432
    const char *p;
1433
    USBDevice *dev = NULL;
1434

    
1435
    if (!usb_enabled)
1436
        return -1;
1437

    
1438
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1439
    dev = usbdevice_create(devname);
1440
    if (dev)
1441
        goto done;
1442

    
1443
    /* the other ones */
1444
    if (strstart(devname, "host:", &p)) {
1445
        dev = usb_host_device_open(p);
1446
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1447
        dev = usb_bt_init(devname[2] ? hci_init(p) :
1448
                        bt_new_hci(qemu_find_bt_vlan(0)));
1449
    } else {
1450
        return -1;
1451
    }
1452
    if (!dev)
1453
        return -1;
1454

    
1455
done:
1456
    return 0;
1457
}
1458

    
1459
static int usb_device_del(const char *devname)
1460
{
1461
    int bus_num, addr;
1462
    const char *p;
1463

    
1464
    if (strstart(devname, "host:", &p))
1465
        return usb_host_device_close(p);
1466

    
1467
    if (!usb_enabled)
1468
        return -1;
1469

    
1470
    p = strchr(devname, '.');
1471
    if (!p)
1472
        return -1;
1473
    bus_num = strtoul(devname, NULL, 0);
1474
    addr = strtoul(p + 1, NULL, 0);
1475

    
1476
    return usb_device_delete_addr(bus_num, addr);
1477
}
1478

    
1479
static int usb_parse(const char *cmdline)
1480
{
1481
    int r;
1482
    r = usb_device_add(cmdline, 0);
1483
    if (r < 0) {
1484
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1485
    }
1486
    return r;
1487
}
1488

    
1489
void do_usb_add(Monitor *mon, const QDict *qdict)
1490
{
1491
    const char *devname = qdict_get_str(qdict, "devname");
1492
    if (usb_device_add(devname, 1) < 0) {
1493
        error_report("could not add USB device '%s'", devname);
1494
    }
1495
}
1496

    
1497
void do_usb_del(Monitor *mon, const QDict *qdict)
1498
{
1499
    const char *devname = qdict_get_str(qdict, "devname");
1500
    if (usb_device_del(devname) < 0) {
1501
        error_report("could not delete USB device '%s'", devname);
1502
    }
1503
}
1504

    
1505
/***********************************************************/
1506
/* PCMCIA/Cardbus */
1507

    
1508
static struct pcmcia_socket_entry_s {
1509
    PCMCIASocket *socket;
1510
    struct pcmcia_socket_entry_s *next;
1511
} *pcmcia_sockets = 0;
1512

    
1513
void pcmcia_socket_register(PCMCIASocket *socket)
1514
{
1515
    struct pcmcia_socket_entry_s *entry;
1516

    
1517
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1518
    entry->socket = socket;
1519
    entry->next = pcmcia_sockets;
1520
    pcmcia_sockets = entry;
1521
}
1522

    
1523
void pcmcia_socket_unregister(PCMCIASocket *socket)
1524
{
1525
    struct pcmcia_socket_entry_s *entry, **ptr;
1526

    
1527
    ptr = &pcmcia_sockets;
1528
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1529
        if (entry->socket == socket) {
1530
            *ptr = entry->next;
1531
            qemu_free(entry);
1532
        }
1533
}
1534

    
1535
void pcmcia_info(Monitor *mon)
1536
{
1537
    struct pcmcia_socket_entry_s *iter;
1538

    
1539
    if (!pcmcia_sockets)
1540
        monitor_printf(mon, "No PCMCIA sockets\n");
1541

    
1542
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1543
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1544
                       iter->socket->attached ? iter->socket->card_string :
1545
                       "Empty");
1546
}
1547

    
1548
/***********************************************************/
1549
/* I/O handling */
1550

    
1551
typedef struct IOHandlerRecord {
1552
    int fd;
1553
    IOCanReadHandler *fd_read_poll;
1554
    IOHandler *fd_read;
1555
    IOHandler *fd_write;
1556
    int deleted;
1557
    void *opaque;
1558
    /* temporary data */
1559
    struct pollfd *ufd;
1560
    QLIST_ENTRY(IOHandlerRecord) next;
1561
} IOHandlerRecord;
1562

    
1563
static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1564
    QLIST_HEAD_INITIALIZER(io_handlers);
1565

    
1566

    
1567
/* XXX: fd_read_poll should be suppressed, but an API change is
1568
   necessary in the character devices to suppress fd_can_read(). */
1569
int qemu_set_fd_handler2(int fd,
1570
                         IOCanReadHandler *fd_read_poll,
1571
                         IOHandler *fd_read,
1572
                         IOHandler *fd_write,
1573
                         void *opaque)
1574
{
1575
    IOHandlerRecord *ioh;
1576

    
1577
    if (!fd_read && !fd_write) {
1578
        QLIST_FOREACH(ioh, &io_handlers, next) {
1579
            if (ioh->fd == fd) {
1580
                ioh->deleted = 1;
1581
                break;
1582
            }
1583
        }
1584
    } else {
1585
        QLIST_FOREACH(ioh, &io_handlers, next) {
1586
            if (ioh->fd == fd)
1587
                goto found;
1588
        }
1589
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1590
        QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1591
    found:
1592
        ioh->fd = fd;
1593
        ioh->fd_read_poll = fd_read_poll;
1594
        ioh->fd_read = fd_read;
1595
        ioh->fd_write = fd_write;
1596
        ioh->opaque = opaque;
1597
        ioh->deleted = 0;
1598
    }
1599
    return 0;
1600
}
1601

    
1602
int qemu_set_fd_handler(int fd,
1603
                        IOHandler *fd_read,
1604
                        IOHandler *fd_write,
1605
                        void *opaque)
1606
{
1607
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1608
}
1609

    
1610
#ifdef _WIN32
1611
/***********************************************************/
1612
/* Polling handling */
1613

    
1614
typedef struct PollingEntry {
1615
    PollingFunc *func;
1616
    void *opaque;
1617
    struct PollingEntry *next;
1618
} PollingEntry;
1619

    
1620
static PollingEntry *first_polling_entry;
1621

    
1622
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1623
{
1624
    PollingEntry **ppe, *pe;
1625
    pe = qemu_mallocz(sizeof(PollingEntry));
1626
    pe->func = func;
1627
    pe->opaque = opaque;
1628
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1629
    *ppe = pe;
1630
    return 0;
1631
}
1632

    
1633
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1634
{
1635
    PollingEntry **ppe, *pe;
1636
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1637
        pe = *ppe;
1638
        if (pe->func == func && pe->opaque == opaque) {
1639
            *ppe = pe->next;
1640
            qemu_free(pe);
1641
            break;
1642
        }
1643
    }
1644
}
1645

    
1646
/***********************************************************/
1647
/* Wait objects support */
1648
typedef struct WaitObjects {
1649
    int num;
1650
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1651
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1652
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1653
} WaitObjects;
1654

    
1655
static WaitObjects wait_objects = {0};
1656

    
1657
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1658
{
1659
    WaitObjects *w = &wait_objects;
1660

    
1661
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
1662
        return -1;
1663
    w->events[w->num] = handle;
1664
    w->func[w->num] = func;
1665
    w->opaque[w->num] = opaque;
1666
    w->num++;
1667
    return 0;
1668
}
1669

    
1670
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1671
{
1672
    int i, found;
1673
    WaitObjects *w = &wait_objects;
1674

    
1675
    found = 0;
1676
    for (i = 0; i < w->num; i++) {
1677
        if (w->events[i] == handle)
1678
            found = 1;
1679
        if (found) {
1680
            w->events[i] = w->events[i + 1];
1681
            w->func[i] = w->func[i + 1];
1682
            w->opaque[i] = w->opaque[i + 1];
1683
        }
1684
    }
1685
    if (found)
1686
        w->num--;
1687
}
1688
#endif
1689

    
1690
/***********************************************************/
1691
/* ram save/restore */
1692

    
1693
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
1694
#define RAM_SAVE_FLAG_COMPRESS        0x02
1695
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
1696
#define RAM_SAVE_FLAG_PAGE        0x08
1697
#define RAM_SAVE_FLAG_EOS        0x10
1698

    
1699
static int is_dup_page(uint8_t *page, uint8_t ch)
1700
{
1701
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1702
    uint32_t *array = (uint32_t *)page;
1703
    int i;
1704

    
1705
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1706
        if (array[i] != val)
1707
            return 0;
1708
    }
1709

    
1710
    return 1;
1711
}
1712

    
1713
static int ram_save_block(QEMUFile *f)
1714
{
1715
    static ram_addr_t current_addr = 0;
1716
    ram_addr_t saved_addr = current_addr;
1717
    ram_addr_t addr = 0;
1718
    int found = 0;
1719

    
1720
    while (addr < last_ram_offset) {
1721
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1722
            uint8_t *p;
1723

    
1724
            cpu_physical_memory_reset_dirty(current_addr,
1725
                                            current_addr + TARGET_PAGE_SIZE,
1726
                                            MIGRATION_DIRTY_FLAG);
1727

    
1728
            p = qemu_get_ram_ptr(current_addr);
1729

    
1730
            if (is_dup_page(p, *p)) {
1731
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1732
                qemu_put_byte(f, *p);
1733
            } else {
1734
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1735
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1736
            }
1737

    
1738
            found = 1;
1739
            break;
1740
        }
1741
        addr += TARGET_PAGE_SIZE;
1742
        current_addr = (saved_addr + addr) % last_ram_offset;
1743
    }
1744

    
1745
    return found;
1746
}
1747

    
1748
static uint64_t bytes_transferred;
1749

    
1750
static ram_addr_t ram_save_remaining(void)
1751
{
1752
    ram_addr_t addr;
1753
    ram_addr_t count = 0;
1754

    
1755
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1756
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1757
            count++;
1758
    }
1759

    
1760
    return count;
1761
}
1762

    
1763
uint64_t ram_bytes_remaining(void)
1764
{
1765
    return ram_save_remaining() * TARGET_PAGE_SIZE;
1766
}
1767

    
1768
uint64_t ram_bytes_transferred(void)
1769
{
1770
    return bytes_transferred;
1771
}
1772

    
1773
uint64_t ram_bytes_total(void)
1774
{
1775
    return last_ram_offset;
1776
}
1777

    
1778
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1779
{
1780
    ram_addr_t addr;
1781
    uint64_t bytes_transferred_last;
1782
    double bwidth = 0;
1783
    uint64_t expected_time = 0;
1784

    
1785
    if (stage < 0) {
1786
        cpu_physical_memory_set_dirty_tracking(0);
1787
        return 0;
1788
    }
1789

    
1790
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1791
        qemu_file_set_error(f);
1792
        return 0;
1793
    }
1794

    
1795
    if (stage == 1) {
1796
        bytes_transferred = 0;
1797

    
1798
        /* Make sure all dirty bits are set */
1799
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1800
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1801
                cpu_physical_memory_set_dirty(addr);
1802
        }
1803

    
1804
        /* Enable dirty memory tracking */
1805
        cpu_physical_memory_set_dirty_tracking(1);
1806

    
1807
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1808
    }
1809

    
1810
    bytes_transferred_last = bytes_transferred;
1811
    bwidth = qemu_get_clock_ns(rt_clock);
1812

    
1813
    while (!qemu_file_rate_limit(f)) {
1814
        int ret;
1815

    
1816
        ret = ram_save_block(f);
1817
        bytes_transferred += ret * TARGET_PAGE_SIZE;
1818
        if (ret == 0) /* no more blocks */
1819
            break;
1820
    }
1821

    
1822
    bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1823
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1824

    
1825
    /* if we haven't transferred anything this round, force expected_time to a
1826
     * a very high value, but without crashing */
1827
    if (bwidth == 0)
1828
        bwidth = 0.000001;
1829

    
1830
    /* try transferring iterative blocks of memory */
1831
    if (stage == 3) {
1832
        /* flush all remaining blocks regardless of rate limiting */
1833
        while (ram_save_block(f) != 0) {
1834
            bytes_transferred += TARGET_PAGE_SIZE;
1835
        }
1836
        cpu_physical_memory_set_dirty_tracking(0);
1837
    }
1838

    
1839
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1840

    
1841
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1842

    
1843
    return (stage == 2) && (expected_time <= migrate_max_downtime());
1844
}
1845

    
1846
static int ram_load(QEMUFile *f, void *opaque, int version_id)
1847
{
1848
    ram_addr_t addr;
1849
    int flags;
1850

    
1851
    if (version_id != 3)
1852
        return -EINVAL;
1853

    
1854
    do {
1855
        addr = qemu_get_be64(f);
1856

    
1857
        flags = addr & ~TARGET_PAGE_MASK;
1858
        addr &= TARGET_PAGE_MASK;
1859

    
1860
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1861
            if (addr != last_ram_offset)
1862
                return -EINVAL;
1863
        }
1864

    
1865
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
1866
            uint8_t ch = qemu_get_byte(f);
1867
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1868
#ifndef _WIN32
1869
            if (ch == 0 &&
1870
                (!kvm_enabled() || kvm_has_sync_mmu())) {
1871
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1872
            }
1873
#endif
1874
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
1875
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1876
        }
1877
        if (qemu_file_has_error(f)) {
1878
            return -EIO;
1879
        }
1880
    } while (!(flags & RAM_SAVE_FLAG_EOS));
1881

    
1882
    return 0;
1883
}
1884

    
1885
void qemu_service_io(void)
1886
{
1887
    qemu_notify_event();
1888
}
1889

    
1890
/***********************************************************/
1891
/* machine registration */
1892

    
1893
static QEMUMachine *first_machine = NULL;
1894
QEMUMachine *current_machine = NULL;
1895

    
1896
int qemu_register_machine(QEMUMachine *m)
1897
{
1898
    QEMUMachine **pm;
1899
    pm = &first_machine;
1900
    while (*pm != NULL)
1901
        pm = &(*pm)->next;
1902
    m->next = NULL;
1903
    *pm = m;
1904
    return 0;
1905
}
1906

    
1907
static QEMUMachine *find_machine(const char *name)
1908
{
1909
    QEMUMachine *m;
1910

    
1911
    for(m = first_machine; m != NULL; m = m->next) {
1912
        if (!strcmp(m->name, name))
1913
            return m;
1914
        if (m->alias && !strcmp(m->alias, name))
1915
            return m;
1916
    }
1917
    return NULL;
1918
}
1919

    
1920
static QEMUMachine *find_default_machine(void)
1921
{
1922
    QEMUMachine *m;
1923

    
1924
    for(m = first_machine; m != NULL; m = m->next) {
1925
        if (m->is_default) {
1926
            return m;
1927
        }
1928
    }
1929
    return NULL;
1930
}
1931

    
1932
/***********************************************************/
1933
/* main execution loop */
1934

    
1935
static void gui_update(void *opaque)
1936
{
1937
    uint64_t interval = GUI_REFRESH_INTERVAL;
1938
    DisplayState *ds = opaque;
1939
    DisplayChangeListener *dcl = ds->listeners;
1940

    
1941
    qemu_flush_coalesced_mmio_buffer();
1942
    dpy_refresh(ds);
1943

    
1944
    while (dcl != NULL) {
1945
        if (dcl->gui_timer_interval &&
1946
            dcl->gui_timer_interval < interval)
1947
            interval = dcl->gui_timer_interval;
1948
        dcl = dcl->next;
1949
    }
1950
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1951
}
1952

    
1953
static void nographic_update(void *opaque)
1954
{
1955
    uint64_t interval = GUI_REFRESH_INTERVAL;
1956

    
1957
    qemu_flush_coalesced_mmio_buffer();
1958
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1959
}
1960

    
1961
void cpu_synchronize_all_states(void)
1962
{
1963
    CPUState *cpu;
1964

    
1965
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1966
        cpu_synchronize_state(cpu);
1967
    }
1968
}
1969

    
1970
void cpu_synchronize_all_post_reset(void)
1971
{
1972
    CPUState *cpu;
1973

    
1974
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1975
        cpu_synchronize_post_reset(cpu);
1976
    }
1977
}
1978

    
1979
void cpu_synchronize_all_post_init(void)
1980
{
1981
    CPUState *cpu;
1982

    
1983
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1984
        cpu_synchronize_post_init(cpu);
1985
    }
1986
}
1987

    
1988
struct vm_change_state_entry {
1989
    VMChangeStateHandler *cb;
1990
    void *opaque;
1991
    QLIST_ENTRY (vm_change_state_entry) entries;
1992
};
1993

    
1994
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1995

    
1996
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1997
                                                     void *opaque)
1998
{
1999
    VMChangeStateEntry *e;
2000

    
2001
    e = qemu_mallocz(sizeof (*e));
2002

    
2003
    e->cb = cb;
2004
    e->opaque = opaque;
2005
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2006
    return e;
2007
}
2008

    
2009
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2010
{
2011
    QLIST_REMOVE (e, entries);
2012
    qemu_free (e);
2013
}
2014

    
2015
static void vm_state_notify(int running, int reason)
2016
{
2017
    VMChangeStateEntry *e;
2018

    
2019
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2020
        e->cb(e->opaque, running, reason);
2021
    }
2022
}
2023

    
2024
static void resume_all_vcpus(void);
2025
static void pause_all_vcpus(void);
2026

    
2027
void vm_start(void)
2028
{
2029
    if (!vm_running) {
2030
        cpu_enable_ticks();
2031
        vm_running = 1;
2032
        vm_state_notify(1, 0);
2033
        resume_all_vcpus();
2034
    }
2035
}
2036

    
2037
/* reset/shutdown handler */
2038

    
2039
typedef struct QEMUResetEntry {
2040
    QTAILQ_ENTRY(QEMUResetEntry) entry;
2041
    QEMUResetHandler *func;
2042
    void *opaque;
2043
} QEMUResetEntry;
2044

    
2045
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2046
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
2047
static int reset_requested;
2048
static int shutdown_requested;
2049
static int powerdown_requested;
2050
static int debug_requested;
2051
static int vmstop_requested;
2052

    
2053
int qemu_shutdown_requested(void)
2054
{
2055
    int r = shutdown_requested;
2056
    shutdown_requested = 0;
2057
    return r;
2058
}
2059

    
2060
int qemu_reset_requested(void)
2061
{
2062
    int r = reset_requested;
2063
    reset_requested = 0;
2064
    return r;
2065
}
2066

    
2067
int qemu_powerdown_requested(void)
2068
{
2069
    int r = powerdown_requested;
2070
    powerdown_requested = 0;
2071
    return r;
2072
}
2073

    
2074
static int qemu_debug_requested(void)
2075
{
2076
    int r = debug_requested;
2077
    debug_requested = 0;
2078
    return r;
2079
}
2080

    
2081
static int qemu_vmstop_requested(void)
2082
{
2083
    int r = vmstop_requested;
2084
    vmstop_requested = 0;
2085
    return r;
2086
}
2087

    
2088
static void do_vm_stop(int reason)
2089
{
2090
    if (vm_running) {
2091
        cpu_disable_ticks();
2092
        vm_running = 0;
2093
        pause_all_vcpus();
2094
        vm_state_notify(0, reason);
2095
        monitor_protocol_event(QEVENT_STOP, NULL);
2096
    }
2097
}
2098

    
2099
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2100
{
2101
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2102

    
2103
    re->func = func;
2104
    re->opaque = opaque;
2105
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2106
}
2107

    
2108
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2109
{
2110
    QEMUResetEntry *re;
2111

    
2112
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
2113
        if (re->func == func && re->opaque == opaque) {
2114
            QTAILQ_REMOVE(&reset_handlers, re, entry);
2115
            qemu_free(re);
2116
            return;
2117
        }
2118
    }
2119
}
2120

    
2121
void qemu_system_reset(void)
2122
{
2123
    QEMUResetEntry *re, *nre;
2124

    
2125
    /* reset all devices */
2126
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2127
        re->func(re->opaque);
2128
    }
2129
    monitor_protocol_event(QEVENT_RESET, NULL);
2130
    cpu_synchronize_all_post_reset();
2131
}
2132

    
2133
void qemu_system_reset_request(void)
2134
{
2135
    if (no_reboot) {
2136
        shutdown_requested = 1;
2137
    } else {
2138
        reset_requested = 1;
2139
    }
2140
    qemu_notify_event();
2141
}
2142

    
2143
void qemu_system_shutdown_request(void)
2144
{
2145
    shutdown_requested = 1;
2146
    qemu_notify_event();
2147
}
2148

    
2149
void qemu_system_powerdown_request(void)
2150
{
2151
    powerdown_requested = 1;
2152
    qemu_notify_event();
2153
}
2154

    
2155
static int cpu_can_run(CPUState *env)
2156
{
2157
    if (env->stop)
2158
        return 0;
2159
    if (env->stopped)
2160
        return 0;
2161
    if (!vm_running)
2162
        return 0;
2163
    return 1;
2164
}
2165

    
2166
static int cpu_has_work(CPUState *env)
2167
{
2168
    if (env->stop)
2169
        return 1;
2170
    if (env->stopped)
2171
        return 0;
2172
    if (!env->halted)
2173
        return 1;
2174
    if (qemu_cpu_has_work(env))
2175
        return 1;
2176
    return 0;
2177
}
2178

    
2179
static int tcg_has_work(void)
2180
{
2181
    CPUState *env;
2182

    
2183
    for (env = first_cpu; env != NULL; env = env->next_cpu)
2184
        if (cpu_has_work(env))
2185
            return 1;
2186
    return 0;
2187
}
2188

    
2189
#ifndef _WIN32
2190
static int io_thread_fd = -1;
2191

    
2192
static void qemu_event_increment(void)
2193
{
2194
    /* Write 8 bytes to be compatible with eventfd.  */
2195
    static uint64_t val = 1;
2196
    ssize_t ret;
2197

    
2198
    if (io_thread_fd == -1)
2199
        return;
2200

    
2201
    do {
2202
        ret = write(io_thread_fd, &val, sizeof(val));
2203
    } while (ret < 0 && errno == EINTR);
2204

    
2205
    /* EAGAIN is fine, a read must be pending.  */
2206
    if (ret < 0 && errno != EAGAIN) {
2207
        fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2208
                strerror(errno));
2209
        exit (1);
2210
    }
2211
}
2212

    
2213
static void qemu_event_read(void *opaque)
2214
{
2215
    int fd = (unsigned long)opaque;
2216
    ssize_t len;
2217
    char buffer[512];
2218

    
2219
    /* Drain the notify pipe.  For eventfd, only 8 bytes will be read.  */
2220
    do {
2221
        len = read(fd, buffer, sizeof(buffer));
2222
    } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2223
}
2224

    
2225
static int qemu_event_init(void)
2226
{
2227
    int err;
2228
    int fds[2];
2229

    
2230
    err = qemu_eventfd(fds);
2231
    if (err == -1)
2232
        return -errno;
2233

    
2234
    err = fcntl_setfl(fds[0], O_NONBLOCK);
2235
    if (err < 0)
2236
        goto fail;
2237

    
2238
    err = fcntl_setfl(fds[1], O_NONBLOCK);
2239
    if (err < 0)
2240
        goto fail;
2241

    
2242
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2243
                         (void *)(unsigned long)fds[0]);
2244

    
2245
    io_thread_fd = fds[1];
2246
    return 0;
2247

    
2248
fail:
2249
    close(fds[0]);
2250
    close(fds[1]);
2251
    return err;
2252
}
2253
#else
2254
HANDLE qemu_event_handle;
2255

    
2256
static void dummy_event_handler(void *opaque)
2257
{
2258
}
2259

    
2260
static int qemu_event_init(void)
2261
{
2262
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2263
    if (!qemu_event_handle) {
2264
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2265
        return -1;
2266
    }
2267
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2268
    return 0;
2269
}
2270

    
2271
static void qemu_event_increment(void)
2272
{
2273
    if (!SetEvent(qemu_event_handle)) {
2274
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2275
                GetLastError());
2276
        exit (1);
2277
    }
2278
}
2279
#endif
2280

    
2281
#ifndef CONFIG_IOTHREAD
2282
static int qemu_init_main_loop(void)
2283
{
2284
    return qemu_event_init();
2285
}
2286

    
2287
void qemu_init_vcpu(void *_env)
2288
{
2289
    CPUState *env = _env;
2290

    
2291
    env->nr_cores = smp_cores;
2292
    env->nr_threads = smp_threads;
2293
    if (kvm_enabled())
2294
        kvm_init_vcpu(env);
2295
    return;
2296
}
2297

    
2298
int qemu_cpu_self(void *env)
2299
{
2300
    return 1;
2301
}
2302

    
2303
static void resume_all_vcpus(void)
2304
{
2305
}
2306

    
2307
static void pause_all_vcpus(void)
2308
{
2309
}
2310

    
2311
void qemu_cpu_kick(void *env)
2312
{
2313
    return;
2314
}
2315

    
2316
void qemu_notify_event(void)
2317
{
2318
    CPUState *env = cpu_single_env;
2319

    
2320
    qemu_event_increment ();
2321
    if (env) {
2322
        cpu_exit(env);
2323
    }
2324
    if (next_cpu && env != next_cpu) {
2325
        cpu_exit(next_cpu);
2326
    }
2327
}
2328

    
2329
void qemu_mutex_lock_iothread(void) {}
2330
void qemu_mutex_unlock_iothread(void) {}
2331

    
2332
void vm_stop(int reason)
2333
{
2334
    do_vm_stop(reason);
2335
}
2336

    
2337
#else /* CONFIG_IOTHREAD */
2338

    
2339
#include "qemu-thread.h"
2340

    
2341
QemuMutex qemu_global_mutex;
2342
static QemuMutex qemu_fair_mutex;
2343

    
2344
static QemuThread io_thread;
2345

    
2346
static QemuThread *tcg_cpu_thread;
2347
static QemuCond *tcg_halt_cond;
2348

    
2349
static int qemu_system_ready;
2350
/* cpu creation */
2351
static QemuCond qemu_cpu_cond;
2352
/* system init */
2353
static QemuCond qemu_system_cond;
2354
static QemuCond qemu_pause_cond;
2355

    
2356
static void tcg_block_io_signals(void);
2357
static void kvm_block_io_signals(CPUState *env);
2358
static void unblock_io_signals(void);
2359

    
2360
static int qemu_init_main_loop(void)
2361
{
2362
    int ret;
2363

    
2364
    ret = qemu_event_init();
2365
    if (ret)
2366
        return ret;
2367

    
2368
    qemu_cond_init(&qemu_pause_cond);
2369
    qemu_mutex_init(&qemu_fair_mutex);
2370
    qemu_mutex_init(&qemu_global_mutex);
2371
    qemu_mutex_lock(&qemu_global_mutex);
2372

    
2373
    unblock_io_signals();
2374
    qemu_thread_self(&io_thread);
2375

    
2376
    return 0;
2377
}
2378

    
2379
static void qemu_wait_io_event_common(CPUState *env)
2380
{
2381
    if (env->stop) {
2382
        env->stop = 0;
2383
        env->stopped = 1;
2384
        qemu_cond_signal(&qemu_pause_cond);
2385
    }
2386
}
2387

    
2388
static void qemu_wait_io_event(CPUState *env)
2389
{
2390
    while (!tcg_has_work())
2391
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2392

    
2393
    qemu_mutex_unlock(&qemu_global_mutex);
2394

    
2395
    /*
2396
     * Users of qemu_global_mutex can be starved, having no chance
2397
     * to acquire it since this path will get to it first.
2398
     * So use another lock to provide fairness.
2399
     */
2400
    qemu_mutex_lock(&qemu_fair_mutex);
2401
    qemu_mutex_unlock(&qemu_fair_mutex);
2402

    
2403
    qemu_mutex_lock(&qemu_global_mutex);
2404
    qemu_wait_io_event_common(env);
2405
}
2406

    
2407
static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2408
{
2409
    struct timespec ts;
2410
    int r, e;
2411
    siginfo_t siginfo;
2412
    sigset_t waitset;
2413

    
2414
    ts.tv_sec = timeout / 1000;
2415
    ts.tv_nsec = (timeout % 1000) * 1000000;
2416

    
2417
    sigemptyset(&waitset);
2418
    sigaddset(&waitset, SIG_IPI);
2419

    
2420
    qemu_mutex_unlock(&qemu_global_mutex);
2421
    r = sigtimedwait(&waitset, &siginfo, &ts);
2422
    e = errno;
2423
    qemu_mutex_lock(&qemu_global_mutex);
2424

    
2425
    if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2426
        fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2427
        exit(1);
2428
    }
2429
}
2430

    
2431
static void qemu_kvm_wait_io_event(CPUState *env)
2432
{
2433
    while (!cpu_has_work(env))
2434
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2435

    
2436
    qemu_kvm_eat_signal(env, 0);
2437
    qemu_wait_io_event_common(env);
2438
}
2439

    
2440
static int qemu_cpu_exec(CPUState *env);
2441

    
2442
static void *kvm_cpu_thread_fn(void *arg)
2443
{
2444
    CPUState *env = arg;
2445

    
2446
    qemu_thread_self(env->thread);
2447
    if (kvm_enabled())
2448
        kvm_init_vcpu(env);
2449

    
2450
    kvm_block_io_signals(env);
2451

    
2452
    /* signal CPU creation */
2453
    qemu_mutex_lock(&qemu_global_mutex);
2454
    env->created = 1;
2455
    qemu_cond_signal(&qemu_cpu_cond);
2456

    
2457
    /* and wait for machine initialization */
2458
    while (!qemu_system_ready)
2459
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2460

    
2461
    while (1) {
2462
        if (cpu_can_run(env))
2463
            qemu_cpu_exec(env);
2464
        qemu_kvm_wait_io_event(env);
2465
    }
2466

    
2467
    return NULL;
2468
}
2469

    
2470
static bool tcg_cpu_exec(void);
2471

    
2472
static void *tcg_cpu_thread_fn(void *arg)
2473
{
2474
    CPUState *env = arg;
2475

    
2476
    tcg_block_io_signals();
2477
    qemu_thread_self(env->thread);
2478

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

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

    
2489
    while (1) {
2490
        tcg_cpu_exec();
2491
        qemu_wait_io_event(cur_cpu);
2492
    }
2493

    
2494
    return NULL;
2495
}
2496

    
2497
void qemu_cpu_kick(void *_env)
2498
{
2499
    CPUState *env = _env;
2500
    qemu_cond_broadcast(env->halt_cond);
2501
    if (kvm_enabled())
2502
        qemu_thread_signal(env->thread, SIG_IPI);
2503
}
2504

    
2505
int qemu_cpu_self(void *_env)
2506
{
2507
    CPUState *env = _env;
2508
    QemuThread this;
2509
 
2510
    qemu_thread_self(&this);
2511
 
2512
    return qemu_thread_equal(&this, env->thread);
2513
}
2514

    
2515
static void cpu_signal(int sig)
2516
{
2517
    if (cpu_single_env)
2518
        cpu_exit(cpu_single_env);
2519
}
2520

    
2521
static void tcg_block_io_signals(void)
2522
{
2523
    sigset_t set;
2524
    struct sigaction sigact;
2525

    
2526
    sigemptyset(&set);
2527
    sigaddset(&set, SIGUSR2);
2528
    sigaddset(&set, SIGIO);
2529
    sigaddset(&set, SIGALRM);
2530
    sigaddset(&set, SIGCHLD);
2531
    pthread_sigmask(SIG_BLOCK, &set, NULL);
2532

    
2533
    sigemptyset(&set);
2534
    sigaddset(&set, SIG_IPI);
2535
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2536

    
2537
    memset(&sigact, 0, sizeof(sigact));
2538
    sigact.sa_handler = cpu_signal;
2539
    sigaction(SIG_IPI, &sigact, NULL);
2540
}
2541

    
2542
static void dummy_signal(int sig)
2543
{
2544
}
2545

    
2546
static void kvm_block_io_signals(CPUState *env)
2547
{
2548
    int r;
2549
    sigset_t set;
2550
    struct sigaction sigact;
2551

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

    
2560
    pthread_sigmask(SIG_BLOCK, NULL, &set);
2561
    sigdelset(&set, SIG_IPI);
2562

    
2563
    memset(&sigact, 0, sizeof(sigact));
2564
    sigact.sa_handler = dummy_signal;
2565
    sigaction(SIG_IPI, &sigact, NULL);
2566

    
2567
    r = kvm_set_signal_mask(env, &set);
2568
    if (r) {
2569
        fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2570
        exit(1);
2571
    }
2572
}
2573

    
2574
static void unblock_io_signals(void)
2575
{
2576
    sigset_t set;
2577

    
2578
    sigemptyset(&set);
2579
    sigaddset(&set, SIGUSR2);
2580
    sigaddset(&set, SIGIO);
2581
    sigaddset(&set, SIGALRM);
2582
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2583

    
2584
    sigemptyset(&set);
2585
    sigaddset(&set, SIG_IPI);
2586
    pthread_sigmask(SIG_BLOCK, &set, NULL);
2587
}
2588

    
2589
static void qemu_signal_lock(unsigned int msecs)
2590
{
2591
    qemu_mutex_lock(&qemu_fair_mutex);
2592

    
2593
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
2594
        qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2595
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2596
            break;
2597
    }
2598
    qemu_mutex_unlock(&qemu_fair_mutex);
2599
}
2600

    
2601
void qemu_mutex_lock_iothread(void)
2602
{
2603
    if (kvm_enabled()) {
2604
        qemu_mutex_lock(&qemu_fair_mutex);
2605
        qemu_mutex_lock(&qemu_global_mutex);
2606
        qemu_mutex_unlock(&qemu_fair_mutex);
2607
    } else
2608
        qemu_signal_lock(100);
2609
}
2610

    
2611
void qemu_mutex_unlock_iothread(void)
2612
{
2613
    qemu_mutex_unlock(&qemu_global_mutex);
2614
}
2615

    
2616
static int all_vcpus_paused(void)
2617
{
2618
    CPUState *penv = first_cpu;
2619

    
2620
    while (penv) {
2621
        if (!penv->stopped)
2622
            return 0;
2623
        penv = (CPUState *)penv->next_cpu;
2624
    }
2625

    
2626
    return 1;
2627
}
2628

    
2629
static void pause_all_vcpus(void)
2630
{
2631
    CPUState *penv = first_cpu;
2632

    
2633
    while (penv) {
2634
        penv->stop = 1;
2635
        qemu_thread_signal(penv->thread, SIG_IPI);
2636
        qemu_cpu_kick(penv);
2637
        penv = (CPUState *)penv->next_cpu;
2638
    }
2639

    
2640
    while (!all_vcpus_paused()) {
2641
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2642
        penv = first_cpu;
2643
        while (penv) {
2644
            qemu_thread_signal(penv->thread, SIG_IPI);
2645
            penv = (CPUState *)penv->next_cpu;
2646
        }
2647
    }
2648
}
2649

    
2650
static void resume_all_vcpus(void)
2651
{
2652
    CPUState *penv = first_cpu;
2653

    
2654
    while (penv) {
2655
        penv->stop = 0;
2656
        penv->stopped = 0;
2657
        qemu_thread_signal(penv->thread, SIG_IPI);
2658
        qemu_cpu_kick(penv);
2659
        penv = (CPUState *)penv->next_cpu;
2660
    }
2661
}
2662

    
2663
static void tcg_init_vcpu(void *_env)
2664
{
2665
    CPUState *env = _env;
2666
    /* share a single thread for all cpus with TCG */
2667
    if (!tcg_cpu_thread) {
2668
        env->thread = qemu_mallocz(sizeof(QemuThread));
2669
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2670
        qemu_cond_init(env->halt_cond);
2671
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2672
        while (env->created == 0)
2673
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2674
        tcg_cpu_thread = env->thread;
2675
        tcg_halt_cond = env->halt_cond;
2676
    } else {
2677
        env->thread = tcg_cpu_thread;
2678
        env->halt_cond = tcg_halt_cond;
2679
    }
2680
}
2681

    
2682
static void kvm_start_vcpu(CPUState *env)
2683
{
2684
    env->thread = qemu_mallocz(sizeof(QemuThread));
2685
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2686
    qemu_cond_init(env->halt_cond);
2687
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2688
    while (env->created == 0)
2689
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2690
}
2691

    
2692
void qemu_init_vcpu(void *_env)
2693
{
2694
    CPUState *env = _env;
2695

    
2696
    env->nr_cores = smp_cores;
2697
    env->nr_threads = smp_threads;
2698
    if (kvm_enabled())
2699
        kvm_start_vcpu(env);
2700
    else
2701
        tcg_init_vcpu(env);
2702
}
2703

    
2704
void qemu_notify_event(void)
2705
{
2706
    qemu_event_increment();
2707
}
2708

    
2709
static void qemu_system_vmstop_request(int reason)
2710
{
2711
    vmstop_requested = reason;
2712
    qemu_notify_event();
2713
}
2714

    
2715
void vm_stop(int reason)
2716
{
2717
    QemuThread me;
2718
    qemu_thread_self(&me);
2719

    
2720
    if (!qemu_thread_equal(&me, &io_thread)) {
2721
        qemu_system_vmstop_request(reason);
2722
        /*
2723
         * FIXME: should not return to device code in case
2724
         * vm_stop() has been requested.
2725
         */
2726
        if (cpu_single_env) {
2727
            cpu_exit(cpu_single_env);
2728
            cpu_single_env->stop = 1;
2729
        }
2730
        return;
2731
    }
2732
    do_vm_stop(reason);
2733
}
2734

    
2735
#endif
2736

    
2737

    
2738
#ifdef _WIN32
2739
static void host_main_loop_wait(int *timeout)
2740
{
2741
    int ret, ret2, i;
2742
    PollingEntry *pe;
2743

    
2744

    
2745
    /* XXX: need to suppress polling by better using win32 events */
2746
    ret = 0;
2747
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2748
        ret |= pe->func(pe->opaque);
2749
    }
2750
    if (ret == 0) {
2751
        int err;
2752
        WaitObjects *w = &wait_objects;
2753

    
2754
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2755
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2756
            if (w->func[ret - WAIT_OBJECT_0])
2757
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2758

    
2759
            /* Check for additional signaled events */
2760
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2761

    
2762
                /* Check if event is signaled */
2763
                ret2 = WaitForSingleObject(w->events[i], 0);
2764
                if(ret2 == WAIT_OBJECT_0) {
2765
                    if (w->func[i])
2766
                        w->func[i](w->opaque[i]);
2767
                } else if (ret2 == WAIT_TIMEOUT) {
2768
                } else {
2769
                    err = GetLastError();
2770
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2771
                }
2772
            }
2773
        } else if (ret == WAIT_TIMEOUT) {
2774
        } else {
2775
            err = GetLastError();
2776
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2777
        }
2778
    }
2779

    
2780
    *timeout = 0;
2781
}
2782
#else
2783
static void host_main_loop_wait(int *timeout)
2784
{
2785
}
2786
#endif
2787

    
2788
void main_loop_wait(int nonblocking)
2789
{
2790
    IOHandlerRecord *ioh;
2791
    fd_set rfds, wfds, xfds;
2792
    int ret, nfds;
2793
    struct timeval tv;
2794
    int timeout;
2795

    
2796
    if (nonblocking)
2797
        timeout = 0;
2798
    else {
2799
        timeout = qemu_calculate_timeout();
2800
        qemu_bh_update_timeout(&timeout);
2801
    }
2802

    
2803
    host_main_loop_wait(&timeout);
2804

    
2805
    /* poll any events */
2806
    /* XXX: separate device handlers from system ones */
2807
    nfds = -1;
2808
    FD_ZERO(&rfds);
2809
    FD_ZERO(&wfds);
2810
    FD_ZERO(&xfds);
2811
    QLIST_FOREACH(ioh, &io_handlers, next) {
2812
        if (ioh->deleted)
2813
            continue;
2814
        if (ioh->fd_read &&
2815
            (!ioh->fd_read_poll ||
2816
             ioh->fd_read_poll(ioh->opaque) != 0)) {
2817
            FD_SET(ioh->fd, &rfds);
2818
            if (ioh->fd > nfds)
2819
                nfds = ioh->fd;
2820
        }
2821
        if (ioh->fd_write) {
2822
            FD_SET(ioh->fd, &wfds);
2823
            if (ioh->fd > nfds)
2824
                nfds = ioh->fd;
2825
        }
2826
    }
2827

    
2828
    tv.tv_sec = timeout / 1000;
2829
    tv.tv_usec = (timeout % 1000) * 1000;
2830

    
2831
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2832

    
2833
    qemu_mutex_unlock_iothread();
2834
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2835
    qemu_mutex_lock_iothread();
2836
    if (ret > 0) {
2837
        IOHandlerRecord *pioh;
2838

    
2839
        QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
2840
            if (ioh->deleted) {
2841
                QLIST_REMOVE(ioh, next);
2842
                qemu_free(ioh);
2843
                continue;
2844
            }
2845
            if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2846
                ioh->fd_read(ioh->opaque);
2847
            }
2848
            if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2849
                ioh->fd_write(ioh->opaque);
2850
            }
2851
        }
2852
    }
2853

    
2854
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2855

    
2856
    qemu_run_all_timers();
2857

    
2858
    /* Check bottom-halves last in case any of the earlier events triggered
2859
       them.  */
2860
    qemu_bh_poll();
2861

    
2862
}
2863

    
2864
static int qemu_cpu_exec(CPUState *env)
2865
{
2866
    int ret;
2867
#ifdef CONFIG_PROFILER
2868
    int64_t ti;
2869
#endif
2870

    
2871
#ifdef CONFIG_PROFILER
2872
    ti = profile_getclock();
2873
#endif
2874
    if (use_icount) {
2875
        int64_t count;
2876
        int decr;
2877
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2878
        env->icount_decr.u16.low = 0;
2879
        env->icount_extra = 0;
2880
        count = qemu_icount_round (qemu_next_deadline());
2881
        qemu_icount += count;
2882
        decr = (count > 0xffff) ? 0xffff : count;
2883
        count -= decr;
2884
        env->icount_decr.u16.low = decr;
2885
        env->icount_extra = count;
2886
    }
2887
    ret = cpu_exec(env);
2888
#ifdef CONFIG_PROFILER
2889
    qemu_time += profile_getclock() - ti;
2890
#endif
2891
    if (use_icount) {
2892
        /* Fold pending instructions back into the
2893
           instruction counter, and clear the interrupt flag.  */
2894
        qemu_icount -= (env->icount_decr.u16.low
2895
                        + env->icount_extra);
2896
        env->icount_decr.u32 = 0;
2897
        env->icount_extra = 0;
2898
    }
2899
    return ret;
2900
}
2901

    
2902
static bool tcg_cpu_exec(void)
2903
{
2904
    int ret = 0;
2905

    
2906
    if (next_cpu == NULL)
2907
        next_cpu = first_cpu;
2908
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2909
        CPUState *env = cur_cpu = next_cpu;
2910

    
2911
        qemu_clock_enable(vm_clock,
2912
                          (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2913

    
2914
        if (qemu_alarm_pending())
2915
            break;
2916
        if (cpu_can_run(env))
2917
            ret = qemu_cpu_exec(env);
2918
        else if (env->stop)
2919
            break;
2920

    
2921
        if (ret == EXCP_DEBUG) {
2922
            gdb_set_stop_cpu(env);
2923
            debug_requested = EXCP_DEBUG;
2924
            break;
2925
        }
2926
    }
2927
    return tcg_has_work();
2928
}
2929

    
2930
static void set_numa_modes(void)
2931
{
2932
    CPUState *env;
2933
    int i;
2934

    
2935
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
2936
        for (i = 0; i < nb_numa_nodes; i++) {
2937
            if (node_cpumask[i] & (1 << env->cpu_index)) {
2938
                env->numa_node = i;
2939
            }
2940
        }
2941
    }
2942
}
2943

    
2944
static int vm_can_run(void)
2945
{
2946
    if (powerdown_requested)
2947
        return 0;
2948
    if (reset_requested)
2949
        return 0;
2950
    if (shutdown_requested)
2951
        return 0;
2952
    if (debug_requested)
2953
        return 0;
2954
    return 1;
2955
}
2956

    
2957
qemu_irq qemu_system_powerdown;
2958

    
2959
static void main_loop(void)
2960
{
2961
    int r;
2962

    
2963
#ifdef CONFIG_IOTHREAD
2964
    qemu_system_ready = 1;
2965
    qemu_cond_broadcast(&qemu_system_cond);
2966
#endif
2967

    
2968
    for (;;) {
2969
        do {
2970
            bool nonblocking = false;
2971
#ifdef CONFIG_PROFILER
2972
            int64_t ti;
2973
#endif
2974
#ifndef CONFIG_IOTHREAD
2975
            nonblocking = tcg_cpu_exec();
2976
#endif
2977
#ifdef CONFIG_PROFILER
2978
            ti = profile_getclock();
2979
#endif
2980
            main_loop_wait(nonblocking);
2981
#ifdef CONFIG_PROFILER
2982
            dev_time += profile_getclock() - ti;
2983
#endif
2984
        } while (vm_can_run());
2985

    
2986
        if ((r = qemu_debug_requested())) {
2987
            vm_stop(r);
2988
        }
2989
        if (qemu_shutdown_requested()) {
2990
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2991
            if (no_shutdown) {
2992
                vm_stop(0);
2993
                no_shutdown = 0;
2994
            } else
2995
                break;
2996
        }
2997
        if (qemu_reset_requested()) {
2998
            pause_all_vcpus();
2999
            qemu_system_reset();
3000
            resume_all_vcpus();
3001
        }
3002
        if (qemu_powerdown_requested()) {
3003
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3004
            qemu_irq_raise(qemu_system_powerdown);
3005
        }
3006
        if ((r = qemu_vmstop_requested())) {
3007
            vm_stop(r);
3008
        }
3009
    }
3010
    pause_all_vcpus();
3011
}
3012

    
3013
static void version(void)
3014
{
3015
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3016
}
3017

    
3018
static void help(int exitcode)
3019
{
3020
    const char *options_help =
3021
#define DEF(option, opt_arg, opt_enum, opt_help)        \
3022
           opt_help
3023
#define DEFHEADING(text) stringify(text) "\n"
3024
#include "qemu-options.h"
3025
#undef DEF
3026
#undef DEFHEADING
3027
#undef GEN_DOCS
3028
        ;
3029
    version();
3030
    printf("usage: %s [options] [disk_image]\n"
3031
           "\n"
3032
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3033
           "\n"
3034
           "%s\n"
3035
           "During emulation, the following keys are useful:\n"
3036
           "ctrl-alt-f      toggle full screen\n"
3037
           "ctrl-alt-n      switch to virtual console 'n'\n"
3038
           "ctrl-alt        toggle mouse and keyboard grab\n"
3039
           "\n"
3040
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
3041
           "qemu",
3042
           options_help);
3043
    exit(exitcode);
3044
}
3045

    
3046
#define HAS_ARG 0x0001
3047

    
3048
enum {
3049
#define DEF(option, opt_arg, opt_enum, opt_help)        \
3050
    opt_enum,
3051
#define DEFHEADING(text)
3052
#include "qemu-options.h"
3053
#undef DEF
3054
#undef DEFHEADING
3055
#undef GEN_DOCS
3056
};
3057

    
3058
typedef struct QEMUOption {
3059
    const char *name;
3060
    int flags;
3061
    int index;
3062
} QEMUOption;
3063

    
3064
static const QEMUOption qemu_options[] = {
3065
    { "h", 0, QEMU_OPTION_h },
3066
#define DEF(option, opt_arg, opt_enum, opt_help)        \
3067
    { option, opt_arg, opt_enum },
3068
#define DEFHEADING(text)
3069
#include "qemu-options.h"
3070
#undef DEF
3071
#undef DEFHEADING
3072
#undef GEN_DOCS
3073
    { NULL },
3074
};
3075

    
3076
#ifdef HAS_AUDIO
3077
struct soundhw soundhw[] = {
3078
#ifdef HAS_AUDIO_CHOICE
3079
#if defined(TARGET_I386) || defined(TARGET_MIPS)
3080
    {
3081
        "pcspk",
3082
        "PC speaker",
3083
        0,
3084
        1,
3085
        { .init_isa = pcspk_audio_init }
3086
    },
3087
#endif
3088

    
3089
#ifdef CONFIG_SB16
3090
    {
3091
        "sb16",
3092
        "Creative Sound Blaster 16",
3093
        0,
3094
        1,
3095
        { .init_isa = SB16_init }
3096
    },
3097
#endif
3098

    
3099
#ifdef CONFIG_CS4231A
3100
    {
3101
        "cs4231a",
3102
        "CS4231A",
3103
        0,
3104
        1,
3105
        { .init_isa = cs4231a_init }
3106
    },
3107
#endif
3108

    
3109
#ifdef CONFIG_ADLIB
3110
    {
3111
        "adlib",
3112
#ifdef HAS_YMF262
3113
        "Yamaha YMF262 (OPL3)",
3114
#else
3115
        "Yamaha YM3812 (OPL2)",
3116
#endif
3117
        0,
3118
        1,
3119
        { .init_isa = Adlib_init }
3120
    },
3121
#endif
3122

    
3123
#ifdef CONFIG_GUS
3124
    {
3125
        "gus",
3126
        "Gravis Ultrasound GF1",
3127
        0,
3128
        1,
3129
        { .init_isa = GUS_init }
3130
    },
3131
#endif
3132

    
3133
#ifdef CONFIG_AC97
3134
    {
3135
        "ac97",
3136
        "Intel 82801AA AC97 Audio",
3137
        0,
3138
        0,
3139
        { .init_pci = ac97_init }
3140
    },
3141
#endif
3142

    
3143
#ifdef CONFIG_ES1370
3144
    {
3145
        "es1370",
3146
        "ENSONIQ AudioPCI ES1370",
3147
        0,
3148
        0,
3149
        { .init_pci = es1370_init }
3150
    },
3151
#endif
3152

    
3153
#endif /* HAS_AUDIO_CHOICE */
3154

    
3155
    { NULL, NULL, 0, 0, { NULL } }
3156
};
3157

    
3158
static void select_soundhw (const char *optarg)
3159
{
3160
    struct soundhw *c;
3161

    
3162
    if (*optarg == '?') {
3163
    show_valid_cards:
3164

    
3165
        printf ("Valid sound card names (comma separated):\n");
3166
        for (c = soundhw; c->name; ++c) {
3167
            printf ("%-11s %s\n", c->name, c->descr);
3168
        }
3169
        printf ("\n-soundhw all will enable all of the above\n");
3170
        exit (*optarg != '?');
3171
    }
3172
    else {
3173
        size_t l;
3174
        const char *p;
3175
        char *e;
3176
        int bad_card = 0;
3177

    
3178
        if (!strcmp (optarg, "all")) {
3179
            for (c = soundhw; c->name; ++c) {
3180
                c->enabled = 1;
3181
            }
3182
            return;
3183
        }
3184

    
3185
        p = optarg;
3186
        while (*p) {
3187
            e = strchr (p, ',');
3188
            l = !e ? strlen (p) : (size_t) (e - p);
3189

    
3190
            for (c = soundhw; c->name; ++c) {
3191
                if (!strncmp (c->name, p, l) && !c->name[l]) {
3192
                    c->enabled = 1;
3193
                    break;
3194
                }
3195
            }
3196

    
3197
            if (!c->name) {
3198
                if (l > 80) {
3199
                    fprintf (stderr,
3200
                             "Unknown sound card name (too big to show)\n");
3201
                }
3202
                else {
3203
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
3204
                             (int) l, p);
3205
                }
3206
                bad_card = 1;
3207
            }
3208
            p += l + (e != NULL);
3209
        }
3210

    
3211
        if (bad_card)
3212
            goto show_valid_cards;
3213
    }
3214
}
3215
#endif
3216

    
3217
static void select_vgahw (const char *p)
3218
{
3219
    const char *opts;
3220

    
3221
    default_vga = 0;
3222
    vga_interface_type = VGA_NONE;
3223
    if (strstart(p, "std", &opts)) {
3224
        vga_interface_type = VGA_STD;
3225
    } else if (strstart(p, "cirrus", &opts)) {
3226
        vga_interface_type = VGA_CIRRUS;
3227
    } else if (strstart(p, "vmware", &opts)) {
3228
        vga_interface_type = VGA_VMWARE;
3229
    } else if (strstart(p, "xenfb", &opts)) {
3230
        vga_interface_type = VGA_XENFB;
3231
    } else if (!strstart(p, "none", &opts)) {
3232
    invalid_vga:
3233
        fprintf(stderr, "Unknown vga type: %s\n", p);
3234
        exit(1);
3235
    }
3236
    while (*opts) {
3237
        const char *nextopt;
3238

    
3239
        if (strstart(opts, ",retrace=", &nextopt)) {
3240
            opts = nextopt;
3241
            if (strstart(opts, "dumb", &nextopt))
3242
                vga_retrace_method = VGA_RETRACE_DUMB;
3243
            else if (strstart(opts, "precise", &nextopt))
3244
                vga_retrace_method = VGA_RETRACE_PRECISE;
3245
            else goto invalid_vga;
3246
        } else goto invalid_vga;
3247
        opts = nextopt;
3248
    }
3249
}
3250

    
3251
#ifdef TARGET_I386
3252
static int balloon_parse(const char *arg)
3253
{
3254
    QemuOpts *opts;
3255

    
3256
    if (strcmp(arg, "none") == 0) {
3257
        return 0;
3258
    }
3259

    
3260
    if (!strncmp(arg, "virtio", 6)) {
3261
        if (arg[6] == ',') {
3262
            /* have params -> parse them */
3263
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3264
            if (!opts)
3265
                return  -1;
3266
        } else {
3267
            /* create empty opts */
3268
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3269
        }
3270
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3271
        return 0;
3272
    }
3273

    
3274
    return -1;
3275
}
3276
#endif
3277

    
3278
#ifdef _WIN32
3279
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3280
{
3281
    exit(STATUS_CONTROL_C_EXIT);
3282
    return TRUE;
3283
}
3284
#endif
3285

    
3286
int qemu_uuid_parse(const char *str, uint8_t *uuid)
3287
{
3288
    int ret;
3289

    
3290
    if(strlen(str) != 36)
3291
        return -1;
3292

    
3293
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3294
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3295
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3296

    
3297
    if(ret != 16)
3298
        return -1;
3299

    
3300
#ifdef TARGET_I386
3301
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3302
#endif
3303

    
3304
    return 0;
3305
}
3306

    
3307
#ifndef _WIN32
3308

    
3309
static void termsig_handler(int signal)
3310
{
3311
    qemu_system_shutdown_request();
3312
}
3313

    
3314
static void sigchld_handler(int signal)
3315
{
3316
    waitpid(-1, NULL, WNOHANG);
3317
}
3318

    
3319
static void sighandler_setup(void)
3320
{
3321
    struct sigaction act;
3322

    
3323
    memset(&act, 0, sizeof(act));
3324
    act.sa_handler = termsig_handler;
3325
    sigaction(SIGINT,  &act, NULL);
3326
    sigaction(SIGHUP,  &act, NULL);
3327
    sigaction(SIGTERM, &act, NULL);
3328

    
3329
    act.sa_handler = sigchld_handler;
3330
    act.sa_flags = SA_NOCLDSTOP;
3331
    sigaction(SIGCHLD, &act, NULL);
3332
}
3333

    
3334
#endif
3335

    
3336
#ifdef _WIN32
3337
/* Look for support files in the same directory as the executable.  */
3338
static char *find_datadir(const char *argv0)
3339
{
3340
    char *p;
3341
    char buf[MAX_PATH];
3342
    DWORD len;
3343

    
3344
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3345
    if (len == 0) {
3346
        return NULL;
3347
    }
3348

    
3349
    buf[len] = 0;
3350
    p = buf + len - 1;
3351
    while (p != buf && *p != '\\')
3352
        p--;
3353
    *p = 0;
3354
    if (access(buf, R_OK) == 0) {
3355
        return qemu_strdup(buf);
3356
    }
3357
    return NULL;
3358
}
3359
#else /* !_WIN32 */
3360

    
3361
/* Find a likely location for support files using the location of the binary.
3362
   For installed binaries this will be "$bindir/../share/qemu".  When
3363
   running from the build tree this will be "$bindir/../pc-bios".  */
3364
#define SHARE_SUFFIX "/share/qemu"
3365
#define BUILD_SUFFIX "/pc-bios"
3366
static char *find_datadir(const char *argv0)
3367
{
3368
    char *dir;
3369
    char *p = NULL;
3370
    char *res;
3371
    char buf[PATH_MAX];
3372
    size_t max_len;
3373

    
3374
#if defined(__linux__)
3375
    {
3376
        int len;
3377
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3378
        if (len > 0) {
3379
            buf[len] = 0;
3380
            p = buf;
3381
        }
3382
    }
3383
#elif defined(__FreeBSD__)
3384
    {
3385
        int len;
3386
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3387
        if (len > 0) {
3388
            buf[len] = 0;
3389
            p = buf;
3390
        }
3391
    }
3392
#endif
3393
    /* If we don't have any way of figuring out the actual executable
3394
       location then try argv[0].  */
3395
    if (!p) {
3396
        p = realpath(argv0, buf);
3397
        if (!p) {
3398
            return NULL;
3399
        }
3400
    }
3401
    dir = dirname(p);
3402
    dir = dirname(dir);
3403

    
3404
    max_len = strlen(dir) +
3405
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3406
    res = qemu_mallocz(max_len);
3407
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3408
    if (access(res, R_OK)) {
3409
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3410
        if (access(res, R_OK)) {
3411
            qemu_free(res);
3412
            res = NULL;
3413
        }
3414
    }
3415

    
3416
    return res;
3417
}
3418
#undef SHARE_SUFFIX
3419
#undef BUILD_SUFFIX
3420
#endif
3421

    
3422
char *qemu_find_file(int type, const char *name)
3423
{
3424
    int len;
3425
    const char *subdir;
3426
    char *buf;
3427

    
3428
    /* If name contains path separators then try it as a straight path.  */
3429
    if ((strchr(name, '/') || strchr(name, '\\'))
3430
        && access(name, R_OK) == 0) {
3431
        return qemu_strdup(name);
3432
    }
3433
    switch (type) {
3434
    case QEMU_FILE_TYPE_BIOS:
3435
        subdir = "";
3436
        break;
3437
    case QEMU_FILE_TYPE_KEYMAP:
3438
        subdir = "keymaps/";
3439
        break;
3440
    default:
3441
        abort();
3442
    }
3443
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3444
    buf = qemu_mallocz(len);
3445
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3446
    if (access(buf, R_OK)) {
3447
        qemu_free(buf);
3448
        return NULL;
3449
    }
3450
    return buf;
3451
}
3452

    
3453
static int device_help_func(QemuOpts *opts, void *opaque)
3454
{
3455
    return qdev_device_help(opts);
3456
}
3457

    
3458
static int device_init_func(QemuOpts *opts, void *opaque)
3459
{
3460
    DeviceState *dev;
3461

    
3462
    dev = qdev_device_add(opts);
3463
    if (!dev)
3464
        return -1;
3465
    return 0;
3466
}
3467

    
3468
static int chardev_init_func(QemuOpts *opts, void *opaque)
3469
{
3470
    CharDriverState *chr;
3471

    
3472
    chr = qemu_chr_open_opts(opts, NULL);
3473
    if (!chr)
3474
        return -1;
3475
    return 0;
3476
}
3477

    
3478
static int mon_init_func(QemuOpts *opts, void *opaque)
3479
{
3480
    CharDriverState *chr;
3481
    const char *chardev;
3482
    const char *mode;
3483
    int flags;
3484

    
3485
    mode = qemu_opt_get(opts, "mode");
3486
    if (mode == NULL) {
3487
        mode = "readline";
3488
    }
3489
    if (strcmp(mode, "readline") == 0) {
3490
        flags = MONITOR_USE_READLINE;
3491
    } else if (strcmp(mode, "control") == 0) {
3492
        flags = MONITOR_USE_CONTROL;
3493
    } else {
3494
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3495
        exit(1);
3496
    }
3497

    
3498
    if (qemu_opt_get_bool(opts, "default", 0))
3499
        flags |= MONITOR_IS_DEFAULT;
3500

    
3501
    chardev = qemu_opt_get(opts, "chardev");
3502
    chr = qemu_chr_find(chardev);
3503
    if (chr == NULL) {
3504
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3505
        exit(1);
3506
    }
3507

    
3508
    monitor_init(chr, flags);
3509
    return 0;
3510
}
3511

    
3512
static void monitor_parse(const char *optarg, const char *mode)
3513
{
3514
    static int monitor_device_index = 0;
3515
    QemuOpts *opts;
3516
    const char *p;
3517
    char label[32];
3518
    int def = 0;
3519

    
3520
    if (strstart(optarg, "chardev:", &p)) {
3521
        snprintf(label, sizeof(label), "%s", p);
3522
    } else {
3523
        if (monitor_device_index) {
3524
            snprintf(label, sizeof(label), "monitor%d",
3525
                     monitor_device_index);
3526
        } else {
3527
            snprintf(label, sizeof(label), "monitor");
3528
            def = 1;
3529
        }
3530
        opts = qemu_chr_parse_compat(label, optarg);
3531
        if (!opts) {
3532
            fprintf(stderr, "parse error: %s\n", optarg);
3533
            exit(1);
3534
        }
3535
    }
3536

    
3537
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3538
    if (!opts) {
3539
        fprintf(stderr, "duplicate chardev: %s\n", label);
3540
        exit(1);
3541
    }
3542
    qemu_opt_set(opts, "mode", mode);
3543
    qemu_opt_set(opts, "chardev", label);
3544
    if (def)
3545
        qemu_opt_set(opts, "default", "on");
3546
    monitor_device_index++;
3547
}
3548

    
3549
struct device_config {
3550
    enum {
3551
        DEV_USB,       /* -usbdevice     */
3552
        DEV_BT,        /* -bt            */
3553
        DEV_SERIAL,    /* -serial        */
3554
        DEV_PARALLEL,  /* -parallel      */
3555
        DEV_VIRTCON,   /* -virtioconsole */
3556
        DEV_DEBUGCON,  /* -debugcon */
3557
    } type;
3558
    const char *cmdline;
3559
    QTAILQ_ENTRY(device_config) next;
3560
};
3561
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3562

    
3563
static void add_device_config(int type, const char *cmdline)
3564
{
3565
    struct device_config *conf;
3566

    
3567
    conf = qemu_mallocz(sizeof(*conf));
3568
    conf->type = type;
3569
    conf->cmdline = cmdline;
3570
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3571
}
3572

    
3573
static int foreach_device_config(int type, int (*func)(const char *cmdline))
3574
{
3575
    struct device_config *conf;
3576
    int rc;
3577

    
3578
    QTAILQ_FOREACH(conf, &device_configs, next) {
3579
        if (conf->type != type)
3580
            continue;
3581
        rc = func(conf->cmdline);
3582
        if (0 != rc)
3583
            return rc;
3584
    }
3585
    return 0;
3586
}
3587

    
3588
static int serial_parse(const char *devname)
3589
{
3590
    static int index = 0;
3591
    char label[32];
3592

    
3593
    if (strcmp(devname, "none") == 0)
3594
        return 0;
3595
    if (index == MAX_SERIAL_PORTS) {
3596
        fprintf(stderr, "qemu: too many serial ports\n");
3597
        exit(1);
3598
    }
3599
    snprintf(label, sizeof(label), "serial%d", index);
3600
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
3601
    if (!serial_hds[index]) {
3602
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3603
                devname, strerror(errno));
3604
        return -1;
3605
    }
3606
    index++;
3607
    return 0;
3608
}
3609

    
3610
static int parallel_parse(const char *devname)
3611
{
3612
    static int index = 0;
3613
    char label[32];
3614

    
3615
    if (strcmp(devname, "none") == 0)
3616
        return 0;
3617
    if (index == MAX_PARALLEL_PORTS) {
3618
        fprintf(stderr, "qemu: too many parallel ports\n");
3619
        exit(1);
3620
    }
3621
    snprintf(label, sizeof(label), "parallel%d", index);
3622
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3623
    if (!parallel_hds[index]) {
3624
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3625
                devname, strerror(errno));
3626
        return -1;
3627
    }
3628
    index++;
3629
    return 0;
3630
}
3631

    
3632
static int virtcon_parse(const char *devname)
3633
{
3634
    static int index = 0;
3635
    char label[32];
3636
    QemuOpts *bus_opts, *dev_opts;
3637

    
3638
    if (strcmp(devname, "none") == 0)
3639
        return 0;
3640
    if (index == MAX_VIRTIO_CONSOLES) {
3641
        fprintf(stderr, "qemu: too many virtio consoles\n");
3642
        exit(1);
3643
    }
3644

    
3645
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3646
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
3647

    
3648
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3649
    qemu_opt_set(dev_opts, "driver", "virtconsole");
3650

    
3651
    snprintf(label, sizeof(label), "virtcon%d", index);
3652
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3653
    if (!virtcon_hds[index]) {
3654
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3655
                devname, strerror(errno));
3656
        return -1;
3657
    }
3658
    qemu_opt_set(dev_opts, "chardev", label);
3659

    
3660
    index++;
3661
    return 0;
3662
}
3663

    
3664
static int debugcon_parse(const char *devname)
3665
{   
3666
    QemuOpts *opts;
3667

    
3668
    if (!qemu_chr_open("debugcon", devname, NULL)) {
3669
        exit(1);
3670
    }
3671
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3672
    if (!opts) {
3673
        fprintf(stderr, "qemu: already have a debugcon device\n");
3674
        exit(1);
3675
    }
3676
    qemu_opt_set(opts, "driver", "isa-debugcon");
3677
    qemu_opt_set(opts, "chardev", "debugcon");
3678
    return 0;
3679
}
3680

    
3681
static const QEMUOption *lookup_opt(int argc, char **argv,
3682
                                    const char **poptarg, int *poptind)
3683
{
3684
    const QEMUOption *popt;
3685
    int optind = *poptind;
3686
    char *r = argv[optind];
3687
    const char *optarg;
3688

    
3689
    loc_set_cmdline(argv, optind, 1);
3690
    optind++;
3691
    /* Treat --foo the same as -foo.  */
3692
    if (r[1] == '-')
3693
        r++;
3694
    popt = qemu_options;
3695
    for(;;) {
3696
        if (!popt->name) {
3697
            error_report("invalid option");
3698
            exit(1);
3699
        }
3700
        if (!strcmp(popt->name, r + 1))
3701
            break;
3702
        popt++;
3703
    }
3704
    if (popt->flags & HAS_ARG) {
3705
        if (optind >= argc) {
3706
            error_report("requires an argument");
3707
            exit(1);
3708
        }
3709
        optarg = argv[optind++];
3710
        loc_set_cmdline(argv, optind - 2, 2);
3711
    } else {
3712
        optarg = NULL;
3713
    }
3714

    
3715
    *poptarg = optarg;
3716
    *poptind = optind;
3717

    
3718
    return popt;
3719
}
3720

    
3721
int main(int argc, char **argv, char **envp)
3722
{
3723
    const char *gdbstub_dev = NULL;
3724
    uint32_t boot_devices_bitmap = 0;
3725
    int i;
3726
    int snapshot, linux_boot, net_boot;
3727
    const char *icount_option = NULL;
3728
    const char *initrd_filename;
3729
    const char *kernel_filename, *kernel_cmdline;
3730
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3731
    DisplayState *ds;
3732
    DisplayChangeListener *dcl;
3733
    int cyls, heads, secs, translation;
3734
    QemuOpts *hda_opts = NULL, *opts;
3735
    int optind;
3736
    const char *optarg;
3737
    const char *loadvm = NULL;
3738
    QEMUMachine *machine;
3739
    const char *cpu_model;
3740
#ifndef _WIN32
3741
    int fds[2];
3742
#endif
3743
    int tb_size;
3744
    const char *pid_file = NULL;
3745
    const char *incoming = NULL;
3746
#ifndef _WIN32
3747
    int fd = 0;
3748
    struct passwd *pwd = NULL;
3749
    const char *chroot_dir = NULL;
3750
    const char *run_as = NULL;
3751
#endif
3752
    int show_vnc_port = 0;
3753
    int defconfig = 1;
3754

    
3755
    error_set_progname(argv[0]);
3756

    
3757
    init_clocks();
3758

    
3759
    qemu_cache_utils_init(envp);
3760

    
3761
    QLIST_INIT (&vm_change_state_head);
3762
#ifndef _WIN32
3763
    {
3764
        struct sigaction act;
3765
        sigfillset(&act.sa_mask);
3766
        act.sa_flags = 0;
3767
        act.sa_handler = SIG_IGN;
3768
        sigaction(SIGPIPE, &act, NULL);
3769
    }
3770
#else
3771
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3772
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
3773
       QEMU to run on a single CPU */
3774
    {
3775
        HANDLE h;
3776
        DWORD mask, smask;
3777
        int i;
3778
        h = GetCurrentProcess();
3779
        if (GetProcessAffinityMask(h, &mask, &smask)) {
3780
            for(i = 0; i < 32; i++) {
3781
                if (mask & (1 << i))
3782
                    break;
3783
            }
3784
            if (i != 32) {
3785
                mask = 1 << i;
3786
                SetProcessAffinityMask(h, mask);
3787
            }
3788
        }
3789
    }
3790
#endif
3791

    
3792
    module_call_init(MODULE_INIT_MACHINE);
3793
    machine = find_default_machine();
3794
    cpu_model = NULL;
3795
    initrd_filename = NULL;
3796
    ram_size = 0;
3797
    snapshot = 0;
3798
    kernel_filename = NULL;
3799
    kernel_cmdline = "";
3800
    cyls = heads = secs = 0;
3801
    translation = BIOS_ATA_TRANSLATION_AUTO;
3802

    
3803
    for (i = 0; i < MAX_NODES; i++) {
3804
        node_mem[i] = 0;
3805
        node_cpumask[i] = 0;
3806
    }
3807

    
3808
    nb_numa_nodes = 0;
3809
    nb_nics = 0;
3810

    
3811
    tb_size = 0;
3812
    autostart= 1;
3813

    
3814
    /* first pass of option parsing */
3815
    optind = 1;
3816
    while (optind < argc) {
3817
        if (argv[optind][0] != '-') {
3818
            /* disk image */
3819
            optind++;
3820
            continue;
3821
        } else {
3822
            const QEMUOption *popt;
3823

    
3824
            popt = lookup_opt(argc, argv, &optarg, &optind);
3825
            switch (popt->index) {
3826
            case QEMU_OPTION_nodefconfig:
3827
                defconfig=0;
3828
                break;
3829
            }
3830
        }
3831
    }
3832

    
3833
    if (defconfig) {
3834
        const char *fname;
3835
        FILE *fp;
3836

    
3837
        fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3838
        fp = fopen(fname, "r");
3839
        if (fp) {
3840
            if (qemu_config_parse(fp, fname) != 0) {
3841
                exit(1);
3842
            }
3843
            fclose(fp);
3844
        }
3845

    
3846
        fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3847
        fp = fopen(fname, "r");
3848
        if (fp) {
3849
            if (qemu_config_parse(fp, fname) != 0) {
3850
                exit(1);
3851
            }
3852
            fclose(fp);
3853
        }
3854
    }
3855
#if defined(cpudef_setup)
3856
    cpudef_setup(); /* parse cpu definitions in target config file */
3857
#endif
3858

    
3859
    /* second pass of option parsing */
3860
    optind = 1;
3861
    for(;;) {
3862
        if (optind >= argc)
3863
            break;
3864
        if (argv[optind][0] != '-') {
3865
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3866
        } else {
3867
            const QEMUOption *popt;
3868

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

    
4029
                    if (!strchr(optarg, '=')) {
4030
                        legacy = 1;
4031
                        pstrcpy(buf, sizeof(buf), optarg);
4032
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4033
                        fprintf(stderr,
4034
                                "qemu: unknown boot parameter '%s' in '%s'\n",
4035
                                buf, optarg);
4036
                        exit(1);
4037
                    }
4038

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

    
4129
                value = strtoul(optarg, &ptr, 10);
4130
                switch (*ptr) {
4131
                case 0: case 'M': case 'm':
4132
                    value <<= 20;
4133
                    break;
4134
                case 'G': case 'g':
4135
                    value <<= 30;
4136
                    break;
4137
                default:
4138
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4139
                    exit(1);
4140
                }
4141

    
4142
                /* On 32-bit hosts, QEMU is limited by virtual address space */
4143
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4144
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4145
                    exit(1);
4146
                }
4147
                if (value != (uint64_t)(ram_addr_t)value) {
4148
                    fprintf(stderr, "qemu: ram size too large\n");
4149
                    exit(1);
4150
                }
4151
                ram_size = value;
4152
                break;
4153
            }
4154
            case QEMU_OPTION_mempath:
4155
                mem_path = optarg;
4156
                break;
4157
#ifdef MAP_POPULATE
4158
            case QEMU_OPTION_mem_prealloc:
4159
                mem_prealloc = 1;
4160
                break;
4161
#endif
4162
            case QEMU_OPTION_d:
4163
                {
4164
                    int mask;
4165
                    const CPULogItem *item;
4166

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

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

    
4561
    /* If no data_dir is specified then try to find it relative to the
4562
       executable path.  */
4563
    if (!data_dir) {
4564
        data_dir = find_datadir(argv[0]);
4565
    }
4566
    /* If all else fails use the install patch specified when building.  */
4567
    if (!data_dir) {
4568
        data_dir = CONFIG_QEMU_SHAREDIR;
4569
    }
4570

    
4571
    /*
4572
     * Default to max_cpus = smp_cpus, in case the user doesn't
4573
     * specify a max_cpus value.
4574
     */
4575
    if (!max_cpus)
4576
        max_cpus = smp_cpus;
4577

    
4578
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4579
    if (smp_cpus > machine->max_cpus) {
4580
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4581
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
4582
                machine->max_cpus);
4583
        exit(1);
4584
    }
4585

    
4586
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4587
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4588

    
4589
    if (machine->no_serial) {
4590
        default_serial = 0;
4591
    }
4592
    if (machine->no_parallel) {
4593
        default_parallel = 0;
4594
    }
4595
    if (!machine->use_virtcon) {
4596
        default_virtcon = 0;
4597
    }
4598
    if (machine->no_vga) {
4599
        default_vga = 0;
4600
    }
4601
    if (machine->no_floppy) {
4602
        default_floppy = 0;
4603
    }
4604
    if (machine->no_cdrom) {
4605
        default_cdrom = 0;
4606
    }
4607
    if (machine->no_sdcard) {
4608
        default_sdcard = 0;
4609
    }
4610

    
4611
    if (display_type == DT_NOGRAPHIC) {
4612
        if (default_parallel)
4613
            add_device_config(DEV_PARALLEL, "null");
4614
        if (default_serial && default_monitor) {
4615
            add_device_config(DEV_SERIAL, "mon:stdio");
4616
        } else if (default_virtcon && default_monitor) {
4617
            add_device_config(DEV_VIRTCON, "mon:stdio");
4618
        } else {
4619
            if (default_serial)
4620
                add_device_config(DEV_SERIAL, "stdio");
4621
            if (default_virtcon)
4622
                add_device_config(DEV_VIRTCON, "stdio");
4623
            if (default_monitor)
4624
                monitor_parse("stdio", "readline");
4625
        }
4626
    } else {
4627
        if (default_serial)
4628
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
4629
        if (default_parallel)
4630
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4631
        if (default_monitor)
4632
            monitor_parse("vc:80Cx24C", "readline");
4633
        if (default_virtcon)
4634
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4635
    }
4636
    if (default_vga)
4637
        vga_interface_type = VGA_CIRRUS;
4638

    
4639
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4640
        exit(1);
4641

    
4642
#ifndef _WIN32
4643
    if (daemonize) {
4644
        pid_t pid;
4645

    
4646
        if (pipe(fds) == -1)
4647
            exit(1);
4648

    
4649
        pid = fork();
4650
        if (pid > 0) {
4651
            uint8_t status;
4652
            ssize_t len;
4653

    
4654
            close(fds[1]);
4655

    
4656
        again:
4657
            len = read(fds[0], &status, 1);
4658
            if (len == -1 && (errno == EINTR))
4659
                goto again;
4660

    
4661
            if (len != 1)
4662
                exit(1);
4663
            else if (status == 1) {
4664
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4665
                exit(1);
4666
            } else
4667
                exit(0);
4668
        } else if (pid < 0)
4669
            exit(1);
4670

    
4671
        close(fds[0]);
4672
        qemu_set_cloexec(fds[1]);
4673

    
4674
        setsid();
4675

    
4676
        pid = fork();
4677
        if (pid > 0)
4678
            exit(0);
4679
        else if (pid < 0)
4680
            exit(1);
4681

    
4682
        umask(027);
4683

    
4684
        signal(SIGTSTP, SIG_IGN);
4685
        signal(SIGTTOU, SIG_IGN);
4686
        signal(SIGTTIN, SIG_IGN);
4687
    }
4688
#endif
4689

    
4690
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4691
#ifndef _WIN32
4692
        if (daemonize) {
4693
            uint8_t status = 1;
4694
            if (write(fds[1], &status, 1) != 1) {
4695
                perror("daemonize. Writing to pipe\n");
4696
            }
4697
        } else
4698
#endif
4699
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4700
        exit(1);
4701
    }
4702

    
4703
    if (kvm_enabled()) {
4704
        int ret;
4705

    
4706
        ret = kvm_init(smp_cpus);
4707
        if (ret < 0) {
4708
            fprintf(stderr, "failed to initialize KVM\n");
4709
            exit(1);
4710
        }
4711
    }
4712

    
4713
    if (qemu_init_main_loop()) {
4714
        fprintf(stderr, "qemu_init_main_loop failed\n");
4715
        exit(1);
4716
    }
4717
    linux_boot = (kernel_filename != NULL);
4718

    
4719
    if (!linux_boot && *kernel_cmdline != '\0') {
4720
        fprintf(stderr, "-append only allowed with -kernel option\n");
4721
        exit(1);
4722
    }
4723

    
4724
    if (!linux_boot && initrd_filename != NULL) {
4725
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
4726
        exit(1);
4727
    }
4728

    
4729
#ifndef _WIN32
4730
    /* Win32 doesn't support line-buffering and requires size >= 2 */
4731
    setvbuf(stdout, NULL, _IOLBF, 0);
4732
#endif
4733

    
4734
    if (init_timer_alarm() < 0) {
4735
        fprintf(stderr, "could not initialize alarm timer\n");
4736
        exit(1);
4737
    }
4738
    configure_icount(icount_option);
4739

    
4740
#ifdef _WIN32
4741
    socket_init();
4742
#endif
4743

    
4744
    if (net_init_clients() < 0) {
4745
        exit(1);
4746
    }
4747

    
4748
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4749
    net_set_boot_mask(net_boot);
4750

    
4751
    /* init the bluetooth world */
4752
    if (foreach_device_config(DEV_BT, bt_parse))
4753
        exit(1);
4754

    
4755
    /* init the memory */
4756
    if (ram_size == 0)
4757
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4758

    
4759
    /* init the dynamic translator */
4760
    cpu_exec_init_all(tb_size * 1024 * 1024);
4761

    
4762
    bdrv_init_with_whitelist();
4763

    
4764
    blk_mig_init();
4765

    
4766
    if (default_cdrom) {
4767
        /* we always create the cdrom drive, even if no disk is there */
4768
        drive_add(NULL, CDROM_ALIAS);
4769
    }
4770

    
4771
    if (default_floppy) {
4772
        /* we always create at least one floppy */
4773
        drive_add(NULL, FD_ALIAS, 0);
4774
    }
4775

    
4776
    if (default_sdcard) {
4777
        /* we always create one sd slot, even if no card is in it */
4778
        drive_add(NULL, SD_ALIAS);
4779
    }
4780

    
4781
    /* open the virtual block devices */
4782
    if (snapshot)
4783
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4784
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4785
        exit(1);
4786

    
4787
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
4788
                         ram_load, NULL);
4789

    
4790
    if (nb_numa_nodes > 0) {
4791
        int i;
4792

    
4793
        if (nb_numa_nodes > smp_cpus) {
4794
            nb_numa_nodes = smp_cpus;
4795
        }
4796

    
4797
        /* If no memory size if given for any node, assume the default case
4798
         * and distribute the available memory equally across all nodes
4799
         */
4800
        for (i = 0; i < nb_numa_nodes; i++) {
4801
            if (node_mem[i] != 0)
4802
                break;
4803
        }
4804
        if (i == nb_numa_nodes) {
4805
            uint64_t usedmem = 0;
4806

    
4807
            /* On Linux, the each node's border has to be 8MB aligned,
4808
             * the final node gets the rest.
4809
             */
4810
            for (i = 0; i < nb_numa_nodes - 1; i++) {
4811
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4812
                usedmem += node_mem[i];
4813
            }
4814
            node_mem[i] = ram_size - usedmem;
4815
        }
4816

    
4817
        for (i = 0; i < nb_numa_nodes; i++) {
4818
            if (node_cpumask[i] != 0)
4819
                break;
4820
        }
4821
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
4822
         * must cope with this anyway, because there are BIOSes out there in
4823
         * real machines which also use this scheme.
4824
         */
4825
        if (i == nb_numa_nodes) {
4826
            for (i = 0; i < smp_cpus; i++) {
4827
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
4828
            }
4829
        }
4830
    }
4831

    
4832
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4833
        exit(1);
4834
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4835
        exit(1);
4836
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4837
        exit(1);
4838
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4839
        exit(1);
4840

    
4841
    module_call_init(MODULE_INIT_DEVICE);
4842

    
4843
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4844
        exit(0);
4845

    
4846
    if (watchdog) {
4847
        i = select_watchdog(watchdog);
4848
        if (i > 0)
4849
            exit (i == 1 ? 1 : 0);
4850
    }
4851

    
4852
    if (machine->compat_props) {
4853
        qdev_prop_register_global_list(machine->compat_props);
4854
    }
4855
    qemu_add_globals();
4856

    
4857
    machine->init(ram_size, boot_devices,
4858
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4859

    
4860
    cpu_synchronize_all_post_init();
4861

    
4862
#ifndef _WIN32
4863
    /* must be after terminal init, SDL library changes signal handlers */
4864
    sighandler_setup();
4865
#endif
4866

    
4867
    set_numa_modes();
4868

    
4869
    current_machine = machine;
4870

    
4871
    /* init USB devices */
4872
    if (usb_enabled) {
<