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