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