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