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