]> git.proxmox.com Git - mirror_qemu.git/blame_incremental - vl.c
CODING_STYLE: Reserve qemu_ prefix for library wrappers
[mirror_qemu.git] / vl.c
... / ...
CommitLineData
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 <pwd.h>
38#include <sys/times.h>
39#include <sys/wait.h>
40#include <termios.h>
41#include <sys/mman.h>
42#include <sys/ioctl.h>
43#include <sys/resource.h>
44#include <sys/socket.h>
45#include <netinet/in.h>
46#include <net/if.h>
47#include <arpa/inet.h>
48#include <dirent.h>
49#include <netdb.h>
50#include <sys/select.h>
51#ifdef CONFIG_BSD
52#include <sys/stat.h>
53#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54#include <libutil.h>
55#else
56#include <util.h>
57#endif
58#else
59#ifdef __linux__
60#include <pty.h>
61#include <malloc.h>
62#include <sys/prctl.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.h>
73#include <netinet/in_systm.h>
74#include <netinet/ip.h>
75#include <netinet/ip_icmp.h> // must come after ip.h
76#include <netinet/udp.h>
77#include <netinet/tcp.h>
78#include <net/if.h>
79#include <syslog.h>
80#include <stropts.h>
81/* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
82 discussion about Solaris header problems */
83extern int madvise(caddr_t, size_t, int);
84#endif
85#endif
86#endif
87
88#if defined(__OpenBSD__)
89#include <util.h>
90#endif
91
92#if defined(CONFIG_VDE)
93#include <libvdeplug.h>
94#endif
95
96#ifdef _WIN32
97#include <windows.h>
98#endif
99
100#ifdef CONFIG_SDL
101#if defined(__APPLE__) || defined(main)
102#include <SDL.h>
103int qemu_main(int argc, char **argv, char **envp);
104int main(int argc, char **argv)
105{
106 return qemu_main(argc, argv, NULL);
107}
108#undef main
109#define main qemu_main
110#endif
111#endif /* CONFIG_SDL */
112
113#ifdef CONFIG_COCOA
114#undef main
115#define main qemu_main
116#endif /* CONFIG_COCOA */
117
118#include "hw/hw.h"
119#include "hw/boards.h"
120#include "hw/usb.h"
121#include "hw/pcmcia.h"
122#include "hw/pc.h"
123#include "hw/audiodev.h"
124#include "hw/isa.h"
125#include "hw/baum.h"
126#include "hw/bt.h"
127#include "hw/watchdog.h"
128#include "hw/smbios.h"
129#include "hw/xen.h"
130#include "hw/qdev.h"
131#include "hw/loader.h"
132#include "bt-host.h"
133#include "net.h"
134#include "net/slirp.h"
135#include "monitor.h"
136#include "console.h"
137#include "sysemu.h"
138#include "gdbstub.h"
139#include "qemu-timer.h"
140#include "qemu-char.h"
141#include "cache-utils.h"
142#include "block.h"
143#include "block_int.h"
144#include "block-migration.h"
145#include "dma.h"
146#include "audio/audio.h"
147#include "migration.h"
148#include "kvm.h"
149#include "balloon.h"
150#include "qemu-option.h"
151#include "qemu-config.h"
152#include "qemu-objects.h"
153
154#include "disas.h"
155
156#include "exec-all.h"
157
158#include "qemu_socket.h"
159
160#include "slirp/libslirp.h"
161
162#include "qemu-queue.h"
163
164//#define DEBUG_NET
165//#define DEBUG_SLIRP
166
167#define DEFAULT_RAM_SIZE 128
168
169#define MAX_VIRTIO_CONSOLES 1
170
171static const char *data_dir;
172const char *bios_name = NULL;
173/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
174 to store the VM snapshots */
175struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
176struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
177enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
178DisplayType display_type = DT_DEFAULT;
179const char* keyboard_layout = NULL;
180ram_addr_t ram_size;
181const char *mem_path = NULL;
182#ifdef MAP_POPULATE
183int mem_prealloc = 0; /* force preallocation of physical target memory */
184#endif
185int nb_nics;
186NICInfo nd_table[MAX_NICS];
187int vm_running;
188int autostart;
189static int rtc_utc = 1;
190static int rtc_date_offset = -1; /* -1 means no change */
191QEMUClock *rtc_clock;
192int vga_interface_type = VGA_NONE;
193#ifdef TARGET_SPARC
194int graphic_width = 1024;
195int graphic_height = 768;
196int graphic_depth = 8;
197#else
198int graphic_width = 800;
199int graphic_height = 600;
200int graphic_depth = 15;
201#endif
202static int full_screen = 0;
203#ifdef CONFIG_SDL
204static int no_frame = 0;
205#endif
206int no_quit = 0;
207CharDriverState *serial_hds[MAX_SERIAL_PORTS];
208CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
209CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
210#ifdef TARGET_I386
211int win2k_install_hack = 0;
212int rtc_td_hack = 0;
213#endif
214int usb_enabled = 0;
215int singlestep = 0;
216int smp_cpus = 1;
217int max_cpus = 0;
218int smp_cores = 1;
219int smp_threads = 1;
220const char *vnc_display;
221int acpi_enabled = 1;
222int no_hpet = 0;
223int fd_bootchk = 1;
224int no_reboot = 0;
225int no_shutdown = 0;
226int cursor_hide = 1;
227int graphic_rotate = 0;
228uint8_t irq0override = 1;
229#ifndef _WIN32
230int daemonize = 0;
231#endif
232const char *watchdog;
233const char *option_rom[MAX_OPTION_ROMS];
234int nb_option_roms;
235int semihosting_enabled = 0;
236#ifdef TARGET_ARM
237int old_param = 0;
238#endif
239const char *qemu_name;
240int alt_grab = 0;
241int ctrl_grab = 0;
242#if defined(TARGET_SPARC) || defined(TARGET_PPC)
243unsigned int nb_prom_envs = 0;
244const char *prom_envs[MAX_PROM_ENVS];
245#endif
246int boot_menu;
247
248int nb_numa_nodes;
249uint64_t node_mem[MAX_NODES];
250uint64_t node_cpumask[MAX_NODES];
251
252static CPUState *cur_cpu;
253static CPUState *next_cpu;
254static QEMUTimer *nographic_timer;
255
256uint8_t qemu_uuid[16];
257
258static QEMUBootSetHandler *boot_set_handler;
259static void *boot_set_opaque;
260
261#ifdef SIGRTMIN
262#define SIG_IPI (SIGRTMIN+4)
263#else
264#define SIG_IPI SIGUSR1
265#endif
266
267static int default_serial = 1;
268static int default_parallel = 1;
269static int default_virtcon = 1;
270static int default_monitor = 1;
271static int default_vga = 1;
272static int default_floppy = 1;
273static int default_cdrom = 1;
274static int default_sdcard = 1;
275
276static struct {
277 const char *driver;
278 int *flag;
279} default_list[] = {
280 { .driver = "isa-serial", .flag = &default_serial },
281 { .driver = "isa-parallel", .flag = &default_parallel },
282 { .driver = "isa-fdc", .flag = &default_floppy },
283 { .driver = "ide-drive", .flag = &default_cdrom },
284 { .driver = "virtio-serial-pci", .flag = &default_virtcon },
285 { .driver = "virtio-serial-s390", .flag = &default_virtcon },
286 { .driver = "virtio-serial", .flag = &default_virtcon },
287 { .driver = "VGA", .flag = &default_vga },
288 { .driver = "cirrus-vga", .flag = &default_vga },
289 { .driver = "vmware-svga", .flag = &default_vga },
290};
291
292static int default_driver_check(QemuOpts *opts, void *opaque)
293{
294 const char *driver = qemu_opt_get(opts, "driver");
295 int i;
296
297 if (!driver)
298 return 0;
299 for (i = 0; i < ARRAY_SIZE(default_list); i++) {
300 if (strcmp(default_list[i].driver, driver) != 0)
301 continue;
302 *(default_list[i].flag) = 0;
303 }
304 return 0;
305}
306
307/***********************************************************/
308/* x86 ISA bus support */
309
310target_phys_addr_t isa_mem_base = 0;
311PicState2 *isa_pic;
312
313/***********************************************************/
314void hw_error(const char *fmt, ...)
315{
316 va_list ap;
317 CPUState *env;
318
319 va_start(ap, fmt);
320 fprintf(stderr, "qemu: hardware error: ");
321 vfprintf(stderr, fmt, ap);
322 fprintf(stderr, "\n");
323 for(env = first_cpu; env != NULL; env = env->next_cpu) {
324 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
325#ifdef TARGET_I386
326 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
327#else
328 cpu_dump_state(env, stderr, fprintf, 0);
329#endif
330 }
331 va_end(ap);
332 abort();
333}
334
335static void set_proc_name(const char *s)
336{
337#if defined(__linux__) && defined(PR_SET_NAME)
338 char name[16];
339 if (!s)
340 return;
341 name[sizeof(name) - 1] = 0;
342 strncpy(name, s, sizeof(name));
343 /* Could rewrite argv[0] too, but that's a bit more complicated.
344 This simple way is enough for `top'. */
345 prctl(PR_SET_NAME, name);
346#endif
347}
348
349/***************/
350/* ballooning */
351
352static QEMUBalloonEvent *qemu_balloon_event;
353void *qemu_balloon_event_opaque;
354
355void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
356{
357 qemu_balloon_event = func;
358 qemu_balloon_event_opaque = opaque;
359}
360
361int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
362{
363 if (qemu_balloon_event) {
364 qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
365 return 1;
366 } else {
367 return 0;
368 }
369}
370
371int qemu_balloon_status(MonitorCompletion cb, void *opaque)
372{
373 if (qemu_balloon_event) {
374 qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
375 return 1;
376 } else {
377 return 0;
378 }
379}
380
381
382/***********************************************************/
383/* real time host monotonic timer */
384
385/* compute with 96 bit intermediate result: (a*b)/c */
386uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
387{
388 union {
389 uint64_t ll;
390 struct {
391#ifdef HOST_WORDS_BIGENDIAN
392 uint32_t high, low;
393#else
394 uint32_t low, high;
395#endif
396 } l;
397 } u, res;
398 uint64_t rl, rh;
399
400 u.ll = a;
401 rl = (uint64_t)u.l.low * (uint64_t)b;
402 rh = (uint64_t)u.l.high * (uint64_t)b;
403 rh += (rl >> 32);
404 res.l.high = rh / c;
405 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
406 return res.ll;
407}
408
409/***********************************************************/
410/* host time/date access */
411void qemu_get_timedate(struct tm *tm, int offset)
412{
413 time_t ti;
414 struct tm *ret;
415
416 time(&ti);
417 ti += offset;
418 if (rtc_date_offset == -1) {
419 if (rtc_utc)
420 ret = gmtime(&ti);
421 else
422 ret = localtime(&ti);
423 } else {
424 ti -= rtc_date_offset;
425 ret = gmtime(&ti);
426 }
427
428 memcpy(tm, ret, sizeof(struct tm));
429}
430
431int qemu_timedate_diff(struct tm *tm)
432{
433 time_t seconds;
434
435 if (rtc_date_offset == -1)
436 if (rtc_utc)
437 seconds = mktimegm(tm);
438 else
439 seconds = mktime(tm);
440 else
441 seconds = mktimegm(tm) + rtc_date_offset;
442
443 return seconds - time(NULL);
444}
445
446void rtc_change_mon_event(struct tm *tm)
447{
448 QObject *data;
449
450 data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
451 monitor_protocol_event(QEVENT_RTC_CHANGE, data);
452 qobject_decref(data);
453}
454
455static void configure_rtc_date_offset(const char *startdate, int legacy)
456{
457 time_t rtc_start_date;
458 struct tm tm;
459
460 if (!strcmp(startdate, "now") && legacy) {
461 rtc_date_offset = -1;
462 } else {
463 if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
464 &tm.tm_year,
465 &tm.tm_mon,
466 &tm.tm_mday,
467 &tm.tm_hour,
468 &tm.tm_min,
469 &tm.tm_sec) == 6) {
470 /* OK */
471 } else if (sscanf(startdate, "%d-%d-%d",
472 &tm.tm_year,
473 &tm.tm_mon,
474 &tm.tm_mday) == 3) {
475 tm.tm_hour = 0;
476 tm.tm_min = 0;
477 tm.tm_sec = 0;
478 } else {
479 goto date_fail;
480 }
481 tm.tm_year -= 1900;
482 tm.tm_mon--;
483 rtc_start_date = mktimegm(&tm);
484 if (rtc_start_date == -1) {
485 date_fail:
486 fprintf(stderr, "Invalid date format. Valid formats are:\n"
487 "'2006-06-17T16:01:21' or '2006-06-17'\n");
488 exit(1);
489 }
490 rtc_date_offset = time(NULL) - rtc_start_date;
491 }
492}
493
494static void configure_rtc(QemuOpts *opts)
495{
496 const char *value;
497
498 value = qemu_opt_get(opts, "base");
499 if (value) {
500 if (!strcmp(value, "utc")) {
501 rtc_utc = 1;
502 } else if (!strcmp(value, "localtime")) {
503 rtc_utc = 0;
504 } else {
505 configure_rtc_date_offset(value, 0);
506 }
507 }
508 value = qemu_opt_get(opts, "clock");
509 if (value) {
510 if (!strcmp(value, "host")) {
511 rtc_clock = host_clock;
512 } else if (!strcmp(value, "vm")) {
513 rtc_clock = vm_clock;
514 } else {
515 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
516 exit(1);
517 }
518 }
519#ifdef CONFIG_TARGET_I386
520 value = qemu_opt_get(opts, "driftfix");
521 if (value) {
522 if (!strcmp(buf, "slew")) {
523 rtc_td_hack = 1;
524 } else if (!strcmp(buf, "none")) {
525 rtc_td_hack = 0;
526 } else {
527 fprintf(stderr, "qemu: invalid option value '%s'\n", value);
528 exit(1);
529 }
530 }
531#endif
532}
533
534#ifdef _WIN32
535static void socket_cleanup(void)
536{
537 WSACleanup();
538}
539
540static int socket_init(void)
541{
542 WSADATA Data;
543 int ret, err;
544
545 ret = WSAStartup(MAKEWORD(2,2), &Data);
546 if (ret != 0) {
547 err = WSAGetLastError();
548 fprintf(stderr, "WSAStartup: %d\n", err);
549 return -1;
550 }
551 atexit(socket_cleanup);
552 return 0;
553}
554#endif
555
556/***********************************************************/
557/* Bluetooth support */
558static int nb_hcis;
559static int cur_hci;
560static struct HCIInfo *hci_table[MAX_NICS];
561
562static struct bt_vlan_s {
563 struct bt_scatternet_s net;
564 int id;
565 struct bt_vlan_s *next;
566} *first_bt_vlan;
567
568/* find or alloc a new bluetooth "VLAN" */
569static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
570{
571 struct bt_vlan_s **pvlan, *vlan;
572 for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
573 if (vlan->id == id)
574 return &vlan->net;
575 }
576 vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
577 vlan->id = id;
578 pvlan = &first_bt_vlan;
579 while (*pvlan != NULL)
580 pvlan = &(*pvlan)->next;
581 *pvlan = vlan;
582 return &vlan->net;
583}
584
585static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
586{
587}
588
589static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
590{
591 return -ENOTSUP;
592}
593
594static struct HCIInfo null_hci = {
595 .cmd_send = null_hci_send,
596 .sco_send = null_hci_send,
597 .acl_send = null_hci_send,
598 .bdaddr_set = null_hci_addr_set,
599};
600
601struct HCIInfo *qemu_next_hci(void)
602{
603 if (cur_hci == nb_hcis)
604 return &null_hci;
605
606 return hci_table[cur_hci++];
607}
608
609static struct HCIInfo *hci_init(const char *str)
610{
611 char *endp;
612 struct bt_scatternet_s *vlan = 0;
613
614 if (!strcmp(str, "null"))
615 /* null */
616 return &null_hci;
617 else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
618 /* host[:hciN] */
619 return bt_host_hci(str[4] ? str + 5 : "hci0");
620 else if (!strncmp(str, "hci", 3)) {
621 /* hci[,vlan=n] */
622 if (str[3]) {
623 if (!strncmp(str + 3, ",vlan=", 6)) {
624 vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
625 if (*endp)
626 vlan = 0;
627 }
628 } else
629 vlan = qemu_find_bt_vlan(0);
630 if (vlan)
631 return bt_new_hci(vlan);
632 }
633
634 fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
635
636 return 0;
637}
638
639static int bt_hci_parse(const char *str)
640{
641 struct HCIInfo *hci;
642 bdaddr_t bdaddr;
643
644 if (nb_hcis >= MAX_NICS) {
645 fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
646 return -1;
647 }
648
649 hci = hci_init(str);
650 if (!hci)
651 return -1;
652
653 bdaddr.b[0] = 0x52;
654 bdaddr.b[1] = 0x54;
655 bdaddr.b[2] = 0x00;
656 bdaddr.b[3] = 0x12;
657 bdaddr.b[4] = 0x34;
658 bdaddr.b[5] = 0x56 + nb_hcis;
659 hci->bdaddr_set(hci, bdaddr.b);
660
661 hci_table[nb_hcis++] = hci;
662
663 return 0;
664}
665
666static void bt_vhci_add(int vlan_id)
667{
668 struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
669
670 if (!vlan->slave)
671 fprintf(stderr, "qemu: warning: adding a VHCI to "
672 "an empty scatternet %i\n", vlan_id);
673
674 bt_vhci_init(bt_new_hci(vlan));
675}
676
677static struct bt_device_s *bt_device_add(const char *opt)
678{
679 struct bt_scatternet_s *vlan;
680 int vlan_id = 0;
681 char *endp = strstr(opt, ",vlan=");
682 int len = (endp ? endp - opt : strlen(opt)) + 1;
683 char devname[10];
684
685 pstrcpy(devname, MIN(sizeof(devname), len), opt);
686
687 if (endp) {
688 vlan_id = strtol(endp + 6, &endp, 0);
689 if (*endp) {
690 fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
691 return 0;
692 }
693 }
694
695 vlan = qemu_find_bt_vlan(vlan_id);
696
697 if (!vlan->slave)
698 fprintf(stderr, "qemu: warning: adding a slave device to "
699 "an empty scatternet %i\n", vlan_id);
700
701 if (!strcmp(devname, "keyboard"))
702 return bt_keyboard_init(vlan);
703
704 fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
705 return 0;
706}
707
708static int bt_parse(const char *opt)
709{
710 const char *endp, *p;
711 int vlan;
712
713 if (strstart(opt, "hci", &endp)) {
714 if (!*endp || *endp == ',') {
715 if (*endp)
716 if (!strstart(endp, ",vlan=", 0))
717 opt = endp + 1;
718
719 return bt_hci_parse(opt);
720 }
721 } else if (strstart(opt, "vhci", &endp)) {
722 if (!*endp || *endp == ',') {
723 if (*endp) {
724 if (strstart(endp, ",vlan=", &p)) {
725 vlan = strtol(p, (char **) &endp, 0);
726 if (*endp) {
727 fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
728 return 1;
729 }
730 } else {
731 fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
732 return 1;
733 }
734 } else
735 vlan = 0;
736
737 bt_vhci_add(vlan);
738 return 0;
739 }
740 } else if (strstart(opt, "device:", &endp))
741 return !bt_device_add(endp);
742
743 fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
744 return 1;
745}
746
747/***********************************************************/
748/* QEMU Block devices */
749
750#define HD_ALIAS "index=%d,media=disk"
751#define CDROM_ALIAS "index=2,media=cdrom"
752#define FD_ALIAS "index=%d,if=floppy"
753#define PFLASH_ALIAS "if=pflash"
754#define MTD_ALIAS "if=mtd"
755#define SD_ALIAS "index=0,if=sd"
756
757QemuOpts *drive_add(const char *file, const char *fmt, ...)
758{
759 va_list ap;
760 char optstr[1024];
761 QemuOpts *opts;
762
763 va_start(ap, fmt);
764 vsnprintf(optstr, sizeof(optstr), fmt, ap);
765 va_end(ap);
766
767 opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
768 if (!opts) {
769 fprintf(stderr, "%s: huh? duplicate? (%s)\n",
770 __FUNCTION__, optstr);
771 return NULL;
772 }
773 if (file)
774 qemu_opt_set(opts, "file", file);
775 return opts;
776}
777
778DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
779{
780 DriveInfo *dinfo;
781
782 /* seek interface, bus and unit */
783
784 QTAILQ_FOREACH(dinfo, &drives, next) {
785 if (dinfo->type == type &&
786 dinfo->bus == bus &&
787 dinfo->unit == unit)
788 return dinfo;
789 }
790
791 return NULL;
792}
793
794DriveInfo *drive_get_by_id(const char *id)
795{
796 DriveInfo *dinfo;
797
798 QTAILQ_FOREACH(dinfo, &drives, next) {
799 if (strcmp(id, dinfo->id))
800 continue;
801 return dinfo;
802 }
803 return NULL;
804}
805
806int drive_get_max_bus(BlockInterfaceType type)
807{
808 int max_bus;
809 DriveInfo *dinfo;
810
811 max_bus = -1;
812 QTAILQ_FOREACH(dinfo, &drives, next) {
813 if(dinfo->type == type &&
814 dinfo->bus > max_bus)
815 max_bus = dinfo->bus;
816 }
817 return max_bus;
818}
819
820const char *drive_get_serial(BlockDriverState *bdrv)
821{
822 DriveInfo *dinfo;
823
824 QTAILQ_FOREACH(dinfo, &drives, next) {
825 if (dinfo->bdrv == bdrv)
826 return dinfo->serial;
827 }
828
829 return "\0";
830}
831
832BlockInterfaceErrorAction drive_get_on_error(
833 BlockDriverState *bdrv, int is_read)
834{
835 DriveInfo *dinfo;
836
837 QTAILQ_FOREACH(dinfo, &drives, next) {
838 if (dinfo->bdrv == bdrv)
839 return is_read ? dinfo->on_read_error : dinfo->on_write_error;
840 }
841
842 return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
843}
844
845static void bdrv_format_print(void *opaque, const char *name)
846{
847 fprintf(stderr, " %s", name);
848}
849
850void drive_uninit(DriveInfo *dinfo)
851{
852 qemu_opts_del(dinfo->opts);
853 bdrv_delete(dinfo->bdrv);
854 QTAILQ_REMOVE(&drives, dinfo, next);
855 qemu_free(dinfo);
856}
857
858static int parse_block_error_action(const char *buf, int is_read)
859{
860 if (!strcmp(buf, "ignore")) {
861 return BLOCK_ERR_IGNORE;
862 } else if (!is_read && !strcmp(buf, "enospc")) {
863 return BLOCK_ERR_STOP_ENOSPC;
864 } else if (!strcmp(buf, "stop")) {
865 return BLOCK_ERR_STOP_ANY;
866 } else if (!strcmp(buf, "report")) {
867 return BLOCK_ERR_REPORT;
868 } else {
869 fprintf(stderr, "qemu: '%s' invalid %s error action\n",
870 buf, is_read ? "read" : "write");
871 return -1;
872 }
873}
874
875DriveInfo *drive_init(QemuOpts *opts, void *opaque,
876 int *fatal_error)
877{
878 const char *buf;
879 const char *file = NULL;
880 char devname[128];
881 const char *serial;
882 const char *mediastr = "";
883 BlockInterfaceType type;
884 enum { MEDIA_DISK, MEDIA_CDROM } media;
885 int bus_id, unit_id;
886 int cyls, heads, secs, translation;
887 BlockDriver *drv = NULL;
888 QEMUMachine *machine = opaque;
889 int max_devs;
890 int index;
891 int cache;
892 int aio = 0;
893 int ro = 0;
894 int bdrv_flags;
895 int on_read_error, on_write_error;
896 const char *devaddr;
897 DriveInfo *dinfo;
898 int snapshot = 0;
899
900 *fatal_error = 1;
901
902 translation = BIOS_ATA_TRANSLATION_AUTO;
903 cache = 1;
904
905 if (machine && machine->use_scsi) {
906 type = IF_SCSI;
907 max_devs = MAX_SCSI_DEVS;
908 pstrcpy(devname, sizeof(devname), "scsi");
909 } else {
910 type = IF_IDE;
911 max_devs = MAX_IDE_DEVS;
912 pstrcpy(devname, sizeof(devname), "ide");
913 }
914 media = MEDIA_DISK;
915
916 /* extract parameters */
917 bus_id = qemu_opt_get_number(opts, "bus", 0);
918 unit_id = qemu_opt_get_number(opts, "unit", -1);
919 index = qemu_opt_get_number(opts, "index", -1);
920
921 cyls = qemu_opt_get_number(opts, "cyls", 0);
922 heads = qemu_opt_get_number(opts, "heads", 0);
923 secs = qemu_opt_get_number(opts, "secs", 0);
924
925 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
926 ro = qemu_opt_get_bool(opts, "readonly", 0);
927
928 file = qemu_opt_get(opts, "file");
929 serial = qemu_opt_get(opts, "serial");
930
931 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
932 pstrcpy(devname, sizeof(devname), buf);
933 if (!strcmp(buf, "ide")) {
934 type = IF_IDE;
935 max_devs = MAX_IDE_DEVS;
936 } else if (!strcmp(buf, "scsi")) {
937 type = IF_SCSI;
938 max_devs = MAX_SCSI_DEVS;
939 } else if (!strcmp(buf, "floppy")) {
940 type = IF_FLOPPY;
941 max_devs = 0;
942 } else if (!strcmp(buf, "pflash")) {
943 type = IF_PFLASH;
944 max_devs = 0;
945 } else if (!strcmp(buf, "mtd")) {
946 type = IF_MTD;
947 max_devs = 0;
948 } else if (!strcmp(buf, "sd")) {
949 type = IF_SD;
950 max_devs = 0;
951 } else if (!strcmp(buf, "virtio")) {
952 type = IF_VIRTIO;
953 max_devs = 0;
954 } else if (!strcmp(buf, "xen")) {
955 type = IF_XEN;
956 max_devs = 0;
957 } else if (!strcmp(buf, "none")) {
958 type = IF_NONE;
959 max_devs = 0;
960 } else {
961 fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
962 return NULL;
963 }
964 }
965
966 if (cyls || heads || secs) {
967 if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
968 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
969 return NULL;
970 }
971 if (heads < 1 || (type == IF_IDE && heads > 16)) {
972 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
973 return NULL;
974 }
975 if (secs < 1 || (type == IF_IDE && secs > 63)) {
976 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
977 return NULL;
978 }
979 }
980
981 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
982 if (!cyls) {
983 fprintf(stderr,
984 "qemu: '%s' trans must be used with cyls,heads and secs\n",
985 buf);
986 return NULL;
987 }
988 if (!strcmp(buf, "none"))
989 translation = BIOS_ATA_TRANSLATION_NONE;
990 else if (!strcmp(buf, "lba"))
991 translation = BIOS_ATA_TRANSLATION_LBA;
992 else if (!strcmp(buf, "auto"))
993 translation = BIOS_ATA_TRANSLATION_AUTO;
994 else {
995 fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
996 return NULL;
997 }
998 }
999
1000 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
1001 if (!strcmp(buf, "disk")) {
1002 media = MEDIA_DISK;
1003 } else if (!strcmp(buf, "cdrom")) {
1004 if (cyls || secs || heads) {
1005 fprintf(stderr,
1006 "qemu: '%s' invalid physical CHS format\n", buf);
1007 return NULL;
1008 }
1009 media = MEDIA_CDROM;
1010 } else {
1011 fprintf(stderr, "qemu: '%s' invalid media\n", buf);
1012 return NULL;
1013 }
1014 }
1015
1016 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
1017 if (!strcmp(buf, "off") || !strcmp(buf, "none"))
1018 cache = 0;
1019 else if (!strcmp(buf, "writethrough"))
1020 cache = 1;
1021 else if (!strcmp(buf, "writeback"))
1022 cache = 2;
1023 else {
1024 fprintf(stderr, "qemu: invalid cache option\n");
1025 return NULL;
1026 }
1027 }
1028
1029#ifdef CONFIG_LINUX_AIO
1030 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
1031 if (!strcmp(buf, "threads"))
1032 aio = 0;
1033 else if (!strcmp(buf, "native"))
1034 aio = 1;
1035 else {
1036 fprintf(stderr, "qemu: invalid aio option\n");
1037 return NULL;
1038 }
1039 }
1040#endif
1041
1042 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
1043 if (strcmp(buf, "?") == 0) {
1044 fprintf(stderr, "qemu: Supported formats:");
1045 bdrv_iterate_format(bdrv_format_print, NULL);
1046 fprintf(stderr, "\n");
1047 return NULL;
1048 }
1049 drv = bdrv_find_whitelisted_format(buf);
1050 if (!drv) {
1051 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
1052 return NULL;
1053 }
1054 }
1055
1056 on_write_error = BLOCK_ERR_STOP_ENOSPC;
1057 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
1058 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
1059 fprintf(stderr, "werror is no supported by this format\n");
1060 return NULL;
1061 }
1062
1063 on_write_error = parse_block_error_action(buf, 0);
1064 if (on_write_error < 0) {
1065 return NULL;
1066 }
1067 }
1068
1069 on_read_error = BLOCK_ERR_REPORT;
1070 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
1071 if (type != IF_IDE && type != IF_VIRTIO) {
1072 fprintf(stderr, "rerror is no supported by this format\n");
1073 return NULL;
1074 }
1075
1076 on_read_error = parse_block_error_action(buf, 1);
1077 if (on_read_error < 0) {
1078 return NULL;
1079 }
1080 }
1081
1082 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
1083 if (type != IF_VIRTIO) {
1084 fprintf(stderr, "addr is not supported\n");
1085 return NULL;
1086 }
1087 }
1088
1089 /* compute bus and unit according index */
1090
1091 if (index != -1) {
1092 if (bus_id != 0 || unit_id != -1) {
1093 fprintf(stderr,
1094 "qemu: index cannot be used with bus and unit\n");
1095 return NULL;
1096 }
1097 if (max_devs == 0)
1098 {
1099 unit_id = index;
1100 bus_id = 0;
1101 } else {
1102 unit_id = index % max_devs;
1103 bus_id = index / max_devs;
1104 }
1105 }
1106
1107 /* if user doesn't specify a unit_id,
1108 * try to find the first free
1109 */
1110
1111 if (unit_id == -1) {
1112 unit_id = 0;
1113 while (drive_get(type, bus_id, unit_id) != NULL) {
1114 unit_id++;
1115 if (max_devs && unit_id >= max_devs) {
1116 unit_id -= max_devs;
1117 bus_id++;
1118 }
1119 }
1120 }
1121
1122 /* check unit id */
1123
1124 if (max_devs && unit_id >= max_devs) {
1125 fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
1126 unit_id, max_devs - 1);
1127 return NULL;
1128 }
1129
1130 /*
1131 * ignore multiple definitions
1132 */
1133
1134 if (drive_get(type, bus_id, unit_id) != NULL) {
1135 *fatal_error = 0;
1136 return NULL;
1137 }
1138
1139 /* init */
1140
1141 dinfo = qemu_mallocz(sizeof(*dinfo));
1142 if ((buf = qemu_opts_id(opts)) != NULL) {
1143 dinfo->id = qemu_strdup(buf);
1144 } else {
1145 /* no id supplied -> create one */
1146 dinfo->id = qemu_mallocz(32);
1147 if (type == IF_IDE || type == IF_SCSI)
1148 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1149 if (max_devs)
1150 snprintf(dinfo->id, 32, "%s%i%s%i",
1151 devname, bus_id, mediastr, unit_id);
1152 else
1153 snprintf(dinfo->id, 32, "%s%s%i",
1154 devname, mediastr, unit_id);
1155 }
1156 dinfo->bdrv = bdrv_new(dinfo->id);
1157 dinfo->devaddr = devaddr;
1158 dinfo->type = type;
1159 dinfo->bus = bus_id;
1160 dinfo->unit = unit_id;
1161 dinfo->on_read_error = on_read_error;
1162 dinfo->on_write_error = on_write_error;
1163 dinfo->opts = opts;
1164 if (serial)
1165 strncpy(dinfo->serial, serial, sizeof(serial));
1166 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
1167
1168 switch(type) {
1169 case IF_IDE:
1170 case IF_SCSI:
1171 case IF_XEN:
1172 case IF_NONE:
1173 switch(media) {
1174 case MEDIA_DISK:
1175 if (cyls != 0) {
1176 bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
1177 bdrv_set_translation_hint(dinfo->bdrv, translation);
1178 }
1179 break;
1180 case MEDIA_CDROM:
1181 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
1182 break;
1183 }
1184 break;
1185 case IF_SD:
1186 /* FIXME: This isn't really a floppy, but it's a reasonable
1187 approximation. */
1188 case IF_FLOPPY:
1189 bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
1190 break;
1191 case IF_PFLASH:
1192 case IF_MTD:
1193 break;
1194 case IF_VIRTIO:
1195 /* add virtio block device */
1196 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
1197 qemu_opt_set(opts, "driver", "virtio-blk-pci");
1198 qemu_opt_set(opts, "drive", dinfo->id);
1199 if (devaddr)
1200 qemu_opt_set(opts, "addr", devaddr);
1201 break;
1202 case IF_COUNT:
1203 abort();
1204 }
1205 if (!file) {
1206 *fatal_error = 0;
1207 return NULL;
1208 }
1209 bdrv_flags = 0;
1210 if (snapshot) {
1211 bdrv_flags |= BDRV_O_SNAPSHOT;
1212 cache = 2; /* always use write-back with snapshot */
1213 }
1214 if (cache == 0) /* no caching */
1215 bdrv_flags |= BDRV_O_NOCACHE;
1216 else if (cache == 2) /* write-back */
1217 bdrv_flags |= BDRV_O_CACHE_WB;
1218
1219 if (aio == 1) {
1220 bdrv_flags |= BDRV_O_NATIVE_AIO;
1221 } else {
1222 bdrv_flags &= ~BDRV_O_NATIVE_AIO;
1223 }
1224
1225 if (ro == 1) {
1226 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
1227 fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
1228 return NULL;
1229 }
1230 }
1231 /*
1232 * cdrom is read-only. Set it now, after above interface checking
1233 * since readonly attribute not explicitly required, so no error.
1234 */
1235 if (media == MEDIA_CDROM) {
1236 ro = 1;
1237 }
1238 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
1239
1240 if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
1241 fprintf(stderr, "qemu: could not open disk image %s: %s\n",
1242 file, strerror(errno));
1243 return NULL;
1244 }
1245
1246 if (bdrv_key_required(dinfo->bdrv))
1247 autostart = 0;
1248 *fatal_error = 0;
1249 return dinfo;
1250}
1251
1252static int drive_init_func(QemuOpts *opts, void *opaque)
1253{
1254 QEMUMachine *machine = opaque;
1255 int fatal_error = 0;
1256
1257 if (drive_init(opts, machine, &fatal_error) == NULL) {
1258 if (fatal_error)
1259 return 1;
1260 }
1261 return 0;
1262}
1263
1264static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
1265{
1266 if (NULL == qemu_opt_get(opts, "snapshot")) {
1267 qemu_opt_set(opts, "snapshot", "on");
1268 }
1269 return 0;
1270}
1271
1272void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
1273{
1274 boot_set_handler = func;
1275 boot_set_opaque = opaque;
1276}
1277
1278int qemu_boot_set(const char *boot_devices)
1279{
1280 if (!boot_set_handler) {
1281 return -EINVAL;
1282 }
1283 return boot_set_handler(boot_set_opaque, boot_devices);
1284}
1285
1286static int parse_bootdevices(char *devices)
1287{
1288 /* We just do some generic consistency checks */
1289 const char *p;
1290 int bitmap = 0;
1291
1292 for (p = devices; *p != '\0'; p++) {
1293 /* Allowed boot devices are:
1294 * a-b: floppy disk drives
1295 * c-f: IDE disk drives
1296 * g-m: machine implementation dependant drives
1297 * n-p: network devices
1298 * It's up to each machine implementation to check if the given boot
1299 * devices match the actual hardware implementation and firmware
1300 * features.
1301 */
1302 if (*p < 'a' || *p > 'p') {
1303 fprintf(stderr, "Invalid boot device '%c'\n", *p);
1304 exit(1);
1305 }
1306 if (bitmap & (1 << (*p - 'a'))) {
1307 fprintf(stderr, "Boot device '%c' was given twice\n", *p);
1308 exit(1);
1309 }
1310 bitmap |= 1 << (*p - 'a');
1311 }
1312 return bitmap;
1313}
1314
1315static void restore_boot_devices(void *opaque)
1316{
1317 char *standard_boot_devices = opaque;
1318
1319 qemu_boot_set(standard_boot_devices);
1320
1321 qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
1322 qemu_free(standard_boot_devices);
1323}
1324
1325static void numa_add(const char *optarg)
1326{
1327 char option[128];
1328 char *endptr;
1329 unsigned long long value, endvalue;
1330 int nodenr;
1331
1332 optarg = get_opt_name(option, 128, optarg, ',') + 1;
1333 if (!strcmp(option, "node")) {
1334 if (get_param_value(option, 128, "nodeid", optarg) == 0) {
1335 nodenr = nb_numa_nodes;
1336 } else {
1337 nodenr = strtoull(option, NULL, 10);
1338 }
1339
1340 if (get_param_value(option, 128, "mem", optarg) == 0) {
1341 node_mem[nodenr] = 0;
1342 } else {
1343 value = strtoull(option, &endptr, 0);
1344 switch (*endptr) {
1345 case 0: case 'M': case 'm':
1346 value <<= 20;
1347 break;
1348 case 'G': case 'g':
1349 value <<= 30;
1350 break;
1351 }
1352 node_mem[nodenr] = value;
1353 }
1354 if (get_param_value(option, 128, "cpus", optarg) == 0) {
1355 node_cpumask[nodenr] = 0;
1356 } else {
1357 value = strtoull(option, &endptr, 10);
1358 if (value >= 64) {
1359 value = 63;
1360 fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
1361 } else {
1362 if (*endptr == '-') {
1363 endvalue = strtoull(endptr+1, &endptr, 10);
1364 if (endvalue >= 63) {
1365 endvalue = 62;
1366 fprintf(stderr,
1367 "only 63 CPUs in NUMA mode supported.\n");
1368 }
1369 value = (2ULL << endvalue) - (1ULL << value);
1370 } else {
1371 value = 1ULL << value;
1372 }
1373 }
1374 node_cpumask[nodenr] = value;
1375 }
1376 nb_numa_nodes++;
1377 }
1378 return;
1379}
1380
1381static void smp_parse(const char *optarg)
1382{
1383 int smp, sockets = 0, threads = 0, cores = 0;
1384 char *endptr;
1385 char option[128];
1386
1387 smp = strtoul(optarg, &endptr, 10);
1388 if (endptr != optarg) {
1389 if (*endptr == ',') {
1390 endptr++;
1391 }
1392 }
1393 if (get_param_value(option, 128, "sockets", endptr) != 0)
1394 sockets = strtoull(option, NULL, 10);
1395 if (get_param_value(option, 128, "cores", endptr) != 0)
1396 cores = strtoull(option, NULL, 10);
1397 if (get_param_value(option, 128, "threads", endptr) != 0)
1398 threads = strtoull(option, NULL, 10);
1399 if (get_param_value(option, 128, "maxcpus", endptr) != 0)
1400 max_cpus = strtoull(option, NULL, 10);
1401
1402 /* compute missing values, prefer sockets over cores over threads */
1403 if (smp == 0 || sockets == 0) {
1404 sockets = sockets > 0 ? sockets : 1;
1405 cores = cores > 0 ? cores : 1;
1406 threads = threads > 0 ? threads : 1;
1407 if (smp == 0) {
1408 smp = cores * threads * sockets;
1409 }
1410 } else {
1411 if (cores == 0) {
1412 threads = threads > 0 ? threads : 1;
1413 cores = smp / (sockets * threads);
1414 } else {
1415 if (sockets) {
1416 threads = smp / (cores * sockets);
1417 }
1418 }
1419 }
1420 smp_cpus = smp;
1421 smp_cores = cores > 0 ? cores : 1;
1422 smp_threads = threads > 0 ? threads : 1;
1423 if (max_cpus == 0)
1424 max_cpus = smp_cpus;
1425}
1426
1427/***********************************************************/
1428/* USB devices */
1429
1430static int usb_device_add(const char *devname, int is_hotplug)
1431{
1432 const char *p;
1433 USBDevice *dev = NULL;
1434
1435 if (!usb_enabled)
1436 return -1;
1437
1438 /* drivers with .usbdevice_name entry in USBDeviceInfo */
1439 dev = usbdevice_create(devname);
1440 if (dev)
1441 goto done;
1442
1443 /* the other ones */
1444 if (strstart(devname, "host:", &p)) {
1445 dev = usb_host_device_open(p);
1446 } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
1447 dev = usb_bt_init(devname[2] ? hci_init(p) :
1448 bt_new_hci(qemu_find_bt_vlan(0)));
1449 } else {
1450 return -1;
1451 }
1452 if (!dev)
1453 return -1;
1454
1455done:
1456 return 0;
1457}
1458
1459static int usb_device_del(const char *devname)
1460{
1461 int bus_num, addr;
1462 const char *p;
1463
1464 if (strstart(devname, "host:", &p))
1465 return usb_host_device_close(p);
1466
1467 if (!usb_enabled)
1468 return -1;
1469
1470 p = strchr(devname, '.');
1471 if (!p)
1472 return -1;
1473 bus_num = strtoul(devname, NULL, 0);
1474 addr = strtoul(p + 1, NULL, 0);
1475
1476 return usb_device_delete_addr(bus_num, addr);
1477}
1478
1479static int usb_parse(const char *cmdline)
1480{
1481 int r;
1482 r = usb_device_add(cmdline, 0);
1483 if (r < 0) {
1484 fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
1485 }
1486 return r;
1487}
1488
1489void do_usb_add(Monitor *mon, const QDict *qdict)
1490{
1491 const char *devname = qdict_get_str(qdict, "devname");
1492 if (usb_device_add(devname, 1) < 0) {
1493 error_report("could not add USB device '%s'", devname);
1494 }
1495}
1496
1497void do_usb_del(Monitor *mon, const QDict *qdict)
1498{
1499 const char *devname = qdict_get_str(qdict, "devname");
1500 if (usb_device_del(devname) < 0) {
1501 error_report("could not delete USB device '%s'", devname);
1502 }
1503}
1504
1505/***********************************************************/
1506/* PCMCIA/Cardbus */
1507
1508static struct pcmcia_socket_entry_s {
1509 PCMCIASocket *socket;
1510 struct pcmcia_socket_entry_s *next;
1511} *pcmcia_sockets = 0;
1512
1513void pcmcia_socket_register(PCMCIASocket *socket)
1514{
1515 struct pcmcia_socket_entry_s *entry;
1516
1517 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
1518 entry->socket = socket;
1519 entry->next = pcmcia_sockets;
1520 pcmcia_sockets = entry;
1521}
1522
1523void pcmcia_socket_unregister(PCMCIASocket *socket)
1524{
1525 struct pcmcia_socket_entry_s *entry, **ptr;
1526
1527 ptr = &pcmcia_sockets;
1528 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
1529 if (entry->socket == socket) {
1530 *ptr = entry->next;
1531 qemu_free(entry);
1532 }
1533}
1534
1535void pcmcia_info(Monitor *mon)
1536{
1537 struct pcmcia_socket_entry_s *iter;
1538
1539 if (!pcmcia_sockets)
1540 monitor_printf(mon, "No PCMCIA sockets\n");
1541
1542 for (iter = pcmcia_sockets; iter; iter = iter->next)
1543 monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
1544 iter->socket->attached ? iter->socket->card_string :
1545 "Empty");
1546}
1547
1548/***********************************************************/
1549/* I/O handling */
1550
1551typedef struct IOHandlerRecord {
1552 int fd;
1553 IOCanRWHandler *fd_read_poll;
1554 IOHandler *fd_read;
1555 IOHandler *fd_write;
1556 int deleted;
1557 void *opaque;
1558 /* temporary data */
1559 struct pollfd *ufd;
1560 struct IOHandlerRecord *next;
1561} IOHandlerRecord;
1562
1563static IOHandlerRecord *first_io_handler;
1564
1565/* XXX: fd_read_poll should be suppressed, but an API change is
1566 necessary in the character devices to suppress fd_can_read(). */
1567int qemu_set_fd_handler2(int fd,
1568 IOCanRWHandler *fd_read_poll,
1569 IOHandler *fd_read,
1570 IOHandler *fd_write,
1571 void *opaque)
1572{
1573 IOHandlerRecord **pioh, *ioh;
1574
1575 if (!fd_read && !fd_write) {
1576 pioh = &first_io_handler;
1577 for(;;) {
1578 ioh = *pioh;
1579 if (ioh == NULL)
1580 break;
1581 if (ioh->fd == fd) {
1582 ioh->deleted = 1;
1583 break;
1584 }
1585 pioh = &ioh->next;
1586 }
1587 } else {
1588 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1589 if (ioh->fd == fd)
1590 goto found;
1591 }
1592 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1593 ioh->next = first_io_handler;
1594 first_io_handler = ioh;
1595 found:
1596 ioh->fd = fd;
1597 ioh->fd_read_poll = fd_read_poll;
1598 ioh->fd_read = fd_read;
1599 ioh->fd_write = fd_write;
1600 ioh->opaque = opaque;
1601 ioh->deleted = 0;
1602 }
1603 return 0;
1604}
1605
1606int qemu_set_fd_handler(int fd,
1607 IOHandler *fd_read,
1608 IOHandler *fd_write,
1609 void *opaque)
1610{
1611 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
1612}
1613
1614#ifdef _WIN32
1615/***********************************************************/
1616/* Polling handling */
1617
1618typedef struct PollingEntry {
1619 PollingFunc *func;
1620 void *opaque;
1621 struct PollingEntry *next;
1622} PollingEntry;
1623
1624static PollingEntry *first_polling_entry;
1625
1626int qemu_add_polling_cb(PollingFunc *func, void *opaque)
1627{
1628 PollingEntry **ppe, *pe;
1629 pe = qemu_mallocz(sizeof(PollingEntry));
1630 pe->func = func;
1631 pe->opaque = opaque;
1632 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
1633 *ppe = pe;
1634 return 0;
1635}
1636
1637void qemu_del_polling_cb(PollingFunc *func, void *opaque)
1638{
1639 PollingEntry **ppe, *pe;
1640 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
1641 pe = *ppe;
1642 if (pe->func == func && pe->opaque == opaque) {
1643 *ppe = pe->next;
1644 qemu_free(pe);
1645 break;
1646 }
1647 }
1648}
1649
1650/***********************************************************/
1651/* Wait objects support */
1652typedef struct WaitObjects {
1653 int num;
1654 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
1655 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
1656 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
1657} WaitObjects;
1658
1659static WaitObjects wait_objects = {0};
1660
1661int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1662{
1663 WaitObjects *w = &wait_objects;
1664
1665 if (w->num >= MAXIMUM_WAIT_OBJECTS)
1666 return -1;
1667 w->events[w->num] = handle;
1668 w->func[w->num] = func;
1669 w->opaque[w->num] = opaque;
1670 w->num++;
1671 return 0;
1672}
1673
1674void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
1675{
1676 int i, found;
1677 WaitObjects *w = &wait_objects;
1678
1679 found = 0;
1680 for (i = 0; i < w->num; i++) {
1681 if (w->events[i] == handle)
1682 found = 1;
1683 if (found) {
1684 w->events[i] = w->events[i + 1];
1685 w->func[i] = w->func[i + 1];
1686 w->opaque[i] = w->opaque[i + 1];
1687 }
1688 }
1689 if (found)
1690 w->num--;
1691}
1692#endif
1693
1694/***********************************************************/
1695/* ram save/restore */
1696
1697#define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
1698#define RAM_SAVE_FLAG_COMPRESS 0x02
1699#define RAM_SAVE_FLAG_MEM_SIZE 0x04
1700#define RAM_SAVE_FLAG_PAGE 0x08
1701#define RAM_SAVE_FLAG_EOS 0x10
1702
1703static int is_dup_page(uint8_t *page, uint8_t ch)
1704{
1705 uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
1706 uint32_t *array = (uint32_t *)page;
1707 int i;
1708
1709 for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
1710 if (array[i] != val)
1711 return 0;
1712 }
1713
1714 return 1;
1715}
1716
1717static int ram_save_block(QEMUFile *f)
1718{
1719 static ram_addr_t current_addr = 0;
1720 ram_addr_t saved_addr = current_addr;
1721 ram_addr_t addr = 0;
1722 int found = 0;
1723
1724 while (addr < last_ram_offset) {
1725 if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
1726 uint8_t *p;
1727
1728 cpu_physical_memory_reset_dirty(current_addr,
1729 current_addr + TARGET_PAGE_SIZE,
1730 MIGRATION_DIRTY_FLAG);
1731
1732 p = qemu_get_ram_ptr(current_addr);
1733
1734 if (is_dup_page(p, *p)) {
1735 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
1736 qemu_put_byte(f, *p);
1737 } else {
1738 qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
1739 qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
1740 }
1741
1742 found = 1;
1743 break;
1744 }
1745 addr += TARGET_PAGE_SIZE;
1746 current_addr = (saved_addr + addr) % last_ram_offset;
1747 }
1748
1749 return found;
1750}
1751
1752static uint64_t bytes_transferred;
1753
1754static ram_addr_t ram_save_remaining(void)
1755{
1756 ram_addr_t addr;
1757 ram_addr_t count = 0;
1758
1759 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1760 if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1761 count++;
1762 }
1763
1764 return count;
1765}
1766
1767uint64_t ram_bytes_remaining(void)
1768{
1769 return ram_save_remaining() * TARGET_PAGE_SIZE;
1770}
1771
1772uint64_t ram_bytes_transferred(void)
1773{
1774 return bytes_transferred;
1775}
1776
1777uint64_t ram_bytes_total(void)
1778{
1779 return last_ram_offset;
1780}
1781
1782static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
1783{
1784 ram_addr_t addr;
1785 uint64_t bytes_transferred_last;
1786 double bwidth = 0;
1787 uint64_t expected_time = 0;
1788
1789 if (stage < 0) {
1790 cpu_physical_memory_set_dirty_tracking(0);
1791 return 0;
1792 }
1793
1794 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
1795 qemu_file_set_error(f);
1796 return 0;
1797 }
1798
1799 if (stage == 1) {
1800 bytes_transferred = 0;
1801
1802 /* Make sure all dirty bits are set */
1803 for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
1804 if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
1805 cpu_physical_memory_set_dirty(addr);
1806 }
1807
1808 /* Enable dirty memory tracking */
1809 cpu_physical_memory_set_dirty_tracking(1);
1810
1811 qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
1812 }
1813
1814 bytes_transferred_last = bytes_transferred;
1815 bwidth = qemu_get_clock_ns(rt_clock);
1816
1817 while (!qemu_file_rate_limit(f)) {
1818 int ret;
1819
1820 ret = ram_save_block(f);
1821 bytes_transferred += ret * TARGET_PAGE_SIZE;
1822 if (ret == 0) /* no more blocks */
1823 break;
1824 }
1825
1826 bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
1827 bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
1828
1829 /* if we haven't transferred anything this round, force expected_time to a
1830 * a very high value, but without crashing */
1831 if (bwidth == 0)
1832 bwidth = 0.000001;
1833
1834 /* try transferring iterative blocks of memory */
1835 if (stage == 3) {
1836 /* flush all remaining blocks regardless of rate limiting */
1837 while (ram_save_block(f) != 0) {
1838 bytes_transferred += TARGET_PAGE_SIZE;
1839 }
1840 cpu_physical_memory_set_dirty_tracking(0);
1841 }
1842
1843 qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
1844
1845 expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
1846
1847 return (stage == 2) && (expected_time <= migrate_max_downtime());
1848}
1849
1850static int ram_load(QEMUFile *f, void *opaque, int version_id)
1851{
1852 ram_addr_t addr;
1853 int flags;
1854
1855 if (version_id != 3)
1856 return -EINVAL;
1857
1858 do {
1859 addr = qemu_get_be64(f);
1860
1861 flags = addr & ~TARGET_PAGE_MASK;
1862 addr &= TARGET_PAGE_MASK;
1863
1864 if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
1865 if (addr != last_ram_offset)
1866 return -EINVAL;
1867 }
1868
1869 if (flags & RAM_SAVE_FLAG_COMPRESS) {
1870 uint8_t ch = qemu_get_byte(f);
1871 memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
1872#ifndef _WIN32
1873 if (ch == 0 &&
1874 (!kvm_enabled() || kvm_has_sync_mmu())) {
1875 madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
1876 }
1877#endif
1878 } else if (flags & RAM_SAVE_FLAG_PAGE) {
1879 qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
1880 }
1881 if (qemu_file_has_error(f)) {
1882 return -EIO;
1883 }
1884 } while (!(flags & RAM_SAVE_FLAG_EOS));
1885
1886 return 0;
1887}
1888
1889void qemu_service_io(void)
1890{
1891 qemu_notify_event();
1892}
1893
1894/***********************************************************/
1895/* machine registration */
1896
1897static QEMUMachine *first_machine = NULL;
1898QEMUMachine *current_machine = NULL;
1899
1900int qemu_register_machine(QEMUMachine *m)
1901{
1902 QEMUMachine **pm;
1903 pm = &first_machine;
1904 while (*pm != NULL)
1905 pm = &(*pm)->next;
1906 m->next = NULL;
1907 *pm = m;
1908 return 0;
1909}
1910
1911static QEMUMachine *find_machine(const char *name)
1912{
1913 QEMUMachine *m;
1914
1915 for(m = first_machine; m != NULL; m = m->next) {
1916 if (!strcmp(m->name, name))
1917 return m;
1918 if (m->alias && !strcmp(m->alias, name))
1919 return m;
1920 }
1921 return NULL;
1922}
1923
1924static QEMUMachine *find_default_machine(void)
1925{
1926 QEMUMachine *m;
1927
1928 for(m = first_machine; m != NULL; m = m->next) {
1929 if (m->is_default) {
1930 return m;
1931 }
1932 }
1933 return NULL;
1934}
1935
1936/***********************************************************/
1937/* main execution loop */
1938
1939static void gui_update(void *opaque)
1940{
1941 uint64_t interval = GUI_REFRESH_INTERVAL;
1942 DisplayState *ds = opaque;
1943 DisplayChangeListener *dcl = ds->listeners;
1944
1945 qemu_flush_coalesced_mmio_buffer();
1946 dpy_refresh(ds);
1947
1948 while (dcl != NULL) {
1949 if (dcl->gui_timer_interval &&
1950 dcl->gui_timer_interval < interval)
1951 interval = dcl->gui_timer_interval;
1952 dcl = dcl->next;
1953 }
1954 qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
1955}
1956
1957static void nographic_update(void *opaque)
1958{
1959 uint64_t interval = GUI_REFRESH_INTERVAL;
1960
1961 qemu_flush_coalesced_mmio_buffer();
1962 qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
1963}
1964
1965void cpu_synchronize_all_states(void)
1966{
1967 CPUState *cpu;
1968
1969 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1970 cpu_synchronize_state(cpu);
1971 }
1972}
1973
1974void cpu_synchronize_all_post_reset(void)
1975{
1976 CPUState *cpu;
1977
1978 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1979 cpu_synchronize_post_reset(cpu);
1980 }
1981}
1982
1983void cpu_synchronize_all_post_init(void)
1984{
1985 CPUState *cpu;
1986
1987 for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
1988 cpu_synchronize_post_init(cpu);
1989 }
1990}
1991
1992struct vm_change_state_entry {
1993 VMChangeStateHandler *cb;
1994 void *opaque;
1995 QLIST_ENTRY (vm_change_state_entry) entries;
1996};
1997
1998static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
1999
2000VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
2001 void *opaque)
2002{
2003 VMChangeStateEntry *e;
2004
2005 e = qemu_mallocz(sizeof (*e));
2006
2007 e->cb = cb;
2008 e->opaque = opaque;
2009 QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
2010 return e;
2011}
2012
2013void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
2014{
2015 QLIST_REMOVE (e, entries);
2016 qemu_free (e);
2017}
2018
2019static void vm_state_notify(int running, int reason)
2020{
2021 VMChangeStateEntry *e;
2022
2023 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
2024 e->cb(e->opaque, running, reason);
2025 }
2026}
2027
2028static void resume_all_vcpus(void);
2029static void pause_all_vcpus(void);
2030
2031void vm_start(void)
2032{
2033 if (!vm_running) {
2034 cpu_enable_ticks();
2035 vm_running = 1;
2036 vm_state_notify(1, 0);
2037 resume_all_vcpus();
2038 }
2039}
2040
2041/* reset/shutdown handler */
2042
2043typedef struct QEMUResetEntry {
2044 QTAILQ_ENTRY(QEMUResetEntry) entry;
2045 QEMUResetHandler *func;
2046 void *opaque;
2047} QEMUResetEntry;
2048
2049static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
2050 QTAILQ_HEAD_INITIALIZER(reset_handlers);
2051static int reset_requested;
2052static int shutdown_requested;
2053static int powerdown_requested;
2054static int debug_requested;
2055static int vmstop_requested;
2056
2057int qemu_shutdown_requested(void)
2058{
2059 int r = shutdown_requested;
2060 shutdown_requested = 0;
2061 return r;
2062}
2063
2064int qemu_reset_requested(void)
2065{
2066 int r = reset_requested;
2067 reset_requested = 0;
2068 return r;
2069}
2070
2071int qemu_powerdown_requested(void)
2072{
2073 int r = powerdown_requested;
2074 powerdown_requested = 0;
2075 return r;
2076}
2077
2078static int qemu_debug_requested(void)
2079{
2080 int r = debug_requested;
2081 debug_requested = 0;
2082 return r;
2083}
2084
2085static int qemu_vmstop_requested(void)
2086{
2087 int r = vmstop_requested;
2088 vmstop_requested = 0;
2089 return r;
2090}
2091
2092static void do_vm_stop(int reason)
2093{
2094 if (vm_running) {
2095 cpu_disable_ticks();
2096 vm_running = 0;
2097 pause_all_vcpus();
2098 vm_state_notify(0, reason);
2099 monitor_protocol_event(QEVENT_STOP, NULL);
2100 }
2101}
2102
2103void qemu_register_reset(QEMUResetHandler *func, void *opaque)
2104{
2105 QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
2106
2107 re->func = func;
2108 re->opaque = opaque;
2109 QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
2110}
2111
2112void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
2113{
2114 QEMUResetEntry *re;
2115
2116 QTAILQ_FOREACH(re, &reset_handlers, entry) {
2117 if (re->func == func && re->opaque == opaque) {
2118 QTAILQ_REMOVE(&reset_handlers, re, entry);
2119 qemu_free(re);
2120 return;
2121 }
2122 }
2123}
2124
2125void qemu_system_reset(void)
2126{
2127 QEMUResetEntry *re, *nre;
2128
2129 /* reset all devices */
2130 QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
2131 re->func(re->opaque);
2132 }
2133 monitor_protocol_event(QEVENT_RESET, NULL);
2134 cpu_synchronize_all_post_reset();
2135}
2136
2137void qemu_system_reset_request(void)
2138{
2139 if (no_reboot) {
2140 shutdown_requested = 1;
2141 } else {
2142 reset_requested = 1;
2143 }
2144 qemu_notify_event();
2145}
2146
2147void qemu_system_shutdown_request(void)
2148{
2149 shutdown_requested = 1;
2150 qemu_notify_event();
2151}
2152
2153void qemu_system_powerdown_request(void)
2154{
2155 powerdown_requested = 1;
2156 qemu_notify_event();
2157}
2158
2159static int cpu_can_run(CPUState *env)
2160{
2161 if (env->stop)
2162 return 0;
2163 if (env->stopped)
2164 return 0;
2165 if (!vm_running)
2166 return 0;
2167 return 1;
2168}
2169
2170static int cpu_has_work(CPUState *env)
2171{
2172 if (env->stop)
2173 return 1;
2174 if (env->stopped)
2175 return 0;
2176 if (!env->halted)
2177 return 1;
2178 if (qemu_cpu_has_work(env))
2179 return 1;
2180 return 0;
2181}
2182
2183static int tcg_has_work(void)
2184{
2185 CPUState *env;
2186
2187 for (env = first_cpu; env != NULL; env = env->next_cpu)
2188 if (cpu_has_work(env))
2189 return 1;
2190 return 0;
2191}
2192
2193#ifndef _WIN32
2194static int io_thread_fd = -1;
2195
2196static void qemu_event_increment(void)
2197{
2198 /* Write 8 bytes to be compatible with eventfd. */
2199 static uint64_t val = 1;
2200 ssize_t ret;
2201
2202 if (io_thread_fd == -1)
2203 return;
2204
2205 do {
2206 ret = write(io_thread_fd, &val, sizeof(val));
2207 } while (ret < 0 && errno == EINTR);
2208
2209 /* EAGAIN is fine, a read must be pending. */
2210 if (ret < 0 && errno != EAGAIN) {
2211 fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
2212 strerror(errno));
2213 exit (1);
2214 }
2215}
2216
2217static void qemu_event_read(void *opaque)
2218{
2219 int fd = (unsigned long)opaque;
2220 ssize_t len;
2221 char buffer[512];
2222
2223 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
2224 do {
2225 len = read(fd, buffer, sizeof(buffer));
2226 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
2227}
2228
2229static int qemu_event_init(void)
2230{
2231 int err;
2232 int fds[2];
2233
2234 err = qemu_eventfd(fds);
2235 if (err == -1)
2236 return -errno;
2237
2238 err = fcntl_setfl(fds[0], O_NONBLOCK);
2239 if (err < 0)
2240 goto fail;
2241
2242 err = fcntl_setfl(fds[1], O_NONBLOCK);
2243 if (err < 0)
2244 goto fail;
2245
2246 qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
2247 (void *)(unsigned long)fds[0]);
2248
2249 io_thread_fd = fds[1];
2250 return 0;
2251
2252fail:
2253 close(fds[0]);
2254 close(fds[1]);
2255 return err;
2256}
2257#else
2258HANDLE qemu_event_handle;
2259
2260static void dummy_event_handler(void *opaque)
2261{
2262}
2263
2264static int qemu_event_init(void)
2265{
2266 qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
2267 if (!qemu_event_handle) {
2268 fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
2269 return -1;
2270 }
2271 qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
2272 return 0;
2273}
2274
2275static void qemu_event_increment(void)
2276{
2277 if (!SetEvent(qemu_event_handle)) {
2278 fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
2279 GetLastError());
2280 exit (1);
2281 }
2282}
2283#endif
2284
2285#ifndef CONFIG_IOTHREAD
2286static int qemu_init_main_loop(void)
2287{
2288 return qemu_event_init();
2289}
2290
2291void qemu_init_vcpu(void *_env)
2292{
2293 CPUState *env = _env;
2294
2295 env->nr_cores = smp_cores;
2296 env->nr_threads = smp_threads;
2297 if (kvm_enabled())
2298 kvm_init_vcpu(env);
2299 return;
2300}
2301
2302int qemu_cpu_self(void *env)
2303{
2304 return 1;
2305}
2306
2307static void resume_all_vcpus(void)
2308{
2309}
2310
2311static void pause_all_vcpus(void)
2312{
2313}
2314
2315void qemu_cpu_kick(void *env)
2316{
2317 return;
2318}
2319
2320void qemu_notify_event(void)
2321{
2322 CPUState *env = cpu_single_env;
2323
2324 qemu_event_increment ();
2325 if (env) {
2326 cpu_exit(env);
2327 }
2328 if (next_cpu && env != next_cpu) {
2329 cpu_exit(next_cpu);
2330 }
2331}
2332
2333void qemu_mutex_lock_iothread(void) {}
2334void qemu_mutex_unlock_iothread(void) {}
2335
2336void vm_stop(int reason)
2337{
2338 do_vm_stop(reason);
2339}
2340
2341#else /* CONFIG_IOTHREAD */
2342
2343#include "qemu-thread.h"
2344
2345QemuMutex qemu_global_mutex;
2346static QemuMutex qemu_fair_mutex;
2347
2348static QemuThread io_thread;
2349
2350static QemuThread *tcg_cpu_thread;
2351static QemuCond *tcg_halt_cond;
2352
2353static int qemu_system_ready;
2354/* cpu creation */
2355static QemuCond qemu_cpu_cond;
2356/* system init */
2357static QemuCond qemu_system_cond;
2358static QemuCond qemu_pause_cond;
2359
2360static void tcg_block_io_signals(void);
2361static void kvm_block_io_signals(CPUState *env);
2362static void unblock_io_signals(void);
2363
2364static int qemu_init_main_loop(void)
2365{
2366 int ret;
2367
2368 ret = qemu_event_init();
2369 if (ret)
2370 return ret;
2371
2372 qemu_cond_init(&qemu_pause_cond);
2373 qemu_mutex_init(&qemu_fair_mutex);
2374 qemu_mutex_init(&qemu_global_mutex);
2375 qemu_mutex_lock(&qemu_global_mutex);
2376
2377 unblock_io_signals();
2378 qemu_thread_self(&io_thread);
2379
2380 return 0;
2381}
2382
2383static void qemu_wait_io_event_common(CPUState *env)
2384{
2385 if (env->stop) {
2386 env->stop = 0;
2387 env->stopped = 1;
2388 qemu_cond_signal(&qemu_pause_cond);
2389 }
2390}
2391
2392static void qemu_wait_io_event(CPUState *env)
2393{
2394 while (!tcg_has_work())
2395 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2396
2397 qemu_mutex_unlock(&qemu_global_mutex);
2398
2399 /*
2400 * Users of qemu_global_mutex can be starved, having no chance
2401 * to acquire it since this path will get to it first.
2402 * So use another lock to provide fairness.
2403 */
2404 qemu_mutex_lock(&qemu_fair_mutex);
2405 qemu_mutex_unlock(&qemu_fair_mutex);
2406
2407 qemu_mutex_lock(&qemu_global_mutex);
2408 qemu_wait_io_event_common(env);
2409}
2410
2411static void qemu_kvm_eat_signal(CPUState *env, int timeout)
2412{
2413 struct timespec ts;
2414 int r, e;
2415 siginfo_t siginfo;
2416 sigset_t waitset;
2417
2418 ts.tv_sec = timeout / 1000;
2419 ts.tv_nsec = (timeout % 1000) * 1000000;
2420
2421 sigemptyset(&waitset);
2422 sigaddset(&waitset, SIG_IPI);
2423
2424 qemu_mutex_unlock(&qemu_global_mutex);
2425 r = sigtimedwait(&waitset, &siginfo, &ts);
2426 e = errno;
2427 qemu_mutex_lock(&qemu_global_mutex);
2428
2429 if (r == -1 && !(e == EAGAIN || e == EINTR)) {
2430 fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
2431 exit(1);
2432 }
2433}
2434
2435static void qemu_kvm_wait_io_event(CPUState *env)
2436{
2437 while (!cpu_has_work(env))
2438 qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
2439
2440 qemu_kvm_eat_signal(env, 0);
2441 qemu_wait_io_event_common(env);
2442}
2443
2444static int qemu_cpu_exec(CPUState *env);
2445
2446static void *kvm_cpu_thread_fn(void *arg)
2447{
2448 CPUState *env = arg;
2449
2450 qemu_thread_self(env->thread);
2451 if (kvm_enabled())
2452 kvm_init_vcpu(env);
2453
2454 kvm_block_io_signals(env);
2455
2456 /* signal CPU creation */
2457 qemu_mutex_lock(&qemu_global_mutex);
2458 env->created = 1;
2459 qemu_cond_signal(&qemu_cpu_cond);
2460
2461 /* and wait for machine initialization */
2462 while (!qemu_system_ready)
2463 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2464
2465 while (1) {
2466 if (cpu_can_run(env))
2467 qemu_cpu_exec(env);
2468 qemu_kvm_wait_io_event(env);
2469 }
2470
2471 return NULL;
2472}
2473
2474static bool tcg_cpu_exec(void);
2475
2476static void *tcg_cpu_thread_fn(void *arg)
2477{
2478 CPUState *env = arg;
2479
2480 tcg_block_io_signals();
2481 qemu_thread_self(env->thread);
2482
2483 /* signal CPU creation */
2484 qemu_mutex_lock(&qemu_global_mutex);
2485 for (env = first_cpu; env != NULL; env = env->next_cpu)
2486 env->created = 1;
2487 qemu_cond_signal(&qemu_cpu_cond);
2488
2489 /* and wait for machine initialization */
2490 while (!qemu_system_ready)
2491 qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
2492
2493 while (1) {
2494 tcg_cpu_exec();
2495 qemu_wait_io_event(cur_cpu);
2496 }
2497
2498 return NULL;
2499}
2500
2501void qemu_cpu_kick(void *_env)
2502{
2503 CPUState *env = _env;
2504 qemu_cond_broadcast(env->halt_cond);
2505 if (kvm_enabled())
2506 qemu_thread_signal(env->thread, SIG_IPI);
2507}
2508
2509int qemu_cpu_self(void *_env)
2510{
2511 CPUState *env = _env;
2512 QemuThread this;
2513
2514 qemu_thread_self(&this);
2515
2516 return qemu_thread_equal(&this, env->thread);
2517}
2518
2519static void cpu_signal(int sig)
2520{
2521 if (cpu_single_env)
2522 cpu_exit(cpu_single_env);
2523}
2524
2525static void tcg_block_io_signals(void)
2526{
2527 sigset_t set;
2528 struct sigaction sigact;
2529
2530 sigemptyset(&set);
2531 sigaddset(&set, SIGUSR2);
2532 sigaddset(&set, SIGIO);
2533 sigaddset(&set, SIGALRM);
2534 sigaddset(&set, SIGCHLD);
2535 pthread_sigmask(SIG_BLOCK, &set, NULL);
2536
2537 sigemptyset(&set);
2538 sigaddset(&set, SIG_IPI);
2539 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2540
2541 memset(&sigact, 0, sizeof(sigact));
2542 sigact.sa_handler = cpu_signal;
2543 sigaction(SIG_IPI, &sigact, NULL);
2544}
2545
2546static void dummy_signal(int sig)
2547{
2548}
2549
2550static void kvm_block_io_signals(CPUState *env)
2551{
2552 int r;
2553 sigset_t set;
2554 struct sigaction sigact;
2555
2556 sigemptyset(&set);
2557 sigaddset(&set, SIGUSR2);
2558 sigaddset(&set, SIGIO);
2559 sigaddset(&set, SIGALRM);
2560 sigaddset(&set, SIGCHLD);
2561 sigaddset(&set, SIG_IPI);
2562 pthread_sigmask(SIG_BLOCK, &set, NULL);
2563
2564 pthread_sigmask(SIG_BLOCK, NULL, &set);
2565 sigdelset(&set, SIG_IPI);
2566
2567 memset(&sigact, 0, sizeof(sigact));
2568 sigact.sa_handler = dummy_signal;
2569 sigaction(SIG_IPI, &sigact, NULL);
2570
2571 r = kvm_set_signal_mask(env, &set);
2572 if (r) {
2573 fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
2574 exit(1);
2575 }
2576}
2577
2578static void unblock_io_signals(void)
2579{
2580 sigset_t set;
2581
2582 sigemptyset(&set);
2583 sigaddset(&set, SIGUSR2);
2584 sigaddset(&set, SIGIO);
2585 sigaddset(&set, SIGALRM);
2586 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
2587
2588 sigemptyset(&set);
2589 sigaddset(&set, SIG_IPI);
2590 pthread_sigmask(SIG_BLOCK, &set, NULL);
2591}
2592
2593static void qemu_signal_lock(unsigned int msecs)
2594{
2595 qemu_mutex_lock(&qemu_fair_mutex);
2596
2597 while (qemu_mutex_trylock(&qemu_global_mutex)) {
2598 qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
2599 if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
2600 break;
2601 }
2602 qemu_mutex_unlock(&qemu_fair_mutex);
2603}
2604
2605void qemu_mutex_lock_iothread(void)
2606{
2607 if (kvm_enabled()) {
2608 qemu_mutex_lock(&qemu_fair_mutex);
2609 qemu_mutex_lock(&qemu_global_mutex);
2610 qemu_mutex_unlock(&qemu_fair_mutex);
2611 } else
2612 qemu_signal_lock(100);
2613}
2614
2615void qemu_mutex_unlock_iothread(void)
2616{
2617 qemu_mutex_unlock(&qemu_global_mutex);
2618}
2619
2620static int all_vcpus_paused(void)
2621{
2622 CPUState *penv = first_cpu;
2623
2624 while (penv) {
2625 if (!penv->stopped)
2626 return 0;
2627 penv = (CPUState *)penv->next_cpu;
2628 }
2629
2630 return 1;
2631}
2632
2633static void pause_all_vcpus(void)
2634{
2635 CPUState *penv = first_cpu;
2636
2637 while (penv) {
2638 penv->stop = 1;
2639 qemu_thread_signal(penv->thread, SIG_IPI);
2640 qemu_cpu_kick(penv);
2641 penv = (CPUState *)penv->next_cpu;
2642 }
2643
2644 while (!all_vcpus_paused()) {
2645 qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
2646 penv = first_cpu;
2647 while (penv) {
2648 qemu_thread_signal(penv->thread, SIG_IPI);
2649 penv = (CPUState *)penv->next_cpu;
2650 }
2651 }
2652}
2653
2654static void resume_all_vcpus(void)
2655{
2656 CPUState *penv = first_cpu;
2657
2658 while (penv) {
2659 penv->stop = 0;
2660 penv->stopped = 0;
2661 qemu_thread_signal(penv->thread, SIG_IPI);
2662 qemu_cpu_kick(penv);
2663 penv = (CPUState *)penv->next_cpu;
2664 }
2665}
2666
2667static void tcg_init_vcpu(void *_env)
2668{
2669 CPUState *env = _env;
2670 /* share a single thread for all cpus with TCG */
2671 if (!tcg_cpu_thread) {
2672 env->thread = qemu_mallocz(sizeof(QemuThread));
2673 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2674 qemu_cond_init(env->halt_cond);
2675 qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
2676 while (env->created == 0)
2677 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2678 tcg_cpu_thread = env->thread;
2679 tcg_halt_cond = env->halt_cond;
2680 } else {
2681 env->thread = tcg_cpu_thread;
2682 env->halt_cond = tcg_halt_cond;
2683 }
2684}
2685
2686static void kvm_start_vcpu(CPUState *env)
2687{
2688 env->thread = qemu_mallocz(sizeof(QemuThread));
2689 env->halt_cond = qemu_mallocz(sizeof(QemuCond));
2690 qemu_cond_init(env->halt_cond);
2691 qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
2692 while (env->created == 0)
2693 qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
2694}
2695
2696void qemu_init_vcpu(void *_env)
2697{
2698 CPUState *env = _env;
2699
2700 env->nr_cores = smp_cores;
2701 env->nr_threads = smp_threads;
2702 if (kvm_enabled())
2703 kvm_start_vcpu(env);
2704 else
2705 tcg_init_vcpu(env);
2706}
2707
2708void qemu_notify_event(void)
2709{
2710 qemu_event_increment();
2711}
2712
2713static void qemu_system_vmstop_request(int reason)
2714{
2715 vmstop_requested = reason;
2716 qemu_notify_event();
2717}
2718
2719void vm_stop(int reason)
2720{
2721 QemuThread me;
2722 qemu_thread_self(&me);
2723
2724 if (!qemu_thread_equal(&me, &io_thread)) {
2725 qemu_system_vmstop_request(reason);
2726 /*
2727 * FIXME: should not return to device code in case
2728 * vm_stop() has been requested.
2729 */
2730 if (cpu_single_env) {
2731 cpu_exit(cpu_single_env);
2732 cpu_single_env->stop = 1;
2733 }
2734 return;
2735 }
2736 do_vm_stop(reason);
2737}
2738
2739#endif
2740
2741
2742#ifdef _WIN32
2743static void host_main_loop_wait(int *timeout)
2744{
2745 int ret, ret2, i;
2746 PollingEntry *pe;
2747
2748
2749 /* XXX: need to suppress polling by better using win32 events */
2750 ret = 0;
2751 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
2752 ret |= pe->func(pe->opaque);
2753 }
2754 if (ret == 0) {
2755 int err;
2756 WaitObjects *w = &wait_objects;
2757
2758 ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
2759 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
2760 if (w->func[ret - WAIT_OBJECT_0])
2761 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
2762
2763 /* Check for additional signaled events */
2764 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
2765
2766 /* Check if event is signaled */
2767 ret2 = WaitForSingleObject(w->events[i], 0);
2768 if(ret2 == WAIT_OBJECT_0) {
2769 if (w->func[i])
2770 w->func[i](w->opaque[i]);
2771 } else if (ret2 == WAIT_TIMEOUT) {
2772 } else {
2773 err = GetLastError();
2774 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
2775 }
2776 }
2777 } else if (ret == WAIT_TIMEOUT) {
2778 } else {
2779 err = GetLastError();
2780 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
2781 }
2782 }
2783
2784 *timeout = 0;
2785}
2786#else
2787static void host_main_loop_wait(int *timeout)
2788{
2789}
2790#endif
2791
2792void main_loop_wait(int nonblocking)
2793{
2794 IOHandlerRecord *ioh;
2795 fd_set rfds, wfds, xfds;
2796 int ret, nfds;
2797 struct timeval tv;
2798 int timeout;
2799
2800 if (nonblocking)
2801 timeout = 0;
2802 else {
2803 timeout = qemu_calculate_timeout();
2804 qemu_bh_update_timeout(&timeout);
2805 }
2806
2807 host_main_loop_wait(&timeout);
2808
2809 /* poll any events */
2810 /* XXX: separate device handlers from system ones */
2811 nfds = -1;
2812 FD_ZERO(&rfds);
2813 FD_ZERO(&wfds);
2814 FD_ZERO(&xfds);
2815 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2816 if (ioh->deleted)
2817 continue;
2818 if (ioh->fd_read &&
2819 (!ioh->fd_read_poll ||
2820 ioh->fd_read_poll(ioh->opaque) != 0)) {
2821 FD_SET(ioh->fd, &rfds);
2822 if (ioh->fd > nfds)
2823 nfds = ioh->fd;
2824 }
2825 if (ioh->fd_write) {
2826 FD_SET(ioh->fd, &wfds);
2827 if (ioh->fd > nfds)
2828 nfds = ioh->fd;
2829 }
2830 }
2831
2832 tv.tv_sec = timeout / 1000;
2833 tv.tv_usec = (timeout % 1000) * 1000;
2834
2835 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
2836
2837 qemu_mutex_unlock_iothread();
2838 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
2839 qemu_mutex_lock_iothread();
2840 if (ret > 0) {
2841 IOHandlerRecord **pioh;
2842
2843 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2844 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
2845 ioh->fd_read(ioh->opaque);
2846 }
2847 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
2848 ioh->fd_write(ioh->opaque);
2849 }
2850 }
2851
2852 /* remove deleted IO handlers */
2853 pioh = &first_io_handler;
2854 while (*pioh) {
2855 ioh = *pioh;
2856 if (ioh->deleted) {
2857 *pioh = ioh->next;
2858 qemu_free(ioh);
2859 } else
2860 pioh = &ioh->next;
2861 }
2862 }
2863
2864 slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
2865
2866 qemu_run_all_timers();
2867
2868 /* Check bottom-halves last in case any of the earlier events triggered
2869 them. */
2870 qemu_bh_poll();
2871
2872}
2873
2874static int qemu_cpu_exec(CPUState *env)
2875{
2876 int ret;
2877#ifdef CONFIG_PROFILER
2878 int64_t ti;
2879#endif
2880
2881#ifdef CONFIG_PROFILER
2882 ti = profile_getclock();
2883#endif
2884 if (use_icount) {
2885 int64_t count;
2886 int decr;
2887 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
2888 env->icount_decr.u16.low = 0;
2889 env->icount_extra = 0;
2890 count = qemu_icount_round (qemu_next_deadline());
2891 qemu_icount += count;
2892 decr = (count > 0xffff) ? 0xffff : count;
2893 count -= decr;
2894 env->icount_decr.u16.low = decr;
2895 env->icount_extra = count;
2896 }
2897 ret = cpu_exec(env);
2898#ifdef CONFIG_PROFILER
2899 qemu_time += profile_getclock() - ti;
2900#endif
2901 if (use_icount) {
2902 /* Fold pending instructions back into the
2903 instruction counter, and clear the interrupt flag. */
2904 qemu_icount -= (env->icount_decr.u16.low
2905 + env->icount_extra);
2906 env->icount_decr.u32 = 0;
2907 env->icount_extra = 0;
2908 }
2909 return ret;
2910}
2911
2912static bool tcg_cpu_exec(void)
2913{
2914 int ret = 0;
2915
2916 if (next_cpu == NULL)
2917 next_cpu = first_cpu;
2918 for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
2919 CPUState *env = cur_cpu = next_cpu;
2920
2921 qemu_clock_enable(vm_clock,
2922 (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
2923
2924 if (qemu_alarm_pending())
2925 break;
2926 if (cpu_can_run(env))
2927 ret = qemu_cpu_exec(env);
2928 else if (env->stop)
2929 break;
2930
2931 if (ret == EXCP_DEBUG) {
2932 gdb_set_stop_cpu(env);
2933 debug_requested = 1;
2934 break;
2935 }
2936 }
2937 return tcg_has_work();
2938}
2939
2940static int vm_can_run(void)
2941{
2942 if (powerdown_requested)
2943 return 0;
2944 if (reset_requested)
2945 return 0;
2946 if (shutdown_requested)
2947 return 0;
2948 if (debug_requested)
2949 return 0;
2950 return 1;
2951}
2952
2953qemu_irq qemu_system_powerdown;
2954
2955static void main_loop(void)
2956{
2957 int r;
2958
2959#ifdef CONFIG_IOTHREAD
2960 qemu_system_ready = 1;
2961 qemu_cond_broadcast(&qemu_system_cond);
2962#endif
2963
2964 for (;;) {
2965 do {
2966 bool nonblocking = false;
2967#ifdef CONFIG_PROFILER
2968 int64_t ti;
2969#endif
2970#ifndef CONFIG_IOTHREAD
2971 nonblocking = tcg_cpu_exec();
2972#endif
2973#ifdef CONFIG_PROFILER
2974 ti = profile_getclock();
2975#endif
2976 main_loop_wait(nonblocking);
2977#ifdef CONFIG_PROFILER
2978 dev_time += profile_getclock() - ti;
2979#endif
2980 } while (vm_can_run());
2981
2982 if (qemu_debug_requested()) {
2983 vm_stop(EXCP_DEBUG);
2984 }
2985 if (qemu_shutdown_requested()) {
2986 monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
2987 if (no_shutdown) {
2988 vm_stop(0);
2989 no_shutdown = 0;
2990 } else
2991 break;
2992 }
2993 if (qemu_reset_requested()) {
2994 pause_all_vcpus();
2995 qemu_system_reset();
2996 resume_all_vcpus();
2997 }
2998 if (qemu_powerdown_requested()) {
2999 monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3000 qemu_irq_raise(qemu_system_powerdown);
3001 }
3002 if ((r = qemu_vmstop_requested())) {
3003 vm_stop(r);
3004 }
3005 }
3006 pause_all_vcpus();
3007}
3008
3009static void version(void)
3010{
3011 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3012}
3013
3014static void help(int exitcode)
3015{
3016 const char *options_help =
3017#define DEF(option, opt_arg, opt_enum, opt_help) \
3018 opt_help
3019#define DEFHEADING(text) stringify(text) "\n"
3020#include "qemu-options.h"
3021#undef DEF
3022#undef DEFHEADING
3023#undef GEN_DOCS
3024 ;
3025 version();
3026 printf("usage: %s [options] [disk_image]\n"
3027 "\n"
3028 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3029 "\n"
3030 "%s\n"
3031 "During emulation, the following keys are useful:\n"
3032 "ctrl-alt-f toggle full screen\n"
3033 "ctrl-alt-n switch to virtual console 'n'\n"
3034 "ctrl-alt toggle mouse and keyboard grab\n"
3035 "\n"
3036 "When using -nographic, press 'ctrl-a h' to get some help.\n",
3037 "qemu",
3038 options_help);
3039 exit(exitcode);
3040}
3041
3042#define HAS_ARG 0x0001
3043
3044enum {
3045#define DEF(option, opt_arg, opt_enum, opt_help) \
3046 opt_enum,
3047#define DEFHEADING(text)
3048#include "qemu-options.h"
3049#undef DEF
3050#undef DEFHEADING
3051#undef GEN_DOCS
3052};
3053
3054typedef struct QEMUOption {
3055 const char *name;
3056 int flags;
3057 int index;
3058} QEMUOption;
3059
3060static const QEMUOption qemu_options[] = {
3061 { "h", 0, QEMU_OPTION_h },
3062#define DEF(option, opt_arg, opt_enum, opt_help) \
3063 { option, opt_arg, opt_enum },
3064#define DEFHEADING(text)
3065#include "qemu-options.h"
3066#undef DEF
3067#undef DEFHEADING
3068#undef GEN_DOCS
3069 { NULL },
3070};
3071
3072#ifdef HAS_AUDIO
3073struct soundhw soundhw[] = {
3074#ifdef HAS_AUDIO_CHOICE
3075#if defined(TARGET_I386) || defined(TARGET_MIPS)
3076 {
3077 "pcspk",
3078 "PC speaker",
3079 0,
3080 1,
3081 { .init_isa = pcspk_audio_init }
3082 },
3083#endif
3084
3085#ifdef CONFIG_SB16
3086 {
3087 "sb16",
3088 "Creative Sound Blaster 16",
3089 0,
3090 1,
3091 { .init_isa = SB16_init }
3092 },
3093#endif
3094
3095#ifdef CONFIG_CS4231A
3096 {
3097 "cs4231a",
3098 "CS4231A",
3099 0,
3100 1,
3101 { .init_isa = cs4231a_init }
3102 },
3103#endif
3104
3105#ifdef CONFIG_ADLIB
3106 {
3107 "adlib",
3108#ifdef HAS_YMF262
3109 "Yamaha YMF262 (OPL3)",
3110#else
3111 "Yamaha YM3812 (OPL2)",
3112#endif
3113 0,
3114 1,
3115 { .init_isa = Adlib_init }
3116 },
3117#endif
3118
3119#ifdef CONFIG_GUS
3120 {
3121 "gus",
3122 "Gravis Ultrasound GF1",
3123 0,
3124 1,
3125 { .init_isa = GUS_init }
3126 },
3127#endif
3128
3129#ifdef CONFIG_AC97
3130 {
3131 "ac97",
3132 "Intel 82801AA AC97 Audio",
3133 0,
3134 0,
3135 { .init_pci = ac97_init }
3136 },
3137#endif
3138
3139#ifdef CONFIG_ES1370
3140 {
3141 "es1370",
3142 "ENSONIQ AudioPCI ES1370",
3143 0,
3144 0,
3145 { .init_pci = es1370_init }
3146 },
3147#endif
3148
3149#endif /* HAS_AUDIO_CHOICE */
3150
3151 { NULL, NULL, 0, 0, { NULL } }
3152};
3153
3154static void select_soundhw (const char *optarg)
3155{
3156 struct soundhw *c;
3157
3158 if (*optarg == '?') {
3159 show_valid_cards:
3160
3161 printf ("Valid sound card names (comma separated):\n");
3162 for (c = soundhw; c->name; ++c) {
3163 printf ("%-11s %s\n", c->name, c->descr);
3164 }
3165 printf ("\n-soundhw all will enable all of the above\n");
3166 exit (*optarg != '?');
3167 }
3168 else {
3169 size_t l;
3170 const char *p;
3171 char *e;
3172 int bad_card = 0;
3173
3174 if (!strcmp (optarg, "all")) {
3175 for (c = soundhw; c->name; ++c) {
3176 c->enabled = 1;
3177 }
3178 return;
3179 }
3180
3181 p = optarg;
3182 while (*p) {
3183 e = strchr (p, ',');
3184 l = !e ? strlen (p) : (size_t) (e - p);
3185
3186 for (c = soundhw; c->name; ++c) {
3187 if (!strncmp (c->name, p, l) && !c->name[l]) {
3188 c->enabled = 1;
3189 break;
3190 }
3191 }
3192
3193 if (!c->name) {
3194 if (l > 80) {
3195 fprintf (stderr,
3196 "Unknown sound card name (too big to show)\n");
3197 }
3198 else {
3199 fprintf (stderr, "Unknown sound card name `%.*s'\n",
3200 (int) l, p);
3201 }
3202 bad_card = 1;
3203 }
3204 p += l + (e != NULL);
3205 }
3206
3207 if (bad_card)
3208 goto show_valid_cards;
3209 }
3210}
3211#endif
3212
3213static void select_vgahw (const char *p)
3214{
3215 const char *opts;
3216
3217 default_vga = 0;
3218 vga_interface_type = VGA_NONE;
3219 if (strstart(p, "std", &opts)) {
3220 vga_interface_type = VGA_STD;
3221 } else if (strstart(p, "cirrus", &opts)) {
3222 vga_interface_type = VGA_CIRRUS;
3223 } else if (strstart(p, "vmware", &opts)) {
3224 vga_interface_type = VGA_VMWARE;
3225 } else if (strstart(p, "xenfb", &opts)) {
3226 vga_interface_type = VGA_XENFB;
3227 } else if (!strstart(p, "none", &opts)) {
3228 invalid_vga:
3229 fprintf(stderr, "Unknown vga type: %s\n", p);
3230 exit(1);
3231 }
3232 while (*opts) {
3233 const char *nextopt;
3234
3235 if (strstart(opts, ",retrace=", &nextopt)) {
3236 opts = nextopt;
3237 if (strstart(opts, "dumb", &nextopt))
3238 vga_retrace_method = VGA_RETRACE_DUMB;
3239 else if (strstart(opts, "precise", &nextopt))
3240 vga_retrace_method = VGA_RETRACE_PRECISE;
3241 else goto invalid_vga;
3242 } else goto invalid_vga;
3243 opts = nextopt;
3244 }
3245}
3246
3247#ifdef TARGET_I386
3248static int balloon_parse(const char *arg)
3249{
3250 QemuOpts *opts;
3251
3252 if (strcmp(arg, "none") == 0) {
3253 return 0;
3254 }
3255
3256 if (!strncmp(arg, "virtio", 6)) {
3257 if (arg[6] == ',') {
3258 /* have params -> parse them */
3259 opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
3260 if (!opts)
3261 return -1;
3262 } else {
3263 /* create empty opts */
3264 opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3265 }
3266 qemu_opt_set(opts, "driver", "virtio-balloon-pci");
3267 return 0;
3268 }
3269
3270 return -1;
3271}
3272#endif
3273
3274#ifdef _WIN32
3275static BOOL WINAPI qemu_ctrl_handler(DWORD type)
3276{
3277 exit(STATUS_CONTROL_C_EXIT);
3278 return TRUE;
3279}
3280#endif
3281
3282int qemu_uuid_parse(const char *str, uint8_t *uuid)
3283{
3284 int ret;
3285
3286 if(strlen(str) != 36)
3287 return -1;
3288
3289 ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
3290 &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
3291 &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
3292
3293 if(ret != 16)
3294 return -1;
3295
3296#ifdef TARGET_I386
3297 smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
3298#endif
3299
3300 return 0;
3301}
3302
3303#ifndef _WIN32
3304
3305static void termsig_handler(int signal)
3306{
3307 qemu_system_shutdown_request();
3308}
3309
3310static void sigchld_handler(int signal)
3311{
3312 waitpid(-1, NULL, WNOHANG);
3313}
3314
3315static void sighandler_setup(void)
3316{
3317 struct sigaction act;
3318
3319 memset(&act, 0, sizeof(act));
3320 act.sa_handler = termsig_handler;
3321 sigaction(SIGINT, &act, NULL);
3322 sigaction(SIGHUP, &act, NULL);
3323 sigaction(SIGTERM, &act, NULL);
3324
3325 act.sa_handler = sigchld_handler;
3326 act.sa_flags = SA_NOCLDSTOP;
3327 sigaction(SIGCHLD, &act, NULL);
3328}
3329
3330#endif
3331
3332#ifdef _WIN32
3333/* Look for support files in the same directory as the executable. */
3334static char *find_datadir(const char *argv0)
3335{
3336 char *p;
3337 char buf[MAX_PATH];
3338 DWORD len;
3339
3340 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
3341 if (len == 0) {
3342 return NULL;
3343 }
3344
3345 buf[len] = 0;
3346 p = buf + len - 1;
3347 while (p != buf && *p != '\\')
3348 p--;
3349 *p = 0;
3350 if (access(buf, R_OK) == 0) {
3351 return qemu_strdup(buf);
3352 }
3353 return NULL;
3354}
3355#else /* !_WIN32 */
3356
3357/* Find a likely location for support files using the location of the binary.
3358 For installed binaries this will be "$bindir/../share/qemu". When
3359 running from the build tree this will be "$bindir/../pc-bios". */
3360#define SHARE_SUFFIX "/share/qemu"
3361#define BUILD_SUFFIX "/pc-bios"
3362static char *find_datadir(const char *argv0)
3363{
3364 char *dir;
3365 char *p = NULL;
3366 char *res;
3367 char buf[PATH_MAX];
3368 size_t max_len;
3369
3370#if defined(__linux__)
3371 {
3372 int len;
3373 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
3374 if (len > 0) {
3375 buf[len] = 0;
3376 p = buf;
3377 }
3378 }
3379#elif defined(__FreeBSD__)
3380 {
3381 int len;
3382 len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
3383 if (len > 0) {
3384 buf[len] = 0;
3385 p = buf;
3386 }
3387 }
3388#endif
3389 /* If we don't have any way of figuring out the actual executable
3390 location then try argv[0]. */
3391 if (!p) {
3392 p = realpath(argv0, buf);
3393 if (!p) {
3394 return NULL;
3395 }
3396 }
3397 dir = dirname(p);
3398 dir = dirname(dir);
3399
3400 max_len = strlen(dir) +
3401 MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
3402 res = qemu_mallocz(max_len);
3403 snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
3404 if (access(res, R_OK)) {
3405 snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
3406 if (access(res, R_OK)) {
3407 qemu_free(res);
3408 res = NULL;
3409 }
3410 }
3411
3412 return res;
3413}
3414#undef SHARE_SUFFIX
3415#undef BUILD_SUFFIX
3416#endif
3417
3418char *qemu_find_file(int type, const char *name)
3419{
3420 int len;
3421 const char *subdir;
3422 char *buf;
3423
3424 /* If name contains path separators then try it as a straight path. */
3425 if ((strchr(name, '/') || strchr(name, '\\'))
3426 && access(name, R_OK) == 0) {
3427 return qemu_strdup(name);
3428 }
3429 switch (type) {
3430 case QEMU_FILE_TYPE_BIOS:
3431 subdir = "";
3432 break;
3433 case QEMU_FILE_TYPE_KEYMAP:
3434 subdir = "keymaps/";
3435 break;
3436 default:
3437 abort();
3438 }
3439 len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
3440 buf = qemu_mallocz(len);
3441 snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
3442 if (access(buf, R_OK)) {
3443 qemu_free(buf);
3444 return NULL;
3445 }
3446 return buf;
3447}
3448
3449static int device_help_func(QemuOpts *opts, void *opaque)
3450{
3451 return qdev_device_help(opts);
3452}
3453
3454static int device_init_func(QemuOpts *opts, void *opaque)
3455{
3456 DeviceState *dev;
3457
3458 dev = qdev_device_add(opts);
3459 if (!dev)
3460 return -1;
3461 return 0;
3462}
3463
3464static int chardev_init_func(QemuOpts *opts, void *opaque)
3465{
3466 CharDriverState *chr;
3467
3468 chr = qemu_chr_open_opts(opts, NULL);
3469 if (!chr)
3470 return -1;
3471 return 0;
3472}
3473
3474static int mon_init_func(QemuOpts *opts, void *opaque)
3475{
3476 CharDriverState *chr;
3477 const char *chardev;
3478 const char *mode;
3479 int flags;
3480
3481 mode = qemu_opt_get(opts, "mode");
3482 if (mode == NULL) {
3483 mode = "readline";
3484 }
3485 if (strcmp(mode, "readline") == 0) {
3486 flags = MONITOR_USE_READLINE;
3487 } else if (strcmp(mode, "control") == 0) {
3488 flags = MONITOR_USE_CONTROL;
3489 } else {
3490 fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
3491 exit(1);
3492 }
3493
3494 if (qemu_opt_get_bool(opts, "default", 0))
3495 flags |= MONITOR_IS_DEFAULT;
3496
3497 chardev = qemu_opt_get(opts, "chardev");
3498 chr = qemu_chr_find(chardev);
3499 if (chr == NULL) {
3500 fprintf(stderr, "chardev \"%s\" not found\n", chardev);
3501 exit(1);
3502 }
3503
3504 monitor_init(chr, flags);
3505 return 0;
3506}
3507
3508static void monitor_parse(const char *optarg, const char *mode)
3509{
3510 static int monitor_device_index = 0;
3511 QemuOpts *opts;
3512 const char *p;
3513 char label[32];
3514 int def = 0;
3515
3516 if (strstart(optarg, "chardev:", &p)) {
3517 snprintf(label, sizeof(label), "%s", p);
3518 } else {
3519 if (monitor_device_index) {
3520 snprintf(label, sizeof(label), "monitor%d",
3521 monitor_device_index);
3522 } else {
3523 snprintf(label, sizeof(label), "monitor");
3524 def = 1;
3525 }
3526 opts = qemu_chr_parse_compat(label, optarg);
3527 if (!opts) {
3528 fprintf(stderr, "parse error: %s\n", optarg);
3529 exit(1);
3530 }
3531 }
3532
3533 opts = qemu_opts_create(&qemu_mon_opts, label, 1);
3534 if (!opts) {
3535 fprintf(stderr, "duplicate chardev: %s\n", label);
3536 exit(1);
3537 }
3538 qemu_opt_set(opts, "mode", mode);
3539 qemu_opt_set(opts, "chardev", label);
3540 if (def)
3541 qemu_opt_set(opts, "default", "on");
3542 monitor_device_index++;
3543}
3544
3545struct device_config {
3546 enum {
3547 DEV_USB, /* -usbdevice */
3548 DEV_BT, /* -bt */
3549 DEV_SERIAL, /* -serial */
3550 DEV_PARALLEL, /* -parallel */
3551 DEV_VIRTCON, /* -virtioconsole */
3552 DEV_DEBUGCON, /* -debugcon */
3553 } type;
3554 const char *cmdline;
3555 QTAILQ_ENTRY(device_config) next;
3556};
3557QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
3558
3559static void add_device_config(int type, const char *cmdline)
3560{
3561 struct device_config *conf;
3562
3563 conf = qemu_mallocz(sizeof(*conf));
3564 conf->type = type;
3565 conf->cmdline = cmdline;
3566 QTAILQ_INSERT_TAIL(&device_configs, conf, next);
3567}
3568
3569static int foreach_device_config(int type, int (*func)(const char *cmdline))
3570{
3571 struct device_config *conf;
3572 int rc;
3573
3574 QTAILQ_FOREACH(conf, &device_configs, next) {
3575 if (conf->type != type)
3576 continue;
3577 rc = func(conf->cmdline);
3578 if (0 != rc)
3579 return rc;
3580 }
3581 return 0;
3582}
3583
3584static int serial_parse(const char *devname)
3585{
3586 static int index = 0;
3587 char label[32];
3588
3589 if (strcmp(devname, "none") == 0)
3590 return 0;
3591 if (index == MAX_SERIAL_PORTS) {
3592 fprintf(stderr, "qemu: too many serial ports\n");
3593 exit(1);
3594 }
3595 snprintf(label, sizeof(label), "serial%d", index);
3596 serial_hds[index] = qemu_chr_open(label, devname, NULL);
3597 if (!serial_hds[index]) {
3598 fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
3599 devname, strerror(errno));
3600 return -1;
3601 }
3602 index++;
3603 return 0;
3604}
3605
3606static int parallel_parse(const char *devname)
3607{
3608 static int index = 0;
3609 char label[32];
3610
3611 if (strcmp(devname, "none") == 0)
3612 return 0;
3613 if (index == MAX_PARALLEL_PORTS) {
3614 fprintf(stderr, "qemu: too many parallel ports\n");
3615 exit(1);
3616 }
3617 snprintf(label, sizeof(label), "parallel%d", index);
3618 parallel_hds[index] = qemu_chr_open(label, devname, NULL);
3619 if (!parallel_hds[index]) {
3620 fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
3621 devname, strerror(errno));
3622 return -1;
3623 }
3624 index++;
3625 return 0;
3626}
3627
3628static int virtcon_parse(const char *devname)
3629{
3630 static int index = 0;
3631 char label[32];
3632 QemuOpts *bus_opts, *dev_opts;
3633
3634 if (strcmp(devname, "none") == 0)
3635 return 0;
3636 if (index == MAX_VIRTIO_CONSOLES) {
3637 fprintf(stderr, "qemu: too many virtio consoles\n");
3638 exit(1);
3639 }
3640
3641 bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3642 qemu_opt_set(bus_opts, "driver", "virtio-serial");
3643
3644 dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
3645 qemu_opt_set(dev_opts, "driver", "virtconsole");
3646
3647 snprintf(label, sizeof(label), "virtcon%d", index);
3648 virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
3649 if (!virtcon_hds[index]) {
3650 fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
3651 devname, strerror(errno));
3652 return -1;
3653 }
3654 qemu_opt_set(dev_opts, "chardev", label);
3655
3656 index++;
3657 return 0;
3658}
3659
3660static int debugcon_parse(const char *devname)
3661{
3662 QemuOpts *opts;
3663
3664 if (!qemu_chr_open("debugcon", devname, NULL)) {
3665 exit(1);
3666 }
3667 opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
3668 if (!opts) {
3669 fprintf(stderr, "qemu: already have a debugcon device\n");
3670 exit(1);
3671 }
3672 qemu_opt_set(opts, "driver", "isa-debugcon");
3673 qemu_opt_set(opts, "chardev", "debugcon");
3674 return 0;
3675}
3676
3677static const QEMUOption *lookup_opt(int argc, char **argv,
3678 const char **poptarg, int *poptind)
3679{
3680 const QEMUOption *popt;
3681 int optind = *poptind;
3682 char *r = argv[optind];
3683 const char *optarg;
3684
3685 loc_set_cmdline(argv, optind, 1);
3686 optind++;
3687 /* Treat --foo the same as -foo. */
3688 if (r[1] == '-')
3689 r++;
3690 popt = qemu_options;
3691 for(;;) {
3692 if (!popt->name) {
3693 error_report("invalid option");
3694 exit(1);
3695 }
3696 if (!strcmp(popt->name, r + 1))
3697 break;
3698 popt++;
3699 }
3700 if (popt->flags & HAS_ARG) {
3701 if (optind >= argc) {
3702 error_report("requires an argument");
3703 exit(1);
3704 }
3705 optarg = argv[optind++];
3706 loc_set_cmdline(argv, optind - 2, 2);
3707 } else {
3708 optarg = NULL;
3709 }
3710
3711 *poptarg = optarg;
3712 *poptind = optind;
3713
3714 return popt;
3715}
3716
3717int main(int argc, char **argv, char **envp)
3718{
3719 const char *gdbstub_dev = NULL;
3720 uint32_t boot_devices_bitmap = 0;
3721 int i;
3722 int snapshot, linux_boot, net_boot;
3723 const char *icount_option = NULL;
3724 const char *initrd_filename;
3725 const char *kernel_filename, *kernel_cmdline;
3726 char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
3727 DisplayState *ds;
3728 DisplayChangeListener *dcl;
3729 int cyls, heads, secs, translation;
3730 QemuOpts *hda_opts = NULL, *opts;
3731 int optind;
3732 const char *optarg;
3733 const char *loadvm = NULL;
3734 QEMUMachine *machine;
3735 const char *cpu_model;
3736#ifndef _WIN32
3737 int fds[2];
3738#endif
3739 int tb_size;
3740 const char *pid_file = NULL;
3741 const char *incoming = NULL;
3742#ifndef _WIN32
3743 int fd = 0;
3744 struct passwd *pwd = NULL;
3745 const char *chroot_dir = NULL;
3746 const char *run_as = NULL;
3747#endif
3748 CPUState *env;
3749 int show_vnc_port = 0;
3750 int defconfig = 1;
3751
3752 error_set_progname(argv[0]);
3753
3754 init_clocks();
3755
3756 qemu_cache_utils_init(envp);
3757
3758 QLIST_INIT (&vm_change_state_head);
3759#ifndef _WIN32
3760 {
3761 struct sigaction act;
3762 sigfillset(&act.sa_mask);
3763 act.sa_flags = 0;
3764 act.sa_handler = SIG_IGN;
3765 sigaction(SIGPIPE, &act, NULL);
3766 }
3767#else
3768 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
3769 /* Note: cpu_interrupt() is currently not SMP safe, so we force
3770 QEMU to run on a single CPU */
3771 {
3772 HANDLE h;
3773 DWORD mask, smask;
3774 int i;
3775 h = GetCurrentProcess();
3776 if (GetProcessAffinityMask(h, &mask, &smask)) {
3777 for(i = 0; i < 32; i++) {
3778 if (mask & (1 << i))
3779 break;
3780 }
3781 if (i != 32) {
3782 mask = 1 << i;
3783 SetProcessAffinityMask(h, mask);
3784 }
3785 }
3786 }
3787#endif
3788
3789 module_call_init(MODULE_INIT_MACHINE);
3790 machine = find_default_machine();
3791 cpu_model = NULL;
3792 initrd_filename = NULL;
3793 ram_size = 0;
3794 snapshot = 0;
3795 kernel_filename = NULL;
3796 kernel_cmdline = "";
3797 cyls = heads = secs = 0;
3798 translation = BIOS_ATA_TRANSLATION_AUTO;
3799
3800 for (i = 0; i < MAX_NODES; i++) {
3801 node_mem[i] = 0;
3802 node_cpumask[i] = 0;
3803 }
3804
3805 nb_numa_nodes = 0;
3806 nb_nics = 0;
3807
3808 tb_size = 0;
3809 autostart= 1;
3810
3811 /* first pass of option parsing */
3812 optind = 1;
3813 while (optind < argc) {
3814 if (argv[optind][0] != '-') {
3815 /* disk image */
3816 optind++;
3817 continue;
3818 } else {
3819 const QEMUOption *popt;
3820
3821 popt = lookup_opt(argc, argv, &optarg, &optind);
3822 switch (popt->index) {
3823 case QEMU_OPTION_nodefconfig:
3824 defconfig=0;
3825 break;
3826 }
3827 }
3828 }
3829
3830 if (defconfig) {
3831 const char *fname;
3832 FILE *fp;
3833
3834 fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
3835 fp = fopen(fname, "r");
3836 if (fp) {
3837 if (qemu_config_parse(fp, fname) != 0) {
3838 exit(1);
3839 }
3840 fclose(fp);
3841 }
3842
3843 fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
3844 fp = fopen(fname, "r");
3845 if (fp) {
3846 if (qemu_config_parse(fp, fname) != 0) {
3847 exit(1);
3848 }
3849 fclose(fp);
3850 }
3851 }
3852#if defined(cpudef_setup)
3853 cpudef_setup(); /* parse cpu definitions in target config file */
3854#endif
3855
3856 /* second pass of option parsing */
3857 optind = 1;
3858 for(;;) {
3859 if (optind >= argc)
3860 break;
3861 if (argv[optind][0] != '-') {
3862 hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
3863 } else {
3864 const QEMUOption *popt;
3865
3866 popt = lookup_opt(argc, argv, &optarg, &optind);
3867 switch(popt->index) {
3868 case QEMU_OPTION_M:
3869 machine = find_machine(optarg);
3870 if (!machine) {
3871 QEMUMachine *m;
3872 printf("Supported machines are:\n");
3873 for(m = first_machine; m != NULL; m = m->next) {
3874 if (m->alias)
3875 printf("%-10s %s (alias of %s)\n",
3876 m->alias, m->desc, m->name);
3877 printf("%-10s %s%s\n",
3878 m->name, m->desc,
3879 m->is_default ? " (default)" : "");
3880 }
3881 exit(*optarg != '?');
3882 }
3883 break;
3884 case QEMU_OPTION_cpu:
3885 /* hw initialization will check this */
3886 if (*optarg == '?') {
3887/* XXX: implement xxx_cpu_list for targets that still miss it */
3888#if defined(cpu_list_id)
3889 cpu_list_id(stdout, &fprintf, optarg);
3890#elif defined(cpu_list)
3891 cpu_list(stdout, &fprintf); /* deprecated */
3892#endif
3893 exit(0);
3894 } else {
3895 cpu_model = optarg;
3896 }
3897 break;
3898 case QEMU_OPTION_initrd:
3899 initrd_filename = optarg;
3900 break;
3901 case QEMU_OPTION_hda:
3902 if (cyls == 0)
3903 hda_opts = drive_add(optarg, HD_ALIAS, 0);
3904 else
3905 hda_opts = drive_add(optarg, HD_ALIAS
3906 ",cyls=%d,heads=%d,secs=%d%s",
3907 0, cyls, heads, secs,
3908 translation == BIOS_ATA_TRANSLATION_LBA ?
3909 ",trans=lba" :
3910 translation == BIOS_ATA_TRANSLATION_NONE ?
3911 ",trans=none" : "");
3912 break;
3913 case QEMU_OPTION_hdb:
3914 case QEMU_OPTION_hdc:
3915 case QEMU_OPTION_hdd:
3916 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
3917 break;
3918 case QEMU_OPTION_drive:
3919 drive_add(NULL, "%s", optarg);
3920 break;
3921 case QEMU_OPTION_set:
3922 if (qemu_set_option(optarg) != 0)
3923 exit(1);
3924 break;
3925 case QEMU_OPTION_global:
3926 if (qemu_global_option(optarg) != 0)
3927 exit(1);
3928 break;
3929 case QEMU_OPTION_mtdblock:
3930 drive_add(optarg, MTD_ALIAS);
3931 break;
3932 case QEMU_OPTION_sd:
3933 drive_add(optarg, SD_ALIAS);
3934 break;
3935 case QEMU_OPTION_pflash:
3936 drive_add(optarg, PFLASH_ALIAS);
3937 break;
3938 case QEMU_OPTION_snapshot:
3939 snapshot = 1;
3940 break;
3941 case QEMU_OPTION_hdachs:
3942 {
3943 const char *p;
3944 p = optarg;
3945 cyls = strtol(p, (char **)&p, 0);
3946 if (cyls < 1 || cyls > 16383)
3947 goto chs_fail;
3948 if (*p != ',')
3949 goto chs_fail;
3950 p++;
3951 heads = strtol(p, (char **)&p, 0);
3952 if (heads < 1 || heads > 16)
3953 goto chs_fail;
3954 if (*p != ',')
3955 goto chs_fail;
3956 p++;
3957 secs = strtol(p, (char **)&p, 0);
3958 if (secs < 1 || secs > 63)
3959 goto chs_fail;
3960 if (*p == ',') {
3961 p++;
3962 if (!strcmp(p, "none"))
3963 translation = BIOS_ATA_TRANSLATION_NONE;
3964 else if (!strcmp(p, "lba"))
3965 translation = BIOS_ATA_TRANSLATION_LBA;
3966 else if (!strcmp(p, "auto"))
3967 translation = BIOS_ATA_TRANSLATION_AUTO;
3968 else
3969 goto chs_fail;
3970 } else if (*p != '\0') {
3971 chs_fail:
3972 fprintf(stderr, "qemu: invalid physical CHS format\n");
3973 exit(1);
3974 }
3975 if (hda_opts != NULL) {
3976 char num[16];
3977 snprintf(num, sizeof(num), "%d", cyls);
3978 qemu_opt_set(hda_opts, "cyls", num);
3979 snprintf(num, sizeof(num), "%d", heads);
3980 qemu_opt_set(hda_opts, "heads", num);
3981 snprintf(num, sizeof(num), "%d", secs);
3982 qemu_opt_set(hda_opts, "secs", num);
3983 if (translation == BIOS_ATA_TRANSLATION_LBA)
3984 qemu_opt_set(hda_opts, "trans", "lba");
3985 if (translation == BIOS_ATA_TRANSLATION_NONE)
3986 qemu_opt_set(hda_opts, "trans", "none");
3987 }
3988 }
3989 break;
3990 case QEMU_OPTION_numa:
3991 if (nb_numa_nodes >= MAX_NODES) {
3992 fprintf(stderr, "qemu: too many NUMA nodes\n");
3993 exit(1);
3994 }
3995 numa_add(optarg);
3996 break;
3997 case QEMU_OPTION_nographic:
3998 display_type = DT_NOGRAPHIC;
3999 break;
4000#ifdef CONFIG_CURSES
4001 case QEMU_OPTION_curses:
4002 display_type = DT_CURSES;
4003 break;
4004#endif
4005 case QEMU_OPTION_portrait:
4006 graphic_rotate = 1;
4007 break;
4008 case QEMU_OPTION_kernel:
4009 kernel_filename = optarg;
4010 break;
4011 case QEMU_OPTION_append:
4012 kernel_cmdline = optarg;
4013 break;
4014 case QEMU_OPTION_cdrom:
4015 drive_add(optarg, CDROM_ALIAS);
4016 break;
4017 case QEMU_OPTION_boot:
4018 {
4019 static const char * const params[] = {
4020 "order", "once", "menu", NULL
4021 };
4022 char buf[sizeof(boot_devices)];
4023 char *standard_boot_devices;
4024 int legacy = 0;
4025
4026 if (!strchr(optarg, '=')) {
4027 legacy = 1;
4028 pstrcpy(buf, sizeof(buf), optarg);
4029 } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4030 fprintf(stderr,
4031 "qemu: unknown boot parameter '%s' in '%s'\n",
4032 buf, optarg);
4033 exit(1);
4034 }
4035
4036 if (legacy ||
4037 get_param_value(buf, sizeof(buf), "order", optarg)) {
4038 boot_devices_bitmap = parse_bootdevices(buf);
4039 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4040 }
4041 if (!legacy) {
4042 if (get_param_value(buf, sizeof(buf),
4043 "once", optarg)) {
4044 boot_devices_bitmap |= parse_bootdevices(buf);
4045 standard_boot_devices = qemu_strdup(boot_devices);
4046 pstrcpy(boot_devices, sizeof(boot_devices), buf);
4047 qemu_register_reset(restore_boot_devices,
4048 standard_boot_devices);
4049 }
4050 if (get_param_value(buf, sizeof(buf),
4051 "menu", optarg)) {
4052 if (!strcmp(buf, "on")) {
4053 boot_menu = 1;
4054 } else if (!strcmp(buf, "off")) {
4055 boot_menu = 0;
4056 } else {
4057 fprintf(stderr,
4058 "qemu: invalid option value '%s'\n",
4059 buf);
4060 exit(1);
4061 }
4062 }
4063 }
4064 }
4065 break;
4066 case QEMU_OPTION_fda:
4067 case QEMU_OPTION_fdb:
4068 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4069 break;
4070#ifdef TARGET_I386
4071 case QEMU_OPTION_no_fd_bootchk:
4072 fd_bootchk = 0;
4073 break;
4074#endif
4075 case QEMU_OPTION_netdev:
4076 if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4077 exit(1);
4078 }
4079 break;
4080 case QEMU_OPTION_net:
4081 if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4082 exit(1);
4083 }
4084 break;
4085#ifdef CONFIG_SLIRP
4086 case QEMU_OPTION_tftp:
4087 legacy_tftp_prefix = optarg;
4088 break;
4089 case QEMU_OPTION_bootp:
4090 legacy_bootp_filename = optarg;
4091 break;
4092#ifndef _WIN32
4093 case QEMU_OPTION_smb:
4094 if (net_slirp_smb(optarg) < 0)
4095 exit(1);
4096 break;
4097#endif
4098 case QEMU_OPTION_redir:
4099 if (net_slirp_redir(optarg) < 0)
4100 exit(1);
4101 break;
4102#endif
4103 case QEMU_OPTION_bt:
4104 add_device_config(DEV_BT, optarg);
4105 break;
4106#ifdef HAS_AUDIO
4107 case QEMU_OPTION_audio_help:
4108 AUD_help ();
4109 exit (0);
4110 break;
4111 case QEMU_OPTION_soundhw:
4112 select_soundhw (optarg);
4113 break;
4114#endif
4115 case QEMU_OPTION_h:
4116 help(0);
4117 break;
4118 case QEMU_OPTION_version:
4119 version();
4120 exit(0);
4121 break;
4122 case QEMU_OPTION_m: {
4123 uint64_t value;
4124 char *ptr;
4125
4126 value = strtoul(optarg, &ptr, 10);
4127 switch (*ptr) {
4128 case 0: case 'M': case 'm':
4129 value <<= 20;
4130 break;
4131 case 'G': case 'g':
4132 value <<= 30;
4133 break;
4134 default:
4135 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4136 exit(1);
4137 }
4138
4139 /* On 32-bit hosts, QEMU is limited by virtual address space */
4140 if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
4141 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4142 exit(1);
4143 }
4144 if (value != (uint64_t)(ram_addr_t)value) {
4145 fprintf(stderr, "qemu: ram size too large\n");
4146 exit(1);
4147 }
4148 ram_size = value;
4149 break;
4150 }
4151 case QEMU_OPTION_mempath:
4152 mem_path = optarg;
4153 break;
4154#ifdef MAP_POPULATE
4155 case QEMU_OPTION_mem_prealloc:
4156 mem_prealloc = 1;
4157 break;
4158#endif
4159 case QEMU_OPTION_d:
4160 {
4161 int mask;
4162 const CPULogItem *item;
4163
4164 mask = cpu_str_to_log_mask(optarg);
4165 if (!mask) {
4166 printf("Log items (comma separated):\n");
4167 for(item = cpu_log_items; item->mask != 0; item++) {
4168 printf("%-10s %s\n", item->name, item->help);
4169 }
4170 exit(1);
4171 }
4172 cpu_set_log(mask);
4173 }
4174 break;
4175 case QEMU_OPTION_s:
4176 gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4177 break;
4178 case QEMU_OPTION_gdb:
4179 gdbstub_dev = optarg;
4180 break;
4181 case QEMU_OPTION_L:
4182 data_dir = optarg;
4183 break;
4184 case QEMU_OPTION_bios:
4185 bios_name = optarg;
4186 break;
4187 case QEMU_OPTION_singlestep:
4188 singlestep = 1;
4189 break;
4190 case QEMU_OPTION_S:
4191 autostart = 0;
4192 break;
4193 case QEMU_OPTION_k:
4194 keyboard_layout = optarg;
4195 break;
4196 case QEMU_OPTION_localtime:
4197 rtc_utc = 0;
4198 break;
4199 case QEMU_OPTION_vga:
4200 select_vgahw (optarg);
4201 break;
4202#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4203 case QEMU_OPTION_g:
4204 {
4205 const char *p;
4206 int w, h, depth;
4207 p = optarg;
4208 w = strtol(p, (char **)&p, 10);
4209 if (w <= 0) {
4210 graphic_error:
4211 fprintf(stderr, "qemu: invalid resolution or depth\n");
4212 exit(1);
4213 }
4214 if (*p != 'x')
4215 goto graphic_error;
4216 p++;
4217 h = strtol(p, (char **)&p, 10);
4218 if (h <= 0)
4219 goto graphic_error;
4220 if (*p == 'x') {
4221 p++;
4222 depth = strtol(p, (char **)&p, 10);
4223 if (depth != 8 && depth != 15 && depth != 16 &&
4224 depth != 24 && depth != 32)
4225 goto graphic_error;
4226 } else if (*p == '\0') {
4227 depth = graphic_depth;
4228 } else {
4229 goto graphic_error;
4230 }
4231
4232 graphic_width = w;
4233 graphic_height = h;
4234 graphic_depth = depth;
4235 }
4236 break;
4237#endif
4238 case QEMU_OPTION_echr:
4239 {
4240 char *r;
4241 term_escape_char = strtol(optarg, &r, 0);
4242 if (r == optarg)
4243 printf("Bad argument to echr\n");
4244 break;
4245 }
4246 case QEMU_OPTION_monitor:
4247 monitor_parse(optarg, "readline");
4248 default_monitor = 0;
4249 break;
4250 case QEMU_OPTION_qmp:
4251 monitor_parse(optarg, "control");
4252 default_monitor = 0;
4253 break;
4254 case QEMU_OPTION_mon:
4255 opts = qemu_opts_parse(&qemu_mon_opts, optarg, 1);
4256 if (!opts) {
4257 fprintf(stderr, "parse error: %s\n", optarg);
4258 exit(1);
4259 }
4260 default_monitor = 0;
4261 break;
4262 case QEMU_OPTION_chardev:
4263 opts = qemu_opts_parse(&qemu_chardev_opts, optarg, 1);
4264 if (!opts) {
4265 fprintf(stderr, "parse error: %s\n", optarg);
4266 exit(1);
4267 }
4268 break;
4269 case QEMU_OPTION_serial:
4270 add_device_config(DEV_SERIAL, optarg);
4271 default_serial = 0;
4272 if (strncmp(optarg, "mon:", 4) == 0) {
4273 default_monitor = 0;
4274 }
4275 break;
4276 case QEMU_OPTION_watchdog:
4277 if (watchdog) {
4278 fprintf(stderr,
4279 "qemu: only one watchdog option may be given\n");
4280 return 1;
4281 }
4282 watchdog = optarg;
4283 break;
4284 case QEMU_OPTION_watchdog_action:
4285 if (select_watchdog_action(optarg) == -1) {
4286 fprintf(stderr, "Unknown -watchdog-action parameter\n");
4287 exit(1);
4288 }
4289 break;
4290 case QEMU_OPTION_virtiocon:
4291 add_device_config(DEV_VIRTCON, optarg);
4292 default_virtcon = 0;
4293 if (strncmp(optarg, "mon:", 4) == 0) {
4294 default_monitor = 0;
4295 }
4296 break;
4297 case QEMU_OPTION_parallel:
4298 add_device_config(DEV_PARALLEL, optarg);
4299 default_parallel = 0;
4300 if (strncmp(optarg, "mon:", 4) == 0) {
4301 default_monitor = 0;
4302 }
4303 break;
4304 case QEMU_OPTION_debugcon:
4305 add_device_config(DEV_DEBUGCON, optarg);
4306 break;
4307 case QEMU_OPTION_loadvm:
4308 loadvm = optarg;
4309 break;
4310 case QEMU_OPTION_full_screen:
4311 full_screen = 1;
4312 break;
4313#ifdef CONFIG_SDL
4314 case QEMU_OPTION_no_frame:
4315 no_frame = 1;
4316 break;
4317 case QEMU_OPTION_alt_grab:
4318 alt_grab = 1;
4319 break;
4320 case QEMU_OPTION_ctrl_grab:
4321 ctrl_grab = 1;
4322 break;
4323 case QEMU_OPTION_no_quit:
4324 no_quit = 1;
4325 break;
4326 case QEMU_OPTION_sdl:
4327 display_type = DT_SDL;
4328 break;
4329#endif
4330 case QEMU_OPTION_pidfile:
4331 pid_file = optarg;
4332 break;
4333#ifdef TARGET_I386
4334 case QEMU_OPTION_win2k_hack:
4335 win2k_install_hack = 1;
4336 break;
4337 case QEMU_OPTION_rtc_td_hack:
4338 rtc_td_hack = 1;
4339 break;
4340 case QEMU_OPTION_acpitable:
4341 if(acpi_table_add(optarg) < 0) {
4342 fprintf(stderr, "Wrong acpi table provided\n");
4343 exit(1);
4344 }
4345 break;
4346 case QEMU_OPTION_smbios:
4347 if(smbios_entry_add(optarg) < 0) {
4348 fprintf(stderr, "Wrong smbios provided\n");
4349 exit(1);
4350 }
4351 break;
4352#endif
4353#ifdef CONFIG_KVM
4354 case QEMU_OPTION_enable_kvm:
4355 kvm_allowed = 1;
4356 break;
4357#endif
4358 case QEMU_OPTION_usb:
4359 usb_enabled = 1;
4360 break;
4361 case QEMU_OPTION_usbdevice:
4362 usb_enabled = 1;
4363 add_device_config(DEV_USB, optarg);
4364 break;
4365 case QEMU_OPTION_device:
4366 if (!qemu_opts_parse(&qemu_device_opts, optarg, 1)) {
4367 exit(1);
4368 }
4369 break;
4370 case QEMU_OPTION_smp:
4371 smp_parse(optarg);
4372 if (smp_cpus < 1) {
4373 fprintf(stderr, "Invalid number of CPUs\n");
4374 exit(1);
4375 }
4376 if (max_cpus < smp_cpus) {
4377 fprintf(stderr, "maxcpus must be equal to or greater than "
4378 "smp\n");
4379 exit(1);
4380 }
4381 if (max_cpus > 255) {
4382 fprintf(stderr, "Unsupported number of maxcpus\n");
4383 exit(1);
4384 }
4385 break;
4386 case QEMU_OPTION_vnc:
4387 display_type = DT_VNC;
4388 vnc_display = optarg;
4389 break;
4390#ifdef TARGET_I386
4391 case QEMU_OPTION_no_acpi:
4392 acpi_enabled = 0;
4393 break;
4394 case QEMU_OPTION_no_hpet:
4395 no_hpet = 1;
4396 break;
4397 case QEMU_OPTION_balloon:
4398 if (balloon_parse(optarg) < 0) {
4399 fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
4400 exit(1);
4401 }
4402 break;
4403#endif
4404 case QEMU_OPTION_no_reboot:
4405 no_reboot = 1;
4406 break;
4407 case QEMU_OPTION_no_shutdown:
4408 no_shutdown = 1;
4409 break;
4410 case QEMU_OPTION_show_cursor:
4411 cursor_hide = 0;
4412 break;
4413 case QEMU_OPTION_uuid:
4414 if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4415 fprintf(stderr, "Fail to parse UUID string."
4416 " Wrong format.\n");
4417 exit(1);
4418 }
4419 break;
4420#ifndef _WIN32
4421 case QEMU_OPTION_daemonize:
4422 daemonize = 1;
4423 break;
4424#endif
4425 case QEMU_OPTION_option_rom:
4426 if (nb_option_roms >= MAX_OPTION_ROMS) {
4427 fprintf(stderr, "Too many option ROMs\n");
4428 exit(1);
4429 }
4430 option_rom[nb_option_roms] = optarg;
4431 nb_option_roms++;
4432 break;
4433#if defined(TARGET_ARM) || defined(TARGET_M68K)
4434 case QEMU_OPTION_semihosting:
4435 semihosting_enabled = 1;
4436 break;
4437#endif
4438 case QEMU_OPTION_name:
4439 qemu_name = qemu_strdup(optarg);
4440 {
4441 char *p = strchr(qemu_name, ',');
4442 if (p != NULL) {
4443 *p++ = 0;
4444 if (strncmp(p, "process=", 8)) {
4445 fprintf(stderr, "Unknown subargument %s to -name", p);
4446 exit(1);
4447 }
4448 p += 8;
4449 set_proc_name(p);
4450 }
4451 }
4452 break;
4453#if defined(TARGET_SPARC) || defined(TARGET_PPC)
4454 case QEMU_OPTION_prom_env:
4455 if (nb_prom_envs >= MAX_PROM_ENVS) {
4456 fprintf(stderr, "Too many prom variables\n");
4457 exit(1);
4458 }
4459 prom_envs[nb_prom_envs] = optarg;
4460 nb_prom_envs++;
4461 break;
4462#endif
4463#ifdef TARGET_ARM
4464 case QEMU_OPTION_old_param:
4465 old_param = 1;
4466 break;
4467#endif
4468 case QEMU_OPTION_clock:
4469 configure_alarms(optarg);
4470 break;
4471 case QEMU_OPTION_startdate:
4472 configure_rtc_date_offset(optarg, 1);
4473 break;
4474 case QEMU_OPTION_rtc:
4475 opts = qemu_opts_parse(&qemu_rtc_opts, optarg, 0);
4476 if (!opts) {
4477 fprintf(stderr, "parse error: %s\n", optarg);
4478 exit(1);
4479 }
4480 configure_rtc(opts);
4481 break;
4482 case QEMU_OPTION_tb_size:
4483 tb_size = strtol(optarg, NULL, 0);
4484 if (tb_size < 0)
4485 tb_size = 0;
4486 break;
4487 case QEMU_OPTION_icount:
4488 icount_option = optarg;
4489 break;
4490 case QEMU_OPTION_incoming:
4491 incoming = optarg;
4492 break;
4493 case QEMU_OPTION_nodefaults:
4494 default_serial = 0;
4495 default_parallel = 0;
4496 default_virtcon = 0;
4497 default_monitor = 0;
4498 default_vga = 0;
4499 default_net = 0;
4500 default_floppy = 0;
4501 default_cdrom = 0;
4502 default_sdcard = 0;
4503 break;
4504#ifndef _WIN32
4505 case QEMU_OPTION_chroot:
4506 chroot_dir = optarg;
4507 break;
4508 case QEMU_OPTION_runas:
4509 run_as = optarg;
4510 break;
4511#endif
4512#ifdef CONFIG_XEN
4513 case QEMU_OPTION_xen_domid:
4514 xen_domid = atoi(optarg);
4515 break;
4516 case QEMU_OPTION_xen_create:
4517 xen_mode = XEN_CREATE;
4518 break;
4519 case QEMU_OPTION_xen_attach:
4520 xen_mode = XEN_ATTACH;
4521 break;
4522#endif
4523 case QEMU_OPTION_readconfig:
4524 {
4525 FILE *fp;
4526 fp = fopen(optarg, "r");
4527 if (fp == NULL) {
4528 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4529 exit(1);
4530 }
4531 if (qemu_config_parse(fp, optarg) != 0) {
4532 exit(1);
4533 }
4534 fclose(fp);
4535 break;
4536 }
4537 case QEMU_OPTION_writeconfig:
4538 {
4539 FILE *fp;
4540 if (strcmp(optarg, "-") == 0) {
4541 fp = stdout;
4542 } else {
4543 fp = fopen(optarg, "w");
4544 if (fp == NULL) {
4545 fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
4546 exit(1);
4547 }
4548 }
4549 qemu_config_write(fp);
4550 fclose(fp);
4551 break;
4552 }
4553 }
4554 }
4555 }
4556 loc_set_none();
4557
4558 /* If no data_dir is specified then try to find it relative to the
4559 executable path. */
4560 if (!data_dir) {
4561 data_dir = find_datadir(argv[0]);
4562 }
4563 /* If all else fails use the install patch specified when building. */
4564 if (!data_dir) {
4565 data_dir = CONFIG_QEMU_SHAREDIR;
4566 }
4567
4568 /*
4569 * Default to max_cpus = smp_cpus, in case the user doesn't
4570 * specify a max_cpus value.
4571 */
4572 if (!max_cpus)
4573 max_cpus = smp_cpus;
4574
4575 machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4576 if (smp_cpus > machine->max_cpus) {
4577 fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4578 "supported by machine `%s' (%d)\n", smp_cpus, machine->name,
4579 machine->max_cpus);
4580 exit(1);
4581 }
4582
4583 qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
4584 qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
4585
4586 if (machine->no_serial) {
4587 default_serial = 0;
4588 }
4589 if (machine->no_parallel) {
4590 default_parallel = 0;
4591 }
4592 if (!machine->use_virtcon) {
4593 default_virtcon = 0;
4594 }
4595 if (machine->no_vga) {
4596 default_vga = 0;
4597 }
4598 if (machine->no_floppy) {
4599 default_floppy = 0;
4600 }
4601 if (machine->no_cdrom) {
4602 default_cdrom = 0;
4603 }
4604 if (machine->no_sdcard) {
4605 default_sdcard = 0;
4606 }
4607
4608 if (display_type == DT_NOGRAPHIC) {
4609 if (default_parallel)
4610 add_device_config(DEV_PARALLEL, "null");
4611 if (default_serial && default_monitor) {
4612 add_device_config(DEV_SERIAL, "mon:stdio");
4613 } else if (default_virtcon && default_monitor) {
4614 add_device_config(DEV_VIRTCON, "mon:stdio");
4615 } else {
4616 if (default_serial)
4617 add_device_config(DEV_SERIAL, "stdio");
4618 if (default_virtcon)
4619 add_device_config(DEV_VIRTCON, "stdio");
4620 if (default_monitor)
4621 monitor_parse("stdio", "readline");
4622 }
4623 } else {
4624 if (default_serial)
4625 add_device_config(DEV_SERIAL, "vc:80Cx24C");
4626 if (default_parallel)
4627 add_device_config(DEV_PARALLEL, "vc:80Cx24C");
4628 if (default_monitor)
4629 monitor_parse("vc:80Cx24C", "readline");
4630 if (default_virtcon)
4631 add_device_config(DEV_VIRTCON, "vc:80Cx24C");
4632 }
4633 if (default_vga)
4634 vga_interface_type = VGA_CIRRUS;
4635
4636 if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
4637 exit(1);
4638
4639#ifndef _WIN32
4640 if (daemonize) {
4641 pid_t pid;
4642
4643 if (pipe(fds) == -1)
4644 exit(1);
4645
4646 pid = fork();
4647 if (pid > 0) {
4648 uint8_t status;
4649 ssize_t len;
4650
4651 close(fds[1]);
4652
4653 again:
4654 len = read(fds[0], &status, 1);
4655 if (len == -1 && (errno == EINTR))
4656 goto again;
4657
4658 if (len != 1)
4659 exit(1);
4660 else if (status == 1) {
4661 fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
4662 exit(1);
4663 } else
4664 exit(0);
4665 } else if (pid < 0)
4666 exit(1);
4667
4668 close(fds[0]);
4669 qemu_set_cloexec(fds[1]);
4670
4671 setsid();
4672
4673 pid = fork();
4674 if (pid > 0)
4675 exit(0);
4676 else if (pid < 0)
4677 exit(1);
4678
4679 umask(027);
4680
4681 signal(SIGTSTP, SIG_IGN);
4682 signal(SIGTTOU, SIG_IGN);
4683 signal(SIGTTIN, SIG_IGN);
4684 }
4685#endif
4686
4687 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
4688#ifndef _WIN32
4689 if (daemonize) {
4690 uint8_t status = 1;
4691 if (write(fds[1], &status, 1) != 1) {
4692 perror("daemonize. Writing to pipe\n");
4693 }
4694 } else
4695#endif
4696 fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
4697 exit(1);
4698 }
4699
4700 if (kvm_enabled()) {
4701 int ret;
4702
4703 ret = kvm_init(smp_cpus);
4704 if (ret < 0) {
4705 fprintf(stderr, "failed to initialize KVM\n");
4706 exit(1);
4707 }
4708 }
4709
4710 if (qemu_init_main_loop()) {
4711 fprintf(stderr, "qemu_init_main_loop failed\n");
4712 exit(1);
4713 }
4714 linux_boot = (kernel_filename != NULL);
4715
4716 if (!linux_boot && *kernel_cmdline != '\0') {
4717 fprintf(stderr, "-append only allowed with -kernel option\n");
4718 exit(1);
4719 }
4720
4721 if (!linux_boot && initrd_filename != NULL) {
4722 fprintf(stderr, "-initrd only allowed with -kernel option\n");
4723 exit(1);
4724 }
4725
4726#ifndef _WIN32
4727 /* Win32 doesn't support line-buffering and requires size >= 2 */
4728 setvbuf(stdout, NULL, _IOLBF, 0);
4729#endif
4730
4731 if (init_timer_alarm() < 0) {
4732 fprintf(stderr, "could not initialize alarm timer\n");
4733 exit(1);
4734 }
4735 configure_icount(icount_option);
4736
4737#ifdef _WIN32
4738 socket_init();
4739#endif
4740
4741 if (net_init_clients() < 0) {
4742 exit(1);
4743 }
4744
4745 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
4746 net_set_boot_mask(net_boot);
4747
4748 /* init the bluetooth world */
4749 if (foreach_device_config(DEV_BT, bt_parse))
4750 exit(1);
4751
4752 /* init the memory */
4753 if (ram_size == 0)
4754 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4755
4756 /* init the dynamic translator */
4757 cpu_exec_init_all(tb_size * 1024 * 1024);
4758
4759 bdrv_init_with_whitelist();
4760
4761 blk_mig_init();
4762
4763 if (default_cdrom) {
4764 /* we always create the cdrom drive, even if no disk is there */
4765 drive_add(NULL, CDROM_ALIAS);
4766 }
4767
4768 if (default_floppy) {
4769 /* we always create at least one floppy */
4770 drive_add(NULL, FD_ALIAS, 0);
4771 }
4772
4773 if (default_sdcard) {
4774 /* we always create one sd slot, even if no card is in it */
4775 drive_add(NULL, SD_ALIAS);
4776 }
4777
4778 /* open the virtual block devices */
4779 if (snapshot)
4780 qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
4781 if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
4782 exit(1);
4783
4784 register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL,
4785 ram_load, NULL);
4786
4787 if (nb_numa_nodes > 0) {
4788 int i;
4789
4790 if (nb_numa_nodes > smp_cpus) {
4791 nb_numa_nodes = smp_cpus;
4792 }
4793
4794 /* If no memory size if given for any node, assume the default case
4795 * and distribute the available memory equally across all nodes
4796 */
4797 for (i = 0; i < nb_numa_nodes; i++) {
4798 if (node_mem[i] != 0)
4799 break;
4800 }
4801 if (i == nb_numa_nodes) {
4802 uint64_t usedmem = 0;
4803
4804 /* On Linux, the each node's border has to be 8MB aligned,
4805 * the final node gets the rest.
4806 */
4807 for (i = 0; i < nb_numa_nodes - 1; i++) {
4808 node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
4809 usedmem += node_mem[i];
4810 }
4811 node_mem[i] = ram_size - usedmem;
4812 }
4813
4814 for (i = 0; i < nb_numa_nodes; i++) {
4815 if (node_cpumask[i] != 0)
4816 break;
4817 }
4818 /* assigning the VCPUs round-robin is easier to implement, guest OSes
4819 * must cope with this anyway, because there are BIOSes out there in
4820 * real machines which also use this scheme.
4821 */
4822 if (i == nb_numa_nodes) {
4823 for (i = 0; i < smp_cpus; i++) {
4824 node_cpumask[i % nb_numa_nodes] |= 1 << i;
4825 }
4826 }
4827 }
4828
4829 if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
4830 exit(1);
4831 if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
4832 exit(1);
4833 if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
4834 exit(1);
4835 if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
4836 exit(1);
4837
4838 module_call_init(MODULE_INIT_DEVICE);
4839
4840 if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
4841 exit(0);
4842
4843 if (watchdog) {
4844 i = select_watchdog(watchdog);
4845 if (i > 0)
4846 exit (i == 1 ? 1 : 0);
4847 }
4848
4849 if (machine->compat_props) {
4850 qdev_prop_register_global_list(machine->compat_props);
4851 }
4852 qemu_add_globals();
4853
4854 machine->init(ram_size, boot_devices,
4855 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
4856
4857 cpu_synchronize_all_post_init();
4858
4859#ifndef _WIN32
4860 /* must be after terminal init, SDL library changes signal handlers */
4861 sighandler_setup();
4862#endif
4863
4864 for (env = first_cpu; env != NULL; env = env->next_cpu) {
4865 for (i = 0; i < nb_numa_nodes; i++) {
4866 if (node_cpumask[i] & (1 << env->cpu_index)) {
4867 env->numa_node = i;
4868 }
4869 }
4870 }
4871
4872 current_machine = machine;
4873
4874 /* init USB devices */
4875 if (usb_enabled) {
4876 if (foreach_device_config(DEV_USB, usb_parse) < 0)
4877 exit(1);
4878 }
4879
4880 /* init generic devices */
4881 if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
4882 exit(1);
4883
4884 net_check_clients();
4885
4886 /* just use the first displaystate for the moment */
4887 ds = get_displaystate();
4888
4889 if (display_type == DT_DEFAULT) {
4890#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
4891 display_type = DT_SDL;
4892#else
4893 display_type = DT_VNC;
4894 vnc_display = "localhost:0,to=99";
4895 show_vnc_port = 1;
4896#endif
4897 }
4898
4899
4900 switch (display_type) {
4901 case DT_NOGRAPHIC:
4902 break;
4903#if defined(CONFIG_CURSES)
4904 case DT_CURSES:
4905 curses_display_init(ds, full_screen);
4906 break;
4907#endif
4908#if defined(CONFIG_SDL)
4909 case DT_SDL:
4910 sdl_display_init(ds, full_screen, no_frame);
4911 break;
4912#elif defined(CONFIG_COCOA)
4913 case DT_SDL:
4914 cocoa_display_init(ds, full_screen);
4915 break;
4916#endif
4917 case DT_VNC:
4918 vnc_display_init(ds);
4919 if (vnc_display_open(ds, vnc_display) < 0)
4920 exit(1);
4921
4922 if (show_vnc_port) {
4923 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
4924 }
4925 break;
4926 default:
4927 break;
4928 }
4929 dpy_resize(ds);
4930
4931 dcl = ds->listeners;
4932 while (dcl != NULL) {
4933 if (dcl->dpy_refresh != NULL) {
4934 ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
4935 qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
4936 }
4937 dcl = dcl->next;
4938 }
4939
4940 if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
4941 nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
4942 qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
4943 }
4944
4945 text_consoles_set_display(ds);
4946
4947 if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
4948 exit(1);
4949
4950 if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
4951 fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
4952 gdbstub_dev);
4953 exit(1);
4954 }
4955
4956 qdev_machine_creation_done();
4957
4958 if (rom_load_all() != 0) {
4959 fprintf(stderr, "rom loading failed\n");
4960 exit(1);
4961 }
4962
4963 qemu_system_reset();
4964 if (loadvm) {
4965 if (load_vmstate(loadvm) < 0) {
4966 autostart = 0;
4967 }
4968 }
4969
4970 if (incoming) {
4971 qemu_start_incoming_migration(incoming);
4972 } else if (autostart) {
4973 vm_start();
4974 }
4975
4976#ifndef _WIN32
4977 if (daemonize) {
4978 uint8_t status = 0;
4979 ssize_t len;
4980
4981 again1:
4982 len = write(fds[1], &status, 1);
4983 if (len == -1 && (errno == EINTR))
4984 goto again1;
4985
4986 if (len != 1)
4987 exit(1);
4988
4989 if (chdir("/")) {
4990 perror("not able to chdir to /");
4991 exit(1);
4992 }
4993 TFR(fd = qemu_open("/dev/null", O_RDWR));
4994 if (fd == -1)
4995 exit(1);
4996 }
4997
4998 if (run_as) {
4999 pwd = getpwnam(run_as);
5000 if (!pwd) {
5001 fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5002 exit(1);
5003 }
5004 }
5005
5006 if (chroot_dir) {
5007 if (chroot(chroot_dir) < 0) {
5008 fprintf(stderr, "chroot failed\n");
5009 exit(1);
5010 }
5011 if (chdir("/")) {
5012 perror("not able to chdir to /");
5013 exit(1);
5014 }
5015 }
5016
5017 if (run_as) {
5018 if (setgid(pwd->pw_gid) < 0) {
5019 fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5020 exit(1);
5021 }
5022 if (setuid(pwd->pw_uid) < 0) {
5023 fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5024 exit(1);
5025 }
5026 if (setuid(0) != -1) {
5027 fprintf(stderr, "Dropping privileges failed\n");
5028 exit(1);
5029 }
5030 }
5031
5032 if (daemonize) {
5033 dup2(fd, 0);
5034 dup2(fd, 1);
5035 dup2(fd, 2);
5036
5037 close(fd);
5038 }
5039#endif
5040
5041 main_loop();
5042 quit_timers();
5043 net_cleanup();
5044
5045 return 0;
5046}