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