Statistics
| Branch: | Revision:

root / vl.c @ ad96090a

History | View | Annotate | Download (104.8 kB)

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

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

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

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

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

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

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

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

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

    
118
#include "hw/hw.h"
119
#include "hw/boards.h"
120
#include "hw/usb.h"
121
#include "hw/pcmcia.h"
122
#include "hw/pc.h"
123
#include "hw/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 "balloon.h"
149
#include "qemu-option.h"
150
#include "qemu-config.h"
151
#include "qemu-objects.h"
152

    
153
#include "disas.h"
154

    
155
#include "qemu_socket.h"
156

    
157
#include "slirp/libslirp.h"
158

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

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

    
166
#define DEFAULT_RAM_SIZE 128
167

    
168
#define MAX_VIRTIO_CONSOLES 1
169

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

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

    
236
static QEMUTimer *nographic_timer;
237

    
238
uint8_t qemu_uuid[16];
239

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

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

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

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

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

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

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

    
293
/***********************************************************/
294
/* x86 ISA bus support */
295

    
296
target_phys_addr_t isa_mem_base = 0;
297
PicState2 *isa_pic;
298

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

    
316
static QEMUBalloonEvent *qemu_balloon_event;
317
void *qemu_balloon_event_opaque;
318

    
319
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
320
{
321
    qemu_balloon_event = func;
322
    qemu_balloon_event_opaque = opaque;
323
}
324

    
325
int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
326
{
327
    if (qemu_balloon_event) {
328
        qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
329
        return 1;
330
    } else {
331
        return 0;
332
    }
333
}
334

    
335
int qemu_balloon_status(MonitorCompletion cb, void *opaque)
336
{
337
    if (qemu_balloon_event) {
338
        qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
339
        return 1;
340
    } else {
341
        return 0;
342
    }
343
}
344

    
345

    
346
/***********************************************************/
347
/* real time host monotonic timer */
348

    
349
/* compute with 96 bit intermediate result: (a*b)/c */
350
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
351
{
352
    union {
353
        uint64_t ll;
354
        struct {
355
#ifdef HOST_WORDS_BIGENDIAN
356
            uint32_t high, low;
357
#else
358
            uint32_t low, high;
359
#endif
360
        } l;
361
    } u, res;
362
    uint64_t rl, rh;
363

    
364
    u.ll = a;
365
    rl = (uint64_t)u.l.low * (uint64_t)b;
366
    rh = (uint64_t)u.l.high * (uint64_t)b;
367
    rh += (rl >> 32);
368
    res.l.high = rh / c;
369
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
370
    return res.ll;
371
}
372

    
373
/***********************************************************/
374
/* host time/date access */
375
void qemu_get_timedate(struct tm *tm, int offset)
376
{
377
    time_t ti;
378
    struct tm *ret;
379

    
380
    time(&ti);
381
    ti += offset;
382
    if (rtc_date_offset == -1) {
383
        if (rtc_utc)
384
            ret = gmtime(&ti);
385
        else
386
            ret = localtime(&ti);
387
    } else {
388
        ti -= rtc_date_offset;
389
        ret = gmtime(&ti);
390
    }
391

    
392
    memcpy(tm, ret, sizeof(struct tm));
393
}
394

    
395
int qemu_timedate_diff(struct tm *tm)
396
{
397
    time_t seconds;
398

    
399
    if (rtc_date_offset == -1)
400
        if (rtc_utc)
401
            seconds = mktimegm(tm);
402
        else
403
            seconds = mktime(tm);
404
    else
405
        seconds = mktimegm(tm) + rtc_date_offset;
406

    
407
    return seconds - time(NULL);
408
}
409

    
410
void rtc_change_mon_event(struct tm *tm)
411
{
412
    QObject *data;
413

    
414
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
415
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
416
    qobject_decref(data);
417
}
418

    
419
static void configure_rtc_date_offset(const char *startdate, int legacy)
420
{
421
    time_t rtc_start_date;
422
    struct tm tm;
423

    
424
    if (!strcmp(startdate, "now") && legacy) {
425
        rtc_date_offset = -1;
426
    } else {
427
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
428
                   &tm.tm_year,
429
                   &tm.tm_mon,
430
                   &tm.tm_mday,
431
                   &tm.tm_hour,
432
                   &tm.tm_min,
433
                   &tm.tm_sec) == 6) {
434
            /* OK */
435
        } else if (sscanf(startdate, "%d-%d-%d",
436
                          &tm.tm_year,
437
                          &tm.tm_mon,
438
                          &tm.tm_mday) == 3) {
439
            tm.tm_hour = 0;
440
            tm.tm_min = 0;
441
            tm.tm_sec = 0;
442
        } else {
443
            goto date_fail;
444
        }
445
        tm.tm_year -= 1900;
446
        tm.tm_mon--;
447
        rtc_start_date = mktimegm(&tm);
448
        if (rtc_start_date == -1) {
449
        date_fail:
450
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
451
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
452
            exit(1);
453
        }
454
        rtc_date_offset = time(NULL) - rtc_start_date;
455
    }
456
}
457

    
458
static void configure_rtc(QemuOpts *opts)
459
{
460
    const char *value;
461

    
462
    value = qemu_opt_get(opts, "base");
463
    if (value) {
464
        if (!strcmp(value, "utc")) {
465
            rtc_utc = 1;
466
        } else if (!strcmp(value, "localtime")) {
467
            rtc_utc = 0;
468
        } else {
469
            configure_rtc_date_offset(value, 0);
470
        }
471
    }
472
    value = qemu_opt_get(opts, "clock");
473
    if (value) {
474
        if (!strcmp(value, "host")) {
475
            rtc_clock = host_clock;
476
        } else if (!strcmp(value, "vm")) {
477
            rtc_clock = vm_clock;
478
        } else {
479
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
480
            exit(1);
481
        }
482
    }
483
    value = qemu_opt_get(opts, "driftfix");
484
    if (value) {
485
        if (!strcmp(value, "slew")) {
486
            rtc_td_hack = 1;
487
        } else if (!strcmp(value, "none")) {
488
            rtc_td_hack = 0;
489
        } else {
490
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
491
            exit(1);
492
        }
493
    }
494
}
495

    
496
#ifdef _WIN32
497
static void socket_cleanup(void)
498
{
499
    WSACleanup();
500
}
501

    
502
static int socket_init(void)
503
{
504
    WSADATA Data;
505
    int ret, err;
506

    
507
    ret = WSAStartup(MAKEWORD(2,2), &Data);
508
    if (ret != 0) {
509
        err = WSAGetLastError();
510
        fprintf(stderr, "WSAStartup: %d\n", err);
511
        return -1;
512
    }
513
    atexit(socket_cleanup);
514
    return 0;
515
}
516
#endif
517

    
518
/***********************************************************/
519
/* Bluetooth support */
520
static int nb_hcis;
521
static int cur_hci;
522
static struct HCIInfo *hci_table[MAX_NICS];
523

    
524
static struct bt_vlan_s {
525
    struct bt_scatternet_s net;
526
    int id;
527
    struct bt_vlan_s *next;
528
} *first_bt_vlan;
529

    
530
/* find or alloc a new bluetooth "VLAN" */
531
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
532
{
533
    struct bt_vlan_s **pvlan, *vlan;
534
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
535
        if (vlan->id == id)
536
            return &vlan->net;
537
    }
538
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
539
    vlan->id = id;
540
    pvlan = &first_bt_vlan;
541
    while (*pvlan != NULL)
542
        pvlan = &(*pvlan)->next;
543
    *pvlan = vlan;
544
    return &vlan->net;
545
}
546

    
547
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
548
{
549
}
550

    
551
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
552
{
553
    return -ENOTSUP;
554
}
555

    
556
static struct HCIInfo null_hci = {
557
    .cmd_send = null_hci_send,
558
    .sco_send = null_hci_send,
559
    .acl_send = null_hci_send,
560
    .bdaddr_set = null_hci_addr_set,
561
};
562

    
563
struct HCIInfo *qemu_next_hci(void)
564
{
565
    if (cur_hci == nb_hcis)
566
        return &null_hci;
567

    
568
    return hci_table[cur_hci++];
569
}
570

    
571
static struct HCIInfo *hci_init(const char *str)
572
{
573
    char *endp;
574
    struct bt_scatternet_s *vlan = 0;
575

    
576
    if (!strcmp(str, "null"))
577
        /* null */
578
        return &null_hci;
579
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
580
        /* host[:hciN] */
581
        return bt_host_hci(str[4] ? str + 5 : "hci0");
582
    else if (!strncmp(str, "hci", 3)) {
583
        /* hci[,vlan=n] */
584
        if (str[3]) {
585
            if (!strncmp(str + 3, ",vlan=", 6)) {
586
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
587
                if (*endp)
588
                    vlan = 0;
589
            }
590
        } else
591
            vlan = qemu_find_bt_vlan(0);
592
        if (vlan)
593
           return bt_new_hci(vlan);
594
    }
595

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

    
598
    return 0;
599
}
600

    
601
static int bt_hci_parse(const char *str)
602
{
603
    struct HCIInfo *hci;
604
    bdaddr_t bdaddr;
605

    
606
    if (nb_hcis >= MAX_NICS) {
607
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
608
        return -1;
609
    }
610

    
611
    hci = hci_init(str);
612
    if (!hci)
613
        return -1;
614

    
615
    bdaddr.b[0] = 0x52;
616
    bdaddr.b[1] = 0x54;
617
    bdaddr.b[2] = 0x00;
618
    bdaddr.b[3] = 0x12;
619
    bdaddr.b[4] = 0x34;
620
    bdaddr.b[5] = 0x56 + nb_hcis;
621
    hci->bdaddr_set(hci, bdaddr.b);
622

    
623
    hci_table[nb_hcis++] = hci;
624

    
625
    return 0;
626
}
627

    
628
static void bt_vhci_add(int vlan_id)
629
{
630
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
631

    
632
    if (!vlan->slave)
633
        fprintf(stderr, "qemu: warning: adding a VHCI to "
634
                        "an empty scatternet %i\n", vlan_id);
635

    
636
    bt_vhci_init(bt_new_hci(vlan));
637
}
638

    
639
static struct bt_device_s *bt_device_add(const char *opt)
640
{
641
    struct bt_scatternet_s *vlan;
642
    int vlan_id = 0;
643
    char *endp = strstr(opt, ",vlan=");
644
    int len = (endp ? endp - opt : strlen(opt)) + 1;
645
    char devname[10];
646

    
647
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
648

    
649
    if (endp) {
650
        vlan_id = strtol(endp + 6, &endp, 0);
651
        if (*endp) {
652
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
653
            return 0;
654
        }
655
    }
656

    
657
    vlan = qemu_find_bt_vlan(vlan_id);
658

    
659
    if (!vlan->slave)
660
        fprintf(stderr, "qemu: warning: adding a slave device to "
661
                        "an empty scatternet %i\n", vlan_id);
662

    
663
    if (!strcmp(devname, "keyboard"))
664
        return bt_keyboard_init(vlan);
665

    
666
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
667
    return 0;
668
}
669

    
670
static int bt_parse(const char *opt)
671
{
672
    const char *endp, *p;
673
    int vlan;
674

    
675
    if (strstart(opt, "hci", &endp)) {
676
        if (!*endp || *endp == ',') {
677
            if (*endp)
678
                if (!strstart(endp, ",vlan=", 0))
679
                    opt = endp + 1;
680

    
681
            return bt_hci_parse(opt);
682
       }
683
    } else if (strstart(opt, "vhci", &endp)) {
684
        if (!*endp || *endp == ',') {
685
            if (*endp) {
686
                if (strstart(endp, ",vlan=", &p)) {
687
                    vlan = strtol(p, (char **) &endp, 0);
688
                    if (*endp) {
689
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
690
                        return 1;
691
                    }
692
                } else {
693
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
694
                    return 1;
695
                }
696
            } else
697
                vlan = 0;
698

    
699
            bt_vhci_add(vlan);
700
            return 0;
701
        }
702
    } else if (strstart(opt, "device:", &endp))
703
        return !bt_device_add(endp);
704

    
705
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
706
    return 1;
707
}
708

    
709
/***********************************************************/
710
/* QEMU Block devices */
711

    
712
#define HD_ALIAS "index=%d,media=disk"
713
#define CDROM_ALIAS "index=2,media=cdrom"
714
#define FD_ALIAS "index=%d,if=floppy"
715
#define PFLASH_ALIAS "if=pflash"
716
#define MTD_ALIAS "if=mtd"
717
#define SD_ALIAS "index=0,if=sd"
718

    
719
QemuOpts *drive_add(const char *file, const char *fmt, ...)
720
{
721
    va_list ap;
722
    char optstr[1024];
723
    QemuOpts *opts;
724

    
725
    va_start(ap, fmt);
726
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
727
    va_end(ap);
728

    
729
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
730
    if (!opts) {
731
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
732
                __FUNCTION__, optstr);
733
        return NULL;
734
    }
735
    if (file)
736
        qemu_opt_set(opts, "file", file);
737
    return opts;
738
}
739

    
740
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
741
{
742
    DriveInfo *dinfo;
743

    
744
    /* seek interface, bus and unit */
745

    
746
    QTAILQ_FOREACH(dinfo, &drives, next) {
747
        if (dinfo->type == type &&
748
            dinfo->bus == bus &&
749
            dinfo->unit == unit)
750
            return dinfo;
751
    }
752

    
753
    return NULL;
754
}
755

    
756
DriveInfo *drive_get_by_id(const char *id)
757
{
758
    DriveInfo *dinfo;
759

    
760
    QTAILQ_FOREACH(dinfo, &drives, next) {
761
        if (strcmp(id, dinfo->id))
762
            continue;
763
        return dinfo;
764
    }
765
    return NULL;
766
}
767

    
768
int drive_get_max_bus(BlockInterfaceType type)
769
{
770
    int max_bus;
771
    DriveInfo *dinfo;
772

    
773
    max_bus = -1;
774
    QTAILQ_FOREACH(dinfo, &drives, next) {
775
        if(dinfo->type == type &&
776
           dinfo->bus > max_bus)
777
            max_bus = dinfo->bus;
778
    }
779
    return max_bus;
780
}
781

    
782
const char *drive_get_serial(BlockDriverState *bdrv)
783
{
784
    DriveInfo *dinfo;
785

    
786
    QTAILQ_FOREACH(dinfo, &drives, next) {
787
        if (dinfo->bdrv == bdrv)
788
            return dinfo->serial;
789
    }
790

    
791
    return "\0";
792
}
793

    
794
BlockInterfaceErrorAction drive_get_on_error(
795
    BlockDriverState *bdrv, int is_read)
796
{
797
    DriveInfo *dinfo;
798

    
799
    QTAILQ_FOREACH(dinfo, &drives, next) {
800
        if (dinfo->bdrv == bdrv)
801
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
802
    }
803

    
804
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
805
}
806

    
807
static void bdrv_format_print(void *opaque, const char *name)
808
{
809
    fprintf(stderr, " %s", name);
810
}
811

    
812
void drive_uninit(DriveInfo *dinfo)
813
{
814
    qemu_opts_del(dinfo->opts);
815
    bdrv_delete(dinfo->bdrv);
816
    QTAILQ_REMOVE(&drives, dinfo, next);
817
    qemu_free(dinfo);
818
}
819

    
820
static int parse_block_error_action(const char *buf, int is_read)
821
{
822
    if (!strcmp(buf, "ignore")) {
823
        return BLOCK_ERR_IGNORE;
824
    } else if (!is_read && !strcmp(buf, "enospc")) {
825
        return BLOCK_ERR_STOP_ENOSPC;
826
    } else if (!strcmp(buf, "stop")) {
827
        return BLOCK_ERR_STOP_ANY;
828
    } else if (!strcmp(buf, "report")) {
829
        return BLOCK_ERR_REPORT;
830
    } else {
831
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
832
            buf, is_read ? "read" : "write");
833
        return -1;
834
    }
835
}
836

    
837
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
838
                      int *fatal_error)
839
{
840
    const char *buf;
841
    const char *file = NULL;
842
    char devname[128];
843
    const char *serial;
844
    const char *mediastr = "";
845
    BlockInterfaceType type;
846
    enum { MEDIA_DISK, MEDIA_CDROM } media;
847
    int bus_id, unit_id;
848
    int cyls, heads, secs, translation;
849
    BlockDriver *drv = NULL;
850
    QEMUMachine *machine = opaque;
851
    int max_devs;
852
    int index;
853
    int cache;
854
    int aio = 0;
855
    int ro = 0;
856
    int bdrv_flags;
857
    int on_read_error, on_write_error;
858
    const char *devaddr;
859
    DriveInfo *dinfo;
860
    int snapshot = 0;
861

    
862
    *fatal_error = 1;
863

    
864
    translation = BIOS_ATA_TRANSLATION_AUTO;
865
    cache = 1;
866

    
867
    if (machine && machine->use_scsi) {
868
        type = IF_SCSI;
869
        max_devs = MAX_SCSI_DEVS;
870
        pstrcpy(devname, sizeof(devname), "scsi");
871
    } else {
872
        type = IF_IDE;
873
        max_devs = MAX_IDE_DEVS;
874
        pstrcpy(devname, sizeof(devname), "ide");
875
    }
876
    media = MEDIA_DISK;
877

    
878
    /* extract parameters */
879
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
880
    unit_id = qemu_opt_get_number(opts, "unit", -1);
881
    index   = qemu_opt_get_number(opts, "index", -1);
882

    
883
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
884
    heads = qemu_opt_get_number(opts, "heads", 0);
885
    secs  = qemu_opt_get_number(opts, "secs", 0);
886

    
887
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
888
    ro = qemu_opt_get_bool(opts, "readonly", 0);
889

    
890
    file = qemu_opt_get(opts, "file");
891
    serial = qemu_opt_get(opts, "serial");
892

    
893
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
894
        pstrcpy(devname, sizeof(devname), buf);
895
        if (!strcmp(buf, "ide")) {
896
            type = IF_IDE;
897
            max_devs = MAX_IDE_DEVS;
898
        } else if (!strcmp(buf, "scsi")) {
899
            type = IF_SCSI;
900
            max_devs = MAX_SCSI_DEVS;
901
        } else if (!strcmp(buf, "floppy")) {
902
            type = IF_FLOPPY;
903
            max_devs = 0;
904
        } else if (!strcmp(buf, "pflash")) {
905
            type = IF_PFLASH;
906
            max_devs = 0;
907
        } else if (!strcmp(buf, "mtd")) {
908
            type = IF_MTD;
909
            max_devs = 0;
910
        } else if (!strcmp(buf, "sd")) {
911
            type = IF_SD;
912
            max_devs = 0;
913
        } else if (!strcmp(buf, "virtio")) {
914
            type = IF_VIRTIO;
915
            max_devs = 0;
916
        } else if (!strcmp(buf, "xen")) {
917
            type = IF_XEN;
918
            max_devs = 0;
919
        } else if (!strcmp(buf, "none")) {
920
            type = IF_NONE;
921
            max_devs = 0;
922
        } else {
923
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
924
            return NULL;
925
        }
926
    }
927

    
928
    if (cyls || heads || secs) {
929
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
930
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
931
            return NULL;
932
        }
933
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
934
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
935
            return NULL;
936
        }
937
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
938
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
939
            return NULL;
940
        }
941
    }
942

    
943
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
944
        if (!cyls) {
945
            fprintf(stderr,
946
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
947
                    buf);
948
            return NULL;
949
        }
950
        if (!strcmp(buf, "none"))
951
            translation = BIOS_ATA_TRANSLATION_NONE;
952
        else if (!strcmp(buf, "lba"))
953
            translation = BIOS_ATA_TRANSLATION_LBA;
954
        else if (!strcmp(buf, "auto"))
955
            translation = BIOS_ATA_TRANSLATION_AUTO;
956
        else {
957
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
958
            return NULL;
959
        }
960
    }
961

    
962
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
963
        if (!strcmp(buf, "disk")) {
964
            media = MEDIA_DISK;
965
        } else if (!strcmp(buf, "cdrom")) {
966
            if (cyls || secs || heads) {
967
                fprintf(stderr,
968
                        "qemu: '%s' invalid physical CHS format\n", buf);
969
                return NULL;
970
            }
971
            media = MEDIA_CDROM;
972
        } else {
973
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
974
            return NULL;
975
        }
976
    }
977

    
978
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
979
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
980
            cache = 0;
981
        else if (!strcmp(buf, "writethrough"))
982
            cache = 1;
983
        else if (!strcmp(buf, "writeback"))
984
            cache = 2;
985
        else {
986
           fprintf(stderr, "qemu: invalid cache option\n");
987
           return NULL;
988
        }
989
    }
990

    
991
#ifdef CONFIG_LINUX_AIO
992
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
993
        if (!strcmp(buf, "threads"))
994
            aio = 0;
995
        else if (!strcmp(buf, "native"))
996
            aio = 1;
997
        else {
998
           fprintf(stderr, "qemu: invalid aio option\n");
999
           return NULL;
1000
        }
1001
    }
1002
#endif
1003

    
1004
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1005
       if (strcmp(buf, "?") == 0) {
1006
            fprintf(stderr, "qemu: Supported formats:");
1007
            bdrv_iterate_format(bdrv_format_print, NULL);
1008
            fprintf(stderr, "\n");
1009
            return NULL;
1010
        }
1011
        drv = bdrv_find_whitelisted_format(buf);
1012
        if (!drv) {
1013
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1014
            return NULL;
1015
        }
1016
    }
1017

    
1018
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
1019
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1020
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1021
            fprintf(stderr, "werror is no supported by this format\n");
1022
            return NULL;
1023
        }
1024

    
1025
        on_write_error = parse_block_error_action(buf, 0);
1026
        if (on_write_error < 0) {
1027
            return NULL;
1028
        }
1029
    }
1030

    
1031
    on_read_error = BLOCK_ERR_REPORT;
1032
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1033
        if (type != IF_IDE && type != IF_VIRTIO) {
1034
            fprintf(stderr, "rerror is no supported by this format\n");
1035
            return NULL;
1036
        }
1037

    
1038
        on_read_error = parse_block_error_action(buf, 1);
1039
        if (on_read_error < 0) {
1040
            return NULL;
1041
        }
1042
    }
1043

    
1044
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1045
        if (type != IF_VIRTIO) {
1046
            fprintf(stderr, "addr is not supported\n");
1047
            return NULL;
1048
        }
1049
    }
1050

    
1051
    /* compute bus and unit according index */
1052

    
1053
    if (index != -1) {
1054
        if (bus_id != 0 || unit_id != -1) {
1055
            fprintf(stderr,
1056
                    "qemu: index cannot be used with bus and unit\n");
1057
            return NULL;
1058
        }
1059
        if (max_devs == 0)
1060
        {
1061
            unit_id = index;
1062
            bus_id = 0;
1063
        } else {
1064
            unit_id = index % max_devs;
1065
            bus_id = index / max_devs;
1066
        }
1067
    }
1068

    
1069
    /* if user doesn't specify a unit_id,
1070
     * try to find the first free
1071
     */
1072

    
1073
    if (unit_id == -1) {
1074
       unit_id = 0;
1075
       while (drive_get(type, bus_id, unit_id) != NULL) {
1076
           unit_id++;
1077
           if (max_devs && unit_id >= max_devs) {
1078
               unit_id -= max_devs;
1079
               bus_id++;
1080
           }
1081
       }
1082
    }
1083

    
1084
    /* check unit id */
1085

    
1086
    if (max_devs && unit_id >= max_devs) {
1087
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1088
                unit_id, max_devs - 1);
1089
        return NULL;
1090
    }
1091

    
1092
    /*
1093
     * ignore multiple definitions
1094
     */
1095

    
1096
    if (drive_get(type, bus_id, unit_id) != NULL) {
1097
        *fatal_error = 0;
1098
        return NULL;
1099
    }
1100

    
1101
    /* init */
1102

    
1103
    dinfo = qemu_mallocz(sizeof(*dinfo));
1104
    if ((buf = qemu_opts_id(opts)) != NULL) {
1105
        dinfo->id = qemu_strdup(buf);
1106
    } else {
1107
        /* no id supplied -> create one */
1108
        dinfo->id = qemu_mallocz(32);
1109
        if (type == IF_IDE || type == IF_SCSI)
1110
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1111
        if (max_devs)
1112
            snprintf(dinfo->id, 32, "%s%i%s%i",
1113
                     devname, bus_id, mediastr, unit_id);
1114
        else
1115
            snprintf(dinfo->id, 32, "%s%s%i",
1116
                     devname, mediastr, unit_id);
1117
    }
1118
    dinfo->bdrv = bdrv_new(dinfo->id);
1119
    dinfo->devaddr = devaddr;
1120
    dinfo->type = type;
1121
    dinfo->bus = bus_id;
1122
    dinfo->unit = unit_id;
1123
    dinfo->on_read_error = on_read_error;
1124
    dinfo->on_write_error = on_write_error;
1125
    dinfo->opts = opts;
1126
    if (serial)
1127
        strncpy(dinfo->serial, serial, sizeof(serial));
1128
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1129

    
1130
    switch(type) {
1131
    case IF_IDE:
1132
    case IF_SCSI:
1133
    case IF_XEN:
1134
    case IF_NONE:
1135
        switch(media) {
1136
        case MEDIA_DISK:
1137
            if (cyls != 0) {
1138
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1139
                bdrv_set_translation_hint(dinfo->bdrv, translation);
1140
            }
1141
            break;
1142
        case MEDIA_CDROM:
1143
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1144
            break;
1145
        }
1146
        break;
1147
    case IF_SD:
1148
        /* FIXME: This isn't really a floppy, but it's a reasonable
1149
           approximation.  */
1150
    case IF_FLOPPY:
1151
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1152
        break;
1153
    case IF_PFLASH:
1154
    case IF_MTD:
1155
        break;
1156
    case IF_VIRTIO:
1157
        /* add virtio block device */
1158
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1159
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
1160
        qemu_opt_set(opts, "drive", dinfo->id);
1161
        if (devaddr)
1162
            qemu_opt_set(opts, "addr", devaddr);
1163
        break;
1164
    case IF_COUNT:
1165
        abort();
1166
    }
1167
    if (!file) {
1168
        *fatal_error = 0;
1169
        return NULL;
1170
    }
1171
    bdrv_flags = 0;
1172
    if (snapshot) {
1173
        bdrv_flags |= BDRV_O_SNAPSHOT;
1174
        cache = 2; /* always use write-back with snapshot */
1175
    }
1176
    if (cache == 0) /* no caching */
1177
        bdrv_flags |= BDRV_O_NOCACHE;
1178
    else if (cache == 2) /* write-back */
1179
        bdrv_flags |= BDRV_O_CACHE_WB;
1180

    
1181
    if (aio == 1) {
1182
        bdrv_flags |= BDRV_O_NATIVE_AIO;
1183
    } else {
1184
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1185
    }
1186

    
1187
    if (ro == 1) {
1188
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1189
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1190
            return NULL;
1191
        }
1192
    }
1193
    /* 
1194
     * cdrom is read-only. Set it now, after above interface checking
1195
     * since readonly attribute not explicitly required, so no error.
1196
     */
1197
    if (media == MEDIA_CDROM) {
1198
        ro = 1;
1199
    }
1200
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1201

    
1202
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1203
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1204
                        file, strerror(errno));
1205
        return NULL;
1206
    }
1207

    
1208
    if (bdrv_key_required(dinfo->bdrv))
1209
        autostart = 0;
1210
    *fatal_error = 0;
1211
    return dinfo;
1212
}
1213

    
1214
static int drive_init_func(QemuOpts *opts, void *opaque)
1215
{
1216
    QEMUMachine *machine = opaque;
1217
    int fatal_error = 0;
1218

    
1219
    if (drive_init(opts, machine, &fatal_error) == NULL) {
1220
        if (fatal_error)
1221
            return 1;
1222
    }
1223
    return 0;
1224
}
1225

    
1226
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1227
{
1228
    if (NULL == qemu_opt_get(opts, "snapshot")) {
1229
        qemu_opt_set(opts, "snapshot", "on");
1230
    }
1231
    return 0;
1232
}
1233

    
1234
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1235
{
1236
    boot_set_handler = func;
1237
    boot_set_opaque = opaque;
1238
}
1239

    
1240
int qemu_boot_set(const char *boot_devices)
1241
{
1242
    if (!boot_set_handler) {
1243
        return -EINVAL;
1244
    }
1245
    return boot_set_handler(boot_set_opaque, boot_devices);
1246
}
1247

    
1248
static int parse_bootdevices(char *devices)
1249
{
1250
    /* We just do some generic consistency checks */
1251
    const char *p;
1252
    int bitmap = 0;
1253

    
1254
    for (p = devices; *p != '\0'; p++) {
1255
        /* Allowed boot devices are:
1256
         * a-b: floppy disk drives
1257
         * c-f: IDE disk drives
1258
         * g-m: machine implementation dependant drives
1259
         * n-p: network devices
1260
         * It's up to each machine implementation to check if the given boot
1261
         * devices match the actual hardware implementation and firmware
1262
         * features.
1263
         */
1264
        if (*p < 'a' || *p > 'p') {
1265
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
1266
            exit(1);
1267
        }
1268
        if (bitmap & (1 << (*p - 'a'))) {
1269
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1270
            exit(1);
1271
        }
1272
        bitmap |= 1 << (*p - 'a');
1273
    }
1274
    return bitmap;
1275
}
1276

    
1277
static void restore_boot_devices(void *opaque)
1278
{
1279
    char *standard_boot_devices = opaque;
1280

    
1281
    qemu_boot_set(standard_boot_devices);
1282

    
1283
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1284
    qemu_free(standard_boot_devices);
1285
}
1286

    
1287
static void numa_add(const char *optarg)
1288
{
1289
    char option[128];
1290
    char *endptr;
1291
    unsigned long long value, endvalue;
1292
    int nodenr;
1293

    
1294
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
1295
    if (!strcmp(option, "node")) {
1296
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1297
            nodenr = nb_numa_nodes;
1298
        } else {
1299
            nodenr = strtoull(option, NULL, 10);
1300
        }
1301

    
1302
        if (get_param_value(option, 128, "mem", optarg) == 0) {
1303
            node_mem[nodenr] = 0;
1304
        } else {
1305
            value = strtoull(option, &endptr, 0);
1306
            switch (*endptr) {
1307
            case 0: case 'M': case 'm':
1308
                value <<= 20;
1309
                break;
1310
            case 'G': case 'g':
1311
                value <<= 30;
1312
                break;
1313
            }
1314
            node_mem[nodenr] = value;
1315
        }
1316
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
1317
            node_cpumask[nodenr] = 0;
1318
        } else {
1319
            value = strtoull(option, &endptr, 10);
1320
            if (value >= 64) {
1321
                value = 63;
1322
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1323
            } else {
1324
                if (*endptr == '-') {
1325
                    endvalue = strtoull(endptr+1, &endptr, 10);
1326
                    if (endvalue >= 63) {
1327
                        endvalue = 62;
1328
                        fprintf(stderr,
1329
                            "only 63 CPUs in NUMA mode supported.\n");
1330
                    }
1331
                    value = (2ULL << endvalue) - (1ULL << value);
1332
                } else {
1333
                    value = 1ULL << value;
1334
                }
1335
            }
1336
            node_cpumask[nodenr] = value;
1337
        }
1338
        nb_numa_nodes++;
1339
    }
1340
    return;
1341
}
1342

    
1343
static void smp_parse(const char *optarg)
1344
{
1345
    int smp, sockets = 0, threads = 0, cores = 0;
1346
    char *endptr;
1347
    char option[128];
1348

    
1349
    smp = strtoul(optarg, &endptr, 10);
1350
    if (endptr != optarg) {
1351
        if (*endptr == ',') {
1352
            endptr++;
1353
        }
1354
    }
1355
    if (get_param_value(option, 128, "sockets", endptr) != 0)
1356
        sockets = strtoull(option, NULL, 10);
1357
    if (get_param_value(option, 128, "cores", endptr) != 0)
1358
        cores = strtoull(option, NULL, 10);
1359
    if (get_param_value(option, 128, "threads", endptr) != 0)
1360
        threads = strtoull(option, NULL, 10);
1361
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1362
        max_cpus = strtoull(option, NULL, 10);
1363

    
1364
    /* compute missing values, prefer sockets over cores over threads */
1365
    if (smp == 0 || sockets == 0) {
1366
        sockets = sockets > 0 ? sockets : 1;
1367
        cores = cores > 0 ? cores : 1;
1368
        threads = threads > 0 ? threads : 1;
1369
        if (smp == 0) {
1370
            smp = cores * threads * sockets;
1371
        }
1372
    } else {
1373
        if (cores == 0) {
1374
            threads = threads > 0 ? threads : 1;
1375
            cores = smp / (sockets * threads);
1376
        } else {
1377
            if (sockets) {
1378
                threads = smp / (cores * sockets);
1379
            }
1380
        }
1381
    }
1382
    smp_cpus = smp;
1383
    smp_cores = cores > 0 ? cores : 1;
1384
    smp_threads = threads > 0 ? threads : 1;
1385
    if (max_cpus == 0)
1386
        max_cpus = smp_cpus;
1387
}
1388

    
1389
/***********************************************************/
1390
/* USB devices */
1391

    
1392
static int usb_device_add(const char *devname, int is_hotplug)
1393
{
1394
    const char *p;
1395
    USBDevice *dev = NULL;
1396

    
1397
    if (!usb_enabled)
1398
        return -1;
1399

    
1400
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1401
    dev = usbdevice_create(devname);
1402
    if (dev)
1403
        goto done;
1404

    
1405
    /* the other ones */
1406
    if (strstart(devname, "host:", &p)) {
1407
        dev = usb_host_device_open(p);
1408
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1409
        dev = usb_bt_init(devname[2] ? hci_init(p) :
1410
                        bt_new_hci(qemu_find_bt_vlan(0)));
1411
    } else {
1412
        return -1;
1413
    }
1414
    if (!dev)
1415
        return -1;
1416

    
1417
done:
1418
    return 0;
1419
}
1420

    
1421
static int usb_device_del(const char *devname)
1422
{
1423
    int bus_num, addr;
1424
    const char *p;
1425

    
1426
    if (strstart(devname, "host:", &p))
1427
        return usb_host_device_close(p);
1428

    
1429
    if (!usb_enabled)
1430
        return -1;
1431

    
1432
    p = strchr(devname, '.');
1433
    if (!p)
1434
        return -1;
1435
    bus_num = strtoul(devname, NULL, 0);
1436
    addr = strtoul(p + 1, NULL, 0);
1437

    
1438
    return usb_device_delete_addr(bus_num, addr);
1439
}
1440

    
1441
static int usb_parse(const char *cmdline)
1442
{
1443
    int r;
1444
    r = usb_device_add(cmdline, 0);
1445
    if (r < 0) {
1446
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1447
    }
1448
    return r;
1449
}
1450

    
1451
void do_usb_add(Monitor *mon, const QDict *qdict)
1452
{
1453
    const char *devname = qdict_get_str(qdict, "devname");
1454
    if (usb_device_add(devname, 1) < 0) {
1455
        error_report("could not add USB device '%s'", devname);
1456
    }
1457
}
1458

    
1459
void do_usb_del(Monitor *mon, const QDict *qdict)
1460
{
1461
    const char *devname = qdict_get_str(qdict, "devname");
1462
    if (usb_device_del(devname) < 0) {
1463
        error_report("could not delete USB device '%s'", devname);
1464
    }
1465
}
1466

    
1467
/***********************************************************/
1468
/* PCMCIA/Cardbus */
1469

    
1470
static struct pcmcia_socket_entry_s {
1471
    PCMCIASocket *socket;
1472
    struct pcmcia_socket_entry_s *next;
1473
} *pcmcia_sockets = 0;
1474

    
1475
void pcmcia_socket_register(PCMCIASocket *socket)
1476
{
1477
    struct pcmcia_socket_entry_s *entry;
1478

    
1479
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1480
    entry->socket = socket;
1481
    entry->next = pcmcia_sockets;
1482
    pcmcia_sockets = entry;
1483
}
1484

    
1485
void pcmcia_socket_unregister(PCMCIASocket *socket)
1486
{
1487
    struct pcmcia_socket_entry_s *entry, **ptr;
1488

    
1489
    ptr = &pcmcia_sockets;
1490
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1491
        if (entry->socket == socket) {
1492
            *ptr = entry->next;
1493
            qemu_free(entry);
1494
        }
1495
}
1496

    
1497
void pcmcia_info(Monitor *mon)
1498
{
1499
    struct pcmcia_socket_entry_s *iter;
1500

    
1501
    if (!pcmcia_sockets)
1502
        monitor_printf(mon, "No PCMCIA sockets\n");
1503

    
1504
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1505
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1506
                       iter->socket->attached ? iter->socket->card_string :
1507
                       "Empty");
1508
}
1509

    
1510
/***********************************************************/
1511
/* I/O handling */
1512

    
1513
typedef struct IOHandlerRecord {
1514
    int fd;
1515
    IOCanReadHandler *fd_read_poll;
1516
    IOHandler *fd_read;
1517
    IOHandler *fd_write;
1518
    int deleted;
1519
    void *opaque;
1520
    /* temporary data */
1521
    struct pollfd *ufd;
1522
    QLIST_ENTRY(IOHandlerRecord) next;
1523
} IOHandlerRecord;
1524

    
1525
static QLIST_HEAD(, IOHandlerRecord) io_handlers =
1526
    QLIST_HEAD_INITIALIZER(io_handlers);
1527

    
1528

    
1529
/* XXX: fd_read_poll should be suppressed, but an API change is
1530
   necessary in the character devices to suppress fd_can_read(). */
1531
int qemu_set_fd_handler2(int fd,
1532
                         IOCanReadHandler *fd_read_poll,
1533
                         IOHandler *fd_read,
1534
                         IOHandler *fd_write,
1535
                         void *opaque)
1536
{
1537
    IOHandlerRecord *ioh;
1538

    
1539
    if (!fd_read && !fd_write) {
1540
        QLIST_FOREACH(ioh, &io_handlers, next) {
1541
            if (ioh->fd == fd) {
1542
                ioh->deleted = 1;
1543
                break;
1544
            }
1545
        }
1546
    } else {
1547
        QLIST_FOREACH(ioh, &io_handlers, next) {
1548
            if (ioh->fd == fd)
1549
                goto found;
1550
        }
1551
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1552
        QLIST_INSERT_HEAD(&io_handlers, ioh, next);
1553
    found:
1554
        ioh->fd = fd;
1555
        ioh->fd_read_poll = fd_read_poll;
1556
        ioh->fd_read = fd_read;
1557
        ioh->fd_write = fd_write;
1558
        ioh->opaque = opaque;
1559
        ioh->deleted = 0;
1560
    }
1561
    return 0;
1562
}
1563

    
1564
int qemu_set_fd_handler(int fd,
1565
                        IOHandler *fd_read,
1566
                        IOHandler *fd_write,
1567
                        void *opaque)
1568
{
1569
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1570
}
1571

    
1572
#ifdef _WIN32
1573
/***********************************************************/
1574
/* Polling handling */
1575

    
1576
typedef struct PollingEntry {
1577
    PollingFunc *func;
1578
    void *opaque;
1579
    struct PollingEntry *next;
1580
} PollingEntry;
1581

    
1582
static PollingEntry *first_polling_entry;
1583

    
1584
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1585
{
1586
    PollingEntry **ppe, *pe;
1587
    pe = qemu_mallocz(sizeof(PollingEntry));
1588
    pe->func = func;
1589
    pe->opaque = opaque;
1590
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1591
    *ppe = pe;
1592
    return 0;
1593
}
1594

    
1595
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1596
{
1597
    PollingEntry **ppe, *pe;
1598
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1599
        pe = *ppe;
1600
        if (pe->func == func && pe->opaque == opaque) {
1601
            *ppe = pe->next;
1602
            qemu_free(pe);
1603
            break;
1604
        }
1605
    }
1606
}
1607

    
1608
/***********************************************************/
1609
/* Wait objects support */
1610
typedef struct WaitObjects {
1611
    int num;
1612
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1613
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1614
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1615
} WaitObjects;
1616

    
1617
static WaitObjects wait_objects = {0};
1618

    
1619
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1620
{
1621
    WaitObjects *w = &wait_objects;
1622

    
1623
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
1624
        return -1;
1625
    w->events[w->num] = handle;
1626
    w->func[w->num] = func;
1627
    w->opaque[w->num] = opaque;
1628
    w->num++;
1629
    return 0;
1630
}
1631

    
1632
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1633
{
1634
    int i, found;
1635
    WaitObjects *w = &wait_objects;
1636

    
1637
    found = 0;
1638
    for (i = 0; i < w->num; i++) {
1639
        if (w->events[i] == handle)
1640
            found = 1;
1641
        if (found) {
1642
            w->events[i] = w->events[i + 1];
1643
            w->func[i] = w->func[i + 1];
1644
            w->opaque[i] = w->opaque[i + 1];
1645
        }
1646
    }
1647
    if (found)
1648
        w->num--;
1649
}
1650
#endif
1651

    
1652
/***********************************************************/
1653
/* machine registration */
1654

    
1655
static QEMUMachine *first_machine = NULL;
1656
QEMUMachine *current_machine = NULL;
1657

    
1658
int qemu_register_machine(QEMUMachine *m)
1659
{
1660
    QEMUMachine **pm;
1661
    pm = &first_machine;
1662
    while (*pm != NULL)
1663
        pm = &(*pm)->next;
1664
    m->next = NULL;
1665
    *pm = m;
1666
    return 0;
1667
}
1668

    
1669
static QEMUMachine *find_machine(const char *name)
1670
{
1671
    QEMUMachine *m;
1672

    
1673
    for(m = first_machine; m != NULL; m = m->next) {
1674
        if (!strcmp(m->name, name))
1675
            return m;
1676
        if (m->alias && !strcmp(m->alias, name))
1677
            return m;
1678
    }
1679
    return NULL;
1680
}
1681

    
1682
static QEMUMachine *find_default_machine(void)
1683
{
1684
    QEMUMachine *m;
1685

    
1686
    for(m = first_machine; m != NULL; m = m->next) {
1687
        if (m->is_default) {
1688
            return m;
1689
        }
1690
    }
1691
    return NULL;
1692
}
1693

    
1694
/***********************************************************/
1695
/* main execution loop */
1696

    
1697
static void gui_update(void *opaque)
1698
{
1699
    uint64_t interval = GUI_REFRESH_INTERVAL;
1700
    DisplayState *ds = opaque;
1701
    DisplayChangeListener *dcl = ds->listeners;
1702

    
1703
    qemu_flush_coalesced_mmio_buffer();
1704
    dpy_refresh(ds);
1705

    
1706
    while (dcl != NULL) {
1707
        if (dcl->gui_timer_interval &&
1708
            dcl->gui_timer_interval < interval)
1709
            interval = dcl->gui_timer_interval;
1710
        dcl = dcl->next;
1711
    }
1712
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1713
}
1714

    
1715
static void nographic_update(void *opaque)
1716
{
1717
    uint64_t interval = GUI_REFRESH_INTERVAL;
1718

    
1719
    qemu_flush_coalesced_mmio_buffer();
1720
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1721
}
1722

    
1723
struct vm_change_state_entry {
1724
    VMChangeStateHandler *cb;
1725
    void *opaque;
1726
    QLIST_ENTRY (vm_change_state_entry) entries;
1727
};
1728

    
1729
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1730

    
1731
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1732
                                                     void *opaque)
1733
{
1734
    VMChangeStateEntry *e;
1735

    
1736
    e = qemu_mallocz(sizeof (*e));
1737

    
1738
    e->cb = cb;
1739
    e->opaque = opaque;
1740
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1741
    return e;
1742
}
1743

    
1744
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1745
{
1746
    QLIST_REMOVE (e, entries);
1747
    qemu_free (e);
1748
}
1749

    
1750
void vm_state_notify(int running, int reason)
1751
{
1752
    VMChangeStateEntry *e;
1753

    
1754
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1755
        e->cb(e->opaque, running, reason);
1756
    }
1757
}
1758

    
1759
void vm_start(void)
1760
{
1761
    if (!vm_running) {
1762
        cpu_enable_ticks();
1763
        vm_running = 1;
1764
        vm_state_notify(1, 0);
1765
        resume_all_vcpus();
1766
    }
1767
}
1768

    
1769
/* reset/shutdown handler */
1770

    
1771
typedef struct QEMUResetEntry {
1772
    QTAILQ_ENTRY(QEMUResetEntry) entry;
1773
    QEMUResetHandler *func;
1774
    void *opaque;
1775
} QEMUResetEntry;
1776

    
1777
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1778
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1779
static int reset_requested;
1780
static int shutdown_requested;
1781
static int powerdown_requested;
1782
int debug_requested;
1783
static int vmstop_requested;
1784

    
1785
int qemu_shutdown_requested(void)
1786
{
1787
    int r = shutdown_requested;
1788
    shutdown_requested = 0;
1789
    return r;
1790
}
1791

    
1792
int qemu_reset_requested(void)
1793
{
1794
    int r = reset_requested;
1795
    reset_requested = 0;
1796
    return r;
1797
}
1798

    
1799
int qemu_powerdown_requested(void)
1800
{
1801
    int r = powerdown_requested;
1802
    powerdown_requested = 0;
1803
    return r;
1804
}
1805

    
1806
static int qemu_debug_requested(void)
1807
{
1808
    int r = debug_requested;
1809
    debug_requested = 0;
1810
    return r;
1811
}
1812

    
1813
static int qemu_vmstop_requested(void)
1814
{
1815
    int r = vmstop_requested;
1816
    vmstop_requested = 0;
1817
    return r;
1818
}
1819

    
1820
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1821
{
1822
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
1823

    
1824
    re->func = func;
1825
    re->opaque = opaque;
1826
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1827
}
1828

    
1829
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1830
{
1831
    QEMUResetEntry *re;
1832

    
1833
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1834
        if (re->func == func && re->opaque == opaque) {
1835
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1836
            qemu_free(re);
1837
            return;
1838
        }
1839
    }
1840
}
1841

    
1842
void qemu_system_reset(void)
1843
{
1844
    QEMUResetEntry *re, *nre;
1845

    
1846
    /* reset all devices */
1847
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1848
        re->func(re->opaque);
1849
    }
1850
    monitor_protocol_event(QEVENT_RESET, NULL);
1851
    cpu_synchronize_all_post_reset();
1852
}
1853

    
1854
void qemu_system_reset_request(void)
1855
{
1856
    if (no_reboot) {
1857
        shutdown_requested = 1;
1858
    } else {
1859
        reset_requested = 1;
1860
    }
1861
    qemu_notify_event();
1862
}
1863

    
1864
void qemu_system_shutdown_request(void)
1865
{
1866
    shutdown_requested = 1;
1867
    qemu_notify_event();
1868
}
1869

    
1870
void qemu_system_powerdown_request(void)
1871
{
1872
    powerdown_requested = 1;
1873
    qemu_notify_event();
1874
}
1875

    
1876
#ifdef _WIN32
1877
static void host_main_loop_wait(int *timeout)
1878
{
1879
    int ret, ret2, i;
1880
    PollingEntry *pe;
1881

    
1882

    
1883
    /* XXX: need to suppress polling by better using win32 events */
1884
    ret = 0;
1885
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
1886
        ret |= pe->func(pe->opaque);
1887
    }
1888
    if (ret == 0) {
1889
        int err;
1890
        WaitObjects *w = &wait_objects;
1891

    
1892
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
1893
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
1894
            if (w->func[ret - WAIT_OBJECT_0])
1895
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
1896

    
1897
            /* Check for additional signaled events */
1898
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
1899

    
1900
                /* Check if event is signaled */
1901
                ret2 = WaitForSingleObject(w->events[i], 0);
1902
                if(ret2 == WAIT_OBJECT_0) {
1903
                    if (w->func[i])
1904
                        w->func[i](w->opaque[i]);
1905
                } else if (ret2 == WAIT_TIMEOUT) {
1906
                } else {
1907
                    err = GetLastError();
1908
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
1909
                }
1910
            }
1911
        } else if (ret == WAIT_TIMEOUT) {
1912
        } else {
1913
            err = GetLastError();
1914
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
1915
        }
1916
    }
1917

    
1918
    *timeout = 0;
1919
}
1920
#else
1921
static void host_main_loop_wait(int *timeout)
1922
{
1923
}
1924
#endif
1925

    
1926
void main_loop_wait(int nonblocking)
1927
{
1928
    IOHandlerRecord *ioh;
1929
    fd_set rfds, wfds, xfds;
1930
    int ret, nfds;
1931
    struct timeval tv;
1932
    int timeout;
1933

    
1934
    if (nonblocking)
1935
        timeout = 0;
1936
    else {
1937
        timeout = qemu_calculate_timeout();
1938
        qemu_bh_update_timeout(&timeout);
1939
    }
1940

    
1941
    host_main_loop_wait(&timeout);
1942

    
1943
    /* poll any events */
1944
    /* XXX: separate device handlers from system ones */
1945
    nfds = -1;
1946
    FD_ZERO(&rfds);
1947
    FD_ZERO(&wfds);
1948
    FD_ZERO(&xfds);
1949
    QLIST_FOREACH(ioh, &io_handlers, next) {
1950
        if (ioh->deleted)
1951
            continue;
1952
        if (ioh->fd_read &&
1953
            (!ioh->fd_read_poll ||
1954
             ioh->fd_read_poll(ioh->opaque) != 0)) {
1955
            FD_SET(ioh->fd, &rfds);
1956
            if (ioh->fd > nfds)
1957
                nfds = ioh->fd;
1958
        }
1959
        if (ioh->fd_write) {
1960
            FD_SET(ioh->fd, &wfds);
1961
            if (ioh->fd > nfds)
1962
                nfds = ioh->fd;
1963
        }
1964
    }
1965

    
1966
    tv.tv_sec = timeout / 1000;
1967
    tv.tv_usec = (timeout % 1000) * 1000;
1968

    
1969
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1970

    
1971
    qemu_mutex_unlock_iothread();
1972
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1973
    qemu_mutex_lock_iothread();
1974
    if (ret > 0) {
1975
        IOHandlerRecord *pioh;
1976

    
1977
        QLIST_FOREACH_SAFE(ioh, &io_handlers, next, pioh) {
1978
            if (ioh->deleted) {
1979
                QLIST_REMOVE(ioh, next);
1980
                qemu_free(ioh);
1981
                continue;
1982
            }
1983
            if (ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
1984
                ioh->fd_read(ioh->opaque);
1985
            }
1986
            if (ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
1987
                ioh->fd_write(ioh->opaque);
1988
            }
1989
        }
1990
    }
1991

    
1992
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1993

    
1994
    qemu_run_all_timers();
1995

    
1996
    /* Check bottom-halves last in case any of the earlier events triggered
1997
       them.  */
1998
    qemu_bh_poll();
1999

    
2000
}
2001

    
2002
static int vm_can_run(void)
2003
{
2004
    if (powerdown_requested)
2005
        return 0;
2006
    if (reset_requested)
2007
        return 0;
2008
    if (shutdown_requested)
2009
        return 0;
2010
    if (debug_requested)
2011
        return 0;
2012
    return 1;
2013
}
2014

    
2015
qemu_irq qemu_system_powerdown;
2016

    
2017
static void main_loop(void)
2018
{
2019
    int r;
2020

    
2021
#ifdef CONFIG_IOTHREAD
2022
    qemu_system_ready = 1;
2023
    qemu_cond_broadcast(&qemu_system_cond);
2024
#endif
2025

    
2026
    for (;;) {
2027
        do {
2028
            bool nonblocking = false;
2029
#ifdef CONFIG_PROFILER
2030
            int64_t ti;
2031
#endif
2032
#ifndef CONFIG_IOTHREAD
2033
            nonblocking = tcg_cpu_exec();
2034
#endif
2035
#ifdef CONFIG_PROFILER
2036
            ti = profile_getclock();
2037
#endif
2038
            main_loop_wait(nonblocking);
2039
#ifdef CONFIG_PROFILER
2040
            dev_time += profile_getclock() - ti;
2041
#endif
2042
        } while (vm_can_run());
2043

    
2044
        if ((r = qemu_debug_requested())) {
2045
            vm_stop(r);
2046
        }
2047
        if (qemu_shutdown_requested()) {
2048
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2049
            if (no_shutdown) {
2050
                vm_stop(0);
2051
                no_shutdown = 0;
2052
            } else
2053
                break;
2054
        }
2055
        if (qemu_reset_requested()) {
2056
            pause_all_vcpus();
2057
            qemu_system_reset();
2058
            resume_all_vcpus();
2059
        }
2060
        if (qemu_powerdown_requested()) {
2061
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
2062
            qemu_irq_raise(qemu_system_powerdown);
2063
        }
2064
        if ((r = qemu_vmstop_requested())) {
2065
            vm_stop(r);
2066
        }
2067
    }
2068
    pause_all_vcpus();
2069
}
2070

    
2071
static void version(void)
2072
{
2073
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2074
}
2075

    
2076
static void help(int exitcode)
2077
{
2078
    const char *options_help =
2079
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
2080
        opt_help
2081
#define DEFHEADING(text) stringify(text) "\n"
2082
#include "qemu-options.h"
2083
#undef DEF
2084
#undef DEFHEADING
2085
#undef GEN_DOCS
2086
        ;
2087
    version();
2088
    printf("usage: %s [options] [disk_image]\n"
2089
           "\n"
2090
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2091
           "\n"
2092
           "%s\n"
2093
           "During emulation, the following keys are useful:\n"
2094
           "ctrl-alt-f      toggle full screen\n"
2095
           "ctrl-alt-n      switch to virtual console 'n'\n"
2096
           "ctrl-alt        toggle mouse and keyboard grab\n"
2097
           "\n"
2098
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
2099
           "qemu",
2100
           options_help);
2101
    exit(exitcode);
2102
}
2103

    
2104
#define HAS_ARG 0x0001
2105

    
2106
enum {
2107
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
2108
    opt_enum,
2109
#define DEFHEADING(text)
2110
#include "qemu-options.h"
2111
#undef DEF
2112
#undef DEFHEADING
2113
#undef GEN_DOCS
2114
};
2115

    
2116
typedef struct QEMUOption {
2117
    const char *name;
2118
    int flags;
2119
    int index;
2120
    uint32_t arch_mask;
2121
} QEMUOption;
2122

    
2123
static const QEMUOption qemu_options[] = {
2124
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2125
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
2126
    { option, opt_arg, opt_enum, arch_mask },
2127
#define DEFHEADING(text)
2128
#include "qemu-options.h"
2129
#undef DEF
2130
#undef DEFHEADING
2131
#undef GEN_DOCS
2132
    { NULL },
2133
};
2134
static void select_vgahw (const char *p)
2135
{
2136
    const char *opts;
2137

    
2138
    default_vga = 0;
2139
    vga_interface_type = VGA_NONE;
2140
    if (strstart(p, "std", &opts)) {
2141
        vga_interface_type = VGA_STD;
2142
    } else if (strstart(p, "cirrus", &opts)) {
2143
        vga_interface_type = VGA_CIRRUS;
2144
    } else if (strstart(p, "vmware", &opts)) {
2145
        vga_interface_type = VGA_VMWARE;
2146
    } else if (strstart(p, "xenfb", &opts)) {
2147
        vga_interface_type = VGA_XENFB;
2148
    } else if (!strstart(p, "none", &opts)) {
2149
    invalid_vga:
2150
        fprintf(stderr, "Unknown vga type: %s\n", p);
2151
        exit(1);
2152
    }
2153
    while (*opts) {
2154
        const char *nextopt;
2155

    
2156
        if (strstart(opts, ",retrace=", &nextopt)) {
2157
            opts = nextopt;
2158
            if (strstart(opts, "dumb", &nextopt))
2159
                vga_retrace_method = VGA_RETRACE_DUMB;
2160
            else if (strstart(opts, "precise", &nextopt))
2161
                vga_retrace_method = VGA_RETRACE_PRECISE;
2162
            else goto invalid_vga;
2163
        } else goto invalid_vga;
2164
        opts = nextopt;
2165
    }
2166
}
2167

    
2168
static int balloon_parse(const char *arg)
2169
{
2170
    QemuOpts *opts;
2171

    
2172
    if (strcmp(arg, "none") == 0) {
2173
        return 0;
2174
    }
2175

    
2176
    if (!strncmp(arg, "virtio", 6)) {
2177
        if (arg[6] == ',') {
2178
            /* have params -> parse them */
2179
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
2180
            if (!opts)
2181
                return  -1;
2182
        } else {
2183
            /* create empty opts */
2184
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2185
        }
2186
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
2187
        return 0;
2188
    }
2189

    
2190
    return -1;
2191
}
2192

    
2193
#ifdef _WIN32
2194
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
2195
{
2196
    exit(STATUS_CONTROL_C_EXIT);
2197
    return TRUE;
2198
}
2199
#endif
2200

    
2201
#ifndef _WIN32
2202

    
2203
static void termsig_handler(int signal)
2204
{
2205
    qemu_system_shutdown_request();
2206
}
2207

    
2208
static void sigchld_handler(int signal)
2209
{
2210
    waitpid(-1, NULL, WNOHANG);
2211
}
2212

    
2213
static void sighandler_setup(void)
2214
{
2215
    struct sigaction act;
2216

    
2217
    memset(&act, 0, sizeof(act));
2218
    act.sa_handler = termsig_handler;
2219
    sigaction(SIGINT,  &act, NULL);
2220
    sigaction(SIGHUP,  &act, NULL);
2221
    sigaction(SIGTERM, &act, NULL);
2222

    
2223
    act.sa_handler = sigchld_handler;
2224
    act.sa_flags = SA_NOCLDSTOP;
2225
    sigaction(SIGCHLD, &act, NULL);
2226
}
2227

    
2228
#endif
2229

    
2230
#ifdef _WIN32
2231
/* Look for support files in the same directory as the executable.  */
2232
static char *find_datadir(const char *argv0)
2233
{
2234
    char *p;
2235
    char buf[MAX_PATH];
2236
    DWORD len;
2237

    
2238
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
2239
    if (len == 0) {
2240
        return NULL;
2241
    }
2242

    
2243
    buf[len] = 0;
2244
    p = buf + len - 1;
2245
    while (p != buf && *p != '\\')
2246
        p--;
2247
    *p = 0;
2248
    if (access(buf, R_OK) == 0) {
2249
        return qemu_strdup(buf);
2250
    }
2251
    return NULL;
2252
}
2253
#else /* !_WIN32 */
2254

    
2255
/* Find a likely location for support files using the location of the binary.
2256
   For installed binaries this will be "$bindir/../share/qemu".  When
2257
   running from the build tree this will be "$bindir/../pc-bios".  */
2258
#define SHARE_SUFFIX "/share/qemu"
2259
#define BUILD_SUFFIX "/pc-bios"
2260
static char *find_datadir(const char *argv0)
2261
{
2262
    char *dir;
2263
    char *p = NULL;
2264
    char *res;
2265
    char buf[PATH_MAX];
2266
    size_t max_len;
2267

    
2268
#if defined(__linux__)
2269
    {
2270
        int len;
2271
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
2272
        if (len > 0) {
2273
            buf[len] = 0;
2274
            p = buf;
2275
        }
2276
    }
2277
#elif defined(__FreeBSD__)
2278
    {
2279
        int len;
2280
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
2281
        if (len > 0) {
2282
            buf[len] = 0;
2283
            p = buf;
2284
        }
2285
    }
2286
#endif
2287
    /* If we don't have any way of figuring out the actual executable
2288
       location then try argv[0].  */
2289
    if (!p) {
2290
        p = realpath(argv0, buf);
2291
        if (!p) {
2292
            return NULL;
2293
        }
2294
    }
2295
    dir = dirname(p);
2296
    dir = dirname(dir);
2297

    
2298
    max_len = strlen(dir) +
2299
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
2300
    res = qemu_mallocz(max_len);
2301
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
2302
    if (access(res, R_OK)) {
2303
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
2304
        if (access(res, R_OK)) {
2305
            qemu_free(res);
2306
            res = NULL;
2307
        }
2308
    }
2309

    
2310
    return res;
2311
}
2312
#undef SHARE_SUFFIX
2313
#undef BUILD_SUFFIX
2314
#endif
2315

    
2316
char *qemu_find_file(int type, const char *name)
2317
{
2318
    int len;
2319
    const char *subdir;
2320
    char *buf;
2321

    
2322
    /* If name contains path separators then try it as a straight path.  */
2323
    if ((strchr(name, '/') || strchr(name, '\\'))
2324
        && access(name, R_OK) == 0) {
2325
        return qemu_strdup(name);
2326
    }
2327
    switch (type) {
2328
    case QEMU_FILE_TYPE_BIOS:
2329
        subdir = "";
2330
        break;
2331
    case QEMU_FILE_TYPE_KEYMAP:
2332
        subdir = "keymaps/";
2333
        break;
2334
    default:
2335
        abort();
2336
    }
2337
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2338
    buf = qemu_mallocz(len);
2339
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2340
    if (access(buf, R_OK)) {
2341
        qemu_free(buf);
2342
        return NULL;
2343
    }
2344
    return buf;
2345
}
2346

    
2347
static int device_help_func(QemuOpts *opts, void *opaque)
2348
{
2349
    return qdev_device_help(opts);
2350
}
2351

    
2352
static int device_init_func(QemuOpts *opts, void *opaque)
2353
{
2354
    DeviceState *dev;
2355

    
2356
    dev = qdev_device_add(opts);
2357
    if (!dev)
2358
        return -1;
2359
    return 0;
2360
}
2361

    
2362
static int chardev_init_func(QemuOpts *opts, void *opaque)
2363
{
2364
    CharDriverState *chr;
2365

    
2366
    chr = qemu_chr_open_opts(opts, NULL);
2367
    if (!chr)
2368
        return -1;
2369
    return 0;
2370
}
2371

    
2372
static int mon_init_func(QemuOpts *opts, void *opaque)
2373
{
2374
    CharDriverState *chr;
2375
    const char *chardev;
2376
    const char *mode;
2377
    int flags;
2378

    
2379
    mode = qemu_opt_get(opts, "mode");
2380
    if (mode == NULL) {
2381
        mode = "readline";
2382
    }
2383
    if (strcmp(mode, "readline") == 0) {
2384
        flags = MONITOR_USE_READLINE;
2385
    } else if (strcmp(mode, "control") == 0) {
2386
        flags = MONITOR_USE_CONTROL;
2387
    } else {
2388
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2389
        exit(1);
2390
    }
2391

    
2392
    if (qemu_opt_get_bool(opts, "default", 0))
2393
        flags |= MONITOR_IS_DEFAULT;
2394

    
2395
    chardev = qemu_opt_get(opts, "chardev");
2396
    chr = qemu_chr_find(chardev);
2397
    if (chr == NULL) {
2398
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2399
        exit(1);
2400
    }
2401

    
2402
    monitor_init(chr, flags);
2403
    return 0;
2404
}
2405

    
2406
static void monitor_parse(const char *optarg, const char *mode)
2407
{
2408
    static int monitor_device_index = 0;
2409
    QemuOpts *opts;
2410
    const char *p;
2411
    char label[32];
2412
    int def = 0;
2413

    
2414
    if (strstart(optarg, "chardev:", &p)) {
2415
        snprintf(label, sizeof(label), "%s", p);
2416
    } else {
2417
        if (monitor_device_index) {
2418
            snprintf(label, sizeof(label), "monitor%d",
2419
                     monitor_device_index);
2420
        } else {
2421
            snprintf(label, sizeof(label), "monitor");
2422
            def = 1;
2423
        }
2424
        opts = qemu_chr_parse_compat(label, optarg);
2425
        if (!opts) {
2426
            fprintf(stderr, "parse error: %s\n", optarg);
2427
            exit(1);
2428
        }
2429
    }
2430

    
2431
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
2432
    if (!opts) {
2433
        fprintf(stderr, "duplicate chardev: %s\n", label);
2434
        exit(1);
2435
    }
2436
    qemu_opt_set(opts, "mode", mode);
2437
    qemu_opt_set(opts, "chardev", label);
2438
    if (def)
2439
        qemu_opt_set(opts, "default", "on");
2440
    monitor_device_index++;
2441
}
2442

    
2443
struct device_config {
2444
    enum {
2445
        DEV_USB,       /* -usbdevice     */
2446
        DEV_BT,        /* -bt            */
2447
        DEV_SERIAL,    /* -serial        */
2448
        DEV_PARALLEL,  /* -parallel      */
2449
        DEV_VIRTCON,   /* -virtioconsole */
2450
        DEV_DEBUGCON,  /* -debugcon */
2451
    } type;
2452
    const char *cmdline;
2453
    QTAILQ_ENTRY(device_config) next;
2454
};
2455
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
2456

    
2457
static void add_device_config(int type, const char *cmdline)
2458
{
2459
    struct device_config *conf;
2460

    
2461
    conf = qemu_mallocz(sizeof(*conf));
2462
    conf->type = type;
2463
    conf->cmdline = cmdline;
2464
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2465
}
2466

    
2467
static int foreach_device_config(int type, int (*func)(const char *cmdline))
2468
{
2469
    struct device_config *conf;
2470
    int rc;
2471

    
2472
    QTAILQ_FOREACH(conf, &device_configs, next) {
2473
        if (conf->type != type)
2474
            continue;
2475
        rc = func(conf->cmdline);
2476
        if (0 != rc)
2477
            return rc;
2478
    }
2479
    return 0;
2480
}
2481

    
2482
static int serial_parse(const char *devname)
2483
{
2484
    static int index = 0;
2485
    char label[32];
2486

    
2487
    if (strcmp(devname, "none") == 0)
2488
        return 0;
2489
    if (index == MAX_SERIAL_PORTS) {
2490
        fprintf(stderr, "qemu: too many serial ports\n");
2491
        exit(1);
2492
    }
2493
    snprintf(label, sizeof(label), "serial%d", index);
2494
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
2495
    if (!serial_hds[index]) {
2496
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2497
                devname, strerror(errno));
2498
        return -1;
2499
    }
2500
    index++;
2501
    return 0;
2502
}
2503

    
2504
static int parallel_parse(const char *devname)
2505
{
2506
    static int index = 0;
2507
    char label[32];
2508

    
2509
    if (strcmp(devname, "none") == 0)
2510
        return 0;
2511
    if (index == MAX_PARALLEL_PORTS) {
2512
        fprintf(stderr, "qemu: too many parallel ports\n");
2513
        exit(1);
2514
    }
2515
    snprintf(label, sizeof(label), "parallel%d", index);
2516
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
2517
    if (!parallel_hds[index]) {
2518
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2519
                devname, strerror(errno));
2520
        return -1;
2521
    }
2522
    index++;
2523
    return 0;
2524
}
2525

    
2526
static int virtcon_parse(const char *devname)
2527
{
2528
    static int index = 0;
2529
    char label[32];
2530
    QemuOpts *bus_opts, *dev_opts;
2531

    
2532
    if (strcmp(devname, "none") == 0)
2533
        return 0;
2534
    if (index == MAX_VIRTIO_CONSOLES) {
2535
        fprintf(stderr, "qemu: too many virtio consoles\n");
2536
        exit(1);
2537
    }
2538

    
2539
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2540
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
2541

    
2542
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2543
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2544

    
2545
    snprintf(label, sizeof(label), "virtcon%d", index);
2546
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
2547
    if (!virtcon_hds[index]) {
2548
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2549
                devname, strerror(errno));
2550
        return -1;
2551
    }
2552
    qemu_opt_set(dev_opts, "chardev", label);
2553

    
2554
    index++;
2555
    return 0;
2556
}
2557

    
2558
static int debugcon_parse(const char *devname)
2559
{   
2560
    QemuOpts *opts;
2561

    
2562
    if (!qemu_chr_open("debugcon", devname, NULL)) {
2563
        exit(1);
2564
    }
2565
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
2566
    if (!opts) {
2567
        fprintf(stderr, "qemu: already have a debugcon device\n");
2568
        exit(1);
2569
    }
2570
    qemu_opt_set(opts, "driver", "isa-debugcon");
2571
    qemu_opt_set(opts, "chardev", "debugcon");
2572
    return 0;
2573
}
2574

    
2575
static const QEMUOption *lookup_opt(int argc, char **argv,
2576
                                    const char **poptarg, int *poptind)
2577
{
2578
    const QEMUOption *popt;
2579
    int optind = *poptind;
2580
    char *r = argv[optind];
2581
    const char *optarg;
2582

    
2583
    loc_set_cmdline(argv, optind, 1);
2584
    optind++;
2585
    /* Treat --foo the same as -foo.  */
2586
    if (r[1] == '-')
2587
        r++;
2588
    popt = qemu_options;
2589
    for(;;) {
2590
        if (!popt->name) {
2591
            error_report("invalid option");
2592
            exit(1);
2593
        }
2594
        if (!strcmp(popt->name, r + 1))
2595
            break;
2596
        popt++;
2597
    }
2598
    if (popt->flags & HAS_ARG) {
2599
        if (optind >= argc) {
2600
            error_report("requires an argument");
2601
            exit(1);
2602
        }
2603
        optarg = argv[optind++];
2604
        loc_set_cmdline(argv, optind - 2, 2);
2605
    } else {
2606
        optarg = NULL;
2607
    }
2608

    
2609
    *poptarg = optarg;
2610
    *poptind = optind;
2611

    
2612
    return popt;
2613
}
2614

    
2615
int main(int argc, char **argv, char **envp)
2616
{
2617
    const char *gdbstub_dev = NULL;
2618
    uint32_t boot_devices_bitmap = 0;
2619
    int i;
2620
    int snapshot, linux_boot, net_boot;
2621
    const char *icount_option = NULL;
2622
    const char *initrd_filename;
2623
    const char *kernel_filename, *kernel_cmdline;
2624
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2625
    DisplayState *ds;
2626
    DisplayChangeListener *dcl;
2627
    int cyls, heads, secs, translation;
2628
    QemuOpts *hda_opts = NULL, *opts;
2629
    int optind;
2630
    const char *optarg;
2631
    const char *loadvm = NULL;
2632
    QEMUMachine *machine;
2633
    const char *cpu_model;
2634
#ifndef _WIN32
2635
    int fds[2];
2636
#endif
2637
    int tb_size;
2638
    const char *pid_file = NULL;
2639
    const char *incoming = NULL;
2640
#ifndef _WIN32
2641
    int fd = 0;
2642
    struct passwd *pwd = NULL;
2643
    const char *chroot_dir = NULL;
2644
    const char *run_as = NULL;
2645
#endif
2646
    int show_vnc_port = 0;
2647
    int defconfig = 1;
2648

    
2649
    error_set_progname(argv[0]);
2650

    
2651
    init_clocks();
2652

    
2653
    qemu_cache_utils_init(envp);
2654

    
2655
    QLIST_INIT (&vm_change_state_head);
2656
#ifndef _WIN32
2657
    {
2658
        struct sigaction act;
2659
        sigfillset(&act.sa_mask);
2660
        act.sa_flags = 0;
2661
        act.sa_handler = SIG_IGN;
2662
        sigaction(SIGPIPE, &act, NULL);
2663
    }
2664
#else
2665
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
2666
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
2667
       QEMU to run on a single CPU */
2668
    {
2669
        HANDLE h;
2670
        DWORD mask, smask;
2671
        int i;
2672
        h = GetCurrentProcess();
2673
        if (GetProcessAffinityMask(h, &mask, &smask)) {
2674
            for(i = 0; i < 32; i++) {
2675
                if (mask & (1 << i))
2676
                    break;
2677
            }
2678
            if (i != 32) {
2679
                mask = 1 << i;
2680
                SetProcessAffinityMask(h, mask);
2681
            }
2682
        }
2683
    }
2684
#endif
2685

    
2686
    module_call_init(MODULE_INIT_MACHINE);
2687
    machine = find_default_machine();
2688
    cpu_model = NULL;
2689
    initrd_filename = NULL;
2690
    ram_size = 0;
2691
    snapshot = 0;
2692
    kernel_filename = NULL;
2693
    kernel_cmdline = "";
2694
    cyls = heads = secs = 0;
2695
    translation = BIOS_ATA_TRANSLATION_AUTO;
2696

    
2697
    for (i = 0; i < MAX_NODES; i++) {
2698
        node_mem[i] = 0;
2699
        node_cpumask[i] = 0;
2700
    }
2701

    
2702
    nb_numa_nodes = 0;
2703
    nb_nics = 0;
2704

    
2705
    tb_size = 0;
2706
    autostart= 1;
2707

    
2708
    /* first pass of option parsing */
2709
    optind = 1;
2710
    while (optind < argc) {
2711
        if (argv[optind][0] != '-') {
2712
            /* disk image */
2713
            optind++;
2714
            continue;
2715
        } else {
2716
            const QEMUOption *popt;
2717

    
2718
            popt = lookup_opt(argc, argv, &optarg, &optind);
2719
            switch (popt->index) {
2720
            case QEMU_OPTION_nodefconfig:
2721
                defconfig=0;
2722
                break;
2723
            }
2724
        }
2725
    }
2726

    
2727
    if (defconfig) {
2728
        const char *fname;
2729
        FILE *fp;
2730

    
2731
        fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
2732
        fp = fopen(fname, "r");
2733
        if (fp) {
2734
            if (qemu_config_parse(fp, fname) != 0) {
2735
                exit(1);
2736
            }
2737
            fclose(fp);
2738
        }
2739

    
2740
        fname = arch_config_name;
2741
        fp = fopen(fname, "r");
2742
        if (fp) {
2743
            if (qemu_config_parse(fp, fname) != 0) {
2744
                exit(1);
2745
            }
2746
            fclose(fp);
2747
        }
2748
    }
2749
    cpudef_init();
2750

    
2751
    /* second pass of option parsing */
2752
    optind = 1;
2753
    for(;;) {
2754
        if (optind >= argc)
2755
            break;
2756
        if (argv[optind][0] != '-') {
2757
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
2758
        } else {
2759
            const QEMUOption *popt;
2760

    
2761
            popt = lookup_opt(argc, argv, &optarg, &optind);
2762
            if (!(popt->arch_mask & arch_type)) {
2763
                printf("Option %s not supported for this target\n", popt->name);
2764
                exit(1);
2765
            }
2766
            switch(popt->index) {
2767
            case QEMU_OPTION_M:
2768
                machine = find_machine(optarg);
2769
                if (!machine) {
2770
                    QEMUMachine *m;
2771
                    printf("Supported machines are:\n");
2772
                    for(m = first_machine; m != NULL; m = m->next) {
2773
                        if (m->alias)
2774
                            printf("%-10s %s (alias of %s)\n",
2775
                                   m->alias, m->desc, m->name);
2776
                        printf("%-10s %s%s\n",
2777
                               m->name, m->desc,
2778
                               m->is_default ? " (default)" : "");
2779
                    }
2780
                    exit(*optarg != '?');
2781
                }
2782
                break;
2783
            case QEMU_OPTION_cpu:
2784
                /* hw initialization will check this */
2785
                if (*optarg == '?') {
2786
/* XXX: implement xxx_cpu_list for targets that still miss it */
2787
#if defined(cpu_list_id)
2788
                    cpu_list_id(stdout, &fprintf, optarg);
2789
#elif defined(cpu_list)
2790
                    cpu_list(stdout, &fprintf);                /* deprecated */
2791
#endif
2792
                    exit(0);
2793
                } else {
2794
                    cpu_model = optarg;
2795
                }
2796
                break;
2797
            case QEMU_OPTION_initrd:
2798
                initrd_filename = optarg;
2799
                break;
2800
            case QEMU_OPTION_hda:
2801
                if (cyls == 0)
2802
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
2803
                else
2804
                    hda_opts = drive_add(optarg, HD_ALIAS
2805
                             ",cyls=%d,heads=%d,secs=%d%s",
2806
                             0, cyls, heads, secs,
2807
                             translation == BIOS_ATA_TRANSLATION_LBA ?
2808
                                 ",trans=lba" :
2809
                             translation == BIOS_ATA_TRANSLATION_NONE ?
2810
                                 ",trans=none" : "");
2811
                 break;
2812
            case QEMU_OPTION_hdb:
2813
            case QEMU_OPTION_hdc:
2814
            case QEMU_OPTION_hdd:
2815
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
2816
                break;
2817
            case QEMU_OPTION_drive:
2818
                drive_add(NULL, "%s", optarg);
2819
                break;
2820
            case QEMU_OPTION_set:
2821
                if (qemu_set_option(optarg) != 0)
2822
                    exit(1);
2823
                break;
2824
            case QEMU_OPTION_global:
2825
                if (qemu_global_option(optarg) != 0)
2826
                    exit(1);
2827
                break;
2828
            case QEMU_OPTION_mtdblock:
2829
                drive_add(optarg, MTD_ALIAS);
2830
                break;
2831
            case QEMU_OPTION_sd:
2832
                drive_add(optarg, SD_ALIAS);
2833
                break;
2834
            case QEMU_OPTION_pflash:
2835
                drive_add(optarg, PFLASH_ALIAS);
2836
                break;
2837
            case QEMU_OPTION_snapshot:
2838
                snapshot = 1;
2839
                break;
2840
            case QEMU_OPTION_hdachs:
2841
                {
2842
                    const char *p;
2843
                    p = optarg;
2844
                    cyls = strtol(p, (char **)&p, 0);
2845
                    if (cyls < 1 || cyls > 16383)
2846
                        goto chs_fail;
2847
                    if (*p != ',')
2848
                        goto chs_fail;
2849
                    p++;
2850
                    heads = strtol(p, (char **)&p, 0);
2851
                    if (heads < 1 || heads > 16)
2852
                        goto chs_fail;
2853
                    if (*p != ',')
2854
                        goto chs_fail;
2855
                    p++;
2856
                    secs = strtol(p, (char **)&p, 0);
2857
                    if (secs < 1 || secs > 63)
2858
                        goto chs_fail;
2859
                    if (*p == ',') {
2860
                        p++;
2861
                        if (!strcmp(p, "none"))
2862
                            translation = BIOS_ATA_TRANSLATION_NONE;
2863
                        else if (!strcmp(p, "lba"))
2864
                            translation = BIOS_ATA_TRANSLATION_LBA;
2865
                        else if (!strcmp(p, "auto"))
2866
                            translation = BIOS_ATA_TRANSLATION_AUTO;
2867
                        else
2868
                            goto chs_fail;
2869
                    } else if (*p != '\0') {
2870
                    chs_fail:
2871
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
2872
                        exit(1);
2873
                    }
2874
                    if (hda_opts != NULL) {
2875
                        char num[16];
2876
                        snprintf(num, sizeof(num), "%d", cyls);
2877
                        qemu_opt_set(hda_opts, "cyls", num);
2878
                        snprintf(num, sizeof(num), "%d", heads);
2879
                        qemu_opt_set(hda_opts, "heads", num);
2880
                        snprintf(num, sizeof(num), "%d", secs);
2881
                        qemu_opt_set(hda_opts, "secs", num);
2882
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
2883
                            qemu_opt_set(hda_opts, "trans", "lba");
2884
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
2885
                            qemu_opt_set(hda_opts, "trans", "none");
2886
                    }
2887
                }
2888
                break;
2889
            case QEMU_OPTION_numa:
2890
                if (nb_numa_nodes >= MAX_NODES) {
2891
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
2892
                    exit(1);
2893
                }
2894
                numa_add(optarg);
2895
                break;
2896
            case QEMU_OPTION_nographic:
2897
                display_type = DT_NOGRAPHIC;
2898
                break;
2899
#ifdef CONFIG_CURSES
2900
            case QEMU_OPTION_curses:
2901
                display_type = DT_CURSES;
2902
                break;
2903
#endif
2904
            case QEMU_OPTION_portrait:
2905
                graphic_rotate = 1;
2906
                break;
2907
            case QEMU_OPTION_kernel:
2908
                kernel_filename = optarg;
2909
                break;
2910
            case QEMU_OPTION_append:
2911
                kernel_cmdline = optarg;
2912
                break;
2913
            case QEMU_OPTION_cdrom:
2914
                drive_add(optarg, CDROM_ALIAS);
2915
                break;
2916
            case QEMU_OPTION_boot:
2917
                {
2918
                    static const char * const params[] = {
2919
                        "order", "once", "menu", NULL
2920
                    };
2921
                    char buf[sizeof(boot_devices)];
2922
                    char *standard_boot_devices;
2923
                    int legacy = 0;
2924

    
2925
                    if (!strchr(optarg, '=')) {
2926
                        legacy = 1;
2927
                        pstrcpy(buf, sizeof(buf), optarg);
2928
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2929
                        fprintf(stderr,
2930
                                "qemu: unknown boot parameter '%s' in '%s'\n",
2931
                                buf, optarg);
2932
                        exit(1);
2933
                    }
2934

    
2935
                    if (legacy ||
2936
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
2937
                        boot_devices_bitmap = parse_bootdevices(buf);
2938
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
2939
                    }
2940
                    if (!legacy) {
2941
                        if (get_param_value(buf, sizeof(buf),
2942
                                            "once", optarg)) {
2943
                            boot_devices_bitmap |= parse_bootdevices(buf);
2944
                            standard_boot_devices = qemu_strdup(boot_devices);
2945
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
2946
                            qemu_register_reset(restore_boot_devices,
2947
                                                standard_boot_devices);
2948
                        }
2949
                        if (get_param_value(buf, sizeof(buf),
2950
                                            "menu", optarg)) {
2951
                            if (!strcmp(buf, "on")) {
2952
                                boot_menu = 1;
2953
                            } else if (!strcmp(buf, "off")) {
2954
                                boot_menu = 0;
2955
                            } else {
2956
                                fprintf(stderr,
2957
                                        "qemu: invalid option value '%s'\n",
2958
                                        buf);
2959
                                exit(1);
2960
                            }
2961
                        }
2962
                    }
2963
                }
2964
                break;
2965
            case QEMU_OPTION_fda:
2966
            case QEMU_OPTION_fdb:
2967
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
2968
                break;
2969
            case QEMU_OPTION_no_fd_bootchk:
2970
                fd_bootchk = 0;
2971
                break;
2972
            case QEMU_OPTION_netdev:
2973
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
2974
                    exit(1);
2975
                }
2976
                break;
2977
            case QEMU_OPTION_net:
2978
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
2979
                    exit(1);
2980
                }
2981
                break;
2982
#ifdef CONFIG_SLIRP
2983
            case QEMU_OPTION_tftp:
2984
                legacy_tftp_prefix = optarg;
2985
                break;
2986
            case QEMU_OPTION_bootp:
2987
                legacy_bootp_filename = optarg;
2988
                break;
2989
#ifndef _WIN32
2990
            case QEMU_OPTION_smb:
2991
                if (net_slirp_smb(optarg) < 0)
2992
                    exit(1);
2993
                break;
2994
#endif
2995
            case QEMU_OPTION_redir:
2996
                if (net_slirp_redir(optarg) < 0)
2997
                    exit(1);
2998
                break;
2999
#endif
3000
            case QEMU_OPTION_bt:
3001
                add_device_config(DEV_BT, optarg);
3002
                break;
3003
            case QEMU_OPTION_audio_help:
3004
                if (!(audio_available())) {
3005
                    printf("Option %s not supported for this target\n", popt->name);
3006
                    exit(1);
3007
                }
3008
                AUD_help ();
3009
                exit (0);
3010
                break;
3011
            case QEMU_OPTION_soundhw:
3012
                if (!(audio_available())) {
3013
                    printf("Option %s not supported for this target\n", popt->name);
3014
                    exit(1);
3015
                }
3016
                select_soundhw (optarg);
3017
                break;
3018
            case QEMU_OPTION_h:
3019
                help(0);
3020
                break;
3021
            case QEMU_OPTION_version:
3022
                version();
3023
                exit(0);
3024
                break;
3025
            case QEMU_OPTION_m: {
3026
                uint64_t value;
3027
                char *ptr;
3028

    
3029
                value = strtoul(optarg, &ptr, 10);
3030
                switch (*ptr) {
3031
                case 0: case 'M': case 'm':
3032
                    value <<= 20;
3033
                    break;
3034
                case 'G': case 'g':
3035
                    value <<= 30;
3036
                    break;
3037
                default:
3038
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
3039
                    exit(1);
3040
                }
3041

    
3042
                /* On 32-bit hosts, QEMU is limited by virtual address space */
3043
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
3044
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3045
                    exit(1);
3046
                }
3047
                if (value != (uint64_t)(ram_addr_t)value) {
3048
                    fprintf(stderr, "qemu: ram size too large\n");
3049
                    exit(1);
3050
                }
3051
                ram_size = value;
3052
                break;
3053
            }
3054
            case QEMU_OPTION_mempath:
3055
                mem_path = optarg;
3056
                break;
3057
#ifdef MAP_POPULATE
3058
            case QEMU_OPTION_mem_prealloc:
3059
                mem_prealloc = 1;
3060
                break;
3061
#endif
3062
            case QEMU_OPTION_d:
3063
                set_cpu_log(optarg);
3064
                break;
3065
            case QEMU_OPTION_s:
3066
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
3067
                break;
3068
            case QEMU_OPTION_gdb:
3069
                gdbstub_dev = optarg;
3070
                break;
3071
            case QEMU_OPTION_L:
3072
                data_dir = optarg;
3073
                break;
3074
            case QEMU_OPTION_bios:
3075
                bios_name = optarg;
3076
                break;
3077
            case QEMU_OPTION_singlestep:
3078
                singlestep = 1;
3079
                break;
3080
            case QEMU_OPTION_S:
3081
                autostart = 0;
3082
                break;
3083
            case QEMU_OPTION_k:
3084
                keyboard_layout = optarg;
3085
                break;
3086
            case QEMU_OPTION_localtime:
3087
                rtc_utc = 0;
3088
                break;
3089
            case QEMU_OPTION_vga:
3090
                select_vgahw (optarg);
3091
                break;
3092
            case QEMU_OPTION_g:
3093
                {
3094
                    const char *p;
3095
                    int w, h, depth;
3096
                    p = optarg;
3097
                    w = strtol(p, (char **)&p, 10);
3098
                    if (w <= 0) {
3099
                    graphic_error:
3100
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
3101
                        exit(1);
3102
                    }
3103
                    if (*p != 'x')
3104
                        goto graphic_error;
3105
                    p++;
3106
                    h = strtol(p, (char **)&p, 10);
3107
                    if (h <= 0)
3108
                        goto graphic_error;
3109
                    if (*p == 'x') {
3110
                        p++;
3111
                        depth = strtol(p, (char **)&p, 10);
3112
                        if (depth != 8 && depth != 15 && depth != 16 &&
3113
                            depth != 24 && depth != 32)
3114
                            goto graphic_error;
3115
                    } else if (*p == '\0') {
3116
                        depth = graphic_depth;
3117
                    } else {
3118
                        goto graphic_error;
3119
                    }
3120

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

    
3442
    /* If no data_dir is specified then try to find it relative to the
3443
       executable path.  */
3444
    if (!data_dir) {
3445
        data_dir = find_datadir(argv[0]);
3446
    }
3447
    /* If all else fails use the install patch specified when building.  */
3448
    if (!data_dir) {
3449
        data_dir = CONFIG_QEMU_SHAREDIR;
3450
    }
3451

    
3452
    /*
3453
     * Default to max_cpus = smp_cpus, in case the user doesn't
3454
     * specify a max_cpus value.
3455
     */
3456
    if (!max_cpus)
3457
        max_cpus = smp_cpus;
3458

    
3459
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3460
    if (smp_cpus > machine->max_cpus) {
3461
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3462
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3463
                machine->max_cpus);
3464
        exit(1);
3465
    }
3466

    
3467
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
3468
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
3469

    
3470
    if (machine->no_serial) {
3471
        default_serial = 0;
3472
    }
3473
    if (machine->no_parallel) {
3474
        default_parallel = 0;
3475
    }
3476
    if (!machine->use_virtcon) {
3477
        default_virtcon = 0;
3478
    }
3479
    if (machine->no_vga) {
3480
        default_vga = 0;
3481
    }
3482
    if (machine->no_floppy) {
3483
        default_floppy = 0;
3484
    }
3485
    if (machine->no_cdrom) {
3486
        default_cdrom = 0;
3487
    }
3488
    if (machine->no_sdcard) {
3489
        default_sdcard = 0;
3490
    }
3491

    
3492
    if (display_type == DT_NOGRAPHIC) {
3493
        if (default_parallel)
3494
            add_device_config(DEV_PARALLEL, "null");
3495
        if (default_serial && default_monitor) {
3496
            add_device_config(DEV_SERIAL, "mon:stdio");
3497
        } else if (default_virtcon && default_monitor) {
3498
            add_device_config(DEV_VIRTCON, "mon:stdio");
3499
        } else {
3500
            if (default_serial)
3501
                add_device_config(DEV_SERIAL, "stdio");
3502
            if (default_virtcon)
3503
                add_device_config(DEV_VIRTCON, "stdio");
3504
            if (default_monitor)
3505
                monitor_parse("stdio", "readline");
3506
        }
3507
    } else {
3508
        if (default_serial)
3509
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
3510
        if (default_parallel)
3511
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3512
        if (default_monitor)
3513
            monitor_parse("vc:80Cx24C", "readline");
3514
        if (default_virtcon)
3515
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3516
    }
3517
    if (default_vga)
3518
        vga_interface_type = VGA_CIRRUS;
3519

    
3520
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
3521
        exit(1);
3522

    
3523
#ifndef _WIN32
3524
    if (daemonize) {
3525
        pid_t pid;
3526

    
3527
        if (pipe(fds) == -1)
3528
            exit(1);
3529

    
3530
        pid = fork();
3531
        if (pid > 0) {
3532
            uint8_t status;
3533
            ssize_t len;
3534

    
3535
            close(fds[1]);
3536

    
3537
        again:
3538
            len = read(fds[0], &status, 1);
3539
            if (len == -1 && (errno == EINTR))
3540
                goto again;
3541

    
3542
            if (len != 1)
3543
                exit(1);
3544
            else if (status == 1) {
3545
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
3546
                exit(1);
3547
            } else
3548
                exit(0);
3549
        } else if (pid < 0)
3550
            exit(1);
3551

    
3552
        close(fds[0]);
3553
        qemu_set_cloexec(fds[1]);
3554

    
3555
        setsid();
3556

    
3557
        pid = fork();
3558
        if (pid > 0)
3559
            exit(0);
3560
        else if (pid < 0)
3561
            exit(1);
3562

    
3563
        umask(027);
3564

    
3565
        signal(SIGTSTP, SIG_IGN);
3566
        signal(SIGTTOU, SIG_IGN);
3567
        signal(SIGTTIN, SIG_IGN);
3568
    }
3569
#endif
3570

    
3571
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3572
#ifndef _WIN32
3573
        if (daemonize) {
3574
            uint8_t status = 1;
3575
            if (write(fds[1], &status, 1) != 1) {
3576
                perror("daemonize. Writing to pipe\n");
3577
            }
3578
        } else
3579
#endif
3580
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
3581
        exit(1);
3582
    }
3583

    
3584
    if (kvm_enabled()) {
3585
        int ret;
3586

    
3587
        ret = kvm_init(smp_cpus);
3588
        if (ret < 0) {
3589
            fprintf(stderr, "failed to initialize KVM\n");
3590
            exit(1);
3591
        }
3592
    }
3593

    
3594
    if (qemu_init_main_loop()) {
3595
        fprintf(stderr, "qemu_init_main_loop failed\n");
3596
        exit(1);
3597
    }
3598
    linux_boot = (kernel_filename != NULL);
3599

    
3600
    if (!linux_boot && *kernel_cmdline != '\0') {
3601
        fprintf(stderr, "-append only allowed with -kernel option\n");
3602
        exit(1);
3603
    }
3604

    
3605
    if (!linux_boot && initrd_filename != NULL) {
3606
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3607
        exit(1);
3608
    }
3609

    
3610
#ifndef _WIN32
3611
    /* Win32 doesn't support line-buffering and requires size >= 2 */
3612
    setvbuf(stdout, NULL, _IOLBF, 0);
3613
#endif
3614

    
3615
    if (init_timer_alarm() < 0) {
3616
        fprintf(stderr, "could not initialize alarm timer\n");
3617
        exit(1);
3618
    }
3619
    configure_icount(icount_option);
3620

    
3621
#ifdef _WIN32
3622
    socket_init();
3623
#endif
3624

    
3625
    if (net_init_clients() < 0) {
3626
        exit(1);
3627
    }
3628

    
3629
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
3630
    net_set_boot_mask(net_boot);
3631

    
3632
    /* init the bluetooth world */
3633
    if (foreach_device_config(DEV_BT, bt_parse))
3634
        exit(1);
3635

    
3636
    /* init the memory */
3637
    if (ram_size == 0)
3638
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3639

    
3640
    /* init the dynamic translator */
3641
    cpu_exec_init_all(tb_size * 1024 * 1024);
3642

    
3643
    bdrv_init_with_whitelist();
3644

    
3645
    blk_mig_init();
3646

    
3647
    if (default_cdrom) {
3648
        /* we always create the cdrom drive, even if no disk is there */
3649
        drive_add(NULL, CDROM_ALIAS);
3650
    }
3651

    
3652
    if (default_floppy) {
3653
        /* we always create at least one floppy */
3654
        drive_add(NULL, FD_ALIAS, 0);
3655
    }
3656

    
3657
    if (default_sdcard) {
3658
        /* we always create one sd slot, even if no card is in it */
3659
        drive_add(NULL, SD_ALIAS);
3660
    }
3661

    
3662
    /* open the virtual block devices */
3663
    if (snapshot)
3664
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
3665
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
3666
        exit(1);
3667

    
3668
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
3669
                         ram_load, NULL);
3670

    
3671
    if (nb_numa_nodes > 0) {
3672
        int i;
3673

    
3674
        if (nb_numa_nodes > smp_cpus) {
3675
            nb_numa_nodes = smp_cpus;
3676
        }
3677

    
3678
        /* If no memory size if given for any node, assume the default case
3679
         * and distribute the available memory equally across all nodes
3680
         */
3681
        for (i = 0; i < nb_numa_nodes; i++) {
3682
            if (node_mem[i] != 0)
3683
                break;
3684
        }
3685
        if (i == nb_numa_nodes) {
3686
            uint64_t usedmem = 0;
3687

    
3688
            /* On Linux, the each node's border has to be 8MB aligned,
3689
             * the final node gets the rest.
3690
             */
3691
            for (i = 0; i < nb_numa_nodes - 1; i++) {
3692
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3693
                usedmem += node_mem[i];
3694
            }
3695
            node_mem[i] = ram_size - usedmem;
3696
        }
3697

    
3698
        for (i = 0; i < nb_numa_nodes; i++) {
3699
            if (node_cpumask[i] != 0)
3700
                break;
3701
        }
3702
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3703
         * must cope with this anyway, because there are BIOSes out there in
3704
         * real machines which also use this scheme.
3705
         */
3706
        if (i == nb_numa_nodes) {
3707
            for (i = 0; i < smp_cpus; i++) {
3708
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
3709
            }
3710
        }
3711
    }
3712

    
3713
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3714
        exit(1);
3715
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3716
        exit(1);
3717
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3718
        exit(1);
3719
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3720
        exit(1);
3721

    
3722
    module_call_init(MODULE_INIT_DEVICE);
3723

    
3724
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
3725
        exit(0);
3726

    
3727
    if (watchdog) {
3728
        i = select_watchdog(watchdog);
3729
        if (i > 0)
3730
            exit (i == 1 ? 1 : 0);
3731
    }
3732

    
3733
    if (machine->compat_props) {
3734
        qdev_prop_register_global_list(machine->compat_props);
3735
    }
3736
    qemu_add_globals();
3737

    
3738
    machine->init(ram_size, boot_devices,
3739
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3740

    
3741
    cpu_synchronize_all_post_init();
3742

    
3743
#ifndef _WIN32
3744
    /* must be after terminal init, SDL library changes signal handlers */
3745
    sighandler_setup();
3746
#endif
3747

    
3748
    set_numa_modes();
3749

    
3750
    current_machine = machine;
3751

    
3752
    /* init USB devices */
3753
    if (usb_enabled) {
3754
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3755
            exit(1);
3756
    }
3757

    
3758
    /* init generic devices */
3759
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
3760
        exit(1);
3761

    
3762
    net_check_clients();
3763

    
3764
    /* just use the first displaystate for the moment */
3765
    ds = get_displaystate();
3766

    
3767
    if (display_type == DT_DEFAULT) {
3768
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3769
        display_type = DT_SDL;
3770
#else
3771
        display_type = DT_VNC;
3772
        vnc_display = "localhost:0,to=99";
3773
        show_vnc_port = 1;
3774
#endif
3775
    }
3776
        
3777

    
3778
    switch (display_type) {
3779
    case DT_NOGRAPHIC:
3780
        break;
3781
#if defined(CONFIG_CURSES)
3782
    case DT_CURSES:
3783
        curses_display_init(ds, full_screen);
3784
        break;
3785
#endif
3786
#if defined(CONFIG_SDL)
3787
    case DT_SDL:
3788
        sdl_display_init(ds, full_screen, no_frame);
3789
        break;
3790
#elif defined(CONFIG_COCOA)
3791
    case DT_SDL:
3792
        cocoa_display_init(ds, full_screen);
3793
        break;
3794
#endif
3795
    case DT_VNC:
3796
        vnc_display_init(ds);
3797
        if (vnc_display_open(ds, vnc_display) < 0)
3798
            exit(1);
3799

    
3800
        if (show_vnc_port) {
3801
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3802
        }
3803
        break;
3804
    default:
3805
        break;
3806
    }
3807
    dpy_resize(ds);
3808

    
3809
    dcl = ds->listeners;
3810
    while (dcl != NULL) {
3811
        if (dcl->dpy_refresh != NULL) {
3812
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
3813
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
3814
        }
3815
        dcl = dcl->next;
3816
    }
3817

    
3818
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
3819
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
3820
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
3821
    }
3822

    
3823
    text_consoles_set_display(ds);
3824

    
3825
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
3826
        exit(1);
3827

    
3828
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3829
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3830
                gdbstub_dev);
3831
        exit(1);
3832
    }
3833

    
3834
    qdev_machine_creation_done();
3835

    
3836
    if (rom_load_all() != 0) {
3837
        fprintf(stderr, "rom loading failed\n");
3838
        exit(1);
3839
    }
3840

    
3841
    qemu_system_reset();
3842
    if (loadvm) {
3843
        if (load_vmstate(loadvm) < 0) {
3844
            autostart = 0;
3845
        }
3846
    }
3847

    
3848
    if (incoming) {
3849
        qemu_start_incoming_migration(incoming);
3850
    } else if (autostart) {
3851
        vm_start();
3852
    }
3853

    
3854
#ifndef _WIN32
3855
    if (daemonize) {
3856
        uint8_t status = 0;
3857
        ssize_t len;
3858

    
3859
    again1:
3860
        len = write(fds[1], &status, 1);
3861
        if (len == -1 && (errno == EINTR))
3862
            goto again1;
3863

    
3864
        if (len != 1)
3865
            exit(1);
3866

    
3867
        if (chdir("/")) {
3868
            perror("not able to chdir to /");
3869
            exit(1);
3870
        }
3871
        TFR(fd = qemu_open("/dev/null", O_RDWR));
3872
        if (fd == -1)
3873
            exit(1);
3874
    }
3875

    
3876
    if (run_as) {
3877
        pwd = getpwnam(run_as);
3878
        if (!pwd) {
3879
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
3880
            exit(1);
3881
        }
3882
    }
3883

    
3884
    if (chroot_dir) {
3885
        if (chroot(chroot_dir) < 0) {
3886
            fprintf(stderr, "chroot failed\n");
3887
            exit(1);
3888
        }
3889
        if (chdir("/")) {
3890
            perror("not able to chdir to /");
3891
            exit(1);
3892
        }
3893
    }
3894

    
3895
    if (run_as) {
3896
        if (setgid(pwd->pw_gid) < 0) {
3897
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
3898
            exit(1);
3899
        }
3900
        if (setuid(pwd->pw_uid) < 0) {
3901
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
3902
            exit(1);
3903
        }
3904
        if (setuid(0) != -1) {
3905
            fprintf(stderr, "Dropping privileges failed\n");
3906
            exit(1);
3907
        }
3908
    }
3909

    
3910
    if (daemonize) {
3911
        dup2(fd, 0);
3912
        dup2(fd, 1);
3913
        dup2(fd, 2);
3914

    
3915
        close(fd);
3916
    }
3917
#endif
3918

    
3919
    main_loop();
3920
    quit_timers();
3921
    net_cleanup();
3922

    
3923
    return 0;
3924
}