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