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