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