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