blob: a9c1940a3169eea2661251d7ccbb0d123d73da9d [file] [log] [blame]
The Android Open Source Project8b23a6c2009-03-03 19:30:32 -08001/*
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 "net.h"
40#include "console.h"
41#include "sysemu.h"
42#include "gdbstub.h"
43#include "qemu-timer.h"
44#include "qemu-char.h"
45#include "block.h"
46#include "audio/audio.h"
47
48#include "qemu_file.h"
49#include "android/android.h"
50#include "charpipe.h"
51#include "shaper.h"
52#include "modem_driver.h"
53#include "android/gps.h"
54#include "android/qemud.h"
55#include "android/hw-kmsg.h"
56#include "tcpdump.h"
57
58#include <unistd.h>
59#include <fcntl.h>
60#include <signal.h>
61#include <time.h>
62#include <errno.h>
63#include <sys/time.h>
64#include <zlib.h>
65
66#ifndef _WIN32
67#include <sys/times.h>
68#include <sys/wait.h>
69#include <termios.h>
70#include <sys/poll.h>
71#include <sys/mman.h>
72#include <sys/ioctl.h>
73#include <sys/socket.h>
74#include <netinet/in.h>
75#include <dirent.h>
76#include <netdb.h>
77#include <sys/select.h>
78#include <arpa/inet.h>
79#ifdef _BSD
80#include <sys/stat.h>
81#if !defined(__APPLE__) && !defined(__OpenBSD__)
82#include <libutil.h>
83#endif
84#ifdef __OpenBSD__
85#include <net/if.h>
86#endif
87#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
88#include <freebsd/stdlib.h>
89#else
90#ifndef __sun__
91#include <linux/if.h>
92#include <linux/if_tun.h>
93#include <pty.h>
94#include <malloc.h>
95#include <linux/rtc.h>
96
97/* For the benefit of older linux systems which don't supply it,
98 we use a local copy of hpet.h. */
99/* #include <linux/hpet.h> */
100#include "hpet.h"
101
102#include <linux/ppdev.h>
103#include <linux/parport.h>
104#else
105#include <sys/stat.h>
106#include <sys/ethernet.h>
107#include <sys/sockio.h>
108#include <netinet/arp.h>
109#include <netinet/in.h>
110#include <netinet/in_systm.h>
111#include <netinet/ip.h>
112#include <netinet/ip_icmp.h> // must come after ip.h
113#include <netinet/udp.h>
114#include <netinet/tcp.h>
115#include <net/if.h>
116#include <syslog.h>
117#include <stropts.h>
118#endif
119#endif
120#endif
121
122#include "qemu_socket.h"
123
124#if defined(CONFIG_SLIRP)
125#include "libslirp.h"
126#endif
127
128#if defined(__OpenBSD__)
129#include <util.h>
130#endif
131
132#if defined(CONFIG_VDE)
133#include <libvdeplug.h>
134#endif
135
136#ifdef _WIN32
137#include <malloc.h>
138#include <sys/timeb.h>
139#include <mmsystem.h>
140#define getopt_long_only getopt_long
141#define memalign(align, size) malloc(size)
142#endif
143
144
145#ifdef CONFIG_COCOA
146#undef main
147#define main qemu_main
148#endif /* CONFIG_COCOA */
149
150#ifdef CONFIG_SKINS
151#undef main
152#define main qemu_main
153#endif
154
155#include "disas.h"
156
157#include "exec-all.h"
158
159#ifdef CONFIG_TRACE
160#include "trace.h"
161#include "dcache.h"
162#endif
163
164#ifdef CONFIG_NAND
165#include "hw/goldfish_nand.h"
166#endif
167
168#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
169#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
170#ifdef __sun__
171#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
172#else
173#define SMBD_COMMAND "/usr/sbin/smbd"
174#endif
175
176//#define DEBUG_UNUSED_IOPORT
177//#define DEBUG_IOPORT
178
179#ifdef TARGET_PPC
180#define DEFAULT_RAM_SIZE 144
181#else
182#define DEFAULT_RAM_SIZE 128
183#endif
184
185/* Max number of USB devices that can be specified on the commandline. */
186#define MAX_USB_CMDLINE 8
187
188/* XXX: use a two level table to limit memory usage */
189#define MAX_IOPORTS 65536
190
191const char *bios_dir = CONFIG_QEMU_SHAREDIR;
192const char *bios_name = NULL;
193void *ioport_opaque[MAX_IOPORTS];
194IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
195IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
196/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
197 to store the VM snapshots */
198DriveInfo drives_table[MAX_DRIVES+1];
199int nb_drives;
200/* point to the block driver where the snapshots are managed */
201BlockDriverState *bs_snapshots;
202int vga_ram_size;
203static DisplayState display_state;
204int nographic;
205int curses;
206const char* keyboard_layout = NULL;
207int64_t ticks_per_sec;
208ram_addr_t ram_size;
209int pit_min_timer_count = 0;
210int nb_nics;
211NICInfo nd_table[MAX_NICS];
212int vm_running;
213static int rtc_utc = 1;
214static int rtc_date_offset = -1; /* -1 means no change */
215int cirrus_vga_enabled = 1;
216int vmsvga_enabled = 0;
217#ifdef TARGET_SPARC
218int graphic_width = 1024;
219int graphic_height = 768;
220int graphic_depth = 8;
221#else
222int graphic_width = 800;
223int graphic_height = 600;
224int graphic_depth = 15;
225#endif
226int full_screen = 0;
227int no_frame = 0;
228int no_quit = 0;
229CharDriverState *serial_hds[MAX_SERIAL_PORTS];
230CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
231#ifdef TARGET_I386
232int win2k_install_hack = 0;
233#endif
234int usb_enabled = 0;
235static VLANState *first_vlan;
236int smp_cpus = 1;
237const char *vnc_display;
238#if defined(TARGET_SPARC)
239#define MAX_CPUS 16
240#elif defined(TARGET_I386)
241#define MAX_CPUS 255
242#else
243#define MAX_CPUS 1
244#endif
245int acpi_enabled = 1;
246int fd_bootchk = 1;
247int no_reboot = 0;
248int no_shutdown = 0;
249int cursor_hide = 1;
250int graphic_rotate = 0;
251int daemonize = 0;
252const char *option_rom[MAX_OPTION_ROMS];
253int nb_option_roms;
254int semihosting_enabled = 0;
255int autostart = 1;
256#ifdef TARGET_ARM
257int old_param = 0;
258#endif
259const char *qemu_name;
260int alt_grab = 0;
261#ifdef TARGET_SPARC
262unsigned int nb_prom_envs = 0;
263const char *prom_envs[MAX_PROM_ENVS];
264#endif
265int nb_drives_opt;
266struct drive_opt {
267 const char *file;
268 char opt[1024];
269} drives_opt[MAX_DRIVES];
270
271static CPUState *cur_cpu;
272static CPUState *next_cpu;
273static int event_pending = 1;
274/* Conversion factor from emulated instructions to virtual clock ticks. */
275static int icount_time_shift;
276/* Arbitrarily pick 1MIPS as the minimum allowable speed. */
277#define MAX_ICOUNT_SHIFT 10
278/* Compensate for varying guest execution speed. */
279static int64_t qemu_icount_bias;
280QEMUTimer *icount_rt_timer;
281QEMUTimer *icount_vm_timer;
282
283
284extern int qemu_cpu_delay;
285extern int android_audio_enabled;
286extern char* audio_input_source;
287
288extern void dprint( const char* format, ... );
289
290#define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
291
292/***********************************************************/
293/* x86 ISA bus support */
294
295target_phys_addr_t isa_mem_base = 0;
296PicState2 *isa_pic;
297
298static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
299static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
300
301static uint32_t ioport_read(int index, uint32_t address)
302{
303 static IOPortReadFunc *default_func[3] = {
304 default_ioport_readb,
305 default_ioport_readw,
306 default_ioport_readl
307 };
308 IOPortReadFunc *func = ioport_read_table[index][address];
309 if (!func)
310 func = default_func[index];
311 return func(ioport_opaque[address], address);
312}
313
314static void ioport_write(int index, uint32_t address, uint32_t data)
315{
316 static IOPortWriteFunc *default_func[3] = {
317 default_ioport_writeb,
318 default_ioport_writew,
319 default_ioport_writel
320 };
321 IOPortWriteFunc *func = ioport_write_table[index][address];
322 if (!func)
323 func = default_func[index];
324 func(ioport_opaque[address], address, data);
325}
326
327static uint32_t default_ioport_readb(void *opaque, uint32_t address)
328{
329#ifdef DEBUG_UNUSED_IOPORT
330 fprintf(stderr, "unused inb: port=0x%04x\n", address);
331#endif
332 return 0xff;
333}
334
335static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
336{
337#ifdef DEBUG_UNUSED_IOPORT
338 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
339#endif
340}
341
342/* default is to make two byte accesses */
343static uint32_t default_ioport_readw(void *opaque, uint32_t address)
344{
345 uint32_t data;
346 data = ioport_read(0, address);
347 address = (address + 1) & (MAX_IOPORTS - 1);
348 data |= ioport_read(0, address) << 8;
349 return data;
350}
351
352static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
353{
354 ioport_write(0, address, data & 0xff);
355 address = (address + 1) & (MAX_IOPORTS - 1);
356 ioport_write(0, address, (data >> 8) & 0xff);
357}
358
359static uint32_t default_ioport_readl(void *opaque, uint32_t address)
360{
361#ifdef DEBUG_UNUSED_IOPORT
362 fprintf(stderr, "unused inl: port=0x%04x\n", address);
363#endif
364 return 0xffffffff;
365}
366
367static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
368{
369#ifdef DEBUG_UNUSED_IOPORT
370 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
371#endif
372}
373
374/* size is the word size in byte */
375int register_ioport_read(int start, int length, int size,
376 IOPortReadFunc *func, void *opaque)
377{
378 int i, bsize;
379
380 if (size == 1) {
381 bsize = 0;
382 } else if (size == 2) {
383 bsize = 1;
384 } else if (size == 4) {
385 bsize = 2;
386 } else {
387 hw_error("register_ioport_read: invalid size");
388 return -1;
389 }
390 for(i = start; i < start + length; i += size) {
391 ioport_read_table[bsize][i] = func;
392 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
393 hw_error("register_ioport_read: invalid opaque");
394 ioport_opaque[i] = opaque;
395 }
396 return 0;
397}
398
399/* size is the word size in byte */
400int register_ioport_write(int start, int length, int size,
401 IOPortWriteFunc *func, void *opaque)
402{
403 int i, bsize;
404
405 if (size == 1) {
406 bsize = 0;
407 } else if (size == 2) {
408 bsize = 1;
409 } else if (size == 4) {
410 bsize = 2;
411 } else {
412 hw_error("register_ioport_write: invalid size");
413 return -1;
414 }
415 for(i = start; i < start + length; i += size) {
416 ioport_write_table[bsize][i] = func;
417 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
418 hw_error("register_ioport_write: invalid opaque");
419 ioport_opaque[i] = opaque;
420 }
421 return 0;
422}
423
424void isa_unassign_ioport(int start, int length)
425{
426 int i;
427
428 for(i = start; i < start + length; i++) {
429 ioport_read_table[0][i] = default_ioport_readb;
430 ioport_read_table[1][i] = default_ioport_readw;
431 ioport_read_table[2][i] = default_ioport_readl;
432
433 ioport_write_table[0][i] = default_ioport_writeb;
434 ioport_write_table[1][i] = default_ioport_writew;
435 ioport_write_table[2][i] = default_ioport_writel;
436 }
437}
438
439/***********************************************************/
440
441void cpu_outb(CPUState *env, int addr, int val)
442{
443#ifdef DEBUG_IOPORT
444 if (loglevel & CPU_LOG_IOPORT)
445 fprintf(logfile, "outb: %04x %02x\n", addr, val);
446#endif
447 ioport_write(0, addr, val);
448#ifdef USE_KQEMU
449 if (env)
450 env->last_io_time = cpu_get_time_fast();
451#endif
452}
453
454void cpu_outw(CPUState *env, int addr, int val)
455{
456#ifdef DEBUG_IOPORT
457 if (loglevel & CPU_LOG_IOPORT)
458 fprintf(logfile, "outw: %04x %04x\n", addr, val);
459#endif
460 ioport_write(1, addr, val);
461#ifdef USE_KQEMU
462 if (env)
463 env->last_io_time = cpu_get_time_fast();
464#endif
465}
466
467void cpu_outl(CPUState *env, int addr, int val)
468{
469#ifdef DEBUG_IOPORT
470 if (loglevel & CPU_LOG_IOPORT)
471 fprintf(logfile, "outl: %04x %08x\n", addr, val);
472#endif
473 ioport_write(2, addr, val);
474#ifdef USE_KQEMU
475 if (env)
476 env->last_io_time = cpu_get_time_fast();
477#endif
478}
479
480int cpu_inb(CPUState *env, int addr)
481{
482 int val;
483 val = ioport_read(0, addr);
484#ifdef DEBUG_IOPORT
485 if (loglevel & CPU_LOG_IOPORT)
486 fprintf(logfile, "inb : %04x %02x\n", addr, val);
487#endif
488#ifdef USE_KQEMU
489 if (env)
490 env->last_io_time = cpu_get_time_fast();
491#endif
492 return val;
493}
494
495int cpu_inw(CPUState *env, int addr)
496{
497 int val;
498 val = ioport_read(1, addr);
499#ifdef DEBUG_IOPORT
500 if (loglevel & CPU_LOG_IOPORT)
501 fprintf(logfile, "inw : %04x %04x\n", addr, val);
502#endif
503#ifdef USE_KQEMU
504 if (env)
505 env->last_io_time = cpu_get_time_fast();
506#endif
507 return val;
508}
509
510int cpu_inl(CPUState *env, int addr)
511{
512 int val;
513 val = ioport_read(2, addr);
514#ifdef DEBUG_IOPORT
515 if (loglevel & CPU_LOG_IOPORT)
516 fprintf(logfile, "inl : %04x %08x\n", addr, val);
517#endif
518#ifdef USE_KQEMU
519 if (env)
520 env->last_io_time = cpu_get_time_fast();
521#endif
522 return val;
523}
524
525/***********************************************************/
526void hw_error(const char *fmt, ...)
527{
528 va_list ap;
529 CPUState *env;
530
531 va_start(ap, fmt);
532 fprintf(stderr, "qemu: hardware error: ");
533 vfprintf(stderr, fmt, ap);
534 fprintf(stderr, "\n");
535 for(env = first_cpu; env != NULL; env = env->next_cpu) {
536 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
537#ifdef TARGET_I386
538 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
539#else
540 cpu_dump_state(env, stderr, fprintf, 0);
541#endif
542 }
543 va_end(ap);
544 abort();
545}
546
547/***********************************************************/
548/* keyboard/mouse */
549
550static QEMUPutKBDEvent* qemu_put_kbd_event;
551static void* qemu_put_kbd_event_opaque;
552
553static QEMUPutKBDEventN* qemu_put_kbd_event_n;
554static void* qemu_put_kbd_event_n_opaque;
555
556
557static QEMUPutGenericEvent* qemu_put_generic_event;
558static void* qemu_put_generic_event_opaque;
559
560static QEMUPutMouseEntry *qemu_put_mouse_event_head;
561static QEMUPutMouseEntry *qemu_put_mouse_event_current;
562
563void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
564{
565 qemu_put_kbd_event_opaque = opaque;
566 qemu_put_kbd_event = func;
567}
568
569void qemu_add_kbd_event_n_handler(QEMUPutKBDEventN *func, void *opaque)
570{
571 qemu_put_kbd_event_n_opaque = opaque;
572 qemu_put_kbd_event_n = func;
573}
574
575#if 0
576void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
577{
578 qemu_put_mouse_event_opaque = opaque;
579 qemu_put_mouse_event = func;
580 qemu_put_mouse_event_absolute = absolute;
581}
582#else
583QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
584 void *opaque, int absolute,
585 const char *name)
586{
587 QEMUPutMouseEntry *s, *cursor;
588
589 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
590 if (!s)
591 return NULL;
592
593 s->qemu_put_mouse_event = func;
594 s->qemu_put_mouse_event_opaque = opaque;
595 s->qemu_put_mouse_event_absolute = absolute;
596 s->qemu_put_mouse_event_name = qemu_strdup(name);
597 s->next = NULL;
598
599 if (!qemu_put_mouse_event_head) {
600 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
601 return s;
602 }
603
604 cursor = qemu_put_mouse_event_head;
605 while (cursor->next != NULL)
606 cursor = cursor->next;
607
608 cursor->next = s;
609 qemu_put_mouse_event_current = s;
610
611 return s;
612}
613
614void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
615{
616 QEMUPutMouseEntry *prev = NULL, *cursor;
617
618 if (!qemu_put_mouse_event_head || entry == NULL)
619 return;
620
621 cursor = qemu_put_mouse_event_head;
622 while (cursor != NULL && cursor != entry) {
623 prev = cursor;
624 cursor = cursor->next;
625 }
626
627 if (cursor == NULL) // does not exist or list empty
628 return;
629 else if (prev == NULL) { // entry is head
630 qemu_put_mouse_event_head = cursor->next;
631 if (qemu_put_mouse_event_current == entry)
632 qemu_put_mouse_event_current = cursor->next;
633 qemu_free(entry->qemu_put_mouse_event_name);
634 qemu_free(entry);
635 return;
636 }
637
638 prev->next = entry->next;
639
640 if (qemu_put_mouse_event_current == entry)
641 qemu_put_mouse_event_current = prev;
642
643 qemu_free(entry->qemu_put_mouse_event_name);
644 qemu_free(entry);
645}
646#endif
647
648void qemu_add_generic_event_handler(QEMUPutGenericEvent *func, void* opaque)
649{
650 qemu_put_generic_event = func;
651 qemu_put_generic_event_opaque = opaque;
652}
653
654void kbd_put_keycode(int keycode)
655{
656 if (qemu_put_kbd_event) {
657 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
658 }
659}
660
661void kbd_put_keycodes(int* keycodes, int count)
662{
663 if (qemu_put_kbd_event_n)
664 {
665 qemu_put_kbd_event_n(qemu_put_kbd_event_n_opaque, keycodes, count);
666 }
667 else if (qemu_put_kbd_event)
668 {
669 int nn;
670
671 for (nn = 0; nn < count; nn++)
672 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycodes[nn]);
673 }
674}
675
676
677void kbd_generic_event(int type, int code, int value)
678{
679 if (qemu_put_generic_event)
680 qemu_put_generic_event(qemu_put_generic_event_opaque, type, code, value);
681}
682
683
684void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
685{
686 QEMUPutMouseEvent *mouse_event;
687 void *mouse_event_opaque;
688 int width;
689
690 if (!qemu_put_mouse_event_current) {
691 return;
692 }
693
694 mouse_event =
695 qemu_put_mouse_event_current->qemu_put_mouse_event;
696 mouse_event_opaque =
697 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
698
699 if (mouse_event) {
700 if (graphic_rotate) {
701 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
702 width = 0x7fff;
703 else
704 width = graphic_width - 1;
705 mouse_event(mouse_event_opaque,
706 width - dy, dx, dz, buttons_state);
707 } else
708 mouse_event(mouse_event_opaque,
709 dx, dy, dz, buttons_state);
710 }
711}
712
713int kbd_mouse_is_absolute(void)
714{
715 if (!qemu_put_mouse_event_current)
716 return 0;
717
718 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
719}
720
721void do_info_mice(void)
722{
723 QEMUPutMouseEntry *cursor;
724 int index = 0;
725
726 if (!qemu_put_mouse_event_head) {
727 term_printf("No mouse devices connected\n");
728 return;
729 }
730
731 term_printf("Mouse devices available:\n");
732 cursor = qemu_put_mouse_event_head;
733 while (cursor != NULL) {
734 term_printf("%c Mouse #%d: %s\n",
735 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
736 index, cursor->qemu_put_mouse_event_name);
737 index++;
738 cursor = cursor->next;
739 }
740}
741
742void do_mouse_set(int index)
743{
744 QEMUPutMouseEntry *cursor;
745 int i = 0;
746
747 if (!qemu_put_mouse_event_head) {
748 term_printf("No mouse devices connected\n");
749 return;
750 }
751
752 cursor = qemu_put_mouse_event_head;
753 while (cursor != NULL && index != i) {
754 i++;
755 cursor = cursor->next;
756 }
757
758 if (cursor != NULL)
759 qemu_put_mouse_event_current = cursor;
760 else
761 term_printf("Mouse at given index not found\n");
762}
763
764/* compute with 96 bit intermediate result: (a*b)/c */
765uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
766{
767 union {
768 uint64_t ll;
769 struct {
770#ifdef WORDS_BIGENDIAN
771 uint32_t high, low;
772#else
773 uint32_t low, high;
774#endif
775 } l;
776 } u, res;
777 uint64_t rl, rh;
778
779 u.ll = a;
780 rl = (uint64_t)u.l.low * (uint64_t)b;
781 rh = (uint64_t)u.l.high * (uint64_t)b;
782 rh += (rl >> 32);
783 res.l.high = rh / c;
784 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
785 return res.ll;
786}
787
788/***********************************************************/
789/* real time host monotonic timer */
790
791#define QEMU_TIMER_BASE 1000000000LL
792
793#ifdef WIN32
794
795static int64_t clock_freq;
796
797static void init_get_clock(void)
798{
799 LARGE_INTEGER freq;
800 int ret;
801 ret = QueryPerformanceFrequency(&freq);
802 if (ret == 0) {
803 fprintf(stderr, "Could not calibrate ticks\n");
804 exit(1);
805 }
806 clock_freq = freq.QuadPart;
807}
808
809static int64_t get_clock(void)
810{
811 LARGE_INTEGER ti;
812 QueryPerformanceCounter(&ti);
813 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
814}
815
816#else
817
818static int use_rt_clock;
819
820static void init_get_clock(void)
821{
822 use_rt_clock = 0;
823#if defined(__linux__)
824 {
825 struct timespec ts;
826 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
827 use_rt_clock = 1;
828 }
829 }
830#endif
831}
832
833static int64_t get_clock(void)
834{
835#if defined(__linux__)
836 if (use_rt_clock) {
837 struct timespec ts;
838 clock_gettime(CLOCK_MONOTONIC, &ts);
839 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
840 } else
841#endif
842 {
843 /* XXX: using gettimeofday leads to problems if the date
844 changes, so it should be avoided. */
845 struct timeval tv;
846 gettimeofday(&tv, NULL);
847 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
848 }
849}
850#endif
851
852/* Return the virtual CPU time, based on the instruction counter. */
853static int64_t cpu_get_icount(void)
854{
855 int64_t icount;
856 CPUState *env = cpu_single_env;;
857 icount = qemu_icount;
858 if (env) {
859 if (!can_do_io(env))
860 fprintf(stderr, "Bad clock read\n");
861 icount -= (env->icount_decr.u16.low + env->icount_extra);
862 }
863 return qemu_icount_bias + (icount << icount_time_shift);
864}
865
866/***********************************************************/
867/* guest cycle counter */
868
869static int64_t cpu_ticks_prev;
870static int64_t cpu_ticks_offset;
871static int64_t cpu_clock_offset;
872static int cpu_ticks_enabled;
873
874/* return the host CPU cycle counter and handle stop/restart */
875int64_t cpu_get_ticks(void)
876{
877 if (use_icount) {
878 return cpu_get_icount();
879 }
880 if (!cpu_ticks_enabled) {
881 return cpu_ticks_offset;
882 } else {
883 int64_t ticks;
884 ticks = cpu_get_real_ticks();
885 if (cpu_ticks_prev > ticks) {
886 /* Note: non increasing ticks may happen if the host uses
887 software suspend */
888 cpu_ticks_offset += cpu_ticks_prev - ticks;
889 }
890 cpu_ticks_prev = ticks;
891 return ticks + cpu_ticks_offset;
892 }
893}
894
895/* return the host CPU monotonic timer and handle stop/restart */
896static int64_t cpu_get_clock(void)
897{
898 int64_t ti;
899 if (!cpu_ticks_enabled) {
900 return cpu_clock_offset;
901 } else {
902 ti = get_clock();
903 return ti + cpu_clock_offset;
904 }
905}
906
907/* enable cpu_get_ticks() */
908void cpu_enable_ticks(void)
909{
910 if (!cpu_ticks_enabled) {
911 cpu_ticks_offset -= cpu_get_real_ticks();
912 cpu_clock_offset -= get_clock();
913 cpu_ticks_enabled = 1;
914 }
915}
916
917/* disable cpu_get_ticks() : the clock is stopped. You must not call
918 cpu_get_ticks() after that. */
919void cpu_disable_ticks(void)
920{
921 if (cpu_ticks_enabled) {
922 cpu_ticks_offset = cpu_get_ticks();
923 cpu_clock_offset = cpu_get_clock();
924 cpu_ticks_enabled = 0;
925 }
926}
927
928/***********************************************************/
929/* timers */
930
931#define QEMU_TIMER_REALTIME 0
932#define QEMU_TIMER_VIRTUAL 1
933
934struct QEMUClock {
935 int type;
936 /* XXX: add frequency */
937};
938
939struct QEMUTimer {
940 QEMUClock *clock;
941 int64_t expire_time;
942 QEMUTimerCB *cb;
943 void *opaque;
944 struct QEMUTimer *next;
945};
946
947struct qemu_alarm_timer {
948 char const *name;
949 unsigned int flags;
950
951 int (*start)(struct qemu_alarm_timer *t);
952 void (*stop)(struct qemu_alarm_timer *t);
953 void (*rearm)(struct qemu_alarm_timer *t);
954 void *priv;
955};
956
957#define ALARM_FLAG_DYNTICKS 0x1
958#define ALARM_FLAG_EXPIRED 0x2
959
960static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
961{
962 return t->flags & ALARM_FLAG_DYNTICKS;
963}
964
965static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
966{
967 if (!alarm_has_dynticks(t))
968 return;
969
970 t->rearm(t);
971}
972
973/* TODO: MIN_TIMER_REARM_US should be optimized */
974#define MIN_TIMER_REARM_US 250
975
976static struct qemu_alarm_timer *alarm_timer;
977
978#ifdef _WIN32
979
980struct qemu_alarm_win32 {
981 MMRESULT timerId;
982 HANDLE host_alarm;
983 unsigned int period;
984} alarm_win32_data = {0, NULL, -1};
985
986static int win32_start_timer(struct qemu_alarm_timer *t);
987static void win32_stop_timer(struct qemu_alarm_timer *t);
988static void win32_rearm_timer(struct qemu_alarm_timer *t);
989
990#else
991
992static int unix_start_timer(struct qemu_alarm_timer *t);
993static void unix_stop_timer(struct qemu_alarm_timer *t);
994
995#ifdef __linux__
996
997static int dynticks_start_timer(struct qemu_alarm_timer *t);
998static void dynticks_stop_timer(struct qemu_alarm_timer *t);
999static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
1000
1001static int hpet_start_timer(struct qemu_alarm_timer *t);
1002static void hpet_stop_timer(struct qemu_alarm_timer *t);
1003
1004static int rtc_start_timer(struct qemu_alarm_timer *t);
1005static void rtc_stop_timer(struct qemu_alarm_timer *t);
1006
1007#endif /* __linux__ */
1008
1009#endif /* _WIN32 */
1010
1011/* Correlation between real and virtual time is always going to be
1012 fairly approximate, so ignore small variation.
1013 When the guest is idle real and virtual time will be aligned in
1014 the IO wait loop. */
1015#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
1016
1017static void icount_adjust(void)
1018{
1019 int64_t cur_time;
1020 int64_t cur_icount;
1021 int64_t delta;
1022 static int64_t last_delta;
1023 /* If the VM is not running, then do nothing. */
1024 if (!vm_running)
1025 return;
1026
1027 cur_time = cpu_get_clock();
1028 cur_icount = qemu_get_clock(vm_clock);
1029 delta = cur_icount - cur_time;
1030 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
1031 if (delta > 0
1032 && last_delta + ICOUNT_WOBBLE < delta * 2
1033 && icount_time_shift > 0) {
1034 /* The guest is getting too far ahead. Slow time down. */
1035 icount_time_shift--;
1036 }
1037 if (delta < 0
1038 && last_delta - ICOUNT_WOBBLE > delta * 2
1039 && icount_time_shift < MAX_ICOUNT_SHIFT) {
1040 /* The guest is getting too far behind. Speed time up. */
1041 icount_time_shift++;
1042 }
1043 last_delta = delta;
1044 qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
1045}
1046
1047static void icount_adjust_rt(void * opaque)
1048{
1049 qemu_mod_timer(icount_rt_timer,
1050 qemu_get_clock(rt_clock) + 1000);
1051 icount_adjust();
1052}
1053
1054static void icount_adjust_vm(void * opaque)
1055{
1056 qemu_mod_timer(icount_vm_timer,
1057 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1058 icount_adjust();
1059}
1060
1061static void init_icount_adjust(void)
1062{
1063 /* Have both realtime and virtual time triggers for speed adjustment.
1064 The realtime trigger catches emulated time passing too slowly,
1065 the virtual time trigger catches emulated time passing too fast.
1066 Realtime triggers occur even when idle, so use them less frequently
1067 than VM triggers. */
1068 icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1069 qemu_mod_timer(icount_rt_timer,
1070 qemu_get_clock(rt_clock) + 1000);
1071 icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1072 qemu_mod_timer(icount_vm_timer,
1073 qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1074}
1075
1076static struct qemu_alarm_timer alarm_timers[] = {
1077#ifndef _WIN32
1078#ifdef __linux__
1079 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1080 dynticks_stop_timer, dynticks_rearm_timer, NULL},
1081 /* HPET - if available - is preferred */
1082 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1083 /* ...otherwise try RTC */
1084 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1085#endif
1086 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1087#else
1088 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1089 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1090 {"win32", 0, win32_start_timer,
1091 win32_stop_timer, NULL, &alarm_win32_data},
1092#endif
1093 {NULL, 0, NULL, NULL, NULL, NULL}
1094};
1095
1096static void show_available_alarms(void)
1097{
1098 int i;
1099
1100 printf("Available alarm timers, in order of precedence:\n");
1101 for (i = 0; alarm_timers[i].name; i++)
1102 printf("%s\n", alarm_timers[i].name);
1103}
1104
1105static void configure_alarms(char const *opt)
1106{
1107 int i;
1108 int cur = 0;
1109 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1110 char *arg;
1111 char *name;
1112 struct qemu_alarm_timer tmp;
1113
1114 if (!strcmp(opt, "?")) {
1115 show_available_alarms();
1116 exit(0);
1117 }
1118
1119 arg = strdup(opt);
1120
1121 /* Reorder the array */
1122 name = strtok(arg, ",");
1123 while (name) {
1124 for (i = 0; i < count && alarm_timers[i].name; i++) {
1125 if (!strcmp(alarm_timers[i].name, name))
1126 break;
1127 }
1128
1129 if (i == count) {
1130 fprintf(stderr, "Unknown clock %s\n", name);
1131 goto next;
1132 }
1133
1134 if (i < cur)
1135 /* Ignore */
1136 goto next;
1137
1138 /* Swap */
1139 tmp = alarm_timers[i];
1140 alarm_timers[i] = alarm_timers[cur];
1141 alarm_timers[cur] = tmp;
1142
1143 cur++;
1144next:
1145 name = strtok(NULL, ",");
1146 }
1147
1148 free(arg);
1149
1150 if (cur) {
1151 /* Disable remaining timers */
1152 for (i = cur; i < count; i++)
1153 alarm_timers[i].name = NULL;
1154 } else {
1155 show_available_alarms();
1156 exit(1);
1157 }
1158}
1159
1160QEMUClock *rt_clock;
1161QEMUClock *vm_clock;
1162
1163static QEMUTimer *active_timers[2];
1164
1165static QEMUClock *qemu_new_clock(int type)
1166{
1167 QEMUClock *clock;
1168 clock = qemu_mallocz(sizeof(QEMUClock));
1169 if (!clock)
1170 return NULL;
1171 clock->type = type;
1172 return clock;
1173}
1174
1175QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1176{
1177 QEMUTimer *ts;
1178
1179 ts = qemu_mallocz(sizeof(QEMUTimer));
1180 ts->clock = clock;
1181 ts->cb = cb;
1182 ts->opaque = opaque;
1183 return ts;
1184}
1185
1186void qemu_free_timer(QEMUTimer *ts)
1187{
1188 qemu_free(ts);
1189}
1190
1191/* stop a timer, but do not dealloc it */
1192void qemu_del_timer(QEMUTimer *ts)
1193{
1194 QEMUTimer **pt, *t;
1195
1196 /* NOTE: this code must be signal safe because
1197 qemu_timer_expired() can be called from a signal. */
1198 pt = &active_timers[ts->clock->type];
1199 for(;;) {
1200 t = *pt;
1201 if (!t)
1202 break;
1203 if (t == ts) {
1204 *pt = t->next;
1205 break;
1206 }
1207 pt = &t->next;
1208 }
1209}
1210
1211/* modify the current timer so that it will be fired when current_time
1212 >= expire_time. The corresponding callback will be called. */
1213void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1214{
1215 QEMUTimer **pt, *t;
1216
1217 qemu_del_timer(ts);
1218
1219 /* add the timer in the sorted list */
1220 /* NOTE: this code must be signal safe because
1221 qemu_timer_expired() can be called from a signal. */
1222 pt = &active_timers[ts->clock->type];
1223 for(;;) {
1224 t = *pt;
1225 if (!t)
1226 break;
1227 if (t->expire_time > expire_time)
1228 break;
1229 pt = &t->next;
1230 }
1231 ts->expire_time = expire_time;
1232 ts->next = *pt;
1233 *pt = ts;
1234
1235 /* Rearm if necessary */
1236 if (pt == &active_timers[ts->clock->type]) {
1237 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1238 qemu_rearm_alarm_timer(alarm_timer);
1239 }
1240 /* Interrupt execution to force deadline recalculation. */
1241 if (use_icount && cpu_single_env) {
1242 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1243 }
1244 }
1245}
1246
1247int qemu_timer_pending(QEMUTimer *ts)
1248{
1249 QEMUTimer *t;
1250 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1251 if (t == ts)
1252 return 1;
1253 }
1254 return 0;
1255}
1256
1257static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1258{
1259 if (!timer_head)
1260 return 0;
1261 return (timer_head->expire_time <= current_time);
1262}
1263
1264static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1265{
1266 QEMUTimer *ts;
1267
1268 for(;;) {
1269 ts = *ptimer_head;
1270 if (!ts || ts->expire_time > current_time)
1271 break;
1272 /* remove timer from the list before calling the callback */
1273 *ptimer_head = ts->next;
1274 ts->next = NULL;
1275
1276 /* run the callback (the timer list can be modified) */
1277 ts->cb(ts->opaque);
1278 }
1279}
1280
1281int64_t qemu_get_clock(QEMUClock *clock)
1282{
1283 switch(clock->type) {
1284 case QEMU_TIMER_REALTIME:
1285 return get_clock() / 1000000;
1286 default:
1287 case QEMU_TIMER_VIRTUAL:
1288 if (use_icount) {
1289 return cpu_get_icount();
1290 } else {
1291 return cpu_get_clock();
1292 }
1293 }
1294}
1295
1296static void init_timers(void)
1297{
1298 init_get_clock();
1299 ticks_per_sec = QEMU_TIMER_BASE;
1300 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1301 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1302}
1303
1304/* save a timer */
1305void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1306{
1307 uint64_t expire_time;
1308
1309 if (qemu_timer_pending(ts)) {
1310 expire_time = ts->expire_time;
1311 } else {
1312 expire_time = -1;
1313 }
1314 qemu_put_be64(f, expire_time);
1315}
1316
1317void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1318{
1319 uint64_t expire_time;
1320
1321 expire_time = qemu_get_be64(f);
1322 if (expire_time != -1) {
1323 qemu_mod_timer(ts, expire_time);
1324 } else {
1325 qemu_del_timer(ts);
1326 }
1327}
1328
1329static void timer_save(QEMUFile *f, void *opaque)
1330{
1331 if (cpu_ticks_enabled) {
1332 hw_error("cannot save state if virtual timers are running");
1333 }
1334 qemu_put_be64(f, cpu_ticks_offset);
1335 qemu_put_be64(f, ticks_per_sec);
1336 qemu_put_be64(f, cpu_clock_offset);
1337}
1338
1339static int timer_load(QEMUFile *f, void *opaque, int version_id)
1340{
1341 if (version_id != 1 && version_id != 2)
1342 return -EINVAL;
1343 if (cpu_ticks_enabled) {
1344 return -EINVAL;
1345 }
1346 cpu_ticks_offset=qemu_get_be64(f);
1347 ticks_per_sec=qemu_get_be64(f);
1348 if (version_id == 2) {
1349 cpu_clock_offset=qemu_get_be64(f);
1350 }
1351 return 0;
1352}
1353
1354#ifdef _WIN32
1355void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1356 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1357#else
1358static void host_alarm_handler(int host_signum)
1359#endif
1360{
1361#if 0
1362#define DISP_FREQ 1000
1363 {
1364 static int64_t delta_min = INT64_MAX;
1365 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1366 static int count;
1367 ti = qemu_get_clock(vm_clock);
1368 if (last_clock != 0) {
1369 delta = ti - last_clock;
1370 if (delta < delta_min)
1371 delta_min = delta;
1372 if (delta > delta_max)
1373 delta_max = delta;
1374 delta_cum += delta;
1375 if (++count == DISP_FREQ) {
1376 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1377 muldiv64(delta_min, 1000000, ticks_per_sec),
1378 muldiv64(delta_max, 1000000, ticks_per_sec),
1379 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1380 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1381 count = 0;
1382 delta_min = INT64_MAX;
1383 delta_max = 0;
1384 delta_cum = 0;
1385 }
1386 }
1387 last_clock = ti;
1388 }
1389#endif
1390 if (alarm_has_dynticks(alarm_timer) ||
1391 (!use_icount &&
1392 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1393 qemu_get_clock(vm_clock))) ||
1394 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1395 qemu_get_clock(rt_clock))) {
1396#ifdef _WIN32
1397 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1398 SetEvent(data->host_alarm);
1399#endif
1400 CPUState *env = next_cpu;
1401
1402 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1403
1404 if (env) {
1405 /* stop the currently executing cpu because a timer occured */
1406 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1407#ifdef USE_KQEMU
1408 if (env->kqemu_enabled) {
1409 kqemu_cpu_interrupt(env);
1410 }
1411#endif
1412 }
1413 event_pending = 1;
1414 }
1415}
1416
1417static int64_t qemu_next_deadline(void)
1418{
1419 int64_t delta;
1420
1421 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1422 delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1423 qemu_get_clock(vm_clock);
1424 } else {
1425 /* To avoid problems with overflow limit this to 2^32. */
1426 delta = INT32_MAX;
1427 }
1428
1429 if (delta < 0)
1430 delta = 0;
1431
1432 return delta;
1433}
1434
1435#if defined(__linux__) || defined(_WIN32)
1436static uint64_t qemu_next_deadline_dyntick(void)
1437{
1438 int64_t delta;
1439 int64_t rtdelta;
1440
1441 if (use_icount)
1442 delta = INT32_MAX;
1443 else
1444 delta = (qemu_next_deadline() + 999) / 1000;
1445
1446 if (active_timers[QEMU_TIMER_REALTIME]) {
1447 rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1448 qemu_get_clock(rt_clock))*1000;
1449 if (rtdelta < delta)
1450 delta = rtdelta;
1451 }
1452
1453 if (delta < MIN_TIMER_REARM_US)
1454 delta = MIN_TIMER_REARM_US;
1455
1456 return delta;
1457}
1458#endif
1459
1460#ifndef _WIN32
1461
1462#if defined(__linux__)
1463
1464#define RTC_FREQ 1024
1465
1466static void enable_sigio_timer(int fd)
1467{
1468 struct sigaction act;
1469
1470 /* timer signal */
1471 sigfillset(&act.sa_mask);
1472 act.sa_flags = 0;
1473 act.sa_handler = host_alarm_handler;
1474
1475 sigaction(SIGIO, &act, NULL);
1476 fcntl(fd, F_SETFL, O_ASYNC);
1477 fcntl(fd, F_SETOWN, getpid());
1478}
1479
1480static int hpet_start_timer(struct qemu_alarm_timer *t)
1481{
1482 struct hpet_info info;
1483 int r, fd;
1484
1485 fd = open("/dev/hpet", O_RDONLY);
1486 if (fd < 0)
1487 return -1;
1488
1489 /* Set frequency */
1490 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1491 if (r < 0) {
1492 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1493 "error, but for better emulation accuracy type:\n"
1494 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1495 goto fail;
1496 }
1497
1498 /* Check capabilities */
1499 r = ioctl(fd, HPET_INFO, &info);
1500 if (r < 0)
1501 goto fail;
1502
1503 /* Enable periodic mode */
1504 r = ioctl(fd, HPET_EPI, 0);
1505 if (info.hi_flags && (r < 0))
1506 goto fail;
1507
1508 /* Enable interrupt */
1509 r = ioctl(fd, HPET_IE_ON, 0);
1510 if (r < 0)
1511 goto fail;
1512
1513 enable_sigio_timer(fd);
1514 t->priv = (void *)(long)fd;
1515
1516 return 0;
1517fail:
1518 close(fd);
1519 return -1;
1520}
1521
1522static void hpet_stop_timer(struct qemu_alarm_timer *t)
1523{
1524 int fd = (long)t->priv;
1525
1526 close(fd);
1527}
1528
1529static int rtc_start_timer(struct qemu_alarm_timer *t)
1530{
1531 int rtc_fd;
1532 unsigned long current_rtc_freq = 0;
1533
1534 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1535 if (rtc_fd < 0)
1536 return -1;
1537 ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1538 if (current_rtc_freq != RTC_FREQ &&
1539 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1540 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1541 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1542 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1543 goto fail;
1544 }
1545 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1546 fail:
1547 close(rtc_fd);
1548 return -1;
1549 }
1550
1551 enable_sigio_timer(rtc_fd);
1552
1553 t->priv = (void *)(long)rtc_fd;
1554
1555 return 0;
1556}
1557
1558static void rtc_stop_timer(struct qemu_alarm_timer *t)
1559{
1560 int rtc_fd = (long)t->priv;
1561
1562 close(rtc_fd);
1563}
1564
1565static int dynticks_start_timer(struct qemu_alarm_timer *t)
1566{
1567 struct sigevent ev;
1568 timer_t host_timer;
1569 struct sigaction act;
1570
1571 sigfillset(&act.sa_mask);
1572 act.sa_flags = 0;
1573 act.sa_handler = host_alarm_handler;
1574
1575 sigaction(SIGALRM, &act, NULL);
1576
1577 ev.sigev_value.sival_int = 0;
1578 ev.sigev_notify = SIGEV_SIGNAL;
1579 ev.sigev_signo = SIGALRM;
1580
1581 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1582 perror("timer_create");
1583
1584 /* disable dynticks */
1585 fprintf(stderr, "Dynamic Ticks disabled\n");
1586
1587 return -1;
1588 }
1589
1590 t->priv = (void *)host_timer;
1591
1592 return 0;
1593}
1594
1595static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1596{
1597 timer_t host_timer = (timer_t)t->priv;
1598
1599 timer_delete(host_timer);
1600}
1601
1602static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1603{
1604 timer_t host_timer = (timer_t)t->priv;
1605 struct itimerspec timeout;
1606 int64_t nearest_delta_us = INT64_MAX;
1607 int64_t current_us;
1608
1609 if (!active_timers[QEMU_TIMER_REALTIME] &&
1610 !active_timers[QEMU_TIMER_VIRTUAL])
1611 return;
1612
1613 nearest_delta_us = qemu_next_deadline_dyntick();
1614
1615 /* check whether a timer is already running */
1616 if (timer_gettime(host_timer, &timeout)) {
1617 perror("gettime");
1618 fprintf(stderr, "Internal timer error: aborting\n");
1619 exit(1);
1620 }
1621 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1622 if (current_us && current_us <= nearest_delta_us)
1623 return;
1624
1625 timeout.it_interval.tv_sec = 0;
1626 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1627 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1628 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1629 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1630 perror("settime");
1631 fprintf(stderr, "Internal timer error: aborting\n");
1632 exit(1);
1633 }
1634}
1635
1636#endif /* defined(__linux__) */
1637
1638static int unix_start_timer(struct qemu_alarm_timer *t)
1639{
1640 struct sigaction act;
1641 struct itimerval itv;
1642 int err;
1643
1644 /* timer signal */
1645 sigfillset(&act.sa_mask);
1646 act.sa_flags = 0;
1647 act.sa_handler = host_alarm_handler;
1648
1649 sigaction(SIGALRM, &act, NULL);
1650
1651 itv.it_interval.tv_sec = 0;
1652 /* for i386 kernel 2.6 to get 1 ms */
1653 itv.it_interval.tv_usec = 999;
1654 itv.it_value.tv_sec = 0;
1655 itv.it_value.tv_usec = 10 * 1000;
1656
1657 err = setitimer(ITIMER_REAL, &itv, NULL);
1658 if (err)
1659 return -1;
1660
1661 return 0;
1662}
1663
1664static void unix_stop_timer(struct qemu_alarm_timer *t)
1665{
1666 struct itimerval itv;
1667
1668 memset(&itv, 0, sizeof(itv));
1669 setitimer(ITIMER_REAL, &itv, NULL);
1670}
1671
1672#endif /* !defined(_WIN32) */
1673
1674#ifdef _WIN32
1675
1676static int win32_start_timer(struct qemu_alarm_timer *t)
1677{
1678 TIMECAPS tc;
1679 struct qemu_alarm_win32 *data = t->priv;
1680 UINT flags;
1681
1682 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1683 if (!data->host_alarm) {
1684 perror("Failed CreateEvent");
1685 return -1;
1686 }
1687
1688 memset(&tc, 0, sizeof(tc));
1689 timeGetDevCaps(&tc, sizeof(tc));
1690
1691 if (data->period < tc.wPeriodMin)
1692 data->period = tc.wPeriodMin;
1693
1694 timeBeginPeriod(data->period);
1695
1696 flags = TIME_CALLBACK_FUNCTION;
1697 if (alarm_has_dynticks(t))
1698 flags |= TIME_ONESHOT;
1699 else
1700 flags |= TIME_PERIODIC;
1701
1702 data->timerId = timeSetEvent(1, // interval (ms)
1703 data->period, // resolution
1704 host_alarm_handler, // function
1705 (DWORD)t, // parameter
1706 flags);
1707
1708 if (!data->timerId) {
1709 perror("Failed to initialize win32 alarm timer");
1710
1711 timeEndPeriod(data->period);
1712 CloseHandle(data->host_alarm);
1713 return -1;
1714 }
1715
1716 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1717
1718 return 0;
1719}
1720
1721static void win32_stop_timer(struct qemu_alarm_timer *t)
1722{
1723 struct qemu_alarm_win32 *data = t->priv;
1724
1725 timeKillEvent(data->timerId);
1726 timeEndPeriod(data->period);
1727
1728 CloseHandle(data->host_alarm);
1729}
1730
1731static void win32_rearm_timer(struct qemu_alarm_timer *t)
1732{
1733 struct qemu_alarm_win32 *data = t->priv;
1734 uint64_t nearest_delta_us;
1735
1736 if (!active_timers[QEMU_TIMER_REALTIME] &&
1737 !active_timers[QEMU_TIMER_VIRTUAL])
1738 return;
1739
1740 nearest_delta_us = qemu_next_deadline_dyntick();
1741 nearest_delta_us /= 1000;
1742
1743 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) {
1752 perror("Failed to re-arm win32 alarm timer");
1753
1754 timeEndPeriod(data->period);
1755 CloseHandle(data->host_alarm);
1756 exit(1);
1757 }
1758}
1759
1760#endif /* _WIN32 */
1761
1762static void init_timer_alarm(void)
1763{
1764 struct qemu_alarm_timer *t;
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 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1777 fprintf(stderr, "Terminating\n");
1778 exit(1);
1779 }
1780
1781 alarm_timer = t;
1782}
1783
1784static void quit_timers(void)
1785{
1786 alarm_timer->stop(alarm_timer);
1787 alarm_timer = NULL;
1788}
1789
1790/***********************************************************/
1791/* host time/date access */
1792void qemu_get_timedate(struct tm *tm, int offset)
1793{
1794 time_t ti;
1795 struct tm *ret;
1796
1797 time(&ti);
1798 ti += offset;
1799 if (rtc_date_offset == -1) {
1800 if (rtc_utc)
1801 ret = gmtime(&ti);
1802 else
1803 ret = localtime(&ti);
1804 } else {
1805 ti -= rtc_date_offset;
1806 ret = gmtime(&ti);
1807 }
1808
1809 memcpy(tm, ret, sizeof(struct tm));
1810}
1811
1812int qemu_timedate_diff(struct tm *tm)
1813{
1814 time_t seconds;
1815
1816 if (rtc_date_offset == -1)
1817 if (rtc_utc)
1818 seconds = mktimegm(tm);
1819 else
1820 seconds = mktime(tm);
1821 else
1822 seconds = mktimegm(tm) + rtc_date_offset;
1823
1824 return seconds - time(NULL);
1825}
1826
1827
1828#ifdef CONFIG_TRACE
1829static int tbflush_requested;
1830static int exit_requested;
1831
1832void start_tracing()
1833{
1834 if (trace_filename == NULL)
1835 return;
1836 if (!tracing) {
1837 fprintf(stderr,"-- start tracing --\n");
1838 start_time = Now();
1839 }
1840 tracing = 1;
1841 tbflush_requested = 1;
1842 if (cpu_single_env)
1843 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1844}
1845
1846void stop_tracing()
1847{
1848 if (trace_filename == NULL)
1849 return;
1850 if (tracing) {
1851 end_time = Now();
1852 elapsed_usecs += end_time - start_time;
1853 fprintf(stderr,"-- stop tracing --\n");
1854 }
1855 tracing = 0;
1856 tbflush_requested = 1;
1857 if (cpu_single_env)
1858 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1859}
1860
1861#ifndef _WIN32
1862/* This is the handler for the SIGUSR1 and SIGUSR2 signals.
1863 * SIGUSR1 turns tracing on. SIGUSR2 turns tracing off.
1864 */
1865void sigusr_handler(int sig)
1866{
1867 if (sig == SIGUSR1)
1868 start_tracing();
1869 else
1870 stop_tracing();
1871}
1872#endif
1873
1874/* This is the handler to catch control-C so that we can exit cleanly.
1875 * This is needed when tracing to flush the buffers to disk.
1876 */
1877void sigint_handler(int sig)
1878{
1879 exit_requested = 1;
1880 if (cpu_single_env)
1881 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1882}
1883#endif /* CONFIG_TRACE */
1884
1885
1886/***********************************************************/
1887/* character device */
1888
1889static void qemu_chr_event(CharDriverState *s, int event)
1890{
1891 if (!s->chr_event)
1892 return;
1893 s->chr_event(s->handler_opaque, event);
1894}
1895
1896static void qemu_chr_reset_bh(void *opaque)
1897{
1898 CharDriverState *s = opaque;
1899 qemu_chr_event(s, CHR_EVENT_RESET);
1900 qemu_bh_delete(s->bh);
1901 s->bh = NULL;
1902}
1903
1904void qemu_chr_reset(CharDriverState *s)
1905{
1906 if (s->bh == NULL) {
1907 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1908 qemu_bh_schedule(s->bh);
1909 }
1910}
1911
1912int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1913{
1914 return s->chr_write(s, buf, len);
1915}
1916
1917int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1918{
1919 if (!s->chr_ioctl)
1920 return -ENOTSUP;
1921 return s->chr_ioctl(s, cmd, arg);
1922}
1923
1924int qemu_chr_can_read(CharDriverState *s)
1925{
1926 if (!s->chr_can_read)
1927 return 0;
1928 return s->chr_can_read(s->handler_opaque);
1929}
1930
1931void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1932{
1933 s->chr_read(s->handler_opaque, buf, len);
1934}
1935
1936void qemu_chr_accept_input(CharDriverState *s)
1937{
1938 if (s->chr_accept_input)
1939 s->chr_accept_input(s);
1940}
1941
1942void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1943{
1944 char buf[4096];
1945 va_list ap;
1946 va_start(ap, fmt);
1947 vsnprintf(buf, sizeof(buf), fmt, ap);
1948 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1949 va_end(ap);
1950}
1951
1952void qemu_chr_send_event(CharDriverState *s, int event)
1953{
1954 if (s->chr_send_event)
1955 s->chr_send_event(s, event);
1956}
1957
1958void qemu_chr_add_handlers(CharDriverState *s,
1959 IOCanRWHandler *fd_can_read,
1960 IOReadHandler *fd_read,
1961 IOEventHandler *fd_event,
1962 void *opaque)
1963{
1964 s->chr_can_read = fd_can_read;
1965 s->chr_read = fd_read;
1966 s->chr_event = fd_event;
1967 s->handler_opaque = opaque;
1968 if (s->chr_update_read_handler)
1969 s->chr_update_read_handler(s);
1970}
1971
1972static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1973{
1974 return len;
1975}
1976
1977static CharDriverState *qemu_chr_open_null(void)
1978{
1979 CharDriverState *chr;
1980
1981 chr = qemu_mallocz(sizeof(CharDriverState));
1982 if (!chr)
1983 return NULL;
1984 chr->chr_write = null_chr_write;
1985 return chr;
1986}
1987
1988/* MUX driver for serial I/O splitting */
1989static int term_timestamps;
1990static int64_t term_timestamps_start;
1991#define MAX_MUX 4
1992#define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1993#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1994typedef struct {
1995 IOCanRWHandler *chr_can_read[MAX_MUX];
1996 IOReadHandler *chr_read[MAX_MUX];
1997 IOEventHandler *chr_event[MAX_MUX];
1998 void *ext_opaque[MAX_MUX];
1999 CharDriverState *drv;
2000 unsigned char buffer[MUX_BUFFER_SIZE];
2001 int prod;
2002 int cons;
2003 int mux_cnt;
2004 int term_got_escape;
2005 int max_size;
2006} MuxDriver;
2007
2008
2009static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2010{
2011 MuxDriver *d = chr->opaque;
2012 int ret;
2013 if (!term_timestamps) {
2014 ret = d->drv->chr_write(d->drv, buf, len);
2015 } else {
2016 int i;
2017
2018 ret = 0;
2019 for(i = 0; i < len; i++) {
2020 ret += d->drv->chr_write(d->drv, buf+i, 1);
2021 if (buf[i] == '\n') {
2022 char buf1[64];
2023 int64_t ti;
2024 int secs;
2025
2026 ti = get_clock();
2027 if (term_timestamps_start == -1)
2028 term_timestamps_start = ti;
2029 ti -= term_timestamps_start;
2030 secs = ti / 1000000000;
2031 snprintf(buf1, sizeof(buf1),
2032 "[%02d:%02d:%02d.%03d] ",
2033 secs / 3600,
2034 (secs / 60) % 60,
2035 secs % 60,
2036 (int)((ti / 1000000) % 1000));
2037 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
2038 }
2039 }
2040 }
2041 return ret;
2042}
2043
2044static const char * const mux_help[] = {
2045 "% h print this help\n\r",
2046 "% x exit emulator\n\r",
2047 "% s save disk data back to file (if -snapshot)\n\r",
2048 "% t toggle console timestamps\n\r"
2049 "% b send break (magic sysrq)\n\r",
2050 "% c switch between console and monitor\n\r",
2051 "% % sends %\n\r",
2052 NULL
2053};
2054
2055static int term_escape_char = 0x01; /* ctrl-a is used for escape */
2056static void mux_print_help(CharDriverState *chr)
2057{
2058 int i, j;
2059 char ebuf[15] = "Escape-Char";
2060 char cbuf[50] = "\n\r";
2061
2062 if (term_escape_char > 0 && term_escape_char < 26) {
2063 snprintf(cbuf, sizeof(cbuf), "\n\r");
2064 snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
2065 } else {
2066 snprintf(cbuf, sizeof(cbuf),
2067 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
2068 term_escape_char);
2069 }
2070 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
2071 for (i = 0; mux_help[i] != NULL; i++) {
2072 for (j=0; mux_help[i][j] != '\0'; j++) {
2073 if (mux_help[i][j] == '%')
2074 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
2075 else
2076 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
2077 }
2078 }
2079}
2080
2081static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
2082{
2083 if (d->term_got_escape) {
2084 d->term_got_escape = 0;
2085 if (ch == term_escape_char)
2086 goto send_char;
2087 switch(ch) {
2088 case '?':
2089 case 'h':
2090 mux_print_help(chr);
2091 break;
2092 case 'x':
2093 {
2094 const char *term = "QEMU: Terminated\n\r";
2095 chr->chr_write(chr,(uint8_t *)term,strlen(term));
2096 exit(0);
2097 break;
2098 }
2099 case 's':
2100 {
2101 int i;
2102 for (i = 0; i < nb_drives; i++) {
2103 bdrv_commit(drives_table[i].bdrv);
2104 }
2105 }
2106 break;
2107 case 'b':
2108 qemu_chr_event(chr, CHR_EVENT_BREAK);
2109 break;
2110 case 'c':
2111 /* Switch to the next registered device */
2112 chr->focus++;
2113 if (chr->focus >= d->mux_cnt)
2114 chr->focus = 0;
2115 break;
2116 case 't':
2117 term_timestamps = !term_timestamps;
2118 term_timestamps_start = -1;
2119 break;
2120 }
2121 } else if (ch == term_escape_char) {
2122 d->term_got_escape = 1;
2123 } else {
2124 send_char:
2125 return 1;
2126 }
2127 return 0;
2128}
2129
2130static void mux_chr_accept_input(CharDriverState *chr)
2131{
2132 int m = chr->focus;
2133 MuxDriver *d = chr->opaque;
2134
2135 while (d->prod != d->cons &&
2136 d->chr_can_read[m] &&
2137 d->chr_can_read[m](d->ext_opaque[m])) {
2138 d->chr_read[m](d->ext_opaque[m],
2139 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
2140 }
2141}
2142
2143static int mux_chr_can_read(void *opaque)
2144{
2145 CharDriverState *chr = opaque;
2146 MuxDriver *d = chr->opaque;
2147
2148 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2149 return 1;
2150 if (d->chr_can_read[chr->focus])
2151 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2152 return 0;
2153}
2154
2155static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2156{
2157 CharDriverState *chr = opaque;
2158 MuxDriver *d = chr->opaque;
2159 int m = chr->focus;
2160 int i;
2161
2162 mux_chr_accept_input (opaque);
2163
2164 for(i = 0; i < size; i++)
2165 if (mux_proc_byte(chr, d, buf[i])) {
2166 if (d->prod == d->cons &&
2167 d->chr_can_read[m] &&
2168 d->chr_can_read[m](d->ext_opaque[m]))
2169 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2170 else
2171 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2172 }
2173}
2174
2175static void mux_chr_event(void *opaque, int event)
2176{
2177 CharDriverState *chr = opaque;
2178 MuxDriver *d = chr->opaque;
2179 int i;
2180
2181 /* Send the event to all registered listeners */
2182 for (i = 0; i < d->mux_cnt; i++)
2183 if (d->chr_event[i])
2184 d->chr_event[i](d->ext_opaque[i], event);
2185}
2186
2187static void mux_chr_update_read_handler(CharDriverState *chr)
2188{
2189 MuxDriver *d = chr->opaque;
2190
2191 if (d->mux_cnt >= MAX_MUX) {
2192 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2193 return;
2194 }
2195 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2196 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2197 d->chr_read[d->mux_cnt] = chr->chr_read;
2198 d->chr_event[d->mux_cnt] = chr->chr_event;
2199 /* Fix up the real driver with mux routines */
2200 if (d->mux_cnt == 0) {
2201 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2202 mux_chr_event, chr);
2203 }
2204 chr->focus = d->mux_cnt;
2205 d->mux_cnt++;
2206}
2207
2208static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2209{
2210 CharDriverState *chr;
2211 MuxDriver *d;
2212
2213 chr = qemu_mallocz(sizeof(CharDriverState));
2214 if (!chr)
2215 return NULL;
2216 d = qemu_mallocz(sizeof(MuxDriver));
2217 if (!d) {
2218 free(chr);
2219 return NULL;
2220 }
2221
2222 chr->opaque = d;
2223 d->drv = drv;
2224 chr->focus = -1;
2225 chr->chr_write = mux_chr_write;
2226 chr->chr_update_read_handler = mux_chr_update_read_handler;
2227 chr->chr_accept_input = mux_chr_accept_input;
2228 return chr;
2229}
2230
2231
2232#ifdef _WIN32
2233
2234static int send_all(int fd, const uint8_t *buf, int len1)
2235{
2236 int ret, len;
2237
2238 len = len1;
2239 while (len > 0) {
2240 ret = socket_send(fd, buf, len);
2241 if (ret < 0) {
2242 if (errno != EWOULDBLOCK) {
2243 return -1;
2244 }
2245 } else if (ret == 0) {
2246 break;
2247 } else {
2248 buf += ret;
2249 len -= ret;
2250 }
2251 }
2252 return len1 - len;
2253}
2254
2255#else
2256
2257static int unix_write(int fd, const uint8_t *buf, int len1)
2258{
2259 int ret, len;
2260
2261 len = len1;
2262 while (len > 0) {
2263 ret = write(fd, buf, len);
2264 if (ret < 0) {
2265 if (errno != EINTR && errno != EAGAIN)
2266 return -1;
2267 } else if (ret == 0) {
2268 break;
2269 } else {
2270 buf += ret;
2271 len -= ret;
2272 }
2273 }
2274 return len1 - len;
2275}
2276
2277static inline int send_all(int fd, const uint8_t *buf, int len1)
2278{
2279 return unix_write(fd, buf, len1);
2280}
2281#endif /* !_WIN32 */
2282
2283#ifndef _WIN32
2284
2285typedef struct {
2286 int fd_in, fd_out;
2287 int max_size;
2288} FDCharDriver;
2289
2290#define STDIO_MAX_CLIENTS 1
2291static int stdio_nb_clients = 0;
2292
2293static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2294{
2295 FDCharDriver *s = chr->opaque;
2296 return unix_write(s->fd_out, buf, len);
2297}
2298
2299static int fd_chr_read_poll(void *opaque)
2300{
2301 CharDriverState *chr = opaque;
2302 FDCharDriver *s = chr->opaque;
2303
2304 s->max_size = qemu_chr_can_read(chr);
2305 return s->max_size;
2306}
2307
2308static void fd_chr_read(void *opaque)
2309{
2310 CharDriverState *chr = opaque;
2311 FDCharDriver *s = chr->opaque;
2312 int size, len;
2313 uint8_t buf[1024];
2314
2315 len = sizeof(buf);
2316 if (len > s->max_size)
2317 len = s->max_size;
2318 if (len == 0)
2319 return;
2320 size = read(s->fd_in, buf, len);
2321 if (size == 0) {
2322 /* FD has been closed. Remove it from the active list. */
2323 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2324 return;
2325 }
2326 if (size > 0) {
2327 qemu_chr_read(chr, buf, size);
2328 }
2329}
2330
2331static void fd_chr_update_read_handler(CharDriverState *chr)
2332{
2333 FDCharDriver *s = chr->opaque;
2334
2335 if (s->fd_in >= 0) {
2336 if (nographic && s->fd_in == 0) {
2337 } else {
2338 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2339 fd_chr_read, NULL, chr);
2340 }
2341 }
2342}
2343
2344static void fd_chr_close(struct CharDriverState *chr)
2345{
2346 FDCharDriver *s = chr->opaque;
2347
2348 if (s->fd_in >= 0) {
2349 if (nographic && s->fd_in == 0) {
2350 } else {
2351 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2352 }
2353 }
2354
2355 qemu_free(s);
2356}
2357
2358/* open a character device to a unix fd */
2359static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2360{
2361 CharDriverState *chr;
2362 FDCharDriver *s;
2363
2364 chr = qemu_mallocz(sizeof(CharDriverState));
2365 if (!chr)
2366 return NULL;
2367 s = qemu_mallocz(sizeof(FDCharDriver));
2368 if (!s) {
2369 free(chr);
2370 return NULL;
2371 }
2372 s->fd_in = fd_in;
2373 s->fd_out = fd_out;
2374 chr->opaque = s;
2375 chr->chr_write = fd_chr_write;
2376 chr->chr_update_read_handler = fd_chr_update_read_handler;
2377 chr->chr_close = fd_chr_close;
2378
2379 qemu_chr_reset(chr);
2380
2381 return chr;
2382}
2383
2384static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2385{
2386 int fd_out;
2387
2388 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2389 if (fd_out < 0)
2390 return NULL;
2391 return qemu_chr_open_fd(-1, fd_out);
2392}
2393
2394static CharDriverState *qemu_chr_open_pipe(const char *filename)
2395{
2396 int fd_in, fd_out;
2397 char filename_in[256], filename_out[256];
2398
2399 snprintf(filename_in, 256, "%s.in", filename);
2400 snprintf(filename_out, 256, "%s.out", filename);
2401 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2402 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2403 if (fd_in < 0 || fd_out < 0) {
2404 if (fd_in >= 0)
2405 close(fd_in);
2406 if (fd_out >= 0)
2407 close(fd_out);
2408 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2409 if (fd_in < 0)
2410 return NULL;
2411 }
2412 return qemu_chr_open_fd(fd_in, fd_out);
2413}
2414
2415CharDriverState *qemu_chr_open_fdpair(const char *fd_pair)
2416{
2417 int fd_in, fd_out;
2418 char *endptr;
2419
2420 /* fd_pair should contain two decimal fd values, separated by
2421 * a colon. */
2422 endptr = NULL;
2423 fd_in = strtol(fd_pair, &endptr, 10);
2424 if (endptr == NULL || endptr == fd_pair || *endptr != ':')
2425 return NULL;
2426 endptr++; // skip colon
2427 fd_pair = endptr;
2428 endptr = NULL;
2429 fd_out = strtol(fd_pair, &endptr, 10);
2430 if (endptr == NULL || endptr == fd_pair || *endptr != '\0')
2431 return NULL;
2432
2433 return qemu_chr_open_fd(fd_in, fd_out);
2434}
2435
2436
2437/* for STDIO, we handle the case where several clients use it
2438 (nographic mode) */
2439
2440#define TERM_FIFO_MAX_SIZE 1
2441
2442static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2443static int term_fifo_size;
2444
2445static int stdio_read_poll(void *opaque)
2446{
2447 CharDriverState *chr = opaque;
2448
2449 /* try to flush the queue if needed */
2450 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2451 qemu_chr_read(chr, term_fifo, 1);
2452 term_fifo_size = 0;
2453 }
2454 /* see if we can absorb more chars */
2455 if (term_fifo_size == 0)
2456 return 1;
2457 else
2458 return 0;
2459}
2460
2461static void stdio_read(void *opaque)
2462{
2463 int size;
2464 uint8_t buf[1];
2465 CharDriverState *chr = opaque;
2466
2467 size = read(0, buf, 1);
2468 if (size == 0) {
2469 /* stdin has been closed. Remove it from the active list. */
2470 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2471 return;
2472 }
2473 if (size > 0) {
2474 if (qemu_chr_can_read(chr) > 0) {
2475 qemu_chr_read(chr, buf, 1);
2476 } else if (term_fifo_size == 0) {
2477 term_fifo[term_fifo_size++] = buf[0];
2478 }
2479 }
2480}
2481
2482/* init terminal so that we can grab keys */
2483static struct termios oldtty;
2484static int old_fd0_flags;
2485static int term_atexit_done;
2486
2487static void term_exit(void)
2488{
2489 tcsetattr (0, TCSANOW, &oldtty);
2490 fcntl(0, F_SETFL, old_fd0_flags);
2491}
2492
2493static void term_init(void)
2494{
2495 struct termios tty;
2496
2497 tcgetattr (0, &tty);
2498 oldtty = tty;
2499 old_fd0_flags = fcntl(0, F_GETFL);
2500
2501 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2502 |INLCR|IGNCR|ICRNL|IXON);
2503 tty.c_oflag |= OPOST;
2504 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2505 /* if graphical mode, we allow Ctrl-C handling */
2506 if (nographic)
2507 tty.c_lflag &= ~ISIG;
2508 tty.c_cflag &= ~(CSIZE|PARENB);
2509 tty.c_cflag |= CS8;
2510 tty.c_cc[VMIN] = 1;
2511 tty.c_cc[VTIME] = 0;
2512
2513 tcsetattr (0, TCSANOW, &tty);
2514
2515 if (!term_atexit_done++)
2516 atexit(term_exit);
2517
2518 fcntl(0, F_SETFL, O_NONBLOCK);
2519}
2520
2521static void qemu_chr_close_stdio(struct CharDriverState *chr)
2522{
2523 term_exit();
2524 stdio_nb_clients--;
2525 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2526 fd_chr_close(chr);
2527}
2528
2529static CharDriverState *qemu_chr_open_stdio(void)
2530{
2531 CharDriverState *chr;
2532
2533 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2534 return NULL;
2535 chr = qemu_chr_open_fd(0, 1);
2536 chr->chr_close = qemu_chr_close_stdio;
2537 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2538 stdio_nb_clients++;
2539 term_init();
2540
2541 return chr;
2542}
2543
2544#ifdef __sun__
2545/* Once Solaris has openpty(), this is going to be removed. */
2546int openpty(int *amaster, int *aslave, char *name,
2547 struct termios *termp, struct winsize *winp)
2548{
2549 const char *slave;
2550 int mfd = -1, sfd = -1;
2551
2552 *amaster = *aslave = -1;
2553
2554 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2555 if (mfd < 0)
2556 goto err;
2557
2558 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2559 goto err;
2560
2561 if ((slave = ptsname(mfd)) == NULL)
2562 goto err;
2563
2564 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2565 goto err;
2566
2567 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2568 (termp != NULL && tcgetattr(sfd, termp) < 0))
2569 goto err;
2570
2571 if (amaster)
2572 *amaster = mfd;
2573 if (aslave)
2574 *aslave = sfd;
2575 if (winp)
2576 ioctl(sfd, TIOCSWINSZ, winp);
2577
2578 return 0;
2579
2580err:
2581 if (sfd != -1)
2582 close(sfd);
2583 close(mfd);
2584 return -1;
2585}
2586
2587void cfmakeraw (struct termios *termios_p)
2588{
2589 termios_p->c_iflag &=
2590 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2591 termios_p->c_oflag &= ~OPOST;
2592 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2593 termios_p->c_cflag &= ~(CSIZE|PARENB);
2594 termios_p->c_cflag |= CS8;
2595
2596 termios_p->c_cc[VMIN] = 0;
2597 termios_p->c_cc[VTIME] = 0;
2598}
2599#endif /* __sun__ */
2600
2601#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2602 || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
2603
2604typedef struct {
2605 int fd;
2606 int connected;
2607 int polling;
2608 int read_bytes;
2609 QEMUTimer *timer;
2610} PtyCharDriver;
2611
2612static void pty_chr_update_read_handler(CharDriverState *chr);
2613static void pty_chr_state(CharDriverState *chr, int connected);
2614
2615static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2616{
2617 PtyCharDriver *s = chr->opaque;
2618
2619 if (!s->connected) {
2620 /* guest sends data, check for (re-)connect */
2621 pty_chr_update_read_handler(chr);
2622 return 0;
2623 }
2624 return unix_write(s->fd, buf, len);
2625}
2626
2627static int pty_chr_read_poll(void *opaque)
2628{
2629 CharDriverState *chr = opaque;
2630 PtyCharDriver *s = chr->opaque;
2631
2632 s->read_bytes = qemu_chr_can_read(chr);
2633 return s->read_bytes;
2634}
2635
2636static void pty_chr_read(void *opaque)
2637{
2638 CharDriverState *chr = opaque;
2639 PtyCharDriver *s = chr->opaque;
2640 int size, len;
2641 uint8_t buf[1024];
2642
2643 len = sizeof(buf);
2644 if (len > s->read_bytes)
2645 len = s->read_bytes;
2646 if (len == 0)
2647 return;
2648 size = read(s->fd, buf, len);
2649 if ((size == -1 && errno == EIO) ||
2650 (size == 0)) {
2651 pty_chr_state(chr, 0);
2652 return;
2653 }
2654 if (size > 0) {
2655 pty_chr_state(chr, 1);
2656 qemu_chr_read(chr, buf, size);
2657 }
2658}
2659
2660static void pty_chr_update_read_handler(CharDriverState *chr)
2661{
2662 PtyCharDriver *s = chr->opaque;
2663
2664 qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2665 pty_chr_read, NULL, chr);
2666 s->polling = 1;
2667 /*
2668 * Short timeout here: just need wait long enougth that qemu makes
2669 * it through the poll loop once. When reconnected we want a
2670 * short timeout so we notice it almost instantly. Otherwise
2671 * read() gives us -EIO instantly, making pty_chr_state() reset the
2672 * timeout to the normal (much longer) poll interval before the
2673 * timer triggers.
2674 */
2675 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2676}
2677
2678static void pty_chr_state(CharDriverState *chr, int connected)
2679{
2680 PtyCharDriver *s = chr->opaque;
2681
2682 if (!connected) {
2683 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2684 s->connected = 0;
2685 s->polling = 0;
2686 /* (re-)connect poll interval for idle guests: once per second.
2687 * We check more frequently in case the guests sends data to
2688 * the virtual device linked to our pty. */
2689 qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2690 } else {
2691 if (!s->connected)
2692 qemu_chr_reset(chr);
2693 s->connected = 1;
2694 }
2695}
2696
2697static void pty_chr_timer(void *opaque)
2698{
2699 struct CharDriverState *chr = opaque;
2700 PtyCharDriver *s = chr->opaque;
2701
2702 if (s->connected)
2703 return;
2704 if (s->polling) {
2705 /* If we arrive here without polling being cleared due
2706 * read returning -EIO, then we are (re-)connected */
2707 pty_chr_state(chr, 1);
2708 return;
2709 }
2710
2711 /* Next poll ... */
2712 pty_chr_update_read_handler(chr);
2713}
2714
2715static void pty_chr_close(struct CharDriverState *chr)
2716{
2717 PtyCharDriver *s = chr->opaque;
2718
2719 qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2720 close(s->fd);
2721 qemu_free(s);
2722}
2723
2724static CharDriverState *qemu_chr_open_pty(void)
2725{
2726 CharDriverState *chr;
2727 PtyCharDriver *s;
2728 struct termios tty;
2729 int slave_fd;
2730#if defined(__OpenBSD__)
2731 char pty_name[PATH_MAX];
2732#define q_ptsname(x) pty_name
2733#else
2734 char *pty_name = NULL;
2735#define q_ptsname(x) ptsname(x)
2736#endif
2737
2738 chr = qemu_mallocz(sizeof(CharDriverState));
2739 if (!chr)
2740 return NULL;
2741 s = qemu_mallocz(sizeof(PtyCharDriver));
2742 if (!s) {
2743 qemu_free(chr);
2744 return NULL;
2745 }
2746
2747 if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2748 return NULL;
2749 }
2750
2751 /* Set raw attributes on the pty. */
2752 cfmakeraw(&tty);
2753 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2754 close(slave_fd);
2755
2756 fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2757
2758 chr->opaque = s;
2759 chr->chr_write = pty_chr_write;
2760 chr->chr_update_read_handler = pty_chr_update_read_handler;
2761 chr->chr_close = pty_chr_close;
2762
2763 s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2764
2765 return chr;
2766}
2767#endif /* __linux__ || __sun__ || __xxxBSD__ */
2768
2769static void tty_serial_init(int fd, int speed,
2770 int parity, int data_bits, int stop_bits)
2771{
2772 struct termios tty;
2773 speed_t spd;
2774
2775#if 0
2776 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2777 speed, parity, data_bits, stop_bits);
2778#endif
2779 tcgetattr (fd, &tty);
2780
2781#define MARGIN 1.1
2782 if (speed <= 50 * MARGIN)
2783 spd = B50;
2784 else if (speed <= 75 * MARGIN)
2785 spd = B75;
2786 else if (speed <= 300 * MARGIN)
2787 spd = B300;
2788 else if (speed <= 600 * MARGIN)
2789 spd = B600;
2790 else if (speed <= 1200 * MARGIN)
2791 spd = B1200;
2792 else if (speed <= 2400 * MARGIN)
2793 spd = B2400;
2794 else if (speed <= 4800 * MARGIN)
2795 spd = B4800;
2796 else if (speed <= 9600 * MARGIN)
2797 spd = B9600;
2798 else if (speed <= 19200 * MARGIN)
2799 spd = B19200;
2800 else if (speed <= 38400 * MARGIN)
2801 spd = B38400;
2802 else if (speed <= 57600 * MARGIN)
2803 spd = B57600;
2804 else if (speed <= 115200 * MARGIN)
2805 spd = B115200;
2806 else
2807 spd = B115200;
2808
2809 cfsetispeed(&tty, spd);
2810 cfsetospeed(&tty, spd);
2811
2812 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2813 |INLCR|IGNCR|ICRNL|IXON);
2814 tty.c_oflag |= OPOST;
2815 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2816 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2817 switch(data_bits) {
2818 default:
2819 case 8:
2820 tty.c_cflag |= CS8;
2821 break;
2822 case 7:
2823 tty.c_cflag |= CS7;
2824 break;
2825 case 6:
2826 tty.c_cflag |= CS6;
2827 break;
2828 case 5:
2829 tty.c_cflag |= CS5;
2830 break;
2831 }
2832 switch(parity) {
2833 default:
2834 case 'N':
2835 break;
2836 case 'E':
2837 tty.c_cflag |= PARENB;
2838 break;
2839 case 'O':
2840 tty.c_cflag |= PARENB | PARODD;
2841 break;
2842 }
2843 if (stop_bits == 2)
2844 tty.c_cflag |= CSTOPB;
2845
2846 tcsetattr (fd, TCSANOW, &tty);
2847}
2848
2849static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2850{
2851 FDCharDriver *s = chr->opaque;
2852
2853 switch(cmd) {
2854 case CHR_IOCTL_SERIAL_SET_PARAMS:
2855 {
2856 QEMUSerialSetParams *ssp = arg;
2857 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2858 ssp->data_bits, ssp->stop_bits);
2859 }
2860 break;
2861 case CHR_IOCTL_SERIAL_SET_BREAK:
2862 {
2863 int enable = *(int *)arg;
2864 if (enable)
2865 tcsendbreak(s->fd_in, 1);
2866 }
2867 break;
2868 case CHR_IOCTL_SERIAL_GET_TIOCM:
2869 {
2870 int sarg = 0;
2871 int *targ = (int *)arg;
2872 ioctl(s->fd_in, TIOCMGET, &sarg);
2873 *targ = 0;
2874 if (sarg | TIOCM_CTS)
2875 *targ |= CHR_TIOCM_CTS;
2876 if (sarg | TIOCM_CAR)
2877 *targ |= CHR_TIOCM_CAR;
2878 if (sarg | TIOCM_DSR)
2879 *targ |= CHR_TIOCM_DSR;
2880 if (sarg | TIOCM_RI)
2881 *targ |= CHR_TIOCM_RI;
2882 if (sarg | TIOCM_DTR)
2883 *targ |= CHR_TIOCM_DTR;
2884 if (sarg | TIOCM_RTS)
2885 *targ |= CHR_TIOCM_RTS;
2886 }
2887 break;
2888 case CHR_IOCTL_SERIAL_SET_TIOCM:
2889 {
2890 int sarg = *(int *)arg;
2891 int targ = 0;
2892 if (sarg | CHR_TIOCM_DTR)
2893 targ |= TIOCM_DTR;
2894 if (sarg | CHR_TIOCM_RTS)
2895 targ |= TIOCM_RTS;
2896 ioctl(s->fd_in, TIOCMSET, &targ);
2897 }
2898 break;
2899 default:
2900 return -ENOTSUP;
2901 }
2902 return 0;
2903}
2904
2905static CharDriverState *qemu_chr_open_tty(const char *filename)
2906{
2907 CharDriverState *chr;
2908 int fd;
2909
2910 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2911 tty_serial_init(fd, 115200, 'N', 8, 1);
2912 chr = qemu_chr_open_fd(fd, fd);
2913 if (!chr) {
2914 close(fd);
2915 return NULL;
2916 }
2917 chr->chr_ioctl = tty_serial_ioctl;
2918 qemu_chr_reset(chr);
2919 return chr;
2920}
2921
2922#if defined(__linux__)
2923typedef struct {
2924 int fd;
2925 int mode;
2926} ParallelCharDriver;
2927
2928static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2929{
2930 if (s->mode != mode) {
2931 int m = mode;
2932 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2933 return 0;
2934 s->mode = mode;
2935 }
2936 return 1;
2937}
2938
2939static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2940{
2941 ParallelCharDriver *drv = chr->opaque;
2942 int fd = drv->fd;
2943 uint8_t b;
2944
2945 switch(cmd) {
2946 case CHR_IOCTL_PP_READ_DATA:
2947 if (ioctl(fd, PPRDATA, &b) < 0)
2948 return -ENOTSUP;
2949 *(uint8_t *)arg = b;
2950 break;
2951 case CHR_IOCTL_PP_WRITE_DATA:
2952 b = *(uint8_t *)arg;
2953 if (ioctl(fd, PPWDATA, &b) < 0)
2954 return -ENOTSUP;
2955 break;
2956 case CHR_IOCTL_PP_READ_CONTROL:
2957 if (ioctl(fd, PPRCONTROL, &b) < 0)
2958 return -ENOTSUP;
2959 /* Linux gives only the lowest bits, and no way to know data
2960 direction! For better compatibility set the fixed upper
2961 bits. */
2962 *(uint8_t *)arg = b | 0xc0;
2963 break;
2964 case CHR_IOCTL_PP_WRITE_CONTROL:
2965 b = *(uint8_t *)arg;
2966 if (ioctl(fd, PPWCONTROL, &b) < 0)
2967 return -ENOTSUP;
2968 break;
2969 case CHR_IOCTL_PP_READ_STATUS:
2970 if (ioctl(fd, PPRSTATUS, &b) < 0)
2971 return -ENOTSUP;
2972 *(uint8_t *)arg = b;
2973 break;
2974 case CHR_IOCTL_PP_DATA_DIR:
2975 if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2976 return -ENOTSUP;
2977 break;
2978 case CHR_IOCTL_PP_EPP_READ_ADDR:
2979 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2980 struct ParallelIOArg *parg = arg;
2981 int n = read(fd, parg->buffer, parg->count);
2982 if (n != parg->count) {
2983 return -EIO;
2984 }
2985 }
2986 break;
2987 case CHR_IOCTL_PP_EPP_READ:
2988 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2989 struct ParallelIOArg *parg = arg;
2990 int n = read(fd, parg->buffer, parg->count);
2991 if (n != parg->count) {
2992 return -EIO;
2993 }
2994 }
2995 break;
2996 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2997 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2998 struct ParallelIOArg *parg = arg;
2999 int n = write(fd, parg->buffer, parg->count);
3000 if (n != parg->count) {
3001 return -EIO;
3002 }
3003 }
3004 break;
3005 case CHR_IOCTL_PP_EPP_WRITE:
3006 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
3007 struct ParallelIOArg *parg = arg;
3008 int n = write(fd, parg->buffer, parg->count);
3009 if (n != parg->count) {
3010 return -EIO;
3011 }
3012 }
3013 break;
3014 default:
3015 return -ENOTSUP;
3016 }
3017 return 0;
3018}
3019
3020static void pp_close(CharDriverState *chr)
3021{
3022 ParallelCharDriver *drv = chr->opaque;
3023 int fd = drv->fd;
3024
3025 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
3026 ioctl(fd, PPRELEASE);
3027 close(fd);
3028 qemu_free(drv);
3029}
3030
3031static CharDriverState *qemu_chr_open_pp(const char *filename)
3032{
3033 CharDriverState *chr;
3034 ParallelCharDriver *drv;
3035 int fd;
3036
3037 TFR(fd = open(filename, O_RDWR));
3038 if (fd < 0)
3039 return NULL;
3040
3041 if (ioctl(fd, PPCLAIM) < 0) {
3042 close(fd);
3043 return NULL;
3044 }
3045
3046 drv = qemu_mallocz(sizeof(ParallelCharDriver));
3047 if (!drv) {
3048 close(fd);
3049 return NULL;
3050 }
3051 drv->fd = fd;
3052 drv->mode = IEEE1284_MODE_COMPAT;
3053
3054 chr = qemu_mallocz(sizeof(CharDriverState));
3055 if (!chr) {
3056 qemu_free(drv);
3057 close(fd);
3058 return NULL;
3059 }
3060 chr->chr_write = null_chr_write;
3061 chr->chr_ioctl = pp_ioctl;
3062 chr->chr_close = pp_close;
3063 chr->opaque = drv;
3064
3065 qemu_chr_reset(chr);
3066
3067 return chr;
3068}
3069#endif /* __linux__ */
3070
3071#else /* _WIN32 */
3072
3073typedef struct {
3074 int max_size;
3075 HANDLE hcom, hrecv, hsend;
3076 OVERLAPPED orecv, osend;
3077 BOOL fpipe;
3078 DWORD len;
3079} WinCharState;
3080
3081#define NSENDBUF 2048
3082#define NRECVBUF 2048
3083#define MAXCONNECT 1
3084#define NTIMEOUT 5000
3085
3086static int win_chr_poll(void *opaque);
3087static int win_chr_pipe_poll(void *opaque);
3088
3089static void win_chr_close(CharDriverState *chr)
3090{
3091 WinCharState *s = chr->opaque;
3092
3093 if (s->hsend) {
3094 CloseHandle(s->hsend);
3095 s->hsend = NULL;
3096 }
3097 if (s->hrecv) {
3098 CloseHandle(s->hrecv);
3099 s->hrecv = NULL;
3100 }
3101 if (s->hcom) {
3102 CloseHandle(s->hcom);
3103 s->hcom = NULL;
3104 }
3105 if (s->fpipe)
3106 qemu_del_polling_cb(win_chr_pipe_poll, chr);
3107 else
3108 qemu_del_polling_cb(win_chr_poll, chr);
3109}
3110
3111static int win_chr_init(CharDriverState *chr, const char *filename)
3112{
3113 WinCharState *s = chr->opaque;
3114 COMMCONFIG comcfg;
3115 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
3116 COMSTAT comstat;
3117 DWORD size;
3118 DWORD err;
3119
3120 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3121 if (!s->hsend) {
3122 fprintf(stderr, "Failed CreateEvent\n");
3123 goto fail;
3124 }
3125 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3126 if (!s->hrecv) {
3127 fprintf(stderr, "Failed CreateEvent\n");
3128 goto fail;
3129 }
3130
3131 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
3132 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
3133 if (s->hcom == INVALID_HANDLE_VALUE) {
3134 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
3135 s->hcom = NULL;
3136 goto fail;
3137 }
3138
3139 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3140 fprintf(stderr, "Failed SetupComm\n");
3141 goto fail;
3142 }
3143
3144 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3145 size = sizeof(COMMCONFIG);
3146 GetDefaultCommConfig(filename, &comcfg, &size);
3147 comcfg.dcb.DCBlength = sizeof(DCB);
3148 CommConfigDialog(filename, NULL, &comcfg);
3149
3150 if (!SetCommState(s->hcom, &comcfg.dcb)) {
3151 fprintf(stderr, "Failed SetCommState\n");
3152 goto fail;
3153 }
3154
3155 if (!SetCommMask(s->hcom, EV_ERR)) {
3156 fprintf(stderr, "Failed SetCommMask\n");
3157 goto fail;
3158 }
3159
3160 cto.ReadIntervalTimeout = MAXDWORD;
3161 if (!SetCommTimeouts(s->hcom, &cto)) {
3162 fprintf(stderr, "Failed SetCommTimeouts\n");
3163 goto fail;
3164 }
3165
3166 if (!ClearCommError(s->hcom, &err, &comstat)) {
3167 fprintf(stderr, "Failed ClearCommError\n");
3168 goto fail;
3169 }
3170 qemu_add_polling_cb(win_chr_poll, chr);
3171 return 0;
3172
3173 fail:
3174 win_chr_close(chr);
3175 return -1;
3176}
3177
3178static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3179{
3180 WinCharState *s = chr->opaque;
3181 DWORD len, ret, size, err;
3182
3183 len = len1;
3184 ZeroMemory(&s->osend, sizeof(s->osend));
3185 s->osend.hEvent = s->hsend;
3186 while (len > 0) {
3187 if (s->hsend)
3188 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3189 else
3190 ret = WriteFile(s->hcom, buf, len, &size, NULL);
3191 if (!ret) {
3192 err = GetLastError();
3193 if (err == ERROR_IO_PENDING) {
3194 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3195 if (ret) {
3196 buf += size;
3197 len -= size;
3198 } else {
3199 break;
3200 }
3201 } else {
3202 break;
3203 }
3204 } else {
3205 buf += size;
3206 len -= size;
3207 }
3208 }
3209 return len1 - len;
3210}
3211
3212static int win_chr_read_poll(CharDriverState *chr)
3213{
3214 WinCharState *s = chr->opaque;
3215
3216 s->max_size = qemu_chr_can_read(chr);
3217 return s->max_size;
3218}
3219
3220static void win_chr_readfile(CharDriverState *chr)
3221{
3222 WinCharState *s = chr->opaque;
3223 int ret, err;
3224 uint8_t buf[1024];
3225 DWORD size;
3226
3227 ZeroMemory(&s->orecv, sizeof(s->orecv));
3228 s->orecv.hEvent = s->hrecv;
3229 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3230 if (!ret) {
3231 err = GetLastError();
3232 if (err == ERROR_IO_PENDING) {
3233 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3234 }
3235 }
3236
3237 if (size > 0) {
3238 qemu_chr_read(chr, buf, size);
3239 }
3240}
3241
3242static void win_chr_read(CharDriverState *chr)
3243{
3244 WinCharState *s = chr->opaque;
3245
3246 if (s->len > s->max_size)
3247 s->len = s->max_size;
3248 if (s->len == 0)
3249 return;
3250
3251 win_chr_readfile(chr);
3252}
3253
3254static int win_chr_poll(void *opaque)
3255{
3256 CharDriverState *chr = opaque;
3257 WinCharState *s = chr->opaque;
3258 COMSTAT status;
3259 DWORD comerr;
3260
3261 ClearCommError(s->hcom, &comerr, &status);
3262 if (status.cbInQue > 0) {
3263 s->len = status.cbInQue;
3264 win_chr_read_poll(chr);
3265 win_chr_read(chr);
3266 return 1;
3267 }
3268 return 0;
3269}
3270
3271static CharDriverState *qemu_chr_open_win(const char *filename)
3272{
3273 CharDriverState *chr;
3274 WinCharState *s;
3275
3276 chr = qemu_mallocz(sizeof(CharDriverState));
3277 if (!chr)
3278 return NULL;
3279 s = qemu_mallocz(sizeof(WinCharState));
3280 if (!s) {
3281 free(chr);
3282 return NULL;
3283 }
3284 chr->opaque = s;
3285 chr->chr_write = win_chr_write;
3286 chr->chr_close = win_chr_close;
3287
3288 if (win_chr_init(chr, filename) < 0) {
3289 free(s);
3290 free(chr);
3291 return NULL;
3292 }
3293 qemu_chr_reset(chr);
3294 return chr;
3295}
3296
3297static int win_chr_pipe_poll(void *opaque)
3298{
3299 CharDriverState *chr = opaque;
3300 WinCharState *s = chr->opaque;
3301 DWORD size;
3302
3303 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3304 if (size > 0) {
3305 s->len = size;
3306 win_chr_read_poll(chr);
3307 win_chr_read(chr);
3308 return 1;
3309 }
3310 return 0;
3311}
3312
3313static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3314{
3315 WinCharState *s = chr->opaque;
3316 OVERLAPPED ov;
3317 int ret;
3318 DWORD size;
3319 char openname[256];
3320
3321 s->fpipe = TRUE;
3322
3323 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3324 if (!s->hsend) {
3325 fprintf(stderr, "Failed CreateEvent\n");
3326 goto fail;
3327 }
3328 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3329 if (!s->hrecv) {
3330 fprintf(stderr, "Failed CreateEvent\n");
3331 goto fail;
3332 }
3333
3334 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3335 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3336 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3337 PIPE_WAIT,
3338 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3339 if (s->hcom == INVALID_HANDLE_VALUE) {
3340 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3341 s->hcom = NULL;
3342 goto fail;
3343 }
3344
3345 ZeroMemory(&ov, sizeof(ov));
3346 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3347 ret = ConnectNamedPipe(s->hcom, &ov);
3348 if (ret) {
3349 fprintf(stderr, "Failed ConnectNamedPipe\n");
3350 goto fail;
3351 }
3352
3353 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3354 if (!ret) {
3355 fprintf(stderr, "Failed GetOverlappedResult\n");
3356 if (ov.hEvent) {
3357 CloseHandle(ov.hEvent);
3358 ov.hEvent = NULL;
3359 }
3360 goto fail;
3361 }
3362
3363 if (ov.hEvent) {
3364 CloseHandle(ov.hEvent);
3365 ov.hEvent = NULL;
3366 }
3367 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3368 return 0;
3369
3370 fail:
3371 win_chr_close(chr);
3372 return -1;
3373}
3374
3375
3376static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3377{
3378 CharDriverState *chr;
3379 WinCharState *s;
3380
3381 chr = qemu_mallocz(sizeof(CharDriverState));
3382 if (!chr)
3383 return NULL;
3384 s = qemu_mallocz(sizeof(WinCharState));
3385 if (!s) {
3386 free(chr);
3387 return NULL;
3388 }
3389 chr->opaque = s;
3390 chr->chr_write = win_chr_write;
3391 chr->chr_close = win_chr_close;
3392
3393 if (win_chr_pipe_init(chr, filename) < 0) {
3394 free(s);
3395 free(chr);
3396 return NULL;
3397 }
3398 qemu_chr_reset(chr);
3399 return chr;
3400}
3401
3402static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3403{
3404 CharDriverState *chr;
3405 WinCharState *s;
3406
3407 chr = qemu_mallocz(sizeof(CharDriverState));
3408 if (!chr)
3409 return NULL;
3410 s = qemu_mallocz(sizeof(WinCharState));
3411 if (!s) {
3412 free(chr);
3413 return NULL;
3414 }
3415 s->hcom = fd_out;
3416 chr->opaque = s;
3417 chr->chr_write = win_chr_write;
3418 qemu_chr_reset(chr);
3419 return chr;
3420}
3421
3422static CharDriverState *qemu_chr_open_win_con(const char *filename)
3423{
3424 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3425}
3426
3427static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3428{
3429 HANDLE fd_out;
3430
3431 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3432 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3433 if (fd_out == INVALID_HANDLE_VALUE)
3434 return NULL;
3435
3436 return qemu_chr_open_win_file(fd_out);
3437}
3438#endif /* !_WIN32 */
3439
3440/***********************************************************/
3441/* UDP Net console */
3442
3443typedef struct {
3444 int fd;
3445 SockAddress daddr;
3446 uint8_t buf[1024];
3447 int bufcnt;
3448 int bufptr;
3449 int max_size;
3450} NetCharDriver;
3451
3452static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3453{
3454 NetCharDriver *s = chr->opaque;
3455
3456 return socket_sendto(s->fd, buf, len, &s->daddr);
3457}
3458
3459static int udp_chr_read_poll(void *opaque)
3460{
3461 CharDriverState *chr = opaque;
3462 NetCharDriver *s = chr->opaque;
3463
3464 s->max_size = qemu_chr_can_read(chr);
3465
3466 /* If there were any stray characters in the queue process them
3467 * first
3468 */
3469 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3470 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3471 s->bufptr++;
3472 s->max_size = qemu_chr_can_read(chr);
3473 }
3474 return s->max_size;
3475}
3476
3477static void udp_chr_read(void *opaque)
3478{
3479 CharDriverState *chr = opaque;
3480 NetCharDriver *s = chr->opaque;
3481
3482 if (s->max_size == 0)
3483 return;
3484 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3485 s->bufptr = s->bufcnt;
3486 if (s->bufcnt <= 0)
3487 return;
3488
3489 s->bufptr = 0;
3490 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3491 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3492 s->bufptr++;
3493 s->max_size = qemu_chr_can_read(chr);
3494 }
3495}
3496
3497static void udp_chr_update_read_handler(CharDriverState *chr)
3498{
3499 NetCharDriver *s = chr->opaque;
3500
3501 if (s->fd >= 0) {
3502 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3503 udp_chr_read, NULL, chr);
3504 }
3505}
3506
3507int parse_host_port(SockAddress *saddr, const char *str);
3508int parse_host_src_port(SockAddress *haddr,
3509 SockAddress *saddr,
3510 const char *str);
3511#ifndef _WIN32
3512static int parse_unix_path(SockAddress *uaddr, const char* str);
3513#endif
3514
3515static CharDriverState *qemu_chr_open_udp(const char *def)
3516{
3517 CharDriverState *chr = NULL;
3518 NetCharDriver *s = NULL;
3519 int fd = -1;
3520 SockAddress saddr;
3521
3522 chr = qemu_mallocz(sizeof(CharDriverState));
3523 if (!chr)
3524 goto return_err;
3525 s = qemu_mallocz(sizeof(NetCharDriver));
3526 if (!s)
3527 goto return_err;
3528
3529 fd = socket(PF_INET, SOCK_DGRAM, 0);
3530 if (fd < 0) {
3531 perror("socket(PF_INET, SOCK_DGRAM)");
3532 goto return_err;
3533 }
3534
3535 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3536 printf("Could not parse: %s\n", def);
3537 goto return_err;
3538 }
3539
3540 if (socket_bind(fd, &saddr) < 0)
3541 {
3542 perror("bind");
3543 goto return_err;
3544 }
3545
3546 s->fd = fd;
3547 s->bufcnt = 0;
3548 s->bufptr = 0;
3549 chr->opaque = s;
3550 chr->chr_write = udp_chr_write;
3551 chr->chr_update_read_handler = udp_chr_update_read_handler;
3552 return chr;
3553
3554return_err:
3555 if (chr)
3556 free(chr);
3557 if (s)
3558 free(s);
3559 if (fd >= 0)
3560 closesocket(fd);
3561 return NULL;
3562}
3563
3564/***********************************************************/
3565/* TCP Net console */
3566
3567typedef struct {
3568 int fd, listen_fd;
3569 int connected;
3570 int max_size;
3571 int do_telnetopt;
3572 int do_nodelay;
3573 int is_unix;
3574} TCPCharDriver;
3575
3576static void tcp_chr_accept(void *opaque);
3577
3578static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3579{
3580 TCPCharDriver *s = chr->opaque;
3581 if (s->connected) {
3582 return send_all(s->fd, buf, len);
3583 } else {
3584 /* XXX: indicate an error ? */
3585 return len;
3586 }
3587}
3588
3589static int tcp_chr_read_poll(void *opaque)
3590{
3591 CharDriverState *chr = opaque;
3592 TCPCharDriver *s = chr->opaque;
3593 if (!s->connected)
3594 return 0;
3595 s->max_size = qemu_chr_can_read(chr);
3596 return s->max_size;
3597}
3598
3599#define IAC 255
3600#define IAC_BREAK 243
3601static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3602 TCPCharDriver *s,
3603 uint8_t *buf, int *size)
3604{
3605 /* Handle any telnet client's basic IAC options to satisfy char by
3606 * char mode with no echo. All IAC options will be removed from
3607 * the buf and the do_telnetopt variable will be used to track the
3608 * state of the width of the IAC information.
3609 *
3610 * IAC commands come in sets of 3 bytes with the exception of the
3611 * "IAC BREAK" command and the double IAC.
3612 */
3613
3614 int i;
3615 int j = 0;
3616
3617 for (i = 0; i < *size; i++) {
3618 if (s->do_telnetopt > 1) {
3619 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3620 /* Double IAC means send an IAC */
3621 if (j != i)
3622 buf[j] = buf[i];
3623 j++;
3624 s->do_telnetopt = 1;
3625 } else {
3626 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3627 /* Handle IAC break commands by sending a serial break */
3628 qemu_chr_event(chr, CHR_EVENT_BREAK);
3629 s->do_telnetopt++;
3630 }
3631 s->do_telnetopt++;
3632 }
3633 if (s->do_telnetopt >= 4) {
3634 s->do_telnetopt = 1;
3635 }
3636 } else {
3637 if ((unsigned char)buf[i] == IAC) {
3638 s->do_telnetopt = 2;
3639 } else {
3640 if (j != i)
3641 buf[j] = buf[i];
3642 j++;
3643 }
3644 }
3645 }
3646 *size = j;
3647}
3648
3649static void tcp_chr_read(void *opaque)
3650{
3651 CharDriverState *chr = opaque;
3652 TCPCharDriver *s = chr->opaque;
3653 uint8_t buf[1024];
3654 int len, size;
3655
3656 if (!s->connected || s->max_size <= 0)
3657 return;
3658 len = sizeof(buf);
3659 if (len > s->max_size)
3660 len = s->max_size;
3661 size = socket_recv(s->fd, buf, len);
3662 if (size == 0) {
3663 /* connection closed */
3664 s->connected = 0;
3665 if (s->listen_fd >= 0) {
3666 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3667 }
3668 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3669 socket_close(s->fd);
3670 s->fd = -1;
3671 } else if (size > 0) {
3672 if (s->do_telnetopt)
3673 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3674 if (size > 0)
3675 qemu_chr_read(chr, buf, size);
3676 }
3677}
3678
3679static void tcp_chr_connect(void *opaque)
3680{
3681 CharDriverState *chr = opaque;
3682 TCPCharDriver *s = chr->opaque;
3683
3684 s->connected = 1;
3685 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3686 tcp_chr_read, NULL, chr);
3687 qemu_chr_reset(chr);
3688}
3689
3690#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3691static void tcp_chr_telnet_init(int fd)
3692{
3693 char buf[3];
3694 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3695 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3696 socket_send(fd, (char *)buf, 3);
3697 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3698 socket_send(fd, (char *)buf, 3);
3699 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3700 socket_send(fd, (char *)buf, 3);
3701 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3702 socket_send(fd, (char *)buf, 3);
3703}
3704
3705static void tcp_chr_accept(void *opaque)
3706{
3707 CharDriverState *chr = opaque;
3708 TCPCharDriver *s = chr->opaque;
3709 int fd;
3710
3711 for(;;) {
3712 fd = socket_accept(s->listen_fd, NULL);
3713 if (fd < 0) {
3714 return;
3715 } else if (fd >= 0) {
3716 if (s->do_telnetopt)
3717 tcp_chr_telnet_init(fd);
3718 break;
3719 }
3720 }
3721 socket_set_nonblock(fd);
3722 if (s->do_nodelay)
3723 socket_set_nodelay(fd);
3724 s->fd = fd;
3725 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3726 tcp_chr_connect(chr);
3727}
3728
3729static void tcp_chr_close(CharDriverState *chr)
3730{
3731 TCPCharDriver *s = chr->opaque;
3732 if (s->fd >= 0)
3733 closesocket(s->fd);
3734 if (s->listen_fd >= 0)
3735 closesocket(s->listen_fd);
3736 qemu_free(s);
3737}
3738
3739static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3740 int is_telnet,
3741 int is_unix)
3742{
3743 CharDriverState *chr = NULL;
3744 TCPCharDriver *s = NULL;
3745 int fd = -1, ret, err;
3746 int is_listen = 0;
3747 int is_waitconnect = 1;
3748 int do_nodelay = 0;
3749 const char *ptr;
3750 SockAddress saddr;
3751
3752#ifndef _WIN32
3753 if (is_unix) {
3754 if (parse_unix_path(&saddr, host_str) < 0)
3755 goto fail;
3756 } else
3757#endif
3758 {
3759 if (parse_host_port(&saddr, host_str) < 0)
3760 goto fail;
3761 }
3762
3763 ptr = host_str;
3764 while((ptr = strchr(ptr,','))) {
3765 ptr++;
3766 if (!strncmp(ptr,"server",6)) {
3767 is_listen = 1;
3768 } else if (!strncmp(ptr,"nowait",6)) {
3769 is_waitconnect = 0;
3770 } else if (!strncmp(ptr,"nodelay",6)) {
3771 do_nodelay = 1;
3772 } else {
3773 printf("Unknown option: %s\n", ptr);
3774 goto fail;
3775 }
3776 }
3777 if (!is_listen)
3778 is_waitconnect = 0;
3779
3780 chr = qemu_mallocz(sizeof(CharDriverState));
3781 if (!chr)
3782 goto fail;
3783 s = qemu_mallocz(sizeof(TCPCharDriver));
3784 if (!s)
3785 goto fail;
3786
3787#ifndef _WIN32
3788 if (is_unix)
3789 fd = socket_create( SOCKET_UNIX, SOCKET_STREAM );
3790 else
3791#endif
3792 fd = socket_create_inet( SOCKET_STREAM );
3793
3794 if (fd < 0)
3795 goto fail;
3796
3797 if (!is_waitconnect)
3798 socket_set_nonblock(fd);
3799
3800 s->connected = 0;
3801 s->fd = -1;
3802 s->listen_fd = -1;
3803 s->is_unix = is_unix;
3804 s->do_nodelay = do_nodelay && !is_unix;
3805
3806 chr->opaque = s;
3807 chr->chr_write = tcp_chr_write;
3808 chr->chr_close = tcp_chr_close;
3809
3810 if (is_listen) {
3811 /* allow fast reuse */
3812#ifndef _WIN32
3813 if (is_unix) {
3814 unlink( sock_address_get_path(&saddr) );
3815 } else
3816#endif
3817 socket_set_xreuseaddr(fd);
3818
3819 if (socket_bind(fd, &saddr) < 0 ||
3820 socket_listen(fd, 0) < 0)
3821 goto fail;
3822
3823 s->listen_fd = fd;
3824 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3825 if (is_telnet)
3826 s->do_telnetopt = 1;
3827 } else {
3828 for(;;) {
3829 ret = socket_connect(fd, &saddr);
3830 if (ret < 0) {
3831 err = errno;
3832 if (err == EINTR || err == EWOULDBLOCK) {
3833 } else if (err == EINPROGRESS) {
3834 break;
3835#ifdef _WIN32
3836 } else if (err == EALREADY) {
3837 break;
3838#endif
3839 } else {
3840 goto fail;
3841 }
3842 } else {
3843 s->connected = 1;
3844 break;
3845 }
3846 }
3847 s->fd = fd;
3848 socket_set_nodelay(fd);
3849 if (s->connected)
3850 tcp_chr_connect(chr);
3851 else
3852 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3853 }
3854
3855 if (is_listen && is_waitconnect) {
3856 printf("QEMU waiting for connection on: %s\n", host_str);
3857 tcp_chr_accept(chr);
3858 socket_set_nonblock(s->listen_fd);
3859 }
3860
3861 return chr;
3862 fail:
3863 if (fd >= 0)
3864 socket_close(fd);
3865 qemu_free(s);
3866 qemu_free(chr);
3867 return NULL;
3868}
3869
3870CharDriverState *qemu_chr_open(const char *filename)
3871{
3872 const char *p;
3873
3874 if (!strcmp(filename, "vc")) {
3875 return text_console_init(&display_state, 0);
3876 } else if (strstart(filename, "vc:", &p)) {
3877 return text_console_init(&display_state, p);
3878 } else if (!strcmp(filename, "null")) {
3879 return qemu_chr_open_null();
3880 } else
3881 if (strstart(filename, "tcp:", &p)) {
3882 return qemu_chr_open_tcp(p, 0, 0);
3883 } else
3884 if (strstart(filename, "telnet:", &p)) {
3885 return qemu_chr_open_tcp(p, 1, 0);
3886 } else
3887 if (strstart(filename, "udp:", &p)) {
3888 return qemu_chr_open_udp(p);
3889 } else
3890 if (strstart(filename, "mon:", &p)) {
3891 CharDriverState *drv = qemu_chr_open(p);
3892 if (drv) {
3893 drv = qemu_chr_open_mux(drv);
3894 monitor_init(drv, !nographic);
3895 return drv;
3896 }
3897 printf("Unable to open driver: %s\n", p);
3898 return 0;
3899 } else
3900#ifndef _WIN32
3901 if (strstart(filename, "unix:", &p)) {
3902 return qemu_chr_open_tcp(p, 0, 1);
3903 } else if (strstart(filename, "file:", &p)) {
3904 return qemu_chr_open_file_out(p);
3905 } else if (strstart(filename, "pipe:", &p)) {
3906 return qemu_chr_open_pipe(p);
3907 } else if (!strcmp(filename, "pty")) {
3908 return qemu_chr_open_pty();
3909 } else if (!strcmp(filename, "stdio")) {
3910 return qemu_chr_open_stdio();
3911 } else if (strstart(filename, "fdpair:", &p)) {
3912 return qemu_chr_open_fdpair(p);
3913 } else
3914#endif
3915#if defined(__linux__)
3916 if (strstart(filename, "/dev/parport", NULL)) {
3917 return qemu_chr_open_pp(filename);
3918 } else
3919#endif
3920#ifndef _WIN32
3921 if (strstart(filename, "/dev/", NULL)) {
3922 return qemu_chr_open_tty(filename);
3923 } else
3924#endif
3925 if (!strcmp(filename, "android-modem")) {
3926 CharDriverState* cs;
3927 qemu_chr_open_charpipe( &cs, &android_modem_cs );
3928 return cs;
3929 } else if (!strcmp(filename, "android-gps")) {
3930 CharDriverState* cs;
3931 qemu_chr_open_charpipe( &cs, &android_gps_cs );
3932 return cs;
3933 } else if (!strcmp(filename, "android-kmsg")) {
3934 return android_kmsg_get_cs();
3935 } else if (!strcmp(filename, "android-qemud")) {
3936 return android_qemud_get_cs();
3937 } else
3938#if defined(__linux__)
3939 if (strstart(filename, "/dev/parport", NULL)) {
3940 return qemu_chr_open_pp(filename);
3941 } else
3942#endif
3943#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3944 || defined(__NetBSD__) || defined(__OpenBSD__)
3945 if (strstart(filename, "/dev/", NULL)) {
3946 return qemu_chr_open_tty(filename);
3947 } else
3948#endif
3949#ifdef _WIN32
3950 if (strstart(filename, "COM", NULL)) {
3951 return qemu_chr_open_win(filename);
3952 } else
3953 if (strstart(filename, "pipe:", &p)) {
3954 return qemu_chr_open_win_pipe(p);
3955 } else
3956 if (strstart(filename, "con:", NULL)) {
3957 return qemu_chr_open_win_con(filename);
3958 } else
3959 if (strstart(filename, "file:", &p)) {
3960 return qemu_chr_open_win_file_out(p);
3961 } else
3962#endif
3963#ifdef CONFIG_BRLAPI
3964 if (!strcmp(filename, "braille")) {
3965 return chr_baum_init();
3966 } else
3967#endif
3968 {
3969 return NULL;
3970 }
3971}
3972
3973void qemu_chr_close(CharDriverState *chr)
3974{
3975 if (chr->chr_close)
3976 chr->chr_close(chr);
3977 qemu_free(chr);
3978}
3979
3980/***********************************************************/
3981/* network device redirectors */
3982
3983__attribute__ (( unused ))
3984static void hex_dump(FILE *f, const uint8_t *buf, int size)
3985{
3986 int len, i, j, c;
3987
3988 for(i=0;i<size;i+=16) {
3989 len = size - i;
3990 if (len > 16)
3991 len = 16;
3992 fprintf(f, "%08x ", i);
3993 for(j=0;j<16;j++) {
3994 if (j < len)
3995 fprintf(f, " %02x", buf[i+j]);
3996 else
3997 fprintf(f, " ");
3998 }
3999 fprintf(f, " ");
4000 for(j=0;j<len;j++) {
4001 c = buf[i+j];
4002 if (c < ' ' || c > '~')
4003 c = '.';
4004 fprintf(f, "%c", c);
4005 }
4006 fprintf(f, "\n");
4007 }
4008}
4009
4010static int parse_macaddr(uint8_t *macaddr, const char *p)
4011{
4012 int i;
4013 char *last_char;
4014 long int offset;
4015
4016 errno = 0;
4017 offset = strtol(p, &last_char, 0);
4018 if (0 == errno && '\0' == *last_char &&
4019 offset >= 0 && offset <= 0xFFFFFF) {
4020 macaddr[3] = (offset & 0xFF0000) >> 16;
4021 macaddr[4] = (offset & 0xFF00) >> 8;
4022 macaddr[5] = offset & 0xFF;
4023 return 0;
4024 } else {
4025 for(i = 0; i < 6; i++) {
4026 macaddr[i] = strtol(p, (char **)&p, 16);
4027 if (i == 5) {
4028 if (*p != '\0')
4029 return -1;
4030 } else {
4031 if (*p != ':' && *p != '-')
4032 return -1;
4033 p++;
4034 }
4035 }
4036 return 0;
4037 }
4038
4039 return -1;
4040}
4041
4042static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
4043{
4044 const char *p, *p1;
4045 int len;
4046 p = *pp;
4047 p1 = strchr(p, sep);
4048 if (!p1)
4049 return -1;
4050 len = p1 - p;
4051 p1++;
4052 if (buf_size > 0) {
4053 if (len > buf_size - 1)
4054 len = buf_size - 1;
4055 memcpy(buf, p, len);
4056 buf[len] = '\0';
4057 }
4058 *pp = p1;
4059 return 0;
4060}
4061
4062int parse_host_src_port(SockAddress *haddr,
4063 SockAddress *saddr,
4064 const char *input_str)
4065{
4066 char *str = strdup(input_str);
4067 char *host_str = str;
4068 char *src_str;
4069 const char *src_str2;
4070 char *ptr;
4071
4072 /*
4073 * Chop off any extra arguments at the end of the string which
4074 * would start with a comma, then fill in the src port information
4075 * if it was provided else use the "any address" and "any port".
4076 */
4077 if ((ptr = strchr(str,',')))
4078 *ptr = '\0';
4079
4080 if ((src_str = strchr(input_str,'@'))) {
4081 *src_str = '\0';
4082 src_str++;
4083 }
4084
4085 if (parse_host_port(haddr, host_str) < 0)
4086 goto fail;
4087
4088 src_str2 = src_str;
4089 if (!src_str || *src_str == '\0')
4090 src_str2 = ":0";
4091
4092 if (parse_host_port(saddr, src_str2) < 0)
4093 goto fail;
4094
4095 free(str);
4096 return(0);
4097
4098fail:
4099 free(str);
4100 return -1;
4101}
4102
4103int parse_host_port(SockAddress *saddr, const char *str)
4104{
4105 char buf[512];
4106 const char *p, *r;
4107 uint16_t port;
4108
4109 p = str;
4110 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4111 return -1;
4112
4113 port = strtol(p, (char **)&r, 0);
4114 if (r == p)
4115 return -1;
4116
4117 if (buf[0] == '\0') {
4118 sock_address_init_inet( saddr, SOCK_ADDRESS_INET_ANY, port );
4119 } else {
4120 if (sock_address_init_resolve( saddr, buf, port, 0 ) < 0)
4121 return -1;
4122 }
4123 return 0;
4124}
4125
4126#ifndef _WIN32
4127static int
4128parse_unix_path(SockAddress* uaddr, const char *str)
4129{
4130 char temp[109];
4131 const char *p;
4132 int len;
4133
4134 len = MIN(108, strlen(str));
4135 p = strchr(str, ',');
4136 if (p)
4137 len = MIN(len, p - str);
4138
4139 memcpy(temp, str, len);
4140 temp[len] = 0;
4141
4142 sock_address_init_unix( uaddr, temp );
4143 return 0;
4144}
4145#endif
4146
4147/* find or alloc a new VLAN */
4148VLANState *qemu_find_vlan(int id)
4149{
4150 VLANState **pvlan, *vlan;
4151 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4152 if (vlan->id == id)
4153 return vlan;
4154 }
4155 vlan = qemu_mallocz(sizeof(VLANState));
4156 if (!vlan)
4157 return NULL;
4158 vlan->id = id;
4159 vlan->next = NULL;
4160 pvlan = &first_vlan;
4161 while (*pvlan != NULL)
4162 pvlan = &(*pvlan)->next;
4163 *pvlan = vlan;
4164 return vlan;
4165}
4166
4167VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4168 IOReadHandler *fd_read,
4169 IOCanRWHandler *fd_can_read,
4170 void *opaque)
4171{
4172 VLANClientState *vc, **pvc;
4173 vc = qemu_mallocz(sizeof(VLANClientState));
4174 if (!vc)
4175 return NULL;
4176 vc->fd_read = fd_read;
4177 vc->fd_can_read = fd_can_read;
4178 vc->opaque = opaque;
4179 vc->vlan = vlan;
4180
4181 vc->next = NULL;
4182 pvc = &vlan->first_client;
4183 while (*pvc != NULL)
4184 pvc = &(*pvc)->next;
4185 *pvc = vc;
4186 return vc;
4187}
4188
4189void qemu_del_vlan_client(VLANClientState *vc)
4190{
4191 VLANClientState **pvc = &vc->vlan->first_client;
4192
4193 while (*pvc != NULL)
4194 if (*pvc == vc) {
4195 *pvc = vc->next;
4196 free(vc);
4197 break;
4198 } else
4199 pvc = &(*pvc)->next;
4200}
4201
4202int qemu_can_send_packet(VLANClientState *vc1)
4203{
4204 VLANState *vlan = vc1->vlan;
4205 VLANClientState *vc;
4206
4207 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4208 if (vc != vc1) {
4209 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4210 return 1;
4211 }
4212 }
4213 return 0;
4214}
4215
4216void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4217{
4218 VLANState *vlan = vc1->vlan;
4219 VLANClientState *vc;
4220
4221#if 0
4222 printf("vlan %d send:\n", vlan->id);
4223 hex_dump(stdout, buf, size);
4224#endif
4225 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4226 if (vc != vc1) {
4227 vc->fd_read(vc->opaque, buf, size);
4228 }
4229 }
4230}
4231
4232#if defined(CONFIG_SLIRP)
4233
4234/* slirp network adapter */
4235
4236int slirp_inited;
4237static VLANClientState *slirp_vc;
4238
4239double qemu_net_upload_speed = 0.;
4240double qemu_net_download_speed = 0.;
4241int qemu_net_min_latency = 0;
4242int qemu_net_max_latency = 0;
4243int qemu_net_disable = 0;
4244
4245int
4246ip_packet_is_internal( const uint8_t* data, size_t size )
4247{
4248 const uint8_t* end = data + size;
4249
4250 /* must have room for Mac + IP header */
4251 if (data + 40 > end)
4252 return 0;
4253
4254 if (data[12] != 0x08 || data[13] != 0x00 )
4255 return 0;
4256
4257 /* must have valid IP header */
4258 data += 14;
4259 if ((data[0] >> 4) != 4 || (data[0] & 15) < 5)
4260 return 0;
4261
4262 /* internal if both source and dest addresses are in 10.x.x.x */
4263 return ( data[12] == 10 && data[16] == 10);
4264}
4265
4266#ifdef CONFIG_SHAPER
4267
4268/* see http://en.wikipedia.org/wiki/List_of_device_bandwidths or a complete list */
4269const NetworkSpeed android_netspeeds[] = {
4270 { "gsm", "GSM/CSD", 14400, 14400 },
4271 { "hscsd", "HSCSD", 14400, 43200 },
4272 { "gprs", "GPRS", 40000, 80000 },
4273 { "edge", "EDGE/EGPRS", 118400, 236800 },
4274 { "umts", "UMTS/3G", 128000, 1920000 },
4275 { "hsdpa", "HSDPA", 348000, 14400000 },
4276 { "full", "no limit", 0, 0 },
4277 { NULL, NULL, 0, 0 }
4278};
4279
4280const NetworkLatency android_netdelays[] = {
4281 /* FIXME: these numbers are totally imaginary */
4282 { "gprs", "GPRS", 150, 550 },
4283 { "edge", "EDGE/EGPRS", 80, 400 },
4284 { "umts", "UMTS/3G", 35, 200 },
4285 { "none", "no latency", 0, 0 },
4286 { NULL, NULL, 0, 0 }
4287};
4288
4289
4290NetShaper slirp_shaper_in;
4291NetShaper slirp_shaper_out;
4292NetDelay slirp_delay_in;
4293
4294static void
4295slirp_delay_in_cb( void* data,
4296 size_t size,
4297 void* opaque )
4298{
4299 slirp_input( (const uint8_t*)data, (int)size );
4300 opaque = opaque;
4301}
4302
4303static void
4304slirp_shaper_in_cb( void* data,
4305 size_t size,
4306 void* opaque )
4307{
4308 netdelay_send_aux( slirp_delay_in, data, size, opaque );
4309}
4310
4311static void
4312slirp_shaper_out_cb( void* data,
4313 size_t size,
4314 void* opaque )
4315{
4316 qemu_send_packet( slirp_vc, (const uint8_t*)data, (int)size );
4317}
4318
4319void
4320slirp_init_shapers( void )
4321{
4322 slirp_delay_in = netdelay_create( slirp_delay_in_cb );
4323 slirp_shaper_in = netshaper_create( 1, slirp_shaper_in_cb );
4324 slirp_shaper_out = netshaper_create( 1, slirp_shaper_out_cb );
4325
4326 netdelay_set_latency( slirp_delay_in, qemu_net_min_latency, qemu_net_max_latency );
4327 netshaper_set_rate( slirp_shaper_out, qemu_net_download_speed );
4328 netshaper_set_rate( slirp_shaper_in, qemu_net_upload_speed );
4329}
4330
4331#endif /* CONFIG_SHAPER */
4332
4333int slirp_can_output(void)
4334{
4335#ifdef CONFIG_SHAPER
4336 return !slirp_vc ||
4337 ( netshaper_can_send( slirp_shaper_out ) &&
4338 qemu_can_send_packet(slirp_vc) );
4339#else
4340 return !slirp_vc || qemu_can_send_packet(slirp_vc);
4341#endif
4342}
4343
4344
4345
4346void slirp_output(const uint8_t *pkt, int pkt_len)
4347{
4348#if 0
4349 printf("slirp output:\n");
4350 hex_dump(stdout, pkt, pkt_len);
4351#endif
4352 if (!slirp_vc)
4353 return;
4354
4355 if (qemu_tcpdump_active)
4356 qemu_tcpdump_packet(pkt, pkt_len);
4357
4358 /* always send internal packets */
4359 if ( ip_packet_is_internal( pkt, pkt_len ) ) {
4360 qemu_send_packet( slirp_vc, pkt, pkt_len );
4361 return;
4362 }
4363
4364 if ( qemu_net_disable )
4365 return;
4366
4367#ifdef CONFIG_SHAPER
4368 netshaper_send( slirp_shaper_out, (void*)pkt, pkt_len );
4369#else
4370 qemu_send_packet(slirp_vc, pkt, pkt_len);
4371#endif
4372}
4373
4374static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4375{
4376#if 0
4377 printf("slirp input:\n");
4378 hex_dump(stdout, buf, size);
4379#endif
4380 if (qemu_tcpdump_active)
4381 qemu_tcpdump_packet(buf, size);
4382
4383 if ( ip_packet_is_internal( buf, size ) ) {
4384 slirp_input(buf, size);
4385 return;
4386 }
4387
4388 if (qemu_net_disable)
4389 return;
4390
4391#ifdef CONFIG_SHAPER
4392 netshaper_send( slirp_shaper_in, (char*)buf, size );
4393#else
4394 slirp_input(buf, size);
4395#endif
4396}
4397
4398static int net_slirp_init(VLANState *vlan)
4399{
4400 if (!slirp_inited) {
4401 slirp_inited = 1;
4402 slirp_init();
4403 }
4404 slirp_vc = qemu_new_vlan_client(vlan,
4405 slirp_receive, NULL, NULL);
4406 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4407 return 0;
4408}
4409
4410static void net_slirp_redir(const char *redir_str)
4411{
4412 int is_udp;
4413 char buf[256], *r;
4414 const char *p;
4415 uint32_t guest_ip;
4416 int host_port, guest_port;
4417
4418 if (!slirp_inited) {
4419 slirp_inited = 1;
4420 slirp_init();
4421 }
4422
4423 p = redir_str;
4424 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4425 goto fail;
4426 if (!strcmp(buf, "tcp")) {
4427 is_udp = 0;
4428 } else if (!strcmp(buf, "udp")) {
4429 is_udp = 1;
4430 } else {
4431 goto fail;
4432 }
4433
4434 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4435 goto fail;
4436 host_port = strtol(buf, &r, 0);
4437 if (r == buf)
4438 goto fail;
4439
4440 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4441 goto fail;
4442 if (buf[0] == '\0') {
4443 pstrcpy(buf, sizeof(buf), "10.0.2.15");
4444 }
4445 if (inet_strtoip(buf, &guest_ip) < 0)
4446 goto fail;
4447
4448 guest_port = strtol(p, &r, 0);
4449 if (r == p)
4450 goto fail;
4451
4452 if (slirp_redir(is_udp, host_port, guest_ip, guest_port) < 0) {
4453 fprintf(stderr, "qemu: could not set up redirection\n");
4454 exit(1);
4455 }
4456 return;
4457 fail:
4458 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4459 exit(1);
4460}
4461
4462#if 0 /* ANDROID disabled */
4463
4464char smb_dir[1024];
4465
4466static void erase_dir(char *dir_name)
4467{
4468 DIR *d;
4469 struct dirent *de;
4470 char filename[1024];
4471
4472 /* erase all the files in the directory */
4473 if ((d = opendir(dir_name)) != 0) {
4474 for(;;) {
4475 de = readdir(d);
4476 if (!de)
4477 break;
4478 if (strcmp(de->d_name, ".") != 0 &&
4479 strcmp(de->d_name, "..") != 0) {
4480 snprintf(filename, sizeof(filename), "%s/%s",
4481 smb_dir, de->d_name);
4482 if (unlink(filename) != 0) /* is it a directory? */
4483 erase_dir(filename);
4484 }
4485 }
4486 closedir(d);
4487 rmdir(dir_name);
4488 }
4489}
4490
4491/* automatic user mode samba server configuration */
4492static void smb_exit(void)
4493{
4494 erase_dir(smb_dir);
4495}
4496
4497/* automatic user mode samba server configuration */
4498static void net_slirp_smb(const char *exported_dir)
4499{
4500 char smb_conf[1024];
4501 char smb_cmdline[1024];
4502 FILE *f;
4503
4504 if (!slirp_inited) {
4505 slirp_inited = 1;
4506 slirp_init();
4507 }
4508
4509 /* XXX: better tmp dir construction */
4510 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4511 if (mkdir(smb_dir, 0700) < 0) {
4512 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4513 exit(1);
4514 }
4515 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4516
4517 f = fopen(smb_conf, "w");
4518 if (!f) {
4519 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4520 exit(1);
4521 }
4522 fprintf(f,
4523 "[global]\n"
4524 "private dir=%s\n"
4525 "smb ports=0\n"
4526 "socket address=127.0.0.1\n"
4527 "pid directory=%s\n"
4528 "lock directory=%s\n"
4529 "log file=%s/log.smbd\n"
4530 "smb passwd file=%s/smbpasswd\n"
4531 "security = share\n"
4532 "[qemu]\n"
4533 "path=%s\n"
4534 "read only=no\n"
4535 "guest ok=yes\n",
4536 smb_dir,
4537 smb_dir,
4538 smb_dir,
4539 smb_dir,
4540 smb_dir,
4541 exported_dir
4542 );
4543 fclose(f);
4544 atexit(smb_exit);
4545
4546 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4547 SMBD_COMMAND, smb_conf);
4548
4549 slirp_add_exec(0, smb_cmdline, 4, 139);
4550}
4551
4552#endif /* !defined(_WIN32) */
4553
4554#endif /* CONFIG_SLIRP */
4555
4556#if !defined(_WIN32)
4557
4558typedef struct TAPState {
4559 VLANClientState *vc;
4560 int fd;
4561 char down_script[1024];
4562} TAPState;
4563
4564static void tap_receive(void *opaque, const uint8_t *buf, int size)
4565{
4566 TAPState *s = opaque;
4567 int ret;
4568 for(;;) {
4569 ret = write(s->fd, buf, size);
4570 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4571 } else {
4572 break;
4573 }
4574 }
4575}
4576
4577static void tap_send(void *opaque)
4578{
4579 TAPState *s = opaque;
4580 uint8_t buf[4096];
4581 int size;
4582
4583#ifdef __sun__
4584 struct strbuf sbuf;
4585 int f = 0;
4586 sbuf.maxlen = sizeof(buf);
4587 sbuf.buf = buf;
4588 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4589#else
4590 size = read(s->fd, buf, sizeof(buf));
4591#endif
4592 if (size > 0) {
4593 qemu_send_packet(s->vc, buf, size);
4594 }
4595}
4596
4597/* fd support */
4598
4599static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4600{
4601 TAPState *s;
4602
4603 s = qemu_mallocz(sizeof(TAPState));
4604 if (!s)
4605 return NULL;
4606 s->fd = fd;
4607 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4608 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4609 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4610 return s;
4611}
4612
4613#if defined (_BSD) || defined (__FreeBSD_kernel__)
4614static int tap_open(char *ifname, int ifname_size)
4615{
4616 int fd;
4617 char *dev;
4618 struct stat s;
4619
4620 TFR(fd = open("/dev/tap", O_RDWR));
4621 if (fd < 0) {
4622 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4623 return -1;
4624 }
4625
4626 fstat(fd, &s);
4627 dev = devname(s.st_rdev, S_IFCHR);
4628 pstrcpy(ifname, ifname_size, dev);
4629
4630 fcntl(fd, F_SETFL, O_NONBLOCK);
4631 return fd;
4632}
4633#elif defined(__sun__)
4634#define TUNNEWPPA (('T'<<16) | 0x0001)
4635/*
4636 * Allocate TAP device, returns opened fd.
4637 * Stores dev name in the first arg(must be large enough).
4638 */
4639int tap_alloc(char *dev, size_t dev_size)
4640{
4641 int tap_fd, if_fd, ppa = -1;
4642 static int ip_fd = 0;
4643 char *ptr;
4644
4645 static int arp_fd = 0;
4646 int ip_muxid, arp_muxid;
4647 struct strioctl strioc_if, strioc_ppa;
4648 int link_type = I_PLINK;;
4649 struct lifreq ifr;
4650 char actual_name[32] = "";
4651
4652 memset(&ifr, 0x0, sizeof(ifr));
4653
4654 if( *dev ){
4655 ptr = dev;
4656 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4657 ppa = atoi(ptr);
4658 }
4659
4660 /* Check if IP device was opened */
4661 if( ip_fd )
4662 close(ip_fd);
4663
4664 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4665 if (ip_fd < 0) {
4666 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4667 return -1;
4668 }
4669
4670 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4671 if (tap_fd < 0) {
4672 syslog(LOG_ERR, "Can't open /dev/tap");
4673 return -1;
4674 }
4675
4676 /* Assign a new PPA and get its unit number. */
4677 strioc_ppa.ic_cmd = TUNNEWPPA;
4678 strioc_ppa.ic_timout = 0;
4679 strioc_ppa.ic_len = sizeof(ppa);
4680 strioc_ppa.ic_dp = (char *)&ppa;
4681 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4682 syslog (LOG_ERR, "Can't assign new interface");
4683
4684 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4685 if (if_fd < 0) {
4686 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4687 return -1;
4688 }
4689 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4690 syslog(LOG_ERR, "Can't push IP module");
4691 return -1;
4692 }
4693
4694 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4695 syslog(LOG_ERR, "Can't get flags\n");
4696
4697 snprintf (actual_name, 32, "tap%d", ppa);
4698 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4699
4700 ifr.lifr_ppa = ppa;
4701 /* Assign ppa according to the unit number returned by tun device */
4702
4703 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4704 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4705 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4706 syslog (LOG_ERR, "Can't get flags\n");
4707 /* Push arp module to if_fd */
4708 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4709 syslog (LOG_ERR, "Can't push ARP module (2)");
4710
4711 /* Push arp module to ip_fd */
4712 if (ioctl (ip_fd, I_POP, NULL) < 0)
4713 syslog (LOG_ERR, "I_POP failed\n");
4714 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4715 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4716 /* Open arp_fd */
4717 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4718 if (arp_fd < 0)
4719 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4720
4721 /* Set ifname to arp */
4722 strioc_if.ic_cmd = SIOCSLIFNAME;
4723 strioc_if.ic_timout = 0;
4724 strioc_if.ic_len = sizeof(ifr);
4725 strioc_if.ic_dp = (char *)&ifr;
4726 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4727 syslog (LOG_ERR, "Can't set ifname to arp\n");
4728 }
4729
4730 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4731 syslog(LOG_ERR, "Can't link TAP device to IP");
4732 return -1;
4733 }
4734
4735 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4736 syslog (LOG_ERR, "Can't link TAP device to ARP");
4737
4738 close (if_fd);
4739
4740 memset(&ifr, 0x0, sizeof(ifr));
4741 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4742 ifr.lifr_ip_muxid = ip_muxid;
4743 ifr.lifr_arp_muxid = arp_muxid;
4744
4745 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4746 {
4747 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4748 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4749 syslog (LOG_ERR, "Can't set multiplexor id");
4750 }
4751
4752 snprintf(dev, dev_size, "tap%d", ppa);
4753 return tap_fd;
4754}
4755
4756static int tap_open(char *ifname, int ifname_size)
4757{
4758 char dev[10]="";
4759 int fd;
4760 if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4761 fprintf(stderr, "Cannot allocate TAP device\n");
4762 return -1;
4763 }
4764 pstrcpy(ifname, ifname_size, dev);
4765 fcntl(fd, F_SETFL, O_NONBLOCK);
4766 return fd;
4767}
4768#else
4769static int tap_open(char *ifname, int ifname_size)
4770{
4771 struct ifreq ifr;
4772 int fd, ret;
4773
4774 TFR(fd = open("/dev/net/tun", O_RDWR));
4775 if (fd < 0) {
4776 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4777 return -1;
4778 }
4779 memset(&ifr, 0, sizeof(ifr));
4780 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4781 if (ifname[0] != '\0')
4782 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4783 else
4784 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4785 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4786 if (ret != 0) {
4787 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4788 close(fd);
4789 return -1;
4790 }
4791 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4792 fcntl(fd, F_SETFL, O_NONBLOCK);
4793 return fd;
4794}
4795#endif
4796
4797static int launch_script(const char *setup_script, const char *ifname, int fd)
4798{
4799 int pid, status;
4800 char *args[3];
4801 char **parg;
4802
4803 /* try to launch network script */
4804 pid = fork();
4805 if (pid >= 0) {
4806 if (pid == 0) {
4807 int open_max = sysconf (_SC_OPEN_MAX), i;
4808 for (i = 0; i < open_max; i++)
4809 if (i != STDIN_FILENO &&
4810 i != STDOUT_FILENO &&
4811 i != STDERR_FILENO &&
4812 i != fd)
4813 close(i);
4814
4815 parg = args;
4816 *parg++ = (char *)setup_script;
4817 *parg++ = (char *)ifname;
4818 *parg++ = NULL;
4819 execv(setup_script, args);
4820 _exit(1);
4821 }
4822 while (waitpid(pid, &status, 0) != pid);
4823 if (!WIFEXITED(status) ||
4824 WEXITSTATUS(status) != 0) {
4825 fprintf(stderr, "%s: could not launch network script\n",
4826 setup_script);
4827 return -1;
4828 }
4829 }
4830 return 0;
4831}
4832
4833static int net_tap_init(VLANState *vlan, const char *ifname1,
4834 const char *setup_script, const char *down_script)
4835{
4836 TAPState *s;
4837 int fd;
4838 char ifname[128];
4839
4840 if (ifname1 != NULL)
4841 pstrcpy(ifname, sizeof(ifname), ifname1);
4842 else
4843 ifname[0] = '\0';
4844 TFR(fd = tap_open(ifname, sizeof(ifname)));
4845 if (fd < 0)
4846 return -1;
4847
4848 if (!setup_script || !strcmp(setup_script, "no"))
4849 setup_script = "";
4850 if (setup_script[0] != '\0') {
4851 if (launch_script(setup_script, ifname, fd))
4852 return -1;
4853 }
4854 s = net_tap_fd_init(vlan, fd);
4855 if (!s)
4856 return -1;
4857 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4858 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4859 if (down_script && strcmp(down_script, "no"))
4860 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4861 return 0;
4862}
4863
4864#endif /* !_WIN32 */
4865
4866#if defined(CONFIG_VDE)
4867typedef struct VDEState {
4868 VLANClientState *vc;
4869 VDECONN *vde;
4870} VDEState;
4871
4872static void vde_to_qemu(void *opaque)
4873{
4874 VDEState *s = opaque;
4875 uint8_t buf[4096];
4876 int size;
4877
4878 size = vde_recv(s->vde, buf, sizeof(buf), 0);
4879 if (size > 0) {
4880 qemu_send_packet(s->vc, buf, size);
4881 }
4882}
4883
4884static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4885{
4886 VDEState *s = opaque;
4887 int ret;
4888 for(;;) {
4889 ret = vde_send(s->vde, buf, size, 0);
4890 if (ret < 0 && errno == EINTR) {
4891 } else {
4892 break;
4893 }
4894 }
4895}
4896
4897static int net_vde_init(VLANState *vlan, const char *sock, int port,
4898 const char *group, int mode)
4899{
4900 VDEState *s;
4901 char *init_group = strlen(group) ? (char *)group : NULL;
4902 char *init_sock = strlen(sock) ? (char *)sock : NULL;
4903
4904 struct vde_open_args args = {
4905 .port = port,
4906 .group = init_group,
4907 .mode = mode,
4908 };
4909
4910 s = qemu_mallocz(sizeof(VDEState));
4911 if (!s)
4912 return -1;
4913 s->vde = vde_open(init_sock, "QEMU", &args);
4914 if (!s->vde){
4915 free(s);
4916 return -1;
4917 }
4918 s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4919 qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4920 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4921 sock, vde_datafd(s->vde));
4922 return 0;
4923}
4924#endif
4925
4926/* network connection */
4927typedef struct NetSocketState {
4928 VLANClientState *vc;
4929 int fd;
4930 int state; /* 0 = getting length, 1 = getting data */
4931 int index;
4932 int packet_len;
4933 uint8_t buf[4096];
4934 SockAddress dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4935} NetSocketState;
4936
4937typedef struct NetSocketListenState {
4938 VLANState *vlan;
4939 int fd;
4940} NetSocketListenState;
4941
4942/* XXX: we consider we can send the whole packet without blocking */
4943static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4944{
4945 NetSocketState *s = opaque;
4946 uint32_t len;
4947 len = htonl(size);
4948
4949 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4950 send_all(s->fd, buf, size);
4951}
4952
4953static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4954{
4955 NetSocketState *s = opaque;
4956 socket_sendto(s->fd, buf, size, &s->dgram_dst);
4957}
4958
4959static void net_socket_send(void *opaque)
4960{
4961 NetSocketState *s = opaque;
4962 int l, size, err;
4963 uint8_t buf1[4096];
4964 const uint8_t *buf;
4965
4966 size = socket_recv(s->fd, buf1, sizeof(buf1));
4967 if (size < 0) {
4968 err = errno;
4969 if (err != EWOULDBLOCK)
4970 goto eoc;
4971 } else if (size == 0) {
4972 /* end of connection */
4973 eoc:
4974 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4975 socket_close(s->fd);
4976 return;
4977 }
4978 buf = buf1;
4979 while (size > 0) {
4980 /* reassemble a packet from the network */
4981 switch(s->state) {
4982 case 0:
4983 l = 4 - s->index;
4984 if (l > size)
4985 l = size;
4986 memcpy(s->buf + s->index, buf, l);
4987 buf += l;
4988 size -= l;
4989 s->index += l;
4990 if (s->index == 4) {
4991 /* got length */
4992 s->packet_len = ntohl(*(uint32_t *)s->buf);
4993 s->index = 0;
4994 s->state = 1;
4995 }
4996 break;
4997 case 1:
4998 l = s->packet_len - s->index;
4999 if (l > size)
5000 l = size;
5001 memcpy(s->buf + s->index, buf, l);
5002 s->index += l;
5003 buf += l;
5004 size -= l;
5005 if (s->index >= s->packet_len) {
5006 qemu_send_packet(s->vc, s->buf, s->packet_len);
5007 s->index = 0;
5008 s->state = 0;
5009 }
5010 break;
5011 }
5012 }
5013}
5014
5015static void net_socket_send_dgram(void *opaque)
5016{
5017 NetSocketState *s = opaque;
5018 int size;
5019
5020 size = socket_recv(s->fd, s->buf, sizeof(s->buf));
5021 if (size < 0)
5022 return;
5023 if (size == 0) {
5024 /* end of connection */
5025 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
5026 return;
5027 }
5028 qemu_send_packet(s->vc, s->buf, size);
5029}
5030
5031static int net_socket_mcast_create(SockAddress* mcastaddr)
5032{
5033 uint32_t mcast_ip = (uint32_t) sock_address_get_ip(mcastaddr);
5034
5035 int fd, ret;
5036
5037 if (!IN_MULTICAST(mcast_ip)) {
5038 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" does not contain a multicast address\n",
5039 sock_address_to_string(mcastaddr));
5040 return -1;
5041
5042 }
5043 fd = socket_create_inet( SOCKET_DGRAM );
5044 if (fd < 0) {
5045 perror("socket(PF_INET, SOCK_DGRAM)");
5046 return -1;
5047 }
5048
5049#if 0
5050 val = 1;
5051 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
5052 (const char *)&val, sizeof(val));
5053#else
5054 ret=socket_set_xreuseaddr(fd);
5055#endif
5056 if (ret < 0) {
5057 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5058 goto fail;
5059 }
5060
5061 if (socket_bind(fd, mcastaddr) < 0) {
5062 perror("bind");
5063 goto fail;
5064 }
5065
5066 /* Add host to multicast group */
5067 if (socket_mcast_inet_add_membership(fd, mcast_ip) < 0) {
5068 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5069 goto fail;
5070 }
5071
5072 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5073 if (socket_mcast_inet_set_loop(fd, 1) < 0) {
5074 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5075 goto fail;
5076 }
5077
5078 socket_set_nonblock(fd);
5079 return fd;
5080fail:
5081 if (fd >= 0)
5082 closesocket(fd);
5083 return -1;
5084}
5085
5086static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
5087 int is_connected)
5088{
5089 SockAddress saddr;
5090 int newfd;
5091 NetSocketState *s;
5092
5093 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5094 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5095 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5096 */
5097
5098 if (is_connected) {
5099 if (socket_get_address(fd, &saddr) == 0) {
5100 /* must be bound */
5101 if (sock_address_get_ip(&saddr) == 0) {
5102 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5103 fd);
5104 return NULL;
5105 }
5106 /* clone dgram socket */
5107 newfd = net_socket_mcast_create(&saddr);
5108 if (newfd < 0) {
5109 /* error already reported by net_socket_mcast_create() */
5110 close(fd);
5111 return NULL;
5112 }
5113 /* clone newfd to fd, close newfd */
5114 dup2(newfd, fd);
5115 close(newfd);
5116
5117 } else {
5118 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5119 fd, errno_str);
5120 return NULL;
5121 }
5122 }
5123
5124 s = qemu_mallocz(sizeof(NetSocketState));
5125 if (!s)
5126 return NULL;
5127 s->fd = fd;
5128
5129 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
5130 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
5131
5132 /* mcast: save bound address as dst */
5133 if (is_connected) s->dgram_dst=saddr;
5134
5135 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5136 "socket: fd=%d (%s mcast=%s)",
5137 fd, is_connected? "cloned" : "",
5138 sock_address_to_string(&saddr));
5139 return s;
5140}
5141
5142static void net_socket_connect(void *opaque)
5143{
5144 NetSocketState *s = opaque;
5145 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
5146}
5147
5148static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
5149 int is_connected)
5150{
5151 NetSocketState *s;
5152 s = qemu_mallocz(sizeof(NetSocketState));
5153 if (!s)
5154 return NULL;
5155 s->fd = fd;
5156 s->vc = qemu_new_vlan_client(vlan,
5157 net_socket_receive, NULL, s);
5158 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5159 "socket: fd=%d", fd);
5160 if (is_connected) {
5161 net_socket_connect(s);
5162 } else {
5163 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
5164 }
5165 return s;
5166}
5167
5168static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
5169 int is_connected)
5170{
5171 SocketType so_type;
5172
5173 so_type = socket_get_type(fd);
5174 switch(so_type) {
5175 case SOCKET_DGRAM:
5176 return net_socket_fd_init_dgram(vlan, fd, is_connected);
5177 case SOCKET_STREAM:
5178 return net_socket_fd_init_stream(vlan, fd, is_connected);
5179 default:
5180 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5181 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
5182 return net_socket_fd_init_stream(vlan, fd, is_connected);
5183 }
5184 return NULL;
5185}
5186
5187static void net_socket_accept(void *opaque)
5188{
5189 NetSocketListenState *s = opaque;
5190 NetSocketState *s1;
5191 SockAddress saddr;
5192 int fd;
5193
5194 fd = socket_accept(s->fd, &saddr);
5195 if (fd < 0)
5196 return;
5197
5198 s1 = net_socket_fd_init(s->vlan, fd, 1);
5199 if (!s1) {
5200 closesocket(fd);
5201 } else {
5202 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
5203 "socket: connection from %s",
5204 sock_address_to_string(&saddr));
5205 }
5206 sock_address_done(&saddr);
5207}
5208
5209static int net_socket_listen_init(VLANState *vlan, const char *host_str)
5210{
5211 NetSocketListenState *s;
5212 int fd, ret;
5213 SockAddress saddr;
5214
5215 if (parse_host_port(&saddr, host_str) < 0)
5216 return -1;
5217
5218 s = qemu_mallocz(sizeof(NetSocketListenState));
5219 if (!s)
5220 return -1;
5221
5222 fd = socket_create_inet( SOCKET_STREAM );
5223 if (fd < 0) {
5224 perror("socket");
5225 return -1;
5226 }
5227 socket_set_nonblock(fd);
5228#if 0
5229 /* allow fast reuse */
5230 val = 1;
5231 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5232#else
5233 socket_set_xreuseaddr(fd);
5234#endif
5235
5236 ret = socket_bind(fd, &saddr);
5237 if (ret < 0) {
5238 perror("bind");
5239 socket_close(fd);
5240 return -1;
5241 }
5242 ret = socket_listen(fd, 0);
5243 if (ret < 0) {
5244 perror("listen");
5245 socket_close(fd);
5246 return -1;
5247 }
5248 s->vlan = vlan;
5249 s->fd = fd;
5250 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5251 return 0;
5252}
5253
5254static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5255{
5256 NetSocketState *s;
5257 int fd, connected, ret, err;
5258 SockAddress saddr;
5259
5260 if (parse_host_port(&saddr, host_str) < 0)
5261 return -1;
5262
5263 fd = socket_create_inet( SOCKET_STREAM );
5264 if (fd < 0) {
5265 perror("socket");
5266 return -1;
5267 }
5268 socket_set_nonblock(fd);
5269
5270 connected = 0;
5271 for(;;) {
5272 ret = socket_connect(fd, &saddr);
5273 if (ret < 0) {
5274 err = errno;
5275 if (err == EINTR || err == EWOULDBLOCK) {
5276 } else if (err == EINPROGRESS) {
5277 break;
5278#ifdef _WIN32
5279 } else if (err == EALREADY) {
5280 break;
5281#endif
5282 } else {
5283 perror("connect");
5284 socket_close(fd);
5285 return -1;
5286 }
5287 } else {
5288 connected = 1;
5289 break;
5290 }
5291 }
5292 s = net_socket_fd_init(vlan, fd, connected);
5293 if (!s)
5294 return -1;
5295
5296 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5297 "socket: connect to %s", sock_address_to_string(&saddr));
5298 return 0;
5299}
5300
5301static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5302{
5303 NetSocketState *s;
5304 int fd;
5305 SockAddress saddr;
5306
5307 if (parse_host_port(&saddr, host_str) < 0)
5308 return -1;
5309
5310
5311 fd = net_socket_mcast_create(&saddr);
5312 if (fd < 0)
5313 return -1;
5314
5315 s = net_socket_fd_init(vlan, fd, 0);
5316 if (!s)
5317 return -1;
5318
5319 s->dgram_dst = saddr;
5320
5321 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5322 "socket: mcast=%s", sock_address_to_string(&saddr));
5323 return 0;
5324
5325}
5326
5327static const char *get_opt_name(char *buf, int buf_size, const char *p)
5328{
5329 char *q;
5330
5331 q = buf;
5332 while (*p != '\0' && *p != '=') {
5333 if (q && (q - buf) < buf_size - 1)
5334 *q++ = *p;
5335 p++;
5336 }
5337 if (q)
5338 *q = '\0';
5339
5340 return p;
5341}
5342
5343static const char *get_opt_value(char *buf, int buf_size, const char *p)
5344{
5345 char *q;
5346
5347 q = buf;
5348 while (*p != '\0') {
5349 if (*p == ',') {
5350 if (*(p + 1) != ',')
5351 break;
5352 p++;
5353 }
5354 if (q && (q - buf) < buf_size - 1)
5355 *q++ = *p;
5356 p++;
5357 }
5358 if (q)
5359 *q = '\0';
5360
5361 return p;
5362}
5363
5364static int get_param_value(char *buf, int buf_size,
5365 const char *tag, const char *str)
5366{
5367 const char *p;
5368 char option[128];
5369
5370 p = str;
5371 for(;;) {
5372 p = get_opt_name(option, sizeof(option), p);
5373 if (*p != '=')
5374 break;
5375 p++;
5376 if (!strcmp(tag, option)) {
5377 (void)get_opt_value(buf, buf_size, p);
5378 return strlen(buf);
5379 } else {
5380 p = get_opt_value(NULL, 0, p);
5381 }
5382 if (*p != ',')
5383 break;
5384 p++;
5385 }
5386 return 0;
5387}
5388
5389static int check_params(char *buf, int buf_size,
5390 const char * const *params, const char *str)
5391{
5392 const char *p;
5393 int i;
5394
5395 p = str;
5396 for(;;) {
5397 p = get_opt_name(buf, buf_size, p);
5398 if (*p != '=')
5399 return -1;
5400 p++;
5401 for(i = 0; params[i] != NULL; i++)
5402 if (!strcmp(params[i], buf))
5403 break;
5404 if (params[i] == NULL)
5405 return -1;
5406 p = get_opt_value(NULL, 0, p);
5407 if (*p != ',')
5408 break;
5409 p++;
5410 }
5411 return 0;
5412}
5413
5414static int net_client_init(const char *device, const char *p)
5415{
5416 char buf[1024];
5417 int vlan_id, ret;
5418 VLANState *vlan;
5419
5420 vlan_id = 0;
5421 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5422 vlan_id = strtol(buf, NULL, 0);
5423 }
5424 vlan = qemu_find_vlan(vlan_id);
5425 if (!vlan) {
5426 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5427 return -1;
5428 }
5429 if (!strcmp(device, "nic")) {
5430 NICInfo *nd;
5431 uint8_t *macaddr;
5432
5433 if (nb_nics >= MAX_NICS) {
5434 fprintf(stderr, "Too Many NICs\n");
5435 return -1;
5436 }
5437 nd = &nd_table[nb_nics];
5438 macaddr = nd->macaddr;
5439 macaddr[0] = 0x52;
5440 macaddr[1] = 0x54;
5441 macaddr[2] = 0x00;
5442 macaddr[3] = 0x12;
5443 macaddr[4] = 0x34;
5444 macaddr[5] = 0x56 + nb_nics;
5445
5446 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5447 if (parse_macaddr(macaddr, buf) < 0) {
5448 fprintf(stderr, "invalid syntax for ethernet address\n");
5449 return -1;
5450 }
5451 }
5452 if (get_param_value(buf, sizeof(buf), "model", p)) {
5453 nd->model = strdup(buf);
5454 }
5455 nd->vlan = vlan;
5456 nb_nics++;
5457 vlan->nb_guest_devs++;
5458 ret = 0;
5459 } else
5460 if (!strcmp(device, "none")) {
5461 /* does nothing. It is needed to signal that no network cards
5462 are wanted */
5463#if 1 /* ANDROID */
5464 fprintf(stderr, "sorry, you need to enable the network to use the Android emulator\n");
5465 return -1;
5466#else
5467 ret = 0;
5468#endif
5469 } else
5470#ifdef CONFIG_SLIRP
5471 if (!strcmp(device, "user")) {
5472 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5473 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5474 }
5475 vlan->nb_host_devs++;
5476 ret = net_slirp_init(vlan);
5477 } else
5478#endif
5479#ifdef _WIN32
5480#if 0
5481 if (!strcmp(device, "tap")) {
5482 char ifname[64];
5483 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5484 fprintf(stderr, "tap: no interface name\n");
5485 return -1;
5486 }
5487 vlan->nb_host_devs++;
5488 ret = tap_win32_init(vlan, ifname);
5489 } else
5490#endif
5491#else
5492 if (!strcmp(device, "tap")) {
5493 char ifname[64];
5494 char setup_script[1024], down_script[1024];
5495 int fd;
5496 vlan->nb_host_devs++;
5497 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5498 fd = strtol(buf, NULL, 0);
5499 socket_set_nonblock(fd);
5500 ret = -1;
5501 if (net_tap_fd_init(vlan, fd))
5502 ret = 0;
5503 } else {
5504 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5505 ifname[0] = '\0';
5506 }
5507 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5508 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5509 }
5510 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5511 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5512 }
5513 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5514 }
5515 } else
5516#endif
5517 if (!strcmp(device, "socket")) {
5518 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5519 int fd;
5520 fd = strtol(buf, NULL, 0);
5521 ret = -1;
5522 if (net_socket_fd_init(vlan, fd, 1))
5523 ret = 0;
5524 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5525 ret = net_socket_listen_init(vlan, buf);
5526 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5527 ret = net_socket_connect_init(vlan, buf);
5528 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5529 ret = net_socket_mcast_init(vlan, buf);
5530 } else {
5531 fprintf(stderr, "Unknown socket options: %s\n", p);
5532 return -1;
5533 }
5534 vlan->nb_host_devs++;
5535 } else
5536#ifdef CONFIG_VDE
5537 if (!strcmp(device, "vde")) {
5538 char vde_sock[1024], vde_group[512];
5539 int vde_port, vde_mode;
5540 vlan->nb_host_devs++;
5541 if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5542 vde_sock[0] = '\0';
5543 }
5544 if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5545 vde_port = strtol(buf, NULL, 10);
5546 } else {
5547 vde_port = 0;
5548 }
5549 if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5550 vde_group[0] = '\0';
5551 }
5552 if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5553 vde_mode = strtol(buf, NULL, 8);
5554 } else {
5555 vde_mode = 0700;
5556 }
5557 ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5558 } else
5559#endif
5560 {
5561 fprintf(stderr, "Unknown network device: %s\n", device);
5562 return -1;
5563 }
5564 if (ret < 0) {
5565 fprintf(stderr, "Could not initialize device '%s'\n", device);
5566 }
5567
5568 return ret;
5569}
5570
5571static int net_client_parse(const char *str)
5572{
5573 const char *p;
5574 char *q;
5575 char device[64];
5576
5577 p = str;
5578 q = device;
5579 while (*p != '\0' && *p != ',') {
5580 if ((q - device) < sizeof(device) - 1)
5581 *q++ = *p;
5582 p++;
5583 }
5584 *q = '\0';
5585 if (*p == ',')
5586 p++;
5587
5588 return net_client_init(device, p);
5589}
5590
5591void do_info_network(void)
5592{
5593 VLANState *vlan;
5594 VLANClientState *vc;
5595
5596 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5597 term_printf("VLAN %d devices:\n", vlan->id);
5598 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5599 term_printf(" %s\n", vc->info_str);
5600 }
5601}
5602
5603#define HD_ALIAS "index=%d,media=disk"
5604#ifdef TARGET_PPC
5605#define CDROM_ALIAS "index=1,media=cdrom"
5606#else
5607#define CDROM_ALIAS "index=2,media=cdrom"
5608#endif
5609#define FD_ALIAS "index=%d,if=floppy"
5610#define PFLASH_ALIAS "if=pflash"
5611#define MTD_ALIAS "if=mtd"
5612#define SD_ALIAS "index=0,if=sd"
5613
5614static int drive_add(const char *file, const char *fmt, ...)
5615{
5616 va_list ap;
5617
5618 if (nb_drives_opt >= MAX_DRIVES) {
5619 fprintf(stderr, "qemu: too many drives\n");
5620 exit(1);
5621 }
5622
5623 drives_opt[nb_drives_opt].file = file;
5624 va_start(ap, fmt);
5625 vsnprintf(drives_opt[nb_drives_opt].opt,
5626 sizeof(drives_opt[0].opt), fmt, ap);
5627 va_end(ap);
5628
5629 return nb_drives_opt++;
5630}
5631
5632int drive_get_index(BlockInterfaceType type, int bus, int unit)
5633{
5634 int index;
5635
5636 /* seek interface, bus and unit */
5637
5638 for (index = 0; index < nb_drives; index++)
5639 if (drives_table[index].type == type &&
5640 drives_table[index].bus == bus &&
5641 drives_table[index].unit == unit)
5642 return index;
5643
5644 return -1;
5645}
5646
5647int drive_get_max_bus(BlockInterfaceType type)
5648{
5649 int max_bus;
5650 int index;
5651
5652 max_bus = -1;
5653 for (index = 0; index < nb_drives; index++) {
5654 if(drives_table[index].type == type &&
5655 drives_table[index].bus > max_bus)
5656 max_bus = drives_table[index].bus;
5657 }
5658 return max_bus;
5659}
5660
5661static void bdrv_format_print(void *opaque, const char *name)
5662{
5663 fprintf(stderr, " %s", name);
5664}
5665
5666static int drive_init(struct drive_opt *arg, int snapshot,
5667 QEMUMachine *machine)
5668{
5669 char buf[128];
5670 char file[1024];
5671 char devname[128];
5672 const char *mediastr = "";
5673 BlockInterfaceType type;
5674 enum { MEDIA_DISK, MEDIA_CDROM } media;
5675 int bus_id, unit_id;
5676 int cyls, heads, secs, translation;
5677 BlockDriverState *bdrv;
5678 BlockDriver *drv = NULL;
5679 int max_devs;
5680 int index;
5681 int cache;
5682 int bdrv_flags;
5683 char *str = arg->opt;
5684 static const char * const params[] = { "bus", "unit", "if", "index",
5685 "cyls", "heads", "secs", "trans",
5686 "media", "snapshot", "file",
5687 "cache", "format", NULL };
5688
5689 if (check_params(buf, sizeof(buf), params, str) < 0) {
5690 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5691 buf, str);
5692 return -1;
5693 }
5694
5695 file[0] = 0;
5696 cyls = heads = secs = 0;
5697 bus_id = 0;
5698 unit_id = -1;
5699 translation = BIOS_ATA_TRANSLATION_AUTO;
5700 index = -1;
5701 cache = 1;
5702
5703 if (!strcmp(machine->name, "realview") ||
5704 !strcmp(machine->name, "SS-5") ||
5705 !strcmp(machine->name, "SS-10") ||
5706 !strcmp(machine->name, "SS-600MP") ||
5707 !strcmp(machine->name, "versatilepb") ||
5708 !strcmp(machine->name, "versatileab")) {
5709 type = IF_SCSI;
5710 max_devs = MAX_SCSI_DEVS;
5711 pstrcpy(devname, sizeof(devname), "scsi");
5712 } else {
5713 type = IF_IDE;
5714 max_devs = MAX_IDE_DEVS;
5715 pstrcpy(devname, sizeof(devname), "ide");
5716 }
5717 media = MEDIA_DISK;
5718
5719 /* extract parameters */
5720
5721 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5722 bus_id = strtol(buf, NULL, 0);
5723 if (bus_id < 0) {
5724 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5725 return -1;
5726 }
5727 }
5728
5729 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5730 unit_id = strtol(buf, NULL, 0);
5731 if (unit_id < 0) {
5732 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5733 return -1;
5734 }
5735 }
5736
5737 if (get_param_value(buf, sizeof(buf), "if", str)) {
5738 pstrcpy(devname, sizeof(devname), buf);
5739 if (!strcmp(buf, "ide")) {
5740 type = IF_IDE;
5741 max_devs = MAX_IDE_DEVS;
5742 } else if (!strcmp(buf, "scsi")) {
5743 type = IF_SCSI;
5744 max_devs = MAX_SCSI_DEVS;
5745 } else if (!strcmp(buf, "floppy")) {
5746 type = IF_FLOPPY;
5747 max_devs = 0;
5748 } else if (!strcmp(buf, "pflash")) {
5749 type = IF_PFLASH;
5750 max_devs = 0;
5751 } else if (!strcmp(buf, "mtd")) {
5752 type = IF_MTD;
5753 max_devs = 0;
5754 } else if (!strcmp(buf, "sd")) {
5755 type = IF_SD;
5756 max_devs = 0;
5757 } else {
5758 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5759 return -1;
5760 }
5761 }
5762
5763 if (get_param_value(buf, sizeof(buf), "index", str)) {
5764 index = strtol(buf, NULL, 0);
5765 if (index < 0) {
5766 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5767 return -1;
5768 }
5769 }
5770
5771 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5772 cyls = strtol(buf, NULL, 0);
5773 }
5774
5775 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5776 heads = strtol(buf, NULL, 0);
5777 }
5778
5779 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5780 secs = strtol(buf, NULL, 0);
5781 }
5782
5783 if (cyls || heads || secs) {
5784 if (cyls < 1 || cyls > 16383) {
5785 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5786 return -1;
5787 }
5788 if (heads < 1 || heads > 16) {
5789 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5790 return -1;
5791 }
5792 if (secs < 1 || secs > 63) {
5793 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5794 return -1;
5795 }
5796 }
5797
5798 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5799 if (!cyls) {
5800 fprintf(stderr,
5801 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5802 str);
5803 return -1;
5804 }
5805 if (!strcmp(buf, "none"))
5806 translation = BIOS_ATA_TRANSLATION_NONE;
5807 else if (!strcmp(buf, "lba"))
5808 translation = BIOS_ATA_TRANSLATION_LBA;
5809 else if (!strcmp(buf, "auto"))
5810 translation = BIOS_ATA_TRANSLATION_AUTO;
5811 else {
5812 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5813 return -1;
5814 }
5815 }
5816
5817 if (get_param_value(buf, sizeof(buf), "media", str)) {
5818 if (!strcmp(buf, "disk")) {
5819 media = MEDIA_DISK;
5820 } else if (!strcmp(buf, "cdrom")) {
5821 if (cyls || secs || heads) {
5822 fprintf(stderr,
5823 "qemu: '%s' invalid physical CHS format\n", str);
5824 return -1;
5825 }
5826 media = MEDIA_CDROM;
5827 } else {
5828 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5829 return -1;
5830 }
5831 }
5832
5833 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5834 if (!strcmp(buf, "on"))
5835 snapshot = 1;
5836 else if (!strcmp(buf, "off"))
5837 snapshot = 0;
5838 else {
5839 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5840 return -1;
5841 }
5842 }
5843
5844 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5845 if (!strcmp(buf, "off"))
5846 cache = 0;
5847 else if (!strcmp(buf, "on"))
5848 cache = 1;
5849 else {
5850 fprintf(stderr, "qemu: invalid cache option\n");
5851 return -1;
5852 }
5853 }
5854
5855 if (get_param_value(buf, sizeof(buf), "format", str)) {
5856 if (strcmp(buf, "?") == 0) {
5857 fprintf(stderr, "qemu: Supported formats:");
5858 bdrv_iterate_format(bdrv_format_print, NULL);
5859 fprintf(stderr, "\n");
5860 return -1;
5861 }
5862 drv = bdrv_find_format(buf);
5863 if (!drv) {
5864 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5865 return -1;
5866 }
5867 }
5868
5869 if (arg->file == NULL)
5870 get_param_value(file, sizeof(file), "file", str);
5871 else
5872 pstrcpy(file, sizeof(file), arg->file);
5873
5874 /* compute bus and unit according index */
5875
5876 if (index != -1) {
5877 if (bus_id != 0 || unit_id != -1) {
5878 fprintf(stderr,
5879 "qemu: '%s' index cannot be used with bus and unit\n", str);
5880 return -1;
5881 }
5882 if (max_devs == 0)
5883 {
5884 unit_id = index;
5885 bus_id = 0;
5886 } else {
5887 unit_id = index % max_devs;
5888 bus_id = index / max_devs;
5889 }
5890 }
5891
5892 /* if user doesn't specify a unit_id,
5893 * try to find the first free
5894 */
5895
5896 if (unit_id == -1) {
5897 unit_id = 0;
5898 while (drive_get_index(type, bus_id, unit_id) != -1) {
5899 unit_id++;
5900 if (max_devs && unit_id >= max_devs) {
5901 unit_id -= max_devs;
5902 bus_id++;
5903 }
5904 }
5905 }
5906
5907 /* check unit id */
5908
5909 if (max_devs && unit_id >= max_devs) {
5910 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5911 str, unit_id, max_devs - 1);
5912 return -1;
5913 }
5914
5915 /*
5916 * ignore multiple definitions
5917 */
5918
5919 if (drive_get_index(type, bus_id, unit_id) != -1)
5920 return 0;
5921
5922 /* init */
5923
5924 if (type == IF_IDE || type == IF_SCSI)
5925 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5926 if (max_devs)
5927 snprintf(buf, sizeof(buf), "%s%i%s%i",
5928 devname, bus_id, mediastr, unit_id);
5929 else
5930 snprintf(buf, sizeof(buf), "%s%s%i",
5931 devname, mediastr, unit_id);
5932 bdrv = bdrv_new(buf);
5933 drives_table[nb_drives].bdrv = bdrv;
5934 drives_table[nb_drives].type = type;
5935 drives_table[nb_drives].bus = bus_id;
5936 drives_table[nb_drives].unit = unit_id;
5937 nb_drives++;
5938
5939 switch(type) {
5940 case IF_IDE:
5941 case IF_SCSI:
5942 switch(media) {
5943 case MEDIA_DISK:
5944 if (cyls != 0) {
5945 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5946 bdrv_set_translation_hint(bdrv, translation);
5947 }
5948 break;
5949 case MEDIA_CDROM:
5950 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5951 break;
5952 }
5953 break;
5954 case IF_SD:
5955 /* FIXME: This isn't really a floppy, but it's a reasonable
5956 approximation. */
5957 case IF_FLOPPY:
5958 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5959 break;
5960 case IF_PFLASH:
5961 case IF_MTD:
5962 break;
5963 }
5964 if (!file[0])
5965 return 0;
5966 bdrv_flags = 0;
5967 if (snapshot)
5968 bdrv_flags |= BDRV_O_SNAPSHOT;
5969 if (!cache)
5970 bdrv_flags |= BDRV_O_DIRECT;
5971 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5972 fprintf(stderr, "qemu: could not open disk image %s\n",
5973 file);
5974 return -1;
5975 }
5976 return 0;
5977}
5978
5979/***********************************************************/
5980/* USB devices */
5981
5982static USBPort *used_usb_ports;
5983static USBPort *free_usb_ports;
5984
5985/* ??? Maybe change this to register a hub to keep track of the topology. */
5986void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5987 usb_attachfn attach)
5988{
5989 port->opaque = opaque;
5990 port->index = index;
5991 port->attach = attach;
5992 port->next = free_usb_ports;
5993 free_usb_ports = port;
5994}
5995
5996int usb_device_add_dev(USBDevice *dev)
5997{
5998 USBPort *port;
5999
6000 /* Find a USB port to add the device to. */
6001 port = free_usb_ports;
6002 if (!port->next) {
6003 USBDevice *hub;
6004
6005 /* Create a new hub and chain it on. */
6006 free_usb_ports = NULL;
6007 port->next = used_usb_ports;
6008 used_usb_ports = port;
6009
6010 hub = usb_hub_init(VM_USB_HUB_SIZE);
6011 usb_attach(port, hub);
6012 port = free_usb_ports;
6013 }
6014
6015 free_usb_ports = port->next;
6016 port->next = used_usb_ports;
6017 used_usb_ports = port;
6018 usb_attach(port, dev);
6019 return 0;
6020}
6021
6022static int usb_device_add(const char *devname)
6023{
6024 const char *p;
6025 USBDevice *dev;
6026
6027 if (!free_usb_ports)
6028 return -1;
6029
6030 if (strstart(devname, "host:", &p)) {
6031 dev = usb_host_device_open(p);
6032 } else if (!strcmp(devname, "mouse")) {
6033 dev = usb_mouse_init();
6034 } else if (!strcmp(devname, "tablet")) {
6035 dev = usb_tablet_init();
6036 } else if (!strcmp(devname, "keyboard")) {
6037 dev = usb_keyboard_init();
6038 } else if (strstart(devname, "disk:", &p)) {
6039 dev = usb_msd_init(p);
6040#if 0
6041 } else if (!strcmp(devname, "wacom-tablet")) {
6042 dev = usb_wacom_init();
6043 } else if (strstart(devname, "serial:", &p)) {
6044 dev = usb_serial_init(p);
6045#ifdef CONFIG_BRLAPI
6046 } else if (!strcmp(devname, "braille")) {
6047 dev = usb_baum_init();
6048#endif
6049 } else if (strstart(devname, "net:", &p)) {
6050 int nic = nb_nics;
6051
6052 if (net_client_init("nic", p) < 0)
6053 return -1;
6054 nd_table[nic].model = "usb";
6055 dev = usb_net_init(&nd_table[nic]);
6056#endif
6057 } else {
6058 return -1;
6059 }
6060 if (!dev)
6061 return -1;
6062
6063 return usb_device_add_dev(dev);
6064}
6065
6066int usb_device_del_addr(int bus_num, int addr)
6067{
6068 USBPort *port;
6069 USBPort **lastp;
6070 USBDevice *dev;
6071
6072 if (!used_usb_ports)
6073 return -1;
6074
6075 if (bus_num != 0)
6076 return -1;
6077
6078 lastp = &used_usb_ports;
6079 port = used_usb_ports;
6080 while (port && port->dev->addr != addr) {
6081 lastp = &port->next;
6082 port = port->next;
6083 }
6084
6085 if (!port)
6086 return -1;
6087
6088 dev = port->dev;
6089 *lastp = port->next;
6090 usb_attach(port, NULL);
6091 dev->handle_destroy(dev);
6092 port->next = free_usb_ports;
6093 free_usb_ports = port;
6094 return 0;
6095}
6096
6097static int usb_device_del(const char *devname)
6098{
6099 int bus_num, addr;
6100 const char *p;
6101
6102 if (strstart(devname, "host:", &p))
6103 return usb_host_device_close(p);
6104
6105 if (!used_usb_ports)
6106 return -1;
6107
6108 p = strchr(devname, '.');
6109 if (!p)
6110 return -1;
6111 bus_num = strtoul(devname, NULL, 0);
6112 addr = strtoul(p + 1, NULL, 0);
6113
6114 return usb_device_del_addr(bus_num, addr);
6115}
6116
6117void do_usb_add(const char *devname)
6118{
6119 usb_device_add(devname);
6120}
6121
6122void do_usb_del(const char *devname)
6123{
6124 usb_device_del(devname);
6125}
6126
6127void usb_info(void)
6128{
6129 USBDevice *dev;
6130 USBPort *port;
6131 const char *speed_str;
6132
6133 if (!usb_enabled) {
6134 term_printf("USB support not enabled\n");
6135 return;
6136 }
6137
6138 for (port = used_usb_ports; port; port = port->next) {
6139 dev = port->dev;
6140 if (!dev)
6141 continue;
6142 switch(dev->speed) {
6143 case USB_SPEED_LOW:
6144 speed_str = "1.5";
6145 break;
6146 case USB_SPEED_FULL:
6147 speed_str = "12";
6148 break;
6149 case USB_SPEED_HIGH:
6150 speed_str = "480";
6151 break;
6152 default:
6153 speed_str = "?";
6154 break;
6155 }
6156 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6157 0, dev->addr, speed_str, dev->devname);
6158 }
6159}
6160
6161/***********************************************************/
6162/* pid file */
6163
6164static char *pid_filename;
6165
6166/* Remove PID file. Called on normal exit */
6167
6168static void remove_pidfile(void)
6169{
6170 unlink (pid_filename);
6171}
6172
6173static void create_pidfile(const char *filename)
6174{
6175 struct stat pidstat;
6176 FILE *f;
6177
6178 /* Try to write our PID to the named file */
6179 if (stat(filename, &pidstat) < 0) {
6180 if (errno == ENOENT) {
6181 if ((f = fopen (filename, "w")) == NULL) {
6182 perror("Opening pidfile");
6183 exit(1);
6184 }
6185 fprintf(f, "%d\n", getpid());
6186 fclose(f);
6187 pid_filename = qemu_strdup(filename);
6188 if (!pid_filename) {
6189 fprintf(stderr, "Could not save PID filename");
6190 exit(1);
6191 }
6192 atexit(remove_pidfile);
6193 }
6194 } else {
6195 fprintf(stderr, "%s already exists. Remove it and try again.\n",
6196 filename);
6197 exit(1);
6198 }
6199}
6200
6201/***********************************************************/
6202/* dumb display */
6203
6204static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
6205{
6206}
6207
6208static void dumb_resize(DisplayState *ds, int w, int h)
6209{
6210}
6211
6212static void dumb_refresh(DisplayState *ds)
6213{
6214#if defined(CONFIG_SDL)
6215 vga_hw_update();
6216#endif
6217}
6218
6219static void dumb_display_init(DisplayState *ds)
6220{
6221 ds->data = NULL;
6222 ds->linesize = 0;
6223 ds->depth = 0;
6224 ds->dpy_update = dumb_update;
6225 ds->dpy_resize = dumb_resize;
6226 ds->dpy_refresh = dumb_refresh;
6227 ds->gui_timer_interval = 500;
6228 ds->idle = 1;
6229}
6230
6231/***********************************************************/
6232/* I/O handling */
6233
6234#define MAX_IO_HANDLERS 64
6235
6236typedef struct IOHandlerRecord {
6237 int fd;
6238 IOCanRWHandler *fd_read_poll;
6239 IOHandler *fd_read;
6240 IOHandler *fd_write;
6241 int deleted;
6242 void *opaque;
6243 /* temporary data */
6244 struct pollfd *ufd;
6245 struct IOHandlerRecord *next;
6246} IOHandlerRecord;
6247
6248static IOHandlerRecord *first_io_handler;
6249
6250/* XXX: fd_read_poll should be suppressed, but an API change is
6251 necessary in the character devices to suppress fd_can_read(). */
6252int qemu_set_fd_handler2(int fd,
6253 IOCanRWHandler *fd_read_poll,
6254 IOHandler *fd_read,
6255 IOHandler *fd_write,
6256 void *opaque)
6257{
6258 IOHandlerRecord **pioh, *ioh;
6259
6260 if (!fd_read && !fd_write) {
6261 pioh = &first_io_handler;
6262 for(;;) {
6263 ioh = *pioh;
6264 if (ioh == NULL)
6265 break;
6266 if (ioh->fd == fd) {
6267 ioh->deleted = 1;
6268 break;
6269 }
6270 pioh = &ioh->next;
6271 }
6272 } else {
6273 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6274 if (ioh->fd == fd)
6275 goto found;
6276 }
6277 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6278 if (!ioh)
6279 return -1;
6280 ioh->next = first_io_handler;
6281 first_io_handler = ioh;
6282 found:
6283 ioh->fd = fd;
6284 ioh->fd_read_poll = fd_read_poll;
6285 ioh->fd_read = fd_read;
6286 ioh->fd_write = fd_write;
6287 ioh->opaque = opaque;
6288 ioh->deleted = 0;
6289 }
6290 return 0;
6291}
6292
6293int qemu_set_fd_handler(int fd,
6294 IOHandler *fd_read,
6295 IOHandler *fd_write,
6296 void *opaque)
6297{
6298 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6299}
6300
6301/***********************************************************/
6302/* Polling handling */
6303
6304typedef struct PollingEntry {
6305 PollingFunc *func;
6306 void *opaque;
6307 struct PollingEntry *next;
6308} PollingEntry;
6309
6310static PollingEntry *first_polling_entry;
6311
6312int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6313{
6314 PollingEntry **ppe, *pe;
6315 pe = qemu_mallocz(sizeof(PollingEntry));
6316 if (!pe)
6317 return -1;
6318 pe->func = func;
6319 pe->opaque = opaque;
6320 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6321 *ppe = pe;
6322 return 0;
6323}
6324
6325void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6326{
6327 PollingEntry **ppe, *pe;
6328 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6329 pe = *ppe;
6330 if (pe->func == func && pe->opaque == opaque) {
6331 *ppe = pe->next;
6332 qemu_free(pe);
6333 break;
6334 }
6335 }
6336}
6337
6338#ifdef _WIN32
6339/***********************************************************/
6340/* Wait objects support */
6341typedef struct WaitObjects {
6342 int num;
6343 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6344 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6345 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6346} WaitObjects;
6347
6348static WaitObjects wait_objects = {0};
6349
6350int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6351{
6352 WaitObjects *w = &wait_objects;
6353
6354 if (w->num >= MAXIMUM_WAIT_OBJECTS)
6355 return -1;
6356 w->events[w->num] = handle;
6357 w->func[w->num] = func;
6358 w->opaque[w->num] = opaque;
6359 w->num++;
6360 return 0;
6361}
6362
6363void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6364{
6365 int i, found;
6366 WaitObjects *w = &wait_objects;
6367
6368 found = 0;
6369 for (i = 0; i < w->num; i++) {
6370 if (w->events[i] == handle)
6371 found = 1;
6372 if (found) {
6373 w->events[i] = w->events[i + 1];
6374 w->func[i] = w->func[i + 1];
6375 w->opaque[i] = w->opaque[i + 1];
6376 }
6377 }
6378 if (found)
6379 w->num--;
6380}
6381#endif
6382
6383/***********************************************************/
6384/* savevm/loadvm support */
6385
6386#define IO_BUF_SIZE 32768
6387
6388struct QEMUFile {
6389 FILE *outfile;
6390 BlockDriverState *bs;
6391 int is_file;
6392 int is_writable;
6393 int64_t base_offset;
6394 int64_t buf_offset; /* start of buffer when writing, end of buffer
6395 when reading */
6396 int buf_index;
6397 int buf_size; /* 0 when writing */
6398 uint8_t buf[IO_BUF_SIZE];
6399};
6400
6401QEMUFile *qemu_fopen(const char *filename, const char *mode)
6402{
6403 QEMUFile *f;
6404
6405 f = qemu_mallocz(sizeof(QEMUFile));
6406 if (!f)
6407 return NULL;
6408 if (!strcmp(mode, "wb")) {
6409 f->is_writable = 1;
6410 } else if (!strcmp(mode, "rb")) {
6411 f->is_writable = 0;
6412 } else {
6413 goto fail;
6414 }
6415 f->outfile = fopen(filename, mode);
6416 if (!f->outfile)
6417 goto fail;
6418 f->is_file = 1;
6419 return f;
6420 fail:
6421 if (f->outfile)
6422 fclose(f->outfile);
6423 qemu_free(f);
6424 return NULL;
6425}
6426
6427static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6428{
6429 QEMUFile *f;
6430
6431 f = qemu_mallocz(sizeof(QEMUFile));
6432 if (!f)
6433 return NULL;
6434 f->is_file = 0;
6435 f->bs = bs;
6436 f->is_writable = is_writable;
6437 f->base_offset = offset;
6438 return f;
6439}
6440
6441void qemu_fflush(QEMUFile *f)
6442{
6443 if (!f->is_writable)
6444 return;
6445 if (f->buf_index > 0) {
6446 if (f->is_file) {
6447 fseek(f->outfile, f->buf_offset, SEEK_SET);
6448 fwrite(f->buf, 1, f->buf_index, f->outfile);
6449 } else {
6450 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
6451 f->buf, f->buf_index);
6452 }
6453 f->buf_offset += f->buf_index;
6454 f->buf_index = 0;
6455 }
6456}
6457
6458static void qemu_fill_buffer(QEMUFile *f)
6459{
6460 int len;
6461
6462 if (f->is_writable)
6463 return;
6464 if (f->is_file) {
6465 fseek(f->outfile, f->buf_offset, SEEK_SET);
6466 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
6467 if (len < 0)
6468 len = 0;
6469 } else {
6470 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
6471 f->buf, IO_BUF_SIZE);
6472 if (len < 0)
6473 len = 0;
6474 }
6475 f->buf_index = 0;
6476 f->buf_size = len;
6477 f->buf_offset += len;
6478}
6479
6480void qemu_fclose(QEMUFile *f)
6481{
6482 if (f->is_writable)
6483 qemu_fflush(f);
6484 if (f->is_file) {
6485 fclose(f->outfile);
6486 }
6487 qemu_free(f);
6488}
6489
6490void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6491{
6492 int l;
6493 while (size > 0) {
6494 l = IO_BUF_SIZE - f->buf_index;
6495 if (l > size)
6496 l = size;
6497 memcpy(f->buf + f->buf_index, buf, l);
6498 f->buf_index += l;
6499 buf += l;
6500 size -= l;
6501 if (f->buf_index >= IO_BUF_SIZE)
6502 qemu_fflush(f);
6503 }
6504}
6505
6506void qemu_put_byte(QEMUFile *f, int v)
6507{
6508 f->buf[f->buf_index++] = v;
6509 if (f->buf_index >= IO_BUF_SIZE)
6510 qemu_fflush(f);
6511}
6512
6513int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6514{
6515 int size, l;
6516
6517 size = size1;
6518 while (size > 0) {
6519 l = f->buf_size - f->buf_index;
6520 if (l == 0) {
6521 qemu_fill_buffer(f);
6522 l = f->buf_size - f->buf_index;
6523 if (l == 0)
6524 break;
6525 }
6526 if (l > size)
6527 l = size;
6528 memcpy(buf, f->buf + f->buf_index, l);
6529 f->buf_index += l;
6530 buf += l;
6531 size -= l;
6532 }
6533 return size1 - size;
6534}
6535
6536int qemu_get_byte(QEMUFile *f)
6537{
6538 if (f->buf_index >= f->buf_size) {
6539 qemu_fill_buffer(f);
6540 if (f->buf_index >= f->buf_size)
6541 return 0;
6542 }
6543 return f->buf[f->buf_index++];
6544}
6545
6546int64_t qemu_ftell(QEMUFile *f)
6547{
6548 return f->buf_offset - f->buf_size + f->buf_index;
6549}
6550
6551int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6552{
6553 if (whence == SEEK_SET) {
6554 /* nothing to do */
6555 } else if (whence == SEEK_CUR) {
6556 pos += qemu_ftell(f);
6557 } else {
6558 /* SEEK_END not supported */
6559 return -1;
6560 }
6561 if (f->is_writable) {
6562 qemu_fflush(f);
6563 f->buf_offset = pos;
6564 } else {
6565 f->buf_offset = pos;
6566 f->buf_index = 0;
6567 f->buf_size = 0;
6568 }
6569 return pos;
6570}
6571
6572void qemu_put_be16(QEMUFile *f, unsigned int v)
6573{
6574 qemu_put_byte(f, v >> 8);
6575 qemu_put_byte(f, v);
6576}
6577
6578void qemu_put_be32(QEMUFile *f, unsigned int v)
6579{
6580 qemu_put_byte(f, v >> 24);
6581 qemu_put_byte(f, v >> 16);
6582 qemu_put_byte(f, v >> 8);
6583 qemu_put_byte(f, v);
6584}
6585
6586void qemu_put_be64(QEMUFile *f, uint64_t v)
6587{
6588 qemu_put_be32(f, v >> 32);
6589 qemu_put_be32(f, v);
6590}
6591
6592unsigned int qemu_get_be16(QEMUFile *f)
6593{
6594 unsigned int v;
6595 v = qemu_get_byte(f) << 8;
6596 v |= qemu_get_byte(f);
6597 return v;
6598}
6599
6600unsigned int qemu_get_be32(QEMUFile *f)
6601{
6602 unsigned int v;
6603 v = qemu_get_byte(f) << 24;
6604 v |= qemu_get_byte(f) << 16;
6605 v |= qemu_get_byte(f) << 8;
6606 v |= qemu_get_byte(f);
6607 return v;
6608}
6609
6610uint64_t qemu_get_be64(QEMUFile *f)
6611{
6612 uint64_t v;
6613 v = (uint64_t)qemu_get_be32(f) << 32;
6614 v |= qemu_get_be32(f);
6615 return v;
6616}
6617
6618void qemu_put_struct(QEMUFile* f, const QField* fields, const void* s)
6619{
6620 const QField* qf = fields;
6621
6622 for (;;) {
6623 uint8_t* p = (uint8_t*)s + qf->offset;
6624
6625 switch (qf->type) {
6626 case Q_FIELD_END:
6627 break;
6628 case Q_FIELD_BYTE:
6629 qemu_put_byte(f, p[0]);
6630 break;
6631 case Q_FIELD_INT16:
6632 qemu_put_be16(f, ((uint16_t*)p)[0]);
6633 break;
6634 case Q_FIELD_INT32:
6635 qemu_put_be32(f, ((uint32_t*)p)[0]);
6636 break;
6637 case Q_FIELD_INT64:
6638 qemu_put_be64(f, ((uint64_t*)p)[0]);
6639 break;
6640 case Q_FIELD_BUFFER:
6641 if (fields[1].type != Q_FIELD_BUFFER_SIZE ||
6642 fields[2].type != Q_FIELD_BUFFER_SIZE)
6643 {
6644 fprintf(stderr, "%s: invalid QFIELD_BUFFER item passed as argument. aborting\n",
6645 __FUNCTION__ );
6646 exit(1);
6647 }
6648 else
6649 {
6650 uint32_t size = ((uint32_t)fields[1].offset << 16) | (uint32_t)fields[2].offset;
6651
6652 qemu_put_buffer(f, p, size);
6653 qf += 2;
6654 }
6655 break;
6656 default:
6657 fprintf(stderr, "%s: invalid fields list passed as argument. aborting\n", __FUNCTION__);
6658 exit(1);
6659 }
6660 qf++;
6661 }
6662}
6663
6664int qemu_get_struct(QEMUFile* f, const QField* fields, void* s)
6665{
6666 const QField* qf = fields;
6667
6668 for (;;) {
6669 uint8_t* p = (uint8_t*)s + qf->offset;
6670
6671 switch (qf->type) {
6672 case Q_FIELD_END:
6673 break;
6674 case Q_FIELD_BYTE:
6675 p[0] = qemu_get_byte(f);
6676 break;
6677 case Q_FIELD_INT16:
6678 ((uint16_t*)p)[0] = qemu_get_be16(f);
6679 break;
6680 case Q_FIELD_INT32:
6681 ((uint32_t*)p)[0] = qemu_get_be32(f);
6682 break;
6683 case Q_FIELD_INT64:
6684 ((uint64_t*)p)[0] = qemu_get_be64(f);
6685 break;
6686 case Q_FIELD_BUFFER:
6687 if (fields[1].type != Q_FIELD_BUFFER_SIZE ||
6688 fields[2].type != Q_FIELD_BUFFER_SIZE)
6689 {
6690 fprintf(stderr, "%s: invalid QFIELD_BUFFER item passed as argument.\n",
6691 __FUNCTION__ );
6692 return -1;
6693 }
6694 else
6695 {
6696 uint32_t size = ((uint32_t)fields[1].offset << 16) | (uint32_t)fields[2].offset;
6697 int ret = qemu_get_buffer(f, p, size);
6698
6699 if (ret != size) {
6700 fprintf(stderr, "%s: not enough bytes to load structure\n", __FUNCTION__);
6701 return -1;
6702 }
6703 qf += 2;
6704 }
6705 break;
6706 default:
6707 fprintf(stderr, "%s: invalid fields list passed as argument. aborting\n", __FUNCTION__);
6708 exit(1);
6709 }
6710 qf++;
6711 }
6712 return 0;
6713}
6714
6715typedef struct SaveStateEntry {
6716 char idstr[256];
6717 int instance_id;
6718 int version_id;
6719 SaveStateHandler *save_state;
6720 LoadStateHandler *load_state;
6721 void *opaque;
6722 struct SaveStateEntry *next;
6723} SaveStateEntry;
6724
6725static SaveStateEntry *first_se;
6726
6727/* TODO: Individual devices generally have very little idea about the rest
6728 of the system, so instance_id should be removed/replaced.
6729 Meanwhile pass -1 as instance_id if you do not already have a clearly
6730 distinguishing id for all instances of your device class. */
6731int register_savevm(const char *idstr,
6732 int instance_id,
6733 int version_id,
6734 SaveStateHandler *save_state,
6735 LoadStateHandler *load_state,
6736 void *opaque)
6737{
6738 SaveStateEntry *se, **pse;
6739
6740 se = qemu_malloc(sizeof(SaveStateEntry));
6741 if (!se)
6742 return -1;
6743 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6744 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6745 se->version_id = version_id;
6746 se->save_state = save_state;
6747 se->load_state = load_state;
6748 se->opaque = opaque;
6749 se->next = NULL;
6750
6751 /* add at the end of list */
6752 pse = &first_se;
6753 while (*pse != NULL) {
6754 if (instance_id == -1
6755 && strcmp(se->idstr, (*pse)->idstr) == 0
6756 && se->instance_id <= (*pse)->instance_id)
6757 se->instance_id = (*pse)->instance_id + 1;
6758 pse = &(*pse)->next;
6759 }
6760 *pse = se;
6761 return 0;
6762}
6763
6764#define QEMU_VM_FILE_MAGIC 0x5145564d
6765#define QEMU_VM_FILE_VERSION 0x00000002
6766
6767static int qemu_savevm_state(QEMUFile *f)
6768{
6769 SaveStateEntry *se;
6770 int len, ret;
6771 int64_t cur_pos, len_pos, total_len_pos;
6772
6773 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6774 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6775 total_len_pos = qemu_ftell(f);
6776 qemu_put_be64(f, 0); /* total size */
6777
6778 for(se = first_se; se != NULL; se = se->next) {
6779 if (se->save_state == NULL)
6780 /* this one has a loader only, for backwards compatibility */
6781 continue;
6782
6783 /* ID string */
6784 len = strlen(se->idstr);
6785 qemu_put_byte(f, len);
6786 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6787
6788 qemu_put_be32(f, se->instance_id);
6789 qemu_put_be32(f, se->version_id);
6790
6791 /* record size: filled later */
6792 len_pos = qemu_ftell(f);
6793 qemu_put_be32(f, 0);
6794 se->save_state(f, se->opaque);
6795
6796 /* fill record size */
6797 cur_pos = qemu_ftell(f);
6798 len = cur_pos - len_pos - 4;
6799 qemu_fseek(f, len_pos, SEEK_SET);
6800 qemu_put_be32(f, len);
6801 qemu_fseek(f, cur_pos, SEEK_SET);
6802 }
6803 cur_pos = qemu_ftell(f);
6804 qemu_fseek(f, total_len_pos, SEEK_SET);
6805 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6806 qemu_fseek(f, cur_pos, SEEK_SET);
6807
6808 ret = 0;
6809 return ret;
6810}
6811
6812static SaveStateEntry *find_se(const char *idstr, int instance_id)
6813{
6814 SaveStateEntry *se;
6815
6816 for(se = first_se; se != NULL; se = se->next) {
6817 if (!strcmp(se->idstr, idstr) &&
6818 instance_id == se->instance_id)
6819 return se;
6820 }
6821 return NULL;
6822}
6823
6824static int qemu_loadvm_state(QEMUFile *f)
6825{
6826 SaveStateEntry *se;
6827 int len, ret, instance_id, record_len, version_id;
6828 int64_t total_len, end_pos, cur_pos;
6829 unsigned int v;
6830 char idstr[256];
6831
6832 v = qemu_get_be32(f);
6833 if (v != QEMU_VM_FILE_MAGIC)
6834 goto fail;
6835 v = qemu_get_be32(f);
6836 if (v != QEMU_VM_FILE_VERSION) {
6837 fail:
6838 ret = -1;
6839 goto the_end;
6840 }
6841 total_len = qemu_get_be64(f);
6842 end_pos = total_len + qemu_ftell(f);
6843 for(;;) {
6844 if (qemu_ftell(f) >= end_pos)
6845 break;
6846 len = qemu_get_byte(f);
6847 qemu_get_buffer(f, (uint8_t *)idstr, len);
6848 idstr[len] = '\0';
6849 instance_id = qemu_get_be32(f);
6850 version_id = qemu_get_be32(f);
6851 record_len = qemu_get_be32(f);
6852#if 0
6853 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6854 idstr, instance_id, version_id, record_len);
6855#endif
6856 cur_pos = qemu_ftell(f);
6857 se = find_se(idstr, instance_id);
6858 if (!se) {
6859 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6860 instance_id, idstr);
6861 } else {
6862 ret = se->load_state(f, se->opaque, version_id);
6863 if (ret < 0) {
6864 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6865 instance_id, idstr);
6866 }
6867 }
6868 /* always seek to exact end of record */
6869 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6870 }
6871 ret = 0;
6872 the_end:
6873 return ret;
6874}
6875
6876/* device can contain snapshots */
6877static int bdrv_can_snapshot(BlockDriverState *bs)
6878{
6879 return (bs &&
6880 !bdrv_is_removable(bs) &&
6881 !bdrv_is_read_only(bs));
6882}
6883
6884/* device must be snapshots in order to have a reliable snapshot */
6885static int bdrv_has_snapshot(BlockDriverState *bs)
6886{
6887 return (bs &&
6888 !bdrv_is_removable(bs) &&
6889 !bdrv_is_read_only(bs));
6890}
6891
6892static BlockDriverState *get_bs_snapshots(void)
6893{
6894 BlockDriverState *bs;
6895 int i;
6896
6897 if (bs_snapshots)
6898 return bs_snapshots;
6899 for(i = 0; i <= nb_drives; i++) {
6900 bs = drives_table[i].bdrv;
6901 if (bdrv_can_snapshot(bs))
6902 goto ok;
6903 }
6904 return NULL;
6905 ok:
6906 bs_snapshots = bs;
6907 return bs;
6908}
6909
6910static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6911 const char *name)
6912{
6913 QEMUSnapshotInfo *sn_tab, *sn;
6914 int nb_sns, i, ret;
6915
6916 ret = -ENOENT;
6917 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6918 if (nb_sns < 0)
6919 return ret;
6920 for(i = 0; i < nb_sns; i++) {
6921 sn = &sn_tab[i];
6922 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6923 *sn_info = *sn;
6924 ret = 0;
6925 break;
6926 }
6927 }
6928 qemu_free(sn_tab);
6929 return ret;
6930}
6931
6932void do_savevm(const char *name)
6933{
6934 BlockDriverState *bs, *bs1;
6935 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6936 int must_delete, ret, i;
6937 BlockDriverInfo bdi1, *bdi = &bdi1;
6938 QEMUFile *f;
6939 int saved_vm_running;
6940#ifdef _WIN32
6941 struct _timeb tb;
6942#else
6943 struct timeval tv;
6944#endif
6945
6946 bs = get_bs_snapshots();
6947 if (!bs) {
6948 term_printf("No block device can accept snapshots\n");
6949 return;
6950 }
6951
6952 /* ??? Should this occur after vm_stop? */
6953 qemu_aio_flush();
6954
6955 saved_vm_running = vm_running;
6956 vm_stop(0);
6957
6958 must_delete = 0;
6959 if (name) {
6960 ret = bdrv_snapshot_find(bs, old_sn, name);
6961 if (ret >= 0) {
6962 must_delete = 1;
6963 }
6964 }
6965 memset(sn, 0, sizeof(*sn));
6966 if (must_delete) {
6967 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6968 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6969 } else {
6970 if (name)
6971 pstrcpy(sn->name, sizeof(sn->name), name);
6972 }
6973
6974 /* fill auxiliary fields */
6975#ifdef _WIN32
6976 _ftime(&tb);
6977 sn->date_sec = tb.time;
6978 sn->date_nsec = tb.millitm * 1000000;
6979#else
6980 gettimeofday(&tv, NULL);
6981 sn->date_sec = tv.tv_sec;
6982 sn->date_nsec = tv.tv_usec * 1000;
6983#endif
6984 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6985
6986 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6987 term_printf("Device %s does not support VM state snapshots\n",
6988 bdrv_get_device_name(bs));
6989 goto the_end;
6990 }
6991
6992 /* save the VM state */
6993 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6994 if (!f) {
6995 term_printf("Could not open VM state file\n");
6996 goto the_end;
6997 }
6998 ret = qemu_savevm_state(f);
6999 sn->vm_state_size = qemu_ftell(f);
7000 qemu_fclose(f);
7001 if (ret < 0) {
7002 term_printf("Error %d while writing VM\n", ret);
7003 goto the_end;
7004 }
7005
7006 /* create the snapshots */
7007
7008 for(i = 0; i < nb_drives; i++) {
7009 bs1 = drives_table[i].bdrv;
7010 if (bdrv_has_snapshot(bs1)) {
7011 if (must_delete) {
7012 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
7013 if (ret < 0) {
7014 term_printf("Error while deleting snapshot on '%s'\n",
7015 bdrv_get_device_name(bs1));
7016 }
7017 }
7018 ret = bdrv_snapshot_create(bs1, sn);
7019 if (ret < 0) {
7020 term_printf("Error while creating snapshot on '%s'\n",
7021 bdrv_get_device_name(bs1));
7022 }
7023 }
7024 }
7025
7026 the_end:
7027 if (saved_vm_running)
7028 vm_start();
7029}
7030
7031void do_loadvm(const char *name)
7032{
7033 BlockDriverState *bs, *bs1;
7034 BlockDriverInfo bdi1, *bdi = &bdi1;
7035 QEMUFile *f;
7036 int i, ret;
7037 int saved_vm_running;
7038
7039 bs = get_bs_snapshots();
7040 if (!bs) {
7041 term_printf("No block device supports snapshots\n");
7042 return;
7043 }
7044
7045 /* Flush all IO requests so they don't interfere with the new state. */
7046 qemu_aio_flush();
7047
7048 saved_vm_running = vm_running;
7049 vm_stop(0);
7050
7051 for(i = 0; i <= nb_drives; i++) {
7052 bs1 = drives_table[i].bdrv;
7053 if (bdrv_has_snapshot(bs1)) {
7054 ret = bdrv_snapshot_goto(bs1, name);
7055 if (ret < 0) {
7056 if (bs != bs1)
7057 term_printf("Warning: ");
7058 switch(ret) {
7059 case -ENOTSUP:
7060 term_printf("Snapshots not supported on device '%s'\n",
7061 bdrv_get_device_name(bs1));
7062 break;
7063 case -ENOENT:
7064 term_printf("Could not find snapshot '%s' on device '%s'\n",
7065 name, bdrv_get_device_name(bs1));
7066 break;
7067 default:
7068 term_printf("Error %d while activating snapshot on '%s'\n",
7069 ret, bdrv_get_device_name(bs1));
7070 break;
7071 }
7072 /* fatal on snapshot block device */
7073 if (bs == bs1)
7074 goto the_end;
7075 }
7076 }
7077 }
7078
7079 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
7080 term_printf("Device %s does not support VM state snapshots\n",
7081 bdrv_get_device_name(bs));
7082 return;
7083 }
7084
7085 /* restore the VM state */
7086 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
7087 if (!f) {
7088 term_printf("Could not open VM state file\n");
7089 goto the_end;
7090 }
7091 ret = qemu_loadvm_state(f);
7092 qemu_fclose(f);
7093 if (ret < 0) {
7094 term_printf("Error %d while loading VM state\n", ret);
7095 }
7096 the_end:
7097 if (saved_vm_running)
7098 vm_start();
7099}
7100
7101void do_delvm(const char *name)
7102{
7103 BlockDriverState *bs, *bs1;
7104 int i, ret;
7105
7106 bs = get_bs_snapshots();
7107 if (!bs) {
7108 term_printf("No block device supports snapshots\n");
7109 return;
7110 }
7111
7112 for(i = 0; i <= nb_drives; i++) {
7113 bs1 = drives_table[i].bdrv;
7114 if (bdrv_has_snapshot(bs1)) {
7115 ret = bdrv_snapshot_delete(bs1, name);
7116 if (ret < 0) {
7117 if (ret == -ENOTSUP)
7118 term_printf("Snapshots not supported on device '%s'\n",
7119 bdrv_get_device_name(bs1));
7120 else
7121 term_printf("Error %d while deleting snapshot on '%s'\n",
7122 ret, bdrv_get_device_name(bs1));
7123 }
7124 }
7125 }
7126}
7127
7128void do_info_snapshots(void)
7129{
7130 BlockDriverState *bs, *bs1;
7131 QEMUSnapshotInfo *sn_tab, *sn;
7132 int nb_sns, i;
7133 char buf[256];
7134
7135 bs = get_bs_snapshots();
7136 if (!bs) {
7137 term_printf("No available block device supports snapshots\n");
7138 return;
7139 }
7140 term_printf("Snapshot devices:");
7141 for(i = 0; i <= nb_drives; i++) {
7142 bs1 = drives_table[i].bdrv;
7143 if (bdrv_has_snapshot(bs1)) {
7144 if (bs == bs1)
7145 term_printf(" %s", bdrv_get_device_name(bs1));
7146 }
7147 }
7148 term_printf("\n");
7149
7150 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
7151 if (nb_sns < 0) {
7152 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
7153 return;
7154 }
7155 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
7156 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
7157 for(i = 0; i < nb_sns; i++) {
7158 sn = &sn_tab[i];
7159 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
7160 }
7161 qemu_free(sn_tab);
7162}
7163
7164/***********************************************************/
7165/* ram save/restore */
7166/* we just avoid storing empty pages */
7167static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
7168{
7169 int i, v;
7170
7171 v = buf[0];
7172 for(i = 1; i < len; i++) {
7173 if (buf[i] != v)
7174 goto normal_save;
7175 }
7176 qemu_put_byte(f, 1);
7177 qemu_put_byte(f, v);
7178 return;
7179 normal_save:
7180 qemu_put_byte(f, 0);
7181 qemu_put_buffer(f, buf, len);
7182}
7183
7184static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
7185{
7186 int v;
7187
7188 v = qemu_get_byte(f);
7189 switch(v) {
7190 case 0:
7191 if (qemu_get_buffer(f, buf, len) != len)
7192 return -EIO;
7193 break;
7194 case 1:
7195 v = qemu_get_byte(f);
7196 memset(buf, v, len);
7197 break;
7198 default:
7199 return -EINVAL;
7200 }
7201 return 0;
7202}
7203
7204static int ram_load_v1(QEMUFile *f, void *opaque)
7205{
7206 int ret;
7207 ram_addr_t i;
7208
7209 if (qemu_get_be32(f) != phys_ram_size)
7210 return -EINVAL;
7211 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
7212 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
7213 if (ret)
7214 return ret;
7215 }
7216 return 0;
7217}
7218
7219#define BDRV_HASH_BLOCK_SIZE 1024
7220#define IOBUF_SIZE 4096
7221#define RAM_CBLOCK_MAGIC 0xfabe
7222
7223typedef struct RamCompressState {
7224 z_stream zstream;
7225 QEMUFile *f;
7226 uint8_t buf[IOBUF_SIZE];
7227} RamCompressState;
7228
7229static int ram_compress_open(RamCompressState *s, QEMUFile *f)
7230{
7231 int ret;
7232 memset(s, 0, sizeof(*s));
7233 s->f = f;
7234 ret = deflateInit2(&s->zstream, 1,
7235 Z_DEFLATED, 15,
7236 9, Z_DEFAULT_STRATEGY);
7237 if (ret != Z_OK)
7238 return -1;
7239 s->zstream.avail_out = IOBUF_SIZE;
7240 s->zstream.next_out = s->buf;
7241 return 0;
7242}
7243
7244static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
7245{
7246 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
7247 qemu_put_be16(s->f, len);
7248 qemu_put_buffer(s->f, buf, len);
7249}
7250
7251static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
7252{
7253 int ret;
7254
7255 s->zstream.avail_in = len;
7256 s->zstream.next_in = (uint8_t *)buf;
7257 while (s->zstream.avail_in > 0) {
7258 ret = deflate(&s->zstream, Z_NO_FLUSH);
7259 if (ret != Z_OK)
7260 return -1;
7261 if (s->zstream.avail_out == 0) {
7262 ram_put_cblock(s, s->buf, IOBUF_SIZE);
7263 s->zstream.avail_out = IOBUF_SIZE;
7264 s->zstream.next_out = s->buf;
7265 }
7266 }
7267 return 0;
7268}
7269
7270static void ram_compress_close(RamCompressState *s)
7271{
7272 int len, ret;
7273
7274 /* compress last bytes */
7275 for(;;) {
7276 ret = deflate(&s->zstream, Z_FINISH);
7277 if (ret == Z_OK || ret == Z_STREAM_END) {
7278 len = IOBUF_SIZE - s->zstream.avail_out;
7279 if (len > 0) {
7280 ram_put_cblock(s, s->buf, len);
7281 }
7282 s->zstream.avail_out = IOBUF_SIZE;
7283 s->zstream.next_out = s->buf;
7284 if (ret == Z_STREAM_END)
7285 break;
7286 } else {
7287 goto fail;
7288 }
7289 }
7290fail:
7291 deflateEnd(&s->zstream);
7292}
7293
7294typedef struct RamDecompressState {
7295 z_stream zstream;
7296 QEMUFile *f;
7297 uint8_t buf[IOBUF_SIZE];
7298} RamDecompressState;
7299
7300static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
7301{
7302 int ret;
7303 memset(s, 0, sizeof(*s));
7304 s->f = f;
7305 ret = inflateInit(&s->zstream);
7306 if (ret != Z_OK)
7307 return -1;
7308 return 0;
7309}
7310
7311static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
7312{
7313 int ret, clen;
7314
7315 s->zstream.avail_out = len;
7316 s->zstream.next_out = buf;
7317 while (s->zstream.avail_out > 0) {
7318 if (s->zstream.avail_in == 0) {
7319 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
7320 return -1;
7321 clen = qemu_get_be16(s->f);
7322 if (clen > IOBUF_SIZE)
7323 return -1;
7324 qemu_get_buffer(s->f, s->buf, clen);
7325 s->zstream.avail_in = clen;
7326 s->zstream.next_in = s->buf;
7327 }
7328 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7329 if (ret != Z_OK && ret != Z_STREAM_END) {
7330 return -1;
7331 }
7332 }
7333 return 0;
7334}
7335
7336static void ram_decompress_close(RamDecompressState *s)
7337{
7338 inflateEnd(&s->zstream);
7339}
7340
7341static void ram_save(QEMUFile *f, void *opaque)
7342{
7343 ram_addr_t i;
7344 RamCompressState s1, *s = &s1;
7345 uint8_t buf[10];
7346
7347 qemu_put_be32(f, phys_ram_size);
7348 if (ram_compress_open(s, f) < 0)
7349 return;
7350 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7351#if 0
7352 if (tight_savevm_enabled) {
7353 int64_t sector_num;
7354 int j;
7355
7356 /* find if the memory block is available on a virtual
7357 block device */
7358 sector_num = -1;
7359 for(j = 0; j < nb_drives; j++) {
7360 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7361 phys_ram_base + i,
7362 BDRV_HASH_BLOCK_SIZE);
7363 if (sector_num >= 0)
7364 break;
7365 }
7366 if (j == nb_drives)
7367 goto normal_compress;
7368 buf[0] = 1;
7369 buf[1] = j;
7370 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7371 ram_compress_buf(s, buf, 10);
7372 } else
7373#endif
7374 {
7375 // normal_compress:
7376 buf[0] = 0;
7377 ram_compress_buf(s, buf, 1);
7378 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7379 }
7380 }
7381 ram_compress_close(s);
7382}
7383
7384static int ram_load(QEMUFile *f, void *opaque, int version_id)
7385{
7386 RamDecompressState s1, *s = &s1;
7387 uint8_t buf[10];
7388 ram_addr_t i;
7389
7390 if (version_id == 1)
7391 return ram_load_v1(f, opaque);
7392 if (version_id != 2)
7393 return -EINVAL;
7394 if (qemu_get_be32(f) != phys_ram_size)
7395 return -EINVAL;
7396 if (ram_decompress_open(s, f) < 0)
7397 return -EINVAL;
7398 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7399 if (ram_decompress_buf(s, buf, 1) < 0) {
7400 fprintf(stderr, "Error while reading ram block header\n");
7401 goto error;
7402 }
7403 if (buf[0] == 0) {
7404 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7405 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7406 goto error;
7407 }
7408 } else
7409#if 0
7410 if (buf[0] == 1) {
7411 int bs_index;
7412 int64_t sector_num;
7413
7414 ram_decompress_buf(s, buf + 1, 9);
7415 bs_index = buf[1];
7416 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7417 if (bs_index >= nb_drives) {
7418 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7419 goto error;
7420 }
7421 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7422 phys_ram_base + i,
7423 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7424 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7425 bs_index, sector_num);
7426 goto error;
7427 }
7428 } else
7429#endif
7430 {
7431 error:
7432 printf("Error block header\n");
7433 return -EINVAL;
7434 }
7435 }
7436 ram_decompress_close(s);
7437 return 0;
7438}
7439
7440/***********************************************************/
7441/* bottom halves (can be seen as timers which expire ASAP) */
7442
7443struct QEMUBH {
7444 QEMUBHFunc *cb;
7445 void *opaque;
7446 int scheduled;
7447 QEMUBH *next;
7448};
7449
7450static QEMUBH *first_bh = NULL;
7451
7452QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7453{
7454 QEMUBH *bh;
7455 bh = qemu_mallocz(sizeof(QEMUBH));
7456 if (!bh)
7457 return NULL;
7458 bh->cb = cb;
7459 bh->opaque = opaque;
7460 return bh;
7461}
7462
7463int qemu_bh_poll(void)
7464{
7465 QEMUBH *bh, **pbh;
7466 int ret;
7467
7468 ret = 0;
7469 for(;;) {
7470 pbh = &first_bh;
7471 bh = *pbh;
7472 if (!bh)
7473 break;
7474 ret = 1;
7475 *pbh = bh->next;
7476 bh->scheduled = 0;
7477 bh->cb(bh->opaque);
7478 }
7479 return ret;
7480}
7481
7482void qemu_bh_schedule(QEMUBH *bh)
7483{
7484 CPUState *env = cpu_single_env;
7485 if (bh->scheduled)
7486 return;
7487 bh->scheduled = 1;
7488 bh->next = first_bh;
7489 first_bh = bh;
7490
7491 /* stop the currently executing CPU to execute the BH ASAP */
7492 if (env) {
7493 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7494 }
7495}
7496
7497void qemu_bh_cancel(QEMUBH *bh)
7498{
7499 QEMUBH **pbh;
7500 if (bh->scheduled) {
7501 pbh = &first_bh;
7502 while (*pbh != bh)
7503 pbh = &(*pbh)->next;
7504 *pbh = bh->next;
7505 bh->scheduled = 0;
7506 }
7507}
7508
7509void qemu_bh_delete(QEMUBH *bh)
7510{
7511 qemu_bh_cancel(bh);
7512 qemu_free(bh);
7513}
7514
7515/***********************************************************/
7516/* machine registration */
7517
7518QEMUMachine *first_machine = NULL;
7519
7520int qemu_register_machine(QEMUMachine *m)
7521{
7522 QEMUMachine **pm;
7523 pm = &first_machine;
7524 while (*pm != NULL)
7525 pm = &(*pm)->next;
7526 m->next = NULL;
7527 *pm = m;
7528 return 0;
7529}
7530
7531static QEMUMachine *find_machine(const char *name)
7532{
7533 QEMUMachine *m;
7534
7535 for(m = first_machine; m != NULL; m = m->next) {
7536 if (!strcmp(m->name, name))
7537 return m;
7538 }
7539 return NULL;
7540}
7541
7542/***********************************************************/
7543/* main execution loop */
7544
7545static void gui_update(void *opaque)
7546{
7547 DisplayState *ds = opaque;
7548 ds->dpy_refresh(ds);
7549 qemu_mod_timer(ds->gui_timer,
7550 (ds->gui_timer_interval ?
7551 ds->gui_timer_interval :
7552 GUI_REFRESH_INTERVAL)
7553 + qemu_get_clock(rt_clock));
7554}
7555
7556struct vm_change_state_entry {
7557 VMChangeStateHandler *cb;
7558 void *opaque;
7559 LIST_ENTRY (vm_change_state_entry) entries;
7560};
7561
7562static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7563
7564VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7565 void *opaque)
7566{
7567 VMChangeStateEntry *e;
7568
7569 e = qemu_mallocz(sizeof (*e));
7570 if (!e)
7571 return NULL;
7572
7573 e->cb = cb;
7574 e->opaque = opaque;
7575 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7576 return e;
7577}
7578
7579void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7580{
7581 LIST_REMOVE (e, entries);
7582 qemu_free (e);
7583}
7584
7585static void vm_state_notify(int running)
7586{
7587 VMChangeStateEntry *e;
7588
7589 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7590 e->cb(e->opaque, running);
7591 }
7592}
7593
7594/* XXX: support several handlers */
7595static VMStopHandler *vm_stop_cb;
7596static void *vm_stop_opaque;
7597
7598int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7599{
7600 vm_stop_cb = cb;
7601 vm_stop_opaque = opaque;
7602 return 0;
7603}
7604
7605void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7606{
7607 vm_stop_cb = NULL;
7608}
7609
7610void vm_start(void)
7611{
7612 if (!vm_running) {
7613 cpu_enable_ticks();
7614 vm_running = 1;
7615 vm_state_notify(1);
7616 qemu_rearm_alarm_timer(alarm_timer);
7617 }
7618}
7619
7620void vm_stop(int reason)
7621{
7622 if (vm_running) {
7623 cpu_disable_ticks();
7624 vm_running = 0;
7625 if (reason != 0) {
7626 if (vm_stop_cb) {
7627 vm_stop_cb(vm_stop_opaque, reason);
7628 }
7629 }
7630 vm_state_notify(0);
7631 }
7632}
7633
7634/* reset/shutdown handler */
7635
7636typedef struct QEMUResetEntry {
7637 QEMUResetHandler *func;
7638 void *opaque;
7639 struct QEMUResetEntry *next;
7640} QEMUResetEntry;
7641
7642static QEMUResetEntry *first_reset_entry;
7643static int reset_requested;
7644static int shutdown_requested;
7645static int powerdown_requested;
7646
7647int qemu_shutdown_requested(void)
7648{
7649 int r = shutdown_requested;
7650 shutdown_requested = 0;
7651 return r;
7652}
7653
7654int qemu_reset_requested(void)
7655{
7656 int r = reset_requested;
7657 reset_requested = 0;
7658 return r;
7659}
7660
7661int qemu_powerdown_requested(void)
7662{
7663 int r = powerdown_requested;
7664 powerdown_requested = 0;
7665 return r;
7666}
7667
7668void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7669{
7670 QEMUResetEntry **pre, *re;
7671
7672 pre = &first_reset_entry;
7673 while (*pre != NULL)
7674 pre = &(*pre)->next;
7675 re = qemu_mallocz(sizeof(QEMUResetEntry));
7676 re->func = func;
7677 re->opaque = opaque;
7678 re->next = NULL;
7679 *pre = re;
7680}
7681
7682void qemu_system_reset(void)
7683{
7684 QEMUResetEntry *re;
7685
7686 /* reset all devices */
7687 for(re = first_reset_entry; re != NULL; re = re->next) {
7688 re->func(re->opaque);
7689 }
7690}
7691
7692void qemu_system_reset_request(void)
7693{
7694 if (no_reboot) {
7695 shutdown_requested = 1;
7696 } else {
7697 reset_requested = 1;
7698 }
7699 if (cpu_single_env)
7700 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7701}
7702
7703#ifdef HAS_AUDIO
7704extern void AUD_cleanup();
7705#endif
7706
7707void qemu_system_shutdown_request(void)
7708{
7709 shutdown_requested = 1;
7710 if (cpu_single_env)
7711 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7712}
7713
7714void qemu_system_powerdown_request(void)
7715{
7716 powerdown_requested = 1;
7717 if (cpu_single_env)
7718 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7719}
7720
7721#define MAIN_LOOP_STATS 0
7722
7723#if MAIN_LOOP_STATS
7724typedef struct {
7725 int counter;
7726 int64_t reset_time; // time when counter is reset
7727 int64_t spent_time_total; // total time spent since last counter reset
7728 int64_t spent_time_min; // minimum time spent in call
7729 int64_t spent_time_max; // maximum time spent in call
7730 int64_t wait_time_total; // total time spent waiting for select()
7731} MainLoopStats;
7732
7733static __inline__ int64_t
7734mainloopstats_now( void )
7735{
7736 return qemu_get_clock( vm_clock );
7737}
7738
7739static __inline__ double
7740mainloopstats_to_ms( int64_t duration )
7741{
7742 return duration / 1000000.;
7743}
7744
7745static void
7746mainloopstats_reset( MainLoopStats* s )
7747{
7748 int64_t now = qemu_get_clock( vm_clock );
7749
7750 s->counter = 0;
7751 s->reset_time = now;
7752 s->spent_time_total = 0;
7753 s->wait_time_total = 0;
7754 s->spent_time_min = INT_MAX;
7755 s->spent_time_max = 0;
7756}
7757
7758static MainLoopStats main_loop_stats;
7759#endif /* MAIN_LOOP_STATS */
7760
7761void main_loop_wait(int timeout)
7762{
7763 IOHandlerRecord *ioh;
7764 fd_set rfds, wfds, xfds;
7765 int ret, nfds;
7766#ifdef _WIN32
7767 int ret2, i;
7768#endif
7769 struct timeval tv;
7770 PollingEntry *pe;
7771
7772#if MAIN_LOOP_STATS
7773 int64 time_before = mainloopstats_now();
7774 int64 time_after_select;
7775#endif
7776
7777 /* XXX: need to suppress polling by better using win32 events */
7778 ret = 0;
7779 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7780 ret |= pe->func(pe->opaque);
7781 }
7782#ifdef _WIN32
7783 if (ret == 0) {
7784 int err;
7785 WaitObjects *w = &wait_objects;
7786
7787 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7788 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7789 if (w->func[ret - WAIT_OBJECT_0])
7790 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7791
7792 /* Check for additional signaled events */
7793 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7794
7795 /* Check if event is signaled */
7796 ret2 = WaitForSingleObject(w->events[i], 0);
7797 if(ret2 == WAIT_OBJECT_0) {
7798 if (w->func[i])
7799 w->func[i](w->opaque[i]);
7800 } else if (ret2 == WAIT_TIMEOUT) {
7801 } else {
7802 err = GetLastError();
7803 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7804 }
7805 }
7806 } else if (ret == WAIT_TIMEOUT) {
7807 } else {
7808 err = GetLastError();
7809 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7810 }
7811 }
7812#endif
7813 /* poll any events */
7814 /* XXX: separate device handlers from system ones */
7815 nfds = -1;
7816 FD_ZERO(&rfds);
7817 FD_ZERO(&wfds);
7818 FD_ZERO(&xfds);
7819 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7820 if (ioh->deleted)
7821 continue;
7822 if (ioh->fd_read &&
7823 (!ioh->fd_read_poll ||
7824 ioh->fd_read_poll(ioh->opaque) != 0)) {
7825 FD_SET(ioh->fd, &rfds);
7826 if (ioh->fd > nfds)
7827 nfds = ioh->fd;
7828 }
7829 if (ioh->fd_write) {
7830 FD_SET(ioh->fd, &wfds);
7831 if (ioh->fd > nfds)
7832 nfds = ioh->fd;
7833 }
7834 }
7835
7836 tv.tv_sec = 0;
7837#ifdef _WIN32
7838 tv.tv_usec = 0;
7839#else
7840 tv.tv_usec = timeout * 1000;
7841#endif
7842#if defined(CONFIG_SLIRP)
7843 if (slirp_inited) {
7844 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7845 }
7846#endif
7847 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7848#if MAIN_LOOP_STATS
7849 time_after_select = mainloopstats_now();
7850#endif
7851 if (ret > 0) {
7852 IOHandlerRecord **pioh;
7853
7854 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7855 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7856 ioh->fd_read(ioh->opaque);
7857 }
7858 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7859 ioh->fd_write(ioh->opaque);
7860 }
7861 }
7862
7863 /* remove deleted IO handlers */
7864 pioh = &first_io_handler;
7865 while (*pioh) {
7866 ioh = *pioh;
7867 if (ioh->deleted) {
7868 *pioh = ioh->next;
7869 qemu_free(ioh);
7870 } else
7871 pioh = &ioh->next;
7872 }
7873 }
7874#if defined(CONFIG_SLIRP)
7875 if (slirp_inited) {
7876 if (ret < 0) {
7877 FD_ZERO(&rfds);
7878 FD_ZERO(&wfds);
7879 FD_ZERO(&xfds);
7880 }
7881 slirp_select_poll(&rfds, &wfds, &xfds);
7882 }
7883#endif
7884 charpipe_poll();
7885
7886 if (vm_running) {
7887 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7888 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7889 qemu_get_clock(vm_clock));
7890 /* run dma transfers, if any */
7891 DMA_run();
7892 }
7893
7894 /* real time timers */
7895 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7896 qemu_get_clock(rt_clock));
7897
7898 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7899 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7900 qemu_rearm_alarm_timer(alarm_timer);
7901 }
7902
7903 /* Check bottom-halves last in case any of the earlier events triggered
7904 them. */
7905 qemu_bh_poll();
7906
7907#if MAIN_LOOP_STATS
7908 {
7909 MainLoopStats* s = &main_loop_stats;
7910 int64_t time_after = mainloopstats_now();
7911 int64_t time_diff = time_after - time_before;
7912
7913 s->spent_time_total += time_diff;
7914 if (time_diff < s->spent_time_min)
7915 s->spent_time_min = time_diff;
7916 if (time_diff > s->spent_time_max)
7917 s->spent_time_max = time_diff;
7918
7919 time_diff = time_after_select - time_before;
7920 s->wait_time_total += time_diff;
7921
7922 if (++s->counter == 1000) {
7923 double period = time_after - s->reset_time;
7924 double average_spent = s->spent_time_total * 1. / s->counter;
7925 double average_wait = s->wait_time_total * 1. / s->counter;
7926
7927 printf( "main loop stats: iterations: %8ld, period: %10.2f ms, avg wait time: %10.2f ms (%.3f %%), avg exec time %10.2f ms (%.3f %%)\n",
7928 s->counter,
7929 mainloopstats_to_ms(period),
7930 mainloopstats_to_ms(average_wait),
7931 s->wait_time_total * 100. / period,
7932 mainloopstats_to_ms(average_spent),
7933 s->spent_time_total * 100. / period );
7934
7935 mainloopstats_reset( s );
7936 }
7937 }
7938#endif /* MAIN_LOOP_STATS */
7939}
7940
7941static int main_loop(void)
7942{
7943 int ret, timeout;
7944#ifdef CONFIG_PROFILER
7945 int64_t ti;
7946#endif
7947 CPUState *env;
7948
7949 cur_cpu = first_cpu;
7950 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7951 for(;;) {
7952 if (vm_running) {
7953
7954 for(;;) {
7955 /* get next cpu */
7956 env = next_cpu;
7957#ifdef CONFIG_PROFILER
7958 ti = profile_getclock();
7959#endif
7960 if (use_icount) {
7961 int64_t count;
7962 int decr;
7963 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7964 env->icount_decr.u16.low = 0;
7965 env->icount_extra = 0;
7966 count = qemu_next_deadline();
7967 count = (count + (1 << icount_time_shift) - 1)
7968 >> icount_time_shift;
7969 qemu_icount += count;
7970 decr = (count > 0xffff) ? 0xffff : count;
7971 count -= decr;
7972 env->icount_decr.u16.low = decr;
7973 env->icount_extra = count;
7974 }
7975 ret = cpu_exec(env);
7976#ifdef CONFIG_PROFILER
7977 qemu_time += profile_getclock() - ti;
7978#endif
7979 if (use_icount) {
7980 /* Fold pending instructions back into the
7981 instruction counter, and clear the interrupt flag. */
7982 qemu_icount -= (env->icount_decr.u16.low
7983 + env->icount_extra);
7984 env->icount_decr.u32 = 0;
7985 env->icount_extra = 0;
7986 }
7987 next_cpu = env->next_cpu ?: first_cpu;
7988 if (event_pending && likely(ret != EXCP_DEBUG)) {
7989 ret = EXCP_INTERRUPT;
7990 event_pending = 0;
7991 break;
7992 }
7993 if (ret == EXCP_HLT) {
7994 /* Give the next CPU a chance to run. */
7995 cur_cpu = env;
7996 continue;
7997 }
7998 if (ret != EXCP_HALTED)
7999 break;
8000 /* all CPUs are halted ? */
8001 if (env == cur_cpu)
8002 break;
8003 }
8004 cur_cpu = env;
8005
8006#ifdef CONFIG_TRACE
8007 if (tbflush_requested) {
8008 tbflush_requested = 0;
8009 tb_flush(env);
8010 ret = EXCP_INTERRUPT;
8011 } else if (exit_requested)
8012 goto ExitRequested;
8013#endif
8014
8015 if (shutdown_requested) {
8016 ret = EXCP_INTERRUPT;
8017 if (no_shutdown) {
8018 vm_stop(0);
8019 no_shutdown = 0;
8020 }
8021 else
8022 break;
8023 }
8024 if (reset_requested) {
8025 reset_requested = 0;
8026 qemu_system_reset();
8027 ret = EXCP_INTERRUPT;
8028 }
8029 if (powerdown_requested) {
8030 powerdown_requested = 0;
8031 qemu_system_powerdown();
8032 ret = EXCP_INTERRUPT;
8033 }
8034 if (unlikely(ret == EXCP_DEBUG)) {
8035 vm_stop(EXCP_DEBUG);
8036 }
8037 /* If all cpus are halted then wait until the next IRQ */
8038 /* XXX: use timeout computed from timers */
8039 if (ret == EXCP_HALTED) {
8040 if (use_icount) {
8041 int64_t add;
8042 int64_t delta;
8043 /* Advance virtual time to the next event. */
8044 if (use_icount == 1) {
8045 /* When not using an adaptive execution frequency
8046 we tend to get badly out of sync with real time,
8047 so just delay for a reasonable amount of time. */
8048 delta = 0;
8049 } else {
8050 delta = cpu_get_icount() - cpu_get_clock();
8051 }
8052 if (delta > 0) {
8053 /* If virtual time is ahead of real time then just
8054 wait for IO. */
8055 timeout = (delta / 1000000) + 1;
8056 } else {
8057 /* Wait for either IO to occur or the next
8058 timer event. */
8059 add = qemu_next_deadline();
8060 /* We advance the timer before checking for IO.
8061 Limit the amount we advance so that early IO
8062 activity won't get the guest too far ahead. */
8063 if (add > 10000000)
8064 add = 10000000;
8065 delta += add;
8066 add = (add + (1 << icount_time_shift) - 1)
8067 >> icount_time_shift;
8068 qemu_icount += add;
8069 timeout = delta / 1000000;
8070 if (timeout < 0)
8071 timeout = 0;
8072 }
8073 } else {
8074 timeout = 10;
8075 }
8076 } else {
8077 timeout = 0;
8078 }
8079 } else {
8080 if (shutdown_requested)
8081 break;
8082 timeout = 10;
8083 }
8084#ifdef CONFIG_PROFILER
8085 ti = profile_getclock();
8086#endif
8087 main_loop_wait(timeout);
8088#ifdef CONFIG_PROFILER
8089 dev_time += profile_getclock() - ti;
8090#endif
8091 }
8092 cpu_disable_ticks();
8093 return ret;
8094
8095#ifdef CONFIG_TRACE
8096ExitRequested:
8097# ifdef HAS_AUDIO
8098 AUD_cleanup();
8099# endif
8100 exit(1);
8101 return 0;
8102#endif
8103}
8104
8105void qemu_help(int exitcode)
8106{
8107 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8108 "usage: %s [options] [disk_image]\n"
8109 "\n"
8110 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8111 "\n"
8112 "Standard options:\n"
8113 "-M machine select emulated machine (-M ? for list)\n"
8114 "-cpu cpu select CPU (-cpu ? for list)\n"
8115 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8116 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8117 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8118 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8119 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8120 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8121 " [,cache=on|off][,format=f]\n"
8122 " use 'file' as a drive image\n"
8123 "-mtdblock file use 'file' as on-board Flash memory image\n"
8124 "-sd file use 'file' as SecureDigital card image\n"
8125 "-pflash file use 'file' as a parallel flash image\n"
8126 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8127 "-snapshot write to temporary files instead of disk image files\n"
8128#ifdef CONFIG_SDL
8129 "-no-frame open SDL window without a frame and window decorations\n"
8130 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8131 "-no-quit disable SDL window close capability\n"
8132#endif
8133#ifdef TARGET_I386
8134 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8135#endif
8136 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8137 "-smp n set the number of CPUs to 'n' [default=1]\n"
8138 "-nographic disable graphical output and redirect serial I/Os to console\n"
8139 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8140#ifndef _WIN32
8141 "-k language use keyboard layout (for example \"fr\" for French)\n"
8142#endif
8143#ifdef HAS_AUDIO
8144 "-audio-help print list of audio drivers and their options\n"
8145 "-soundhw c1,... enable audio support\n"
8146 " and only specified sound cards (comma separated list)\n"
8147 " use -soundhw ? to get the list of supported cards\n"
8148 " use -soundhw all to enable all of them\n"
8149#endif
8150 "-localtime set the real time clock to local time [default=utc]\n"
8151 "-full-screen start in full screen\n"
8152#ifdef TARGET_I386
8153 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8154#endif
8155 "-usb enable the USB driver (will be the default soon)\n"
8156 "-usbdevice name add the host or guest USB device 'name'\n"
8157#if defined(TARGET_PPC) || defined(TARGET_SPARC)
8158 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8159#endif
8160 "-name string set the name of the guest\n"
8161 "\n"
8162 "Network options:\n"
8163 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8164 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8165#ifdef CONFIG_SLIRP
8166 "-net user[,vlan=n][,hostname=host]\n"
8167 " connect the user mode network stack to VLAN 'n' and send\n"
8168 " hostname 'host' to DHCP clients\n"
8169#endif
8170#ifdef _WIN32
8171 "-net tap[,vlan=n],ifname=name\n"
8172 " connect the host TAP network interface to VLAN 'n'\n"
8173#else
8174 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8175 " connect the host TAP network interface to VLAN 'n' and use the\n"
8176 " network scripts 'file' (default=%s)\n"
8177 " and 'dfile' (default=%s);\n"
8178 " use '[down]script=no' to disable script execution;\n"
8179 " use 'fd=h' to connect to an already opened TAP interface\n"
8180#endif
8181 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8182 " connect the vlan 'n' to another VLAN using a socket connection\n"
8183 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8184 " connect the vlan 'n' to multicast maddr and port\n"
8185 "-net none use it alone to have zero network devices; if no -net option\n"
8186 " is provided, the default is '-net nic -net user'\n"
8187 "\n"
8188#ifdef CONFIG_SLIRP
8189 "-tftp dir allow tftp access to files in dir [-net user]\n"
8190 "-bootp file advertise file in BOOTP replies\n"
8191#ifndef _WIN32
8192 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8193#endif
8194 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8195 " redirect TCP or UDP connections from host to guest [-net user]\n"
8196#endif
8197 "\n"
8198 "Linux boot specific:\n"
8199 "-kernel bzImage use 'bzImage' as kernel image\n"
8200 "-append cmdline use 'cmdline' as kernel command line\n"
8201 "-initrd file use 'file' as initial ram disk\n"
8202 "\n"
8203 "Debug/Expert options:\n"
8204 "-monitor dev redirect the monitor to char device 'dev'\n"
8205 "-serial dev redirect the serial port to char device 'dev'\n"
8206 "-parallel dev redirect the parallel port to char device 'dev'\n"
8207 "-pidfile file Write PID to 'file'\n"
8208 "-S freeze CPU at startup (use 'c' to start execution)\n"
8209 "-s wait gdb connection to port\n"
8210 "-p port set gdb connection port [default=%s]\n"
8211 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8212 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8213 " translation (t=none or lba) (usually qemu can guess them)\n"
8214 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8215#ifdef USE_KQEMU
8216 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8217 "-no-kqemu disable KQEMU kernel module usage\n"
8218#endif
8219#ifdef TARGET_I386
8220 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8221 " (default is CL-GD5446 PCI VGA)\n"
8222 "-no-acpi disable ACPI\n"
8223#endif
8224#ifdef CONFIG_CURSES
8225 "-curses use a curses/ncurses interface instead of SDL\n"
8226#endif
8227 "-no-reboot exit instead of rebooting\n"
8228 "-no-shutdown stop before shutdown\n"
8229 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8230 "-vnc display start a VNC server on display\n"
8231#ifdef CONFIG_TRACE
8232 "-trace file create an execution trace in 'file' (implies -tracing on)\n"
8233 "-tracing off start with tracing off\n"
8234 "-trace_miss include tracing of cache miss addresses\n"
8235 "-trace_addr include tracing of all load/store addresses\n"
8236 "-dcache_load_miss cycles\n"
8237 " set the dcache load miss penalty to 'cycles'\n"
8238 "-dcache_store_miss cycles\n"
8239 " set the dcache store miss penalty to 'cycles'\n"
8240#endif
8241#ifdef CONFIG_NAND
8242 "-nand name[,readonly][,size=size][,pagesize=size][,extrasize=size][,erasepages=pages][,initfile=file][,file=file]"
8243#endif
8244#ifndef _WIN32
8245 "-daemonize daemonize QEMU after initializing\n"
8246#endif
8247 "-option-rom rom load a file, rom, into the option ROM space\n"
8248#ifdef TARGET_SPARC
8249 "-prom-env variable=value set OpenBIOS nvram variables\n"
8250#endif
8251 "-clock force the use of the given methods for timer alarm.\n"
8252 " To see what timers are available use -clock ?\n"
8253 "-startdate select initial date of the clock\n"
8254 "-icount [N|auto]\n"
8255 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8256 "\n"
8257 "During emulation, the following keys are useful:\n"
8258 "ctrl-alt-f toggle full screen\n"
8259 "ctrl-alt-n switch to virtual console 'n'\n"
8260 "ctrl-alt toggle mouse and keyboard grab\n"
8261 "\n"
8262 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8263 ,
8264 "qemu",
8265 DEFAULT_RAM_SIZE,
8266#ifndef _WIN32
8267 DEFAULT_NETWORK_SCRIPT,
8268 DEFAULT_NETWORK_DOWN_SCRIPT,
8269#endif
8270 DEFAULT_GDBSTUB_PORT,
8271 "/tmp/qemu.log");
8272 exit(exitcode);
8273}
8274
8275#define HAS_ARG 0x0001
8276
8277enum {
8278 QEMU_OPTION_h,
8279
8280 QEMU_OPTION_M,
8281 QEMU_OPTION_cpu,
8282 QEMU_OPTION_fda,
8283 QEMU_OPTION_fdb,
8284 QEMU_OPTION_hda,
8285 QEMU_OPTION_hdb,
8286 QEMU_OPTION_hdc,
8287 QEMU_OPTION_hdd,
8288 QEMU_OPTION_drive,
8289 QEMU_OPTION_cdrom,
8290 QEMU_OPTION_mtdblock,
8291 QEMU_OPTION_sd,
8292 QEMU_OPTION_pflash,
8293 QEMU_OPTION_boot,
8294 QEMU_OPTION_snapshot,
8295#ifdef TARGET_I386
8296 QEMU_OPTION_no_fd_bootchk,
8297#endif
8298 QEMU_OPTION_m,
8299 QEMU_OPTION_nographic,
8300 QEMU_OPTION_portrait,
8301#ifdef HAS_AUDIO
8302 QEMU_OPTION_audio_help,
8303 QEMU_OPTION_soundhw,
8304#endif
8305
8306 QEMU_OPTION_net,
8307 QEMU_OPTION_tftp,
8308 QEMU_OPTION_bootp,
8309 QEMU_OPTION_smb,
8310 QEMU_OPTION_redir,
8311
8312 QEMU_OPTION_kernel,
8313 QEMU_OPTION_append,
8314 QEMU_OPTION_initrd,
8315
8316 QEMU_OPTION_S,
8317 QEMU_OPTION_s,
8318 QEMU_OPTION_p,
8319 QEMU_OPTION_d,
8320 QEMU_OPTION_hdachs,
8321 QEMU_OPTION_L,
8322 QEMU_OPTION_bios,
8323 QEMU_OPTION_k,
8324 QEMU_OPTION_localtime,
8325 QEMU_OPTION_cirrusvga,
8326 QEMU_OPTION_vmsvga,
8327 QEMU_OPTION_g,
8328 QEMU_OPTION_std_vga,
8329 QEMU_OPTION_echr,
8330 QEMU_OPTION_monitor,
8331 QEMU_OPTION_serial,
8332 QEMU_OPTION_parallel,
8333 QEMU_OPTION_loadvm,
8334 QEMU_OPTION_full_screen,
8335 QEMU_OPTION_no_frame,
8336 QEMU_OPTION_alt_grab,
8337 QEMU_OPTION_no_quit,
8338 QEMU_OPTION_pidfile,
8339 QEMU_OPTION_no_kqemu,
8340 QEMU_OPTION_kernel_kqemu,
8341 QEMU_OPTION_win2k_hack,
8342 QEMU_OPTION_usb,
8343 QEMU_OPTION_usbdevice,
8344 QEMU_OPTION_smp,
8345 QEMU_OPTION_vnc,
8346 QEMU_OPTION_no_acpi,
8347 QEMU_OPTION_curses,
8348 QEMU_OPTION_no_reboot,
8349 QEMU_OPTION_no_shutdown,
8350 QEMU_OPTION_show_cursor,
8351 QEMU_OPTION_daemonize,
8352 QEMU_OPTION_option_rom,
8353 QEMU_OPTION_semihosting,
8354 QEMU_OPTION_name,
8355 QEMU_OPTION_prom_env,
8356 QEMU_OPTION_old_param,
8357 QEMU_OPTION_noaudio,
8358 QEMU_OPTION_mic,
8359#ifdef CONFIG_TRACE
8360 QEMU_OPTION_trace_file,
8361 QEMU_OPTION_tracing,
8362 QEMU_OPTION_trace_miss,
8363 QEMU_OPTION_trace_addr,
8364 QEMU_OPTION_dcache_load_miss,
8365 QEMU_OPTION_dcache_store_miss,
8366#endif
8367#ifdef CONFIG_NAND
8368 QEMU_OPTION_nand,
8369#endif
8370 QEMU_OPTION_clock,
8371 QEMU_OPTION_startdate,
8372 QEMU_OPTION_tb_size,
8373 QEMU_OPTION_icount,
8374};
8375
8376typedef struct QEMUOption {
8377 const char *name;
8378 int flags;
8379 int index;
8380} QEMUOption;
8381
8382const QEMUOption qemu_options[] = {
8383 { "h", 0, QEMU_OPTION_h },
8384 { "help", 0, QEMU_OPTION_h },
8385
8386 { "M", HAS_ARG, QEMU_OPTION_M },
8387 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
8388 { "fda", HAS_ARG, QEMU_OPTION_fda },
8389 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
8390 { "hda", HAS_ARG, QEMU_OPTION_hda },
8391 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
8392 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
8393 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
8394 { "drive", HAS_ARG, QEMU_OPTION_drive },
8395 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
8396 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
8397 { "sd", HAS_ARG, QEMU_OPTION_sd },
8398 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
8399 { "boot", HAS_ARG, QEMU_OPTION_boot },
8400 { "snapshot", 0, QEMU_OPTION_snapshot },
8401#ifdef TARGET_I386
8402 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
8403#endif
8404 { "m", HAS_ARG, QEMU_OPTION_m },
8405 { "nographic", 0, QEMU_OPTION_nographic },
8406 { "portrait", 0, QEMU_OPTION_portrait },
8407 { "k", HAS_ARG, QEMU_OPTION_k },
8408#ifdef HAS_AUDIO
8409 { "audio-help", 0, QEMU_OPTION_audio_help },
8410 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
8411#endif
8412
8413 { "net", HAS_ARG, QEMU_OPTION_net},
8414#ifdef CONFIG_SLIRP
8415 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
8416 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
8417#ifndef _WIN32
8418 { "smb", HAS_ARG, QEMU_OPTION_smb },
8419#endif
8420 { "redir", HAS_ARG, QEMU_OPTION_redir },
8421#endif
8422
8423 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
8424 { "append", HAS_ARG, QEMU_OPTION_append },
8425 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
8426
8427 { "S", 0, QEMU_OPTION_S },
8428 { "s", 0, QEMU_OPTION_s },
8429 { "p", HAS_ARG, QEMU_OPTION_p },
8430 { "d", HAS_ARG, QEMU_OPTION_d },
8431 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
8432 { "L", HAS_ARG, QEMU_OPTION_L },
8433 { "bios", HAS_ARG, QEMU_OPTION_bios },
8434#ifdef USE_KQEMU
8435 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
8436 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
8437#endif
8438#if defined(TARGET_PPC) || defined(TARGET_SPARC)
8439 { "g", HAS_ARG, QEMU_OPTION_g },
8440#endif
8441 { "localtime", 0, QEMU_OPTION_localtime },
8442 { "std-vga", 0, QEMU_OPTION_std_vga },
8443 { "echr", HAS_ARG, QEMU_OPTION_echr },
8444 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
8445 { "serial", HAS_ARG, QEMU_OPTION_serial },
8446 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
8447 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
8448 { "full-screen", 0, QEMU_OPTION_full_screen },
8449#ifdef CONFIG_SDL
8450 { "no-frame", 0, QEMU_OPTION_no_frame },
8451 { "alt-grab", 0, QEMU_OPTION_alt_grab },
8452 { "no-quit", 0, QEMU_OPTION_no_quit },
8453#endif
8454 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
8455 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
8456 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
8457 { "smp", HAS_ARG, QEMU_OPTION_smp },
8458 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
8459#ifdef CONFIG_CURSES
8460 { "curses", 0, QEMU_OPTION_curses },
8461#endif
8462
8463 /* temporary options */
8464 { "usb", 0, QEMU_OPTION_usb },
8465 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8466 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8467 { "no-acpi", 0, QEMU_OPTION_no_acpi },
8468 { "no-reboot", 0, QEMU_OPTION_no_reboot },
8469 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8470 { "show-cursor", 0, QEMU_OPTION_show_cursor },
8471 { "daemonize", 0, QEMU_OPTION_daemonize },
8472 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8473#if defined(TARGET_ARM) || defined(TARGET_M68K)
8474 { "semihosting", 0, QEMU_OPTION_semihosting },
8475#endif
8476 { "name", HAS_ARG, QEMU_OPTION_name },
8477#if defined(TARGET_SPARC)
8478 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8479#endif
8480#if defined(TARGET_ARM)
8481 { "old-param", 0, QEMU_OPTION_old_param },
8482#endif
8483
8484 /* android stuff */
8485 { "noaudio", 0, QEMU_OPTION_noaudio },
8486 { "mic", HAS_ARG, QEMU_OPTION_mic },
8487#ifdef CONFIG_TRACE
8488 { "trace", HAS_ARG, QEMU_OPTION_trace_file },
8489 { "tracing", HAS_ARG, QEMU_OPTION_tracing },
8490 { "trace_miss", 0, QEMU_OPTION_trace_miss },
8491 { "trace_addr", 0, QEMU_OPTION_trace_addr },
8492 { "dcache_load_miss", HAS_ARG, QEMU_OPTION_dcache_load_miss },
8493 { "dcache_store_miss", HAS_ARG, QEMU_OPTION_dcache_store_miss },
8494#endif
8495#ifdef CONFIG_NAND
8496 { "nand", HAS_ARG, QEMU_OPTION_nand },
8497#endif
8498 { "clock", HAS_ARG, QEMU_OPTION_clock },
8499 { NULL, 0, 0 },
8500};
8501
8502/* password input */
8503
8504int qemu_key_check(BlockDriverState *bs, const char *name)
8505{
8506 char password[256];
8507 int i;
8508
8509 if (!bdrv_is_encrypted(bs))
8510 return 0;
8511
8512 term_printf("%s is encrypted.\n", name);
8513 for(i = 0; i < 3; i++) {
8514 monitor_readline("Password: ", 1, password, sizeof(password));
8515 if (bdrv_set_key(bs, password) == 0)
8516 return 0;
8517 term_printf("invalid password\n");
8518 }
8519 return -EPERM;
8520}
8521
8522static BlockDriverState *get_bdrv(int index)
8523{
8524 if (index > nb_drives)
8525 return NULL;
8526 return drives_table[index].bdrv;
8527}
8528
8529static void read_passwords(void)
8530{
8531 BlockDriverState *bs;
8532 int i;
8533
8534 for(i = 0; i < 6; i++) {
8535 bs = get_bdrv(i);
8536 if (bs)
8537 qemu_key_check(bs, bdrv_get_device_name(bs));
8538 }
8539}
8540
8541#ifdef HAS_AUDIO
8542struct soundhw soundhw[] = {
8543#if 0 /* ANDROID */
8544#ifdef TARGET_I386
8545 {
8546 "pcspk",
8547 "PC speaker",
8548 0,
8549 1,
8550 { .init_isa = pcspk_audio_init }
8551 },
8552#endif
8553 {
8554 "sb16",
8555 "Creative Sound Blaster 16",
8556 0,
8557 1,
8558 { .init_isa = SB16_init }
8559 },
8560
8561#ifdef CONFIG_CS4231A
8562 {
8563 "cs4231a",
8564 "CS4231A",
8565 0,
8566 1,
8567 { .init_isa = cs4231a_init }
8568 },
8569#endif
8570
8571#ifdef CONFIG_ADLIB
8572 {
8573 "adlib",
8574#ifdef HAS_YMF262
8575 "Yamaha YMF262 (OPL3)",
8576#else
8577 "Yamaha YM3812 (OPL2)",
8578#endif
8579 0,
8580 1,
8581 { .init_isa = Adlib_init }
8582 },
8583#endif
8584
8585#ifdef CONFIG_GUS
8586 {
8587 "gus",
8588 "Gravis Ultrasound GF1",
8589 0,
8590 1,
8591 { .init_isa = GUS_init }
8592 },
8593#endif
8594
8595#ifdef CONFIG_AC97
8596 {
8597 "ac97",
8598 "Intel 82801AA AC97 Audio",
8599 0,
8600 0,
8601 { .init_pci = ac97_init }
8602 },
8603#endif
8604
8605 {
8606 "es1370",
8607 "ENSONIQ AudioPCI ES1370",
8608 0,
8609 0,
8610 { .init_pci = es1370_init }
8611 },
8612#endif /* ANDROID */
8613
8614 { NULL, NULL, 0, 0, { NULL } }
8615};
8616
8617static void select_soundhw (const char *optarg)
8618{
8619 struct soundhw *c;
8620
8621 if (*optarg == '?') {
8622 show_valid_cards:
8623
8624 printf ("Valid sound card names (comma separated):\n");
8625 for (c = soundhw; c->name; ++c) {
8626 printf ("%-11s %s\n", c->name, c->descr);
8627 }
8628 printf ("\n-soundhw all will enable all of the above\n");
8629 exit (*optarg != '?');
8630 }
8631 else {
8632 size_t l;
8633 const char *p;
8634 char *e;
8635 int bad_card = 0;
8636
8637 if (!strcmp (optarg, "all")) {
8638 for (c = soundhw; c->name; ++c) {
8639 c->enabled = 1;
8640 }
8641 return;
8642 }
8643
8644 p = optarg;
8645 while (*p) {
8646 e = strchr (p, ',');
8647 l = !e ? strlen (p) : (size_t) (e - p);
8648
8649 for (c = soundhw; c->name; ++c) {
8650 if (!strncmp (c->name, p, l)) {
8651 c->enabled = 1;
8652 break;
8653 }
8654 }
8655
8656 if (!c->name) {
8657 if (l > 80) {
8658 fprintf (stderr,
8659 "Unknown sound card name (too big to show)\n");
8660 }
8661 else {
8662 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8663 (int) l, p);
8664 }
8665 bad_card = 1;
8666 }
8667 p += l + (e != NULL);
8668 }
8669
8670 if (bad_card)
8671 goto show_valid_cards;
8672 }
8673}
8674#endif
8675
8676#ifdef _WIN32
8677static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8678{
8679 exit(STATUS_CONTROL_C_EXIT);
8680 return TRUE;
8681}
8682#endif
8683
8684#define MAX_NET_CLIENTS 32
8685
8686#ifndef _WIN32
8687
8688static void termsig_handler(int signal)
8689{
8690 qemu_system_shutdown_request();
8691}
8692
8693static void termsig_setup(void)
8694{
8695 struct sigaction act;
8696
8697 memset(&act, 0, sizeof(act));
8698 act.sa_handler = termsig_handler;
8699 sigaction(SIGINT, &act, NULL);
8700 sigaction(SIGHUP, &act, NULL);
8701 sigaction(SIGTERM, &act, NULL);
8702}
8703
8704#endif
8705
8706int main(int argc, char **argv)
8707{
8708#ifdef CONFIG_GDBSTUB
8709 int use_gdbstub;
8710 const char *gdbstub_port;
8711#endif
8712 uint32_t boot_devices_bitmap = 0;
8713 int i;
8714 int snapshot, linux_boot, net_boot;
8715 const char *initrd_filename;
8716 const char *kernel_filename, *kernel_cmdline;
8717 const char *boot_devices = "";
8718 DisplayState *ds = &display_state;
8719 int cyls, heads, secs, translation;
8720 const char *net_clients[MAX_NET_CLIENTS];
8721 int nb_net_clients;
8722 int hda_index;
8723 int optind;
8724 const char *r, *optarg;
8725 CharDriverState *monitor_hd;
8726 const char *monitor_device;
8727 const char *serial_devices[MAX_SERIAL_PORTS];
8728 int serial_device_index;
8729 const char *parallel_devices[MAX_PARALLEL_PORTS];
8730 int parallel_device_index;
8731 const char *loadvm = NULL;
8732 QEMUMachine *machine;
8733 const char *cpu_model;
8734 const char *usb_devices[MAX_USB_CMDLINE];
8735 int usb_devices_index;
8736 int fds[2];
8737 int tb_size;
8738 const char *pid_file = NULL;
8739 VLANState *vlan;
8740
8741 LIST_INIT (&vm_change_state_head);
8742#ifndef _WIN32
8743 {
8744 struct sigaction act;
8745 sigfillset(&act.sa_mask);
8746 act.sa_flags = 0;
8747 act.sa_handler = SIG_IGN;
8748 sigaction(SIGPIPE, &act, NULL);
8749 }
8750#else
8751 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8752 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8753 QEMU to run on a single CPU */
8754 {
8755 HANDLE h;
8756 DWORD mask, smask;
8757 int i;
8758 h = GetCurrentProcess();
8759 if (GetProcessAffinityMask(h, &mask, &smask)) {
8760 for(i = 0; i < 32; i++) {
8761 if (mask & (1 << i))
8762 break;
8763 }
8764 if (i != 32) {
8765 mask = 1 << i;
8766 SetProcessAffinityMask(h, mask);
8767 }
8768 }
8769 }
8770#endif
8771
8772 register_machines();
8773 machine = first_machine;
8774 cpu_model = NULL;
8775 initrd_filename = NULL;
8776 ram_size = 0;
8777 vga_ram_size = VGA_RAM_SIZE;
8778#ifdef CONFIG_GDBSTUB
8779 use_gdbstub = 0;
8780 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8781#endif
8782 snapshot = 0;
8783 nographic = 0;
8784 curses = 0;
8785 kernel_filename = NULL;
8786 kernel_cmdline = "";
8787 cyls = heads = secs = 0;
8788 translation = BIOS_ATA_TRANSLATION_AUTO;
8789 monitor_device = "vc";
8790
8791 serial_devices[0] = "vc:80Cx24C";
8792 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8793 serial_devices[i] = NULL;
8794 serial_device_index = 0;
8795
8796 parallel_devices[0] = "vc:640x480";
8797 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8798 parallel_devices[i] = NULL;
8799 parallel_device_index = 0;
8800
8801 usb_devices_index = 0;
8802
8803 nb_net_clients = 0;
8804 nb_drives = 0;
8805 nb_drives_opt = 0;
8806 hda_index = -1;
8807
8808 nb_nics = 0;
8809
8810 tb_size = 0;
8811 android_audio_enabled = 1;
8812
8813 optind = 1;
8814 for(;;) {
8815 if (optind >= argc)
8816 break;
8817 r = argv[optind];
8818 if (r[0] != '-') {
8819 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8820 } else {
8821 const QEMUOption *popt;
8822
8823 optind++;
8824 /* Treat --foo the same as -foo. */
8825 if (r[1] == '-')
8826 r++;
8827 popt = qemu_options;
8828 for(;;) {
8829 if (!popt->name) {
8830 fprintf(stderr, "%s: invalid option -- '%s'\n",
8831 argv[0], r);
8832 exit(1);
8833 }
8834 if (!strcmp(popt->name, r + 1))
8835 break;
8836 popt++;
8837 }
8838 if (popt->flags & HAS_ARG) {
8839 if (optind >= argc) {
8840 fprintf(stderr, "%s: option '%s' requires an argument\n",
8841 argv[0], r);
8842 exit(1);
8843 }
8844 optarg = argv[optind++];
8845 } else {
8846 optarg = NULL;
8847 }
8848
8849 switch(popt->index) {
8850 case QEMU_OPTION_M:
8851 machine = find_machine(optarg);
8852 if (!machine) {
8853 QEMUMachine *m;
8854 printf("Supported machines are:\n");
8855 for(m = first_machine; m != NULL; m = m->next) {
8856 printf("%-10s %s%s\n",
8857 m->name, m->desc,
8858 m == first_machine ? " (default)" : "");
8859 }
8860 exit(*optarg != '?');
8861 }
8862 break;
8863 case QEMU_OPTION_cpu:
8864 /* hw initialization will check this */
8865 if (*optarg == '?') {
8866/* XXX: implement xxx_cpu_list for targets that still miss it */
8867#if defined(cpu_list)
8868 cpu_list(stdout, &fprintf);
8869#endif
8870 exit(0);
8871 } else {
8872 cpu_model = optarg;
8873 }
8874 break;
8875 case QEMU_OPTION_initrd:
8876 initrd_filename = optarg;
8877 break;
8878 case QEMU_OPTION_hda:
8879 if (cyls == 0)
8880 hda_index = drive_add(optarg, HD_ALIAS, 0);
8881 else
8882 hda_index = drive_add(optarg, HD_ALIAS
8883 ",cyls=%d,heads=%d,secs=%d%s",
8884 0, cyls, heads, secs,
8885 translation == BIOS_ATA_TRANSLATION_LBA ?
8886 ",trans=lba" :
8887 translation == BIOS_ATA_TRANSLATION_NONE ?
8888 ",trans=none" : "");
8889 break;
8890 case QEMU_OPTION_hdb:
8891 case QEMU_OPTION_hdc:
8892 case QEMU_OPTION_hdd:
8893 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8894 break;
8895 case QEMU_OPTION_drive:
8896 drive_add(NULL, "%s", optarg);
8897 break;
8898 case QEMU_OPTION_mtdblock:
8899 drive_add(optarg, MTD_ALIAS);
8900 break;
8901 case QEMU_OPTION_sd:
8902 drive_add(optarg, SD_ALIAS);
8903 break;
8904 case QEMU_OPTION_pflash:
8905 drive_add(optarg, PFLASH_ALIAS);
8906 break;
8907 case QEMU_OPTION_snapshot:
8908 snapshot = 1;
8909 break;
8910 case QEMU_OPTION_hdachs:
8911 {
8912 const char *p;
8913 p = optarg;
8914 cyls = strtol(p, (char **)&p, 0);
8915 if (cyls < 1 || cyls > 16383)
8916 goto chs_fail;
8917 if (*p != ',')
8918 goto chs_fail;
8919 p++;
8920 heads = strtol(p, (char **)&p, 0);
8921 if (heads < 1 || heads > 16)
8922 goto chs_fail;
8923 if (*p != ',')
8924 goto chs_fail;
8925 p++;
8926 secs = strtol(p, (char **)&p, 0);
8927 if (secs < 1 || secs > 63)
8928 goto chs_fail;
8929 if (*p == ',') {
8930 p++;
8931 if (!strcmp(p, "none"))
8932 translation = BIOS_ATA_TRANSLATION_NONE;
8933 else if (!strcmp(p, "lba"))
8934 translation = BIOS_ATA_TRANSLATION_LBA;
8935 else if (!strcmp(p, "auto"))
8936 translation = BIOS_ATA_TRANSLATION_AUTO;
8937 else
8938 goto chs_fail;
8939 } else if (*p != '\0') {
8940 chs_fail:
8941 fprintf(stderr, "qemu: invalid physical CHS format\n");
8942 exit(1);
8943 }
8944 if (hda_index != -1)
8945 snprintf(drives_opt[hda_index].opt,
8946 sizeof(drives_opt[hda_index].opt),
8947 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8948 0, cyls, heads, secs,
8949 translation == BIOS_ATA_TRANSLATION_LBA ?
8950 ",trans=lba" :
8951 translation == BIOS_ATA_TRANSLATION_NONE ?
8952 ",trans=none" : "");
8953 }
8954 break;
8955 case QEMU_OPTION_nographic:
8956 nographic = 1;
8957 break;
8958#ifdef CONFIG_CURSES
8959 case QEMU_OPTION_curses:
8960 curses = 1;
8961 break;
8962#endif
8963 case QEMU_OPTION_portrait:
8964 graphic_rotate = 1;
8965 break;
8966 case QEMU_OPTION_kernel:
8967 kernel_filename = optarg;
8968 break;
8969 case QEMU_OPTION_append:
8970 kernel_cmdline = optarg;
8971 break;
8972 case QEMU_OPTION_cdrom:
8973 drive_add(optarg, CDROM_ALIAS);
8974 break;
8975 case QEMU_OPTION_boot:
8976 boot_devices = optarg;
8977 /* We just do some generic consistency checks */
8978 {
8979 /* Could easily be extended to 64 devices if needed */
8980 const char *p;
8981
8982 boot_devices_bitmap = 0;
8983 for (p = boot_devices; *p != '\0'; p++) {
8984 /* Allowed boot devices are:
8985 * a b : floppy disk drives
8986 * c ... f : IDE disk drives
8987 * g ... m : machine implementation dependant drives
8988 * n ... p : network devices
8989 * It's up to each machine implementation to check
8990 * if the given boot devices match the actual hardware
8991 * implementation and firmware features.
8992 */
8993 if (*p < 'a' || *p > 'q') {
8994 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8995 exit(1);
8996 }
8997 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8998 fprintf(stderr,
8999 "Boot device '%c' was given twice\n",*p);
9000 exit(1);
9001 }
9002 boot_devices_bitmap |= 1 << (*p - 'a');
9003 }
9004 }
9005 break;
9006 case QEMU_OPTION_fda:
9007 case QEMU_OPTION_fdb:
9008 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
9009 break;
9010#ifdef TARGET_I386
9011 case QEMU_OPTION_no_fd_bootchk:
9012 fd_bootchk = 0;
9013 break;
9014#endif
9015 case QEMU_OPTION_net:
9016 if (nb_net_clients >= MAX_NET_CLIENTS) {
9017 fprintf(stderr, "qemu: too many network clients\n");
9018 exit(1);
9019 }
9020 net_clients[nb_net_clients] = optarg;
9021 nb_net_clients++;
9022 break;
9023#ifdef CONFIG_SLIRP
9024 case QEMU_OPTION_tftp:
9025 tftp_prefix = optarg;
9026 break;
9027 case QEMU_OPTION_bootp:
9028 bootp_filename = optarg;
9029 break;
9030#if 0 /* ANDROID disabled */
9031 case QEMU_OPTION_smb:
9032 net_slirp_smb(optarg);
9033 break;
9034#endif
9035 case QEMU_OPTION_redir:
9036 net_slirp_redir(optarg);
9037 break;
9038#endif
9039#ifdef HAS_AUDIO
9040 case QEMU_OPTION_audio_help:
9041 AUD_help ();
9042 exit (0);
9043 break;
9044 case QEMU_OPTION_soundhw:
9045 select_soundhw (optarg);
9046 break;
9047#endif
9048 case QEMU_OPTION_h:
9049 qemu_help(0);
9050 break;
9051 case QEMU_OPTION_m: {
9052 uint64_t value;
9053 char *ptr;
9054
9055 value = strtoul(optarg, &ptr, 10);
9056 switch (*ptr) {
9057 case 0: case 'M': case 'm':
9058 value <<= 20;
9059 break;
9060 case 'G': case 'g':
9061 value <<= 30;
9062 break;
9063 default:
9064 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
9065 exit(1);
9066 }
9067
9068 /* On 32-bit hosts, QEMU is limited by virtual address space */
9069 if (value > (2047 << 20)
9070#ifndef USE_KQEMU
9071 && HOST_LONG_BITS == 32
9072#endif
9073 ) {
9074 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
9075 exit(1);
9076 }
9077 if (value != (uint64_t)(ram_addr_t)value) {
9078 fprintf(stderr, "qemu: ram size too large\n");
9079 exit(1);
9080 }
9081 ram_size = value;
9082 break;
9083 }
9084 case QEMU_OPTION_d:
9085 {
9086 int mask;
9087 CPULogItem *item;
9088
9089 mask = cpu_str_to_log_mask(optarg);
9090 if (!mask) {
9091 printf("Log items (comma separated):\n");
9092 for(item = cpu_log_items; item->mask != 0; item++) {
9093 printf("%-10s %s\n", item->name, item->help);
9094 }
9095 exit(1);
9096 }
9097 cpu_set_log(mask);
9098 }
9099 break;
9100#ifdef CONFIG_GDBSTUB
9101 case QEMU_OPTION_s:
9102 use_gdbstub = 1;
9103 break;
9104 case QEMU_OPTION_p:
9105 gdbstub_port = optarg;
9106 break;
9107#endif
9108 case QEMU_OPTION_L:
9109 bios_dir = optarg;
9110 break;
9111 case QEMU_OPTION_S:
9112#if 1 /* ANDROID */
9113 fprintf(stderr, "Sorry, stopped launch is not supported in the Android emulator\n" );
9114 exit(1);
9115#else
9116 autostart = 0;
9117 break;
9118#endif
9119 case QEMU_OPTION_k:
9120 keyboard_layout = optarg;
9121 break;
9122 case QEMU_OPTION_localtime:
9123 rtc_utc = 0;
9124 break;
9125 case QEMU_OPTION_cirrusvga:
9126 cirrus_vga_enabled = 1;
9127 vmsvga_enabled = 0;
9128 break;
9129 case QEMU_OPTION_vmsvga:
9130 cirrus_vga_enabled = 0;
9131 vmsvga_enabled = 1;
9132 break;
9133 case QEMU_OPTION_std_vga:
9134 cirrus_vga_enabled = 0;
9135 vmsvga_enabled = 0;
9136 break;
9137 case QEMU_OPTION_g:
9138 {
9139 const char *p;
9140 int w, h, depth;
9141 p = optarg;
9142 w = strtol(p, (char **)&p, 10);
9143 if (w <= 0) {
9144 graphic_error:
9145 fprintf(stderr, "qemu: invalid resolution or depth\n");
9146 exit(1);
9147 }
9148 if (*p != 'x')
9149 goto graphic_error;
9150 p++;
9151 h = strtol(p, (char **)&p, 10);
9152 if (h <= 0)
9153 goto graphic_error;
9154 if (*p == 'x') {
9155 p++;
9156 depth = strtol(p, (char **)&p, 10);
9157 if (depth != 8 && depth != 15 && depth != 16 &&
9158 depth != 24 && depth != 32)
9159 goto graphic_error;
9160 } else if (*p == '\0') {
9161 depth = graphic_depth;
9162 } else {
9163 goto graphic_error;
9164 }
9165
9166 graphic_width = w;
9167 graphic_height = h;
9168 graphic_depth = depth;
9169 }
9170 break;
9171 case QEMU_OPTION_echr:
9172 {
9173 char *r;
9174 term_escape_char = strtol(optarg, &r, 0);
9175 if (r == optarg)
9176 printf("Bad argument to echr\n");
9177 break;
9178 }
9179 case QEMU_OPTION_monitor:
9180 monitor_device = optarg;
9181 break;
9182 case QEMU_OPTION_serial:
9183 if (serial_device_index >= MAX_SERIAL_PORTS) {
9184 fprintf(stderr, "qemu: too many serial ports\n");
9185 exit(1);
9186 }
9187 serial_devices[serial_device_index] = optarg;
9188 serial_device_index++;
9189 break;
9190 case QEMU_OPTION_parallel:
9191 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
9192 fprintf(stderr, "qemu: too many parallel ports\n");
9193 exit(1);
9194 }
9195 parallel_devices[parallel_device_index] = optarg;
9196 parallel_device_index++;
9197 break;
9198 case QEMU_OPTION_loadvm:
9199 loadvm = optarg;
9200 break;
9201 case QEMU_OPTION_full_screen:
9202 full_screen = 1;
9203 break;
9204#ifdef CONFIG_SDL
9205 case QEMU_OPTION_no_frame:
9206 no_frame = 1;
9207 break;
9208 case QEMU_OPTION_alt_grab:
9209 alt_grab = 1;
9210 break;
9211 case QEMU_OPTION_no_quit:
9212 no_quit = 1;
9213 break;
9214#endif
9215 case QEMU_OPTION_pidfile:
9216 pid_file = optarg;
9217 break;
9218#ifdef TARGET_I386
9219 case QEMU_OPTION_win2k_hack:
9220 win2k_install_hack = 1;
9221 break;
9222#endif
9223#ifdef USE_KQEMU
9224 case QEMU_OPTION_no_kqemu:
9225 kqemu_allowed = 0;
9226 break;
9227 case QEMU_OPTION_kernel_kqemu:
9228 kqemu_allowed = 2;
9229 break;
9230#endif
9231 case QEMU_OPTION_usb:
9232 usb_enabled = 1;
9233 break;
9234 case QEMU_OPTION_usbdevice:
9235 usb_enabled = 1;
9236 if (usb_devices_index >= MAX_USB_CMDLINE) {
9237 fprintf(stderr, "Too many USB devices\n");
9238 exit(1);
9239 }
9240 usb_devices[usb_devices_index] = optarg;
9241 usb_devices_index++;
9242 break;
9243 case QEMU_OPTION_smp:
9244 smp_cpus = atoi(optarg);
9245 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
9246 fprintf(stderr, "Invalid number of CPUs\n");
9247 exit(1);
9248 }
9249 break;
9250 case QEMU_OPTION_vnc:
9251 vnc_display = optarg;
9252 break;
9253 case QEMU_OPTION_no_acpi:
9254 acpi_enabled = 0;
9255 break;
9256 case QEMU_OPTION_no_reboot:
9257 no_reboot = 1;
9258 break;
9259 case QEMU_OPTION_no_shutdown:
9260 no_shutdown = 1;
9261 break;
9262 case QEMU_OPTION_show_cursor:
9263 cursor_hide = 0;
9264 break;
9265 case QEMU_OPTION_daemonize:
9266 daemonize = 1;
9267 break;
9268 case QEMU_OPTION_option_rom:
9269 if (nb_option_roms >= MAX_OPTION_ROMS) {
9270 fprintf(stderr, "Too many option ROMs\n");
9271 exit(1);
9272 }
9273 option_rom[nb_option_roms] = optarg;
9274 nb_option_roms++;
9275 break;
9276 case QEMU_OPTION_semihosting:
9277 semihosting_enabled = 1;
9278 break;
9279 case QEMU_OPTION_name:
9280 qemu_name = optarg;
9281 break;
9282#ifdef TARGET_SPARC
9283 case QEMU_OPTION_prom_env:
9284 if (nb_prom_envs >= MAX_PROM_ENVS) {
9285 fprintf(stderr, "Too many prom variables\n");
9286 exit(1);
9287 }
9288 prom_envs[nb_prom_envs] = optarg;
9289 nb_prom_envs++;
9290 break;
9291#endif
9292#ifdef TARGET_ARM
9293 case QEMU_OPTION_old_param:
9294 old_param = 1;
9295 break;
9296#endif
9297 case QEMU_OPTION_clock:
9298 configure_alarms(optarg);
9299 break;
9300 case QEMU_OPTION_startdate:
9301 {
9302 struct tm tm;
9303 time_t rtc_start_date;
9304 if (!strcmp(optarg, "now")) {
9305 rtc_date_offset = -1;
9306 } else {
9307 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
9308 &tm.tm_year,
9309 &tm.tm_mon,
9310 &tm.tm_mday,
9311 &tm.tm_hour,
9312 &tm.tm_min,
9313 &tm.tm_sec) == 6) {
9314 /* OK */
9315 } else if (sscanf(optarg, "%d-%d-%d",
9316 &tm.tm_year,
9317 &tm.tm_mon,
9318 &tm.tm_mday) == 3) {
9319 tm.tm_hour = 0;
9320 tm.tm_min = 0;
9321 tm.tm_sec = 0;
9322 } else {
9323 goto date_fail;
9324 }
9325 tm.tm_year -= 1900;
9326 tm.tm_mon--;
9327 rtc_start_date = mktimegm(&tm);
9328 if (rtc_start_date == -1) {
9329 date_fail:
9330 fprintf(stderr, "Invalid date format. Valid format are:\n"
9331 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9332 exit(1);
9333 }
9334 rtc_date_offset = time(NULL) - rtc_start_date;
9335 }
9336 }
9337 break;
9338 case QEMU_OPTION_tb_size:
9339 tb_size = strtol(optarg, NULL, 0);
9340 if (tb_size < 0)
9341 tb_size = 0;
9342 break;
9343 case QEMU_OPTION_icount:
9344 use_icount = 1;
9345 if (strcmp(optarg, "auto") == 0) {
9346 icount_time_shift = -1;
9347 } else {
9348 icount_time_shift = strtol(optarg, NULL, 0);
9349 }
9350 break;
9351
9352 case QEMU_OPTION_noaudio:
9353 android_audio_enabled = 0;
9354 break;
9355 case QEMU_OPTION_mic:
9356 audio_input_source = (char*)optarg;
9357 break;
9358#ifdef CONFIG_TRACE
9359 case QEMU_OPTION_trace_file:
9360 trace_filename = optarg;
9361 tracing = 1;
9362 break;
9363 case QEMU_OPTION_trace_miss:
9364 trace_cache_miss = 1;
9365 break;
9366 case QEMU_OPTION_trace_addr:
9367 trace_all_addr = 1;
9368 break;
9369 case QEMU_OPTION_tracing:
9370 if (strcmp(optarg, "off") == 0)
9371 tracing = 0;
9372 else if (strcmp(optarg, "on") == 0 && trace_filename)
9373 tracing = 1;
9374 else {
9375 fprintf(stderr, "Unexpected option to -tracing ('%s')\n",
9376 optarg);
9377 exit(1);
9378 }
9379 break;
9380 case QEMU_OPTION_dcache_load_miss:
9381 dcache_load_miss_penalty = atoi(optarg);
9382 break;
9383 case QEMU_OPTION_dcache_store_miss:
9384 dcache_store_miss_penalty = atoi(optarg);
9385 break;
9386#endif
9387#ifdef CONFIG_NAND
9388 case QEMU_OPTION_nand:
9389 nand_add_dev(optarg);
9390 break;
9391#endif
9392 }
9393 }
9394 }
9395
9396 if (nographic) {
9397 if (serial_device_index == 0)
9398 serial_devices[0] = "stdio";
9399 if (parallel_device_index == 0)
9400 parallel_devices[0] = "null";
9401 if (strncmp(monitor_device, "vc", 2) == 0)
9402 monitor_device = "stdio";
9403 }
9404
9405#ifndef _WIN32
9406 if (daemonize) {
9407 pid_t pid;
9408
9409 if (pipe(fds) == -1)
9410 exit(1);
9411
9412 pid = fork();
9413 if (pid > 0) {
9414 uint8_t status;
9415 ssize_t len;
9416
9417 close(fds[1]);
9418
9419 again:
9420 len = read(fds[0], &status, 1);
9421 if (len == -1 && (errno == EINTR))
9422 goto again;
9423
9424 if (len != 1)
9425 exit(1);
9426 else if (status == 1) {
9427 fprintf(stderr, "Could not acquire pidfile\n");
9428 exit(1);
9429 } else
9430 exit(0);
9431 } else if (pid < 0)
9432 exit(1);
9433
9434 setsid();
9435
9436 pid = fork();
9437 if (pid > 0)
9438 exit(0);
9439 else if (pid < 0)
9440 exit(1);
9441
9442 umask(027);
9443
9444 signal(SIGTSTP, SIG_IGN);
9445 signal(SIGTTOU, SIG_IGN);
9446 signal(SIGTTIN, SIG_IGN);
9447 }
9448#endif
9449
9450 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
9451 if (daemonize) {
9452 uint8_t status = 1;
9453 write(fds[1], &status, 1);
9454 } else
9455 fprintf(stderr, "Could not acquire pid file\n");
9456 exit(1);
9457 }
9458
9459#ifdef USE_KQEMU
9460 if (smp_cpus > 1)
9461 kqemu_allowed = 0;
9462#endif
9463 linux_boot = (kernel_filename != NULL);
9464 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
9465
9466 if (!linux_boot && net_boot == 0 &&
9467 !machine->nodisk_ok && nb_drives_opt == 0)
9468 qemu_help(1);
9469
9470 if (!linux_boot && *kernel_cmdline != '\0') {
9471 fprintf(stderr, "-append only allowed with -kernel option\n");
9472 exit(1);
9473 }
9474
9475 if (!linux_boot && initrd_filename != NULL) {
9476 fprintf(stderr, "-initrd only allowed with -kernel option\n");
9477 exit(1);
9478 }
9479
9480 /* boot to floppy or the default cd if no hard disk defined yet */
9481 if (!boot_devices[0]) {
9482 boot_devices = "cad";
9483 }
9484 setvbuf(stdout, NULL, _IOLBF, 0);
9485
9486 init_timers();
9487 init_timer_alarm();
9488 qemu_aio_init();
9489 if (use_icount && icount_time_shift < 0) {
9490 use_icount = 2;
9491 /* 125MIPS seems a reasonable initial guess at the guest speed.
9492 It will be corrected fairly quickly anyway. */
9493 icount_time_shift = 3;
9494 init_icount_adjust();
9495 }
9496
9497#ifdef _WIN32
9498 socket_init();
9499#endif
9500
9501 /* init network clients */
9502 if (nb_net_clients == 0) {
9503 /* if no clients, we use a default config */
9504 net_clients[nb_net_clients++] = "nic";
9505#ifdef CONFIG_SLIRP
9506 net_clients[nb_net_clients++] = "user";
9507#endif
9508 }
9509
9510 for(i = 0;i < nb_net_clients; i++) {
9511 if (net_client_parse(net_clients[i]) < 0)
9512 exit(1);
9513 }
9514 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9515 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
9516 continue;
9517 if (vlan->nb_guest_devs == 0)
9518 fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9519 if (vlan->nb_host_devs == 0)
9520 fprintf(stderr,
9521 "Warning: vlan %d is not connected to host network\n",
9522 vlan->id);
9523 }
9524
9525#ifdef TARGET_I386
9526 /* XXX: this should be moved in the PC machine instantiation code */
9527 if (net_boot != 0) {
9528 int netroms = 0;
9529 for (i = 0; i < nb_nics && i < 4; i++) {
9530 const char *model = nd_table[i].model;
9531 char buf[1024];
9532 if (net_boot & (1 << i)) {
9533 if (model == NULL)
9534 model = "ne2k_pci";
9535 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9536 if (get_image_size(buf) > 0) {
9537 if (nb_option_roms >= MAX_OPTION_ROMS) {
9538 fprintf(stderr, "Too many option ROMs\n");
9539 exit(1);
9540 }
9541 option_rom[nb_option_roms] = strdup(buf);
9542 nb_option_roms++;
9543 netroms++;
9544 }
9545 }
9546 }
9547 if (netroms == 0) {
9548 fprintf(stderr, "No valid PXE rom found for network device\n");
9549 exit(1);
9550 }
9551 }
9552#endif
9553
9554 /* init the memory */
9555 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9556
9557 if (machine->ram_require & RAMSIZE_FIXED) {
9558 if (ram_size > 0) {
9559 if (ram_size < phys_ram_size) {
9560 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9561 machine->name, (unsigned long long) phys_ram_size);
9562 exit(-1);
9563 }
9564
9565 phys_ram_size = ram_size;
9566 } else
9567 ram_size = phys_ram_size;
9568 } else {
9569 if (ram_size == 0)
9570 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9571
9572 phys_ram_size += ram_size;
9573 }
9574
9575 phys_ram_base = qemu_vmalloc(phys_ram_size);
9576 if (!phys_ram_base) {
9577 fprintf(stderr, "Could not allocate physical memory\n");
9578 exit(1);
9579 }
9580
9581 /* init the dynamic translator */
9582 cpu_exec_init_all(tb_size * 1024 * 1024);
9583
9584 bdrv_init();
9585
9586 /* we always create the cdrom drive, even if no disk is there */
9587
9588 if (nb_drives_opt < MAX_DRIVES)
9589 drive_add(NULL, CDROM_ALIAS);
9590
9591 /* we always create at least one floppy */
9592
9593 if (nb_drives_opt < MAX_DRIVES)
9594 drive_add(NULL, FD_ALIAS, 0);
9595
9596 /* we always create one sd slot, even if no card is in it */
9597
9598 if (nb_drives_opt < MAX_DRIVES)
9599 drive_add(NULL, SD_ALIAS);
9600
9601 /* open the virtual block devices */
9602
9603 for(i = 0; i < nb_drives_opt; i++)
9604 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9605 exit(1);
9606
9607 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9608 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9609
9610 /* terminal init */
9611 memset(&display_state, 0, sizeof(display_state));
9612 if (nographic) {
9613 if (curses) {
9614 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9615 exit(1);
9616 }
9617 /* nearly nothing to do */
9618 dumb_display_init(ds);
9619 } else if (vnc_display != NULL) {
9620 vnc_display_init(ds);
9621 if (vnc_display_open(ds, vnc_display) < 0)
9622 exit(1);
9623 } else
9624#if defined(CONFIG_CURSES)
9625 if (curses) {
9626 curses_display_init(ds, full_screen);
9627 } else
9628#endif
9629 {
9630#if defined(CONFIG_SDL)
9631 sdl_display_init(ds, full_screen, no_frame);
9632#elif defined(CONFIG_COCOA)
9633 cocoa_display_init(ds, full_screen);
9634#else
9635 dumb_display_init(ds);
9636#endif
9637 }
9638
9639#ifndef _WIN32
9640 /* must be after terminal init, SDL library changes signal handlers */
9641 termsig_setup();
9642#endif
9643
9644 /* Maintain compatibility with multiple stdio monitors */
9645 if (!strcmp(monitor_device,"stdio")) {
9646 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9647 const char *devname = serial_devices[i];
9648 if (devname && !strcmp(devname,"mon:stdio")) {
9649 monitor_device = NULL;
9650 break;
9651 } else if (devname && !strcmp(devname,"stdio")) {
9652 monitor_device = NULL;
9653 serial_devices[i] = "mon:stdio";
9654 break;
9655 }
9656 }
9657 }
9658 if (monitor_device) {
9659 monitor_hd = qemu_chr_open(monitor_device);
9660 if (!monitor_hd) {
9661 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9662 exit(1);
9663 }
9664 monitor_init(monitor_hd, !nographic);
9665 }
9666
9667 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9668 const char *devname = serial_devices[i];
9669 if (devname && strcmp(devname, "none")) {
9670 serial_hds[i] = qemu_chr_open(devname);
9671 if (!serial_hds[i]) {
9672 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9673 devname);
9674 exit(1);
9675 }
9676 if (strstart(devname, "vc", 0))
9677 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9678 }
9679 }
9680
9681 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9682 const char *devname = parallel_devices[i];
9683 if (devname && strcmp(devname, "none")) {
9684 parallel_hds[i] = qemu_chr_open(devname);
9685 if (!parallel_hds[i]) {
9686 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9687 devname);
9688 exit(1);
9689 }
9690 if (strstart(devname, "vc", 0))
9691 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9692 }
9693 }
9694
9695#ifdef CONFIG_TRACE
9696 if (trace_filename) {
9697 trace_init(trace_filename);
9698 dcache_init(dcache_size, dcache_ways, dcache_line_size,
9699 dcache_replace_policy, dcache_load_miss_penalty,
9700 dcache_store_miss_penalty);
9701 fprintf(stderr, "-- When done tracing, exit the emulator. --\n");
9702 }
9703#endif
9704
9705 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9706 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9707
9708 /* init USB devices */
9709 if (usb_enabled) {
9710 for(i = 0; i < usb_devices_index; i++) {
9711 if (usb_device_add(usb_devices[i]) < 0) {
9712 fprintf(stderr, "Warning: could not add USB device %s\n",
9713 usb_devices[i]);
9714 }
9715 }
9716 }
9717
9718 if (display_state.dpy_refresh) {
9719 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9720 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9721 }
9722
9723#ifdef CONFIG_GDBSTUB
9724 if (use_gdbstub) {
9725 /* XXX: use standard host:port notation and modify options
9726 accordingly. */
9727 if (gdbserver_start(gdbstub_port) < 0) {
9728 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9729 gdbstub_port);
9730 exit(1);
9731 }
9732 }
9733#endif
9734
9735 if (loadvm)
9736 do_loadvm(loadvm);
9737
9738 /* call android-specific setup function */
9739 android_emulation_setup();
9740
9741 {
9742 /* XXX: simplify init */
9743 read_passwords();
9744 if (autostart) {
9745 vm_start();
9746 }
9747 }
9748
9749 if (daemonize) {
9750 uint8_t status = 0;
9751 ssize_t len;
9752 int fd;
9753
9754 again1:
9755 len = write(fds[1], &status, 1);
9756 if (len == -1 && (errno == EINTR))
9757 goto again1;
9758
9759 if (len != 1)
9760 exit(1);
9761
9762 chdir("/");
9763 TFR(fd = open("/dev/null", O_RDWR));
9764 if (fd == -1)
9765 exit(1);
9766
9767 dup2(fd, 0);
9768 dup2(fd, 1);
9769 dup2(fd, 2);
9770
9771 close(fd);
9772 }
9773
9774 main_loop();
9775 quit_timers();
9776
9777#if !defined(_WIN32)
9778 /* close network clients */
9779 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9780 VLANClientState *vc;
9781
9782 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9783 if (vc->fd_read == tap_receive) {
9784 char ifname[64];
9785 TAPState *s = vc->opaque;
9786
9787 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9788 s->down_script[0])
9789 launch_script(s->down_script, ifname, s->fd);
9790 }
9791#if defined(CONFIG_VDE)
9792 if (vc->fd_read == vde_from_qemu) {
9793 VDEState *s = vc->opaque;
9794 vde_close(s->vde);
9795 }
9796#endif
9797 }
9798 }
9799#endif
9800
9801 android_emulation_teardown();
9802 return 0;
9803}