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