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