Statistics
| Branch: | Revision:

root / vl.c @ 4fdcac0e

History | View | Annotate | Download (109.3 kB)

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

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

    
36
#ifndef _WIN32
37
#include <libgen.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

    
52
#ifdef CONFIG_BSD
53
#include <sys/stat.h>
54
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
55
#include <sys/sysctl.h>
56
#else
57
#include <util.h>
58
#endif
59
#else
60
#ifdef __linux__
61
#include <malloc.h>
62

    
63
#include <linux/ppdev.h>
64
#include <linux/parport.h>
65
#endif
66

    
67
#ifdef CONFIG_SECCOMP
68
#include "qemu-seccomp.h"
69
#endif
70

    
71
#ifdef __sun__
72
#include <sys/stat.h>
73
#include <sys/ethernet.h>
74
#include <sys/sockio.h>
75
#include <netinet/arp.h>
76
#include <netinet/in_systm.h>
77
#include <netinet/ip.h>
78
#include <netinet/ip_icmp.h> // must come after ip.h
79
#include <netinet/udp.h>
80
#include <netinet/tcp.h>
81
#include <net/if.h>
82
#include <syslog.h>
83
#include <stropts.h>
84
#endif
85
#endif
86
#endif
87

    
88
#if defined(CONFIG_VDE)
89
#include <libvdeplug.h>
90
#endif
91

    
92
#ifdef _WIN32
93
#include <windows.h>
94
#endif
95

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

    
109
#ifdef CONFIG_COCOA
110
#undef main
111
#define main qemu_main
112
#endif /* CONFIG_COCOA */
113

    
114
#include <glib.h>
115

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

    
157
#include "disas.h"
158

    
159
#include "qemu_socket.h"
160

    
161
#include "slirp/libslirp.h"
162

    
163
#include "trace.h"
164
#include "trace/control.h"
165
#include "qemu-queue.h"
166
#include "cpus.h"
167
#include "arch_init.h"
168
#include "osdep.h"
169

    
170
#include "ui/qemu-spice.h"
171

    
172
//#define DEBUG_NET
173
//#define DEBUG_SLIRP
174

    
175
#define DEFAULT_RAM_SIZE 128
176

    
177
#define MAX_VIRTIO_CONSOLES 1
178

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

    
236
typedef struct FWBootEntry FWBootEntry;
237

    
238
struct FWBootEntry {
239
    QTAILQ_ENTRY(FWBootEntry) link;
240
    int32_t bootindex;
241
    DeviceState *dev;
242
    char *suffix;
243
};
244

    
245
static QTAILQ_HEAD(, FWBootEntry) fw_boot_order =
246
    QTAILQ_HEAD_INITIALIZER(fw_boot_order);
247

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

    
252
uint8_t qemu_uuid[16];
253

    
254
static QEMUBootSetHandler *boot_set_handler;
255
static void *boot_set_opaque;
256

    
257
static NotifierList exit_notifiers =
258
    NOTIFIER_LIST_INITIALIZER(exit_notifiers);
259

    
260
static NotifierList machine_init_done_notifiers =
261
    NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
262

    
263
static int tcg_allowed = 1;
264
int kvm_allowed = 0;
265
int xen_allowed = 0;
266
uint32_t xen_domid;
267
enum xen_mode xen_mode = XEN_EMULATE;
268
static int tcg_tb_size;
269

    
270
static int default_serial = 1;
271
static int default_parallel = 1;
272
static int default_virtcon = 1;
273
static int default_monitor = 1;
274
static int default_floppy = 1;
275
static int default_cdrom = 1;
276
static int default_sdcard = 1;
277
static int default_vga = 1;
278

    
279
static struct {
280
    const char *driver;
281
    int *flag;
282
} default_list[] = {
283
    { .driver = "isa-serial",           .flag = &default_serial    },
284
    { .driver = "isa-parallel",         .flag = &default_parallel  },
285
    { .driver = "isa-fdc",              .flag = &default_floppy    },
286
    { .driver = "ide-cd",               .flag = &default_cdrom     },
287
    { .driver = "ide-hd",               .flag = &default_cdrom     },
288
    { .driver = "ide-drive",            .flag = &default_cdrom     },
289
    { .driver = "scsi-cd",              .flag = &default_cdrom     },
290
    { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
291
    { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
292
    { .driver = "virtio-serial",        .flag = &default_virtcon   },
293
    { .driver = "VGA",                  .flag = &default_vga       },
294
    { .driver = "isa-vga",              .flag = &default_vga       },
295
    { .driver = "cirrus-vga",           .flag = &default_vga       },
296
    { .driver = "isa-cirrus-vga",       .flag = &default_vga       },
297
    { .driver = "vmware-svga",          .flag = &default_vga       },
298
    { .driver = "qxl-vga",              .flag = &default_vga       },
299
};
300

    
301
const char *qemu_get_vm_name(void)
302
{
303
    return qemu_name;
304
}
305

    
306
static void res_free(void)
307
{
308
    if (boot_splash_filedata != NULL) {
309
        g_free(boot_splash_filedata);
310
        boot_splash_filedata = NULL;
311
    }
312
}
313

    
314
static int default_driver_check(QemuOpts *opts, void *opaque)
315
{
316
    const char *driver = qemu_opt_get(opts, "driver");
317
    int i;
318

    
319
    if (!driver)
320
        return 0;
321
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
322
        if (strcmp(default_list[i].driver, driver) != 0)
323
            continue;
324
        *(default_list[i].flag) = 0;
325
    }
326
    return 0;
327
}
328

    
329
/***********************************************************/
330
/* QEMU state */
331

    
332
static RunState current_run_state = RUN_STATE_PRELAUNCH;
333

    
334
typedef struct {
335
    RunState from;
336
    RunState to;
337
} RunStateTransition;
338

    
339
static const RunStateTransition runstate_transitions_def[] = {
340
    /*     from      ->     to      */
341
    { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
342

    
343
    { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
344
    { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
345

    
346
    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
347
    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
348

    
349
    { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
350
    { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
351

    
352
    { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
353
    { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
354

    
355
    { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
356
    { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
357

    
358
    { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
359
    { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
360
    { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
361

    
362
    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
363
    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
364

    
365
    { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
366

    
367
    { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
368
    { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
369
    { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
370
    { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
371
    { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
372
    { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
373
    { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
374
    { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
375
    { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
376

    
377
    { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
378

    
379
    { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
380
    { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
381

    
382
    { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
383
    { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
384
    { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
385
    { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
386

    
387
    { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
388
    { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
389

    
390
    { RUN_STATE_MAX, RUN_STATE_MAX },
391
};
392

    
393
static bool runstate_valid_transitions[RUN_STATE_MAX][RUN_STATE_MAX];
394

    
395
bool runstate_check(RunState state)
396
{
397
    return current_run_state == state;
398
}
399

    
400
static void runstate_init(void)
401
{
402
    const RunStateTransition *p;
403

    
404
    memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
405

    
406
    for (p = &runstate_transitions_def[0]; p->from != RUN_STATE_MAX; p++) {
407
        runstate_valid_transitions[p->from][p->to] = true;
408
    }
409
}
410

    
411
/* This function will abort() on invalid state transitions */
412
void runstate_set(RunState new_state)
413
{
414
    assert(new_state < RUN_STATE_MAX);
415

    
416
    if (!runstate_valid_transitions[current_run_state][new_state]) {
417
        fprintf(stderr, "ERROR: invalid runstate transition: '%s' -> '%s'\n",
418
                RunState_lookup[current_run_state],
419
                RunState_lookup[new_state]);
420
        abort();
421
    }
422

    
423
    current_run_state = new_state;
424
}
425

    
426
int runstate_is_running(void)
427
{
428
    return runstate_check(RUN_STATE_RUNNING);
429
}
430

    
431
StatusInfo *qmp_query_status(Error **errp)
432
{
433
    StatusInfo *info = g_malloc0(sizeof(*info));
434

    
435
    info->running = runstate_is_running();
436
    info->singlestep = singlestep;
437
    info->status = current_run_state;
438

    
439
    return info;
440
}
441

    
442
/***********************************************************/
443
/* real time host monotonic timer */
444

    
445
/***********************************************************/
446
/* host time/date access */
447
void qemu_get_timedate(struct tm *tm, int offset)
448
{
449
    time_t ti;
450
    struct tm *ret;
451

    
452
    time(&ti);
453
    ti += offset;
454
    if (rtc_date_offset == -1) {
455
        if (rtc_utc)
456
            ret = gmtime(&ti);
457
        else
458
            ret = localtime(&ti);
459
    } else {
460
        ti -= rtc_date_offset;
461
        ret = gmtime(&ti);
462
    }
463

    
464
    memcpy(tm, ret, sizeof(struct tm));
465
}
466

    
467
int qemu_timedate_diff(struct tm *tm)
468
{
469
    time_t seconds;
470

    
471
    if (rtc_date_offset == -1)
472
        if (rtc_utc)
473
            seconds = mktimegm(tm);
474
        else {
475
            struct tm tmp = *tm;
476
            tmp.tm_isdst = -1; /* use timezone to figure it out */
477
            seconds = mktime(&tmp);
478
        }
479
    else
480
        seconds = mktimegm(tm) + rtc_date_offset;
481

    
482
    return seconds - time(NULL);
483
}
484

    
485
void rtc_change_mon_event(struct tm *tm)
486
{
487
    QObject *data;
488

    
489
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
490
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
491
    qobject_decref(data);
492
}
493

    
494
static void configure_rtc_date_offset(const char *startdate, int legacy)
495
{
496
    time_t rtc_start_date;
497
    struct tm tm;
498

    
499
    if (!strcmp(startdate, "now") && legacy) {
500
        rtc_date_offset = -1;
501
    } else {
502
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
503
                   &tm.tm_year,
504
                   &tm.tm_mon,
505
                   &tm.tm_mday,
506
                   &tm.tm_hour,
507
                   &tm.tm_min,
508
                   &tm.tm_sec) == 6) {
509
            /* OK */
510
        } else if (sscanf(startdate, "%d-%d-%d",
511
                          &tm.tm_year,
512
                          &tm.tm_mon,
513
                          &tm.tm_mday) == 3) {
514
            tm.tm_hour = 0;
515
            tm.tm_min = 0;
516
            tm.tm_sec = 0;
517
        } else {
518
            goto date_fail;
519
        }
520
        tm.tm_year -= 1900;
521
        tm.tm_mon--;
522
        rtc_start_date = mktimegm(&tm);
523
        if (rtc_start_date == -1) {
524
        date_fail:
525
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
526
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
527
            exit(1);
528
        }
529
        rtc_date_offset = time(NULL) - rtc_start_date;
530
    }
531
}
532

    
533
static void configure_rtc(QemuOpts *opts)
534
{
535
    const char *value;
536

    
537
    value = qemu_opt_get(opts, "base");
538
    if (value) {
539
        if (!strcmp(value, "utc")) {
540
            rtc_utc = 1;
541
        } else if (!strcmp(value, "localtime")) {
542
            rtc_utc = 0;
543
        } else {
544
            configure_rtc_date_offset(value, 0);
545
        }
546
    }
547
    value = qemu_opt_get(opts, "clock");
548
    if (value) {
549
        if (!strcmp(value, "host")) {
550
            rtc_clock = host_clock;
551
        } else if (!strcmp(value, "rt")) {
552
            rtc_clock = rt_clock;
553
        } else if (!strcmp(value, "vm")) {
554
            rtc_clock = vm_clock;
555
        } else {
556
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
557
            exit(1);
558
        }
559
    }
560
    value = qemu_opt_get(opts, "driftfix");
561
    if (value) {
562
        if (!strcmp(value, "slew")) {
563
            static GlobalProperty slew_lost_ticks[] = {
564
                {
565
                    .driver   = "mc146818rtc",
566
                    .property = "lost_tick_policy",
567
                    .value    = "slew",
568
                },
569
                { /* end of list */ }
570
            };
571

    
572
            qdev_prop_register_global_list(slew_lost_ticks);
573
        } else if (!strcmp(value, "none")) {
574
            /* discard is default */
575
        } else {
576
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
577
            exit(1);
578
        }
579
    }
580
}
581

    
582
/***********************************************************/
583
/* Bluetooth support */
584
static int nb_hcis;
585
static int cur_hci;
586
static struct HCIInfo *hci_table[MAX_NICS];
587

    
588
static struct bt_vlan_s {
589
    struct bt_scatternet_s net;
590
    int id;
591
    struct bt_vlan_s *next;
592
} *first_bt_vlan;
593

    
594
/* find or alloc a new bluetooth "VLAN" */
595
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
596
{
597
    struct bt_vlan_s **pvlan, *vlan;
598
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
599
        if (vlan->id == id)
600
            return &vlan->net;
601
    }
602
    vlan = g_malloc0(sizeof(struct bt_vlan_s));
603
    vlan->id = id;
604
    pvlan = &first_bt_vlan;
605
    while (*pvlan != NULL)
606
        pvlan = &(*pvlan)->next;
607
    *pvlan = vlan;
608
    return &vlan->net;
609
}
610

    
611
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
612
{
613
}
614

    
615
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
616
{
617
    return -ENOTSUP;
618
}
619

    
620
static struct HCIInfo null_hci = {
621
    .cmd_send = null_hci_send,
622
    .sco_send = null_hci_send,
623
    .acl_send = null_hci_send,
624
    .bdaddr_set = null_hci_addr_set,
625
};
626

    
627
struct HCIInfo *qemu_next_hci(void)
628
{
629
    if (cur_hci == nb_hcis)
630
        return &null_hci;
631

    
632
    return hci_table[cur_hci++];
633
}
634

    
635
static struct HCIInfo *hci_init(const char *str)
636
{
637
    char *endp;
638
    struct bt_scatternet_s *vlan = 0;
639

    
640
    if (!strcmp(str, "null"))
641
        /* null */
642
        return &null_hci;
643
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
644
        /* host[:hciN] */
645
        return bt_host_hci(str[4] ? str + 5 : "hci0");
646
    else if (!strncmp(str, "hci", 3)) {
647
        /* hci[,vlan=n] */
648
        if (str[3]) {
649
            if (!strncmp(str + 3, ",vlan=", 6)) {
650
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
651
                if (*endp)
652
                    vlan = 0;
653
            }
654
        } else
655
            vlan = qemu_find_bt_vlan(0);
656
        if (vlan)
657
           return bt_new_hci(vlan);
658
    }
659

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

    
662
    return 0;
663
}
664

    
665
static int bt_hci_parse(const char *str)
666
{
667
    struct HCIInfo *hci;
668
    bdaddr_t bdaddr;
669

    
670
    if (nb_hcis >= MAX_NICS) {
671
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
672
        return -1;
673
    }
674

    
675
    hci = hci_init(str);
676
    if (!hci)
677
        return -1;
678

    
679
    bdaddr.b[0] = 0x52;
680
    bdaddr.b[1] = 0x54;
681
    bdaddr.b[2] = 0x00;
682
    bdaddr.b[3] = 0x12;
683
    bdaddr.b[4] = 0x34;
684
    bdaddr.b[5] = 0x56 + nb_hcis;
685
    hci->bdaddr_set(hci, bdaddr.b);
686

    
687
    hci_table[nb_hcis++] = hci;
688

    
689
    return 0;
690
}
691

    
692
static void bt_vhci_add(int vlan_id)
693
{
694
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
695

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

    
700
    bt_vhci_init(bt_new_hci(vlan));
701
}
702

    
703
static struct bt_device_s *bt_device_add(const char *opt)
704
{
705
    struct bt_scatternet_s *vlan;
706
    int vlan_id = 0;
707
    char *endp = strstr(opt, ",vlan=");
708
    int len = (endp ? endp - opt : strlen(opt)) + 1;
709
    char devname[10];
710

    
711
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
712

    
713
    if (endp) {
714
        vlan_id = strtol(endp + 6, &endp, 0);
715
        if (*endp) {
716
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
717
            return 0;
718
        }
719
    }
720

    
721
    vlan = qemu_find_bt_vlan(vlan_id);
722

    
723
    if (!vlan->slave)
724
        fprintf(stderr, "qemu: warning: adding a slave device to "
725
                        "an empty scatternet %i\n", vlan_id);
726

    
727
    if (!strcmp(devname, "keyboard"))
728
        return bt_keyboard_init(vlan);
729

    
730
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
731
    return 0;
732
}
733

    
734
static int bt_parse(const char *opt)
735
{
736
    const char *endp, *p;
737
    int vlan;
738

    
739
    if (strstart(opt, "hci", &endp)) {
740
        if (!*endp || *endp == ',') {
741
            if (*endp)
742
                if (!strstart(endp, ",vlan=", 0))
743
                    opt = endp + 1;
744

    
745
            return bt_hci_parse(opt);
746
       }
747
    } else if (strstart(opt, "vhci", &endp)) {
748
        if (!*endp || *endp == ',') {
749
            if (*endp) {
750
                if (strstart(endp, ",vlan=", &p)) {
751
                    vlan = strtol(p, (char **) &endp, 0);
752
                    if (*endp) {
753
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
754
                        return 1;
755
                    }
756
                } else {
757
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
758
                    return 1;
759
                }
760
            } else
761
                vlan = 0;
762

    
763
            bt_vhci_add(vlan);
764
            return 0;
765
        }
766
    } else if (strstart(opt, "device:", &endp))
767
        return !bt_device_add(endp);
768

    
769
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
770
    return 1;
771
}
772

    
773
static int parse_sandbox(QemuOpts *opts, void *opaque)
774
{
775
    /* FIXME: change this to true for 1.3 */
776
    if (qemu_opt_get_bool(opts, "enable", false)) {
777
#ifdef CONFIG_SECCOMP
778
        if (seccomp_start() < 0) {
779
            qerror_report(ERROR_CLASS_GENERIC_ERROR,
780
                          "failed to install seccomp syscall filter in the kernel");
781
            return -1;
782
        }
783
#else
784
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
785
                      "sandboxing request but seccomp is not compiled into this build");
786
        return -1;
787
#endif
788
    }
789

    
790
    return 0;
791
}
792

    
793
/*********QEMU USB setting******/
794
bool usb_enabled(bool default_usb)
795
{
796
    QemuOpts *mach_opts;
797
    mach_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
798
    if (mach_opts) {
799
        return qemu_opt_get_bool(mach_opts, "usb", default_usb);
800
    }
801
    return default_usb;
802
}
803

    
804
#ifndef _WIN32
805
static int parse_add_fd(QemuOpts *opts, void *opaque)
806
{
807
    int fd, dupfd, flags;
808
    int64_t fdset_id;
809
    const char *fd_opaque = NULL;
810

    
811
    fd = qemu_opt_get_number(opts, "fd", -1);
812
    fdset_id = qemu_opt_get_number(opts, "set", -1);
813
    fd_opaque = qemu_opt_get(opts, "opaque");
814

    
815
    if (fd < 0) {
816
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
817
                      "fd option is required and must be non-negative");
818
        return -1;
819
    }
820

    
821
    if (fd <= STDERR_FILENO) {
822
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
823
                      "fd cannot be a standard I/O stream");
824
        return -1;
825
    }
826

    
827
    /*
828
     * All fds inherited across exec() necessarily have FD_CLOEXEC
829
     * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
830
     */
831
    flags = fcntl(fd, F_GETFD);
832
    if (flags == -1 || (flags & FD_CLOEXEC)) {
833
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
834
                      "fd is not valid or already in use");
835
        return -1;
836
    }
837

    
838
    if (fdset_id < 0) {
839
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
840
                      "set option is required and must be non-negative");
841
        return -1;
842
    }
843

    
844
#ifdef F_DUPFD_CLOEXEC
845
    dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
846
#else
847
    dupfd = dup(fd);
848
    if (dupfd != -1) {
849
        qemu_set_cloexec(dupfd);
850
    }
851
#endif
852
    if (dupfd == -1) {
853
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
854
                      "Error duplicating fd: %s", strerror(errno));
855
        return -1;
856
    }
857

    
858
    /* add the duplicate fd, and optionally the opaque string, to the fd set */
859
    monitor_fdset_add_fd(dupfd, true, fdset_id, fd_opaque ? true : false,
860
                         fd_opaque, NULL);
861

    
862
    return 0;
863
}
864

    
865
static int cleanup_add_fd(QemuOpts *opts, void *opaque)
866
{
867
    int fd;
868

    
869
    fd = qemu_opt_get_number(opts, "fd", -1);
870
    close(fd);
871

    
872
    return 0;
873
}
874
#endif
875

    
876
/***********************************************************/
877
/* QEMU Block devices */
878

    
879
#define HD_OPTS "media=disk"
880
#define CDROM_OPTS "media=cdrom"
881
#define FD_OPTS ""
882
#define PFLASH_OPTS ""
883
#define MTD_OPTS ""
884
#define SD_OPTS ""
885

    
886
static int drive_init_func(QemuOpts *opts, void *opaque)
887
{
888
    int *use_scsi = opaque;
889

    
890
    return drive_init(opts, *use_scsi) == NULL;
891
}
892

    
893
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
894
{
895
    if (NULL == qemu_opt_get(opts, "snapshot")) {
896
        qemu_opt_set(opts, "snapshot", "on");
897
    }
898
    return 0;
899
}
900

    
901
static void default_drive(int enable, int snapshot, int use_scsi,
902
                          BlockInterfaceType type, int index,
903
                          const char *optstr)
904
{
905
    QemuOpts *opts;
906

    
907
    if (type == IF_DEFAULT) {
908
        type = use_scsi ? IF_SCSI : IF_IDE;
909
    }
910

    
911
    if (!enable || drive_get_by_index(type, index)) {
912
        return;
913
    }
914

    
915
    opts = drive_add(type, index, NULL, optstr);
916
    if (snapshot) {
917
        drive_enable_snapshot(opts, NULL);
918
    }
919
    if (!drive_init(opts, use_scsi)) {
920
        exit(1);
921
    }
922
}
923

    
924
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
925
{
926
    boot_set_handler = func;
927
    boot_set_opaque = opaque;
928
}
929

    
930
int qemu_boot_set(const char *boot_devices)
931
{
932
    if (!boot_set_handler) {
933
        return -EINVAL;
934
    }
935
    return boot_set_handler(boot_set_opaque, boot_devices);
936
}
937

    
938
static void validate_bootdevices(char *devices)
939
{
940
    /* We just do some generic consistency checks */
941
    const char *p;
942
    int bitmap = 0;
943

    
944
    for (p = devices; *p != '\0'; p++) {
945
        /* Allowed boot devices are:
946
         * a-b: floppy disk drives
947
         * c-f: IDE disk drives
948
         * g-m: machine implementation dependent drives
949
         * n-p: network devices
950
         * It's up to each machine implementation to check if the given boot
951
         * devices match the actual hardware implementation and firmware
952
         * features.
953
         */
954
        if (*p < 'a' || *p > 'p') {
955
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
956
            exit(1);
957
        }
958
        if (bitmap & (1 << (*p - 'a'))) {
959
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
960
            exit(1);
961
        }
962
        bitmap |= 1 << (*p - 'a');
963
    }
964
}
965

    
966
static void restore_boot_devices(void *opaque)
967
{
968
    char *standard_boot_devices = opaque;
969
    static int first = 1;
970

    
971
    /* Restore boot order and remove ourselves after the first boot */
972
    if (first) {
973
        first = 0;
974
        return;
975
    }
976

    
977
    qemu_boot_set(standard_boot_devices);
978

    
979
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
980
    g_free(standard_boot_devices);
981
}
982

    
983
void add_boot_device_path(int32_t bootindex, DeviceState *dev,
984
                          const char *suffix)
985
{
986
    FWBootEntry *node, *i;
987

    
988
    if (bootindex < 0) {
989
        return;
990
    }
991

    
992
    assert(dev != NULL || suffix != NULL);
993

    
994
    node = g_malloc0(sizeof(FWBootEntry));
995
    node->bootindex = bootindex;
996
    node->suffix = suffix ? g_strdup(suffix) : NULL;
997
    node->dev = dev;
998

    
999
    QTAILQ_FOREACH(i, &fw_boot_order, link) {
1000
        if (i->bootindex == bootindex) {
1001
            fprintf(stderr, "Two devices with same boot index %d\n", bootindex);
1002
            exit(1);
1003
        } else if (i->bootindex < bootindex) {
1004
            continue;
1005
        }
1006
        QTAILQ_INSERT_BEFORE(i, node, link);
1007
        return;
1008
    }
1009
    QTAILQ_INSERT_TAIL(&fw_boot_order, node, link);
1010
}
1011

    
1012
/*
1013
 * This function returns null terminated string that consist of new line
1014
 * separated device paths.
1015
 *
1016
 * memory pointed by "size" is assigned total length of the array in bytes
1017
 *
1018
 */
1019
char *get_boot_devices_list(uint32_t *size)
1020
{
1021
    FWBootEntry *i;
1022
    uint32_t total = 0;
1023
    char *list = NULL;
1024

    
1025
    QTAILQ_FOREACH(i, &fw_boot_order, link) {
1026
        char *devpath = NULL, *bootpath;
1027
        int len;
1028

    
1029
        if (i->dev) {
1030
            devpath = qdev_get_fw_dev_path(i->dev);
1031
            assert(devpath);
1032
        }
1033

    
1034
        if (i->suffix && devpath) {
1035
            size_t bootpathlen = strlen(devpath) + strlen(i->suffix) + 1;
1036

    
1037
            bootpath = g_malloc(bootpathlen);
1038
            snprintf(bootpath, bootpathlen, "%s%s", devpath, i->suffix);
1039
            g_free(devpath);
1040
        } else if (devpath) {
1041
            bootpath = devpath;
1042
        } else {
1043
            assert(i->suffix);
1044
            bootpath = g_strdup(i->suffix);
1045
        }
1046

    
1047
        if (total) {
1048
            list[total-1] = '\n';
1049
        }
1050
        len = strlen(bootpath) + 1;
1051
        list = g_realloc(list, total + len);
1052
        memcpy(&list[total], bootpath, len);
1053
        total += len;
1054
        g_free(bootpath);
1055
    }
1056

    
1057
    *size = total;
1058

    
1059
    return list;
1060
}
1061

    
1062
static void numa_add(const char *optarg)
1063
{
1064
    char option[128];
1065
    char *endptr;
1066
    unsigned long long value, endvalue;
1067
    int nodenr;
1068

    
1069
    value = endvalue = 0ULL;
1070

    
1071
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
1072
    if (!strcmp(option, "node")) {
1073
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1074
            nodenr = nb_numa_nodes;
1075
        } else {
1076
            nodenr = strtoull(option, NULL, 10);
1077
        }
1078

    
1079
        if (get_param_value(option, 128, "mem", optarg) == 0) {
1080
            node_mem[nodenr] = 0;
1081
        } else {
1082
            int64_t sval;
1083
            sval = strtosz(option, &endptr);
1084
            if (sval < 0 || *endptr) {
1085
                fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);
1086
                exit(1);
1087
            }
1088
            node_mem[nodenr] = sval;
1089
        }
1090
        if (get_param_value(option, 128, "cpus", optarg) != 0) {
1091
            value = strtoull(option, &endptr, 10);
1092
            if (*endptr == '-') {
1093
                endvalue = strtoull(endptr+1, &endptr, 10);
1094
            } else {
1095
                endvalue = value;
1096
            }
1097

    
1098
            if (!(endvalue < MAX_CPUMASK_BITS)) {
1099
                endvalue = MAX_CPUMASK_BITS - 1;
1100
                fprintf(stderr,
1101
                    "A max of %d CPUs are supported in a guest\n",
1102
                     MAX_CPUMASK_BITS);
1103
            }
1104

    
1105
            bitmap_set(node_cpumask[nodenr], value, endvalue-value+1);
1106
        }
1107
        nb_numa_nodes++;
1108
    }
1109
}
1110

    
1111
static void smp_parse(const char *optarg)
1112
{
1113
    int smp, sockets = 0, threads = 0, cores = 0;
1114
    char *endptr;
1115
    char option[128];
1116

    
1117
    smp = strtoul(optarg, &endptr, 10);
1118
    if (endptr != optarg) {
1119
        if (*endptr == ',') {
1120
            endptr++;
1121
        }
1122
    }
1123
    if (get_param_value(option, 128, "sockets", endptr) != 0)
1124
        sockets = strtoull(option, NULL, 10);
1125
    if (get_param_value(option, 128, "cores", endptr) != 0)
1126
        cores = strtoull(option, NULL, 10);
1127
    if (get_param_value(option, 128, "threads", endptr) != 0)
1128
        threads = strtoull(option, NULL, 10);
1129
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1130
        max_cpus = strtoull(option, NULL, 10);
1131

    
1132
    /* compute missing values, prefer sockets over cores over threads */
1133
    if (smp == 0 || sockets == 0) {
1134
        sockets = sockets > 0 ? sockets : 1;
1135
        cores = cores > 0 ? cores : 1;
1136
        threads = threads > 0 ? threads : 1;
1137
        if (smp == 0) {
1138
            smp = cores * threads * sockets;
1139
        }
1140
    } else {
1141
        if (cores == 0) {
1142
            threads = threads > 0 ? threads : 1;
1143
            cores = smp / (sockets * threads);
1144
        } else {
1145
            threads = smp / (cores * sockets);
1146
        }
1147
    }
1148
    smp_cpus = smp;
1149
    smp_cores = cores > 0 ? cores : 1;
1150
    smp_threads = threads > 0 ? threads : 1;
1151
    if (max_cpus == 0)
1152
        max_cpus = smp_cpus;
1153
}
1154

    
1155
/***********************************************************/
1156
/* USB devices */
1157

    
1158
static int usb_device_add(const char *devname)
1159
{
1160
    const char *p;
1161
    USBDevice *dev = NULL;
1162

    
1163
    if (!usb_enabled(false)) {
1164
        return -1;
1165
    }
1166

    
1167
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1168
    dev = usbdevice_create(devname);
1169
    if (dev)
1170
        goto done;
1171

    
1172
    /* the other ones */
1173
#ifndef CONFIG_LINUX
1174
    /* only the linux version is qdev-ified, usb-bsd still needs this */
1175
    if (strstart(devname, "host:", &p)) {
1176
        dev = usb_host_device_open(usb_bus_find(-1), p);
1177
    } else
1178
#endif
1179
    if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1180
        dev = usb_bt_init(usb_bus_find(-1),
1181
                          devname[2] ? hci_init(p)
1182
                                     : bt_new_hci(qemu_find_bt_vlan(0)));
1183
    } else {
1184
        return -1;
1185
    }
1186
    if (!dev)
1187
        return -1;
1188

    
1189
done:
1190
    return 0;
1191
}
1192

    
1193
static int usb_device_del(const char *devname)
1194
{
1195
    int bus_num, addr;
1196
    const char *p;
1197

    
1198
    if (strstart(devname, "host:", &p))
1199
        return usb_host_device_close(p);
1200

    
1201
    if (!usb_enabled(false)) {
1202
        return -1;
1203
    }
1204

    
1205
    p = strchr(devname, '.');
1206
    if (!p)
1207
        return -1;
1208
    bus_num = strtoul(devname, NULL, 0);
1209
    addr = strtoul(p + 1, NULL, 0);
1210

    
1211
    return usb_device_delete_addr(bus_num, addr);
1212
}
1213

    
1214
static int usb_parse(const char *cmdline)
1215
{
1216
    int r;
1217
    r = usb_device_add(cmdline);
1218
    if (r < 0) {
1219
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1220
    }
1221
    return r;
1222
}
1223

    
1224
void do_usb_add(Monitor *mon, const QDict *qdict)
1225
{
1226
    const char *devname = qdict_get_str(qdict, "devname");
1227
    if (usb_device_add(devname) < 0) {
1228
        error_report("could not add USB device '%s'", devname);
1229
    }
1230
}
1231

    
1232
void do_usb_del(Monitor *mon, const QDict *qdict)
1233
{
1234
    const char *devname = qdict_get_str(qdict, "devname");
1235
    if (usb_device_del(devname) < 0) {
1236
        error_report("could not delete USB device '%s'", devname);
1237
    }
1238
}
1239

    
1240
/***********************************************************/
1241
/* PCMCIA/Cardbus */
1242

    
1243
static struct pcmcia_socket_entry_s {
1244
    PCMCIASocket *socket;
1245
    struct pcmcia_socket_entry_s *next;
1246
} *pcmcia_sockets = 0;
1247

    
1248
void pcmcia_socket_register(PCMCIASocket *socket)
1249
{
1250
    struct pcmcia_socket_entry_s *entry;
1251

    
1252
    entry = g_malloc(sizeof(struct pcmcia_socket_entry_s));
1253
    entry->socket = socket;
1254
    entry->next = pcmcia_sockets;
1255
    pcmcia_sockets = entry;
1256
}
1257

    
1258
void pcmcia_socket_unregister(PCMCIASocket *socket)
1259
{
1260
    struct pcmcia_socket_entry_s *entry, **ptr;
1261

    
1262
    ptr = &pcmcia_sockets;
1263
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1264
        if (entry->socket == socket) {
1265
            *ptr = entry->next;
1266
            g_free(entry);
1267
        }
1268
}
1269

    
1270
void pcmcia_info(Monitor *mon)
1271
{
1272
    struct pcmcia_socket_entry_s *iter;
1273

    
1274
    if (!pcmcia_sockets)
1275
        monitor_printf(mon, "No PCMCIA sockets\n");
1276

    
1277
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1278
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1279
                       iter->socket->attached ? iter->socket->card_string :
1280
                       "Empty");
1281
}
1282

    
1283
/***********************************************************/
1284
/* machine registration */
1285

    
1286
static QEMUMachine *first_machine = NULL;
1287
QEMUMachine *current_machine = NULL;
1288

    
1289
int qemu_register_machine(QEMUMachine *m)
1290
{
1291
    QEMUMachine **pm;
1292
    pm = &first_machine;
1293
    while (*pm != NULL)
1294
        pm = &(*pm)->next;
1295
    m->next = NULL;
1296
    *pm = m;
1297
    return 0;
1298
}
1299

    
1300
static QEMUMachine *find_machine(const char *name)
1301
{
1302
    QEMUMachine *m;
1303

    
1304
    for(m = first_machine; m != NULL; m = m->next) {
1305
        if (!strcmp(m->name, name))
1306
            return m;
1307
        if (m->alias && !strcmp(m->alias, name))
1308
            return m;
1309
    }
1310
    return NULL;
1311
}
1312

    
1313
QEMUMachine *find_default_machine(void)
1314
{
1315
    QEMUMachine *m;
1316

    
1317
    for(m = first_machine; m != NULL; m = m->next) {
1318
        if (m->is_default) {
1319
            return m;
1320
        }
1321
    }
1322
    return NULL;
1323
}
1324

    
1325
MachineInfoList *qmp_query_machines(Error **errp)
1326
{
1327
    MachineInfoList *mach_list = NULL;
1328
    QEMUMachine *m;
1329

    
1330
    for (m = first_machine; m; m = m->next) {
1331
        MachineInfoList *entry;
1332
        MachineInfo *info;
1333

    
1334
        info = g_malloc0(sizeof(*info));
1335
        if (m->is_default) {
1336
            info->has_is_default = true;
1337
            info->is_default = true;
1338
        }
1339

    
1340
        if (m->alias) {
1341
            info->has_alias = true;
1342
            info->alias = g_strdup(m->alias);
1343
        }
1344

    
1345
        info->name = g_strdup(m->name);
1346

    
1347
        entry = g_malloc0(sizeof(*entry));
1348
        entry->value = info;
1349
        entry->next = mach_list;
1350
        mach_list = entry;
1351
    }
1352

    
1353
    return mach_list;
1354
}
1355

    
1356
/***********************************************************/
1357
/* main execution loop */
1358

    
1359
static void gui_update(void *opaque)
1360
{
1361
    uint64_t interval = GUI_REFRESH_INTERVAL;
1362
    DisplayState *ds = opaque;
1363
    DisplayChangeListener *dcl = ds->listeners;
1364

    
1365
    dpy_refresh(ds);
1366

    
1367
    while (dcl != NULL) {
1368
        if (dcl->gui_timer_interval &&
1369
            dcl->gui_timer_interval < interval)
1370
            interval = dcl->gui_timer_interval;
1371
        dcl = dcl->next;
1372
    }
1373
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock_ms(rt_clock));
1374
}
1375

    
1376
struct vm_change_state_entry {
1377
    VMChangeStateHandler *cb;
1378
    void *opaque;
1379
    QLIST_ENTRY (vm_change_state_entry) entries;
1380
};
1381

    
1382
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1383

    
1384
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1385
                                                     void *opaque)
1386
{
1387
    VMChangeStateEntry *e;
1388

    
1389
    e = g_malloc0(sizeof (*e));
1390

    
1391
    e->cb = cb;
1392
    e->opaque = opaque;
1393
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1394
    return e;
1395
}
1396

    
1397
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1398
{
1399
    QLIST_REMOVE (e, entries);
1400
    g_free (e);
1401
}
1402

    
1403
void vm_state_notify(int running, RunState state)
1404
{
1405
    VMChangeStateEntry *e;
1406

    
1407
    trace_vm_state_notify(running, state);
1408

    
1409
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1410
        e->cb(e->opaque, running, state);
1411
    }
1412
}
1413

    
1414
void vm_start(void)
1415
{
1416
    if (!runstate_is_running()) {
1417
        cpu_enable_ticks();
1418
        runstate_set(RUN_STATE_RUNNING);
1419
        vm_state_notify(1, RUN_STATE_RUNNING);
1420
        resume_all_vcpus();
1421
        monitor_protocol_event(QEVENT_RESUME, NULL);
1422
    }
1423
}
1424

    
1425
/* reset/shutdown handler */
1426

    
1427
typedef struct QEMUResetEntry {
1428
    QTAILQ_ENTRY(QEMUResetEntry) entry;
1429
    QEMUResetHandler *func;
1430
    void *opaque;
1431
} QEMUResetEntry;
1432

    
1433
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1434
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1435
static int reset_requested;
1436
static int shutdown_requested, shutdown_signal = -1;
1437
static pid_t shutdown_pid;
1438
static int powerdown_requested;
1439
static int debug_requested;
1440
static int suspend_requested;
1441
static int wakeup_requested;
1442
static NotifierList powerdown_notifiers =
1443
    NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1444
static NotifierList suspend_notifiers =
1445
    NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1446
static NotifierList wakeup_notifiers =
1447
    NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1448
static uint32_t wakeup_reason_mask = ~0;
1449
static RunState vmstop_requested = RUN_STATE_MAX;
1450

    
1451
int qemu_shutdown_requested_get(void)
1452
{
1453
    return shutdown_requested;
1454
}
1455

    
1456
int qemu_reset_requested_get(void)
1457
{
1458
    return reset_requested;
1459
}
1460

    
1461
static int qemu_shutdown_requested(void)
1462
{
1463
    int r = shutdown_requested;
1464
    shutdown_requested = 0;
1465
    return r;
1466
}
1467

    
1468
static void qemu_kill_report(void)
1469
{
1470
    if (!qtest_enabled() && shutdown_signal != -1) {
1471
        fprintf(stderr, "qemu: terminating on signal %d", shutdown_signal);
1472
        if (shutdown_pid == 0) {
1473
            /* This happens for eg ^C at the terminal, so it's worth
1474
             * avoiding printing an odd message in that case.
1475
             */
1476
            fputc('\n', stderr);
1477
        } else {
1478
            fprintf(stderr, " from pid " FMT_pid "\n", shutdown_pid);
1479
        }
1480
        shutdown_signal = -1;
1481
    }
1482
}
1483

    
1484
static int qemu_reset_requested(void)
1485
{
1486
    int r = reset_requested;
1487
    reset_requested = 0;
1488
    return r;
1489
}
1490

    
1491
static int qemu_suspend_requested(void)
1492
{
1493
    int r = suspend_requested;
1494
    suspend_requested = 0;
1495
    return r;
1496
}
1497

    
1498
static int qemu_wakeup_requested(void)
1499
{
1500
    int r = wakeup_requested;
1501
    wakeup_requested = 0;
1502
    return r;
1503
}
1504

    
1505
static int qemu_powerdown_requested(void)
1506
{
1507
    int r = powerdown_requested;
1508
    powerdown_requested = 0;
1509
    return r;
1510
}
1511

    
1512
static int qemu_debug_requested(void)
1513
{
1514
    int r = debug_requested;
1515
    debug_requested = 0;
1516
    return r;
1517
}
1518

    
1519
/* We use RUN_STATE_MAX but any invalid value will do */
1520
static bool qemu_vmstop_requested(RunState *r)
1521
{
1522
    if (vmstop_requested < RUN_STATE_MAX) {
1523
        *r = vmstop_requested;
1524
        vmstop_requested = RUN_STATE_MAX;
1525
        return true;
1526
    }
1527

    
1528
    return false;
1529
}
1530

    
1531
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1532
{
1533
    QEMUResetEntry *re = g_malloc0(sizeof(QEMUResetEntry));
1534

    
1535
    re->func = func;
1536
    re->opaque = opaque;
1537
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1538
}
1539

    
1540
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1541
{
1542
    QEMUResetEntry *re;
1543

    
1544
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1545
        if (re->func == func && re->opaque == opaque) {
1546
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1547
            g_free(re);
1548
            return;
1549
        }
1550
    }
1551
}
1552

    
1553
void qemu_devices_reset(void)
1554
{
1555
    QEMUResetEntry *re, *nre;
1556

    
1557
    /* reset all devices */
1558
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1559
        re->func(re->opaque);
1560
    }
1561
}
1562

    
1563
void qemu_system_reset(bool report)
1564
{
1565
    if (current_machine && current_machine->reset) {
1566
        current_machine->reset();
1567
    } else {
1568
        qemu_devices_reset();
1569
    }
1570
    if (report) {
1571
        monitor_protocol_event(QEVENT_RESET, NULL);
1572
    }
1573
    cpu_synchronize_all_post_reset();
1574
}
1575

    
1576
void qemu_system_reset_request(void)
1577
{
1578
    if (no_reboot) {
1579
        shutdown_requested = 1;
1580
    } else {
1581
        reset_requested = 1;
1582
    }
1583
    cpu_stop_current();
1584
    qemu_notify_event();
1585
}
1586

    
1587
static void qemu_system_suspend(void)
1588
{
1589
    pause_all_vcpus();
1590
    notifier_list_notify(&suspend_notifiers, NULL);
1591
    runstate_set(RUN_STATE_SUSPENDED);
1592
    monitor_protocol_event(QEVENT_SUSPEND, NULL);
1593
}
1594

    
1595
void qemu_system_suspend_request(void)
1596
{
1597
    if (runstate_check(RUN_STATE_SUSPENDED)) {
1598
        return;
1599
    }
1600
    suspend_requested = 1;
1601
    cpu_stop_current();
1602
    qemu_notify_event();
1603
}
1604

    
1605
void qemu_register_suspend_notifier(Notifier *notifier)
1606
{
1607
    notifier_list_add(&suspend_notifiers, notifier);
1608
}
1609

    
1610
void qemu_system_wakeup_request(WakeupReason reason)
1611
{
1612
    if (!runstate_check(RUN_STATE_SUSPENDED)) {
1613
        return;
1614
    }
1615
    if (!(wakeup_reason_mask & (1 << reason))) {
1616
        return;
1617
    }
1618
    runstate_set(RUN_STATE_RUNNING);
1619
    notifier_list_notify(&wakeup_notifiers, &reason);
1620
    wakeup_requested = 1;
1621
    qemu_notify_event();
1622
}
1623

    
1624
void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1625
{
1626
    if (enabled) {
1627
        wakeup_reason_mask |= (1 << reason);
1628
    } else {
1629
        wakeup_reason_mask &= ~(1 << reason);
1630
    }
1631
}
1632

    
1633
void qemu_register_wakeup_notifier(Notifier *notifier)
1634
{
1635
    notifier_list_add(&wakeup_notifiers, notifier);
1636
}
1637

    
1638
void qemu_system_killed(int signal, pid_t pid)
1639
{
1640
    shutdown_signal = signal;
1641
    shutdown_pid = pid;
1642
    no_shutdown = 0;
1643
    qemu_system_shutdown_request();
1644
}
1645

    
1646
void qemu_system_shutdown_request(void)
1647
{
1648
    shutdown_requested = 1;
1649
    qemu_notify_event();
1650
}
1651

    
1652
static void qemu_system_powerdown(void)
1653
{
1654
    monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1655
    notifier_list_notify(&powerdown_notifiers, NULL);
1656
}
1657

    
1658
void qemu_system_powerdown_request(void)
1659
{
1660
    powerdown_requested = 1;
1661
    qemu_notify_event();
1662
}
1663

    
1664
void qemu_register_powerdown_notifier(Notifier *notifier)
1665
{
1666
    notifier_list_add(&powerdown_notifiers, notifier);
1667
}
1668

    
1669
void qemu_system_debug_request(void)
1670
{
1671
    debug_requested = 1;
1672
    qemu_notify_event();
1673
}
1674

    
1675
void qemu_system_vmstop_request(RunState state)
1676
{
1677
    vmstop_requested = state;
1678
    qemu_notify_event();
1679
}
1680

    
1681
static bool main_loop_should_exit(void)
1682
{
1683
    RunState r;
1684
    if (qemu_debug_requested()) {
1685
        vm_stop(RUN_STATE_DEBUG);
1686
    }
1687
    if (qemu_suspend_requested()) {
1688
        qemu_system_suspend();
1689
    }
1690
    if (qemu_shutdown_requested()) {
1691
        qemu_kill_report();
1692
        monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1693
        if (no_shutdown) {
1694
            vm_stop(RUN_STATE_SHUTDOWN);
1695
        } else {
1696
            return true;
1697
        }
1698
    }
1699
    if (qemu_reset_requested()) {
1700
        pause_all_vcpus();
1701
        cpu_synchronize_all_states();
1702
        qemu_system_reset(VMRESET_REPORT);
1703
        resume_all_vcpus();
1704
        if (runstate_check(RUN_STATE_INTERNAL_ERROR) ||
1705
            runstate_check(RUN_STATE_SHUTDOWN)) {
1706
            runstate_set(RUN_STATE_PAUSED);
1707
        }
1708
    }
1709
    if (qemu_wakeup_requested()) {
1710
        pause_all_vcpus();
1711
        cpu_synchronize_all_states();
1712
        qemu_system_reset(VMRESET_SILENT);
1713
        resume_all_vcpus();
1714
        monitor_protocol_event(QEVENT_WAKEUP, NULL);
1715
    }
1716
    if (qemu_powerdown_requested()) {
1717
        qemu_system_powerdown();
1718
    }
1719
    if (qemu_vmstop_requested(&r)) {
1720
        vm_stop(r);
1721
    }
1722
    return false;
1723
}
1724

    
1725
static void main_loop(void)
1726
{
1727
    bool nonblocking;
1728
    int last_io = 0;
1729
#ifdef CONFIG_PROFILER
1730
    int64_t ti;
1731
#endif
1732
    do {
1733
        nonblocking = !kvm_enabled() && last_io > 0;
1734
#ifdef CONFIG_PROFILER
1735
        ti = profile_getclock();
1736
#endif
1737
        last_io = main_loop_wait(nonblocking);
1738
#ifdef CONFIG_PROFILER
1739
        dev_time += profile_getclock() - ti;
1740
#endif
1741
    } while (!main_loop_should_exit());
1742
}
1743

    
1744
static void version(void)
1745
{
1746
    printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
1747
}
1748

    
1749
static void help(int exitcode)
1750
{
1751
    version();
1752
    printf("usage: %s [options] [disk_image]\n\n"
1753
           "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1754
            error_get_progname());
1755

    
1756
#define QEMU_OPTIONS_GENERATE_HELP
1757
#include "qemu-options-wrapper.h"
1758

    
1759
    printf("\nDuring emulation, the following keys are useful:\n"
1760
           "ctrl-alt-f      toggle full screen\n"
1761
           "ctrl-alt-n      switch to virtual console 'n'\n"
1762
           "ctrl-alt        toggle mouse and keyboard grab\n"
1763
           "\n"
1764
           "When using -nographic, press 'ctrl-a h' to get some help.\n");
1765

    
1766
    exit(exitcode);
1767
}
1768

    
1769
#define HAS_ARG 0x0001
1770

    
1771
typedef struct QEMUOption {
1772
    const char *name;
1773
    int flags;
1774
    int index;
1775
    uint32_t arch_mask;
1776
} QEMUOption;
1777

    
1778
static const QEMUOption qemu_options[] = {
1779
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1780
#define QEMU_OPTIONS_GENERATE_OPTIONS
1781
#include "qemu-options-wrapper.h"
1782
    { NULL },
1783
};
1784

    
1785
static bool vga_available(void)
1786
{
1787
    return object_class_by_name("VGA") || object_class_by_name("isa-vga");
1788
}
1789

    
1790
static bool cirrus_vga_available(void)
1791
{
1792
    return object_class_by_name("cirrus-vga")
1793
           || object_class_by_name("isa-cirrus-vga");
1794
}
1795

    
1796
static bool vmware_vga_available(void)
1797
{
1798
    return object_class_by_name("vmware-svga");
1799
}
1800

    
1801
static bool qxl_vga_available(void)
1802
{
1803
    return object_class_by_name("qxl-vga");
1804
}
1805

    
1806
static void select_vgahw (const char *p)
1807
{
1808
    const char *opts;
1809

    
1810
    vga_interface_type = VGA_NONE;
1811
    if (strstart(p, "std", &opts)) {
1812
        if (vga_available()) {
1813
            vga_interface_type = VGA_STD;
1814
        } else {
1815
            fprintf(stderr, "Error: standard VGA not available\n");
1816
            exit(0);
1817
        }
1818
    } else if (strstart(p, "cirrus", &opts)) {
1819
        if (cirrus_vga_available()) {
1820
            vga_interface_type = VGA_CIRRUS;
1821
        } else {
1822
            fprintf(stderr, "Error: Cirrus VGA not available\n");
1823
            exit(0);
1824
        }
1825
    } else if (strstart(p, "vmware", &opts)) {
1826
        if (vmware_vga_available()) {
1827
            vga_interface_type = VGA_VMWARE;
1828
        } else {
1829
            fprintf(stderr, "Error: VMWare SVGA not available\n");
1830
            exit(0);
1831
        }
1832
    } else if (strstart(p, "xenfb", &opts)) {
1833
        vga_interface_type = VGA_XENFB;
1834
    } else if (strstart(p, "qxl", &opts)) {
1835
        if (qxl_vga_available()) {
1836
            vga_interface_type = VGA_QXL;
1837
        } else {
1838
            fprintf(stderr, "Error: QXL VGA not available\n");
1839
            exit(0);
1840
        }
1841
    } else if (!strstart(p, "none", &opts)) {
1842
    invalid_vga:
1843
        fprintf(stderr, "Unknown vga type: %s\n", p);
1844
        exit(1);
1845
    }
1846
    while (*opts) {
1847
        const char *nextopt;
1848

    
1849
        if (strstart(opts, ",retrace=", &nextopt)) {
1850
            opts = nextopt;
1851
            if (strstart(opts, "dumb", &nextopt))
1852
                vga_retrace_method = VGA_RETRACE_DUMB;
1853
            else if (strstart(opts, "precise", &nextopt))
1854
                vga_retrace_method = VGA_RETRACE_PRECISE;
1855
            else goto invalid_vga;
1856
        } else goto invalid_vga;
1857
        opts = nextopt;
1858
    }
1859
}
1860

    
1861
static DisplayType select_display(const char *p)
1862
{
1863
    const char *opts;
1864
    DisplayType display = DT_DEFAULT;
1865

    
1866
    if (strstart(p, "sdl", &opts)) {
1867
#ifdef CONFIG_SDL
1868
        display = DT_SDL;
1869
        while (*opts) {
1870
            const char *nextopt;
1871

    
1872
            if (strstart(opts, ",frame=", &nextopt)) {
1873
                opts = nextopt;
1874
                if (strstart(opts, "on", &nextopt)) {
1875
                    no_frame = 0;
1876
                } else if (strstart(opts, "off", &nextopt)) {
1877
                    no_frame = 1;
1878
                } else {
1879
                    goto invalid_sdl_args;
1880
                }
1881
            } else if (strstart(opts, ",alt_grab=", &nextopt)) {
1882
                opts = nextopt;
1883
                if (strstart(opts, "on", &nextopt)) {
1884
                    alt_grab = 1;
1885
                } else if (strstart(opts, "off", &nextopt)) {
1886
                    alt_grab = 0;
1887
                } else {
1888
                    goto invalid_sdl_args;
1889
                }
1890
            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1891
                opts = nextopt;
1892
                if (strstart(opts, "on", &nextopt)) {
1893
                    ctrl_grab = 1;
1894
                } else if (strstart(opts, "off", &nextopt)) {
1895
                    ctrl_grab = 0;
1896
                } else {
1897
                    goto invalid_sdl_args;
1898
                }
1899
            } else if (strstart(opts, ",window_close=", &nextopt)) {
1900
                opts = nextopt;
1901
                if (strstart(opts, "on", &nextopt)) {
1902
                    no_quit = 0;
1903
                } else if (strstart(opts, "off", &nextopt)) {
1904
                    no_quit = 1;
1905
                } else {
1906
                    goto invalid_sdl_args;
1907
                }
1908
            } else {
1909
            invalid_sdl_args:
1910
                fprintf(stderr, "Invalid SDL option string: %s\n", p);
1911
                exit(1);
1912
            }
1913
            opts = nextopt;
1914
        }
1915
#else
1916
        fprintf(stderr, "SDL support is disabled\n");
1917
        exit(1);
1918
#endif
1919
    } else if (strstart(p, "vnc", &opts)) {
1920
#ifdef CONFIG_VNC
1921
        display_remote++;
1922

    
1923
        if (*opts) {
1924
            const char *nextopt;
1925

    
1926
            if (strstart(opts, "=", &nextopt)) {
1927
                vnc_display = nextopt;
1928
            }
1929
        }
1930
        if (!vnc_display) {
1931
            fprintf(stderr, "VNC requires a display argument vnc=<display>\n");
1932
            exit(1);
1933
        }
1934
#else
1935
        fprintf(stderr, "VNC support is disabled\n");
1936
        exit(1);
1937
#endif
1938
    } else if (strstart(p, "curses", &opts)) {
1939
#ifdef CONFIG_CURSES
1940
        display = DT_CURSES;
1941
#else
1942
        fprintf(stderr, "Curses support is disabled\n");
1943
        exit(1);
1944
#endif
1945
    } else if (strstart(p, "none", &opts)) {
1946
        display = DT_NONE;
1947
    } else {
1948
        fprintf(stderr, "Unknown display type: %s\n", p);
1949
        exit(1);
1950
    }
1951

    
1952
    return display;
1953
}
1954

    
1955
static int balloon_parse(const char *arg)
1956
{
1957
    QemuOpts *opts;
1958

    
1959
    if (strcmp(arg, "none") == 0) {
1960
        return 0;
1961
    }
1962

    
1963
    if (!strncmp(arg, "virtio", 6)) {
1964
        if (arg[6] == ',') {
1965
            /* have params -> parse them */
1966
            opts = qemu_opts_parse(qemu_find_opts("device"), arg+7, 0);
1967
            if (!opts)
1968
                return  -1;
1969
        } else {
1970
            /* create empty opts */
1971
            opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0, NULL);
1972
        }
1973
        qemu_opt_set(opts, "driver", "virtio-balloon");
1974
        return 0;
1975
    }
1976

    
1977
    return -1;
1978
}
1979

    
1980
char *qemu_find_file(int type, const char *name)
1981
{
1982
    int len;
1983
    const char *subdir;
1984
    char *buf;
1985

    
1986
    /* Try the name as a straight path first */
1987
    if (access(name, R_OK) == 0) {
1988
        return g_strdup(name);
1989
    }
1990
    switch (type) {
1991
    case QEMU_FILE_TYPE_BIOS:
1992
        subdir = "";
1993
        break;
1994
    case QEMU_FILE_TYPE_KEYMAP:
1995
        subdir = "keymaps/";
1996
        break;
1997
    default:
1998
        abort();
1999
    }
2000
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
2001
    buf = g_malloc0(len);
2002
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
2003
    if (access(buf, R_OK)) {
2004
        g_free(buf);
2005
        return NULL;
2006
    }
2007
    return buf;
2008
}
2009

    
2010
static int device_help_func(QemuOpts *opts, void *opaque)
2011
{
2012
    return qdev_device_help(opts);
2013
}
2014

    
2015
static int device_init_func(QemuOpts *opts, void *opaque)
2016
{
2017
    DeviceState *dev;
2018

    
2019
    dev = qdev_device_add(opts);
2020
    if (!dev)
2021
        return -1;
2022
    return 0;
2023
}
2024

    
2025
static int chardev_init_func(QemuOpts *opts, void *opaque)
2026
{
2027
    CharDriverState *chr;
2028

    
2029
    chr = qemu_chr_new_from_opts(opts, NULL);
2030
    if (!chr)
2031
        return -1;
2032
    return 0;
2033
}
2034

    
2035
#ifdef CONFIG_VIRTFS
2036
static int fsdev_init_func(QemuOpts *opts, void *opaque)
2037
{
2038
    int ret;
2039
    ret = qemu_fsdev_add(opts);
2040

    
2041
    return ret;
2042
}
2043
#endif
2044

    
2045
static int mon_init_func(QemuOpts *opts, void *opaque)
2046
{
2047
    CharDriverState *chr;
2048
    const char *chardev;
2049
    const char *mode;
2050
    int flags;
2051

    
2052
    mode = qemu_opt_get(opts, "mode");
2053
    if (mode == NULL) {
2054
        mode = "readline";
2055
    }
2056
    if (strcmp(mode, "readline") == 0) {
2057
        flags = MONITOR_USE_READLINE;
2058
    } else if (strcmp(mode, "control") == 0) {
2059
        flags = MONITOR_USE_CONTROL;
2060
    } else {
2061
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2062
        exit(1);
2063
    }
2064

    
2065
    if (qemu_opt_get_bool(opts, "pretty", 0))
2066
        flags |= MONITOR_USE_PRETTY;
2067

    
2068
    if (qemu_opt_get_bool(opts, "default", 0))
2069
        flags |= MONITOR_IS_DEFAULT;
2070

    
2071
    chardev = qemu_opt_get(opts, "chardev");
2072
    chr = qemu_chr_find(chardev);
2073
    if (chr == NULL) {
2074
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2075
        exit(1);
2076
    }
2077

    
2078
    monitor_init(chr, flags);
2079
    return 0;
2080
}
2081

    
2082
static void monitor_parse(const char *optarg, const char *mode)
2083
{
2084
    static int monitor_device_index = 0;
2085
    QemuOpts *opts;
2086
    const char *p;
2087
    char label[32];
2088
    int def = 0;
2089

    
2090
    if (strstart(optarg, "chardev:", &p)) {
2091
        snprintf(label, sizeof(label), "%s", p);
2092
    } else {
2093
        snprintf(label, sizeof(label), "compat_monitor%d",
2094
                 monitor_device_index);
2095
        if (monitor_device_index == 0) {
2096
            def = 1;
2097
        }
2098
        opts = qemu_chr_parse_compat(label, optarg);
2099
        if (!opts) {
2100
            fprintf(stderr, "parse error: %s\n", optarg);
2101
            exit(1);
2102
        }
2103
    }
2104

    
2105
    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, NULL);
2106
    if (!opts) {
2107
        fprintf(stderr, "duplicate chardev: %s\n", label);
2108
        exit(1);
2109
    }
2110
    qemu_opt_set(opts, "mode", mode);
2111
    qemu_opt_set(opts, "chardev", label);
2112
    if (def)
2113
        qemu_opt_set(opts, "default", "on");
2114
    monitor_device_index++;
2115
}
2116

    
2117
struct device_config {
2118
    enum {
2119
        DEV_USB,       /* -usbdevice     */
2120
        DEV_BT,        /* -bt            */
2121
        DEV_SERIAL,    /* -serial        */
2122
        DEV_PARALLEL,  /* -parallel      */
2123
        DEV_VIRTCON,   /* -virtioconsole */
2124
        DEV_DEBUGCON,  /* -debugcon */
2125
        DEV_GDB,       /* -gdb, -s */
2126
    } type;
2127
    const char *cmdline;
2128
    Location loc;
2129
    QTAILQ_ENTRY(device_config) next;
2130
};
2131

    
2132
static QTAILQ_HEAD(, device_config) device_configs =
2133
    QTAILQ_HEAD_INITIALIZER(device_configs);
2134

    
2135
static void add_device_config(int type, const char *cmdline)
2136
{
2137
    struct device_config *conf;
2138

    
2139
    conf = g_malloc0(sizeof(*conf));
2140
    conf->type = type;
2141
    conf->cmdline = cmdline;
2142
    loc_save(&conf->loc);
2143
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2144
}
2145

    
2146
static int foreach_device_config(int type, int (*func)(const char *cmdline))
2147
{
2148
    struct device_config *conf;
2149
    int rc;
2150

    
2151
    QTAILQ_FOREACH(conf, &device_configs, next) {
2152
        if (conf->type != type)
2153
            continue;
2154
        loc_push_restore(&conf->loc);
2155
        rc = func(conf->cmdline);
2156
        loc_pop(&conf->loc);
2157
        if (0 != rc)
2158
            return rc;
2159
    }
2160
    return 0;
2161
}
2162

    
2163
static int serial_parse(const char *devname)
2164
{
2165
    static int index = 0;
2166
    char label[32];
2167

    
2168
    if (strcmp(devname, "none") == 0)
2169
        return 0;
2170
    if (index == MAX_SERIAL_PORTS) {
2171
        fprintf(stderr, "qemu: too many serial ports\n");
2172
        exit(1);
2173
    }
2174
    snprintf(label, sizeof(label), "serial%d", index);
2175
    serial_hds[index] = qemu_chr_new(label, devname, NULL);
2176
    if (!serial_hds[index]) {
2177
        fprintf(stderr, "qemu: could not connect serial device"
2178
                " to character backend '%s'\n", devname);
2179
        return -1;
2180
    }
2181
    index++;
2182
    return 0;
2183
}
2184

    
2185
static int parallel_parse(const char *devname)
2186
{
2187
    static int index = 0;
2188
    char label[32];
2189

    
2190
    if (strcmp(devname, "none") == 0)
2191
        return 0;
2192
    if (index == MAX_PARALLEL_PORTS) {
2193
        fprintf(stderr, "qemu: too many parallel ports\n");
2194
        exit(1);
2195
    }
2196
    snprintf(label, sizeof(label), "parallel%d", index);
2197
    parallel_hds[index] = qemu_chr_new(label, devname, NULL);
2198
    if (!parallel_hds[index]) {
2199
        fprintf(stderr, "qemu: could not connect parallel device"
2200
                " to character backend '%s'\n", devname);
2201
        return -1;
2202
    }
2203
    index++;
2204
    return 0;
2205
}
2206

    
2207
static int virtcon_parse(const char *devname)
2208
{
2209
    QemuOptsList *device = qemu_find_opts("device");
2210
    static int index = 0;
2211
    char label[32];
2212
    QemuOpts *bus_opts, *dev_opts;
2213

    
2214
    if (strcmp(devname, "none") == 0)
2215
        return 0;
2216
    if (index == MAX_VIRTIO_CONSOLES) {
2217
        fprintf(stderr, "qemu: too many virtio consoles\n");
2218
        exit(1);
2219
    }
2220

    
2221
    bus_opts = qemu_opts_create(device, NULL, 0, NULL);
2222
    if (arch_type == QEMU_ARCH_S390X) {
2223
        qemu_opt_set(bus_opts, "driver", "virtio-serial-s390");
2224
    } else {
2225
        qemu_opt_set(bus_opts, "driver", "virtio-serial-pci");
2226
    } 
2227

    
2228
    dev_opts = qemu_opts_create(device, NULL, 0, NULL);
2229
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2230

    
2231
    snprintf(label, sizeof(label), "virtcon%d", index);
2232
    virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
2233
    if (!virtcon_hds[index]) {
2234
        fprintf(stderr, "qemu: could not connect virtio console"
2235
                " to character backend '%s'\n", devname);
2236
        return -1;
2237
    }
2238
    qemu_opt_set(dev_opts, "chardev", label);
2239

    
2240
    index++;
2241
    return 0;
2242
}
2243

    
2244
static int debugcon_parse(const char *devname)
2245
{   
2246
    QemuOpts *opts;
2247

    
2248
    if (!qemu_chr_new("debugcon", devname, NULL)) {
2249
        exit(1);
2250
    }
2251
    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2252
    if (!opts) {
2253
        fprintf(stderr, "qemu: already have a debugcon device\n");
2254
        exit(1);
2255
    }
2256
    qemu_opt_set(opts, "driver", "isa-debugcon");
2257
    qemu_opt_set(opts, "chardev", "debugcon");
2258
    return 0;
2259
}
2260

    
2261
static QEMUMachine *machine_parse(const char *name)
2262
{
2263
    QEMUMachine *m, *machine = NULL;
2264

    
2265
    if (name) {
2266
        machine = find_machine(name);
2267
    }
2268
    if (machine) {
2269
        return machine;
2270
    }
2271
    printf("Supported machines are:\n");
2272
    for (m = first_machine; m != NULL; m = m->next) {
2273
        if (m->alias) {
2274
            printf("%-20s %s (alias of %s)\n", m->alias, m->desc, m->name);
2275
        }
2276
        printf("%-20s %s%s\n", m->name, m->desc,
2277
               m->is_default ? " (default)" : "");
2278
    }
2279
    exit(!name || !is_help_option(name));
2280
}
2281

    
2282
static int tcg_init(void)
2283
{
2284
    tcg_exec_init(tcg_tb_size * 1024 * 1024);
2285
    return 0;
2286
}
2287

    
2288
static struct {
2289
    const char *opt_name;
2290
    const char *name;
2291
    int (*available)(void);
2292
    int (*init)(void);
2293
    int *allowed;
2294
} accel_list[] = {
2295
    { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
2296
    { "xen", "Xen", xen_available, xen_init, &xen_allowed },
2297
    { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
2298
    { "qtest", "QTest", qtest_available, qtest_init, &qtest_allowed },
2299
};
2300

    
2301
static int configure_accelerator(void)
2302
{
2303
    const char *p = NULL;
2304
    char buf[10];
2305
    int i, ret;
2306
    bool accel_initialised = 0;
2307
    bool init_failed = 0;
2308

    
2309
    QemuOptsList *list = qemu_find_opts("machine");
2310
    if (!QTAILQ_EMPTY(&list->head)) {
2311
        p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
2312
    }
2313

    
2314
    if (p == NULL) {
2315
        /* Use the default "accelerator", tcg */
2316
        p = "tcg";
2317
    }
2318

    
2319
    while (!accel_initialised && *p != '\0') {
2320
        if (*p == ':') {
2321
            p++;
2322
        }
2323
        p = get_opt_name(buf, sizeof (buf), p, ':');
2324
        for (i = 0; i < ARRAY_SIZE(accel_list); i++) {
2325
            if (strcmp(accel_list[i].opt_name, buf) == 0) {
2326
                *(accel_list[i].allowed) = 1;
2327
                ret = accel_list[i].init();
2328
                if (ret < 0) {
2329
                    init_failed = 1;
2330
                    if (!accel_list[i].available()) {
2331
                        printf("%s not supported for this target\n",
2332
                               accel_list[i].name);
2333
                    } else {
2334
                        fprintf(stderr, "failed to initialize %s: %s\n",
2335
                                accel_list[i].name,
2336
                                strerror(-ret));
2337
                    }
2338
                    *(accel_list[i].allowed) = 0;
2339
                } else {
2340
                    accel_initialised = 1;
2341
                }
2342
                break;
2343
            }
2344
        }
2345
        if (i == ARRAY_SIZE(accel_list)) {
2346
            fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);
2347
        }
2348
    }
2349

    
2350
    if (!accel_initialised) {
2351
        fprintf(stderr, "No accelerator found!\n");
2352
        exit(1);
2353
    }
2354

    
2355
    if (init_failed) {
2356
        fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
2357
    }
2358

    
2359
    return !accel_initialised;
2360
}
2361

    
2362
void qemu_add_exit_notifier(Notifier *notify)
2363
{
2364
    notifier_list_add(&exit_notifiers, notify);
2365
}
2366

    
2367
void qemu_remove_exit_notifier(Notifier *notify)
2368
{
2369
    notifier_remove(notify);
2370
}
2371

    
2372
static void qemu_run_exit_notifiers(void)
2373
{
2374
    notifier_list_notify(&exit_notifiers, NULL);
2375
}
2376

    
2377
void qemu_add_machine_init_done_notifier(Notifier *notify)
2378
{
2379
    notifier_list_add(&machine_init_done_notifiers, notify);
2380
}
2381

    
2382
static void qemu_run_machine_init_done_notifiers(void)
2383
{
2384
    notifier_list_notify(&machine_init_done_notifiers, NULL);
2385
}
2386

    
2387
static const QEMUOption *lookup_opt(int argc, char **argv,
2388
                                    const char **poptarg, int *poptind)
2389
{
2390
    const QEMUOption *popt;
2391
    int optind = *poptind;
2392
    char *r = argv[optind];
2393
    const char *optarg;
2394

    
2395
    loc_set_cmdline(argv, optind, 1);
2396
    optind++;
2397
    /* Treat --foo the same as -foo.  */
2398
    if (r[1] == '-')
2399
        r++;
2400
    popt = qemu_options;
2401
    for(;;) {
2402
        if (!popt->name) {
2403
            error_report("invalid option");
2404
            exit(1);
2405
        }
2406
        if (!strcmp(popt->name, r + 1))
2407
            break;
2408
        popt++;
2409
    }
2410
    if (popt->flags & HAS_ARG) {
2411
        if (optind >= argc) {
2412
            error_report("requires an argument");
2413
            exit(1);
2414
        }
2415
        optarg = argv[optind++];
2416
        loc_set_cmdline(argv, optind - 2, 2);
2417
    } else {
2418
        optarg = NULL;
2419
    }
2420

    
2421
    *poptarg = optarg;
2422
    *poptind = optind;
2423

    
2424
    return popt;
2425
}
2426

    
2427
static gpointer malloc_and_trace(gsize n_bytes)
2428
{
2429
    void *ptr = malloc(n_bytes);
2430
    trace_g_malloc(n_bytes, ptr);
2431
    return ptr;
2432
}
2433

    
2434
static gpointer realloc_and_trace(gpointer mem, gsize n_bytes)
2435
{
2436
    void *ptr = realloc(mem, n_bytes);
2437
    trace_g_realloc(mem, n_bytes, ptr);
2438
    return ptr;
2439
}
2440

    
2441
static void free_and_trace(gpointer mem)
2442
{
2443
    trace_g_free(mem);
2444
    free(mem);
2445
}
2446

    
2447
int qemu_init_main_loop(void)
2448
{
2449
    return main_loop_init();
2450
}
2451

    
2452
int main(int argc, char **argv, char **envp)
2453
{
2454
    int i;
2455
    int snapshot, linux_boot;
2456
    const char *icount_option = NULL;
2457
    const char *initrd_filename;
2458
    const char *kernel_filename, *kernel_cmdline;
2459
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2460
    DisplayState *ds;
2461
    DisplayChangeListener *dcl;
2462
    int cyls, heads, secs, translation;
2463
    QemuOpts *hda_opts = NULL, *opts, *machine_opts;
2464
    QemuOptsList *olist;
2465
    int optind;
2466
    const char *optarg;
2467
    const char *loadvm = NULL;
2468
    QEMUMachine *machine;
2469
    const char *cpu_model;
2470
    const char *vga_model = "none";
2471
    const char *pid_file = NULL;
2472
    const char *incoming = NULL;
2473
#ifdef CONFIG_VNC
2474
    int show_vnc_port = 0;
2475
#endif
2476
    bool defconfig = true;
2477
    bool userconfig = true;
2478
    const char *log_mask = NULL;
2479
    const char *log_file = NULL;
2480
    GMemVTable mem_trace = {
2481
        .malloc = malloc_and_trace,
2482
        .realloc = realloc_and_trace,
2483
        .free = free_and_trace,
2484
    };
2485
    const char *trace_events = NULL;
2486
    const char *trace_file = NULL;
2487

    
2488
    atexit(qemu_run_exit_notifiers);
2489
    error_set_progname(argv[0]);
2490

    
2491
    g_mem_set_vtable(&mem_trace);
2492
    if (!g_thread_supported()) {
2493
#if !GLIB_CHECK_VERSION(2, 31, 0)
2494
        g_thread_init(NULL);
2495
#else
2496
        fprintf(stderr, "glib threading failed to initialize.\n");
2497
        exit(1);
2498
#endif
2499
    }
2500

    
2501
    module_call_init(MODULE_INIT_QOM);
2502

    
2503
    runstate_init();
2504

    
2505
    init_clocks();
2506
    rtc_clock = host_clock;
2507

    
2508
    qemu_cache_utils_init(envp);
2509

    
2510
    QLIST_INIT (&vm_change_state_head);
2511
    os_setup_early_signal_handling();
2512

    
2513
    module_call_init(MODULE_INIT_MACHINE);
2514
    machine = find_default_machine();
2515
    cpu_model = NULL;
2516
    ram_size = 0;
2517
    snapshot = 0;
2518
    cyls = heads = secs = 0;
2519
    translation = BIOS_ATA_TRANSLATION_AUTO;
2520

    
2521
    for (i = 0; i < MAX_NODES; i++) {
2522
        node_mem[i] = 0;
2523
        node_cpumask[i] = bitmap_new(MAX_CPUMASK_BITS);
2524
    }
2525

    
2526
    nb_numa_nodes = 0;
2527
    nb_nics = 0;
2528

    
2529
    autostart= 1;
2530

    
2531
    /* first pass of option parsing */
2532
    optind = 1;
2533
    while (optind < argc) {
2534
        if (argv[optind][0] != '-') {
2535
            /* disk image */
2536
            optind++;
2537
            continue;
2538
        } else {
2539
            const QEMUOption *popt;
2540

    
2541
            popt = lookup_opt(argc, argv, &optarg, &optind);
2542
            switch (popt->index) {
2543
            case QEMU_OPTION_nodefconfig:
2544
                defconfig = false;
2545
                break;
2546
            case QEMU_OPTION_nouserconfig:
2547
                userconfig = false;
2548
                break;
2549
            }
2550
        }
2551
    }
2552

    
2553
    if (defconfig) {
2554
        int ret;
2555
        ret = qemu_read_default_config_files(userconfig);
2556
        if (ret < 0) {
2557
            exit(1);
2558
        }
2559
    }
2560

    
2561
    /* second pass of option parsing */
2562
    optind = 1;
2563
    for(;;) {
2564
        if (optind >= argc)
2565
            break;
2566
        if (argv[optind][0] != '-') {
2567
            hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2568
        } else {
2569
            const QEMUOption *popt;
2570

    
2571
            popt = lookup_opt(argc, argv, &optarg, &optind);
2572
            if (!(popt->arch_mask & arch_type)) {
2573
                printf("Option %s not supported for this target\n", popt->name);
2574
                exit(1);
2575
            }
2576
            switch(popt->index) {
2577
            case QEMU_OPTION_M:
2578
                machine = machine_parse(optarg);
2579
                break;
2580
            case QEMU_OPTION_cpu:
2581
                /* hw initialization will check this */
2582
                cpu_model = optarg;
2583
                break;
2584
            case QEMU_OPTION_hda:
2585
                {
2586
                    char buf[256];
2587
                    if (cyls == 0)
2588
                        snprintf(buf, sizeof(buf), "%s", HD_OPTS);
2589
                    else
2590
                        snprintf(buf, sizeof(buf),
2591
                                 "%s,cyls=%d,heads=%d,secs=%d%s",
2592
                                 HD_OPTS , cyls, heads, secs,
2593
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
2594
                                 ",trans=lba" :
2595
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
2596
                                 ",trans=none" : "");
2597
                    drive_add(IF_DEFAULT, 0, optarg, buf);
2598
                    break;
2599
                }
2600
            case QEMU_OPTION_hdb:
2601
            case QEMU_OPTION_hdc:
2602
            case QEMU_OPTION_hdd:
2603
                drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
2604
                          HD_OPTS);
2605
                break;
2606
            case QEMU_OPTION_drive:
2607
                if (drive_def(optarg) == NULL) {
2608
                    exit(1);
2609
                }
2610
                break;
2611
            case QEMU_OPTION_set:
2612
                if (qemu_set_option(optarg) != 0)
2613
                    exit(1);
2614
                break;
2615
            case QEMU_OPTION_global:
2616
                if (qemu_global_option(optarg) != 0)
2617
                    exit(1);
2618
                break;
2619
            case QEMU_OPTION_mtdblock:
2620
                drive_add(IF_MTD, -1, optarg, MTD_OPTS);
2621
                break;
2622
            case QEMU_OPTION_sd:
2623
                drive_add(IF_SD, 0, optarg, SD_OPTS);
2624
                break;
2625
            case QEMU_OPTION_pflash:
2626
                drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
2627
                break;
2628
            case QEMU_OPTION_snapshot:
2629
                snapshot = 1;
2630
                break;
2631
            case QEMU_OPTION_hdachs:
2632
                {
2633
                    const char *p;
2634
                    p = optarg;
2635
                    cyls = strtol(p, (char **)&p, 0);
2636
                    if (cyls < 1 || cyls > 16383)
2637
                        goto chs_fail;
2638
                    if (*p != ',')
2639
                        goto chs_fail;
2640
                    p++;
2641
                    heads = strtol(p, (char **)&p, 0);
2642
                    if (heads < 1 || heads > 16)
2643
                        goto chs_fail;
2644
                    if (*p != ',')
2645
                        goto chs_fail;
2646
                    p++;
2647
                    secs = strtol(p, (char **)&p, 0);
2648
                    if (secs < 1 || secs > 63)
2649
                        goto chs_fail;
2650
                    if (*p == ',') {
2651
                        p++;
2652
                        if (!strcmp(p, "none"))
2653
                            translation = BIOS_ATA_TRANSLATION_NONE;
2654
                        else if (!strcmp(p, "lba"))
2655
                            translation = BIOS_ATA_TRANSLATION_LBA;
2656
                        else if (!strcmp(p, "auto"))
2657
                            translation = BIOS_ATA_TRANSLATION_AUTO;
2658
                        else
2659
                            goto chs_fail;
2660
                    } else if (*p != '\0') {
2661
                    chs_fail:
2662
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
2663
                        exit(1);
2664
                    }
2665
                    if (hda_opts != NULL) {
2666
                        char num[16];
2667
                        snprintf(num, sizeof(num), "%d", cyls);
2668
                        qemu_opt_set(hda_opts, "cyls", num);
2669
                        snprintf(num, sizeof(num), "%d", heads);
2670
                        qemu_opt_set(hda_opts, "heads", num);
2671
                        snprintf(num, sizeof(num), "%d", secs);
2672
                        qemu_opt_set(hda_opts, "secs", num);
2673
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
2674
                            qemu_opt_set(hda_opts, "trans", "lba");
2675
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
2676
                            qemu_opt_set(hda_opts, "trans", "none");
2677
                    }
2678
                }
2679
                break;
2680
            case QEMU_OPTION_numa:
2681
                if (nb_numa_nodes >= MAX_NODES) {
2682
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
2683
                    exit(1);
2684
                }
2685
                numa_add(optarg);
2686
                break;
2687
            case QEMU_OPTION_display:
2688
                display_type = select_display(optarg);
2689
                break;
2690
            case QEMU_OPTION_nographic:
2691
                display_type = DT_NOGRAPHIC;
2692
                break;
2693
            case QEMU_OPTION_curses:
2694
#ifdef CONFIG_CURSES
2695
                display_type = DT_CURSES;
2696
#else
2697
                fprintf(stderr, "Curses support is disabled\n");
2698
                exit(1);
2699
#endif
2700
                break;
2701
            case QEMU_OPTION_portrait:
2702
                graphic_rotate = 90;
2703
                break;
2704
            case QEMU_OPTION_rotate:
2705
                graphic_rotate = strtol(optarg, (char **) &optarg, 10);
2706
                if (graphic_rotate != 0 && graphic_rotate != 90 &&
2707
                    graphic_rotate != 180 && graphic_rotate != 270) {
2708
                    fprintf(stderr,
2709
                        "qemu: only 90, 180, 270 deg rotation is available\n");
2710
                    exit(1);
2711
                }
2712
                break;
2713
            case QEMU_OPTION_kernel:
2714
                qemu_opts_set(qemu_find_opts("machine"), 0, "kernel", optarg);
2715
                break;
2716
            case QEMU_OPTION_initrd:
2717
                qemu_opts_set(qemu_find_opts("machine"), 0, "initrd", optarg);
2718
                break;
2719
            case QEMU_OPTION_append:
2720
                qemu_opts_set(qemu_find_opts("machine"), 0, "append", optarg);
2721
                break;
2722
            case QEMU_OPTION_dtb:
2723
                qemu_opts_set(qemu_find_opts("machine"), 0, "dtb", optarg);
2724
                break;
2725
            case QEMU_OPTION_cdrom:
2726
                drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
2727
                break;
2728
            case QEMU_OPTION_boot:
2729
                {
2730
                    static const char * const params[] = {
2731
                        "order", "once", "menu",
2732
                        "splash", "splash-time",
2733
                        "reboot-timeout", NULL
2734
                    };
2735
                    char buf[sizeof(boot_devices)];
2736
                    char *standard_boot_devices;
2737
                    int legacy = 0;
2738

    
2739
                    if (!strchr(optarg, '=')) {
2740
                        legacy = 1;
2741
                        pstrcpy(buf, sizeof(buf), optarg);
2742
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2743
                        fprintf(stderr,
2744
                                "qemu: unknown boot parameter '%s' in '%s'\n",
2745
                                buf, optarg);
2746
                        exit(1);
2747
                    }
2748

    
2749
                    if (legacy ||
2750
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
2751
                        validate_bootdevices(buf);
2752
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
2753
                    }
2754
                    if (!legacy) {
2755
                        if (get_param_value(buf, sizeof(buf),
2756
                                            "once", optarg)) {
2757
                            validate_bootdevices(buf);
2758
                            standard_boot_devices = g_strdup(boot_devices);
2759
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
2760
                            qemu_register_reset(restore_boot_devices,
2761
                                                standard_boot_devices);
2762
                        }
2763
                        if (get_param_value(buf, sizeof(buf),
2764
                                            "menu", optarg)) {
2765
                            if (!strcmp(buf, "on")) {
2766
                                boot_menu = 1;
2767
                            } else if (!strcmp(buf, "off")) {
2768
                                boot_menu = 0;
2769
                            } else {
2770
                                fprintf(stderr,
2771
                                        "qemu: invalid option value '%s'\n",
2772
                                        buf);
2773
                                exit(1);
2774
                            }
2775
                        }
2776
                        qemu_opts_parse(qemu_find_opts("boot-opts"),
2777
                                        optarg, 0);
2778
                    }
2779
                }
2780
                break;
2781
            case QEMU_OPTION_fda:
2782
            case QEMU_OPTION_fdb:
2783
                drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
2784
                          optarg, FD_OPTS);
2785
                break;
2786
            case QEMU_OPTION_no_fd_bootchk:
2787
                fd_bootchk = 0;
2788
                break;
2789
            case QEMU_OPTION_netdev:
2790
                if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
2791
                    exit(1);
2792
                }
2793
                break;
2794
            case QEMU_OPTION_net:
2795
                if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
2796
                    exit(1);
2797
                }
2798
                break;
2799
#ifdef CONFIG_LIBISCSI
2800
            case QEMU_OPTION_iscsi:
2801
                opts = qemu_opts_parse(qemu_find_opts("iscsi"), optarg, 0);
2802
                if (!opts) {
2803
                    exit(1);
2804
                }
2805
                break;
2806
#endif
2807
#ifdef CONFIG_SLIRP
2808
            case QEMU_OPTION_tftp:
2809
                legacy_tftp_prefix = optarg;
2810
                break;
2811
            case QEMU_OPTION_bootp:
2812
                legacy_bootp_filename = optarg;
2813
                break;
2814
            case QEMU_OPTION_redir:
2815
                if (net_slirp_redir(optarg) < 0)
2816
                    exit(1);
2817
                break;
2818
#endif
2819
            case QEMU_OPTION_bt:
2820
                add_device_config(DEV_BT, optarg);
2821
                break;
2822
            case QEMU_OPTION_audio_help:
2823
                if (!(audio_available())) {
2824
                    printf("Option %s not supported for this target\n", popt->name);
2825
                    exit(1);
2826
                }
2827
                AUD_help ();
2828
                exit (0);
2829
                break;
2830
            case QEMU_OPTION_soundhw:
2831
                if (!(audio_available())) {
2832
                    printf("Option %s not supported for this target\n", popt->name);
2833
                    exit(1);
2834
                }
2835
                select_soundhw (optarg);
2836
                break;
2837
            case QEMU_OPTION_h:
2838
                help(0);
2839
                break;
2840
            case QEMU_OPTION_version:
2841
                version();
2842
                exit(0);
2843
                break;
2844
            case QEMU_OPTION_m: {
2845
                int64_t value;
2846
                uint64_t sz;
2847
                char *end;
2848

    
2849
                value = strtosz(optarg, &end);
2850
                if (value < 0 || *end) {
2851
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
2852
                    exit(1);
2853
                }
2854
                sz = QEMU_ALIGN_UP((uint64_t)value, 8192);
2855
                ram_size = sz;
2856
                if (ram_size != sz) {
2857
                    fprintf(stderr, "qemu: ram size too large\n");
2858
                    exit(1);
2859
                }
2860
                break;
2861
            }
2862
            case QEMU_OPTION_mempath:
2863
                mem_path = optarg;
2864
                break;
2865
#ifdef MAP_POPULATE
2866
            case QEMU_OPTION_mem_prealloc:
2867
                mem_prealloc = 1;
2868
                break;
2869
#endif
2870
            case QEMU_OPTION_d:
2871
                log_mask = optarg;
2872
                break;
2873
            case QEMU_OPTION_D:
2874
                log_file = optarg;
2875
                break;
2876
            case QEMU_OPTION_s:
2877
                add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
2878
                break;
2879
            case QEMU_OPTION_gdb:
2880
                add_device_config(DEV_GDB, optarg);
2881
                break;
2882
            case QEMU_OPTION_L:
2883
                data_dir = optarg;
2884
                break;
2885
            case QEMU_OPTION_bios:
2886
                bios_name = optarg;
2887
                break;
2888
            case QEMU_OPTION_singlestep:
2889
                singlestep = 1;
2890
                break;
2891
            case QEMU_OPTION_S:
2892
                autostart = 0;
2893
                break;
2894
            case QEMU_OPTION_k:
2895
                keyboard_layout = optarg;
2896
                break;
2897
            case QEMU_OPTION_localtime:
2898
                rtc_utc = 0;
2899
                break;
2900
            case QEMU_OPTION_vga:
2901
                vga_model = optarg;
2902
                default_vga = 0;
2903
                break;
2904
            case QEMU_OPTION_g:
2905
                {
2906
                    const char *p;
2907
                    int w, h, depth;
2908
                    p = optarg;
2909
                    w = strtol(p, (char **)&p, 10);
2910
                    if (w <= 0) {
2911
                    graphic_error:
2912
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
2913
                        exit(1);
2914
                    }
2915
                    if (*p != 'x')
2916
                        goto graphic_error;
2917
                    p++;
2918
                    h = strtol(p, (char **)&p, 10);
2919
                    if (h <= 0)
2920
                        goto graphic_error;
2921
                    if (*p == 'x') {
2922
                        p++;
2923
                        depth = strtol(p, (char **)&p, 10);
2924
                        if (depth != 8 && depth != 15 && depth != 16 &&
2925
                            depth != 24 && depth != 32)
2926
                            goto graphic_error;
2927
                    } else if (*p == '\0') {
2928
                        depth = graphic_depth;
2929
                    } else {
2930
                        goto graphic_error;
2931
                    }
2932

    
2933
                    graphic_width = w;
2934
                    graphic_height = h;
2935
                    graphic_depth = depth;
2936
                }
2937
                break;
2938
            case QEMU_OPTION_echr:
2939
                {
2940
                    char *r;
2941
                    term_escape_char = strtol(optarg, &r, 0);
2942
                    if (r == optarg)
2943
                        printf("Bad argument to echr\n");
2944
                    break;
2945
                }
2946
            case QEMU_OPTION_monitor:
2947
                monitor_parse(optarg, "readline");
2948
                default_monitor = 0;
2949
                break;
2950
            case QEMU_OPTION_qmp:
2951
                monitor_parse(optarg, "control");
2952
                default_monitor = 0;
2953
                break;
2954
            case QEMU_OPTION_mon:
2955
                opts = qemu_opts_parse(qemu_find_opts("mon"), optarg, 1);
2956
                if (!opts) {
2957
                    exit(1);
2958
                }
2959
                default_monitor = 0;
2960
                break;
2961
            case QEMU_OPTION_chardev:
2962
                opts = qemu_opts_parse(qemu_find_opts("chardev"), optarg, 1);
2963
                if (!opts) {
2964
                    exit(1);
2965
                }
2966
                break;
2967
            case QEMU_OPTION_fsdev:
2968
                olist = qemu_find_opts("fsdev");
2969
                if (!olist) {
2970
                    fprintf(stderr, "fsdev is not supported by this qemu build.\n");
2971
                    exit(1);
2972
                }
2973
                opts = qemu_opts_parse(olist, optarg, 1);
2974
                if (!opts) {
2975
                    fprintf(stderr, "parse error: %s\n", optarg);
2976
                    exit(1);
2977
                }
2978
                break;
2979
            case QEMU_OPTION_virtfs: {
2980
                QemuOpts *fsdev;
2981
                QemuOpts *device;
2982
                const char *writeout, *sock_fd, *socket;
2983

    
2984
                olist = qemu_find_opts("virtfs");
2985
                if (!olist) {
2986
                    fprintf(stderr, "virtfs is not supported by this qemu build.\n");
2987
                    exit(1);
2988
                }
2989
                opts = qemu_opts_parse(olist, optarg, 1);
2990
                if (!opts) {
2991
                    fprintf(stderr, "parse error: %s\n", optarg);
2992
                    exit(1);
2993
                }
2994

    
2995
                if (qemu_opt_get(opts, "fsdriver") == NULL ||
2996
                    qemu_opt_get(opts, "mount_tag") == NULL) {
2997
                    fprintf(stderr, "Usage: -virtfs fsdriver,mount_tag=tag.\n");
2998
                    exit(1);
2999
                }
3000
                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3001
                                         qemu_opt_get(opts, "mount_tag"),
3002
                                         1, NULL);
3003
                if (!fsdev) {
3004
                    fprintf(stderr, "duplicate fsdev id: %s\n",
3005
                            qemu_opt_get(opts, "mount_tag"));
3006
                    exit(1);
3007
                }
3008

    
3009
                writeout = qemu_opt_get(opts, "writeout");
3010
                if (writeout) {
3011
#ifdef CONFIG_SYNC_FILE_RANGE
3012
                    qemu_opt_set(fsdev, "writeout", writeout);
3013
#else
3014
                    fprintf(stderr, "writeout=immediate not supported on "
3015
                            "this platform\n");
3016
                    exit(1);
3017
#endif
3018
                }
3019
                qemu_opt_set(fsdev, "fsdriver", qemu_opt_get(opts, "fsdriver"));
3020
                qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"));
3021
                qemu_opt_set(fsdev, "security_model",
3022
                             qemu_opt_get(opts, "security_model"));
3023
                socket = qemu_opt_get(opts, "socket");
3024
                if (socket) {
3025
                    qemu_opt_set(fsdev, "socket", socket);
3026
                }
3027
                sock_fd = qemu_opt_get(opts, "sock_fd");
3028
                if (sock_fd) {
3029
                    qemu_opt_set(fsdev, "sock_fd", sock_fd);
3030
                }
3031

    
3032
                qemu_opt_set_bool(fsdev, "readonly",
3033
                                qemu_opt_get_bool(opts, "readonly", 0));
3034
                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3035
                                          NULL);
3036
                qemu_opt_set(device, "driver", "virtio-9p-pci");
3037
                qemu_opt_set(device, "fsdev",
3038
                             qemu_opt_get(opts, "mount_tag"));
3039
                qemu_opt_set(device, "mount_tag",
3040
                             qemu_opt_get(opts, "mount_tag"));
3041
                break;
3042
            }
3043
            case QEMU_OPTION_virtfs_synth: {
3044
                QemuOpts *fsdev;
3045
                QemuOpts *device;
3046

    
3047
                fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth",
3048
                                         1, NULL);
3049
                if (!fsdev) {
3050
                    fprintf(stderr, "duplicate option: %s\n", "virtfs_synth");
3051
                    exit(1);
3052
                }
3053
                qemu_opt_set(fsdev, "fsdriver", "synth");
3054

    
3055
                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3056
                                          NULL);
3057
                qemu_opt_set(device, "driver", "virtio-9p-pci");
3058
                qemu_opt_set(device, "fsdev", "v_synth");
3059
                qemu_opt_set(device, "mount_tag", "v_synth");
3060
                break;
3061
            }
3062
            case QEMU_OPTION_serial:
3063
                add_device_config(DEV_SERIAL, optarg);
3064
                default_serial = 0;
3065
                if (strncmp(optarg, "mon:", 4) == 0) {
3066
                    default_monitor = 0;
3067
                }
3068
                break;
3069
            case QEMU_OPTION_watchdog:
3070
                if (watchdog) {
3071
                    fprintf(stderr,
3072
                            "qemu: only one watchdog option may be given\n");
3073
                    return 1;
3074
                }
3075
                watchdog = optarg;
3076
                break;
3077
            case QEMU_OPTION_watchdog_action:
3078
                if (select_watchdog_action(optarg) == -1) {
3079
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
3080
                    exit(1);
3081
                }
3082
                break;
3083
            case QEMU_OPTION_virtiocon:
3084
                add_device_config(DEV_VIRTCON, optarg);
3085
                default_virtcon = 0;
3086
                if (strncmp(optarg, "mon:", 4) == 0) {
3087
                    default_monitor = 0;
3088
                }
3089
                break;
3090
            case QEMU_OPTION_parallel:
3091
                add_device_config(DEV_PARALLEL, optarg);
3092
                default_parallel = 0;
3093
                if (strncmp(optarg, "mon:", 4) == 0) {
3094
                    default_monitor = 0;
3095
                }
3096
                break;
3097
            case QEMU_OPTION_debugcon:
3098
                add_device_config(DEV_DEBUGCON, optarg);
3099
                break;
3100
            case QEMU_OPTION_loadvm:
3101
                loadvm = optarg;
3102
                break;
3103
            case QEMU_OPTION_full_screen:
3104
                full_screen = 1;
3105
                break;
3106
#ifdef CONFIG_SDL
3107
            case QEMU_OPTION_no_frame:
3108
                no_frame = 1;
3109
                break;
3110
            case QEMU_OPTION_alt_grab:
3111
                alt_grab = 1;
3112
                break;
3113
            case QEMU_OPTION_ctrl_grab:
3114
                ctrl_grab = 1;
3115
                break;
3116
            case QEMU_OPTION_no_quit:
3117
                no_quit = 1;
3118
                break;
3119
            case QEMU_OPTION_sdl:
3120
                display_type = DT_SDL;
3121
                break;
3122
#else
3123
            case QEMU_OPTION_no_frame:
3124
            case QEMU_OPTION_alt_grab:
3125
            case QEMU_OPTION_ctrl_grab:
3126
            case QEMU_OPTION_no_quit:
3127
            case QEMU_OPTION_sdl:
3128
                fprintf(stderr, "SDL support is disabled\n");
3129
                exit(1);
3130
#endif
3131
            case QEMU_OPTION_pidfile:
3132
                pid_file = optarg;
3133
                break;
3134
            case QEMU_OPTION_win2k_hack:
3135
                win2k_install_hack = 1;
3136
                break;
3137
            case QEMU_OPTION_rtc_td_hack: {
3138
                static GlobalProperty slew_lost_ticks[] = {
3139
                    {
3140
                        .driver   = "mc146818rtc",
3141
                        .property = "lost_tick_policy",
3142
                        .value    = "slew",
3143
                    },
3144
                    { /* end of list */ }
3145
                };
3146

    
3147
                qdev_prop_register_global_list(slew_lost_ticks);
3148
                break;
3149
            }
3150
            case QEMU_OPTION_acpitable:
3151
                do_acpitable_option(optarg);
3152
                break;
3153
            case QEMU_OPTION_smbios:
3154
                do_smbios_option(optarg);
3155
                break;
3156
            case QEMU_OPTION_enable_kvm:
3157
                olist = qemu_find_opts("machine");
3158
                qemu_opts_parse(olist, "accel=kvm", 0);
3159
                break;
3160
            case QEMU_OPTION_machine:
3161
                olist = qemu_find_opts("machine");
3162
                opts = qemu_opts_parse(olist, optarg, 1);
3163
                if (!opts) {
3164
                    fprintf(stderr, "parse error: %s\n", optarg);
3165
                    exit(1);
3166
                }
3167
                optarg = qemu_opt_get(opts, "type");
3168
                if (optarg) {
3169
                    machine = machine_parse(optarg);
3170
                }
3171
                break;
3172
            case QEMU_OPTION_usb:
3173
                machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
3174
                if (machine_opts) {
3175
                    qemu_opt_set_bool(machine_opts, "usb", true);
3176
                }
3177
                break;
3178
            case QEMU_OPTION_usbdevice:
3179
                machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
3180
                if (machine_opts) {
3181
                    qemu_opt_set_bool(machine_opts, "usb", true);
3182
                }
3183
                add_device_config(DEV_USB, optarg);
3184
                break;
3185
            case QEMU_OPTION_device:
3186
                if (!qemu_opts_parse(qemu_find_opts("device"), optarg, 1)) {
3187
                    exit(1);
3188
                }
3189
                break;
3190
            case QEMU_OPTION_smp:
3191
                smp_parse(optarg);
3192
                if (smp_cpus < 1) {
3193
                    fprintf(stderr, "Invalid number of CPUs\n");
3194
                    exit(1);
3195
                }
3196
                if (max_cpus < smp_cpus) {
3197
                    fprintf(stderr, "maxcpus must be equal to or greater than "
3198
                            "smp\n");
3199
                    exit(1);
3200
                }
3201
                if (max_cpus > 255) {
3202
                    fprintf(stderr, "Unsupported number of maxcpus\n");
3203
                    exit(1);
3204
                }
3205
                break;
3206
            case QEMU_OPTION_vnc:
3207
#ifdef CONFIG_VNC
3208
                display_remote++;
3209
                vnc_display = optarg;
3210
#else
3211
                fprintf(stderr, "VNC support is disabled\n");
3212
                exit(1);
3213
#endif
3214
                break;
3215
            case QEMU_OPTION_no_acpi:
3216
                acpi_enabled = 0;
3217
                break;
3218
            case QEMU_OPTION_no_hpet:
3219
                no_hpet = 1;
3220
                break;
3221
            case QEMU_OPTION_balloon:
3222
                if (balloon_parse(optarg) < 0) {
3223
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3224
                    exit(1);
3225
                }
3226
                break;
3227
            case QEMU_OPTION_no_reboot:
3228
                no_reboot = 1;
3229
                break;
3230
            case QEMU_OPTION_no_shutdown:
3231
                no_shutdown = 1;
3232
                break;
3233
            case QEMU_OPTION_show_cursor:
3234
                cursor_hide = 0;
3235
                break;
3236
            case QEMU_OPTION_uuid:
3237
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3238
                    fprintf(stderr, "Fail to parse UUID string."
3239
                            " Wrong format.\n");
3240
                    exit(1);
3241
                }
3242
                break;
3243
            case QEMU_OPTION_option_rom:
3244
                if (nb_option_roms >= MAX_OPTION_ROMS) {
3245
                    fprintf(stderr, "Too many option ROMs\n");
3246
                    exit(1);
3247
                }
3248
                opts = qemu_opts_parse(qemu_find_opts("option-rom"), optarg, 1);
3249
                option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3250
                option_rom[nb_option_roms].bootindex =
3251
                    qemu_opt_get_number(opts, "bootindex", -1);
3252
                if (!option_rom[nb_option_roms].name) {
3253
                    fprintf(stderr, "Option ROM file is not specified\n");
3254
                    exit(1);
3255
                }
3256
                nb_option_roms++;
3257
                break;
3258
            case QEMU_OPTION_semihosting:
3259
                semihosting_enabled = 1;
3260
                break;
3261
            case QEMU_OPTION_name:
3262
                qemu_name = g_strdup(optarg);
3263
                 {
3264
                     char *p = strchr(qemu_name, ',');
3265
                     if (p != NULL) {
3266
                        *p++ = 0;
3267
                        if (strncmp(p, "process=", 8)) {
3268
                            fprintf(stderr, "Unknown subargument %s to -name\n", p);
3269
                            exit(1);
3270
                        }
3271
                        p += 8;
3272
                        os_set_proc_name(p);
3273
                     }        
3274
                 }        
3275
                break;
3276
            case QEMU_OPTION_prom_env:
3277
                if (nb_prom_envs >= MAX_PROM_ENVS) {
3278
                    fprintf(stderr, "Too many prom variables\n");
3279
                    exit(1);
3280
                }
3281
                prom_envs[nb_prom_envs] = optarg;
3282
                nb_prom_envs++;
3283
                break;
3284
            case QEMU_OPTION_old_param:
3285
                old_param = 1;
3286
                break;
3287
            case QEMU_OPTION_clock:
3288
                configure_alarms(optarg);
3289
                break;
3290
            case QEMU_OPTION_startdate:
3291
                configure_rtc_date_offset(optarg, 1);
3292
                break;
3293
            case QEMU_OPTION_rtc:
3294
                opts = qemu_opts_parse(qemu_find_opts("rtc"), optarg, 0);
3295
                if (!opts) {
3296
                    exit(1);
3297
                }
3298
                configure_rtc(opts);
3299
                break;
3300
            case QEMU_OPTION_tb_size:
3301
                tcg_tb_size = strtol(optarg, NULL, 0);
3302
                if (tcg_tb_size < 0) {
3303
                    tcg_tb_size = 0;
3304
                }
3305
                break;
3306
            case QEMU_OPTION_icount:
3307
                icount_option = optarg;
3308
                break;
3309
            case QEMU_OPTION_incoming:
3310
                incoming = optarg;
3311
                runstate_set(RUN_STATE_INMIGRATE);
3312
                break;
3313
            case QEMU_OPTION_nodefaults:
3314
                default_serial = 0;
3315
                default_parallel = 0;
3316
                default_virtcon = 0;
3317
                default_monitor = 0;
3318
                default_net = 0;
3319
                default_floppy = 0;
3320
                default_cdrom = 0;
3321
                default_sdcard = 0;
3322
                default_vga = 0;
3323
                break;
3324
            case QEMU_OPTION_xen_domid:
3325
                if (!(xen_available())) {
3326
                    printf("Option %s not supported for this target\n", popt->name);
3327
                    exit(1);
3328
                }
3329
                xen_domid = atoi(optarg);
3330
                break;
3331
            case QEMU_OPTION_xen_create:
3332
                if (!(xen_available())) {
3333
                    printf("Option %s not supported for this target\n", popt->name);
3334
                    exit(1);
3335
                }
3336
                xen_mode = XEN_CREATE;
3337
                break;
3338
            case QEMU_OPTION_xen_attach:
3339
                if (!(xen_available())) {
3340
                    printf("Option %s not supported for this target\n", popt->name);
3341
                    exit(1);
3342
                }
3343
                xen_mode = XEN_ATTACH;
3344
                break;
3345
            case QEMU_OPTION_trace:
3346
            {
3347
                opts = qemu_opts_parse(qemu_find_opts("trace"), optarg, 0);
3348
                if (!opts) {
3349
                    exit(1);
3350
                }
3351
                trace_events = qemu_opt_get(opts, "events");
3352
                trace_file = qemu_opt_get(opts, "file");
3353
                break;
3354
            }
3355
            case QEMU_OPTION_readconfig:
3356
                {
3357
                    int ret = qemu_read_config_file(optarg);
3358
                    if (ret < 0) {
3359
                        fprintf(stderr, "read config %s: %s\n", optarg,
3360
                            strerror(-ret));
3361
                        exit(1);
3362
                    }
3363
                    break;
3364
                }
3365
            case QEMU_OPTION_spice:
3366
                olist = qemu_find_opts("spice");
3367
                if (!olist) {
3368
                    fprintf(stderr, "spice is not supported by this qemu build.\n");
3369
                    exit(1);
3370
                }
3371
                opts = qemu_opts_parse(olist, optarg, 0);
3372
                if (!opts) {
3373
                    fprintf(stderr, "parse error: %s\n", optarg);
3374
                    exit(1);
3375
                }
3376
                break;
3377
            case QEMU_OPTION_writeconfig:
3378
                {
3379
                    FILE *fp;
3380
                    if (strcmp(optarg, "-") == 0) {
3381
                        fp = stdout;
3382
                    } else {
3383
                        fp = fopen(optarg, "w");
3384
                        if (fp == NULL) {
3385
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3386
                            exit(1);
3387
                        }
3388
                    }
3389
                    qemu_config_write(fp);
3390
                    fclose(fp);
3391
                    break;
3392
                }
3393
            case QEMU_OPTION_qtest:
3394
                qtest_chrdev = optarg;
3395
                break;
3396
            case QEMU_OPTION_qtest_log:
3397
                qtest_log = optarg;
3398
                break;
3399
            case QEMU_OPTION_sandbox:
3400
                opts = qemu_opts_parse(qemu_find_opts("sandbox"), optarg, 1);
3401
                if (!opts) {
3402
                    exit(0);
3403
                }
3404
                break;
3405
            case QEMU_OPTION_add_fd:
3406
#ifndef _WIN32
3407
                opts = qemu_opts_parse(qemu_find_opts("add-fd"), optarg, 0);
3408
                if (!opts) {
3409
                    exit(0);
3410
                }
3411
#else
3412
                error_report("File descriptor passing is disabled on this "
3413
                             "platform");
3414
                exit(1);
3415
#endif
3416
                break;
3417
            default:
3418
                os_parse_cmd_args(popt->index, optarg);
3419
            }
3420
        }
3421
    }
3422
    loc_set_none();
3423

    
3424
    if (qemu_opts_foreach(qemu_find_opts("sandbox"), parse_sandbox, NULL, 0)) {
3425
        exit(1);
3426
    }
3427

    
3428
#ifndef _WIN32
3429
    if (qemu_opts_foreach(qemu_find_opts("add-fd"), parse_add_fd, NULL, 1)) {
3430
        exit(1);
3431
    }
3432

    
3433
    if (qemu_opts_foreach(qemu_find_opts("add-fd"), cleanup_add_fd, NULL, 1)) {
3434
        exit(1);
3435
    }
3436
#endif
3437

    
3438
    if (machine == NULL) {
3439
        fprintf(stderr, "No machine found.\n");
3440
        exit(1);
3441
    }
3442

    
3443
    if (machine->hw_version) {
3444
        qemu_set_version(machine->hw_version);
3445
    }
3446

    
3447
    /* Init CPU def lists, based on config
3448
     * - Must be called after all the qemu_read_config_file() calls
3449
     * - Must be called before list_cpus()
3450
     * - Must be called before machine->init()
3451
     */
3452
    cpudef_init();
3453

    
3454
    if (cpu_model && is_help_option(cpu_model)) {
3455
        list_cpus(stdout, &fprintf, cpu_model);
3456
        exit(0);
3457
    }
3458

    
3459
    /* Open the logfile at this point, if necessary. We can't open the logfile
3460
     * when encountering either of the logging options (-d or -D) because the
3461
     * other one may be encountered later on the command line, changing the
3462
     * location or level of logging.
3463
     */
3464
    if (log_mask) {
3465
        if (log_file) {
3466
            set_cpu_log_filename(log_file);
3467
        }
3468
        set_cpu_log(log_mask);
3469
    }
3470

    
3471
    if (!trace_backend_init(trace_events, trace_file)) {
3472
        exit(1);
3473
    }
3474

    
3475
    /* If no data_dir is specified then try to find it relative to the
3476
       executable path.  */
3477
    if (!data_dir) {
3478
        data_dir = os_find_datadir(argv[0]);
3479
    }
3480
    /* If all else fails use the install path specified when building. */
3481
    if (!data_dir) {
3482
        data_dir = CONFIG_QEMU_DATADIR;
3483
    }
3484

    
3485
    /*
3486
     * Default to max_cpus = smp_cpus, in case the user doesn't
3487
     * specify a max_cpus value.
3488
     */
3489
    if (!max_cpus)
3490
        max_cpus = smp_cpus;
3491

    
3492
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3493
    if (smp_cpus > machine->max_cpus) {
3494
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3495
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3496
                machine->max_cpus);
3497
        exit(1);
3498
    }
3499

    
3500
    /*
3501
     * Get the default machine options from the machine if it is not already
3502
     * specified either by the configuration file or by the command line.
3503
     */
3504
    if (machine->default_machine_opts) {
3505
        qemu_opts_set_defaults(qemu_find_opts("machine"),
3506
                               machine->default_machine_opts, 0);
3507
    }
3508

    
3509
    qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
3510
    qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
3511

    
3512
    if (machine->no_serial) {
3513
        default_serial = 0;
3514
    }
3515
    if (machine->no_parallel) {
3516
        default_parallel = 0;
3517
    }
3518
    if (!machine->use_virtcon) {
3519
        default_virtcon = 0;
3520
    }
3521
    if (machine->no_floppy) {
3522
        default_floppy = 0;
3523
    }
3524
    if (machine->no_cdrom) {
3525
        default_cdrom = 0;
3526
    }
3527
    if (machine->no_sdcard) {
3528
        default_sdcard = 0;
3529
    }
3530

    
3531
    if (display_type == DT_NOGRAPHIC) {
3532
        if (default_parallel)
3533
            add_device_config(DEV_PARALLEL, "null");
3534
        if (default_serial && default_monitor) {
3535
            add_device_config(DEV_SERIAL, "mon:stdio");
3536
        } else if (default_virtcon && default_monitor) {
3537
            add_device_config(DEV_VIRTCON, "mon:stdio");
3538
        } else {
3539
            if (default_serial)
3540
                add_device_config(DEV_SERIAL, "stdio");
3541
            if (default_virtcon)
3542
                add_device_config(DEV_VIRTCON, "stdio");
3543
            if (default_monitor)
3544
                monitor_parse("stdio", "readline");
3545
        }
3546
    } else {
3547
        if (default_serial)
3548
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
3549
        if (default_parallel)
3550
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3551
        if (default_monitor)
3552
            monitor_parse("vc:80Cx24C", "readline");
3553
        if (default_virtcon)
3554
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3555
    }
3556

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

    
3562
    socket_init();
3563

    
3564
    if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)
3565
        exit(1);
3566
#ifdef CONFIG_VIRTFS
3567
    if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {
3568
        exit(1);
3569
    }
3570
#endif
3571

    
3572
    os_daemonize();
3573

    
3574
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3575
        os_pidfile_error();
3576
        exit(1);
3577
    }
3578

    
3579
    /* init the memory */
3580
    if (ram_size == 0) {
3581
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3582
    }
3583

    
3584
    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0)
3585
        != 0) {
3586
        exit(0);
3587
    }
3588

    
3589
    configure_accelerator();
3590

    
3591
    qemu_init_cpu_loop();
3592
    if (qemu_init_main_loop()) {
3593
        fprintf(stderr, "qemu_init_main_loop failed\n");
3594
        exit(1);
3595
    }
3596

    
3597
    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
3598
    if (machine_opts) {
3599
        kernel_filename = qemu_opt_get(machine_opts, "kernel");
3600
        initrd_filename = qemu_opt_get(machine_opts, "initrd");
3601
        kernel_cmdline = qemu_opt_get(machine_opts, "append");
3602
    } else {
3603
        kernel_filename = initrd_filename = kernel_cmdline = NULL;
3604
    }
3605

    
3606
    if (!kernel_cmdline) {
3607
        kernel_cmdline = "";
3608
    }
3609

    
3610
    linux_boot = (kernel_filename != NULL);
3611

    
3612
    if (!linux_boot && *kernel_cmdline != '\0') {
3613
        fprintf(stderr, "-append only allowed with -kernel option\n");
3614
        exit(1);
3615
    }
3616

    
3617
    if (!linux_boot && initrd_filename != NULL) {
3618
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3619
        exit(1);
3620
    }
3621

    
3622
    if (!linux_boot && machine_opts && qemu_opt_get(machine_opts, "dtb")) {
3623
        fprintf(stderr, "-dtb only allowed with -kernel option\n");
3624
        exit(1);
3625
    }
3626

    
3627
    os_set_line_buffering();
3628

    
3629
#ifdef CONFIG_SPICE
3630
    /* spice needs the timers to be initialized by this point */
3631
    qemu_spice_init();
3632
#endif
3633

    
3634
    if (icount_option && (kvm_enabled() || xen_enabled())) {
3635
        fprintf(stderr, "-icount is not allowed with kvm or xen\n");
3636
        exit(1);
3637
    }
3638
    configure_icount(icount_option);
3639

    
3640
    if (net_init_clients() < 0) {
3641
        exit(1);
3642
    }
3643

    
3644
    /* init the bluetooth world */
3645
    if (foreach_device_config(DEV_BT, bt_parse))
3646
        exit(1);
3647

    
3648
    if (!xen_enabled()) {
3649
        /* On 32-bit hosts, QEMU is limited by virtual address space */
3650
        if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
3651
            fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3652
            exit(1);
3653
        }
3654
    }
3655

    
3656
    cpu_exec_init_all();
3657

    
3658
    bdrv_init_with_whitelist();
3659

    
3660
    blk_mig_init();
3661

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

    
3668
    default_drive(default_cdrom, snapshot, machine->use_scsi,
3669
                  IF_DEFAULT, 2, CDROM_OPTS);
3670
    default_drive(default_floppy, snapshot, machine->use_scsi,
3671
                  IF_FLOPPY, 0, FD_OPTS);
3672
    default_drive(default_sdcard, snapshot, machine->use_scsi,
3673
                  IF_SD, 0, SD_OPTS);
3674

    
3675
    register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, NULL);
3676

    
3677
    if (nb_numa_nodes > 0) {
3678
        int i;
3679

    
3680
        if (nb_numa_nodes > MAX_NODES) {
3681
            nb_numa_nodes = MAX_NODES;
3682
        }
3683

    
3684
        /* If no memory size if given for any node, assume the default case
3685
         * and distribute the available memory equally across all nodes
3686
         */
3687
        for (i = 0; i < nb_numa_nodes; i++) {
3688
            if (node_mem[i] != 0)
3689
                break;
3690
        }
3691
        if (i == nb_numa_nodes) {
3692
            uint64_t usedmem = 0;
3693

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

    
3704
        for (i = 0; i < nb_numa_nodes; i++) {
3705
            if (!bitmap_empty(node_cpumask[i], MAX_CPUMASK_BITS)) {
3706
                break;
3707
            }
3708
        }
3709
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3710
         * must cope with this anyway, because there are BIOSes out there in
3711
         * real machines which also use this scheme.
3712
         */
3713
        if (i == nb_numa_nodes) {
3714
            for (i = 0; i < max_cpus; i++) {
3715
                set_bit(i, node_cpumask[i % nb_numa_nodes]);
3716
            }
3717
        }
3718
    }
3719

    
3720
    if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {
3721
        exit(1);
3722
    }
3723

    
3724
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3725
        exit(1);
3726
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3727
        exit(1);
3728
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3729
        exit(1);
3730
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3731
        exit(1);
3732

    
3733
    /* If no default VGA is requested, the default is "none".  */
3734
    if (default_vga) {
3735
        if (cirrus_vga_available()) {
3736
            vga_model = "cirrus";
3737
        } else if (vga_available()) {
3738
            vga_model = "std";
3739
        }
3740
    }
3741
    select_vgahw(vga_model);
3742

    
3743
    if (watchdog) {
3744
        i = select_watchdog(watchdog);
3745
        if (i > 0)
3746
            exit (i == 1 ? 1 : 0);
3747
    }
3748

    
3749
    if (machine->compat_props) {
3750
        qdev_prop_register_global_list(machine->compat_props);
3751
    }
3752
    qemu_add_globals();
3753

    
3754
    qdev_machine_init();
3755

    
3756
    QEMUMachineInitArgs args = { .ram_size = ram_size,
3757
                                 .boot_device = boot_devices,
3758
                                 .kernel_filename = kernel_filename,
3759
                                 .kernel_cmdline = kernel_cmdline,
3760
                                 .initrd_filename = initrd_filename,
3761
                                 .cpu_model = cpu_model };
3762
    machine->init(&args);
3763

    
3764
    cpu_synchronize_all_post_init();
3765

    
3766
    set_numa_modes();
3767

    
3768
    current_machine = machine;
3769

    
3770
    /* init USB devices */
3771
    if (usb_enabled(false)) {
3772
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3773
            exit(1);
3774
    }
3775

    
3776
    /* init generic devices */
3777
    if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)
3778
        exit(1);
3779

    
3780
    net_check_clients();
3781

    
3782
    /* just use the first displaystate for the moment */
3783
    ds = get_displaystate();
3784

    
3785
    if (using_spice)
3786
        display_remote++;
3787
    if (display_type == DT_DEFAULT && !display_remote) {
3788
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3789
        display_type = DT_SDL;
3790
#elif defined(CONFIG_VNC)
3791
        vnc_display = "localhost:0,to=99";
3792
        show_vnc_port = 1;
3793
#else
3794
        display_type = DT_NONE;
3795
#endif
3796
    }
3797

    
3798

    
3799
    /* init local displays */
3800
    switch (display_type) {
3801
    case DT_NOGRAPHIC:
3802
        break;
3803
#if defined(CONFIG_CURSES)
3804
    case DT_CURSES:
3805
        if (!is_daemonized()) {
3806
            curses_display_init(ds, full_screen);
3807
        }
3808
        break;
3809
#endif
3810
#if defined(CONFIG_SDL)
3811
    case DT_SDL:
3812
        sdl_display_init(ds, full_screen, no_frame);
3813
        break;
3814
#elif defined(CONFIG_COCOA)
3815
    case DT_SDL:
3816
        cocoa_display_init(ds, full_screen);
3817
        break;
3818
#endif
3819
    default:
3820
        break;
3821
    }
3822

    
3823
    /* must be after terminal init, SDL library changes signal handlers */
3824
    os_setup_signal_handling();
3825

    
3826
#ifdef CONFIG_VNC
3827
    /* init remote displays */
3828
    if (vnc_display) {
3829
        Error *local_err = NULL;
3830
        vnc_display_init(ds);
3831
        vnc_display_open(ds, vnc_display, &local_err);
3832
        if (local_err != NULL) {
3833
            fprintf(stderr, "Failed to start VNC server on `%s': %s\n",
3834
                    vnc_display, error_get_pretty(local_err));
3835
            error_free(local_err);
3836
            exit(1);
3837
        }
3838

    
3839
        if (show_vnc_port) {
3840
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3841
        }
3842
    }
3843
#endif
3844
#ifdef CONFIG_SPICE
3845
    if (using_spice && !qxl_enabled) {
3846
        qemu_spice_display_init(ds);
3847
    }
3848
#endif
3849

    
3850
    /* display setup */
3851
    dpy_resize(ds);
3852
    dcl = ds->listeners;
3853
    while (dcl != NULL) {
3854
        if (dcl->dpy_refresh != NULL) {
3855
            ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);
3856
            qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));
3857
            break;
3858
        }
3859
        dcl = dcl->next;
3860
    }
3861
    text_consoles_set_display(ds);
3862

    
3863
    if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
3864
        exit(1);
3865
    }
3866

    
3867
    qdev_machine_creation_done();
3868

    
3869
    if (rom_load_all() != 0) {
3870
        fprintf(stderr, "rom loading failed\n");
3871
        exit(1);
3872
    }
3873

    
3874
    /* TODO: once all bus devices are qdevified, this should be done
3875
     * when bus is created by qdev.c */
3876
    qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
3877
    qemu_run_machine_init_done_notifiers();
3878

    
3879
    qemu_system_reset(VMRESET_SILENT);
3880
    if (loadvm) {
3881
        if (load_vmstate(loadvm) < 0) {
3882
            autostart = 0;
3883
        }
3884
    }
3885

    
3886
    if (incoming) {
3887
        Error *local_err = NULL;
3888
        qemu_start_incoming_migration(incoming, &local_err);
3889
        if (local_err) {
3890
            fprintf(stderr, "-incoming %s: %s\n", incoming, error_get_pretty(local_err));
3891
            error_free(local_err);
3892
            exit(1);
3893
        }
3894
    } else if (autostart) {
3895
        vm_start();
3896
    }
3897

    
3898
    os_setup_post();
3899

    
3900
    resume_all_vcpus();
3901
    main_loop();
3902
    bdrv_close_all();
3903
    pause_all_vcpus();
3904
    net_cleanup();
3905
    res_free();
3906

    
3907
    return 0;
3908
}