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