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