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