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