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