Statistics
| Branch: | Revision:

root / vl.c @ c21fb4f8

History | View | Annotate | Download (110.2 kB)

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

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

    
36
#ifndef _WIN32
37
#include <libgen.h>
38
#include <sys/times.h>
39
#include <sys/wait.h>
40
#include <termios.h>
41
#include <sys/mman.h>
42
#include <sys/ioctl.h>
43
#include <sys/resource.h>
44
#include <sys/socket.h>
45
#include <netinet/in.h>
46
#include <net/if.h>
47
#include <arpa/inet.h>
48
#include <dirent.h>
49
#include <netdb.h>
50
#include <sys/select.h>
51

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

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

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

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

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

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

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

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

    
114
#include <glib.h>
115

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

    
157
#include "disas.h"
158

    
159
#include "qemu_socket.h"
160

    
161
#include "slirp/libslirp.h"
162

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

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

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

    
175
#define DEFAULT_RAM_SIZE 128
176

    
177
#define MAX_VIRTIO_CONSOLES 1
178

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

    
236
typedef struct FWBootEntry FWBootEntry;
237

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

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

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

    
251
uint8_t qemu_uuid[16];
252

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

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

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

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

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

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

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

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

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

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

    
328
/***********************************************************/
329
/* QEMU state */
330

    
331
static RunState current_run_state = RUN_STATE_PRELAUNCH;
332

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

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

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

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

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

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

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

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

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

    
364
    { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
365

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

    
376
    { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
377

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

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

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

    
389
    { RUN_STATE_MAX, RUN_STATE_MAX },
390
};
391

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

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

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

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

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

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

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

    
422
    current_run_state = new_state;
423
}
424

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

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

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

    
438
    return info;
439
}
440

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
661
    return 0;
662
}
663

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

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

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

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

    
686
    hci_table[nb_hcis++] = hci;
687

    
688
    return 0;
689
}
690

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

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

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

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

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

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

    
720
    vlan = qemu_find_bt_vlan(vlan_id);
721

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

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

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

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

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

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

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

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

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

    
789
    return 0;
790
}
791

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

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

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

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

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

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

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

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

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

    
861
    return 0;
862
}
863

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

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

    
871
    return 0;
872
}
873
#endif
874

    
875
/***********************************************************/
876
/* QEMU Block devices */
877

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
976
    qemu_boot_set(standard_boot_devices);
977

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

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

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

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

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

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

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

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

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

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

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

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

    
1056
    *size = total;
1057

    
1058
    return list;
1059
}
1060

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

    
1068
    value = endvalue = 0ULL;
1069

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

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

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

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

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

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

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

    
1154
/***********************************************************/
1155
/* USB devices */
1156

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

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

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

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

    
1188
done:
1189
    return 0;
1190
}
1191

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

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

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

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

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

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

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

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

    
1239
/***********************************************************/
1240
/* PCMCIA/Cardbus */
1241

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

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

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

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

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

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

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

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

    
1282
/***********************************************************/
1283
/* machine registration */
1284

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

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

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

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

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

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

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

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

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

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

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

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

    
1352
    return mach_list;
1353
}
1354

    
1355
/***********************************************************/
1356
/* main execution loop */
1357

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

    
1364
    dpy_refresh(ds);
1365

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

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

    
1381
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1382

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

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

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

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

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

    
1406
    trace_vm_state_notify(running, state);
1407

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

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

    
1424
/* reset/shutdown handler */
1425

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

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

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

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

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

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

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

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

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

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

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

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

    
1527
    return false;
1528
}
1529

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1765
    exit(exitcode);
1766
}
1767

    
1768
#define HAS_ARG 0x0001
1769

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1951
    return display;
1952
}
1953

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

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

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

    
1976
    return -1;
1977
}
1978

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

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

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

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

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

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

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

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

    
2040
    return ret;
2041
}
2042
#endif
2043

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

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

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

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

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

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

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

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

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

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

    
2132
static void add_device_config(int type, const char *cmdline)
2133
{
2134
    struct device_config *conf;
2135

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

    
2143
static int foreach_device_config(int type, int (*func)(const char *cmdline))
2144
{
2145
    struct device_config *conf;
2146
    int rc;
2147

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

    
2160
static int serial_parse(const char *devname)
2161
{
2162
    static int index = 0;
2163
    char label[32];
2164

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

    
2182
static int parallel_parse(const char *devname)
2183
{
2184
    static int index = 0;
2185
    char label[32];
2186

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

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

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

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

    
2225
    dev_opts = qemu_opts_create(device, NULL, 0, NULL);
2226
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2227

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

    
2237
    index++;
2238
    return 0;
2239
}
2240

    
2241
static int debugcon_parse(const char *devname)
2242
{   
2243
    QemuOpts *opts;
2244

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

    
2258
static QEMUMachine *machine_parse(const char *name)
2259
{
2260
    QEMUMachine *m, *machine = NULL;
2261

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

    
2279
static int tcg_init(void)
2280
{
2281
    tcg_exec_init(tcg_tb_size * 1024 * 1024);
2282
    return 0;
2283
}
2284

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

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

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

    
2311
    if (p == NULL) {
2312
        /* Use the default "accelerator", tcg */
2313
        p = "tcg";
2314
    }
2315

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

    
2347
    if (!accel_initialised) {
2348
        fprintf(stderr, "No accelerator found!\n");
2349
        exit(1);
2350
    }
2351

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

    
2356
    return !accel_initialised;
2357
}
2358

    
2359
void qemu_add_exit_notifier(Notifier *notify)
2360
{
2361
    notifier_list_add(&exit_notifiers, notify);
2362
}
2363

    
2364
void qemu_remove_exit_notifier(Notifier *notify)
2365
{
2366
    notifier_remove(notify);
2367
}
2368

    
2369
static void qemu_run_exit_notifiers(void)
2370
{
2371
    notifier_list_notify(&exit_notifiers, NULL);
2372
}
2373

    
2374
void qemu_add_machine_init_done_notifier(Notifier *notify)
2375
{
2376
    notifier_list_add(&machine_init_done_notifiers, notify);
2377
}
2378

    
2379
static void qemu_run_machine_init_done_notifiers(void)
2380
{
2381
    notifier_list_notify(&machine_init_done_notifiers, NULL);
2382
}
2383

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

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

    
2418
    *poptarg = optarg;
2419
    *poptind = optind;
2420

    
2421
    return popt;
2422
}
2423

    
2424
static gpointer malloc_and_trace(gsize n_bytes)
2425
{
2426
    void *ptr = malloc(n_bytes);
2427
    trace_g_malloc(n_bytes, ptr);
2428
    return ptr;
2429
}
2430

    
2431
static gpointer realloc_and_trace(gpointer mem, gsize n_bytes)
2432
{
2433
    void *ptr = realloc(mem, n_bytes);
2434
    trace_g_realloc(mem, n_bytes, ptr);
2435
    return ptr;
2436
}
2437

    
2438
static void free_and_trace(gpointer mem)
2439
{
2440
    trace_g_free(mem);
2441
    free(mem);
2442
}
2443

    
2444
int qemu_init_main_loop(void)
2445
{
2446
    return main_loop_init();
2447
}
2448

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

    
2485
    atexit(qemu_run_exit_notifiers);
2486
    error_set_progname(argv[0]);
2487

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

    
2498
    module_call_init(MODULE_INIT_QOM);
2499

    
2500
    runstate_init();
2501

    
2502
    init_clocks();
2503
    rtc_clock = host_clock;
2504

    
2505
    qemu_cache_utils_init(envp);
2506

    
2507
    QLIST_INIT (&vm_change_state_head);
2508
    os_setup_early_signal_handling();
2509

    
2510
    module_call_init(MODULE_INIT_MACHINE);
2511
    machine = find_default_machine();
2512
    cpu_model = NULL;
2513
    ram_size = 0;
2514
    snapshot = 0;
2515
    cyls = heads = secs = 0;
2516
    translation = BIOS_ATA_TRANSLATION_AUTO;
2517

    
2518
    for (i = 0; i < MAX_NODES; i++) {
2519
        node_mem[i] = 0;
2520
        node_cpumask[i] = bitmap_new(MAX_CPUMASK_BITS);
2521
    }
2522

    
2523
    nb_numa_nodes = 0;
2524
    nb_nics = 0;
2525

    
2526
    autostart= 1;
2527

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

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

    
2550
    if (defconfig) {
2551
        int ret;
2552
        ret = qemu_read_default_config_files(userconfig);
2553
        if (ret < 0) {
2554
            exit(1);
2555
        }
2556
    }
2557

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

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

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

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

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

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

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

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

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

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

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

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

    
3149
                qdev_prop_register_global_list(slew_lost_ticks);
3150
                break;
3151
            }
3152
            case QEMU_OPTION_acpitable:
3153
                do_acpitable_option(optarg);
3154
                break;
3155
            case QEMU_OPTION_smbios:
3156
                do_smbios_option(optarg);
3157
                break;
3158
            case QEMU_OPTION_enable_kvm:
3159
                olist = qemu_find_opts("machine");
3160
                qemu_opts_parse(olist, "accel=kvm", 0);
3161
                break;
3162
            case QEMU_OPTION_machine:
3163
                olist = qemu_find_opts("machine");
3164
                opts = qemu_opts_parse(olist, optarg, 1);
3165
                if (!opts) {
3166
                    fprintf(stderr, "parse error: %s\n", optarg);
3167
                    exit(1);
3168
                }
3169
                optarg = qemu_opt_get(opts, "type");
3170
                if (optarg) {
3171
                    machine = machine_parse(optarg);
3172
                }
3173
                break;
3174
            case QEMU_OPTION_no_kvm_pit: {
3175
                fprintf(stderr, "Warning: KVM PIT can no longer be disabled "
3176
                                "separately.\n");
3177
                break;
3178
            }
3179
            case QEMU_OPTION_no_kvm_pit_reinjection: {
3180
                static GlobalProperty kvm_pit_lost_tick_policy[] = {
3181
                    {
3182
                        .driver   = "kvm-pit",
3183
                        .property = "lost_tick_policy",
3184
                        .value    = "discard",
3185
                    },
3186
                    { /* end of list */ }
3187
                };
3188

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

    
3446
    if (qemu_opts_foreach(qemu_find_opts("sandbox"), parse_sandbox, NULL, 0)) {
3447
        exit(1);
3448
    }
3449

    
3450
#ifndef _WIN32
3451
    if (qemu_opts_foreach(qemu_find_opts("add-fd"), parse_add_fd, NULL, 1)) {
3452
        exit(1);
3453
    }
3454

    
3455
    if (qemu_opts_foreach(qemu_find_opts("add-fd"), cleanup_add_fd, NULL, 1)) {
3456
        exit(1);
3457
    }
3458
#endif
3459

    
3460
    if (machine == NULL) {
3461
        fprintf(stderr, "No machine found.\n");
3462
        exit(1);
3463
    }
3464

    
3465
    if (machine->hw_version) {
3466
        qemu_set_version(machine->hw_version);
3467
    }
3468

    
3469
    /* Init CPU def lists, based on config
3470
     * - Must be called after all the qemu_read_config_file() calls
3471
     * - Must be called before list_cpus()
3472
     * - Must be called before machine->init()
3473
     */
3474
    cpudef_init();
3475

    
3476
    if (cpu_model && is_help_option(cpu_model)) {
3477
        list_cpus(stdout, &fprintf, cpu_model);
3478
        exit(0);
3479
    }
3480

    
3481
    /* Open the logfile at this point, if necessary. We can't open the logfile
3482
     * when encountering either of the logging options (-d or -D) because the
3483
     * other one may be encountered later on the command line, changing the
3484
     * location or level of logging.
3485
     */
3486
    if (log_mask) {
3487
        if (log_file) {
3488
            set_cpu_log_filename(log_file);
3489
        }
3490
        set_cpu_log(log_mask);
3491
    }
3492

    
3493
    if (!trace_backend_init(trace_events, trace_file)) {
3494
        exit(1);
3495
    }
3496

    
3497
    /* If no data_dir is specified then try to find it relative to the
3498
       executable path.  */
3499
    if (!data_dir) {
3500
        data_dir = os_find_datadir(argv[0]);
3501
    }
3502
    /* If all else fails use the install path specified when building. */
3503
    if (!data_dir) {
3504
        data_dir = CONFIG_QEMU_DATADIR;
3505
    }
3506

    
3507
    /*
3508
     * Default to max_cpus = smp_cpus, in case the user doesn't
3509
     * specify a max_cpus value.
3510
     */
3511
    if (!max_cpus)
3512
        max_cpus = smp_cpus;
3513

    
3514
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3515
    if (smp_cpus > machine->max_cpus) {
3516
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3517
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3518
                machine->max_cpus);
3519
        exit(1);
3520
    }
3521

    
3522
    /*
3523
     * Get the default machine options from the machine if it is not already
3524
     * specified either by the configuration file or by the command line.
3525
     */
3526
    if (machine->default_machine_opts) {
3527
        qemu_opts_set_defaults(qemu_find_opts("machine"),
3528
                               machine->default_machine_opts, 0);
3529
    }
3530

    
3531
    qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
3532
    qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
3533

    
3534
    if (machine->no_serial) {
3535
        default_serial = 0;
3536
    }
3537
    if (machine->no_parallel) {
3538
        default_parallel = 0;
3539
    }
3540
    if (!machine->use_virtcon) {
3541
        default_virtcon = 0;
3542
    }
3543
    if (machine->no_floppy) {
3544
        default_floppy = 0;
3545
    }
3546
    if (machine->no_cdrom) {
3547
        default_cdrom = 0;
3548
    }
3549
    if (machine->no_sdcard) {
3550
        default_sdcard = 0;
3551
    }
3552

    
3553
    if (display_type == DT_NOGRAPHIC) {
3554
        if (default_parallel)
3555
            add_device_config(DEV_PARALLEL, "null");
3556
        if (default_serial && default_monitor) {
3557
            add_device_config(DEV_SERIAL, "mon:stdio");
3558
        } else if (default_virtcon && default_monitor) {
3559
            add_device_config(DEV_VIRTCON, "mon:stdio");
3560
        } else {
3561
            if (default_serial)
3562
                add_device_config(DEV_SERIAL, "stdio");
3563
            if (default_virtcon)
3564
                add_device_config(DEV_VIRTCON, "stdio");
3565
            if (default_monitor)
3566
                monitor_parse("stdio", "readline");
3567
        }
3568
    } else {
3569
        if (default_serial)
3570
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
3571
        if (default_parallel)
3572
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3573
        if (default_monitor)
3574
            monitor_parse("vc:80Cx24C", "readline");
3575
        if (default_virtcon)
3576
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3577
    }
3578

    
3579
    socket_init();
3580

    
3581
    if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)
3582
        exit(1);
3583
#ifdef CONFIG_VIRTFS
3584
    if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {
3585
        exit(1);
3586
    }
3587
#endif
3588

    
3589
    os_daemonize();
3590

    
3591
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3592
        os_pidfile_error();
3593
        exit(1);
3594
    }
3595

    
3596
    /* init the memory */
3597
    if (ram_size == 0) {
3598
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3599
    }
3600

    
3601
    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0)
3602
        != 0) {
3603
        exit(0);
3604
    }
3605

    
3606
    configure_accelerator();
3607

    
3608
    qemu_init_cpu_loop();
3609
    if (qemu_init_main_loop()) {
3610
        fprintf(stderr, "qemu_init_main_loop failed\n");
3611
        exit(1);
3612
    }
3613

    
3614
    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
3615
    if (machine_opts) {
3616
        kernel_filename = qemu_opt_get(machine_opts, "kernel");
3617
        initrd_filename = qemu_opt_get(machine_opts, "initrd");
3618
        kernel_cmdline = qemu_opt_get(machine_opts, "append");
3619
    } else {
3620
        kernel_filename = initrd_filename = kernel_cmdline = NULL;
3621
    }
3622

    
3623
    if (!kernel_cmdline) {
3624
        kernel_cmdline = "";
3625
    }
3626

    
3627
    linux_boot = (kernel_filename != NULL);
3628

    
3629
    if (!linux_boot && *kernel_cmdline != '\0') {
3630
        fprintf(stderr, "-append only allowed with -kernel option\n");
3631
        exit(1);
3632
    }
3633

    
3634
    if (!linux_boot && initrd_filename != NULL) {
3635
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3636
        exit(1);
3637
    }
3638

    
3639
    if (!linux_boot && machine_opts && qemu_opt_get(machine_opts, "dtb")) {
3640
        fprintf(stderr, "-dtb only allowed with -kernel option\n");
3641
        exit(1);
3642
    }
3643

    
3644
    os_set_line_buffering();
3645

    
3646
    if (init_timer_alarm() < 0) {
3647
        fprintf(stderr, "could not initialize alarm timer\n");
3648
        exit(1);
3649
    }
3650

    
3651
#ifdef CONFIG_SPICE
3652
    /* spice needs the timers to be initialized by this point */
3653
    qemu_spice_init();
3654
#endif
3655

    
3656
    if (icount_option && (kvm_enabled() || xen_enabled())) {
3657
        fprintf(stderr, "-icount is not allowed with kvm or xen\n");
3658
        exit(1);
3659
    }
3660
    configure_icount(icount_option);
3661

    
3662
    if (net_init_clients() < 0) {
3663
        exit(1);
3664
    }
3665

    
3666
    /* init the bluetooth world */
3667
    if (foreach_device_config(DEV_BT, bt_parse))
3668
        exit(1);
3669

    
3670
    if (!xen_enabled()) {
3671
        /* On 32-bit hosts, QEMU is limited by virtual address space */
3672
        if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
3673
            fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3674
            exit(1);
3675
        }
3676
    }
3677

    
3678
    cpu_exec_init_all();
3679

    
3680
    bdrv_init_with_whitelist();
3681

    
3682
    blk_mig_init();
3683

    
3684
    /* open the virtual block devices */
3685
    if (snapshot)
3686
        qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
3687
    if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)
3688
        exit(1);
3689

    
3690
    default_drive(default_cdrom, snapshot, machine->use_scsi,
3691
                  IF_DEFAULT, 2, CDROM_OPTS);
3692
    default_drive(default_floppy, snapshot, machine->use_scsi,
3693
                  IF_FLOPPY, 0, FD_OPTS);
3694
    default_drive(default_sdcard, snapshot, machine->use_scsi,
3695
                  IF_SD, 0, SD_OPTS);
3696

    
3697
    register_savevm_live(NULL, "ram", 0, 4, &savevm_ram_handlers, NULL);
3698

    
3699
    if (nb_numa_nodes > 0) {
3700
        int i;
3701

    
3702
        if (nb_numa_nodes > MAX_NODES) {
3703
            nb_numa_nodes = MAX_NODES;
3704
        }
3705

    
3706
        /* If no memory size if given for any node, assume the default case
3707
         * and distribute the available memory equally across all nodes
3708
         */
3709
        for (i = 0; i < nb_numa_nodes; i++) {
3710
            if (node_mem[i] != 0)
3711
                break;
3712
        }
3713
        if (i == nb_numa_nodes) {
3714
            uint64_t usedmem = 0;
3715

    
3716
            /* On Linux, the each node's border has to be 8MB aligned,
3717
             * the final node gets the rest.
3718
             */
3719
            for (i = 0; i < nb_numa_nodes - 1; i++) {
3720
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3721
                usedmem += node_mem[i];
3722
            }
3723
            node_mem[i] = ram_size - usedmem;
3724
        }
3725

    
3726
        for (i = 0; i < nb_numa_nodes; i++) {
3727
            if (!bitmap_empty(node_cpumask[i], MAX_CPUMASK_BITS)) {
3728
                break;
3729
            }
3730
        }
3731
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3732
         * must cope with this anyway, because there are BIOSes out there in
3733
         * real machines which also use this scheme.
3734
         */
3735
        if (i == nb_numa_nodes) {
3736
            for (i = 0; i < max_cpus; i++) {
3737
                set_bit(i, node_cpumask[i % nb_numa_nodes]);
3738
            }
3739
        }
3740
    }
3741

    
3742
    if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {
3743
        exit(1);
3744
    }
3745

    
3746
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3747
        exit(1);
3748
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3749
        exit(1);
3750
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3751
        exit(1);
3752
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3753
        exit(1);
3754

    
3755
    /* If no default VGA is requested, the default is "none".  */
3756
    if (default_vga) {
3757
        if (cirrus_vga_available()) {
3758
            vga_model = "cirrus";
3759
        } else if (vga_available()) {
3760
            vga_model = "std";
3761
        }
3762
    }
3763
    select_vgahw(vga_model);
3764

    
3765
    if (watchdog) {
3766
        i = select_watchdog(watchdog);
3767
        if (i > 0)
3768
            exit (i == 1 ? 1 : 0);
3769
    }
3770

    
3771
    if (machine->compat_props) {
3772
        qdev_prop_register_global_list(machine->compat_props);
3773
    }
3774
    qemu_add_globals();
3775

    
3776
    qdev_machine_init();
3777

    
3778
    QEMUMachineInitArgs args = { .ram_size = ram_size,
3779
                                 .boot_device = boot_devices,
3780
                                 .kernel_filename = kernel_filename,
3781
                                 .kernel_cmdline = kernel_cmdline,
3782
                                 .initrd_filename = initrd_filename,
3783
                                 .cpu_model = cpu_model };
3784
    machine->init(&args);
3785

    
3786
    cpu_synchronize_all_post_init();
3787

    
3788
    set_numa_modes();
3789

    
3790
    current_machine = machine;
3791

    
3792
    /* init USB devices */
3793
    if (usb_enabled(false)) {
3794
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3795
            exit(1);
3796
    }
3797

    
3798
    /* init generic devices */
3799
    if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)
3800
        exit(1);
3801

    
3802
    net_check_clients();
3803

    
3804
    /* just use the first displaystate for the moment */
3805
    ds = get_displaystate();
3806

    
3807
    if (using_spice)
3808
        display_remote++;
3809
    if (display_type == DT_DEFAULT && !display_remote) {
3810
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3811
        display_type = DT_SDL;
3812
#elif defined(CONFIG_VNC)
3813
        vnc_display = "localhost:0,to=99";
3814
        show_vnc_port = 1;
3815
#else
3816
        display_type = DT_NONE;
3817
#endif
3818
    }
3819

    
3820

    
3821
    /* init local displays */
3822
    switch (display_type) {
3823
    case DT_NOGRAPHIC:
3824
        break;
3825
#if defined(CONFIG_CURSES)
3826
    case DT_CURSES:
3827
        if (!is_daemonized()) {
3828
            curses_display_init(ds, full_screen);
3829
        }
3830
        break;
3831
#endif
3832
#if defined(CONFIG_SDL)
3833
    case DT_SDL:
3834
        sdl_display_init(ds, full_screen, no_frame);
3835
        break;
3836
#elif defined(CONFIG_COCOA)
3837
    case DT_SDL:
3838
        cocoa_display_init(ds, full_screen);
3839
        break;
3840
#endif
3841
    default:
3842
        break;
3843
    }
3844

    
3845
    /* must be after terminal init, SDL library changes signal handlers */
3846
    os_setup_signal_handling();
3847

    
3848
#ifdef CONFIG_VNC
3849
    /* init remote displays */
3850
    if (vnc_display) {
3851
        Error *local_err = NULL;
3852
        vnc_display_init(ds);
3853
        vnc_display_open(ds, vnc_display, &local_err);
3854
        if (local_err != NULL) {
3855
            fprintf(stderr, "Failed to start VNC server on `%s': %s\n",
3856
                    vnc_display, error_get_pretty(local_err));
3857
            error_free(local_err);
3858
            exit(1);
3859
        }
3860

    
3861
        if (show_vnc_port) {
3862
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3863
        }
3864
    }
3865
#endif
3866
#ifdef CONFIG_SPICE
3867
    if (using_spice && !qxl_enabled) {
3868
        qemu_spice_display_init(ds);
3869
    }
3870
#endif
3871

    
3872
    /* display setup */
3873
    dpy_resize(ds);
3874
    dcl = ds->listeners;
3875
    while (dcl != NULL) {
3876
        if (dcl->dpy_refresh != NULL) {
3877
            ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);
3878
            qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));
3879
            break;
3880
        }
3881
        dcl = dcl->next;
3882
    }
3883
    text_consoles_set_display(ds);
3884

    
3885
    if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
3886
        exit(1);
3887
    }
3888

    
3889
    qdev_machine_creation_done();
3890

    
3891
    if (rom_load_all() != 0) {
3892
        fprintf(stderr, "rom loading failed\n");
3893
        exit(1);
3894
    }
3895

    
3896
    /* TODO: once all bus devices are qdevified, this should be done
3897
     * when bus is created by qdev.c */
3898
    qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
3899
    qemu_run_machine_init_done_notifiers();
3900

    
3901
    qemu_system_reset(VMRESET_SILENT);
3902
    if (loadvm) {
3903
        if (load_vmstate(loadvm) < 0) {
3904
            autostart = 0;
3905
        }
3906
    }
3907

    
3908
    if (incoming) {
3909
        Error *local_err = NULL;
3910
        qemu_start_incoming_migration(incoming, &local_err);
3911
        if (local_err) {
3912
            fprintf(stderr, "-incoming %s: %s\n", incoming, error_get_pretty(local_err));
3913
            error_free(local_err);
3914
            exit(1);
3915
        }
3916
    } else if (autostart) {
3917
        vm_start();
3918
    }
3919

    
3920
    os_setup_post();
3921

    
3922
    resume_all_vcpus();
3923
    main_loop();
3924
    bdrv_close_all();
3925
    pause_all_vcpus();
3926
    net_cleanup();
3927
    res_free();
3928

    
3929
    return 0;
3930
}