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