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