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