Statistics
| Branch: | Revision:

root / vl.c @ 28c28973

History | View | Annotate | Download (103.7 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 "block_int.h"
144
#include "block-migration.h"
145
#include "dma.h"
146
#include "audio/audio.h"
147
#include "migration.h"
148
#include "kvm.h"
149
#include "qemu-option.h"
150
#include "qemu-config.h"
151
#include "qemu-objects.h"
152

    
153
#include "disas.h"
154

    
155
#include "qemu_socket.h"
156

    
157
#include "slirp/libslirp.h"
158

    
159
#include "qemu-queue.h"
160
#include "cpus.h"
161
#include "arch_init.h"
162

    
163
//#define DEBUG_NET
164
//#define DEBUG_SLIRP
165

    
166
#define DEFAULT_RAM_SIZE 128
167

    
168
#define MAX_VIRTIO_CONSOLES 1
169

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

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

    
236
static QEMUTimer *nographic_timer;
237

    
238
uint8_t qemu_uuid[16];
239

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

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

    
247
#ifdef SIGRTMIN
248
#define SIG_IPI (SIGRTMIN+4)
249
#else
250
#define SIG_IPI SIGUSR1
251
#endif
252

    
253
static int default_serial = 1;
254
static int default_parallel = 1;
255
static int default_virtcon = 1;
256
static int default_monitor = 1;
257
static int default_vga = 1;
258
static int default_floppy = 1;
259
static int default_cdrom = 1;
260
static int default_sdcard = 1;
261

    
262
static struct {
263
    const char *driver;
264
    int *flag;
265
} default_list[] = {
266
    { .driver = "isa-serial",           .flag = &default_serial    },
267
    { .driver = "isa-parallel",         .flag = &default_parallel  },
268
    { .driver = "isa-fdc",              .flag = &default_floppy    },
269
    { .driver = "ide-drive",            .flag = &default_cdrom     },
270
    { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
271
    { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
272
    { .driver = "virtio-serial",        .flag = &default_virtcon   },
273
    { .driver = "VGA",                  .flag = &default_vga       },
274
    { .driver = "cirrus-vga",           .flag = &default_vga       },
275
    { .driver = "vmware-svga",          .flag = &default_vga       },
276
};
277

    
278
static int default_driver_check(QemuOpts *opts, void *opaque)
279
{
280
    const char *driver = qemu_opt_get(opts, "driver");
281
    int i;
282

    
283
    if (!driver)
284
        return 0;
285
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
286
        if (strcmp(default_list[i].driver, driver) != 0)
287
            continue;
288
        *(default_list[i].flag) = 0;
289
    }
290
    return 0;
291
}
292

    
293
/***********************************************************/
294

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

    
312
/* compute with 96 bit intermediate result: (a*b)/c */
313
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
314
{
315
    union {
316
        uint64_t ll;
317
        struct {
318
#ifdef HOST_WORDS_BIGENDIAN
319
            uint32_t high, low;
320
#else
321
            uint32_t low, high;
322
#endif
323
        } l;
324
    } u, res;
325
    uint64_t rl, rh;
326

    
327
    u.ll = a;
328
    rl = (uint64_t)u.l.low * (uint64_t)b;
329
    rh = (uint64_t)u.l.high * (uint64_t)b;
330
    rh += (rl >> 32);
331
    res.l.high = rh / c;
332
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
333
    return res.ll;
334
}
335

    
336
/***********************************************************/
337
/* host time/date access */
338
void qemu_get_timedate(struct tm *tm, int offset)
339
{
340
    time_t ti;
341
    struct tm *ret;
342

    
343
    time(&ti);
344
    ti += offset;
345
    if (rtc_date_offset == -1) {
346
        if (rtc_utc)
347
            ret = gmtime(&ti);
348
        else
349
            ret = localtime(&ti);
350
    } else {
351
        ti -= rtc_date_offset;
352
        ret = gmtime(&ti);
353
    }
354

    
355
    memcpy(tm, ret, sizeof(struct tm));
356
}
357

    
358
int qemu_timedate_diff(struct tm *tm)
359
{
360
    time_t seconds;
361

    
362
    if (rtc_date_offset == -1)
363
        if (rtc_utc)
364
            seconds = mktimegm(tm);
365
        else
366
            seconds = mktime(tm);
367
    else
368
        seconds = mktimegm(tm) + rtc_date_offset;
369

    
370
    return seconds - time(NULL);
371
}
372

    
373
void rtc_change_mon_event(struct tm *tm)
374
{
375
    QObject *data;
376

    
377
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
378
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
379
    qobject_decref(data);
380
}
381

    
382
static void configure_rtc_date_offset(const char *startdate, int legacy)
383
{
384
    time_t rtc_start_date;
385
    struct tm tm;
386

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

    
421
static void configure_rtc(QemuOpts *opts)
422
{
423
    const char *value;
424

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

    
459
/***********************************************************/
460
/* Bluetooth support */
461
static int nb_hcis;
462
static int cur_hci;
463
static struct HCIInfo *hci_table[MAX_NICS];
464

    
465
static struct bt_vlan_s {
466
    struct bt_scatternet_s net;
467
    int id;
468
    struct bt_vlan_s *next;
469
} *first_bt_vlan;
470

    
471
/* find or alloc a new bluetooth "VLAN" */
472
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
473
{
474
    struct bt_vlan_s **pvlan, *vlan;
475
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
476
        if (vlan->id == id)
477
            return &vlan->net;
478
    }
479
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
480
    vlan->id = id;
481
    pvlan = &first_bt_vlan;
482
    while (*pvlan != NULL)
483
        pvlan = &(*pvlan)->next;
484
    *pvlan = vlan;
485
    return &vlan->net;
486
}
487

    
488
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
489
{
490
}
491

    
492
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
493
{
494
    return -ENOTSUP;
495
}
496

    
497
static struct HCIInfo null_hci = {
498
    .cmd_send = null_hci_send,
499
    .sco_send = null_hci_send,
500
    .acl_send = null_hci_send,
501
    .bdaddr_set = null_hci_addr_set,
502
};
503

    
504
struct HCIInfo *qemu_next_hci(void)
505
{
506
    if (cur_hci == nb_hcis)
507
        return &null_hci;
508

    
509
    return hci_table[cur_hci++];
510
}
511

    
512
static struct HCIInfo *hci_init(const char *str)
513
{
514
    char *endp;
515
    struct bt_scatternet_s *vlan = 0;
516

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

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

    
539
    return 0;
540
}
541

    
542
static int bt_hci_parse(const char *str)
543
{
544
    struct HCIInfo *hci;
545
    bdaddr_t bdaddr;
546

    
547
    if (nb_hcis >= MAX_NICS) {
548
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
549
        return -1;
550
    }
551

    
552
    hci = hci_init(str);
553
    if (!hci)
554
        return -1;
555

    
556
    bdaddr.b[0] = 0x52;
557
    bdaddr.b[1] = 0x54;
558
    bdaddr.b[2] = 0x00;
559
    bdaddr.b[3] = 0x12;
560
    bdaddr.b[4] = 0x34;
561
    bdaddr.b[5] = 0x56 + nb_hcis;
562
    hci->bdaddr_set(hci, bdaddr.b);
563

    
564
    hci_table[nb_hcis++] = hci;
565

    
566
    return 0;
567
}
568

    
569
static void bt_vhci_add(int vlan_id)
570
{
571
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
572

    
573
    if (!vlan->slave)
574
        fprintf(stderr, "qemu: warning: adding a VHCI to "
575
                        "an empty scatternet %i\n", vlan_id);
576

    
577
    bt_vhci_init(bt_new_hci(vlan));
578
}
579

    
580
static struct bt_device_s *bt_device_add(const char *opt)
581
{
582
    struct bt_scatternet_s *vlan;
583
    int vlan_id = 0;
584
    char *endp = strstr(opt, ",vlan=");
585
    int len = (endp ? endp - opt : strlen(opt)) + 1;
586
    char devname[10];
587

    
588
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
589

    
590
    if (endp) {
591
        vlan_id = strtol(endp + 6, &endp, 0);
592
        if (*endp) {
593
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
594
            return 0;
595
        }
596
    }
597

    
598
    vlan = qemu_find_bt_vlan(vlan_id);
599

    
600
    if (!vlan->slave)
601
        fprintf(stderr, "qemu: warning: adding a slave device to "
602
                        "an empty scatternet %i\n", vlan_id);
603

    
604
    if (!strcmp(devname, "keyboard"))
605
        return bt_keyboard_init(vlan);
606

    
607
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
608
    return 0;
609
}
610

    
611
static int bt_parse(const char *opt)
612
{
613
    const char *endp, *p;
614
    int vlan;
615

    
616
    if (strstart(opt, "hci", &endp)) {
617
        if (!*endp || *endp == ',') {
618
            if (*endp)
619
                if (!strstart(endp, ",vlan=", 0))
620
                    opt = endp + 1;
621

    
622
            return bt_hci_parse(opt);
623
       }
624
    } else if (strstart(opt, "vhci", &endp)) {
625
        if (!*endp || *endp == ',') {
626
            if (*endp) {
627
                if (strstart(endp, ",vlan=", &p)) {
628
                    vlan = strtol(p, (char **) &endp, 0);
629
                    if (*endp) {
630
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
631
                        return 1;
632
                    }
633
                } else {
634
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
635
                    return 1;
636
                }
637
            } else
638
                vlan = 0;
639

    
640
            bt_vhci_add(vlan);
641
            return 0;
642
        }
643
    } else if (strstart(opt, "device:", &endp))
644
        return !bt_device_add(endp);
645

    
646
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
647
    return 1;
648
}
649

    
650
/***********************************************************/
651
/* QEMU Block devices */
652

    
653
#define HD_ALIAS "index=%d,media=disk"
654
#define CDROM_ALIAS "index=2,media=cdrom"
655
#define FD_ALIAS "index=%d,if=floppy"
656
#define PFLASH_ALIAS "if=pflash"
657
#define MTD_ALIAS "if=mtd"
658
#define SD_ALIAS "index=0,if=sd"
659

    
660
QemuOpts *drive_add(const char *file, const char *fmt, ...)
661
{
662
    va_list ap;
663
    char optstr[1024];
664
    QemuOpts *opts;
665

    
666
    va_start(ap, fmt);
667
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
668
    va_end(ap);
669

    
670
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
671
    if (!opts) {
672
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
673
                __FUNCTION__, optstr);
674
        return NULL;
675
    }
676
    if (file)
677
        qemu_opt_set(opts, "file", file);
678
    return opts;
679
}
680

    
681
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
682
{
683
    DriveInfo *dinfo;
684

    
685
    /* seek interface, bus and unit */
686

    
687
    QTAILQ_FOREACH(dinfo, &drives, next) {
688
        if (dinfo->type == type &&
689
            dinfo->bus == bus &&
690
            dinfo->unit == unit)
691
            return dinfo;
692
    }
693

    
694
    return NULL;
695
}
696

    
697
DriveInfo *drive_get_by_id(const char *id)
698
{
699
    DriveInfo *dinfo;
700

    
701
    QTAILQ_FOREACH(dinfo, &drives, next) {
702
        if (strcmp(id, dinfo->id))
703
            continue;
704
        return dinfo;
705
    }
706
    return NULL;
707
}
708

    
709
int drive_get_max_bus(BlockInterfaceType type)
710
{
711
    int max_bus;
712
    DriveInfo *dinfo;
713

    
714
    max_bus = -1;
715
    QTAILQ_FOREACH(dinfo, &drives, next) {
716
        if(dinfo->type == type &&
717
           dinfo->bus > max_bus)
718
            max_bus = dinfo->bus;
719
    }
720
    return max_bus;
721
}
722

    
723
const char *drive_get_serial(BlockDriverState *bdrv)
724
{
725
    DriveInfo *dinfo;
726

    
727
    QTAILQ_FOREACH(dinfo, &drives, next) {
728
        if (dinfo->bdrv == bdrv)
729
            return dinfo->serial;
730
    }
731

    
732
    return "\0";
733
}
734

    
735
BlockInterfaceErrorAction drive_get_on_error(
736
    BlockDriverState *bdrv, int is_read)
737
{
738
    DriveInfo *dinfo;
739

    
740
    QTAILQ_FOREACH(dinfo, &drives, next) {
741
        if (dinfo->bdrv == bdrv)
742
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
743
    }
744

    
745
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
746
}
747

    
748
static void bdrv_format_print(void *opaque, const char *name)
749
{
750
    fprintf(stderr, " %s", name);
751
}
752

    
753
void drive_uninit(DriveInfo *dinfo)
754
{
755
    qemu_opts_del(dinfo->opts);
756
    bdrv_delete(dinfo->bdrv);
757
    QTAILQ_REMOVE(&drives, dinfo, next);
758
    qemu_free(dinfo);
759
}
760

    
761
static int parse_block_error_action(const char *buf, int is_read)
762
{
763
    if (!strcmp(buf, "ignore")) {
764
        return BLOCK_ERR_IGNORE;
765
    } else if (!is_read && !strcmp(buf, "enospc")) {
766
        return BLOCK_ERR_STOP_ENOSPC;
767
    } else if (!strcmp(buf, "stop")) {
768
        return BLOCK_ERR_STOP_ANY;
769
    } else if (!strcmp(buf, "report")) {
770
        return BLOCK_ERR_REPORT;
771
    } else {
772
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
773
            buf, is_read ? "read" : "write");
774
        return -1;
775
    }
776
}
777

    
778
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
779
                      int *fatal_error)
780
{
781
    const char *buf;
782
    const char *file = NULL;
783
    char devname[128];
784
    const char *serial;
785
    const char *mediastr = "";
786
    BlockInterfaceType type;
787
    enum { MEDIA_DISK, MEDIA_CDROM } media;
788
    int bus_id, unit_id;
789
    int cyls, heads, secs, translation;
790
    BlockDriver *drv = NULL;
791
    QEMUMachine *machine = opaque;
792
    int max_devs;
793
    int index;
794
    int cache;
795
    int aio = 0;
796
    int ro = 0;
797
    int bdrv_flags;
798
    int on_read_error, on_write_error;
799
    const char *devaddr;
800
    DriveInfo *dinfo;
801
    int snapshot = 0;
802

    
803
    *fatal_error = 1;
804

    
805
    translation = BIOS_ATA_TRANSLATION_AUTO;
806
    cache = 1;
807

    
808
    if (machine && machine->use_scsi) {
809
        type = IF_SCSI;
810
        max_devs = MAX_SCSI_DEVS;
811
        pstrcpy(devname, sizeof(devname), "scsi");
812
    } else {
813
        type = IF_IDE;
814
        max_devs = MAX_IDE_DEVS;
815
        pstrcpy(devname, sizeof(devname), "ide");
816
    }
817
    media = MEDIA_DISK;
818

    
819
    /* extract parameters */
820
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
821
    unit_id = qemu_opt_get_number(opts, "unit", -1);
822
    index   = qemu_opt_get_number(opts, "index", -1);
823

    
824
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
825
    heads = qemu_opt_get_number(opts, "heads", 0);
826
    secs  = qemu_opt_get_number(opts, "secs", 0);
827

    
828
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
829
    ro = qemu_opt_get_bool(opts, "readonly", 0);
830

    
831
    file = qemu_opt_get(opts, "file");
832
    serial = qemu_opt_get(opts, "serial");
833

    
834
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
835
        pstrcpy(devname, sizeof(devname), buf);
836
        if (!strcmp(buf, "ide")) {
837
            type = IF_IDE;
838
            max_devs = MAX_IDE_DEVS;
839
        } else if (!strcmp(buf, "scsi")) {
840
            type = IF_SCSI;
841
            max_devs = MAX_SCSI_DEVS;
842
        } else if (!strcmp(buf, "floppy")) {
843
            type = IF_FLOPPY;
844
            max_devs = 0;
845
        } else if (!strcmp(buf, "pflash")) {
846
            type = IF_PFLASH;
847
            max_devs = 0;
848
        } else if (!strcmp(buf, "mtd")) {
849
            type = IF_MTD;
850
            max_devs = 0;
851
        } else if (!strcmp(buf, "sd")) {
852
            type = IF_SD;
853
            max_devs = 0;
854
        } else if (!strcmp(buf, "virtio")) {
855
            type = IF_VIRTIO;
856
            max_devs = 0;
857
        } else if (!strcmp(buf, "xen")) {
858
            type = IF_XEN;
859
            max_devs = 0;
860
        } else if (!strcmp(buf, "none")) {
861
            type = IF_NONE;
862
            max_devs = 0;
863
        } else {
864
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
865
            return NULL;
866
        }
867
    }
868

    
869
    if (cyls || heads || secs) {
870
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
871
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
872
            return NULL;
873
        }
874
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
875
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
876
            return NULL;
877
        }
878
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
879
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
880
            return NULL;
881
        }
882
    }
883

    
884
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
885
        if (!cyls) {
886
            fprintf(stderr,
887
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
888
                    buf);
889
            return NULL;
890
        }
891
        if (!strcmp(buf, "none"))
892
            translation = BIOS_ATA_TRANSLATION_NONE;
893
        else if (!strcmp(buf, "lba"))
894
            translation = BIOS_ATA_TRANSLATION_LBA;
895
        else if (!strcmp(buf, "auto"))
896
            translation = BIOS_ATA_TRANSLATION_AUTO;
897
        else {
898
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
899
            return NULL;
900
        }
901
    }
902

    
903
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
904
        if (!strcmp(buf, "disk")) {
905
            media = MEDIA_DISK;
906
        } else if (!strcmp(buf, "cdrom")) {
907
            if (cyls || secs || heads) {
908
                fprintf(stderr,
909
                        "qemu: '%s' invalid physical CHS format\n", buf);
910
                return NULL;
911
            }
912
            media = MEDIA_CDROM;
913
        } else {
914
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
915
            return NULL;
916
        }
917
    }
918

    
919
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
920
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
921
            cache = 0;
922
        else if (!strcmp(buf, "writethrough"))
923
            cache = 1;
924
        else if (!strcmp(buf, "writeback"))
925
            cache = 2;
926
        else {
927
           fprintf(stderr, "qemu: invalid cache option\n");
928
           return NULL;
929
        }
930
    }
931

    
932
#ifdef CONFIG_LINUX_AIO
933
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
934
        if (!strcmp(buf, "threads"))
935
            aio = 0;
936
        else if (!strcmp(buf, "native"))
937
            aio = 1;
938
        else {
939
           fprintf(stderr, "qemu: invalid aio option\n");
940
           return NULL;
941
        }
942
    }
943
#endif
944

    
945
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
946
       if (strcmp(buf, "?") == 0) {
947
            fprintf(stderr, "qemu: Supported formats:");
948
            bdrv_iterate_format(bdrv_format_print, NULL);
949
            fprintf(stderr, "\n");
950
            return NULL;
951
        }
952
        drv = bdrv_find_whitelisted_format(buf);
953
        if (!drv) {
954
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
955
            return NULL;
956
        }
957
    }
958

    
959
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
960
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
961
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
962
            fprintf(stderr, "werror is no supported by this format\n");
963
            return NULL;
964
        }
965

    
966
        on_write_error = parse_block_error_action(buf, 0);
967
        if (on_write_error < 0) {
968
            return NULL;
969
        }
970
    }
971

    
972
    on_read_error = BLOCK_ERR_REPORT;
973
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
974
        if (type != IF_IDE && type != IF_VIRTIO) {
975
            fprintf(stderr, "rerror is no supported by this format\n");
976
            return NULL;
977
        }
978

    
979
        on_read_error = parse_block_error_action(buf, 1);
980
        if (on_read_error < 0) {
981
            return NULL;
982
        }
983
    }
984

    
985
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
986
        if (type != IF_VIRTIO) {
987
            fprintf(stderr, "addr is not supported\n");
988
            return NULL;
989
        }
990
    }
991

    
992
    /* compute bus and unit according index */
993

    
994
    if (index != -1) {
995
        if (bus_id != 0 || unit_id != -1) {
996
            fprintf(stderr,
997
                    "qemu: index cannot be used with bus and unit\n");
998
            return NULL;
999
        }
1000
        if (max_devs == 0)
1001
        {
1002
            unit_id = index;
1003
            bus_id = 0;
1004
        } else {
1005
            unit_id = index % max_devs;
1006
            bus_id = index / max_devs;
1007
        }
1008
    }
1009

    
1010
    /* if user doesn't specify a unit_id,
1011
     * try to find the first free
1012
     */
1013

    
1014
    if (unit_id == -1) {
1015
       unit_id = 0;
1016
       while (drive_get(type, bus_id, unit_id) != NULL) {
1017
           unit_id++;
1018
           if (max_devs && unit_id >= max_devs) {
1019
               unit_id -= max_devs;
1020
               bus_id++;
1021
           }
1022
       }
1023
    }
1024

    
1025
    /* check unit id */
1026

    
1027
    if (max_devs && unit_id >= max_devs) {
1028
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1029
                unit_id, max_devs - 1);
1030
        return NULL;
1031
    }
1032

    
1033
    /*
1034
     * ignore multiple definitions
1035
     */
1036

    
1037
    if (drive_get(type, bus_id, unit_id) != NULL) {
1038
        *fatal_error = 0;
1039
        return NULL;
1040
    }
1041

    
1042
    /* init */
1043

    
1044
    dinfo = qemu_mallocz(sizeof(*dinfo));
1045
    if ((buf = qemu_opts_id(opts)) != NULL) {
1046
        dinfo->id = qemu_strdup(buf);
1047
    } else {
1048
        /* no id supplied -> create one */
1049
        dinfo->id = qemu_mallocz(32);
1050
        if (type == IF_IDE || type == IF_SCSI)
1051
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1052
        if (max_devs)
1053
            snprintf(dinfo->id, 32, "%s%i%s%i",
1054
                     devname, bus_id, mediastr, unit_id);
1055
        else
1056
            snprintf(dinfo->id, 32, "%s%s%i",
1057
                     devname, mediastr, unit_id);
1058
    }
1059
    dinfo->bdrv = bdrv_new(dinfo->id);
1060
    dinfo->devaddr = devaddr;
1061
    dinfo->type = type;
1062
    dinfo->bus = bus_id;
1063
    dinfo->unit = unit_id;
1064
    dinfo->on_read_error = on_read_error;
1065
    dinfo->on_write_error = on_write_error;
1066
    dinfo->opts = opts;
1067
    if (serial)
1068
        strncpy(dinfo->serial, serial, sizeof(serial));
1069
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1070

    
1071
    switch(type) {
1072
    case IF_IDE:
1073
    case IF_SCSI:
1074
    case IF_XEN:
1075
    case IF_NONE:
1076
        switch(media) {
1077
        case MEDIA_DISK:
1078
            if (cyls != 0) {
1079
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1080
                bdrv_set_translation_hint(dinfo->bdrv, translation);
1081
            }
1082
            break;
1083
        case MEDIA_CDROM:
1084
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1085
            break;
1086
        }
1087
        break;
1088
    case IF_SD:
1089
        /* FIXME: This isn't really a floppy, but it's a reasonable
1090
           approximation.  */
1091
    case IF_FLOPPY:
1092
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1093
        break;
1094
    case IF_PFLASH:
1095
    case IF_MTD:
1096
        break;
1097
    case IF_VIRTIO:
1098
        /* add virtio block device */
1099
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1100
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
1101
        qemu_opt_set(opts, "drive", dinfo->id);
1102
        if (devaddr)
1103
            qemu_opt_set(opts, "addr", devaddr);
1104
        break;
1105
    case IF_COUNT:
1106
        abort();
1107
    }
1108
    if (!file) {
1109
        *fatal_error = 0;
1110
        return NULL;
1111
    }
1112
    bdrv_flags = 0;
1113
    if (snapshot) {
1114
        bdrv_flags |= BDRV_O_SNAPSHOT;
1115
        cache = 2; /* always use write-back with snapshot */
1116
    }
1117
    if (cache == 0) /* no caching */
1118
        bdrv_flags |= BDRV_O_NOCACHE;
1119
    else if (cache == 2) /* write-back */
1120
        bdrv_flags |= BDRV_O_CACHE_WB;
1121

    
1122
    if (aio == 1) {
1123
        bdrv_flags |= BDRV_O_NATIVE_AIO;
1124
    } else {
1125
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1126
    }
1127

    
1128
    if (media == MEDIA_CDROM) {
1129
        /* CDROM is fine for any interface, don't check.  */
1130
        ro = 1;
1131
    } else if (ro == 1) {
1132
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1133
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1134
            return NULL;
1135
        }
1136
    }
1137

    
1138
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1139

    
1140
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1141
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1142
                        file, strerror(errno));
1143
        return NULL;
1144
    }
1145

    
1146
    if (bdrv_key_required(dinfo->bdrv))
1147
        autostart = 0;
1148
    *fatal_error = 0;
1149
    return dinfo;
1150
}
1151

    
1152
static int drive_init_func(QemuOpts *opts, void *opaque)
1153
{
1154
    QEMUMachine *machine = opaque;
1155
    int fatal_error = 0;
1156

    
1157
    if (drive_init(opts, machine, &fatal_error) == NULL) {
1158
        if (fatal_error)
1159
            return 1;
1160
    }
1161
    return 0;
1162
}
1163

    
1164
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1165
{
1166
    if (NULL == qemu_opt_get(opts, "snapshot")) {
1167
        qemu_opt_set(opts, "snapshot", "on");
1168
    }
1169
    return 0;
1170
}
1171

    
1172
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1173
{
1174
    boot_set_handler = func;
1175
    boot_set_opaque = opaque;
1176
}
1177

    
1178
int qemu_boot_set(const char *boot_devices)
1179
{
1180
    if (!boot_set_handler) {
1181
        return -EINVAL;
1182
    }
1183
    return boot_set_handler(boot_set_opaque, boot_devices);
1184
}
1185

    
1186
static int parse_bootdevices(char *devices)
1187
{
1188
    /* We just do some generic consistency checks */
1189
    const char *p;
1190
    int bitmap = 0;
1191

    
1192
    for (p = devices; *p != '\0'; p++) {
1193
        /* Allowed boot devices are:
1194
         * a-b: floppy disk drives
1195
         * c-f: IDE disk drives
1196
         * g-m: machine implementation dependant drives
1197
         * n-p: network devices
1198
         * It's up to each machine implementation to check if the given boot
1199
         * devices match the actual hardware implementation and firmware
1200
         * features.
1201
         */
1202
        if (*p < 'a' || *p > 'p') {
1203
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
1204
            exit(1);
1205
        }
1206
        if (bitmap & (1 << (*p - 'a'))) {
1207
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1208
            exit(1);
1209
        }
1210
        bitmap |= 1 << (*p - 'a');
1211
    }
1212
    return bitmap;
1213
}
1214

    
1215
static void restore_boot_devices(void *opaque)
1216
{
1217
    char *standard_boot_devices = opaque;
1218

    
1219
    qemu_boot_set(standard_boot_devices);
1220

    
1221
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1222
    qemu_free(standard_boot_devices);
1223
}
1224

    
1225
static void numa_add(const char *optarg)
1226
{
1227
    char option[128];
1228
    char *endptr;
1229
    unsigned long long value, endvalue;
1230
    int nodenr;
1231

    
1232
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
1233
    if (!strcmp(option, "node")) {
1234
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1235
            nodenr = nb_numa_nodes;
1236
        } else {
1237
            nodenr = strtoull(option, NULL, 10);
1238
        }
1239

    
1240
        if (get_param_value(option, 128, "mem", optarg) == 0) {
1241
            node_mem[nodenr] = 0;
1242
        } else {
1243
            value = strtoull(option, &endptr, 0);
1244
            switch (*endptr) {
1245
            case 0: case 'M': case 'm':
1246
                value <<= 20;
1247
                break;
1248
            case 'G': case 'g':
1249
                value <<= 30;
1250
                break;
1251
            }
1252
            node_mem[nodenr] = value;
1253
        }
1254
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
1255
            node_cpumask[nodenr] = 0;
1256
        } else {
1257
            value = strtoull(option, &endptr, 10);
1258
            if (value >= 64) {
1259
                value = 63;
1260
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1261
            } else {
1262
                if (*endptr == '-') {
1263
                    endvalue = strtoull(endptr+1, &endptr, 10);
1264
                    if (endvalue >= 63) {
1265
                        endvalue = 62;
1266
                        fprintf(stderr,
1267
                            "only 63 CPUs in NUMA mode supported.\n");
1268
                    }
1269
                    value = (2ULL << endvalue) - (1ULL << value);
1270
                } else {
1271
                    value = 1ULL << value;
1272
                }
1273
            }
1274
            node_cpumask[nodenr] = value;
1275
        }
1276
        nb_numa_nodes++;
1277
    }
1278
    return;
1279
}
1280

    
1281
static void smp_parse(const char *optarg)
1282
{
1283
    int smp, sockets = 0, threads = 0, cores = 0;
1284
    char *endptr;
1285
    char option[128];
1286

    
1287
    smp = strtoul(optarg, &endptr, 10);
1288
    if (endptr != optarg) {
1289
        if (*endptr == ',') {
1290
            endptr++;
1291
        }
1292
    }
1293
    if (get_param_value(option, 128, "sockets", endptr) != 0)
1294
        sockets = strtoull(option, NULL, 10);
1295
    if (get_param_value(option, 128, "cores", endptr) != 0)
1296
        cores = strtoull(option, NULL, 10);
1297
    if (get_param_value(option, 128, "threads", endptr) != 0)
1298
        threads = strtoull(option, NULL, 10);
1299
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1300
        max_cpus = strtoull(option, NULL, 10);
1301

    
1302
    /* compute missing values, prefer sockets over cores over threads */
1303
    if (smp == 0 || sockets == 0) {
1304
        sockets = sockets > 0 ? sockets : 1;
1305
        cores = cores > 0 ? cores : 1;
1306
        threads = threads > 0 ? threads : 1;
1307
        if (smp == 0) {
1308
            smp = cores * threads * sockets;
1309
        }
1310
    } else {
1311
        if (cores == 0) {
1312
            threads = threads > 0 ? threads : 1;
1313
            cores = smp / (sockets * threads);
1314
        } else {
1315
            if (sockets) {
1316
                threads = smp / (cores * sockets);
1317
            }
1318
        }
1319
    }
1320
    smp_cpus = smp;
1321
    smp_cores = cores > 0 ? cores : 1;
1322
    smp_threads = threads > 0 ? threads : 1;
1323
    if (max_cpus == 0)
1324
        max_cpus = smp_cpus;
1325
}
1326

    
1327
/***********************************************************/
1328
/* USB devices */
1329

    
1330
static int usb_device_add(const char *devname, int is_hotplug)
1331
{
1332
    const char *p;
1333
    USBDevice *dev = NULL;
1334

    
1335
    if (!usb_enabled)
1336
        return -1;
1337

    
1338
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1339
    dev = usbdevice_create(devname);
1340
    if (dev)
1341
        goto done;
1342

    
1343
    /* the other ones */
1344
    if (strstart(devname, "host:", &p)) {
1345
        dev = usb_host_device_open(p);
1346
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1347
        dev = usb_bt_init(devname[2] ? hci_init(p) :
1348
                        bt_new_hci(qemu_find_bt_vlan(0)));
1349
    } else {
1350
        return -1;
1351
    }
1352
    if (!dev)
1353
        return -1;
1354

    
1355
done:
1356
    return 0;
1357
}
1358

    
1359
static int usb_device_del(const char *devname)
1360
{
1361
    int bus_num, addr;
1362
    const char *p;
1363

    
1364
    if (strstart(devname, "host:", &p))
1365
        return usb_host_device_close(p);
1366

    
1367
    if (!usb_enabled)
1368
        return -1;
1369

    
1370
    p = strchr(devname, '.');
1371
    if (!p)
1372
        return -1;
1373
    bus_num = strtoul(devname, NULL, 0);
1374
    addr = strtoul(p + 1, NULL, 0);
1375

    
1376
    return usb_device_delete_addr(bus_num, addr);
1377
}
1378

    
1379
static int usb_parse(const char *cmdline)
1380
{
1381
    int r;
1382
    r = usb_device_add(cmdline, 0);
1383
    if (r < 0) {
1384
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1385
    }
1386
    return r;
1387
}
1388

    
1389
void do_usb_add(Monitor *mon, const QDict *qdict)
1390
{
1391
    const char *devname = qdict_get_str(qdict, "devname");
1392
    if (usb_device_add(devname, 1) < 0) {
1393
        error_report("could not add USB device '%s'", devname);
1394
    }
1395
}
1396

    
1397
void do_usb_del(Monitor *mon, const QDict *qdict)
1398
{
1399
    const char *devname = qdict_get_str(qdict, "devname");
1400
    if (usb_device_del(devname) < 0) {
1401
        error_report("could not delete USB device '%s'", devname);
1402
    }
1403
}
1404

    
1405
/***********************************************************/
1406
/* PCMCIA/Cardbus */
1407

    
1408
static struct pcmcia_socket_entry_s {
1409
    PCMCIASocket *socket;
1410
    struct pcmcia_socket_entry_s *next;
1411
} *pcmcia_sockets = 0;
1412

    
1413
void pcmcia_socket_register(PCMCIASocket *socket)
1414
{
1415
    struct pcmcia_socket_entry_s *entry;
1416

    
1417
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1418
    entry->socket = socket;
1419
    entry->next = pcmcia_sockets;
1420
    pcmcia_sockets = entry;
1421
}
1422

    
1423
void pcmcia_socket_unregister(PCMCIASocket *socket)
1424
{
1425
    struct pcmcia_socket_entry_s *entry, **ptr;
1426

    
1427
    ptr = &pcmcia_sockets;
1428
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1429
        if (entry->socket == socket) {
1430
            *ptr = entry->next;
1431
            qemu_free(entry);
1432
        }
1433
}
1434

    
1435
void pcmcia_info(Monitor *mon)
1436
{
1437
    struct pcmcia_socket_entry_s *iter;
1438

    
1439
    if (!pcmcia_sockets)
1440
        monitor_printf(mon, "No PCMCIA sockets\n");
1441

    
1442
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1443
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1444
                       iter->socket->attached ? iter->socket->card_string :
1445
                       "Empty");
1446
}
1447

    
1448
/***********************************************************/
1449
/* I/O handling */
1450

    
1451
typedef struct IOHandlerRecord {
1452
    int fd;
1453
    IOCanReadHandler *fd_read_poll;
1454
    IOHandler *fd_read;
1455
    IOHandler *fd_write;
1456
    int deleted;
1457
    void *opaque;
1458
    /* temporary data */
1459
    struct pollfd *ufd;
1460
    QLIST_ENTRY(IOHandlerRecord) next;
1461
} IOHandlerRecord;
1462

    
1463
static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1464
    QLIST_HEAD_INITIALIZER(io_handlers);
1465

    
1466

    
1467
/* XXX: fd_read_poll should be suppressed, but an API change is
1468
   necessary in the character devices to suppress fd_can_read(). */
1469
int qemu_set_fd_handler2(int fd,
1470
                         IOCanReadHandler *fd_read_poll,
1471
                         IOHandler *fd_read,
1472
                         IOHandler *fd_write,
1473
                         void *opaque)
1474
{
1475
    IOHandlerRecord *ioh;
1476

    
1477
    if (!fd_read && !fd_write) {
1478
        QLIST_FOREACH(ioh, &io_handlers, next) {
1479
            if (ioh->fd == fd) {
1480
                ioh->deleted = 1;
1481
                break;
1482
            }
1483
        }
1484
    } else {
1485
        QLIST_FOREACH(ioh, &io_handlers, next) {
1486
            if (ioh->fd == fd)
1487
                goto found;
1488
        }
1489
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1490
        QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1491
    found:
1492
        ioh->fd = fd;
1493
        ioh->fd_read_poll = fd_read_poll;
1494
        ioh->fd_read = fd_read;
1495
        ioh->fd_write = fd_write;
1496
        ioh->opaque = opaque;
1497
        ioh->deleted = 0;
1498
    }
1499
    return 0;
1500
}
1501

    
1502
int qemu_set_fd_handler(int fd,
1503
                        IOHandler *fd_read,
1504
                        IOHandler *fd_write,
1505
                        void *opaque)
1506
{
1507
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1508
}
1509

    
1510
#ifdef _WIN32
1511
/***********************************************************/
1512
/* Polling handling */
1513

    
1514
typedef struct PollingEntry {
1515
    PollingFunc *func;
1516
    void *opaque;
1517
    struct PollingEntry *next;
1518
} PollingEntry;
1519

    
1520
static PollingEntry *first_polling_entry;
1521

    
1522
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1523
{
1524
    PollingEntry **ppe, *pe;
1525
    pe = qemu_mallocz(sizeof(PollingEntry));
1526
    pe->func = func;
1527
    pe->opaque = opaque;
1528
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1529
    *ppe = pe;
1530
    return 0;
1531
}
1532

    
1533
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1534
{
1535
    PollingEntry **ppe, *pe;
1536
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1537
        pe = *ppe;
1538
        if (pe->func == func && pe->opaque == opaque) {
1539
            *ppe = pe->next;
1540
            qemu_free(pe);
1541
            break;
1542
        }
1543
    }
1544
}
1545

    
1546
/***********************************************************/
1547
/* Wait objects support */
1548
typedef struct WaitObjects {
1549
    int num;
1550
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1551
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1552
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1553
} WaitObjects;
1554

    
1555
static WaitObjects wait_objects = {0};
1556

    
1557
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1558
{
1559
    WaitObjects *w = &wait_objects;
1560

    
1561
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
1562
        return -1;
1563
    w->events[w->num] = handle;
1564
    w->func[w->num] = func;
1565
    w->opaque[w->num] = opaque;
1566
    w->num++;
1567
    return 0;
1568
}
1569

    
1570
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1571
{
1572
    int i, found;
1573
    WaitObjects *w = &wait_objects;
1574

    
1575
    found = 0;
1576
    for (i = 0; i < w->num; i++) {
1577
        if (w->events[i] == handle)
1578
            found = 1;
1579
        if (found) {
1580
            w->events[i] = w->events[i + 1];
1581
            w->func[i] = w->func[i + 1];
1582
            w->opaque[i] = w->opaque[i + 1];
1583
        }
1584
    }
1585
    if (found)
1586
        w->num--;
1587
}
1588
#endif
1589

    
1590
/***********************************************************/
1591
/* machine registration */
1592

    
1593
static QEMUMachine *first_machine = NULL;
1594
QEMUMachine *current_machine = NULL;
1595

    
1596
int qemu_register_machine(QEMUMachine *m)
1597
{
1598
    QEMUMachine **pm;
1599
    pm = &first_machine;
1600
    while (*pm != NULL)
1601
        pm = &(*pm)->next;
1602
    m->next = NULL;
1603
    *pm = m;
1604
    return 0;
1605
}
1606

    
1607
static QEMUMachine *find_machine(const char *name)
1608
{
1609
    QEMUMachine *m;
1610

    
1611
    for(m = first_machine; m != NULL; m = m->next) {
1612
        if (!strcmp(m->name, name))
1613
            return m;
1614
        if (m->alias && !strcmp(m->alias, name))
1615
            return m;
1616
    }
1617
    return NULL;
1618
}
1619

    
1620
static QEMUMachine *find_default_machine(void)
1621
{
1622
    QEMUMachine *m;
1623

    
1624
    for(m = first_machine; m != NULL; m = m->next) {
1625
        if (m->is_default) {
1626
            return m;
1627
        }
1628
    }
1629
    return NULL;
1630
}
1631

    
1632
/***********************************************************/
1633
/* main execution loop */
1634

    
1635
static void gui_update(void *opaque)
1636
{
1637
    uint64_t interval = GUI_REFRESH_INTERVAL;
1638
    DisplayState *ds = opaque;
1639
    DisplayChangeListener *dcl = ds->listeners;
1640

    
1641
    qemu_flush_coalesced_mmio_buffer();
1642
    dpy_refresh(ds);
1643

    
1644
    while (dcl != NULL) {
1645
        if (dcl->gui_timer_interval &&
1646
            dcl->gui_timer_interval < interval)
1647
            interval = dcl->gui_timer_interval;
1648
        dcl = dcl->next;
1649
    }
1650
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1651
}
1652

    
1653
static void nographic_update(void *opaque)
1654
{
1655
    uint64_t interval = GUI_REFRESH_INTERVAL;
1656

    
1657
    qemu_flush_coalesced_mmio_buffer();
1658
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1659
}
1660

    
1661
struct vm_change_state_entry {
1662
    VMChangeStateHandler *cb;
1663
    void *opaque;
1664
    QLIST_ENTRY (vm_change_state_entry) entries;
1665
};
1666

    
1667
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1668

    
1669
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1670
                                                     void *opaque)
1671
{
1672
    VMChangeStateEntry *e;
1673

    
1674
    e = qemu_mallocz(sizeof (*e));
1675

    
1676
    e->cb = cb;
1677
    e->opaque = opaque;
1678
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1679
    return e;
1680
}
1681

    
1682
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1683
{
1684
    QLIST_REMOVE (e, entries);
1685
    qemu_free (e);
1686
}
1687

    
1688
void vm_state_notify(int running, int reason)
1689
{
1690
    VMChangeStateEntry *e;
1691

    
1692
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1693
        e->cb(e->opaque, running, reason);
1694
    }
1695
}
1696

    
1697
void vm_start(void)
1698
{
1699
    if (!vm_running) {
1700
        cpu_enable_ticks();
1701
        vm_running = 1;
1702
        vm_state_notify(1, 0);
1703
        resume_all_vcpus();
1704
    }
1705
}
1706

    
1707
/* reset/shutdown handler */
1708

    
1709
typedef struct QEMUResetEntry {
1710
    QTAILQ_ENTRY(QEMUResetEntry) entry;
1711
    QEMUResetHandler *func;
1712
    void *opaque;
1713
} QEMUResetEntry;
1714

    
1715
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1716
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1717
static int reset_requested;
1718
static int shutdown_requested;
1719
static int powerdown_requested;
1720
int debug_requested;
1721
static int vmstop_requested;
1722

    
1723
int qemu_shutdown_requested(void)
1724
{
1725
    int r = shutdown_requested;
1726
    shutdown_requested = 0;
1727
    return r;
1728
}
1729

    
1730
int qemu_reset_requested(void)
1731
{
1732
    int r = reset_requested;
1733
    reset_requested = 0;
1734
    return r;
1735
}
1736

    
1737
int qemu_powerdown_requested(void)
1738
{
1739
    int r = powerdown_requested;
1740
    powerdown_requested = 0;
1741
    return r;
1742
}
1743

    
1744
static int qemu_debug_requested(void)
1745
{
1746
    int r = debug_requested;
1747
    debug_requested = 0;
1748
    return r;
1749
}
1750

    
1751
static int qemu_vmstop_requested(void)
1752
{
1753
    int r = vmstop_requested;
1754
    vmstop_requested = 0;
1755
    return r;
1756
}
1757

    
1758
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1759
{
1760
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1761

    
1762
    re->func = func;
1763
    re->opaque = opaque;
1764
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1765
}
1766

    
1767
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1768
{
1769
    QEMUResetEntry *re;
1770

    
1771
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1772
        if (re->func == func && re->opaque == opaque) {
1773
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1774
            qemu_free(re);
1775
            return;
1776
        }
1777
    }
1778
}
1779

    
1780
void qemu_system_reset(void)
1781
{
1782
    QEMUResetEntry *re, *nre;
1783

    
1784
    /* reset all devices */
1785
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1786
        re->func(re->opaque);
1787
    }
1788
    monitor_protocol_event(QEVENT_RESET, NULL);
1789
    cpu_synchronize_all_post_reset();
1790
}
1791

    
1792
void qemu_system_reset_request(void)
1793
{
1794
    if (no_reboot) {
1795
        shutdown_requested = 1;
1796
    } else {
1797
        reset_requested = 1;
1798
    }
1799
    qemu_notify_event();
1800
}
1801

    
1802
void qemu_system_shutdown_request(void)
1803
{
1804
    shutdown_requested = 1;
1805
    qemu_notify_event();
1806
}
1807

    
1808
void qemu_system_powerdown_request(void)
1809
{
1810
    powerdown_requested = 1;
1811
    qemu_notify_event();
1812
}
1813

    
1814
#ifdef _WIN32
1815
static void host_main_loop_wait(int *timeout)
1816
{
1817
    int ret, ret2, i;
1818
    PollingEntry *pe;
1819

    
1820

    
1821
    /* XXX: need to suppress polling by better using win32 events */
1822
    ret = 0;
1823
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
1824
        ret |= pe->func(pe->opaque);
1825
    }
1826
    if (ret == 0) {
1827
        int err;
1828
        WaitObjects *w = &wait_objects;
1829

    
1830
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
1831
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
1832
            if (w->func[ret - WAIT_OBJECT_0])
1833
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
1834

    
1835
            /* Check for additional signaled events */
1836
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
1837

    
1838
                /* Check if event is signaled */
1839
                ret2 = WaitForSingleObject(w->events[i], 0);
1840
                if(ret2 == WAIT_OBJECT_0) {
1841
                    if (w->func[i])
1842
                        w->func[i](w->opaque[i]);
1843
                } else if (ret2 == WAIT_TIMEOUT) {
1844
                } else {
1845
                    err = GetLastError();
1846
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
1847
                }
1848
            }
1849
        } else if (ret == WAIT_TIMEOUT) {
1850
        } else {
1851
            err = GetLastError();
1852
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
1853
        }
1854
    }
1855

    
1856
    *timeout = 0;
1857
}
1858
#else
1859
static void host_main_loop_wait(int *timeout)
1860
{
1861
}
1862
#endif
1863

    
1864
void main_loop_wait(int nonblocking)
1865
{
1866
    IOHandlerRecord *ioh;
1867
    fd_set rfds, wfds, xfds;
1868
    int ret, nfds;
1869
    struct timeval tv;
1870
    int timeout;
1871

    
1872
    if (nonblocking)
1873
        timeout = 0;
1874
    else {
1875
        timeout = qemu_calculate_timeout();
1876
        qemu_bh_update_timeout(&timeout);
1877
    }
1878

    
1879
    host_main_loop_wait(&timeout);
1880

    
1881
    /* poll any events */
1882
    /* XXX: separate device handlers from system ones */
1883
    nfds = -1;
1884
    FD_ZERO(&rfds);
1885
    FD_ZERO(&wfds);
1886
    FD_ZERO(&xfds);
1887
    QLIST_FOREACH(ioh, &io_handlers, next) {
1888
        if (ioh->deleted)
1889
            continue;
1890
        if (ioh->fd_read &&
1891
            (!ioh->fd_read_poll ||
1892
             ioh->fd_read_poll(ioh->opaque) != 0)) {
1893
            FD_SET(ioh->fd, &rfds);
1894
            if (ioh->fd > nfds)
1895
                nfds = ioh->fd;
1896
        }
1897
        if (ioh->fd_write) {
1898
            FD_SET(ioh->fd, &wfds);
1899
            if (ioh->fd > nfds)
1900
                nfds = ioh->fd;
1901
        }
1902
    }
1903

    
1904
    tv.tv_sec = timeout / 1000;
1905
    tv.tv_usec = (timeout % 1000) * 1000;
1906

    
1907
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1908

    
1909
    qemu_mutex_unlock_iothread();
1910
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1911
    qemu_mutex_lock_iothread();
1912
    if (ret > 0) {
1913
        IOHandlerRecord *pioh;
1914

    
1915
        QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
1916
            if (ioh->deleted) {
1917
                QLIST_REMOVE(ioh, next);
1918
                qemu_free(ioh);
1919
                continue;
1920
            }
1921
            if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
1922
                ioh->fd_read(ioh->opaque);
1923
            }
1924
            if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
1925
                ioh->fd_write(ioh->opaque);
1926
            }
1927
        }
1928
    }
1929

    
1930
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1931

    
1932
    qemu_run_all_timers();
1933

    
1934
    /* Check bottom-halves last in case any of the earlier events triggered
1935
       them.  */
1936
    qemu_bh_poll();
1937

    
1938
}
1939

    
1940
static int vm_can_run(void)
1941
{
1942
    if (powerdown_requested)
1943
        return 0;
1944
    if (reset_requested)
1945
        return 0;
1946
    if (shutdown_requested)
1947
        return 0;
1948
    if (debug_requested)
1949
        return 0;
1950
    return 1;
1951
}
1952

    
1953
qemu_irq qemu_system_powerdown;
1954

    
1955
static void main_loop(void)
1956
{
1957
    int r;
1958

    
1959
#ifdef CONFIG_IOTHREAD
1960
    qemu_system_ready = 1;
1961
    qemu_cond_broadcast(&qemu_system_cond);
1962
#endif
1963

    
1964
    for (;;) {
1965
        do {
1966
            bool nonblocking = false;
1967
#ifdef CONFIG_PROFILER
1968
            int64_t ti;
1969
#endif
1970
#ifndef CONFIG_IOTHREAD
1971
            nonblocking = tcg_cpu_exec();
1972
#endif
1973
#ifdef CONFIG_PROFILER
1974
            ti = profile_getclock();
1975
#endif
1976
            main_loop_wait(nonblocking);
1977
#ifdef CONFIG_PROFILER
1978
            dev_time += profile_getclock() - ti;
1979
#endif
1980
        } while (vm_can_run());
1981

    
1982
        if ((r = qemu_debug_requested())) {
1983
            vm_stop(r);
1984
        }
1985
        if (qemu_shutdown_requested()) {
1986
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1987
            if (no_shutdown) {
1988
                vm_stop(0);
1989
                no_shutdown = 0;
1990
            } else
1991
                break;
1992
        }
1993
        if (qemu_reset_requested()) {
1994
            pause_all_vcpus();
1995
            qemu_system_reset();
1996
            resume_all_vcpus();
1997
        }
1998
        if (qemu_powerdown_requested()) {
1999
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2000
            qemu_irq_raise(qemu_system_powerdown);
2001
        }
2002
        if ((r = qemu_vmstop_requested())) {
2003
            vm_stop(r);
2004
        }
2005
    }
2006
    pause_all_vcpus();
2007
}
2008

    
2009
static void version(void)
2010
{
2011
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2012
}
2013

    
2014
static void help(int exitcode)
2015
{
2016
    const char *options_help =
2017
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
2018
        opt_help
2019
#define DEFHEADING(text) stringify(text) "\n"
2020
#include "qemu-options.h"
2021
#undef DEF
2022
#undef DEFHEADING
2023
#undef GEN_DOCS
2024
        ;
2025
    version();
2026
    printf("usage: %s [options] [disk_image]\n"
2027
           "\n"
2028
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2029
           "\n"
2030
           "%s\n"
2031
           "During emulation, the following keys are useful:\n"
2032
           "ctrl-alt-f      toggle full screen\n"
2033
           "ctrl-alt-n      switch to virtual console 'n'\n"
2034
           "ctrl-alt        toggle mouse and keyboard grab\n"
2035
           "\n"
2036
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
2037
           "qemu",
2038
           options_help);
2039
    exit(exitcode);
2040
}
2041

    
2042
#define HAS_ARG 0x0001
2043

    
2044
enum {
2045
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
2046
    opt_enum,
2047
#define DEFHEADING(text)
2048
#include "qemu-options.h"
2049
#undef DEF
2050
#undef DEFHEADING
2051
#undef GEN_DOCS
2052
};
2053

    
2054
typedef struct QEMUOption {
2055
    const char *name;
2056
    int flags;
2057
    int index;
2058
    uint32_t arch_mask;
2059
} QEMUOption;
2060

    
2061
static const QEMUOption qemu_options[] = {
2062
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2063
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
2064
    { option, opt_arg, opt_enum, arch_mask },
2065
#define DEFHEADING(text)
2066
#include "qemu-options.h"
2067
#undef DEF
2068
#undef DEFHEADING
2069
#undef GEN_DOCS
2070
    { NULL },
2071
};
2072
static void select_vgahw (const char *p)
2073
{
2074
    const char *opts;
2075

    
2076
    default_vga = 0;
2077
    vga_interface_type = VGA_NONE;
2078
    if (strstart(p, "std", &opts)) {
2079
        vga_interface_type = VGA_STD;
2080
    } else if (strstart(p, "cirrus", &opts)) {
2081
        vga_interface_type = VGA_CIRRUS;
2082
    } else if (strstart(p, "vmware", &opts)) {
2083
        vga_interface_type = VGA_VMWARE;
2084
    } else if (strstart(p, "xenfb", &opts)) {
2085
        vga_interface_type = VGA_XENFB;
2086
    } else if (!strstart(p, "none", &opts)) {
2087
    invalid_vga:
2088
        fprintf(stderr, "Unknown vga type: %s\n", p);
2089
        exit(1);
2090
    }
2091
    while (*opts) {
2092
        const char *nextopt;
2093

    
2094
        if (strstart(opts, ",retrace=", &nextopt)) {
2095
            opts = nextopt;
2096
            if (strstart(opts, "dumb", &nextopt))
2097
                vga_retrace_method = VGA_RETRACE_DUMB;
2098
            else if (strstart(opts, "precise", &nextopt))
2099
                vga_retrace_method = VGA_RETRACE_PRECISE;
2100
            else goto invalid_vga;
2101
        } else goto invalid_vga;
2102
        opts = nextopt;
2103
    }
2104
}
2105

    
2106
static int balloon_parse(const char *arg)
2107
{
2108
    QemuOpts *opts;
2109

    
2110
    if (strcmp(arg, "none") == 0) {
2111
        return 0;
2112
    }
2113

    
2114
    if (!strncmp(arg, "virtio", 6)) {
2115
        if (arg[6] == ',') {
2116
            /* have params -> parse them */
2117
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
2118
            if (!opts)
2119
                return  -1;
2120
        } else {
2121
            /* create empty opts */
2122
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2123
        }
2124
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
2125
        return 0;
2126
    }
2127

    
2128
    return -1;
2129
}
2130

    
2131
#ifdef _WIN32
2132
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
2133
{
2134
    exit(STATUS_CONTROL_C_EXIT);
2135
    return TRUE;
2136
}
2137
#endif
2138

    
2139
#ifndef _WIN32
2140

    
2141
static void termsig_handler(int signal)
2142
{
2143
    qemu_system_shutdown_request();
2144
}
2145

    
2146
static void sigchld_handler(int signal)
2147
{
2148
    waitpid(-1, NULL, WNOHANG);
2149
}
2150

    
2151
static void sighandler_setup(void)
2152
{
2153
    struct sigaction act;
2154

    
2155
    memset(&act, 0, sizeof(act));
2156
    act.sa_handler = termsig_handler;
2157
    sigaction(SIGINT,  &act, NULL);
2158
    sigaction(SIGHUP,  &act, NULL);
2159
    sigaction(SIGTERM, &act, NULL);
2160

    
2161
    act.sa_handler = sigchld_handler;
2162
    act.sa_flags = SA_NOCLDSTOP;
2163
    sigaction(SIGCHLD, &act, NULL);
2164
}
2165

    
2166
#endif
2167

    
2168
#ifdef _WIN32
2169
/* Look for support files in the same directory as the executable.  */
2170
static char *find_datadir(const char *argv0)
2171
{
2172
    char *p;
2173
    char buf[MAX_PATH];
2174
    DWORD len;
2175

    
2176
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
2177
    if (len == 0) {
2178
        return NULL;
2179
    }
2180

    
2181
    buf[len] = 0;
2182
    p = buf + len - 1;
2183
    while (p != buf && *p != '\\')
2184
        p--;
2185
    *p = 0;
2186
    if (access(buf, R_OK) == 0) {
2187
        return qemu_strdup(buf);
2188
    }
2189
    return NULL;
2190
}
2191
#else /* !_WIN32 */
2192

    
2193
/* Find a likely location for support files using the location of the binary.
2194
   For installed binaries this will be "$bindir/../share/qemu".  When
2195
   running from the build tree this will be "$bindir/../pc-bios".  */
2196
#define SHARE_SUFFIX "/share/qemu"
2197
#define BUILD_SUFFIX "/pc-bios"
2198
static char *find_datadir(const char *argv0)
2199
{
2200
    char *dir;
2201
    char *p = NULL;
2202
    char *res;
2203
    char buf[PATH_MAX];
2204
    size_t max_len;
2205

    
2206
#if defined(__linux__)
2207
    {
2208
        int len;
2209
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2210
        if (len > 0) {
2211
            buf[len] = 0;
2212
            p = buf;
2213
        }
2214
    }
2215
#elif defined(__FreeBSD__)
2216
    {
2217
        static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
2218
        size_t len = sizeof(buf) - 1;
2219

    
2220
        *buf = '\0';
2221
        if (!sysctl(mib, sizeof(mib)/sizeof(*mib), buf, &len, NULL, 0) &&
2222
            *buf) {
2223
            buf[sizeof(buf) - 1] = '\0';
2224
            p = buf;
2225
        }
2226
    }
2227
#endif
2228
    /* If we don't have any way of figuring out the actual executable
2229
       location then try argv[0].  */
2230
    if (!p) {
2231
        p = realpath(argv0, buf);
2232
        if (!p) {
2233
            return NULL;
2234
        }
2235
    }
2236
    dir = dirname(p);
2237
    dir = dirname(dir);
2238

    
2239
    max_len = strlen(dir) +
2240
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
2241
    res = qemu_mallocz(max_len);
2242
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
2243
    if (access(res, R_OK)) {
2244
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
2245
        if (access(res, R_OK)) {
2246
            qemu_free(res);
2247
            res = NULL;
2248
        }
2249
    }
2250

    
2251
    return res;
2252
}
2253
#undef SHARE_SUFFIX
2254
#undef BUILD_SUFFIX
2255
#endif
2256

    
2257
char *qemu_find_file(int type, const char *name)
2258
{
2259
    int len;
2260
    const char *subdir;
2261
    char *buf;
2262

    
2263
    /* If name contains path separators then try it as a straight path.  */
2264
    if ((strchr(name, '/') || strchr(name, '\\'))
2265
        && access(name, R_OK) == 0) {
2266
        return qemu_strdup(name);
2267
    }
2268
    switch (type) {
2269
    case QEMU_FILE_TYPE_BIOS:
2270
        subdir = "";
2271
        break;
2272
    case QEMU_FILE_TYPE_KEYMAP:
2273
        subdir = "keymaps/";
2274
        break;
2275
    default:
2276
        abort();
2277
    }
2278
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2279
    buf = qemu_mallocz(len);
2280
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2281
    if (access(buf, R_OK)) {
2282
        qemu_free(buf);
2283
        return NULL;
2284
    }
2285
    return buf;
2286
}
2287

    
2288
static int device_help_func(QemuOpts *opts, void *opaque)
2289
{
2290
    return qdev_device_help(opts);
2291
}
2292

    
2293
static int device_init_func(QemuOpts *opts, void *opaque)
2294
{
2295
    DeviceState *dev;
2296

    
2297
    dev = qdev_device_add(opts);
2298
    if (!dev)
2299
        return -1;
2300
    return 0;
2301
}
2302

    
2303
static int chardev_init_func(QemuOpts *opts, void *opaque)
2304
{
2305
    CharDriverState *chr;
2306

    
2307
    chr = qemu_chr_open_opts(opts, NULL);
2308
    if (!chr)
2309
        return -1;
2310
    return 0;
2311
}
2312

    
2313
static int mon_init_func(QemuOpts *opts, void *opaque)
2314
{
2315
    CharDriverState *chr;
2316
    const char *chardev;
2317
    const char *mode;
2318
    int flags;
2319

    
2320
    mode = qemu_opt_get(opts, "mode");
2321
    if (mode == NULL) {
2322
        mode = "readline";
2323
    }
2324
    if (strcmp(mode, "readline") == 0) {
2325
        flags = MONITOR_USE_READLINE;
2326
    } else if (strcmp(mode, "control") == 0) {
2327
        flags = MONITOR_USE_CONTROL;
2328
    } else {
2329
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2330
        exit(1);
2331
    }
2332

    
2333
    if (qemu_opt_get_bool(opts, "default", 0))
2334
        flags |= MONITOR_IS_DEFAULT;
2335

    
2336
    chardev = qemu_opt_get(opts, "chardev");
2337
    chr = qemu_chr_find(chardev);
2338
    if (chr == NULL) {
2339
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2340
        exit(1);
2341
    }
2342

    
2343
    monitor_init(chr, flags);
2344
    return 0;
2345
}
2346

    
2347
static void monitor_parse(const char *optarg, const char *mode)
2348
{
2349
    static int monitor_device_index = 0;
2350
    QemuOpts *opts;
2351
    const char *p;
2352
    char label[32];
2353
    int def = 0;
2354

    
2355
    if (strstart(optarg, "chardev:", &p)) {
2356
        snprintf(label, sizeof(label), "%s", p);
2357
    } else {
2358
        if (monitor_device_index) {
2359
            snprintf(label, sizeof(label), "monitor%d",
2360
                     monitor_device_index);
2361
        } else {
2362
            snprintf(label, sizeof(label), "monitor");
2363
            def = 1;
2364
        }
2365
        opts = qemu_chr_parse_compat(label, optarg);
2366
        if (!opts) {
2367
            fprintf(stderr, "parse error: %s\n", optarg);
2368
            exit(1);
2369
        }
2370
    }
2371

    
2372
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
2373
    if (!opts) {
2374
        fprintf(stderr, "duplicate chardev: %s\n", label);
2375
        exit(1);
2376
    }
2377
    qemu_opt_set(opts, "mode", mode);
2378
    qemu_opt_set(opts, "chardev", label);
2379
    if (def)
2380
        qemu_opt_set(opts, "default", "on");
2381
    monitor_device_index++;
2382
}
2383

    
2384
struct device_config {
2385
    enum {
2386
        DEV_USB,       /* -usbdevice     */
2387
        DEV_BT,        /* -bt            */
2388
        DEV_SERIAL,    /* -serial        */
2389
        DEV_PARALLEL,  /* -parallel      */
2390
        DEV_VIRTCON,   /* -virtioconsole */
2391
        DEV_DEBUGCON,  /* -debugcon */
2392
    } type;
2393
    const char *cmdline;
2394
    QTAILQ_ENTRY(device_config) next;
2395
};
2396
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
2397

    
2398
static void add_device_config(int type, const char *cmdline)
2399
{
2400
    struct device_config *conf;
2401

    
2402
    conf = qemu_mallocz(sizeof(*conf));
2403
    conf->type = type;
2404
    conf->cmdline = cmdline;
2405
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2406
}
2407

    
2408
static int foreach_device_config(int type, int (*func)(const char *cmdline))
2409
{
2410
    struct device_config *conf;
2411
    int rc;
2412

    
2413
    QTAILQ_FOREACH(conf, &device_configs, next) {
2414
        if (conf->type != type)
2415
            continue;
2416
        rc = func(conf->cmdline);
2417
        if (0 != rc)
2418
            return rc;
2419
    }
2420
    return 0;
2421
}
2422

    
2423
static int serial_parse(const char *devname)
2424
{
2425
    static int index = 0;
2426
    char label[32];
2427

    
2428
    if (strcmp(devname, "none") == 0)
2429
        return 0;
2430
    if (index == MAX_SERIAL_PORTS) {
2431
        fprintf(stderr, "qemu: too many serial ports\n");
2432
        exit(1);
2433
    }
2434
    snprintf(label, sizeof(label), "serial%d", index);
2435
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
2436
    if (!serial_hds[index]) {
2437
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2438
                devname, strerror(errno));
2439
        return -1;
2440
    }
2441
    index++;
2442
    return 0;
2443
}
2444

    
2445
static int parallel_parse(const char *devname)
2446
{
2447
    static int index = 0;
2448
    char label[32];
2449

    
2450
    if (strcmp(devname, "none") == 0)
2451
        return 0;
2452
    if (index == MAX_PARALLEL_PORTS) {
2453
        fprintf(stderr, "qemu: too many parallel ports\n");
2454
        exit(1);
2455
    }
2456
    snprintf(label, sizeof(label), "parallel%d", index);
2457
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
2458
    if (!parallel_hds[index]) {
2459
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2460
                devname, strerror(errno));
2461
        return -1;
2462
    }
2463
    index++;
2464
    return 0;
2465
}
2466

    
2467
static int virtcon_parse(const char *devname)
2468
{
2469
    static int index = 0;
2470
    char label[32];
2471
    QemuOpts *bus_opts, *dev_opts;
2472

    
2473
    if (strcmp(devname, "none") == 0)
2474
        return 0;
2475
    if (index == MAX_VIRTIO_CONSOLES) {
2476
        fprintf(stderr, "qemu: too many virtio consoles\n");
2477
        exit(1);
2478
    }
2479

    
2480
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2481
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
2482

    
2483
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2484
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2485

    
2486
    snprintf(label, sizeof(label), "virtcon%d", index);
2487
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2488
    if (!virtcon_hds[index]) {
2489
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2490
                devname, strerror(errno));
2491
        return -1;
2492
    }
2493
    qemu_opt_set(dev_opts, "chardev", label);
2494

    
2495
    index++;
2496
    return 0;
2497
}
2498

    
2499
static int debugcon_parse(const char *devname)
2500
{   
2501
    QemuOpts *opts;
2502

    
2503
    if (!qemu_chr_open("debugcon", devname, NULL)) {
2504
        exit(1);
2505
    }
2506
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2507
    if (!opts) {
2508
        fprintf(stderr, "qemu: already have a debugcon device\n");
2509
        exit(1);
2510
    }
2511
    qemu_opt_set(opts, "driver", "isa-debugcon");
2512
    qemu_opt_set(opts, "chardev", "debugcon");
2513
    return 0;
2514
}
2515

    
2516
static const QEMUOption *lookup_opt(int argc, char **argv,
2517
                                    const char **poptarg, int *poptind)
2518
{
2519
    const QEMUOption *popt;
2520
    int optind = *poptind;
2521
    char *r = argv[optind];
2522
    const char *optarg;
2523

    
2524
    loc_set_cmdline(argv, optind, 1);
2525
    optind++;
2526
    /* Treat --foo the same as -foo.  */
2527
    if (r[1] == '-')
2528
        r++;
2529
    popt = qemu_options;
2530
    for(;;) {
2531
        if (!popt->name) {
2532
            error_report("invalid option");
2533
            exit(1);
2534
        }
2535
        if (!strcmp(popt->name, r + 1))
2536
            break;
2537
        popt++;
2538
    }
2539
    if (popt->flags & HAS_ARG) {
2540
        if (optind >= argc) {
2541
            error_report("requires an argument");
2542
            exit(1);
2543
        }
2544
        optarg = argv[optind++];
2545
        loc_set_cmdline(argv, optind - 2, 2);
2546
    } else {
2547
        optarg = NULL;
2548
    }
2549

    
2550
    *poptarg = optarg;
2551
    *poptind = optind;
2552

    
2553
    return popt;
2554
}
2555

    
2556
int main(int argc, char **argv, char **envp)
2557
{
2558
    const char *gdbstub_dev = NULL;
2559
    uint32_t boot_devices_bitmap = 0;
2560
    int i;
2561
    int snapshot, linux_boot, net_boot;
2562
    const char *icount_option = NULL;
2563
    const char *initrd_filename;
2564
    const char *kernel_filename, *kernel_cmdline;
2565
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2566
    DisplayState *ds;
2567
    DisplayChangeListener *dcl;
2568
    int cyls, heads, secs, translation;
2569
    QemuOpts *hda_opts = NULL, *opts;
2570
    int optind;
2571
    const char *optarg;
2572
    const char *loadvm = NULL;
2573
    QEMUMachine *machine;
2574
    const char *cpu_model;
2575
#ifndef _WIN32
2576
    int fds[2];
2577
#endif
2578
    int tb_size;
2579
    const char *pid_file = NULL;
2580
    const char *incoming = NULL;
2581
#ifndef _WIN32
2582
    int fd = 0;
2583
    struct passwd *pwd = NULL;
2584
    const char *chroot_dir = NULL;
2585
    const char *run_as = NULL;
2586
#endif
2587
    int show_vnc_port = 0;
2588
    int defconfig = 1;
2589

    
2590
    error_set_progname(argv[0]);
2591

    
2592
    init_clocks();
2593

    
2594
    qemu_cache_utils_init(envp);
2595

    
2596
    QLIST_INIT (&vm_change_state_head);
2597
#ifndef _WIN32
2598
    {
2599
        struct sigaction act;
2600
        sigfillset(&act.sa_mask);
2601
        act.sa_flags = 0;
2602
        act.sa_handler = SIG_IGN;
2603
        sigaction(SIGPIPE, &act, NULL);
2604
    }
2605
#else
2606
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
2607
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
2608
       QEMU to run on a single CPU */
2609
    {
2610
        HANDLE h;
2611
        DWORD mask, smask;
2612
        int i;
2613
        h = GetCurrentProcess();
2614
        if (GetProcessAffinityMask(h, &mask, &smask)) {
2615
            for(i = 0; i < 32; i++) {
2616
                if (mask & (1 << i))
2617
                    break;
2618
            }
2619
            if (i != 32) {
2620
                mask = 1 << i;
2621
                SetProcessAffinityMask(h, mask);
2622
            }
2623
        }
2624
    }
2625
#endif
2626

    
2627
    module_call_init(MODULE_INIT_MACHINE);
2628
    machine = find_default_machine();
2629
    cpu_model = NULL;
2630
    initrd_filename = NULL;
2631
    ram_size = 0;
2632
    snapshot = 0;
2633
    kernel_filename = NULL;
2634
    kernel_cmdline = "";
2635
    cyls = heads = secs = 0;
2636
    translation = BIOS_ATA_TRANSLATION_AUTO;
2637

    
2638
    for (i = 0; i < MAX_NODES; i++) {
2639
        node_mem[i] = 0;
2640
        node_cpumask[i] = 0;
2641
    }
2642

    
2643
    nb_numa_nodes = 0;
2644
    nb_nics = 0;
2645

    
2646
    tb_size = 0;
2647
    autostart= 1;
2648

    
2649
    /* first pass of option parsing */
2650
    optind = 1;
2651
    while (optind < argc) {
2652
        if (argv[optind][0] != '-') {
2653
            /* disk image */
2654
            optind++;
2655
            continue;
2656
        } else {
2657
            const QEMUOption *popt;
2658

    
2659
            popt = lookup_opt(argc, argv, &optarg, &optind);
2660
            switch (popt->index) {
2661
            case QEMU_OPTION_nodefconfig:
2662
                defconfig=0;
2663
                break;
2664
            }
2665
        }
2666
    }
2667

    
2668
    if (defconfig) {
2669
        const char *fname;
2670
        FILE *fp;
2671

    
2672
        fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
2673
        fp = fopen(fname, "r");
2674
        if (fp) {
2675
            if (qemu_config_parse(fp, fname) != 0) {
2676
                exit(1);
2677
            }
2678
            fclose(fp);
2679
        }
2680

    
2681
        fname = arch_config_name;
2682
        fp = fopen(fname, "r");
2683
        if (fp) {
2684
            if (qemu_config_parse(fp, fname) != 0) {
2685
                exit(1);
2686
            }
2687
            fclose(fp);
2688
        }
2689
    }
2690
    cpudef_init();
2691

    
2692
    /* second pass of option parsing */
2693
    optind = 1;
2694
    for(;;) {
2695
        if (optind >= argc)
2696
            break;
2697
        if (argv[optind][0] != '-') {
2698
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2699
        } else {
2700
            const QEMUOption *popt;
2701

    
2702
            popt = lookup_opt(argc, argv, &optarg, &optind);
2703
            if (!(popt->arch_mask & arch_type)) {
2704
                printf("Option %s not supported for this target\n", popt->name);
2705
                exit(1);
2706
            }
2707
            switch(popt->index) {
2708
            case QEMU_OPTION_M:
2709
                machine = find_machine(optarg);
2710
                if (!machine) {
2711
                    QEMUMachine *m;
2712
                    printf("Supported machines are:\n");
2713
                    for(m = first_machine; m != NULL; m = m->next) {
2714
                        if (m->alias)
2715
                            printf("%-10s %s (alias of %s)\n",
2716
                                   m->alias, m->desc, m->name);
2717
                        printf("%-10s %s%s\n",
2718
                               m->name, m->desc,
2719
                               m->is_default ? " (default)" : "");
2720
                    }
2721
                    exit(*optarg != '?');
2722
                }
2723
                break;
2724
            case QEMU_OPTION_cpu:
2725
                /* hw initialization will check this */
2726
                if (*optarg == '?') {
2727
/* XXX: implement xxx_cpu_list for targets that still miss it */
2728
#if defined(cpu_list_id)
2729
                    cpu_list_id(stdout, &fprintf, optarg);
2730
#elif defined(cpu_list)
2731
                    cpu_list(stdout, &fprintf);                /* deprecated */
2732
#endif
2733
                    exit(0);
2734
                } else {
2735
                    cpu_model = optarg;
2736
                }
2737
                break;
2738
            case QEMU_OPTION_initrd:
2739
                initrd_filename = optarg;
2740
                break;
2741
            case QEMU_OPTION_hda:
2742
                if (cyls == 0)
2743
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
2744
                else
2745
                    hda_opts = drive_add(optarg, HD_ALIAS
2746
                             ",cyls=%d,heads=%d,secs=%d%s",
2747
                             0, cyls, heads, secs,
2748
                             translation == BIOS_ATA_TRANSLATION_LBA ?
2749
                                 ",trans=lba" :
2750
                             translation == BIOS_ATA_TRANSLATION_NONE ?
2751
                                 ",trans=none" : "");
2752
                 break;
2753
            case QEMU_OPTION_hdb:
2754
            case QEMU_OPTION_hdc:
2755
            case QEMU_OPTION_hdd:
2756
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2757
                break;
2758
            case QEMU_OPTION_drive:
2759
                drive_add(NULL, "%s", optarg);
2760
                break;
2761
            case QEMU_OPTION_set:
2762
                if (qemu_set_option(optarg) != 0)
2763
                    exit(1);
2764
                break;
2765
            case QEMU_OPTION_global:
2766
                if (qemu_global_option(optarg) != 0)
2767
                    exit(1);
2768
                break;
2769
            case QEMU_OPTION_mtdblock:
2770
                drive_add(optarg, MTD_ALIAS);
2771
                break;
2772
            case QEMU_OPTION_sd:
2773
                drive_add(optarg, SD_ALIAS);
2774
                break;
2775
            case QEMU_OPTION_pflash:
2776
                drive_add(optarg, PFLASH_ALIAS);
2777
                break;
2778
            case QEMU_OPTION_snapshot:
2779
                snapshot = 1;
2780
                break;
2781
            case QEMU_OPTION_hdachs:
2782
                {
2783
                    const char *p;
2784
                    p = optarg;
2785
                    cyls = strtol(p, (char **)&p, 0);
2786
                    if (cyls < 1 || cyls > 16383)
2787
                        goto chs_fail;
2788
                    if (*p != ',')
2789
                        goto chs_fail;
2790
                    p++;
2791
                    heads = strtol(p, (char **)&p, 0);
2792
                    if (heads < 1 || heads > 16)
2793
                        goto chs_fail;
2794
                    if (*p != ',')
2795
                        goto chs_fail;
2796
                    p++;
2797
                    secs = strtol(p, (char **)&p, 0);
2798
                    if (secs < 1 || secs > 63)
2799
                        goto chs_fail;
2800
                    if (*p == ',') {
2801
                        p++;
2802
                        if (!strcmp(p, "none"))
2803
                            translation = BIOS_ATA_TRANSLATION_NONE;
2804
                        else if (!strcmp(p, "lba"))
2805
                            translation = BIOS_ATA_TRANSLATION_LBA;
2806
                        else if (!strcmp(p, "auto"))
2807
                            translation = BIOS_ATA_TRANSLATION_AUTO;
2808
                        else
2809
                            goto chs_fail;
2810
                    } else if (*p != '\0') {
2811
                    chs_fail:
2812
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
2813
                        exit(1);
2814
                    }
2815
                    if (hda_opts != NULL) {
2816
                        char num[16];
2817
                        snprintf(num, sizeof(num), "%d", cyls);
2818
                        qemu_opt_set(hda_opts, "cyls", num);
2819
                        snprintf(num, sizeof(num), "%d", heads);
2820
                        qemu_opt_set(hda_opts, "heads", num);
2821
                        snprintf(num, sizeof(num), "%d", secs);
2822
                        qemu_opt_set(hda_opts, "secs", num);
2823
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
2824
                            qemu_opt_set(hda_opts, "trans", "lba");
2825
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
2826
                            qemu_opt_set(hda_opts, "trans", "none");
2827
                    }
2828
                }
2829
                break;
2830
            case QEMU_OPTION_numa:
2831
                if (nb_numa_nodes >= MAX_NODES) {
2832
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
2833
                    exit(1);
2834
                }
2835
                numa_add(optarg);
2836
                break;
2837
            case QEMU_OPTION_nographic:
2838
                display_type = DT_NOGRAPHIC;
2839
                break;
2840
#ifdef CONFIG_CURSES
2841
            case QEMU_OPTION_curses:
2842
                display_type = DT_CURSES;
2843
                break;
2844
#endif
2845
            case QEMU_OPTION_portrait:
2846
                graphic_rotate = 1;
2847
                break;
2848
            case QEMU_OPTION_kernel:
2849
                kernel_filename = optarg;
2850
                break;
2851
            case QEMU_OPTION_append:
2852
                kernel_cmdline = optarg;
2853
                break;
2854
            case QEMU_OPTION_cdrom:
2855
                drive_add(optarg, CDROM_ALIAS);
2856
                break;
2857
            case QEMU_OPTION_boot:
2858
                {
2859
                    static const char * const params[] = {
2860
                        "order", "once", "menu", NULL
2861
                    };
2862
                    char buf[sizeof(boot_devices)];
2863
                    char *standard_boot_devices;
2864
                    int legacy = 0;
2865

    
2866
                    if (!strchr(optarg, '=')) {
2867
                        legacy = 1;
2868
                        pstrcpy(buf, sizeof(buf), optarg);
2869
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2870
                        fprintf(stderr,
2871
                                "qemu: unknown boot parameter '%s' in '%s'\n",
2872
                                buf, optarg);
2873
                        exit(1);
2874
                    }
2875

    
2876
                    if (legacy ||
2877
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
2878
                        boot_devices_bitmap = parse_bootdevices(buf);
2879
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
2880
                    }
2881
                    if (!legacy) {
2882
                        if (get_param_value(buf, sizeof(buf),
2883
                                            "once", optarg)) {
2884
                            boot_devices_bitmap |= parse_bootdevices(buf);
2885
                            standard_boot_devices = qemu_strdup(boot_devices);
2886
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
2887
                            qemu_register_reset(restore_boot_devices,
2888
                                                standard_boot_devices);
2889
                        }
2890
                        if (get_param_value(buf, sizeof(buf),
2891
                                            "menu", optarg)) {
2892
                            if (!strcmp(buf, "on")) {
2893
                                boot_menu = 1;
2894
                            } else if (!strcmp(buf, "off")) {
2895
                                boot_menu = 0;
2896
                            } else {
2897
                                fprintf(stderr,
2898
                                        "qemu: invalid option value '%s'\n",
2899
                                        buf);
2900
                                exit(1);
2901
                            }
2902
                        }
2903
                    }
2904
                }
2905
                break;
2906
            case QEMU_OPTION_fda:
2907
            case QEMU_OPTION_fdb:
2908
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2909
                break;
2910
            case QEMU_OPTION_no_fd_bootchk:
2911
                fd_bootchk = 0;
2912
                break;
2913
            case QEMU_OPTION_netdev:
2914
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
2915
                    exit(1);
2916
                }
2917
                break;
2918
            case QEMU_OPTION_net:
2919
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
2920
                    exit(1);
2921
                }
2922
                break;
2923
#ifdef CONFIG_SLIRP
2924
            case QEMU_OPTION_tftp:
2925
                legacy_tftp_prefix = optarg;
2926
                break;
2927
            case QEMU_OPTION_bootp:
2928
                legacy_bootp_filename = optarg;
2929
                break;
2930
#ifndef _WIN32
2931
            case QEMU_OPTION_smb:
2932
                if (net_slirp_smb(optarg) < 0)
2933
                    exit(1);
2934
                break;
2935
#endif
2936
            case QEMU_OPTION_redir:
2937
                if (net_slirp_redir(optarg) < 0)
2938
                    exit(1);
2939
                break;
2940
#endif
2941
            case QEMU_OPTION_bt:
2942
                add_device_config(DEV_BT, optarg);
2943
                break;
2944
            case QEMU_OPTION_audio_help:
2945
                if (!(audio_available())) {
2946
                    printf("Option %s not supported for this target\n", popt->name);
2947
                    exit(1);
2948
                }
2949
                AUD_help ();
2950
                exit (0);
2951
                break;
2952
            case QEMU_OPTION_soundhw:
2953
                if (!(audio_available())) {
2954
                    printf("Option %s not supported for this target\n", popt->name);
2955
                    exit(1);
2956
                }
2957
                select_soundhw (optarg);
2958
                break;
2959
            case QEMU_OPTION_h:
2960
                help(0);
2961
                break;
2962
            case QEMU_OPTION_version:
2963
                version();
2964
                exit(0);
2965
                break;
2966
            case QEMU_OPTION_m: {
2967
                uint64_t value;
2968
                char *ptr;
2969

    
2970
                value = strtoul(optarg, &ptr, 10);
2971
                switch (*ptr) {
2972
                case 0: case 'M': case 'm':
2973
                    value <<= 20;
2974
                    break;
2975
                case 'G': case 'g':
2976
                    value <<= 30;
2977
                    break;
2978
                default:
2979
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
2980
                    exit(1);
2981
                }
2982

    
2983
                /* On 32-bit hosts, QEMU is limited by virtual address space */
2984
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
2985
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
2986
                    exit(1);
2987
                }
2988
                if (value != (uint64_t)(ram_addr_t)value) {
2989
                    fprintf(stderr, "qemu: ram size too large\n");
2990
                    exit(1);
2991
                }
2992
                ram_size = value;
2993
                break;
2994
            }
2995
            case QEMU_OPTION_mempath:
2996
                mem_path = optarg;
2997
                break;
2998
#ifdef MAP_POPULATE
2999
            case QEMU_OPTION_mem_prealloc:
3000
                mem_prealloc = 1;
3001
                break;
3002
#endif
3003
            case QEMU_OPTION_d:
3004
                set_cpu_log(optarg);
3005
                break;
3006
            case QEMU_OPTION_s:
3007
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
3008
                break;
3009
            case QEMU_OPTION_gdb:
3010
                gdbstub_dev = optarg;
3011
                break;
3012
            case QEMU_OPTION_L:
3013
                data_dir = optarg;
3014
                break;
3015
            case QEMU_OPTION_bios:
3016
                bios_name = optarg;
3017
                break;
3018
            case QEMU_OPTION_singlestep:
3019
                singlestep = 1;
3020
                break;
3021
            case QEMU_OPTION_S:
3022
                autostart = 0;
3023
                break;
3024
            case QEMU_OPTION_k:
3025
                keyboard_layout = optarg;
3026
                break;
3027
            case QEMU_OPTION_localtime:
3028
                rtc_utc = 0;
3029
                break;
3030
            case QEMU_OPTION_vga:
3031
                select_vgahw (optarg);
3032
                break;
3033
            case QEMU_OPTION_g:
3034
                {
3035
                    const char *p;
3036
                    int w, h, depth;
3037
                    p = optarg;
3038
                    w = strtol(p, (char **)&p, 10);
3039
                    if (w <= 0) {
3040
                    graphic_error:
3041
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
3042
                        exit(1);
3043
                    }
3044
                    if (*p != 'x')
3045
                        goto graphic_error;
3046
                    p++;
3047
                    h = strtol(p, (char **)&p, 10);
3048
                    if (h <= 0)
3049
                        goto graphic_error;
3050
                    if (*p == 'x') {
3051
                        p++;
3052
                        depth = strtol(p, (char **)&p, 10);
3053
                        if (depth != 8 && depth != 15 && depth != 16 &&
3054
                            depth != 24 && depth != 32)
3055
                            goto graphic_error;
3056
                    } else if (*p == '\0') {
3057
                        depth = graphic_depth;
3058
                    } else {
3059
                        goto graphic_error;
3060
                    }
3061

    
3062
                    graphic_width = w;
3063
                    graphic_height = h;
3064
                    graphic_depth = depth;
3065
                }
3066
                break;
3067
            case QEMU_OPTION_echr:
3068
                {
3069
                    char *r;
3070
                    term_escape_char = strtol(optarg, &r, 0);
3071
                    if (r == optarg)
3072
                        printf("Bad argument to echr\n");
3073
                    break;
3074
                }
3075
            case QEMU_OPTION_monitor:
3076
                monitor_parse(optarg, "readline");
3077
                default_monitor = 0;
3078
                break;
3079
            case QEMU_OPTION_qmp:
3080
                monitor_parse(optarg, "control");
3081
                default_monitor = 0;
3082
                break;
3083
            case QEMU_OPTION_mon:
3084
                opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
3085
                if (!opts) {
3086
                    fprintf(stderr, "parse error: %s\n", optarg);
3087
                    exit(1);
3088
                }
3089
                default_monitor = 0;
3090
                break;
3091
            case QEMU_OPTION_chardev:
3092
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
3093
                if (!opts) {
3094
                    fprintf(stderr, "parse error: %s\n", optarg);
3095
                    exit(1);
3096
                }
3097
                break;
3098
            case QEMU_OPTION_serial:
3099
                add_device_config(DEV_SERIAL, optarg);
3100
                default_serial = 0;
3101
                if (strncmp(optarg, "mon:", 4) == 0) {
3102
                    default_monitor = 0;
3103
                }
3104
                break;
3105
            case QEMU_OPTION_watchdog:
3106
                if (watchdog) {
3107
                    fprintf(stderr,
3108
                            "qemu: only one watchdog option may be given\n");
3109
                    return 1;
3110
                }
3111
                watchdog = optarg;
3112
                break;
3113
            case QEMU_OPTION_watchdog_action:
3114
                if (select_watchdog_action(optarg) == -1) {
3115
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
3116
                    exit(1);
3117
                }
3118
                break;
3119
            case QEMU_OPTION_virtiocon:
3120
                add_device_config(DEV_VIRTCON, optarg);
3121
                default_virtcon = 0;
3122
                if (strncmp(optarg, "mon:", 4) == 0) {
3123
                    default_monitor = 0;
3124
                }
3125
                break;
3126
            case QEMU_OPTION_parallel:
3127
                add_device_config(DEV_PARALLEL, optarg);
3128
                default_parallel = 0;
3129
                if (strncmp(optarg, "mon:", 4) == 0) {
3130
                    default_monitor = 0;
3131
                }
3132
                break;
3133
            case QEMU_OPTION_debugcon:
3134
                add_device_config(DEV_DEBUGCON, optarg);
3135
                break;
3136
            case QEMU_OPTION_loadvm:
3137
                loadvm = optarg;
3138
                break;
3139
            case QEMU_OPTION_full_screen:
3140
                full_screen = 1;
3141
                break;
3142
#ifdef CONFIG_SDL
3143
            case QEMU_OPTION_no_frame:
3144
                no_frame = 1;
3145
                break;
3146
            case QEMU_OPTION_alt_grab:
3147
                alt_grab = 1;
3148
                break;
3149
            case QEMU_OPTION_ctrl_grab:
3150
                ctrl_grab = 1;
3151
                break;
3152
            case QEMU_OPTION_no_quit:
3153
                no_quit = 1;
3154
                break;
3155
            case QEMU_OPTION_sdl:
3156
                display_type = DT_SDL;
3157
                break;
3158
#endif
3159
            case QEMU_OPTION_pidfile:
3160
                pid_file = optarg;
3161
                break;
3162
            case QEMU_OPTION_win2k_hack:
3163
                win2k_install_hack = 1;
3164
                break;
3165
            case QEMU_OPTION_rtc_td_hack:
3166
                rtc_td_hack = 1;
3167
                break;
3168
            case QEMU_OPTION_acpitable:
3169
                do_acpitable_option(optarg);
3170
                break;
3171
            case QEMU_OPTION_smbios:
3172
                do_smbios_option(optarg);
3173
                break;
3174
            case QEMU_OPTION_enable_kvm:
3175
                if (!(kvm_available())) {
3176
                    printf("Option %s not supported for this target\n", popt->name);
3177
                    exit(1);
3178
                }
3179
                kvm_allowed = 1;
3180
                break;
3181
            case QEMU_OPTION_usb:
3182
                usb_enabled = 1;
3183
                break;
3184
            case QEMU_OPTION_usbdevice:
3185
                usb_enabled = 1;
3186
                add_device_config(DEV_USB, optarg);
3187
                break;
3188
            case QEMU_OPTION_device:
3189
                if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
3190
                    exit(1);
3191
                }
3192
                break;
3193
            case QEMU_OPTION_smp:
3194
                smp_parse(optarg);
3195
                if (smp_cpus < 1) {
3196
                    fprintf(stderr, "Invalid number of CPUs\n");
3197
                    exit(1);
3198
                }
3199
                if (max_cpus < smp_cpus) {
3200
                    fprintf(stderr, "maxcpus must be equal to or greater than "
3201
                            "smp\n");
3202
                    exit(1);
3203
                }
3204
                if (max_cpus > 255) {
3205
                    fprintf(stderr, "Unsupported number of maxcpus\n");
3206
                    exit(1);
3207
                }
3208
                break;
3209
            case QEMU_OPTION_vnc:
3210
                display_type = DT_VNC;
3211
                vnc_display = optarg;
3212
                break;
3213
            case QEMU_OPTION_no_acpi:
3214
                acpi_enabled = 0;
3215
                break;
3216
            case QEMU_OPTION_no_hpet:
3217
                no_hpet = 1;
3218
                break;
3219
            case QEMU_OPTION_balloon:
3220
                if (balloon_parse(optarg) < 0) {
3221
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3222
                    exit(1);
3223
                }
3224
                break;
3225
            case QEMU_OPTION_no_reboot:
3226
                no_reboot = 1;
3227
                break;
3228
            case QEMU_OPTION_no_shutdown:
3229
                no_shutdown = 1;
3230
                break;
3231
            case QEMU_OPTION_show_cursor:
3232
                cursor_hide = 0;
3233
                break;
3234
            case QEMU_OPTION_uuid:
3235
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3236
                    fprintf(stderr, "Fail to parse UUID string."
3237
                            " Wrong format.\n");
3238
                    exit(1);
3239
                }
3240
                break;
3241
#ifndef _WIN32
3242
            case QEMU_OPTION_daemonize:
3243
                daemonize = 1;
3244
                break;
3245
#endif
3246
            case QEMU_OPTION_option_rom:
3247
                if (nb_option_roms >= MAX_OPTION_ROMS) {
3248
                    fprintf(stderr, "Too many option ROMs\n");
3249
                    exit(1);
3250
                }
3251
                option_rom[nb_option_roms] = optarg;
3252
                nb_option_roms++;
3253
                break;
3254
            case QEMU_OPTION_semihosting:
3255
                semihosting_enabled = 1;
3256
                break;
3257
            case QEMU_OPTION_name:
3258
                qemu_name = qemu_strdup(optarg);
3259
                 {
3260
                     char *p = strchr(qemu_name, ',');
3261
                     if (p != NULL) {
3262
                        *p++ = 0;
3263
                        if (strncmp(p, "process=", 8)) {
3264
                            fprintf(stderr, "Unknown subargument %s to -name", p);
3265
                            exit(1);
3266
                        }
3267
                        p += 8;
3268
                        set_proc_name(p);
3269
                     }        
3270
                 }        
3271
                break;
3272
            case QEMU_OPTION_prom_env:
3273
                if (nb_prom_envs >= MAX_PROM_ENVS) {
3274
                    fprintf(stderr, "Too many prom variables\n");
3275
                    exit(1);
3276
                }
3277
                prom_envs[nb_prom_envs] = optarg;
3278
                nb_prom_envs++;
3279
                break;
3280
            case QEMU_OPTION_old_param:
3281
                old_param = 1;
3282
                break;
3283
            case QEMU_OPTION_clock:
3284
                configure_alarms(optarg);
3285
                break;
3286
            case QEMU_OPTION_startdate:
3287
                configure_rtc_date_offset(optarg, 1);
3288
                break;
3289
            case QEMU_OPTION_rtc:
3290
                opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
3291
                if (!opts) {
3292
                    fprintf(stderr, "parse error: %s\n", optarg);
3293
                    exit(1);
3294
                }
3295
                configure_rtc(opts);
3296
                break;
3297
            case QEMU_OPTION_tb_size:
3298
                tb_size = strtol(optarg, NULL, 0);
3299
                if (tb_size < 0)
3300
                    tb_size = 0;
3301
                break;
3302
            case QEMU_OPTION_icount:
3303
                icount_option = optarg;
3304
                break;
3305
            case QEMU_OPTION_incoming:
3306
                incoming = optarg;
3307
                break;
3308
            case QEMU_OPTION_nodefaults:
3309
                default_serial = 0;
3310
                default_parallel = 0;
3311
                default_virtcon = 0;
3312
                default_monitor = 0;
3313
                default_vga = 0;
3314
                default_net = 0;
3315
                default_floppy = 0;
3316
                default_cdrom = 0;
3317
                default_sdcard = 0;
3318
                break;
3319
#ifndef _WIN32
3320
            case QEMU_OPTION_chroot:
3321
                chroot_dir = optarg;
3322
                break;
3323
            case QEMU_OPTION_runas:
3324
                run_as = optarg;
3325
                break;
3326
#endif
3327
            case QEMU_OPTION_xen_domid:
3328
                if (!(xen_available())) {
3329
                    printf("Option %s not supported for this target\n", popt->name);
3330
                    exit(1);
3331
                }
3332
                xen_domid = atoi(optarg);
3333
                break;
3334
            case QEMU_OPTION_xen_create:
3335
                if (!(xen_available())) {
3336
                    printf("Option %s not supported for this target\n", popt->name);
3337
                    exit(1);
3338
                }
3339
                xen_mode = XEN_CREATE;
3340
                break;
3341
            case QEMU_OPTION_xen_attach:
3342
                if (!(xen_available())) {
3343
                    printf("Option %s not supported for this target\n", popt->name);
3344
                    exit(1);
3345
                }
3346
                xen_mode = XEN_ATTACH;
3347
                break;
3348
            case QEMU_OPTION_readconfig:
3349
                {
3350
                    FILE *fp;
3351
                    fp = fopen(optarg, "r");
3352
                    if (fp == NULL) {
3353
                        fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3354
                        exit(1);
3355
                    }
3356
                    if (qemu_config_parse(fp, optarg) != 0) {
3357
                        exit(1);
3358
                    }
3359
                    fclose(fp);
3360
                    break;
3361
                }
3362
            case QEMU_OPTION_writeconfig:
3363
                {
3364
                    FILE *fp;
3365
                    if (strcmp(optarg, "-") == 0) {
3366
                        fp = stdout;
3367
                    } else {
3368
                        fp = fopen(optarg, "w");
3369
                        if (fp == NULL) {
3370
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3371
                            exit(1);
3372
                        }
3373
                    }
3374
                    qemu_config_write(fp);
3375
                    fclose(fp);
3376
                    break;
3377
                }
3378
            }
3379
        }
3380
    }
3381
    loc_set_none();
3382

    
3383
    /* If no data_dir is specified then try to find it relative to the
3384
       executable path.  */
3385
    if (!data_dir) {
3386
        data_dir = find_datadir(argv[0]);
3387
    }
3388
    /* If all else fails use the install patch specified when building.  */
3389
    if (!data_dir) {
3390
        data_dir = CONFIG_QEMU_SHAREDIR;
3391
    }
3392

    
3393
    /*
3394
     * Default to max_cpus = smp_cpus, in case the user doesn't
3395
     * specify a max_cpus value.
3396
     */
3397
    if (!max_cpus)
3398
        max_cpus = smp_cpus;
3399

    
3400
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3401
    if (smp_cpus > machine->max_cpus) {
3402
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3403
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3404
                machine->max_cpus);
3405
        exit(1);
3406
    }
3407

    
3408
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
3409
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
3410

    
3411
    if (machine->no_serial) {
3412
        default_serial = 0;
3413
    }
3414
    if (machine->no_parallel) {
3415
        default_parallel = 0;
3416
    }
3417
    if (!machine->use_virtcon) {
3418
        default_virtcon = 0;
3419
    }
3420
    if (machine->no_vga) {
3421
        default_vga = 0;
3422
    }
3423
    if (machine->no_floppy) {
3424
        default_floppy = 0;
3425
    }
3426
    if (machine->no_cdrom) {
3427
        default_cdrom = 0;
3428
    }
3429
    if (machine->no_sdcard) {
3430
        default_sdcard = 0;
3431
    }
3432

    
3433
    if (display_type == DT_NOGRAPHIC) {
3434
        if (default_parallel)
3435
            add_device_config(DEV_PARALLEL, "null");
3436
        if (default_serial && default_monitor) {
3437
            add_device_config(DEV_SERIAL, "mon:stdio");
3438
        } else if (default_virtcon && default_monitor) {
3439
            add_device_config(DEV_VIRTCON, "mon:stdio");
3440
        } else {
3441
            if (default_serial)
3442
                add_device_config(DEV_SERIAL, "stdio");
3443
            if (default_virtcon)
3444
                add_device_config(DEV_VIRTCON, "stdio");
3445
            if (default_monitor)
3446
                monitor_parse("stdio", "readline");
3447
        }
3448
    } else {
3449
        if (default_serial)
3450
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
3451
        if (default_parallel)
3452
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3453
        if (default_monitor)
3454
            monitor_parse("vc:80Cx24C", "readline");
3455
        if (default_virtcon)
3456
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3457
    }
3458
    if (default_vga)
3459
        vga_interface_type = VGA_CIRRUS;
3460

    
3461
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3462
        exit(1);
3463

    
3464
#ifndef _WIN32
3465
    if (daemonize) {
3466
        pid_t pid;
3467

    
3468
        if (pipe(fds) == -1)
3469
            exit(1);
3470

    
3471
        pid = fork();
3472
        if (pid > 0) {
3473
            uint8_t status;
3474
            ssize_t len;
3475

    
3476
            close(fds[1]);
3477

    
3478
        again:
3479
            len = read(fds[0], &status, 1);
3480
            if (len == -1 && (errno == EINTR))
3481
                goto again;
3482

    
3483
            if (len != 1)
3484
                exit(1);
3485
            else if (status == 1) {
3486
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3487
                exit(1);
3488
            } else
3489
                exit(0);
3490
        } else if (pid < 0)
3491
            exit(1);
3492

    
3493
        close(fds[0]);
3494
        qemu_set_cloexec(fds[1]);
3495

    
3496
        setsid();
3497

    
3498
        pid = fork();
3499
        if (pid > 0)
3500
            exit(0);
3501
        else if (pid < 0)
3502
            exit(1);
3503

    
3504
        umask(027);
3505

    
3506
        signal(SIGTSTP, SIG_IGN);
3507
        signal(SIGTTOU, SIG_IGN);
3508
        signal(SIGTTIN, SIG_IGN);
3509
    }
3510
#endif
3511

    
3512
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3513
#ifndef _WIN32
3514
        if (daemonize) {
3515
            uint8_t status = 1;
3516
            if (write(fds[1], &status, 1) != 1) {
3517
                perror("daemonize. Writing to pipe\n");
3518
            }
3519
        } else
3520
#endif
3521
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3522
        exit(1);
3523
    }
3524

    
3525
    if (kvm_enabled()) {
3526
        int ret;
3527

    
3528
        ret = kvm_init(smp_cpus);
3529
        if (ret < 0) {
3530
            fprintf(stderr, "failed to initialize KVM\n");
3531
            exit(1);
3532
        }
3533
    }
3534

    
3535
    if (qemu_init_main_loop()) {
3536
        fprintf(stderr, "qemu_init_main_loop failed\n");
3537
        exit(1);
3538
    }
3539
    linux_boot = (kernel_filename != NULL);
3540

    
3541
    if (!linux_boot && *kernel_cmdline != '\0') {
3542
        fprintf(stderr, "-append only allowed with -kernel option\n");
3543
        exit(1);
3544
    }
3545

    
3546
    if (!linux_boot && initrd_filename != NULL) {
3547
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3548
        exit(1);
3549
    }
3550

    
3551
#ifndef _WIN32
3552
    /* Win32 doesn't support line-buffering and requires size >= 2 */
3553
    setvbuf(stdout, NULL, _IOLBF, 0);
3554
#endif
3555

    
3556
    if (init_timer_alarm() < 0) {
3557
        fprintf(stderr, "could not initialize alarm timer\n");
3558
        exit(1);
3559
    }
3560
    configure_icount(icount_option);
3561

    
3562
    socket_init();
3563

    
3564
    if (net_init_clients() < 0) {
3565
        exit(1);
3566
    }
3567

    
3568
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
3569
    net_set_boot_mask(net_boot);
3570

    
3571
    /* init the bluetooth world */
3572
    if (foreach_device_config(DEV_BT, bt_parse))
3573
        exit(1);
3574

    
3575
    /* init the memory */
3576
    if (ram_size == 0)
3577
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3578

    
3579
    /* init the dynamic translator */
3580
    cpu_exec_init_all(tb_size * 1024 * 1024);
3581

    
3582
    bdrv_init_with_whitelist();
3583

    
3584
    blk_mig_init();
3585

    
3586
    if (default_cdrom) {
3587
        /* we always create the cdrom drive, even if no disk is there */
3588
        drive_add(NULL, CDROM_ALIAS);
3589
    }
3590

    
3591
    if (default_floppy) {
3592
        /* we always create at least one floppy */
3593
        drive_add(NULL, FD_ALIAS, 0);
3594
    }
3595

    
3596
    if (default_sdcard) {
3597
        /* we always create one sd slot, even if no card is in it */
3598
        drive_add(NULL, SD_ALIAS);
3599
    }
3600

    
3601
    /* open the virtual block devices */
3602
    if (snapshot)
3603
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
3604
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
3605
        exit(1);
3606

    
3607
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
3608
                         ram_load, NULL);
3609

    
3610
    if (nb_numa_nodes > 0) {
3611
        int i;
3612

    
3613
        if (nb_numa_nodes > smp_cpus) {
3614
            nb_numa_nodes = smp_cpus;
3615
        }
3616

    
3617
        /* If no memory size if given for any node, assume the default case
3618
         * and distribute the available memory equally across all nodes
3619
         */
3620
        for (i = 0; i < nb_numa_nodes; i++) {
3621
            if (node_mem[i] != 0)
3622
                break;
3623
        }
3624
        if (i == nb_numa_nodes) {
3625
            uint64_t usedmem = 0;
3626

    
3627
            /* On Linux, the each node's border has to be 8MB aligned,
3628
             * the final node gets the rest.
3629
             */
3630
            for (i = 0; i < nb_numa_nodes - 1; i++) {
3631
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3632
                usedmem += node_mem[i];
3633
            }
3634
            node_mem[i] = ram_size - usedmem;
3635
        }
3636

    
3637
        for (i = 0; i < nb_numa_nodes; i++) {
3638
            if (node_cpumask[i] != 0)
3639
                break;
3640
        }
3641
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3642
         * must cope with this anyway, because there are BIOSes out there in
3643
         * real machines which also use this scheme.
3644
         */
3645
        if (i == nb_numa_nodes) {
3646
            for (i = 0; i < smp_cpus; i++) {
3647
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
3648
            }
3649
        }
3650
    }
3651

    
3652
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3653
        exit(1);
3654
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3655
        exit(1);
3656
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3657
        exit(1);
3658
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3659
        exit(1);
3660

    
3661
    module_call_init(MODULE_INIT_DEVICE);
3662

    
3663
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
3664
        exit(0);
3665

    
3666
    if (watchdog) {
3667
        i = select_watchdog(watchdog);
3668
        if (i > 0)
3669
            exit (i == 1 ? 1 : 0);
3670
    }
3671

    
3672
    if (machine->compat_props) {
3673
        qdev_prop_register_global_list(machine->compat_props);
3674
    }
3675
    qemu_add_globals();
3676

    
3677
    machine->init(ram_size, boot_devices,
3678
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3679

    
3680
    cpu_synchronize_all_post_init();
3681

    
3682
#ifndef _WIN32
3683
    /* must be after terminal init, SDL library changes signal handlers */
3684
    sighandler_setup();
3685
#endif
3686

    
3687
    set_numa_modes();
3688

    
3689
    current_machine = machine;
3690

    
3691
    /* init USB devices */
3692
    if (usb_enabled) {
3693
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3694
            exit(1);
3695
    }
3696

    
3697
    /* init generic devices */
3698
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
3699
        exit(1);
3700

    
3701
    net_check_clients();
3702

    
3703
    /* just use the first displaystate for the moment */
3704
    ds = get_displaystate();
3705

    
3706
    if (display_type == DT_DEFAULT) {
3707
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3708
        display_type = DT_SDL;
3709
#else
3710
        display_type = DT_VNC;
3711
        vnc_display = "localhost:0,to=99";
3712
        show_vnc_port = 1;
3713
#endif
3714
    }
3715
        
3716

    
3717
    switch (display_type) {
3718
    case DT_NOGRAPHIC:
3719
        break;
3720
#if defined(CONFIG_CURSES)
3721
    case DT_CURSES:
3722
        curses_display_init(ds, full_screen);
3723
        break;
3724
#endif
3725
#if defined(CONFIG_SDL)
3726
    case DT_SDL:
3727
        sdl_display_init(ds, full_screen, no_frame);
3728
        break;
3729
#elif defined(CONFIG_COCOA)
3730
    case DT_SDL:
3731
        cocoa_display_init(ds, full_screen);
3732
        break;
3733
#endif
3734
    case DT_VNC:
3735
        vnc_display_init(ds);
3736
        if (vnc_display_open(ds, vnc_display) < 0)
3737
            exit(1);
3738

    
3739
        if (show_vnc_port) {
3740
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3741
        }
3742
        break;
3743
    default:
3744
        break;
3745
    }
3746
    dpy_resize(ds);
3747

    
3748
    dcl = ds->listeners;
3749
    while (dcl != NULL) {
3750
        if (dcl->dpy_refresh != NULL) {
3751
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
3752
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
3753
        }
3754
        dcl = dcl->next;
3755
    }
3756

    
3757
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
3758
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
3759
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
3760
    }
3761

    
3762
    text_consoles_set_display(ds);
3763

    
3764
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
3765
        exit(1);
3766

    
3767
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3768
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3769
                gdbstub_dev);
3770
        exit(1);
3771
    }
3772

    
3773
    qdev_machine_creation_done();
3774

    
3775
    if (rom_load_all() != 0) {
3776
        fprintf(stderr, "rom loading failed\n");
3777
        exit(1);
3778
    }
3779

    
3780
    qemu_system_reset();
3781
    if (loadvm) {
3782
        if (load_vmstate(loadvm) < 0) {
3783
            autostart = 0;
3784
        }
3785
    }
3786

    
3787
    if (incoming) {
3788
        qemu_start_incoming_migration(incoming);
3789
    } else if (autostart) {
3790
        vm_start();
3791
    }
3792

    
3793
#ifndef _WIN32
3794
    if (daemonize) {
3795
        uint8_t status = 0;
3796
        ssize_t len;
3797

    
3798
    again1:
3799
        len = write(fds[1], &status, 1);
3800
        if (len == -1 && (errno == EINTR))
3801
            goto again1;
3802

    
3803
        if (len != 1)
3804
            exit(1);
3805

    
3806
        if (chdir("/")) {
3807
            perror("not able to chdir to /");
3808
            exit(1);
3809
        }
3810
        TFR(fd = qemu_open("/dev/null", O_RDWR));
3811
        if (fd == -1)
3812
            exit(1);
3813
    }
3814

    
3815
    if (run_as) {
3816
        pwd = getpwnam(run_as);
3817
        if (!pwd) {
3818
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
3819
            exit(1);
3820
        }
3821
    }
3822

    
3823
    if (chroot_dir) {
3824
        if (chroot(chroot_dir) < 0) {
3825
            fprintf(stderr, "chroot failed\n");
3826
            exit(1);
3827
        }
3828
        if (chdir("/")) {
3829
            perror("not able to chdir to /");
3830
            exit(1);
3831
        }
3832
    }
3833

    
3834
    if (run_as) {
3835
        if (setgid(pwd->pw_gid) < 0) {
3836
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
3837
            exit(1);
3838
        }
3839
        if (setuid(pwd->pw_uid) < 0) {
3840
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
3841
            exit(1);
3842
        }
3843
        if (setuid(0) != -1) {
3844
            fprintf(stderr, "Dropping privileges failed\n");
3845
            exit(1);
3846
        }
3847
    }
3848

    
3849
    if (daemonize) {
3850
        dup2(fd, 0);
3851
        dup2(fd, 1);
3852
        dup2(fd, 2);
3853

    
3854
        close(fd);
3855
    }
3856
#endif
3857

    
3858
    main_loop();
3859
    quit_timers();
3860
    net_cleanup();
3861

    
3862
    return 0;
3863
}