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