Statistics
| Branch: | Revision:

root / vl.c @ 9e37b9dc

History | View | Annotate | Download (99.8 kB)

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

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

    
35
#ifndef _WIN32
36
#include <libgen.h>
37
#include <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 "qemu-option.h"
147
#include "qemu-config.h"
148
#include "qemu-objects.h"
149
#include "qemu-options.h"
150
#ifdef CONFIG_VIRTFS
151
#include "fsdev/qemu-fsdev.h"
152
#endif
153

    
154
#include "disas.h"
155

    
156
#include "qemu_socket.h"
157

    
158
#include "slirp/libslirp.h"
159

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

    
166
#include "ui/qemu-spice.h"
167

    
168
//#define DEBUG_NET
169
//#define DEBUG_SLIRP
170

    
171
#define DEFAULT_RAM_SIZE 128
172

    
173
#define MAX_VIRTIO_CONSOLES 1
174

    
175
static const char *data_dir;
176
const char *bios_name = NULL;
177
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
178
DisplayType display_type = DT_DEFAULT;
179
int display_remote = 0;
180
const char* keyboard_layout = NULL;
181
ram_addr_t ram_size;
182
const char *mem_path = NULL;
183
#ifdef MAP_POPULATE
184
int mem_prealloc = 0; /* force preallocation of physical target memory */
185
#endif
186
int nb_nics;
187
NICInfo nd_table[MAX_NICS];
188
int autostart;
189
static int rtc_utc = 1;
190
static int rtc_date_offset = -1; /* -1 means no change */
191
QEMUClock *rtc_clock;
192
int vga_interface_type = VGA_NONE;
193
static int full_screen = 0;
194
#ifdef CONFIG_SDL
195
static int no_frame = 0;
196
#endif
197
int no_quit = 0;
198
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
199
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
200
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
201
int win2k_install_hack = 0;
202
int rtc_td_hack = 0;
203
int usb_enabled = 0;
204
int singlestep = 0;
205
int smp_cpus = 1;
206
int max_cpus = 0;
207
int smp_cores = 1;
208
int smp_threads = 1;
209
#ifdef CONFIG_VNC
210
const char *vnc_display;
211
#endif
212
int acpi_enabled = 1;
213
int no_hpet = 0;
214
int fd_bootchk = 1;
215
int no_reboot = 0;
216
int no_shutdown = 0;
217
int cursor_hide = 1;
218
int graphic_rotate = 0;
219
uint8_t irq0override = 1;
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
static QEMUTimer *nographic_timer;
251

    
252
uint8_t qemu_uuid[16];
253

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

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

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

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

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

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

    
300
static void res_free(void)
301
{
302
    if (boot_splash_filedata != NULL) {
303
        g_free(boot_splash_filedata);
304
        boot_splash_filedata = NULL;
305
    }
306
}
307

    
308
static int default_driver_check(QemuOpts *opts, void *opaque)
309
{
310
    const char *driver = qemu_opt_get(opts, "driver");
311
    int i;
312

    
313
    if (!driver)
314
        return 0;
315
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
316
        if (strcmp(default_list[i].driver, driver) != 0)
317
            continue;
318
        *(default_list[i].flag) = 0;
319
    }
320
    return 0;
321
}
322

    
323
/***********************************************************/
324
/* QEMU state */
325

    
326
static RunState current_run_state = RSTATE_NO_STATE;
327

    
328
typedef struct {
329
    RunState from;
330
    RunState to;
331
} RunStateTransition;
332

    
333
static const RunStateTransition runstate_transitions_def[] = {
334
    /*     from      ->     to      */
335
    { RSTATE_NO_STATE, RSTATE_RUNNING },
336
    { RSTATE_NO_STATE, RSTATE_IN_MIGRATE },
337
    { RSTATE_NO_STATE, RSTATE_PRE_LAUNCH },
338

    
339
    { RSTATE_DEBUG, RSTATE_RUNNING },
340

    
341
    { RSTATE_IN_MIGRATE, RSTATE_RUNNING },
342
    { RSTATE_IN_MIGRATE, RSTATE_PRE_LAUNCH },
343

    
344
    { RSTATE_PANICKED, RSTATE_PAUSED },
345

    
346
    { RSTATE_IO_ERROR, RSTATE_RUNNING },
347

    
348
    { RSTATE_PAUSED, RSTATE_RUNNING },
349

    
350
    { RSTATE_POST_MIGRATE, RSTATE_RUNNING },
351

    
352
    { RSTATE_PRE_LAUNCH, RSTATE_RUNNING },
353
    { RSTATE_PRE_LAUNCH, RSTATE_POST_MIGRATE },
354

    
355
    { RSTATE_PRE_MIGRATE, RSTATE_RUNNING },
356
    { RSTATE_PRE_MIGRATE, RSTATE_POST_MIGRATE },
357

    
358
    { RSTATE_RESTORE, RSTATE_RUNNING },
359

    
360
    { RSTATE_RUNNING, RSTATE_DEBUG },
361
    { RSTATE_RUNNING, RSTATE_PANICKED },
362
    { RSTATE_RUNNING, RSTATE_IO_ERROR },
363
    { RSTATE_RUNNING, RSTATE_PAUSED },
364
    { RSTATE_RUNNING, RSTATE_PRE_MIGRATE },
365
    { RSTATE_RUNNING, RSTATE_RESTORE },
366
    { RSTATE_RUNNING, RSTATE_SAVEVM },
367
    { RSTATE_RUNNING, RSTATE_SHUTDOWN },
368
    { RSTATE_RUNNING, RSTATE_WATCHDOG },
369

    
370
    { RSTATE_SAVEVM, RSTATE_RUNNING },
371

    
372
    { RSTATE_SHUTDOWN, RSTATE_PAUSED },
373

    
374
    { RSTATE_WATCHDOG, RSTATE_RUNNING },
375

    
376
    { RSTATE_MAX, RSTATE_MAX },
377
};
378

    
379
static bool runstate_valid_transitions[RSTATE_MAX][RSTATE_MAX];
380

    
381
static const char *const runstate_name_tbl[RSTATE_MAX] = {
382
    [RSTATE_DEBUG] = "debug",
383
    [RSTATE_IN_MIGRATE] = "incoming-migration",
384
    [RSTATE_PANICKED] = "internal-error",
385
    [RSTATE_IO_ERROR] = "io-error",
386
    [RSTATE_PAUSED] = "paused",
387
    [RSTATE_POST_MIGRATE] = "post-migrate",
388
    [RSTATE_PRE_LAUNCH] = "prelaunch",
389
    [RSTATE_PRE_MIGRATE] = "finish-migrate",
390
    [RSTATE_RESTORE] = "restore-vm",
391
    [RSTATE_RUNNING] = "running",
392
    [RSTATE_SAVEVM] = "save-vm",
393
    [RSTATE_SHUTDOWN] = "shutdown",
394
    [RSTATE_WATCHDOG] = "watchdog",
395
};
396

    
397
bool runstate_check(RunState state)
398
{
399
    return current_run_state == state;
400
}
401

    
402
void runstate_init(void)
403
{
404
    const RunStateTransition *p;
405

    
406
    memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
407

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

    
413
/* This function will abort() on invalid state transitions */
414
void runstate_set(RunState new_state)
415
{
416
    if (new_state >= RSTATE_MAX ||
417
        !runstate_valid_transitions[current_run_state][new_state]) {
418
        fprintf(stderr, "invalid runstate transition\n");
419
        abort();
420
    }
421

    
422
    current_run_state = new_state;
423
}
424

    
425
const char *runstate_as_string(void)
426
{
427
    assert(current_run_state > RSTATE_NO_STATE &&
428
           current_run_state < RSTATE_MAX);
429
    return runstate_name_tbl[current_run_state];
430
}
431

    
432
int runstate_is_running(void)
433
{
434
    return runstate_check(RSTATE_RUNNING);
435
}
436

    
437
/***********************************************************/
438
/* real time host monotonic timer */
439

    
440
/***********************************************************/
441
/* host time/date access */
442
void qemu_get_timedate(struct tm *tm, int offset)
443
{
444
    time_t ti;
445
    struct tm *ret;
446

    
447
    time(&ti);
448
    ti += offset;
449
    if (rtc_date_offset == -1) {
450
        if (rtc_utc)
451
            ret = gmtime(&ti);
452
        else
453
            ret = localtime(&ti);
454
    } else {
455
        ti -= rtc_date_offset;
456
        ret = gmtime(&ti);
457
    }
458

    
459
    memcpy(tm, ret, sizeof(struct tm));
460
}
461

    
462
int qemu_timedate_diff(struct tm *tm)
463
{
464
    time_t seconds;
465

    
466
    if (rtc_date_offset == -1)
467
        if (rtc_utc)
468
            seconds = mktimegm(tm);
469
        else
470
            seconds = mktime(tm);
471
    else
472
        seconds = mktimegm(tm) + rtc_date_offset;
473

    
474
    return seconds - time(NULL);
475
}
476

    
477
void rtc_change_mon_event(struct tm *tm)
478
{
479
    QObject *data;
480

    
481
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
482
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
483
    qobject_decref(data);
484
}
485

    
486
static void configure_rtc_date_offset(const char *startdate, int legacy)
487
{
488
    time_t rtc_start_date;
489
    struct tm tm;
490

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

    
525
static void configure_rtc(QemuOpts *opts)
526
{
527
    const char *value;
528

    
529
    value = qemu_opt_get(opts, "base");
530
    if (value) {
531
        if (!strcmp(value, "utc")) {
532
            rtc_utc = 1;
533
        } else if (!strcmp(value, "localtime")) {
534
            rtc_utc = 0;
535
        } else {
536
            configure_rtc_date_offset(value, 0);
537
        }
538
    }
539
    value = qemu_opt_get(opts, "clock");
540
    if (value) {
541
        if (!strcmp(value, "host")) {
542
            rtc_clock = host_clock;
543
        } else if (!strcmp(value, "vm")) {
544
            rtc_clock = vm_clock;
545
        } else {
546
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
547
            exit(1);
548
        }
549
    }
550
    value = qemu_opt_get(opts, "driftfix");
551
    if (value) {
552
        if (!strcmp(value, "slew")) {
553
            rtc_td_hack = 1;
554
        } else if (!strcmp(value, "none")) {
555
            rtc_td_hack = 0;
556
        } else {
557
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
558
            exit(1);
559
        }
560
    }
561
}
562

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

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

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

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

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

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

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

    
613
    return hci_table[cur_hci++];
614
}
615

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

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

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

    
643
    return 0;
644
}
645

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

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

    
656
    hci = hci_init(str);
657
    if (!hci)
658
        return -1;
659

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

    
668
    hci_table[nb_hcis++] = hci;
669

    
670
    return 0;
671
}
672

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

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

    
681
    bt_vhci_init(bt_new_hci(vlan));
682
}
683

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

    
692
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
693

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

    
702
    vlan = qemu_find_bt_vlan(vlan_id);
703

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

    
708
    if (!strcmp(devname, "keyboard"))
709
        return bt_keyboard_init(vlan);
710

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

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

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

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

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

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

    
754
/***********************************************************/
755
/* QEMU Block devices */
756

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

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

    
768
    return drive_init(opts, *use_scsi) == NULL;
769
}
770

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

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

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

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

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

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

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

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

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

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

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

    
855
    qemu_boot_set(standard_boot_devices);
856

    
857
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
858
    g_free(standard_boot_devices);
859
}
860

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

    
866
    if (bootindex < 0) {
867
        return;
868
    }
869

    
870
    assert(dev != NULL || suffix != NULL);
871

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

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

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

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

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

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

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

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

    
935
    *size = total;
936

    
937
    return list;
938
}
939

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

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

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

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

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

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

    
1037
/***********************************************************/
1038
/* USB devices */
1039

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

    
1045
    if (!usb_enabled)
1046
        return -1;
1047

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

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

    
1069
done:
1070
    return 0;
1071
}
1072

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

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

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

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

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

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

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

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

    
1119
/***********************************************************/
1120
/* PCMCIA/Cardbus */
1121

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

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

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

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

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

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

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

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

    
1162
/***********************************************************/
1163
/* machine registration */
1164

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

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

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

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

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

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

    
1204
/***********************************************************/
1205
/* main execution loop */
1206

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

    
1213
    qemu_flush_coalesced_mmio_buffer();
1214
    dpy_refresh(ds);
1215

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

    
1225
static void nographic_update(void *opaque)
1226
{
1227
    uint64_t interval = GUI_REFRESH_INTERVAL;
1228

    
1229
    qemu_flush_coalesced_mmio_buffer();
1230
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock_ms(rt_clock));
1231
}
1232

    
1233
struct vm_change_state_entry {
1234
    VMChangeStateHandler *cb;
1235
    void *opaque;
1236
    QLIST_ENTRY (vm_change_state_entry) entries;
1237
};
1238

    
1239
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1240

    
1241
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1242
                                                     void *opaque)
1243
{
1244
    VMChangeStateEntry *e;
1245

    
1246
    e = g_malloc0(sizeof (*e));
1247

    
1248
    e->cb = cb;
1249
    e->opaque = opaque;
1250
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1251
    return e;
1252
}
1253

    
1254
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1255
{
1256
    QLIST_REMOVE (e, entries);
1257
    g_free (e);
1258
}
1259

    
1260
void vm_state_notify(int running, RunState state)
1261
{
1262
    VMChangeStateEntry *e;
1263

    
1264
    trace_vm_state_notify(running, state);
1265

    
1266
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1267
        e->cb(e->opaque, running, state);
1268
    }
1269
}
1270

    
1271
void vm_start(void)
1272
{
1273
    if (!runstate_is_running()) {
1274
        cpu_enable_ticks();
1275
        runstate_set(RSTATE_RUNNING);
1276
        vm_state_notify(1, RSTATE_RUNNING);
1277
        resume_all_vcpus();
1278
        monitor_protocol_event(QEVENT_RESUME, NULL);
1279
    }
1280
}
1281

    
1282
/* reset/shutdown handler */
1283

    
1284
typedef struct QEMUResetEntry {
1285
    QTAILQ_ENTRY(QEMUResetEntry) entry;
1286
    QEMUResetHandler *func;
1287
    void *opaque;
1288
} QEMUResetEntry;
1289

    
1290
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1291
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1292
static int reset_requested;
1293
static int shutdown_requested, shutdown_signal = -1;
1294
static pid_t shutdown_pid;
1295
static int powerdown_requested;
1296
static int debug_requested;
1297
static RunState vmstop_requested = RSTATE_NO_STATE;
1298

    
1299
int qemu_shutdown_requested_get(void)
1300
{
1301
    return shutdown_requested;
1302
}
1303

    
1304
int qemu_reset_requested_get(void)
1305
{
1306
    return reset_requested;
1307
}
1308

    
1309
int qemu_shutdown_requested(void)
1310
{
1311
    int r = shutdown_requested;
1312
    shutdown_requested = 0;
1313
    return r;
1314
}
1315

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

    
1332
int qemu_reset_requested(void)
1333
{
1334
    int r = reset_requested;
1335
    reset_requested = 0;
1336
    return r;
1337
}
1338

    
1339
int qemu_powerdown_requested(void)
1340
{
1341
    int r = powerdown_requested;
1342
    powerdown_requested = 0;
1343
    return r;
1344
}
1345

    
1346
static int qemu_debug_requested(void)
1347
{
1348
    int r = debug_requested;
1349
    debug_requested = 0;
1350
    return r;
1351
}
1352

    
1353
static RunState qemu_vmstop_requested(void)
1354
{
1355
    RunState s = vmstop_requested;
1356
    vmstop_requested = RSTATE_NO_STATE;
1357
    return s;
1358
}
1359

    
1360
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1361
{
1362
    QEMUResetEntry *re = g_malloc0(sizeof(QEMUResetEntry));
1363

    
1364
    re->func = func;
1365
    re->opaque = opaque;
1366
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1367
}
1368

    
1369
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1370
{
1371
    QEMUResetEntry *re;
1372

    
1373
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1374
        if (re->func == func && re->opaque == opaque) {
1375
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1376
            g_free(re);
1377
            return;
1378
        }
1379
    }
1380
}
1381

    
1382
void qemu_system_reset(bool report)
1383
{
1384
    QEMUResetEntry *re, *nre;
1385

    
1386
    /* reset all devices */
1387
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1388
        re->func(re->opaque);
1389
    }
1390
    if (report) {
1391
        monitor_protocol_event(QEVENT_RESET, NULL);
1392
    }
1393
    cpu_synchronize_all_post_reset();
1394
}
1395

    
1396
void qemu_system_reset_request(void)
1397
{
1398
    if (no_reboot) {
1399
        shutdown_requested = 1;
1400
    } else {
1401
        reset_requested = 1;
1402
    }
1403
    cpu_stop_current();
1404
    qemu_notify_event();
1405
}
1406

    
1407
void qemu_system_killed(int signal, pid_t pid)
1408
{
1409
    shutdown_signal = signal;
1410
    shutdown_pid = pid;
1411
    qemu_system_shutdown_request();
1412
}
1413

    
1414
void qemu_system_shutdown_request(void)
1415
{
1416
    shutdown_requested = 1;
1417
    qemu_notify_event();
1418
}
1419

    
1420
void qemu_system_powerdown_request(void)
1421
{
1422
    powerdown_requested = 1;
1423
    qemu_notify_event();
1424
}
1425

    
1426
void qemu_system_debug_request(void)
1427
{
1428
    debug_requested = 1;
1429
    qemu_notify_event();
1430
}
1431

    
1432
void qemu_system_vmstop_request(RunState state)
1433
{
1434
    vmstop_requested = state;
1435
    qemu_notify_event();
1436
}
1437

    
1438
static GPollFD poll_fds[1024 * 2]; /* this is probably overkill */
1439
static int n_poll_fds;
1440
static int max_priority;
1441

    
1442
static void glib_select_fill(int *max_fd, fd_set *rfds, fd_set *wfds,
1443
                             fd_set *xfds, struct timeval *tv)
1444
{
1445
    GMainContext *context = g_main_context_default();
1446
    int i;
1447
    int timeout = 0, cur_timeout;
1448

    
1449
    g_main_context_prepare(context, &max_priority);
1450

    
1451
    n_poll_fds = g_main_context_query(context, max_priority, &timeout,
1452
                                      poll_fds, ARRAY_SIZE(poll_fds));
1453
    g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));
1454

    
1455
    for (i = 0; i < n_poll_fds; i++) {
1456
        GPollFD *p = &poll_fds[i];
1457

    
1458
        if ((p->events & G_IO_IN)) {
1459
            FD_SET(p->fd, rfds);
1460
            *max_fd = MAX(*max_fd, p->fd);
1461
        }
1462
        if ((p->events & G_IO_OUT)) {
1463
            FD_SET(p->fd, wfds);
1464
            *max_fd = MAX(*max_fd, p->fd);
1465
        }
1466
        if ((p->events & G_IO_ERR)) {
1467
            FD_SET(p->fd, xfds);
1468
            *max_fd = MAX(*max_fd, p->fd);
1469
        }
1470
    }
1471

    
1472
    cur_timeout = (tv->tv_sec * 1000) + ((tv->tv_usec + 500) / 1000);
1473
    if (timeout >= 0 && timeout < cur_timeout) {
1474
        tv->tv_sec = timeout / 1000;
1475
        tv->tv_usec = (timeout % 1000) * 1000;
1476
    }
1477
}
1478

    
1479
static void glib_select_poll(fd_set *rfds, fd_set *wfds, fd_set *xfds,
1480
                             bool err)
1481
{
1482
    GMainContext *context = g_main_context_default();
1483

    
1484
    if (!err) {
1485
        int i;
1486

    
1487
        for (i = 0; i < n_poll_fds; i++) {
1488
            GPollFD *p = &poll_fds[i];
1489

    
1490
            if ((p->events & G_IO_IN) && FD_ISSET(p->fd, rfds)) {
1491
                p->revents |= G_IO_IN;
1492
            }
1493
            if ((p->events & G_IO_OUT) && FD_ISSET(p->fd, wfds)) {
1494
                p->revents |= G_IO_OUT;
1495
            }
1496
            if ((p->events & G_IO_ERR) && FD_ISSET(p->fd, xfds)) {
1497
                p->revents |= G_IO_ERR;
1498
            }
1499
        }
1500
    }
1501

    
1502
    if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {
1503
        g_main_context_dispatch(context);
1504
    }
1505
}
1506

    
1507
int main_loop_wait(int nonblocking)
1508
{
1509
    fd_set rfds, wfds, xfds;
1510
    int ret, nfds;
1511
    struct timeval tv;
1512
    int timeout;
1513

    
1514
    if (nonblocking)
1515
        timeout = 0;
1516
    else {
1517
        timeout = qemu_calculate_timeout();
1518
        qemu_bh_update_timeout(&timeout);
1519
    }
1520

    
1521
    os_host_main_loop_wait(&timeout);
1522

    
1523
    tv.tv_sec = timeout / 1000;
1524
    tv.tv_usec = (timeout % 1000) * 1000;
1525

    
1526
    /* poll any events */
1527
    /* XXX: separate device handlers from system ones */
1528
    nfds = -1;
1529
    FD_ZERO(&rfds);
1530
    FD_ZERO(&wfds);
1531
    FD_ZERO(&xfds);
1532

    
1533
    qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds);
1534
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1535
    glib_select_fill(&nfds, &rfds, &wfds, &xfds, &tv);
1536

    
1537
    if (timeout > 0) {
1538
        qemu_mutex_unlock_iothread();
1539
    }
1540

    
1541
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1542

    
1543
    if (timeout > 0) {
1544
        qemu_mutex_lock_iothread();
1545
    }
1546

    
1547
    qemu_iohandler_poll(&rfds, &wfds, &xfds, ret);
1548
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1549
    glib_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1550

    
1551
    qemu_run_all_timers();
1552

    
1553
    /* Check bottom-halves last in case any of the earlier events triggered
1554
       them.  */
1555
    qemu_bh_poll();
1556

    
1557
    return ret;
1558
}
1559

    
1560
qemu_irq qemu_system_powerdown;
1561

    
1562
static void main_loop(void)
1563
{
1564
    bool nonblocking;
1565
    int last_io __attribute__ ((unused)) = 0;
1566
#ifdef CONFIG_PROFILER
1567
    int64_t ti;
1568
#endif
1569
    int r;
1570

    
1571
    qemu_main_loop_start();
1572

    
1573
    for (;;) {
1574
        nonblocking = !kvm_enabled() && last_io > 0;
1575
#ifdef CONFIG_PROFILER
1576
        ti = profile_getclock();
1577
#endif
1578
        last_io = main_loop_wait(nonblocking);
1579
#ifdef CONFIG_PROFILER
1580
        dev_time += profile_getclock() - ti;
1581
#endif
1582

    
1583
        if (qemu_debug_requested()) {
1584
            vm_stop(RSTATE_DEBUG);
1585
        }
1586
        if (qemu_shutdown_requested()) {
1587
            qemu_kill_report();
1588
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1589
            if (no_shutdown) {
1590
                vm_stop(RSTATE_SHUTDOWN);
1591
            } else
1592
                break;
1593
        }
1594
        if (qemu_reset_requested()) {
1595
            pause_all_vcpus();
1596
            cpu_synchronize_all_states();
1597
            qemu_system_reset(VMRESET_REPORT);
1598
            resume_all_vcpus();
1599
            if (runstate_check(RSTATE_PANICKED) ||
1600
                runstate_check(RSTATE_SHUTDOWN)) {
1601
                runstate_set(RSTATE_PAUSED);
1602
            }
1603
        }
1604
        if (qemu_powerdown_requested()) {
1605
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1606
            qemu_irq_raise(qemu_system_powerdown);
1607
        }
1608
        if ((r = qemu_vmstop_requested())) {
1609
            vm_stop(r);
1610
        }
1611
    }
1612
    bdrv_close_all();
1613
    pause_all_vcpus();
1614
}
1615

    
1616
static void version(void)
1617
{
1618
    printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
1619
}
1620

    
1621
static void help(int exitcode)
1622
{
1623
    const char *options_help =
1624
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1625
        opt_help
1626
#define DEFHEADING(text) stringify(text) "\n"
1627
#include "qemu-options.def"
1628
#undef DEF
1629
#undef DEFHEADING
1630
#undef GEN_DOCS
1631
        ;
1632
    version();
1633
    printf("usage: %s [options] [disk_image]\n"
1634
           "\n"
1635
           "'disk_image' is a raw hard disk image for IDE hard disk 0\n"
1636
           "\n"
1637
           "%s\n"
1638
           "During emulation, the following keys are useful:\n"
1639
           "ctrl-alt-f      toggle full screen\n"
1640
           "ctrl-alt-n      switch to virtual console 'n'\n"
1641
           "ctrl-alt        toggle mouse and keyboard grab\n"
1642
           "\n"
1643
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
1644
           "qemu",
1645
           options_help);
1646
    exit(exitcode);
1647
}
1648

    
1649
#define HAS_ARG 0x0001
1650

    
1651
typedef struct QEMUOption {
1652
    const char *name;
1653
    int flags;
1654
    int index;
1655
    uint32_t arch_mask;
1656
} QEMUOption;
1657

    
1658
static const QEMUOption qemu_options[] = {
1659
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1660
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1661
    { option, opt_arg, opt_enum, arch_mask },
1662
#define DEFHEADING(text)
1663
#include "qemu-options.def"
1664
#undef DEF
1665
#undef DEFHEADING
1666
#undef GEN_DOCS
1667
    { NULL },
1668
};
1669
static void select_vgahw (const char *p)
1670
{
1671
    const char *opts;
1672

    
1673
    default_vga = 0;
1674
    vga_interface_type = VGA_NONE;
1675
    if (strstart(p, "std", &opts)) {
1676
        vga_interface_type = VGA_STD;
1677
    } else if (strstart(p, "cirrus", &opts)) {
1678
        vga_interface_type = VGA_CIRRUS;
1679
    } else if (strstart(p, "vmware", &opts)) {
1680
        vga_interface_type = VGA_VMWARE;
1681
    } else if (strstart(p, "xenfb", &opts)) {
1682
        vga_interface_type = VGA_XENFB;
1683
    } else if (strstart(p, "qxl", &opts)) {
1684
        vga_interface_type = VGA_QXL;
1685
    } else if (!strstart(p, "none", &opts)) {
1686
    invalid_vga:
1687
        fprintf(stderr, "Unknown vga type: %s\n", p);
1688
        exit(1);
1689
    }
1690
    while (*opts) {
1691
        const char *nextopt;
1692

    
1693
        if (strstart(opts, ",retrace=", &nextopt)) {
1694
            opts = nextopt;
1695
            if (strstart(opts, "dumb", &nextopt))
1696
                vga_retrace_method = VGA_RETRACE_DUMB;
1697
            else if (strstart(opts, "precise", &nextopt))
1698
                vga_retrace_method = VGA_RETRACE_PRECISE;
1699
            else goto invalid_vga;
1700
        } else goto invalid_vga;
1701
        opts = nextopt;
1702
    }
1703
}
1704

    
1705
static DisplayType select_display(const char *p)
1706
{
1707
    const char *opts;
1708
    DisplayType display = DT_DEFAULT;
1709

    
1710
    if (strstart(p, "sdl", &opts)) {
1711
#ifdef CONFIG_SDL
1712
        display = DT_SDL;
1713
        while (*opts) {
1714
            const char *nextopt;
1715

    
1716
            if (strstart(opts, ",frame=", &nextopt)) {
1717
                opts = nextopt;
1718
                if (strstart(opts, "on", &nextopt)) {
1719
                    no_frame = 0;
1720
                } else if (strstart(opts, "off", &nextopt)) {
1721
                    no_frame = 1;
1722
                } else {
1723
                    goto invalid_sdl_args;
1724
                }
1725
            } else if (strstart(opts, ",alt_grab=", &nextopt)) {
1726
                opts = nextopt;
1727
                if (strstart(opts, "on", &nextopt)) {
1728
                    alt_grab = 1;
1729
                } else if (strstart(opts, "off", &nextopt)) {
1730
                    alt_grab = 0;
1731
                } else {
1732
                    goto invalid_sdl_args;
1733
                }
1734
            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {
1735
                opts = nextopt;
1736
                if (strstart(opts, "on", &nextopt)) {
1737
                    ctrl_grab = 1;
1738
                } else if (strstart(opts, "off", &nextopt)) {
1739
                    ctrl_grab = 0;
1740
                } else {
1741
                    goto invalid_sdl_args;
1742
                }
1743
            } else if (strstart(opts, ",window_close=", &nextopt)) {
1744
                opts = nextopt;
1745
                if (strstart(opts, "on", &nextopt)) {
1746
                    no_quit = 0;
1747
                } else if (strstart(opts, "off", &nextopt)) {
1748
                    no_quit = 1;
1749
                } else {
1750
                    goto invalid_sdl_args;
1751
                }
1752
            } else {
1753
            invalid_sdl_args:
1754
                fprintf(stderr, "Invalid SDL option string: %s\n", p);
1755
                exit(1);
1756
            }
1757
            opts = nextopt;
1758
        }
1759
#else
1760
        fprintf(stderr, "SDL support is disabled\n");
1761
        exit(1);
1762
#endif
1763
    } else if (strstart(p, "vnc", &opts)) {
1764
#ifdef CONFIG_VNC
1765
        display_remote++;
1766

    
1767
        if (*opts) {
1768
            const char *nextopt;
1769

    
1770
            if (strstart(opts, "=", &nextopt)) {
1771
                vnc_display = nextopt;
1772
            }
1773
        }
1774
        if (!vnc_display) {
1775
            fprintf(stderr, "VNC requires a display argument vnc=<display>\n");
1776
            exit(1);
1777
        }
1778
#else
1779
        fprintf(stderr, "VNC support is disabled\n");
1780
        exit(1);
1781
#endif
1782
    } else if (strstart(p, "curses", &opts)) {
1783
#ifdef CONFIG_CURSES
1784
        display = DT_CURSES;
1785
#else
1786
        fprintf(stderr, "Curses support is disabled\n");
1787
        exit(1);
1788
#endif
1789
    } else if (strstart(p, "none", &opts)) {
1790
        display = DT_NONE;
1791
    } else {
1792
        fprintf(stderr, "Unknown display type: %s\n", p);
1793
        exit(1);
1794
    }
1795

    
1796
    return display;
1797
}
1798

    
1799
static int balloon_parse(const char *arg)
1800
{
1801
    QemuOpts *opts;
1802

    
1803
    if (strcmp(arg, "none") == 0) {
1804
        return 0;
1805
    }
1806

    
1807
    if (!strncmp(arg, "virtio", 6)) {
1808
        if (arg[6] == ',') {
1809
            /* have params -> parse them */
1810
            opts = qemu_opts_parse(qemu_find_opts("device"), arg+7, 0);
1811
            if (!opts)
1812
                return  -1;
1813
        } else {
1814
            /* create empty opts */
1815
            opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
1816
        }
1817
        qemu_opt_set(opts, "driver", "virtio-balloon");
1818
        return 0;
1819
    }
1820

    
1821
    return -1;
1822
}
1823

    
1824
char *qemu_find_file(int type, const char *name)
1825
{
1826
    int len;
1827
    const char *subdir;
1828
    char *buf;
1829

    
1830
    /* If name contains path separators then try it as a straight path.  */
1831
    if ((strchr(name, '/') || strchr(name, '\\'))
1832
        && access(name, R_OK) == 0) {
1833
        return g_strdup(name);
1834
    }
1835
    switch (type) {
1836
    case QEMU_FILE_TYPE_BIOS:
1837
        subdir = "";
1838
        break;
1839
    case QEMU_FILE_TYPE_KEYMAP:
1840
        subdir = "keymaps/";
1841
        break;
1842
    default:
1843
        abort();
1844
    }
1845
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
1846
    buf = g_malloc0(len);
1847
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
1848
    if (access(buf, R_OK)) {
1849
        g_free(buf);
1850
        return NULL;
1851
    }
1852
    return buf;
1853
}
1854

    
1855
static int device_help_func(QemuOpts *opts, void *opaque)
1856
{
1857
    return qdev_device_help(opts);
1858
}
1859

    
1860
static int device_init_func(QemuOpts *opts, void *opaque)
1861
{
1862
    DeviceState *dev;
1863

    
1864
    dev = qdev_device_add(opts);
1865
    if (!dev)
1866
        return -1;
1867
    return 0;
1868
}
1869

    
1870
static int chardev_init_func(QemuOpts *opts, void *opaque)
1871
{
1872
    CharDriverState *chr;
1873

    
1874
    chr = qemu_chr_new_from_opts(opts, NULL);
1875
    if (!chr)
1876
        return -1;
1877
    return 0;
1878
}
1879

    
1880
#ifdef CONFIG_VIRTFS
1881
static int fsdev_init_func(QemuOpts *opts, void *opaque)
1882
{
1883
    int ret;
1884
    ret = qemu_fsdev_add(opts);
1885

    
1886
    return ret;
1887
}
1888
#endif
1889

    
1890
static int mon_init_func(QemuOpts *opts, void *opaque)
1891
{
1892
    CharDriverState *chr;
1893
    const char *chardev;
1894
    const char *mode;
1895
    int flags;
1896

    
1897
    mode = qemu_opt_get(opts, "mode");
1898
    if (mode == NULL) {
1899
        mode = "readline";
1900
    }
1901
    if (strcmp(mode, "readline") == 0) {
1902
        flags = MONITOR_USE_READLINE;
1903
    } else if (strcmp(mode, "control") == 0) {
1904
        flags = MONITOR_USE_CONTROL;
1905
    } else {
1906
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
1907
        exit(1);
1908
    }
1909

    
1910
    if (qemu_opt_get_bool(opts, "pretty", 0))
1911
        flags |= MONITOR_USE_PRETTY;
1912

    
1913
    if (qemu_opt_get_bool(opts, "default", 0))
1914
        flags |= MONITOR_IS_DEFAULT;
1915

    
1916
    chardev = qemu_opt_get(opts, "chardev");
1917
    chr = qemu_chr_find(chardev);
1918
    if (chr == NULL) {
1919
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
1920
        exit(1);
1921
    }
1922

    
1923
    monitor_init(chr, flags);
1924
    return 0;
1925
}
1926

    
1927
static void monitor_parse(const char *optarg, const char *mode)
1928
{
1929
    static int monitor_device_index = 0;
1930
    QemuOpts *opts;
1931
    const char *p;
1932
    char label[32];
1933
    int def = 0;
1934

    
1935
    if (strstart(optarg, "chardev:", &p)) {
1936
        snprintf(label, sizeof(label), "%s", p);
1937
    } else {
1938
        snprintf(label, sizeof(label), "compat_monitor%d",
1939
                 monitor_device_index);
1940
        if (monitor_device_index == 0) {
1941
            def = 1;
1942
        }
1943
        opts = qemu_chr_parse_compat(label, optarg);
1944
        if (!opts) {
1945
            fprintf(stderr, "parse error: %s\n", optarg);
1946
            exit(1);
1947
        }
1948
    }
1949

    
1950
    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1);
1951
    if (!opts) {
1952
        fprintf(stderr, "duplicate chardev: %s\n", label);
1953
        exit(1);
1954
    }
1955
    qemu_opt_set(opts, "mode", mode);
1956
    qemu_opt_set(opts, "chardev", label);
1957
    if (def)
1958
        qemu_opt_set(opts, "default", "on");
1959
    monitor_device_index++;
1960
}
1961

    
1962
struct device_config {
1963
    enum {
1964
        DEV_USB,       /* -usbdevice     */
1965
        DEV_BT,        /* -bt            */
1966
        DEV_SERIAL,    /* -serial        */
1967
        DEV_PARALLEL,  /* -parallel      */
1968
        DEV_VIRTCON,   /* -virtioconsole */
1969
        DEV_DEBUGCON,  /* -debugcon */
1970
    } type;
1971
    const char *cmdline;
1972
    QTAILQ_ENTRY(device_config) next;
1973
};
1974
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
1975

    
1976
static void add_device_config(int type, const char *cmdline)
1977
{
1978
    struct device_config *conf;
1979

    
1980
    conf = g_malloc0(sizeof(*conf));
1981
    conf->type = type;
1982
    conf->cmdline = cmdline;
1983
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
1984
}
1985

    
1986
static int foreach_device_config(int type, int (*func)(const char *cmdline))
1987
{
1988
    struct device_config *conf;
1989
    int rc;
1990

    
1991
    QTAILQ_FOREACH(conf, &device_configs, next) {
1992
        if (conf->type != type)
1993
            continue;
1994
        rc = func(conf->cmdline);
1995
        if (0 != rc)
1996
            return rc;
1997
    }
1998
    return 0;
1999
}
2000

    
2001
static int serial_parse(const char *devname)
2002
{
2003
    static int index = 0;
2004
    char label[32];
2005

    
2006
    if (strcmp(devname, "none") == 0)
2007
        return 0;
2008
    if (index == MAX_SERIAL_PORTS) {
2009
        fprintf(stderr, "qemu: too many serial ports\n");
2010
        exit(1);
2011
    }
2012
    snprintf(label, sizeof(label), "serial%d", index);
2013
    serial_hds[index] = qemu_chr_new(label, devname, NULL);
2014
    if (!serial_hds[index]) {
2015
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
2016
                devname, strerror(errno));
2017
        return -1;
2018
    }
2019
    index++;
2020
    return 0;
2021
}
2022

    
2023
static int parallel_parse(const char *devname)
2024
{
2025
    static int index = 0;
2026
    char label[32];
2027

    
2028
    if (strcmp(devname, "none") == 0)
2029
        return 0;
2030
    if (index == MAX_PARALLEL_PORTS) {
2031
        fprintf(stderr, "qemu: too many parallel ports\n");
2032
        exit(1);
2033
    }
2034
    snprintf(label, sizeof(label), "parallel%d", index);
2035
    parallel_hds[index] = qemu_chr_new(label, devname, NULL);
2036
    if (!parallel_hds[index]) {
2037
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2038
                devname, strerror(errno));
2039
        return -1;
2040
    }
2041
    index++;
2042
    return 0;
2043
}
2044

    
2045
static int virtcon_parse(const char *devname)
2046
{
2047
    QemuOptsList *device = qemu_find_opts("device");
2048
    static int index = 0;
2049
    char label[32];
2050
    QemuOpts *bus_opts, *dev_opts;
2051

    
2052
    if (strcmp(devname, "none") == 0)
2053
        return 0;
2054
    if (index == MAX_VIRTIO_CONSOLES) {
2055
        fprintf(stderr, "qemu: too many virtio consoles\n");
2056
        exit(1);
2057
    }
2058

    
2059
    bus_opts = qemu_opts_create(device, NULL, 0);
2060
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
2061

    
2062
    dev_opts = qemu_opts_create(device, NULL, 0);
2063
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2064

    
2065
    snprintf(label, sizeof(label), "virtcon%d", index);
2066
    virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
2067
    if (!virtcon_hds[index]) {
2068
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2069
                devname, strerror(errno));
2070
        return -1;
2071
    }
2072
    qemu_opt_set(dev_opts, "chardev", label);
2073

    
2074
    index++;
2075
    return 0;
2076
}
2077

    
2078
static int debugcon_parse(const char *devname)
2079
{   
2080
    QemuOpts *opts;
2081

    
2082
    if (!qemu_chr_new("debugcon", devname, NULL)) {
2083
        exit(1);
2084
    }
2085
    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1);
2086
    if (!opts) {
2087
        fprintf(stderr, "qemu: already have a debugcon device\n");
2088
        exit(1);
2089
    }
2090
    qemu_opt_set(opts, "driver", "isa-debugcon");
2091
    qemu_opt_set(opts, "chardev", "debugcon");
2092
    return 0;
2093
}
2094

    
2095
static QEMUMachine *machine_parse(const char *name)
2096
{
2097
    QEMUMachine *m, *machine = NULL;
2098

    
2099
    if (name) {
2100
        machine = find_machine(name);
2101
    }
2102
    if (machine) {
2103
        return machine;
2104
    }
2105
    printf("Supported machines are:\n");
2106
    for (m = first_machine; m != NULL; m = m->next) {
2107
        if (m->alias) {
2108
            printf("%-10s %s (alias of %s)\n", m->alias, m->desc, m->name);
2109
        }
2110
        printf("%-10s %s%s\n", m->name, m->desc,
2111
               m->is_default ? " (default)" : "");
2112
    }
2113
    exit(!name || *name != '?');
2114
}
2115

    
2116
static int tcg_init(void)
2117
{
2118
    tcg_exec_init(tcg_tb_size * 1024 * 1024);
2119
    return 0;
2120
}
2121

    
2122
static struct {
2123
    const char *opt_name;
2124
    const char *name;
2125
    int (*available)(void);
2126
    int (*init)(void);
2127
    int *allowed;
2128
} accel_list[] = {
2129
    { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
2130
    { "xen", "Xen", xen_available, xen_init, &xen_allowed },
2131
    { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
2132
};
2133

    
2134
static int configure_accelerator(void)
2135
{
2136
    const char *p = NULL;
2137
    char buf[10];
2138
    int i, ret;
2139
    bool accel_initalised = 0;
2140
    bool init_failed = 0;
2141

    
2142
    QemuOptsList *list = qemu_find_opts("machine");
2143
    if (!QTAILQ_EMPTY(&list->head)) {
2144
        p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
2145
    }
2146

    
2147
    if (p == NULL) {
2148
        /* Use the default "accelerator", tcg */
2149
        p = "tcg";
2150
    }
2151

    
2152
    while (!accel_initalised && *p != '\0') {
2153
        if (*p == ':') {
2154
            p++;
2155
        }
2156
        p = get_opt_name(buf, sizeof (buf), p, ':');
2157
        for (i = 0; i < ARRAY_SIZE(accel_list); i++) {
2158
            if (strcmp(accel_list[i].opt_name, buf) == 0) {
2159
                *(accel_list[i].allowed) = 1;
2160
                ret = accel_list[i].init();
2161
                if (ret < 0) {
2162
                    init_failed = 1;
2163
                    if (!accel_list[i].available()) {
2164
                        printf("%s not supported for this target\n",
2165
                               accel_list[i].name);
2166
                    } else {
2167
                        fprintf(stderr, "failed to initialize %s: %s\n",
2168
                                accel_list[i].name,
2169
                                strerror(-ret));
2170
                    }
2171
                    *(accel_list[i].allowed) = 0;
2172
                } else {
2173
                    accel_initalised = 1;
2174
                }
2175
                break;
2176
            }
2177
        }
2178
        if (i == ARRAY_SIZE(accel_list)) {
2179
            fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);
2180
        }
2181
    }
2182

    
2183
    if (!accel_initalised) {
2184
        fprintf(stderr, "No accelerator found!\n");
2185
        exit(1);
2186
    }
2187

    
2188
    if (init_failed) {
2189
        fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
2190
    }
2191

    
2192
    return !accel_initalised;
2193
}
2194

    
2195
void qemu_add_exit_notifier(Notifier *notify)
2196
{
2197
    notifier_list_add(&exit_notifiers, notify);
2198
}
2199

    
2200
void qemu_remove_exit_notifier(Notifier *notify)
2201
{
2202
    notifier_list_remove(&exit_notifiers, notify);
2203
}
2204

    
2205
static void qemu_run_exit_notifiers(void)
2206
{
2207
    notifier_list_notify(&exit_notifiers, NULL);
2208
}
2209

    
2210
void qemu_add_machine_init_done_notifier(Notifier *notify)
2211
{
2212
    notifier_list_add(&machine_init_done_notifiers, notify);
2213
}
2214

    
2215
static void qemu_run_machine_init_done_notifiers(void)
2216
{
2217
    notifier_list_notify(&machine_init_done_notifiers, NULL);
2218
}
2219

    
2220
static const QEMUOption *lookup_opt(int argc, char **argv,
2221
                                    const char **poptarg, int *poptind)
2222
{
2223
    const QEMUOption *popt;
2224
    int optind = *poptind;
2225
    char *r = argv[optind];
2226
    const char *optarg;
2227

    
2228
    loc_set_cmdline(argv, optind, 1);
2229
    optind++;
2230
    /* Treat --foo the same as -foo.  */
2231
    if (r[1] == '-')
2232
        r++;
2233
    popt = qemu_options;
2234
    for(;;) {
2235
        if (!popt->name) {
2236
            error_report("invalid option");
2237
            exit(1);
2238
        }
2239
        if (!strcmp(popt->name, r + 1))
2240
            break;
2241
        popt++;
2242
    }
2243
    if (popt->flags & HAS_ARG) {
2244
        if (optind >= argc) {
2245
            error_report("requires an argument");
2246
            exit(1);
2247
        }
2248
        optarg = argv[optind++];
2249
        loc_set_cmdline(argv, optind - 2, 2);
2250
    } else {
2251
        optarg = NULL;
2252
    }
2253

    
2254
    *poptarg = optarg;
2255
    *poptind = optind;
2256

    
2257
    return popt;
2258
}
2259

    
2260
static gpointer malloc_and_trace(gsize n_bytes)
2261
{
2262
    void *ptr = malloc(n_bytes);
2263
    trace_g_malloc(n_bytes, ptr);
2264
    return ptr;
2265
}
2266

    
2267
static gpointer realloc_and_trace(gpointer mem, gsize n_bytes)
2268
{
2269
    void *ptr = realloc(mem, n_bytes);
2270
    trace_g_realloc(mem, n_bytes, ptr);
2271
    return ptr;
2272
}
2273

    
2274
static void free_and_trace(gpointer mem)
2275
{
2276
    trace_g_free(mem);
2277
    free(mem);
2278
}
2279

    
2280
int main(int argc, char **argv, char **envp)
2281
{
2282
    const char *gdbstub_dev = NULL;
2283
    int i;
2284
    int snapshot, linux_boot;
2285
    const char *icount_option = NULL;
2286
    const char *initrd_filename;
2287
    const char *kernel_filename, *kernel_cmdline;
2288
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
2289
    DisplayState *ds;
2290
    DisplayChangeListener *dcl;
2291
    int cyls, heads, secs, translation;
2292
    QemuOpts *hda_opts = NULL, *opts;
2293
    QemuOptsList *olist;
2294
    int optind;
2295
    const char *optarg;
2296
    const char *loadvm = NULL;
2297
    QEMUMachine *machine;
2298
    const char *cpu_model;
2299
    const char *pid_file = NULL;
2300
    const char *incoming = NULL;
2301
#ifdef CONFIG_VNC
2302
    int show_vnc_port = 0;
2303
#endif
2304
    int defconfig = 1;
2305
    const char *log_mask = NULL;
2306
    const char *log_file = NULL;
2307
    GMemVTable mem_trace = {
2308
        .malloc = malloc_and_trace,
2309
        .realloc = realloc_and_trace,
2310
        .free = free_and_trace,
2311
    };
2312
    const char *trace_events = NULL;
2313
    const char *trace_file = NULL;
2314

    
2315
    atexit(qemu_run_exit_notifiers);
2316
    error_set_progname(argv[0]);
2317

    
2318
    g_mem_set_vtable(&mem_trace);
2319
    g_thread_init(NULL);
2320

    
2321
    runstate_init();
2322

    
2323
    init_clocks();
2324

    
2325
    qemu_cache_utils_init(envp);
2326

    
2327
    QLIST_INIT (&vm_change_state_head);
2328
    os_setup_early_signal_handling();
2329

    
2330
    module_call_init(MODULE_INIT_MACHINE);
2331
    machine = find_default_machine();
2332
    cpu_model = NULL;
2333
    initrd_filename = NULL;
2334
    ram_size = 0;
2335
    snapshot = 0;
2336
    kernel_filename = NULL;
2337
    kernel_cmdline = "";
2338
    cyls = heads = secs = 0;
2339
    translation = BIOS_ATA_TRANSLATION_AUTO;
2340

    
2341
    for (i = 0; i < MAX_NODES; i++) {
2342
        node_mem[i] = 0;
2343
        node_cpumask[i] = 0;
2344
    }
2345

    
2346
    nb_numa_nodes = 0;
2347
    nb_nics = 0;
2348

    
2349
    autostart= 1;
2350

    
2351
    /* first pass of option parsing */
2352
    optind = 1;
2353
    while (optind < argc) {
2354
        if (argv[optind][0] != '-') {
2355
            /* disk image */
2356
            optind++;
2357
            continue;
2358
        } else {
2359
            const QEMUOption *popt;
2360

    
2361
            popt = lookup_opt(argc, argv, &optarg, &optind);
2362
            switch (popt->index) {
2363
            case QEMU_OPTION_nodefconfig:
2364
                defconfig=0;
2365
                break;
2366
            }
2367
        }
2368
    }
2369

    
2370
    if (defconfig) {
2371
        int ret;
2372

    
2373
        ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2374
        if (ret < 0 && ret != -ENOENT) {
2375
            exit(1);
2376
        }
2377

    
2378
        ret = qemu_read_config_file(arch_config_name);
2379
        if (ret < 0 && ret != -ENOENT) {
2380
            exit(1);
2381
        }
2382
    }
2383
    cpudef_init();
2384

    
2385
    /* second pass of option parsing */
2386
    optind = 1;
2387
    for(;;) {
2388
        if (optind >= argc)
2389
            break;
2390
        if (argv[optind][0] != '-') {
2391
            hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2392
        } else {
2393
            const QEMUOption *popt;
2394

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

    
2564
                    if (!strchr(optarg, '=')) {
2565
                        legacy = 1;
2566
                        pstrcpy(buf, sizeof(buf), optarg);
2567
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2568
                        fprintf(stderr,
2569
                                "qemu: unknown boot parameter '%s' in '%s'\n",
2570
                                buf, optarg);
2571
                        exit(1);
2572
                    }
2573

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

    
2664
                value = strtosz(optarg, NULL);
2665
                if (value < 0) {
2666
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
2667
                    exit(1);
2668
                }
2669

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

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

    
2797
                olist = qemu_find_opts("virtfs");
2798
                if (!olist) {
2799
                    fprintf(stderr, "virtfs is not supported by this qemu build.\n");
2800
                    exit(1);
2801
                }
2802
                opts = qemu_opts_parse(olist, optarg, 1);
2803
                if (!opts) {
2804
                    fprintf(stderr, "parse error: %s\n", optarg);
2805
                    exit(1);
2806
                }
2807

    
2808
                if (qemu_opt_get(opts, "fstype") == NULL ||
2809
                        qemu_opt_get(opts, "mount_tag") == NULL ||
2810
                        qemu_opt_get(opts, "path") == NULL ||
2811
                        qemu_opt_get(opts, "security_model") == NULL) {
2812
                    fprintf(stderr, "Usage: -virtfs fstype,path=/share_path/,"
2813
                            "security_model=[mapped|passthrough|none],"
2814
                            "mount_tag=tag.\n");
2815
                    exit(1);
2816
                }
2817

    
2818
                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
2819
                                         qemu_opt_get(opts, "mount_tag"), 1);
2820
                if (!fsdev) {
2821
                    fprintf(stderr, "duplicate fsdev id: %s\n",
2822
                            qemu_opt_get(opts, "mount_tag"));
2823
                    exit(1);
2824
                }
2825
                qemu_opt_set(fsdev, "fstype", qemu_opt_get(opts, "fstype"));
2826
                qemu_opt_set(fsdev, "path", qemu_opt_get(opts, "path"));
2827
                qemu_opt_set(fsdev, "security_model",
2828
                             qemu_opt_get(opts, "security_model"));
2829

    
2830
                device = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
2831
                qemu_opt_set(device, "driver", "virtio-9p-pci");
2832
                qemu_opt_set(device, "fsdev",
2833
                             qemu_opt_get(opts, "mount_tag"));
2834
                qemu_opt_set(device, "mount_tag",
2835
                             qemu_opt_get(opts, "mount_tag"));
2836
                break;
2837
            }
2838
            case QEMU_OPTION_serial:
2839
                add_device_config(DEV_SERIAL, optarg);
2840
                default_serial = 0;
2841
                if (strncmp(optarg, "mon:", 4) == 0) {
2842
                    default_monitor = 0;
2843
                }
2844
                break;
2845
            case QEMU_OPTION_watchdog:
2846
                if (watchdog) {
2847
                    fprintf(stderr,
2848
                            "qemu: only one watchdog option may be given\n");
2849
                    return 1;
2850
                }
2851
                watchdog = optarg;
2852
                break;
2853
            case QEMU_OPTION_watchdog_action:
2854
                if (select_watchdog_action(optarg) == -1) {
2855
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
2856
                    exit(1);
2857
                }
2858
                break;
2859
            case QEMU_OPTION_virtiocon:
2860
                add_device_config(DEV_VIRTCON, optarg);
2861
                default_virtcon = 0;
2862
                if (strncmp(optarg, "mon:", 4) == 0) {
2863
                    default_monitor = 0;
2864
                }
2865
                break;
2866
            case QEMU_OPTION_parallel:
2867
                add_device_config(DEV_PARALLEL, optarg);
2868
                default_parallel = 0;
2869
                if (strncmp(optarg, "mon:", 4) == 0) {
2870
                    default_monitor = 0;
2871
                }
2872
                break;
2873
            case QEMU_OPTION_debugcon:
2874
                add_device_config(DEV_DEBUGCON, optarg);
2875
                break;
2876
            case QEMU_OPTION_loadvm:
2877
                loadvm = optarg;
2878
                break;
2879
            case QEMU_OPTION_full_screen:
2880
                full_screen = 1;
2881
                break;
2882
#ifdef CONFIG_SDL
2883
            case QEMU_OPTION_no_frame:
2884
                no_frame = 1;
2885
                break;
2886
            case QEMU_OPTION_alt_grab:
2887
                alt_grab = 1;
2888
                break;
2889
            case QEMU_OPTION_ctrl_grab:
2890
                ctrl_grab = 1;
2891
                break;
2892
            case QEMU_OPTION_no_quit:
2893
                no_quit = 1;
2894
                break;
2895
            case QEMU_OPTION_sdl:
2896
                display_type = DT_SDL;
2897
                break;
2898
#else
2899
            case QEMU_OPTION_no_frame:
2900
            case QEMU_OPTION_alt_grab:
2901
            case QEMU_OPTION_ctrl_grab:
2902
            case QEMU_OPTION_no_quit:
2903
            case QEMU_OPTION_sdl:
2904
                fprintf(stderr, "SDL support is disabled\n");
2905
                exit(1);
2906
#endif
2907
            case QEMU_OPTION_pidfile:
2908
                pid_file = optarg;
2909
                break;
2910
            case QEMU_OPTION_win2k_hack:
2911
                win2k_install_hack = 1;
2912
                break;
2913
            case QEMU_OPTION_rtc_td_hack:
2914
                rtc_td_hack = 1;
2915
                break;
2916
            case QEMU_OPTION_acpitable:
2917
                do_acpitable_option(optarg);
2918
                break;
2919
            case QEMU_OPTION_smbios:
2920
                do_smbios_option(optarg);
2921
                break;
2922
            case QEMU_OPTION_enable_kvm:
2923
                olist = qemu_find_opts("machine");
2924
                qemu_opts_reset(olist);
2925
                qemu_opts_parse(olist, "accel=kvm", 0);
2926
                break;
2927
            case QEMU_OPTION_machine:
2928
                olist = qemu_find_opts("machine");
2929
                qemu_opts_reset(olist);
2930
                opts = qemu_opts_parse(olist, optarg, 1);
2931
                if (!opts) {
2932
                    fprintf(stderr, "parse error: %s\n", optarg);
2933
                    exit(1);
2934
                }
2935
                optarg = qemu_opt_get(opts, "type");
2936
                if (optarg) {
2937
                    machine = machine_parse(optarg);
2938
                }
2939
                break;
2940
            case QEMU_OPTION_usb:
2941
                usb_enabled = 1;
2942
                break;
2943
            case QEMU_OPTION_usbdevice:
2944
                usb_enabled = 1;
2945
                add_device_config(DEV_USB, optarg);
2946
                break;
2947
            case QEMU_OPTION_device:
2948
                if (!qemu_opts_parse(qemu_find_opts("device"), optarg, 1)) {
2949
                    exit(1);
2950
                }
2951
                break;
2952
            case QEMU_OPTION_smp:
2953
                smp_parse(optarg);
2954
                if (smp_cpus < 1) {
2955
                    fprintf(stderr, "Invalid number of CPUs\n");
2956
                    exit(1);
2957
                }
2958
                if (max_cpus < smp_cpus) {
2959
                    fprintf(stderr, "maxcpus must be equal to or greater than "
2960
                            "smp\n");
2961
                    exit(1);
2962
                }
2963
                if (max_cpus > 255) {
2964
                    fprintf(stderr, "Unsupported number of maxcpus\n");
2965
                    exit(1);
2966
                }
2967
                break;
2968
            case QEMU_OPTION_vnc:
2969
#ifdef CONFIG_VNC
2970
                display_remote++;
2971
                vnc_display = optarg;
2972
#else
2973
                fprintf(stderr, "VNC support is disabled\n");
2974
                exit(1);
2975
#endif
2976
                break;
2977
            case QEMU_OPTION_no_acpi:
2978
                acpi_enabled = 0;
2979
                break;
2980
            case QEMU_OPTION_no_hpet:
2981
                no_hpet = 1;
2982
                break;
2983
            case QEMU_OPTION_balloon:
2984
                if (balloon_parse(optarg) < 0) {
2985
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
2986
                    exit(1);
2987
                }
2988
                break;
2989
            case QEMU_OPTION_no_reboot:
2990
                no_reboot = 1;
2991
                break;
2992
            case QEMU_OPTION_no_shutdown:
2993
                no_shutdown = 1;
2994
                break;
2995
            case QEMU_OPTION_show_cursor:
2996
                cursor_hide = 0;
2997
                break;
2998
            case QEMU_OPTION_uuid:
2999
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
3000
                    fprintf(stderr, "Fail to parse UUID string."
3001
                            " Wrong format.\n");
3002
                    exit(1);
3003
                }
3004
                break;
3005
            case QEMU_OPTION_option_rom:
3006
                if (nb_option_roms >= MAX_OPTION_ROMS) {
3007
                    fprintf(stderr, "Too many option ROMs\n");
3008
                    exit(1);
3009
                }
3010
                opts = qemu_opts_parse(qemu_find_opts("option-rom"), optarg, 1);
3011
                option_rom[nb_option_roms].name = qemu_opt_get(opts, "romfile");
3012
                option_rom[nb_option_roms].bootindex =
3013
                    qemu_opt_get_number(opts, "bootindex", -1);
3014
                if (!option_rom[nb_option_roms].name) {
3015
                    fprintf(stderr, "Option ROM file is not specified\n");
3016
                    exit(1);
3017
                }
3018
                nb_option_roms++;
3019
                break;
3020
            case QEMU_OPTION_semihosting:
3021
                semihosting_enabled = 1;
3022
                break;
3023
            case QEMU_OPTION_name:
3024
                qemu_name = g_strdup(optarg);
3025
                 {
3026
                     char *p = strchr(qemu_name, ',');
3027
                     if (p != NULL) {
3028
                        *p++ = 0;
3029
                        if (strncmp(p, "process=", 8)) {
3030
                            fprintf(stderr, "Unknown subargument %s to -name\n", p);
3031
                            exit(1);
3032
                        }
3033
                        p += 8;
3034
                        os_set_proc_name(p);
3035
                     }        
3036
                 }        
3037
                break;
3038
            case QEMU_OPTION_prom_env:
3039
                if (nb_prom_envs >= MAX_PROM_ENVS) {
3040
                    fprintf(stderr, "Too many prom variables\n");
3041
                    exit(1);
3042
                }
3043
                prom_envs[nb_prom_envs] = optarg;
3044
                nb_prom_envs++;
3045
                break;
3046
            case QEMU_OPTION_old_param:
3047
                old_param = 1;
3048
                break;
3049
            case QEMU_OPTION_clock:
3050
                configure_alarms(optarg);
3051
                break;
3052
            case QEMU_OPTION_startdate:
3053
                configure_rtc_date_offset(optarg, 1);
3054
                break;
3055
            case QEMU_OPTION_rtc:
3056
                opts = qemu_opts_parse(qemu_find_opts("rtc"), optarg, 0);
3057
                if (!opts) {
3058
                    exit(1);
3059
                }
3060
                configure_rtc(opts);
3061
                break;
3062
            case QEMU_OPTION_tb_size:
3063
                tcg_tb_size = strtol(optarg, NULL, 0);
3064
                if (tcg_tb_size < 0) {
3065
                    tcg_tb_size = 0;
3066
                }
3067
                break;
3068
            case QEMU_OPTION_icount:
3069
                icount_option = optarg;
3070
                break;
3071
            case QEMU_OPTION_incoming:
3072
                incoming = optarg;
3073
                break;
3074
            case QEMU_OPTION_nodefaults:
3075
                default_serial = 0;
3076
                default_parallel = 0;
3077
                default_virtcon = 0;
3078
                default_monitor = 0;
3079
                default_vga = 0;
3080
                default_net = 0;
3081
                default_floppy = 0;
3082
                default_cdrom = 0;
3083
                default_sdcard = 0;
3084
                break;
3085
            case QEMU_OPTION_xen_domid:
3086
                if (!(xen_available())) {
3087
                    printf("Option %s not supported for this target\n", popt->name);
3088
                    exit(1);
3089
                }
3090
                xen_domid = atoi(optarg);
3091
                break;
3092
            case QEMU_OPTION_xen_create:
3093
                if (!(xen_available())) {
3094
                    printf("Option %s not supported for this target\n", popt->name);
3095
                    exit(1);
3096
                }
3097
                xen_mode = XEN_CREATE;
3098
                break;
3099
            case QEMU_OPTION_xen_attach:
3100
                if (!(xen_available())) {
3101
                    printf("Option %s not supported for this target\n", popt->name);
3102
                    exit(1);
3103
                }
3104
                xen_mode = XEN_ATTACH;
3105
                break;
3106
            case QEMU_OPTION_trace:
3107
            {
3108
                opts = qemu_opts_parse(qemu_find_opts("trace"), optarg, 0);
3109
                if (!opts) {
3110
                    exit(1);
3111
                }
3112
                trace_events = qemu_opt_get(opts, "events");
3113
                trace_file = qemu_opt_get(opts, "file");
3114
                break;
3115
            }
3116
            case QEMU_OPTION_readconfig:
3117
                {
3118
                    int ret = qemu_read_config_file(optarg);
3119
                    if (ret < 0) {
3120
                        fprintf(stderr, "read config %s: %s\n", optarg,
3121
                            strerror(-ret));
3122
                        exit(1);
3123
                    }
3124
                    break;
3125
                }
3126
            case QEMU_OPTION_spice:
3127
                olist = qemu_find_opts("spice");
3128
                if (!olist) {
3129
                    fprintf(stderr, "spice is not supported by this qemu build.\n");
3130
                    exit(1);
3131
                }
3132
                opts = qemu_opts_parse(olist, optarg, 0);
3133
                if (!opts) {
3134
                    fprintf(stderr, "parse error: %s\n", optarg);
3135
                    exit(1);
3136
                }
3137
                break;
3138
            case QEMU_OPTION_writeconfig:
3139
                {
3140
                    FILE *fp;
3141
                    if (strcmp(optarg, "-") == 0) {
3142
                        fp = stdout;
3143
                    } else {
3144
                        fp = fopen(optarg, "w");
3145
                        if (fp == NULL) {
3146
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
3147
                            exit(1);
3148
                        }
3149
                    }
3150
                    qemu_config_write(fp);
3151
                    fclose(fp);
3152
                    break;
3153
                }
3154
            default:
3155
                os_parse_cmd_args(popt->index, optarg);
3156
            }
3157
        }
3158
    }
3159
    loc_set_none();
3160

    
3161
    /* Open the logfile at this point, if necessary. We can't open the logfile
3162
     * when encountering either of the logging options (-d or -D) because the
3163
     * other one may be encountered later on the command line, changing the
3164
     * location or level of logging.
3165
     */
3166
    if (log_mask) {
3167
        if (log_file) {
3168
            set_cpu_log_filename(log_file);
3169
        }
3170
        set_cpu_log(log_mask);
3171
    }
3172

    
3173
    if (!trace_backend_init(trace_events, trace_file)) {
3174
        exit(1);
3175
    }
3176

    
3177
    /* If no data_dir is specified then try to find it relative to the
3178
       executable path.  */
3179
    if (!data_dir) {
3180
        data_dir = os_find_datadir(argv[0]);
3181
    }
3182
    /* If all else fails use the install path specified when building. */
3183
    if (!data_dir) {
3184
        data_dir = CONFIG_QEMU_DATADIR;
3185
    }
3186

    
3187
    /*
3188
     * Default to max_cpus = smp_cpus, in case the user doesn't
3189
     * specify a max_cpus value.
3190
     */
3191
    if (!max_cpus)
3192
        max_cpus = smp_cpus;
3193

    
3194
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
3195
    if (smp_cpus > machine->max_cpus) {
3196
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
3197
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
3198
                machine->max_cpus);
3199
        exit(1);
3200
    }
3201

    
3202
    /*
3203
     * Get the default machine options from the machine if it is not already
3204
     * specified either by the configuration file or by the command line.
3205
     */
3206
    if (machine->default_machine_opts) {
3207
        QemuOptsList *list = qemu_find_opts("machine");
3208
        const char *p = NULL;
3209

    
3210
        if (!QTAILQ_EMPTY(&list->head)) {
3211
            p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
3212
        }
3213
        if (p == NULL) {
3214
            qemu_opts_reset(list);
3215
            opts = qemu_opts_parse(list, machine->default_machine_opts, 0);
3216
            if (!opts) {
3217
                fprintf(stderr, "parse error for machine %s: %s\n",
3218
                        machine->name, machine->default_machine_opts);
3219
                exit(1);
3220
            }
3221
        }
3222
    }
3223

    
3224
    qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
3225
    qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
3226

    
3227
    if (machine->no_serial) {
3228
        default_serial = 0;
3229
    }
3230
    if (machine->no_parallel) {
3231
        default_parallel = 0;
3232
    }
3233
    if (!machine->use_virtcon) {
3234
        default_virtcon = 0;
3235
    }
3236
    if (machine->no_vga) {
3237
        default_vga = 0;
3238
    }
3239
    if (machine->no_floppy) {
3240
        default_floppy = 0;
3241
    }
3242
    if (machine->no_cdrom) {
3243
        default_cdrom = 0;
3244
    }
3245
    if (machine->no_sdcard) {
3246
        default_sdcard = 0;
3247
    }
3248

    
3249
    if (display_type == DT_NOGRAPHIC) {
3250
        if (default_parallel)
3251
            add_device_config(DEV_PARALLEL, "null");
3252
        if (default_serial && default_monitor) {
3253
            add_device_config(DEV_SERIAL, "mon:stdio");
3254
        } else if (default_virtcon && default_monitor) {
3255
            add_device_config(DEV_VIRTCON, "mon:stdio");
3256
        } else {
3257
            if (default_serial)
3258
                add_device_config(DEV_SERIAL, "stdio");
3259
            if (default_virtcon)
3260
                add_device_config(DEV_VIRTCON, "stdio");
3261
            if (default_monitor)
3262
                monitor_parse("stdio", "readline");
3263
        }
3264
    } else {
3265
        if (default_serial)
3266
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
3267
        if (default_parallel)
3268
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
3269
        if (default_monitor)
3270
            monitor_parse("vc:80Cx24C", "readline");
3271
        if (default_virtcon)
3272
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
3273
    }
3274
    if (default_vga)
3275
        vga_interface_type = VGA_CIRRUS;
3276

    
3277
    socket_init();
3278

    
3279
    if (qemu_opts_foreach(qemu_find_opts("chardev"), chardev_init_func, NULL, 1) != 0)
3280
        exit(1);
3281
#ifdef CONFIG_VIRTFS
3282
    if (qemu_opts_foreach(qemu_find_opts("fsdev"), fsdev_init_func, NULL, 1) != 0) {
3283
        exit(1);
3284
    }
3285
#endif
3286

    
3287
    os_daemonize();
3288

    
3289
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
3290
        os_pidfile_error();
3291
        exit(1);
3292
    }
3293

    
3294
    /* init the memory */
3295
    if (ram_size == 0) {
3296
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
3297
    }
3298

    
3299
    configure_accelerator();
3300

    
3301
    if (qemu_init_main_loop()) {
3302
        fprintf(stderr, "qemu_init_main_loop failed\n");
3303
        exit(1);
3304
    }
3305
    linux_boot = (kernel_filename != NULL);
3306

    
3307
    if (!linux_boot && *kernel_cmdline != '\0') {
3308
        fprintf(stderr, "-append only allowed with -kernel option\n");
3309
        exit(1);
3310
    }
3311

    
3312
    if (!linux_boot && initrd_filename != NULL) {
3313
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
3314
        exit(1);
3315
    }
3316

    
3317
    os_set_line_buffering();
3318

    
3319
    if (init_timer_alarm() < 0) {
3320
        fprintf(stderr, "could not initialize alarm timer\n");
3321
        exit(1);
3322
    }
3323
    configure_icount(icount_option);
3324

    
3325
    if (net_init_clients() < 0) {
3326
        exit(1);
3327
    }
3328

    
3329
    /* init the bluetooth world */
3330
    if (foreach_device_config(DEV_BT, bt_parse))
3331
        exit(1);
3332

    
3333
    if (!xen_enabled()) {
3334
        /* On 32-bit hosts, QEMU is limited by virtual address space */
3335
        if (ram_size > (2047 << 20) && HOST_LONG_BITS == 32) {
3336
            fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
3337
            exit(1);
3338
        }
3339
    }
3340

    
3341
    cpu_exec_init_all();
3342

    
3343
    bdrv_init_with_whitelist();
3344

    
3345
    blk_mig_init();
3346

    
3347
    /* open the virtual block devices */
3348
    if (snapshot)
3349
        qemu_opts_foreach(qemu_find_opts("drive"), drive_enable_snapshot, NULL, 0);
3350
    if (qemu_opts_foreach(qemu_find_opts("drive"), drive_init_func, &machine->use_scsi, 1) != 0)
3351
        exit(1);
3352

    
3353
    default_drive(default_cdrom, snapshot, machine->use_scsi,
3354
                  IF_DEFAULT, 2, CDROM_OPTS);
3355
    default_drive(default_floppy, snapshot, machine->use_scsi,
3356
                  IF_FLOPPY, 0, FD_OPTS);
3357
    default_drive(default_sdcard, snapshot, machine->use_scsi,
3358
                  IF_SD, 0, SD_OPTS);
3359

    
3360
    register_savevm_live(NULL, "ram", 0, 4, NULL, ram_save_live, NULL,
3361
                         ram_load, NULL);
3362

    
3363
    if (nb_numa_nodes > 0) {
3364
        int i;
3365

    
3366
        if (nb_numa_nodes > MAX_NODES) {
3367
            nb_numa_nodes = MAX_NODES;
3368
        }
3369

    
3370
        /* If no memory size if given for any node, assume the default case
3371
         * and distribute the available memory equally across all nodes
3372
         */
3373
        for (i = 0; i < nb_numa_nodes; i++) {
3374
            if (node_mem[i] != 0)
3375
                break;
3376
        }
3377
        if (i == nb_numa_nodes) {
3378
            uint64_t usedmem = 0;
3379

    
3380
            /* On Linux, the each node's border has to be 8MB aligned,
3381
             * the final node gets the rest.
3382
             */
3383
            for (i = 0; i < nb_numa_nodes - 1; i++) {
3384
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
3385
                usedmem += node_mem[i];
3386
            }
3387
            node_mem[i] = ram_size - usedmem;
3388
        }
3389

    
3390
        for (i = 0; i < nb_numa_nodes; i++) {
3391
            if (node_cpumask[i] != 0)
3392
                break;
3393
        }
3394
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
3395
         * must cope with this anyway, because there are BIOSes out there in
3396
         * real machines which also use this scheme.
3397
         */
3398
        if (i == nb_numa_nodes) {
3399
            for (i = 0; i < smp_cpus; i++) {
3400
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
3401
            }
3402
        }
3403
    }
3404

    
3405
    if (qemu_opts_foreach(qemu_find_opts("mon"), mon_init_func, NULL, 1) != 0) {
3406
        exit(1);
3407
    }
3408

    
3409
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
3410
        exit(1);
3411
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
3412
        exit(1);
3413
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
3414
        exit(1);
3415
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
3416
        exit(1);
3417

    
3418
    module_call_init(MODULE_INIT_DEVICE);
3419

    
3420
    if (qemu_opts_foreach(qemu_find_opts("device"), device_help_func, NULL, 0) != 0)
3421
        exit(0);
3422

    
3423
    if (watchdog) {
3424
        i = select_watchdog(watchdog);
3425
        if (i > 0)
3426
            exit (i == 1 ? 1 : 0);
3427
    }
3428

    
3429
    if (machine->compat_props) {
3430
        qdev_prop_register_global_list(machine->compat_props);
3431
    }
3432
    qemu_add_globals();
3433

    
3434
    machine->init(ram_size, boot_devices,
3435
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3436

    
3437
    cpu_synchronize_all_post_init();
3438

    
3439
    set_numa_modes();
3440

    
3441
    current_machine = machine;
3442

    
3443
    /* init USB devices */
3444
    if (usb_enabled) {
3445
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
3446
            exit(1);
3447
    }
3448

    
3449
    /* init generic devices */
3450
    if (qemu_opts_foreach(qemu_find_opts("device"), device_init_func, NULL, 1) != 0)
3451
        exit(1);
3452

    
3453
    net_check_clients();
3454

    
3455
    /* just use the first displaystate for the moment */
3456
    ds = get_displaystate();
3457

    
3458
    if (using_spice)
3459
        display_remote++;
3460
    if (display_type == DT_DEFAULT && !display_remote) {
3461
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
3462
        display_type = DT_SDL;
3463
#elif defined(CONFIG_VNC)
3464
        vnc_display = "localhost:0,to=99";
3465
        show_vnc_port = 1;
3466
#else
3467
        display_type = DT_NONE;
3468
#endif
3469
    }
3470

    
3471

    
3472
    /* init local displays */
3473
    switch (display_type) {
3474
    case DT_NOGRAPHIC:
3475
        break;
3476
#if defined(CONFIG_CURSES)
3477
    case DT_CURSES:
3478
        curses_display_init(ds, full_screen);
3479
        break;
3480
#endif
3481
#if defined(CONFIG_SDL)
3482
    case DT_SDL:
3483
        sdl_display_init(ds, full_screen, no_frame);
3484
        break;
3485
#elif defined(CONFIG_COCOA)
3486
    case DT_SDL:
3487
        cocoa_display_init(ds, full_screen);
3488
        break;
3489
#endif
3490
    default:
3491
        break;
3492
    }
3493

    
3494
    /* must be after terminal init, SDL library changes signal handlers */
3495
    os_setup_signal_handling();
3496

    
3497
#ifdef CONFIG_VNC
3498
    /* init remote displays */
3499
    if (vnc_display) {
3500
        vnc_display_init(ds);
3501
        if (vnc_display_open(ds, vnc_display) < 0)
3502
            exit(1);
3503

    
3504
        if (show_vnc_port) {
3505
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
3506
        }
3507
    }
3508
#endif
3509
#ifdef CONFIG_SPICE
3510
    if (using_spice && !qxl_enabled) {
3511
        qemu_spice_display_init(ds);
3512
    }
3513
#endif
3514

    
3515
    /* display setup */
3516
    dpy_resize(ds);
3517
    dcl = ds->listeners;
3518
    while (dcl != NULL) {
3519
        if (dcl->dpy_refresh != NULL) {
3520
            ds->gui_timer = qemu_new_timer_ms(rt_clock, gui_update, ds);
3521
            qemu_mod_timer(ds->gui_timer, qemu_get_clock_ms(rt_clock));
3522
            break;
3523
        }
3524
        dcl = dcl->next;
3525
    }
3526
    if (ds->gui_timer == NULL) {
3527
        nographic_timer = qemu_new_timer_ms(rt_clock, nographic_update, NULL);
3528
        qemu_mod_timer(nographic_timer, qemu_get_clock_ms(rt_clock));
3529
    }
3530
    text_consoles_set_display(ds);
3531

    
3532
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
3533
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
3534
                gdbstub_dev);
3535
        exit(1);
3536
    }
3537

    
3538
    qdev_machine_creation_done();
3539

    
3540
    if (rom_load_all() != 0) {
3541
        fprintf(stderr, "rom loading failed\n");
3542
        exit(1);
3543
    }
3544

    
3545
    /* TODO: once all bus devices are qdevified, this should be done
3546
     * when bus is created by qdev.c */
3547
    qemu_register_reset(qbus_reset_all_fn, sysbus_get_default());
3548
    qemu_run_machine_init_done_notifiers();
3549

    
3550
    qemu_system_reset(VMRESET_SILENT);
3551
    if (loadvm) {
3552
        if (load_vmstate(loadvm) < 0) {
3553
            autostart = 0;
3554
        }
3555
    }
3556

    
3557
    if (incoming) {
3558
        runstate_set(RSTATE_IN_MIGRATE);
3559
        int ret = qemu_start_incoming_migration(incoming);
3560
        if (ret < 0) {
3561
            fprintf(stderr, "Migration failed. Exit code %s(%d), exiting.\n",
3562
                    incoming, ret);
3563
            exit(ret);
3564
        }
3565
    } else if (autostart) {
3566
        vm_start();
3567
    } else {
3568
        runstate_set(RSTATE_PRE_LAUNCH);
3569
    }
3570

    
3571
    os_setup_post();
3572

    
3573
    main_loop();
3574
    quit_timers();
3575
    net_cleanup();
3576
    res_free();
3577

    
3578
    return 0;
3579
}