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