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