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