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