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