Statistics
| Branch: | Revision:

root / vl.c @ 8d963e6a

History | View | Annotate | Download (100.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_systm.h>
74
#include <netinet/ip.h>
75
#include <netinet/ip_icmp.h> // must come after ip.h
76
#include <netinet/udp.h>
77
#include <netinet/tcp.h>
78
#include <net/if.h>
79
#include <syslog.h>
80
#include <stropts.h>
81
/* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
82
   discussion about Solaris header problems */
83
extern int madvise(caddr_t, size_t, int);
84
#endif
85
#endif
86
#endif
87

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

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

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

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

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

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

    
155
#include "disas.h"
156

    
157
#include "qemu_socket.h"
158

    
159
#include "slirp/libslirp.h"
160

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

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

    
168
#define DEFAULT_RAM_SIZE 128
169

    
170
#define MAX_VIRTIO_CONSOLES 1
171

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

    
234
int nb_numa_nodes;
235
uint64_t node_mem[MAX_NODES];
236
uint64_t node_cpumask[MAX_NODES];
237

    
238
static QEMUTimer *nographic_timer;
239

    
240
uint8_t qemu_uuid[16];
241

    
242
static QEMUBootSetHandler *boot_set_handler;
243
static void *boot_set_opaque;
244

    
245
int kvm_allowed = 0;
246
uint32_t xen_domid;
247
enum xen_mode xen_mode = XEN_EMULATE;
248

    
249
static int default_serial = 1;
250
static int default_parallel = 1;
251
static int default_virtcon = 1;
252
static int default_monitor = 1;
253
static int default_vga = 1;
254
static int default_floppy = 1;
255
static int default_cdrom = 1;
256
static int default_sdcard = 1;
257

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

    
274
static int default_driver_check(QemuOpts *opts, void *opaque)
275
{
276
    const char *driver = qemu_opt_get(opts, "driver");
277
    int i;
278

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

    
289
/***********************************************************/
290

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

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

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

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

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

    
351
    memcpy(tm, ret, sizeof(struct tm));
352
}
353

    
354
int qemu_timedate_diff(struct tm *tm)
355
{
356
    time_t seconds;
357

    
358
    if (rtc_date_offset == -1)
359
        if (rtc_utc)
360
            seconds = mktimegm(tm);
361
        else
362
            seconds = mktime(tm);
363
    else
364
        seconds = mktimegm(tm) + rtc_date_offset;
365

    
366
    return seconds - time(NULL);
367
}
368

    
369
void rtc_change_mon_event(struct tm *tm)
370
{
371
    QObject *data;
372

    
373
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
374
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
375
    qobject_decref(data);
376
}
377

    
378
static void configure_rtc_date_offset(const char *startdate, int legacy)
379
{
380
    time_t rtc_start_date;
381
    struct tm tm;
382

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

    
417
static void configure_rtc(QemuOpts *opts)
418
{
419
    const char *value;
420

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

    
455
/***********************************************************/
456
/* Bluetooth support */
457
static int nb_hcis;
458
static int cur_hci;
459
static struct HCIInfo *hci_table[MAX_NICS];
460

    
461
static struct bt_vlan_s {
462
    struct bt_scatternet_s net;
463
    int id;
464
    struct bt_vlan_s *next;
465
} *first_bt_vlan;
466

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

    
484
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
485
{
486
}
487

    
488
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
489
{
490
    return -ENOTSUP;
491
}
492

    
493
static struct HCIInfo null_hci = {
494
    .cmd_send = null_hci_send,
495
    .sco_send = null_hci_send,
496
    .acl_send = null_hci_send,
497
    .bdaddr_set = null_hci_addr_set,
498
};
499

    
500
struct HCIInfo *qemu_next_hci(void)
501
{
502
    if (cur_hci == nb_hcis)
503
        return &null_hci;
504

    
505
    return hci_table[cur_hci++];
506
}
507

    
508
static struct HCIInfo *hci_init(const char *str)
509
{
510
    char *endp;
511
    struct bt_scatternet_s *vlan = 0;
512

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

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

    
535
    return 0;
536
}
537

    
538
static int bt_hci_parse(const char *str)
539
{
540
    struct HCIInfo *hci;
541
    bdaddr_t bdaddr;
542

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

    
548
    hci = hci_init(str);
549
    if (!hci)
550
        return -1;
551

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

    
560
    hci_table[nb_hcis++] = hci;
561

    
562
    return 0;
563
}
564

    
565
static void bt_vhci_add(int vlan_id)
566
{
567
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
568

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

    
573
    bt_vhci_init(bt_new_hci(vlan));
574
}
575

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

    
584
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
585

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

    
594
    vlan = qemu_find_bt_vlan(vlan_id);
595

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

    
600
    if (!strcmp(devname, "keyboard"))
601
        return bt_keyboard_init(vlan);
602

    
603
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
604
    return 0;
605
}
606

    
607
static int bt_parse(const char *opt)
608
{
609
    const char *endp, *p;
610
    int vlan;
611

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

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

    
636
            bt_vhci_add(vlan);
637
            return 0;
638
        }
639
    } else if (strstart(opt, "device:", &endp))
640
        return !bt_device_add(endp);
641

    
642
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
643
    return 1;
644
}
645

    
646
/***********************************************************/
647
/* QEMU Block devices */
648

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

    
656
QemuOpts *drive_add(const char *file, const char *fmt, ...)
657
{
658
    va_list ap;
659
    char optstr[1024];
660
    QemuOpts *opts;
661

    
662
    va_start(ap, fmt);
663
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
664
    va_end(ap);
665

    
666
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
667
    if (!opts) {
668
        return NULL;
669
    }
670
    if (file)
671
        qemu_opt_set(opts, "file", file);
672
    return opts;
673
}
674

    
675
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
676
{
677
    DriveInfo *dinfo;
678

    
679
    /* seek interface, bus and unit */
680

    
681
    QTAILQ_FOREACH(dinfo, &drives, next) {
682
        if (dinfo->type == type &&
683
            dinfo->bus == bus &&
684
            dinfo->unit == unit)
685
            return dinfo;
686
    }
687

    
688
    return NULL;
689
}
690

    
691
DriveInfo *drive_get_by_id(const char *id)
692
{
693
    DriveInfo *dinfo;
694

    
695
    QTAILQ_FOREACH(dinfo, &drives, next) {
696
        if (strcmp(id, dinfo->id))
697
            continue;
698
        return dinfo;
699
    }
700
    return NULL;
701
}
702

    
703
int drive_get_max_bus(BlockInterfaceType type)
704
{
705
    int max_bus;
706
    DriveInfo *dinfo;
707

    
708
    max_bus = -1;
709
    QTAILQ_FOREACH(dinfo, &drives, next) {
710
        if(dinfo->type == type &&
711
           dinfo->bus > max_bus)
712
            max_bus = dinfo->bus;
713
    }
714
    return max_bus;
715
}
716

    
717
const char *drive_get_serial(BlockDriverState *bdrv)
718
{
719
    DriveInfo *dinfo;
720

    
721
    QTAILQ_FOREACH(dinfo, &drives, next) {
722
        if (dinfo->bdrv == bdrv)
723
            return dinfo->serial;
724
    }
725

    
726
    return "\0";
727
}
728

    
729
BlockInterfaceErrorAction drive_get_on_error(
730
    BlockDriverState *bdrv, int is_read)
731
{
732
    DriveInfo *dinfo;
733

    
734
    QTAILQ_FOREACH(dinfo, &drives, next) {
735
        if (dinfo->bdrv == bdrv)
736
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
737
    }
738

    
739
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
740
}
741

    
742
static void bdrv_format_print(void *opaque, const char *name)
743
{
744
    fprintf(stderr, " %s", name);
745
}
746

    
747
void drive_uninit(DriveInfo *dinfo)
748
{
749
    qemu_opts_del(dinfo->opts);
750
    bdrv_delete(dinfo->bdrv);
751
    QTAILQ_REMOVE(&drives, dinfo, next);
752
    qemu_free(dinfo);
753
}
754

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

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

    
795
    *fatal_error = 1;
796

    
797
    translation = BIOS_ATA_TRANSLATION_AUTO;
798

    
799
    if (machine && machine->use_scsi) {
800
        type = IF_SCSI;
801
        max_devs = MAX_SCSI_DEVS;
802
        pstrcpy(devname, sizeof(devname), "scsi");
803
    } else {
804
        type = IF_IDE;
805
        max_devs = MAX_IDE_DEVS;
806
        pstrcpy(devname, sizeof(devname), "ide");
807
    }
808
    media = MEDIA_DISK;
809

    
810
    /* extract parameters */
811
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
812
    unit_id = qemu_opt_get_number(opts, "unit", -1);
813
    index   = qemu_opt_get_number(opts, "index", -1);
814

    
815
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
816
    heads = qemu_opt_get_number(opts, "heads", 0);
817
    secs  = qemu_opt_get_number(opts, "secs", 0);
818

    
819
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
820
    ro = qemu_opt_get_bool(opts, "readonly", 0);
821

    
822
    file = qemu_opt_get(opts, "file");
823
    serial = qemu_opt_get(opts, "serial");
824

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

    
860
    if (cyls || heads || secs) {
861
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
862
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
863
            return NULL;
864
        }
865
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
866
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
867
            return NULL;
868
        }
869
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
870
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
871
            return NULL;
872
        }
873
    }
874

    
875
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
876
        if (!cyls) {
877
            fprintf(stderr,
878
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
879
                    buf);
880
            return NULL;
881
        }
882
        if (!strcmp(buf, "none"))
883
            translation = BIOS_ATA_TRANSLATION_NONE;
884
        else if (!strcmp(buf, "lba"))
885
            translation = BIOS_ATA_TRANSLATION_LBA;
886
        else if (!strcmp(buf, "auto"))
887
            translation = BIOS_ATA_TRANSLATION_AUTO;
888
        else {
889
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
890
            return NULL;
891
        }
892
    }
893

    
894
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
895
        if (!strcmp(buf, "disk")) {
896
            media = MEDIA_DISK;
897
        } else if (!strcmp(buf, "cdrom")) {
898
            if (cyls || secs || heads) {
899
                fprintf(stderr,
900
                        "qemu: '%s' invalid physical CHS format\n", buf);
901
                return NULL;
902
            }
903
            media = MEDIA_CDROM;
904
        } else {
905
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
906
            return NULL;
907
        }
908
    }
909

    
910
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
911
        if (!strcmp(buf, "off") || !strcmp(buf, "none")) {
912
            bdrv_flags |= BDRV_O_NOCACHE;
913
        } else if (!strcmp(buf, "writeback")) {
914
            bdrv_flags |= BDRV_O_CACHE_WB;
915
        } else if (!strcmp(buf, "unsafe")) {
916
            bdrv_flags |= BDRV_O_CACHE_WB;
917
            bdrv_flags |= BDRV_O_NO_FLUSH;
918
        } else if (!strcmp(buf, "writethrough")) {
919
            /* this is the default */
920
        } else {
921
           fprintf(stderr, "qemu: invalid cache option\n");
922
           return NULL;
923
        }
924
    }
925

    
926
#ifdef CONFIG_LINUX_AIO
927
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
928
        if (!strcmp(buf, "native")) {
929
            bdrv_flags |= BDRV_O_NATIVE_AIO;
930
        } else if (!strcmp(buf, "threads")) {
931
            /* this is the default */
932
        } else {
933
           fprintf(stderr, "qemu: invalid aio option\n");
934
           return NULL;
935
        }
936
    }
937
#endif
938

    
939
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
940
       if (strcmp(buf, "?") == 0) {
941
            fprintf(stderr, "qemu: Supported formats:");
942
            bdrv_iterate_format(bdrv_format_print, NULL);
943
            fprintf(stderr, "\n");
944
            return NULL;
945
        }
946
        drv = bdrv_find_whitelisted_format(buf);
947
        if (!drv) {
948
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
949
            return NULL;
950
        }
951
    }
952

    
953
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
954
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
955
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
956
            fprintf(stderr, "werror is no supported by this format\n");
957
            return NULL;
958
        }
959

    
960
        on_write_error = parse_block_error_action(buf, 0);
961
        if (on_write_error < 0) {
962
            return NULL;
963
        }
964
    }
965

    
966
    on_read_error = BLOCK_ERR_REPORT;
967
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
968
        if (type != IF_IDE && type != IF_VIRTIO && type != IF_NONE) {
969
            fprintf(stderr, "rerror is no supported by this format\n");
970
            return NULL;
971
        }
972

    
973
        on_read_error = parse_block_error_action(buf, 1);
974
        if (on_read_error < 0) {
975
            return NULL;
976
        }
977
    }
978

    
979
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
980
        if (type != IF_VIRTIO) {
981
            fprintf(stderr, "addr is not supported\n");
982
            return NULL;
983
        }
984
    }
985

    
986
    /* compute bus and unit according index */
987

    
988
    if (index != -1) {
989
        if (bus_id != 0 || unit_id != -1) {
990
            fprintf(stderr,
991
                    "qemu: index cannot be used with bus and unit\n");
992
            return NULL;
993
        }
994
        if (max_devs == 0)
995
        {
996
            unit_id = index;
997
            bus_id = 0;
998
        } else {
999
            unit_id = index % max_devs;
1000
            bus_id = index / max_devs;
1001
        }
1002
    }
1003

    
1004
    /* if user doesn't specify a unit_id,
1005
     * try to find the first free
1006
     */
1007

    
1008
    if (unit_id == -1) {
1009
       unit_id = 0;
1010
       while (drive_get(type, bus_id, unit_id) != NULL) {
1011
           unit_id++;
1012
           if (max_devs && unit_id >= max_devs) {
1013
               unit_id -= max_devs;
1014
               bus_id++;
1015
           }
1016
       }
1017
    }
1018

    
1019
    /* check unit id */
1020

    
1021
    if (max_devs && unit_id >= max_devs) {
1022
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1023
                unit_id, max_devs - 1);
1024
        return NULL;
1025
    }
1026

    
1027
    /*
1028
     * ignore multiple definitions
1029
     */
1030

    
1031
    if (drive_get(type, bus_id, unit_id) != NULL) {
1032
        *fatal_error = 0;
1033
        return NULL;
1034
    }
1035

    
1036
    /* init */
1037

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

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

    
1112
    if (media == MEDIA_CDROM) {
1113
        /* CDROM is fine for any interface, don't check.  */
1114
        ro = 1;
1115
    } else if (ro == 1) {
1116
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY && type != IF_NONE) {
1117
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1118
            return NULL;
1119
        }
1120
    }
1121

    
1122
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1123

    
1124
    if (bdrv_open(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1125
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1126
                        file, strerror(errno));
1127
        return NULL;
1128
    }
1129

    
1130
    if (bdrv_key_required(dinfo->bdrv))
1131
        autostart = 0;
1132
    *fatal_error = 0;
1133
    return dinfo;
1134
}
1135

    
1136
static int drive_init_func(QemuOpts *opts, void *opaque)
1137
{
1138
    QEMUMachine *machine = opaque;
1139
    int fatal_error = 0;
1140

    
1141
    if (drive_init(opts, machine, &fatal_error) == NULL) {
1142
        if (fatal_error)
1143
            return 1;
1144
    }
1145
    return 0;
1146
}
1147

    
1148
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1149
{
1150
    if (NULL == qemu_opt_get(opts, "snapshot")) {
1151
        qemu_opt_set(opts, "snapshot", "on");
1152
    }
1153
    return 0;
1154
}
1155

    
1156
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1157
{
1158
    boot_set_handler = func;
1159
    boot_set_opaque = opaque;
1160
}
1161

    
1162
int qemu_boot_set(const char *boot_devices)
1163
{
1164
    if (!boot_set_handler) {
1165
        return -EINVAL;
1166
    }
1167
    return boot_set_handler(boot_set_opaque, boot_devices);
1168
}
1169

    
1170
static void validate_bootdevices(char *devices)
1171
{
1172
    /* We just do some generic consistency checks */
1173
    const char *p;
1174
    int bitmap = 0;
1175

    
1176
    for (p = devices; *p != '\0'; p++) {
1177
        /* Allowed boot devices are:
1178
         * a-b: floppy disk drives
1179
         * c-f: IDE disk drives
1180
         * g-m: machine implementation dependant drives
1181
         * n-p: network devices
1182
         * It's up to each machine implementation to check if the given boot
1183
         * devices match the actual hardware implementation and firmware
1184
         * features.
1185
         */
1186
        if (*p < 'a' || *p > 'p') {
1187
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
1188
            exit(1);
1189
        }
1190
        if (bitmap & (1 << (*p - 'a'))) {
1191
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1192
            exit(1);
1193
        }
1194
        bitmap |= 1 << (*p - 'a');
1195
    }
1196
}
1197

    
1198
static void restore_boot_devices(void *opaque)
1199
{
1200
    char *standard_boot_devices = opaque;
1201
    static int first = 1;
1202

    
1203
    /* Restore boot order and remove ourselves after the first boot */
1204
    if (first) {
1205
        first = 0;
1206
        return;
1207
    }
1208

    
1209
    qemu_boot_set(standard_boot_devices);
1210

    
1211
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1212
    qemu_free(standard_boot_devices);
1213
}
1214

    
1215
static void numa_add(const char *optarg)
1216
{
1217
    char option[128];
1218
    char *endptr;
1219
    unsigned long long value, endvalue;
1220
    int nodenr;
1221

    
1222
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
1223
    if (!strcmp(option, "node")) {
1224
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1225
            nodenr = nb_numa_nodes;
1226
        } else {
1227
            nodenr = strtoull(option, NULL, 10);
1228
        }
1229

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

    
1271
static void smp_parse(const char *optarg)
1272
{
1273
    int smp, sockets = 0, threads = 0, cores = 0;
1274
    char *endptr;
1275
    char option[128];
1276

    
1277
    smp = strtoul(optarg, &endptr, 10);
1278
    if (endptr != optarg) {
1279
        if (*endptr == ',') {
1280
            endptr++;
1281
        }
1282
    }
1283
    if (get_param_value(option, 128, "sockets", endptr) != 0)
1284
        sockets = strtoull(option, NULL, 10);
1285
    if (get_param_value(option, 128, "cores", endptr) != 0)
1286
        cores = strtoull(option, NULL, 10);
1287
    if (get_param_value(option, 128, "threads", endptr) != 0)
1288
        threads = strtoull(option, NULL, 10);
1289
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1290
        max_cpus = strtoull(option, NULL, 10);
1291

    
1292
    /* compute missing values, prefer sockets over cores over threads */
1293
    if (smp == 0 || sockets == 0) {
1294
        sockets = sockets > 0 ? sockets : 1;
1295
        cores = cores > 0 ? cores : 1;
1296
        threads = threads > 0 ? threads : 1;
1297
        if (smp == 0) {
1298
            smp = cores * threads * sockets;
1299
        }
1300
    } else {
1301
        if (cores == 0) {
1302
            threads = threads > 0 ? threads : 1;
1303
            cores = smp / (sockets * threads);
1304
        } else {
1305
            if (sockets) {
1306
                threads = smp / (cores * sockets);
1307
            }
1308
        }
1309
    }
1310
    smp_cpus = smp;
1311
    smp_cores = cores > 0 ? cores : 1;
1312
    smp_threads = threads > 0 ? threads : 1;
1313
    if (max_cpus == 0)
1314
        max_cpus = smp_cpus;
1315
}
1316

    
1317
/***********************************************************/
1318
/* USB devices */
1319

    
1320
static int usb_device_add(const char *devname, int is_hotplug)
1321
{
1322
    const char *p;
1323
    USBDevice *dev = NULL;
1324

    
1325
    if (!usb_enabled)
1326
        return -1;
1327

    
1328
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1329
    dev = usbdevice_create(devname);
1330
    if (dev)
1331
        goto done;
1332

    
1333
    /* the other ones */
1334
    if (strstart(devname, "host:", &p)) {
1335
        dev = usb_host_device_open(p);
1336
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1337
        dev = usb_bt_init(devname[2] ? hci_init(p) :
1338
                        bt_new_hci(qemu_find_bt_vlan(0)));
1339
    } else {
1340
        return -1;
1341
    }
1342
    if (!dev)
1343
        return -1;
1344

    
1345
done:
1346
    return 0;
1347
}
1348

    
1349
static int usb_device_del(const char *devname)
1350
{
1351
    int bus_num, addr;
1352
    const char *p;
1353

    
1354
    if (strstart(devname, "host:", &p))
1355
        return usb_host_device_close(p);
1356

    
1357
    if (!usb_enabled)
1358
        return -1;
1359

    
1360
    p = strchr(devname, '.');
1361
    if (!p)
1362
        return -1;
1363
    bus_num = strtoul(devname, NULL, 0);
1364
    addr = strtoul(p + 1, NULL, 0);
1365

    
1366
    return usb_device_delete_addr(bus_num, addr);
1367
}
1368

    
1369
static int usb_parse(const char *cmdline)
1370
{
1371
    int r;
1372
    r = usb_device_add(cmdline, 0);
1373
    if (r < 0) {
1374
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1375
    }
1376
    return r;
1377
}
1378

    
1379
void do_usb_add(Monitor *mon, const QDict *qdict)
1380
{
1381
    const char *devname = qdict_get_str(qdict, "devname");
1382
    if (usb_device_add(devname, 1) < 0) {
1383
        error_report("could not add USB device '%s'", devname);
1384
    }
1385
}
1386

    
1387
void do_usb_del(Monitor *mon, const QDict *qdict)
1388
{
1389
    const char *devname = qdict_get_str(qdict, "devname");
1390
    if (usb_device_del(devname) < 0) {
1391
        error_report("could not delete USB device '%s'", devname);
1392
    }
1393
}
1394

    
1395
/***********************************************************/
1396
/* PCMCIA/Cardbus */
1397

    
1398
static struct pcmcia_socket_entry_s {
1399
    PCMCIASocket *socket;
1400
    struct pcmcia_socket_entry_s *next;
1401
} *pcmcia_sockets = 0;
1402

    
1403
void pcmcia_socket_register(PCMCIASocket *socket)
1404
{
1405
    struct pcmcia_socket_entry_s *entry;
1406

    
1407
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1408
    entry->socket = socket;
1409
    entry->next = pcmcia_sockets;
1410
    pcmcia_sockets = entry;
1411
}
1412

    
1413
void pcmcia_socket_unregister(PCMCIASocket *socket)
1414
{
1415
    struct pcmcia_socket_entry_s *entry, **ptr;
1416

    
1417
    ptr = &pcmcia_sockets;
1418
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1419
        if (entry->socket == socket) {
1420
            *ptr = entry->next;
1421
            qemu_free(entry);
1422
        }
1423
}
1424

    
1425
void pcmcia_info(Monitor *mon)
1426
{
1427
    struct pcmcia_socket_entry_s *iter;
1428

    
1429
    if (!pcmcia_sockets)
1430
        monitor_printf(mon, "No PCMCIA sockets\n");
1431

    
1432
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1433
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1434
                       iter->socket->attached ? iter->socket->card_string :
1435
                       "Empty");
1436
}
1437

    
1438
/***********************************************************/
1439
/* I/O handling */
1440

    
1441
typedef struct IOHandlerRecord {
1442
    int fd;
1443
    IOCanReadHandler *fd_read_poll;
1444
    IOHandler *fd_read;
1445
    IOHandler *fd_write;
1446
    int deleted;
1447
    void *opaque;
1448
    /* temporary data */
1449
    struct pollfd *ufd;
1450
    QLIST_ENTRY(IOHandlerRecord) next;
1451
} IOHandlerRecord;
1452

    
1453
static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1454
    QLIST_HEAD_INITIALIZER(io_handlers);
1455

    
1456

    
1457
/* XXX: fd_read_poll should be suppressed, but an API change is
1458
   necessary in the character devices to suppress fd_can_read(). */
1459
int qemu_set_fd_handler2(int fd,
1460
                         IOCanReadHandler *fd_read_poll,
1461
                         IOHandler *fd_read,
1462
                         IOHandler *fd_write,
1463
                         void *opaque)
1464
{
1465
    IOHandlerRecord *ioh;
1466

    
1467
    if (!fd_read && !fd_write) {
1468
        QLIST_FOREACH(ioh, &io_handlers, next) {
1469
            if (ioh->fd == fd) {
1470
                ioh->deleted = 1;
1471
                break;
1472
            }
1473
        }
1474
    } else {
1475
        QLIST_FOREACH(ioh, &io_handlers, next) {
1476
            if (ioh->fd == fd)
1477
                goto found;
1478
        }
1479
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1480
        QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1481
    found:
1482
        ioh->fd = fd;
1483
        ioh->fd_read_poll = fd_read_poll;
1484
        ioh->fd_read = fd_read;
1485
        ioh->fd_write = fd_write;
1486
        ioh->opaque = opaque;
1487
        ioh->deleted = 0;
1488
    }
1489
    return 0;
1490
}
1491

    
1492
int qemu_set_fd_handler(int fd,
1493
                        IOHandler *fd_read,
1494
                        IOHandler *fd_write,
1495
                        void *opaque)
1496
{
1497
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1498
}
1499

    
1500
/***********************************************************/
1501
/* machine registration */
1502

    
1503
static QEMUMachine *first_machine = NULL;
1504
QEMUMachine *current_machine = NULL;
1505

    
1506
int qemu_register_machine(QEMUMachine *m)
1507
{
1508
    QEMUMachine **pm;
1509
    pm = &first_machine;
1510
    while (*pm != NULL)
1511
        pm = &(*pm)->next;
1512
    m->next = NULL;
1513
    *pm = m;
1514
    return 0;
1515
}
1516

    
1517
static QEMUMachine *find_machine(const char *name)
1518
{
1519
    QEMUMachine *m;
1520

    
1521
    for(m = first_machine; m != NULL; m = m->next) {
1522
        if (!strcmp(m->name, name))
1523
            return m;
1524
        if (m->alias && !strcmp(m->alias, name))
1525
            return m;
1526
    }
1527
    return NULL;
1528
}
1529

    
1530
static QEMUMachine *find_default_machine(void)
1531
{
1532
    QEMUMachine *m;
1533

    
1534
    for(m = first_machine; m != NULL; m = m->next) {
1535
        if (m->is_default) {
1536
            return m;
1537
        }
1538
    }
1539
    return NULL;
1540
}
1541

    
1542
/***********************************************************/
1543
/* main execution loop */
1544

    
1545
static void gui_update(void *opaque)
1546
{
1547
    uint64_t interval = GUI_REFRESH_INTERVAL;
1548
    DisplayState *ds = opaque;
1549
    DisplayChangeListener *dcl = ds->listeners;
1550

    
1551
    qemu_flush_coalesced_mmio_buffer();
1552
    dpy_refresh(ds);
1553

    
1554
    while (dcl != NULL) {
1555
        if (dcl->gui_timer_interval &&
1556
            dcl->gui_timer_interval < interval)
1557
            interval = dcl->gui_timer_interval;
1558
        dcl = dcl->next;
1559
    }
1560
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1561
}
1562

    
1563
static void nographic_update(void *opaque)
1564
{
1565
    uint64_t interval = GUI_REFRESH_INTERVAL;
1566

    
1567
    qemu_flush_coalesced_mmio_buffer();
1568
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1569
}
1570

    
1571
struct vm_change_state_entry {
1572
    VMChangeStateHandler *cb;
1573
    void *opaque;
1574
    QLIST_ENTRY (vm_change_state_entry) entries;
1575
};
1576

    
1577
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1578

    
1579
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1580
                                                     void *opaque)
1581
{
1582
    VMChangeStateEntry *e;
1583

    
1584
    e = qemu_mallocz(sizeof (*e));
1585

    
1586
    e->cb = cb;
1587
    e->opaque = opaque;
1588
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1589
    return e;
1590
}
1591

    
1592
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1593
{
1594
    QLIST_REMOVE (e, entries);
1595
    qemu_free (e);
1596
}
1597

    
1598
void vm_state_notify(int running, int reason)
1599
{
1600
    VMChangeStateEntry *e;
1601

    
1602
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1603
        e->cb(e->opaque, running, reason);
1604
    }
1605
}
1606

    
1607
void vm_start(void)
1608
{
1609
    if (!vm_running) {
1610
        cpu_enable_ticks();
1611
        vm_running = 1;
1612
        vm_state_notify(1, 0);
1613
        resume_all_vcpus();
1614
        monitor_protocol_event(QEVENT_RESUME, NULL);
1615
    }
1616
}
1617

    
1618
/* reset/shutdown handler */
1619

    
1620
typedef struct QEMUResetEntry {
1621
    QTAILQ_ENTRY(QEMUResetEntry) entry;
1622
    QEMUResetHandler *func;
1623
    void *opaque;
1624
} QEMUResetEntry;
1625

    
1626
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1627
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1628
static int reset_requested;
1629
static int shutdown_requested;
1630
static int powerdown_requested;
1631
int debug_requested;
1632
int vmstop_requested;
1633

    
1634
int qemu_shutdown_requested(void)
1635
{
1636
    int r = shutdown_requested;
1637
    shutdown_requested = 0;
1638
    return r;
1639
}
1640

    
1641
int qemu_reset_requested(void)
1642
{
1643
    int r = reset_requested;
1644
    reset_requested = 0;
1645
    return r;
1646
}
1647

    
1648
int qemu_powerdown_requested(void)
1649
{
1650
    int r = powerdown_requested;
1651
    powerdown_requested = 0;
1652
    return r;
1653
}
1654

    
1655
static int qemu_debug_requested(void)
1656
{
1657
    int r = debug_requested;
1658
    debug_requested = 0;
1659
    return r;
1660
}
1661

    
1662
static int qemu_vmstop_requested(void)
1663
{
1664
    int r = vmstop_requested;
1665
    vmstop_requested = 0;
1666
    return r;
1667
}
1668

    
1669
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1670
{
1671
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1672

    
1673
    re->func = func;
1674
    re->opaque = opaque;
1675
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1676
}
1677

    
1678
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1679
{
1680
    QEMUResetEntry *re;
1681

    
1682
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1683
        if (re->func == func && re->opaque == opaque) {
1684
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1685
            qemu_free(re);
1686
            return;
1687
        }
1688
    }
1689
}
1690

    
1691
void qemu_system_reset(void)
1692
{
1693
    QEMUResetEntry *re, *nre;
1694

    
1695
    /* reset all devices */
1696
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1697
        re->func(re->opaque);
1698
    }
1699
    monitor_protocol_event(QEVENT_RESET, NULL);
1700
    cpu_synchronize_all_post_reset();
1701
}
1702

    
1703
void qemu_system_reset_request(void)
1704
{
1705
    if (no_reboot) {
1706
        shutdown_requested = 1;
1707
    } else {
1708
        reset_requested = 1;
1709
    }
1710
    qemu_notify_event();
1711
}
1712

    
1713
void qemu_system_shutdown_request(void)
1714
{
1715
    shutdown_requested = 1;
1716
    qemu_notify_event();
1717
}
1718

    
1719
void qemu_system_powerdown_request(void)
1720
{
1721
    powerdown_requested = 1;
1722
    qemu_notify_event();
1723
}
1724

    
1725
void main_loop_wait(int nonblocking)
1726
{
1727
    IOHandlerRecord *ioh;
1728
    fd_set rfds, wfds, xfds;
1729
    int ret, nfds;
1730
    struct timeval tv;
1731
    int timeout;
1732

    
1733
    if (nonblocking)
1734
        timeout = 0;
1735
    else {
1736
        timeout = qemu_calculate_timeout();
1737
        qemu_bh_update_timeout(&timeout);
1738
    }
1739

    
1740
    os_host_main_loop_wait(&timeout);
1741

    
1742
    /* poll any events */
1743
    /* XXX: separate device handlers from system ones */
1744
    nfds = -1;
1745
    FD_ZERO(&rfds);
1746
    FD_ZERO(&wfds);
1747
    FD_ZERO(&xfds);
1748
    QLIST_FOREACH(ioh, &io_handlers, next) {
1749
        if (ioh->deleted)
1750
            continue;
1751
        if (ioh->fd_read &&
1752
            (!ioh->fd_read_poll ||
1753
             ioh->fd_read_poll(ioh->opaque) != 0)) {
1754
            FD_SET(ioh->fd, &rfds);
1755
            if (ioh->fd > nfds)
1756
                nfds = ioh->fd;
1757
        }
1758
        if (ioh->fd_write) {
1759
            FD_SET(ioh->fd, &wfds);
1760
            if (ioh->fd > nfds)
1761
                nfds = ioh->fd;
1762
        }
1763
    }
1764

    
1765
    tv.tv_sec = timeout / 1000;
1766
    tv.tv_usec = (timeout % 1000) * 1000;
1767

    
1768
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1769

    
1770
    qemu_mutex_unlock_iothread();
1771
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1772
    qemu_mutex_lock_iothread();
1773
    if (ret > 0) {
1774
        IOHandlerRecord *pioh;
1775

    
1776
        QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
1777
            if (ioh->deleted) {
1778
                QLIST_REMOVE(ioh, next);
1779
                qemu_free(ioh);
1780
                continue;
1781
            }
1782
            if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
1783
                ioh->fd_read(ioh->opaque);
1784
            }
1785
            if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
1786
                ioh->fd_write(ioh->opaque);
1787
            }
1788
        }
1789
    }
1790

    
1791
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1792

    
1793
    qemu_run_all_timers();
1794

    
1795
    /* Check bottom-halves last in case any of the earlier events triggered
1796
       them.  */
1797
    qemu_bh_poll();
1798

    
1799
}
1800

    
1801
static int vm_can_run(void)
1802
{
1803
    if (powerdown_requested)
1804
        return 0;
1805
    if (reset_requested)
1806
        return 0;
1807
    if (shutdown_requested)
1808
        return 0;
1809
    if (debug_requested)
1810
        return 0;
1811
    return 1;
1812
}
1813

    
1814
qemu_irq qemu_system_powerdown;
1815

    
1816
static void main_loop(void)
1817
{
1818
    int r;
1819

    
1820
    qemu_main_loop_start();
1821

    
1822
    for (;;) {
1823
        do {
1824
            bool nonblocking = false;
1825
#ifdef CONFIG_PROFILER
1826
            int64_t ti;
1827
#endif
1828
#ifndef CONFIG_IOTHREAD
1829
            nonblocking = tcg_cpu_exec();
1830
#endif
1831
#ifdef CONFIG_PROFILER
1832
            ti = profile_getclock();
1833
#endif
1834
            main_loop_wait(nonblocking);
1835
#ifdef CONFIG_PROFILER
1836
            dev_time += profile_getclock() - ti;
1837
#endif
1838
        } while (vm_can_run());
1839

    
1840
        if ((r = qemu_debug_requested())) {
1841
            vm_stop(r);
1842
        }
1843
        if (qemu_shutdown_requested()) {
1844
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1845
            if (no_shutdown) {
1846
                vm_stop(0);
1847
                no_shutdown = 0;
1848
            } else
1849
                break;
1850
        }
1851
        if (qemu_reset_requested()) {
1852
            pause_all_vcpus();
1853
            qemu_system_reset();
1854
            resume_all_vcpus();
1855
        }
1856
        if (qemu_powerdown_requested()) {
1857
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1858
            qemu_irq_raise(qemu_system_powerdown);
1859
        }
1860
        if ((r = qemu_vmstop_requested())) {
1861
            vm_stop(r);
1862
        }
1863
    }
1864
    pause_all_vcpus();
1865
}
1866

    
1867
static void version(void)
1868
{
1869
    printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
1870
}
1871

    
1872
static void help(int exitcode)
1873
{
1874
    const char *options_help =
1875
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1876
        opt_help
1877
#define DEFHEADING(text) stringify(text) "\n"
1878
#include "qemu-options.h"
1879
#undef DEF
1880
#undef DEFHEADING
1881
#undef GEN_DOCS
1882
        ;
1883
    version();
1884
    printf("usage: %s [options] [disk_image]\n"
1885
           "\n"
1886
           "'disk_image' is a raw hard disk image for IDE hard disk 0\n"
1887
           "\n"
1888
           "%s\n"
1889
           "During emulation, the following keys are useful:\n"
1890
           "ctrl-alt-f      toggle full screen\n"
1891
           "ctrl-alt-n      switch to virtual console 'n'\n"
1892
           "ctrl-alt        toggle mouse and keyboard grab\n"
1893
           "\n"
1894
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
1895
           "qemu",
1896
           options_help);
1897
    exit(exitcode);
1898
}
1899

    
1900
#define HAS_ARG 0x0001
1901

    
1902
enum {
1903
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1904
    opt_enum,
1905
#define DEFHEADING(text)
1906
#include "qemu-options.h"
1907
#undef DEF
1908
#undef DEFHEADING
1909
#undef GEN_DOCS
1910
};
1911

    
1912
typedef struct QEMUOption {
1913
    const char *name;
1914
    int flags;
1915
    int index;
1916
    uint32_t arch_mask;
1917
} QEMUOption;
1918

    
1919
static const QEMUOption qemu_options[] = {
1920
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1921
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1922
    { option, opt_arg, opt_enum, arch_mask },
1923
#define DEFHEADING(text)
1924
#include "qemu-options.h"
1925
#undef DEF
1926
#undef DEFHEADING
1927
#undef GEN_DOCS
1928
    { NULL },
1929
};
1930
static void select_vgahw (const char *p)
1931
{
1932
    const char *opts;
1933

    
1934
    default_vga = 0;
1935
    vga_interface_type = VGA_NONE;
1936
    if (strstart(p, "std", &opts)) {
1937
        vga_interface_type = VGA_STD;
1938
    } else if (strstart(p, "cirrus", &opts)) {
1939
        vga_interface_type = VGA_CIRRUS;
1940
    } else if (strstart(p, "vmware", &opts)) {
1941
        vga_interface_type = VGA_VMWARE;
1942
    } else if (strstart(p, "xenfb", &opts)) {
1943
        vga_interface_type = VGA_XENFB;
1944
    } else if (!strstart(p, "none", &opts)) {
1945
    invalid_vga:
1946
        fprintf(stderr, "Unknown vga type: %s\n", p);
1947
        exit(1);
1948
    }
1949
    while (*opts) {
1950
        const char *nextopt;
1951

    
1952
        if (strstart(opts, ",retrace=", &nextopt)) {
1953
            opts = nextopt;
1954
            if (strstart(opts, "dumb", &nextopt))
1955
                vga_retrace_method = VGA_RETRACE_DUMB;
1956
            else if (strstart(opts, "precise", &nextopt))
1957
                vga_retrace_method = VGA_RETRACE_PRECISE;
1958
            else goto invalid_vga;
1959
        } else goto invalid_vga;
1960
        opts = nextopt;
1961
    }
1962
}
1963

    
1964
static int balloon_parse(const char *arg)
1965
{
1966
    QemuOpts *opts;
1967

    
1968
    if (strcmp(arg, "none") == 0) {
1969
        return 0;
1970
    }
1971

    
1972
    if (!strncmp(arg, "virtio", 6)) {
1973
        if (arg[6] == ',') {
1974
            /* have params -> parse them */
1975
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
1976
            if (!opts)
1977
                return  -1;
1978
        } else {
1979
            /* create empty opts */
1980
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1981
        }
1982
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
1983
        return 0;
1984
    }
1985

    
1986
    return -1;
1987
}
1988

    
1989
#ifdef _WIN32
1990
/* Look for support files in the same directory as the executable.  */
1991
static char *find_datadir(const char *argv0)
1992
{
1993
    char *p;
1994
    char buf[MAX_PATH];
1995
    DWORD len;
1996

    
1997
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
1998
    if (len == 0) {
1999
        return NULL;
2000
    }
2001

    
2002
    buf[len] = 0;
2003
    p = buf + len - 1;
2004
    while (p != buf && *p != '\\')
2005
        p--;
2006
    *p = 0;
2007
    if (access(buf, R_OK) == 0) {
2008
        return qemu_strdup(buf);
2009
    }
2010
    return NULL;
2011
}
2012
#else /* !_WIN32 */
2013

    
2014
/* Find a likely location for support files using the location of the binary.
2015
   For installed binaries this will be "$bindir/../share/qemu".  When
2016
   running from the build tree this will be "$bindir/../pc-bios".  */
2017
#define SHARE_SUFFIX "/share/qemu"
2018
#define BUILD_SUFFIX "/pc-bios"
2019
static char *find_datadir(const char *argv0)
2020
{
2021
    char *dir;
2022
    char *p = NULL;
2023
    char *res;
2024
    char buf[PATH_MAX];
2025
    size_t max_len;
2026

    
2027
#if defined(__linux__)
2028
    {
2029
        int len;
2030
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2031
        if (len > 0) {
2032
            buf[len] = 0;
2033
            p = buf;
2034
        }
2035
    }
2036
#elif defined(__FreeBSD__)
2037
    {
2038
        static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
2039
        size_t len = sizeof(buf) - 1;
2040

    
2041
        *buf = '\0';
2042
        if (!sysctl(mib, sizeof(mib)/sizeof(*mib), buf, &len, NULL, 0) &&
2043
            *buf) {
2044
            buf[sizeof(buf) - 1] = '\0';
2045
            p = buf;
2046
        }
2047
    }
2048
#endif
2049
    /* If we don't have any way of figuring out the actual executable
2050
       location then try argv[0].  */
2051
    if (!p) {
2052
        p = realpath(argv0, buf);
2053
        if (!p) {
2054
            return NULL;
2055
        }
2056
    }
2057
    dir = dirname(p);
2058
    dir = dirname(dir);
2059

    
2060
    max_len = strlen(dir) +
2061
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
2062
    res = qemu_mallocz(max_len);
2063
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
2064
    if (access(res, R_OK)) {
2065
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
2066
        if (access(res, R_OK)) {
2067
            qemu_free(res);
2068
            res = NULL;
2069
        }
2070
    }
2071

    
2072
    return res;
2073
}
2074
#undef SHARE_SUFFIX
2075
#undef BUILD_SUFFIX
2076
#endif
2077

    
2078
char *qemu_find_file(int type, const char *name)
2079
{
2080
    int len;
2081
    const char *subdir;
2082
    char *buf;
2083

    
2084
    /* If name contains path separators then try it as a straight path.  */
2085
    if ((strchr(name, '/') || strchr(name, '\\'))
2086
        && access(name, R_OK) == 0) {
2087
        return qemu_strdup(name);
2088
    }
2089
    switch (type) {
2090
    case QEMU_FILE_TYPE_BIOS:
2091
        subdir = "";
2092
        break;
2093
    case QEMU_FILE_TYPE_KEYMAP:
2094
        subdir = "keymaps/";
2095
        break;
2096
    default:
2097
        abort();
2098
    }
2099
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2100
    buf = qemu_mallocz(len);
2101
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2102
    if (access(buf, R_OK)) {
2103
        qemu_free(buf);
2104
        return NULL;
2105
    }
2106
    return buf;
2107
}
2108

    
2109
static int device_help_func(QemuOpts *opts, void *opaque)
2110
{
2111
    return qdev_device_help(opts);
2112
}
2113

    
2114
static int device_init_func(QemuOpts *opts, void *opaque)
2115
{
2116
    DeviceState *dev;
2117

    
2118
    dev = qdev_device_add(opts);
2119
    if (!dev)
2120
        return -1;
2121
    return 0;
2122
}
2123

    
2124
static int chardev_init_func(QemuOpts *opts, void *opaque)
2125
{
2126
    CharDriverState *chr;
2127

    
2128
    chr = qemu_chr_open_opts(opts, NULL);
2129
    if (!chr)
2130
        return -1;
2131
    return 0;
2132
}
2133

    
2134
#ifdef CONFIG_LINUX
2135
static int fsdev_init_func(QemuOpts *opts, void *opaque)
2136
{
2137
    int ret;
2138
    ret = qemu_fsdev_add(opts);
2139

    
2140
    return ret;
2141
}
2142
#endif
2143

    
2144
static int mon_init_func(QemuOpts *opts, void *opaque)
2145
{
2146
    CharDriverState *chr;
2147
    const char *chardev;
2148
    const char *mode;
2149
    int flags;
2150

    
2151
    mode = qemu_opt_get(opts, "mode");
2152
    if (mode == NULL) {
2153
        mode = "readline";
2154
    }
2155
    if (strcmp(mode, "readline") == 0) {
2156
        flags = MONITOR_USE_READLINE;
2157
    } else if (strcmp(mode, "control") == 0) {
2158
        flags = MONITOR_USE_CONTROL;
2159
    } else {
2160
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2161
        exit(1);
2162
    }
2163

    
2164
    if (qemu_opt_get_bool(opts, "default", 0))
2165
        flags |= MONITOR_IS_DEFAULT;
2166

    
2167
    chardev = qemu_opt_get(opts, "chardev");
2168
    chr = qemu_chr_find(chardev);
2169
    if (chr == NULL) {
2170
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2171
        exit(1);
2172
    }
2173

    
2174
    monitor_init(chr, flags);
2175
    return 0;
2176
}
2177

    
2178
static void monitor_parse(const char *optarg, const char *mode)
2179
{
2180
    static int monitor_device_index = 0;
2181
    QemuOpts *opts;
2182
    const char *p;
2183
    char label[32];
2184
    int def = 0;
2185

    
2186
    if (strstart(optarg, "chardev:", &p)) {
2187
        snprintf(label, sizeof(label), "%s", p);
2188
    } else {
2189
        snprintf(label, sizeof(label), "compat_monitor%d",
2190
                 monitor_device_index);
2191
        if (monitor_device_index == 0) {
2192
            def = 1;
2193
        }
2194
        opts = qemu_chr_parse_compat(label, optarg);
2195
        if (!opts) {
2196
            fprintf(stderr, "parse error: %s\n", optarg);
2197
            exit(1);
2198
        }
2199
    }
2200

    
2201
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
2202
    if (!opts) {
2203
        fprintf(stderr, "duplicate chardev: %s\n", label);
2204
        exit(1);
2205
    }
2206
    qemu_opt_set(opts, "mode", mode);
2207
    qemu_opt_set(opts, "chardev", label);
2208
    if (def)
2209
        qemu_opt_set(opts, "default", "on");
2210
    monitor_device_index++;
2211
}
2212

    
2213
struct device_config {
2214
    enum {
2215
        DEV_USB,       /* -usbdevice     */
2216
        DEV_BT,        /* -bt            */
2217
        DEV_SERIAL,    /* -serial        */
2218
        DEV_PARALLEL,  /* -parallel      */
2219
        DEV_VIRTCON,   /* -virtioconsole */
2220
        DEV_DEBUGCON,  /* -debugcon */
2221
    } type;
2222
    const char *cmdline;
2223
    QTAILQ_ENTRY(device_config) next;
2224
};
2225
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
2226

    
2227
static void add_device_config(int type, const char *cmdline)
2228
{
2229
    struct device_config *conf;
2230

    
2231
    conf = qemu_mallocz(sizeof(*conf));
2232
    conf->type = type;
2233
    conf->cmdline = cmdline;
2234
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2235
}
2236

    
2237
static int foreach_device_config(int type, int (*func)(const char *cmdline))
2238
{
2239
    struct device_config *conf;
2240
    int rc;
2241

    
2242
    QTAILQ_FOREACH(conf, &device_configs, next) {
2243
        if (conf->type != type)
2244
            continue;
2245
        rc = func(conf->cmdline);
2246
        if (0 != rc)
2247
            return rc;
2248
    }
2249
    return 0;
2250
}
2251

    
2252
static int serial_parse(const char *devname)
2253
{
2254
    static int index = 0;
2255
    char label[32];
2256

    
2257
    if (strcmp(devname, "none") == 0)
2258
        return 0;
2259
    if (index == MAX_SERIAL_PORTS) {
2260
        fprintf(stderr, "qemu: too many serial ports\n");
2261
        exit(1);
2262
    }
2263
    snprintf(label, sizeof(label), "serial%d", index);
2264
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
2265
    if (!serial_hds[index]) {
2266
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2267
                devname, strerror(errno));
2268
        return -1;
2269
    }
2270
    index++;
2271
    return 0;
2272
}
2273

    
2274
static int parallel_parse(const char *devname)
2275
{
2276
    static int index = 0;
2277
    char label[32];
2278

    
2279
    if (strcmp(devname, "none") == 0)
2280
        return 0;
2281
    if (index == MAX_PARALLEL_PORTS) {
2282
        fprintf(stderr, "qemu: too many parallel ports\n");
2283
        exit(1);
2284
    }
2285
    snprintf(label, sizeof(label), "parallel%d", index);
2286
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
2287
    if (!parallel_hds[index]) {
2288
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2289
                devname, strerror(errno));
2290
        return -1;
2291
    }
2292
    index++;
2293
    return 0;
2294
}
2295

    
2296
static int virtcon_parse(const char *devname)
2297
{
2298
    static int index = 0;
2299
    char label[32];
2300
    QemuOpts *bus_opts, *dev_opts;
2301

    
2302
    if (strcmp(devname, "none") == 0)
2303
        return 0;
2304
    if (index == MAX_VIRTIO_CONSOLES) {
2305
        fprintf(stderr, "qemu: too many virtio consoles\n");
2306
        exit(1);
2307
    }
2308

    
2309
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2310
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
2311

    
2312
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2313
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2314

    
2315
    snprintf(label, sizeof(label), "virtcon%d", index);
2316
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2317
    if (!virtcon_hds[index]) {
2318
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2319
                devname, strerror(errno));
2320
        return -1;
2321
    }
2322
    qemu_opt_set(dev_opts, "chardev", label);
2323

    
2324
    index++;
2325
    return 0;
2326
}
2327

    
2328
static int debugcon_parse(const char *devname)
2329
{   
2330
    QemuOpts *opts;
2331

    
2332
    if (!qemu_chr_open("debugcon", devname, NULL)) {
2333
        exit(1);
2334
    }
2335
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2336
    if (!opts) {
2337
        fprintf(stderr, "qemu: already have a debugcon device\n");
2338
        exit(1);
2339
    }
2340
    qemu_opt_set(opts, "driver", "isa-debugcon");
2341
    qemu_opt_set(opts, "chardev", "debugcon");
2342
    return 0;
2343
}
2344

    
2345
static const QEMUOption *lookup_opt(int argc, char **argv,
2346
                                    const char **poptarg, int *poptind)
2347
{
2348
    const QEMUOption *popt;
2349
    int optind = *poptind;
2350
    char *r = argv[optind];
2351
    const char *optarg;
2352

    
2353
    loc_set_cmdline(argv, optind, 1);
2354
    optind++;
2355
    /* Treat --foo the same as -foo.  */
2356
    if (r[1] == '-')
2357
        r++;
2358
    popt = qemu_options;
2359
    for(;;) {
2360
        if (!popt->name) {
2361
            error_report("invalid option");
2362
            exit(1);
2363
        }
2364
        if (!strcmp(popt->name, r + 1))
2365
            break;
2366
        popt++;
2367
    }
2368
    if (popt->flags & HAS_ARG) {
2369
        if (optind >= argc) {
2370
            error_report("requires an argument");
2371
            exit(1);
2372
        }
2373
        optarg = argv[optind++];
2374
        loc_set_cmdline(argv, optind - 2, 2);
2375
    } else {
2376
        optarg = NULL;
2377
    }
2378

    
2379
    *poptarg = optarg;
2380
    *poptind = optind;
2381

    
2382
    return popt;
2383
}
2384

    
2385
int main(int argc, char **argv, char **envp)
2386
{
2387
    const char *gdbstub_dev = NULL;
2388
    int i;
2389
    int snapshot, linux_boot;
2390
    const char *icount_option = NULL;
2391
    const char *initrd_filename;
2392
    const char *kernel_filename, *kernel_cmdline;
2393
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2394
    DisplayState *ds;
2395
    DisplayChangeListener *dcl;
2396
    int cyls, heads, secs, translation;
2397
    QemuOpts *hda_opts = NULL, *opts;
2398
    int optind;
2399
    const char *optarg;
2400
    const char *loadvm = NULL;
2401
    QEMUMachine *machine;
2402
    const char *cpu_model;
2403
#ifndef _WIN32
2404
    int fds[2];
2405
#endif
2406
    int tb_size;
2407
    const char *pid_file = NULL;
2408
    const char *incoming = NULL;
2409
#ifndef _WIN32
2410
    int fd = 0;
2411
    struct passwd *pwd = NULL;
2412
    const char *chroot_dir = NULL;
2413
    const char *run_as = NULL;
2414
#endif
2415
    int show_vnc_port = 0;
2416
    int defconfig = 1;
2417

    
2418
    error_set_progname(argv[0]);
2419

    
2420
    init_clocks();
2421

    
2422
    qemu_cache_utils_init(envp);
2423

    
2424
    QLIST_INIT (&vm_change_state_head);
2425
    os_setup_early_signal_handling();
2426

    
2427
    module_call_init(MODULE_INIT_MACHINE);
2428
    machine = find_default_machine();
2429
    cpu_model = NULL;
2430
    initrd_filename = NULL;
2431
    ram_size = 0;
2432
    snapshot = 0;
2433
    kernel_filename = NULL;
2434
    kernel_cmdline = "";
2435
    cyls = heads = secs = 0;
2436
    translation = BIOS_ATA_TRANSLATION_AUTO;
2437

    
2438
    for (i = 0; i < MAX_NODES; i++) {
2439
        node_mem[i] = 0;
2440
        node_cpumask[i] = 0;
2441
    }
2442

    
2443
    nb_numa_nodes = 0;
2444
    nb_nics = 0;
2445

    
2446
    tb_size = 0;
2447
    autostart= 1;
2448

    
2449
    /* first pass of option parsing */
2450
    optind = 1;
2451
    while (optind < argc) {
2452
        if (argv[optind][0] != '-') {
2453
            /* disk image */
2454
            optind++;
2455
            continue;
2456
        } else {
2457
            const QEMUOption *popt;
2458

    
2459
            popt = lookup_opt(argc, argv, &optarg, &optind);
2460
            switch (popt->index) {
2461
            case QEMU_OPTION_nodefconfig:
2462
                defconfig=0;
2463
                break;
2464
            }
2465
        }
2466
    }
2467

    
2468
    if (defconfig) {
2469
        int ret;
2470

    
2471
        ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2472
        if (ret < 0 && ret != -ENOENT) {
2473
            exit(1);
2474
        }
2475

    
2476
        ret = qemu_read_config_file(arch_config_name);
2477
        if (ret < 0 && ret != -ENOENT) {
2478
            exit(1);
2479
        }
2480
    }
2481
    cpudef_init();
2482

    
2483
    /* second pass of option parsing */
2484
    optind = 1;
2485
    for(;;) {
2486
        if (optind >= argc)
2487
            break;
2488
        if (argv[optind][0] != '-') {
2489
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2490
        } else {
2491
            const QEMUOption *popt;
2492

    
2493
            popt = lookup_opt(argc, argv, &optarg, &optind);
2494
            if (!(popt->arch_mask & arch_type)) {
2495
                printf("Option %s not supported for this target\n", popt->name);
2496
                exit(1);
2497
            }
2498
            switch(popt->index) {
2499
            case QEMU_OPTION_M:
2500
                machine = find_machine(optarg);
2501
                if (!machine) {
2502
                    QEMUMachine *m;
2503
                    printf("Supported machines are:\n");
2504
                    for(m = first_machine; m != NULL; m = m->next) {
2505
                        if (m->alias)
2506
                            printf("%-10s %s (alias of %s)\n",
2507
                                   m->alias, m->desc, m->name);
2508
                        printf("%-10s %s%s\n",
2509
                               m->name, m->desc,
2510
                               m->is_default ? " (default)" : "");
2511
                    }
2512
                    exit(*optarg != '?');
2513
                }
2514
                break;
2515
            case QEMU_OPTION_cpu:
2516
                /* hw initialization will check this */
2517
                if (*optarg == '?') {
2518
                    list_cpus(stdout, &fprintf, optarg);
2519
                    exit(0);
2520
                } else {
2521
                    cpu_model = optarg;
2522
                }
2523
                break;
2524
            case QEMU_OPTION_initrd:
2525
                initrd_filename = optarg;
2526
                break;
2527
            case QEMU_OPTION_hda:
2528
                if (cyls == 0)
2529
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
2530
                else
2531
                    hda_opts = drive_add(optarg, HD_ALIAS
2532
                             ",cyls=%d,heads=%d,secs=%d%s",
2533
                             0, cyls, heads, secs,
2534
                             translation == BIOS_ATA_TRANSLATION_LBA ?
2535
                                 ",trans=lba" :
2536
                             translation == BIOS_ATA_TRANSLATION_NONE ?
2537
                                 ",trans=none" : "");
2538
                 break;
2539
            case QEMU_OPTION_hdb:
2540
            case QEMU_OPTION_hdc:
2541
            case QEMU_OPTION_hdd:
2542
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2543
                break;
2544
            case QEMU_OPTION_drive:
2545
                drive_add(NULL, "%s", optarg);
2546
                break;
2547
            case QEMU_OPTION_set:
2548
                if (qemu_set_option(optarg) != 0)
2549
                    exit(1);
2550
                break;
2551
            case QEMU_OPTION_global:
2552
                if (qemu_global_option(optarg) != 0)
2553
                    exit(1);
2554
                break;
2555
            case QEMU_OPTION_mtdblock:
2556
                drive_add(optarg, MTD_ALIAS);
2557
                break;
2558
            case QEMU_OPTION_sd:
2559
                drive_add(optarg, SD_ALIAS);
2560
                break;
2561
            case QEMU_OPTION_pflash:
2562
                drive_add(optarg, PFLASH_ALIAS);
2563
                break;
2564
            case QEMU_OPTION_snapshot:
2565
                snapshot = 1;
2566
                break;
2567
            case QEMU_OPTION_hdachs:
2568
                {
2569
                    const char *p;
2570
                    p = optarg;
2571
                    cyls = strtol(p, (char **)&p, 0);
2572
                    if (cyls < 1 || cyls > 16383)
2573
                        goto chs_fail;
2574
                    if (*p != ',')
2575
                        goto chs_fail;
2576
                    p++;
2577
                    heads = strtol(p, (char **)&p, 0);
2578
                    if (heads < 1 || heads > 16)
2579
                        goto chs_fail;
2580
                    if (*p != ',')
2581
                        goto chs_fail;
2582
                    p++;
2583
                    secs = strtol(p, (char **)&p, 0);
2584
                    if (secs < 1 || secs > 63)
2585
                        goto chs_fail;
2586
                    if (*p == ',') {
2587
                        p++;
2588
                        if (!strcmp(p, "none"))
2589
                            translation = BIOS_ATA_TRANSLATION_NONE;
2590
                        else if (!strcmp(p, "lba"))
2591
                            translation = BIOS_ATA_TRANSLATION_LBA;
2592
                        else if (!strcmp(p, "auto"))
2593
                            translation = BIOS_ATA_TRANSLATION_AUTO;
2594
                        else
2595
                            goto chs_fail;
2596
                    } else if (*p != '\0') {
2597
                    chs_fail:
2598
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
2599
                        exit(1);
2600
                    }
2601
                    if (hda_opts != NULL) {
2602
                        char num[16];
2603
                        snprintf(num, sizeof(num), "%d", cyls);
2604
                        qemu_opt_set(hda_opts, "cyls", num);
2605
                        snprintf(num, sizeof(num), "%d", heads);
2606
                        qemu_opt_set(hda_opts, "heads", num);
2607
                        snprintf(num, sizeof(num), "%d", secs);
2608
                        qemu_opt_set(hda_opts, "secs", num);
2609
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
2610
                            qemu_opt_set(hda_opts, "trans", "lba");
2611
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
2612
                            qemu_opt_set(hda_opts, "trans", "none");
2613
                    }
2614
                }
2615
                break;
2616
            case QEMU_OPTION_numa:
2617
                if (nb_numa_nodes >= MAX_NODES) {
2618
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
2619
                    exit(1);
2620
                }
2621
                numa_add(optarg);
2622
                break;
2623
            case QEMU_OPTION_nographic:
2624
                display_type = DT_NOGRAPHIC;
2625
                break;
2626
#ifdef CONFIG_CURSES
2627
            case QEMU_OPTION_curses:
2628
                display_type = DT_CURSES;
2629
                break;
2630
#endif
2631
            case QEMU_OPTION_portrait:
2632
                graphic_rotate = 1;
2633
                break;
2634
            case QEMU_OPTION_kernel:
2635
                kernel_filename = optarg;
2636
                break;
2637
            case QEMU_OPTION_append:
2638
                kernel_cmdline = optarg;
2639
                break;
2640
            case QEMU_OPTION_cdrom:
2641
                drive_add(optarg, CDROM_ALIAS);
2642
                break;
2643
            case QEMU_OPTION_boot:
2644
                {
2645
                    static const char * const params[] = {
2646
                        "order", "once", "menu", NULL
2647
                    };
2648
                    char buf[sizeof(boot_devices)];
2649
                    char *standard_boot_devices;
2650
                    int legacy = 0;
2651

    
2652
                    if (!strchr(optarg, '=')) {
2653
                        legacy = 1;
2654
                        pstrcpy(buf, sizeof(buf), optarg);
2655
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2656
                        fprintf(stderr,
2657
                                "qemu: unknown boot parameter '%s' in '%s'\n",
2658
                                buf, optarg);
2659
                        exit(1);
2660
                    }
2661

    
2662
                    if (legacy ||
2663
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
2664
                        validate_bootdevices(buf);
2665
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
2666
                    }
2667
                    if (!legacy) {
2668
                        if (get_param_value(buf, sizeof(buf),
2669
                                            "once", optarg)) {
2670
                            validate_bootdevices(buf);
2671
                            standard_boot_devices = qemu_strdup(boot_devices);
2672
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
2673
                            qemu_register_reset(restore_boot_devices,
2674
                                                standard_boot_devices);
2675
                        }
2676
                        if (get_param_value(buf, sizeof(buf),
2677
                                            "menu", optarg)) {
2678
                            if (!strcmp(buf, "on")) {
2679
                                boot_menu = 1;
2680
                            } else if (!strcmp(buf, "off")) {
2681
                                boot_menu = 0;
2682
                            } else {
2683
                                fprintf(stderr,
2684
                                        "qemu: invalid option value '%s'\n",
2685
                                        buf);
2686
                                exit(1);
2687
                            }
2688
                        }
2689
                    }
2690
                }
2691
                break;
2692
            case QEMU_OPTION_fda:
2693
            case QEMU_OPTION_fdb:
2694
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2695
                break;
2696
            case QEMU_OPTION_no_fd_bootchk:
2697
                fd_bootchk = 0;
2698
                break;
2699
            case QEMU_OPTION_netdev:
2700
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
2701
                    exit(1);
2702
                }
2703
                break;
2704
            case QEMU_OPTION_net:
2705
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
2706
                    exit(1);
2707
                }
2708
                break;
2709
#ifdef CONFIG_SLIRP
2710
            case QEMU_OPTION_tftp:
2711
                legacy_tftp_prefix = optarg;
2712
                break;
2713
            case QEMU_OPTION_bootp:
2714
                legacy_bootp_filename = optarg;
2715
                break;
2716
#ifndef _WIN32
2717
            case QEMU_OPTION_smb:
2718
                if (net_slirp_smb(optarg) < 0)
2719
                    exit(1);
2720
                break;
2721
#endif
2722
            case QEMU_OPTION_redir:
2723
                if (net_slirp_redir(optarg) < 0)
2724
                    exit(1);
2725
                break;
2726
#endif
2727
            case QEMU_OPTION_bt:
2728
                add_device_config(DEV_BT, optarg);
2729
                break;
2730
            case QEMU_OPTION_audio_help:
2731
                if (!(audio_available())) {
2732
                    printf("Option %s not supported for this target\n", popt->name);
2733
                    exit(1);
2734
                }
2735
                AUD_help ();
2736
                exit (0);
2737
                break;
2738
            case QEMU_OPTION_soundhw:
2739
                if (!(audio_available())) {
2740
                    printf("Option %s not supported for this target\n", popt->name);
2741
                    exit(1);
2742
                }
2743
                select_soundhw (optarg);
2744
                break;
2745
            case QEMU_OPTION_h:
2746
                help(0);
2747
                break;
2748
            case QEMU_OPTION_version:
2749
                version();
2750
                exit(0);
2751
                break;
2752
            case QEMU_OPTION_m: {
2753
                uint64_t value;
2754
                char *ptr;
2755

    
2756
                value = strtoul(optarg, &ptr, 10);
2757
                switch (*ptr) {
2758
                case 0: case 'M': case 'm':
2759
                    value <<= 20;
2760
                    break;
2761
                case 'G': case 'g':
2762
                    value <<= 30;
2763
                    break;
2764
                default:
2765
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
2766
                    exit(1);
2767
                }
2768

    
2769
                /* On 32-bit hosts, QEMU is limited by virtual address space */
2770
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
2771
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
2772
                    exit(1);
2773
                }
2774
                if (value != (uint64_t)(ram_addr_t)value) {
2775
                    fprintf(stderr, "qemu: ram size too large\n");
2776
                    exit(1);
2777
                }
2778
                ram_size = value;
2779
                break;
2780
            }
2781
            case QEMU_OPTION_mempath:
2782
                mem_path = optarg;
2783
                break;
2784
#ifdef MAP_POPULATE
2785
            case QEMU_OPTION_mem_prealloc:
2786
                mem_prealloc = 1;
2787
                break;
2788
#endif
2789
            case QEMU_OPTION_d:
2790
                set_cpu_log(optarg);
2791
                break;
2792
            case QEMU_OPTION_s:
2793
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
2794
                break;
2795
            case QEMU_OPTION_gdb:
2796
                gdbstub_dev = optarg;
2797
                break;
2798
            case QEMU_OPTION_L:
2799
                data_dir = optarg;
2800
                break;
2801
            case QEMU_OPTION_bios:
2802
                bios_name = optarg;
2803
                break;
2804
            case QEMU_OPTION_singlestep:
2805
                singlestep = 1;
2806
                break;
2807
            case QEMU_OPTION_S:
2808
                autostart = 0;
2809
                break;
2810
            case QEMU_OPTION_k:
2811
                keyboard_layout = optarg;
2812
                break;
2813
            case QEMU_OPTION_localtime:
2814
                rtc_utc = 0;
2815
                break;
2816
            case QEMU_OPTION_vga:
2817
                select_vgahw (optarg);
2818
                break;
2819
            case QEMU_OPTION_g:
2820
                {
2821
                    const char *p;
2822
                    int w, h, depth;
2823
                    p = optarg;
2824
                    w = strtol(p, (char **)&p, 10);
2825
                    if (w <= 0) {
2826
                    graphic_error:
2827
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
2828
                        exit(1);
2829
                    }
2830
                    if (*p != 'x')
2831
                        goto graphic_error;
2832
                    p++;
2833
                    h = strtol(p, (char **)&p, 10);
2834
                    if (h <= 0)
2835
                        goto graphic_error;
2836
                    if (*p == 'x') {
2837
                        p++;
2838
                        depth = strtol(p, (char **)&p, 10);
2839
                        if (depth != 8 && depth != 15 && depth != 16 &&
2840
                            depth != 24 && depth != 32)
2841
                            goto graphic_error;
2842
                    } else if (*p == '\0') {
2843
                        depth = graphic_depth;
2844
                    } else {
2845
                        goto graphic_error;
2846
                    }
2847

    
2848
                    graphic_width = w;
2849
                    graphic_height = h;
2850
                    graphic_depth = depth;
2851
                }
2852
                break;
2853
            case QEMU_OPTION_echr:
2854
                {
2855
                    char *r;
2856
                    term_escape_char = strtol(optarg, &r, 0);
2857
                    if (r == optarg)
2858
                        printf("Bad argument to echr\n");
2859
                    break;
2860
                }
2861
            case QEMU_OPTION_monitor:
2862
                monitor_parse(optarg, "readline");
2863
                default_monitor = 0;
2864
                break;
2865
            case QEMU_OPTION_qmp:
2866
                monitor_parse(optarg, "control");
2867
                default_monitor = 0;
2868
                break;
2869
            case QEMU_OPTION_mon:
2870
                opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
2871
                if (!opts) {
2872
                    exit(1);
2873
                }
2874
                default_monitor = 0;
2875
                break;
2876
            case QEMU_OPTION_chardev:
2877
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
2878
                if (!opts) {
2879
                    exit(1);
2880
                }
2881
                break;
2882
#ifdef CONFIG_LINUX
2883
            case QEMU_OPTION_fsdev:
2884
                opts = qemu_opts_parse(&qemu_fsdev_opts, optarg, 1);
2885
                if (!opts) {
2886
                    fprintf(stderr, "parse error: %s\n", optarg);
2887
                    exit(1);
2888
                }
2889
                break;
2890
            case QEMU_OPTION_virtfs: {
2891
                char *arg_fsdev = NULL;
2892
                char *arg_9p = NULL;
2893
                int len = 0;
2894

    
2895
                opts = qemu_opts_parse(&qemu_virtfs_opts, optarg, 1);
2896
                if (!opts) {
2897
                    fprintf(stderr, "parse error: %s\n", optarg);
2898
                    exit(1);
2899
                }
2900

    
2901
                len = strlen(",id=,path=");
2902
                len += strlen(qemu_opt_get(opts, "fstype"));
2903
                len += strlen(qemu_opt_get(opts, "mount_tag"));
2904
                len += strlen(qemu_opt_get(opts, "path"));
2905
                arg_fsdev = qemu_malloc((len + 1) * sizeof(*arg_fsdev));
2906

    
2907
                if (!arg_fsdev) {
2908
                    fprintf(stderr, "No memory to parse -fsdev for %s\n",
2909
                            optarg);
2910
                    exit(1);
2911
                }
2912

    
2913
                sprintf(arg_fsdev, "%s,id=%s,path=%s",
2914
                                qemu_opt_get(opts, "fstype"),
2915
                                qemu_opt_get(opts, "mount_tag"),
2916
                                qemu_opt_get(opts, "path"));
2917

    
2918
                len = strlen("virtio-9p-pci,fsdev=,mount_tag=");
2919
                len += 2*strlen(qemu_opt_get(opts, "mount_tag"));
2920
                arg_9p = qemu_malloc((len + 1) * sizeof(*arg_9p));
2921

    
2922
                if (!arg_9p) {
2923
                    fprintf(stderr, "No memory to parse -device for %s\n",
2924
                            optarg);
2925
                    exit(1);
2926
                }
2927

    
2928
                sprintf(arg_9p, "virtio-9p-pci,fsdev=%s,mount_tag=%s",
2929
                                qemu_opt_get(opts, "mount_tag"),
2930
                                qemu_opt_get(opts, "mount_tag"));
2931

    
2932
                if (!qemu_opts_parse(&qemu_fsdev_opts, arg_fsdev, 1)) {
2933
                    fprintf(stderr, "parse error [fsdev]: %s\n", optarg);
2934
                    exit(1);
2935
                }
2936

    
2937
                if (!qemu_opts_parse(&qemu_device_opts, arg_9p, 1)) {
2938
                    fprintf(stderr, "parse error [device]: %s\n", optarg);
2939
                    exit(1);
2940
                }
2941

    
2942
                qemu_free(arg_fsdev);
2943
                qemu_free(arg_9p);
2944
                break;
2945
            }
2946
#endif
2947
            case QEMU_OPTION_serial:
2948
                add_device_config(DEV_SERIAL, optarg);
2949
                default_serial = 0;
2950
                if (strncmp(optarg, "mon:", 4) == 0) {
2951
                    default_monitor = 0;
2952
                }
2953
                break;
2954
            case QEMU_OPTION_watchdog:
2955
                if (watchdog) {
2956
                    fprintf(stderr,
2957
                            "qemu: only one watchdog option may be given\n");
2958
                    return 1;
2959
                }
2960
                watchdog = optarg;
2961
                break;
2962
            case QEMU_OPTION_watchdog_action:
2963
                if (select_watchdog_action(optarg) == -1) {
2964
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
2965
                    exit(1);
2966
                }
2967
                break;
2968
            case QEMU_OPTION_virtiocon:
2969
                add_device_config(DEV_VIRTCON, optarg);
2970
                default_virtcon = 0;
2971
                if (strncmp(optarg, "mon:", 4) == 0) {
2972
                    default_monitor = 0;
2973
                }
2974
                break;
2975
            case QEMU_OPTION_parallel:
2976
                add_device_config(DEV_PARALLEL, optarg);
2977
                default_parallel = 0;
2978
                if (strncmp(optarg, "mon:", 4) == 0) {
2979
                    default_monitor = 0;
2980
                }
2981
                break;
2982
            case QEMU_OPTION_debugcon:
2983
                add_device_config(DEV_DEBUGCON, optarg);
2984
                break;
2985
            case QEMU_OPTION_loadvm:
2986
                loadvm = optarg;
2987
                break;
2988
            case QEMU_OPTION_full_screen:
2989
                full_screen = 1;
2990
                break;
2991
#ifdef CONFIG_SDL
2992
            case QEMU_OPTION_no_frame:
2993
                no_frame = 1;
2994
                break;
2995
            case QEMU_OPTION_alt_grab:
2996
                alt_grab = 1;
2997
                break;
2998
            case QEMU_OPTION_ctrl_grab:
2999
                ctrl_grab = 1;
3000
                break;
3001
            case QEMU_OPTION_no_quit:
3002
                no_quit = 1;
3003
                break;
3004
            case QEMU_OPTION_sdl:
3005
                display_type = DT_SDL;
3006
                break;
3007
#endif
3008
            case QEMU_OPTION_pidfile:
3009
                pid_file = optarg;
3010
                break;
3011
            case QEMU_OPTION_win2k_hack:
3012
                win2k_install_hack = 1;
3013
                break;
3014
            case QEMU_OPTION_rtc_td_hack:
3015
                rtc_td_hack = 1;
3016
                break;
3017
            case QEMU_OPTION_acpitable:
3018
                do_acpitable_option(optarg);
3019
                break;
3020
            case QEMU_OPTION_smbios:
3021
                do_smbios_option(optarg);
3022
                break;
3023
            case QEMU_OPTION_enable_kvm:
3024
                kvm_allowed = 1;
3025
                break;
3026
            case QEMU_OPTION_usb:
3027
                usb_enabled = 1;
3028
                break;
3029
            case QEMU_OPTION_usbdevice:
3030
                usb_enabled = 1;
3031
                add_device_config(DEV_USB, optarg);
3032
                break;
3033
            case QEMU_OPTION_device:
3034
                if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
3035
                    exit(1);
3036
                }
3037
                break;
3038
            case QEMU_OPTION_smp:
3039
                smp_parse(optarg);
3040
                if (smp_cpus < 1) {
3041
                    fprintf(stderr, "Invalid number of CPUs\n");
3042
                    exit(1);
3043
                }
3044
                if (max_cpus < smp_cpus) {
3045
                    fprintf(stderr, "maxcpus must be equal to or greater than "
3046
                            "smp\n");
3047
                    exit(1);
3048
                }
3049
                if (max_cpus > 255) {
3050
                    fprintf(stderr, "Unsupported number of maxcpus\n");
3051
                    exit(1);
3052
                }
3053
                break;
3054
            case QEMU_OPTION_vnc:
3055
                display_type = DT_VNC;
3056
                vnc_display = optarg;
3057
                break;
3058
            case QEMU_OPTION_no_acpi:
3059
                acpi_enabled = 0;
3060
                break;
3061
            case QEMU_OPTION_no_hpet:
3062
                no_hpet = 1;
3063
                break;
3064
            case QEMU_OPTION_balloon:
3065
                if (balloon_parse(optarg) < 0) {
3066
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3067
                    exit(1);
3068
                }
3069
                break;
3070
            case QEMU_OPTION_no_reboot:
3071
                no_reboot = 1;
3072
                break;
3073
            case QEMU_OPTION_no_shutdown:
3074
                no_shutdown = 1;
3075
                break;
3076
            case QEMU_OPTION_show_cursor:
3077
                cursor_hide = 0;
3078
                break;
3079
            case QEMU_OPTION_uuid:
3080
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3081
                    fprintf(stderr, "Fail to parse UUID string."
3082
                            " Wrong format.\n");
3083
                    exit(1);
3084
                }
3085
                break;
3086
#ifndef _WIN32
3087
            case QEMU_OPTION_daemonize:
3088
                daemonize = 1;
3089
                break;
3090
#endif
3091
            case QEMU_OPTION_option_rom:
3092
                if (nb_option_roms >= MAX_OPTION_ROMS) {
3093
                    fprintf(stderr, "Too many option ROMs\n");
3094
                    exit(1);
3095
                }
3096
                option_rom[nb_option_roms] = optarg;
3097
                nb_option_roms++;
3098
                break;
3099
            case QEMU_OPTION_semihosting:
3100
                semihosting_enabled = 1;
3101
                break;
3102
            case QEMU_OPTION_name:
3103
                qemu_name = qemu_strdup(optarg);
3104
                 {
3105
                     char *p = strchr(qemu_name, ',');
3106
                     if (p != NULL) {
3107
                        *p++ = 0;
3108
                        if (strncmp(p, "process=", 8)) {
3109
                            fprintf(stderr, "Unknown subargument %s to -name", p);
3110
                            exit(1);
3111
                        }
3112
                        p += 8;
3113
                        set_proc_name(p);
3114
                     }        
3115
                 }        
3116
                break;
3117
            case QEMU_OPTION_prom_env:
3118
                if (nb_prom_envs >= MAX_PROM_ENVS) {
3119
                    fprintf(stderr, "Too many prom variables\n");
3120
                    exit(1);
3121
                }
3122
                prom_envs[nb_prom_envs] = optarg;
3123
                nb_prom_envs++;
3124
                break;
3125
            case QEMU_OPTION_old_param:
3126
                old_param = 1;
3127
                break;
3128
            case QEMU_OPTION_clock:
3129
                configure_alarms(optarg);
3130
                break;
3131
            case QEMU_OPTION_startdate:
3132
                configure_rtc_date_offset(optarg, 1);
3133
                break;
3134
            case QEMU_OPTION_rtc:
3135
                opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
3136
                if (!opts) {
3137
                    exit(1);
3138
                }
3139
                configure_rtc(opts);
3140
                break;
3141
            case QEMU_OPTION_tb_size:
3142
                tb_size = strtol(optarg, NULL, 0);
3143
                if (tb_size < 0)
3144
                    tb_size = 0;
3145
                break;
3146
            case QEMU_OPTION_icount:
3147
                icount_option = optarg;
3148
                break;
3149
            case QEMU_OPTION_incoming:
3150
                incoming = optarg;
3151
                break;
3152
            case QEMU_OPTION_nodefaults:
3153
                default_serial = 0;
3154
                default_parallel = 0;
3155
                default_virtcon = 0;
3156
                default_monitor = 0;
3157
                default_vga = 0;
3158
                default_net = 0;
3159
                default_floppy = 0;
3160
                default_cdrom = 0;
3161
                default_sdcard = 0;
3162
                break;
3163
#ifndef _WIN32
3164
            case QEMU_OPTION_chroot:
3165
                chroot_dir = optarg;
3166
                break;
3167
            case QEMU_OPTION_runas:
3168
                run_as = optarg;
3169
                break;
3170
#endif
3171
            case QEMU_OPTION_xen_domid:
3172
                if (!(xen_available())) {
3173
                    printf("Option %s not supported for this target\n", popt->name);
3174
                    exit(1);
3175
                }
3176
                xen_domid = atoi(optarg);
3177
                break;
3178
            case QEMU_OPTION_xen_create:
3179
                if (!(xen_available())) {
3180
                    printf("Option %s not supported for this target\n", popt->name);
3181
                    exit(1);
3182
                }
3183
                xen_mode = XEN_CREATE;
3184
                break;
3185
            case QEMU_OPTION_xen_attach:
3186
                if (!(xen_available())) {
3187
                    printf("Option %s not supported for this target\n", popt->name);
3188
                    exit(1);
3189
                }
3190
                xen_mode = XEN_ATTACH;
3191
                break;
3192
            case QEMU_OPTION_readconfig:
3193
                {
3194
                    int ret = qemu_read_config_file(optarg);
3195
                    if (ret < 0) {
3196
                        fprintf(stderr, "read config %s: %s\n", optarg,
3197
                            strerror(-ret));
3198
                        exit(1);
3199
                    }
3200
                    break;
3201
                }
3202
            case QEMU_OPTION_writeconfig:
3203
                {
3204
                    FILE *fp;
3205
                    if (strcmp(optarg, "-") == 0) {
3206
                        fp = stdout;
3207
                    } else {
3208
                        fp = fopen(optarg, "w");
3209
                        if (fp == NULL) {
3210
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3211
                            exit(1);
3212
                        }
3213
                    }
3214
                    qemu_config_write(fp);
3215
                    fclose(fp);
3216
                    break;
3217
                }
3218
            }
3219
        }
3220
    }
3221
    loc_set_none();
3222

    
3223
    /* If no data_dir is specified then try to find it relative to the
3224
       executable path.  */
3225
    if (!data_dir) {
3226
        data_dir = find_datadir(argv[0]);
3227
    }
3228
    /* If all else fails use the install patch specified when building.  */
3229
    if (!data_dir) {
3230
        data_dir = CONFIG_QEMU_DATADIR;
3231
    }
3232

    
3233
    /*
3234
     * Default to max_cpus = smp_cpus, in case the user doesn't
3235
     * specify a max_cpus value.
3236
     */
3237
    if (!max_cpus)
3238
        max_cpus = smp_cpus;
3239

    
3240
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3241
    if (smp_cpus > machine->max_cpus) {
3242
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3243
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3244
                machine->max_cpus);
3245
        exit(1);
3246
    }
3247

    
3248
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
3249
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
3250

    
3251
    if (machine->no_serial) {
3252
        default_serial = 0;
3253
    }
3254
    if (machine->no_parallel) {
3255
        default_parallel = 0;
3256
    }
3257
    if (!machine->use_virtcon) {
3258
        default_virtcon = 0;
3259
    }
3260
    if (machine->no_vga) {
3261
        default_vga = 0;
3262
    }
3263
    if (machine->no_floppy) {
3264
        default_floppy = 0;
3265
    }
3266
    if (machine->no_cdrom) {
3267
        default_cdrom = 0;
3268
    }
3269
    if (machine->no_sdcard) {
3270
        default_sdcard = 0;
3271
    }
3272

    
3273
    if (display_type == DT_NOGRAPHIC) {
3274
        if (default_parallel)
3275
            add_device_config(DEV_PARALLEL, "null");
3276
        if (default_serial && default_monitor) {
3277
            add_device_config(DEV_SERIAL, "mon:stdio");
3278
        } else if (default_virtcon && default_monitor) {
3279
            add_device_config(DEV_VIRTCON, "mon:stdio");
3280
        } else {
3281
            if (default_serial)
3282
                add_device_config(DEV_SERIAL, "stdio");
3283
            if (default_virtcon)
3284
                add_device_config(DEV_VIRTCON, "stdio");
3285
            if (default_monitor)
3286
                monitor_parse("stdio", "readline");
3287
        }
3288
    } else {
3289
        if (default_serial)
3290
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
3291
        if (default_parallel)
3292
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3293
        if (default_monitor)
3294
            monitor_parse("vc:80Cx24C", "readline");
3295
        if (default_virtcon)
3296
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3297
    }
3298
    if (default_vga)
3299
        vga_interface_type = VGA_CIRRUS;
3300

    
3301
    socket_init();
3302

    
3303
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3304
        exit(1);
3305
#ifdef CONFIG_LINUX
3306
    if (qemu_opts_foreach(&qemu_fsdev_opts, fsdev_init_func, NULL, 1) != 0) {
3307
        exit(1);
3308
    }
3309
#endif
3310

    
3311
#ifndef _WIN32
3312
    if (daemonize) {
3313
        pid_t pid;
3314

    
3315
        if (pipe(fds) == -1)
3316
            exit(1);
3317

    
3318
        pid = fork();
3319
        if (pid > 0) {
3320
            uint8_t status;
3321
            ssize_t len;
3322

    
3323
            close(fds[1]);
3324

    
3325
        again:
3326
            len = read(fds[0], &status, 1);
3327
            if (len == -1 && (errno == EINTR))
3328
                goto again;
3329

    
3330
            if (len != 1)
3331
                exit(1);
3332
            else if (status == 1) {
3333
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3334
                exit(1);
3335
            } else
3336
                exit(0);
3337
        } else if (pid < 0)
3338
            exit(1);
3339

    
3340
        close(fds[0]);
3341
        qemu_set_cloexec(fds[1]);
3342

    
3343
        setsid();
3344

    
3345
        pid = fork();
3346
        if (pid > 0)
3347
            exit(0);
3348
        else if (pid < 0)
3349
            exit(1);
3350

    
3351
        umask(027);
3352

    
3353
        signal(SIGTSTP, SIG_IGN);
3354
        signal(SIGTTOU, SIG_IGN);
3355
        signal(SIGTTIN, SIG_IGN);
3356
    }
3357
#endif
3358

    
3359
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3360
#ifndef _WIN32
3361
        if (daemonize) {
3362
            uint8_t status = 1;
3363
            if (write(fds[1], &status, 1) != 1) {
3364
                perror("daemonize. Writing to pipe\n");
3365
            }
3366
        } else
3367
#endif
3368
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3369
        exit(1);
3370
    }
3371

    
3372
    if (kvm_allowed) {
3373
        int ret = kvm_init(smp_cpus);
3374
        if (ret < 0) {
3375
            if (!kvm_available()) {
3376
                printf("KVM not supported for this target\n");
3377
            } else {
3378
                fprintf(stderr, "failed to initialize KVM: %s\n", strerror(-ret));
3379
            }
3380
            exit(1);
3381
        }
3382
    }
3383

    
3384
    if (qemu_init_main_loop()) {
3385
        fprintf(stderr, "qemu_init_main_loop failed\n");
3386
        exit(1);
3387
    }
3388
    linux_boot = (kernel_filename != NULL);
3389

    
3390
    if (!linux_boot && *kernel_cmdline != '\0') {
3391
        fprintf(stderr, "-append only allowed with -kernel option\n");
3392
        exit(1);
3393
    }
3394

    
3395
    if (!linux_boot && initrd_filename != NULL) {
3396
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3397
        exit(1);
3398
    }
3399

    
3400
#ifndef _WIN32
3401
    /* Win32 doesn't support line-buffering and requires size >= 2 */
3402
    setvbuf(stdout, NULL, _IOLBF, 0);
3403
#endif
3404

    
3405
    if (init_timer_alarm() < 0) {
3406
        fprintf(stderr, "could not initialize alarm timer\n");
3407
        exit(1);
3408
    }
3409
    configure_icount(icount_option);
3410

    
3411
    if (net_init_clients() < 0) {
3412
        exit(1);
3413
    }
3414

    
3415
    /* init the bluetooth world */
3416
    if (foreach_device_config(DEV_BT, bt_parse))
3417
        exit(1);
3418

    
3419
    /* init the memory */
3420
    if (ram_size == 0)
3421
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3422

    
3423
    /* init the dynamic translator */
3424
    cpu_exec_init_all(tb_size * 1024 * 1024);
3425

    
3426
    bdrv_init_with_whitelist();
3427

    
3428
    blk_mig_init();
3429

    
3430
    if (default_cdrom) {
3431
        /* we always create the cdrom drive, even if no disk is there */
3432
        drive_add(NULL, CDROM_ALIAS);
3433
    }
3434

    
3435
    if (default_floppy) {
3436
        /* we always create at least one floppy */
3437
        drive_add(NULL, FD_ALIAS, 0);
3438
    }
3439

    
3440
    if (default_sdcard) {
3441
        /* we always create one sd slot, even if no card is in it */
3442
        drive_add(NULL, SD_ALIAS);
3443
    }
3444

    
3445
    /* open the virtual block devices */
3446
    if (snapshot)
3447
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
3448
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
3449
        exit(1);
3450

    
3451
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
3452
                         ram_load, NULL);
3453

    
3454
    if (nb_numa_nodes > 0) {
3455
        int i;
3456

    
3457
        if (nb_numa_nodes > smp_cpus) {
3458
            nb_numa_nodes = smp_cpus;
3459
        }
3460

    
3461
        /* If no memory size if given for any node, assume the default case
3462
         * and distribute the available memory equally across all nodes
3463
         */
3464
        for (i = 0; i < nb_numa_nodes; i++) {
3465
            if (node_mem[i] != 0)
3466
                break;
3467
        }
3468
        if (i == nb_numa_nodes) {
3469
            uint64_t usedmem = 0;
3470

    
3471
            /* On Linux, the each node's border has to be 8MB aligned,
3472
             * the final node gets the rest.
3473
             */
3474
            for (i = 0; i < nb_numa_nodes - 1; i++) {
3475
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3476
                usedmem += node_mem[i];
3477
            }
3478
            node_mem[i] = ram_size - usedmem;
3479
        }
3480

    
3481
        for (i = 0; i < nb_numa_nodes; i++) {
3482
            if (node_cpumask[i] != 0)
3483
                break;
3484
        }
3485
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3486
         * must cope with this anyway, because there are BIOSes out there in
3487
         * real machines which also use this scheme.
3488
         */
3489
        if (i == nb_numa_nodes) {
3490
            for (i = 0; i < smp_cpus; i++) {
3491
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
3492
            }
3493
        }
3494
    }
3495

    
3496
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0) {
3497
        exit(1);
3498
    }
3499

    
3500
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3501
        exit(1);
3502
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3503
        exit(1);
3504
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3505
        exit(1);
3506
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3507
        exit(1);
3508

    
3509
    module_call_init(MODULE_INIT_DEVICE);
3510

    
3511
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
3512
        exit(0);
3513

    
3514
    if (watchdog) {
3515
        i = select_watchdog(watchdog);
3516
        if (i > 0)
3517
            exit (i == 1 ? 1 : 0);
3518
    }
3519

    
3520
    if (machine->compat_props) {
3521
        qdev_prop_register_global_list(machine->compat_props);
3522
    }
3523
    qemu_add_globals();
3524

    
3525
    machine->init(ram_size, boot_devices,
3526
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3527

    
3528
    cpu_synchronize_all_post_init();
3529

    
3530
    /* must be after terminal init, SDL library changes signal handlers */
3531
    os_setup_signal_handling();
3532

    
3533
    set_numa_modes();
3534

    
3535
    current_machine = machine;
3536

    
3537
    /* init USB devices */
3538
    if (usb_enabled) {
3539
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3540
            exit(1);
3541
    }
3542

    
3543
    /* init generic devices */
3544
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
3545
        exit(1);
3546

    
3547
    net_check_clients();
3548

    
3549
    /* just use the first displaystate for the moment */
3550
    ds = get_displaystate();
3551

    
3552
    if (display_type == DT_DEFAULT) {
3553
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3554
        display_type = DT_SDL;
3555
#else
3556
        display_type = DT_VNC;
3557
        vnc_display = "localhost:0,to=99";
3558
        show_vnc_port = 1;
3559
#endif
3560
    }
3561
        
3562

    
3563
    switch (display_type) {
3564
    case DT_NOGRAPHIC:
3565
        break;
3566
#if defined(CONFIG_CURSES)
3567
    case DT_CURSES:
3568
        curses_display_init(ds, full_screen);
3569
        break;
3570
#endif
3571
#if defined(CONFIG_SDL)
3572
    case DT_SDL:
3573
        sdl_display_init(ds, full_screen, no_frame);
3574
        break;
3575
#elif defined(CONFIG_COCOA)
3576
    case DT_SDL:
3577
        cocoa_display_init(ds, full_screen);
3578
        break;
3579
#endif
3580
    case DT_VNC:
3581
        vnc_display_init(ds);
3582
        if (vnc_display_open(ds, vnc_display) < 0)
3583
            exit(1);
3584

    
3585
        if (show_vnc_port) {
3586
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3587
        }
3588
        break;
3589
    default:
3590
        break;
3591
    }
3592
    dpy_resize(ds);
3593

    
3594
    dcl = ds->listeners;
3595
    while (dcl != NULL) {
3596
        if (dcl->dpy_refresh != NULL) {
3597
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
3598
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
3599
            break;
3600
        }
3601
        dcl = dcl->next;
3602
    }
3603

    
3604
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
3605
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
3606
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
3607
    }
3608

    
3609
    text_consoles_set_display(ds);
3610

    
3611
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3612
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3613
                gdbstub_dev);
3614
        exit(1);
3615
    }
3616

    
3617
    qdev_machine_creation_done();
3618

    
3619
    if (rom_load_all() != 0) {
3620
        fprintf(stderr, "rom loading failed\n");
3621
        exit(1);
3622
    }
3623

    
3624
    qemu_system_reset();
3625
    if (loadvm) {
3626
        if (load_vmstate(loadvm) < 0) {
3627
            autostart = 0;
3628
        }
3629
    }
3630

    
3631
    if (incoming) {
3632
        qemu_start_incoming_migration(incoming);
3633
    } else if (autostart) {
3634
        vm_start();
3635
    }
3636

    
3637
#ifndef _WIN32
3638
    if (daemonize) {
3639
        uint8_t status = 0;
3640
        ssize_t len;
3641

    
3642
    again1:
3643
        len = write(fds[1], &status, 1);
3644
        if (len == -1 && (errno == EINTR))
3645
            goto again1;
3646

    
3647
        if (len != 1)
3648
            exit(1);
3649

    
3650
        if (chdir("/")) {
3651
            perror("not able to chdir to /");
3652
            exit(1);
3653
        }
3654
        TFR(fd = qemu_open("/dev/null", O_RDWR));
3655
        if (fd == -1)
3656
            exit(1);
3657
    }
3658

    
3659
    if (run_as) {
3660
        pwd = getpwnam(run_as);
3661
        if (!pwd) {
3662
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
3663
            exit(1);
3664
        }
3665
    }
3666

    
3667
    if (chroot_dir) {
3668
        if (chroot(chroot_dir) < 0) {
3669
            fprintf(stderr, "chroot failed\n");
3670
            exit(1);
3671
        }
3672
        if (chdir("/")) {
3673
            perror("not able to chdir to /");
3674
            exit(1);
3675
        }
3676
    }
3677

    
3678
    if (run_as) {
3679
        if (setgid(pwd->pw_gid) < 0) {
3680
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
3681
            exit(1);
3682
        }
3683
        if (setuid(pwd->pw_uid) < 0) {
3684
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
3685
            exit(1);
3686
        }
3687
        if (setuid(0) != -1) {
3688
            fprintf(stderr, "Dropping privileges failed\n");
3689
            exit(1);
3690
        }
3691
    }
3692

    
3693
    if (daemonize) {
3694
        dup2(fd, 0);
3695
        dup2(fd, 1);
3696
        dup2(fd, 2);
3697

    
3698
        close(fd);
3699
    }
3700
#endif
3701

    
3702
    main_loop();
3703
    quit_timers();
3704
    net_cleanup();
3705

    
3706
    return 0;
3707
}