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