Statistics
| Branch: | Revision:

root / vl.c @ 44a9b356

History | View | Annotate | Download (99.9 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
#include "qmp-commands.h"
151
#include "main-loop.h"
152
#ifdef CONFIG_VIRTFS
153
#include "fsdev/qemu-fsdev.h"
154
#endif
155

    
156
#include "disas.h"
157

    
158
#include "qemu_socket.h"
159

    
160
#include "slirp/libslirp.h"
161

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

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

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

    
173
#define DEFAULT_RAM_SIZE 128
174

    
175
#define MAX_VIRTIO_CONSOLES 1
176

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

    
237
typedef struct FWBootEntry FWBootEntry;
238

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

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

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

    
252
uint8_t qemu_uuid[16];
253

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

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

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

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

    
270
static int default_serial = 1;
271
static int default_parallel = 1;
272
static int default_virtcon = 1;
273
static int default_monitor = 1;
274
static int default_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 = RUN_STATE_PRELAUNCH;
327

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

    
333
static const RunStateTransition runstate_transitions_def[] = {
334
    /*     from      ->     to      */
335
    { RUN_STATE_DEBUG, RUN_STATE_RUNNING },
336

    
337
    { RUN_STATE_INMIGRATE, RUN_STATE_RUNNING },
338
    { RUN_STATE_INMIGRATE, RUN_STATE_PRELAUNCH },
339

    
340
    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_PAUSED },
341
    { RUN_STATE_INTERNAL_ERROR, RUN_STATE_FINISH_MIGRATE },
342

    
343
    { RUN_STATE_IO_ERROR, RUN_STATE_RUNNING },
344
    { RUN_STATE_IO_ERROR, RUN_STATE_FINISH_MIGRATE },
345

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

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

    
352
    { RUN_STATE_PRELAUNCH, RUN_STATE_RUNNING },
353
    { RUN_STATE_PRELAUNCH, RUN_STATE_FINISH_MIGRATE },
354
    { RUN_STATE_PRELAUNCH, RUN_STATE_INMIGRATE },
355

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

    
359
    { RUN_STATE_RESTORE_VM, RUN_STATE_RUNNING },
360

    
361
    { RUN_STATE_RUNNING, RUN_STATE_DEBUG },
362
    { RUN_STATE_RUNNING, RUN_STATE_INTERNAL_ERROR },
363
    { RUN_STATE_RUNNING, RUN_STATE_IO_ERROR },
364
    { RUN_STATE_RUNNING, RUN_STATE_PAUSED },
365
    { RUN_STATE_RUNNING, RUN_STATE_FINISH_MIGRATE },
366
    { RUN_STATE_RUNNING, RUN_STATE_RESTORE_VM },
367
    { RUN_STATE_RUNNING, RUN_STATE_SAVE_VM },
368
    { RUN_STATE_RUNNING, RUN_STATE_SHUTDOWN },
369
    { RUN_STATE_RUNNING, RUN_STATE_WATCHDOG },
370

    
371
    { RUN_STATE_SAVE_VM, RUN_STATE_RUNNING },
372

    
373
    { RUN_STATE_SHUTDOWN, RUN_STATE_PAUSED },
374
    { RUN_STATE_SHUTDOWN, RUN_STATE_FINISH_MIGRATE },
375

    
376
    { RUN_STATE_WATCHDOG, RUN_STATE_RUNNING },
377
    { RUN_STATE_WATCHDOG, RUN_STATE_FINISH_MIGRATE },
378

    
379
    { RUN_STATE_MAX, RUN_STATE_MAX },
380
};
381

    
382
static bool runstate_valid_transitions[RUN_STATE_MAX][RUN_STATE_MAX];
383

    
384
bool runstate_check(RunState state)
385
{
386
    return current_run_state == state;
387
}
388

    
389
void runstate_init(void)
390
{
391
    const RunStateTransition *p;
392

    
393
    memset(&runstate_valid_transitions, 0, sizeof(runstate_valid_transitions));
394

    
395
    for (p = &runstate_transitions_def[0]; p->from != RUN_STATE_MAX; p++) {
396
        runstate_valid_transitions[p->from][p->to] = true;
397
    }
398
}
399

    
400
/* This function will abort() on invalid state transitions */
401
void runstate_set(RunState new_state)
402
{
403
    assert(new_state < RUN_STATE_MAX);
404

    
405
    if (!runstate_valid_transitions[current_run_state][new_state]) {
406
        fprintf(stderr, "ERROR: invalid runstate transition: '%s' -> '%s'\n",
407
                RunState_lookup[current_run_state],
408
                RunState_lookup[new_state]);
409
        abort();
410
    }
411

    
412
    current_run_state = new_state;
413
}
414

    
415
int runstate_is_running(void)
416
{
417
    return runstate_check(RUN_STATE_RUNNING);
418
}
419

    
420
StatusInfo *qmp_query_status(Error **errp)
421
{
422
    StatusInfo *info = g_malloc0(sizeof(*info));
423

    
424
    info->running = runstate_is_running();
425
    info->singlestep = singlestep;
426
    info->status = current_run_state;
427

    
428
    return info;
429
}
430

    
431
/***********************************************************/
432
/* real time host monotonic timer */
433

    
434
/***********************************************************/
435
/* host time/date access */
436
void qemu_get_timedate(struct tm *tm, int offset)
437
{
438
    time_t ti;
439
    struct tm *ret;
440

    
441
    time(&ti);
442
    ti += offset;
443
    if (rtc_date_offset == -1) {
444
        if (rtc_utc)
445
            ret = gmtime(&ti);
446
        else
447
            ret = localtime(&ti);
448
    } else {
449
        ti -= rtc_date_offset;
450
        ret = gmtime(&ti);
451
    }
452

    
453
    memcpy(tm, ret, sizeof(struct tm));
454
}
455

    
456
int qemu_timedate_diff(struct tm *tm)
457
{
458
    time_t seconds;
459

    
460
    if (rtc_date_offset == -1)
461
        if (rtc_utc)
462
            seconds = mktimegm(tm);
463
        else
464
            seconds = mktime(tm);
465
    else
466
        seconds = mktimegm(tm) + rtc_date_offset;
467

    
468
    return seconds - time(NULL);
469
}
470

    
471
void rtc_change_mon_event(struct tm *tm)
472
{
473
    QObject *data;
474

    
475
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
476
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
477
    qobject_decref(data);
478
}
479

    
480
static void configure_rtc_date_offset(const char *startdate, int legacy)
481
{
482
    time_t rtc_start_date;
483
    struct tm tm;
484

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

    
519
static void configure_rtc(QemuOpts *opts)
520
{
521
    const char *value;
522

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

    
557
/***********************************************************/
558
/* Bluetooth support */
559
static int nb_hcis;
560
static int cur_hci;
561
static struct HCIInfo *hci_table[MAX_NICS];
562

    
563
static struct bt_vlan_s {
564
    struct bt_scatternet_s net;
565
    int id;
566
    struct bt_vlan_s *next;
567
} *first_bt_vlan;
568

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

    
586
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
587
{
588
}
589

    
590
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
591
{
592
    return -ENOTSUP;
593
}
594

    
595
static struct HCIInfo null_hci = {
596
    .cmd_send = null_hci_send,
597
    .sco_send = null_hci_send,
598
    .acl_send = null_hci_send,
599
    .bdaddr_set = null_hci_addr_set,
600
};
601

    
602
struct HCIInfo *qemu_next_hci(void)
603
{
604
    if (cur_hci == nb_hcis)
605
        return &null_hci;
606

    
607
    return hci_table[cur_hci++];
608
}
609

    
610
static struct HCIInfo *hci_init(const char *str)
611
{
612
    char *endp;
613
    struct bt_scatternet_s *vlan = 0;
614

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

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

    
637
    return 0;
638
}
639

    
640
static int bt_hci_parse(const char *str)
641
{
642
    struct HCIInfo *hci;
643
    bdaddr_t bdaddr;
644

    
645
    if (nb_hcis >= MAX_NICS) {
646
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
647
        return -1;
648
    }
649

    
650
    hci = hci_init(str);
651
    if (!hci)
652
        return -1;
653

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

    
662
    hci_table[nb_hcis++] = hci;
663

    
664
    return 0;
665
}
666

    
667
static void bt_vhci_add(int vlan_id)
668
{
669
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
670

    
671
    if (!vlan->slave)
672
        fprintf(stderr, "qemu: warning: adding a VHCI to "
673
                        "an empty scatternet %i\n", vlan_id);
674

    
675
    bt_vhci_init(bt_new_hci(vlan));
676
}
677

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

    
686
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
687

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

    
696
    vlan = qemu_find_bt_vlan(vlan_id);
697

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

    
702
    if (!strcmp(devname, "keyboard"))
703
        return bt_keyboard_init(vlan);
704

    
705
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
706
    return 0;
707
}
708

    
709
static int bt_parse(const char *opt)
710
{
711
    const char *endp, *p;
712
    int vlan;
713

    
714
    if (strstart(opt, "hci", &endp)) {
715
        if (!*endp || *endp == ',') {
716
            if (*endp)
717
                if (!strstart(endp, ",vlan=", 0))
718
                    opt = endp + 1;
719

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

    
738
            bt_vhci_add(vlan);
739
            return 0;
740
        }
741
    } else if (strstart(opt, "device:", &endp))
742
        return !bt_device_add(endp);
743

    
744
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
745
    return 1;
746
}
747

    
748
/***********************************************************/
749
/* QEMU Block devices */
750

    
751
#define HD_OPTS "media=disk"
752
#define CDROM_OPTS "media=cdrom"
753
#define FD_OPTS ""
754
#define PFLASH_OPTS ""
755
#define MTD_OPTS ""
756
#define SD_OPTS ""
757

    
758
static int drive_init_func(QemuOpts *opts, void *opaque)
759
{
760
    int *use_scsi = opaque;
761

    
762
    return drive_init(opts, *use_scsi) == NULL;
763
}
764

    
765
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
766
{
767
    if (NULL == qemu_opt_get(opts, "snapshot")) {
768
        qemu_opt_set(opts, "snapshot", "on");
769
    }
770
    return 0;
771
}
772

    
773
static void default_drive(int enable, int snapshot, int use_scsi,
774
                          BlockInterfaceType type, int index,
775
                          const char *optstr)
776
{
777
    QemuOpts *opts;
778

    
779
    if (type == IF_DEFAULT) {
780
        type = use_scsi ? IF_SCSI : IF_IDE;
781
    }
782

    
783
    if (!enable || drive_get_by_index(type, index)) {
784
        return;
785
    }
786

    
787
    opts = drive_add(type, index, NULL, optstr);
788
    if (snapshot) {
789
        drive_enable_snapshot(opts, NULL);
790
    }
791
    if (!drive_init(opts, use_scsi)) {
792
        exit(1);
793
    }
794
}
795

    
796
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
797
{
798
    boot_set_handler = func;
799
    boot_set_opaque = opaque;
800
}
801

    
802
int qemu_boot_set(const char *boot_devices)
803
{
804
    if (!boot_set_handler) {
805
        return -EINVAL;
806
    }
807
    return boot_set_handler(boot_set_opaque, boot_devices);
808
}
809

    
810
static void validate_bootdevices(char *devices)
811
{
812
    /* We just do some generic consistency checks */
813
    const char *p;
814
    int bitmap = 0;
815

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

    
838
static void restore_boot_devices(void *opaque)
839
{
840
    char *standard_boot_devices = opaque;
841
    static int first = 1;
842

    
843
    /* Restore boot order and remove ourselves after the first boot */
844
    if (first) {
845
        first = 0;
846
        return;
847
    }
848

    
849
    qemu_boot_set(standard_boot_devices);
850

    
851
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
852
    g_free(standard_boot_devices);
853
}
854

    
855
void add_boot_device_path(int32_t bootindex, DeviceState *dev,
856
                          const char *suffix)
857
{
858
    FWBootEntry *node, *i;
859

    
860
    if (bootindex < 0) {
861
        return;
862
    }
863

    
864
    assert(dev != NULL || suffix != NULL);
865

    
866
    node = g_malloc0(sizeof(FWBootEntry));
867
    node->bootindex = bootindex;
868
    node->suffix = suffix ? g_strdup(suffix) : NULL;
869
    node->dev = dev;
870

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

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

    
897
    QTAILQ_FOREACH(i, &fw_boot_order, link) {
898
        char *devpath = NULL, *bootpath;
899
        int len;
900

    
901
        if (i->dev) {
902
            devpath = qdev_get_fw_dev_path(i->dev);
903
            assert(devpath);
904
        }
905

    
906
        if (i->suffix && devpath) {
907
            size_t bootpathlen = strlen(devpath) + strlen(i->suffix) + 1;
908

    
909
            bootpath = g_malloc(bootpathlen);
910
            snprintf(bootpath, bootpathlen, "%s%s", devpath, i->suffix);
911
            g_free(devpath);
912
        } else if (devpath) {
913
            bootpath = devpath;
914
        } else {
915
            bootpath = g_strdup(i->suffix);
916
            assert(bootpath);
917
        }
918

    
919
        if (total) {
920
            list[total-1] = '\n';
921
        }
922
        len = strlen(bootpath) + 1;
923
        list = g_realloc(list, total + len);
924
        memcpy(&list[total], bootpath, len);
925
        total += len;
926
        g_free(bootpath);
927
    }
928

    
929
    *size = total;
930

    
931
    return list;
932
}
933

    
934
static void numa_add(const char *optarg)
935
{
936
    char option[128];
937
    char *endptr;
938
    unsigned long long value, endvalue;
939
    int nodenr;
940

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

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

    
987
static void smp_parse(const char *optarg)
988
{
989
    int smp, sockets = 0, threads = 0, cores = 0;
990
    char *endptr;
991
    char option[128];
992

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

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

    
1031
/***********************************************************/
1032
/* USB devices */
1033

    
1034
static int usb_device_add(const char *devname)
1035
{
1036
    const char *p;
1037
    USBDevice *dev = NULL;
1038

    
1039
    if (!usb_enabled)
1040
        return -1;
1041

    
1042
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
1043
    dev = usbdevice_create(devname);
1044
    if (dev)
1045
        goto done;
1046

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

    
1063
done:
1064
    return 0;
1065
}
1066

    
1067
static int usb_device_del(const char *devname)
1068
{
1069
    int bus_num, addr;
1070
    const char *p;
1071

    
1072
    if (strstart(devname, "host:", &p))
1073
        return usb_host_device_close(p);
1074

    
1075
    if (!usb_enabled)
1076
        return -1;
1077

    
1078
    p = strchr(devname, '.');
1079
    if (!p)
1080
        return -1;
1081
    bus_num = strtoul(devname, NULL, 0);
1082
    addr = strtoul(p + 1, NULL, 0);
1083

    
1084
    return usb_device_delete_addr(bus_num, addr);
1085
}
1086

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

    
1097
void do_usb_add(Monitor *mon, const QDict *qdict)
1098
{
1099
    const char *devname = qdict_get_str(qdict, "devname");
1100
    if (usb_device_add(devname) < 0) {
1101
        error_report("could not add USB device '%s'", devname);
1102
    }
1103
}
1104

    
1105
void do_usb_del(Monitor *mon, const QDict *qdict)
1106
{
1107
    const char *devname = qdict_get_str(qdict, "devname");
1108
    if (usb_device_del(devname) < 0) {
1109
        error_report("could not delete USB device '%s'", devname);
1110
    }
1111
}
1112

    
1113
/***********************************************************/
1114
/* PCMCIA/Cardbus */
1115

    
1116
static struct pcmcia_socket_entry_s {
1117
    PCMCIASocket *socket;
1118
    struct pcmcia_socket_entry_s *next;
1119
} *pcmcia_sockets = 0;
1120

    
1121
void pcmcia_socket_register(PCMCIASocket *socket)
1122
{
1123
    struct pcmcia_socket_entry_s *entry;
1124

    
1125
    entry = g_malloc(sizeof(struct pcmcia_socket_entry_s));
1126
    entry->socket = socket;
1127
    entry->next = pcmcia_sockets;
1128
    pcmcia_sockets = entry;
1129
}
1130

    
1131
void pcmcia_socket_unregister(PCMCIASocket *socket)
1132
{
1133
    struct pcmcia_socket_entry_s *entry, **ptr;
1134

    
1135
    ptr = &pcmcia_sockets;
1136
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1137
        if (entry->socket == socket) {
1138
            *ptr = entry->next;
1139
            g_free(entry);
1140
        }
1141
}
1142

    
1143
void pcmcia_info(Monitor *mon)
1144
{
1145
    struct pcmcia_socket_entry_s *iter;
1146

    
1147
    if (!pcmcia_sockets)
1148
        monitor_printf(mon, "No PCMCIA sockets\n");
1149

    
1150
    for (iter = pcmcia_sockets; iter; iter = iter->next)
1151
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1152
                       iter->socket->attached ? iter->socket->card_string :
1153
                       "Empty");
1154
}
1155

    
1156
/***********************************************************/
1157
/* machine registration */
1158

    
1159
static QEMUMachine *first_machine = NULL;
1160
QEMUMachine *current_machine = NULL;
1161

    
1162
int qemu_register_machine(QEMUMachine *m)
1163
{
1164
    QEMUMachine **pm;
1165
    pm = &first_machine;
1166
    while (*pm != NULL)
1167
        pm = &(*pm)->next;
1168
    m->next = NULL;
1169
    *pm = m;
1170
    return 0;
1171
}
1172

    
1173
static QEMUMachine *find_machine(const char *name)
1174
{
1175
    QEMUMachine *m;
1176

    
1177
    for(m = first_machine; m != NULL; m = m->next) {
1178
        if (!strcmp(m->name, name))
1179
            return m;
1180
        if (m->alias && !strcmp(m->alias, name))
1181
            return m;
1182
    }
1183
    return NULL;
1184
}
1185

    
1186
static QEMUMachine *find_default_machine(void)
1187
{
1188
    QEMUMachine *m;
1189

    
1190
    for(m = first_machine; m != NULL; m = m->next) {
1191
        if (m->is_default) {
1192
            return m;
1193
        }
1194
    }
1195
    return NULL;
1196
}
1197

    
1198
/***********************************************************/
1199
/* main execution loop */
1200

    
1201
static void gui_update(void *opaque)
1202
{
1203
    uint64_t interval = GUI_REFRESH_INTERVAL;
1204
    DisplayState *ds = opaque;
1205
    DisplayChangeListener *dcl = ds->listeners;
1206

    
1207
    dpy_refresh(ds);
1208

    
1209
    while (dcl != NULL) {
1210
        if (dcl->gui_timer_interval &&
1211
            dcl->gui_timer_interval < interval)
1212
            interval = dcl->gui_timer_interval;
1213
        dcl = dcl->next;
1214
    }
1215
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock_ms(rt_clock));
1216
}
1217

    
1218
struct vm_change_state_entry {
1219
    VMChangeStateHandler *cb;
1220
    void *opaque;
1221
    QLIST_ENTRY (vm_change_state_entry) entries;
1222
};
1223

    
1224
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1225

    
1226
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
1227
                                                     void *opaque)
1228
{
1229
    VMChangeStateEntry *e;
1230

    
1231
    e = g_malloc0(sizeof (*e));
1232

    
1233
    e->cb = cb;
1234
    e->opaque = opaque;
1235
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
1236
    return e;
1237
}
1238

    
1239
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
1240
{
1241
    QLIST_REMOVE (e, entries);
1242
    g_free (e);
1243
}
1244

    
1245
void vm_state_notify(int running, RunState state)
1246
{
1247
    VMChangeStateEntry *e;
1248

    
1249
    trace_vm_state_notify(running, state);
1250

    
1251
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
1252
        e->cb(e->opaque, running, state);
1253
    }
1254
}
1255

    
1256
void vm_start(void)
1257
{
1258
    if (!runstate_is_running()) {
1259
        cpu_enable_ticks();
1260
        runstate_set(RUN_STATE_RUNNING);
1261
        vm_state_notify(1, RUN_STATE_RUNNING);
1262
        resume_all_vcpus();
1263
        monitor_protocol_event(QEVENT_RESUME, NULL);
1264
    }
1265
}
1266

    
1267
/* reset/shutdown handler */
1268

    
1269
typedef struct QEMUResetEntry {
1270
    QTAILQ_ENTRY(QEMUResetEntry) entry;
1271
    QEMUResetHandler *func;
1272
    void *opaque;
1273
} QEMUResetEntry;
1274

    
1275
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
1276
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
1277
static int reset_requested;
1278
static int shutdown_requested, shutdown_signal = -1;
1279
static pid_t shutdown_pid;
1280
static int powerdown_requested;
1281
static int debug_requested;
1282
static RunState vmstop_requested = RUN_STATE_MAX;
1283

    
1284
int qemu_shutdown_requested_get(void)
1285
{
1286
    return shutdown_requested;
1287
}
1288

    
1289
int qemu_reset_requested_get(void)
1290
{
1291
    return reset_requested;
1292
}
1293

    
1294
int qemu_shutdown_requested(void)
1295
{
1296
    int r = shutdown_requested;
1297
    shutdown_requested = 0;
1298
    return r;
1299
}
1300

    
1301
void qemu_kill_report(void)
1302
{
1303
    if (shutdown_signal != -1) {
1304
        fprintf(stderr, "qemu: terminating on signal %d", shutdown_signal);
1305
        if (shutdown_pid == 0) {
1306
            /* This happens for eg ^C at the terminal, so it's worth
1307
             * avoiding printing an odd message in that case.
1308
             */
1309
            fputc('\n', stderr);
1310
        } else {
1311
            fprintf(stderr, " from pid " FMT_pid "\n", shutdown_pid);
1312
        }
1313
        shutdown_signal = -1;
1314
    }
1315
}
1316

    
1317
int qemu_reset_requested(void)
1318
{
1319
    int r = reset_requested;
1320
    reset_requested = 0;
1321
    return r;
1322
}
1323

    
1324
int qemu_powerdown_requested(void)
1325
{
1326
    int r = powerdown_requested;
1327
    powerdown_requested = 0;
1328
    return r;
1329
}
1330

    
1331
static int qemu_debug_requested(void)
1332
{
1333
    int r = debug_requested;
1334
    debug_requested = 0;
1335
    return r;
1336
}
1337

    
1338
/* We use RUN_STATE_MAX but any invalid value will do */
1339
static bool qemu_vmstop_requested(RunState *r)
1340
{
1341
    if (vmstop_requested < RUN_STATE_MAX) {
1342
        *r = vmstop_requested;
1343
        vmstop_requested = RUN_STATE_MAX;
1344
        return true;
1345
    }
1346

    
1347
    return false;
1348
}
1349

    
1350
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
1351
{
1352
    QEMUResetEntry *re = g_malloc0(sizeof(QEMUResetEntry));
1353

    
1354
    re->func = func;
1355
    re->opaque = opaque;
1356
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
1357
}
1358

    
1359
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
1360
{
1361
    QEMUResetEntry *re;
1362

    
1363
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
1364
        if (re->func == func && re->opaque == opaque) {
1365
            QTAILQ_REMOVE(&reset_handlers, re, entry);
1366
            g_free(re);
1367
            return;
1368
        }
1369
    }
1370
}
1371

    
1372
void qemu_system_reset(bool report)
1373
{
1374
    QEMUResetEntry *re, *nre;
1375

    
1376
    /* reset all devices */
1377
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
1378
        re->func(re->opaque);
1379
    }
1380
    if (report) {
1381
        monitor_protocol_event(QEVENT_RESET, NULL);
1382
    }
1383
    cpu_synchronize_all_post_reset();
1384
}
1385

    
1386
void qemu_system_reset_request(void)
1387
{
1388
    if (no_reboot) {
1389
        shutdown_requested = 1;
1390
    } else {
1391
        reset_requested = 1;
1392
    }
1393
    cpu_stop_current();
1394
    qemu_notify_event();
1395
}
1396

    
1397
void qemu_system_killed(int signal, pid_t pid)
1398
{
1399
    shutdown_signal = signal;
1400
    shutdown_pid = pid;
1401
    no_shutdown = 0;
1402
    qemu_system_shutdown_request();
1403
}
1404

    
1405
void qemu_system_shutdown_request(void)
1406
{
1407
    shutdown_requested = 1;
1408
    qemu_notify_event();
1409
}
1410

    
1411
void qemu_system_powerdown_request(void)
1412
{
1413
    powerdown_requested = 1;
1414
    qemu_notify_event();
1415
}
1416

    
1417
void qemu_system_debug_request(void)
1418
{
1419
    debug_requested = 1;
1420
    qemu_notify_event();
1421
}
1422

    
1423
void qemu_system_vmstop_request(RunState state)
1424
{
1425
    vmstop_requested = state;
1426
    qemu_notify_event();
1427
}
1428

    
1429
static GPollFD poll_fds[1024 * 2]; /* this is probably overkill */
1430
static int n_poll_fds;
1431
static int max_priority;
1432

    
1433
static void glib_select_fill(int *max_fd, fd_set *rfds, fd_set *wfds,
1434
                             fd_set *xfds, struct timeval *tv)
1435
{
1436
    GMainContext *context = g_main_context_default();
1437
    int i;
1438
    int timeout = 0, cur_timeout;
1439

    
1440
    g_main_context_prepare(context, &max_priority);
1441

    
1442
    n_poll_fds = g_main_context_query(context, max_priority, &timeout,
1443
                                      poll_fds, ARRAY_SIZE(poll_fds));
1444
    g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));
1445

    
1446
    for (i = 0; i < n_poll_fds; i++) {
1447
        GPollFD *p = &poll_fds[i];
1448

    
1449
        if ((p->events & G_IO_IN)) {
1450
            FD_SET(p->fd, rfds);
1451
            *max_fd = MAX(*max_fd, p->fd);
1452
        }
1453
        if ((p->events & G_IO_OUT)) {
1454
            FD_SET(p->fd, wfds);
1455
            *max_fd = MAX(*max_fd, p->fd);
1456
        }
1457
        if ((p->events & G_IO_ERR)) {
1458
            FD_SET(p->fd, xfds);
1459
            *max_fd = MAX(*max_fd, p->fd);
1460
        }
1461
    }
1462

    
1463
    cur_timeout = (tv->tv_sec * 1000) + ((tv->tv_usec + 500) / 1000);
1464
    if (timeout >= 0 && timeout < cur_timeout) {
1465
        tv->tv_sec = timeout / 1000;
1466
        tv->tv_usec = (timeout % 1000) * 1000;
1467
    }
1468
}
1469

    
1470
static void glib_select_poll(fd_set *rfds, fd_set *wfds, fd_set *xfds,
1471
                             bool err)
1472
{
1473
    GMainContext *context = g_main_context_default();
1474

    
1475
    if (!err) {
1476
        int i;
1477

    
1478
        for (i = 0; i < n_poll_fds; i++) {
1479
            GPollFD *p = &poll_fds[i];
1480

    
1481
            if ((p->events & G_IO_IN) && FD_ISSET(p->fd, rfds)) {
1482
                p->revents |= G_IO_IN;
1483
            }
1484
            if ((p->events & G_IO_OUT) && FD_ISSET(p->fd, wfds)) {
1485
                p->revents |= G_IO_OUT;
1486
            }
1487
            if ((p->events & G_IO_ERR) && FD_ISSET(p->fd, xfds)) {
1488
                p->revents |= G_IO_ERR;
1489
            }
1490
        }
1491
    }
1492

    
1493
    if (g_main_context_check(context, max_priority, poll_fds, n_poll_fds)) {
1494
        g_main_context_dispatch(context);
1495
    }
1496
}
1497

    
1498
int main_loop_wait(int nonblocking)
1499
{
1500
    fd_set rfds, wfds, xfds;
1501
    int ret, nfds;
1502
    struct timeval tv;
1503
    int timeout;
1504

    
1505
    if (nonblocking)
1506
        timeout = 0;
1507
    else {
1508
        timeout = qemu_calculate_timeout();
1509
        qemu_bh_update_timeout(&timeout);
1510
    }
1511

    
1512
    os_host_main_loop_wait(&timeout);
1513

    
1514
    tv.tv_sec = timeout / 1000;
1515
    tv.tv_usec = (timeout % 1000) * 1000;
1516

    
1517
    /* poll any events */
1518
    /* XXX: separate device handlers from system ones */
1519
    nfds = -1;
1520
    FD_ZERO(&rfds);
1521
    FD_ZERO(&wfds);
1522
    FD_ZERO(&xfds);
1523

    
1524
    qemu_iohandler_fill(&nfds, &rfds, &wfds, &xfds);
1525
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1526
    glib_select_fill(&nfds, &rfds, &wfds, &xfds, &tv);
1527

    
1528
    if (timeout > 0) {
1529
        qemu_mutex_unlock_iothread();
1530
    }
1531

    
1532
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1533

    
1534
    if (timeout > 0) {
1535
        qemu_mutex_lock_iothread();
1536
    }
1537

    
1538
    qemu_iohandler_poll(&rfds, &wfds, &xfds, ret);
1539
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1540
    glib_select_poll(&rfds, &wfds, &xfds, (ret < 0));
1541

    
1542
    qemu_run_all_timers();
1543

    
1544
    /* Check bottom-halves last in case any of the earlier events triggered
1545
       them.  */
1546
    qemu_bh_poll();
1547

    
1548
    return ret;
1549
}
1550

    
1551
qemu_irq qemu_system_powerdown;
1552

    
1553
static void main_loop(void)
1554
{
1555
    bool nonblocking;
1556
    int last_io __attribute__ ((unused)) = 0;
1557
#ifdef CONFIG_PROFILER
1558
    int64_t ti;
1559
#endif
1560
    RunState r;
1561

    
1562
    qemu_main_loop_start();
1563

    
1564
    for (;;) {
1565
        nonblocking = !kvm_enabled() && last_io > 0;
1566
#ifdef CONFIG_PROFILER
1567
        ti = profile_getclock();
1568
#endif
1569
        last_io = main_loop_wait(nonblocking);
1570
#ifdef CONFIG_PROFILER
1571
        dev_time += profile_getclock() - ti;
1572
#endif
1573

    
1574
        if (qemu_debug_requested()) {
1575
            vm_stop(RUN_STATE_DEBUG);
1576
        }
1577
        if (qemu_shutdown_requested()) {
1578
            qemu_kill_report();
1579
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
1580
            if (no_shutdown) {
1581
                vm_stop(RUN_STATE_SHUTDOWN);
1582
            } else
1583
                break;
1584
        }
1585
        if (qemu_reset_requested()) {
1586
            pause_all_vcpus();
1587
            cpu_synchronize_all_states();
1588
            qemu_system_reset(VMRESET_REPORT);
1589
            resume_all_vcpus();
1590
            if (runstate_check(RUN_STATE_INTERNAL_ERROR) ||
1591
                runstate_check(RUN_STATE_SHUTDOWN)) {
1592
                runstate_set(RUN_STATE_PAUSED);
1593
            }
1594
        }
1595
        if (qemu_powerdown_requested()) {
1596
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
1597
            qemu_irq_raise(qemu_system_powerdown);
1598
        }
1599
        if (qemu_vmstop_requested(&r)) {
1600
            vm_stop(r);
1601
        }
1602
    }
1603
    bdrv_close_all();
1604
    pause_all_vcpus();
1605
}
1606

    
1607
static void version(void)
1608
{
1609
    printf("QEMU emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
1610
}
1611

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

    
1640
#define HAS_ARG 0x0001
1641

    
1642
typedef struct QEMUOption {
1643
    const char *name;
1644
    int flags;
1645
    int index;
1646
    uint32_t arch_mask;
1647
} QEMUOption;
1648

    
1649
static const QEMUOption qemu_options[] = {
1650
    { "h", 0, QEMU_OPTION_h, QEMU_ARCH_ALL },
1651
#define DEF(option, opt_arg, opt_enum, opt_help, arch_mask)     \
1652
    { option, opt_arg, opt_enum, arch_mask },
1653
#define DEFHEADING(text)
1654
#include "qemu-options.def"
1655
#undef DEF
1656
#undef DEFHEADING
1657
#undef GEN_DOCS
1658
    { NULL },
1659
};
1660
static void select_vgahw (const char *p)
1661
{
1662
    const char *opts;
1663

    
1664
    default_vga = 0;
1665
    vga_interface_type = VGA_NONE;
1666
    if (strstart(p, "std", &opts)) {
1667
        vga_interface_type = VGA_STD;
1668
    } else if (strstart(p, "cirrus", &opts)) {
1669
        vga_interface_type = VGA_CIRRUS;
1670
    } else if (strstart(p, "vmware", &opts)) {
1671
        vga_interface_type = VGA_VMWARE;
1672
    } else if (strstart(p, "xenfb", &opts)) {
1673
        vga_interface_type = VGA_XENFB;
1674
    } else if (strstart(p, "qxl", &opts)) {
1675
        vga_interface_type = VGA_QXL;
1676
    } else if (!strstart(p, "none", &opts)) {
1677
    invalid_vga:
1678
        fprintf(stderr, "Unknown vga type: %s\n", p);
1679
        exit(1);
1680
    }
1681
    while (*opts) {
1682
        const char *nextopt;
1683

    
1684
        if (strstart(opts, ",retrace=", &nextopt)) {
1685
            opts = nextopt;
1686
            if (strstart(opts, "dumb", &nextopt))
1687
                vga_retrace_method = VGA_RETRACE_DUMB;
1688
            else if (strstart(opts, "precise", &nextopt))
1689
                vga_retrace_method = VGA_RETRACE_PRECISE;
1690
            else goto invalid_vga;
1691
        } else goto invalid_vga;
1692
        opts = nextopt;
1693
    }
1694
}
1695

    
1696
static DisplayType select_display(const char *p)
1697
{
1698
    const char *opts;
1699
    DisplayType display = DT_DEFAULT;
1700

    
1701
    if (strstart(p, "sdl", &opts)) {
1702
#ifdef CONFIG_SDL
1703
        display = DT_SDL;
1704
        while (*opts) {
1705
            const char *nextopt;
1706

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

    
1758
        if (*opts) {
1759
            const char *nextopt;
1760

    
1761
            if (strstart(opts, "=", &nextopt)) {
1762
                vnc_display = nextopt;
1763
            }
1764
        }
1765
        if (!vnc_display) {
1766
            fprintf(stderr, "VNC requires a display argument vnc=<display>\n");
1767
            exit(1);
1768
        }
1769
#else
1770
        fprintf(stderr, "VNC support is disabled\n");
1771
        exit(1);
1772
#endif
1773
    } else if (strstart(p, "curses", &opts)) {
1774
#ifdef CONFIG_CURSES
1775
        display = DT_CURSES;
1776
#else
1777
        fprintf(stderr, "Curses support is disabled\n");
1778
        exit(1);
1779
#endif
1780
    } else if (strstart(p, "none", &opts)) {
1781
        display = DT_NONE;
1782
    } else {
1783
        fprintf(stderr, "Unknown display type: %s\n", p);
1784
        exit(1);
1785
    }
1786

    
1787
    return display;
1788
}
1789

    
1790
static int balloon_parse(const char *arg)
1791
{
1792
    QemuOpts *opts;
1793

    
1794
    if (strcmp(arg, "none") == 0) {
1795
        return 0;
1796
    }
1797

    
1798
    if (!strncmp(arg, "virtio", 6)) {
1799
        if (arg[6] == ',') {
1800
            /* have params -> parse them */
1801
            opts = qemu_opts_parse(qemu_find_opts("device"), arg+7, 0);
1802
            if (!opts)
1803
                return  -1;
1804
        } else {
1805
            /* create empty opts */
1806
            opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
1807
        }
1808
        qemu_opt_set(opts, "driver", "virtio-balloon");
1809
        return 0;
1810
    }
1811

    
1812
    return -1;
1813
}
1814

    
1815
char *qemu_find_file(int type, const char *name)
1816
{
1817
    int len;
1818
    const char *subdir;
1819
    char *buf;
1820

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

    
1846
static int device_help_func(QemuOpts *opts, void *opaque)
1847
{
1848
    return qdev_device_help(opts);
1849
}
1850

    
1851
static int device_init_func(QemuOpts *opts, void *opaque)
1852
{
1853
    DeviceState *dev;
1854

    
1855
    dev = qdev_device_add(opts);
1856
    if (!dev)
1857
        return -1;
1858
    return 0;
1859
}
1860

    
1861
static int chardev_init_func(QemuOpts *opts, void *opaque)
1862
{
1863
    CharDriverState *chr;
1864

    
1865
    chr = qemu_chr_new_from_opts(opts, NULL);
1866
    if (!chr)
1867
        return -1;
1868
    return 0;
1869
}
1870

    
1871
#ifdef CONFIG_VIRTFS
1872
static int fsdev_init_func(QemuOpts *opts, void *opaque)
1873
{
1874
    int ret;
1875
    ret = qemu_fsdev_add(opts);
1876

    
1877
    return ret;
1878
}
1879
#endif
1880

    
1881
static int mon_init_func(QemuOpts *opts, void *opaque)
1882
{
1883
    CharDriverState *chr;
1884
    const char *chardev;
1885
    const char *mode;
1886
    int flags;
1887

    
1888
    mode = qemu_opt_get(opts, "mode");
1889
    if (mode == NULL) {
1890
        mode = "readline";
1891
    }
1892
    if (strcmp(mode, "readline") == 0) {
1893
        flags = MONITOR_USE_READLINE;
1894
    } else if (strcmp(mode, "control") == 0) {
1895
        flags = MONITOR_USE_CONTROL;
1896
    } else {
1897
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
1898
        exit(1);
1899
    }
1900

    
1901
    if (qemu_opt_get_bool(opts, "pretty", 0))
1902
        flags |= MONITOR_USE_PRETTY;
1903

    
1904
    if (qemu_opt_get_bool(opts, "default", 0))
1905
        flags |= MONITOR_IS_DEFAULT;
1906

    
1907
    chardev = qemu_opt_get(opts, "chardev");
1908
    chr = qemu_chr_find(chardev);
1909
    if (chr == NULL) {
1910
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
1911
        exit(1);
1912
    }
1913

    
1914
    monitor_init(chr, flags);
1915
    return 0;
1916
}
1917

    
1918
static void monitor_parse(const char *optarg, const char *mode)
1919
{
1920
    static int monitor_device_index = 0;
1921
    QemuOpts *opts;
1922
    const char *p;
1923
    char label[32];
1924
    int def = 0;
1925

    
1926
    if (strstart(optarg, "chardev:", &p)) {
1927
        snprintf(label, sizeof(label), "%s", p);
1928
    } else {
1929
        snprintf(label, sizeof(label), "compat_monitor%d",
1930
                 monitor_device_index);
1931
        if (monitor_device_index == 0) {
1932
            def = 1;
1933
        }
1934
        opts = qemu_chr_parse_compat(label, optarg);
1935
        if (!opts) {
1936
            fprintf(stderr, "parse error: %s\n", optarg);
1937
            exit(1);
1938
        }
1939
    }
1940

    
1941
    opts = qemu_opts_create(qemu_find_opts("mon"), label, 1);
1942
    if (!opts) {
1943
        fprintf(stderr, "duplicate chardev: %s\n", label);
1944
        exit(1);
1945
    }
1946
    qemu_opt_set(opts, "mode", mode);
1947
    qemu_opt_set(opts, "chardev", label);
1948
    if (def)
1949
        qemu_opt_set(opts, "default", "on");
1950
    monitor_device_index++;
1951
}
1952

    
1953
struct device_config {
1954
    enum {
1955
        DEV_USB,       /* -usbdevice     */
1956
        DEV_BT,        /* -bt            */
1957
        DEV_SERIAL,    /* -serial        */
1958
        DEV_PARALLEL,  /* -parallel      */
1959
        DEV_VIRTCON,   /* -virtioconsole */
1960
        DEV_DEBUGCON,  /* -debugcon */
1961
    } type;
1962
    const char *cmdline;
1963
    QTAILQ_ENTRY(device_config) next;
1964
};
1965
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
1966

    
1967
static void add_device_config(int type, const char *cmdline)
1968
{
1969
    struct device_config *conf;
1970

    
1971
    conf = g_malloc0(sizeof(*conf));
1972
    conf->type = type;
1973
    conf->cmdline = cmdline;
1974
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
1975
}
1976

    
1977
static int foreach_device_config(int type, int (*func)(const char *cmdline))
1978
{
1979
    struct device_config *conf;
1980
    int rc;
1981

    
1982
    QTAILQ_FOREACH(conf, &device_configs, next) {
1983
        if (conf->type != type)
1984
            continue;
1985
        rc = func(conf->cmdline);
1986
        if (0 != rc)
1987
            return rc;
1988
    }
1989
    return 0;
1990
}
1991

    
1992
static int serial_parse(const char *devname)
1993
{
1994
    static int index = 0;
1995
    char label[32];
1996

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

    
2014
static int parallel_parse(const char *devname)
2015
{
2016
    static int index = 0;
2017
    char label[32];
2018

    
2019
    if (strcmp(devname, "none") == 0)
2020
        return 0;
2021
    if (index == MAX_PARALLEL_PORTS) {
2022
        fprintf(stderr, "qemu: too many parallel ports\n");
2023
        exit(1);
2024
    }
2025
    snprintf(label, sizeof(label), "parallel%d", index);
2026
    parallel_hds[index] = qemu_chr_new(label, devname, NULL);
2027
    if (!parallel_hds[index]) {
2028
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
2029
                devname, strerror(errno));
2030
        return -1;
2031
    }
2032
    index++;
2033
    return 0;
2034
}
2035

    
2036
static int virtcon_parse(const char *devname)
2037
{
2038
    QemuOptsList *device = qemu_find_opts("device");
2039
    static int index = 0;
2040
    char label[32];
2041
    QemuOpts *bus_opts, *dev_opts;
2042

    
2043
    if (strcmp(devname, "none") == 0)
2044
        return 0;
2045
    if (index == MAX_VIRTIO_CONSOLES) {
2046
        fprintf(stderr, "qemu: too many virtio consoles\n");
2047
        exit(1);
2048
    }
2049

    
2050
    bus_opts = qemu_opts_create(device, NULL, 0);
2051
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
2052

    
2053
    dev_opts = qemu_opts_create(device, NULL, 0);
2054
    qemu_opt_set(dev_opts, "driver", "virtconsole");
2055

    
2056
    snprintf(label, sizeof(label), "virtcon%d", index);
2057
    virtcon_hds[index] = qemu_chr_new(label, devname, NULL);
2058
    if (!virtcon_hds[index]) {
2059
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
2060
                devname, strerror(errno));
2061
        return -1;
2062
    }
2063
    qemu_opt_set(dev_opts, "chardev", label);
2064

    
2065
    index++;
2066
    return 0;
2067
}
2068

    
2069
static int debugcon_parse(const char *devname)
2070
{   
2071
    QemuOpts *opts;
2072

    
2073
    if (!qemu_chr_new("debugcon", devname, NULL)) {
2074
        exit(1);
2075
    }
2076
    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1);
2077
    if (!opts) {
2078
        fprintf(stderr, "qemu: already have a debugcon device\n");
2079
        exit(1);
2080
    }
2081
    qemu_opt_set(opts, "driver", "isa-debugcon");
2082
    qemu_opt_set(opts, "chardev", "debugcon");
2083
    return 0;
2084
}
2085

    
2086
static QEMUMachine *machine_parse(const char *name)
2087
{
2088
    QEMUMachine *m, *machine = NULL;
2089

    
2090
    if (name) {
2091
        machine = find_machine(name);
2092
    }
2093
    if (machine) {
2094
        return machine;
2095
    }
2096
    printf("Supported machines are:\n");
2097
    for (m = first_machine; m != NULL; m = m->next) {
2098
        if (m->alias) {
2099
            printf("%-10s %s (alias of %s)\n", m->alias, m->desc, m->name);
2100
        }
2101
        printf("%-10s %s%s\n", m->name, m->desc,
2102
               m->is_default ? " (default)" : "");
2103
    }
2104
    exit(!name || *name != '?');
2105
}
2106

    
2107
static int tcg_init(void)
2108
{
2109
    tcg_exec_init(tcg_tb_size * 1024 * 1024);
2110
    return 0;
2111
}
2112

    
2113
static struct {
2114
    const char *opt_name;
2115
    const char *name;
2116
    int (*available)(void);
2117
    int (*init)(void);
2118
    int *allowed;
2119
} accel_list[] = {
2120
    { "tcg", "tcg", tcg_available, tcg_init, &tcg_allowed },
2121
    { "xen", "Xen", xen_available, xen_init, &xen_allowed },
2122
    { "kvm", "KVM", kvm_available, kvm_init, &kvm_allowed },
2123
};
2124

    
2125
static int configure_accelerator(void)
2126
{
2127
    const char *p = NULL;
2128
    char buf[10];
2129
    int i, ret;
2130
    bool accel_initalised = 0;
2131
    bool init_failed = 0;
2132

    
2133
    QemuOptsList *list = qemu_find_opts("machine");
2134
    if (!QTAILQ_EMPTY(&list->head)) {
2135
        p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");
2136
    }
2137

    
2138
    if (p == NULL) {
2139
        /* Use the default "accelerator", tcg */
2140
        p = "tcg";
2141
    }
2142

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

    
2174
    if (!accel_initalised) {
2175
        fprintf(stderr, "No accelerator found!\n");
2176
        exit(1);
2177
    }
2178

    
2179
    if (init_failed) {
2180
        fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);
2181
    }
2182

    
2183
    return !accel_initalised;
2184
}
2185

    
2186
void qemu_add_exit_notifier(Notifier *notify)
2187
{
2188
    notifier_list_add(&exit_notifiers, notify);
2189
}
2190

    
2191
void qemu_remove_exit_notifier(Notifier *notify)
2192
{
2193
    notifier_list_remove(&exit_notifiers, notify);
2194
}
2195

    
2196
static void qemu_run_exit_notifiers(void)
2197
{
2198
    notifier_list_notify(&exit_notifiers, NULL);
2199
}
2200

    
2201
void qemu_add_machine_init_done_notifier(Notifier *notify)
2202
{
2203
    notifier_list_add(&machine_init_done_notifiers, notify);
2204
}
2205

    
2206
static void qemu_run_machine_init_done_notifiers(void)
2207
{
2208
    notifier_list_notify(&machine_init_done_notifiers, NULL);
2209
}
2210

    
2211
static const QEMUOption *lookup_opt(int argc, char **argv,
2212
                                    const char **poptarg, int *poptind)
2213
{
2214
    const QEMUOption *popt;
2215
    int optind = *poptind;
2216
    char *r = argv[optind];
2217
    const char *optarg;
2218

    
2219
    loc_set_cmdline(argv, optind, 1);
2220
    optind++;
2221
    /* Treat --foo the same as -foo.  */
2222
    if (r[1] == '-')
2223
        r++;
2224
    popt = qemu_options;
2225
    for(;;) {
2226
        if (!popt->name) {
2227
            error_report("invalid option");
2228
            exit(1);
2229
        }
2230
        if (!strcmp(popt->name, r + 1))
2231
            break;
2232
        popt++;
2233
    }
2234
    if (popt->flags & HAS_ARG) {
2235
        if (optind >= argc) {
2236
            error_report("requires an argument");
2237
            exit(1);
2238
        }
2239
        optarg = argv[optind++];
2240
        loc_set_cmdline(argv, optind - 2, 2);
2241
    } else {
2242
        optarg = NULL;
2243
    }
2244

    
2245
    *poptarg = optarg;
2246
    *poptind = optind;
2247

    
2248
    return popt;
2249
}
2250

    
2251
static gpointer malloc_and_trace(gsize n_bytes)
2252
{
2253
    void *ptr = malloc(n_bytes);
2254
    trace_g_malloc(n_bytes, ptr);
2255
    return ptr;
2256
}
2257

    
2258
static gpointer realloc_and_trace(gpointer mem, gsize n_bytes)
2259
{
2260
    void *ptr = realloc(mem, n_bytes);
2261
    trace_g_realloc(mem, n_bytes, ptr);
2262
    return ptr;
2263
}
2264

    
2265
static void free_and_trace(gpointer mem)
2266
{
2267
    trace_g_free(mem);
2268
    free(mem);
2269
}
2270

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

    
2306
    atexit(qemu_run_exit_notifiers);
2307
    error_set_progname(argv[0]);
2308

    
2309
    g_mem_set_vtable(&mem_trace);
2310
    g_thread_init(NULL);
2311

    
2312
    runstate_init();
2313

    
2314
    init_clocks();
2315
    rtc_clock = host_clock;
2316

    
2317
    qemu_cache_utils_init(envp);
2318

    
2319
    QLIST_INIT (&vm_change_state_head);
2320
    os_setup_early_signal_handling();
2321

    
2322
    module_call_init(MODULE_INIT_MACHINE);
2323
    machine = find_default_machine();
2324
    cpu_model = NULL;
2325
    initrd_filename = NULL;
2326
    ram_size = 0;
2327
    snapshot = 0;
2328
    kernel_filename = NULL;
2329
    kernel_cmdline = "";
2330
    cyls = heads = secs = 0;
2331
    translation = BIOS_ATA_TRANSLATION_AUTO;
2332

    
2333
    for (i = 0; i < MAX_NODES; i++) {
2334
        node_mem[i] = 0;
2335
        node_cpumask[i] = 0;
2336
    }
2337

    
2338
    nb_numa_nodes = 0;
2339
    nb_nics = 0;
2340

    
2341
    autostart= 1;
2342

    
2343
    /* first pass of option parsing */
2344
    optind = 1;
2345
    while (optind < argc) {
2346
        if (argv[optind][0] != '-') {
2347
            /* disk image */
2348
            optind++;
2349
            continue;
2350
        } else {
2351
            const QEMUOption *popt;
2352

    
2353
            popt = lookup_opt(argc, argv, &optarg, &optind);
2354
            switch (popt->index) {
2355
            case QEMU_OPTION_nodefconfig:
2356
                defconfig=0;
2357
                break;
2358
            }
2359
        }
2360
    }
2361

    
2362
    if (defconfig) {
2363
        int ret;
2364

    
2365
        ret = qemu_read_config_file(CONFIG_QEMU_CONFDIR "/qemu.conf");
2366
        if (ret < 0 && ret != -ENOENT) {
2367
            exit(1);
2368
        }
2369

    
2370
        ret = qemu_read_config_file(arch_config_name);
2371
        if (ret < 0 && ret != -ENOENT) {
2372
            exit(1);
2373
        }
2374
    }
2375
    cpudef_init();
2376

    
2377
    /* second pass of option parsing */
2378
    optind = 1;
2379
    for(;;) {
2380
        if (optind >= argc)
2381
            break;
2382
        if (argv[optind][0] != '-') {
2383
            hda_opts = drive_add(IF_DEFAULT, 0, argv[optind++], HD_OPTS);
2384
        } else {
2385
            const QEMUOption *popt;
2386

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

    
2556
                    if (!strchr(optarg, '=')) {
2557
                        legacy = 1;
2558
                        pstrcpy(buf, sizeof(buf), optarg);
2559
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
2560
                        fprintf(stderr,
2561
                                "qemu: unknown boot parameter '%s' in '%s'\n",
2562
                                buf, optarg);
2563
                        exit(1);
2564
                    }
2565

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

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

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

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

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

    
2801
                if (qemu_opt_get(opts, "fsdriver") == NULL ||
2802
                        qemu_opt_get(opts, "mount_tag") == NULL ||
2803
                        qemu_opt_get(opts, "path") == NULL) {
2804
                    fprintf(stderr, "Usage: -virtfs fsdriver,path=/share_path/,"
2805
                            "[security_model={mapped|passthrough|none}],"
2806
                            "mount_tag=tag.\n");
2807
                    exit(1);
2808
                }
2809
                fsdev = qemu_opts_create(qemu_find_opts("fsdev"),
2810
                                         qemu_opt_get(opts, "mount_tag"), 1);
2811
                if (!fsdev) {
2812
                    fprintf(stderr, "duplicate fsdev id: %s\n",
2813
                            qemu_opt_get(opts, "mount_tag"));
2814
                    exit(1);
2815
                }
2816

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

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

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

    
3175
    if (!trace_backend_init(trace_events, trace_file)) {
3176
        exit(1);
3177
    }
3178

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

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

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

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

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

    
3226
    qemu_opts_foreach(qemu_find_opts("device"), default_driver_check, NULL, 0);
3227
    qemu_opts_foreach(qemu_find_opts("global"), default_driver_check, NULL, 0);
3228

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

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

    
3279
    socket_init();
3280

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

    
3289
    os_daemonize();
3290

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

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

    
3301
    configure_accelerator();
3302

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

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

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

    
3319
    os_set_line_buffering();
3320

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

    
3327
    if (net_init_clients() < 0) {
3328
        exit(1);
3329
    }
3330

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

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

    
3343
    cpu_exec_init_all();
3344

    
3345
    bdrv_init_with_whitelist();
3346

    
3347
    blk_mig_init();
3348

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

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

    
3362
    register_savevm_live(NULL, "ram", 0, 4, NULL, ram_save_live, NULL,
3363
                         ram_load, NULL);
3364

    
3365
    if (nb_numa_nodes > 0) {
3366
        int i;
3367

    
3368
        if (nb_numa_nodes > MAX_NODES) {
3369
            nb_numa_nodes = MAX_NODES;
3370
        }
3371

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

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

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

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

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

    
3420
    module_call_init(MODULE_INIT_DEVICE);
3421

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

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

    
3431
    if (machine->compat_props) {
3432
        qdev_prop_register_global_list(machine->compat_props);
3433
    }
3434
    qemu_add_globals();
3435

    
3436
    machine->init(ram_size, boot_devices,
3437
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
3438

    
3439
    cpu_synchronize_all_post_init();
3440

    
3441
    set_numa_modes();
3442

    
3443
    current_machine = machine;
3444

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

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

    
3455
    net_check_clients();
3456

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

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

    
3473

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

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

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

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

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

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

    
3536
    qdev_machine_creation_done();
3537

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

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

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

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

    
3567
    os_setup_post();
3568

    
3569
    main_loop();
3570
    net_cleanup();
3571
    res_free();
3572

    
3573
    return 0;
3574
}