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