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