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