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