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