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