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