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