Statistics
| Branch: | Revision:

root / vl.c @ 371c6489

History | View | Annotate | Download (101.4 kB)

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

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

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

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

    
64
#include <linux/ppdev.h>
65
#include <linux/parport.h>
66
#endif
67
#ifdef __sun__
68
#include <sys/stat.h>
69
#include <sys/ethernet.h>
70
#include <sys/sockio.h>
71
#include <netinet/arp.h>
72
#include <netinet/in_systm.h>
73
#include <netinet/ip.h>
74
#include <netinet/ip_icmp.h> // must come after ip.h
75
#include <netinet/udp.h>
76
#include <netinet/tcp.h>
77
#include <net/if.h>
78
#include <syslog.h>
79
#include <stropts.h>
80
#endif
81
#endif
82
#endif
83

    
84
#if defined(__OpenBSD__)
85
#include <util.h>
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 "block.h"
140
#include "blockdev.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

    
156
#include "disas.h"
157

    
158
#include "qemu_socket.h"
159

    
160
#include "slirp/libslirp.h"
161

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

    
168
#include "ui/qemu-spice.h"
169

    
170
//#define DEBUG_NET
171
//#define DEBUG_SLIRP
172

    
173
#define DEFAULT_RAM_SIZE 128
174

    
175
#define MAX_VIRTIO_CONSOLES 1
176

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

    
235
typedef struct FWBootEntry FWBootEntry;
236

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

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

    
246
int nb_numa_nodes;
247
uint64_t node_mem[MAX_NODES];
248
uint64_t node_cpumask[MAX_NODES];
249

    
250
uint8_t qemu_uuid[16];
251

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

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

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

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

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

    
276
static struct {
277
    const char *driver;
278
    int *flag;
279
} default_list[] = {
280
    { .driver = "isa-serial",           .flag = &default_serial    },
281
    { .driver = "isa-parallel",         .flag = &default_parallel  },
282
    { .driver = "isa-fdc",              .flag = &default_floppy    },
283
    { .driver = "ide-cd",               .flag = &default_cdrom     },
284
    { .driver = "ide-hd",               .flag = &default_cdrom     },
285
    { .driver = "ide-drive",            .flag = &default_cdrom     },
286
    { .driver = "scsi-cd",              .flag = &default_cdrom     },
287
    { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
288
    { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
289
    { .driver = "virtio-serial",        .flag = &default_virtcon   },
290
};
291

    
292
static void res_free(void)
293
{
294
    if (boot_splash_filedata != NULL) {
295
        g_free(boot_splash_filedata);
296
        boot_splash_filedata = NULL;
297
    }
298
}
299

    
300
static int default_driver_check(QemuOpts *opts, void *opaque)
301
{
302
    const char *driver = qemu_opt_get(opts, "driver");
303
    int i;
304

    
305
    if (!driver)
306
        return 0;
307
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
308
        if (strcmp(default_list[i].driver, driver) != 0)
309
            continue;
310
        *(default_list[i].flag) = 0;
311
    }
312
    return 0;
313
}
314

    
315
/***********************************************************/
316
/* QEMU state */
317

    
318
static RunState current_run_state = RUN_STATE_PRELAUNCH;
319

    
320
typedef struct {
321
    RunState from;
322
    RunState to;
323
} RunStateTransition;
324

    
325
static const RunStateTransition runstate_transitions_def[] = {
326
    /*     from      ->     to      */
327
    { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
328

    
329
    { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
330
    { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
331

    
332
    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
333
    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
334

    
335
    { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
336
    { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
337

    
338
    { RUN_STATE_PAUSED, RUN_STATE_RUNNING },
339
    { RUN_STATE_PAUSED, RUN_STATE_FINISH_MIGRATE },
340

    
341
    { RUN_STATE_POSTMIGRATE, RUN_STATE_RUNNING },
342
    { RUN_STATE_POSTMIGRATE, RUN_STATE_FINISH_MIGRATE },
343

    
344
    { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
345
    { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
346
    { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
347

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

    
351
    { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
352

    
353
    { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
354
    { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
355
    { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
356
    { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
357
    { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
358
    { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
359
    { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
360
    { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
361
    { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
362

    
363
    { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
364

    
365
    { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
366
    { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
367

    
368
    { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
369
    { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
370

    
371
    { RUN_STATE_MAX, RUN_STATE_MAX },
372
};
373

    
374
static bool runstate_valid_transitions[RUN_STATE_MAX][RUN_STATE_MAX];
375

    
376
bool runstate_check(RunState state)
377
{
378
    return current_run_state == state;
379
}
380

    
381
void runstate_init(void)
382
{
383
    const RunStateTransition *p;
384

    
385
    memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
386

    
387
    for (p = &runstate_transitions_def[0]; p->from != RUN_STATE_MAX; p++) {
388
        runstate_valid_transitions[p->from][p->to] = true;
389
    }
390
}
391

    
392
/* This function will abort() on invalid state transitions */
393
void runstate_set(RunState new_state)
394
{
395
    assert(new_state < RUN_STATE_MAX);
396

    
397
    if (!runstate_valid_transitions[current_run_state][new_state]) {
398
        fprintf(stderr, "ERROR: invalid runstate transition: '%s' -> '%s'\n",
399
                RunState_lookup[current_run_state],
400
                RunState_lookup[new_state]);
401
        abort();
402
    }
403

    
404
    current_run_state = new_state;
405
}
406

    
407
int runstate_is_running(void)
408
{
409
    return runstate_check(RUN_STATE_RUNNING);
410
}
411

    
412
StatusInfo *qmp_query_status(Error **errp)
413
{
414
    StatusInfo *info = g_malloc0(sizeof(*info));
415

    
416
    info->running = runstate_is_running();
417
    info->singlestep = singlestep;
418
    info->status = current_run_state;
419

    
420
    return info;
421
}
422

    
423
/***********************************************************/
424
/* real time host monotonic timer */
425

    
426
/***********************************************************/
427
/* host time/date access */
428
void qemu_get_timedate(struct tm *tm, int offset)
429
{
430
    time_t ti;
431
    struct tm *ret;
432

    
433
    time(&ti);
434
    ti += offset;
435
    if (rtc_date_offset == -1) {
436
        if (rtc_utc)
437
            ret = gmtime(&ti);
438
        else
439
            ret = localtime(&ti);
440
    } else {
441
        ti -= rtc_date_offset;
442
        ret = gmtime(&ti);
443
    }
444

    
445
    memcpy(tm, ret, sizeof(struct tm));
446
}
447

    
448
int qemu_timedate_diff(struct tm *tm)
449
{
450
    time_t seconds;
451

    
452
    if (rtc_date_offset == -1)
453
        if (rtc_utc)
454
            seconds = mktimegm(tm);
455
        else {
456
            struct tm tmp = *tm;
457
            tmp.tm_isdst = -1; /* use timezone to figure it out */
458
            seconds = mktime(&tmp);
459
        }
460
    else
461
        seconds = mktimegm(tm) + rtc_date_offset;
462

    
463
    return seconds - time(NULL);
464
}
465

    
466
void rtc_change_mon_event(struct tm *tm)
467
{
468
    QObject *data;
469

    
470
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
471
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
472
    qobject_decref(data);
473
}
474

    
475
static void configure_rtc_date_offset(const char *startdate, int legacy)
476
{
477
    time_t rtc_start_date;
478
    struct tm tm;
479

    
480
    if (!strcmp(startdate, "now") && legacy) {
481
        rtc_date_offset = -1;
482
    } else {
483
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
484
                   &tm.tm_year,
485
                   &tm.tm_mon,
486
                   &tm.tm_mday,
487
                   &tm.tm_hour,
488
                   &tm.tm_min,
489
                   &tm.tm_sec) == 6) {
490
            /* OK */
491
        } else if (sscanf(startdate, "%d-%d-%d",
492
                          &tm.tm_year,
493
                          &tm.tm_mon,
494
                          &tm.tm_mday) == 3) {
495
            tm.tm_hour = 0;
496
            tm.tm_min = 0;
497
            tm.tm_sec = 0;
498
        } else {
499
            goto date_fail;
500
        }
501
        tm.tm_year -= 1900;
502
        tm.tm_mon--;
503
        rtc_start_date = mktimegm(&tm);
504
        if (rtc_start_date == -1) {
505
        date_fail:
506
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
507
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
508
            exit(1);
509
        }
510
        rtc_date_offset = time(NULL) - rtc_start_date;
511
    }
512
}
513

    
514
static void configure_rtc(QemuOpts *opts)
515
{
516
    const char *value;
517

    
518
    value = qemu_opt_get(opts, "base");
519
    if (value) {
520
        if (!strcmp(value, "utc")) {
521
            rtc_utc = 1;
522
        } else if (!strcmp(value, "localtime")) {
523
            rtc_utc = 0;
524
        } else {
525
            configure_rtc_date_offset(value, 0);
526
        }
527
    }
528
    value = qemu_opt_get(opts, "clock");
529
    if (value) {
530
        if (!strcmp(value, "host")) {
531
            rtc_clock = host_clock;
532
        } else if (!strcmp(value, "vm")) {
533
            rtc_clock = vm_clock;
534
        } else {
535
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
536
            exit(1);
537
        }
538
    }
539
    value = qemu_opt_get(opts, "driftfix");
540
    if (value) {
541
        if (!strcmp(value, "slew")) {
542
            static GlobalProperty slew_lost_ticks[] = {
543
                {
544
                    .driver   = "mc146818rtc",
545
                    .property = "lost_tick_policy",
546
                    .value    = "slew",
547
                },
548
                { /* end of list */ }
549
            };
550

    
551
            qdev_prop_register_global_list(slew_lost_ticks);
552
        } else if (!strcmp(value, "none")) {
553
            /* discard is default */
554
        } else {
555
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
556
            exit(1);
557
        }
558
    }
559
}
560

    
561
/***********************************************************/
562
/* Bluetooth support */
563
static int nb_hcis;
564
static int cur_hci;
565
static struct HCIInfo *hci_table[MAX_NICS];
566

    
567
static struct bt_vlan_s {
568
    struct bt_scatternet_s net;
569
    int id;
570
    struct bt_vlan_s *next;
571
} *first_bt_vlan;
572

    
573
/* find or alloc a new bluetooth "VLAN" */
574
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
575
{
576
    struct bt_vlan_s **pvlan, *vlan;
577
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
578
        if (vlan->id == id)
579
            return &vlan->net;
580
    }
581
    vlan = g_malloc0(sizeof(struct bt_vlan_s));
582
    vlan->id = id;
583
    pvlan = &first_bt_vlan;
584
    while (*pvlan != NULL)
585
        pvlan = &(*pvlan)->next;
586
    *pvlan = vlan;
587
    return &vlan->net;
588
}
589

    
590
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
591
{
592
}
593

    
594
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
595
{
596
    return -ENOTSUP;
597
}
598

    
599
static struct HCIInfo null_hci = {
600
    .cmd_send = null_hci_send,
601
    .sco_send = null_hci_send,
602
    .acl_send = null_hci_send,
603
    .bdaddr_set = null_hci_addr_set,
604
};
605

    
606
struct HCIInfo *qemu_next_hci(void)
607
{
608
    if (cur_hci == nb_hcis)
609
        return &null_hci;
610

    
611
    return hci_table[cur_hci++];
612
}
613

    
614
static struct HCIInfo *hci_init(const char *str)
615
{
616
    char *endp;
617
    struct bt_scatternet_s *vlan = 0;
618

    
619
    if (!strcmp(str, "null"))
620
        /* null */
621
        return &null_hci;
622
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
623
        /* host[:hciN] */
624
        return bt_host_hci(str[4] ? str + 5 : "hci0");
625
    else if (!strncmp(str, "hci", 3)) {
626
        /* hci[,vlan=n] */
627
        if (str[3]) {
628
            if (!strncmp(str + 3, ",vlan=", 6)) {
629
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
630
                if (*endp)
631
                    vlan = 0;
632
            }
633
        } else
634
            vlan = qemu_find_bt_vlan(0);
635
        if (vlan)
636
           return bt_new_hci(vlan);
637
    }
638

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

    
641
    return 0;
642
}
643

    
644
static int bt_hci_parse(const char *str)
645
{
646
    struct HCIInfo *hci;
647
    bdaddr_t bdaddr;
648

    
649
    if (nb_hcis >= MAX_NICS) {
650
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
651
        return -1;
652
    }
653

    
654
    hci = hci_init(str);
655
    if (!hci)
656
        return -1;
657

    
658
    bdaddr.b[0] = 0x52;
659
    bdaddr.b[1] = 0x54;
660
    bdaddr.b[2] = 0x00;
661
    bdaddr.b[3] = 0x12;
662
    bdaddr.b[4] = 0x34;
663
    bdaddr.b[5] = 0x56 + nb_hcis;
664
    hci->bdaddr_set(hci, bdaddr.b);
665

    
666
    hci_table[nb_hcis++] = hci;
667

    
668
    return 0;
669
}
670

    
671
static void bt_vhci_add(int vlan_id)
672
{
673
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
674

    
675
    if (!vlan->slave)
676
        fprintf(stderr, "qemu: warning: adding a VHCI to "
677
                        "an empty scatternet %i\n", vlan_id);
678

    
679
    bt_vhci_init(bt_new_hci(vlan));
680
}
681

    
682
static struct bt_device_s *bt_device_add(const char *opt)
683
{
684
    struct bt_scatternet_s *vlan;
685
    int vlan_id = 0;
686
    char *endp = strstr(opt, ",vlan=");
687
    int len = (endp ? endp - opt : strlen(opt)) + 1;
688
    char devname[10];
689

    
690
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
691

    
692
    if (endp) {
693
        vlan_id = strtol(endp + 6, &endp, 0);
694
        if (*endp) {
695
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
696
            return 0;
697
        }
698
    }
699

    
700
    vlan = qemu_find_bt_vlan(vlan_id);
701

    
702
    if (!vlan->slave)
703
        fprintf(stderr, "qemu: warning: adding a slave device to "
704
                        "an empty scatternet %i\n", vlan_id);
705

    
706
    if (!strcmp(devname, "keyboard"))
707
        return bt_keyboard_init(vlan);
708

    
709
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
710
    return 0;
711
}
712

    
713
static int bt_parse(const char *opt)
714
{
715
    const char *endp, *p;
716
    int vlan;
717

    
718
    if (strstart(opt, "hci", &endp)) {
719
        if (!*endp || *endp == ',') {
720
            if (*endp)
721
                if (!strstart(endp, ",vlan=", 0))
722
                    opt = endp + 1;
723

    
724
            return bt_hci_parse(opt);
725
       }
726
    } else if (strstart(opt, "vhci", &endp)) {
727
        if (!*endp || *endp == ',') {
728
            if (*endp) {
729
                if (strstart(endp, ",vlan=", &p)) {
730
                    vlan = strtol(p, (char **) &endp, 0);
731
                    if (*endp) {
732
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
733
                        return 1;
734
                    }
735
                } else {
736
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
737
                    return 1;
738
                }
739
            } else
740
                vlan = 0;
741

    
742
            bt_vhci_add(vlan);
743
            return 0;
744
        }
745
    } else if (strstart(opt, "device:", &endp))
746
        return !bt_device_add(endp);
747

    
748
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
749
    return 1;
750
}
751

    
752
/***********************************************************/
753
/* QEMU Block devices */
754

    
755
#define HD_OPTS "media=disk"
756
#define CDROM_OPTS "media=cdrom"
757
#define FD_OPTS ""
758
#define PFLASH_OPTS ""
759
#define MTD_OPTS ""
760
#define SD_OPTS ""
761

    
762
static int drive_init_func(QemuOpts *opts, void *opaque)
763
{
764
    int *use_scsi = opaque;
765

    
766
    return drive_init(opts, *use_scsi) == NULL;
767
}
768

    
769
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
770
{
771
    if (NULL == qemu_opt_get(opts, "snapshot")) {
772
        qemu_opt_set(opts, "snapshot", "on");
773
    }
774
    return 0;
775
}
776

    
777
static void default_drive(int enable, int snapshot, int use_scsi,
778
                          BlockInterfaceType type, int index,
779
                          const char *optstr)
780
{
781
    QemuOpts *opts;
782

    
783
    if (type == IF_DEFAULT) {
784
        type = use_scsi ? IF_SCSI : IF_IDE;
785
    }
786

    
787
    if (!enable || drive_get_by_index(type, index)) {
788
        return;
789
    }
790

    
791
    opts = drive_add(type, index, NULL, optstr);
792
    if (snapshot) {
793
        drive_enable_snapshot(opts, NULL);
794
    }
795
    if (!drive_init(opts, use_scsi)) {
796
        exit(1);
797
    }
798
}
799

    
800
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
801
{
802
    boot_set_handler = func;
803
    boot_set_opaque = opaque;
804
}
805

    
806
int qemu_boot_set(const char *boot_devices)
807
{
808
    if (!boot_set_handler) {
809
        return -EINVAL;
810
    }
811
    return boot_set_handler(boot_set_opaque, boot_devices);
812
}
813

    
814
static void validate_bootdevices(char *devices)
815
{
816
    /* We just do some generic consistency checks */
817
    const char *p;
818
    int bitmap = 0;
819

    
820
    for (p = devices; *p != '\0'; p++) {
821
        /* Allowed boot devices are:
822
         * a-b: floppy disk drives
823
         * c-f: IDE disk drives
824
         * g-m: machine implementation dependent drives
825
         * n-p: network devices
826
         * It's up to each machine implementation to check if the given boot
827
         * devices match the actual hardware implementation and firmware
828
         * features.
829
         */
830
        if (*p < 'a' || *p > 'p') {
831
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
832
            exit(1);
833
        }
834
        if (bitmap & (1 << (*p - 'a'))) {
835
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
836
            exit(1);
837
        }
838
        bitmap |= 1 << (*p - 'a');
839
    }
840
}
841

    
842
static void restore_boot_devices(void *opaque)
843
{
844
    char *standard_boot_devices = opaque;
845
    static int first = 1;
846

    
847
    /* Restore boot order and remove ourselves after the first boot */
848
    if (first) {
849
        first = 0;
850
        return;
851
    }
852

    
853
    qemu_boot_set(standard_boot_devices);
854

    
855
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
856
    g_free(standard_boot_devices);
857
}
858

    
859
void add_boot_device_path(int32_t bootindex, DeviceState *dev,
860
                          const char *suffix)
861
{
862
    FWBootEntry *node, *i;
863

    
864
    if (bootindex < 0) {
865
        return;
866
    }
867

    
868
    assert(dev != NULL || suffix != NULL);
869

    
870
    node = g_malloc0(sizeof(FWBootEntry));
871
    node->bootindex = bootindex;
872
    node->suffix = suffix ? g_strdup(suffix) : NULL;
873
    node->dev = dev;
874

    
875
    QTAILQ_FOREACH(i, &fw_boot_order, link) {
876
        if (i->bootindex == bootindex) {
877
            fprintf(stderr, "Two devices with same boot index %d\n", bootindex);
878
            exit(1);
879
        } else if (i->bootindex < bootindex) {
880
            continue;
881
        }
882
        QTAILQ_INSERT_BEFORE(i, node, link);
883
        return;
884
    }
885
    QTAILQ_INSERT_TAIL(&fw_boot_order, node, link);
886
}
887

    
888
/*
889
 * This function returns null terminated string that consist of new line
890
 * separated device paths.
891
 *
892
 * memory pointed by "size" is assigned total length of the array in bytes
893
 *
894
 */
895
char *get_boot_devices_list(uint32_t *size)
896
{
897
    FWBootEntry *i;
898
    uint32_t total = 0;
899
    char *list = NULL;
900

    
901
    QTAILQ_FOREACH(i, &fw_boot_order, link) {
902
        char *devpath = NULL, *bootpath;
903
        int len;
904

    
905
        if (i->dev) {
906
            devpath = qdev_get_fw_dev_path(i->dev);
907
            assert(devpath);
908
        }
909

    
910
        if (i->suffix && devpath) {
911
            size_t bootpathlen = strlen(devpath) + strlen(i->suffix) + 1;
912

    
913
            bootpath = g_malloc(bootpathlen);
914
            snprintf(bootpath, bootpathlen, "%s%s", devpath, i->suffix);
915
            g_free(devpath);
916
        } else if (devpath) {
917
            bootpath = devpath;
918
        } else {
919
            assert(i->suffix);
920
            bootpath = g_strdup(i->suffix);
921
        }
922

    
923
        if (total) {
924
            list[total-1] = '\n';
925
        }
926
        len = strlen(bootpath) + 1;
927
        list = g_realloc(list, total + len);
928
        memcpy(&list[total], bootpath, len);
929
        total += len;
930
        g_free(bootpath);
931
    }
932

    
933
    *size = total;
934

    
935
    return list;
936
}
937

    
938
static void numa_add(const char *optarg)
939
{
940
    char option[128];
941
    char *endptr;
942
    unsigned long long value, endvalue;
943
    int nodenr;
944

    
945
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
946
    if (!strcmp(option, "node")) {
947
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
948
            nodenr = nb_numa_nodes;
949
        } else {
950
            nodenr = strtoull(option, NULL, 10);
951
        }
952

    
953
        if (get_param_value(option, 128, "mem", optarg) == 0) {
954
            node_mem[nodenr] = 0;
955
        } else {
956
            int64_t sval;
957
            sval = strtosz(option, &endptr);
958
            if (sval < 0 || *endptr) {
959
                fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);
960
                exit(1);
961
            }
962
            node_mem[nodenr] = sval;
963
        }
964
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
965
            node_cpumask[nodenr] = 0;
966
        } else {
967
            value = strtoull(option, &endptr, 10);
968
            if (value >= 64) {
969
                value = 63;
970
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
971
            } else {
972
                if (*endptr == '-') {
973
                    endvalue = strtoull(endptr+1, &endptr, 10);
974
                    if (endvalue >= 63) {
975
                        endvalue = 62;
976
                        fprintf(stderr,
977
                            "only 63 CPUs in NUMA mode supported.\n");
978
                    }
979
                    value = (2ULL << endvalue) - (1ULL << value);
980
                } else {
981
                    value = 1ULL << value;
982
                }
983
            }
984
            node_cpumask[nodenr] = value;
985
        }
986
        nb_numa_nodes++;
987
    }
988
    return;
989
}
990

    
991
static void smp_parse(const char *optarg)
992
{
993
    int smp, sockets = 0, threads = 0, cores = 0;
994
    char *endptr;
995
    char option[128];
996

    
997
    smp = strtoul(optarg, &endptr, 10);
998
    if (endptr != optarg) {
999
        if (*endptr == ',') {
1000
            endptr++;
1001
        }
1002
    }
1003
    if (get_param_value(option, 128, "sockets", endptr) != 0)
1004
        sockets = strtoull(option, NULL, 10);
1005
    if (get_param_value(option, 128, "cores", endptr) != 0)
1006
        cores = strtoull(option, NULL, 10);
1007
    if (get_param_value(option, 128, "threads", endptr) != 0)
1008
        threads = strtoull(option, NULL, 10);
1009
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1010
        max_cpus = strtoull(option, NULL, 10);
1011

    
1012
    /* compute missing values, prefer sockets over cores over threads */
1013
    if (smp == 0 || sockets == 0) {
1014
        sockets = sockets > 0 ? sockets : 1;
1015
        cores = cores > 0 ? cores : 1;
1016
        threads = threads > 0 ? threads : 1;
1017
        if (smp == 0) {
1018
            smp = cores * threads * sockets;
1019
        }
1020
    } else {
1021
        if (cores == 0) {
1022
            threads = threads > 0 ? threads : 1;
1023
            cores = smp / (sockets * threads);
1024
        } else {
1025
            threads = smp / (cores * sockets);
1026
        }
1027
    }
1028
    smp_cpus = smp;
1029
    smp_cores = cores > 0 ? cores : 1;
1030
    smp_threads = threads > 0 ? threads : 1;
1031
    if (max_cpus == 0)
1032
        max_cpus = smp_cpus;
1033
}
1034

    
1035
/***********************************************************/
1036
/* USB devices */
1037

    
1038
static int usb_device_add(const char *devname)
1039
{
1040
    const char *p;
1041
    USBDevice *dev = NULL;
1042

    
1043
    if (!usb_enabled)
1044
        return -1;
1045

    
1046
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1047
    dev = usbdevice_create(devname);
1048
    if (dev)
1049
        goto done;
1050

    
1051
    /* the other ones */
1052
#ifndef CONFIG_LINUX
1053
    /* only the linux version is qdev-ified, usb-bsd still needs this */
1054
    if (strstart(devname, "host:", &p)) {
1055
        dev = usb_host_device_open(usb_bus_find(-1), p);
1056
    } else
1057
#endif
1058
    if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1059
        dev = usb_bt_init(usb_bus_find(-1),
1060
                          devname[2] ? hci_init(p)
1061
                                     : bt_new_hci(qemu_find_bt_vlan(0)));
1062
    } else {
1063
        return -1;
1064
    }
1065
    if (!dev)
1066
        return -1;
1067

    
1068
done:
1069
    return 0;
1070
}
1071

    
1072
static int usb_device_del(const char *devname)
1073
{
1074
    int bus_num, addr;
1075
    const char *p;
1076

    
1077
    if (strstart(devname, "host:", &p))
1078
        return usb_host_device_close(p);
1079

    
1080
    if (!usb_enabled)
1081
        return -1;
1082

    
1083
    p = strchr(devname, '.');
1084
    if (!p)
1085
        return -1;
1086
    bus_num = strtoul(devname, NULL, 0);
1087
    addr = strtoul(p + 1, NULL, 0);
1088

    
1089
    return usb_device_delete_addr(bus_num, addr);
1090
}
1091

    
1092
static int usb_parse(const char *cmdline)
1093
{
1094
    int r;
1095
    r = usb_device_add(cmdline);
1096
    if (r < 0) {
1097
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1098
    }
1099
    return r;
1100
}
1101

    
1102
void do_usb_add(Monitor *mon, const QDict *qdict)
1103
{
1104
    const char *devname = qdict_get_str(qdict, "devname");
1105
    if (usb_device_add(devname) < 0) {
1106
        error_report("could not add USB device '%s'", devname);
1107
    }
1108
}
1109

    
1110
void do_usb_del(Monitor *mon, const QDict *qdict)
1111
{
1112
    const char *devname = qdict_get_str(qdict, "devname");
1113
    if (usb_device_del(devname) < 0) {
1114
        error_report("could not delete USB device '%s'", devname);
1115
    }
1116
}
1117

    
1118
/***********************************************************/
1119
/* PCMCIA/Cardbus */
1120

    
1121
static struct pcmcia_socket_entry_s {
1122
    PCMCIASocket *socket;
1123
    struct pcmcia_socket_entry_s *next;
1124
} *pcmcia_sockets = 0;
1125

    
1126
void pcmcia_socket_register(PCMCIASocket *socket)
1127
{
1128
    struct pcmcia_socket_entry_s *entry;
1129

    
1130
    entry = g_malloc(sizeof(struct pcmcia_socket_entry_s));
1131
    entry->socket = socket;
1132
    entry->next = pcmcia_sockets;
1133
    pcmcia_sockets = entry;
1134
}
1135

    
1136
void pcmcia_socket_unregister(PCMCIASocket *socket)
1137
{
1138
    struct pcmcia_socket_entry_s *entry, **ptr;
1139

    
1140
    ptr = &pcmcia_sockets;
1141
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1142
        if (entry->socket == socket) {
1143
            *ptr = entry->next;
1144
            g_free(entry);
1145
        }
1146
}
1147

    
1148
void pcmcia_info(Monitor *mon)
1149
{
1150
    struct pcmcia_socket_entry_s *iter;
1151

    
1152
    if (!pcmcia_sockets)
1153
        monitor_printf(mon, "No PCMCIA sockets\n");
1154

    
1155
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1156
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1157
                       iter->socket->attached ? iter->socket->card_string :
1158
                       "Empty");
1159
}
1160

    
1161
/***********************************************************/
1162
/* machine registration */
1163

    
1164
static QEMUMachine *first_machine = NULL;
1165
QEMUMachine *current_machine = NULL;
1166

    
1167
int qemu_register_machine(QEMUMachine *m)
1168
{
1169
    QEMUMachine **pm;
1170
    pm = &first_machine;
1171
    while (*pm != NULL)
1172
        pm = &(*pm)->next;
1173
    m->next = NULL;
1174
    *pm = m;
1175
    return 0;
1176
}
1177

    
1178
static QEMUMachine *find_machine(const char *name)
1179
{
1180
    QEMUMachine *m;
1181

    
1182
    for(m = first_machine; m != NULL; m = m->next) {
1183
        if (!strcmp(m->name, name))
1184
            return m;
1185
        if (m->alias && !strcmp(m->alias, name))
1186
            return m;
1187
    }
1188
    return NULL;
1189
}
1190

    
1191
QEMUMachine *find_default_machine(void)
1192
{
1193
    QEMUMachine *m;
1194

    
1195
    for(m = first_machine; m != NULL; m = m->next) {
1196
        if (m->is_default) {
1197
            return m;
1198
        }
1199
    }
1200
    return NULL;
1201
}
1202

    
1203
/***********************************************************/
1204
/* main execution loop */
1205

    
1206
static void gui_update(void *opaque)
1207
{
1208
    uint64_t interval = GUI_REFRESH_INTERVAL;
1209
    DisplayState *ds = opaque;
1210
    DisplayChangeListener *dcl = ds->listeners;
1211

    
1212
    dpy_refresh(ds);
1213

    
1214
    while (dcl != NULL) {
1215
        if (dcl->gui_timer_interval &&
1216
            dcl->gui_timer_interval < interval)
1217
            interval = dcl->gui_timer_interval;
1218
        dcl = dcl->next;
1219
    }
1220
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock_ms(rt_clock));
1221
}
1222

    
1223
struct vm_change_state_entry {
1224
    VMChangeStateHandler *cb;
1225
    void *opaque;
1226
    QLIST_ENTRY (vm_change_state_entry) entries;
1227
};
1228

    
1229
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1230

    
1231
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1232
                                                     void *opaque)
1233
{
1234
    VMChangeStateEntry *e;
1235

    
1236
    e = g_malloc0(sizeof (*e));
1237

    
1238
    e->cb = cb;
1239
    e->opaque = opaque;
1240
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1241
    return e;
1242
}
1243

    
1244
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1245
{
1246
    QLIST_REMOVE (e, entries);
1247
    g_free (e);
1248
}
1249

    
1250
void vm_state_notify(int running, RunState state)
1251
{
1252
    VMChangeStateEntry *e;
1253

    
1254
    trace_vm_state_notify(running, state);
1255

    
1256
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1257
        e->cb(e->opaque, running, state);
1258
    }
1259
}
1260

    
1261
void vm_start(void)
1262
{
1263
    if (!runstate_is_running()) {
1264
        cpu_enable_ticks();
1265
        runstate_set(RUN_STATE_RUNNING);
1266
        vm_state_notify(1, RUN_STATE_RUNNING);
1267
        resume_all_vcpus();
1268
        monitor_protocol_event(QEVENT_RESUME, NULL);
1269
    }
1270
}
1271

    
1272
/* reset/shutdown handler */
1273

    
1274
typedef struct QEMUResetEntry {
1275
    QTAILQ_ENTRY(QEMUResetEntry) entry;
1276
    QEMUResetHandler *func;
1277
    void *opaque;
1278
} QEMUResetEntry;
1279

    
1280
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1281
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1282
static int reset_requested;
1283
static int shutdown_requested, shutdown_signal = -1;
1284
static pid_t shutdown_pid;
1285
static int powerdown_requested;
1286
static int debug_requested;
1287
static int suspend_requested;
1288
static bool is_suspended;
1289
static NotifierList suspend_notifiers =
1290
    NOTIFIER_LIST_INITIALIZER(suspend_notifiers);
1291
static NotifierList wakeup_notifiers =
1292
    NOTIFIER_LIST_INITIALIZER(wakeup_notifiers);
1293
static uint32_t wakeup_reason_mask = ~0;
1294
static RunState vmstop_requested = RUN_STATE_MAX;
1295

    
1296
int qemu_shutdown_requested_get(void)
1297
{
1298
    return shutdown_requested;
1299
}
1300

    
1301
int qemu_reset_requested_get(void)
1302
{
1303
    return reset_requested;
1304
}
1305

    
1306
int qemu_shutdown_requested(void)
1307
{
1308
    int r = shutdown_requested;
1309
    shutdown_requested = 0;
1310
    return r;
1311
}
1312

    
1313
void qemu_kill_report(void)
1314
{
1315
    if (shutdown_signal != -1) {
1316
        fprintf(stderr, "qemu: terminating on signal %d", shutdown_signal);
1317
        if (shutdown_pid == 0) {
1318
            /* This happens for eg ^C at the terminal, so it's worth
1319
             * avoiding printing an odd message in that case.
1320
             */
1321
            fputc('\n', stderr);
1322
        } else {
1323
            fprintf(stderr, " from pid " FMT_pid "\n", shutdown_pid);
1324
        }
1325
        shutdown_signal = -1;
1326
    }
1327
}
1328

    
1329
int qemu_reset_requested(void)
1330
{
1331
    int r = reset_requested;
1332
    reset_requested = 0;
1333
    return r;
1334
}
1335

    
1336
static int qemu_suspend_requested(void)
1337
{
1338
    int r = suspend_requested;
1339
    suspend_requested = 0;
1340
    return r;
1341
}
1342

    
1343
int qemu_powerdown_requested(void)
1344
{
1345
    int r = powerdown_requested;
1346
    powerdown_requested = 0;
1347
    return r;
1348
}
1349

    
1350
static int qemu_debug_requested(void)
1351
{
1352
    int r = debug_requested;
1353
    debug_requested = 0;
1354
    return r;
1355
}
1356

    
1357
/* We use RUN_STATE_MAX but any invalid value will do */
1358
static bool qemu_vmstop_requested(RunState *r)
1359
{
1360
    if (vmstop_requested < RUN_STATE_MAX) {
1361
        *r = vmstop_requested;
1362
        vmstop_requested = RUN_STATE_MAX;
1363
        return true;
1364
    }
1365

    
1366
    return false;
1367
}
1368

    
1369
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1370
{
1371
    QEMUResetEntry *re = g_malloc0(sizeof(QEMUResetEntry));
1372

    
1373
    re->func = func;
1374
    re->opaque = opaque;
1375
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1376
}
1377

    
1378
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1379
{
1380
    QEMUResetEntry *re;
1381

    
1382
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1383
        if (re->func == func && re->opaque == opaque) {
1384
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1385
            g_free(re);
1386
            return;
1387
        }
1388
    }
1389
}
1390

    
1391
void qemu_system_reset(bool report)
1392
{
1393
    QEMUResetEntry *re, *nre;
1394

    
1395
    /* reset all devices */
1396
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1397
        re->func(re->opaque);
1398
    }
1399
    if (report) {
1400
        monitor_protocol_event(QEVENT_RESET, NULL);
1401
    }
1402
    cpu_synchronize_all_post_reset();
1403
}
1404

    
1405
void qemu_system_reset_request(void)
1406
{
1407
    if (no_reboot) {
1408
        shutdown_requested = 1;
1409
    } else {
1410
        reset_requested = 1;
1411
    }
1412
    cpu_stop_current();
1413
    qemu_notify_event();
1414
}
1415

    
1416
static void qemu_system_suspend(void)
1417
{
1418
    pause_all_vcpus();
1419
    notifier_list_notify(&suspend_notifiers, NULL);
1420
    monitor_protocol_event(QEVENT_SUSPEND, NULL);
1421
    is_suspended = true;
1422
}
1423

    
1424
void qemu_system_suspend_request(void)
1425
{
1426
    if (is_suspended) {
1427
        return;
1428
    }
1429
    suspend_requested = 1;
1430
    cpu_stop_current();
1431
    qemu_notify_event();
1432
}
1433

    
1434
void qemu_register_suspend_notifier(Notifier *notifier)
1435
{
1436
    notifier_list_add(&suspend_notifiers, notifier);
1437
}
1438

    
1439
void qemu_system_wakeup_request(WakeupReason reason)
1440
{
1441
    if (!is_suspended) {
1442
        return;
1443
    }
1444
    if (!(wakeup_reason_mask & (1 << reason))) {
1445
        return;
1446
    }
1447
    monitor_protocol_event(QEVENT_WAKEUP, NULL);
1448
    notifier_list_notify(&wakeup_notifiers, &reason);
1449
    reset_requested = 1;
1450
    qemu_notify_event();
1451
    is_suspended = false;
1452
}
1453

    
1454
void qemu_system_wakeup_enable(WakeupReason reason, bool enabled)
1455
{
1456
    if (enabled) {
1457
        wakeup_reason_mask |= (1 << reason);
1458
    } else {
1459
        wakeup_reason_mask &= ~(1 << reason);
1460
    }
1461
}
1462

    
1463
void qemu_register_wakeup_notifier(Notifier *notifier)
1464
{
1465
    notifier_list_add(&wakeup_notifiers, notifier);
1466
}
1467

    
1468
void qemu_system_killed(int signal, pid_t pid)
1469
{
1470
    shutdown_signal = signal;
1471
    shutdown_pid = pid;
1472
    no_shutdown = 0;
1473
    qemu_system_shutdown_request();
1474
}
1475

    
1476
void qemu_system_shutdown_request(void)
1477
{
1478
    shutdown_requested = 1;
1479
    qemu_notify_event();
1480
}
1481

    
1482
void qemu_system_powerdown_request(void)
1483
{
1484
    powerdown_requested = 1;
1485
    qemu_notify_event();
1486
}
1487

    
1488
void qemu_system_debug_request(void)
1489
{
1490
    debug_requested = 1;
1491
    qemu_notify_event();
1492
}
1493

    
1494
void qemu_system_vmstop_request(RunState state)
1495
{
1496
    vmstop_requested = state;
1497
    qemu_notify_event();
1498
}
1499

    
1500
qemu_irq qemu_system_powerdown;
1501

    
1502
static bool main_loop_should_exit(void)
1503
{
1504
    RunState r;
1505
    if (qemu_debug_requested()) {
1506
        vm_stop(RUN_STATE_DEBUG);
1507
    }
1508
    if (qemu_suspend_requested()) {
1509
        qemu_system_suspend();
1510
    }
1511
    if (qemu_shutdown_requested()) {
1512
        qemu_kill_report();
1513
        monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1514
        if (no_shutdown) {
1515
            vm_stop(RUN_STATE_SHUTDOWN);
1516
        } else {
1517
            return true;
1518
        }
1519
    }
1520
    if (qemu_reset_requested()) {
1521
        pause_all_vcpus();
1522
        cpu_synchronize_all_states();
1523
        qemu_system_reset(VMRESET_REPORT);
1524
        resume_all_vcpus();
1525
        if (runstate_check(RUN_STATE_INTERNAL_ERROR) ||
1526
            runstate_check(RUN_STATE_SHUTDOWN)) {
1527
            runstate_set(RUN_STATE_PAUSED);
1528
        }
1529
    }
1530
    if (qemu_powerdown_requested()) {
1531
        monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1532
        qemu_irq_raise(qemu_system_powerdown);
1533
    }
1534
    if (qemu_vmstop_requested(&r)) {
1535
        vm_stop(r);
1536
    }
1537
    return false;
1538
}
1539

    
1540
static void main_loop(void)
1541
{
1542
    bool nonblocking;
1543
    int last_io = 0;
1544
#ifdef CONFIG_PROFILER
1545
    int64_t ti;
1546
#endif
1547
    do {
1548
        nonblocking = !kvm_enabled() && last_io > 0;
1549
#ifdef CONFIG_PROFILER
1550
        ti = profile_getclock();
1551
#endif
1552
        last_io = main_loop_wait(nonblocking);
1553
#ifdef CONFIG_PROFILER
1554
        dev_time += profile_getclock() - ti;
1555
#endif
1556
    } while (!main_loop_should_exit());
1557
}
1558

    
1559
static void version(void)
1560
{
1561
    printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
1562
}
1563

    
1564
static void help(int exitcode)
1565
{
1566
    version();
1567
    printf("usage: %s [options] [disk_image]\n\n"
1568
           "'disk_image' is a raw hard disk image for IDE hard disk 0\n\n",
1569
            error_get_progname());
1570

    
1571
#define QEMU_OPTIONS_GENERATE_HELP
1572
#include "qemu-options-wrapper.h"
1573

    
1574
    printf("\nDuring emulation, the following keys are useful:\n"
1575
           "ctrl-alt-f      toggle full screen\n"
1576
           "ctrl-alt-n      switch to virtual console 'n'\n"
1577
           "ctrl-alt        toggle mouse and keyboard grab\n"
1578
           "\n"
1579
           "When using -nographic, press 'ctrl-a h' to get some help.\n");
1580

    
1581
    exit(exitcode);
1582
}
1583

    
1584
#define HAS_ARG 0x0001
1585

    
1586
typedef struct QEMUOption {
1587
    const char *name;
1588
    int flags;
1589
    int index;
1590
    uint32_t arch_mask;
1591
} QEMUOption;
1592

    
1593
static const QEMUOption qemu_options[] = {
1594
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1595
#define QEMU_OPTIONS_GENERATE_OPTIONS
1596
#include "qemu-options-wrapper.h"
1597
    { NULL },
1598
};
1599

    
1600
static bool vga_available(void)
1601
{
1602
    return qdev_exists("VGA") || qdev_exists("isa-vga");
1603
}
1604

    
1605
static bool cirrus_vga_available(void)
1606
{
1607
    return qdev_exists("cirrus-vga") || qdev_exists("isa-cirrus-vga");
1608
}
1609

    
1610
static bool vmware_vga_available(void)
1611
{
1612
    return qdev_exists("vmware-svga");
1613
}
1614

    
1615
static void select_vgahw (const char *p)
1616
{
1617
    const char *opts;
1618

    
1619
    vga_interface_type = VGA_NONE;
1620
    if (strstart(p, "std", &opts)) {
1621
        if (vga_available()) {
1622
            vga_interface_type = VGA_STD;
1623
        } else {
1624
            fprintf(stderr, "Error: standard VGA not available\n");
1625
            exit(0);
1626
        }
1627
    } else if (strstart(p, "cirrus", &opts)) {
1628
        if (cirrus_vga_available()) {
1629
            vga_interface_type = VGA_CIRRUS;
1630
        } else {
1631
            fprintf(stderr, "Error: Cirrus VGA not available\n");
1632
            exit(0);
1633
        }
1634
    } else if (strstart(p, "vmware", &opts)) {
1635
        if (vmware_vga_available()) {
1636
            vga_interface_type = VGA_VMWARE;
1637
        } else {
1638
            fprintf(stderr, "Error: VMWare SVGA not available\n");
1639
            exit(0);
1640
        }
1641
    } else if (strstart(p, "xenfb", &opts)) {
1642
        vga_interface_type = VGA_XENFB;
1643
    } else if (strstart(p, "qxl", &opts)) {
1644
        vga_interface_type = VGA_QXL;
1645
    } else if (!strstart(p, "none", &opts)) {
1646
    invalid_vga:
1647
        fprintf(stderr, "Unknown vga type: %s\n", p);
1648
        exit(1);
1649
    }
1650
    while (*opts) {
1651
        const char *nextopt;
1652

    
1653
        if (strstart(opts, ",retrace=", &nextopt)) {
1654
            opts = nextopt;
1655
            if (strstart(opts, "dumb", &nextopt))
1656
                vga_retrace_method = VGA_RETRACE_DUMB;
1657
            else if (strstart(opts, "precise", &nextopt))
1658
                vga_retrace_method = VGA_RETRACE_PRECISE;
1659
            else goto invalid_vga;
1660
        } else goto invalid_vga;
1661
        opts = nextopt;
1662
    }
1663
}
1664

    
1665
static DisplayType select_display(const char *p)
1666
{
1667
    const char *opts;
1668
    DisplayType display = DT_DEFAULT;
1669

    
1670
    if (strstart(p, "sdl", &opts)) {
1671
#ifdef CONFIG_SDL
1672
        display = DT_SDL;
1673
        while (*opts) {
1674
            const char *nextopt;
1675

    
1676
            if (strstart(opts, ",frame=", &nextopt)) {
1677
                opts = nextopt;
1678
                if (strstart(opts, "on", &nextopt)) {
1679
                    no_frame = 0;
1680
                } else if (strstart(opts, "off", &nextopt)) {
1681
                    no_frame = 1;
1682
                } else {
1683
                    goto invalid_sdl_args;
1684
                }
1685
            } else if (strstart(opts, ",alt_grab=", &nextopt)) {
1686
                opts = nextopt;
1687
                if (strstart(opts, "on", &nextopt)) {
1688
                    alt_grab = 1;
1689
                } else if (strstart(opts, "off", &nextopt)) {
1690
                    alt_grab = 0;
1691
                } else {
1692
                    goto invalid_sdl_args;
1693
                }
1694
            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1695
                opts = nextopt;
1696
                if (strstart(opts, "on", &nextopt)) {
1697
                    ctrl_grab = 1;
1698
                } else if (strstart(opts, "off", &nextopt)) {
1699
                    ctrl_grab = 0;
1700
                } else {
1701
                    goto invalid_sdl_args;
1702
                }
1703
            } else if (strstart(opts, ",window_close=", &nextopt)) {
1704
                opts = nextopt;
1705
                if (strstart(opts, "on", &nextopt)) {
1706
                    no_quit = 0;
1707
                } else if (strstart(opts, "off", &nextopt)) {
1708
                    no_quit = 1;
1709
                } else {
1710
                    goto invalid_sdl_args;
1711
                }
1712
            } else {
1713
            invalid_sdl_args:
1714
                fprintf(stderr, "Invalid SDL option string: %s\n", p);
1715
                exit(1);
1716
            }
1717
            opts = nextopt;
1718
        }
1719
#else
1720
        fprintf(stderr, "SDL support is disabled\n");
1721
        exit(1);
1722
#endif
1723
    } else if (strstart(p, "vnc", &opts)) {
1724
#ifdef CONFIG_VNC
1725
        display_remote++;
1726

    
1727
        if (*opts) {
1728
            const char *nextopt;
1729

    
1730
            if (strstart(opts, "=", &nextopt)) {
1731
                vnc_display = nextopt;
1732
            }
1733
        }
1734
        if (!vnc_display) {
1735
            fprintf(stderr, "VNC requires a display argument vnc=<display>\n");
1736
            exit(1);
1737
        }
1738
#else
1739
        fprintf(stderr, "VNC support is disabled\n");
1740
        exit(1);
1741
#endif
1742
    } else if (strstart(p, "curses", &opts)) {
1743
#ifdef CONFIG_CURSES
1744
        display = DT_CURSES;
1745
#else
1746
        fprintf(stderr, "Curses support is disabled\n");
1747
        exit(1);
1748
#endif
1749
    } else if (strstart(p, "none", &opts)) {
1750
        display = DT_NONE;
1751
    } else {
1752
        fprintf(stderr, "Unknown display type: %s\n", p);
1753
        exit(1);
1754
    }
1755

    
1756
    return display;
1757
}
1758

    
1759
static int balloon_parse(const char *arg)
1760
{
1761
    QemuOpts *opts;
1762

    
1763
    if (strcmp(arg, "none") == 0) {
1764
        return 0;
1765
    }
1766

    
1767
    if (!strncmp(arg, "virtio", 6)) {
1768
        if (arg[6] == ',') {
1769
            /* have params -> parse them */
1770
            opts = qemu_opts_parse(qemu_find_opts("device"), arg+7, 0);
1771
            if (!opts)
1772
                return  -1;
1773
        } else {
1774
            /* create empty opts */
1775
            opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
1776
        }
1777
        qemu_opt_set(opts, "driver", "virtio-balloon");
1778
        return 0;
1779
    }
1780

    
1781
    return -1;
1782
}
1783

    
1784
char *qemu_find_file(int type, const char *name)
1785
{
1786
    int len;
1787
    const char *subdir;
1788
    char *buf;
1789

    
1790
    /* If name contains path separators then try it as a straight path.  */
1791
    if ((strchr(name, '/') || strchr(name, '\\'))
1792
        && access(name, R_OK) == 0) {
1793
        return g_strdup(name);
1794
    }
1795
    switch (type) {
1796
    case QEMU_FILE_TYPE_BIOS:
1797
        subdir = "";
1798
        break;
1799
    case QEMU_FILE_TYPE_KEYMAP:
1800
        subdir = "keymaps/";
1801
        break;
1802
    default:
1803
        abort();
1804
    }
1805
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
1806
    buf = g_malloc0(len);
1807
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
1808
    if (access(buf, R_OK)) {
1809
        g_free(buf);
1810
        return NULL;
1811
    }
1812
    return buf;
1813
}
1814

    
1815
static int device_help_func(QemuOpts *opts, void *opaque)
1816
{
1817
    return qdev_device_help(opts);
1818
}
1819

    
1820
static int device_init_func(QemuOpts *opts, void *opaque)
1821
{
1822
    DeviceState *dev;
1823

    
1824
    dev = qdev_device_add(opts);
1825
    if (!dev)
1826
        return -1;
1827
    return 0;
1828
}
1829

    
1830
static int chardev_init_func(QemuOpts *opts, void *opaque)
1831
{
1832
    CharDriverState *chr;
1833

    
1834
    chr = qemu_chr_new_from_opts(opts, NULL);
1835
    if (!chr)
1836
        return -1;
1837
    return 0;
1838
}
1839

    
1840
#ifdef CONFIG_VIRTFS
1841
static int fsdev_init_func(QemuOpts *opts, void *opaque)
1842
{
1843
    int ret;
1844
    ret = qemu_fsdev_add(opts);
1845

    
1846
    return ret;
1847
}
1848
#endif
1849

    
1850
static int mon_init_func(QemuOpts *opts, void *opaque)
1851
{
1852
    CharDriverState *chr;
1853
    const char *chardev;
1854
    const char *mode;
1855
    int flags;
1856

    
1857
    mode = qemu_opt_get(opts, "mode");
1858
    if (mode == NULL) {
1859
        mode = "readline";
1860
    }
1861
    if (strcmp(mode, "readline") == 0) {
1862
        flags = MONITOR_USE_READLINE;
1863
    } else if (strcmp(mode, "control") == 0) {
1864
        flags = MONITOR_USE_CONTROL;
1865
    } else {
1866
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
1867
        exit(1);
1868
    }
1869

    
1870
    if (qemu_opt_get_bool(opts, "pretty", 0))
1871
        flags |= MONITOR_USE_PRETTY;
1872

    
1873
    if (qemu_opt_get_bool(opts, "default", 0))
1874
        flags |= MONITOR_IS_DEFAULT;
1875

    
1876
    chardev = qemu_opt_get(opts, "chardev");
1877
    chr = qemu_chr_find(chardev);
1878
    if (chr == NULL) {
1879
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
1880
        exit(1);
1881
    }
1882

    
1883
    monitor_init(chr, flags);
1884
    return 0;
1885
}
1886

    
1887
static void monitor_parse(const char *optarg, const char *mode)
1888
{
1889
    static int monitor_device_index = 0;
1890
    QemuOpts *opts;
1891
    const char *p;
1892
    char label[32];
1893
    int def = 0;
1894

    
1895
    if (strstart(optarg, "chardev:", &p)) {
1896
        snprintf(label, sizeof(label), "%s", p);
1897
    } else {
1898
        snprintf(label, sizeof(label), "compat_monitor%d",
1899
                 monitor_device_index);
1900
        if (monitor_device_index == 0) {
1901
            def = 1;
1902
        }
1903
        opts = qemu_chr_parse_compat(label, optarg);
1904
        if (!opts) {
1905
            fprintf(stderr, "parse error: %s\n", optarg);
1906
            exit(1);
1907
        }
1908
    }
1909

    
1910
    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1);
1911
    if (!opts) {
1912
        fprintf(stderr, "duplicate chardev: %s\n", label);
1913
        exit(1);
1914
    }
1915
    qemu_opt_set(opts, "mode", mode);
1916
    qemu_opt_set(opts, "chardev", label);
1917
    if (def)
1918
        qemu_opt_set(opts, "default", "on");
1919
    monitor_device_index++;
1920
}
1921

    
1922
struct device_config {
1923
    enum {
1924
        DEV_USB,       /* -usbdevice     */
1925
        DEV_BT,        /* -bt            */
1926
        DEV_SERIAL,    /* -serial        */
1927
        DEV_PARALLEL,  /* -parallel      */
1928
        DEV_VIRTCON,   /* -virtioconsole */
1929
        DEV_DEBUGCON,  /* -debugcon */
1930
        DEV_GDB,       /* -gdb, -s */
1931
    } type;
1932
    const char *cmdline;
1933
    Location loc;
1934
    QTAILQ_ENTRY(device_config) next;
1935
};
1936
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
1937

    
1938
static void add_device_config(int type, const char *cmdline)
1939
{
1940
    struct device_config *conf;
1941

    
1942
    conf = g_malloc0(sizeof(*conf));
1943
    conf->type = type;
1944
    conf->cmdline = cmdline;
1945
    loc_save(&conf->loc);
1946
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
1947
}
1948

    
1949
static int foreach_device_config(int type, int (*func)(const char *cmdline))
1950
{
1951
    struct device_config *conf;
1952
    int rc;
1953

    
1954
    QTAILQ_FOREACH(conf, &device_configs, next) {
1955
        if (conf->type != type)
1956
            continue;
1957
        loc_push_restore(&conf->loc);
1958
        rc = func(conf->cmdline);
1959
        loc_pop(&conf->loc);
1960
        if (0 != rc)
1961
            return rc;
1962
    }
1963
    return 0;
1964
}
1965

    
1966
static int serial_parse(const char *devname)
1967
{
1968
    static int index = 0;
1969
    char label[32];
1970

    
1971
    if (strcmp(devname, "none") == 0)
1972
        return 0;
1973
    if (index == MAX_SERIAL_PORTS) {
1974
        fprintf(stderr, "qemu: too many serial ports\n");
1975
        exit(1);
1976
    }
1977
    snprintf(label, sizeof(label), "serial%d", index);
1978
    serial_hds[index] = qemu_chr_new(label, devname, NULL);
1979
    if (!serial_hds[index]) {
1980
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
1981
                devname, strerror(errno));
1982
        return -1;
1983
    }
1984
    index++;
1985
    return 0;
1986
}
1987

    
1988
static int parallel_parse(const char *devname)
1989
{
1990
    static int index = 0;
1991
    char label[32];
1992

    
1993
    if (strcmp(devname, "none") == 0)
1994
        return 0;
1995
    if (index == MAX_PARALLEL_PORTS) {
1996
        fprintf(stderr, "qemu: too many parallel ports\n");
1997
        exit(1);
1998
    }
1999
    snprintf(label, sizeof(label), "parallel%d", index);
2000
    parallel_hds[index] = qemu_chr_new(label, devname, NULL);
2001
    if (!parallel_hds[index]) {
2002
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2003
                devname, strerror(errno));
2004
        return -1;
2005
    }
2006
    index++;
2007
    return 0;
2008
}
2009

    
2010
static int virtcon_parse(const char *devname)
2011
{
2012
    QemuOptsList *device = qemu_find_opts("device");
2013
    static int index = 0;
2014
    char label[32];
2015
    QemuOpts *bus_opts, *dev_opts;
2016

    
2017
    if (strcmp(devname, "none") == 0)
2018
        return 0;
2019
    if (index == MAX_VIRTIO_CONSOLES) {
2020
        fprintf(stderr, "qemu: too many virtio consoles\n");
2021
        exit(1);
2022
    }
2023

    
2024
    bus_opts = qemu_opts_create(device, NULL, 0);
2025
    if (arch_type == QEMU_ARCH_S390X) {
2026
        qemu_opt_set(bus_opts, "driver", "virtio-serial-s390");
2027
    } else {
2028
        qemu_opt_set(bus_opts, "driver", "virtio-serial-pci");
2029
    } 
2030

    
2031
    dev_opts = qemu_opts_create(device, NULL, 0);
2032
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2033

    
2034
    snprintf(label, sizeof(label), "virtcon%d", index);
2035
    virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
2036
    if (!virtcon_hds[index]) {
2037
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2038
                devname, strerror(errno));
2039
        return -1;
2040
    }
2041
    qemu_opt_set(dev_opts, "chardev", label);
2042

    
2043
    index++;
2044
    return 0;
2045
}
2046

    
2047
static int debugcon_parse(const char *devname)
2048
{   
2049
    QemuOpts *opts;
2050

    
2051
    if (!qemu_chr_new("debugcon", devname, NULL)) {
2052
        exit(1);
2053
    }
2054
    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1);
2055
    if (!opts) {
2056
        fprintf(stderr, "qemu: already have a debugcon device\n");
2057
        exit(1);
2058
    }
2059
    qemu_opt_set(opts, "driver", "isa-debugcon");
2060
    qemu_opt_set(opts, "chardev", "debugcon");
2061
    return 0;
2062
}
2063

    
2064
static QEMUMachine *machine_parse(const char *name)
2065
{
2066
    QEMUMachine *m, *machine = NULL;
2067

    
2068
    if (name) {
2069
        machine = find_machine(name);
2070
    }
2071
    if (machine) {
2072
        return machine;
2073
    }
2074
    printf("Supported machines are:\n");
2075
    for (m = first_machine; m != NULL; m = m->next) {
2076
        if (m->alias) {
2077
            printf("%-20s %s (alias of %s)\n", m->alias, m->desc, m->name);
2078
        }
2079
        printf("%-20s %s%s\n", m->name, m->desc,
2080
               m->is_default ? " (default)" : "");
2081
    }
2082
    exit(!name || *name != '?');
2083
}
2084

    
2085
static int tcg_init(void)
2086
{
2087
    tcg_exec_init(tcg_tb_size * 1024 * 1024);
2088
    return 0;
2089
}
2090

    
2091
static struct {
2092
    const char *opt_name;
2093
    const char *name;
2094
    int (*available)(void);
2095
    int (*init)(void);
2096
    int *allowed;
2097
} accel_list[] = {
2098
    { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
2099
    { "xen", "Xen", xen_available, xen_init, &xen_allowed },
2100
    { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
2101
};
2102

    
2103
static int configure_accelerator(void)
2104
{
2105
    const char *p = NULL;
2106
    char buf[10];
2107
    int i, ret;
2108
    bool accel_initialised = 0;
2109
    bool init_failed = 0;
2110

    
2111
    QemuOptsList *list = qemu_find_opts("machine");
2112
    if (!QTAILQ_EMPTY(&list->head)) {
2113
        p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
2114
    }
2115

    
2116
    if (p == NULL) {
2117
        /* Use the default "accelerator", tcg */
2118
        p = "tcg";
2119
    }
2120

    
2121
    while (!accel_initialised && *p != '\0') {
2122
        if (*p == ':') {
2123
            p++;
2124
        }
2125
        p = get_opt_name(buf, sizeof (buf), p, ':');
2126
        for (i = 0; i < ARRAY_SIZE(accel_list); i++) {
2127
            if (strcmp(accel_list[i].opt_name, buf) == 0) {
2128
                *(accel_list[i].allowed) = 1;
2129
                ret = accel_list[i].init();
2130
                if (ret < 0) {
2131
                    init_failed = 1;
2132
                    if (!accel_list[i].available()) {
2133
                        printf("%s not supported for this target\n",
2134
                               accel_list[i].name);
2135
                    } else {
2136
                        fprintf(stderr, "failed to initialize %s: %s\n",
2137
                                accel_list[i].name,
2138
                                strerror(-ret));
2139
                    }
2140
                    *(accel_list[i].allowed) = 0;
2141
                } else {
2142
                    accel_initialised = 1;
2143
                }
2144
                break;
2145
            }
2146
        }
2147
        if (i == ARRAY_SIZE(accel_list)) {
2148
            fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);
2149
        }
2150
    }
2151

    
2152
    if (!accel_initialised) {
2153
        fprintf(stderr, "No accelerator found!\n");
2154
        exit(1);
2155
    }
2156

    
2157
    if (init_failed) {
2158
        fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
2159
    }
2160

    
2161
    return !accel_initialised;
2162
}
2163

    
2164
void qemu_add_exit_notifier(Notifier *notify)
2165
{
2166
    notifier_list_add(&exit_notifiers, notify);
2167
}
2168

    
2169
void qemu_remove_exit_notifier(Notifier *notify)
2170
{
2171
    notifier_remove(notify);
2172
}
2173

    
2174
static void qemu_run_exit_notifiers(void)
2175
{
2176
    notifier_list_notify(&exit_notifiers, NULL);
2177
}
2178

    
2179
void qemu_add_machine_init_done_notifier(Notifier *notify)
2180
{
2181
    notifier_list_add(&machine_init_done_notifiers, notify);
2182
}
2183

    
2184
static void qemu_run_machine_init_done_notifiers(void)
2185
{
2186
    notifier_list_notify(&machine_init_done_notifiers, NULL);
2187
}
2188

    
2189
static const QEMUOption *lookup_opt(int argc, char **argv,
2190
                                    const char **poptarg, int *poptind)
2191
{
2192
    const QEMUOption *popt;
2193
    int optind = *poptind;
2194
    char *r = argv[optind];
2195
    const char *optarg;
2196

    
2197
    loc_set_cmdline(argv, optind, 1);
2198
    optind++;
2199
    /* Treat --foo the same as -foo.  */
2200
    if (r[1] == '-')
2201
        r++;
2202
    popt = qemu_options;
2203
    for(;;) {
2204
        if (!popt->name) {
2205
            error_report("invalid option");
2206
            exit(1);
2207
        }
2208
        if (!strcmp(popt->name, r + 1))
2209
            break;
2210
        popt++;
2211
    }
2212
    if (popt->flags & HAS_ARG) {
2213
        if (optind >= argc) {
2214
            error_report("requires an argument");
2215
            exit(1);
2216
        }
2217
        optarg = argv[optind++];
2218
        loc_set_cmdline(argv, optind - 2, 2);
2219
    } else {
2220
        optarg = NULL;
2221
    }
2222

    
2223
    *poptarg = optarg;
2224
    *poptind = optind;
2225

    
2226
    return popt;
2227
}
2228

    
2229
static gpointer malloc_and_trace(gsize n_bytes)
2230
{
2231
    void *ptr = malloc(n_bytes);
2232
    trace_g_malloc(n_bytes, ptr);
2233
    return ptr;
2234
}
2235

    
2236
static gpointer realloc_and_trace(gpointer mem, gsize n_bytes)
2237
{
2238
    void *ptr = realloc(mem, n_bytes);
2239
    trace_g_realloc(mem, n_bytes, ptr);
2240
    return ptr;
2241
}
2242

    
2243
static void free_and_trace(gpointer mem)
2244
{
2245
    trace_g_free(mem);
2246
    free(mem);
2247
}
2248

    
2249
int qemu_init_main_loop(void)
2250
{
2251
    return main_loop_init();
2252
}
2253

    
2254
int main(int argc, char **argv, char **envp)
2255
{
2256
    int i;
2257
    int snapshot, linux_boot;
2258
    const char *icount_option = NULL;
2259
    const char *initrd_filename;
2260
    const char *kernel_filename, *kernel_cmdline;
2261
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2262
    DisplayState *ds;
2263
    DisplayChangeListener *dcl;
2264
    int cyls, heads, secs, translation;
2265
    QemuOpts *hda_opts = NULL, *opts, *machine_opts;
2266
    QemuOptsList *olist;
2267
    int optind;
2268
    const char *optarg;
2269
    const char *loadvm = NULL;
2270
    QEMUMachine *machine;
2271
    const char *cpu_model;
2272
    const char *vga_model = NULL;
2273
    const char *pid_file = NULL;
2274
    const char *incoming = NULL;
2275
#ifdef CONFIG_VNC
2276
    int show_vnc_port = 0;
2277
#endif
2278
    int defconfig = 1;
2279
    const char *log_mask = NULL;
2280
    const char *log_file = NULL;
2281
    GMemVTable mem_trace = {
2282
        .malloc = malloc_and_trace,
2283
        .realloc = realloc_and_trace,
2284
        .free = free_and_trace,
2285
    };
2286
    const char *trace_events = NULL;
2287
    const char *trace_file = NULL;
2288

    
2289
    atexit(qemu_run_exit_notifiers);
2290
    error_set_progname(argv[0]);
2291

    
2292
    g_mem_set_vtable(&mem_trace);
2293
    if (!g_thread_supported()) {
2294
#if !GLIB_CHECK_VERSION(2, 31, 0)
2295
        g_thread_init(NULL);
2296
#else
2297
        fprintf(stderr, "glib threading failed to initialize.\n");
2298
        exit(1);
2299
#endif
2300
    }
2301

    
2302
    runstate_init();
2303

    
2304
    init_clocks();
2305
    rtc_clock = host_clock;
2306

    
2307
    qemu_cache_utils_init(envp);
2308

    
2309
    QLIST_INIT (&vm_change_state_head);
2310
    os_setup_early_signal_handling();
2311

    
2312
    module_call_init(MODULE_INIT_MACHINE);
2313
    machine = find_default_machine();
2314
    cpu_model = NULL;
2315
    ram_size = 0;
2316
    snapshot = 0;
2317
    cyls = heads = secs = 0;
2318
    translation = BIOS_ATA_TRANSLATION_AUTO;
2319

    
2320
    for (i = 0; i < MAX_NODES; i++) {
2321
        node_mem[i] = 0;
2322
        node_cpumask[i] = 0;
2323
    }
2324

    
2325
    nb_numa_nodes = 0;
2326
    nb_nics = 0;
2327

    
2328
    autostart= 1;
2329

    
2330
    /* first pass of option parsing */
2331
    optind = 1;
2332
    while (optind < argc) {
2333
        if (argv[optind][0] != '-') {
2334
            /* disk image */
2335
            optind++;
2336
            continue;
2337
        } else {
2338
            const QEMUOption *popt;
2339

    
2340
            popt = lookup_opt(argc, argv, &optarg, &optind);
2341
            switch (popt->index) {
2342
            case QEMU_OPTION_nodefconfig:
2343
                defconfig=0;
2344
                break;
2345
            }
2346
        }
2347
    }
2348

    
2349
    if (defconfig) {
2350
        int ret;
2351

    
2352
        ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2353
        if (ret < 0 && ret != -ENOENT) {
2354
            exit(1);
2355
        }
2356

    
2357
        ret = qemu_read_config_file(arch_config_name);
2358
        if (ret < 0 && ret != -ENOENT) {
2359
            exit(1);
2360
        }
2361
    }
2362
    cpudef_init();
2363

    
2364
    /* second pass of option parsing */
2365
    optind = 1;
2366
    for(;;) {
2367
        if (optind >= argc)
2368
            break;
2369
        if (argv[optind][0] != '-') {
2370
            hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2371
        } else {
2372
            const QEMUOption *popt;
2373

    
2374
            popt = lookup_opt(argc, argv, &optarg, &optind);
2375
            if (!(popt->arch_mask & arch_type)) {
2376
                printf("Option %s not supported for this target\n", popt->name);
2377
                exit(1);
2378
            }
2379
            switch(popt->index) {
2380
            case QEMU_OPTION_M:
2381
                machine = machine_parse(optarg);
2382
                break;
2383
            case QEMU_OPTION_cpu:
2384
                /* hw initialization will check this */
2385
                if (*optarg == '?') {
2386
                    list_cpus(stdout, &fprintf, optarg);
2387
                    exit(0);
2388
                } else {
2389
                    cpu_model = optarg;
2390
                }
2391
                break;
2392
            case QEMU_OPTION_hda:
2393
                {
2394
                    char buf[256];
2395
                    if (cyls == 0)
2396
                        snprintf(buf, sizeof(buf), "%s", HD_OPTS);
2397
                    else
2398
                        snprintf(buf, sizeof(buf),
2399
                                 "%s,cyls=%d,heads=%d,secs=%d%s",
2400
                                 HD_OPTS , cyls, heads, secs,
2401
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
2402
                                 ",trans=lba" :
2403
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
2404
                                 ",trans=none" : "");
2405
                    drive_add(IF_DEFAULT, 0, optarg, buf);
2406
                    break;
2407
                }
2408
            case QEMU_OPTION_hdb:
2409
            case QEMU_OPTION_hdc:
2410
            case QEMU_OPTION_hdd:
2411
                drive_add(IF_DEFAULT, popt->index - QEMU_OPTION_hda, optarg,
2412
                          HD_OPTS);
2413
                break;
2414
            case QEMU_OPTION_drive:
2415
                if (drive_def(optarg) == NULL) {
2416
                    exit(1);
2417
                }
2418
                break;
2419
            case QEMU_OPTION_set:
2420
                if (qemu_set_option(optarg) != 0)
2421
                    exit(1);
2422
                break;
2423
            case QEMU_OPTION_global:
2424
                if (qemu_global_option(optarg) != 0)
2425
                    exit(1);
2426
                break;
2427
            case QEMU_OPTION_mtdblock:
2428
                drive_add(IF_MTD, -1, optarg, MTD_OPTS);
2429
                break;
2430
            case QEMU_OPTION_sd:
2431
                drive_add(IF_SD, 0, optarg, SD_OPTS);
2432
                break;
2433
            case QEMU_OPTION_pflash:
2434
                drive_add(IF_PFLASH, -1, optarg, PFLASH_OPTS);
2435
                break;
2436
            case QEMU_OPTION_snapshot:
2437
                snapshot = 1;
2438
                break;
2439
            case QEMU_OPTION_hdachs:
2440
                {
2441
                    const char *p;
2442
                    p = optarg;
2443
                    cyls = strtol(p, (char **)&p, 0);
2444
                    if (cyls < 1 || cyls > 16383)
2445
                        goto chs_fail;
2446
                    if (*p != ',')
2447
                        goto chs_fail;
2448
                    p++;
2449
                    heads = strtol(p, (char **)&p, 0);
2450
                    if (heads < 1 || heads > 16)
2451
                        goto chs_fail;
2452
                    if (*p != ',')
2453
                        goto chs_fail;
2454
                    p++;
2455
                    secs = strtol(p, (char **)&p, 0);
2456
                    if (secs < 1 || secs > 63)
2457
                        goto chs_fail;
2458
                    if (*p == ',') {
2459
                        p++;
2460
                        if (!strcmp(p, "none"))
2461
                            translation = BIOS_ATA_TRANSLATION_NONE;
2462
                        else if (!strcmp(p, "lba"))
2463
                            translation = BIOS_ATA_TRANSLATION_LBA;
2464
                        else if (!strcmp(p, "auto"))
2465
                            translation = BIOS_ATA_TRANSLATION_AUTO;
2466
                        else
2467
                            goto chs_fail;
2468
                    } else if (*p != '\0') {
2469
                    chs_fail:
2470
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
2471
                        exit(1);
2472
                    }
2473
                    if (hda_opts != NULL) {
2474
                        char num[16];
2475
                        snprintf(num, sizeof(num), "%d", cyls);
2476
                        qemu_opt_set(hda_opts, "cyls", num);
2477
                        snprintf(num, sizeof(num), "%d", heads);
2478
                        qemu_opt_set(hda_opts, "heads", num);
2479
                        snprintf(num, sizeof(num), "%d", secs);
2480
                        qemu_opt_set(hda_opts, "secs", num);
2481
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
2482
                            qemu_opt_set(hda_opts, "trans", "lba");
2483
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
2484
                            qemu_opt_set(hda_opts, "trans", "none");
2485
                    }
2486
                }
2487
                break;
2488
            case QEMU_OPTION_numa:
2489
                if (nb_numa_nodes >= MAX_NODES) {
2490
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
2491
                    exit(1);
2492
                }
2493
                numa_add(optarg);
2494
                break;
2495
            case QEMU_OPTION_display:
2496
                display_type = select_display(optarg);
2497
                break;
2498
            case QEMU_OPTION_nographic:
2499
                display_type = DT_NOGRAPHIC;
2500
                break;
2501
            case QEMU_OPTION_curses:
2502
#ifdef CONFIG_CURSES
2503
                display_type = DT_CURSES;
2504
#else
2505
                fprintf(stderr, "Curses support is disabled\n");
2506
                exit(1);
2507
#endif
2508
                break;
2509
            case QEMU_OPTION_portrait:
2510
                graphic_rotate = 90;
2511
                break;
2512
            case QEMU_OPTION_rotate:
2513
                graphic_rotate = strtol(optarg, (char **) &optarg, 10);
2514
                if (graphic_rotate != 0 && graphic_rotate != 90 &&
2515
                    graphic_rotate != 180 && graphic_rotate != 270) {
2516
                    fprintf(stderr,
2517
                        "qemu: only 90, 180, 270 deg rotation is available\n");
2518
                    exit(1);
2519
                }
2520
                break;
2521
            case QEMU_OPTION_kernel:
2522
                qemu_opts_set(qemu_find_opts("machine"), 0, "kernel", optarg);
2523
                break;
2524
            case QEMU_OPTION_initrd:
2525
                qemu_opts_set(qemu_find_opts("machine"), 0, "initrd", optarg);
2526
                break;
2527
            case QEMU_OPTION_append:
2528
                qemu_opts_set(qemu_find_opts("machine"), 0, "append", optarg);
2529
                break;
2530
            case QEMU_OPTION_dtb:
2531
                qemu_opts_set(qemu_find_opts("machine"), 0, "dtb", optarg);
2532
                break;
2533
            case QEMU_OPTION_cdrom:
2534
                drive_add(IF_DEFAULT, 2, optarg, CDROM_OPTS);
2535
                break;
2536
            case QEMU_OPTION_boot:
2537
                {
2538
                    static const char * const params[] = {
2539
                        "order", "once", "menu",
2540
                        "splash", "splash-time", NULL
2541
                    };
2542
                    char buf[sizeof(boot_devices)];
2543
                    char *standard_boot_devices;
2544
                    int legacy = 0;
2545

    
2546
                    if (!strchr(optarg, '=')) {
2547
                        legacy = 1;
2548
                        pstrcpy(buf, sizeof(buf), optarg);
2549
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2550
                        fprintf(stderr,
2551
                                "qemu: unknown boot parameter '%s' in '%s'\n",
2552
                                buf, optarg);
2553
                        exit(1);
2554
                    }
2555

    
2556
                    if (legacy ||
2557
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
2558
                        validate_bootdevices(buf);
2559
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
2560
                    }
2561
                    if (!legacy) {
2562
                        if (get_param_value(buf, sizeof(buf),
2563
                                            "once", optarg)) {
2564
                            validate_bootdevices(buf);
2565
                            standard_boot_devices = g_strdup(boot_devices);
2566
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
2567
                            qemu_register_reset(restore_boot_devices,
2568
                                                standard_boot_devices);
2569
                        }
2570
                        if (get_param_value(buf, sizeof(buf),
2571
                                            "menu", optarg)) {
2572
                            if (!strcmp(buf, "on")) {
2573
                                boot_menu = 1;
2574
                            } else if (!strcmp(buf, "off")) {
2575
                                boot_menu = 0;
2576
                            } else {
2577
                                fprintf(stderr,
2578
                                        "qemu: invalid option value '%s'\n",
2579
                                        buf);
2580
                                exit(1);
2581
                            }
2582
                        }
2583
                        qemu_opts_parse(qemu_find_opts("boot-opts"),
2584
                                        optarg, 0);
2585
                    }
2586
                }
2587
                break;
2588
            case QEMU_OPTION_fda:
2589
            case QEMU_OPTION_fdb:
2590
                drive_add(IF_FLOPPY, popt->index - QEMU_OPTION_fda,
2591
                          optarg, FD_OPTS);
2592
                break;
2593
            case QEMU_OPTION_no_fd_bootchk:
2594
                fd_bootchk = 0;
2595
                break;
2596
            case QEMU_OPTION_netdev:
2597
                if (net_client_parse(qemu_find_opts("netdev"), optarg) == -1) {
2598
                    exit(1);
2599
                }
2600
                break;
2601
            case QEMU_OPTION_net:
2602
                if (net_client_parse(qemu_find_opts("net"), optarg) == -1) {
2603
                    exit(1);
2604
                }
2605
                break;
2606
#ifdef CONFIG_LIBISCSI
2607
            case QEMU_OPTION_iscsi:
2608
                opts = qemu_opts_parse(qemu_find_opts("iscsi"), optarg, 0);
2609
                if (!opts) {
2610
                    exit(1);
2611
                }
2612
                break;
2613
#endif
2614
#ifdef CONFIG_SLIRP
2615
            case QEMU_OPTION_tftp:
2616
                legacy_tftp_prefix = optarg;
2617
                break;
2618
            case QEMU_OPTION_bootp:
2619
                legacy_bootp_filename = optarg;
2620
                break;
2621
            case QEMU_OPTION_redir:
2622
                if (net_slirp_redir(optarg) < 0)
2623
                    exit(1);
2624
                break;
2625
#endif
2626
            case QEMU_OPTION_bt:
2627
                add_device_config(DEV_BT, optarg);
2628
                break;
2629
            case QEMU_OPTION_audio_help:
2630
                if (!(audio_available())) {
2631
                    printf("Option %s not supported for this target\n", popt->name);
2632
                    exit(1);
2633
                }
2634
                AUD_help ();
2635
                exit (0);
2636
                break;
2637
            case QEMU_OPTION_soundhw:
2638
                if (!(audio_available())) {
2639
                    printf("Option %s not supported for this target\n", popt->name);
2640
                    exit(1);
2641
                }
2642
                select_soundhw (optarg);
2643
                break;
2644
            case QEMU_OPTION_h:
2645
                help(0);
2646
                break;
2647
            case QEMU_OPTION_version:
2648
                version();
2649
                exit(0);
2650
                break;
2651
            case QEMU_OPTION_m: {
2652
                int64_t value;
2653
                char *end;
2654

    
2655
                value = strtosz(optarg, &end);
2656
                if (value < 0 || *end) {
2657
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
2658
                    exit(1);
2659
                }
2660

    
2661
                if (value != (uint64_t)(ram_addr_t)value) {
2662
                    fprintf(stderr, "qemu: ram size too large\n");
2663
                    exit(1);
2664
                }
2665
                ram_size = value;
2666
                break;
2667
            }
2668
            case QEMU_OPTION_mempath:
2669
                mem_path = optarg;
2670
                break;
2671
#ifdef MAP_POPULATE
2672
            case QEMU_OPTION_mem_prealloc:
2673
                mem_prealloc = 1;
2674
                break;
2675
#endif
2676
            case QEMU_OPTION_d:
2677
                log_mask = optarg;
2678
                break;
2679
            case QEMU_OPTION_D:
2680
                log_file = optarg;
2681
                break;
2682
            case QEMU_OPTION_s:
2683
                add_device_config(DEV_GDB, "tcp::" DEFAULT_GDBSTUB_PORT);
2684
                break;
2685
            case QEMU_OPTION_gdb:
2686
                add_device_config(DEV_GDB, optarg);
2687
                break;
2688
            case QEMU_OPTION_L:
2689
                data_dir = optarg;
2690
                break;
2691
            case QEMU_OPTION_bios:
2692
                bios_name = optarg;
2693
                break;
2694
            case QEMU_OPTION_singlestep:
2695
                singlestep = 1;
2696
                break;
2697
            case QEMU_OPTION_S:
2698
                autostart = 0;
2699
                break;
2700
            case QEMU_OPTION_k:
2701
                keyboard_layout = optarg;
2702
                break;
2703
            case QEMU_OPTION_localtime:
2704
                rtc_utc = 0;
2705
                break;
2706
            case QEMU_OPTION_vga:
2707
                vga_model = optarg;
2708
                break;
2709
            case QEMU_OPTION_g:
2710
                {
2711
                    const char *p;
2712
                    int w, h, depth;
2713
                    p = optarg;
2714
                    w = strtol(p, (char **)&p, 10);
2715
                    if (w <= 0) {
2716
                    graphic_error:
2717
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
2718
                        exit(1);
2719
                    }
2720
                    if (*p != 'x')
2721
                        goto graphic_error;
2722
                    p++;
2723
                    h = strtol(p, (char **)&p, 10);
2724
                    if (h <= 0)
2725
                        goto graphic_error;
2726
                    if (*p == 'x') {
2727
                        p++;
2728
                        depth = strtol(p, (char **)&p, 10);
2729
                        if (depth != 8 && depth != 15 && depth != 16 &&
2730
                            depth != 24 && depth != 32)
2731
                            goto graphic_error;
2732
                    } else if (*p == '\0') {
2733
                        depth = graphic_depth;
2734
                    } else {
2735
                        goto graphic_error;
2736
                    }
2737

    
2738
                    graphic_width = w;
2739
                    graphic_height = h;
2740
                    graphic_depth = depth;
2741
                }
2742
                break;
2743
            case QEMU_OPTION_echr:
2744
                {
2745
                    char *r;
2746
                    term_escape_char = strtol(optarg, &r, 0);
2747
                    if (r == optarg)
2748
                        printf("Bad argument to echr\n");
2749
                    break;
2750
                }
2751
            case QEMU_OPTION_monitor:
2752
                monitor_parse(optarg, "readline");
2753
                default_monitor = 0;
2754
                break;
2755
            case QEMU_OPTION_qmp:
2756
                monitor_parse(optarg, "control");
2757
                default_monitor = 0;
2758
                break;
2759
            case QEMU_OPTION_mon:
2760
                opts = qemu_opts_parse(qemu_find_opts("mon"), optarg, 1);
2761
                if (!opts) {
2762
                    exit(1);
2763
                }
2764
                default_monitor = 0;
2765
                break;
2766
            case QEMU_OPTION_chardev:
2767
                opts = qemu_opts_parse(qemu_find_opts("chardev"), optarg, 1);
2768
                if (!opts) {
2769
                    exit(1);
2770
                }
2771
                break;
2772
            case QEMU_OPTION_fsdev:
2773
                olist = qemu_find_opts("fsdev");
2774
                if (!olist) {
2775
                    fprintf(stderr, "fsdev is not supported by this qemu build.\n");
2776
                    exit(1);
2777
                }
2778
                opts = qemu_opts_parse(olist, optarg, 1);
2779
                if (!opts) {
2780
                    fprintf(stderr, "parse error: %s\n", optarg);
2781
                    exit(1);
2782
                }
2783
                break;
2784
            case QEMU_OPTION_virtfs: {
2785
                QemuOpts *fsdev;
2786
                QemuOpts *device;
2787
                const char *writeout, *sock_fd, *socket;
2788

    
2789
                olist = qemu_find_opts("virtfs");
2790
                if (!olist) {
2791
                    fprintf(stderr, "virtfs is not supported by this qemu build.\n");
2792
                    exit(1);
2793
                }
2794
                opts = qemu_opts_parse(olist, optarg, 1);
2795
                if (!opts) {
2796
                    fprintf(stderr, "parse error: %s\n", optarg);
2797
                    exit(1);
2798
                }
2799

    
2800
                if (qemu_opt_get(opts, "fsdriver") == NULL ||
2801
                    qemu_opt_get(opts, "mount_tag") == NULL) {
2802
                    fprintf(stderr, "Usage: -virtfs fsdriver,mount_tag=tag.\n");
2803
                    exit(1);
2804
                }
2805
                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
2806
                                         qemu_opt_get(opts, "mount_tag"), 1);
2807
                if (!fsdev) {
2808
                    fprintf(stderr, "duplicate fsdev id: %s\n",
2809
                            qemu_opt_get(opts, "mount_tag"));
2810
                    exit(1);
2811
                }
2812

    
2813
                writeout = qemu_opt_get(opts, "writeout");
2814
                if (writeout) {
2815
#ifdef CONFIG_SYNC_FILE_RANGE
2816
                    qemu_opt_set(fsdev, "writeout", writeout);
2817
#else
2818
                    fprintf(stderr, "writeout=immediate not supported on "
2819
                            "this platform\n");
2820
                    exit(1);
2821
#endif
2822
                }
2823
                qemu_opt_set(fsdev, "fsdriver", qemu_opt_get(opts, "fsdriver"));
2824
                qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"));
2825
                qemu_opt_set(fsdev, "security_model",
2826
                             qemu_opt_get(opts, "security_model"));
2827
                socket = qemu_opt_get(opts, "socket");
2828
                if (socket) {
2829
                    qemu_opt_set(fsdev, "socket", socket);
2830
                }
2831
                sock_fd = qemu_opt_get(opts, "sock_fd");
2832
                if (sock_fd) {
2833
                    qemu_opt_set(fsdev, "sock_fd", sock_fd);
2834
                }
2835

    
2836
                qemu_opt_set_bool(fsdev, "readonly",
2837
                                qemu_opt_get_bool(opts, "readonly", 0));
2838
                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
2839
                qemu_opt_set(device, "driver", "virtio-9p-pci");
2840
                qemu_opt_set(device, "fsdev",
2841
                             qemu_opt_get(opts, "mount_tag"));
2842
                qemu_opt_set(device, "mount_tag",
2843
                             qemu_opt_get(opts, "mount_tag"));
2844
                break;
2845
            }
2846
            case QEMU_OPTION_virtfs_synth: {
2847
                QemuOpts *fsdev;
2848
                QemuOpts *device;
2849

    
2850
                fsdev = qemu_opts_create(qemu_find_opts("fsdev"), "v_synth", 1);
2851
                if (!fsdev) {
2852
                    fprintf(stderr, "duplicate option: %s\n", "virtfs_synth");
2853
                    exit(1);
2854
                }
2855
                qemu_opt_set(fsdev, "fsdriver", "synth");
2856

    
2857
                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
2858
                qemu_opt_set(device, "driver", "virtio-9p-pci");
2859
                qemu_opt_set(device, "fsdev", "v_synth");
2860
                qemu_opt_set(device, "mount_tag", "v_synth");
2861
                break;
2862
            }
2863
            case QEMU_OPTION_serial:
2864
                add_device_config(DEV_SERIAL, optarg);
2865
                default_serial = 0;
2866
                if (strncmp(optarg, "mon:", 4) == 0) {
2867
                    default_monitor = 0;
2868
                }
2869
                break;
2870
            case QEMU_OPTION_watchdog:
2871
                if (watchdog) {
2872
                    fprintf(stderr,
2873
                            "qemu: only one watchdog option may be given\n");
2874
                    return 1;
2875
                }
2876
                watchdog = optarg;
2877
                break;
2878
            case QEMU_OPTION_watchdog_action:
2879
                if (select_watchdog_action(optarg) == -1) {
2880
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
2881
                    exit(1);
2882
                }
2883
                break;
2884
            case QEMU_OPTION_virtiocon:
2885
                add_device_config(DEV_VIRTCON, optarg);
2886
                default_virtcon = 0;
2887
                if (strncmp(optarg, "mon:", 4) == 0) {
2888
                    default_monitor = 0;
2889
                }
2890
                break;
2891
            case QEMU_OPTION_parallel:
2892
                add_device_config(DEV_PARALLEL, optarg);
2893
                default_parallel = 0;
2894
                if (strncmp(optarg, "mon:", 4) == 0) {
2895
                    default_monitor = 0;
2896
                }
2897
                break;
2898
            case QEMU_OPTION_debugcon:
2899
                add_device_config(DEV_DEBUGCON, optarg);
2900
                break;
2901
            case QEMU_OPTION_loadvm:
2902
                loadvm = optarg;
2903
                break;
2904
            case QEMU_OPTION_full_screen:
2905
                full_screen = 1;
2906
                break;
2907
#ifdef CONFIG_SDL
2908
            case QEMU_OPTION_no_frame:
2909
                no_frame = 1;
2910
                break;
2911
            case QEMU_OPTION_alt_grab:
2912
                alt_grab = 1;
2913
                break;
2914
            case QEMU_OPTION_ctrl_grab:
2915
                ctrl_grab = 1;
2916
                break;
2917
            case QEMU_OPTION_no_quit:
2918
                no_quit = 1;
2919
                break;
2920
            case QEMU_OPTION_sdl:
2921
                display_type = DT_SDL;
2922
                break;
2923
#else
2924
            case QEMU_OPTION_no_frame:
2925
            case QEMU_OPTION_alt_grab:
2926
            case QEMU_OPTION_ctrl_grab:
2927
            case QEMU_OPTION_no_quit:
2928
            case QEMU_OPTION_sdl:
2929
                fprintf(stderr, "SDL support is disabled\n");
2930
                exit(1);
2931
#endif
2932
            case QEMU_OPTION_pidfile:
2933
                pid_file = optarg;
2934
                break;
2935
            case QEMU_OPTION_win2k_hack:
2936
                win2k_install_hack = 1;
2937
                break;
2938
            case QEMU_OPTION_rtc_td_hack: {
2939
                static GlobalProperty slew_lost_ticks[] = {
2940
                    {
2941
                        .driver   = "mc146818rtc",
2942
                        .property = "lost_tick_policy",
2943
                        .value    = "slew",
2944
                    },
2945
                    { /* end of list */ }
2946
                };
2947

    
2948
                qdev_prop_register_global_list(slew_lost_ticks);
2949
                break;
2950
            }
2951
            case QEMU_OPTION_acpitable:
2952
                do_acpitable_option(optarg);
2953
                break;
2954
            case QEMU_OPTION_smbios:
2955
                do_smbios_option(optarg);
2956
                break;
2957
            case QEMU_OPTION_enable_kvm:
2958
                olist = qemu_find_opts("machine");
2959
                qemu_opts_parse(olist, "accel=kvm", 0);
2960
                break;
2961
            case QEMU_OPTION_machine:
2962
                olist = qemu_find_opts("machine");
2963
                opts = qemu_opts_parse(olist, optarg, 1);
2964
                if (!opts) {
2965
                    fprintf(stderr, "parse error: %s\n", optarg);
2966
                    exit(1);
2967
                }
2968
                optarg = qemu_opt_get(opts, "type");
2969
                if (optarg) {
2970
                    machine = machine_parse(optarg);
2971
                }
2972
                break;
2973
            case QEMU_OPTION_usb:
2974
                usb_enabled = 1;
2975
                break;
2976
            case QEMU_OPTION_usbdevice:
2977
                usb_enabled = 1;
2978
                add_device_config(DEV_USB, optarg);
2979
                break;
2980
            case QEMU_OPTION_device:
2981
                if (!qemu_opts_parse(qemu_find_opts("device"), optarg, 1)) {
2982
                    exit(1);
2983
                }
2984
                break;
2985
            case QEMU_OPTION_smp:
2986
                smp_parse(optarg);
2987
                if (smp_cpus < 1) {
2988
                    fprintf(stderr, "Invalid number of CPUs\n");
2989
                    exit(1);
2990
                }
2991
                if (max_cpus < smp_cpus) {
2992
                    fprintf(stderr, "maxcpus must be equal to or greater than "
2993
                            "smp\n");
2994
                    exit(1);
2995
                }
2996
                if (max_cpus > 255) {
2997
                    fprintf(stderr, "Unsupported number of maxcpus\n");
2998
                    exit(1);
2999
                }
3000
                break;
3001
            case QEMU_OPTION_vnc:
3002
#ifdef CONFIG_VNC
3003
                display_remote++;
3004
                vnc_display = optarg;
3005
#else
3006
                fprintf(stderr, "VNC support is disabled\n");
3007
                exit(1);
3008
#endif
3009
                break;
3010
            case QEMU_OPTION_no_acpi:
3011
                acpi_enabled = 0;
3012
                break;
3013
            case QEMU_OPTION_no_hpet:
3014
                no_hpet = 1;
3015
                break;
3016
            case QEMU_OPTION_balloon:
3017
                if (balloon_parse(optarg) < 0) {
3018
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
3019
                    exit(1);
3020
                }
3021
                break;
3022
            case QEMU_OPTION_no_reboot:
3023
                no_reboot = 1;
3024
                break;
3025
            case QEMU_OPTION_no_shutdown:
3026
                no_shutdown = 1;
3027
                break;
3028
            case QEMU_OPTION_show_cursor:
3029
                cursor_hide = 0;
3030
                break;
3031
            case QEMU_OPTION_uuid:
3032
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3033
                    fprintf(stderr, "Fail to parse UUID string."
3034
                            " Wrong format.\n");
3035
                    exit(1);
3036
                }
3037
                break;
3038
            case QEMU_OPTION_option_rom:
3039
                if (nb_option_roms >= MAX_OPTION_ROMS) {
3040
                    fprintf(stderr, "Too many option ROMs\n");
3041
                    exit(1);
3042
                }
3043
                opts = qemu_opts_parse(qemu_find_opts("option-rom"), optarg, 1);
3044
                option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3045
                option_rom[nb_option_roms].bootindex =
3046
                    qemu_opt_get_number(opts, "bootindex", -1);
3047
                if (!option_rom[nb_option_roms].name) {
3048
                    fprintf(stderr, "Option ROM file is not specified\n");
3049
                    exit(1);
3050
                }
3051
                nb_option_roms++;
3052
                break;
3053
            case QEMU_OPTION_semihosting:
3054
                semihosting_enabled = 1;
3055
                break;
3056
            case QEMU_OPTION_name:
3057
                qemu_name = g_strdup(optarg);
3058
                 {
3059
                     char *p = strchr(qemu_name, ',');
3060
                     if (p != NULL) {
3061
                        *p++ = 0;
3062
                        if (strncmp(p, "process=", 8)) {
3063
                            fprintf(stderr, "Unknown subargument %s to -name\n", p);
3064
                            exit(1);
3065
                        }
3066
                        p += 8;
3067
                        os_set_proc_name(p);
3068
                     }        
3069
                 }        
3070
                break;
3071
            case QEMU_OPTION_prom_env:
3072
                if (nb_prom_envs >= MAX_PROM_ENVS) {
3073
                    fprintf(stderr, "Too many prom variables\n");
3074
                    exit(1);
3075
                }
3076
                prom_envs[nb_prom_envs] = optarg;
3077
                nb_prom_envs++;
3078
                break;
3079
            case QEMU_OPTION_old_param:
3080
                old_param = 1;
3081
                break;
3082
            case QEMU_OPTION_clock:
3083
                configure_alarms(optarg);
3084
                break;
3085
            case QEMU_OPTION_startdate:
3086
                configure_rtc_date_offset(optarg, 1);
3087
                break;
3088
            case QEMU_OPTION_rtc:
3089
                opts = qemu_opts_parse(qemu_find_opts("rtc"), optarg, 0);
3090
                if (!opts) {
3091
                    exit(1);
3092
                }
3093
                configure_rtc(opts);
3094
                break;
3095
            case QEMU_OPTION_tb_size:
3096
                tcg_tb_size = strtol(optarg, NULL, 0);
3097
                if (tcg_tb_size < 0) {
3098
                    tcg_tb_size = 0;
3099
                }
3100
                break;
3101
            case QEMU_OPTION_icount:
3102
                icount_option = optarg;
3103
                break;
3104
            case QEMU_OPTION_incoming:
3105
                incoming = optarg;
3106
                break;
3107
            case QEMU_OPTION_nodefaults:
3108
                default_serial = 0;
3109
                default_parallel = 0;
3110
                default_virtcon = 0;
3111
                default_monitor = 0;
3112
                default_net = 0;
3113
                default_floppy = 0;
3114
                default_cdrom = 0;
3115
                default_sdcard = 0;
3116
                vga_model = "none";
3117
                break;
3118
            case QEMU_OPTION_xen_domid:
3119
                if (!(xen_available())) {
3120
                    printf("Option %s not supported for this target\n", popt->name);
3121
                    exit(1);
3122
                }
3123
                xen_domid = atoi(optarg);
3124
                break;
3125
            case QEMU_OPTION_xen_create:
3126
                if (!(xen_available())) {
3127
                    printf("Option %s not supported for this target\n", popt->name);
3128
                    exit(1);
3129
                }
3130
                xen_mode = XEN_CREATE;
3131
                break;
3132
            case QEMU_OPTION_xen_attach:
3133
                if (!(xen_available())) {
3134
                    printf("Option %s not supported for this target\n", popt->name);
3135
                    exit(1);
3136
                }
3137
                xen_mode = XEN_ATTACH;
3138
                break;
3139
            case QEMU_OPTION_trace:
3140
            {
3141
                opts = qemu_opts_parse(qemu_find_opts("trace"), optarg, 0);
3142
                if (!opts) {
3143
                    exit(1);
3144
                }
3145
                trace_events = qemu_opt_get(opts, "events");
3146
                trace_file = qemu_opt_get(opts, "file");
3147
                break;
3148
            }
3149
            case QEMU_OPTION_readconfig:
3150
                {
3151
                    int ret = qemu_read_config_file(optarg);
3152
                    if (ret < 0) {
3153
                        fprintf(stderr, "read config %s: %s\n", optarg,
3154
                            strerror(-ret));
3155
                        exit(1);
3156
                    }
3157
                    break;
3158
                }
3159
            case QEMU_OPTION_spice:
3160
                olist = qemu_find_opts("spice");
3161
                if (!olist) {
3162
                    fprintf(stderr, "spice is not supported by this qemu build.\n");
3163
                    exit(1);
3164
                }
3165
                opts = qemu_opts_parse(olist, optarg, 0);
3166
                if (!opts) {
3167
                    fprintf(stderr, "parse error: %s\n", optarg);
3168
                    exit(1);
3169
                }
3170
                break;
3171
            case QEMU_OPTION_writeconfig:
3172
                {
3173
                    FILE *fp;
3174
                    if (strcmp(optarg, "-") == 0) {
3175
                        fp = stdout;
3176
                    } else {
3177
                        fp = fopen(optarg, "w");
3178
                        if (fp == NULL) {
3179
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3180
                            exit(1);
3181
                        }
3182
                    }
3183
                    qemu_config_write(fp);
3184
                    fclose(fp);
3185
                    break;
3186
                }
3187
            default:
3188
                os_parse_cmd_args(popt->index, optarg);
3189
            }
3190
        }
3191
    }
3192
    loc_set_none();
3193

    
3194
    /* Open the logfile at this point, if necessary. We can't open the logfile
3195
     * when encountering either of the logging options (-d or -D) because the
3196
     * other one may be encountered later on the command line, changing the
3197
     * location or level of logging.
3198
     */
3199
    if (log_mask) {
3200
        if (log_file) {
3201
            set_cpu_log_filename(log_file);
3202
        }
3203
        set_cpu_log(log_mask);
3204
    }
3205

    
3206
    if (!trace_backend_init(trace_events, trace_file)) {
3207
        exit(1);
3208
    }
3209

    
3210
    /* If no data_dir is specified then try to find it relative to the
3211
       executable path.  */
3212
    if (!data_dir) {
3213
        data_dir = os_find_datadir(argv[0]);
3214
    }
3215
    /* If all else fails use the install path specified when building. */
3216
    if (!data_dir) {
3217
        data_dir = CONFIG_QEMU_DATADIR;
3218
    }
3219

    
3220
    if (machine == NULL) {
3221
        fprintf(stderr, "No machine found.\n");
3222
        exit(1);
3223
    }
3224

    
3225
    /*
3226
     * Default to max_cpus = smp_cpus, in case the user doesn't
3227
     * specify a max_cpus value.
3228
     */
3229
    if (!max_cpus)
3230
        max_cpus = smp_cpus;
3231

    
3232
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3233
    if (smp_cpus > machine->max_cpus) {
3234
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3235
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3236
                machine->max_cpus);
3237
        exit(1);
3238
    }
3239

    
3240
    /*
3241
     * Get the default machine options from the machine if it is not already
3242
     * specified either by the configuration file or by the command line.
3243
     */
3244
    if (machine->default_machine_opts) {
3245
        qemu_opts_set_defaults(qemu_find_opts("machine"),
3246
                               machine->default_machine_opts, 0);
3247
    }
3248

    
3249
    qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
3250
    qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
3251

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

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

    
3297
    socket_init();
3298

    
3299
    if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)
3300
        exit(1);
3301
#ifdef CONFIG_VIRTFS
3302
    if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {
3303
        exit(1);
3304
    }
3305
#endif
3306

    
3307
    os_daemonize();
3308

    
3309
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3310
        os_pidfile_error();
3311
        exit(1);
3312
    }
3313

    
3314
    /* init the memory */
3315
    if (ram_size == 0) {
3316
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3317
    }
3318

    
3319
    configure_accelerator();
3320

    
3321
    qemu_init_cpu_loop();
3322
    if (qemu_init_main_loop()) {
3323
        fprintf(stderr, "qemu_init_main_loop failed\n");
3324
        exit(1);
3325
    }
3326

    
3327
    machine_opts = qemu_opts_find(qemu_find_opts("machine"), 0);
3328
    if (machine_opts) {
3329
        kernel_filename = qemu_opt_get(machine_opts, "kernel");
3330
        initrd_filename = qemu_opt_get(machine_opts, "initrd");
3331
        kernel_cmdline = qemu_opt_get(machine_opts, "append");
3332
    } else {
3333
        kernel_filename = initrd_filename = kernel_cmdline = NULL;
3334
    }
3335

    
3336
    if (!kernel_cmdline) {
3337
        kernel_cmdline = "";
3338
    }
3339

    
3340
    linux_boot = (kernel_filename != NULL);
3341

    
3342
    if (!linux_boot && *kernel_cmdline != '\0') {
3343
        fprintf(stderr, "-append only allowed with -kernel option\n");
3344
        exit(1);
3345
    }
3346

    
3347
    if (!linux_boot && initrd_filename != NULL) {
3348
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3349
        exit(1);
3350
    }
3351

    
3352
    if (!linux_boot && machine_opts && qemu_opt_get(machine_opts, "dtb")) {
3353
        fprintf(stderr, "-dtb only allowed with -kernel option\n");
3354
        exit(1);
3355
    }
3356

    
3357
    os_set_line_buffering();
3358

    
3359
    if (init_timer_alarm() < 0) {
3360
        fprintf(stderr, "could not initialize alarm timer\n");
3361
        exit(1);
3362
    }
3363

    
3364
    if (icount_option && (kvm_enabled() || xen_enabled())) {
3365
        fprintf(stderr, "-icount is not allowed with kvm or xen\n");
3366
        exit(1);
3367
    }
3368
    configure_icount(icount_option);
3369

    
3370
    if (net_init_clients() < 0) {
3371
        exit(1);
3372
    }
3373

    
3374
    /* init the bluetooth world */
3375
    if (foreach_device_config(DEV_BT, bt_parse))
3376
        exit(1);
3377

    
3378
    if (!xen_enabled()) {
3379
        /* On 32-bit hosts, QEMU is limited by virtual address space */
3380
        if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
3381
            fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3382
            exit(1);
3383
        }
3384
    }
3385

    
3386
    cpu_exec_init_all();
3387

    
3388
    bdrv_init_with_whitelist();
3389

    
3390
    blk_mig_init();
3391

    
3392
    /* open the virtual block devices */
3393
    if (snapshot)
3394
        qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
3395
    if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)
3396
        exit(1);
3397

    
3398
    default_drive(default_cdrom, snapshot, machine->use_scsi,
3399
                  IF_DEFAULT, 2, CDROM_OPTS);
3400
    default_drive(default_floppy, snapshot, machine->use_scsi,
3401
                  IF_FLOPPY, 0, FD_OPTS);
3402
    default_drive(default_sdcard, snapshot, machine->use_scsi,
3403
                  IF_SD, 0, SD_OPTS);
3404

    
3405
    register_savevm_live(NULL, "ram", 0, 4, NULL, ram_save_live, NULL,
3406
                         ram_load, NULL);
3407

    
3408
    if (nb_numa_nodes > 0) {
3409
        int i;
3410

    
3411
        if (nb_numa_nodes > MAX_NODES) {
3412
            nb_numa_nodes = MAX_NODES;
3413
        }
3414

    
3415
        /* If no memory size if given for any node, assume the default case
3416
         * and distribute the available memory equally across all nodes
3417
         */
3418
        for (i = 0; i < nb_numa_nodes; i++) {
3419
            if (node_mem[i] != 0)
3420
                break;
3421
        }
3422
        if (i == nb_numa_nodes) {
3423
            uint64_t usedmem = 0;
3424

    
3425
            /* On Linux, the each node's border has to be 8MB aligned,
3426
             * the final node gets the rest.
3427
             */
3428
            for (i = 0; i < nb_numa_nodes - 1; i++) {
3429
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3430
                usedmem += node_mem[i];
3431
            }
3432
            node_mem[i] = ram_size - usedmem;
3433
        }
3434

    
3435
        for (i = 0; i < nb_numa_nodes; i++) {
3436
            if (node_cpumask[i] != 0)
3437
                break;
3438
        }
3439
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3440
         * must cope with this anyway, because there are BIOSes out there in
3441
         * real machines which also use this scheme.
3442
         */
3443
        if (i == nb_numa_nodes) {
3444
            for (i = 0; i < max_cpus; i++) {
3445
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
3446
            }
3447
        }
3448
    }
3449

    
3450
    if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {
3451
        exit(1);
3452
    }
3453

    
3454
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3455
        exit(1);
3456
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3457
        exit(1);
3458
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3459
        exit(1);
3460
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3461
        exit(1);
3462

    
3463
    module_call_init(MODULE_INIT_QOM);
3464

    
3465
    /* must be after qdev registration but before machine init */
3466
    if (vga_model) {
3467
        select_vgahw(vga_model);
3468
    } else if (cirrus_vga_available()) {
3469
        select_vgahw("cirrus");
3470
    } else {
3471
        select_vgahw("none");
3472
    }
3473

    
3474
    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0) != 0)
3475
        exit(0);
3476

    
3477
    if (watchdog) {
3478
        i = select_watchdog(watchdog);
3479
        if (i > 0)
3480
            exit (i == 1 ? 1 : 0);
3481
    }
3482

    
3483
    if (machine->compat_props) {
3484
        qdev_prop_register_global_list(machine->compat_props);
3485
    }
3486
    qemu_add_globals();
3487

    
3488
    qdev_machine_init();
3489

    
3490
    machine->init(ram_size, boot_devices,
3491
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3492

    
3493
    cpu_synchronize_all_post_init();
3494

    
3495
    set_numa_modes();
3496

    
3497
    current_machine = machine;
3498

    
3499
    /* init USB devices */
3500
    if (usb_enabled) {
3501
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3502
            exit(1);
3503
    }
3504

    
3505
    /* init generic devices */
3506
    if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)
3507
        exit(1);
3508

    
3509
    net_check_clients();
3510

    
3511
    /* just use the first displaystate for the moment */
3512
    ds = get_displaystate();
3513

    
3514
    if (using_spice)
3515
        display_remote++;
3516
    if (display_type == DT_DEFAULT && !display_remote) {
3517
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3518
        display_type = DT_SDL;
3519
#elif defined(CONFIG_VNC)
3520
        vnc_display = "localhost:0,to=99";
3521
        show_vnc_port = 1;
3522
#else
3523
        display_type = DT_NONE;
3524
#endif
3525
    }
3526

    
3527

    
3528
    /* init local displays */
3529
    switch (display_type) {
3530
    case DT_NOGRAPHIC:
3531
        break;
3532
#if defined(CONFIG_CURSES)
3533
    case DT_CURSES:
3534
        curses_display_init(ds, full_screen);
3535
        break;
3536
#endif
3537
#if defined(CONFIG_SDL)
3538
    case DT_SDL:
3539
        sdl_display_init(ds, full_screen, no_frame);
3540
        break;
3541
#elif defined(CONFIG_COCOA)
3542
    case DT_SDL:
3543
        cocoa_display_init(ds, full_screen);
3544
        break;
3545
#endif
3546
    default:
3547
        break;
3548
    }
3549

    
3550
    /* must be after terminal init, SDL library changes signal handlers */
3551
    os_setup_signal_handling();
3552

    
3553
#ifdef CONFIG_VNC
3554
    /* init remote displays */
3555
    if (vnc_display) {
3556
        vnc_display_init(ds);
3557
        if (vnc_display_open(ds, vnc_display) < 0)
3558
            exit(1);
3559

    
3560
        if (show_vnc_port) {
3561
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3562
        }
3563
    }
3564
#endif
3565
#ifdef CONFIG_SPICE
3566
    if (using_spice && !qxl_enabled) {
3567
        qemu_spice_display_init(ds);
3568
    }
3569
#endif
3570

    
3571
    /* display setup */
3572
    dpy_resize(ds);
3573
    dcl = ds->listeners;
3574
    while (dcl != NULL) {
3575
        if (dcl->dpy_refresh != NULL) {
3576
            ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);
3577
            qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));
3578
            break;
3579
        }
3580
        dcl = dcl->next;
3581
    }
3582
    text_consoles_set_display(ds);
3583

    
3584
    if (foreach_device_config(DEV_GDB, gdbserver_start) < 0) {
3585
        exit(1);
3586
    }
3587

    
3588
    qdev_machine_creation_done();
3589

    
3590
    if (rom_load_all() != 0) {
3591
        fprintf(stderr, "rom loading failed\n");
3592
        exit(1);
3593
    }
3594

    
3595
    /* TODO: once all bus devices are qdevified, this should be done
3596
     * when bus is created by qdev.c */
3597
    qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
3598
    qemu_run_machine_init_done_notifiers();
3599

    
3600
    qemu_system_reset(VMRESET_SILENT);
3601
    if (loadvm) {
3602
        if (load_vmstate(loadvm) < 0) {
3603
            autostart = 0;
3604
        }
3605
    }
3606

    
3607
    if (incoming) {
3608
        runstate_set(RUN_STATE_INMIGRATE);
3609
        int ret = qemu_start_incoming_migration(incoming);
3610
        if (ret < 0) {
3611
            fprintf(stderr, "Migration failed. Exit code %s(%d), exiting.\n",
3612
                    incoming, ret);
3613
            exit(ret);
3614
        }
3615
    } else if (autostart) {
3616
        vm_start();
3617
    }
3618

    
3619
    os_setup_post();
3620

    
3621
    resume_all_vcpus();
3622
    main_loop();
3623
    bdrv_close_all();
3624
    pause_all_vcpus();
3625
    net_cleanup();
3626
    res_free();
3627

    
3628
    return 0;
3629
}