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