Statistics
| Branch: | Revision:

root / vl.c @ 35b30712

History | View | Annotate | Download (122.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 "qemu/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 "sysemu/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/i386/pc.h"
121
#include "hw/isa/isa.h"
122
#include "hw/bt.h"
123
#include "sysemu/watchdog.h"
124
#include "hw/i386/smbios.h"
125
#include "hw/xen/xen.h"
126
#include "hw/qdev.h"
127
#include "hw/loader.h"
128
#include "monitor/qdev.h"
129
#include "sysemu/bt.h"
130
#include "net/net.h"
131
#include "net/slirp.h"
132
#include "monitor/monitor.h"
133
#include "ui/console.h"
134
#include "sysemu/sysemu.h"
135
#include "exec/gdbstub.h"
136
#include "qemu/timer.h"
137
#include "sysemu/char.h"
138
#include "qemu/cache-utils.h"
139
#include "sysemu/blockdev.h"
140
#include "hw/block/block.h"
141
#include "migration/block.h"
142
#include "sysemu/tpm.h"
143
#include "sysemu/dma.h"
144
#include "audio/audio.h"
145
#include "migration/migration.h"
146
#include "sysemu/kvm.h"
147
#include "qapi/qmp/qjson.h"
148
#include "qemu/option.h"
149
#include "qemu/config-file.h"
150
#include "qemu-options.h"
151
#include "qmp-commands.h"
152
#include "qemu/main-loop.h"
153
#ifdef CONFIG_VIRTFS
154
#include "fsdev/qemu-fsdev.h"
155
#endif
156
#include "sysemu/qtest.h"
157

    
158
#include "disas/disas.h"
159

    
160
#include "qemu/sockets.h"
161

    
162
#include "slirp/libslirp.h"
163

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

    
171
#include "ui/qemu-spice.h"
172
#include "qapi/string-input-visitor.h"
173
#include "qom/object_interfaces.h"
174

    
175
//#define DEBUG_NET
176
//#define DEBUG_SLIRP
177

    
178
#define DEFAULT_RAM_SIZE 128
179

    
180
#define MAX_VIRTIO_CONSOLES 1
181
#define MAX_SCLP_CONSOLES 1
182

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

    
239
typedef struct FWBootEntry FWBootEntry;
240

    
241
struct FWBootEntry {
242
    QTAILQ_ENTRY(FWBootEntry) link;
243
    int32_t bootindex;
244
    DeviceState *dev;
245
    char *suffix;
246
};
247

    
248
static QTAILQ_HEAD(, FWBootEntry) fw_boot_order =
249
    QTAILQ_HEAD_INITIALIZER(fw_boot_order);
250

    
251
int nb_numa_nodes;
252
uint64_t node_mem[MAX_NODES];
253
unsigned long *node_cpumask[MAX_NODES];
254

    
255
uint8_t qemu_uuid[16];
256
bool qemu_uuid_set;
257

    
258
static QEMUBootSetHandler *boot_set_handler;
259
static void *boot_set_opaque;
260

    
261
static NotifierList exit_notifiers =
262
    NOTIFIER_LIST_INITIALIZER(exit_notifiers);
263

    
264
static NotifierList machine_init_done_notifiers =
265
    NOTIFIER_LIST_INITIALIZER(machine_init_done_notifiers);
266

    
267
static bool tcg_allowed = true;
268
bool xen_allowed;
269
uint32_t xen_domid;
270
enum xen_mode xen_mode = XEN_EMULATE;
271
static int tcg_tb_size;
272

    
273
static int default_serial = 1;
274
static int default_parallel = 1;
275
static int default_virtcon = 1;
276
static int default_sclp = 1;
277
static int default_monitor = 1;
278
static int default_floppy = 1;
279
static int default_cdrom = 1;
280
static int default_sdcard = 1;
281
static int default_vga = 1;
282

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

    
305
static QemuOptsList qemu_rtc_opts = {
306
    .name = "rtc",
307
    .head = QTAILQ_HEAD_INITIALIZER(qemu_rtc_opts.head),
308
    .desc = {
309
        {
310
            .name = "base",
311
            .type = QEMU_OPT_STRING,
312
        },{
313
            .name = "clock",
314
            .type = QEMU_OPT_STRING,
315
        },{
316
            .name = "driftfix",
317
            .type = QEMU_OPT_STRING,
318
        },
319
        { /* end of list */ }
320
    },
321
};
322

    
323
static QemuOptsList qemu_sandbox_opts = {
324
    .name = "sandbox",
325
    .implied_opt_name = "enable",
326
    .head = QTAILQ_HEAD_INITIALIZER(qemu_sandbox_opts.head),
327
    .desc = {
328
        {
329
            .name = "enable",
330
            .type = QEMU_OPT_BOOL,
331
        },
332
        { /* end of list */ }
333
    },
334
};
335

    
336
static QemuOptsList qemu_trace_opts = {
337
    .name = "trace",
338
    .implied_opt_name = "trace",
339
    .head = QTAILQ_HEAD_INITIALIZER(qemu_trace_opts.head),
340
    .desc = {
341
        {
342
            .name = "events",
343
            .type = QEMU_OPT_STRING,
344
        },{
345
            .name = "file",
346
            .type = QEMU_OPT_STRING,
347
        },
348
        { /* end of list */ }
349
    },
350
};
351

    
352
static QemuOptsList qemu_option_rom_opts = {
353
    .name = "option-rom",
354
    .implied_opt_name = "romfile",
355
    .head = QTAILQ_HEAD_INITIALIZER(qemu_option_rom_opts.head),
356
    .desc = {
357
        {
358
            .name = "bootindex",
359
            .type = QEMU_OPT_NUMBER,
360
        }, {
361
            .name = "romfile",
362
            .type = QEMU_OPT_STRING,
363
        },
364
        { /* end of list */ }
365
    },
366
};
367

    
368
static QemuOptsList qemu_machine_opts = {
369
    .name = "machine",
370
    .implied_opt_name = "type",
371
    .merge_lists = true,
372
    .head = QTAILQ_HEAD_INITIALIZER(qemu_machine_opts.head),
373
    .desc = {
374
        {
375
            .name = "type",
376
            .type = QEMU_OPT_STRING,
377
            .help = "emulated machine"
378
        }, {
379
            .name = "accel",
380
            .type = QEMU_OPT_STRING,
381
            .help = "accelerator list",
382
        }, {
383
            .name = "kernel_irqchip",
384
            .type = QEMU_OPT_BOOL,
385
            .help = "use KVM in-kernel irqchip",
386
        }, {
387
            .name = "kvm_shadow_mem",
388
            .type = QEMU_OPT_SIZE,
389
            .help = "KVM shadow MMU size",
390
        }, {
391
            .name = "kernel",
392
            .type = QEMU_OPT_STRING,
393
            .help = "Linux kernel image file",
394
        }, {
395
            .name = "initrd",
396
            .type = QEMU_OPT_STRING,
397
            .help = "Linux initial ramdisk file",
398
        }, {
399
            .name = "append",
400
            .type = QEMU_OPT_STRING,
401
            .help = "Linux kernel command line",
402
        }, {
403
            .name = "dtb",
404
            .type = QEMU_OPT_STRING,
405
            .help = "Linux kernel device tree file",
406
        }, {
407
            .name = "dumpdtb",
408
            .type = QEMU_OPT_STRING,
409
            .help = "Dump current dtb to a file and quit",
410
        }, {
411
            .name = "phandle_start",
412
            .type = QEMU_OPT_NUMBER,
413
            .help = "The first phandle ID we may generate dynamically",
414
        }, {
415
            .name = "dt_compatible",
416
            .type = QEMU_OPT_STRING,
417
            .help = "Overrides the \"compatible\" property of the dt root node",
418
        }, {
419
            .name = "dump-guest-core",
420
            .type = QEMU_OPT_BOOL,
421
            .help = "Include guest memory in  a core dump",
422
        }, {
423
            .name = "mem-merge",
424
            .type = QEMU_OPT_BOOL,
425
            .help = "enable/disable memory merge support",
426
        },{
427
            .name = "usb",
428
            .type = QEMU_OPT_BOOL,
429
            .help = "Set on/off to enable/disable usb",
430
        },{
431
            .name = "firmware",
432
            .type = QEMU_OPT_STRING,
433
            .help = "firmware image",
434
        },
435
        { /* End of list */ }
436
    },
437
};
438

    
439
static QemuOptsList qemu_boot_opts = {
440
    .name = "boot-opts",
441
    .implied_opt_name = "order",
442
    .merge_lists = true,
443
    .head = QTAILQ_HEAD_INITIALIZER(qemu_boot_opts.head),
444
    .desc = {
445
        {
446
            .name = "order",
447
            .type = QEMU_OPT_STRING,
448
        }, {
449
            .name = "once",
450
            .type = QEMU_OPT_STRING,
451
        }, {
452
            .name = "menu",
453
            .type = QEMU_OPT_BOOL,
454
        }, {
455
            .name = "splash",
456
            .type = QEMU_OPT_STRING,
457
        }, {
458
            .name = "splash-time",
459
            .type = QEMU_OPT_STRING,
460
        }, {
461
            .name = "reboot-timeout",
462
            .type = QEMU_OPT_STRING,
463
        }, {
464
            .name = "strict",
465
            .type = QEMU_OPT_BOOL,
466
        },
467
        { /*End of list */ }
468
    },
469
};
470

    
471
static QemuOptsList qemu_add_fd_opts = {
472
    .name = "add-fd",
473
    .head = QTAILQ_HEAD_INITIALIZER(qemu_add_fd_opts.head),
474
    .desc = {
475
        {
476
            .name = "fd",
477
            .type = QEMU_OPT_NUMBER,
478
            .help = "file descriptor of which a duplicate is added to fd set",
479
        },{
480
            .name = "set",
481
            .type = QEMU_OPT_NUMBER,
482
            .help = "ID of the fd set to add fd to",
483
        },{
484
            .name = "opaque",
485
            .type = QEMU_OPT_STRING,
486
            .help = "free-form string used to describe fd",
487
        },
488
        { /* end of list */ }
489
    },
490
};
491

    
492
static QemuOptsList qemu_object_opts = {
493
    .name = "object",
494
    .implied_opt_name = "qom-type",
495
    .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
496
    .desc = {
497
        { }
498
    },
499
};
500

    
501
static QemuOptsList qemu_tpmdev_opts = {
502
    .name = "tpmdev",
503
    .implied_opt_name = "type",
504
    .head = QTAILQ_HEAD_INITIALIZER(qemu_tpmdev_opts.head),
505
    .desc = {
506
        /* options are defined in the TPM backends */
507
        { /* end of list */ }
508
    },
509
};
510

    
511
static QemuOptsList qemu_realtime_opts = {
512
    .name = "realtime",
513
    .head = QTAILQ_HEAD_INITIALIZER(qemu_realtime_opts.head),
514
    .desc = {
515
        {
516
            .name = "mlock",
517
            .type = QEMU_OPT_BOOL,
518
        },
519
        { /* end of list */ }
520
    },
521
};
522

    
523
static QemuOptsList qemu_msg_opts = {
524
    .name = "msg",
525
    .head = QTAILQ_HEAD_INITIALIZER(qemu_msg_opts.head),
526
    .desc = {
527
        {
528
            .name = "timestamp",
529
            .type = QEMU_OPT_BOOL,
530
        },
531
        { /* end of list */ }
532
    },
533
};
534

    
535
/**
536
 * Get machine options
537
 *
538
 * Returns: machine options (never null).
539
 */
540
QemuOpts *qemu_get_machine_opts(void)
541
{
542
    QemuOptsList *list;
543
    QemuOpts *opts;
544

    
545
    list = qemu_find_opts("machine");
546
    assert(list);
547
    opts = qemu_opts_find(list, NULL);
548
    if (!opts) {
549
        opts = qemu_opts_create(list, NULL, 0, &error_abort);
550
    }
551
    return opts;
552
}
553

    
554
const char *qemu_get_vm_name(void)
555
{
556
    return qemu_name;
557
}
558

    
559
static void res_free(void)
560
{
561
    if (boot_splash_filedata != NULL) {
562
        g_free(boot_splash_filedata);
563
        boot_splash_filedata = NULL;
564
    }
565
}
566

    
567
static int default_driver_check(QemuOpts *opts, void *opaque)
568
{
569
    const char *driver = qemu_opt_get(opts, "driver");
570
    int i;
571

    
572
    if (!driver)
573
        return 0;
574
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
575
        if (strcmp(default_list[i].driver, driver) != 0)
576
            continue;
577
        *(default_list[i].flag) = 0;
578
    }
579
    return 0;
580
}
581

    
582
/***********************************************************/
583
/* QEMU state */
584

    
585
static RunState current_run_state = RUN_STATE_PRELAUNCH;
586

    
587
typedef struct {
588
    RunState from;
589
    RunState to;
590
} RunStateTransition;
591

    
592
static const RunStateTransition runstate_transitions_def[] = {
593
    /*     from      ->     to      */
594
    { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
595
    { RUN_STATE_DEBUG, RUN_STATE_FINISH_MIGRATE },
596

    
597
    { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
598
    { RUN_STATE_INMIGRATE, RUN_STATE_PAUSED },
599

    
600
    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
601
    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
602

    
603
    { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
604
    { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
605

    
606
    { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
607
    { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
608

    
609
    { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
610
    { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
611

    
612
    { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
613
    { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
614
    { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
615

    
616
    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_RUNNING },
617
    { RUN_STATE_FINISH_MIGRATE, RUN_STATE_POSTMIGRATE },
618

    
619
    { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
620

    
621
    { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
622
    { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
623
    { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
624
    { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
625
    { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
626
    { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
627
    { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
628
    { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
629
    { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
630
    { RUN_STATE_RUNNING, RUN_STATE_GUEST_PANICKED },
631

    
632
    { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
633

    
634
    { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
635
    { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
636

    
637
    { RUN_STATE_DEBUG, RUN_STATE_SUSPENDED },
638
    { RUN_STATE_RUNNING, RUN_STATE_SUSPENDED },
639
    { RUN_STATE_SUSPENDED, RUN_STATE_RUNNING },
640
    { RUN_STATE_SUSPENDED, RUN_STATE_FINISH_MIGRATE },
641

    
642
    { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
643
    { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
644

    
645
    { RUN_STATE_GUEST_PANICKED, RUN_STATE_RUNNING },
646
    { RUN_STATE_GUEST_PANICKED, RUN_STATE_FINISH_MIGRATE },
647

    
648
    { RUN_STATE_MAX, RUN_STATE_MAX },
649
};
650

    
651
static bool runstate_valid_transitions[RUN_STATE_MAX][RUN_STATE_MAX];
652

    
653
bool runstate_check(RunState state)
654
{
655
    return current_run_state == state;
656
}
657

    
658
static void runstate_init(void)
659
{
660
    const RunStateTransition *p;
661

    
662
    memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
663

    
664
    for (p = &runstate_transitions_def[0]; p->from != RUN_STATE_MAX; p++) {
665
        runstate_valid_transitions[p->from][p->to] = true;
666
    }
667
}
668

    
669
/* This function will abort() on invalid state transitions */
670
void runstate_set(RunState new_state)
671
{
672
    assert(new_state < RUN_STATE_MAX);
673

    
674
    if (!runstate_valid_transitions[current_run_state][new_state]) {
675
        fprintf(stderr, "ERROR: invalid runstate transition: '%s' -> '%s'\n",
676
                RunState_lookup[current_run_state],
677
                RunState_lookup[new_state]);
678
        abort();
679
    }
680
    trace_runstate_set(new_state);
681
    current_run_state = new_state;
682
}
683

    
684
int runstate_is_running(void)
685
{
686
    return runstate_check(RUN_STATE_RUNNING);
687
}
688

    
689
bool runstate_needs_reset(void)
690
{
691
    return runstate_check(RUN_STATE_INTERNAL_ERROR) ||
692
        runstate_check(RUN_STATE_SHUTDOWN);
693
}
694

    
695
StatusInfo *qmp_query_status(Error **errp)
696
{
697
    StatusInfo *info = g_malloc0(sizeof(*info));
698

    
699
    info->running = runstate_is_running();
700
    info->singlestep = singlestep;
701
    info->status = current_run_state;
702

    
703
    return info;
704
}
705

    
706
/***********************************************************/
707
/* real time host monotonic timer */
708

    
709
/***********************************************************/
710
/* host time/date access */
711
void qemu_get_timedate(struct tm *tm, int offset)
712
{
713
    time_t ti;
714

    
715
    time(&ti);
716
    ti += offset;
717
    if (rtc_date_offset == -1) {
718
        if (rtc_utc)
719
            gmtime_r(&ti, tm);
720
        else
721
            localtime_r(&ti, tm);
722
    } else {
723
        ti -= rtc_date_offset;
724
        gmtime_r(&ti, tm);
725
    }
726
}
727

    
728
int qemu_timedate_diff(struct tm *tm)
729
{
730
    time_t seconds;
731

    
732
    if (rtc_date_offset == -1)
733
        if (rtc_utc)
734
            seconds = mktimegm(tm);
735
        else {
736
            struct tm tmp = *tm;
737
            tmp.tm_isdst = -1; /* use timezone to figure it out */
738
            seconds = mktime(&tmp);
739
        }
740
    else
741
        seconds = mktimegm(tm) + rtc_date_offset;
742

    
743
    return seconds - time(NULL);
744
}
745

    
746
void rtc_change_mon_event(struct tm *tm)
747
{
748
    QObject *data;
749

    
750
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
751
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
752
    qobject_decref(data);
753
}
754

    
755
static void configure_rtc_date_offset(const char *startdate, int legacy)
756
{
757
    time_t rtc_start_date;
758
    struct tm tm;
759

    
760
    if (!strcmp(startdate, "now") && legacy) {
761
        rtc_date_offset = -1;
762
    } else {
763
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
764
                   &tm.tm_year,
765
                   &tm.tm_mon,
766
                   &tm.tm_mday,
767
                   &tm.tm_hour,
768
                   &tm.tm_min,
769
                   &tm.tm_sec) == 6) {
770
            /* OK */
771
        } else if (sscanf(startdate, "%d-%d-%d",
772
                          &tm.tm_year,
773
                          &tm.tm_mon,
774
                          &tm.tm_mday) == 3) {
775
            tm.tm_hour = 0;
776
            tm.tm_min = 0;
777
            tm.tm_sec = 0;
778
        } else {
779
            goto date_fail;
780
        }
781
        tm.tm_year -= 1900;
782
        tm.tm_mon--;
783
        rtc_start_date = mktimegm(&tm);
784
        if (rtc_start_date == -1) {
785
        date_fail:
786
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
787
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
788
            exit(1);
789
        }
790
        rtc_date_offset = time(NULL) - rtc_start_date;
791
    }
792
}
793

    
794
static void configure_rtc(QemuOpts *opts)
795
{
796
    const char *value;
797

    
798
    value = qemu_opt_get(opts, "base");
799
    if (value) {
800
        if (!strcmp(value, "utc")) {
801
            rtc_utc = 1;
802
        } else if (!strcmp(value, "localtime")) {
803
            rtc_utc = 0;
804
        } else {
805
            configure_rtc_date_offset(value, 0);
806
        }
807
    }
808
    value = qemu_opt_get(opts, "clock");
809
    if (value) {
810
        if (!strcmp(value, "host")) {
811
            rtc_clock = QEMU_CLOCK_HOST;
812
        } else if (!strcmp(value, "rt")) {
813
            rtc_clock = QEMU_CLOCK_REALTIME;
814
        } else if (!strcmp(value, "vm")) {
815
            rtc_clock = QEMU_CLOCK_VIRTUAL;
816
        } else {
817
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
818
            exit(1);
819
        }
820
    }
821
    value = qemu_opt_get(opts, "driftfix");
822
    if (value) {
823
        if (!strcmp(value, "slew")) {
824
            static GlobalProperty slew_lost_ticks[] = {
825
                {
826
                    .driver   = "mc146818rtc",
827
                    .property = "lost_tick_policy",
828
                    .value    = "slew",
829
                },
830
                { /* end of list */ }
831
            };
832

    
833
            qdev_prop_register_global_list(slew_lost_ticks);
834
        } else if (!strcmp(value, "none")) {
835
            /* discard is default */
836
        } else {
837
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
838
            exit(1);
839
        }
840
    }
841
}
842

    
843
/***********************************************************/
844
/* Bluetooth support */
845
static int nb_hcis;
846
static int cur_hci;
847
static struct HCIInfo *hci_table[MAX_NICS];
848

    
849
struct HCIInfo *qemu_next_hci(void)
850
{
851
    if (cur_hci == nb_hcis)
852
        return &null_hci;
853

    
854
    return hci_table[cur_hci++];
855
}
856

    
857
static int bt_hci_parse(const char *str)
858
{
859
    struct HCIInfo *hci;
860
    bdaddr_t bdaddr;
861

    
862
    if (nb_hcis >= MAX_NICS) {
863
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
864
        return -1;
865
    }
866

    
867
    hci = hci_init(str);
868
    if (!hci)
869
        return -1;
870

    
871
    bdaddr.b[0] = 0x52;
872
    bdaddr.b[1] = 0x54;
873
    bdaddr.b[2] = 0x00;
874
    bdaddr.b[3] = 0x12;
875
    bdaddr.b[4] = 0x34;
876
    bdaddr.b[5] = 0x56 + nb_hcis;
877
    hci->bdaddr_set(hci, bdaddr.b);
878

    
879
    hci_table[nb_hcis++] = hci;
880

    
881
    return 0;
882
}
883

    
884
static void bt_vhci_add(int vlan_id)
885
{
886
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
887

    
888
    if (!vlan->slave)
889
        fprintf(stderr, "qemu: warning: adding a VHCI to "
890
                        "an empty scatternet %i\n", vlan_id);
891

    
892
    bt_vhci_init(bt_new_hci(vlan));
893
}
894

    
895
static struct bt_device_s *bt_device_add(const char *opt)
896
{
897
    struct bt_scatternet_s *vlan;
898
    int vlan_id = 0;
899
    char *endp = strstr(opt, ",vlan=");
900
    int len = (endp ? endp - opt : strlen(opt)) + 1;
901
    char devname[10];
902

    
903
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
904

    
905
    if (endp) {
906
        vlan_id = strtol(endp + 6, &endp, 0);
907
        if (*endp) {
908
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
909
            return 0;
910
        }
911
    }
912

    
913
    vlan = qemu_find_bt_vlan(vlan_id);
914

    
915
    if (!vlan->slave)
916
        fprintf(stderr, "qemu: warning: adding a slave device to "
917
                        "an empty scatternet %i\n", vlan_id);
918

    
919
    if (!strcmp(devname, "keyboard"))
920
        return bt_keyboard_init(vlan);
921

    
922
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
923
    return 0;
924
}
925

    
926
static int bt_parse(const char *opt)
927
{
928
    const char *endp, *p;
929
    int vlan;
930

    
931
    if (strstart(opt, "hci", &endp)) {
932
        if (!*endp || *endp == ',') {
933
            if (*endp)
934
                if (!strstart(endp, ",vlan=", 0))
935
                    opt = endp + 1;
936

    
937
            return bt_hci_parse(opt);
938
       }
939
    } else if (strstart(opt, "vhci", &endp)) {
940
        if (!*endp || *endp == ',') {
941
            if (*endp) {
942
                if (strstart(endp, ",vlan=", &p)) {
943
                    vlan = strtol(p, (char **) &endp, 0);
944
                    if (*endp) {
945
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
946
                        return 1;
947
                    }
948
                } else {
949
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
950
                    return 1;
951
                }
952
            } else
953
                vlan = 0;
954

    
955
            bt_vhci_add(vlan);
956
            return 0;
957
        }
958
    } else if (strstart(opt, "device:", &endp))
959
        return !bt_device_add(endp);
960

    
961
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
962
    return 1;
963
}
964

    
965
static int parse_sandbox(QemuOpts *opts, void *opaque)
966
{
967
    /* FIXME: change this to true for 1.3 */
968
    if (qemu_opt_get_bool(opts, "enable", false)) {
969
#ifdef CONFIG_SECCOMP
970
        if (seccomp_start() < 0) {
971
            qerror_report(ERROR_CLASS_GENERIC_ERROR,
972
                          "failed to install seccomp syscall filter in the kernel");
973
            return -1;
974
        }
975
#else
976
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
977
                      "sandboxing request but seccomp is not compiled into this build");
978
        return -1;
979
#endif
980
    }
981

    
982
    return 0;
983
}
984

    
985
bool usb_enabled(bool default_usb)
986
{
987
    return qemu_opt_get_bool(qemu_get_machine_opts(), "usb", default_usb);
988
}
989

    
990
#ifndef _WIN32
991
static int parse_add_fd(QemuOpts *opts, void *opaque)
992
{
993
    int fd, dupfd, flags;
994
    int64_t fdset_id;
995
    const char *fd_opaque = NULL;
996

    
997
    fd = qemu_opt_get_number(opts, "fd", -1);
998
    fdset_id = qemu_opt_get_number(opts, "set", -1);
999
    fd_opaque = qemu_opt_get(opts, "opaque");
1000

    
1001
    if (fd < 0) {
1002
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
1003
                      "fd option is required and must be non-negative");
1004
        return -1;
1005
    }
1006

    
1007
    if (fd <= STDERR_FILENO) {
1008
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
1009
                      "fd cannot be a standard I/O stream");
1010
        return -1;
1011
    }
1012

    
1013
    /*
1014
     * All fds inherited across exec() necessarily have FD_CLOEXEC
1015
     * clear, while qemu sets FD_CLOEXEC on all other fds used internally.
1016
     */
1017
    flags = fcntl(fd, F_GETFD);
1018
    if (flags == -1 || (flags & FD_CLOEXEC)) {
1019
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
1020
                      "fd is not valid or already in use");
1021
        return -1;
1022
    }
1023

    
1024
    if (fdset_id < 0) {
1025
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
1026
                      "set option is required and must be non-negative");
1027
        return -1;
1028
    }
1029

    
1030
#ifdef F_DUPFD_CLOEXEC
1031
    dupfd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
1032
#else
1033
    dupfd = dup(fd);
1034
    if (dupfd != -1) {
1035
        qemu_set_cloexec(dupfd);
1036
    }
1037
#endif
1038
    if (dupfd == -1) {
1039
        qerror_report(ERROR_CLASS_GENERIC_ERROR,
1040
                      "Error duplicating fd: %s", strerror(errno));
1041
        return -1;
1042
    }
1043

    
1044
    /* add the duplicate fd, and optionally the opaque string, to the fd set */
1045
    monitor_fdset_add_fd(dupfd, true, fdset_id, fd_opaque ? true : false,
1046
                         fd_opaque, NULL);
1047

    
1048
    return 0;
1049
}
1050

    
1051
static int cleanup_add_fd(QemuOpts *opts, void *opaque)
1052
{
1053
    int fd;
1054

    
1055
    fd = qemu_opt_get_number(opts, "fd", -1);
1056
    close(fd);
1057

    
1058
    return 0;
1059
}
1060
#endif
1061

    
1062
/***********************************************************/
1063
/* QEMU Block devices */
1064

    
1065
#define HD_OPTS "media=disk"
1066
#define CDROM_OPTS "media=cdrom"
1067
#define FD_OPTS ""
1068
#define PFLASH_OPTS ""
1069
#define MTD_OPTS ""
1070
#define SD_OPTS ""
1071

    
1072
static int drive_init_func(QemuOpts *opts, void *opaque)
1073
{
1074
    BlockInterfaceType *block_default_type = opaque;
1075

    
1076
    return drive_init(opts, *block_default_type) == NULL;
1077
}
1078

    
1079
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1080
{
1081
    if (NULL == qemu_opt_get(opts, "snapshot")) {
1082
        qemu_opt_set(opts, "snapshot", "on");
1083
    }
1084
    return 0;
1085
}
1086

    
1087
static void default_drive(int enable, int snapshot, BlockInterfaceType type,
1088
                          int index, const char *optstr)
1089
{
1090
    QemuOpts *opts;
1091

    
1092
    if (!enable || drive_get_by_index(type, index)) {
1093
        return;
1094
    }
1095

    
1096
    opts = drive_add(type, index, NULL, optstr);
1097
    if (snapshot) {
1098
        drive_enable_snapshot(opts, NULL);
1099
    }
1100
    if (!drive_init(opts, type)) {
1101
        exit(1);
1102
    }
1103
}
1104

    
1105
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1106
{
1107
    boot_set_handler = func;
1108
    boot_set_opaque = opaque;
1109
}
1110

    
1111
int qemu_boot_set(const char *boot_order)
1112
{
1113
    if (!boot_set_handler) {
1114
        return -EINVAL;
1115
    }
1116
    return boot_set_handler(boot_set_opaque, boot_order);
1117
}
1118

    
1119
static void validate_bootdevices(const char *devices)
1120
{
1121
    /* We just do some generic consistency checks */
1122
    const char *p;
1123
    int bitmap = 0;
1124

    
1125
    for (p = devices; *p != '\0'; p++) {
1126
        /* Allowed boot devices are:
1127
         * a-b: floppy disk drives
1128
         * c-f: IDE disk drives
1129
         * g-m: machine implementation dependent drives
1130
         * n-p: network devices
1131
         * It's up to each machine implementation to check if the given boot
1132
         * devices match the actual hardware implementation and firmware
1133
         * features.
1134
         */
1135
        if (*p < 'a' || *p > 'p') {
1136
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
1137
            exit(1);
1138
        }
1139
        if (bitmap & (1 << (*p - 'a'))) {
1140
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1141
            exit(1);
1142
        }
1143
        bitmap |= 1 << (*p - 'a');
1144
    }
1145
}
1146

    
1147
static void restore_boot_order(void *opaque)
1148
{
1149
    char *normal_boot_order = opaque;
1150
    static int first = 1;
1151

    
1152
    /* Restore boot order and remove ourselves after the first boot */
1153
    if (first) {
1154
        first = 0;
1155
        return;
1156
    }
1157

    
1158
    qemu_boot_set(normal_boot_order);
1159

    
1160
    qemu_unregister_reset(restore_boot_order, normal_boot_order);
1161
    g_free(normal_boot_order);
1162
}
1163

    
1164
void add_boot_device_path(int32_t bootindex, DeviceState *dev,
1165
                          const char *suffix)
1166
{
1167
    FWBootEntry *node, *i;
1168

    
1169
    if (bootindex < 0) {
1170
        return;
1171
    }
1172

    
1173
    assert(dev != NULL || suffix != NULL);
1174

    
1175
    node = g_malloc0(sizeof(FWBootEntry));
1176
    node->bootindex = bootindex;
1177
    node->suffix = g_strdup(suffix);
1178
    node->dev = dev;
1179

    
1180
    QTAILQ_FOREACH(i, &fw_boot_order, link) {
1181
        if (i->bootindex == bootindex) {
1182
            fprintf(stderr, "Two devices with same boot index %d\n", bootindex);
1183
            exit(1);
1184
        } else if (i->bootindex < bootindex) {
1185
            continue;
1186
        }
1187
        QTAILQ_INSERT_BEFORE(i, node, link);
1188
        return;
1189
    }
1190
    QTAILQ_INSERT_TAIL(&fw_boot_order, node, link);
1191
}
1192

    
1193
DeviceState *get_boot_device(uint32_t position)
1194
{
1195
    uint32_t counter = 0;
1196
    FWBootEntry *i = NULL;
1197
    DeviceState *res = NULL;
1198

    
1199
    if (!QTAILQ_EMPTY(&fw_boot_order)) {
1200
        QTAILQ_FOREACH(i, &fw_boot_order, link) {
1201
            if (counter == position) {
1202
                res = i->dev;
1203
                break;
1204
            }
1205
            counter++;
1206
        }
1207
    }
1208
    return res;
1209
}
1210

    
1211
/*
1212
 * This function returns null terminated string that consist of new line
1213
 * separated device paths.
1214
 *
1215
 * memory pointed by "size" is assigned total length of the array in bytes
1216
 *
1217
 */
1218
char *get_boot_devices_list(size_t *size)
1219
{
1220
    FWBootEntry *i;
1221
    size_t total = 0;
1222
    char *list = NULL;
1223

    
1224
    QTAILQ_FOREACH(i, &fw_boot_order, link) {
1225
        char *devpath = NULL, *bootpath;
1226
        size_t len;
1227

    
1228
        if (i->dev) {
1229
            devpath = qdev_get_fw_dev_path(i->dev);
1230
            assert(devpath);
1231
        }
1232

    
1233
        if (i->suffix && devpath) {
1234
            size_t bootpathlen = strlen(devpath) + strlen(i->suffix) + 1;
1235

    
1236
            bootpath = g_malloc(bootpathlen);
1237
            snprintf(bootpath, bootpathlen, "%s%s", devpath, i->suffix);
1238
            g_free(devpath);
1239
        } else if (devpath) {
1240
            bootpath = devpath;
1241
        } else {
1242
            assert(i->suffix);
1243
            bootpath = g_strdup(i->suffix);
1244
        }
1245

    
1246
        if (total) {
1247
            list[total-1] = '\n';
1248
        }
1249
        len = strlen(bootpath) + 1;
1250
        list = g_realloc(list, total + len);
1251
        memcpy(&list[total], bootpath, len);
1252
        total += len;
1253
        g_free(bootpath);
1254
    }
1255

    
1256
    *size = total;
1257

    
1258
    if (boot_strict && *size > 0) {
1259
        list[total-1] = '\n';
1260
        list = g_realloc(list, total + 5);
1261
        memcpy(&list[total], "HALT", 5);
1262
        *size = total + 5;
1263
    }
1264
    return list;
1265
}
1266

    
1267
static void numa_node_parse_cpus(int nodenr, const char *cpus)
1268
{
1269
    char *endptr;
1270
    unsigned long long value, endvalue;
1271

    
1272
    /* Empty CPU range strings will be considered valid, they will simply
1273
     * not set any bit in the CPU bitmap.
1274
     */
1275
    if (!*cpus) {
1276
        return;
1277
    }
1278

    
1279
    if (parse_uint(cpus, &value, &endptr, 10) < 0) {
1280
        goto error;
1281
    }
1282
    if (*endptr == '-') {
1283
        if (parse_uint_full(endptr + 1, &endvalue, 10) < 0) {
1284
            goto error;
1285
        }
1286
    } else if (*endptr == '\0') {
1287
        endvalue = value;
1288
    } else {
1289
        goto error;
1290
    }
1291

    
1292
    if (endvalue >= MAX_CPUMASK_BITS) {
1293
        endvalue = MAX_CPUMASK_BITS - 1;
1294
        fprintf(stderr,
1295
            "qemu: NUMA: A max of %d VCPUs are supported\n",
1296
             MAX_CPUMASK_BITS);
1297
    }
1298

    
1299
    if (endvalue < value) {
1300
        goto error;
1301
    }
1302

    
1303
    bitmap_set(node_cpumask[nodenr], value, endvalue-value+1);
1304
    return;
1305

    
1306
error:
1307
    fprintf(stderr, "qemu: Invalid NUMA CPU range: %s\n", cpus);
1308
    exit(1);
1309
}
1310

    
1311
static void numa_add(const char *optarg)
1312
{
1313
    char option[128];
1314
    char *endptr;
1315
    unsigned long long nodenr;
1316

    
1317
    optarg = get_opt_name(option, 128, optarg, ',');
1318
    if (*optarg == ',') {
1319
        optarg++;
1320
    }
1321
    if (!strcmp(option, "node")) {
1322

    
1323
        if (nb_numa_nodes >= MAX_NODES) {
1324
            fprintf(stderr, "qemu: too many NUMA nodes\n");
1325
            exit(1);
1326
        }
1327

    
1328
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1329
            nodenr = nb_numa_nodes;
1330
        } else {
1331
            if (parse_uint_full(option, &nodenr, 10) < 0) {
1332
                fprintf(stderr, "qemu: Invalid NUMA nodeid: %s\n", option);
1333
                exit(1);
1334
            }
1335
        }
1336

    
1337
        if (nodenr >= MAX_NODES) {
1338
            fprintf(stderr, "qemu: invalid NUMA nodeid: %llu\n", nodenr);
1339
            exit(1);
1340
        }
1341

    
1342
        if (get_param_value(option, 128, "mem", optarg) == 0) {
1343
            node_mem[nodenr] = 0;
1344
        } else {
1345
            int64_t sval;
1346
            sval = strtosz(option, &endptr);
1347
            if (sval < 0 || *endptr) {
1348
                fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);
1349
                exit(1);
1350
            }
1351
            node_mem[nodenr] = sval;
1352
        }
1353
        if (get_param_value(option, 128, "cpus", optarg) != 0) {
1354
            numa_node_parse_cpus(nodenr, option);
1355
        }
1356
        nb_numa_nodes++;
1357
    } else {
1358
        fprintf(stderr, "Invalid -numa option: %s\n", option);
1359
        exit(1);
1360
    }
1361
}
1362

    
1363
static QemuOptsList qemu_smp_opts = {
1364
    .name = "smp-opts",
1365
    .implied_opt_name = "cpus",
1366
    .merge_lists = true,
1367
    .head = QTAILQ_HEAD_INITIALIZER(qemu_smp_opts.head),
1368
    .desc = {
1369
        {
1370
            .name = "cpus",
1371
            .type = QEMU_OPT_NUMBER,
1372
        }, {
1373
            .name = "sockets",
1374
            .type = QEMU_OPT_NUMBER,
1375
        }, {
1376
            .name = "cores",
1377
            .type = QEMU_OPT_NUMBER,
1378
        }, {
1379
            .name = "threads",
1380
            .type = QEMU_OPT_NUMBER,
1381
        }, {
1382
            .name = "maxcpus",
1383
            .type = QEMU_OPT_NUMBER,
1384
        },
1385
        { /*End of list */ }
1386
    },
1387
};
1388

    
1389
static void smp_parse(QemuOpts *opts)
1390
{
1391
    if (opts) {
1392

    
1393
        unsigned cpus    = qemu_opt_get_number(opts, "cpus", 0);
1394
        unsigned sockets = qemu_opt_get_number(opts, "sockets", 0);
1395
        unsigned cores   = qemu_opt_get_number(opts, "cores", 0);
1396
        unsigned threads = qemu_opt_get_number(opts, "threads", 0);
1397

    
1398
        /* compute missing values, prefer sockets over cores over threads */
1399
        if (cpus == 0 || sockets == 0) {
1400
            sockets = sockets > 0 ? sockets : 1;
1401
            cores = cores > 0 ? cores : 1;
1402
            threads = threads > 0 ? threads : 1;
1403
            if (cpus == 0) {
1404
                cpus = cores * threads * sockets;
1405
            }
1406
        } else {
1407
            if (cores == 0) {
1408
                threads = threads > 0 ? threads : 1;
1409
                cores = cpus / (sockets * threads);
1410
            } else {
1411
                threads = cpus / (cores * sockets);
1412
            }
1413
        }
1414

    
1415
        max_cpus = qemu_opt_get_number(opts, "maxcpus", 0);
1416

    
1417
        smp_cpus = cpus;
1418
        smp_cores = cores > 0 ? cores : 1;
1419
        smp_threads = threads > 0 ? threads : 1;
1420

    
1421
    }
1422

    
1423
    if (max_cpus == 0) {
1424
        max_cpus = smp_cpus;
1425
    }
1426

    
1427
    if (max_cpus > 255) {
1428
        fprintf(stderr, "Unsupported number of maxcpus\n");
1429
        exit(1);
1430
    }
1431
    if (max_cpus < smp_cpus) {
1432
        fprintf(stderr, "maxcpus must be equal to or greater than smp\n");
1433
        exit(1);
1434
    }
1435

    
1436
}
1437

    
1438
static void configure_realtime(QemuOpts *opts)
1439
{
1440
    bool enable_mlock;
1441

    
1442
    enable_mlock = qemu_opt_get_bool(opts, "mlock", true);
1443

    
1444
    if (enable_mlock) {
1445
        if (os_mlock() < 0) {
1446
            fprintf(stderr, "qemu: locking memory failed\n");
1447
            exit(1);
1448
        }
1449
    }
1450
}
1451

    
1452

    
1453
static void configure_msg(QemuOpts *opts)
1454
{
1455
    enable_timestamp_msg = qemu_opt_get_bool(opts, "timestamp", true);
1456
}
1457

    
1458
/***********************************************************/
1459
/* USB devices */
1460

    
1461
static int usb_device_add(const char *devname)
1462
{
1463
    USBDevice *dev = NULL;
1464
#ifndef CONFIG_LINUX
1465
    const char *p;
1466
#endif
1467

    
1468
    if (!usb_enabled(false)) {
1469
        return -1;
1470
    }
1471

    
1472
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1473
    dev = usbdevice_create(devname);
1474
    if (dev)
1475
        goto done;
1476

    
1477
    /* the other ones */
1478
#ifndef CONFIG_LINUX
1479
    /* only the linux version is qdev-ified, usb-bsd still needs this */
1480
    if (strstart(devname, "host:", &p)) {
1481
        dev = usb_host_device_open(usb_bus_find(-1), p);
1482
    }
1483
#endif
1484
    if (!dev)
1485
        return -1;
1486

    
1487
done:
1488
    return 0;
1489
}
1490

    
1491
static int usb_device_del(const char *devname)
1492
{
1493
    int bus_num, addr;
1494
    const char *p;
1495

    
1496
    if (strstart(devname, "host:", &p)) {
1497
        return -1;
1498
    }
1499

    
1500
    if (!usb_enabled(false)) {
1501
        return -1;
1502
    }
1503

    
1504
    p = strchr(devname, '.');
1505
    if (!p)
1506
        return -1;
1507
    bus_num = strtoul(devname, NULL, 0);
1508
    addr = strtoul(p + 1, NULL, 0);
1509

    
1510
    return usb_device_delete_addr(bus_num, addr);
1511
}
1512

    
1513
static int usb_parse(const char *cmdline)
1514
{
1515
    int r;
1516
    r = usb_device_add(cmdline);
1517
    if (r < 0) {
1518
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1519
    }
1520
    return r;
1521
}
1522

    
1523
void do_usb_add(Monitor *mon, const QDict *qdict)
1524
{
1525
    const char *devname = qdict_get_str(qdict, "devname");
1526
    if (usb_device_add(devname) < 0) {
1527
        error_report("could not add USB device '%s'", devname);
1528
    }
1529
}
1530

    
1531
void do_usb_del(Monitor *mon, const QDict *qdict)
1532
{
1533
    const char *devname = qdict_get_str(qdict, "devname");
1534
    if (usb_device_del(devname) < 0) {
1535
        error_report("could not delete USB device '%s'", devname);
1536
    }
1537
}
1538

    
1539
/***********************************************************/
1540
/* PCMCIA/Cardbus */
1541

    
1542
static struct pcmcia_socket_entry_s {
1543
    PCMCIASocket *socket;
1544
    struct pcmcia_socket_entry_s *next;
1545
} *pcmcia_sockets = 0;
1546

    
1547
void pcmcia_socket_register(PCMCIASocket *socket)
1548
{
1549
    struct pcmcia_socket_entry_s *entry;
1550

    
1551
    entry = g_malloc(sizeof(struct pcmcia_socket_entry_s));
1552
    entry->socket = socket;
1553
    entry->next = pcmcia_sockets;
1554
    pcmcia_sockets = entry;
1555
}
1556

    
1557
void pcmcia_socket_unregister(PCMCIASocket *socket)
1558
{
1559
    struct pcmcia_socket_entry_s *entry, **ptr;
1560

    
1561
    ptr = &pcmcia_sockets;
1562
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1563
        if (entry->socket == socket) {
1564
            *ptr = entry->next;
1565
            g_free(entry);
1566
        }
1567
}
1568

    
1569
void pcmcia_info(Monitor *mon, const QDict *qdict)
1570
{
1571
    struct pcmcia_socket_entry_s *iter;
1572

    
1573
    if (!pcmcia_sockets)
1574
        monitor_printf(mon, "No PCMCIA sockets\n");
1575

    
1576
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1577
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1578
                       iter->socket->attached ? iter->socket->card_string :
1579
                       "Empty");
1580
}
1581

    
1582
/***********************************************************/
1583
/* machine registration */
1584

    
1585
static QEMUMachine *first_machine = NULL;
1586
QEMUMachine *current_machine = NULL;
1587

    
1588
int qemu_register_machine(QEMUMachine *m)
1589
{
1590
    QEMUMachine **pm;
1591
    pm = &first_machine;
1592
    while (*pm != NULL)
1593
        pm = &(*pm)->next;
1594
    m->next = NULL;
1595
    *pm = m;
1596
    return 0;
1597
}
1598

    
1599
static QEMUMachine *find_machine(const char *name)
1600
{
1601
    QEMUMachine *m;
1602

    
1603
    for(m = first_machine; m != NULL; m = m->next) {
1604
        if (!strcmp(m->name, name))
1605
            return m;
1606
        if (m->alias && !strcmp(m->alias, name))
1607
            return m;
1608
    }
1609
    return NULL;
1610
}
1611

    
1612
QEMUMachine *find_default_machine(void)
1613
{
1614
    QEMUMachine *m;
1615

    
1616
    for(m = first_machine; m != NULL; m = m->next) {
1617
        if (m->is_default) {
1618
            return m;
1619
        }
1620
    }
1621
    return NULL;
1622
}
1623

    
1624
MachineInfoList *qmp_query_machines(Error **errp)
1625
{
1626
    MachineInfoList *mach_list = NULL;
1627
    QEMUMachine *m;
1628

    
1629
    for (m = first_machine; m; m = m->next) {
1630
        MachineInfoList *entry;
1631
        MachineInfo *info;
1632

    
1633
        info = g_malloc0(sizeof(*info));
1634
        if (m->is_default) {
1635
            info->has_is_default = true;
1636
            info->is_default = true;
1637
        }
1638

    
1639
        if (m->alias) {
1640
            info->has_alias = true;
1641
            info->alias = g_strdup(m->alias);
1642
        }
1643

    
1644
        info->name = g_strdup(m->name);
1645
        info->cpu_max = !m->max_cpus ? 1 : m->max_cpus;
1646

    
1647
        entry = g_malloc0(sizeof(*entry));
1648
        entry->value = info;
1649
        entry->next = mach_list;
1650
        mach_list = entry;
1651
    }
1652

    
1653
    return mach_list;
1654
}
1655

    
1656
/***********************************************************/
1657
/* main execution loop */
1658

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

    
1665
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1666

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

    
1672
    e = g_malloc0(sizeof (*e));
1673

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

    
1680
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1681
{
1682
    QLIST_REMOVE (e, entries);
1683
    g_free (e);
1684
}
1685

    
1686
void vm_state_notify(int running, RunState state)
1687
{
1688
    VMChangeStateEntry *e;
1689

    
1690
    trace_vm_state_notify(running, state);
1691

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

    
1697
void vm_start(void)
1698
{
1699
    if (!runstate_is_running()) {
1700
        cpu_enable_ticks();
1701
        runstate_set(RUN_STATE_RUNNING);
1702
        vm_state_notify(1, RUN_STATE_RUNNING);
1703
        resume_all_vcpus();
1704
        monitor_protocol_event(QEVENT_RESUME, NULL);
1705
    }
1706
}
1707

    
1708
/* reset/shutdown handler */
1709

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

    
1716
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1717
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1718
static int reset_requested;
1719
static int shutdown_requested, shutdown_signal = -1;
1720
static pid_t shutdown_pid;
1721
static int powerdown_requested;
1722
static int debug_requested;
1723
static int suspend_requested;
1724
static WakeupReason wakeup_reason;
1725
static NotifierList powerdown_notifiers =
1726
    NOTIFIER_LIST_INITIALIZER(powerdown_notifiers);
1727
static NotifierList suspend_notifiers =
1728
    NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1729
static NotifierList wakeup_notifiers =
1730
    NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1731
static uint32_t wakeup_reason_mask = ~(1 << QEMU_WAKEUP_REASON_NONE);
1732
static RunState vmstop_requested = RUN_STATE_MAX;
1733

    
1734
int qemu_shutdown_requested_get(void)
1735
{
1736
    return shutdown_requested;
1737
}
1738

    
1739
int qemu_reset_requested_get(void)
1740
{
1741
    return reset_requested;
1742
}
1743

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

    
1751
static void qemu_kill_report(void)
1752
{
1753
    if (!qtest_driver() && shutdown_signal != -1) {
1754
        fprintf(stderr, "qemu: terminating on signal %d", shutdown_signal);
1755
        if (shutdown_pid == 0) {
1756
            /* This happens for eg ^C at the terminal, so it's worth
1757
             * avoiding printing an odd message in that case.
1758
             */
1759
            fputc('\n', stderr);
1760
        } else {
1761
            fprintf(stderr, " from pid " FMT_pid "\n", shutdown_pid);
1762
        }
1763
        shutdown_signal = -1;
1764
    }
1765
}
1766

    
1767
static int qemu_reset_requested(void)
1768
{
1769
    int r = reset_requested;
1770
    reset_requested = 0;
1771
    return r;
1772
}
1773

    
1774
static int qemu_suspend_requested(void)
1775
{
1776
    int r = suspend_requested;
1777
    suspend_requested = 0;
1778
    return r;
1779
}
1780

    
1781
static WakeupReason qemu_wakeup_requested(void)
1782
{
1783
    return wakeup_reason;
1784
}
1785

    
1786
static int qemu_powerdown_requested(void)
1787
{
1788
    int r = powerdown_requested;
1789
    powerdown_requested = 0;
1790
    return r;
1791
}
1792

    
1793
static int qemu_debug_requested(void)
1794
{
1795
    int r = debug_requested;
1796
    debug_requested = 0;
1797
    return r;
1798
}
1799

    
1800
/* We use RUN_STATE_MAX but any invalid value will do */
1801
static bool qemu_vmstop_requested(RunState *r)
1802
{
1803
    if (vmstop_requested < RUN_STATE_MAX) {
1804
        *r = vmstop_requested;
1805
        vmstop_requested = RUN_STATE_MAX;
1806
        return true;
1807
    }
1808

    
1809
    return false;
1810
}
1811

    
1812
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1813
{
1814
    QEMUResetEntry *re = g_malloc0(sizeof(QEMUResetEntry));
1815

    
1816
    re->func = func;
1817
    re->opaque = opaque;
1818
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1819
}
1820

    
1821
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1822
{
1823
    QEMUResetEntry *re;
1824

    
1825
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1826
        if (re->func == func && re->opaque == opaque) {
1827
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1828
            g_free(re);
1829
            return;
1830
        }
1831
    }
1832
}
1833

    
1834
void qemu_devices_reset(void)
1835
{
1836
    QEMUResetEntry *re, *nre;
1837

    
1838
    /* reset all devices */
1839
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1840
        re->func(re->opaque);
1841
    }
1842
}
1843

    
1844
void qemu_system_reset(bool report)
1845
{
1846
    if (current_machine && current_machine->reset) {
1847
        current_machine->reset();
1848
    } else {
1849
        qemu_devices_reset();
1850
    }
1851
    if (report) {
1852
        monitor_protocol_event(QEVENT_RESET, NULL);
1853
    }
1854
    cpu_synchronize_all_post_reset();
1855
}
1856

    
1857
void qemu_system_reset_request(void)
1858
{
1859
    if (no_reboot) {
1860
        shutdown_requested = 1;
1861
    } else {
1862
        reset_requested = 1;
1863
    }
1864
    cpu_stop_current();
1865
    qemu_notify_event();
1866
}
1867

    
1868
static void qemu_system_suspend(void)
1869
{
1870
    pause_all_vcpus();
1871
    notifier_list_notify(&suspend_notifiers, NULL);
1872
    runstate_set(RUN_STATE_SUSPENDED);
1873
    monitor_protocol_event(QEVENT_SUSPEND, NULL);
1874
}
1875

    
1876
void qemu_system_suspend_request(void)
1877
{
1878
    if (runstate_check(RUN_STATE_SUSPENDED)) {
1879
        return;
1880
    }
1881
    suspend_requested = 1;
1882
    cpu_stop_current();
1883
    qemu_notify_event();
1884
}
1885

    
1886
void qemu_register_suspend_notifier(Notifier *notifier)
1887
{
1888
    notifier_list_add(&suspend_notifiers, notifier);
1889
}
1890

    
1891
void qemu_system_wakeup_request(WakeupReason reason)
1892
{
1893
    if (!runstate_check(RUN_STATE_SUSPENDED)) {
1894
        return;
1895
    }
1896
    if (!(wakeup_reason_mask & (1 << reason))) {
1897
        return;
1898
    }
1899
    runstate_set(RUN_STATE_RUNNING);
1900
    wakeup_reason = reason;
1901
    qemu_notify_event();
1902
}
1903

    
1904
void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1905
{
1906
    if (enabled) {
1907
        wakeup_reason_mask |= (1 << reason);
1908
    } else {
1909
        wakeup_reason_mask &= ~(1 << reason);
1910
    }
1911
}
1912

    
1913
void qemu_register_wakeup_notifier(Notifier *notifier)
1914
{
1915
    notifier_list_add(&wakeup_notifiers, notifier);
1916
}
1917

    
1918
void qemu_system_killed(int signal, pid_t pid)
1919
{
1920
    shutdown_signal = signal;
1921
    shutdown_pid = pid;
1922
    no_shutdown = 0;
1923
    qemu_system_shutdown_request();
1924
}
1925

    
1926
void qemu_system_shutdown_request(void)
1927
{
1928
    shutdown_requested = 1;
1929
    qemu_notify_event();
1930
}
1931

    
1932
static void qemu_system_powerdown(void)
1933
{
1934
    monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1935
    notifier_list_notify(&powerdown_notifiers, NULL);
1936
}
1937

    
1938
void qemu_system_powerdown_request(void)
1939
{
1940
    powerdown_requested = 1;
1941
    qemu_notify_event();
1942
}
1943

    
1944
void qemu_register_powerdown_notifier(Notifier *notifier)
1945
{
1946
    notifier_list_add(&powerdown_notifiers, notifier);
1947
}
1948

    
1949
void qemu_system_debug_request(void)
1950
{
1951
    debug_requested = 1;
1952
    qemu_notify_event();
1953
}
1954

    
1955
void qemu_system_vmstop_request(RunState state)
1956
{
1957
    vmstop_requested = state;
1958
    qemu_notify_event();
1959
}
1960

    
1961
static bool main_loop_should_exit(void)
1962
{
1963
    RunState r;
1964
    if (qemu_debug_requested()) {
1965
        vm_stop(RUN_STATE_DEBUG);
1966
    }
1967
    if (qemu_suspend_requested()) {
1968
        qemu_system_suspend();
1969
    }
1970
    if (qemu_shutdown_requested()) {
1971
        qemu_kill_report();
1972
        monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1973
        if (no_shutdown) {
1974
            vm_stop(RUN_STATE_SHUTDOWN);
1975
        } else {
1976
            return true;
1977
        }
1978
    }
1979
    if (qemu_reset_requested()) {
1980
        pause_all_vcpus();
1981
        cpu_synchronize_all_states();
1982
        qemu_system_reset(VMRESET_REPORT);
1983
        resume_all_vcpus();
1984
        if (runstate_needs_reset()) {
1985
            runstate_set(RUN_STATE_PAUSED);
1986
        }
1987
    }
1988
    if (qemu_wakeup_requested()) {
1989
        pause_all_vcpus();
1990
        cpu_synchronize_all_states();
1991
        qemu_system_reset(VMRESET_SILENT);
1992
        notifier_list_notify(&wakeup_notifiers, &wakeup_reason);
1993
        wakeup_reason = QEMU_WAKEUP_REASON_NONE;
1994
        resume_all_vcpus();
1995
        monitor_protocol_event(QEVENT_WAKEUP, NULL);
1996
    }
1997
    if (qemu_powerdown_requested()) {
1998
        qemu_system_powerdown();
1999
    }
2000
    if (qemu_vmstop_requested(&r)) {
2001
        vm_stop(r);
2002
    }
2003
    return false;
2004
}
2005

    
2006
static void main_loop(void)
2007
{
2008
    bool nonblocking;
2009
    int last_io = 0;
2010
#ifdef CONFIG_PROFILER
2011
    int64_t ti;
2012
#endif
2013
    do {
2014
        nonblocking = !kvm_enabled() && !xen_enabled() && last_io > 0;
2015
#ifdef CONFIG_PROFILER
2016
        ti = profile_getclock();
2017
#endif
2018
        last_io = main_loop_wait(nonblocking);
2019
#ifdef CONFIG_PROFILER
2020
        dev_time += profile_getclock() - ti;
2021
#endif
2022
    } while (!main_loop_should_exit());
2023
}
2024

    
2025
static void version(void)
2026
{
2027
    printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
2028
}
2029

    
2030
static void help(int exitcode)
2031
{
2032
    version();
2033
    printf("usage: %s [options] [disk_image]\n\n"
2034
           "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
2035
            error_get_progname());
2036

    
2037
#define QEMU_OPTIONS_GENERATE_HELP
2038
#include "qemu-options-wrapper.h"
2039

    
2040
    printf("\nDuring emulation, the following keys are useful:\n"
2041
           "ctrl-alt-f      toggle full screen\n"
2042
           "ctrl-alt-n      switch to virtual console 'n'\n"
2043
           "ctrl-alt        toggle mouse and keyboard grab\n"
2044
           "\n"
2045
           "When using -nographic, press 'ctrl-a h' to get some help.\n");
2046

    
2047
    exit(exitcode);
2048
}
2049

    
2050
#define HAS_ARG 0x0001
2051

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

    
2059
static const QEMUOption qemu_options[] = {
2060
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
2061
#define QEMU_OPTIONS_GENERATE_OPTIONS
2062
#include "qemu-options-wrapper.h"
2063
    { NULL },
2064
};
2065

    
2066
static bool vga_available(void)
2067
{
2068
    return object_class_by_name("VGA") || object_class_by_name("isa-vga");
2069
}
2070

    
2071
static bool cirrus_vga_available(void)
2072
{
2073
    return object_class_by_name("cirrus-vga")
2074
           || object_class_by_name("isa-cirrus-vga");
2075
}
2076

    
2077
static bool vmware_vga_available(void)
2078
{
2079
    return object_class_by_name("vmware-svga");
2080
}
2081

    
2082
static bool qxl_vga_available(void)
2083
{
2084
    return object_class_by_name("qxl-vga");
2085
}
2086

    
2087
static void select_vgahw (const char *p)
2088
{
2089
    const char *opts;
2090

    
2091
    vga_interface_type = VGA_NONE;
2092
    if (strstart(p, "std", &opts)) {
2093
        if (vga_available()) {
2094
            vga_interface_type = VGA_STD;
2095
        } else {
2096
            fprintf(stderr, "Error: standard VGA not available\n");
2097
            exit(0);
2098
        }
2099
    } else if (strstart(p, "cirrus", &opts)) {
2100
        if (cirrus_vga_available()) {
2101
            vga_interface_type = VGA_CIRRUS;
2102
        } else {
2103
            fprintf(stderr, "Error: Cirrus VGA not available\n");
2104
            exit(0);
2105
        }
2106
    } else if (strstart(p, "vmware", &opts)) {
2107
        if (vmware_vga_available()) {
2108
            vga_interface_type = VGA_VMWARE;
2109
        } else {
2110
            fprintf(stderr, "Error: VMWare SVGA not available\n");
2111
            exit(0);
2112
        }
2113
    } else if (strstart(p, "xenfb", &opts)) {
2114
        vga_interface_type = VGA_XENFB;
2115
    } else if (strstart(p, "qxl", &opts)) {
2116
        if (qxl_vga_available()) {
2117
            vga_interface_type = VGA_QXL;
2118
        } else {
2119
            fprintf(stderr, "Error: QXL VGA not available\n");
2120
            exit(0);
2121
        }
2122
    } else if (!strstart(p, "none", &opts)) {
2123
    invalid_vga:
2124
        fprintf(stderr, "Unknown vga type: %s\n", p);
2125
        exit(1);
2126
    }
2127
    while (*opts) {
2128
        const char *nextopt;
2129

    
2130
        if (strstart(opts, ",retrace=", &nextopt)) {
2131
            opts = nextopt;
2132
            if (strstart(opts, "dumb", &nextopt))
2133
                vga_retrace_method = VGA_RETRACE_DUMB;
2134
            else if (strstart(opts, "precise", &nextopt))
2135
                vga_retrace_method = VGA_RETRACE_PRECISE;
2136
            else goto invalid_vga;
2137
        } else goto invalid_vga;
2138
        opts = nextopt;
2139
    }
2140
}
2141

    
2142
static DisplayType select_display(const char *p)
2143
{
2144
    const char *opts;
2145
    DisplayType display = DT_DEFAULT;
2146

    
2147
    if (strstart(p, "sdl", &opts)) {
2148
#ifdef CONFIG_SDL
2149
        display = DT_SDL;
2150
        while (*opts) {
2151
            const char *nextopt;
2152

    
2153
            if (strstart(opts, ",frame=", &nextopt)) {
2154
                opts = nextopt;
2155
                if (strstart(opts, "on", &nextopt)) {
2156
                    no_frame = 0;
2157
                } else if (strstart(opts, "off", &nextopt)) {
2158
                    no_frame = 1;
2159
                } else {
2160
                    goto invalid_sdl_args;
2161
                }
2162
            } else if (strstart(opts, ",alt_grab=", &nextopt)) {
2163
                opts = nextopt;
2164
                if (strstart(opts, "on", &nextopt)) {
2165
                    alt_grab = 1;
2166
                } else if (strstart(opts, "off", &nextopt)) {
2167
                    alt_grab = 0;
2168
                } else {
2169
                    goto invalid_sdl_args;
2170
                }
2171
            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
2172
                opts = nextopt;
2173
                if (strstart(opts, "on", &nextopt)) {
2174
                    ctrl_grab = 1;
2175
                } else if (strstart(opts, "off", &nextopt)) {
2176
                    ctrl_grab = 0;
2177
                } else {
2178
                    goto invalid_sdl_args;
2179
                }
2180
            } else if (strstart(opts, ",window_close=", &nextopt)) {
2181
                opts = nextopt;
2182
                if (strstart(opts, "on", &nextopt)) {
2183
                    no_quit = 0;
2184
                } else if (strstart(opts, "off", &nextopt)) {
2185
                    no_quit = 1;
2186
                } else {
2187
                    goto invalid_sdl_args;
2188
                }
2189
            } else {
2190
            invalid_sdl_args:
2191
                fprintf(stderr, "Invalid SDL option string: %s\n", p);
2192
                exit(1);
2193
            }
2194
            opts = nextopt;
2195
        }
2196
#else
2197
        fprintf(stderr, "SDL support is disabled\n");
2198
        exit(1);
2199
#endif
2200
    } else if (strstart(p, "vnc", &opts)) {
2201
#ifdef CONFIG_VNC
2202
        display_remote++;
2203

    
2204
        if (*opts) {
2205
            const char *nextopt;
2206

    
2207
            if (strstart(opts, "=", &nextopt)) {
2208
                vnc_display = nextopt;
2209
            }
2210
        }
2211
        if (!vnc_display) {
2212
            fprintf(stderr, "VNC requires a display argument vnc=<display>\n");
2213
            exit(1);
2214
        }
2215
#else
2216
        fprintf(stderr, "VNC support is disabled\n");
2217
        exit(1);
2218
#endif
2219
    } else if (strstart(p, "curses", &opts)) {
2220
#ifdef CONFIG_CURSES
2221
        display = DT_CURSES;
2222
#else
2223
        fprintf(stderr, "Curses support is disabled\n");
2224
        exit(1);
2225
#endif
2226
    } else if (strstart(p, "gtk", &opts)) {
2227
#ifdef CONFIG_GTK
2228
        display = DT_GTK;
2229
#else
2230
        fprintf(stderr, "GTK support is disabled\n");
2231
        exit(1);
2232
#endif
2233
    } else if (strstart(p, "none", &opts)) {
2234
        display = DT_NONE;
2235
    } else {
2236
        fprintf(stderr, "Unknown display type: %s\n", p);
2237
        exit(1);
2238
    }
2239

    
2240
    return display;
2241
}
2242

    
2243
static int balloon_parse(const char *arg)
2244
{
2245
    QemuOpts *opts;
2246

    
2247
    if (strcmp(arg, "none") == 0) {
2248
        return 0;
2249
    }
2250

    
2251
    if (!strncmp(arg, "virtio", 6)) {
2252
        if (arg[6] == ',') {
2253
            /* have params -> parse them */
2254
            opts = qemu_opts_parse(qemu_find_opts("device"), arg+7, 0);
2255
            if (!opts)
2256
                return  -1;
2257
        } else {
2258
            /* create empty opts */
2259
            opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
2260
                                    &error_abort);
2261
        }
2262
        qemu_opt_set(opts, "driver", "virtio-balloon");
2263
        return 0;
2264
    }
2265

    
2266
    return -1;
2267
}
2268

    
2269
char *qemu_find_file(int type, const char *name)
2270
{
2271
    int i;
2272
    const char *subdir;
2273
    char *buf;
2274

    
2275
    /* Try the name as a straight path first */
2276
    if (access(name, R_OK) == 0) {
2277
        trace_load_file(name, name);
2278
        return g_strdup(name);
2279
    }
2280

    
2281
    switch (type) {
2282
    case QEMU_FILE_TYPE_BIOS:
2283
        subdir = "";
2284
        break;
2285
    case QEMU_FILE_TYPE_KEYMAP:
2286
        subdir = "keymaps/";
2287
        break;
2288
    default:
2289
        abort();
2290
    }
2291

    
2292
    for (i = 0; i < data_dir_idx; i++) {
2293
        buf = g_strdup_printf("%s/%s%s", data_dir[i], subdir, name);
2294
        if (access(buf, R_OK) == 0) {
2295
            trace_load_file(name, buf);
2296
            return buf;
2297
        }
2298
        g_free(buf);
2299
    }
2300
    return NULL;
2301
}
2302

    
2303
static int device_help_func(QemuOpts *opts, void *opaque)
2304
{
2305
    return qdev_device_help(opts);
2306
}
2307

    
2308
static int device_init_func(QemuOpts *opts, void *opaque)
2309
{
2310
    DeviceState *dev;
2311

    
2312
    dev = qdev_device_add(opts);
2313
    if (!dev)
2314
        return -1;
2315
    object_unref(OBJECT(dev));
2316
    return 0;
2317
}
2318

    
2319
static int chardev_init_func(QemuOpts *opts, void *opaque)
2320
{
2321
    Error *local_err = NULL;
2322

    
2323
    qemu_chr_new_from_opts(opts, NULL, &local_err);
2324
    if (error_is_set(&local_err)) {
2325
        error_report("%s", error_get_pretty(local_err));
2326
        error_free(local_err);
2327
        return -1;
2328
    }
2329
    return 0;
2330
}
2331

    
2332
#ifdef CONFIG_VIRTFS
2333
static int fsdev_init_func(QemuOpts *opts, void *opaque)
2334
{
2335
    int ret;
2336
    ret = qemu_fsdev_add(opts);
2337

    
2338
    return ret;
2339
}
2340
#endif
2341

    
2342
static int mon_init_func(QemuOpts *opts, void *opaque)
2343
{
2344
    CharDriverState *chr;
2345
    const char *chardev;
2346
    const char *mode;
2347
    int flags;
2348

    
2349
    mode = qemu_opt_get(opts, "mode");
2350
    if (mode == NULL) {
2351
        mode = "readline";
2352
    }
2353
    if (strcmp(mode, "readline") == 0) {
2354
        flags = MONITOR_USE_READLINE;
2355
    } else if (strcmp(mode, "control") == 0) {
2356
        flags = MONITOR_USE_CONTROL;
2357
    } else {
2358
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
2359
        exit(1);
2360
    }
2361

    
2362
    if (qemu_opt_get_bool(opts, "pretty", 0))
2363
        flags |= MONITOR_USE_PRETTY;
2364

    
2365
    if (qemu_opt_get_bool(opts, "default", 0))
2366
        flags |= MONITOR_IS_DEFAULT;
2367

    
2368
    chardev = qemu_opt_get(opts, "chardev");
2369
    chr = qemu_chr_find(chardev);
2370
    if (chr == NULL) {
2371
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
2372
        exit(1);
2373
    }
2374

    
2375
    qemu_chr_fe_claim_no_fail(chr);
2376
    monitor_init(chr, flags);
2377
    return 0;
2378
}
2379

    
2380
static void monitor_parse(const char *optarg, const char *mode)
2381
{
2382
    static int monitor_device_index = 0;
2383
    QemuOpts *opts;
2384
    const char *p;
2385
    char label[32];
2386
    int def = 0;
2387

    
2388
    if (strstart(optarg, "chardev:", &p)) {
2389
        snprintf(label, sizeof(label), "%s", p);
2390
    } else {
2391
        snprintf(label, sizeof(label), "compat_monitor%d",
2392
                 monitor_device_index);
2393
        if (monitor_device_index == 0) {
2394
            def = 1;
2395
        }
2396
        opts = qemu_chr_parse_compat(label, optarg);
2397
        if (!opts) {
2398
            fprintf(stderr, "parse error: %s\n", optarg);
2399
            exit(1);
2400
        }
2401
    }
2402

    
2403
    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1, NULL);
2404
    if (!opts) {
2405
        fprintf(stderr, "duplicate chardev: %s\n", label);
2406
        exit(1);
2407
    }
2408
    qemu_opt_set(opts, "mode", mode);
2409
    qemu_opt_set(opts, "chardev", label);
2410
    if (def)
2411
        qemu_opt_set(opts, "default", "on");
2412
    monitor_device_index++;
2413
}
2414

    
2415
struct device_config {
2416
    enum {
2417
        DEV_USB,       /* -usbdevice     */
2418
        DEV_BT,        /* -bt            */
2419
        DEV_SERIAL,    /* -serial        */
2420
        DEV_PARALLEL,  /* -parallel      */
2421
        DEV_VIRTCON,   /* -virtioconsole */
2422
        DEV_DEBUGCON,  /* -debugcon */
2423
        DEV_GDB,       /* -gdb, -s */
2424
        DEV_SCLP,      /* s390 sclp */
2425
    } type;
2426
    const char *cmdline;
2427
    Location loc;
2428
    QTAILQ_ENTRY(device_config) next;
2429
};
2430

    
2431
static QTAILQ_HEAD(, device_config) device_configs =
2432
    QTAILQ_HEAD_INITIALIZER(device_configs);
2433

    
2434
static void add_device_config(int type, const char *cmdline)
2435
{
2436
    struct device_config *conf;
2437

    
2438
    conf = g_malloc0(sizeof(*conf));
2439
    conf->type = type;
2440
    conf->cmdline = cmdline;
2441
    loc_save(&conf->loc);
2442
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
2443
}
2444

    
2445
static int foreach_device_config(int type, int (*func)(const char *cmdline))
2446
{
2447
    struct device_config *conf;
2448
    int rc;
2449

    
2450
    QTAILQ_FOREACH(conf, &device_configs, next) {
2451
        if (conf->type != type)
2452
            continue;
2453
        loc_push_restore(&conf->loc);
2454
        rc = func(conf->cmdline);
2455
        loc_pop(&conf->loc);
2456
        if (0 != rc)
2457
            return rc;
2458
    }
2459
    return 0;
2460
}
2461

    
2462
static int serial_parse(const char *devname)
2463
{
2464
    static int index = 0;
2465
    char label[32];
2466

    
2467
    if (strcmp(devname, "none") == 0)
2468
        return 0;
2469
    if (index == MAX_SERIAL_PORTS) {
2470
        fprintf(stderr, "qemu: too many serial ports\n");
2471
        exit(1);
2472
    }
2473
    snprintf(label, sizeof(label), "serial%d", index);
2474
    serial_hds[index] = qemu_chr_new(label, devname, NULL);
2475
    if (!serial_hds[index]) {
2476
        fprintf(stderr, "qemu: could not connect serial device"
2477
                " to character backend '%s'\n", devname);
2478
        return -1;
2479
    }
2480
    index++;
2481
    return 0;
2482
}
2483

    
2484
static int parallel_parse(const char *devname)
2485
{
2486
    static int index = 0;
2487
    char label[32];
2488

    
2489
    if (strcmp(devname, "none") == 0)
2490
        return 0;
2491
    if (index == MAX_PARALLEL_PORTS) {
2492
        fprintf(stderr, "qemu: too many parallel ports\n");
2493
        exit(1);
2494
    }
2495
    snprintf(label, sizeof(label), "parallel%d", index);
2496
    parallel_hds[index] = qemu_chr_new(label, devname, NULL);
2497
    if (!parallel_hds[index]) {
2498
        fprintf(stderr, "qemu: could not connect parallel device"
2499
                " to character backend '%s'\n", devname);
2500
        return -1;
2501
    }
2502
    index++;
2503
    return 0;
2504
}
2505

    
2506
static int virtcon_parse(const char *devname)
2507
{
2508
    QemuOptsList *device = qemu_find_opts("device");
2509
    static int index = 0;
2510
    char label[32];
2511
    QemuOpts *bus_opts, *dev_opts;
2512

    
2513
    if (strcmp(devname, "none") == 0)
2514
        return 0;
2515
    if (index == MAX_VIRTIO_CONSOLES) {
2516
        fprintf(stderr, "qemu: too many virtio consoles\n");
2517
        exit(1);
2518
    }
2519

    
2520
    bus_opts = qemu_opts_create(device, NULL, 0, &error_abort);
2521
    if (arch_type == QEMU_ARCH_S390X) {
2522
        qemu_opt_set(bus_opts, "driver", "virtio-serial-s390");
2523
    } else {
2524
        qemu_opt_set(bus_opts, "driver", "virtio-serial-pci");
2525
    }
2526

    
2527
    dev_opts = qemu_opts_create(device, NULL, 0, &error_abort);
2528
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2529

    
2530
    snprintf(label, sizeof(label), "virtcon%d", index);
2531
    virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
2532
    if (!virtcon_hds[index]) {
2533
        fprintf(stderr, "qemu: could not connect virtio console"
2534
                " to character backend '%s'\n", devname);
2535
        return -1;
2536
    }
2537
    qemu_opt_set(dev_opts, "chardev", label);
2538

    
2539
    index++;
2540
    return 0;
2541
}
2542

    
2543
static int sclp_parse(const char *devname)
2544
{
2545
    QemuOptsList *device = qemu_find_opts("device");
2546
    static int index = 0;
2547
    char label[32];
2548
    QemuOpts *dev_opts;
2549

    
2550
    if (strcmp(devname, "none") == 0) {
2551
        return 0;
2552
    }
2553
    if (index == MAX_SCLP_CONSOLES) {
2554
        fprintf(stderr, "qemu: too many sclp consoles\n");
2555
        exit(1);
2556
    }
2557

    
2558
    assert(arch_type == QEMU_ARCH_S390X);
2559

    
2560
    dev_opts = qemu_opts_create(device, NULL, 0, NULL);
2561
    qemu_opt_set(dev_opts, "driver", "sclpconsole");
2562

    
2563
    snprintf(label, sizeof(label), "sclpcon%d", index);
2564
    sclp_hds[index] = qemu_chr_new(label, devname, NULL);
2565
    if (!sclp_hds[index]) {
2566
        fprintf(stderr, "qemu: could not connect sclp console"
2567
                " to character backend '%s'\n", devname);
2568
        return -1;
2569
    }
2570
    qemu_opt_set(dev_opts, "chardev", label);
2571

    
2572
    index++;
2573
    return 0;
2574
}
2575

    
2576
static int debugcon_parse(const char *devname)
2577
{
2578
    QemuOpts *opts;
2579

    
2580
    if (!qemu_chr_new("debugcon", devname, NULL)) {
2581
        exit(1);
2582
    }
2583
    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);
2584
    if (!opts) {
2585
        fprintf(stderr, "qemu: already have a debugcon device\n");
2586
        exit(1);
2587
    }
2588
    qemu_opt_set(opts, "driver", "isa-debugcon");
2589
    qemu_opt_set(opts, "chardev", "debugcon");
2590
    return 0;
2591
}
2592

    
2593
static QEMUMachine *machine_parse(const char *name)
2594
{
2595
    QEMUMachine *m, *machine = NULL;
2596

    
2597
    if (name) {
2598
        machine = find_machine(name);
2599
    }
2600
    if (machine) {
2601
        return machine;
2602
    }
2603
    printf("Supported machines are:\n");
2604
    for (m = first_machine; m != NULL; m = m->next) {
2605
        if (m->alias) {
2606
            printf("%-20s %s (alias of %s)\n", m->alias, m->desc, m->name);
2607
        }
2608
        printf("%-20s %s%s\n", m->name, m->desc,
2609
               m->is_default ? " (default)" : "");
2610
    }
2611
    exit(!name || !is_help_option(name));
2612
}
2613

    
2614
static int tcg_init(void)
2615
{
2616
    tcg_exec_init(tcg_tb_size * 1024 * 1024);
2617
    return 0;
2618
}
2619

    
2620
static struct {
2621
    const char *opt_name;
2622
    const char *name;
2623
    int (*available)(void);
2624
    int (*init)(void);
2625
    bool *allowed;
2626
} accel_list[] = {
2627
    { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
2628
    { "xen", "Xen", xen_available, xen_init, &xen_allowed },
2629
    { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
2630
    { "qtest", "QTest", qtest_available, qtest_init_accel, &qtest_allowed },
2631
};
2632

    
2633
static int configure_accelerator(void)
2634
{
2635
    const char *p;
2636
    char buf[10];
2637
    int i, ret;
2638
    bool accel_initialised = false;
2639
    bool init_failed = false;
2640

    
2641
    p = qemu_opt_get(qemu_get_machine_opts(), "accel");
2642
    if (p == NULL) {
2643
        /* Use the default "accelerator", tcg */
2644
        p = "tcg";
2645
    }
2646

    
2647
    while (!accel_initialised && *p != '\0') {
2648
        if (*p == ':') {
2649
            p++;
2650
        }
2651
        p = get_opt_name(buf, sizeof (buf), p, ':');
2652
        for (i = 0; i < ARRAY_SIZE(accel_list); i++) {
2653
            if (strcmp(accel_list[i].opt_name, buf) == 0) {
2654
                if (!accel_list[i].available()) {
2655
                    printf("%s not supported for this target\n",
2656
                           accel_list[i].name);
2657
                    continue;
2658
                }
2659
                *(accel_list[i].allowed) = true;
2660
                ret = accel_list[i].init();
2661
                if (ret < 0) {
2662
                    init_failed = true;
2663
                    fprintf(stderr, "failed to initialize %s: %s\n",
2664
                            accel_list[i].name,
2665
                            strerror(-ret));
2666
                    *(accel_list[i].allowed) = false;
2667
                } else {
2668
                    accel_initialised = true;
2669
                }
2670
                break;
2671
            }
2672
        }
2673
        if (i == ARRAY_SIZE(accel_list)) {
2674
            fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);
2675
        }
2676
    }
2677

    
2678
    if (!accel_initialised) {
2679
        if (!init_failed) {
2680
            fprintf(stderr, "No accelerator found!\n");
2681
        }
2682
        exit(1);
2683
    }
2684

    
2685
    if (init_failed) {
2686
        fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
2687
    }
2688

    
2689
    return !accel_initialised;
2690
}
2691

    
2692
void qemu_add_exit_notifier(Notifier *notify)
2693
{
2694
    notifier_list_add(&exit_notifiers, notify);
2695
}
2696

    
2697
void qemu_remove_exit_notifier(Notifier *notify)
2698
{
2699
    notifier_remove(notify);
2700
}
2701

    
2702
static void qemu_run_exit_notifiers(void)
2703
{
2704
    notifier_list_notify(&exit_notifiers, NULL);
2705
}
2706

    
2707
void qemu_add_machine_init_done_notifier(Notifier *notify)
2708
{
2709
    notifier_list_add(&machine_init_done_notifiers, notify);
2710
}
2711

    
2712
static void qemu_run_machine_init_done_notifiers(void)
2713
{
2714
    notifier_list_notify(&machine_init_done_notifiers, NULL);
2715
}
2716

    
2717
static const QEMUOption *lookup_opt(int argc, char **argv,
2718
                                    const char **poptarg, int *poptind)
2719
{
2720
    const QEMUOption *popt;
2721
    int optind = *poptind;
2722
    char *r = argv[optind];
2723
    const char *optarg;
2724

    
2725
    loc_set_cmdline(argv, optind, 1);
2726
    optind++;
2727
    /* Treat --foo the same as -foo.  */
2728
    if (r[1] == '-')
2729
        r++;
2730
    popt = qemu_options;
2731
    for(;;) {
2732
        if (!popt->name) {
2733
            error_report("invalid option");
2734
            exit(1);
2735
        }
2736
        if (!strcmp(popt->name, r + 1))
2737
            break;
2738
        popt++;
2739
    }
2740
    if (popt->flags & HAS_ARG) {
2741
        if (optind >= argc) {
2742
            error_report("requires an argument");
2743
            exit(1);
2744
        }
2745
        optarg = argv[optind++];
2746
        loc_set_cmdline(argv, optind - 2, 2);
2747
    } else {
2748
        optarg = NULL;
2749
    }
2750

    
2751
    *poptarg = optarg;
2752
    *poptind = optind;
2753

    
2754
    return popt;
2755
}
2756

    
2757
static gpointer malloc_and_trace(gsize n_bytes)
2758
{
2759
    void *ptr = malloc(n_bytes);
2760
    trace_g_malloc(n_bytes, ptr);
2761
    return ptr;
2762
}
2763

    
2764
static gpointer realloc_and_trace(gpointer mem, gsize n_bytes)
2765
{
2766
    void *ptr = realloc(mem, n_bytes);
2767
    trace_g_realloc(mem, n_bytes, ptr);
2768
    return ptr;
2769
}
2770

    
2771
static void free_and_trace(gpointer mem)
2772
{
2773
    trace_g_free(mem);
2774
    free(mem);
2775
}
2776

    
2777
static int object_set_property(const char *name, const char *value, void *opaque)
2778
{
2779
    Object *obj = OBJECT(opaque);
2780
    StringInputVisitor *siv;
2781
    Error *local_err = NULL;
2782

    
2783
    if (strcmp(name, "qom-type") == 0 || strcmp(name, "id") == 0) {
2784
        return 0;
2785
    }
2786

    
2787
    siv = string_input_visitor_new(value);
2788
    object_property_set(obj, string_input_get_visitor(siv), name, &local_err);
2789
    string_input_visitor_cleanup(siv);
2790

    
2791
    if (local_err) {
2792
        qerror_report_err(local_err);
2793
        error_free(local_err);
2794
        return -1;
2795
    }
2796

    
2797
    return 0;
2798
}
2799

    
2800
static int object_create(QemuOpts *opts, void *opaque)
2801
{
2802
    const char *type = qemu_opt_get(opts, "qom-type");
2803
    const char *id = qemu_opts_id(opts);
2804
    Error *local_err = NULL;
2805
    Object *obj;
2806

    
2807
    g_assert(type != NULL);
2808

    
2809
    if (id == NULL) {
2810
        qerror_report(QERR_MISSING_PARAMETER, "id");
2811
        return -1;
2812
    }
2813

    
2814
    obj = object_new(type);
2815
    if (qemu_opt_foreach(opts, object_set_property, obj, 1) < 0) {
2816
        object_unref(obj);
2817
        return -1;
2818
    }
2819

    
2820
    if (!object_dynamic_cast(obj, TYPE_USER_CREATABLE)) {
2821
        error_setg(&local_err, "object '%s' isn't supported by -object",
2822
                   id);
2823
        goto out;
2824
    }
2825

    
2826
    user_creatable_complete(obj, &local_err);
2827
    if (local_err) {
2828
        goto out;
2829
    }
2830

    
2831
    object_property_add_child(container_get(object_get_root(), "/objects"),
2832
                              id, obj, &local_err);
2833

    
2834
out:
2835
    object_unref(obj);
2836
    if (local_err) {
2837
        qerror_report_err(local_err);
2838
        error_free(local_err);
2839
        return -1;
2840
    }
2841
    return 0;
2842
}
2843

    
2844
int main(int argc, char **argv, char **envp)
2845
{
2846
    int i;
2847
    int snapshot, linux_boot;
2848
    const char *icount_option = NULL;
2849
    const char *initrd_filename;
2850
    const char *kernel_filename, *kernel_cmdline;
2851
    const char *boot_order;
2852
    DisplayState *ds;
2853
    int cyls, heads, secs, translation;
2854
    QemuOpts *hda_opts = NULL, *opts, *machine_opts;
2855
    QemuOptsList *olist;
2856
    int optind;
2857
    const char *optarg;
2858
    const char *loadvm = NULL;
2859
    QEMUMachine *machine;
2860
    const char *cpu_model;
2861
    const char *vga_model = "none";
2862
    const char *qtest_chrdev = NULL;
2863
    const char *qtest_log = NULL;
2864
    const char *pid_file = NULL;
2865
    const char *incoming = NULL;
2866
#ifdef CONFIG_VNC
2867
    int show_vnc_port = 0;
2868
#endif
2869
    bool defconfig = true;
2870
    bool userconfig = true;
2871
    const char *log_mask = NULL;
2872
    const char *log_file = NULL;
2873
    GMemVTable mem_trace = {
2874
        .malloc = malloc_and_trace,
2875
        .realloc = realloc_and_trace,
2876
        .free = free_and_trace,
2877
    };
2878
    const char *trace_events = NULL;
2879
    const char *trace_file = NULL;
2880

    
2881
    atexit(qemu_run_exit_notifiers);
2882
    error_set_progname(argv[0]);
2883

    
2884
    g_mem_set_vtable(&mem_trace);
2885
    if (!g_thread_supported()) {
2886
#if !GLIB_CHECK_VERSION(2, 31, 0)
2887
        g_thread_init(NULL);
2888
#else
2889
        fprintf(stderr, "glib threading failed to initialize.\n");
2890
        exit(1);
2891
#endif
2892
    }
2893

    
2894
    module_call_init(MODULE_INIT_QOM);
2895

    
2896
    qemu_add_opts(&qemu_drive_opts);
2897
    qemu_add_drive_opts(&qemu_legacy_drive_opts);
2898
    qemu_add_drive_opts(&qemu_common_drive_opts);
2899
    qemu_add_drive_opts(&qemu_drive_opts);
2900
    qemu_add_opts(&qemu_chardev_opts);
2901
    qemu_add_opts(&qemu_device_opts);
2902
    qemu_add_opts(&qemu_netdev_opts);
2903
    qemu_add_opts(&qemu_net_opts);
2904
    qemu_add_opts(&qemu_rtc_opts);
2905
    qemu_add_opts(&qemu_global_opts);
2906
    qemu_add_opts(&qemu_mon_opts);
2907
    qemu_add_opts(&qemu_trace_opts);
2908
    qemu_add_opts(&qemu_option_rom_opts);
2909
    qemu_add_opts(&qemu_machine_opts);
2910
    qemu_add_opts(&qemu_smp_opts);
2911
    qemu_add_opts(&qemu_boot_opts);
2912
    qemu_add_opts(&qemu_sandbox_opts);
2913
    qemu_add_opts(&qemu_add_fd_opts);
2914
    qemu_add_opts(&qemu_object_opts);
2915
    qemu_add_opts(&qemu_tpmdev_opts);
2916
    qemu_add_opts(&qemu_realtime_opts);
2917
    qemu_add_opts(&qemu_msg_opts);
2918

    
2919
    runstate_init();
2920

    
2921
    init_clocks();
2922
    rtc_clock = QEMU_CLOCK_HOST;
2923

    
2924
    qemu_init_auxval(envp);
2925
    qemu_cache_utils_init();
2926

    
2927
    QLIST_INIT (&vm_change_state_head);
2928
    os_setup_early_signal_handling();
2929

    
2930
    module_call_init(MODULE_INIT_MACHINE);
2931
    machine = find_default_machine();
2932
    cpu_model = NULL;
2933
    ram_size = 0;
2934
    snapshot = 0;
2935
    cyls = heads = secs = 0;
2936
    translation = BIOS_ATA_TRANSLATION_AUTO;
2937

    
2938
    for (i = 0; i < MAX_NODES; i++) {
2939
        node_mem[i] = 0;
2940
        node_cpumask[i] = bitmap_new(MAX_CPUMASK_BITS);
2941
    }
2942

    
2943
    nb_numa_nodes = 0;
2944
    nb_nics = 0;
2945

    
2946
    bdrv_init_with_whitelist();
2947

    
2948
    autostart = 1;
2949

    
2950
    /* first pass of option parsing */
2951
    optind = 1;
2952
    while (optind < argc) {
2953
        if (argv[optind][0] != '-') {
2954
            /* disk image */
2955
            optind++;
2956
            continue;
2957
        } else {
2958
            const QEMUOption *popt;
2959

    
2960
            popt = lookup_opt(argc, argv, &optarg, &optind);
2961
            switch (popt->index) {
2962
            case QEMU_OPTION_nodefconfig:
2963
                defconfig = false;
2964
                break;
2965
            case QEMU_OPTION_nouserconfig:
2966
                userconfig = false;
2967
                break;
2968
            }
2969
        }
2970
    }
2971

    
2972
    if (defconfig) {
2973
        int ret;
2974
        ret = qemu_read_default_config_files(userconfig);
2975
        if (ret < 0) {
2976
            exit(1);
2977
        }
2978
    }
2979

    
2980
    /* second pass of option parsing */
2981
    optind = 1;
2982
    for(;;) {
2983
        if (optind >= argc)
2984
            break;
2985
        if (argv[optind][0] != '-') {
2986
            hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2987
        } else {
2988
            const QEMUOption *popt;
2989

    
2990
            popt = lookup_opt(argc, argv, &optarg, &optind);
2991
            if (!(popt->arch_mask & arch_type)) {
2992
                printf("Option %s not supported for this target\n", popt->name);
2993
                exit(1);
2994
            }
2995
            switch(popt->index) {
2996
            case QEMU_OPTION_M:
2997
                machine = machine_parse(optarg);
2998
                break;
2999
            case QEMU_OPTION_no_kvm_irqchip: {
3000
                olist = qemu_find_opts("machine");
3001
                qemu_opts_parse(olist, "kernel_irqchip=off", 0);
3002
                break;
3003
            }
3004
            case QEMU_OPTION_cpu:
3005
                /* hw initialization will check this */
3006
                cpu_model = optarg;
3007
                break;
3008
            case QEMU_OPTION_hda:
3009
                {
3010
                    char buf[256];
3011
                    if (cyls == 0)
3012
                        snprintf(buf, sizeof(buf), "%s", HD_OPTS);
3013
                    else
3014
                        snprintf(buf, sizeof(buf),
3015
                                 "%s,cyls=%d,heads=%d,secs=%d%s",
3016
                                 HD_OPTS , cyls, heads, secs,
3017
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
3018
                                 ",trans=lba" :
3019
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
3020
                                 ",trans=none" : "");
3021
                    drive_add(IF_DEFAULT, 0, optarg, buf);
3022
                    break;
3023
                }
3024
            case QEMU_OPTION_hdb:
3025
            case QEMU_OPTION_hdc:
3026
            case QEMU_OPTION_hdd:
3027
                drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
3028
                          HD_OPTS);
3029
                break;
3030
            case QEMU_OPTION_drive:
3031
                if (drive_def(optarg) == NULL) {
3032
                    exit(1);
3033
                }
3034
                break;
3035
            case QEMU_OPTION_set:
3036
                if (qemu_set_option(optarg) != 0)
3037
                    exit(1);
3038
                break;
3039
            case QEMU_OPTION_global:
3040
                if (qemu_global_option(optarg) != 0)
3041
                    exit(1);
3042
                break;
3043
            case QEMU_OPTION_mtdblock:
3044
                drive_add(IF_MTD, -1, optarg, MTD_OPTS);
3045
                break;
3046
            case QEMU_OPTION_sd:
3047
                drive_add(IF_SD, -1, optarg, SD_OPTS);
3048
                break;
3049
            case QEMU_OPTION_pflash:
3050
                drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
3051
                break;
3052
            case QEMU_OPTION_snapshot:
3053
                snapshot = 1;
3054
                break;
3055
            case QEMU_OPTION_hdachs:
3056
                {
3057
                    const char *p;
3058
                    p = optarg;
3059
                    cyls = strtol(p, (char **)&p, 0);
3060
                    if (cyls < 1 || cyls > 16383)
3061
                        goto chs_fail;
3062
                    if (*p != ',')
3063
                        goto chs_fail;
3064
                    p++;
3065
                    heads = strtol(p, (char **)&p, 0);
3066
                    if (heads < 1 || heads > 16)
3067
                        goto chs_fail;
3068
                    if (*p != ',')
3069
                        goto chs_fail;
3070
                    p++;
3071
                    secs = strtol(p, (char **)&p, 0);
3072
                    if (secs < 1 || secs > 63)
3073
                        goto chs_fail;
3074
                    if (*p == ',') {
3075
                        p++;
3076
                        if (!strcmp(p, "none"))
3077
                            translation = BIOS_ATA_TRANSLATION_NONE;
3078
                        else if (!strcmp(p, "lba"))
3079
                            translation = BIOS_ATA_TRANSLATION_LBA;
3080
                        else if (!strcmp(p, "auto"))
3081
                            translation = BIOS_ATA_TRANSLATION_AUTO;
3082
                        else
3083
                            goto chs_fail;
3084
                    } else if (*p != '\0') {
3085
                    chs_fail:
3086
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
3087
                        exit(1);
3088
                    }
3089
                    if (hda_opts != NULL) {
3090
                        char num[16];
3091
                        snprintf(num, sizeof(num), "%d", cyls);
3092
                        qemu_opt_set(hda_opts, "cyls", num);
3093
                        snprintf(num, sizeof(num), "%d", heads);
3094
                        qemu_opt_set(hda_opts, "heads", num);
3095
                        snprintf(num, sizeof(num), "%d", secs);
3096
                        qemu_opt_set(hda_opts, "secs", num);
3097
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
3098
                            qemu_opt_set(hda_opts, "trans", "lba");
3099
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
3100
                            qemu_opt_set(hda_opts, "trans", "none");
3101
                    }
3102
                }
3103
                break;
3104
            case QEMU_OPTION_numa:
3105
                numa_add(optarg);
3106
                break;
3107
            case QEMU_OPTION_display:
3108
                display_type = select_display(optarg);
3109
                break;
3110
            case QEMU_OPTION_nographic:
3111
                display_type = DT_NOGRAPHIC;
3112
                break;
3113
            case QEMU_OPTION_curses:
3114
#ifdef CONFIG_CURSES
3115
                display_type = DT_CURSES;
3116
#else
3117
                fprintf(stderr, "Curses support is disabled\n");
3118
                exit(1);
3119
#endif
3120
                break;
3121
            case QEMU_OPTION_portrait:
3122
                graphic_rotate = 90;
3123
                break;
3124
            case QEMU_OPTION_rotate:
3125
                graphic_rotate = strtol(optarg, (char **) &optarg, 10);
3126
                if (graphic_rotate != 0 && graphic_rotate != 90 &&
3127
                    graphic_rotate != 180 && graphic_rotate != 270) {
3128
                    fprintf(stderr,
3129
                        "qemu: only 90, 180, 270 deg rotation is available\n");
3130
                    exit(1);
3131
                }
3132
                break;
3133
            case QEMU_OPTION_kernel:
3134
                qemu_opts_set(qemu_find_opts("machine"), 0, "kernel", optarg);
3135
                break;
3136
            case QEMU_OPTION_initrd:
3137
                qemu_opts_set(qemu_find_opts("machine"), 0, "initrd", optarg);
3138
                break;
3139
            case QEMU_OPTION_append:
3140
                qemu_opts_set(qemu_find_opts("machine"), 0, "append", optarg);
3141
                break;
3142
            case QEMU_OPTION_dtb:
3143
                qemu_opts_set(qemu_find_opts("machine"), 0, "dtb", optarg);
3144
                break;
3145
            case QEMU_OPTION_cdrom:
3146
                drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
3147
                break;
3148
            case QEMU_OPTION_boot:
3149
                opts = qemu_opts_parse(qemu_find_opts("boot-opts"), optarg, 1);
3150
                if (!opts) {
3151
                    exit(1);
3152
                }
3153
                break;
3154
            case QEMU_OPTION_fda:
3155
            case QEMU_OPTION_fdb:
3156
                drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
3157
                          optarg, FD_OPTS);
3158
                break;
3159
            case QEMU_OPTION_no_fd_bootchk:
3160
                fd_bootchk = 0;
3161
                break;
3162
            case QEMU_OPTION_netdev:
3163
                if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
3164
                    exit(1);
3165
                }
3166
                break;
3167
            case QEMU_OPTION_net:
3168
                if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
3169
                    exit(1);
3170
                }
3171
                break;
3172
#ifdef CONFIG_LIBISCSI
3173
            case QEMU_OPTION_iscsi:
3174
                opts = qemu_opts_parse(qemu_find_opts("iscsi"), optarg, 0);
3175
                if (!opts) {
3176
                    exit(1);
3177
                }
3178
                break;
3179
#endif
3180
#ifdef CONFIG_SLIRP
3181
            case QEMU_OPTION_tftp:
3182
                legacy_tftp_prefix = optarg;
3183
                break;
3184
            case QEMU_OPTION_bootp:
3185
                legacy_bootp_filename = optarg;
3186
                break;
3187
            case QEMU_OPTION_redir:
3188
                if (net_slirp_redir(optarg) < 0)
3189
                    exit(1);
3190
                break;
3191
#endif
3192
            case QEMU_OPTION_bt:
3193
                add_device_config(DEV_BT, optarg);
3194
                break;
3195
            case QEMU_OPTION_audio_help:
3196
                AUD_help ();
3197
                exit (0);
3198
                break;
3199
            case QEMU_OPTION_soundhw:
3200
                select_soundhw (optarg);
3201
                break;
3202
            case QEMU_OPTION_h:
3203
                help(0);
3204
                break;
3205
            case QEMU_OPTION_version:
3206
                version();
3207
                exit(0);
3208
                break;
3209
            case QEMU_OPTION_m: {
3210
                int64_t value;
3211
                uint64_t sz;
3212
                char *end;
3213

    
3214
                value = strtosz(optarg, &end);
3215
                if (value < 0 || *end) {
3216
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
3217
                    exit(1);
3218
                }
3219
                sz = QEMU_ALIGN_UP((uint64_t)value, 8192);
3220
                ram_size = sz;
3221
                if (ram_size != sz) {
3222
                    fprintf(stderr, "qemu: ram size too large\n");
3223
                    exit(1);
3224
                }
3225
                break;
3226
            }
3227
#ifdef CONFIG_TPM
3228
            case QEMU_OPTION_tpmdev:
3229
                if (tpm_config_parse(qemu_find_opts("tpmdev"), optarg) < 0) {
3230
                    exit(1);
3231
                }
3232
                break;
3233
#endif
3234
            case QEMU_OPTION_mempath:
3235
                mem_path = optarg;
3236
                break;
3237
            case QEMU_OPTION_mem_prealloc:
3238
                mem_prealloc = 1;
3239
                break;
3240
            case QEMU_OPTION_d:
3241
                log_mask = optarg;
3242
                break;
3243
            case QEMU_OPTION_D:
3244
                log_file = optarg;
3245
                break;
3246
            case QEMU_OPTION_s:
3247
                add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
3248
                break;
3249
            case QEMU_OPTION_gdb:
3250
                add_device_config(DEV_GDB, optarg);
3251
                break;
3252
            case QEMU_OPTION_L:
3253
                if (data_dir_idx < ARRAY_SIZE(data_dir)) {
3254
                    data_dir[data_dir_idx++] = optarg;
3255
                }
3256
                break;
3257
            case QEMU_OPTION_bios:
3258
                qemu_opts_set(qemu_find_opts("machine"), 0, "firmware", optarg);
3259
                break;
3260
            case QEMU_OPTION_singlestep:
3261
                singlestep = 1;
3262
                break;
3263
            case QEMU_OPTION_S:
3264
                autostart = 0;
3265
                break;
3266
            case QEMU_OPTION_k:
3267
                keyboard_layout = optarg;
3268
                break;
3269
            case QEMU_OPTION_localtime:
3270
                rtc_utc = 0;
3271
                break;
3272
            case QEMU_OPTION_vga:
3273
                vga_model = optarg;
3274
                default_vga = 0;
3275
                break;
3276
            case QEMU_OPTION_g:
3277
                {
3278
                    const char *p;
3279
                    int w, h, depth;
3280
                    p = optarg;
3281
                    w = strtol(p, (char **)&p, 10);
3282
                    if (w <= 0) {
3283
                    graphic_error:
3284
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
3285
                        exit(1);
3286
                    }
3287
                    if (*p != 'x')
3288
                        goto graphic_error;
3289
                    p++;
3290
                    h = strtol(p, (char **)&p, 10);
3291
                    if (h <= 0)
3292
                        goto graphic_error;
3293
                    if (*p == 'x') {
3294
                        p++;
3295
                        depth = strtol(p, (char **)&p, 10);
3296
                        if (depth != 8 && depth != 15 && depth != 16 &&
3297
                            depth != 24 && depth != 32)
3298
                            goto graphic_error;
3299
                    } else if (*p == '\0') {
3300
                        depth = graphic_depth;
3301
                    } else {
3302
                        goto graphic_error;
3303
                    }
3304

    
3305
                    graphic_width = w;
3306
                    graphic_height = h;
3307
                    graphic_depth = depth;
3308
                }
3309
                break;
3310
            case QEMU_OPTION_echr:
3311
                {
3312
                    char *r;
3313
                    term_escape_char = strtol(optarg, &r, 0);
3314
                    if (r == optarg)
3315
                        printf("Bad argument to echr\n");
3316
                    break;
3317
                }
3318
            case QEMU_OPTION_monitor:
3319
                default_monitor = 0;
3320
                if (strncmp(optarg, "none", 4)) {
3321
                    monitor_parse(optarg, "readline");
3322
                }
3323
                break;
3324
            case QEMU_OPTION_qmp:
3325
                monitor_parse(optarg, "control");
3326
                default_monitor = 0;
3327
                break;
3328
            case QEMU_OPTION_mon:
3329
                opts = qemu_opts_parse(qemu_find_opts("mon"), optarg, 1);
3330
                if (!opts) {
3331
                    exit(1);
3332
                }
3333
                default_monitor = 0;
3334
                break;
3335
            case QEMU_OPTION_chardev:
3336
                opts = qemu_opts_parse(qemu_find_opts("chardev"), optarg, 1);
3337
                if (!opts) {
3338
                    exit(1);
3339
                }
3340
                break;
3341
            case QEMU_OPTION_fsdev:
3342
                olist = qemu_find_opts("fsdev");
3343
                if (!olist) {
3344
                    fprintf(stderr, "fsdev is not supported by this qemu build.\n");
3345
                    exit(1);
3346
                }
3347
                opts = qemu_opts_parse(olist, optarg, 1);
3348
                if (!opts) {
3349
                    exit(1);
3350
                }
3351
                break;
3352
            case QEMU_OPTION_virtfs: {
3353
                QemuOpts *fsdev;
3354
                QemuOpts *device;
3355
                const char *writeout, *sock_fd, *socket;
3356

    
3357
                olist = qemu_find_opts("virtfs");
3358
                if (!olist) {
3359
                    fprintf(stderr, "virtfs is not supported by this qemu build.\n");
3360
                    exit(1);
3361
                }
3362
                opts = qemu_opts_parse(olist, optarg, 1);
3363
                if (!opts) {
3364
                    exit(1);
3365
                }
3366

    
3367
                if (qemu_opt_get(opts, "fsdriver") == NULL ||
3368
                    qemu_opt_get(opts, "mount_tag") == NULL) {
3369
                    fprintf(stderr, "Usage: -virtfs fsdriver,mount_tag=tag.\n");
3370
                    exit(1);
3371
                }
3372
                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
3373
                                         qemu_opt_get(opts, "mount_tag"),
3374
                                         1, NULL);
3375
                if (!fsdev) {
3376
                    fprintf(stderr, "duplicate fsdev id: %s\n",
3377
                            qemu_opt_get(opts, "mount_tag"));
3378
                    exit(1);
3379
                }
3380

    
3381
                writeout = qemu_opt_get(opts, "writeout");
3382
                if (writeout) {
3383
#ifdef CONFIG_SYNC_FILE_RANGE
3384
                    qemu_opt_set(fsdev, "writeout", writeout);
3385
#else
3386
                    fprintf(stderr, "writeout=immediate not supported on "
3387
                            "this platform\n");
3388
                    exit(1);
3389
#endif
3390
                }
3391
                qemu_opt_set(fsdev, "fsdriver", qemu_opt_get(opts, "fsdriver"));
3392
                qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"));
3393
                qemu_opt_set(fsdev, "security_model",
3394
                             qemu_opt_get(opts, "security_model"));
3395
                socket = qemu_opt_get(opts, "socket");
3396
                if (socket) {
3397
                    qemu_opt_set(fsdev, "socket", socket);
3398
                }
3399
                sock_fd = qemu_opt_get(opts, "sock_fd");
3400
                if (sock_fd) {
3401
                    qemu_opt_set(fsdev, "sock_fd", sock_fd);
3402
                }
3403

    
3404
                qemu_opt_set_bool(fsdev, "readonly",
3405
                                qemu_opt_get_bool(opts, "readonly", 0));
3406
                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3407
                                          &error_abort);
3408
                qemu_opt_set(device, "driver", "virtio-9p-pci");
3409
                qemu_opt_set(device, "fsdev",
3410
                             qemu_opt_get(opts, "mount_tag"));
3411
                qemu_opt_set(device, "mount_tag",
3412
                             qemu_opt_get(opts, "mount_tag"));
3413
                break;
3414
            }
3415
            case QEMU_OPTION_virtfs_synth: {
3416
                QemuOpts *fsdev;
3417
                QemuOpts *device;
3418

    
3419
                fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth",
3420
                                         1, NULL);
3421
                if (!fsdev) {
3422
                    fprintf(stderr, "duplicate option: %s\n", "virtfs_synth");
3423
                    exit(1);
3424
                }
3425
                qemu_opt_set(fsdev, "fsdriver", "synth");
3426

    
3427
                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
3428
                                          &error_abort);
3429
                qemu_opt_set(device, "driver", "virtio-9p-pci");
3430
                qemu_opt_set(device, "fsdev", "v_synth");
3431
                qemu_opt_set(device, "mount_tag", "v_synth");
3432
                break;
3433
            }
3434
            case QEMU_OPTION_serial:
3435
                add_device_config(DEV_SERIAL, optarg);
3436
                default_serial = 0;
3437
                if (strncmp(optarg, "mon:", 4) == 0) {
3438
                    default_monitor = 0;
3439
                }
3440
                break;
3441
            case QEMU_OPTION_watchdog:
3442
                if (watchdog) {
3443
                    fprintf(stderr,
3444
                            "qemu: only one watchdog option may be given\n");
3445
                    return 1;
3446
                }
3447
                watchdog = optarg;
3448
                break;
3449
            case QEMU_OPTION_watchdog_action:
3450
                if (select_watchdog_action(optarg) == -1) {
3451
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
3452
                    exit(1);
3453
                }
3454
                break;
3455
            case QEMU_OPTION_virtiocon:
3456
                add_device_config(DEV_VIRTCON, optarg);
3457
                default_virtcon = 0;
3458
                if (strncmp(optarg, "mon:", 4) == 0) {
3459
                    default_monitor = 0;
3460
                }
3461
                break;
3462
            case QEMU_OPTION_parallel:
3463
                add_device_config(DEV_PARALLEL, optarg);
3464
                default_parallel = 0;
3465
                if (strncmp(optarg, "mon:", 4) == 0) {
3466
                    default_monitor = 0;
3467
                }
3468
                break;
3469
            case QEMU_OPTION_debugcon:
3470
                add_device_config(DEV_DEBUGCON, optarg);
3471
                break;
3472
            case QEMU_OPTION_loadvm:
3473
                loadvm = optarg;
3474
                break;
3475
            case QEMU_OPTION_full_screen:
3476
                full_screen = 1;
3477
                break;
3478
            case QEMU_OPTION_no_frame:
3479
                no_frame = 1;
3480
                break;
3481
            case QEMU_OPTION_alt_grab:
3482
                alt_grab = 1;
3483
                break;
3484
            case QEMU_OPTION_ctrl_grab:
3485
                ctrl_grab = 1;
3486
                break;
3487
            case QEMU_OPTION_no_quit:
3488
                no_quit = 1;
3489
                break;
3490
            case QEMU_OPTION_sdl:
3491
#ifdef CONFIG_SDL
3492
                display_type = DT_SDL;
3493
                break;
3494
#else
3495
                fprintf(stderr, "SDL support is disabled\n");
3496
                exit(1);
3497
#endif
3498
            case QEMU_OPTION_pidfile:
3499
                pid_file = optarg;
3500
                break;
3501
            case QEMU_OPTION_win2k_hack:
3502
                win2k_install_hack = 1;
3503
                break;
3504
            case QEMU_OPTION_rtc_td_hack: {
3505
                static GlobalProperty slew_lost_ticks[] = {
3506
                    {
3507
                        .driver   = "mc146818rtc",
3508
                        .property = "lost_tick_policy",
3509
                        .value    = "slew",
3510
                    },
3511
                    { /* end of list */ }
3512
                };
3513

    
3514
                qdev_prop_register_global_list(slew_lost_ticks);
3515
                break;
3516
            }
3517
            case QEMU_OPTION_acpitable:
3518
                opts = qemu_opts_parse(qemu_find_opts("acpi"), optarg, 1);
3519
                if (!opts) {
3520
                    exit(1);
3521
                }
3522
                do_acpitable_option(opts);
3523
                break;
3524
            case QEMU_OPTION_smbios:
3525
                opts = qemu_opts_parse(qemu_find_opts("smbios"), optarg, 0);
3526
                if (!opts) {
3527
                    exit(1);
3528
                }
3529
                do_smbios_option(opts);
3530
                break;
3531
            case QEMU_OPTION_enable_kvm:
3532
                olist = qemu_find_opts("machine");
3533
                qemu_opts_parse(olist, "accel=kvm", 0);
3534
                break;
3535
            case QEMU_OPTION_machine:
3536
                olist = qemu_find_opts("machine");
3537
                opts = qemu_opts_parse(olist, optarg, 1);
3538
                if (!opts) {
3539
                    exit(1);
3540
                }
3541
                optarg = qemu_opt_get(opts, "type");
3542
                if (optarg) {
3543
                    machine = machine_parse(optarg);
3544
                }
3545
                break;
3546
             case QEMU_OPTION_no_kvm:
3547
                olist = qemu_find_opts("machine");
3548
                qemu_opts_parse(olist, "accel=tcg", 0);
3549
                break;
3550
            case QEMU_OPTION_no_kvm_pit: {
3551
                fprintf(stderr, "Warning: KVM PIT can no longer be disabled "
3552
                                "separately.\n");
3553
                break;
3554
            }
3555
            case QEMU_OPTION_no_kvm_pit_reinjection: {
3556
                static GlobalProperty kvm_pit_lost_tick_policy[] = {
3557
                    {
3558
                        .driver   = "kvm-pit",
3559
                        .property = "lost_tick_policy",
3560
                        .value    = "discard",
3561
                    },
3562
                    { /* end of list */ }
3563
                };
3564

    
3565
                fprintf(stderr, "Warning: option deprecated, use "
3566
                        "lost_tick_policy property of kvm-pit instead.\n");
3567
                qdev_prop_register_global_list(kvm_pit_lost_tick_policy);
3568
                break;
3569
            }
3570
            case QEMU_OPTION_usb:
3571
                olist = qemu_find_opts("machine");
3572
                qemu_opts_parse(olist, "usb=on", 0);
3573
                break;
3574
            case QEMU_OPTION_usbdevice:
3575
                olist = qemu_find_opts("machine");
3576
                qemu_opts_parse(olist, "usb=on", 0);
3577
                add_device_config(DEV_USB, optarg);
3578
                break;
3579
            case QEMU_OPTION_device:
3580
                if (!qemu_opts_parse(qemu_find_opts("device"), optarg, 1)) {
3581
                    exit(1);
3582
                }
3583
                break;
3584
            case QEMU_OPTION_smp:
3585
                if (!qemu_opts_parse(qemu_find_opts("smp-opts"), optarg, 1)) {
3586
                    exit(1);
3587
                }
3588
                break;
3589
            case QEMU_OPTION_vnc:
3590
#ifdef CONFIG_VNC
3591
                display_remote++;
3592
                vnc_display = optarg;
3593
#else
3594
                fprintf(stderr, "VNC support is disabled\n");
3595
                exit(1);
3596
#endif
3597
                break;
3598
            case QEMU_OPTION_no_acpi:
3599
                acpi_enabled = 0;
3600
                break;
3601
            case QEMU_OPTION_no_hpet:
3602
                no_hpet = 1;
3603
                break;
3604
            case QEMU_OPTION_balloon:
3605
                if (balloon_parse(optarg) < 0) {
3606
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3607
                    exit(1);
3608
                }
3609
                break;
3610
            case QEMU_OPTION_no_reboot:
3611
                no_reboot = 1;
3612
                break;
3613
            case QEMU_OPTION_no_shutdown:
3614
                no_shutdown = 1;
3615
                break;
3616
            case QEMU_OPTION_show_cursor:
3617
                cursor_hide = 0;
3618
                break;
3619
            case QEMU_OPTION_uuid:
3620
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3621
                    fprintf(stderr, "Fail to parse UUID string."
3622
                            " Wrong format.\n");
3623
                    exit(1);
3624
                }
3625
                qemu_uuid_set = true;
3626
                break;
3627
            case QEMU_OPTION_option_rom:
3628
                if (nb_option_roms >= MAX_OPTION_ROMS) {
3629
                    fprintf(stderr, "Too many option ROMs\n");
3630
                    exit(1);
3631
                }
3632
                opts = qemu_opts_parse(qemu_find_opts("option-rom"), optarg, 1);
3633
                if (!opts) {
3634
                    exit(1);
3635
                }
3636
                option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3637
                option_rom[nb_option_roms].bootindex =
3638
                    qemu_opt_get_number(opts, "bootindex", -1);
3639
                if (!option_rom[nb_option_roms].name) {
3640
                    fprintf(stderr, "Option ROM file is not specified\n");
3641
                    exit(1);
3642
                }
3643
                nb_option_roms++;
3644
                break;
3645
            case QEMU_OPTION_semihosting:
3646
                semihosting_enabled = 1;
3647
                break;
3648
            case QEMU_OPTION_tdf:
3649
                fprintf(stderr, "Warning: user space PIT time drift fix "
3650
                                "is no longer supported.\n");
3651
                break;
3652
            case QEMU_OPTION_name:
3653
                qemu_name = g_strdup(optarg);
3654
                 {
3655
                     char *p = strchr(qemu_name, ',');
3656
                     if (p != NULL) {
3657
                        *p++ = 0;
3658
                        if (strncmp(p, "process=", 8)) {
3659
                            fprintf(stderr, "Unknown subargument %s to -name\n", p);
3660
                            exit(1);
3661
                        }
3662
                        p += 8;
3663
                        os_set_proc_name(p);
3664
                     }
3665
                 }
3666
                break;
3667
            case QEMU_OPTION_prom_env:
3668
                if (nb_prom_envs >= MAX_PROM_ENVS) {
3669
                    fprintf(stderr, "Too many prom variables\n");
3670
                    exit(1);
3671
                }
3672
                prom_envs[nb_prom_envs] = optarg;
3673
                nb_prom_envs++;
3674
                break;
3675
            case QEMU_OPTION_old_param:
3676
                old_param = 1;
3677
                break;
3678
            case QEMU_OPTION_clock:
3679
                /* Clock options no longer exist.  Keep this option for
3680
                 * backward compatibility.
3681
                 */
3682
                break;
3683
            case QEMU_OPTION_startdate:
3684
                configure_rtc_date_offset(optarg, 1);
3685
                break;
3686
            case QEMU_OPTION_rtc:
3687
                opts = qemu_opts_parse(qemu_find_opts("rtc"), optarg, 0);
3688
                if (!opts) {
3689
                    exit(1);
3690
                }
3691
                configure_rtc(opts);
3692
                break;
3693
            case QEMU_OPTION_tb_size:
3694
                tcg_tb_size = strtol(optarg, NULL, 0);
3695
                if (tcg_tb_size < 0) {
3696
                    tcg_tb_size = 0;
3697
                }
3698
                break;
3699
            case QEMU_OPTION_icount:
3700
                icount_option = optarg;
3701
                break;
3702
            case QEMU_OPTION_incoming:
3703
                incoming = optarg;
3704
                runstate_set(RUN_STATE_INMIGRATE);
3705
                break;
3706
            case QEMU_OPTION_nodefaults:
3707
                default_serial = 0;
3708
                default_parallel = 0;
3709
                default_virtcon = 0;
3710
                default_sclp = 0;
3711
                default_monitor = 0;
3712
                default_net = 0;
3713
                default_floppy = 0;
3714
                default_cdrom = 0;
3715
                default_sdcard = 0;
3716
                default_vga = 0;
3717
                break;
3718
            case QEMU_OPTION_xen_domid:
3719
                if (!(xen_available())) {
3720
                    printf("Option %s not supported for this target\n", popt->name);
3721
                    exit(1);
3722
                }
3723
                xen_domid = atoi(optarg);
3724
                break;
3725
            case QEMU_OPTION_xen_create:
3726
                if (!(xen_available())) {
3727
                    printf("Option %s not supported for this target\n", popt->name);
3728
                    exit(1);
3729
                }
3730
                xen_mode = XEN_CREATE;
3731
                break;
3732
            case QEMU_OPTION_xen_attach:
3733
                if (!(xen_available())) {
3734
                    printf("Option %s not supported for this target\n", popt->name);
3735
                    exit(1);
3736
                }
3737
                xen_mode = XEN_ATTACH;
3738
                break;
3739
            case QEMU_OPTION_trace:
3740
            {
3741
                opts = qemu_opts_parse(qemu_find_opts("trace"), optarg, 0);
3742
                if (!opts) {
3743
                    exit(1);
3744
                }
3745
                trace_events = qemu_opt_get(opts, "events");
3746
                trace_file = qemu_opt_get(opts, "file");
3747
                break;
3748
            }
3749
            case QEMU_OPTION_readconfig:
3750
                {
3751
                    int ret = qemu_read_config_file(optarg);
3752
                    if (ret < 0) {
3753
                        fprintf(stderr, "read config %s: %s\n", optarg,
3754
                            strerror(-ret));
3755
                        exit(1);
3756
                    }
3757
                    break;
3758
                }
3759
            case QEMU_OPTION_spice:
3760
                olist = qemu_find_opts("spice");
3761
                if (!olist) {
3762
                    fprintf(stderr, "spice is not supported by this qemu build.\n");
3763
                    exit(1);
3764
                }
3765
                opts = qemu_opts_parse(olist, optarg, 0);
3766
                if (!opts) {
3767
                    exit(1);
3768
                }
3769
                display_remote++;
3770
                break;
3771
            case QEMU_OPTION_writeconfig:
3772
                {
3773
                    FILE *fp;
3774
                    if (strcmp(optarg, "-") == 0) {
3775
                        fp = stdout;
3776
                    } else {
3777
                        fp = fopen(optarg, "w");
3778
                        if (fp == NULL) {
3779
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3780
                            exit(1);
3781
                        }
3782
                    }
3783
                    qemu_config_write(fp);
3784
                    fclose(fp);
3785
                    break;
3786
                }
3787
            case QEMU_OPTION_qtest:
3788
                qtest_chrdev = optarg;
3789
                break;
3790
            case QEMU_OPTION_qtest_log:
3791
                qtest_log = optarg;
3792
                break;
3793
            case QEMU_OPTION_sandbox:
3794
                opts = qemu_opts_parse(qemu_find_opts("sandbox"), optarg, 1);
3795
                if (!opts) {
3796
                    exit(1);
3797
                }
3798
                break;
3799
            case QEMU_OPTION_add_fd:
3800
#ifndef _WIN32
3801
                opts = qemu_opts_parse(qemu_find_opts("add-fd"), optarg, 0);
3802
                if (!opts) {
3803
                    exit(1);
3804
                }
3805
#else
3806
                error_report("File descriptor passing is disabled on this "
3807
                             "platform");
3808
                exit(1);
3809
#endif
3810
                break;
3811
            case QEMU_OPTION_object:
3812
                opts = qemu_opts_parse(qemu_find_opts("object"), optarg, 1);
3813
                if (!opts) {
3814
                    exit(1);
3815
                }
3816
                break;
3817
            case QEMU_OPTION_realtime:
3818
                opts = qemu_opts_parse(qemu_find_opts("realtime"), optarg, 0);
3819
                if (!opts) {
3820
                    exit(1);
3821
                }
3822
                configure_realtime(opts);
3823
                break;
3824
            case QEMU_OPTION_msg:
3825
                opts = qemu_opts_parse(qemu_find_opts("msg"), optarg, 0);
3826
                if (!opts) {
3827
                    exit(1);
3828
                }
3829
                configure_msg(opts);
3830
                break;
3831
            default:
3832
                os_parse_cmd_args(popt->index, optarg);
3833
            }
3834
        }
3835
    }
3836
    loc_set_none();
3837

    
3838
    if (qemu_init_main_loop()) {
3839
        fprintf(stderr, "qemu_init_main_loop failed\n");
3840
        exit(1);
3841
    }
3842

    
3843
    if (qemu_opts_foreach(qemu_find_opts("sandbox"), parse_sandbox, NULL, 0)) {
3844
        exit(1);
3845
    }
3846

    
3847
#ifndef _WIN32
3848
    if (qemu_opts_foreach(qemu_find_opts("add-fd"), parse_add_fd, NULL, 1)) {
3849
        exit(1);
3850
    }
3851

    
3852
    if (qemu_opts_foreach(qemu_find_opts("add-fd"), cleanup_add_fd, NULL, 1)) {
3853
        exit(1);
3854
    }
3855
#endif
3856

    
3857
    if (machine == NULL) {
3858
        fprintf(stderr, "No machine found.\n");
3859
        exit(1);
3860
    }
3861

    
3862
    if (machine->hw_version) {
3863
        qemu_set_version(machine->hw_version);
3864
    }
3865

    
3866
    if (qemu_opts_foreach(qemu_find_opts("object"),
3867
                          object_create, NULL, 0) != 0) {
3868
        exit(1);
3869
    }
3870

    
3871
    /* Init CPU def lists, based on config
3872
     * - Must be called after all the qemu_read_config_file() calls
3873
     * - Must be called before list_cpus()
3874
     * - Must be called before machine->init()
3875
     */
3876
    cpudef_init();
3877

    
3878
    if (cpu_model && is_help_option(cpu_model)) {
3879
        list_cpus(stdout, &fprintf, cpu_model);
3880
        exit(0);
3881
    }
3882

    
3883
    /* Open the logfile at this point, if necessary. We can't open the logfile
3884
     * when encountering either of the logging options (-d or -D) because the
3885
     * other one may be encountered later on the command line, changing the
3886
     * location or level of logging.
3887
     */
3888
    if (log_mask) {
3889
        int mask;
3890
        if (log_file) {
3891
            qemu_set_log_filename(log_file);
3892
        }
3893

    
3894
        mask = qemu_str_to_log_mask(log_mask);
3895
        if (!mask) {
3896
            qemu_print_log_usage(stdout);
3897
            exit(1);
3898
        }
3899
        qemu_set_log(mask);
3900
    }
3901

    
3902
    if (!is_daemonized()) {
3903
        if (!trace_backend_init(trace_events, trace_file)) {
3904
            exit(1);
3905
        }
3906
    }
3907

    
3908
    /* If no data_dir is specified then try to find it relative to the
3909
       executable path.  */
3910
    if (data_dir_idx < ARRAY_SIZE(data_dir)) {
3911
        data_dir[data_dir_idx] = os_find_datadir(argv[0]);
3912
        if (data_dir[data_dir_idx] != NULL) {
3913
            data_dir_idx++;
3914
        }
3915
    }
3916
    /* If all else fails use the install path specified when building. */
3917
    if (data_dir_idx < ARRAY_SIZE(data_dir)) {
3918
        data_dir[data_dir_idx++] = CONFIG_QEMU_DATADIR;
3919
    }
3920

    
3921
    smp_parse(qemu_opts_find(qemu_find_opts("smp-opts"), NULL));
3922

    
3923
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3924
    if (smp_cpus > machine->max_cpus) {
3925
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3926
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3927
                machine->max_cpus);
3928
        exit(1);
3929
    }
3930

    
3931
    /*
3932
     * Get the default machine options from the machine if it is not already
3933
     * specified either by the configuration file or by the command line.
3934
     */
3935
    if (machine->default_machine_opts) {
3936
        qemu_opts_set_defaults(qemu_find_opts("machine"),
3937
                               machine->default_machine_opts, 0);
3938
    }
3939

    
3940
    qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
3941
    qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
3942

    
3943
    if (machine->no_serial) {
3944
        default_serial = 0;
3945
    }
3946
    if (machine->no_parallel) {
3947
        default_parallel = 0;
3948
    }
3949
    if (!machine->use_virtcon) {
3950
        default_virtcon = 0;
3951
    }
3952
    if (!machine->use_sclp) {
3953
        default_sclp = 0;
3954
    }
3955
    if (machine->no_floppy) {
3956
        default_floppy = 0;
3957
    }
3958
    if (machine->no_cdrom) {
3959
        default_cdrom = 0;
3960
    }
3961
    if (machine->no_sdcard) {
3962
        default_sdcard = 0;
3963
    }
3964

    
3965
    if (is_daemonized()) {
3966
        /* According to documentation and historically, -nographic redirects
3967
         * serial port, parallel port and monitor to stdio, which does not work
3968
         * with -daemonize.  We can redirect these to null instead, but since
3969
         * -nographic is legacy, let's just error out.
3970
         * We disallow -nographic only if all other ports are not redirected
3971
         * explicitly, to not break existing legacy setups which uses
3972
         * -nographic _and_ redirects all ports explicitly - this is valid
3973
         * usage, -nographic is just a no-op in this case.
3974
         */
3975
        if (display_type == DT_NOGRAPHIC
3976
            && (default_parallel || default_serial
3977
                || default_monitor || default_virtcon)) {
3978
            fprintf(stderr, "-nographic can not be used with -daemonize\n");
3979
            exit(1);
3980
        }
3981
#ifdef CONFIG_CURSES
3982
        if (display_type == DT_CURSES) {
3983
            fprintf(stderr, "curses display can not be used with -daemonize\n");
3984
            exit(1);
3985
        }
3986
#endif
3987
    }
3988

    
3989
    if (display_type == DT_NOGRAPHIC) {
3990
        if (default_parallel)
3991
            add_device_config(DEV_PARALLEL, "null");
3992
        if (default_serial && default_monitor) {
3993
            add_device_config(DEV_SERIAL, "mon:stdio");
3994
        } else if (default_virtcon && default_monitor) {
3995
            add_device_config(DEV_VIRTCON, "mon:stdio");
3996
        } else if (default_sclp && default_monitor) {
3997
            add_device_config(DEV_SCLP, "mon:stdio");
3998
        } else {
3999
            if (default_serial)
4000
                add_device_config(DEV_SERIAL, "stdio");
4001
            if (default_virtcon)
4002
                add_device_config(DEV_VIRTCON, "stdio");
4003
            if (default_sclp) {
4004
                add_device_config(DEV_SCLP, "stdio");
4005
            }
4006
            if (default_monitor)
4007
                monitor_parse("stdio", "readline");
4008
        }
4009
    } else {
4010
        if (default_serial)
4011
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
4012
        if (default_parallel)
4013
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4014
        if (default_monitor)
4015
            monitor_parse("vc:80Cx24C", "readline");
4016
        if (default_virtcon)
4017
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4018
        if (default_sclp) {
4019
            add_device_config(DEV_SCLP, "vc:80Cx24C");
4020
        }
4021
    }
4022

    
4023
    if (display_type == DT_DEFAULT && !display_remote) {
4024
#if defined(CONFIG_GTK)
4025
        display_type = DT_GTK;
4026
#elif defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4027
        display_type = DT_SDL;
4028
#elif defined(CONFIG_VNC)
4029
        vnc_display = "localhost:0,to=99";
4030
        show_vnc_port = 1;
4031
#else
4032
        display_type = DT_NONE;
4033
#endif
4034
    }
4035

    
4036
    if ((no_frame || alt_grab || ctrl_grab) && display_type != DT_SDL) {
4037
        fprintf(stderr, "-no-frame, -alt-grab and -ctrl-grab are only valid "
4038
                        "for SDL, ignoring option\n");
4039
    }
4040
    if (no_quit && (display_type != DT_GTK && display_type != DT_SDL)) {
4041
        fprintf(stderr, "-no-quit is only valid for GTK and SDL, "
4042
                        "ignoring option\n");
4043
    }
4044

    
4045
#if defined(CONFIG_GTK)
4046
    if (display_type == DT_GTK) {
4047
        early_gtk_display_init();
4048
    }
4049
#endif
4050

    
4051
    socket_init();
4052

    
4053
    if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)
4054
        exit(1);
4055
#ifdef CONFIG_VIRTFS
4056
    if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {
4057
        exit(1);
4058
    }
4059
#endif
4060

    
4061
    os_daemonize();
4062

    
4063
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4064
        os_pidfile_error();
4065
        exit(1);
4066
    }
4067

    
4068
    /* init the memory */
4069
    if (ram_size == 0) {
4070
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4071
    }
4072

    
4073
    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0)
4074
        != 0) {
4075
        exit(0);
4076
    }
4077

    
4078
    configure_accelerator();
4079

    
4080
    if (qtest_chrdev) {
4081
        qtest_init(qtest_chrdev, qtest_log);
4082
    }
4083

    
4084
    machine_opts = qemu_get_machine_opts();
4085
    kernel_filename = qemu_opt_get(machine_opts, "kernel");
4086
    initrd_filename = qemu_opt_get(machine_opts, "initrd");
4087
    kernel_cmdline = qemu_opt_get(machine_opts, "append");
4088
    bios_name = qemu_opt_get(machine_opts, "firmware");
4089

    
4090
    boot_order = machine->default_boot_order;
4091
    opts = qemu_opts_find(qemu_find_opts("boot-opts"), NULL);
4092
    if (opts) {
4093
        char *normal_boot_order;
4094
        const char *order, *once;
4095

    
4096
        order = qemu_opt_get(opts, "order");
4097
        if (order) {
4098
            validate_bootdevices(order);
4099
            boot_order = order;
4100
        }
4101

    
4102
        once = qemu_opt_get(opts, "once");
4103
        if (once) {
4104
            validate_bootdevices(once);
4105
            normal_boot_order = g_strdup(boot_order);
4106
            boot_order = once;
4107
            qemu_register_reset(restore_boot_order, normal_boot_order);
4108
        }
4109

    
4110
        boot_menu = qemu_opt_get_bool(opts, "menu", boot_menu);
4111
        boot_strict = qemu_opt_get_bool(opts, "strict", false);
4112
    }
4113

    
4114
    if (!kernel_cmdline) {
4115
        kernel_cmdline = "";
4116
    }
4117

    
4118
    linux_boot = (kernel_filename != NULL);
4119

    
4120
    if (!linux_boot && *kernel_cmdline != '\0') {
4121
        fprintf(stderr, "-append only allowed with -kernel option\n");
4122
        exit(1);
4123
    }
4124

    
4125
    if (!linux_boot && initrd_filename != NULL) {
4126
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
4127
        exit(1);
4128
    }
4129

    
4130
    if (!linux_boot && qemu_opt_get(machine_opts, "dtb")) {
4131
        fprintf(stderr, "-dtb only allowed with -kernel option\n");
4132
        exit(1);
4133
    }
4134

    
4135
    os_set_line_buffering();
4136

    
4137
    qemu_init_cpu_loop();
4138
    qemu_mutex_lock_iothread();
4139

    
4140
#ifdef CONFIG_SPICE
4141
    /* spice needs the timers to be initialized by this point */
4142
    qemu_spice_init();
4143
#endif
4144

    
4145
    if (icount_option && (kvm_enabled() || xen_enabled())) {
4146
        fprintf(stderr, "-icount is not allowed with kvm or xen\n");
4147
        exit(1);
4148
    }
4149
    configure_icount(icount_option);
4150

    
4151
    /* clean up network at qemu process termination */
4152
    atexit(&net_cleanup);
4153

    
4154
    if (net_init_clients() < 0) {
4155
        exit(1);
4156
    }
4157

    
4158
#ifdef CONFIG_TPM
4159
    if (tpm_init() < 0) {
4160
        exit(1);
4161
    }
4162
#endif
4163

    
4164
    /* init the bluetooth world */
4165
    if (foreach_device_config(DEV_BT, bt_parse))
4166
        exit(1);
4167

    
4168
    if (!xen_enabled()) {
4169
        /* On 32-bit hosts, QEMU is limited by virtual address space */
4170
        if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
4171
            fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4172
            exit(1);
4173
        }
4174
    }
4175

    
4176
    cpu_exec_init_all();
4177

    
4178
    blk_mig_init();
4179

    
4180
    /* open the virtual block devices */
4181
    if (snapshot)
4182
        qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
4183
    if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func,
4184
                          &machine->block_default_type, 1) != 0) {
4185
        exit(1);
4186
    }
4187

    
4188
    default_drive(default_cdrom, snapshot, machine->block_default_type, 2,
4189
                  CDROM_OPTS);
4190
    default_drive(default_floppy, snapshot, IF_FLOPPY, 0, FD_OPTS);
4191
    default_drive(default_sdcard, snapshot, IF_SD, 0, SD_OPTS);
4192

    
4193
    register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, NULL);
4194

    
4195
    if (nb_numa_nodes > 0) {
4196
        int i;
4197

    
4198
        if (nb_numa_nodes > MAX_NODES) {
4199
            nb_numa_nodes = MAX_NODES;
4200
        }
4201

    
4202
        /* If no memory size if given for any node, assume the default case
4203
         * and distribute the available memory equally across all nodes
4204
         */
4205
        for (i = 0; i < nb_numa_nodes; i++) {
4206
            if (node_mem[i] != 0)
4207
                break;
4208
        }
4209
        if (i == nb_numa_nodes) {
4210
            uint64_t usedmem = 0;
4211

    
4212
            /* On Linux, the each node's border has to be 8MB aligned,
4213
             * the final node gets the rest.
4214
             */
4215
            for (i = 0; i < nb_numa_nodes - 1; i++) {
4216
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4217
                usedmem += node_mem[i];
4218
            }
4219
            node_mem[i] = ram_size - usedmem;
4220
        }
4221

    
4222
        for (i = 0; i < nb_numa_nodes; i++) {
4223
            if (!bitmap_empty(node_cpumask[i], MAX_CPUMASK_BITS)) {
4224
                break;
4225
            }
4226
        }
4227
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
4228
         * must cope with this anyway, because there are BIOSes out there in
4229
         * real machines which also use this scheme.
4230
         */
4231
        if (i == nb_numa_nodes) {
4232
            for (i = 0; i < max_cpus; i++) {
4233
                set_bit(i, node_cpumask[i % nb_numa_nodes]);
4234
            }
4235
        }
4236
    }
4237

    
4238
    if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {
4239
        exit(1);
4240
    }
4241

    
4242
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4243
        exit(1);
4244
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4245
        exit(1);
4246
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4247
        exit(1);
4248
    if (foreach_device_config(DEV_SCLP, sclp_parse) < 0) {
4249
        exit(1);
4250
    }
4251
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4252
        exit(1);
4253

    
4254
    /* If no default VGA is requested, the default is "none".  */
4255
    if (default_vga) {
4256
        if (cirrus_vga_available()) {
4257
            vga_model = "cirrus";
4258
        } else if (vga_available()) {
4259
            vga_model = "std";
4260
        }
4261
    }
4262
    select_vgahw(vga_model);
4263

    
4264
    if (watchdog) {
4265
        i = select_watchdog(watchdog);
4266
        if (i > 0)
4267
            exit (i == 1 ? 1 : 0);
4268
    }
4269

    
4270
    if (machine->compat_props) {
4271
        qdev_prop_register_global_list(machine->compat_props);
4272
    }
4273
    qemu_add_globals();
4274

    
4275
    qdev_machine_init();
4276

    
4277
    QEMUMachineInitArgs args = { .machine = machine,
4278
                                 .ram_size = ram_size,
4279
                                 .boot_order = boot_order,
4280
                                 .kernel_filename = kernel_filename,
4281
                                 .kernel_cmdline = kernel_cmdline,
4282
                                 .initrd_filename = initrd_filename,
4283
                                 .cpu_model = cpu_model };
4284
    machine->init(&args);
4285

    
4286
    audio_init();
4287

    
4288
    cpu_synchronize_all_post_init();
4289

    
4290
    set_numa_modes();
4291

    
4292
    current_machine = machine;
4293

    
4294
    /* init USB devices */
4295
    if (usb_enabled(false)) {
4296
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
4297
            exit(1);
4298
    }
4299

    
4300
    /* init generic devices */
4301
    if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)
4302
        exit(1);
4303

    
4304
    net_check_clients();
4305

    
4306
    ds = init_displaystate();
4307

    
4308
    /* init local displays */
4309
    switch (display_type) {
4310
    case DT_NOGRAPHIC:
4311
        (void)ds;        /* avoid warning if no display is configured */
4312
        break;
4313
#if defined(CONFIG_CURSES)
4314
    case DT_CURSES:
4315
        curses_display_init(ds, full_screen);
4316
        break;
4317
#endif
4318
#if defined(CONFIG_SDL)
4319
    case DT_SDL:
4320
        sdl_display_init(ds, full_screen, no_frame);
4321
        break;
4322
#elif defined(CONFIG_COCOA)
4323
    case DT_SDL:
4324
        cocoa_display_init(ds, full_screen);
4325
        break;
4326
#endif
4327
#if defined(CONFIG_GTK)
4328
    case DT_GTK:
4329
        gtk_display_init(ds, full_screen);
4330
        break;
4331
#endif
4332
    default:
4333
        break;
4334
    }
4335

    
4336
    /* must be after terminal init, SDL library changes signal handlers */
4337
    os_setup_signal_handling();
4338

    
4339
#ifdef CONFIG_VNC
4340
    /* init remote displays */
4341
    if (vnc_display) {
4342
        Error *local_err = NULL;
4343
        vnc_display_init(ds);
4344
        vnc_display_open(ds, vnc_display, &local_err);
4345
        if (local_err != NULL) {
4346
            error_report("Failed to start VNC server on `%s': %s",
4347
                         vnc_display, error_get_pretty(local_err));
4348
            error_free(local_err);
4349
            exit(1);
4350
        }
4351

    
4352
        if (show_vnc_port) {
4353
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4354
        }
4355
    }
4356
#endif
4357
#ifdef CONFIG_SPICE
4358
    if (using_spice) {
4359
        qemu_spice_display_init();
4360
    }
4361
#endif
4362

    
4363
    if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
4364
        exit(1);
4365
    }
4366

    
4367
    qdev_machine_creation_done();
4368

    
4369
    if (rom_load_all() != 0) {
4370
        fprintf(stderr, "rom loading failed\n");
4371
        exit(1);
4372
    }
4373

    
4374
    /* TODO: once all bus devices are qdevified, this should be done
4375
     * when bus is created by qdev.c */
4376
    qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
4377
    qemu_run_machine_init_done_notifiers();
4378

    
4379
    /* Done notifiers can load ROMs */
4380
    rom_load_done();
4381

    
4382
    qemu_system_reset(VMRESET_SILENT);
4383
    if (loadvm) {
4384
        if (load_vmstate(loadvm) < 0) {
4385
            autostart = 0;
4386
        }
4387
    }
4388

    
4389
    if (incoming) {
4390
        Error *local_err = NULL;
4391
        qemu_start_incoming_migration(incoming, &local_err);
4392
        if (local_err) {
4393
            error_report("-incoming %s: %s", incoming,
4394
                         error_get_pretty(local_err));
4395
            error_free(local_err);
4396
            exit(1);
4397
        }
4398
    } else if (autostart) {
4399
        vm_start();
4400
    }
4401

    
4402
    os_setup_post();
4403

    
4404
    if (is_daemonized()) {
4405
        if (!trace_backend_init(trace_events, trace_file)) {
4406
            exit(1);
4407
        }
4408
    }
4409

    
4410
    main_loop();
4411
    bdrv_close_all();
4412
    pause_all_vcpus();
4413
    res_free();
4414
#ifdef CONFIG_TPM
4415
    tpm_cleanup();
4416
#endif
4417

    
4418
    return 0;
4419
}