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