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