Statistics
| Branch: | Revision:

root / vl.c @ 666daa68

History | View | Annotate | Download (92.3 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2008 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include <unistd.h>
25
#include <fcntl.h>
26
#include <signal.h>
27
#include <time.h>
28
#include <errno.h>
29
#include <sys/time.h>
30
#include <zlib.h>
31

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

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

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

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

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

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

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

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

    
119
#include "hw/hw.h"
120
#include "hw/boards.h"
121
#include "hw/usb.h"
122
#include "hw/pcmcia.h"
123
#include "hw/pc.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 "blockdev.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 "qemu-option.h"
150
#include "qemu-config.h"
151
#include "qemu-objects.h"
152
#ifdef CONFIG_LINUX
153
#include "fsdev/qemu-fsdev.h"
154
#endif
155

    
156
#include "disas.h"
157

    
158
#include "qemu_socket.h"
159

    
160
#include "slirp/libslirp.h"
161

    
162
#include "qemu-queue.h"
163
#include "cpus.h"
164
#include "arch_init.h"
165

    
166
//#define DEBUG_NET
167
//#define DEBUG_SLIRP
168

    
169
#define DEFAULT_RAM_SIZE 128
170

    
171
#define MAX_VIRTIO_CONSOLES 1
172

    
173
static const char *data_dir;
174
const char *bios_name = NULL;
175
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
176
DisplayType display_type = DT_DEFAULT;
177
const char* keyboard_layout = NULL;
178
ram_addr_t ram_size;
179
const char *mem_path = NULL;
180
#ifdef MAP_POPULATE
181
int mem_prealloc = 0; /* force preallocation of physical target memory */
182
#endif
183
int nb_nics;
184
NICInfo nd_table[MAX_NICS];
185
int vm_running;
186
int autostart;
187
static int rtc_utc = 1;
188
static int rtc_date_offset = -1; /* -1 means no change */
189
QEMUClock *rtc_clock;
190
int vga_interface_type = VGA_NONE;
191
static int full_screen = 0;
192
#ifdef CONFIG_SDL
193
static int no_frame = 0;
194
#endif
195
int no_quit = 0;
196
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
197
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
198
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
199
int win2k_install_hack = 0;
200
int rtc_td_hack = 0;
201
int usb_enabled = 0;
202
int singlestep = 0;
203
int smp_cpus = 1;
204
int max_cpus = 0;
205
int smp_cores = 1;
206
int smp_threads = 1;
207
const char *vnc_display;
208
int acpi_enabled = 1;
209
int no_hpet = 0;
210
int fd_bootchk = 1;
211
int no_reboot = 0;
212
int no_shutdown = 0;
213
int cursor_hide = 1;
214
int graphic_rotate = 0;
215
uint8_t irq0override = 1;
216
#ifndef _WIN32
217
int daemonize = 0;
218
#endif
219
const char *watchdog;
220
const char *option_rom[MAX_OPTION_ROMS];
221
int nb_option_roms;
222
int semihosting_enabled = 0;
223
int old_param = 0;
224
const char *qemu_name;
225
int alt_grab = 0;
226
int ctrl_grab = 0;
227
unsigned int nb_prom_envs = 0;
228
const char *prom_envs[MAX_PROM_ENVS];
229
int boot_menu;
230

    
231
int nb_numa_nodes;
232
uint64_t node_mem[MAX_NODES];
233
uint64_t node_cpumask[MAX_NODES];
234

    
235
static QEMUTimer *nographic_timer;
236

    
237
uint8_t qemu_uuid[16];
238

    
239
static QEMUBootSetHandler *boot_set_handler;
240
static void *boot_set_opaque;
241

    
242
int kvm_allowed = 0;
243
uint32_t xen_domid;
244
enum xen_mode xen_mode = XEN_EMULATE;
245

    
246
static int default_serial = 1;
247
static int default_parallel = 1;
248
static int default_virtcon = 1;
249
static int default_monitor = 1;
250
static int default_vga = 1;
251
static int default_floppy = 1;
252
static int default_cdrom = 1;
253
static int default_sdcard = 1;
254

    
255
static struct {
256
    const char *driver;
257
    int *flag;
258
} default_list[] = {
259
    { .driver = "isa-serial",           .flag = &default_serial    },
260
    { .driver = "isa-parallel",         .flag = &default_parallel  },
261
    { .driver = "isa-fdc",              .flag = &default_floppy    },
262
    { .driver = "ide-drive",            .flag = &default_cdrom     },
263
    { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
264
    { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
265
    { .driver = "virtio-serial",        .flag = &default_virtcon   },
266
    { .driver = "VGA",                  .flag = &default_vga       },
267
    { .driver = "cirrus-vga",           .flag = &default_vga       },
268
    { .driver = "vmware-svga",          .flag = &default_vga       },
269
};
270

    
271
static int default_driver_check(QemuOpts *opts, void *opaque)
272
{
273
    const char *driver = qemu_opt_get(opts, "driver");
274
    int i;
275

    
276
    if (!driver)
277
        return 0;
278
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
279
        if (strcmp(default_list[i].driver, driver) != 0)
280
            continue;
281
        *(default_list[i].flag) = 0;
282
    }
283
    return 0;
284
}
285

    
286
/***********************************************************/
287

    
288
static void set_proc_name(const char *s)
289
{
290
#if defined(__linux__) && defined(PR_SET_NAME)
291
    char name[16];
292
    if (!s)
293
        return;
294
    name[sizeof(name) - 1] = 0;
295
    strncpy(name, s, sizeof(name));
296
    /* Could rewrite argv[0] too, but that's a bit more complicated.
297
       This simple way is enough for `top'. */
298
    prctl(PR_SET_NAME, name);
299
#endif            
300
}
301
 
302
/***********************************************************/
303
/* real time host monotonic timer */
304

    
305
/* compute with 96 bit intermediate result: (a*b)/c */
306
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
307
{
308
    union {
309
        uint64_t ll;
310
        struct {
311
#ifdef HOST_WORDS_BIGENDIAN
312
            uint32_t high, low;
313
#else
314
            uint32_t low, high;
315
#endif
316
        } l;
317
    } u, res;
318
    uint64_t rl, rh;
319

    
320
    u.ll = a;
321
    rl = (uint64_t)u.l.low * (uint64_t)b;
322
    rh = (uint64_t)u.l.high * (uint64_t)b;
323
    rh += (rl >> 32);
324
    res.l.high = rh / c;
325
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
326
    return res.ll;
327
}
328

    
329
/***********************************************************/
330
/* host time/date access */
331
void qemu_get_timedate(struct tm *tm, int offset)
332
{
333
    time_t ti;
334
    struct tm *ret;
335

    
336
    time(&ti);
337
    ti += offset;
338
    if (rtc_date_offset == -1) {
339
        if (rtc_utc)
340
            ret = gmtime(&ti);
341
        else
342
            ret = localtime(&ti);
343
    } else {
344
        ti -= rtc_date_offset;
345
        ret = gmtime(&ti);
346
    }
347

    
348
    memcpy(tm, ret, sizeof(struct tm));
349
}
350

    
351
int qemu_timedate_diff(struct tm *tm)
352
{
353
    time_t seconds;
354

    
355
    if (rtc_date_offset == -1)
356
        if (rtc_utc)
357
            seconds = mktimegm(tm);
358
        else
359
            seconds = mktime(tm);
360
    else
361
        seconds = mktimegm(tm) + rtc_date_offset;
362

    
363
    return seconds - time(NULL);
364
}
365

    
366
void rtc_change_mon_event(struct tm *tm)
367
{
368
    QObject *data;
369

    
370
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
371
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
372
    qobject_decref(data);
373
}
374

    
375
static void configure_rtc_date_offset(const char *startdate, int legacy)
376
{
377
    time_t rtc_start_date;
378
    struct tm tm;
379

    
380
    if (!strcmp(startdate, "now") && legacy) {
381
        rtc_date_offset = -1;
382
    } else {
383
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
384
                   &tm.tm_year,
385
                   &tm.tm_mon,
386
                   &tm.tm_mday,
387
                   &tm.tm_hour,
388
                   &tm.tm_min,
389
                   &tm.tm_sec) == 6) {
390
            /* OK */
391
        } else if (sscanf(startdate, "%d-%d-%d",
392
                          &tm.tm_year,
393
                          &tm.tm_mon,
394
                          &tm.tm_mday) == 3) {
395
            tm.tm_hour = 0;
396
            tm.tm_min = 0;
397
            tm.tm_sec = 0;
398
        } else {
399
            goto date_fail;
400
        }
401
        tm.tm_year -= 1900;
402
        tm.tm_mon--;
403
        rtc_start_date = mktimegm(&tm);
404
        if (rtc_start_date == -1) {
405
        date_fail:
406
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
407
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
408
            exit(1);
409
        }
410
        rtc_date_offset = time(NULL) - rtc_start_date;
411
    }
412
}
413

    
414
static void configure_rtc(QemuOpts *opts)
415
{
416
    const char *value;
417

    
418
    value = qemu_opt_get(opts, "base");
419
    if (value) {
420
        if (!strcmp(value, "utc")) {
421
            rtc_utc = 1;
422
        } else if (!strcmp(value, "localtime")) {
423
            rtc_utc = 0;
424
        } else {
425
            configure_rtc_date_offset(value, 0);
426
        }
427
    }
428
    value = qemu_opt_get(opts, "clock");
429
    if (value) {
430
        if (!strcmp(value, "host")) {
431
            rtc_clock = host_clock;
432
        } else if (!strcmp(value, "vm")) {
433
            rtc_clock = vm_clock;
434
        } else {
435
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
436
            exit(1);
437
        }
438
    }
439
    value = qemu_opt_get(opts, "driftfix");
440
    if (value) {
441
        if (!strcmp(value, "slew")) {
442
            rtc_td_hack = 1;
443
        } else if (!strcmp(value, "none")) {
444
            rtc_td_hack = 0;
445
        } else {
446
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
447
            exit(1);
448
        }
449
    }
450
}
451

    
452
/***********************************************************/
453
/* Bluetooth support */
454
static int nb_hcis;
455
static int cur_hci;
456
static struct HCIInfo *hci_table[MAX_NICS];
457

    
458
static struct bt_vlan_s {
459
    struct bt_scatternet_s net;
460
    int id;
461
    struct bt_vlan_s *next;
462
} *first_bt_vlan;
463

    
464
/* find or alloc a new bluetooth "VLAN" */
465
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
466
{
467
    struct bt_vlan_s **pvlan, *vlan;
468
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
469
        if (vlan->id == id)
470
            return &vlan->net;
471
    }
472
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
473
    vlan->id = id;
474
    pvlan = &first_bt_vlan;
475
    while (*pvlan != NULL)
476
        pvlan = &(*pvlan)->next;
477
    *pvlan = vlan;
478
    return &vlan->net;
479
}
480

    
481
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
482
{
483
}
484

    
485
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
486
{
487
    return -ENOTSUP;
488
}
489

    
490
static struct HCIInfo null_hci = {
491
    .cmd_send = null_hci_send,
492
    .sco_send = null_hci_send,
493
    .acl_send = null_hci_send,
494
    .bdaddr_set = null_hci_addr_set,
495
};
496

    
497
struct HCIInfo *qemu_next_hci(void)
498
{
499
    if (cur_hci == nb_hcis)
500
        return &null_hci;
501

    
502
    return hci_table[cur_hci++];
503
}
504

    
505
static struct HCIInfo *hci_init(const char *str)
506
{
507
    char *endp;
508
    struct bt_scatternet_s *vlan = 0;
509

    
510
    if (!strcmp(str, "null"))
511
        /* null */
512
        return &null_hci;
513
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
514
        /* host[:hciN] */
515
        return bt_host_hci(str[4] ? str + 5 : "hci0");
516
    else if (!strncmp(str, "hci", 3)) {
517
        /* hci[,vlan=n] */
518
        if (str[3]) {
519
            if (!strncmp(str + 3, ",vlan=", 6)) {
520
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
521
                if (*endp)
522
                    vlan = 0;
523
            }
524
        } else
525
            vlan = qemu_find_bt_vlan(0);
526
        if (vlan)
527
           return bt_new_hci(vlan);
528
    }
529

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

    
532
    return 0;
533
}
534

    
535
static int bt_hci_parse(const char *str)
536
{
537
    struct HCIInfo *hci;
538
    bdaddr_t bdaddr;
539

    
540
    if (nb_hcis >= MAX_NICS) {
541
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
542
        return -1;
543
    }
544

    
545
    hci = hci_init(str);
546
    if (!hci)
547
        return -1;
548

    
549
    bdaddr.b[0] = 0x52;
550
    bdaddr.b[1] = 0x54;
551
    bdaddr.b[2] = 0x00;
552
    bdaddr.b[3] = 0x12;
553
    bdaddr.b[4] = 0x34;
554
    bdaddr.b[5] = 0x56 + nb_hcis;
555
    hci->bdaddr_set(hci, bdaddr.b);
556

    
557
    hci_table[nb_hcis++] = hci;
558

    
559
    return 0;
560
}
561

    
562
static void bt_vhci_add(int vlan_id)
563
{
564
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
565

    
566
    if (!vlan->slave)
567
        fprintf(stderr, "qemu: warning: adding a VHCI to "
568
                        "an empty scatternet %i\n", vlan_id);
569

    
570
    bt_vhci_init(bt_new_hci(vlan));
571
}
572

    
573
static struct bt_device_s *bt_device_add(const char *opt)
574
{
575
    struct bt_scatternet_s *vlan;
576
    int vlan_id = 0;
577
    char *endp = strstr(opt, ",vlan=");
578
    int len = (endp ? endp - opt : strlen(opt)) + 1;
579
    char devname[10];
580

    
581
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
582

    
583
    if (endp) {
584
        vlan_id = strtol(endp + 6, &endp, 0);
585
        if (*endp) {
586
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
587
            return 0;
588
        }
589
    }
590

    
591
    vlan = qemu_find_bt_vlan(vlan_id);
592

    
593
    if (!vlan->slave)
594
        fprintf(stderr, "qemu: warning: adding a slave device to "
595
                        "an empty scatternet %i\n", vlan_id);
596

    
597
    if (!strcmp(devname, "keyboard"))
598
        return bt_keyboard_init(vlan);
599

    
600
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
601
    return 0;
602
}
603

    
604
static int bt_parse(const char *opt)
605
{
606
    const char *endp, *p;
607
    int vlan;
608

    
609
    if (strstart(opt, "hci", &endp)) {
610
        if (!*endp || *endp == ',') {
611
            if (*endp)
612
                if (!strstart(endp, ",vlan=", 0))
613
                    opt = endp + 1;
614

    
615
            return bt_hci_parse(opt);
616
       }
617
    } else if (strstart(opt, "vhci", &endp)) {
618
        if (!*endp || *endp == ',') {
619
            if (*endp) {
620
                if (strstart(endp, ",vlan=", &p)) {
621
                    vlan = strtol(p, (char **) &endp, 0);
622
                    if (*endp) {
623
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
624
                        return 1;
625
                    }
626
                } else {
627
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
628
                    return 1;
629
                }
630
            } else
631
                vlan = 0;
632

    
633
            bt_vhci_add(vlan);
634
            return 0;
635
        }
636
    } else if (strstart(opt, "device:", &endp))
637
        return !bt_device_add(endp);
638

    
639
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
640
    return 1;
641
}
642

    
643
/***********************************************************/
644
/* QEMU Block devices */
645

    
646
#define HD_ALIAS "index=%d,media=disk"
647
#define CDROM_ALIAS "index=2,media=cdrom"
648
#define FD_ALIAS "index=%d,if=floppy"
649
#define PFLASH_ALIAS "if=pflash"
650
#define MTD_ALIAS "if=mtd"
651
#define SD_ALIAS "index=0,if=sd"
652

    
653
static int drive_init_func(QemuOpts *opts, void *opaque)
654
{
655
    int *use_scsi = opaque;
656
    int fatal_error = 0;
657

    
658
    if (drive_init(opts, *use_scsi, &fatal_error) == NULL) {
659
        if (fatal_error)
660
            return 1;
661
    }
662
    return 0;
663
}
664

    
665
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
666
{
667
    if (NULL == qemu_opt_get(opts, "snapshot")) {
668
        qemu_opt_set(opts, "snapshot", "on");
669
    }
670
    return 0;
671
}
672

    
673
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
674
{
675
    boot_set_handler = func;
676
    boot_set_opaque = opaque;
677
}
678

    
679
int qemu_boot_set(const char *boot_devices)
680
{
681
    if (!boot_set_handler) {
682
        return -EINVAL;
683
    }
684
    return boot_set_handler(boot_set_opaque, boot_devices);
685
}
686

    
687
static void validate_bootdevices(char *devices)
688
{
689
    /* We just do some generic consistency checks */
690
    const char *p;
691
    int bitmap = 0;
692

    
693
    for (p = devices; *p != '\0'; p++) {
694
        /* Allowed boot devices are:
695
         * a-b: floppy disk drives
696
         * c-f: IDE disk drives
697
         * g-m: machine implementation dependant drives
698
         * n-p: network devices
699
         * It's up to each machine implementation to check if the given boot
700
         * devices match the actual hardware implementation and firmware
701
         * features.
702
         */
703
        if (*p < 'a' || *p > 'p') {
704
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
705
            exit(1);
706
        }
707
        if (bitmap & (1 << (*p - 'a'))) {
708
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
709
            exit(1);
710
        }
711
        bitmap |= 1 << (*p - 'a');
712
    }
713
}
714

    
715
static void restore_boot_devices(void *opaque)
716
{
717
    char *standard_boot_devices = opaque;
718
    static int first = 1;
719

    
720
    /* Restore boot order and remove ourselves after the first boot */
721
    if (first) {
722
        first = 0;
723
        return;
724
    }
725

    
726
    qemu_boot_set(standard_boot_devices);
727

    
728
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
729
    qemu_free(standard_boot_devices);
730
}
731

    
732
static void numa_add(const char *optarg)
733
{
734
    char option[128];
735
    char *endptr;
736
    unsigned long long value, endvalue;
737
    int nodenr;
738

    
739
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
740
    if (!strcmp(option, "node")) {
741
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
742
            nodenr = nb_numa_nodes;
743
        } else {
744
            nodenr = strtoull(option, NULL, 10);
745
        }
746

    
747
        if (get_param_value(option, 128, "mem", optarg) == 0) {
748
            node_mem[nodenr] = 0;
749
        } else {
750
            value = strtoull(option, &endptr, 0);
751
            switch (*endptr) {
752
            case 0: case 'M': case 'm':
753
                value <<= 20;
754
                break;
755
            case 'G': case 'g':
756
                value <<= 30;
757
                break;
758
            }
759
            node_mem[nodenr] = value;
760
        }
761
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
762
            node_cpumask[nodenr] = 0;
763
        } else {
764
            value = strtoull(option, &endptr, 10);
765
            if (value >= 64) {
766
                value = 63;
767
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
768
            } else {
769
                if (*endptr == '-') {
770
                    endvalue = strtoull(endptr+1, &endptr, 10);
771
                    if (endvalue >= 63) {
772
                        endvalue = 62;
773
                        fprintf(stderr,
774
                            "only 63 CPUs in NUMA mode supported.\n");
775
                    }
776
                    value = (2ULL << endvalue) - (1ULL << value);
777
                } else {
778
                    value = 1ULL << value;
779
                }
780
            }
781
            node_cpumask[nodenr] = value;
782
        }
783
        nb_numa_nodes++;
784
    }
785
    return;
786
}
787

    
788
static void smp_parse(const char *optarg)
789
{
790
    int smp, sockets = 0, threads = 0, cores = 0;
791
    char *endptr;
792
    char option[128];
793

    
794
    smp = strtoul(optarg, &endptr, 10);
795
    if (endptr != optarg) {
796
        if (*endptr == ',') {
797
            endptr++;
798
        }
799
    }
800
    if (get_param_value(option, 128, "sockets", endptr) != 0)
801
        sockets = strtoull(option, NULL, 10);
802
    if (get_param_value(option, 128, "cores", endptr) != 0)
803
        cores = strtoull(option, NULL, 10);
804
    if (get_param_value(option, 128, "threads", endptr) != 0)
805
        threads = strtoull(option, NULL, 10);
806
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
807
        max_cpus = strtoull(option, NULL, 10);
808

    
809
    /* compute missing values, prefer sockets over cores over threads */
810
    if (smp == 0 || sockets == 0) {
811
        sockets = sockets > 0 ? sockets : 1;
812
        cores = cores > 0 ? cores : 1;
813
        threads = threads > 0 ? threads : 1;
814
        if (smp == 0) {
815
            smp = cores * threads * sockets;
816
        }
817
    } else {
818
        if (cores == 0) {
819
            threads = threads > 0 ? threads : 1;
820
            cores = smp / (sockets * threads);
821
        } else {
822
            if (sockets) {
823
                threads = smp / (cores * sockets);
824
            }
825
        }
826
    }
827
    smp_cpus = smp;
828
    smp_cores = cores > 0 ? cores : 1;
829
    smp_threads = threads > 0 ? threads : 1;
830
    if (max_cpus == 0)
831
        max_cpus = smp_cpus;
832
}
833

    
834
/***********************************************************/
835
/* USB devices */
836

    
837
static int usb_device_add(const char *devname)
838
{
839
    const char *p;
840
    USBDevice *dev = NULL;
841

    
842
    if (!usb_enabled)
843
        return -1;
844

    
845
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
846
    dev = usbdevice_create(devname);
847
    if (dev)
848
        goto done;
849

    
850
    /* the other ones */
851
    if (strstart(devname, "host:", &p)) {
852
        dev = usb_host_device_open(p);
853
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
854
        dev = usb_bt_init(devname[2] ? hci_init(p) :
855
                        bt_new_hci(qemu_find_bt_vlan(0)));
856
    } else {
857
        return -1;
858
    }
859
    if (!dev)
860
        return -1;
861

    
862
done:
863
    return 0;
864
}
865

    
866
static int usb_device_del(const char *devname)
867
{
868
    int bus_num, addr;
869
    const char *p;
870

    
871
    if (strstart(devname, "host:", &p))
872
        return usb_host_device_close(p);
873

    
874
    if (!usb_enabled)
875
        return -1;
876

    
877
    p = strchr(devname, '.');
878
    if (!p)
879
        return -1;
880
    bus_num = strtoul(devname, NULL, 0);
881
    addr = strtoul(p + 1, NULL, 0);
882

    
883
    return usb_device_delete_addr(bus_num, addr);
884
}
885

    
886
static int usb_parse(const char *cmdline)
887
{
888
    int r;
889
    r = usb_device_add(cmdline);
890
    if (r < 0) {
891
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
892
    }
893
    return r;
894
}
895

    
896
void do_usb_add(Monitor *mon, const QDict *qdict)
897
{
898
    const char *devname = qdict_get_str(qdict, "devname");
899
    if (usb_device_add(devname) < 0) {
900
        error_report("could not add USB device '%s'", devname);
901
    }
902
}
903

    
904
void do_usb_del(Monitor *mon, const QDict *qdict)
905
{
906
    const char *devname = qdict_get_str(qdict, "devname");
907
    if (usb_device_del(devname) < 0) {
908
        error_report("could not delete USB device '%s'", devname);
909
    }
910
}
911

    
912
/***********************************************************/
913
/* PCMCIA/Cardbus */
914

    
915
static struct pcmcia_socket_entry_s {
916
    PCMCIASocket *socket;
917
    struct pcmcia_socket_entry_s *next;
918
} *pcmcia_sockets = 0;
919

    
920
void pcmcia_socket_register(PCMCIASocket *socket)
921
{
922
    struct pcmcia_socket_entry_s *entry;
923

    
924
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
925
    entry->socket = socket;
926
    entry->next = pcmcia_sockets;
927
    pcmcia_sockets = entry;
928
}
929

    
930
void pcmcia_socket_unregister(PCMCIASocket *socket)
931
{
932
    struct pcmcia_socket_entry_s *entry, **ptr;
933

    
934
    ptr = &pcmcia_sockets;
935
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
936
        if (entry->socket == socket) {
937
            *ptr = entry->next;
938
            qemu_free(entry);
939
        }
940
}
941

    
942
void pcmcia_info(Monitor *mon)
943
{
944
    struct pcmcia_socket_entry_s *iter;
945

    
946
    if (!pcmcia_sockets)
947
        monitor_printf(mon, "No PCMCIA sockets\n");
948

    
949
    for (iter = pcmcia_sockets; iter; iter = iter->next)
950
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
951
                       iter->socket->attached ? iter->socket->card_string :
952
                       "Empty");
953
}
954

    
955
/***********************************************************/
956
/* I/O handling */
957

    
958
typedef struct IOHandlerRecord {
959
    int fd;
960
    IOCanReadHandler *fd_read_poll;
961
    IOHandler *fd_read;
962
    IOHandler *fd_write;
963
    int deleted;
964
    void *opaque;
965
    /* temporary data */
966
    struct pollfd *ufd;
967
    QLIST_ENTRY(IOHandlerRecord) next;
968
} IOHandlerRecord;
969

    
970
static QLIST_HEAD(, IOHandlerRecord) io_handlers =
971
    QLIST_HEAD_INITIALIZER(io_handlers);
972

    
973

    
974
/* XXX: fd_read_poll should be suppressed, but an API change is
975
   necessary in the character devices to suppress fd_can_read(). */
976
int qemu_set_fd_handler2(int fd,
977
                         IOCanReadHandler *fd_read_poll,
978
                         IOHandler *fd_read,
979
                         IOHandler *fd_write,
980
                         void *opaque)
981
{
982
    IOHandlerRecord *ioh;
983

    
984
    if (!fd_read && !fd_write) {
985
        QLIST_FOREACH(ioh, &io_handlers, next) {
986
            if (ioh->fd == fd) {
987
                ioh->deleted = 1;
988
                break;
989
            }
990
        }
991
    } else {
992
        QLIST_FOREACH(ioh, &io_handlers, next) {
993
            if (ioh->fd == fd)
994
                goto found;
995
        }
996
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
997
        QLIST_INSERT_HEAD(&io_handlers, ioh, next);
998
    found:
999
        ioh->fd = fd;
1000
        ioh->fd_read_poll = fd_read_poll;
1001
        ioh->fd_read = fd_read;
1002
        ioh->fd_write = fd_write;
1003
        ioh->opaque = opaque;
1004
        ioh->deleted = 0;
1005
    }
1006
    return 0;
1007
}
1008

    
1009
int qemu_set_fd_handler(int fd,
1010
                        IOHandler *fd_read,
1011
                        IOHandler *fd_write,
1012
                        void *opaque)
1013
{
1014
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1015
}
1016

    
1017
#ifdef _WIN32
1018
/***********************************************************/
1019
/* Polling handling */
1020

    
1021
typedef struct PollingEntry {
1022
    PollingFunc *func;
1023
    void *opaque;
1024
    struct PollingEntry *next;
1025
} PollingEntry;
1026

    
1027
static PollingEntry *first_polling_entry;
1028

    
1029
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1030
{
1031
    PollingEntry **ppe, *pe;
1032
    pe = qemu_mallocz(sizeof(PollingEntry));
1033
    pe->func = func;
1034
    pe->opaque = opaque;
1035
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1036
    *ppe = pe;
1037
    return 0;
1038
}
1039

    
1040
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1041
{
1042
    PollingEntry **ppe, *pe;
1043
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1044
        pe = *ppe;
1045
        if (pe->func == func && pe->opaque == opaque) {
1046
            *ppe = pe->next;
1047
            qemu_free(pe);
1048
            break;
1049
        }
1050
    }
1051
}
1052

    
1053
/***********************************************************/
1054
/* Wait objects support */
1055
typedef struct WaitObjects {
1056
    int num;
1057
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1058
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1059
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1060
} WaitObjects;
1061

    
1062
static WaitObjects wait_objects = {0};
1063

    
1064
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1065
{
1066
    WaitObjects *w = &wait_objects;
1067

    
1068
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
1069
        return -1;
1070
    w->events[w->num] = handle;
1071
    w->func[w->num] = func;
1072
    w->opaque[w->num] = opaque;
1073
    w->num++;
1074
    return 0;
1075
}
1076

    
1077
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1078
{
1079
    int i, found;
1080
    WaitObjects *w = &wait_objects;
1081

    
1082
    found = 0;
1083
    for (i = 0; i < w->num; i++) {
1084
        if (w->events[i] == handle)
1085
            found = 1;
1086
        if (found) {
1087
            w->events[i] = w->events[i + 1];
1088
            w->func[i] = w->func[i + 1];
1089
            w->opaque[i] = w->opaque[i + 1];
1090
        }
1091
    }
1092
    if (found)
1093
        w->num--;
1094
}
1095
#endif
1096

    
1097
/***********************************************************/
1098
/* machine registration */
1099

    
1100
static QEMUMachine *first_machine = NULL;
1101
QEMUMachine *current_machine = NULL;
1102

    
1103
int qemu_register_machine(QEMUMachine *m)
1104
{
1105
    QEMUMachine **pm;
1106
    pm = &first_machine;
1107
    while (*pm != NULL)
1108
        pm = &(*pm)->next;
1109
    m->next = NULL;
1110
    *pm = m;
1111
    return 0;
1112
}
1113

    
1114
static QEMUMachine *find_machine(const char *name)
1115
{
1116
    QEMUMachine *m;
1117

    
1118
    for(m = first_machine; m != NULL; m = m->next) {
1119
        if (!strcmp(m->name, name))
1120
            return m;
1121
        if (m->alias && !strcmp(m->alias, name))
1122
            return m;
1123
    }
1124
    return NULL;
1125
}
1126

    
1127
static QEMUMachine *find_default_machine(void)
1128
{
1129
    QEMUMachine *m;
1130

    
1131
    for(m = first_machine; m != NULL; m = m->next) {
1132
        if (m->is_default) {
1133
            return m;
1134
        }
1135
    }
1136
    return NULL;
1137
}
1138

    
1139
/***********************************************************/
1140
/* main execution loop */
1141

    
1142
static void gui_update(void *opaque)
1143
{
1144
    uint64_t interval = GUI_REFRESH_INTERVAL;
1145
    DisplayState *ds = opaque;
1146
    DisplayChangeListener *dcl = ds->listeners;
1147

    
1148
    qemu_flush_coalesced_mmio_buffer();
1149
    dpy_refresh(ds);
1150

    
1151
    while (dcl != NULL) {
1152
        if (dcl->gui_timer_interval &&
1153
            dcl->gui_timer_interval < interval)
1154
            interval = dcl->gui_timer_interval;
1155
        dcl = dcl->next;
1156
    }
1157
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1158
}
1159

    
1160
static void nographic_update(void *opaque)
1161
{
1162
    uint64_t interval = GUI_REFRESH_INTERVAL;
1163

    
1164
    qemu_flush_coalesced_mmio_buffer();
1165
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1166
}
1167

    
1168
struct vm_change_state_entry {
1169
    VMChangeStateHandler *cb;
1170
    void *opaque;
1171
    QLIST_ENTRY (vm_change_state_entry) entries;
1172
};
1173

    
1174
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1175

    
1176
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1177
                                                     void *opaque)
1178
{
1179
    VMChangeStateEntry *e;
1180

    
1181
    e = qemu_mallocz(sizeof (*e));
1182

    
1183
    e->cb = cb;
1184
    e->opaque = opaque;
1185
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1186
    return e;
1187
}
1188

    
1189
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1190
{
1191
    QLIST_REMOVE (e, entries);
1192
    qemu_free (e);
1193
}
1194

    
1195
void vm_state_notify(int running, int reason)
1196
{
1197
    VMChangeStateEntry *e;
1198

    
1199
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1200
        e->cb(e->opaque, running, reason);
1201
    }
1202
}
1203

    
1204
void vm_start(void)
1205
{
1206
    if (!vm_running) {
1207
        cpu_enable_ticks();
1208
        vm_running = 1;
1209
        vm_state_notify(1, 0);
1210
        resume_all_vcpus();
1211
        monitor_protocol_event(QEVENT_RESUME, NULL);
1212
    }
1213
}
1214

    
1215
/* reset/shutdown handler */
1216

    
1217
typedef struct QEMUResetEntry {
1218
    QTAILQ_ENTRY(QEMUResetEntry) entry;
1219
    QEMUResetHandler *func;
1220
    void *opaque;
1221
} QEMUResetEntry;
1222

    
1223
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1224
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1225
static int reset_requested;
1226
static int shutdown_requested;
1227
static int powerdown_requested;
1228
int debug_requested;
1229
int vmstop_requested;
1230

    
1231
int qemu_shutdown_requested(void)
1232
{
1233
    int r = shutdown_requested;
1234
    shutdown_requested = 0;
1235
    return r;
1236
}
1237

    
1238
int qemu_reset_requested(void)
1239
{
1240
    int r = reset_requested;
1241
    reset_requested = 0;
1242
    return r;
1243
}
1244

    
1245
int qemu_powerdown_requested(void)
1246
{
1247
    int r = powerdown_requested;
1248
    powerdown_requested = 0;
1249
    return r;
1250
}
1251

    
1252
static int qemu_debug_requested(void)
1253
{
1254
    int r = debug_requested;
1255
    debug_requested = 0;
1256
    return r;
1257
}
1258

    
1259
static int qemu_vmstop_requested(void)
1260
{
1261
    int r = vmstop_requested;
1262
    vmstop_requested = 0;
1263
    return r;
1264
}
1265

    
1266
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1267
{
1268
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1269

    
1270
    re->func = func;
1271
    re->opaque = opaque;
1272
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1273
}
1274

    
1275
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1276
{
1277
    QEMUResetEntry *re;
1278

    
1279
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1280
        if (re->func == func && re->opaque == opaque) {
1281
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1282
            qemu_free(re);
1283
            return;
1284
        }
1285
    }
1286
}
1287

    
1288
void qemu_system_reset(void)
1289
{
1290
    QEMUResetEntry *re, *nre;
1291

    
1292
    /* reset all devices */
1293
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1294
        re->func(re->opaque);
1295
    }
1296
    monitor_protocol_event(QEVENT_RESET, NULL);
1297
    cpu_synchronize_all_post_reset();
1298
}
1299

    
1300
void qemu_system_reset_request(void)
1301
{
1302
    if (no_reboot) {
1303
        shutdown_requested = 1;
1304
    } else {
1305
        reset_requested = 1;
1306
    }
1307
    qemu_notify_event();
1308
}
1309

    
1310
void qemu_system_shutdown_request(void)
1311
{
1312
    shutdown_requested = 1;
1313
    qemu_notify_event();
1314
}
1315

    
1316
void qemu_system_powerdown_request(void)
1317
{
1318
    powerdown_requested = 1;
1319
    qemu_notify_event();
1320
}
1321

    
1322
#ifdef _WIN32
1323
static void host_main_loop_wait(int *timeout)
1324
{
1325
    int ret, ret2, i;
1326
    PollingEntry *pe;
1327

    
1328

    
1329
    /* XXX: need to suppress polling by better using win32 events */
1330
    ret = 0;
1331
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
1332
        ret |= pe->func(pe->opaque);
1333
    }
1334
    if (ret == 0) {
1335
        int err;
1336
        WaitObjects *w = &wait_objects;
1337

    
1338
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
1339
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
1340
            if (w->func[ret - WAIT_OBJECT_0])
1341
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
1342

    
1343
            /* Check for additional signaled events */
1344
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
1345

    
1346
                /* Check if event is signaled */
1347
                ret2 = WaitForSingleObject(w->events[i], 0);
1348
                if(ret2 == WAIT_OBJECT_0) {
1349
                    if (w->func[i])
1350
                        w->func[i](w->opaque[i]);
1351
                } else if (ret2 == WAIT_TIMEOUT) {
1352
                } else {
1353
                    err = GetLastError();
1354
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
1355
                }
1356
            }
1357
        } else if (ret == WAIT_TIMEOUT) {
1358
        } else {
1359
            err = GetLastError();
1360
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
1361
        }
1362
    }
1363

    
1364
    *timeout = 0;
1365
}
1366
#else
1367
static void host_main_loop_wait(int *timeout)
1368
{
1369
}
1370
#endif
1371

    
1372
void main_loop_wait(int nonblocking)
1373
{
1374
    IOHandlerRecord *ioh;
1375
    fd_set rfds, wfds, xfds;
1376
    int ret, nfds;
1377
    struct timeval tv;
1378
    int timeout;
1379

    
1380
    if (nonblocking)
1381
        timeout = 0;
1382
    else {
1383
        timeout = qemu_calculate_timeout();
1384
        qemu_bh_update_timeout(&timeout);
1385
    }
1386

    
1387
    host_main_loop_wait(&timeout);
1388

    
1389
    /* poll any events */
1390
    /* XXX: separate device handlers from system ones */
1391
    nfds = -1;
1392
    FD_ZERO(&rfds);
1393
    FD_ZERO(&wfds);
1394
    FD_ZERO(&xfds);
1395
    QLIST_FOREACH(ioh, &io_handlers, next) {
1396
        if (ioh->deleted)
1397
            continue;
1398
        if (ioh->fd_read &&
1399
            (!ioh->fd_read_poll ||
1400
             ioh->fd_read_poll(ioh->opaque) != 0)) {
1401
            FD_SET(ioh->fd, &rfds);
1402
            if (ioh->fd > nfds)
1403
                nfds = ioh->fd;
1404
        }
1405
        if (ioh->fd_write) {
1406
            FD_SET(ioh->fd, &wfds);
1407
            if (ioh->fd > nfds)
1408
                nfds = ioh->fd;
1409
        }
1410
    }
1411

    
1412
    tv.tv_sec = timeout / 1000;
1413
    tv.tv_usec = (timeout % 1000) * 1000;
1414

    
1415
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1416

    
1417
    qemu_mutex_unlock_iothread();
1418
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1419
    qemu_mutex_lock_iothread();
1420
    if (ret > 0) {
1421
        IOHandlerRecord *pioh;
1422

    
1423
        QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
1424
            if (ioh->deleted) {
1425
                QLIST_REMOVE(ioh, next);
1426
                qemu_free(ioh);
1427
                continue;
1428
            }
1429
            if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
1430
                ioh->fd_read(ioh->opaque);
1431
            }
1432
            if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
1433
                ioh->fd_write(ioh->opaque);
1434
            }
1435
        }
1436
    }
1437

    
1438
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1439

    
1440
    qemu_run_all_timers();
1441

    
1442
    /* Check bottom-halves last in case any of the earlier events triggered
1443
       them.  */
1444
    qemu_bh_poll();
1445

    
1446
}
1447

    
1448
static int vm_can_run(void)
1449
{
1450
    if (powerdown_requested)
1451
        return 0;
1452
    if (reset_requested)
1453
        return 0;
1454
    if (shutdown_requested)
1455
        return 0;
1456
    if (debug_requested)
1457
        return 0;
1458
    return 1;
1459
}
1460

    
1461
qemu_irq qemu_system_powerdown;
1462

    
1463
static void main_loop(void)
1464
{
1465
    int r;
1466

    
1467
    qemu_main_loop_start();
1468

    
1469
    for (;;) {
1470
        do {
1471
            bool nonblocking = false;
1472
#ifdef CONFIG_PROFILER
1473
            int64_t ti;
1474
#endif
1475
#ifndef CONFIG_IOTHREAD
1476
            nonblocking = tcg_cpu_exec();
1477
#endif
1478
#ifdef CONFIG_PROFILER
1479
            ti = profile_getclock();
1480
#endif
1481
            main_loop_wait(nonblocking);
1482
#ifdef CONFIG_PROFILER
1483
            dev_time += profile_getclock() - ti;
1484
#endif
1485
        } while (vm_can_run());
1486

    
1487
        if ((r = qemu_debug_requested())) {
1488
            vm_stop(r);
1489
        }
1490
        if (qemu_shutdown_requested()) {
1491
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1492
            if (no_shutdown) {
1493
                vm_stop(0);
1494
                no_shutdown = 0;
1495
            } else
1496
                break;
1497
        }
1498
        if (qemu_reset_requested()) {
1499
            pause_all_vcpus();
1500
            qemu_system_reset();
1501
            resume_all_vcpus();
1502
        }
1503
        if (qemu_powerdown_requested()) {
1504
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1505
            qemu_irq_raise(qemu_system_powerdown);
1506
        }
1507
        if ((r = qemu_vmstop_requested())) {
1508
            vm_stop(r);
1509
        }
1510
    }
1511
    bdrv_close_all();
1512
    pause_all_vcpus();
1513
}
1514

    
1515
static void version(void)
1516
{
1517
    printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
1518
}
1519

    
1520
static void help(int exitcode)
1521
{
1522
    const char *options_help =
1523
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1524
        opt_help
1525
#define DEFHEADING(text) stringify(text) "\n"
1526
#include "qemu-options.h"
1527
#undef DEF
1528
#undef DEFHEADING
1529
#undef GEN_DOCS
1530
        ;
1531
    version();
1532
    printf("usage: %s [options] [disk_image]\n"
1533
           "\n"
1534
           "'disk_image' is a raw hard disk image for IDE hard disk 0\n"
1535
           "\n"
1536
           "%s\n"
1537
           "During emulation, the following keys are useful:\n"
1538
           "ctrl-alt-f      toggle full screen\n"
1539
           "ctrl-alt-n      switch to virtual console 'n'\n"
1540
           "ctrl-alt        toggle mouse and keyboard grab\n"
1541
           "\n"
1542
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
1543
           "qemu",
1544
           options_help);
1545
    exit(exitcode);
1546
}
1547

    
1548
#define HAS_ARG 0x0001
1549

    
1550
enum {
1551
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1552
    opt_enum,
1553
#define DEFHEADING(text)
1554
#include "qemu-options.h"
1555
#undef DEF
1556
#undef DEFHEADING
1557
#undef GEN_DOCS
1558
};
1559

    
1560
typedef struct QEMUOption {
1561
    const char *name;
1562
    int flags;
1563
    int index;
1564
    uint32_t arch_mask;
1565
} QEMUOption;
1566

    
1567
static const QEMUOption qemu_options[] = {
1568
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1569
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1570
    { option, opt_arg, opt_enum, arch_mask },
1571
#define DEFHEADING(text)
1572
#include "qemu-options.h"
1573
#undef DEF
1574
#undef DEFHEADING
1575
#undef GEN_DOCS
1576
    { NULL },
1577
};
1578
static void select_vgahw (const char *p)
1579
{
1580
    const char *opts;
1581

    
1582
    default_vga = 0;
1583
    vga_interface_type = VGA_NONE;
1584
    if (strstart(p, "std", &opts)) {
1585
        vga_interface_type = VGA_STD;
1586
    } else if (strstart(p, "cirrus", &opts)) {
1587
        vga_interface_type = VGA_CIRRUS;
1588
    } else if (strstart(p, "vmware", &opts)) {
1589
        vga_interface_type = VGA_VMWARE;
1590
    } else if (strstart(p, "xenfb", &opts)) {
1591
        vga_interface_type = VGA_XENFB;
1592
    } else if (!strstart(p, "none", &opts)) {
1593
    invalid_vga:
1594
        fprintf(stderr, "Unknown vga type: %s\n", p);
1595
        exit(1);
1596
    }
1597
    while (*opts) {
1598
        const char *nextopt;
1599

    
1600
        if (strstart(opts, ",retrace=", &nextopt)) {
1601
            opts = nextopt;
1602
            if (strstart(opts, "dumb", &nextopt))
1603
                vga_retrace_method = VGA_RETRACE_DUMB;
1604
            else if (strstart(opts, "precise", &nextopt))
1605
                vga_retrace_method = VGA_RETRACE_PRECISE;
1606
            else goto invalid_vga;
1607
        } else goto invalid_vga;
1608
        opts = nextopt;
1609
    }
1610
}
1611

    
1612
static int balloon_parse(const char *arg)
1613
{
1614
    QemuOpts *opts;
1615

    
1616
    if (strcmp(arg, "none") == 0) {
1617
        return 0;
1618
    }
1619

    
1620
    if (!strncmp(arg, "virtio", 6)) {
1621
        if (arg[6] == ',') {
1622
            /* have params -> parse them */
1623
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
1624
            if (!opts)
1625
                return  -1;
1626
        } else {
1627
            /* create empty opts */
1628
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1629
        }
1630
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
1631
        return 0;
1632
    }
1633

    
1634
    return -1;
1635
}
1636

    
1637
#ifdef _WIN32
1638
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
1639
{
1640
    exit(STATUS_CONTROL_C_EXIT);
1641
    return TRUE;
1642
}
1643
#endif
1644

    
1645
#ifndef _WIN32
1646

    
1647
static void termsig_handler(int signal)
1648
{
1649
    qemu_system_shutdown_request();
1650
}
1651

    
1652
static void sigchld_handler(int signal)
1653
{
1654
    waitpid(-1, NULL, WNOHANG);
1655
}
1656

    
1657
static void sighandler_setup(void)
1658
{
1659
    struct sigaction act;
1660

    
1661
    memset(&act, 0, sizeof(act));
1662
    act.sa_handler = termsig_handler;
1663
    sigaction(SIGINT,  &act, NULL);
1664
    sigaction(SIGHUP,  &act, NULL);
1665
    sigaction(SIGTERM, &act, NULL);
1666

    
1667
    act.sa_handler = sigchld_handler;
1668
    act.sa_flags = SA_NOCLDSTOP;
1669
    sigaction(SIGCHLD, &act, NULL);
1670
}
1671

    
1672
#endif
1673

    
1674
#ifdef _WIN32
1675
/* Look for support files in the same directory as the executable.  */
1676
static char *find_datadir(const char *argv0)
1677
{
1678
    char *p;
1679
    char buf[MAX_PATH];
1680
    DWORD len;
1681

    
1682
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
1683
    if (len == 0) {
1684
        return NULL;
1685
    }
1686

    
1687
    buf[len] = 0;
1688
    p = buf + len - 1;
1689
    while (p != buf && *p != '\\')
1690
        p--;
1691
    *p = 0;
1692
    if (access(buf, R_OK) == 0) {
1693
        return qemu_strdup(buf);
1694
    }
1695
    return NULL;
1696
}
1697
#else /* !_WIN32 */
1698

    
1699
/* Find a likely location for support files using the location of the binary.
1700
   For installed binaries this will be "$bindir/../share/qemu".  When
1701
   running from the build tree this will be "$bindir/../pc-bios".  */
1702
#define SHARE_SUFFIX "/share/qemu"
1703
#define BUILD_SUFFIX "/pc-bios"
1704
static char *find_datadir(const char *argv0)
1705
{
1706
    char *dir;
1707
    char *p = NULL;
1708
    char *res;
1709
    char buf[PATH_MAX];
1710
    size_t max_len;
1711

    
1712
#if defined(__linux__)
1713
    {
1714
        int len;
1715
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
1716
        if (len > 0) {
1717
            buf[len] = 0;
1718
            p = buf;
1719
        }
1720
    }
1721
#elif defined(__FreeBSD__)
1722
    {
1723
        static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1724
        size_t len = sizeof(buf) - 1;
1725

    
1726
        *buf = '\0';
1727
        if (!sysctl(mib, sizeof(mib)/sizeof(*mib), buf, &len, NULL, 0) &&
1728
            *buf) {
1729
            buf[sizeof(buf) - 1] = '\0';
1730
            p = buf;
1731
        }
1732
    }
1733
#endif
1734
    /* If we don't have any way of figuring out the actual executable
1735
       location then try argv[0].  */
1736
    if (!p) {
1737
        p = realpath(argv0, buf);
1738
        if (!p) {
1739
            return NULL;
1740
        }
1741
    }
1742
    dir = dirname(p);
1743
    dir = dirname(dir);
1744

    
1745
    max_len = strlen(dir) +
1746
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
1747
    res = qemu_mallocz(max_len);
1748
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
1749
    if (access(res, R_OK)) {
1750
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
1751
        if (access(res, R_OK)) {
1752
            qemu_free(res);
1753
            res = NULL;
1754
        }
1755
    }
1756

    
1757
    return res;
1758
}
1759
#undef SHARE_SUFFIX
1760
#undef BUILD_SUFFIX
1761
#endif
1762

    
1763
char *qemu_find_file(int type, const char *name)
1764
{
1765
    int len;
1766
    const char *subdir;
1767
    char *buf;
1768

    
1769
    /* If name contains path separators then try it as a straight path.  */
1770
    if ((strchr(name, '/') || strchr(name, '\\'))
1771
        && access(name, R_OK) == 0) {
1772
        return qemu_strdup(name);
1773
    }
1774
    switch (type) {
1775
    case QEMU_FILE_TYPE_BIOS:
1776
        subdir = "";
1777
        break;
1778
    case QEMU_FILE_TYPE_KEYMAP:
1779
        subdir = "keymaps/";
1780
        break;
1781
    default:
1782
        abort();
1783
    }
1784
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
1785
    buf = qemu_mallocz(len);
1786
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
1787
    if (access(buf, R_OK)) {
1788
        qemu_free(buf);
1789
        return NULL;
1790
    }
1791
    return buf;
1792
}
1793

    
1794
static int device_help_func(QemuOpts *opts, void *opaque)
1795
{
1796
    return qdev_device_help(opts);
1797
}
1798

    
1799
static int device_init_func(QemuOpts *opts, void *opaque)
1800
{
1801
    DeviceState *dev;
1802

    
1803
    dev = qdev_device_add(opts);
1804
    if (!dev)
1805
        return -1;
1806
    return 0;
1807
}
1808

    
1809
static int chardev_init_func(QemuOpts *opts, void *opaque)
1810
{
1811
    CharDriverState *chr;
1812

    
1813
    chr = qemu_chr_open_opts(opts, NULL);
1814
    if (!chr)
1815
        return -1;
1816
    return 0;
1817
}
1818

    
1819
#ifdef CONFIG_LINUX
1820
static int fsdev_init_func(QemuOpts *opts, void *opaque)
1821
{
1822
    int ret;
1823
    ret = qemu_fsdev_add(opts);
1824

    
1825
    return ret;
1826
}
1827
#endif
1828

    
1829
static int mon_init_func(QemuOpts *opts, void *opaque)
1830
{
1831
    CharDriverState *chr;
1832
    const char *chardev;
1833
    const char *mode;
1834
    int flags;
1835

    
1836
    mode = qemu_opt_get(opts, "mode");
1837
    if (mode == NULL) {
1838
        mode = "readline";
1839
    }
1840
    if (strcmp(mode, "readline") == 0) {
1841
        flags = MONITOR_USE_READLINE;
1842
    } else if (strcmp(mode, "control") == 0) {
1843
        flags = MONITOR_USE_CONTROL;
1844
    } else {
1845
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
1846
        exit(1);
1847
    }
1848

    
1849
    if (qemu_opt_get_bool(opts, "default", 0))
1850
        flags |= MONITOR_IS_DEFAULT;
1851

    
1852
    chardev = qemu_opt_get(opts, "chardev");
1853
    chr = qemu_chr_find(chardev);
1854
    if (chr == NULL) {
1855
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
1856
        exit(1);
1857
    }
1858

    
1859
    monitor_init(chr, flags);
1860
    return 0;
1861
}
1862

    
1863
static void monitor_parse(const char *optarg, const char *mode)
1864
{
1865
    static int monitor_device_index = 0;
1866
    QemuOpts *opts;
1867
    const char *p;
1868
    char label[32];
1869
    int def = 0;
1870

    
1871
    if (strstart(optarg, "chardev:", &p)) {
1872
        snprintf(label, sizeof(label), "%s", p);
1873
    } else {
1874
        snprintf(label, sizeof(label), "compat_monitor%d",
1875
                 monitor_device_index);
1876
        if (monitor_device_index == 0) {
1877
            def = 1;
1878
        }
1879
        opts = qemu_chr_parse_compat(label, optarg);
1880
        if (!opts) {
1881
            fprintf(stderr, "parse error: %s\n", optarg);
1882
            exit(1);
1883
        }
1884
    }
1885

    
1886
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
1887
    if (!opts) {
1888
        fprintf(stderr, "duplicate chardev: %s\n", label);
1889
        exit(1);
1890
    }
1891
    qemu_opt_set(opts, "mode", mode);
1892
    qemu_opt_set(opts, "chardev", label);
1893
    if (def)
1894
        qemu_opt_set(opts, "default", "on");
1895
    monitor_device_index++;
1896
}
1897

    
1898
struct device_config {
1899
    enum {
1900
        DEV_USB,       /* -usbdevice     */
1901
        DEV_BT,        /* -bt            */
1902
        DEV_SERIAL,    /* -serial        */
1903
        DEV_PARALLEL,  /* -parallel      */
1904
        DEV_VIRTCON,   /* -virtioconsole */
1905
        DEV_DEBUGCON,  /* -debugcon */
1906
    } type;
1907
    const char *cmdline;
1908
    QTAILQ_ENTRY(device_config) next;
1909
};
1910
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
1911

    
1912
static void add_device_config(int type, const char *cmdline)
1913
{
1914
    struct device_config *conf;
1915

    
1916
    conf = qemu_mallocz(sizeof(*conf));
1917
    conf->type = type;
1918
    conf->cmdline = cmdline;
1919
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
1920
}
1921

    
1922
static int foreach_device_config(int type, int (*func)(const char *cmdline))
1923
{
1924
    struct device_config *conf;
1925
    int rc;
1926

    
1927
    QTAILQ_FOREACH(conf, &device_configs, next) {
1928
        if (conf->type != type)
1929
            continue;
1930
        rc = func(conf->cmdline);
1931
        if (0 != rc)
1932
            return rc;
1933
    }
1934
    return 0;
1935
}
1936

    
1937
static int serial_parse(const char *devname)
1938
{
1939
    static int index = 0;
1940
    char label[32];
1941

    
1942
    if (strcmp(devname, "none") == 0)
1943
        return 0;
1944
    if (index == MAX_SERIAL_PORTS) {
1945
        fprintf(stderr, "qemu: too many serial ports\n");
1946
        exit(1);
1947
    }
1948
    snprintf(label, sizeof(label), "serial%d", index);
1949
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
1950
    if (!serial_hds[index]) {
1951
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
1952
                devname, strerror(errno));
1953
        return -1;
1954
    }
1955
    index++;
1956
    return 0;
1957
}
1958

    
1959
static int parallel_parse(const char *devname)
1960
{
1961
    static int index = 0;
1962
    char label[32];
1963

    
1964
    if (strcmp(devname, "none") == 0)
1965
        return 0;
1966
    if (index == MAX_PARALLEL_PORTS) {
1967
        fprintf(stderr, "qemu: too many parallel ports\n");
1968
        exit(1);
1969
    }
1970
    snprintf(label, sizeof(label), "parallel%d", index);
1971
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
1972
    if (!parallel_hds[index]) {
1973
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
1974
                devname, strerror(errno));
1975
        return -1;
1976
    }
1977
    index++;
1978
    return 0;
1979
}
1980

    
1981
static int virtcon_parse(const char *devname)
1982
{
1983
    static int index = 0;
1984
    char label[32];
1985
    QemuOpts *bus_opts, *dev_opts;
1986

    
1987
    if (strcmp(devname, "none") == 0)
1988
        return 0;
1989
    if (index == MAX_VIRTIO_CONSOLES) {
1990
        fprintf(stderr, "qemu: too many virtio consoles\n");
1991
        exit(1);
1992
    }
1993

    
1994
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1995
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
1996

    
1997
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1998
    qemu_opt_set(dev_opts, "driver", "virtconsole");
1999

    
2000
    snprintf(label, sizeof(label), "virtcon%d", index);
2001
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2002
    if (!virtcon_hds[index]) {
2003
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2004
                devname, strerror(errno));
2005
        return -1;
2006
    }
2007
    qemu_opt_set(dev_opts, "chardev", label);
2008

    
2009
    index++;
2010
    return 0;
2011
}
2012

    
2013
static int debugcon_parse(const char *devname)
2014
{   
2015
    QemuOpts *opts;
2016

    
2017
    if (!qemu_chr_open("debugcon", devname, NULL)) {
2018
        exit(1);
2019
    }
2020
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2021
    if (!opts) {
2022
        fprintf(stderr, "qemu: already have a debugcon device\n");
2023
        exit(1);
2024
    }
2025
    qemu_opt_set(opts, "driver", "isa-debugcon");
2026
    qemu_opt_set(opts, "chardev", "debugcon");
2027
    return 0;
2028
}
2029

    
2030
static const QEMUOption *lookup_opt(int argc, char **argv,
2031
                                    const char **poptarg, int *poptind)
2032
{
2033
    const QEMUOption *popt;
2034
    int optind = *poptind;
2035
    char *r = argv[optind];
2036
    const char *optarg;
2037

    
2038
    loc_set_cmdline(argv, optind, 1);
2039
    optind++;
2040
    /* Treat --foo the same as -foo.  */
2041
    if (r[1] == '-')
2042
        r++;
2043
    popt = qemu_options;
2044
    for(;;) {
2045
        if (!popt->name) {
2046
            error_report("invalid option");
2047
            exit(1);
2048
        }
2049
        if (!strcmp(popt->name, r + 1))
2050
            break;
2051
        popt++;
2052
    }
2053
    if (popt->flags & HAS_ARG) {
2054
        if (optind >= argc) {
2055
            error_report("requires an argument");
2056
            exit(1);
2057
        }
2058
        optarg = argv[optind++];
2059
        loc_set_cmdline(argv, optind - 2, 2);
2060
    } else {
2061
        optarg = NULL;
2062
    }
2063

    
2064
    *poptarg = optarg;
2065
    *poptind = optind;
2066

    
2067
    return popt;
2068
}
2069

    
2070
int main(int argc, char **argv, char **envp)
2071
{
2072
    const char *gdbstub_dev = NULL;
2073
    int i;
2074
    int snapshot, linux_boot;
2075
    const char *icount_option = NULL;
2076
    const char *initrd_filename;
2077
    const char *kernel_filename, *kernel_cmdline;
2078
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2079
    DisplayState *ds;
2080
    DisplayChangeListener *dcl;
2081
    int cyls, heads, secs, translation;
2082
    QemuOpts *hda_opts = NULL, *opts;
2083
    int optind;
2084
    const char *optarg;
2085
    const char *loadvm = NULL;
2086
    QEMUMachine *machine;
2087
    const char *cpu_model;
2088
#ifndef _WIN32
2089
    int fds[2];
2090
#endif
2091
    int tb_size;
2092
    const char *pid_file = NULL;
2093
    const char *incoming = NULL;
2094
#ifndef _WIN32
2095
    int fd = 0;
2096
    struct passwd *pwd = NULL;
2097
    const char *chroot_dir = NULL;
2098
    const char *run_as = NULL;
2099
#endif
2100
    int show_vnc_port = 0;
2101
    int defconfig = 1;
2102

    
2103
    error_set_progname(argv[0]);
2104

    
2105
    init_clocks();
2106

    
2107
    qemu_cache_utils_init(envp);
2108

    
2109
    QLIST_INIT (&vm_change_state_head);
2110
#ifndef _WIN32
2111
    {
2112
        struct sigaction act;
2113
        sigfillset(&act.sa_mask);
2114
        act.sa_flags = 0;
2115
        act.sa_handler = SIG_IGN;
2116
        sigaction(SIGPIPE, &act, NULL);
2117
    }
2118
#else
2119
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
2120
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
2121
       QEMU to run on a single CPU */
2122
    {
2123
        HANDLE h;
2124
        DWORD mask, smask;
2125
        int i;
2126
        h = GetCurrentProcess();
2127
        if (GetProcessAffinityMask(h, &mask, &smask)) {
2128
            for(i = 0; i < 32; i++) {
2129
                if (mask & (1 << i))
2130
                    break;
2131
            }
2132
            if (i != 32) {
2133
                mask = 1 << i;
2134
                SetProcessAffinityMask(h, mask);
2135
            }
2136
        }
2137
    }
2138
#endif
2139

    
2140
    module_call_init(MODULE_INIT_MACHINE);
2141
    machine = find_default_machine();
2142
    cpu_model = NULL;
2143
    initrd_filename = NULL;
2144
    ram_size = 0;
2145
    snapshot = 0;
2146
    kernel_filename = NULL;
2147
    kernel_cmdline = "";
2148
    cyls = heads = secs = 0;
2149
    translation = BIOS_ATA_TRANSLATION_AUTO;
2150

    
2151
    for (i = 0; i < MAX_NODES; i++) {
2152
        node_mem[i] = 0;
2153
        node_cpumask[i] = 0;
2154
    }
2155

    
2156
    nb_numa_nodes = 0;
2157
    nb_nics = 0;
2158

    
2159
    tb_size = 0;
2160
    autostart= 1;
2161

    
2162
    /* first pass of option parsing */
2163
    optind = 1;
2164
    while (optind < argc) {
2165
        if (argv[optind][0] != '-') {
2166
            /* disk image */
2167
            optind++;
2168
            continue;
2169
        } else {
2170
            const QEMUOption *popt;
2171

    
2172
            popt = lookup_opt(argc, argv, &optarg, &optind);
2173
            switch (popt->index) {
2174
            case QEMU_OPTION_nodefconfig:
2175
                defconfig=0;
2176
                break;
2177
            }
2178
        }
2179
    }
2180

    
2181
    if (defconfig) {
2182
        int ret;
2183

    
2184
        ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2185
        if (ret < 0 && ret != -ENOENT) {
2186
            exit(1);
2187
        }
2188

    
2189
        ret = qemu_read_config_file(arch_config_name);
2190
        if (ret < 0 && ret != -ENOENT) {
2191
            exit(1);
2192
        }
2193
    }
2194
    cpudef_init();
2195

    
2196
    /* second pass of option parsing */
2197
    optind = 1;
2198
    for(;;) {
2199
        if (optind >= argc)
2200
            break;
2201
        if (argv[optind][0] != '-') {
2202
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2203
        } else {
2204
            const QEMUOption *popt;
2205

    
2206
            popt = lookup_opt(argc, argv, &optarg, &optind);
2207
            if (!(popt->arch_mask & arch_type)) {
2208
                printf("Option %s not supported for this target\n", popt->name);
2209
                exit(1);
2210
            }
2211
            switch(popt->index) {
2212
            case QEMU_OPTION_M:
2213
                machine = find_machine(optarg);
2214
                if (!machine) {
2215
                    QEMUMachine *m;
2216
                    printf("Supported machines are:\n");
2217
                    for(m = first_machine; m != NULL; m = m->next) {
2218
                        if (m->alias)
2219
                            printf("%-10s %s (alias of %s)\n",
2220
                                   m->alias, m->desc, m->name);
2221
                        printf("%-10s %s%s\n",
2222
                               m->name, m->desc,
2223
                               m->is_default ? " (default)" : "");
2224
                    }
2225
                    exit(*optarg != '?');
2226
                }
2227
                break;
2228
            case QEMU_OPTION_cpu:
2229
                /* hw initialization will check this */
2230
                if (*optarg == '?') {
2231
                    list_cpus(stdout, &fprintf, optarg);
2232
                    exit(0);
2233
                } else {
2234
                    cpu_model = optarg;
2235
                }
2236
                break;
2237
            case QEMU_OPTION_initrd:
2238
                initrd_filename = optarg;
2239
                break;
2240
            case QEMU_OPTION_hda:
2241
                if (cyls == 0)
2242
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
2243
                else
2244
                    hda_opts = drive_add(optarg, HD_ALIAS
2245
                             ",cyls=%d,heads=%d,secs=%d%s",
2246
                             0, cyls, heads, secs,
2247
                             translation == BIOS_ATA_TRANSLATION_LBA ?
2248
                                 ",trans=lba" :
2249
                             translation == BIOS_ATA_TRANSLATION_NONE ?
2250
                                 ",trans=none" : "");
2251
                 break;
2252
            case QEMU_OPTION_hdb:
2253
            case QEMU_OPTION_hdc:
2254
            case QEMU_OPTION_hdd:
2255
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2256
                break;
2257
            case QEMU_OPTION_drive:
2258
                drive_add(NULL, "%s", optarg);
2259
                break;
2260
            case QEMU_OPTION_set:
2261
                if (qemu_set_option(optarg) != 0)
2262
                    exit(1);
2263
                break;
2264
            case QEMU_OPTION_global:
2265
                if (qemu_global_option(optarg) != 0)
2266
                    exit(1);
2267
                break;
2268
            case QEMU_OPTION_mtdblock:
2269
                drive_add(optarg, MTD_ALIAS);
2270
                break;
2271
            case QEMU_OPTION_sd:
2272
                drive_add(optarg, SD_ALIAS);
2273
                break;
2274
            case QEMU_OPTION_pflash:
2275
                drive_add(optarg, PFLASH_ALIAS);
2276
                break;
2277
            case QEMU_OPTION_snapshot:
2278
                snapshot = 1;
2279
                break;
2280
            case QEMU_OPTION_hdachs:
2281
                {
2282
                    const char *p;
2283
                    p = optarg;
2284
                    cyls = strtol(p, (char **)&p, 0);
2285
                    if (cyls < 1 || cyls > 16383)
2286
                        goto chs_fail;
2287
                    if (*p != ',')
2288
                        goto chs_fail;
2289
                    p++;
2290
                    heads = strtol(p, (char **)&p, 0);
2291
                    if (heads < 1 || heads > 16)
2292
                        goto chs_fail;
2293
                    if (*p != ',')
2294
                        goto chs_fail;
2295
                    p++;
2296
                    secs = strtol(p, (char **)&p, 0);
2297
                    if (secs < 1 || secs > 63)
2298
                        goto chs_fail;
2299
                    if (*p == ',') {
2300
                        p++;
2301
                        if (!strcmp(p, "none"))
2302
                            translation = BIOS_ATA_TRANSLATION_NONE;
2303
                        else if (!strcmp(p, "lba"))
2304
                            translation = BIOS_ATA_TRANSLATION_LBA;
2305
                        else if (!strcmp(p, "auto"))
2306
                            translation = BIOS_ATA_TRANSLATION_AUTO;
2307
                        else
2308
                            goto chs_fail;
2309
                    } else if (*p != '\0') {
2310
                    chs_fail:
2311
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
2312
                        exit(1);
2313
                    }
2314
                    if (hda_opts != NULL) {
2315
                        char num[16];
2316
                        snprintf(num, sizeof(num), "%d", cyls);
2317
                        qemu_opt_set(hda_opts, "cyls", num);
2318
                        snprintf(num, sizeof(num), "%d", heads);
2319
                        qemu_opt_set(hda_opts, "heads", num);
2320
                        snprintf(num, sizeof(num), "%d", secs);
2321
                        qemu_opt_set(hda_opts, "secs", num);
2322
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
2323
                            qemu_opt_set(hda_opts, "trans", "lba");
2324
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
2325
                            qemu_opt_set(hda_opts, "trans", "none");
2326
                    }
2327
                }
2328
                break;
2329
            case QEMU_OPTION_numa:
2330
                if (nb_numa_nodes >= MAX_NODES) {
2331
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
2332
                    exit(1);
2333
                }
2334
                numa_add(optarg);
2335
                break;
2336
            case QEMU_OPTION_nographic:
2337
                display_type = DT_NOGRAPHIC;
2338
                break;
2339
#ifdef CONFIG_CURSES
2340
            case QEMU_OPTION_curses:
2341
                display_type = DT_CURSES;
2342
                break;
2343
#endif
2344
            case QEMU_OPTION_portrait:
2345
                graphic_rotate = 1;
2346
                break;
2347
            case QEMU_OPTION_kernel:
2348
                kernel_filename = optarg;
2349
                break;
2350
            case QEMU_OPTION_append:
2351
                kernel_cmdline = optarg;
2352
                break;
2353
            case QEMU_OPTION_cdrom:
2354
                drive_add(optarg, CDROM_ALIAS);
2355
                break;
2356
            case QEMU_OPTION_boot:
2357
                {
2358
                    static const char * const params[] = {
2359
                        "order", "once", "menu", NULL
2360
                    };
2361
                    char buf[sizeof(boot_devices)];
2362
                    char *standard_boot_devices;
2363
                    int legacy = 0;
2364

    
2365
                    if (!strchr(optarg, '=')) {
2366
                        legacy = 1;
2367
                        pstrcpy(buf, sizeof(buf), optarg);
2368
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2369
                        fprintf(stderr,
2370
                                "qemu: unknown boot parameter '%s' in '%s'\n",
2371
                                buf, optarg);
2372
                        exit(1);
2373
                    }
2374

    
2375
                    if (legacy ||
2376
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
2377
                        validate_bootdevices(buf);
2378
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
2379
                    }
2380
                    if (!legacy) {
2381
                        if (get_param_value(buf, sizeof(buf),
2382
                                            "once", optarg)) {
2383
                            validate_bootdevices(buf);
2384
                            standard_boot_devices = qemu_strdup(boot_devices);
2385
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
2386
                            qemu_register_reset(restore_boot_devices,
2387
                                                standard_boot_devices);
2388
                        }
2389
                        if (get_param_value(buf, sizeof(buf),
2390
                                            "menu", optarg)) {
2391
                            if (!strcmp(buf, "on")) {
2392
                                boot_menu = 1;
2393
                            } else if (!strcmp(buf, "off")) {
2394
                                boot_menu = 0;
2395
                            } else {
2396
                                fprintf(stderr,
2397
                                        "qemu: invalid option value '%s'\n",
2398
                                        buf);
2399
                                exit(1);
2400
                            }
2401
                        }
2402
                    }
2403
                }
2404
                break;
2405
            case QEMU_OPTION_fda:
2406
            case QEMU_OPTION_fdb:
2407
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2408
                break;
2409
            case QEMU_OPTION_no_fd_bootchk:
2410
                fd_bootchk = 0;
2411
                break;
2412
            case QEMU_OPTION_netdev:
2413
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
2414
                    exit(1);
2415
                }
2416
                break;
2417
            case QEMU_OPTION_net:
2418
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
2419
                    exit(1);
2420
                }
2421
                break;
2422
#ifdef CONFIG_SLIRP
2423
            case QEMU_OPTION_tftp:
2424
                legacy_tftp_prefix = optarg;
2425
                break;
2426
            case QEMU_OPTION_bootp:
2427
                legacy_bootp_filename = optarg;
2428
                break;
2429
#ifndef _WIN32
2430
            case QEMU_OPTION_smb:
2431
                if (net_slirp_smb(optarg) < 0)
2432
                    exit(1);
2433
                break;
2434
#endif
2435
            case QEMU_OPTION_redir:
2436
                if (net_slirp_redir(optarg) < 0)
2437
                    exit(1);
2438
                break;
2439
#endif
2440
            case QEMU_OPTION_bt:
2441
                add_device_config(DEV_BT, optarg);
2442
                break;
2443
            case QEMU_OPTION_audio_help:
2444
                if (!(audio_available())) {
2445
                    printf("Option %s not supported for this target\n", popt->name);
2446
                    exit(1);
2447
                }
2448
                AUD_help ();
2449
                exit (0);
2450
                break;
2451
            case QEMU_OPTION_soundhw:
2452
                if (!(audio_available())) {
2453
                    printf("Option %s not supported for this target\n", popt->name);
2454
                    exit(1);
2455
                }
2456
                select_soundhw (optarg);
2457
                break;
2458
            case QEMU_OPTION_h:
2459
                help(0);
2460
                break;
2461
            case QEMU_OPTION_version:
2462
                version();
2463
                exit(0);
2464
                break;
2465
            case QEMU_OPTION_m: {
2466
                uint64_t value;
2467
                char *ptr;
2468

    
2469
                value = strtoul(optarg, &ptr, 10);
2470
                switch (*ptr) {
2471
                case 0: case 'M': case 'm':
2472
                    value <<= 20;
2473
                    break;
2474
                case 'G': case 'g':
2475
                    value <<= 30;
2476
                    break;
2477
                default:
2478
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
2479
                    exit(1);
2480
                }
2481

    
2482
                /* On 32-bit hosts, QEMU is limited by virtual address space */
2483
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
2484
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
2485
                    exit(1);
2486
                }
2487
                if (value != (uint64_t)(ram_addr_t)value) {
2488
                    fprintf(stderr, "qemu: ram size too large\n");
2489
                    exit(1);
2490
                }
2491
                ram_size = value;
2492
                break;
2493
            }
2494
            case QEMU_OPTION_mempath:
2495
                mem_path = optarg;
2496
                break;
2497
#ifdef MAP_POPULATE
2498
            case QEMU_OPTION_mem_prealloc:
2499
                mem_prealloc = 1;
2500
                break;
2501
#endif
2502
            case QEMU_OPTION_d:
2503
                set_cpu_log(optarg);
2504
                break;
2505
            case QEMU_OPTION_s:
2506
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
2507
                break;
2508
            case QEMU_OPTION_gdb:
2509
                gdbstub_dev = optarg;
2510
                break;
2511
            case QEMU_OPTION_L:
2512
                data_dir = optarg;
2513
                break;
2514
            case QEMU_OPTION_bios:
2515
                bios_name = optarg;
2516
                break;
2517
            case QEMU_OPTION_singlestep:
2518
                singlestep = 1;
2519
                break;
2520
            case QEMU_OPTION_S:
2521
                autostart = 0;
2522
                break;
2523
            case QEMU_OPTION_k:
2524
                keyboard_layout = optarg;
2525
                break;
2526
            case QEMU_OPTION_localtime:
2527
                rtc_utc = 0;
2528
                break;
2529
            case QEMU_OPTION_vga:
2530
                select_vgahw (optarg);
2531
                break;
2532
            case QEMU_OPTION_g:
2533
                {
2534
                    const char *p;
2535
                    int w, h, depth;
2536
                    p = optarg;
2537
                    w = strtol(p, (char **)&p, 10);
2538
                    if (w <= 0) {
2539
                    graphic_error:
2540
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
2541
                        exit(1);
2542
                    }
2543
                    if (*p != 'x')
2544
                        goto graphic_error;
2545
                    p++;
2546
                    h = strtol(p, (char **)&p, 10);
2547
                    if (h <= 0)
2548
                        goto graphic_error;
2549
                    if (*p == 'x') {
2550
                        p++;
2551
                        depth = strtol(p, (char **)&p, 10);
2552
                        if (depth != 8 && depth != 15 && depth != 16 &&
2553
                            depth != 24 && depth != 32)
2554
                            goto graphic_error;
2555
                    } else if (*p == '\0') {
2556
                        depth = graphic_depth;
2557
                    } else {
2558
                        goto graphic_error;
2559
                    }
2560

    
2561
                    graphic_width = w;
2562
                    graphic_height = h;
2563
                    graphic_depth = depth;
2564
                }
2565
                break;
2566
            case QEMU_OPTION_echr:
2567
                {
2568
                    char *r;
2569
                    term_escape_char = strtol(optarg, &r, 0);
2570
                    if (r == optarg)
2571
                        printf("Bad argument to echr\n");
2572
                    break;
2573
                }
2574
            case QEMU_OPTION_monitor:
2575
                monitor_parse(optarg, "readline");
2576
                default_monitor = 0;
2577
                break;
2578
            case QEMU_OPTION_qmp:
2579
                monitor_parse(optarg, "control");
2580
                default_monitor = 0;
2581
                break;
2582
            case QEMU_OPTION_mon:
2583
                opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
2584
                if (!opts) {
2585
                    exit(1);
2586
                }
2587
                default_monitor = 0;
2588
                break;
2589
            case QEMU_OPTION_chardev:
2590
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
2591
                if (!opts) {
2592
                    exit(1);
2593
                }
2594
                break;
2595
#ifdef CONFIG_LINUX
2596
            case QEMU_OPTION_fsdev:
2597
                opts = qemu_opts_parse(&qemu_fsdev_opts, optarg, 1);
2598
                if (!opts) {
2599
                    fprintf(stderr, "parse error: %s\n", optarg);
2600
                    exit(1);
2601
                }
2602
                break;
2603
            case QEMU_OPTION_virtfs: {
2604
                char *arg_fsdev = NULL;
2605
                char *arg_9p = NULL;
2606
                int len = 0;
2607

    
2608
                opts = qemu_opts_parse(&qemu_virtfs_opts, optarg, 1);
2609
                if (!opts) {
2610
                    fprintf(stderr, "parse error: %s\n", optarg);
2611
                    exit(1);
2612
                }
2613

    
2614
                len = strlen(",id=,path=");
2615
                len += strlen(qemu_opt_get(opts, "fstype"));
2616
                len += strlen(qemu_opt_get(opts, "mount_tag"));
2617
                len += strlen(qemu_opt_get(opts, "path"));
2618
                arg_fsdev = qemu_malloc((len + 1) * sizeof(*arg_fsdev));
2619

    
2620
                if (!arg_fsdev) {
2621
                    fprintf(stderr, "No memory to parse -fsdev for %s\n",
2622
                            optarg);
2623
                    exit(1);
2624
                }
2625

    
2626
                sprintf(arg_fsdev, "%s,id=%s,path=%s",
2627
                                qemu_opt_get(opts, "fstype"),
2628
                                qemu_opt_get(opts, "mount_tag"),
2629
                                qemu_opt_get(opts, "path"));
2630

    
2631
                len = strlen("virtio-9p-pci,fsdev=,mount_tag=");
2632
                len += 2*strlen(qemu_opt_get(opts, "mount_tag"));
2633
                arg_9p = qemu_malloc((len + 1) * sizeof(*arg_9p));
2634

    
2635
                if (!arg_9p) {
2636
                    fprintf(stderr, "No memory to parse -device for %s\n",
2637
                            optarg);
2638
                    exit(1);
2639
                }
2640

    
2641
                sprintf(arg_9p, "virtio-9p-pci,fsdev=%s,mount_tag=%s",
2642
                                qemu_opt_get(opts, "mount_tag"),
2643
                                qemu_opt_get(opts, "mount_tag"));
2644

    
2645
                if (!qemu_opts_parse(&qemu_fsdev_opts, arg_fsdev, 1)) {
2646
                    fprintf(stderr, "parse error [fsdev]: %s\n", optarg);
2647
                    exit(1);
2648
                }
2649

    
2650
                if (!qemu_opts_parse(&qemu_device_opts, arg_9p, 1)) {
2651
                    fprintf(stderr, "parse error [device]: %s\n", optarg);
2652
                    exit(1);
2653
                }
2654

    
2655
                qemu_free(arg_fsdev);
2656
                qemu_free(arg_9p);
2657
                break;
2658
            }
2659
#endif
2660
            case QEMU_OPTION_serial:
2661
                add_device_config(DEV_SERIAL, optarg);
2662
                default_serial = 0;
2663
                if (strncmp(optarg, "mon:", 4) == 0) {
2664
                    default_monitor = 0;
2665
                }
2666
                break;
2667
            case QEMU_OPTION_watchdog:
2668
                if (watchdog) {
2669
                    fprintf(stderr,
2670
                            "qemu: only one watchdog option may be given\n");
2671
                    return 1;
2672
                }
2673
                watchdog = optarg;
2674
                break;
2675
            case QEMU_OPTION_watchdog_action:
2676
                if (select_watchdog_action(optarg) == -1) {
2677
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
2678
                    exit(1);
2679
                }
2680
                break;
2681
            case QEMU_OPTION_virtiocon:
2682
                add_device_config(DEV_VIRTCON, optarg);
2683
                default_virtcon = 0;
2684
                if (strncmp(optarg, "mon:", 4) == 0) {
2685
                    default_monitor = 0;
2686
                }
2687
                break;
2688
            case QEMU_OPTION_parallel:
2689
                add_device_config(DEV_PARALLEL, optarg);
2690
                default_parallel = 0;
2691
                if (strncmp(optarg, "mon:", 4) == 0) {
2692
                    default_monitor = 0;
2693
                }
2694
                break;
2695
            case QEMU_OPTION_debugcon:
2696
                add_device_config(DEV_DEBUGCON, optarg);
2697
                break;
2698
            case QEMU_OPTION_loadvm:
2699
                loadvm = optarg;
2700
                break;
2701
            case QEMU_OPTION_full_screen:
2702
                full_screen = 1;
2703
                break;
2704
#ifdef CONFIG_SDL
2705
            case QEMU_OPTION_no_frame:
2706
                no_frame = 1;
2707
                break;
2708
            case QEMU_OPTION_alt_grab:
2709
                alt_grab = 1;
2710
                break;
2711
            case QEMU_OPTION_ctrl_grab:
2712
                ctrl_grab = 1;
2713
                break;
2714
            case QEMU_OPTION_no_quit:
2715
                no_quit = 1;
2716
                break;
2717
            case QEMU_OPTION_sdl:
2718
                display_type = DT_SDL;
2719
                break;
2720
#endif
2721
            case QEMU_OPTION_pidfile:
2722
                pid_file = optarg;
2723
                break;
2724
            case QEMU_OPTION_win2k_hack:
2725
                win2k_install_hack = 1;
2726
                break;
2727
            case QEMU_OPTION_rtc_td_hack:
2728
                rtc_td_hack = 1;
2729
                break;
2730
            case QEMU_OPTION_acpitable:
2731
                do_acpitable_option(optarg);
2732
                break;
2733
            case QEMU_OPTION_smbios:
2734
                do_smbios_option(optarg);
2735
                break;
2736
            case QEMU_OPTION_enable_kvm:
2737
                kvm_allowed = 1;
2738
                break;
2739
            case QEMU_OPTION_usb:
2740
                usb_enabled = 1;
2741
                break;
2742
            case QEMU_OPTION_usbdevice:
2743
                usb_enabled = 1;
2744
                add_device_config(DEV_USB, optarg);
2745
                break;
2746
            case QEMU_OPTION_device:
2747
                if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
2748
                    exit(1);
2749
                }
2750
                break;
2751
            case QEMU_OPTION_smp:
2752
                smp_parse(optarg);
2753
                if (smp_cpus < 1) {
2754
                    fprintf(stderr, "Invalid number of CPUs\n");
2755
                    exit(1);
2756
                }
2757
                if (max_cpus < smp_cpus) {
2758
                    fprintf(stderr, "maxcpus must be equal to or greater than "
2759
                            "smp\n");
2760
                    exit(1);
2761
                }
2762
                if (max_cpus > 255) {
2763
                    fprintf(stderr, "Unsupported number of maxcpus\n");
2764
                    exit(1);
2765
                }
2766
                break;
2767
            case QEMU_OPTION_vnc:
2768
                display_type = DT_VNC;
2769
                vnc_display = optarg;
2770
                break;
2771
            case QEMU_OPTION_no_acpi:
2772
                acpi_enabled = 0;
2773
                break;
2774
            case QEMU_OPTION_no_hpet:
2775
                no_hpet = 1;
2776
                break;
2777
            case QEMU_OPTION_balloon:
2778
                if (balloon_parse(optarg) < 0) {
2779
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
2780
                    exit(1);
2781
                }
2782
                break;
2783
            case QEMU_OPTION_no_reboot:
2784
                no_reboot = 1;
2785
                break;
2786
            case QEMU_OPTION_no_shutdown:
2787
                no_shutdown = 1;
2788
                break;
2789
            case QEMU_OPTION_show_cursor:
2790
                cursor_hide = 0;
2791
                break;
2792
            case QEMU_OPTION_uuid:
2793
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
2794
                    fprintf(stderr, "Fail to parse UUID string."
2795
                            " Wrong format.\n");
2796
                    exit(1);
2797
                }
2798
                break;
2799
#ifndef _WIN32
2800
            case QEMU_OPTION_daemonize:
2801
                daemonize = 1;
2802
                break;
2803
#endif
2804
            case QEMU_OPTION_option_rom:
2805
                if (nb_option_roms >= MAX_OPTION_ROMS) {
2806
                    fprintf(stderr, "Too many option ROMs\n");
2807
                    exit(1);
2808
                }
2809
                option_rom[nb_option_roms] = optarg;
2810
                nb_option_roms++;
2811
                break;
2812
            case QEMU_OPTION_semihosting:
2813
                semihosting_enabled = 1;
2814
                break;
2815
            case QEMU_OPTION_name:
2816
                qemu_name = qemu_strdup(optarg);
2817
                 {
2818
                     char *p = strchr(qemu_name, ',');
2819
                     if (p != NULL) {
2820
                        *p++ = 0;
2821
                        if (strncmp(p, "process=", 8)) {
2822
                            fprintf(stderr, "Unknown subargument %s to -name", p);
2823
                            exit(1);
2824
                        }
2825
                        p += 8;
2826
                        set_proc_name(p);
2827
                     }        
2828
                 }        
2829
                break;
2830
            case QEMU_OPTION_prom_env:
2831
                if (nb_prom_envs >= MAX_PROM_ENVS) {
2832
                    fprintf(stderr, "Too many prom variables\n");
2833
                    exit(1);
2834
                }
2835
                prom_envs[nb_prom_envs] = optarg;
2836
                nb_prom_envs++;
2837
                break;
2838
            case QEMU_OPTION_old_param:
2839
                old_param = 1;
2840
                break;
2841
            case QEMU_OPTION_clock:
2842
                configure_alarms(optarg);
2843
                break;
2844
            case QEMU_OPTION_startdate:
2845
                configure_rtc_date_offset(optarg, 1);
2846
                break;
2847
            case QEMU_OPTION_rtc:
2848
                opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
2849
                if (!opts) {
2850
                    exit(1);
2851
                }
2852
                configure_rtc(opts);
2853
                break;
2854
            case QEMU_OPTION_tb_size:
2855
                tb_size = strtol(optarg, NULL, 0);
2856
                if (tb_size < 0)
2857
                    tb_size = 0;
2858
                break;
2859
            case QEMU_OPTION_icount:
2860
                icount_option = optarg;
2861
                break;
2862
            case QEMU_OPTION_incoming:
2863
                incoming = optarg;
2864
                break;
2865
            case QEMU_OPTION_nodefaults:
2866
                default_serial = 0;
2867
                default_parallel = 0;
2868
                default_virtcon = 0;
2869
                default_monitor = 0;
2870
                default_vga = 0;
2871
                default_net = 0;
2872
                default_floppy = 0;
2873
                default_cdrom = 0;
2874
                default_sdcard = 0;
2875
                break;
2876
#ifndef _WIN32
2877
            case QEMU_OPTION_chroot:
2878
                chroot_dir = optarg;
2879
                break;
2880
            case QEMU_OPTION_runas:
2881
                run_as = optarg;
2882
                break;
2883
#endif
2884
            case QEMU_OPTION_xen_domid:
2885
                if (!(xen_available())) {
2886
                    printf("Option %s not supported for this target\n", popt->name);
2887
                    exit(1);
2888
                }
2889
                xen_domid = atoi(optarg);
2890
                break;
2891
            case QEMU_OPTION_xen_create:
2892
                if (!(xen_available())) {
2893
                    printf("Option %s not supported for this target\n", popt->name);
2894
                    exit(1);
2895
                }
2896
                xen_mode = XEN_CREATE;
2897
                break;
2898
            case QEMU_OPTION_xen_attach:
2899
                if (!(xen_available())) {
2900
                    printf("Option %s not supported for this target\n", popt->name);
2901
                    exit(1);
2902
                }
2903
                xen_mode = XEN_ATTACH;
2904
                break;
2905
            case QEMU_OPTION_readconfig:
2906
                {
2907
                    int ret = qemu_read_config_file(optarg);
2908
                    if (ret < 0) {
2909
                        fprintf(stderr, "read config %s: %s\n", optarg,
2910
                            strerror(-ret));
2911
                        exit(1);
2912
                    }
2913
                    break;
2914
                }
2915
            case QEMU_OPTION_writeconfig:
2916
                {
2917
                    FILE *fp;
2918
                    if (strcmp(optarg, "-") == 0) {
2919
                        fp = stdout;
2920
                    } else {
2921
                        fp = fopen(optarg, "w");
2922
                        if (fp == NULL) {
2923
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
2924
                            exit(1);
2925
                        }
2926
                    }
2927
                    qemu_config_write(fp);
2928
                    fclose(fp);
2929
                    break;
2930
                }
2931
            }
2932
        }
2933
    }
2934
    loc_set_none();
2935

    
2936
    /* If no data_dir is specified then try to find it relative to the
2937
       executable path.  */
2938
    if (!data_dir) {
2939
        data_dir = find_datadir(argv[0]);
2940
    }
2941
    /* If all else fails use the install patch specified when building.  */
2942
    if (!data_dir) {
2943
        data_dir = CONFIG_QEMU_SHAREDIR;
2944
    }
2945

    
2946
    /*
2947
     * Default to max_cpus = smp_cpus, in case the user doesn't
2948
     * specify a max_cpus value.
2949
     */
2950
    if (!max_cpus)
2951
        max_cpus = smp_cpus;
2952

    
2953
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
2954
    if (smp_cpus > machine->max_cpus) {
2955
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
2956
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
2957
                machine->max_cpus);
2958
        exit(1);
2959
    }
2960

    
2961
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
2962
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
2963

    
2964
    if (machine->no_serial) {
2965
        default_serial = 0;
2966
    }
2967
    if (machine->no_parallel) {
2968
        default_parallel = 0;
2969
    }
2970
    if (!machine->use_virtcon) {
2971
        default_virtcon = 0;
2972
    }
2973
    if (machine->no_vga) {
2974
        default_vga = 0;
2975
    }
2976
    if (machine->no_floppy) {
2977
        default_floppy = 0;
2978
    }
2979
    if (machine->no_cdrom) {
2980
        default_cdrom = 0;
2981
    }
2982
    if (machine->no_sdcard) {
2983
        default_sdcard = 0;
2984
    }
2985

    
2986
    if (display_type == DT_NOGRAPHIC) {
2987
        if (default_parallel)
2988
            add_device_config(DEV_PARALLEL, "null");
2989
        if (default_serial && default_monitor) {
2990
            add_device_config(DEV_SERIAL, "mon:stdio");
2991
        } else if (default_virtcon && default_monitor) {
2992
            add_device_config(DEV_VIRTCON, "mon:stdio");
2993
        } else {
2994
            if (default_serial)
2995
                add_device_config(DEV_SERIAL, "stdio");
2996
            if (default_virtcon)
2997
                add_device_config(DEV_VIRTCON, "stdio");
2998
            if (default_monitor)
2999
                monitor_parse("stdio", "readline");
3000
        }
3001
    } else {
3002
        if (default_serial)
3003
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
3004
        if (default_parallel)
3005
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3006
        if (default_monitor)
3007
            monitor_parse("vc:80Cx24C", "readline");
3008
        if (default_virtcon)
3009
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3010
    }
3011
    if (default_vga)
3012
        vga_interface_type = VGA_CIRRUS;
3013

    
3014
    socket_init();
3015

    
3016
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3017
        exit(1);
3018
#ifdef CONFIG_LINUX
3019
    if (qemu_opts_foreach(&qemu_fsdev_opts, fsdev_init_func, NULL, 1) != 0) {
3020
        exit(1);
3021
    }
3022
#endif
3023

    
3024
#ifndef _WIN32
3025
    if (daemonize) {
3026
        pid_t pid;
3027

    
3028
        if (pipe(fds) == -1)
3029
            exit(1);
3030

    
3031
        pid = fork();
3032
        if (pid > 0) {
3033
            uint8_t status;
3034
            ssize_t len;
3035

    
3036
            close(fds[1]);
3037

    
3038
        again:
3039
            len = read(fds[0], &status, 1);
3040
            if (len == -1 && (errno == EINTR))
3041
                goto again;
3042

    
3043
            if (len != 1)
3044
                exit(1);
3045
            else if (status == 1) {
3046
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3047
                exit(1);
3048
            } else
3049
                exit(0);
3050
        } else if (pid < 0)
3051
            exit(1);
3052

    
3053
        close(fds[0]);
3054
        qemu_set_cloexec(fds[1]);
3055

    
3056
        setsid();
3057

    
3058
        pid = fork();
3059
        if (pid > 0)
3060
            exit(0);
3061
        else if (pid < 0)
3062
            exit(1);
3063

    
3064
        umask(027);
3065

    
3066
        signal(SIGTSTP, SIG_IGN);
3067
        signal(SIGTTOU, SIG_IGN);
3068
        signal(SIGTTIN, SIG_IGN);
3069
    }
3070
#endif
3071

    
3072
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3073
#ifndef _WIN32
3074
        if (daemonize) {
3075
            uint8_t status = 1;
3076
            if (write(fds[1], &status, 1) != 1) {
3077
                perror("daemonize. Writing to pipe\n");
3078
            }
3079
        } else
3080
#endif
3081
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3082
        exit(1);
3083
    }
3084

    
3085
    if (kvm_allowed) {
3086
        int ret = kvm_init(smp_cpus);
3087
        if (ret < 0) {
3088
            if (!kvm_available()) {
3089
                printf("KVM not supported for this target\n");
3090
            } else {
3091
                fprintf(stderr, "failed to initialize KVM: %s\n", strerror(-ret));
3092
            }
3093
            exit(1);
3094
        }
3095
    }
3096

    
3097
    if (qemu_init_main_loop()) {
3098
        fprintf(stderr, "qemu_init_main_loop failed\n");
3099
        exit(1);
3100
    }
3101
    linux_boot = (kernel_filename != NULL);
3102

    
3103
    if (!linux_boot && *kernel_cmdline != '\0') {
3104
        fprintf(stderr, "-append only allowed with -kernel option\n");
3105
        exit(1);
3106
    }
3107

    
3108
    if (!linux_boot && initrd_filename != NULL) {
3109
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3110
        exit(1);
3111
    }
3112

    
3113
#ifndef _WIN32
3114
    /* Win32 doesn't support line-buffering and requires size >= 2 */
3115
    setvbuf(stdout, NULL, _IOLBF, 0);
3116
#endif
3117

    
3118
    if (init_timer_alarm() < 0) {
3119
        fprintf(stderr, "could not initialize alarm timer\n");
3120
        exit(1);
3121
    }
3122
    configure_icount(icount_option);
3123

    
3124
    if (net_init_clients() < 0) {
3125
        exit(1);
3126
    }
3127

    
3128
    /* init the bluetooth world */
3129
    if (foreach_device_config(DEV_BT, bt_parse))
3130
        exit(1);
3131

    
3132
    /* init the memory */
3133
    if (ram_size == 0)
3134
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3135

    
3136
    /* init the dynamic translator */
3137
    cpu_exec_init_all(tb_size * 1024 * 1024);
3138

    
3139
    bdrv_init_with_whitelist();
3140

    
3141
    blk_mig_init();
3142

    
3143
    if (default_cdrom) {
3144
        /* we always create the cdrom drive, even if no disk is there */
3145
        drive_add(NULL, CDROM_ALIAS);
3146
    }
3147

    
3148
    if (default_floppy) {
3149
        /* we always create at least one floppy */
3150
        drive_add(NULL, FD_ALIAS, 0);
3151
    }
3152

    
3153
    if (default_sdcard) {
3154
        /* we always create one sd slot, even if no card is in it */
3155
        drive_add(NULL, SD_ALIAS);
3156
    }
3157

    
3158
    /* open the virtual block devices */
3159
    if (snapshot)
3160
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
3161
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, &machine->use_scsi, 1) != 0)
3162
        exit(1);
3163

    
3164
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
3165
                         ram_load, NULL);
3166

    
3167
    if (nb_numa_nodes > 0) {
3168
        int i;
3169

    
3170
        if (nb_numa_nodes > smp_cpus) {
3171
            nb_numa_nodes = smp_cpus;
3172
        }
3173

    
3174
        /* If no memory size if given for any node, assume the default case
3175
         * and distribute the available memory equally across all nodes
3176
         */
3177
        for (i = 0; i < nb_numa_nodes; i++) {
3178
            if (node_mem[i] != 0)
3179
                break;
3180
        }
3181
        if (i == nb_numa_nodes) {
3182
            uint64_t usedmem = 0;
3183

    
3184
            /* On Linux, the each node's border has to be 8MB aligned,
3185
             * the final node gets the rest.
3186
             */
3187
            for (i = 0; i < nb_numa_nodes - 1; i++) {
3188
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3189
                usedmem += node_mem[i];
3190
            }
3191
            node_mem[i] = ram_size - usedmem;
3192
        }
3193

    
3194
        for (i = 0; i < nb_numa_nodes; i++) {
3195
            if (node_cpumask[i] != 0)
3196
                break;
3197
        }
3198
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3199
         * must cope with this anyway, because there are BIOSes out there in
3200
         * real machines which also use this scheme.
3201
         */
3202
        if (i == nb_numa_nodes) {
3203
            for (i = 0; i < smp_cpus; i++) {
3204
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
3205
            }
3206
        }
3207
    }
3208

    
3209
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0) {
3210
        exit(1);
3211
    }
3212

    
3213
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3214
        exit(1);
3215
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3216
        exit(1);
3217
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3218
        exit(1);
3219
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3220
        exit(1);
3221

    
3222
    module_call_init(MODULE_INIT_DEVICE);
3223

    
3224
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
3225
        exit(0);
3226

    
3227
    if (watchdog) {
3228
        i = select_watchdog(watchdog);
3229
        if (i > 0)
3230
            exit (i == 1 ? 1 : 0);
3231
    }
3232

    
3233
    if (machine->compat_props) {
3234
        qdev_prop_register_global_list(machine->compat_props);
3235
    }
3236
    qemu_add_globals();
3237

    
3238
    machine->init(ram_size, boot_devices,
3239
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3240

    
3241
    cpu_synchronize_all_post_init();
3242

    
3243
#ifndef _WIN32
3244
    /* must be after terminal init, SDL library changes signal handlers */
3245
    sighandler_setup();
3246
#endif
3247

    
3248
    set_numa_modes();
3249

    
3250
    current_machine = machine;
3251

    
3252
    /* init USB devices */
3253
    if (usb_enabled) {
3254
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3255
            exit(1);
3256
    }
3257

    
3258
    /* init generic devices */
3259
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
3260
        exit(1);
3261

    
3262
    net_check_clients();
3263

    
3264
    /* just use the first displaystate for the moment */
3265
    ds = get_displaystate();
3266

    
3267
    if (display_type == DT_DEFAULT) {
3268
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3269
        display_type = DT_SDL;
3270
#else
3271
        display_type = DT_VNC;
3272
        vnc_display = "localhost:0,to=99";
3273
        show_vnc_port = 1;
3274
#endif
3275
    }
3276
        
3277

    
3278
    switch (display_type) {
3279
    case DT_NOGRAPHIC:
3280
        break;
3281
#if defined(CONFIG_CURSES)
3282
    case DT_CURSES:
3283
        curses_display_init(ds, full_screen);
3284
        break;
3285
#endif
3286
#if defined(CONFIG_SDL)
3287
    case DT_SDL:
3288
        sdl_display_init(ds, full_screen, no_frame);
3289
        break;
3290
#elif defined(CONFIG_COCOA)
3291
    case DT_SDL:
3292
        cocoa_display_init(ds, full_screen);
3293
        break;
3294
#endif
3295
    case DT_VNC:
3296
        vnc_display_init(ds);
3297
        if (vnc_display_open(ds, vnc_display) < 0)
3298
            exit(1);
3299

    
3300
        if (show_vnc_port) {
3301
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3302
        }
3303
        break;
3304
    default:
3305
        break;
3306
    }
3307
    dpy_resize(ds);
3308

    
3309
    dcl = ds->listeners;
3310
    while (dcl != NULL) {
3311
        if (dcl->dpy_refresh != NULL) {
3312
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
3313
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
3314
        }
3315
        dcl = dcl->next;
3316
    }
3317

    
3318
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
3319
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
3320
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
3321
    }
3322

    
3323
    text_consoles_set_display(ds);
3324

    
3325
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3326
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3327
                gdbstub_dev);
3328
        exit(1);
3329
    }
3330

    
3331
    qdev_machine_creation_done();
3332

    
3333
    if (rom_load_all() != 0) {
3334
        fprintf(stderr, "rom loading failed\n");
3335
        exit(1);
3336
    }
3337

    
3338
    qemu_system_reset();
3339
    if (loadvm) {
3340
        if (load_vmstate(loadvm) < 0) {
3341
            autostart = 0;
3342
        }
3343
    }
3344

    
3345
    if (incoming) {
3346
        qemu_start_incoming_migration(incoming);
3347
    } else if (autostart) {
3348
        vm_start();
3349
    }
3350

    
3351
#ifndef _WIN32
3352
    if (daemonize) {
3353
        uint8_t status = 0;
3354
        ssize_t len;
3355

    
3356
    again1:
3357
        len = write(fds[1], &status, 1);
3358
        if (len == -1 && (errno == EINTR))
3359
            goto again1;
3360

    
3361
        if (len != 1)
3362
            exit(1);
3363

    
3364
        if (chdir("/")) {
3365
            perror("not able to chdir to /");
3366
            exit(1);
3367
        }
3368
        TFR(fd = qemu_open("/dev/null", O_RDWR));
3369
        if (fd == -1)
3370
            exit(1);
3371
    }
3372

    
3373
    if (run_as) {
3374
        pwd = getpwnam(run_as);
3375
        if (!pwd) {
3376
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
3377
            exit(1);
3378
        }
3379
    }
3380

    
3381
    if (chroot_dir) {
3382
        if (chroot(chroot_dir) < 0) {
3383
            fprintf(stderr, "chroot failed\n");
3384
            exit(1);
3385
        }
3386
        if (chdir("/")) {
3387
            perror("not able to chdir to /");
3388
            exit(1);
3389
        }
3390
    }
3391

    
3392
    if (run_as) {
3393
        if (setgid(pwd->pw_gid) < 0) {
3394
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
3395
            exit(1);
3396
        }
3397
        if (setuid(pwd->pw_uid) < 0) {
3398
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
3399
            exit(1);
3400
        }
3401
        if (setuid(0) != -1) {
3402
            fprintf(stderr, "Dropping privileges failed\n");
3403
            exit(1);
3404
        }
3405
    }
3406

    
3407
    if (daemonize) {
3408
        dup2(fd, 0);
3409
        dup2(fd, 1);
3410
        dup2(fd, 2);
3411

    
3412
        close(fd);
3413
    }
3414
#endif
3415

    
3416
    main_loop();
3417
    quit_timers();
3418
    net_cleanup();
3419

    
3420
    return 0;
3421
}