]> git.proxmox.com Git - mirror_qemu.git/blob - vl.c
Do not disturb old fd flags (eg O_APPEND) when setting nonblock, by
[mirror_qemu.git] / vl.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #include "hw/hw.h"
25 #include "hw/boards.h"
26 #include "hw/usb.h"
27 #include "hw/pcmcia.h"
28 #include "hw/pc.h"
29 #include "hw/audiodev.h"
30 #include "hw/isa.h"
31 #include "hw/baum.h"
32 #include "net.h"
33 #include "console.h"
34 #include "sysemu.h"
35 #include "gdbstub.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
38 #include "block.h"
39 #include "audio/audio.h"
40
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <signal.h>
44 #include <time.h>
45 #include <errno.h>
46 #include <sys/time.h>
47 #include <zlib.h>
48
49 #ifndef _WIN32
50 #include <sys/times.h>
51 #include <sys/wait.h>
52 #include <termios.h>
53 #include <sys/poll.h>
54 #include <sys/mman.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <dirent.h>
59 #include <netdb.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
62 #ifdef _BSD
63 #include <sys/stat.h>
64 #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 int f;
2145 f = fcntl(fd, F_GETFL);
2146 fcntl(fd, F_SETFL, f | O_NONBLOCK);
2147 }
2148 #endif /* !_WIN32 */
2149
2150 #ifndef _WIN32
2151
2152 typedef struct {
2153 int fd_in, fd_out;
2154 int max_size;
2155 } FDCharDriver;
2156
2157 #define STDIO_MAX_CLIENTS 1
2158 static int stdio_nb_clients = 0;
2159
2160 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2161 {
2162 FDCharDriver *s = chr->opaque;
2163 return unix_write(s->fd_out, buf, len);
2164 }
2165
2166 static int fd_chr_read_poll(void *opaque)
2167 {
2168 CharDriverState *chr = opaque;
2169 FDCharDriver *s = chr->opaque;
2170
2171 s->max_size = qemu_chr_can_read(chr);
2172 return s->max_size;
2173 }
2174
2175 static void fd_chr_read(void *opaque)
2176 {
2177 CharDriverState *chr = opaque;
2178 FDCharDriver *s = chr->opaque;
2179 int size, len;
2180 uint8_t buf[1024];
2181
2182 len = sizeof(buf);
2183 if (len > s->max_size)
2184 len = s->max_size;
2185 if (len == 0)
2186 return;
2187 size = read(s->fd_in, buf, len);
2188 if (size == 0) {
2189 /* FD has been closed. Remove it from the active list. */
2190 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2191 return;
2192 }
2193 if (size > 0) {
2194 qemu_chr_read(chr, buf, size);
2195 }
2196 }
2197
2198 static void fd_chr_update_read_handler(CharDriverState *chr)
2199 {
2200 FDCharDriver *s = chr->opaque;
2201
2202 if (s->fd_in >= 0) {
2203 if (nographic && s->fd_in == 0) {
2204 } else {
2205 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2206 fd_chr_read, NULL, chr);
2207 }
2208 }
2209 }
2210
2211 static void fd_chr_close(struct CharDriverState *chr)
2212 {
2213 FDCharDriver *s = chr->opaque;
2214
2215 if (s->fd_in >= 0) {
2216 if (nographic && s->fd_in == 0) {
2217 } else {
2218 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2219 }
2220 }
2221
2222 qemu_free(s);
2223 }
2224
2225 /* open a character device to a unix fd */
2226 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2227 {
2228 CharDriverState *chr;
2229 FDCharDriver *s;
2230
2231 chr = qemu_mallocz(sizeof(CharDriverState));
2232 if (!chr)
2233 return NULL;
2234 s = qemu_mallocz(sizeof(FDCharDriver));
2235 if (!s) {
2236 free(chr);
2237 return NULL;
2238 }
2239 s->fd_in = fd_in;
2240 s->fd_out = fd_out;
2241 chr->opaque = s;
2242 chr->chr_write = fd_chr_write;
2243 chr->chr_update_read_handler = fd_chr_update_read_handler;
2244 chr->chr_close = fd_chr_close;
2245
2246 qemu_chr_reset(chr);
2247
2248 return chr;
2249 }
2250
2251 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2252 {
2253 int fd_out;
2254
2255 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2256 if (fd_out < 0)
2257 return NULL;
2258 return qemu_chr_open_fd(-1, fd_out);
2259 }
2260
2261 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2262 {
2263 int fd_in, fd_out;
2264 char filename_in[256], filename_out[256];
2265
2266 snprintf(filename_in, 256, "%s.in", filename);
2267 snprintf(filename_out, 256, "%s.out", filename);
2268 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2269 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2270 if (fd_in < 0 || fd_out < 0) {
2271 if (fd_in >= 0)
2272 close(fd_in);
2273 if (fd_out >= 0)
2274 close(fd_out);
2275 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2276 if (fd_in < 0)
2277 return NULL;
2278 }
2279 return qemu_chr_open_fd(fd_in, fd_out);
2280 }
2281
2282
2283 /* for STDIO, we handle the case where several clients use it
2284 (nographic mode) */
2285
2286 #define TERM_FIFO_MAX_SIZE 1
2287
2288 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2289 static int term_fifo_size;
2290
2291 static int stdio_read_poll(void *opaque)
2292 {
2293 CharDriverState *chr = opaque;
2294
2295 /* try to flush the queue if needed */
2296 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2297 qemu_chr_read(chr, term_fifo, 1);
2298 term_fifo_size = 0;
2299 }
2300 /* see if we can absorb more chars */
2301 if (term_fifo_size == 0)
2302 return 1;
2303 else
2304 return 0;
2305 }
2306
2307 static void stdio_read(void *opaque)
2308 {
2309 int size;
2310 uint8_t buf[1];
2311 CharDriverState *chr = opaque;
2312
2313 size = read(0, buf, 1);
2314 if (size == 0) {
2315 /* stdin has been closed. Remove it from the active list. */
2316 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2317 return;
2318 }
2319 if (size > 0) {
2320 if (qemu_chr_can_read(chr) > 0) {
2321 qemu_chr_read(chr, buf, 1);
2322 } else if (term_fifo_size == 0) {
2323 term_fifo[term_fifo_size++] = buf[0];
2324 }
2325 }
2326 }
2327
2328 /* init terminal so that we can grab keys */
2329 static struct termios oldtty;
2330 static int old_fd0_flags;
2331 static int term_atexit_done;
2332
2333 static void term_exit(void)
2334 {
2335 tcsetattr (0, TCSANOW, &oldtty);
2336 fcntl(0, F_SETFL, old_fd0_flags);
2337 }
2338
2339 static void term_init(void)
2340 {
2341 struct termios tty;
2342
2343 tcgetattr (0, &tty);
2344 oldtty = tty;
2345 old_fd0_flags = fcntl(0, F_GETFL);
2346
2347 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2348 |INLCR|IGNCR|ICRNL|IXON);
2349 tty.c_oflag |= OPOST;
2350 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2351 /* if graphical mode, we allow Ctrl-C handling */
2352 if (nographic)
2353 tty.c_lflag &= ~ISIG;
2354 tty.c_cflag &= ~(CSIZE|PARENB);
2355 tty.c_cflag |= CS8;
2356 tty.c_cc[VMIN] = 1;
2357 tty.c_cc[VTIME] = 0;
2358
2359 tcsetattr (0, TCSANOW, &tty);
2360
2361 if (!term_atexit_done++)
2362 atexit(term_exit);
2363
2364 fcntl(0, F_SETFL, O_NONBLOCK);
2365 }
2366
2367 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2368 {
2369 term_exit();
2370 stdio_nb_clients--;
2371 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2372 fd_chr_close(chr);
2373 }
2374
2375 static CharDriverState *qemu_chr_open_stdio(void)
2376 {
2377 CharDriverState *chr;
2378
2379 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2380 return NULL;
2381 chr = qemu_chr_open_fd(0, 1);
2382 chr->chr_close = qemu_chr_close_stdio;
2383 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2384 stdio_nb_clients++;
2385 term_init();
2386
2387 return chr;
2388 }
2389
2390 #ifdef __sun__
2391 /* Once Solaris has openpty(), this is going to be removed. */
2392 int openpty(int *amaster, int *aslave, char *name,
2393 struct termios *termp, struct winsize *winp)
2394 {
2395 const char *slave;
2396 int mfd = -1, sfd = -1;
2397
2398 *amaster = *aslave = -1;
2399
2400 mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2401 if (mfd < 0)
2402 goto err;
2403
2404 if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2405 goto err;
2406
2407 if ((slave = ptsname(mfd)) == NULL)
2408 goto err;
2409
2410 if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2411 goto err;
2412
2413 if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2414 (termp != NULL && tcgetattr(sfd, termp) < 0))
2415 goto err;
2416
2417 if (amaster)
2418 *amaster = mfd;
2419 if (aslave)
2420 *aslave = sfd;
2421 if (winp)
2422 ioctl(sfd, TIOCSWINSZ, winp);
2423
2424 return 0;
2425
2426 err:
2427 if (sfd != -1)
2428 close(sfd);
2429 close(mfd);
2430 return -1;
2431 }
2432
2433 void cfmakeraw (struct termios *termios_p)
2434 {
2435 termios_p->c_iflag &=
2436 ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2437 termios_p->c_oflag &= ~OPOST;
2438 termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2439 termios_p->c_cflag &= ~(CSIZE|PARENB);
2440 termios_p->c_cflag |= CS8;
2441
2442 termios_p->c_cc[VMIN] = 0;
2443 termios_p->c_cc[VTIME] = 0;
2444 }
2445 #endif
2446
2447 #if defined(__linux__) || defined(__sun__)
2448 static CharDriverState *qemu_chr_open_pty(void)
2449 {
2450 struct termios tty;
2451 int master_fd, slave_fd;
2452
2453 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
2454 return NULL;
2455 }
2456
2457 /* Set raw attributes on the pty. */
2458 cfmakeraw(&tty);
2459 tcsetattr(slave_fd, TCSAFLUSH, &tty);
2460
2461 fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
2462 return qemu_chr_open_fd(master_fd, master_fd);
2463 }
2464
2465 static void tty_serial_init(int fd, int speed,
2466 int parity, int data_bits, int stop_bits)
2467 {
2468 struct termios tty;
2469 speed_t spd;
2470
2471 #if 0
2472 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2473 speed, parity, data_bits, stop_bits);
2474 #endif
2475 tcgetattr (fd, &tty);
2476
2477 #define MARGIN 1.1
2478 if (speed <= 50 * MARGIN)
2479 spd = B50;
2480 else if (speed <= 75 * MARGIN)
2481 spd = B75;
2482 else if (speed <= 300 * MARGIN)
2483 spd = B300;
2484 else if (speed <= 600 * MARGIN)
2485 spd = B600;
2486 else if (speed <= 1200 * MARGIN)
2487 spd = B1200;
2488 else if (speed <= 2400 * MARGIN)
2489 spd = B2400;
2490 else if (speed <= 4800 * MARGIN)
2491 spd = B4800;
2492 else if (speed <= 9600 * MARGIN)
2493 spd = B9600;
2494 else if (speed <= 19200 * MARGIN)
2495 spd = B19200;
2496 else if (speed <= 38400 * MARGIN)
2497 spd = B38400;
2498 else if (speed <= 57600 * MARGIN)
2499 spd = B57600;
2500 else if (speed <= 115200 * MARGIN)
2501 spd = B115200;
2502 else
2503 spd = B115200;
2504
2505 cfsetispeed(&tty, spd);
2506 cfsetospeed(&tty, spd);
2507
2508 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2509 |INLCR|IGNCR|ICRNL|IXON);
2510 tty.c_oflag |= OPOST;
2511 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2512 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2513 switch(data_bits) {
2514 default:
2515 case 8:
2516 tty.c_cflag |= CS8;
2517 break;
2518 case 7:
2519 tty.c_cflag |= CS7;
2520 break;
2521 case 6:
2522 tty.c_cflag |= CS6;
2523 break;
2524 case 5:
2525 tty.c_cflag |= CS5;
2526 break;
2527 }
2528 switch(parity) {
2529 default:
2530 case 'N':
2531 break;
2532 case 'E':
2533 tty.c_cflag |= PARENB;
2534 break;
2535 case 'O':
2536 tty.c_cflag |= PARENB | PARODD;
2537 break;
2538 }
2539 if (stop_bits == 2)
2540 tty.c_cflag |= CSTOPB;
2541
2542 tcsetattr (fd, TCSANOW, &tty);
2543 }
2544
2545 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2546 {
2547 FDCharDriver *s = chr->opaque;
2548
2549 switch(cmd) {
2550 case CHR_IOCTL_SERIAL_SET_PARAMS:
2551 {
2552 QEMUSerialSetParams *ssp = arg;
2553 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2554 ssp->data_bits, ssp->stop_bits);
2555 }
2556 break;
2557 case CHR_IOCTL_SERIAL_SET_BREAK:
2558 {
2559 int enable = *(int *)arg;
2560 if (enable)
2561 tcsendbreak(s->fd_in, 1);
2562 }
2563 break;
2564 default:
2565 return -ENOTSUP;
2566 }
2567 return 0;
2568 }
2569
2570 static CharDriverState *qemu_chr_open_tty(const char *filename)
2571 {
2572 CharDriverState *chr;
2573 int fd;
2574
2575 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2576 fcntl(fd, F_SETFL, O_NONBLOCK);
2577 tty_serial_init(fd, 115200, 'N', 8, 1);
2578 chr = qemu_chr_open_fd(fd, fd);
2579 if (!chr) {
2580 close(fd);
2581 return NULL;
2582 }
2583 chr->chr_ioctl = tty_serial_ioctl;
2584 qemu_chr_reset(chr);
2585 return chr;
2586 }
2587 #else /* ! __linux__ && ! __sun__ */
2588 static CharDriverState *qemu_chr_open_pty(void)
2589 {
2590 return NULL;
2591 }
2592 #endif /* __linux__ || __sun__ */
2593
2594 #if defined(__linux__)
2595 typedef struct {
2596 int fd;
2597 int mode;
2598 } ParallelCharDriver;
2599
2600 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2601 {
2602 if (s->mode != mode) {
2603 int m = mode;
2604 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2605 return 0;
2606 s->mode = mode;
2607 }
2608 return 1;
2609 }
2610
2611 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2612 {
2613 ParallelCharDriver *drv = chr->opaque;
2614 int fd = drv->fd;
2615 uint8_t b;
2616
2617 switch(cmd) {
2618 case CHR_IOCTL_PP_READ_DATA:
2619 if (ioctl(fd, PPRDATA, &b) < 0)
2620 return -ENOTSUP;
2621 *(uint8_t *)arg = b;
2622 break;
2623 case CHR_IOCTL_PP_WRITE_DATA:
2624 b = *(uint8_t *)arg;
2625 if (ioctl(fd, PPWDATA, &b) < 0)
2626 return -ENOTSUP;
2627 break;
2628 case CHR_IOCTL_PP_READ_CONTROL:
2629 if (ioctl(fd, PPRCONTROL, &b) < 0)
2630 return -ENOTSUP;
2631 /* Linux gives only the lowest bits, and no way to know data
2632 direction! For better compatibility set the fixed upper
2633 bits. */
2634 *(uint8_t *)arg = b | 0xc0;
2635 break;
2636 case CHR_IOCTL_PP_WRITE_CONTROL:
2637 b = *(uint8_t *)arg;
2638 if (ioctl(fd, PPWCONTROL, &b) < 0)
2639 return -ENOTSUP;
2640 break;
2641 case CHR_IOCTL_PP_READ_STATUS:
2642 if (ioctl(fd, PPRSTATUS, &b) < 0)
2643 return -ENOTSUP;
2644 *(uint8_t *)arg = b;
2645 break;
2646 case CHR_IOCTL_PP_EPP_READ_ADDR:
2647 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2648 struct ParallelIOArg *parg = arg;
2649 int n = read(fd, parg->buffer, parg->count);
2650 if (n != parg->count) {
2651 return -EIO;
2652 }
2653 }
2654 break;
2655 case CHR_IOCTL_PP_EPP_READ:
2656 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2657 struct ParallelIOArg *parg = arg;
2658 int n = read(fd, parg->buffer, parg->count);
2659 if (n != parg->count) {
2660 return -EIO;
2661 }
2662 }
2663 break;
2664 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2665 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2666 struct ParallelIOArg *parg = arg;
2667 int n = write(fd, parg->buffer, parg->count);
2668 if (n != parg->count) {
2669 return -EIO;
2670 }
2671 }
2672 break;
2673 case CHR_IOCTL_PP_EPP_WRITE:
2674 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2675 struct ParallelIOArg *parg = arg;
2676 int n = write(fd, parg->buffer, parg->count);
2677 if (n != parg->count) {
2678 return -EIO;
2679 }
2680 }
2681 break;
2682 default:
2683 return -ENOTSUP;
2684 }
2685 return 0;
2686 }
2687
2688 static void pp_close(CharDriverState *chr)
2689 {
2690 ParallelCharDriver *drv = chr->opaque;
2691 int fd = drv->fd;
2692
2693 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2694 ioctl(fd, PPRELEASE);
2695 close(fd);
2696 qemu_free(drv);
2697 }
2698
2699 static CharDriverState *qemu_chr_open_pp(const char *filename)
2700 {
2701 CharDriverState *chr;
2702 ParallelCharDriver *drv;
2703 int fd;
2704
2705 TFR(fd = open(filename, O_RDWR));
2706 if (fd < 0)
2707 return NULL;
2708
2709 if (ioctl(fd, PPCLAIM) < 0) {
2710 close(fd);
2711 return NULL;
2712 }
2713
2714 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2715 if (!drv) {
2716 close(fd);
2717 return NULL;
2718 }
2719 drv->fd = fd;
2720 drv->mode = IEEE1284_MODE_COMPAT;
2721
2722 chr = qemu_mallocz(sizeof(CharDriverState));
2723 if (!chr) {
2724 qemu_free(drv);
2725 close(fd);
2726 return NULL;
2727 }
2728 chr->chr_write = null_chr_write;
2729 chr->chr_ioctl = pp_ioctl;
2730 chr->chr_close = pp_close;
2731 chr->opaque = drv;
2732
2733 qemu_chr_reset(chr);
2734
2735 return chr;
2736 }
2737 #endif /* __linux__ */
2738
2739 #else /* _WIN32 */
2740
2741 typedef struct {
2742 int max_size;
2743 HANDLE hcom, hrecv, hsend;
2744 OVERLAPPED orecv, osend;
2745 BOOL fpipe;
2746 DWORD len;
2747 } WinCharState;
2748
2749 #define NSENDBUF 2048
2750 #define NRECVBUF 2048
2751 #define MAXCONNECT 1
2752 #define NTIMEOUT 5000
2753
2754 static int win_chr_poll(void *opaque);
2755 static int win_chr_pipe_poll(void *opaque);
2756
2757 static void win_chr_close(CharDriverState *chr)
2758 {
2759 WinCharState *s = chr->opaque;
2760
2761 if (s->hsend) {
2762 CloseHandle(s->hsend);
2763 s->hsend = NULL;
2764 }
2765 if (s->hrecv) {
2766 CloseHandle(s->hrecv);
2767 s->hrecv = NULL;
2768 }
2769 if (s->hcom) {
2770 CloseHandle(s->hcom);
2771 s->hcom = NULL;
2772 }
2773 if (s->fpipe)
2774 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2775 else
2776 qemu_del_polling_cb(win_chr_poll, chr);
2777 }
2778
2779 static int win_chr_init(CharDriverState *chr, const char *filename)
2780 {
2781 WinCharState *s = chr->opaque;
2782 COMMCONFIG comcfg;
2783 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2784 COMSTAT comstat;
2785 DWORD size;
2786 DWORD err;
2787
2788 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2789 if (!s->hsend) {
2790 fprintf(stderr, "Failed CreateEvent\n");
2791 goto fail;
2792 }
2793 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2794 if (!s->hrecv) {
2795 fprintf(stderr, "Failed CreateEvent\n");
2796 goto fail;
2797 }
2798
2799 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2800 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2801 if (s->hcom == INVALID_HANDLE_VALUE) {
2802 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2803 s->hcom = NULL;
2804 goto fail;
2805 }
2806
2807 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2808 fprintf(stderr, "Failed SetupComm\n");
2809 goto fail;
2810 }
2811
2812 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2813 size = sizeof(COMMCONFIG);
2814 GetDefaultCommConfig(filename, &comcfg, &size);
2815 comcfg.dcb.DCBlength = sizeof(DCB);
2816 CommConfigDialog(filename, NULL, &comcfg);
2817
2818 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2819 fprintf(stderr, "Failed SetCommState\n");
2820 goto fail;
2821 }
2822
2823 if (!SetCommMask(s->hcom, EV_ERR)) {
2824 fprintf(stderr, "Failed SetCommMask\n");
2825 goto fail;
2826 }
2827
2828 cto.ReadIntervalTimeout = MAXDWORD;
2829 if (!SetCommTimeouts(s->hcom, &cto)) {
2830 fprintf(stderr, "Failed SetCommTimeouts\n");
2831 goto fail;
2832 }
2833
2834 if (!ClearCommError(s->hcom, &err, &comstat)) {
2835 fprintf(stderr, "Failed ClearCommError\n");
2836 goto fail;
2837 }
2838 qemu_add_polling_cb(win_chr_poll, chr);
2839 return 0;
2840
2841 fail:
2842 win_chr_close(chr);
2843 return -1;
2844 }
2845
2846 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2847 {
2848 WinCharState *s = chr->opaque;
2849 DWORD len, ret, size, err;
2850
2851 len = len1;
2852 ZeroMemory(&s->osend, sizeof(s->osend));
2853 s->osend.hEvent = s->hsend;
2854 while (len > 0) {
2855 if (s->hsend)
2856 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2857 else
2858 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2859 if (!ret) {
2860 err = GetLastError();
2861 if (err == ERROR_IO_PENDING) {
2862 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2863 if (ret) {
2864 buf += size;
2865 len -= size;
2866 } else {
2867 break;
2868 }
2869 } else {
2870 break;
2871 }
2872 } else {
2873 buf += size;
2874 len -= size;
2875 }
2876 }
2877 return len1 - len;
2878 }
2879
2880 static int win_chr_read_poll(CharDriverState *chr)
2881 {
2882 WinCharState *s = chr->opaque;
2883
2884 s->max_size = qemu_chr_can_read(chr);
2885 return s->max_size;
2886 }
2887
2888 static void win_chr_readfile(CharDriverState *chr)
2889 {
2890 WinCharState *s = chr->opaque;
2891 int ret, err;
2892 uint8_t buf[1024];
2893 DWORD size;
2894
2895 ZeroMemory(&s->orecv, sizeof(s->orecv));
2896 s->orecv.hEvent = s->hrecv;
2897 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2898 if (!ret) {
2899 err = GetLastError();
2900 if (err == ERROR_IO_PENDING) {
2901 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2902 }
2903 }
2904
2905 if (size > 0) {
2906 qemu_chr_read(chr, buf, size);
2907 }
2908 }
2909
2910 static void win_chr_read(CharDriverState *chr)
2911 {
2912 WinCharState *s = chr->opaque;
2913
2914 if (s->len > s->max_size)
2915 s->len = s->max_size;
2916 if (s->len == 0)
2917 return;
2918
2919 win_chr_readfile(chr);
2920 }
2921
2922 static int win_chr_poll(void *opaque)
2923 {
2924 CharDriverState *chr = opaque;
2925 WinCharState *s = chr->opaque;
2926 COMSTAT status;
2927 DWORD comerr;
2928
2929 ClearCommError(s->hcom, &comerr, &status);
2930 if (status.cbInQue > 0) {
2931 s->len = status.cbInQue;
2932 win_chr_read_poll(chr);
2933 win_chr_read(chr);
2934 return 1;
2935 }
2936 return 0;
2937 }
2938
2939 static CharDriverState *qemu_chr_open_win(const char *filename)
2940 {
2941 CharDriverState *chr;
2942 WinCharState *s;
2943
2944 chr = qemu_mallocz(sizeof(CharDriverState));
2945 if (!chr)
2946 return NULL;
2947 s = qemu_mallocz(sizeof(WinCharState));
2948 if (!s) {
2949 free(chr);
2950 return NULL;
2951 }
2952 chr->opaque = s;
2953 chr->chr_write = win_chr_write;
2954 chr->chr_close = win_chr_close;
2955
2956 if (win_chr_init(chr, filename) < 0) {
2957 free(s);
2958 free(chr);
2959 return NULL;
2960 }
2961 qemu_chr_reset(chr);
2962 return chr;
2963 }
2964
2965 static int win_chr_pipe_poll(void *opaque)
2966 {
2967 CharDriverState *chr = opaque;
2968 WinCharState *s = chr->opaque;
2969 DWORD size;
2970
2971 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2972 if (size > 0) {
2973 s->len = size;
2974 win_chr_read_poll(chr);
2975 win_chr_read(chr);
2976 return 1;
2977 }
2978 return 0;
2979 }
2980
2981 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2982 {
2983 WinCharState *s = chr->opaque;
2984 OVERLAPPED ov;
2985 int ret;
2986 DWORD size;
2987 char openname[256];
2988
2989 s->fpipe = TRUE;
2990
2991 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2992 if (!s->hsend) {
2993 fprintf(stderr, "Failed CreateEvent\n");
2994 goto fail;
2995 }
2996 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2997 if (!s->hrecv) {
2998 fprintf(stderr, "Failed CreateEvent\n");
2999 goto fail;
3000 }
3001
3002 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3003 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3004 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3005 PIPE_WAIT,
3006 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3007 if (s->hcom == INVALID_HANDLE_VALUE) {
3008 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3009 s->hcom = NULL;
3010 goto fail;
3011 }
3012
3013 ZeroMemory(&ov, sizeof(ov));
3014 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3015 ret = ConnectNamedPipe(s->hcom, &ov);
3016 if (ret) {
3017 fprintf(stderr, "Failed ConnectNamedPipe\n");
3018 goto fail;
3019 }
3020
3021 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3022 if (!ret) {
3023 fprintf(stderr, "Failed GetOverlappedResult\n");
3024 if (ov.hEvent) {
3025 CloseHandle(ov.hEvent);
3026 ov.hEvent = NULL;
3027 }
3028 goto fail;
3029 }
3030
3031 if (ov.hEvent) {
3032 CloseHandle(ov.hEvent);
3033 ov.hEvent = NULL;
3034 }
3035 qemu_add_polling_cb(win_chr_pipe_poll, chr);
3036 return 0;
3037
3038 fail:
3039 win_chr_close(chr);
3040 return -1;
3041 }
3042
3043
3044 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3045 {
3046 CharDriverState *chr;
3047 WinCharState *s;
3048
3049 chr = qemu_mallocz(sizeof(CharDriverState));
3050 if (!chr)
3051 return NULL;
3052 s = qemu_mallocz(sizeof(WinCharState));
3053 if (!s) {
3054 free(chr);
3055 return NULL;
3056 }
3057 chr->opaque = s;
3058 chr->chr_write = win_chr_write;
3059 chr->chr_close = win_chr_close;
3060
3061 if (win_chr_pipe_init(chr, filename) < 0) {
3062 free(s);
3063 free(chr);
3064 return NULL;
3065 }
3066 qemu_chr_reset(chr);
3067 return chr;
3068 }
3069
3070 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3071 {
3072 CharDriverState *chr;
3073 WinCharState *s;
3074
3075 chr = qemu_mallocz(sizeof(CharDriverState));
3076 if (!chr)
3077 return NULL;
3078 s = qemu_mallocz(sizeof(WinCharState));
3079 if (!s) {
3080 free(chr);
3081 return NULL;
3082 }
3083 s->hcom = fd_out;
3084 chr->opaque = s;
3085 chr->chr_write = win_chr_write;
3086 qemu_chr_reset(chr);
3087 return chr;
3088 }
3089
3090 static CharDriverState *qemu_chr_open_win_con(const char *filename)
3091 {
3092 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3093 }
3094
3095 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3096 {
3097 HANDLE fd_out;
3098
3099 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3100 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3101 if (fd_out == INVALID_HANDLE_VALUE)
3102 return NULL;
3103
3104 return qemu_chr_open_win_file(fd_out);
3105 }
3106 #endif /* !_WIN32 */
3107
3108 /***********************************************************/
3109 /* UDP Net console */
3110
3111 typedef struct {
3112 int fd;
3113 struct sockaddr_in daddr;
3114 uint8_t buf[1024];
3115 int bufcnt;
3116 int bufptr;
3117 int max_size;
3118 } NetCharDriver;
3119
3120 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3121 {
3122 NetCharDriver *s = chr->opaque;
3123
3124 return sendto(s->fd, buf, len, 0,
3125 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3126 }
3127
3128 static int udp_chr_read_poll(void *opaque)
3129 {
3130 CharDriverState *chr = opaque;
3131 NetCharDriver *s = chr->opaque;
3132
3133 s->max_size = qemu_chr_can_read(chr);
3134
3135 /* If there were any stray characters in the queue process them
3136 * first
3137 */
3138 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3139 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3140 s->bufptr++;
3141 s->max_size = qemu_chr_can_read(chr);
3142 }
3143 return s->max_size;
3144 }
3145
3146 static void udp_chr_read(void *opaque)
3147 {
3148 CharDriverState *chr = opaque;
3149 NetCharDriver *s = chr->opaque;
3150
3151 if (s->max_size == 0)
3152 return;
3153 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3154 s->bufptr = s->bufcnt;
3155 if (s->bufcnt <= 0)
3156 return;
3157
3158 s->bufptr = 0;
3159 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3160 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3161 s->bufptr++;
3162 s->max_size = qemu_chr_can_read(chr);
3163 }
3164 }
3165
3166 static void udp_chr_update_read_handler(CharDriverState *chr)
3167 {
3168 NetCharDriver *s = chr->opaque;
3169
3170 if (s->fd >= 0) {
3171 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3172 udp_chr_read, NULL, chr);
3173 }
3174 }
3175
3176 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3177 #ifndef _WIN32
3178 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3179 #endif
3180 int parse_host_src_port(struct sockaddr_in *haddr,
3181 struct sockaddr_in *saddr,
3182 const char *str);
3183
3184 static CharDriverState *qemu_chr_open_udp(const char *def)
3185 {
3186 CharDriverState *chr = NULL;
3187 NetCharDriver *s = NULL;
3188 int fd = -1;
3189 struct sockaddr_in saddr;
3190
3191 chr = qemu_mallocz(sizeof(CharDriverState));
3192 if (!chr)
3193 goto return_err;
3194 s = qemu_mallocz(sizeof(NetCharDriver));
3195 if (!s)
3196 goto return_err;
3197
3198 fd = socket(PF_INET, SOCK_DGRAM, 0);
3199 if (fd < 0) {
3200 perror("socket(PF_INET, SOCK_DGRAM)");
3201 goto return_err;
3202 }
3203
3204 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3205 printf("Could not parse: %s\n", def);
3206 goto return_err;
3207 }
3208
3209 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3210 {
3211 perror("bind");
3212 goto return_err;
3213 }
3214
3215 s->fd = fd;
3216 s->bufcnt = 0;
3217 s->bufptr = 0;
3218 chr->opaque = s;
3219 chr->chr_write = udp_chr_write;
3220 chr->chr_update_read_handler = udp_chr_update_read_handler;
3221 return chr;
3222
3223 return_err:
3224 if (chr)
3225 free(chr);
3226 if (s)
3227 free(s);
3228 if (fd >= 0)
3229 closesocket(fd);
3230 return NULL;
3231 }
3232
3233 /***********************************************************/
3234 /* TCP Net console */
3235
3236 typedef struct {
3237 int fd, listen_fd;
3238 int connected;
3239 int max_size;
3240 int do_telnetopt;
3241 int do_nodelay;
3242 int is_unix;
3243 } TCPCharDriver;
3244
3245 static void tcp_chr_accept(void *opaque);
3246
3247 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3248 {
3249 TCPCharDriver *s = chr->opaque;
3250 if (s->connected) {
3251 return send_all(s->fd, buf, len);
3252 } else {
3253 /* XXX: indicate an error ? */
3254 return len;
3255 }
3256 }
3257
3258 static int tcp_chr_read_poll(void *opaque)
3259 {
3260 CharDriverState *chr = opaque;
3261 TCPCharDriver *s = chr->opaque;
3262 if (!s->connected)
3263 return 0;
3264 s->max_size = qemu_chr_can_read(chr);
3265 return s->max_size;
3266 }
3267
3268 #define IAC 255
3269 #define IAC_BREAK 243
3270 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3271 TCPCharDriver *s,
3272 uint8_t *buf, int *size)
3273 {
3274 /* Handle any telnet client's basic IAC options to satisfy char by
3275 * char mode with no echo. All IAC options will be removed from
3276 * the buf and the do_telnetopt variable will be used to track the
3277 * state of the width of the IAC information.
3278 *
3279 * IAC commands come in sets of 3 bytes with the exception of the
3280 * "IAC BREAK" command and the double IAC.
3281 */
3282
3283 int i;
3284 int j = 0;
3285
3286 for (i = 0; i < *size; i++) {
3287 if (s->do_telnetopt > 1) {
3288 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3289 /* Double IAC means send an IAC */
3290 if (j != i)
3291 buf[j] = buf[i];
3292 j++;
3293 s->do_telnetopt = 1;
3294 } else {
3295 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3296 /* Handle IAC break commands by sending a serial break */
3297 qemu_chr_event(chr, CHR_EVENT_BREAK);
3298 s->do_telnetopt++;
3299 }
3300 s->do_telnetopt++;
3301 }
3302 if (s->do_telnetopt >= 4) {
3303 s->do_telnetopt = 1;
3304 }
3305 } else {
3306 if ((unsigned char)buf[i] == IAC) {
3307 s->do_telnetopt = 2;
3308 } else {
3309 if (j != i)
3310 buf[j] = buf[i];
3311 j++;
3312 }
3313 }
3314 }
3315 *size = j;
3316 }
3317
3318 static void tcp_chr_read(void *opaque)
3319 {
3320 CharDriverState *chr = opaque;
3321 TCPCharDriver *s = chr->opaque;
3322 uint8_t buf[1024];
3323 int len, size;
3324
3325 if (!s->connected || s->max_size <= 0)
3326 return;
3327 len = sizeof(buf);
3328 if (len > s->max_size)
3329 len = s->max_size;
3330 size = recv(s->fd, buf, len, 0);
3331 if (size == 0) {
3332 /* connection closed */
3333 s->connected = 0;
3334 if (s->listen_fd >= 0) {
3335 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3336 }
3337 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3338 closesocket(s->fd);
3339 s->fd = -1;
3340 } else if (size > 0) {
3341 if (s->do_telnetopt)
3342 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3343 if (size > 0)
3344 qemu_chr_read(chr, buf, size);
3345 }
3346 }
3347
3348 static void tcp_chr_connect(void *opaque)
3349 {
3350 CharDriverState *chr = opaque;
3351 TCPCharDriver *s = chr->opaque;
3352
3353 s->connected = 1;
3354 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3355 tcp_chr_read, NULL, chr);
3356 qemu_chr_reset(chr);
3357 }
3358
3359 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3360 static void tcp_chr_telnet_init(int fd)
3361 {
3362 char buf[3];
3363 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3364 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3365 send(fd, (char *)buf, 3, 0);
3366 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3367 send(fd, (char *)buf, 3, 0);
3368 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3369 send(fd, (char *)buf, 3, 0);
3370 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3371 send(fd, (char *)buf, 3, 0);
3372 }
3373
3374 static void socket_set_nodelay(int fd)
3375 {
3376 int val = 1;
3377 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3378 }
3379
3380 static void tcp_chr_accept(void *opaque)
3381 {
3382 CharDriverState *chr = opaque;
3383 TCPCharDriver *s = chr->opaque;
3384 struct sockaddr_in saddr;
3385 #ifndef _WIN32
3386 struct sockaddr_un uaddr;
3387 #endif
3388 struct sockaddr *addr;
3389 socklen_t len;
3390 int fd;
3391
3392 for(;;) {
3393 #ifndef _WIN32
3394 if (s->is_unix) {
3395 len = sizeof(uaddr);
3396 addr = (struct sockaddr *)&uaddr;
3397 } else
3398 #endif
3399 {
3400 len = sizeof(saddr);
3401 addr = (struct sockaddr *)&saddr;
3402 }
3403 fd = accept(s->listen_fd, addr, &len);
3404 if (fd < 0 && errno != EINTR) {
3405 return;
3406 } else if (fd >= 0) {
3407 if (s->do_telnetopt)
3408 tcp_chr_telnet_init(fd);
3409 break;
3410 }
3411 }
3412 socket_set_nonblock(fd);
3413 if (s->do_nodelay)
3414 socket_set_nodelay(fd);
3415 s->fd = fd;
3416 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3417 tcp_chr_connect(chr);
3418 }
3419
3420 static void tcp_chr_close(CharDriverState *chr)
3421 {
3422 TCPCharDriver *s = chr->opaque;
3423 if (s->fd >= 0)
3424 closesocket(s->fd);
3425 if (s->listen_fd >= 0)
3426 closesocket(s->listen_fd);
3427 qemu_free(s);
3428 }
3429
3430 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3431 int is_telnet,
3432 int is_unix)
3433 {
3434 CharDriverState *chr = NULL;
3435 TCPCharDriver *s = NULL;
3436 int fd = -1, ret, err, val;
3437 int is_listen = 0;
3438 int is_waitconnect = 1;
3439 int do_nodelay = 0;
3440 const char *ptr;
3441 struct sockaddr_in saddr;
3442 #ifndef _WIN32
3443 struct sockaddr_un uaddr;
3444 #endif
3445 struct sockaddr *addr;
3446 socklen_t addrlen;
3447
3448 #ifndef _WIN32
3449 if (is_unix) {
3450 addr = (struct sockaddr *)&uaddr;
3451 addrlen = sizeof(uaddr);
3452 if (parse_unix_path(&uaddr, host_str) < 0)
3453 goto fail;
3454 } else
3455 #endif
3456 {
3457 addr = (struct sockaddr *)&saddr;
3458 addrlen = sizeof(saddr);
3459 if (parse_host_port(&saddr, host_str) < 0)
3460 goto fail;
3461 }
3462
3463 ptr = host_str;
3464 while((ptr = strchr(ptr,','))) {
3465 ptr++;
3466 if (!strncmp(ptr,"server",6)) {
3467 is_listen = 1;
3468 } else if (!strncmp(ptr,"nowait",6)) {
3469 is_waitconnect = 0;
3470 } else if (!strncmp(ptr,"nodelay",6)) {
3471 do_nodelay = 1;
3472 } else {
3473 printf("Unknown option: %s\n", ptr);
3474 goto fail;
3475 }
3476 }
3477 if (!is_listen)
3478 is_waitconnect = 0;
3479
3480 chr = qemu_mallocz(sizeof(CharDriverState));
3481 if (!chr)
3482 goto fail;
3483 s = qemu_mallocz(sizeof(TCPCharDriver));
3484 if (!s)
3485 goto fail;
3486
3487 #ifndef _WIN32
3488 if (is_unix)
3489 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3490 else
3491 #endif
3492 fd = socket(PF_INET, SOCK_STREAM, 0);
3493
3494 if (fd < 0)
3495 goto fail;
3496
3497 if (!is_waitconnect)
3498 socket_set_nonblock(fd);
3499
3500 s->connected = 0;
3501 s->fd = -1;
3502 s->listen_fd = -1;
3503 s->is_unix = is_unix;
3504 s->do_nodelay = do_nodelay && !is_unix;
3505
3506 chr->opaque = s;
3507 chr->chr_write = tcp_chr_write;
3508 chr->chr_close = tcp_chr_close;
3509
3510 if (is_listen) {
3511 /* allow fast reuse */
3512 #ifndef _WIN32
3513 if (is_unix) {
3514 char path[109];
3515 pstrcpy(path, sizeof(path), uaddr.sun_path);
3516 unlink(path);
3517 } else
3518 #endif
3519 {
3520 val = 1;
3521 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3522 }
3523
3524 ret = bind(fd, addr, addrlen);
3525 if (ret < 0)
3526 goto fail;
3527
3528 ret = listen(fd, 0);
3529 if (ret < 0)
3530 goto fail;
3531
3532 s->listen_fd = fd;
3533 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3534 if (is_telnet)
3535 s->do_telnetopt = 1;
3536 } else {
3537 for(;;) {
3538 ret = connect(fd, addr, addrlen);
3539 if (ret < 0) {
3540 err = socket_error();
3541 if (err == EINTR || err == EWOULDBLOCK) {
3542 } else if (err == EINPROGRESS) {
3543 break;
3544 #ifdef _WIN32
3545 } else if (err == WSAEALREADY) {
3546 break;
3547 #endif
3548 } else {
3549 goto fail;
3550 }
3551 } else {
3552 s->connected = 1;
3553 break;
3554 }
3555 }
3556 s->fd = fd;
3557 socket_set_nodelay(fd);
3558 if (s->connected)
3559 tcp_chr_connect(chr);
3560 else
3561 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3562 }
3563
3564 if (is_listen && is_waitconnect) {
3565 printf("QEMU waiting for connection on: %s\n", host_str);
3566 tcp_chr_accept(chr);
3567 socket_set_nonblock(s->listen_fd);
3568 }
3569
3570 return chr;
3571 fail:
3572 if (fd >= 0)
3573 closesocket(fd);
3574 qemu_free(s);
3575 qemu_free(chr);
3576 return NULL;
3577 }
3578
3579 CharDriverState *qemu_chr_open(const char *filename)
3580 {
3581 const char *p;
3582
3583 if (!strcmp(filename, "vc")) {
3584 return text_console_init(&display_state, 0);
3585 } else if (strstart(filename, "vc:", &p)) {
3586 return text_console_init(&display_state, p);
3587 } else if (!strcmp(filename, "null")) {
3588 return qemu_chr_open_null();
3589 } else
3590 if (strstart(filename, "tcp:", &p)) {
3591 return qemu_chr_open_tcp(p, 0, 0);
3592 } else
3593 if (strstart(filename, "telnet:", &p)) {
3594 return qemu_chr_open_tcp(p, 1, 0);
3595 } else
3596 if (strstart(filename, "udp:", &p)) {
3597 return qemu_chr_open_udp(p);
3598 } else
3599 if (strstart(filename, "mon:", &p)) {
3600 CharDriverState *drv = qemu_chr_open(p);
3601 if (drv) {
3602 drv = qemu_chr_open_mux(drv);
3603 monitor_init(drv, !nographic);
3604 return drv;
3605 }
3606 printf("Unable to open driver: %s\n", p);
3607 return 0;
3608 } else
3609 #ifndef _WIN32
3610 if (strstart(filename, "unix:", &p)) {
3611 return qemu_chr_open_tcp(p, 0, 1);
3612 } else if (strstart(filename, "file:", &p)) {
3613 return qemu_chr_open_file_out(p);
3614 } else if (strstart(filename, "pipe:", &p)) {
3615 return qemu_chr_open_pipe(p);
3616 } else if (!strcmp(filename, "pty")) {
3617 return qemu_chr_open_pty();
3618 } else if (!strcmp(filename, "stdio")) {
3619 return qemu_chr_open_stdio();
3620 } else
3621 #if defined(__linux__)
3622 if (strstart(filename, "/dev/parport", NULL)) {
3623 return qemu_chr_open_pp(filename);
3624 } else
3625 #endif
3626 #if defined(__linux__) || defined(__sun__)
3627 if (strstart(filename, "/dev/", NULL)) {
3628 return qemu_chr_open_tty(filename);
3629 } else
3630 #endif
3631 #else /* !_WIN32 */
3632 if (strstart(filename, "COM", NULL)) {
3633 return qemu_chr_open_win(filename);
3634 } else
3635 if (strstart(filename, "pipe:", &p)) {
3636 return qemu_chr_open_win_pipe(p);
3637 } else
3638 if (strstart(filename, "con:", NULL)) {
3639 return qemu_chr_open_win_con(filename);
3640 } else
3641 if (strstart(filename, "file:", &p)) {
3642 return qemu_chr_open_win_file_out(p);
3643 } else
3644 #endif
3645 #ifdef CONFIG_BRLAPI
3646 if (!strcmp(filename, "braille")) {
3647 return chr_baum_init();
3648 } else
3649 #endif
3650 {
3651 return NULL;
3652 }
3653 }
3654
3655 void qemu_chr_close(CharDriverState *chr)
3656 {
3657 if (chr->chr_close)
3658 chr->chr_close(chr);
3659 qemu_free(chr);
3660 }
3661
3662 /***********************************************************/
3663 /* network device redirectors */
3664
3665 __attribute__ (( unused ))
3666 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3667 {
3668 int len, i, j, c;
3669
3670 for(i=0;i<size;i+=16) {
3671 len = size - i;
3672 if (len > 16)
3673 len = 16;
3674 fprintf(f, "%08x ", i);
3675 for(j=0;j<16;j++) {
3676 if (j < len)
3677 fprintf(f, " %02x", buf[i+j]);
3678 else
3679 fprintf(f, " ");
3680 }
3681 fprintf(f, " ");
3682 for(j=0;j<len;j++) {
3683 c = buf[i+j];
3684 if (c < ' ' || c > '~')
3685 c = '.';
3686 fprintf(f, "%c", c);
3687 }
3688 fprintf(f, "\n");
3689 }
3690 }
3691
3692 static int parse_macaddr(uint8_t *macaddr, const char *p)
3693 {
3694 int i;
3695 char *last_char;
3696 long int offset;
3697
3698 errno = 0;
3699 offset = strtol(p, &last_char, 0);
3700 if (0 == errno && '\0' == *last_char &&
3701 offset >= 0 && offset <= 0xFFFFFF) {
3702 macaddr[3] = (offset & 0xFF0000) >> 16;
3703 macaddr[4] = (offset & 0xFF00) >> 8;
3704 macaddr[5] = offset & 0xFF;
3705 return 0;
3706 } else {
3707 for(i = 0; i < 6; i++) {
3708 macaddr[i] = strtol(p, (char **)&p, 16);
3709 if (i == 5) {
3710 if (*p != '\0')
3711 return -1;
3712 } else {
3713 if (*p != ':' && *p != '-')
3714 return -1;
3715 p++;
3716 }
3717 }
3718 return 0;
3719 }
3720
3721 return -1;
3722 }
3723
3724 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3725 {
3726 const char *p, *p1;
3727 int len;
3728 p = *pp;
3729 p1 = strchr(p, sep);
3730 if (!p1)
3731 return -1;
3732 len = p1 - p;
3733 p1++;
3734 if (buf_size > 0) {
3735 if (len > buf_size - 1)
3736 len = buf_size - 1;
3737 memcpy(buf, p, len);
3738 buf[len] = '\0';
3739 }
3740 *pp = p1;
3741 return 0;
3742 }
3743
3744 int parse_host_src_port(struct sockaddr_in *haddr,
3745 struct sockaddr_in *saddr,
3746 const char *input_str)
3747 {
3748 char *str = strdup(input_str);
3749 char *host_str = str;
3750 char *src_str;
3751 char *ptr;
3752
3753 /*
3754 * Chop off any extra arguments at the end of the string which
3755 * would start with a comma, then fill in the src port information
3756 * if it was provided else use the "any address" and "any port".
3757 */
3758 if ((ptr = strchr(str,',')))
3759 *ptr = '\0';
3760
3761 if ((src_str = strchr(input_str,'@'))) {
3762 *src_str = '\0';
3763 src_str++;
3764 }
3765
3766 if (parse_host_port(haddr, host_str) < 0)
3767 goto fail;
3768
3769 if (!src_str || *src_str == '\0')
3770 src_str = ":0";
3771
3772 if (parse_host_port(saddr, src_str) < 0)
3773 goto fail;
3774
3775 free(str);
3776 return(0);
3777
3778 fail:
3779 free(str);
3780 return -1;
3781 }
3782
3783 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3784 {
3785 char buf[512];
3786 struct hostent *he;
3787 const char *p, *r;
3788 int port;
3789
3790 p = str;
3791 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3792 return -1;
3793 saddr->sin_family = AF_INET;
3794 if (buf[0] == '\0') {
3795 saddr->sin_addr.s_addr = 0;
3796 } else {
3797 if (isdigit(buf[0])) {
3798 if (!inet_aton(buf, &saddr->sin_addr))
3799 return -1;
3800 } else {
3801 if ((he = gethostbyname(buf)) == NULL)
3802 return - 1;
3803 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3804 }
3805 }
3806 port = strtol(p, (char **)&r, 0);
3807 if (r == p)
3808 return -1;
3809 saddr->sin_port = htons(port);
3810 return 0;
3811 }
3812
3813 #ifndef _WIN32
3814 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3815 {
3816 const char *p;
3817 int len;
3818
3819 len = MIN(108, strlen(str));
3820 p = strchr(str, ',');
3821 if (p)
3822 len = MIN(len, p - str);
3823
3824 memset(uaddr, 0, sizeof(*uaddr));
3825
3826 uaddr->sun_family = AF_UNIX;
3827 memcpy(uaddr->sun_path, str, len);
3828
3829 return 0;
3830 }
3831 #endif
3832
3833 /* find or alloc a new VLAN */
3834 VLANState *qemu_find_vlan(int id)
3835 {
3836 VLANState **pvlan, *vlan;
3837 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3838 if (vlan->id == id)
3839 return vlan;
3840 }
3841 vlan = qemu_mallocz(sizeof(VLANState));
3842 if (!vlan)
3843 return NULL;
3844 vlan->id = id;
3845 vlan->next = NULL;
3846 pvlan = &first_vlan;
3847 while (*pvlan != NULL)
3848 pvlan = &(*pvlan)->next;
3849 *pvlan = vlan;
3850 return vlan;
3851 }
3852
3853 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3854 IOReadHandler *fd_read,
3855 IOCanRWHandler *fd_can_read,
3856 void *opaque)
3857 {
3858 VLANClientState *vc, **pvc;
3859 vc = qemu_mallocz(sizeof(VLANClientState));
3860 if (!vc)
3861 return NULL;
3862 vc->fd_read = fd_read;
3863 vc->fd_can_read = fd_can_read;
3864 vc->opaque = opaque;
3865 vc->vlan = vlan;
3866
3867 vc->next = NULL;
3868 pvc = &vlan->first_client;
3869 while (*pvc != NULL)
3870 pvc = &(*pvc)->next;
3871 *pvc = vc;
3872 return vc;
3873 }
3874
3875 void qemu_del_vlan_client(VLANClientState *vc)
3876 {
3877 VLANClientState **pvc = &vc->vlan->first_client;
3878
3879 while (*pvc != NULL)
3880 if (*pvc == vc) {
3881 *pvc = vc->next;
3882 free(vc);
3883 break;
3884 } else
3885 pvc = &(*pvc)->next;
3886 }
3887
3888 int qemu_can_send_packet(VLANClientState *vc1)
3889 {
3890 VLANState *vlan = vc1->vlan;
3891 VLANClientState *vc;
3892
3893 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3894 if (vc != vc1) {
3895 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3896 return 1;
3897 }
3898 }
3899 return 0;
3900 }
3901
3902 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3903 {
3904 VLANState *vlan = vc1->vlan;
3905 VLANClientState *vc;
3906
3907 #if 0
3908 printf("vlan %d send:\n", vlan->id);
3909 hex_dump(stdout, buf, size);
3910 #endif
3911 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3912 if (vc != vc1) {
3913 vc->fd_read(vc->opaque, buf, size);
3914 }
3915 }
3916 }
3917
3918 #if defined(CONFIG_SLIRP)
3919
3920 /* slirp network adapter */
3921
3922 static int slirp_inited;
3923 static VLANClientState *slirp_vc;
3924
3925 int slirp_can_output(void)
3926 {
3927 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3928 }
3929
3930 void slirp_output(const uint8_t *pkt, int pkt_len)
3931 {
3932 #if 0
3933 printf("slirp output:\n");
3934 hex_dump(stdout, pkt, pkt_len);
3935 #endif
3936 if (!slirp_vc)
3937 return;
3938 qemu_send_packet(slirp_vc, pkt, pkt_len);
3939 }
3940
3941 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3942 {
3943 #if 0
3944 printf("slirp input:\n");
3945 hex_dump(stdout, buf, size);
3946 #endif
3947 slirp_input(buf, size);
3948 }
3949
3950 static int net_slirp_init(VLANState *vlan)
3951 {
3952 if (!slirp_inited) {
3953 slirp_inited = 1;
3954 slirp_init();
3955 }
3956 slirp_vc = qemu_new_vlan_client(vlan,
3957 slirp_receive, NULL, NULL);
3958 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3959 return 0;
3960 }
3961
3962 static void net_slirp_redir(const char *redir_str)
3963 {
3964 int is_udp;
3965 char buf[256], *r;
3966 const char *p;
3967 struct in_addr guest_addr;
3968 int host_port, guest_port;
3969
3970 if (!slirp_inited) {
3971 slirp_inited = 1;
3972 slirp_init();
3973 }
3974
3975 p = redir_str;
3976 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3977 goto fail;
3978 if (!strcmp(buf, "tcp")) {
3979 is_udp = 0;
3980 } else if (!strcmp(buf, "udp")) {
3981 is_udp = 1;
3982 } else {
3983 goto fail;
3984 }
3985
3986 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3987 goto fail;
3988 host_port = strtol(buf, &r, 0);
3989 if (r == buf)
3990 goto fail;
3991
3992 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3993 goto fail;
3994 if (buf[0] == '\0') {
3995 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3996 }
3997 if (!inet_aton(buf, &guest_addr))
3998 goto fail;
3999
4000 guest_port = strtol(p, &r, 0);
4001 if (r == p)
4002 goto fail;
4003
4004 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4005 fprintf(stderr, "qemu: could not set up redirection\n");
4006 exit(1);
4007 }
4008 return;
4009 fail:
4010 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4011 exit(1);
4012 }
4013
4014 #ifndef _WIN32
4015
4016 char smb_dir[1024];
4017
4018 static void erase_dir(char *dir_name)
4019 {
4020 DIR *d;
4021 struct dirent *de;
4022 char filename[1024];
4023
4024 /* erase all the files in the directory */
4025 if ((d = opendir(dir_name)) != 0) {
4026 for(;;) {
4027 de = readdir(d);
4028 if (!de)
4029 break;
4030 if (strcmp(de->d_name, ".") != 0 &&
4031 strcmp(de->d_name, "..") != 0) {
4032 snprintf(filename, sizeof(filename), "%s/%s",
4033 smb_dir, de->d_name);
4034 if (unlink(filename) != 0) /* is it a directory? */
4035 erase_dir(filename);
4036 }
4037 }
4038 closedir(d);
4039 rmdir(dir_name);
4040 }
4041 }
4042
4043 /* automatic user mode samba server configuration */
4044 static void smb_exit(void)
4045 {
4046 erase_dir(smb_dir);
4047 }
4048
4049 /* automatic user mode samba server configuration */
4050 static void net_slirp_smb(const char *exported_dir)
4051 {
4052 char smb_conf[1024];
4053 char smb_cmdline[1024];
4054 FILE *f;
4055
4056 if (!slirp_inited) {
4057 slirp_inited = 1;
4058 slirp_init();
4059 }
4060
4061 /* XXX: better tmp dir construction */
4062 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4063 if (mkdir(smb_dir, 0700) < 0) {
4064 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4065 exit(1);
4066 }
4067 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4068
4069 f = fopen(smb_conf, "w");
4070 if (!f) {
4071 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4072 exit(1);
4073 }
4074 fprintf(f,
4075 "[global]\n"
4076 "private dir=%s\n"
4077 "smb ports=0\n"
4078 "socket address=127.0.0.1\n"
4079 "pid directory=%s\n"
4080 "lock directory=%s\n"
4081 "log file=%s/log.smbd\n"
4082 "smb passwd file=%s/smbpasswd\n"
4083 "security = share\n"
4084 "[qemu]\n"
4085 "path=%s\n"
4086 "read only=no\n"
4087 "guest ok=yes\n",
4088 smb_dir,
4089 smb_dir,
4090 smb_dir,
4091 smb_dir,
4092 smb_dir,
4093 exported_dir
4094 );
4095 fclose(f);
4096 atexit(smb_exit);
4097
4098 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4099 SMBD_COMMAND, smb_conf);
4100
4101 slirp_add_exec(0, smb_cmdline, 4, 139);
4102 }
4103
4104 #endif /* !defined(_WIN32) */
4105 void do_info_slirp(void)
4106 {
4107 slirp_stats();
4108 }
4109
4110 #endif /* CONFIG_SLIRP */
4111
4112 #if !defined(_WIN32)
4113
4114 typedef struct TAPState {
4115 VLANClientState *vc;
4116 int fd;
4117 char down_script[1024];
4118 } TAPState;
4119
4120 static void tap_receive(void *opaque, const uint8_t *buf, int size)
4121 {
4122 TAPState *s = opaque;
4123 int ret;
4124 for(;;) {
4125 ret = write(s->fd, buf, size);
4126 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4127 } else {
4128 break;
4129 }
4130 }
4131 }
4132
4133 static void tap_send(void *opaque)
4134 {
4135 TAPState *s = opaque;
4136 uint8_t buf[4096];
4137 int size;
4138
4139 #ifdef __sun__
4140 struct strbuf sbuf;
4141 int f = 0;
4142 sbuf.maxlen = sizeof(buf);
4143 sbuf.buf = buf;
4144 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4145 #else
4146 size = read(s->fd, buf, sizeof(buf));
4147 #endif
4148 if (size > 0) {
4149 qemu_send_packet(s->vc, buf, size);
4150 }
4151 }
4152
4153 /* fd support */
4154
4155 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4156 {
4157 TAPState *s;
4158
4159 s = qemu_mallocz(sizeof(TAPState));
4160 if (!s)
4161 return NULL;
4162 s->fd = fd;
4163 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4164 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4165 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4166 return s;
4167 }
4168
4169 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4170 static int tap_open(char *ifname, int ifname_size)
4171 {
4172 int fd;
4173 char *dev;
4174 struct stat s;
4175
4176 TFR(fd = open("/dev/tap", O_RDWR));
4177 if (fd < 0) {
4178 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4179 return -1;
4180 }
4181
4182 fstat(fd, &s);
4183 dev = devname(s.st_rdev, S_IFCHR);
4184 pstrcpy(ifname, ifname_size, dev);
4185
4186 fcntl(fd, F_SETFL, O_NONBLOCK);
4187 return fd;
4188 }
4189 #elif defined(__sun__)
4190 #define TUNNEWPPA (('T'<<16) | 0x0001)
4191 /*
4192 * Allocate TAP device, returns opened fd.
4193 * Stores dev name in the first arg(must be large enough).
4194 */
4195 int tap_alloc(char *dev)
4196 {
4197 int tap_fd, if_fd, ppa = -1;
4198 static int ip_fd = 0;
4199 char *ptr;
4200
4201 static int arp_fd = 0;
4202 int ip_muxid, arp_muxid;
4203 struct strioctl strioc_if, strioc_ppa;
4204 int link_type = I_PLINK;;
4205 struct lifreq ifr;
4206 char actual_name[32] = "";
4207
4208 memset(&ifr, 0x0, sizeof(ifr));
4209
4210 if( *dev ){
4211 ptr = dev;
4212 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4213 ppa = atoi(ptr);
4214 }
4215
4216 /* Check if IP device was opened */
4217 if( ip_fd )
4218 close(ip_fd);
4219
4220 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4221 if (ip_fd < 0) {
4222 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4223 return -1;
4224 }
4225
4226 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4227 if (tap_fd < 0) {
4228 syslog(LOG_ERR, "Can't open /dev/tap");
4229 return -1;
4230 }
4231
4232 /* Assign a new PPA and get its unit number. */
4233 strioc_ppa.ic_cmd = TUNNEWPPA;
4234 strioc_ppa.ic_timout = 0;
4235 strioc_ppa.ic_len = sizeof(ppa);
4236 strioc_ppa.ic_dp = (char *)&ppa;
4237 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4238 syslog (LOG_ERR, "Can't assign new interface");
4239
4240 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4241 if (if_fd < 0) {
4242 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4243 return -1;
4244 }
4245 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4246 syslog(LOG_ERR, "Can't push IP module");
4247 return -1;
4248 }
4249
4250 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4251 syslog(LOG_ERR, "Can't get flags\n");
4252
4253 snprintf (actual_name, 32, "tap%d", ppa);
4254 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4255
4256 ifr.lifr_ppa = ppa;
4257 /* Assign ppa according to the unit number returned by tun device */
4258
4259 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4260 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4261 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4262 syslog (LOG_ERR, "Can't get flags\n");
4263 /* Push arp module to if_fd */
4264 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4265 syslog (LOG_ERR, "Can't push ARP module (2)");
4266
4267 /* Push arp module to ip_fd */
4268 if (ioctl (ip_fd, I_POP, NULL) < 0)
4269 syslog (LOG_ERR, "I_POP failed\n");
4270 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4271 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4272 /* Open arp_fd */
4273 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4274 if (arp_fd < 0)
4275 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4276
4277 /* Set ifname to arp */
4278 strioc_if.ic_cmd = SIOCSLIFNAME;
4279 strioc_if.ic_timout = 0;
4280 strioc_if.ic_len = sizeof(ifr);
4281 strioc_if.ic_dp = (char *)&ifr;
4282 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4283 syslog (LOG_ERR, "Can't set ifname to arp\n");
4284 }
4285
4286 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4287 syslog(LOG_ERR, "Can't link TAP device to IP");
4288 return -1;
4289 }
4290
4291 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4292 syslog (LOG_ERR, "Can't link TAP device to ARP");
4293
4294 close (if_fd);
4295
4296 memset(&ifr, 0x0, sizeof(ifr));
4297 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4298 ifr.lifr_ip_muxid = ip_muxid;
4299 ifr.lifr_arp_muxid = arp_muxid;
4300
4301 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4302 {
4303 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4304 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4305 syslog (LOG_ERR, "Can't set multiplexor id");
4306 }
4307
4308 sprintf(dev, "tap%d", ppa);
4309 return tap_fd;
4310 }
4311
4312 static int tap_open(char *ifname, int ifname_size)
4313 {
4314 char dev[10]="";
4315 int fd;
4316 if( (fd = tap_alloc(dev)) < 0 ){
4317 fprintf(stderr, "Cannot allocate TAP device\n");
4318 return -1;
4319 }
4320 pstrcpy(ifname, ifname_size, dev);
4321 fcntl(fd, F_SETFL, O_NONBLOCK);
4322 return fd;
4323 }
4324 #else
4325 static int tap_open(char *ifname, int ifname_size)
4326 {
4327 struct ifreq ifr;
4328 int fd, ret;
4329
4330 TFR(fd = open("/dev/net/tun", O_RDWR));
4331 if (fd < 0) {
4332 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4333 return -1;
4334 }
4335 memset(&ifr, 0, sizeof(ifr));
4336 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4337 if (ifname[0] != '\0')
4338 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4339 else
4340 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4341 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4342 if (ret != 0) {
4343 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4344 close(fd);
4345 return -1;
4346 }
4347 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4348 fcntl(fd, F_SETFL, O_NONBLOCK);
4349 return fd;
4350 }
4351 #endif
4352
4353 static int launch_script(const char *setup_script, const char *ifname, int fd)
4354 {
4355 int pid, status;
4356 char *args[3];
4357 char **parg;
4358
4359 /* try to launch network script */
4360 pid = fork();
4361 if (pid >= 0) {
4362 if (pid == 0) {
4363 int open_max = sysconf (_SC_OPEN_MAX), i;
4364 for (i = 0; i < open_max; i++)
4365 if (i != STDIN_FILENO &&
4366 i != STDOUT_FILENO &&
4367 i != STDERR_FILENO &&
4368 i != fd)
4369 close(i);
4370
4371 parg = args;
4372 *parg++ = (char *)setup_script;
4373 *parg++ = (char *)ifname;
4374 *parg++ = NULL;
4375 execv(setup_script, args);
4376 _exit(1);
4377 }
4378 while (waitpid(pid, &status, 0) != pid);
4379 if (!WIFEXITED(status) ||
4380 WEXITSTATUS(status) != 0) {
4381 fprintf(stderr, "%s: could not launch network script\n",
4382 setup_script);
4383 return -1;
4384 }
4385 }
4386 return 0;
4387 }
4388
4389 static int net_tap_init(VLANState *vlan, const char *ifname1,
4390 const char *setup_script, const char *down_script)
4391 {
4392 TAPState *s;
4393 int fd;
4394 char ifname[128];
4395
4396 if (ifname1 != NULL)
4397 pstrcpy(ifname, sizeof(ifname), ifname1);
4398 else
4399 ifname[0] = '\0';
4400 TFR(fd = tap_open(ifname, sizeof(ifname)));
4401 if (fd < 0)
4402 return -1;
4403
4404 if (!setup_script || !strcmp(setup_script, "no"))
4405 setup_script = "";
4406 if (setup_script[0] != '\0') {
4407 if (launch_script(setup_script, ifname, fd))
4408 return -1;
4409 }
4410 s = net_tap_fd_init(vlan, fd);
4411 if (!s)
4412 return -1;
4413 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4414 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4415 if (down_script && strcmp(down_script, "no"))
4416 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4417 return 0;
4418 }
4419
4420 #endif /* !_WIN32 */
4421
4422 /* network connection */
4423 typedef struct NetSocketState {
4424 VLANClientState *vc;
4425 int fd;
4426 int state; /* 0 = getting length, 1 = getting data */
4427 int index;
4428 int packet_len;
4429 uint8_t buf[4096];
4430 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4431 } NetSocketState;
4432
4433 typedef struct NetSocketListenState {
4434 VLANState *vlan;
4435 int fd;
4436 } NetSocketListenState;
4437
4438 /* XXX: we consider we can send the whole packet without blocking */
4439 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4440 {
4441 NetSocketState *s = opaque;
4442 uint32_t len;
4443 len = htonl(size);
4444
4445 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4446 send_all(s->fd, buf, size);
4447 }
4448
4449 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4450 {
4451 NetSocketState *s = opaque;
4452 sendto(s->fd, buf, size, 0,
4453 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4454 }
4455
4456 static void net_socket_send(void *opaque)
4457 {
4458 NetSocketState *s = opaque;
4459 int l, size, err;
4460 uint8_t buf1[4096];
4461 const uint8_t *buf;
4462
4463 size = recv(s->fd, buf1, sizeof(buf1), 0);
4464 if (size < 0) {
4465 err = socket_error();
4466 if (err != EWOULDBLOCK)
4467 goto eoc;
4468 } else if (size == 0) {
4469 /* end of connection */
4470 eoc:
4471 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4472 closesocket(s->fd);
4473 return;
4474 }
4475 buf = buf1;
4476 while (size > 0) {
4477 /* reassemble a packet from the network */
4478 switch(s->state) {
4479 case 0:
4480 l = 4 - s->index;
4481 if (l > size)
4482 l = size;
4483 memcpy(s->buf + s->index, buf, l);
4484 buf += l;
4485 size -= l;
4486 s->index += l;
4487 if (s->index == 4) {
4488 /* got length */
4489 s->packet_len = ntohl(*(uint32_t *)s->buf);
4490 s->index = 0;
4491 s->state = 1;
4492 }
4493 break;
4494 case 1:
4495 l = s->packet_len - s->index;
4496 if (l > size)
4497 l = size;
4498 memcpy(s->buf + s->index, buf, l);
4499 s->index += l;
4500 buf += l;
4501 size -= l;
4502 if (s->index >= s->packet_len) {
4503 qemu_send_packet(s->vc, s->buf, s->packet_len);
4504 s->index = 0;
4505 s->state = 0;
4506 }
4507 break;
4508 }
4509 }
4510 }
4511
4512 static void net_socket_send_dgram(void *opaque)
4513 {
4514 NetSocketState *s = opaque;
4515 int size;
4516
4517 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4518 if (size < 0)
4519 return;
4520 if (size == 0) {
4521 /* end of connection */
4522 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4523 return;
4524 }
4525 qemu_send_packet(s->vc, s->buf, size);
4526 }
4527
4528 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4529 {
4530 struct ip_mreq imr;
4531 int fd;
4532 int val, ret;
4533 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4534 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4535 inet_ntoa(mcastaddr->sin_addr),
4536 (int)ntohl(mcastaddr->sin_addr.s_addr));
4537 return -1;
4538
4539 }
4540 fd = socket(PF_INET, SOCK_DGRAM, 0);
4541 if (fd < 0) {
4542 perror("socket(PF_INET, SOCK_DGRAM)");
4543 return -1;
4544 }
4545
4546 val = 1;
4547 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4548 (const char *)&val, sizeof(val));
4549 if (ret < 0) {
4550 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4551 goto fail;
4552 }
4553
4554 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4555 if (ret < 0) {
4556 perror("bind");
4557 goto fail;
4558 }
4559
4560 /* Add host to multicast group */
4561 imr.imr_multiaddr = mcastaddr->sin_addr;
4562 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4563
4564 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4565 (const char *)&imr, sizeof(struct ip_mreq));
4566 if (ret < 0) {
4567 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4568 goto fail;
4569 }
4570
4571 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4572 val = 1;
4573 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4574 (const char *)&val, sizeof(val));
4575 if (ret < 0) {
4576 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4577 goto fail;
4578 }
4579
4580 socket_set_nonblock(fd);
4581 return fd;
4582 fail:
4583 if (fd >= 0)
4584 closesocket(fd);
4585 return -1;
4586 }
4587
4588 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4589 int is_connected)
4590 {
4591 struct sockaddr_in saddr;
4592 int newfd;
4593 socklen_t saddr_len;
4594 NetSocketState *s;
4595
4596 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4597 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4598 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4599 */
4600
4601 if (is_connected) {
4602 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4603 /* must be bound */
4604 if (saddr.sin_addr.s_addr==0) {
4605 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4606 fd);
4607 return NULL;
4608 }
4609 /* clone dgram socket */
4610 newfd = net_socket_mcast_create(&saddr);
4611 if (newfd < 0) {
4612 /* error already reported by net_socket_mcast_create() */
4613 close(fd);
4614 return NULL;
4615 }
4616 /* clone newfd to fd, close newfd */
4617 dup2(newfd, fd);
4618 close(newfd);
4619
4620 } else {
4621 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4622 fd, strerror(errno));
4623 return NULL;
4624 }
4625 }
4626
4627 s = qemu_mallocz(sizeof(NetSocketState));
4628 if (!s)
4629 return NULL;
4630 s->fd = fd;
4631
4632 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4633 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4634
4635 /* mcast: save bound address as dst */
4636 if (is_connected) s->dgram_dst=saddr;
4637
4638 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4639 "socket: fd=%d (%s mcast=%s:%d)",
4640 fd, is_connected? "cloned" : "",
4641 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4642 return s;
4643 }
4644
4645 static void net_socket_connect(void *opaque)
4646 {
4647 NetSocketState *s = opaque;
4648 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4649 }
4650
4651 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4652 int is_connected)
4653 {
4654 NetSocketState *s;
4655 s = qemu_mallocz(sizeof(NetSocketState));
4656 if (!s)
4657 return NULL;
4658 s->fd = fd;
4659 s->vc = qemu_new_vlan_client(vlan,
4660 net_socket_receive, NULL, s);
4661 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4662 "socket: fd=%d", fd);
4663 if (is_connected) {
4664 net_socket_connect(s);
4665 } else {
4666 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4667 }
4668 return s;
4669 }
4670
4671 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4672 int is_connected)
4673 {
4674 int so_type=-1, optlen=sizeof(so_type);
4675
4676 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4677 (socklen_t *)&optlen)< 0) {
4678 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4679 return NULL;
4680 }
4681 switch(so_type) {
4682 case SOCK_DGRAM:
4683 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4684 case SOCK_STREAM:
4685 return net_socket_fd_init_stream(vlan, fd, is_connected);
4686 default:
4687 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4688 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4689 return net_socket_fd_init_stream(vlan, fd, is_connected);
4690 }
4691 return NULL;
4692 }
4693
4694 static void net_socket_accept(void *opaque)
4695 {
4696 NetSocketListenState *s = opaque;
4697 NetSocketState *s1;
4698 struct sockaddr_in saddr;
4699 socklen_t len;
4700 int fd;
4701
4702 for(;;) {
4703 len = sizeof(saddr);
4704 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4705 if (fd < 0 && errno != EINTR) {
4706 return;
4707 } else if (fd >= 0) {
4708 break;
4709 }
4710 }
4711 s1 = net_socket_fd_init(s->vlan, fd, 1);
4712 if (!s1) {
4713 closesocket(fd);
4714 } else {
4715 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4716 "socket: connection from %s:%d",
4717 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4718 }
4719 }
4720
4721 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4722 {
4723 NetSocketListenState *s;
4724 int fd, val, ret;
4725 struct sockaddr_in saddr;
4726
4727 if (parse_host_port(&saddr, host_str) < 0)
4728 return -1;
4729
4730 s = qemu_mallocz(sizeof(NetSocketListenState));
4731 if (!s)
4732 return -1;
4733
4734 fd = socket(PF_INET, SOCK_STREAM, 0);
4735 if (fd < 0) {
4736 perror("socket");
4737 return -1;
4738 }
4739 socket_set_nonblock(fd);
4740
4741 /* allow fast reuse */
4742 val = 1;
4743 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4744
4745 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4746 if (ret < 0) {
4747 perror("bind");
4748 return -1;
4749 }
4750 ret = listen(fd, 0);
4751 if (ret < 0) {
4752 perror("listen");
4753 return -1;
4754 }
4755 s->vlan = vlan;
4756 s->fd = fd;
4757 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4758 return 0;
4759 }
4760
4761 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4762 {
4763 NetSocketState *s;
4764 int fd, connected, ret, err;
4765 struct sockaddr_in saddr;
4766
4767 if (parse_host_port(&saddr, host_str) < 0)
4768 return -1;
4769
4770 fd = socket(PF_INET, SOCK_STREAM, 0);
4771 if (fd < 0) {
4772 perror("socket");
4773 return -1;
4774 }
4775 socket_set_nonblock(fd);
4776
4777 connected = 0;
4778 for(;;) {
4779 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4780 if (ret < 0) {
4781 err = socket_error();
4782 if (err == EINTR || err == EWOULDBLOCK) {
4783 } else if (err == EINPROGRESS) {
4784 break;
4785 #ifdef _WIN32
4786 } else if (err == WSAEALREADY) {
4787 break;
4788 #endif
4789 } else {
4790 perror("connect");
4791 closesocket(fd);
4792 return -1;
4793 }
4794 } else {
4795 connected = 1;
4796 break;
4797 }
4798 }
4799 s = net_socket_fd_init(vlan, fd, connected);
4800 if (!s)
4801 return -1;
4802 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4803 "socket: connect to %s:%d",
4804 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4805 return 0;
4806 }
4807
4808 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4809 {
4810 NetSocketState *s;
4811 int fd;
4812 struct sockaddr_in saddr;
4813
4814 if (parse_host_port(&saddr, host_str) < 0)
4815 return -1;
4816
4817
4818 fd = net_socket_mcast_create(&saddr);
4819 if (fd < 0)
4820 return -1;
4821
4822 s = net_socket_fd_init(vlan, fd, 0);
4823 if (!s)
4824 return -1;
4825
4826 s->dgram_dst = saddr;
4827
4828 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4829 "socket: mcast=%s:%d",
4830 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4831 return 0;
4832
4833 }
4834
4835 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4836 {
4837 char *q;
4838
4839 q = buf;
4840 while (*p != '\0' && *p != '=') {
4841 if (q && (q - buf) < buf_size - 1)
4842 *q++ = *p;
4843 p++;
4844 }
4845 if (q)
4846 *q = '\0';
4847
4848 return p;
4849 }
4850
4851 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4852 {
4853 char *q;
4854
4855 q = buf;
4856 while (*p != '\0') {
4857 if (*p == ',') {
4858 if (*(p + 1) != ',')
4859 break;
4860 p++;
4861 }
4862 if (q && (q - buf) < buf_size - 1)
4863 *q++ = *p;
4864 p++;
4865 }
4866 if (q)
4867 *q = '\0';
4868
4869 return p;
4870 }
4871
4872 static int get_param_value(char *buf, int buf_size,
4873 const char *tag, const char *str)
4874 {
4875 const char *p;
4876 char option[128];
4877
4878 p = str;
4879 for(;;) {
4880 p = get_opt_name(option, sizeof(option), p);
4881 if (*p != '=')
4882 break;
4883 p++;
4884 if (!strcmp(tag, option)) {
4885 (void)get_opt_value(buf, buf_size, p);
4886 return strlen(buf);
4887 } else {
4888 p = get_opt_value(NULL, 0, p);
4889 }
4890 if (*p != ',')
4891 break;
4892 p++;
4893 }
4894 return 0;
4895 }
4896
4897 static int check_params(char *buf, int buf_size,
4898 char **params, const char *str)
4899 {
4900 const char *p;
4901 int i;
4902
4903 p = str;
4904 for(;;) {
4905 p = get_opt_name(buf, buf_size, p);
4906 if (*p != '=')
4907 return -1;
4908 p++;
4909 for(i = 0; params[i] != NULL; i++)
4910 if (!strcmp(params[i], buf))
4911 break;
4912 if (params[i] == NULL)
4913 return -1;
4914 p = get_opt_value(NULL, 0, p);
4915 if (*p != ',')
4916 break;
4917 p++;
4918 }
4919 return 0;
4920 }
4921
4922
4923 static int net_client_init(const char *str)
4924 {
4925 const char *p;
4926 char *q;
4927 char device[64];
4928 char buf[1024];
4929 int vlan_id, ret;
4930 VLANState *vlan;
4931
4932 p = str;
4933 q = device;
4934 while (*p != '\0' && *p != ',') {
4935 if ((q - device) < sizeof(device) - 1)
4936 *q++ = *p;
4937 p++;
4938 }
4939 *q = '\0';
4940 if (*p == ',')
4941 p++;
4942 vlan_id = 0;
4943 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4944 vlan_id = strtol(buf, NULL, 0);
4945 }
4946 vlan = qemu_find_vlan(vlan_id);
4947 if (!vlan) {
4948 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4949 return -1;
4950 }
4951 if (!strcmp(device, "nic")) {
4952 NICInfo *nd;
4953 uint8_t *macaddr;
4954
4955 if (nb_nics >= MAX_NICS) {
4956 fprintf(stderr, "Too Many NICs\n");
4957 return -1;
4958 }
4959 nd = &nd_table[nb_nics];
4960 macaddr = nd->macaddr;
4961 macaddr[0] = 0x52;
4962 macaddr[1] = 0x54;
4963 macaddr[2] = 0x00;
4964 macaddr[3] = 0x12;
4965 macaddr[4] = 0x34;
4966 macaddr[5] = 0x56 + nb_nics;
4967
4968 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4969 if (parse_macaddr(macaddr, buf) < 0) {
4970 fprintf(stderr, "invalid syntax for ethernet address\n");
4971 return -1;
4972 }
4973 }
4974 if (get_param_value(buf, sizeof(buf), "model", p)) {
4975 nd->model = strdup(buf);
4976 }
4977 nd->vlan = vlan;
4978 nb_nics++;
4979 vlan->nb_guest_devs++;
4980 ret = 0;
4981 } else
4982 if (!strcmp(device, "none")) {
4983 /* does nothing. It is needed to signal that no network cards
4984 are wanted */
4985 ret = 0;
4986 } else
4987 #ifdef CONFIG_SLIRP
4988 if (!strcmp(device, "user")) {
4989 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4990 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4991 }
4992 vlan->nb_host_devs++;
4993 ret = net_slirp_init(vlan);
4994 } else
4995 #endif
4996 #ifdef _WIN32
4997 if (!strcmp(device, "tap")) {
4998 char ifname[64];
4999 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5000 fprintf(stderr, "tap: no interface name\n");
5001 return -1;
5002 }
5003 vlan->nb_host_devs++;
5004 ret = tap_win32_init(vlan, ifname);
5005 } else
5006 #else
5007 if (!strcmp(device, "tap")) {
5008 char ifname[64];
5009 char setup_script[1024], down_script[1024];
5010 int fd;
5011 vlan->nb_host_devs++;
5012 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5013 fd = strtol(buf, NULL, 0);
5014 fcntl(fd, F_SETFL, O_NONBLOCK);
5015 ret = -1;
5016 if (net_tap_fd_init(vlan, fd))
5017 ret = 0;
5018 } else {
5019 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5020 ifname[0] = '\0';
5021 }
5022 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5023 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5024 }
5025 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5026 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5027 }
5028 ret = net_tap_init(vlan, ifname, setup_script, down_script);
5029 }
5030 } else
5031 #endif
5032 if (!strcmp(device, "socket")) {
5033 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5034 int fd;
5035 fd = strtol(buf, NULL, 0);
5036 ret = -1;
5037 if (net_socket_fd_init(vlan, fd, 1))
5038 ret = 0;
5039 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5040 ret = net_socket_listen_init(vlan, buf);
5041 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5042 ret = net_socket_connect_init(vlan, buf);
5043 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5044 ret = net_socket_mcast_init(vlan, buf);
5045 } else {
5046 fprintf(stderr, "Unknown socket options: %s\n", p);
5047 return -1;
5048 }
5049 vlan->nb_host_devs++;
5050 } else
5051 {
5052 fprintf(stderr, "Unknown network device: %s\n", device);
5053 return -1;
5054 }
5055 if (ret < 0) {
5056 fprintf(stderr, "Could not initialize device '%s'\n", device);
5057 }
5058
5059 return ret;
5060 }
5061
5062 void do_info_network(void)
5063 {
5064 VLANState *vlan;
5065 VLANClientState *vc;
5066
5067 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5068 term_printf("VLAN %d devices:\n", vlan->id);
5069 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5070 term_printf(" %s\n", vc->info_str);
5071 }
5072 }
5073
5074 #define HD_ALIAS "index=%d,media=disk"
5075 #ifdef TARGET_PPC
5076 #define CDROM_ALIAS "index=1,media=cdrom"
5077 #else
5078 #define CDROM_ALIAS "index=2,media=cdrom"
5079 #endif
5080 #define FD_ALIAS "index=%d,if=floppy"
5081 #define PFLASH_ALIAS "if=pflash"
5082 #define MTD_ALIAS "if=mtd"
5083 #define SD_ALIAS "index=0,if=sd"
5084
5085 static int drive_add(const char *file, const char *fmt, ...)
5086 {
5087 va_list ap;
5088
5089 if (nb_drives_opt >= MAX_DRIVES) {
5090 fprintf(stderr, "qemu: too many drives\n");
5091 exit(1);
5092 }
5093
5094 drives_opt[nb_drives_opt].file = file;
5095 va_start(ap, fmt);
5096 vsnprintf(drives_opt[nb_drives_opt].opt,
5097 sizeof(drives_opt[0].opt), fmt, ap);
5098 va_end(ap);
5099
5100 return nb_drives_opt++;
5101 }
5102
5103 int drive_get_index(BlockInterfaceType type, int bus, int unit)
5104 {
5105 int index;
5106
5107 /* seek interface, bus and unit */
5108
5109 for (index = 0; index < nb_drives; index++)
5110 if (drives_table[index].type == type &&
5111 drives_table[index].bus == bus &&
5112 drives_table[index].unit == unit)
5113 return index;
5114
5115 return -1;
5116 }
5117
5118 int drive_get_max_bus(BlockInterfaceType type)
5119 {
5120 int max_bus;
5121 int index;
5122
5123 max_bus = -1;
5124 for (index = 0; index < nb_drives; index++) {
5125 if(drives_table[index].type == type &&
5126 drives_table[index].bus > max_bus)
5127 max_bus = drives_table[index].bus;
5128 }
5129 return max_bus;
5130 }
5131
5132 static void bdrv_format_print(void *opaque, const char *name)
5133 {
5134 fprintf(stderr, " %s", name);
5135 }
5136
5137 static int drive_init(struct drive_opt *arg, int snapshot,
5138 QEMUMachine *machine)
5139 {
5140 char buf[128];
5141 char file[1024];
5142 char devname[128];
5143 const char *mediastr = "";
5144 BlockInterfaceType type;
5145 enum { MEDIA_DISK, MEDIA_CDROM } media;
5146 int bus_id, unit_id;
5147 int cyls, heads, secs, translation;
5148 BlockDriverState *bdrv;
5149 BlockDriver *drv = NULL;
5150 int max_devs;
5151 int index;
5152 int cache;
5153 int bdrv_flags;
5154 char *str = arg->opt;
5155 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5156 "secs", "trans", "media", "snapshot", "file",
5157 "cache", "format", NULL };
5158
5159 if (check_params(buf, sizeof(buf), params, str) < 0) {
5160 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5161 buf, str);
5162 return -1;
5163 }
5164
5165 file[0] = 0;
5166 cyls = heads = secs = 0;
5167 bus_id = 0;
5168 unit_id = -1;
5169 translation = BIOS_ATA_TRANSLATION_AUTO;
5170 index = -1;
5171 cache = 1;
5172
5173 if (!strcmp(machine->name, "realview") ||
5174 !strcmp(machine->name, "SS-5") ||
5175 !strcmp(machine->name, "SS-10") ||
5176 !strcmp(machine->name, "SS-600MP") ||
5177 !strcmp(machine->name, "versatilepb") ||
5178 !strcmp(machine->name, "versatileab")) {
5179 type = IF_SCSI;
5180 max_devs = MAX_SCSI_DEVS;
5181 strcpy(devname, "scsi");
5182 } else {
5183 type = IF_IDE;
5184 max_devs = MAX_IDE_DEVS;
5185 strcpy(devname, "ide");
5186 }
5187 media = MEDIA_DISK;
5188
5189 /* extract parameters */
5190
5191 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5192 bus_id = strtol(buf, NULL, 0);
5193 if (bus_id < 0) {
5194 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5195 return -1;
5196 }
5197 }
5198
5199 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5200 unit_id = strtol(buf, NULL, 0);
5201 if (unit_id < 0) {
5202 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5203 return -1;
5204 }
5205 }
5206
5207 if (get_param_value(buf, sizeof(buf), "if", str)) {
5208 pstrcpy(devname, sizeof(devname), buf);
5209 if (!strcmp(buf, "ide")) {
5210 type = IF_IDE;
5211 max_devs = MAX_IDE_DEVS;
5212 } else if (!strcmp(buf, "scsi")) {
5213 type = IF_SCSI;
5214 max_devs = MAX_SCSI_DEVS;
5215 } else if (!strcmp(buf, "floppy")) {
5216 type = IF_FLOPPY;
5217 max_devs = 0;
5218 } else if (!strcmp(buf, "pflash")) {
5219 type = IF_PFLASH;
5220 max_devs = 0;
5221 } else if (!strcmp(buf, "mtd")) {
5222 type = IF_MTD;
5223 max_devs = 0;
5224 } else if (!strcmp(buf, "sd")) {
5225 type = IF_SD;
5226 max_devs = 0;
5227 } else {
5228 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5229 return -1;
5230 }
5231 }
5232
5233 if (get_param_value(buf, sizeof(buf), "index", str)) {
5234 index = strtol(buf, NULL, 0);
5235 if (index < 0) {
5236 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5237 return -1;
5238 }
5239 }
5240
5241 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5242 cyls = strtol(buf, NULL, 0);
5243 }
5244
5245 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5246 heads = strtol(buf, NULL, 0);
5247 }
5248
5249 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5250 secs = strtol(buf, NULL, 0);
5251 }
5252
5253 if (cyls || heads || secs) {
5254 if (cyls < 1 || cyls > 16383) {
5255 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5256 return -1;
5257 }
5258 if (heads < 1 || heads > 16) {
5259 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5260 return -1;
5261 }
5262 if (secs < 1 || secs > 63) {
5263 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5264 return -1;
5265 }
5266 }
5267
5268 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5269 if (!cyls) {
5270 fprintf(stderr,
5271 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5272 str);
5273 return -1;
5274 }
5275 if (!strcmp(buf, "none"))
5276 translation = BIOS_ATA_TRANSLATION_NONE;
5277 else if (!strcmp(buf, "lba"))
5278 translation = BIOS_ATA_TRANSLATION_LBA;
5279 else if (!strcmp(buf, "auto"))
5280 translation = BIOS_ATA_TRANSLATION_AUTO;
5281 else {
5282 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5283 return -1;
5284 }
5285 }
5286
5287 if (get_param_value(buf, sizeof(buf), "media", str)) {
5288 if (!strcmp(buf, "disk")) {
5289 media = MEDIA_DISK;
5290 } else if (!strcmp(buf, "cdrom")) {
5291 if (cyls || secs || heads) {
5292 fprintf(stderr,
5293 "qemu: '%s' invalid physical CHS format\n", str);
5294 return -1;
5295 }
5296 media = MEDIA_CDROM;
5297 } else {
5298 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5299 return -1;
5300 }
5301 }
5302
5303 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5304 if (!strcmp(buf, "on"))
5305 snapshot = 1;
5306 else if (!strcmp(buf, "off"))
5307 snapshot = 0;
5308 else {
5309 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5310 return -1;
5311 }
5312 }
5313
5314 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5315 if (!strcmp(buf, "off"))
5316 cache = 0;
5317 else if (!strcmp(buf, "on"))
5318 cache = 1;
5319 else {
5320 fprintf(stderr, "qemu: invalid cache option\n");
5321 return -1;
5322 }
5323 }
5324
5325 if (get_param_value(buf, sizeof(buf), "format", str)) {
5326 if (strcmp(buf, "?") == 0) {
5327 fprintf(stderr, "qemu: Supported formats:");
5328 bdrv_iterate_format(bdrv_format_print, NULL);
5329 fprintf(stderr, "\n");
5330 return -1;
5331 }
5332 drv = bdrv_find_format(buf);
5333 if (!drv) {
5334 fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5335 return -1;
5336 }
5337 }
5338
5339 if (arg->file == NULL)
5340 get_param_value(file, sizeof(file), "file", str);
5341 else
5342 pstrcpy(file, sizeof(file), arg->file);
5343
5344 /* compute bus and unit according index */
5345
5346 if (index != -1) {
5347 if (bus_id != 0 || unit_id != -1) {
5348 fprintf(stderr,
5349 "qemu: '%s' index cannot be used with bus and unit\n", str);
5350 return -1;
5351 }
5352 if (max_devs == 0)
5353 {
5354 unit_id = index;
5355 bus_id = 0;
5356 } else {
5357 unit_id = index % max_devs;
5358 bus_id = index / max_devs;
5359 }
5360 }
5361
5362 /* if user doesn't specify a unit_id,
5363 * try to find the first free
5364 */
5365
5366 if (unit_id == -1) {
5367 unit_id = 0;
5368 while (drive_get_index(type, bus_id, unit_id) != -1) {
5369 unit_id++;
5370 if (max_devs && unit_id >= max_devs) {
5371 unit_id -= max_devs;
5372 bus_id++;
5373 }
5374 }
5375 }
5376
5377 /* check unit id */
5378
5379 if (max_devs && unit_id >= max_devs) {
5380 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5381 str, unit_id, max_devs - 1);
5382 return -1;
5383 }
5384
5385 /*
5386 * ignore multiple definitions
5387 */
5388
5389 if (drive_get_index(type, bus_id, unit_id) != -1)
5390 return 0;
5391
5392 /* init */
5393
5394 if (type == IF_IDE || type == IF_SCSI)
5395 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5396 if (max_devs)
5397 snprintf(buf, sizeof(buf), "%s%i%s%i",
5398 devname, bus_id, mediastr, unit_id);
5399 else
5400 snprintf(buf, sizeof(buf), "%s%s%i",
5401 devname, mediastr, unit_id);
5402 bdrv = bdrv_new(buf);
5403 drives_table[nb_drives].bdrv = bdrv;
5404 drives_table[nb_drives].type = type;
5405 drives_table[nb_drives].bus = bus_id;
5406 drives_table[nb_drives].unit = unit_id;
5407 nb_drives++;
5408
5409 switch(type) {
5410 case IF_IDE:
5411 case IF_SCSI:
5412 switch(media) {
5413 case MEDIA_DISK:
5414 if (cyls != 0) {
5415 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5416 bdrv_set_translation_hint(bdrv, translation);
5417 }
5418 break;
5419 case MEDIA_CDROM:
5420 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5421 break;
5422 }
5423 break;
5424 case IF_SD:
5425 /* FIXME: This isn't really a floppy, but it's a reasonable
5426 approximation. */
5427 case IF_FLOPPY:
5428 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5429 break;
5430 case IF_PFLASH:
5431 case IF_MTD:
5432 break;
5433 }
5434 if (!file[0])
5435 return 0;
5436 bdrv_flags = 0;
5437 if (snapshot)
5438 bdrv_flags |= BDRV_O_SNAPSHOT;
5439 if (!cache)
5440 bdrv_flags |= BDRV_O_DIRECT;
5441 if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5442 fprintf(stderr, "qemu: could not open disk image %s\n",
5443 file);
5444 return -1;
5445 }
5446 return 0;
5447 }
5448
5449 /***********************************************************/
5450 /* USB devices */
5451
5452 static USBPort *used_usb_ports;
5453 static USBPort *free_usb_ports;
5454
5455 /* ??? Maybe change this to register a hub to keep track of the topology. */
5456 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5457 usb_attachfn attach)
5458 {
5459 port->opaque = opaque;
5460 port->index = index;
5461 port->attach = attach;
5462 port->next = free_usb_ports;
5463 free_usb_ports = port;
5464 }
5465
5466 static int usb_device_add(const char *devname)
5467 {
5468 const char *p;
5469 USBDevice *dev;
5470 USBPort *port;
5471
5472 if (!free_usb_ports)
5473 return -1;
5474
5475 if (strstart(devname, "host:", &p)) {
5476 dev = usb_host_device_open(p);
5477 } else if (!strcmp(devname, "mouse")) {
5478 dev = usb_mouse_init();
5479 } else if (!strcmp(devname, "tablet")) {
5480 dev = usb_tablet_init();
5481 } else if (!strcmp(devname, "keyboard")) {
5482 dev = usb_keyboard_init();
5483 } else if (strstart(devname, "disk:", &p)) {
5484 dev = usb_msd_init(p);
5485 } else if (!strcmp(devname, "wacom-tablet")) {
5486 dev = usb_wacom_init();
5487 } else if (strstart(devname, "serial:", &p)) {
5488 dev = usb_serial_init(p);
5489 #ifdef CONFIG_BRLAPI
5490 } else if (!strcmp(devname, "braille")) {
5491 dev = usb_baum_init();
5492 #endif
5493 } else if (strstart(devname, "net:", &p)) {
5494 int nicidx = strtoul(p, NULL, 0);
5495
5496 if (nicidx >= nb_nics || strcmp(nd_table[nicidx].model, "usb"))
5497 return -1;
5498 dev = usb_net_init(&nd_table[nicidx]);
5499 } else {
5500 return -1;
5501 }
5502 if (!dev)
5503 return -1;
5504
5505 /* Find a USB port to add the device to. */
5506 port = free_usb_ports;
5507 if (!port->next) {
5508 USBDevice *hub;
5509
5510 /* Create a new hub and chain it on. */
5511 free_usb_ports = NULL;
5512 port->next = used_usb_ports;
5513 used_usb_ports = port;
5514
5515 hub = usb_hub_init(VM_USB_HUB_SIZE);
5516 usb_attach(port, hub);
5517 port = free_usb_ports;
5518 }
5519
5520 free_usb_ports = port->next;
5521 port->next = used_usb_ports;
5522 used_usb_ports = port;
5523 usb_attach(port, dev);
5524 return 0;
5525 }
5526
5527 static int usb_device_del(const char *devname)
5528 {
5529 USBPort *port;
5530 USBPort **lastp;
5531 USBDevice *dev;
5532 int bus_num, addr;
5533 const char *p;
5534
5535 if (!used_usb_ports)
5536 return -1;
5537
5538 p = strchr(devname, '.');
5539 if (!p)
5540 return -1;
5541 bus_num = strtoul(devname, NULL, 0);
5542 addr = strtoul(p + 1, NULL, 0);
5543 if (bus_num != 0)
5544 return -1;
5545
5546 lastp = &used_usb_ports;
5547 port = used_usb_ports;
5548 while (port && port->dev->addr != addr) {
5549 lastp = &port->next;
5550 port = port->next;
5551 }
5552
5553 if (!port)
5554 return -1;
5555
5556 dev = port->dev;
5557 *lastp = port->next;
5558 usb_attach(port, NULL);
5559 dev->handle_destroy(dev);
5560 port->next = free_usb_ports;
5561 free_usb_ports = port;
5562 return 0;
5563 }
5564
5565 void do_usb_add(const char *devname)
5566 {
5567 int ret;
5568 ret = usb_device_add(devname);
5569 if (ret < 0)
5570 term_printf("Could not add USB device '%s'\n", devname);
5571 }
5572
5573 void do_usb_del(const char *devname)
5574 {
5575 int ret;
5576 ret = usb_device_del(devname);
5577 if (ret < 0)
5578 term_printf("Could not remove USB device '%s'\n", devname);
5579 }
5580
5581 void usb_info(void)
5582 {
5583 USBDevice *dev;
5584 USBPort *port;
5585 const char *speed_str;
5586
5587 if (!usb_enabled) {
5588 term_printf("USB support not enabled\n");
5589 return;
5590 }
5591
5592 for (port = used_usb_ports; port; port = port->next) {
5593 dev = port->dev;
5594 if (!dev)
5595 continue;
5596 switch(dev->speed) {
5597 case USB_SPEED_LOW:
5598 speed_str = "1.5";
5599 break;
5600 case USB_SPEED_FULL:
5601 speed_str = "12";
5602 break;
5603 case USB_SPEED_HIGH:
5604 speed_str = "480";
5605 break;
5606 default:
5607 speed_str = "?";
5608 break;
5609 }
5610 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5611 0, dev->addr, speed_str, dev->devname);
5612 }
5613 }
5614
5615 /***********************************************************/
5616 /* PCMCIA/Cardbus */
5617
5618 static struct pcmcia_socket_entry_s {
5619 struct pcmcia_socket_s *socket;
5620 struct pcmcia_socket_entry_s *next;
5621 } *pcmcia_sockets = 0;
5622
5623 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5624 {
5625 struct pcmcia_socket_entry_s *entry;
5626
5627 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5628 entry->socket = socket;
5629 entry->next = pcmcia_sockets;
5630 pcmcia_sockets = entry;
5631 }
5632
5633 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5634 {
5635 struct pcmcia_socket_entry_s *entry, **ptr;
5636
5637 ptr = &pcmcia_sockets;
5638 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5639 if (entry->socket == socket) {
5640 *ptr = entry->next;
5641 qemu_free(entry);
5642 }
5643 }
5644
5645 void pcmcia_info(void)
5646 {
5647 struct pcmcia_socket_entry_s *iter;
5648 if (!pcmcia_sockets)
5649 term_printf("No PCMCIA sockets\n");
5650
5651 for (iter = pcmcia_sockets; iter; iter = iter->next)
5652 term_printf("%s: %s\n", iter->socket->slot_string,
5653 iter->socket->attached ? iter->socket->card_string :
5654 "Empty");
5655 }
5656
5657 /***********************************************************/
5658 /* dumb display */
5659
5660 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5661 {
5662 }
5663
5664 static void dumb_resize(DisplayState *ds, int w, int h)
5665 {
5666 }
5667
5668 static void dumb_refresh(DisplayState *ds)
5669 {
5670 #if defined(CONFIG_SDL)
5671 vga_hw_update();
5672 #endif
5673 }
5674
5675 static void dumb_display_init(DisplayState *ds)
5676 {
5677 ds->data = NULL;
5678 ds->linesize = 0;
5679 ds->depth = 0;
5680 ds->dpy_update = dumb_update;
5681 ds->dpy_resize = dumb_resize;
5682 ds->dpy_refresh = dumb_refresh;
5683 }
5684
5685 /***********************************************************/
5686 /* I/O handling */
5687
5688 #define MAX_IO_HANDLERS 64
5689
5690 typedef struct IOHandlerRecord {
5691 int fd;
5692 IOCanRWHandler *fd_read_poll;
5693 IOHandler *fd_read;
5694 IOHandler *fd_write;
5695 int deleted;
5696 void *opaque;
5697 /* temporary data */
5698 struct pollfd *ufd;
5699 struct IOHandlerRecord *next;
5700 } IOHandlerRecord;
5701
5702 static IOHandlerRecord *first_io_handler;
5703
5704 /* XXX: fd_read_poll should be suppressed, but an API change is
5705 necessary in the character devices to suppress fd_can_read(). */
5706 int qemu_set_fd_handler2(int fd,
5707 IOCanRWHandler *fd_read_poll,
5708 IOHandler *fd_read,
5709 IOHandler *fd_write,
5710 void *opaque)
5711 {
5712 IOHandlerRecord **pioh, *ioh;
5713
5714 if (!fd_read && !fd_write) {
5715 pioh = &first_io_handler;
5716 for(;;) {
5717 ioh = *pioh;
5718 if (ioh == NULL)
5719 break;
5720 if (ioh->fd == fd) {
5721 ioh->deleted = 1;
5722 break;
5723 }
5724 pioh = &ioh->next;
5725 }
5726 } else {
5727 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5728 if (ioh->fd == fd)
5729 goto found;
5730 }
5731 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5732 if (!ioh)
5733 return -1;
5734 ioh->next = first_io_handler;
5735 first_io_handler = ioh;
5736 found:
5737 ioh->fd = fd;
5738 ioh->fd_read_poll = fd_read_poll;
5739 ioh->fd_read = fd_read;
5740 ioh->fd_write = fd_write;
5741 ioh->opaque = opaque;
5742 ioh->deleted = 0;
5743 }
5744 return 0;
5745 }
5746
5747 int qemu_set_fd_handler(int fd,
5748 IOHandler *fd_read,
5749 IOHandler *fd_write,
5750 void *opaque)
5751 {
5752 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5753 }
5754
5755 /***********************************************************/
5756 /* Polling handling */
5757
5758 typedef struct PollingEntry {
5759 PollingFunc *func;
5760 void *opaque;
5761 struct PollingEntry *next;
5762 } PollingEntry;
5763
5764 static PollingEntry *first_polling_entry;
5765
5766 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5767 {
5768 PollingEntry **ppe, *pe;
5769 pe = qemu_mallocz(sizeof(PollingEntry));
5770 if (!pe)
5771 return -1;
5772 pe->func = func;
5773 pe->opaque = opaque;
5774 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5775 *ppe = pe;
5776 return 0;
5777 }
5778
5779 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5780 {
5781 PollingEntry **ppe, *pe;
5782 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5783 pe = *ppe;
5784 if (pe->func == func && pe->opaque == opaque) {
5785 *ppe = pe->next;
5786 qemu_free(pe);
5787 break;
5788 }
5789 }
5790 }
5791
5792 #ifdef _WIN32
5793 /***********************************************************/
5794 /* Wait objects support */
5795 typedef struct WaitObjects {
5796 int num;
5797 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5798 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5799 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5800 } WaitObjects;
5801
5802 static WaitObjects wait_objects = {0};
5803
5804 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5805 {
5806 WaitObjects *w = &wait_objects;
5807
5808 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5809 return -1;
5810 w->events[w->num] = handle;
5811 w->func[w->num] = func;
5812 w->opaque[w->num] = opaque;
5813 w->num++;
5814 return 0;
5815 }
5816
5817 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5818 {
5819 int i, found;
5820 WaitObjects *w = &wait_objects;
5821
5822 found = 0;
5823 for (i = 0; i < w->num; i++) {
5824 if (w->events[i] == handle)
5825 found = 1;
5826 if (found) {
5827 w->events[i] = w->events[i + 1];
5828 w->func[i] = w->func[i + 1];
5829 w->opaque[i] = w->opaque[i + 1];
5830 }
5831 }
5832 if (found)
5833 w->num--;
5834 }
5835 #endif
5836
5837 /***********************************************************/
5838 /* savevm/loadvm support */
5839
5840 #define IO_BUF_SIZE 32768
5841
5842 struct QEMUFile {
5843 FILE *outfile;
5844 BlockDriverState *bs;
5845 int is_file;
5846 int is_writable;
5847 int64_t base_offset;
5848 int64_t buf_offset; /* start of buffer when writing, end of buffer
5849 when reading */
5850 int buf_index;
5851 int buf_size; /* 0 when writing */
5852 uint8_t buf[IO_BUF_SIZE];
5853 };
5854
5855 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5856 {
5857 QEMUFile *f;
5858
5859 f = qemu_mallocz(sizeof(QEMUFile));
5860 if (!f)
5861 return NULL;
5862 if (!strcmp(mode, "wb")) {
5863 f->is_writable = 1;
5864 } else if (!strcmp(mode, "rb")) {
5865 f->is_writable = 0;
5866 } else {
5867 goto fail;
5868 }
5869 f->outfile = fopen(filename, mode);
5870 if (!f->outfile)
5871 goto fail;
5872 f->is_file = 1;
5873 return f;
5874 fail:
5875 if (f->outfile)
5876 fclose(f->outfile);
5877 qemu_free(f);
5878 return NULL;
5879 }
5880
5881 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5882 {
5883 QEMUFile *f;
5884
5885 f = qemu_mallocz(sizeof(QEMUFile));
5886 if (!f)
5887 return NULL;
5888 f->is_file = 0;
5889 f->bs = bs;
5890 f->is_writable = is_writable;
5891 f->base_offset = offset;
5892 return f;
5893 }
5894
5895 void qemu_fflush(QEMUFile *f)
5896 {
5897 if (!f->is_writable)
5898 return;
5899 if (f->buf_index > 0) {
5900 if (f->is_file) {
5901 fseek(f->outfile, f->buf_offset, SEEK_SET);
5902 fwrite(f->buf, 1, f->buf_index, f->outfile);
5903 } else {
5904 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5905 f->buf, f->buf_index);
5906 }
5907 f->buf_offset += f->buf_index;
5908 f->buf_index = 0;
5909 }
5910 }
5911
5912 static void qemu_fill_buffer(QEMUFile *f)
5913 {
5914 int len;
5915
5916 if (f->is_writable)
5917 return;
5918 if (f->is_file) {
5919 fseek(f->outfile, f->buf_offset, SEEK_SET);
5920 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5921 if (len < 0)
5922 len = 0;
5923 } else {
5924 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5925 f->buf, IO_BUF_SIZE);
5926 if (len < 0)
5927 len = 0;
5928 }
5929 f->buf_index = 0;
5930 f->buf_size = len;
5931 f->buf_offset += len;
5932 }
5933
5934 void qemu_fclose(QEMUFile *f)
5935 {
5936 if (f->is_writable)
5937 qemu_fflush(f);
5938 if (f->is_file) {
5939 fclose(f->outfile);
5940 }
5941 qemu_free(f);
5942 }
5943
5944 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5945 {
5946 int l;
5947 while (size > 0) {
5948 l = IO_BUF_SIZE - f->buf_index;
5949 if (l > size)
5950 l = size;
5951 memcpy(f->buf + f->buf_index, buf, l);
5952 f->buf_index += l;
5953 buf += l;
5954 size -= l;
5955 if (f->buf_index >= IO_BUF_SIZE)
5956 qemu_fflush(f);
5957 }
5958 }
5959
5960 void qemu_put_byte(QEMUFile *f, int v)
5961 {
5962 f->buf[f->buf_index++] = v;
5963 if (f->buf_index >= IO_BUF_SIZE)
5964 qemu_fflush(f);
5965 }
5966
5967 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5968 {
5969 int size, l;
5970
5971 size = size1;
5972 while (size > 0) {
5973 l = f->buf_size - f->buf_index;
5974 if (l == 0) {
5975 qemu_fill_buffer(f);
5976 l = f->buf_size - f->buf_index;
5977 if (l == 0)
5978 break;
5979 }
5980 if (l > size)
5981 l = size;
5982 memcpy(buf, f->buf + f->buf_index, l);
5983 f->buf_index += l;
5984 buf += l;
5985 size -= l;
5986 }
5987 return size1 - size;
5988 }
5989
5990 int qemu_get_byte(QEMUFile *f)
5991 {
5992 if (f->buf_index >= f->buf_size) {
5993 qemu_fill_buffer(f);
5994 if (f->buf_index >= f->buf_size)
5995 return 0;
5996 }
5997 return f->buf[f->buf_index++];
5998 }
5999
6000 int64_t qemu_ftell(QEMUFile *f)
6001 {
6002 return f->buf_offset - f->buf_size + f->buf_index;
6003 }
6004
6005 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6006 {
6007 if (whence == SEEK_SET) {
6008 /* nothing to do */
6009 } else if (whence == SEEK_CUR) {
6010 pos += qemu_ftell(f);
6011 } else {
6012 /* SEEK_END not supported */
6013 return -1;
6014 }
6015 if (f->is_writable) {
6016 qemu_fflush(f);
6017 f->buf_offset = pos;
6018 } else {
6019 f->buf_offset = pos;
6020 f->buf_index = 0;
6021 f->buf_size = 0;
6022 }
6023 return pos;
6024 }
6025
6026 void qemu_put_be16(QEMUFile *f, unsigned int v)
6027 {
6028 qemu_put_byte(f, v >> 8);
6029 qemu_put_byte(f, v);
6030 }
6031
6032 void qemu_put_be32(QEMUFile *f, unsigned int v)
6033 {
6034 qemu_put_byte(f, v >> 24);
6035 qemu_put_byte(f, v >> 16);
6036 qemu_put_byte(f, v >> 8);
6037 qemu_put_byte(f, v);
6038 }
6039
6040 void qemu_put_be64(QEMUFile *f, uint64_t v)
6041 {
6042 qemu_put_be32(f, v >> 32);
6043 qemu_put_be32(f, v);
6044 }
6045
6046 unsigned int qemu_get_be16(QEMUFile *f)
6047 {
6048 unsigned int v;
6049 v = qemu_get_byte(f) << 8;
6050 v |= qemu_get_byte(f);
6051 return v;
6052 }
6053
6054 unsigned int qemu_get_be32(QEMUFile *f)
6055 {
6056 unsigned int v;
6057 v = qemu_get_byte(f) << 24;
6058 v |= qemu_get_byte(f) << 16;
6059 v |= qemu_get_byte(f) << 8;
6060 v |= qemu_get_byte(f);
6061 return v;
6062 }
6063
6064 uint64_t qemu_get_be64(QEMUFile *f)
6065 {
6066 uint64_t v;
6067 v = (uint64_t)qemu_get_be32(f) << 32;
6068 v |= qemu_get_be32(f);
6069 return v;
6070 }
6071
6072 typedef struct SaveStateEntry {
6073 char idstr[256];
6074 int instance_id;
6075 int version_id;
6076 SaveStateHandler *save_state;
6077 LoadStateHandler *load_state;
6078 void *opaque;
6079 struct SaveStateEntry *next;
6080 } SaveStateEntry;
6081
6082 static SaveStateEntry *first_se;
6083
6084 /* TODO: Individual devices generally have very little idea about the rest
6085 of the system, so instance_id should be removed/replaced. */
6086 int register_savevm(const char *idstr,
6087 int instance_id,
6088 int version_id,
6089 SaveStateHandler *save_state,
6090 LoadStateHandler *load_state,
6091 void *opaque)
6092 {
6093 SaveStateEntry *se, **pse;
6094
6095 se = qemu_malloc(sizeof(SaveStateEntry));
6096 if (!se)
6097 return -1;
6098 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6099 se->instance_id = (instance_id == -1) ? 0 : instance_id;
6100 se->version_id = version_id;
6101 se->save_state = save_state;
6102 se->load_state = load_state;
6103 se->opaque = opaque;
6104 se->next = NULL;
6105
6106 /* add at the end of list */
6107 pse = &first_se;
6108 while (*pse != NULL) {
6109 if (instance_id == -1
6110 && strcmp(se->idstr, (*pse)->idstr) == 0
6111 && se->instance_id <= (*pse)->instance_id)
6112 se->instance_id = (*pse)->instance_id + 1;
6113 pse = &(*pse)->next;
6114 }
6115 *pse = se;
6116 return 0;
6117 }
6118
6119 #define QEMU_VM_FILE_MAGIC 0x5145564d
6120 #define QEMU_VM_FILE_VERSION 0x00000002
6121
6122 static int qemu_savevm_state(QEMUFile *f)
6123 {
6124 SaveStateEntry *se;
6125 int len, ret;
6126 int64_t cur_pos, len_pos, total_len_pos;
6127
6128 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6129 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6130 total_len_pos = qemu_ftell(f);
6131 qemu_put_be64(f, 0); /* total size */
6132
6133 for(se = first_se; se != NULL; se = se->next) {
6134 if (se->save_state == NULL)
6135 /* this one has a loader only, for backwards compatibility */
6136 continue;
6137
6138 /* ID string */
6139 len = strlen(se->idstr);
6140 qemu_put_byte(f, len);
6141 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6142
6143 qemu_put_be32(f, se->instance_id);
6144 qemu_put_be32(f, se->version_id);
6145
6146 /* record size: filled later */
6147 len_pos = qemu_ftell(f);
6148 qemu_put_be32(f, 0);
6149 se->save_state(f, se->opaque);
6150
6151 /* fill record size */
6152 cur_pos = qemu_ftell(f);
6153 len = cur_pos - len_pos - 4;
6154 qemu_fseek(f, len_pos, SEEK_SET);
6155 qemu_put_be32(f, len);
6156 qemu_fseek(f, cur_pos, SEEK_SET);
6157 }
6158 cur_pos = qemu_ftell(f);
6159 qemu_fseek(f, total_len_pos, SEEK_SET);
6160 qemu_put_be64(f, cur_pos - total_len_pos - 8);
6161 qemu_fseek(f, cur_pos, SEEK_SET);
6162
6163 ret = 0;
6164 return ret;
6165 }
6166
6167 static SaveStateEntry *find_se(const char *idstr, int instance_id)
6168 {
6169 SaveStateEntry *se;
6170
6171 for(se = first_se; se != NULL; se = se->next) {
6172 if (!strcmp(se->idstr, idstr) &&
6173 instance_id == se->instance_id)
6174 return se;
6175 }
6176 return NULL;
6177 }
6178
6179 static int qemu_loadvm_state(QEMUFile *f)
6180 {
6181 SaveStateEntry *se;
6182 int len, ret, instance_id, record_len, version_id;
6183 int64_t total_len, end_pos, cur_pos;
6184 unsigned int v;
6185 char idstr[256];
6186
6187 v = qemu_get_be32(f);
6188 if (v != QEMU_VM_FILE_MAGIC)
6189 goto fail;
6190 v = qemu_get_be32(f);
6191 if (v != QEMU_VM_FILE_VERSION) {
6192 fail:
6193 ret = -1;
6194 goto the_end;
6195 }
6196 total_len = qemu_get_be64(f);
6197 end_pos = total_len + qemu_ftell(f);
6198 for(;;) {
6199 if (qemu_ftell(f) >= end_pos)
6200 break;
6201 len = qemu_get_byte(f);
6202 qemu_get_buffer(f, (uint8_t *)idstr, len);
6203 idstr[len] = '\0';
6204 instance_id = qemu_get_be32(f);
6205 version_id = qemu_get_be32(f);
6206 record_len = qemu_get_be32(f);
6207 #if 0
6208 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6209 idstr, instance_id, version_id, record_len);
6210 #endif
6211 cur_pos = qemu_ftell(f);
6212 se = find_se(idstr, instance_id);
6213 if (!se) {
6214 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6215 instance_id, idstr);
6216 } else {
6217 ret = se->load_state(f, se->opaque, version_id);
6218 if (ret < 0) {
6219 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6220 instance_id, idstr);
6221 }
6222 }
6223 /* always seek to exact end of record */
6224 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6225 }
6226 ret = 0;
6227 the_end:
6228 return ret;
6229 }
6230
6231 /* device can contain snapshots */
6232 static int bdrv_can_snapshot(BlockDriverState *bs)
6233 {
6234 return (bs &&
6235 !bdrv_is_removable(bs) &&
6236 !bdrv_is_read_only(bs));
6237 }
6238
6239 /* device must be snapshots in order to have a reliable snapshot */
6240 static int bdrv_has_snapshot(BlockDriverState *bs)
6241 {
6242 return (bs &&
6243 !bdrv_is_removable(bs) &&
6244 !bdrv_is_read_only(bs));
6245 }
6246
6247 static BlockDriverState *get_bs_snapshots(void)
6248 {
6249 BlockDriverState *bs;
6250 int i;
6251
6252 if (bs_snapshots)
6253 return bs_snapshots;
6254 for(i = 0; i <= nb_drives; i++) {
6255 bs = drives_table[i].bdrv;
6256 if (bdrv_can_snapshot(bs))
6257 goto ok;
6258 }
6259 return NULL;
6260 ok:
6261 bs_snapshots = bs;
6262 return bs;
6263 }
6264
6265 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6266 const char *name)
6267 {
6268 QEMUSnapshotInfo *sn_tab, *sn;
6269 int nb_sns, i, ret;
6270
6271 ret = -ENOENT;
6272 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6273 if (nb_sns < 0)
6274 return ret;
6275 for(i = 0; i < nb_sns; i++) {
6276 sn = &sn_tab[i];
6277 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6278 *sn_info = *sn;
6279 ret = 0;
6280 break;
6281 }
6282 }
6283 qemu_free(sn_tab);
6284 return ret;
6285 }
6286
6287 void do_savevm(const char *name)
6288 {
6289 BlockDriverState *bs, *bs1;
6290 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6291 int must_delete, ret, i;
6292 BlockDriverInfo bdi1, *bdi = &bdi1;
6293 QEMUFile *f;
6294 int saved_vm_running;
6295 #ifdef _WIN32
6296 struct _timeb tb;
6297 #else
6298 struct timeval tv;
6299 #endif
6300
6301 bs = get_bs_snapshots();
6302 if (!bs) {
6303 term_printf("No block device can accept snapshots\n");
6304 return;
6305 }
6306
6307 /* ??? Should this occur after vm_stop? */
6308 qemu_aio_flush();
6309
6310 saved_vm_running = vm_running;
6311 vm_stop(0);
6312
6313 must_delete = 0;
6314 if (name) {
6315 ret = bdrv_snapshot_find(bs, old_sn, name);
6316 if (ret >= 0) {
6317 must_delete = 1;
6318 }
6319 }
6320 memset(sn, 0, sizeof(*sn));
6321 if (must_delete) {
6322 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6323 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6324 } else {
6325 if (name)
6326 pstrcpy(sn->name, sizeof(sn->name), name);
6327 }
6328
6329 /* fill auxiliary fields */
6330 #ifdef _WIN32
6331 _ftime(&tb);
6332 sn->date_sec = tb.time;
6333 sn->date_nsec = tb.millitm * 1000000;
6334 #else
6335 gettimeofday(&tv, NULL);
6336 sn->date_sec = tv.tv_sec;
6337 sn->date_nsec = tv.tv_usec * 1000;
6338 #endif
6339 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6340
6341 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6342 term_printf("Device %s does not support VM state snapshots\n",
6343 bdrv_get_device_name(bs));
6344 goto the_end;
6345 }
6346
6347 /* save the VM state */
6348 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6349 if (!f) {
6350 term_printf("Could not open VM state file\n");
6351 goto the_end;
6352 }
6353 ret = qemu_savevm_state(f);
6354 sn->vm_state_size = qemu_ftell(f);
6355 qemu_fclose(f);
6356 if (ret < 0) {
6357 term_printf("Error %d while writing VM\n", ret);
6358 goto the_end;
6359 }
6360
6361 /* create the snapshots */
6362
6363 for(i = 0; i < nb_drives; i++) {
6364 bs1 = drives_table[i].bdrv;
6365 if (bdrv_has_snapshot(bs1)) {
6366 if (must_delete) {
6367 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6368 if (ret < 0) {
6369 term_printf("Error while deleting snapshot on '%s'\n",
6370 bdrv_get_device_name(bs1));
6371 }
6372 }
6373 ret = bdrv_snapshot_create(bs1, sn);
6374 if (ret < 0) {
6375 term_printf("Error while creating snapshot on '%s'\n",
6376 bdrv_get_device_name(bs1));
6377 }
6378 }
6379 }
6380
6381 the_end:
6382 if (saved_vm_running)
6383 vm_start();
6384 }
6385
6386 void do_loadvm(const char *name)
6387 {
6388 BlockDriverState *bs, *bs1;
6389 BlockDriverInfo bdi1, *bdi = &bdi1;
6390 QEMUFile *f;
6391 int i, ret;
6392 int saved_vm_running;
6393
6394 bs = get_bs_snapshots();
6395 if (!bs) {
6396 term_printf("No block device supports snapshots\n");
6397 return;
6398 }
6399
6400 /* Flush all IO requests so they don't interfere with the new state. */
6401 qemu_aio_flush();
6402
6403 saved_vm_running = vm_running;
6404 vm_stop(0);
6405
6406 for(i = 0; i <= nb_drives; i++) {
6407 bs1 = drives_table[i].bdrv;
6408 if (bdrv_has_snapshot(bs1)) {
6409 ret = bdrv_snapshot_goto(bs1, name);
6410 if (ret < 0) {
6411 if (bs != bs1)
6412 term_printf("Warning: ");
6413 switch(ret) {
6414 case -ENOTSUP:
6415 term_printf("Snapshots not supported on device '%s'\n",
6416 bdrv_get_device_name(bs1));
6417 break;
6418 case -ENOENT:
6419 term_printf("Could not find snapshot '%s' on device '%s'\n",
6420 name, bdrv_get_device_name(bs1));
6421 break;
6422 default:
6423 term_printf("Error %d while activating snapshot on '%s'\n",
6424 ret, bdrv_get_device_name(bs1));
6425 break;
6426 }
6427 /* fatal on snapshot block device */
6428 if (bs == bs1)
6429 goto the_end;
6430 }
6431 }
6432 }
6433
6434 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6435 term_printf("Device %s does not support VM state snapshots\n",
6436 bdrv_get_device_name(bs));
6437 return;
6438 }
6439
6440 /* restore the VM state */
6441 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6442 if (!f) {
6443 term_printf("Could not open VM state file\n");
6444 goto the_end;
6445 }
6446 ret = qemu_loadvm_state(f);
6447 qemu_fclose(f);
6448 if (ret < 0) {
6449 term_printf("Error %d while loading VM state\n", ret);
6450 }
6451 the_end:
6452 if (saved_vm_running)
6453 vm_start();
6454 }
6455
6456 void do_delvm(const char *name)
6457 {
6458 BlockDriverState *bs, *bs1;
6459 int i, ret;
6460
6461 bs = get_bs_snapshots();
6462 if (!bs) {
6463 term_printf("No block device supports snapshots\n");
6464 return;
6465 }
6466
6467 for(i = 0; i <= nb_drives; i++) {
6468 bs1 = drives_table[i].bdrv;
6469 if (bdrv_has_snapshot(bs1)) {
6470 ret = bdrv_snapshot_delete(bs1, name);
6471 if (ret < 0) {
6472 if (ret == -ENOTSUP)
6473 term_printf("Snapshots not supported on device '%s'\n",
6474 bdrv_get_device_name(bs1));
6475 else
6476 term_printf("Error %d while deleting snapshot on '%s'\n",
6477 ret, bdrv_get_device_name(bs1));
6478 }
6479 }
6480 }
6481 }
6482
6483 void do_info_snapshots(void)
6484 {
6485 BlockDriverState *bs, *bs1;
6486 QEMUSnapshotInfo *sn_tab, *sn;
6487 int nb_sns, i;
6488 char buf[256];
6489
6490 bs = get_bs_snapshots();
6491 if (!bs) {
6492 term_printf("No available block device supports snapshots\n");
6493 return;
6494 }
6495 term_printf("Snapshot devices:");
6496 for(i = 0; i <= nb_drives; i++) {
6497 bs1 = drives_table[i].bdrv;
6498 if (bdrv_has_snapshot(bs1)) {
6499 if (bs == bs1)
6500 term_printf(" %s", bdrv_get_device_name(bs1));
6501 }
6502 }
6503 term_printf("\n");
6504
6505 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6506 if (nb_sns < 0) {
6507 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6508 return;
6509 }
6510 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6511 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6512 for(i = 0; i < nb_sns; i++) {
6513 sn = &sn_tab[i];
6514 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6515 }
6516 qemu_free(sn_tab);
6517 }
6518
6519 /***********************************************************/
6520 /* ram save/restore */
6521
6522 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6523 {
6524 int v;
6525
6526 v = qemu_get_byte(f);
6527 switch(v) {
6528 case 0:
6529 if (qemu_get_buffer(f, buf, len) != len)
6530 return -EIO;
6531 break;
6532 case 1:
6533 v = qemu_get_byte(f);
6534 memset(buf, v, len);
6535 break;
6536 default:
6537 return -EINVAL;
6538 }
6539 return 0;
6540 }
6541
6542 static int ram_load_v1(QEMUFile *f, void *opaque)
6543 {
6544 int ret;
6545 ram_addr_t i;
6546
6547 if (qemu_get_be32(f) != phys_ram_size)
6548 return -EINVAL;
6549 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6550 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6551 if (ret)
6552 return ret;
6553 }
6554 return 0;
6555 }
6556
6557 #define BDRV_HASH_BLOCK_SIZE 1024
6558 #define IOBUF_SIZE 4096
6559 #define RAM_CBLOCK_MAGIC 0xfabe
6560
6561 typedef struct RamCompressState {
6562 z_stream zstream;
6563 QEMUFile *f;
6564 uint8_t buf[IOBUF_SIZE];
6565 } RamCompressState;
6566
6567 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6568 {
6569 int ret;
6570 memset(s, 0, sizeof(*s));
6571 s->f = f;
6572 ret = deflateInit2(&s->zstream, 1,
6573 Z_DEFLATED, 15,
6574 9, Z_DEFAULT_STRATEGY);
6575 if (ret != Z_OK)
6576 return -1;
6577 s->zstream.avail_out = IOBUF_SIZE;
6578 s->zstream.next_out = s->buf;
6579 return 0;
6580 }
6581
6582 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6583 {
6584 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6585 qemu_put_be16(s->f, len);
6586 qemu_put_buffer(s->f, buf, len);
6587 }
6588
6589 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6590 {
6591 int ret;
6592
6593 s->zstream.avail_in = len;
6594 s->zstream.next_in = (uint8_t *)buf;
6595 while (s->zstream.avail_in > 0) {
6596 ret = deflate(&s->zstream, Z_NO_FLUSH);
6597 if (ret != Z_OK)
6598 return -1;
6599 if (s->zstream.avail_out == 0) {
6600 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6601 s->zstream.avail_out = IOBUF_SIZE;
6602 s->zstream.next_out = s->buf;
6603 }
6604 }
6605 return 0;
6606 }
6607
6608 static void ram_compress_close(RamCompressState *s)
6609 {
6610 int len, ret;
6611
6612 /* compress last bytes */
6613 for(;;) {
6614 ret = deflate(&s->zstream, Z_FINISH);
6615 if (ret == Z_OK || ret == Z_STREAM_END) {
6616 len = IOBUF_SIZE - s->zstream.avail_out;
6617 if (len > 0) {
6618 ram_put_cblock(s, s->buf, len);
6619 }
6620 s->zstream.avail_out = IOBUF_SIZE;
6621 s->zstream.next_out = s->buf;
6622 if (ret == Z_STREAM_END)
6623 break;
6624 } else {
6625 goto fail;
6626 }
6627 }
6628 fail:
6629 deflateEnd(&s->zstream);
6630 }
6631
6632 typedef struct RamDecompressState {
6633 z_stream zstream;
6634 QEMUFile *f;
6635 uint8_t buf[IOBUF_SIZE];
6636 } RamDecompressState;
6637
6638 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6639 {
6640 int ret;
6641 memset(s, 0, sizeof(*s));
6642 s->f = f;
6643 ret = inflateInit(&s->zstream);
6644 if (ret != Z_OK)
6645 return -1;
6646 return 0;
6647 }
6648
6649 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6650 {
6651 int ret, clen;
6652
6653 s->zstream.avail_out = len;
6654 s->zstream.next_out = buf;
6655 while (s->zstream.avail_out > 0) {
6656 if (s->zstream.avail_in == 0) {
6657 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6658 return -1;
6659 clen = qemu_get_be16(s->f);
6660 if (clen > IOBUF_SIZE)
6661 return -1;
6662 qemu_get_buffer(s->f, s->buf, clen);
6663 s->zstream.avail_in = clen;
6664 s->zstream.next_in = s->buf;
6665 }
6666 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6667 if (ret != Z_OK && ret != Z_STREAM_END) {
6668 return -1;
6669 }
6670 }
6671 return 0;
6672 }
6673
6674 static void ram_decompress_close(RamDecompressState *s)
6675 {
6676 inflateEnd(&s->zstream);
6677 }
6678
6679 static void ram_save(QEMUFile *f, void *opaque)
6680 {
6681 ram_addr_t i;
6682 RamCompressState s1, *s = &s1;
6683 uint8_t buf[10];
6684
6685 qemu_put_be32(f, phys_ram_size);
6686 if (ram_compress_open(s, f) < 0)
6687 return;
6688 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6689 #if 0
6690 if (tight_savevm_enabled) {
6691 int64_t sector_num;
6692 int j;
6693
6694 /* find if the memory block is available on a virtual
6695 block device */
6696 sector_num = -1;
6697 for(j = 0; j < nb_drives; j++) {
6698 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6699 phys_ram_base + i,
6700 BDRV_HASH_BLOCK_SIZE);
6701 if (sector_num >= 0)
6702 break;
6703 }
6704 if (j == nb_drives)
6705 goto normal_compress;
6706 buf[0] = 1;
6707 buf[1] = j;
6708 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6709 ram_compress_buf(s, buf, 10);
6710 } else
6711 #endif
6712 {
6713 // normal_compress:
6714 buf[0] = 0;
6715 ram_compress_buf(s, buf, 1);
6716 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6717 }
6718 }
6719 ram_compress_close(s);
6720 }
6721
6722 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6723 {
6724 RamDecompressState s1, *s = &s1;
6725 uint8_t buf[10];
6726 ram_addr_t i;
6727
6728 if (version_id == 1)
6729 return ram_load_v1(f, opaque);
6730 if (version_id != 2)
6731 return -EINVAL;
6732 if (qemu_get_be32(f) != phys_ram_size)
6733 return -EINVAL;
6734 if (ram_decompress_open(s, f) < 0)
6735 return -EINVAL;
6736 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6737 if (ram_decompress_buf(s, buf, 1) < 0) {
6738 fprintf(stderr, "Error while reading ram block header\n");
6739 goto error;
6740 }
6741 if (buf[0] == 0) {
6742 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6743 fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
6744 goto error;
6745 }
6746 } else
6747 #if 0
6748 if (buf[0] == 1) {
6749 int bs_index;
6750 int64_t sector_num;
6751
6752 ram_decompress_buf(s, buf + 1, 9);
6753 bs_index = buf[1];
6754 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6755 if (bs_index >= nb_drives) {
6756 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6757 goto error;
6758 }
6759 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6760 phys_ram_base + i,
6761 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6762 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6763 bs_index, sector_num);
6764 goto error;
6765 }
6766 } else
6767 #endif
6768 {
6769 error:
6770 printf("Error block header\n");
6771 return -EINVAL;
6772 }
6773 }
6774 ram_decompress_close(s);
6775 return 0;
6776 }
6777
6778 /***********************************************************/
6779 /* bottom halves (can be seen as timers which expire ASAP) */
6780
6781 struct QEMUBH {
6782 QEMUBHFunc *cb;
6783 void *opaque;
6784 int scheduled;
6785 QEMUBH *next;
6786 };
6787
6788 static QEMUBH *first_bh = NULL;
6789
6790 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6791 {
6792 QEMUBH *bh;
6793 bh = qemu_mallocz(sizeof(QEMUBH));
6794 if (!bh)
6795 return NULL;
6796 bh->cb = cb;
6797 bh->opaque = opaque;
6798 return bh;
6799 }
6800
6801 int qemu_bh_poll(void)
6802 {
6803 QEMUBH *bh, **pbh;
6804 int ret;
6805
6806 ret = 0;
6807 for(;;) {
6808 pbh = &first_bh;
6809 bh = *pbh;
6810 if (!bh)
6811 break;
6812 ret = 1;
6813 *pbh = bh->next;
6814 bh->scheduled = 0;
6815 bh->cb(bh->opaque);
6816 }
6817 return ret;
6818 }
6819
6820 void qemu_bh_schedule(QEMUBH *bh)
6821 {
6822 CPUState *env = cpu_single_env;
6823 if (bh->scheduled)
6824 return;
6825 bh->scheduled = 1;
6826 bh->next = first_bh;
6827 first_bh = bh;
6828
6829 /* stop the currently executing CPU to execute the BH ASAP */
6830 if (env) {
6831 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6832 }
6833 }
6834
6835 void qemu_bh_cancel(QEMUBH *bh)
6836 {
6837 QEMUBH **pbh;
6838 if (bh->scheduled) {
6839 pbh = &first_bh;
6840 while (*pbh != bh)
6841 pbh = &(*pbh)->next;
6842 *pbh = bh->next;
6843 bh->scheduled = 0;
6844 }
6845 }
6846
6847 void qemu_bh_delete(QEMUBH *bh)
6848 {
6849 qemu_bh_cancel(bh);
6850 qemu_free(bh);
6851 }
6852
6853 /***********************************************************/
6854 /* machine registration */
6855
6856 QEMUMachine *first_machine = NULL;
6857
6858 int qemu_register_machine(QEMUMachine *m)
6859 {
6860 QEMUMachine **pm;
6861 pm = &first_machine;
6862 while (*pm != NULL)
6863 pm = &(*pm)->next;
6864 m->next = NULL;
6865 *pm = m;
6866 return 0;
6867 }
6868
6869 static QEMUMachine *find_machine(const char *name)
6870 {
6871 QEMUMachine *m;
6872
6873 for(m = first_machine; m != NULL; m = m->next) {
6874 if (!strcmp(m->name, name))
6875 return m;
6876 }
6877 return NULL;
6878 }
6879
6880 /***********************************************************/
6881 /* main execution loop */
6882
6883 static void gui_update(void *opaque)
6884 {
6885 DisplayState *ds = opaque;
6886 ds->dpy_refresh(ds);
6887 qemu_mod_timer(ds->gui_timer,
6888 (ds->gui_timer_interval ?
6889 ds->gui_timer_interval :
6890 GUI_REFRESH_INTERVAL)
6891 + qemu_get_clock(rt_clock));
6892 }
6893
6894 struct vm_change_state_entry {
6895 VMChangeStateHandler *cb;
6896 void *opaque;
6897 LIST_ENTRY (vm_change_state_entry) entries;
6898 };
6899
6900 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6901
6902 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6903 void *opaque)
6904 {
6905 VMChangeStateEntry *e;
6906
6907 e = qemu_mallocz(sizeof (*e));
6908 if (!e)
6909 return NULL;
6910
6911 e->cb = cb;
6912 e->opaque = opaque;
6913 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6914 return e;
6915 }
6916
6917 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6918 {
6919 LIST_REMOVE (e, entries);
6920 qemu_free (e);
6921 }
6922
6923 static void vm_state_notify(int running)
6924 {
6925 VMChangeStateEntry *e;
6926
6927 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6928 e->cb(e->opaque, running);
6929 }
6930 }
6931
6932 /* XXX: support several handlers */
6933 static VMStopHandler *vm_stop_cb;
6934 static void *vm_stop_opaque;
6935
6936 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6937 {
6938 vm_stop_cb = cb;
6939 vm_stop_opaque = opaque;
6940 return 0;
6941 }
6942
6943 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6944 {
6945 vm_stop_cb = NULL;
6946 }
6947
6948 void vm_start(void)
6949 {
6950 if (!vm_running) {
6951 cpu_enable_ticks();
6952 vm_running = 1;
6953 vm_state_notify(1);
6954 qemu_rearm_alarm_timer(alarm_timer);
6955 }
6956 }
6957
6958 void vm_stop(int reason)
6959 {
6960 if (vm_running) {
6961 cpu_disable_ticks();
6962 vm_running = 0;
6963 if (reason != 0) {
6964 if (vm_stop_cb) {
6965 vm_stop_cb(vm_stop_opaque, reason);
6966 }
6967 }
6968 vm_state_notify(0);
6969 }
6970 }
6971
6972 /* reset/shutdown handler */
6973
6974 typedef struct QEMUResetEntry {
6975 QEMUResetHandler *func;
6976 void *opaque;
6977 struct QEMUResetEntry *next;
6978 } QEMUResetEntry;
6979
6980 static QEMUResetEntry *first_reset_entry;
6981 static int reset_requested;
6982 static int shutdown_requested;
6983 static int powerdown_requested;
6984
6985 int qemu_shutdown_requested(void)
6986 {
6987 int r = shutdown_requested;
6988 shutdown_requested = 0;
6989 return r;
6990 }
6991
6992 int qemu_reset_requested(void)
6993 {
6994 int r = reset_requested;
6995 reset_requested = 0;
6996 return r;
6997 }
6998
6999 int qemu_powerdown_requested(void)
7000 {
7001 int r = powerdown_requested;
7002 powerdown_requested = 0;
7003 return r;
7004 }
7005
7006 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7007 {
7008 QEMUResetEntry **pre, *re;
7009
7010 pre = &first_reset_entry;
7011 while (*pre != NULL)
7012 pre = &(*pre)->next;
7013 re = qemu_mallocz(sizeof(QEMUResetEntry));
7014 re->func = func;
7015 re->opaque = opaque;
7016 re->next = NULL;
7017 *pre = re;
7018 }
7019
7020 void qemu_system_reset(void)
7021 {
7022 QEMUResetEntry *re;
7023
7024 /* reset all devices */
7025 for(re = first_reset_entry; re != NULL; re = re->next) {
7026 re->func(re->opaque);
7027 }
7028 }
7029
7030 void qemu_system_reset_request(void)
7031 {
7032 if (no_reboot) {
7033 shutdown_requested = 1;
7034 } else {
7035 reset_requested = 1;
7036 }
7037 if (cpu_single_env)
7038 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7039 }
7040
7041 void qemu_system_shutdown_request(void)
7042 {
7043 shutdown_requested = 1;
7044 if (cpu_single_env)
7045 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7046 }
7047
7048 void qemu_system_powerdown_request(void)
7049 {
7050 powerdown_requested = 1;
7051 if (cpu_single_env)
7052 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7053 }
7054
7055 void main_loop_wait(int timeout)
7056 {
7057 IOHandlerRecord *ioh;
7058 fd_set rfds, wfds, xfds;
7059 int ret, nfds;
7060 #ifdef _WIN32
7061 int ret2, i;
7062 #endif
7063 struct timeval tv;
7064 PollingEntry *pe;
7065
7066
7067 /* XXX: need to suppress polling by better using win32 events */
7068 ret = 0;
7069 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7070 ret |= pe->func(pe->opaque);
7071 }
7072 #ifdef _WIN32
7073 if (ret == 0) {
7074 int err;
7075 WaitObjects *w = &wait_objects;
7076
7077 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7078 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7079 if (w->func[ret - WAIT_OBJECT_0])
7080 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7081
7082 /* Check for additional signaled events */
7083 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7084
7085 /* Check if event is signaled */
7086 ret2 = WaitForSingleObject(w->events[i], 0);
7087 if(ret2 == WAIT_OBJECT_0) {
7088 if (w->func[i])
7089 w->func[i](w->opaque[i]);
7090 } else if (ret2 == WAIT_TIMEOUT) {
7091 } else {
7092 err = GetLastError();
7093 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7094 }
7095 }
7096 } else if (ret == WAIT_TIMEOUT) {
7097 } else {
7098 err = GetLastError();
7099 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7100 }
7101 }
7102 #endif
7103 /* poll any events */
7104 /* XXX: separate device handlers from system ones */
7105 nfds = -1;
7106 FD_ZERO(&rfds);
7107 FD_ZERO(&wfds);
7108 FD_ZERO(&xfds);
7109 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7110 if (ioh->deleted)
7111 continue;
7112 if (ioh->fd_read &&
7113 (!ioh->fd_read_poll ||
7114 ioh->fd_read_poll(ioh->opaque) != 0)) {
7115 FD_SET(ioh->fd, &rfds);
7116 if (ioh->fd > nfds)
7117 nfds = ioh->fd;
7118 }
7119 if (ioh->fd_write) {
7120 FD_SET(ioh->fd, &wfds);
7121 if (ioh->fd > nfds)
7122 nfds = ioh->fd;
7123 }
7124 }
7125
7126 tv.tv_sec = 0;
7127 #ifdef _WIN32
7128 tv.tv_usec = 0;
7129 #else
7130 tv.tv_usec = timeout * 1000;
7131 #endif
7132 #if defined(CONFIG_SLIRP)
7133 if (slirp_inited) {
7134 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7135 }
7136 #endif
7137 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7138 if (ret > 0) {
7139 IOHandlerRecord **pioh;
7140
7141 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7142 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7143 ioh->fd_read(ioh->opaque);
7144 }
7145 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7146 ioh->fd_write(ioh->opaque);
7147 }
7148 }
7149
7150 /* remove deleted IO handlers */
7151 pioh = &first_io_handler;
7152 while (*pioh) {
7153 ioh = *pioh;
7154 if (ioh->deleted) {
7155 *pioh = ioh->next;
7156 qemu_free(ioh);
7157 } else
7158 pioh = &ioh->next;
7159 }
7160 }
7161 #if defined(CONFIG_SLIRP)
7162 if (slirp_inited) {
7163 if (ret < 0) {
7164 FD_ZERO(&rfds);
7165 FD_ZERO(&wfds);
7166 FD_ZERO(&xfds);
7167 }
7168 slirp_select_poll(&rfds, &wfds, &xfds);
7169 }
7170 #endif
7171 qemu_aio_poll();
7172
7173 if (vm_running) {
7174 if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7175 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7176 qemu_get_clock(vm_clock));
7177 /* run dma transfers, if any */
7178 DMA_run();
7179 }
7180
7181 /* real time timers */
7182 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7183 qemu_get_clock(rt_clock));
7184
7185 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7186 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7187 qemu_rearm_alarm_timer(alarm_timer);
7188 }
7189
7190 /* Check bottom-halves last in case any of the earlier events triggered
7191 them. */
7192 qemu_bh_poll();
7193
7194 }
7195
7196 static int main_loop(void)
7197 {
7198 int ret, timeout;
7199 #ifdef CONFIG_PROFILER
7200 int64_t ti;
7201 #endif
7202 CPUState *env;
7203
7204 cur_cpu = first_cpu;
7205 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7206 for(;;) {
7207 if (vm_running) {
7208
7209 for(;;) {
7210 /* get next cpu */
7211 env = next_cpu;
7212 #ifdef CONFIG_PROFILER
7213 ti = profile_getclock();
7214 #endif
7215 if (use_icount) {
7216 int64_t count;
7217 int decr;
7218 qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7219 env->icount_decr.u16.low = 0;
7220 env->icount_extra = 0;
7221 count = qemu_next_deadline();
7222 count = (count + (1 << icount_time_shift) - 1)
7223 >> icount_time_shift;
7224 qemu_icount += count;
7225 decr = (count > 0xffff) ? 0xffff : count;
7226 count -= decr;
7227 env->icount_decr.u16.low = decr;
7228 env->icount_extra = count;
7229 }
7230 ret = cpu_exec(env);
7231 #ifdef CONFIG_PROFILER
7232 qemu_time += profile_getclock() - ti;
7233 #endif
7234 if (use_icount) {
7235 /* Fold pending instructions back into the
7236 instruction counter, and clear the interrupt flag. */
7237 qemu_icount -= (env->icount_decr.u16.low
7238 + env->icount_extra);
7239 env->icount_decr.u32 = 0;
7240 env->icount_extra = 0;
7241 }
7242 next_cpu = env->next_cpu ?: first_cpu;
7243 if (event_pending && likely(ret != EXCP_DEBUG)) {
7244 ret = EXCP_INTERRUPT;
7245 event_pending = 0;
7246 break;
7247 }
7248 if (ret == EXCP_HLT) {
7249 /* Give the next CPU a chance to run. */
7250 cur_cpu = env;
7251 continue;
7252 }
7253 if (ret != EXCP_HALTED)
7254 break;
7255 /* all CPUs are halted ? */
7256 if (env == cur_cpu)
7257 break;
7258 }
7259 cur_cpu = env;
7260
7261 if (shutdown_requested) {
7262 ret = EXCP_INTERRUPT;
7263 if (no_shutdown) {
7264 vm_stop(0);
7265 no_shutdown = 0;
7266 }
7267 else
7268 break;
7269 }
7270 if (reset_requested) {
7271 reset_requested = 0;
7272 qemu_system_reset();
7273 ret = EXCP_INTERRUPT;
7274 }
7275 if (powerdown_requested) {
7276 powerdown_requested = 0;
7277 qemu_system_powerdown();
7278 ret = EXCP_INTERRUPT;
7279 }
7280 if (unlikely(ret == EXCP_DEBUG)) {
7281 vm_stop(EXCP_DEBUG);
7282 }
7283 /* If all cpus are halted then wait until the next IRQ */
7284 /* XXX: use timeout computed from timers */
7285 if (ret == EXCP_HALTED) {
7286 if (use_icount) {
7287 int64_t add;
7288 int64_t delta;
7289 /* Advance virtual time to the next event. */
7290 if (use_icount == 1) {
7291 /* When not using an adaptive execution frequency
7292 we tend to get badly out of sync with real time,
7293 so just delay for a reasonable amount of time. */
7294 delta = 0;
7295 } else {
7296 delta = cpu_get_icount() - cpu_get_clock();
7297 }
7298 if (delta > 0) {
7299 /* If virtual time is ahead of real time then just
7300 wait for IO. */
7301 timeout = (delta / 1000000) + 1;
7302 } else {
7303 /* Wait for either IO to occur or the next
7304 timer event. */
7305 add = qemu_next_deadline();
7306 /* We advance the timer before checking for IO.
7307 Limit the amount we advance so that early IO
7308 activity won't get the guest too far ahead. */
7309 if (add > 10000000)
7310 add = 10000000;
7311 delta += add;
7312 add = (add + (1 << icount_time_shift) - 1)
7313 >> icount_time_shift;
7314 qemu_icount += add;
7315 timeout = delta / 1000000;
7316 if (timeout < 0)
7317 timeout = 0;
7318 }
7319 } else {
7320 timeout = 10;
7321 }
7322 } else {
7323 timeout = 0;
7324 }
7325 } else {
7326 timeout = 10;
7327 }
7328 #ifdef CONFIG_PROFILER
7329 ti = profile_getclock();
7330 #endif
7331 main_loop_wait(timeout);
7332 #ifdef CONFIG_PROFILER
7333 dev_time += profile_getclock() - ti;
7334 #endif
7335 }
7336 cpu_disable_ticks();
7337 return ret;
7338 }
7339
7340 static void help(int exitcode)
7341 {
7342 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7343 "usage: %s [options] [disk_image]\n"
7344 "\n"
7345 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7346 "\n"
7347 "Standard options:\n"
7348 "-M machine select emulated machine (-M ? for list)\n"
7349 "-cpu cpu select CPU (-cpu ? for list)\n"
7350 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7351 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7352 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7353 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7354 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7355 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7356 " [,cache=on|off][,format=f]\n"
7357 " use 'file' as a drive image\n"
7358 "-mtdblock file use 'file' as on-board Flash memory image\n"
7359 "-sd file use 'file' as SecureDigital card image\n"
7360 "-pflash file use 'file' as a parallel flash image\n"
7361 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7362 "-snapshot write to temporary files instead of disk image files\n"
7363 #ifdef CONFIG_SDL
7364 "-no-frame open SDL window without a frame and window decorations\n"
7365 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7366 "-no-quit disable SDL window close capability\n"
7367 #endif
7368 #ifdef TARGET_I386
7369 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7370 #endif
7371 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7372 "-smp n set the number of CPUs to 'n' [default=1]\n"
7373 "-nographic disable graphical output and redirect serial I/Os to console\n"
7374 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7375 #ifndef _WIN32
7376 "-k language use keyboard layout (for example \"fr\" for French)\n"
7377 #endif
7378 #ifdef HAS_AUDIO
7379 "-audio-help print list of audio drivers and their options\n"
7380 "-soundhw c1,... enable audio support\n"
7381 " and only specified sound cards (comma separated list)\n"
7382 " use -soundhw ? to get the list of supported cards\n"
7383 " use -soundhw all to enable all of them\n"
7384 #endif
7385 "-localtime set the real time clock to local time [default=utc]\n"
7386 "-full-screen start in full screen\n"
7387 #ifdef TARGET_I386
7388 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7389 #endif
7390 "-usb enable the USB driver (will be the default soon)\n"
7391 "-usbdevice name add the host or guest USB device 'name'\n"
7392 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7393 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7394 #endif
7395 "-name string set the name of the guest\n"
7396 "\n"
7397 "Network options:\n"
7398 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7399 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7400 #ifdef CONFIG_SLIRP
7401 "-net user[,vlan=n][,hostname=host]\n"
7402 " connect the user mode network stack to VLAN 'n' and send\n"
7403 " hostname 'host' to DHCP clients\n"
7404 #endif
7405 #ifdef _WIN32
7406 "-net tap[,vlan=n],ifname=name\n"
7407 " connect the host TAP network interface to VLAN 'n'\n"
7408 #else
7409 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7410 " connect the host TAP network interface to VLAN 'n' and use the\n"
7411 " network scripts 'file' (default=%s)\n"
7412 " and 'dfile' (default=%s);\n"
7413 " use '[down]script=no' to disable script execution;\n"
7414 " use 'fd=h' to connect to an already opened TAP interface\n"
7415 #endif
7416 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7417 " connect the vlan 'n' to another VLAN using a socket connection\n"
7418 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7419 " connect the vlan 'n' to multicast maddr and port\n"
7420 "-net none use it alone to have zero network devices; if no -net option\n"
7421 " is provided, the default is '-net nic -net user'\n"
7422 "\n"
7423 #ifdef CONFIG_SLIRP
7424 "-tftp dir allow tftp access to files in dir [-net user]\n"
7425 "-bootp file advertise file in BOOTP replies\n"
7426 #ifndef _WIN32
7427 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7428 #endif
7429 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7430 " redirect TCP or UDP connections from host to guest [-net user]\n"
7431 #endif
7432 "\n"
7433 "Linux boot specific:\n"
7434 "-kernel bzImage use 'bzImage' as kernel image\n"
7435 "-append cmdline use 'cmdline' as kernel command line\n"
7436 "-initrd file use 'file' as initial ram disk\n"
7437 "\n"
7438 "Debug/Expert options:\n"
7439 "-monitor dev redirect the monitor to char device 'dev'\n"
7440 "-serial dev redirect the serial port to char device 'dev'\n"
7441 "-parallel dev redirect the parallel port to char device 'dev'\n"
7442 "-pidfile file Write PID to 'file'\n"
7443 "-S freeze CPU at startup (use 'c' to start execution)\n"
7444 "-s wait gdb connection to port\n"
7445 "-p port set gdb connection port [default=%s]\n"
7446 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7447 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7448 " translation (t=none or lba) (usually qemu can guess them)\n"
7449 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7450 #ifdef USE_KQEMU
7451 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7452 "-no-kqemu disable KQEMU kernel module usage\n"
7453 #endif
7454 #ifdef TARGET_I386
7455 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7456 " (default is CL-GD5446 PCI VGA)\n"
7457 "-no-acpi disable ACPI\n"
7458 #endif
7459 #ifdef CONFIG_CURSES
7460 "-curses use a curses/ncurses interface instead of SDL\n"
7461 #endif
7462 "-no-reboot exit instead of rebooting\n"
7463 "-no-shutdown stop before shutdown\n"
7464 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7465 "-vnc display start a VNC server on display\n"
7466 #ifndef _WIN32
7467 "-daemonize daemonize QEMU after initializing\n"
7468 #endif
7469 "-option-rom rom load a file, rom, into the option ROM space\n"
7470 #ifdef TARGET_SPARC
7471 "-prom-env variable=value set OpenBIOS nvram variables\n"
7472 #endif
7473 "-clock force the use of the given methods for timer alarm.\n"
7474 " To see what timers are available use -clock ?\n"
7475 "-startdate select initial date of the clock\n"
7476 "-icount [N|auto]\n"
7477 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7478 "\n"
7479 "During emulation, the following keys are useful:\n"
7480 "ctrl-alt-f toggle full screen\n"
7481 "ctrl-alt-n switch to virtual console 'n'\n"
7482 "ctrl-alt toggle mouse and keyboard grab\n"
7483 "\n"
7484 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7485 ,
7486 "qemu",
7487 DEFAULT_RAM_SIZE,
7488 #ifndef _WIN32
7489 DEFAULT_NETWORK_SCRIPT,
7490 DEFAULT_NETWORK_DOWN_SCRIPT,
7491 #endif
7492 DEFAULT_GDBSTUB_PORT,
7493 "/tmp/qemu.log");
7494 exit(exitcode);
7495 }
7496
7497 #define HAS_ARG 0x0001
7498
7499 enum {
7500 QEMU_OPTION_h,
7501
7502 QEMU_OPTION_M,
7503 QEMU_OPTION_cpu,
7504 QEMU_OPTION_fda,
7505 QEMU_OPTION_fdb,
7506 QEMU_OPTION_hda,
7507 QEMU_OPTION_hdb,
7508 QEMU_OPTION_hdc,
7509 QEMU_OPTION_hdd,
7510 QEMU_OPTION_drive,
7511 QEMU_OPTION_cdrom,
7512 QEMU_OPTION_mtdblock,
7513 QEMU_OPTION_sd,
7514 QEMU_OPTION_pflash,
7515 QEMU_OPTION_boot,
7516 QEMU_OPTION_snapshot,
7517 #ifdef TARGET_I386
7518 QEMU_OPTION_no_fd_bootchk,
7519 #endif
7520 QEMU_OPTION_m,
7521 QEMU_OPTION_nographic,
7522 QEMU_OPTION_portrait,
7523 #ifdef HAS_AUDIO
7524 QEMU_OPTION_audio_help,
7525 QEMU_OPTION_soundhw,
7526 #endif
7527
7528 QEMU_OPTION_net,
7529 QEMU_OPTION_tftp,
7530 QEMU_OPTION_bootp,
7531 QEMU_OPTION_smb,
7532 QEMU_OPTION_redir,
7533
7534 QEMU_OPTION_kernel,
7535 QEMU_OPTION_append,
7536 QEMU_OPTION_initrd,
7537
7538 QEMU_OPTION_S,
7539 QEMU_OPTION_s,
7540 QEMU_OPTION_p,
7541 QEMU_OPTION_d,
7542 QEMU_OPTION_hdachs,
7543 QEMU_OPTION_L,
7544 QEMU_OPTION_bios,
7545 QEMU_OPTION_k,
7546 QEMU_OPTION_localtime,
7547 QEMU_OPTION_cirrusvga,
7548 QEMU_OPTION_vmsvga,
7549 QEMU_OPTION_g,
7550 QEMU_OPTION_std_vga,
7551 QEMU_OPTION_echr,
7552 QEMU_OPTION_monitor,
7553 QEMU_OPTION_serial,
7554 QEMU_OPTION_parallel,
7555 QEMU_OPTION_loadvm,
7556 QEMU_OPTION_full_screen,
7557 QEMU_OPTION_no_frame,
7558 QEMU_OPTION_alt_grab,
7559 QEMU_OPTION_no_quit,
7560 QEMU_OPTION_pidfile,
7561 QEMU_OPTION_no_kqemu,
7562 QEMU_OPTION_kernel_kqemu,
7563 QEMU_OPTION_win2k_hack,
7564 QEMU_OPTION_usb,
7565 QEMU_OPTION_usbdevice,
7566 QEMU_OPTION_smp,
7567 QEMU_OPTION_vnc,
7568 QEMU_OPTION_no_acpi,
7569 QEMU_OPTION_curses,
7570 QEMU_OPTION_no_reboot,
7571 QEMU_OPTION_no_shutdown,
7572 QEMU_OPTION_show_cursor,
7573 QEMU_OPTION_daemonize,
7574 QEMU_OPTION_option_rom,
7575 QEMU_OPTION_semihosting,
7576 QEMU_OPTION_name,
7577 QEMU_OPTION_prom_env,
7578 QEMU_OPTION_old_param,
7579 QEMU_OPTION_clock,
7580 QEMU_OPTION_startdate,
7581 QEMU_OPTION_tb_size,
7582 QEMU_OPTION_icount,
7583 };
7584
7585 typedef struct QEMUOption {
7586 const char *name;
7587 int flags;
7588 int index;
7589 } QEMUOption;
7590
7591 const QEMUOption qemu_options[] = {
7592 { "h", 0, QEMU_OPTION_h },
7593 { "help", 0, QEMU_OPTION_h },
7594
7595 { "M", HAS_ARG, QEMU_OPTION_M },
7596 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7597 { "fda", HAS_ARG, QEMU_OPTION_fda },
7598 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7599 { "hda", HAS_ARG, QEMU_OPTION_hda },
7600 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7601 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7602 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7603 { "drive", HAS_ARG, QEMU_OPTION_drive },
7604 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7605 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7606 { "sd", HAS_ARG, QEMU_OPTION_sd },
7607 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7608 { "boot", HAS_ARG, QEMU_OPTION_boot },
7609 { "snapshot", 0, QEMU_OPTION_snapshot },
7610 #ifdef TARGET_I386
7611 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7612 #endif
7613 { "m", HAS_ARG, QEMU_OPTION_m },
7614 { "nographic", 0, QEMU_OPTION_nographic },
7615 { "portrait", 0, QEMU_OPTION_portrait },
7616 { "k", HAS_ARG, QEMU_OPTION_k },
7617 #ifdef HAS_AUDIO
7618 { "audio-help", 0, QEMU_OPTION_audio_help },
7619 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7620 #endif
7621
7622 { "net", HAS_ARG, QEMU_OPTION_net},
7623 #ifdef CONFIG_SLIRP
7624 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7625 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7626 #ifndef _WIN32
7627 { "smb", HAS_ARG, QEMU_OPTION_smb },
7628 #endif
7629 { "redir", HAS_ARG, QEMU_OPTION_redir },
7630 #endif
7631
7632 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7633 { "append", HAS_ARG, QEMU_OPTION_append },
7634 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7635
7636 { "S", 0, QEMU_OPTION_S },
7637 { "s", 0, QEMU_OPTION_s },
7638 { "p", HAS_ARG, QEMU_OPTION_p },
7639 { "d", HAS_ARG, QEMU_OPTION_d },
7640 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7641 { "L", HAS_ARG, QEMU_OPTION_L },
7642 { "bios", HAS_ARG, QEMU_OPTION_bios },
7643 #ifdef USE_KQEMU
7644 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7645 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7646 #endif
7647 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7648 { "g", 1, QEMU_OPTION_g },
7649 #endif
7650 { "localtime", 0, QEMU_OPTION_localtime },
7651 { "std-vga", 0, QEMU_OPTION_std_vga },
7652 { "echr", HAS_ARG, QEMU_OPTION_echr },
7653 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7654 { "serial", HAS_ARG, QEMU_OPTION_serial },
7655 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7656 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7657 { "full-screen", 0, QEMU_OPTION_full_screen },
7658 #ifdef CONFIG_SDL
7659 { "no-frame", 0, QEMU_OPTION_no_frame },
7660 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7661 { "no-quit", 0, QEMU_OPTION_no_quit },
7662 #endif
7663 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7664 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7665 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7666 { "smp", HAS_ARG, QEMU_OPTION_smp },
7667 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7668 #ifdef CONFIG_CURSES
7669 { "curses", 0, QEMU_OPTION_curses },
7670 #endif
7671
7672 /* temporary options */
7673 { "usb", 0, QEMU_OPTION_usb },
7674 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7675 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7676 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7677 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7678 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7679 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7680 { "daemonize", 0, QEMU_OPTION_daemonize },
7681 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7682 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7683 { "semihosting", 0, QEMU_OPTION_semihosting },
7684 #endif
7685 { "name", HAS_ARG, QEMU_OPTION_name },
7686 #if defined(TARGET_SPARC)
7687 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7688 #endif
7689 #if defined(TARGET_ARM)
7690 { "old-param", 0, QEMU_OPTION_old_param },
7691 #endif
7692 { "clock", HAS_ARG, QEMU_OPTION_clock },
7693 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7694 { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
7695 { "icount", HAS_ARG, QEMU_OPTION_icount },
7696 { NULL },
7697 };
7698
7699 /* password input */
7700
7701 int qemu_key_check(BlockDriverState *bs, const char *name)
7702 {
7703 char password[256];
7704 int i;
7705
7706 if (!bdrv_is_encrypted(bs))
7707 return 0;
7708
7709 term_printf("%s is encrypted.\n", name);
7710 for(i = 0; i < 3; i++) {
7711 monitor_readline("Password: ", 1, password, sizeof(password));
7712 if (bdrv_set_key(bs, password) == 0)
7713 return 0;
7714 term_printf("invalid password\n");
7715 }
7716 return -EPERM;
7717 }
7718
7719 static BlockDriverState *get_bdrv(int index)
7720 {
7721 if (index > nb_drives)
7722 return NULL;
7723 return drives_table[index].bdrv;
7724 }
7725
7726 static void read_passwords(void)
7727 {
7728 BlockDriverState *bs;
7729 int i;
7730
7731 for(i = 0; i < 6; i++) {
7732 bs = get_bdrv(i);
7733 if (bs)
7734 qemu_key_check(bs, bdrv_get_device_name(bs));
7735 }
7736 }
7737
7738 #ifdef HAS_AUDIO
7739 struct soundhw soundhw[] = {
7740 #ifdef HAS_AUDIO_CHOICE
7741 #if defined(TARGET_I386) || defined(TARGET_MIPS)
7742 {
7743 "pcspk",
7744 "PC speaker",
7745 0,
7746 1,
7747 { .init_isa = pcspk_audio_init }
7748 },
7749 #endif
7750 {
7751 "sb16",
7752 "Creative Sound Blaster 16",
7753 0,
7754 1,
7755 { .init_isa = SB16_init }
7756 },
7757
7758 #ifdef CONFIG_CS4231A
7759 {
7760 "cs4231a",
7761 "CS4231A",
7762 0,
7763 1,
7764 { .init_isa = cs4231a_init }
7765 },
7766 #endif
7767
7768 #ifdef CONFIG_ADLIB
7769 {
7770 "adlib",
7771 #ifdef HAS_YMF262
7772 "Yamaha YMF262 (OPL3)",
7773 #else
7774 "Yamaha YM3812 (OPL2)",
7775 #endif
7776 0,
7777 1,
7778 { .init_isa = Adlib_init }
7779 },
7780 #endif
7781
7782 #ifdef CONFIG_GUS
7783 {
7784 "gus",
7785 "Gravis Ultrasound GF1",
7786 0,
7787 1,
7788 { .init_isa = GUS_init }
7789 },
7790 #endif
7791
7792 #ifdef CONFIG_AC97
7793 {
7794 "ac97",
7795 "Intel 82801AA AC97 Audio",
7796 0,
7797 0,
7798 { .init_pci = ac97_init }
7799 },
7800 #endif
7801
7802 {
7803 "es1370",
7804 "ENSONIQ AudioPCI ES1370",
7805 0,
7806 0,
7807 { .init_pci = es1370_init }
7808 },
7809 #endif
7810
7811 { NULL, NULL, 0, 0, { NULL } }
7812 };
7813
7814 static void select_soundhw (const char *optarg)
7815 {
7816 struct soundhw *c;
7817
7818 if (*optarg == '?') {
7819 show_valid_cards:
7820
7821 printf ("Valid sound card names (comma separated):\n");
7822 for (c = soundhw; c->name; ++c) {
7823 printf ("%-11s %s\n", c->name, c->descr);
7824 }
7825 printf ("\n-soundhw all will enable all of the above\n");
7826 exit (*optarg != '?');
7827 }
7828 else {
7829 size_t l;
7830 const char *p;
7831 char *e;
7832 int bad_card = 0;
7833
7834 if (!strcmp (optarg, "all")) {
7835 for (c = soundhw; c->name; ++c) {
7836 c->enabled = 1;
7837 }
7838 return;
7839 }
7840
7841 p = optarg;
7842 while (*p) {
7843 e = strchr (p, ',');
7844 l = !e ? strlen (p) : (size_t) (e - p);
7845
7846 for (c = soundhw; c->name; ++c) {
7847 if (!strncmp (c->name, p, l)) {
7848 c->enabled = 1;
7849 break;
7850 }
7851 }
7852
7853 if (!c->name) {
7854 if (l > 80) {
7855 fprintf (stderr,
7856 "Unknown sound card name (too big to show)\n");
7857 }
7858 else {
7859 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7860 (int) l, p);
7861 }
7862 bad_card = 1;
7863 }
7864 p += l + (e != NULL);
7865 }
7866
7867 if (bad_card)
7868 goto show_valid_cards;
7869 }
7870 }
7871 #endif
7872
7873 #ifdef _WIN32
7874 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7875 {
7876 exit(STATUS_CONTROL_C_EXIT);
7877 return TRUE;
7878 }
7879 #endif
7880
7881 #define MAX_NET_CLIENTS 32
7882
7883 int main(int argc, char **argv)
7884 {
7885 #ifdef CONFIG_GDBSTUB
7886 int use_gdbstub;
7887 const char *gdbstub_port;
7888 #endif
7889 uint32_t boot_devices_bitmap = 0;
7890 int i;
7891 int snapshot, linux_boot, net_boot;
7892 const char *initrd_filename;
7893 const char *kernel_filename, *kernel_cmdline;
7894 const char *boot_devices = "";
7895 DisplayState *ds = &display_state;
7896 int cyls, heads, secs, translation;
7897 const char *net_clients[MAX_NET_CLIENTS];
7898 int nb_net_clients;
7899 int hda_index;
7900 int optind;
7901 const char *r, *optarg;
7902 CharDriverState *monitor_hd;
7903 const char *monitor_device;
7904 const char *serial_devices[MAX_SERIAL_PORTS];
7905 int serial_device_index;
7906 const char *parallel_devices[MAX_PARALLEL_PORTS];
7907 int parallel_device_index;
7908 const char *loadvm = NULL;
7909 QEMUMachine *machine;
7910 const char *cpu_model;
7911 const char *usb_devices[MAX_USB_CMDLINE];
7912 int usb_devices_index;
7913 int fds[2];
7914 int tb_size;
7915 const char *pid_file = NULL;
7916 VLANState *vlan;
7917
7918 LIST_INIT (&vm_change_state_head);
7919 #ifndef _WIN32
7920 {
7921 struct sigaction act;
7922 sigfillset(&act.sa_mask);
7923 act.sa_flags = 0;
7924 act.sa_handler = SIG_IGN;
7925 sigaction(SIGPIPE, &act, NULL);
7926 }
7927 #else
7928 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7929 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7930 QEMU to run on a single CPU */
7931 {
7932 HANDLE h;
7933 DWORD mask, smask;
7934 int i;
7935 h = GetCurrentProcess();
7936 if (GetProcessAffinityMask(h, &mask, &smask)) {
7937 for(i = 0; i < 32; i++) {
7938 if (mask & (1 << i))
7939 break;
7940 }
7941 if (i != 32) {
7942 mask = 1 << i;
7943 SetProcessAffinityMask(h, mask);
7944 }
7945 }
7946 }
7947 #endif
7948
7949 register_machines();
7950 machine = first_machine;
7951 cpu_model = NULL;
7952 initrd_filename = NULL;
7953 ram_size = 0;
7954 vga_ram_size = VGA_RAM_SIZE;
7955 #ifdef CONFIG_GDBSTUB
7956 use_gdbstub = 0;
7957 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7958 #endif
7959 snapshot = 0;
7960 nographic = 0;
7961 curses = 0;
7962 kernel_filename = NULL;
7963 kernel_cmdline = "";
7964 cyls = heads = secs = 0;
7965 translation = BIOS_ATA_TRANSLATION_AUTO;
7966 monitor_device = "vc";
7967
7968 serial_devices[0] = "vc:80Cx24C";
7969 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7970 serial_devices[i] = NULL;
7971 serial_device_index = 0;
7972
7973 parallel_devices[0] = "vc:640x480";
7974 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7975 parallel_devices[i] = NULL;
7976 parallel_device_index = 0;
7977
7978 usb_devices_index = 0;
7979
7980 nb_net_clients = 0;
7981 nb_drives = 0;
7982 nb_drives_opt = 0;
7983 hda_index = -1;
7984
7985 nb_nics = 0;
7986
7987 tb_size = 0;
7988
7989 optind = 1;
7990 for(;;) {
7991 if (optind >= argc)
7992 break;
7993 r = argv[optind];
7994 if (r[0] != '-') {
7995 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
7996 } else {
7997 const QEMUOption *popt;
7998
7999 optind++;
8000 /* Treat --foo the same as -foo. */
8001 if (r[1] == '-')
8002 r++;
8003 popt = qemu_options;
8004 for(;;) {
8005 if (!popt->name) {
8006 fprintf(stderr, "%s: invalid option -- '%s'\n",
8007 argv[0], r);
8008 exit(1);
8009 }
8010 if (!strcmp(popt->name, r + 1))
8011 break;
8012 popt++;
8013 }
8014 if (popt->flags & HAS_ARG) {
8015 if (optind >= argc) {
8016 fprintf(stderr, "%s: option '%s' requires an argument\n",
8017 argv[0], r);
8018 exit(1);
8019 }
8020 optarg = argv[optind++];
8021 } else {
8022 optarg = NULL;
8023 }
8024
8025 switch(popt->index) {
8026 case QEMU_OPTION_M:
8027 machine = find_machine(optarg);
8028 if (!machine) {
8029 QEMUMachine *m;
8030 printf("Supported machines are:\n");
8031 for(m = first_machine; m != NULL; m = m->next) {
8032 printf("%-10s %s%s\n",
8033 m->name, m->desc,
8034 m == first_machine ? " (default)" : "");
8035 }
8036 exit(*optarg != '?');
8037 }
8038 break;
8039 case QEMU_OPTION_cpu:
8040 /* hw initialization will check this */
8041 if (*optarg == '?') {
8042 /* XXX: implement xxx_cpu_list for targets that still miss it */
8043 #if defined(cpu_list)
8044 cpu_list(stdout, &fprintf);
8045 #endif
8046 exit(0);
8047 } else {
8048 cpu_model = optarg;
8049 }
8050 break;
8051 case QEMU_OPTION_initrd:
8052 initrd_filename = optarg;
8053 break;
8054 case QEMU_OPTION_hda:
8055 if (cyls == 0)
8056 hda_index = drive_add(optarg, HD_ALIAS, 0);
8057 else
8058 hda_index = drive_add(optarg, HD_ALIAS
8059 ",cyls=%d,heads=%d,secs=%d%s",
8060 0, cyls, heads, secs,
8061 translation == BIOS_ATA_TRANSLATION_LBA ?
8062 ",trans=lba" :
8063 translation == BIOS_ATA_TRANSLATION_NONE ?
8064 ",trans=none" : "");
8065 break;
8066 case QEMU_OPTION_hdb:
8067 case QEMU_OPTION_hdc:
8068 case QEMU_OPTION_hdd:
8069 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8070 break;
8071 case QEMU_OPTION_drive:
8072 drive_add(NULL, "%s", optarg);
8073 break;
8074 case QEMU_OPTION_mtdblock:
8075 drive_add(optarg, MTD_ALIAS);
8076 break;
8077 case QEMU_OPTION_sd:
8078 drive_add(optarg, SD_ALIAS);
8079 break;
8080 case QEMU_OPTION_pflash:
8081 drive_add(optarg, PFLASH_ALIAS);
8082 break;
8083 case QEMU_OPTION_snapshot:
8084 snapshot = 1;
8085 break;
8086 case QEMU_OPTION_hdachs:
8087 {
8088 const char *p;
8089 p = optarg;
8090 cyls = strtol(p, (char **)&p, 0);
8091 if (cyls < 1 || cyls > 16383)
8092 goto chs_fail;
8093 if (*p != ',')
8094 goto chs_fail;
8095 p++;
8096 heads = strtol(p, (char **)&p, 0);
8097 if (heads < 1 || heads > 16)
8098 goto chs_fail;
8099 if (*p != ',')
8100 goto chs_fail;
8101 p++;
8102 secs = strtol(p, (char **)&p, 0);
8103 if (secs < 1 || secs > 63)
8104 goto chs_fail;
8105 if (*p == ',') {
8106 p++;
8107 if (!strcmp(p, "none"))
8108 translation = BIOS_ATA_TRANSLATION_NONE;
8109 else if (!strcmp(p, "lba"))
8110 translation = BIOS_ATA_TRANSLATION_LBA;
8111 else if (!strcmp(p, "auto"))
8112 translation = BIOS_ATA_TRANSLATION_AUTO;
8113 else
8114 goto chs_fail;
8115 } else if (*p != '\0') {
8116 chs_fail:
8117 fprintf(stderr, "qemu: invalid physical CHS format\n");
8118 exit(1);
8119 }
8120 if (hda_index != -1)
8121 snprintf(drives_opt[hda_index].opt,
8122 sizeof(drives_opt[hda_index].opt),
8123 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8124 0, cyls, heads, secs,
8125 translation == BIOS_ATA_TRANSLATION_LBA ?
8126 ",trans=lba" :
8127 translation == BIOS_ATA_TRANSLATION_NONE ?
8128 ",trans=none" : "");
8129 }
8130 break;
8131 case QEMU_OPTION_nographic:
8132 serial_devices[0] = "stdio";
8133 parallel_devices[0] = "null";
8134 monitor_device = "stdio";
8135 nographic = 1;
8136 break;
8137 #ifdef CONFIG_CURSES
8138 case QEMU_OPTION_curses:
8139 curses = 1;
8140 break;
8141 #endif
8142 case QEMU_OPTION_portrait:
8143 graphic_rotate = 1;
8144 break;
8145 case QEMU_OPTION_kernel:
8146 kernel_filename = optarg;
8147 break;
8148 case QEMU_OPTION_append:
8149 kernel_cmdline = optarg;
8150 break;
8151 case QEMU_OPTION_cdrom:
8152 drive_add(optarg, CDROM_ALIAS);
8153 break;
8154 case QEMU_OPTION_boot:
8155 boot_devices = optarg;
8156 /* We just do some generic consistency checks */
8157 {
8158 /* Could easily be extended to 64 devices if needed */
8159 const char *p;
8160
8161 boot_devices_bitmap = 0;
8162 for (p = boot_devices; *p != '\0'; p++) {
8163 /* Allowed boot devices are:
8164 * a b : floppy disk drives
8165 * c ... f : IDE disk drives
8166 * g ... m : machine implementation dependant drives
8167 * n ... p : network devices
8168 * It's up to each machine implementation to check
8169 * if the given boot devices match the actual hardware
8170 * implementation and firmware features.
8171 */
8172 if (*p < 'a' || *p > 'q') {
8173 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8174 exit(1);
8175 }
8176 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8177 fprintf(stderr,
8178 "Boot device '%c' was given twice\n",*p);
8179 exit(1);
8180 }
8181 boot_devices_bitmap |= 1 << (*p - 'a');
8182 }
8183 }
8184 break;
8185 case QEMU_OPTION_fda:
8186 case QEMU_OPTION_fdb:
8187 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8188 break;
8189 #ifdef TARGET_I386
8190 case QEMU_OPTION_no_fd_bootchk:
8191 fd_bootchk = 0;
8192 break;
8193 #endif
8194 case QEMU_OPTION_net:
8195 if (nb_net_clients >= MAX_NET_CLIENTS) {
8196 fprintf(stderr, "qemu: too many network clients\n");
8197 exit(1);
8198 }
8199 net_clients[nb_net_clients] = optarg;
8200 nb_net_clients++;
8201 break;
8202 #ifdef CONFIG_SLIRP
8203 case QEMU_OPTION_tftp:
8204 tftp_prefix = optarg;
8205 break;
8206 case QEMU_OPTION_bootp:
8207 bootp_filename = optarg;
8208 break;
8209 #ifndef _WIN32
8210 case QEMU_OPTION_smb:
8211 net_slirp_smb(optarg);
8212 break;
8213 #endif
8214 case QEMU_OPTION_redir:
8215 net_slirp_redir(optarg);
8216 break;
8217 #endif
8218 #ifdef HAS_AUDIO
8219 case QEMU_OPTION_audio_help:
8220 AUD_help ();
8221 exit (0);
8222 break;
8223 case QEMU_OPTION_soundhw:
8224 select_soundhw (optarg);
8225 break;
8226 #endif
8227 case QEMU_OPTION_h:
8228 help(0);
8229 break;
8230 case QEMU_OPTION_m: {
8231 uint64_t value;
8232 char *ptr;
8233
8234 value = strtoul(optarg, &ptr, 10);
8235 switch (*ptr) {
8236 case 0: case 'M': case 'm':
8237 value <<= 20;
8238 break;
8239 case 'G': case 'g':
8240 value <<= 30;
8241 break;
8242 default:
8243 fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8244 exit(1);
8245 }
8246
8247 /* On 32-bit hosts, QEMU is limited by virtual address space */
8248 if (value > (2047 << 20)
8249 #ifndef USE_KQEMU
8250 && HOST_LONG_BITS == 32
8251 #endif
8252 ) {
8253 fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8254 exit(1);
8255 }
8256 if (value != (uint64_t)(ram_addr_t)value) {
8257 fprintf(stderr, "qemu: ram size too large\n");
8258 exit(1);
8259 }
8260 ram_size = value;
8261 break;
8262 }
8263 case QEMU_OPTION_d:
8264 {
8265 int mask;
8266 CPULogItem *item;
8267
8268 mask = cpu_str_to_log_mask(optarg);
8269 if (!mask) {
8270 printf("Log items (comma separated):\n");
8271 for(item = cpu_log_items; item->mask != 0; item++) {
8272 printf("%-10s %s\n", item->name, item->help);
8273 }
8274 exit(1);
8275 }
8276 cpu_set_log(mask);
8277 }
8278 break;
8279 #ifdef CONFIG_GDBSTUB
8280 case QEMU_OPTION_s:
8281 use_gdbstub = 1;
8282 break;
8283 case QEMU_OPTION_p:
8284 gdbstub_port = optarg;
8285 break;
8286 #endif
8287 case QEMU_OPTION_L:
8288 bios_dir = optarg;
8289 break;
8290 case QEMU_OPTION_bios:
8291 bios_name = optarg;
8292 break;
8293 case QEMU_OPTION_S:
8294 autostart = 0;
8295 break;
8296 case QEMU_OPTION_k:
8297 keyboard_layout = optarg;
8298 break;
8299 case QEMU_OPTION_localtime:
8300 rtc_utc = 0;
8301 break;
8302 case QEMU_OPTION_cirrusvga:
8303 cirrus_vga_enabled = 1;
8304 vmsvga_enabled = 0;
8305 break;
8306 case QEMU_OPTION_vmsvga:
8307 cirrus_vga_enabled = 0;
8308 vmsvga_enabled = 1;
8309 break;
8310 case QEMU_OPTION_std_vga:
8311 cirrus_vga_enabled = 0;
8312 vmsvga_enabled = 0;
8313 break;
8314 case QEMU_OPTION_g:
8315 {
8316 const char *p;
8317 int w, h, depth;
8318 p = optarg;
8319 w = strtol(p, (char **)&p, 10);
8320 if (w <= 0) {
8321 graphic_error:
8322 fprintf(stderr, "qemu: invalid resolution or depth\n");
8323 exit(1);
8324 }
8325 if (*p != 'x')
8326 goto graphic_error;
8327 p++;
8328 h = strtol(p, (char **)&p, 10);
8329 if (h <= 0)
8330 goto graphic_error;
8331 if (*p == 'x') {
8332 p++;
8333 depth = strtol(p, (char **)&p, 10);
8334 if (depth != 8 && depth != 15 && depth != 16 &&
8335 depth != 24 && depth != 32)
8336 goto graphic_error;
8337 } else if (*p == '\0') {
8338 depth = graphic_depth;
8339 } else {
8340 goto graphic_error;
8341 }
8342
8343 graphic_width = w;
8344 graphic_height = h;
8345 graphic_depth = depth;
8346 }
8347 break;
8348 case QEMU_OPTION_echr:
8349 {
8350 char *r;
8351 term_escape_char = strtol(optarg, &r, 0);
8352 if (r == optarg)
8353 printf("Bad argument to echr\n");
8354 break;
8355 }
8356 case QEMU_OPTION_monitor:
8357 monitor_device = optarg;
8358 break;
8359 case QEMU_OPTION_serial:
8360 if (serial_device_index >= MAX_SERIAL_PORTS) {
8361 fprintf(stderr, "qemu: too many serial ports\n");
8362 exit(1);
8363 }
8364 serial_devices[serial_device_index] = optarg;
8365 serial_device_index++;
8366 break;
8367 case QEMU_OPTION_parallel:
8368 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8369 fprintf(stderr, "qemu: too many parallel ports\n");
8370 exit(1);
8371 }
8372 parallel_devices[parallel_device_index] = optarg;
8373 parallel_device_index++;
8374 break;
8375 case QEMU_OPTION_loadvm:
8376 loadvm = optarg;
8377 break;
8378 case QEMU_OPTION_full_screen:
8379 full_screen = 1;
8380 break;
8381 #ifdef CONFIG_SDL
8382 case QEMU_OPTION_no_frame:
8383 no_frame = 1;
8384 break;
8385 case QEMU_OPTION_alt_grab:
8386 alt_grab = 1;
8387 break;
8388 case QEMU_OPTION_no_quit:
8389 no_quit = 1;
8390 break;
8391 #endif
8392 case QEMU_OPTION_pidfile:
8393 pid_file = optarg;
8394 break;
8395 #ifdef TARGET_I386
8396 case QEMU_OPTION_win2k_hack:
8397 win2k_install_hack = 1;
8398 break;
8399 #endif
8400 #ifdef USE_KQEMU
8401 case QEMU_OPTION_no_kqemu:
8402 kqemu_allowed = 0;
8403 break;
8404 case QEMU_OPTION_kernel_kqemu:
8405 kqemu_allowed = 2;
8406 break;
8407 #endif
8408 case QEMU_OPTION_usb:
8409 usb_enabled = 1;
8410 break;
8411 case QEMU_OPTION_usbdevice:
8412 usb_enabled = 1;
8413 if (usb_devices_index >= MAX_USB_CMDLINE) {
8414 fprintf(stderr, "Too many USB devices\n");
8415 exit(1);
8416 }
8417 usb_devices[usb_devices_index] = optarg;
8418 usb_devices_index++;
8419 break;
8420 case QEMU_OPTION_smp:
8421 smp_cpus = atoi(optarg);
8422 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8423 fprintf(stderr, "Invalid number of CPUs\n");
8424 exit(1);
8425 }
8426 break;
8427 case QEMU_OPTION_vnc:
8428 vnc_display = optarg;
8429 break;
8430 case QEMU_OPTION_no_acpi:
8431 acpi_enabled = 0;
8432 break;
8433 case QEMU_OPTION_no_reboot:
8434 no_reboot = 1;
8435 break;
8436 case QEMU_OPTION_no_shutdown:
8437 no_shutdown = 1;
8438 break;
8439 case QEMU_OPTION_show_cursor:
8440 cursor_hide = 0;
8441 break;
8442 case QEMU_OPTION_daemonize:
8443 daemonize = 1;
8444 break;
8445 case QEMU_OPTION_option_rom:
8446 if (nb_option_roms >= MAX_OPTION_ROMS) {
8447 fprintf(stderr, "Too many option ROMs\n");
8448 exit(1);
8449 }
8450 option_rom[nb_option_roms] = optarg;
8451 nb_option_roms++;
8452 break;
8453 case QEMU_OPTION_semihosting:
8454 semihosting_enabled = 1;
8455 break;
8456 case QEMU_OPTION_name:
8457 qemu_name = optarg;
8458 break;
8459 #ifdef TARGET_SPARC
8460 case QEMU_OPTION_prom_env:
8461 if (nb_prom_envs >= MAX_PROM_ENVS) {
8462 fprintf(stderr, "Too many prom variables\n");
8463 exit(1);
8464 }
8465 prom_envs[nb_prom_envs] = optarg;
8466 nb_prom_envs++;
8467 break;
8468 #endif
8469 #ifdef TARGET_ARM
8470 case QEMU_OPTION_old_param:
8471 old_param = 1;
8472 break;
8473 #endif
8474 case QEMU_OPTION_clock:
8475 configure_alarms(optarg);
8476 break;
8477 case QEMU_OPTION_startdate:
8478 {
8479 struct tm tm;
8480 time_t rtc_start_date;
8481 if (!strcmp(optarg, "now")) {
8482 rtc_date_offset = -1;
8483 } else {
8484 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8485 &tm.tm_year,
8486 &tm.tm_mon,
8487 &tm.tm_mday,
8488 &tm.tm_hour,
8489 &tm.tm_min,
8490 &tm.tm_sec) == 6) {
8491 /* OK */
8492 } else if (sscanf(optarg, "%d-%d-%d",
8493 &tm.tm_year,
8494 &tm.tm_mon,
8495 &tm.tm_mday) == 3) {
8496 tm.tm_hour = 0;
8497 tm.tm_min = 0;
8498 tm.tm_sec = 0;
8499 } else {
8500 goto date_fail;
8501 }
8502 tm.tm_year -= 1900;
8503 tm.tm_mon--;
8504 rtc_start_date = mktimegm(&tm);
8505 if (rtc_start_date == -1) {
8506 date_fail:
8507 fprintf(stderr, "Invalid date format. Valid format are:\n"
8508 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8509 exit(1);
8510 }
8511 rtc_date_offset = time(NULL) - rtc_start_date;
8512 }
8513 }
8514 break;
8515 case QEMU_OPTION_tb_size:
8516 tb_size = strtol(optarg, NULL, 0);
8517 if (tb_size < 0)
8518 tb_size = 0;
8519 break;
8520 case QEMU_OPTION_icount:
8521 use_icount = 1;
8522 if (strcmp(optarg, "auto") == 0) {
8523 icount_time_shift = -1;
8524 } else {
8525 icount_time_shift = strtol(optarg, NULL, 0);
8526 }
8527 break;
8528 }
8529 }
8530 }
8531
8532 #ifndef _WIN32
8533 if (daemonize && !nographic && vnc_display == NULL) {
8534 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8535 daemonize = 0;
8536 }
8537
8538 if (daemonize) {
8539 pid_t pid;
8540
8541 if (pipe(fds) == -1)
8542 exit(1);
8543
8544 pid = fork();
8545 if (pid > 0) {
8546 uint8_t status;
8547 ssize_t len;
8548
8549 close(fds[1]);
8550
8551 again:
8552 len = read(fds[0], &status, 1);
8553 if (len == -1 && (errno == EINTR))
8554 goto again;
8555
8556 if (len != 1)
8557 exit(1);
8558 else if (status == 1) {
8559 fprintf(stderr, "Could not acquire pidfile\n");
8560 exit(1);
8561 } else
8562 exit(0);
8563 } else if (pid < 0)
8564 exit(1);
8565
8566 setsid();
8567
8568 pid = fork();
8569 if (pid > 0)
8570 exit(0);
8571 else if (pid < 0)
8572 exit(1);
8573
8574 umask(027);
8575 chdir("/");
8576
8577 signal(SIGTSTP, SIG_IGN);
8578 signal(SIGTTOU, SIG_IGN);
8579 signal(SIGTTIN, SIG_IGN);
8580 }
8581 #endif
8582
8583 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8584 if (daemonize) {
8585 uint8_t status = 1;
8586 write(fds[1], &status, 1);
8587 } else
8588 fprintf(stderr, "Could not acquire pid file\n");
8589 exit(1);
8590 }
8591
8592 #ifdef USE_KQEMU
8593 if (smp_cpus > 1)
8594 kqemu_allowed = 0;
8595 #endif
8596 linux_boot = (kernel_filename != NULL);
8597 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8598
8599 /* XXX: this should not be: some embedded targets just have flash */
8600 if (!linux_boot && net_boot == 0 &&
8601 nb_drives_opt == 0)
8602 help(1);
8603
8604 if (!linux_boot && *kernel_cmdline != '\0') {
8605 fprintf(stderr, "-append only allowed with -kernel option\n");
8606 exit(1);
8607 }
8608
8609 if (!linux_boot && initrd_filename != NULL) {
8610 fprintf(stderr, "-initrd only allowed with -kernel option\n");
8611 exit(1);
8612 }
8613
8614 /* boot to floppy or the default cd if no hard disk defined yet */
8615 if (!boot_devices[0]) {
8616 boot_devices = "cad";
8617 }
8618 setvbuf(stdout, NULL, _IOLBF, 0);
8619
8620 init_timers();
8621 init_timer_alarm();
8622 qemu_aio_init();
8623 if (use_icount && icount_time_shift < 0) {
8624 use_icount = 2;
8625 /* 125MIPS seems a reasonable initial guess at the guest speed.
8626 It will be corrected fairly quickly anyway. */
8627 icount_time_shift = 3;
8628 init_icount_adjust();
8629 }
8630
8631 #ifdef _WIN32
8632 socket_init();
8633 #endif
8634
8635 /* init network clients */
8636 if (nb_net_clients == 0) {
8637 /* if no clients, we use a default config */
8638 net_clients[0] = "nic";
8639 net_clients[1] = "user";
8640 nb_net_clients = 2;
8641 }
8642
8643 for(i = 0;i < nb_net_clients; i++) {
8644 if (net_client_init(net_clients[i]) < 0)
8645 exit(1);
8646 }
8647 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8648 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8649 continue;
8650 if (vlan->nb_guest_devs == 0) {
8651 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8652 exit(1);
8653 }
8654 if (vlan->nb_host_devs == 0)
8655 fprintf(stderr,
8656 "Warning: vlan %d is not connected to host network\n",
8657 vlan->id);
8658 }
8659
8660 #ifdef TARGET_I386
8661 /* XXX: this should be moved in the PC machine instantiation code */
8662 if (net_boot != 0) {
8663 int netroms = 0;
8664 for (i = 0; i < nb_nics && i < 4; i++) {
8665 const char *model = nd_table[i].model;
8666 char buf[1024];
8667 if (net_boot & (1 << i)) {
8668 if (model == NULL)
8669 model = "ne2k_pci";
8670 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8671 if (get_image_size(buf) > 0) {
8672 if (nb_option_roms >= MAX_OPTION_ROMS) {
8673 fprintf(stderr, "Too many option ROMs\n");
8674 exit(1);
8675 }
8676 option_rom[nb_option_roms] = strdup(buf);
8677 nb_option_roms++;
8678 netroms++;
8679 }
8680 }
8681 }
8682 if (netroms == 0) {
8683 fprintf(stderr, "No valid PXE rom found for network device\n");
8684 exit(1);
8685 }
8686 }
8687 #endif
8688
8689 /* init the memory */
8690 phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
8691
8692 if (machine->ram_require & RAMSIZE_FIXED) {
8693 if (ram_size > 0) {
8694 if (ram_size < phys_ram_size) {
8695 fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
8696 machine->name, (unsigned long long) phys_ram_size);
8697 exit(-1);
8698 }
8699
8700 phys_ram_size = ram_size;
8701 } else
8702 ram_size = phys_ram_size;
8703 } else {
8704 if (ram_size == 0)
8705 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8706
8707 phys_ram_size += ram_size;
8708 }
8709
8710 phys_ram_base = qemu_vmalloc(phys_ram_size);
8711 if (!phys_ram_base) {
8712 fprintf(stderr, "Could not allocate physical memory\n");
8713 exit(1);
8714 }
8715
8716 /* init the dynamic translator */
8717 cpu_exec_init_all(tb_size * 1024 * 1024);
8718
8719 bdrv_init();
8720
8721 /* we always create the cdrom drive, even if no disk is there */
8722
8723 if (nb_drives_opt < MAX_DRIVES)
8724 drive_add(NULL, CDROM_ALIAS);
8725
8726 /* we always create at least one floppy */
8727
8728 if (nb_drives_opt < MAX_DRIVES)
8729 drive_add(NULL, FD_ALIAS, 0);
8730
8731 /* we always create one sd slot, even if no card is in it */
8732
8733 if (nb_drives_opt < MAX_DRIVES)
8734 drive_add(NULL, SD_ALIAS);
8735
8736 /* open the virtual block devices */
8737
8738 for(i = 0; i < nb_drives_opt; i++)
8739 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8740 exit(1);
8741
8742 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8743 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8744
8745 init_ioports();
8746
8747 /* terminal init */
8748 memset(&display_state, 0, sizeof(display_state));
8749 if (nographic) {
8750 if (curses) {
8751 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
8752 exit(1);
8753 }
8754 /* nearly nothing to do */
8755 dumb_display_init(ds);
8756 } else if (vnc_display != NULL) {
8757 vnc_display_init(ds);
8758 if (vnc_display_open(ds, vnc_display) < 0)
8759 exit(1);
8760 } else
8761 #if defined(CONFIG_CURSES)
8762 if (curses) {
8763 curses_display_init(ds, full_screen);
8764 } else
8765 #endif
8766 {
8767 #if defined(CONFIG_SDL)
8768 sdl_display_init(ds, full_screen, no_frame);
8769 #elif defined(CONFIG_COCOA)
8770 cocoa_display_init(ds, full_screen);
8771 #else
8772 dumb_display_init(ds);
8773 #endif
8774 }
8775
8776 /* Maintain compatibility with multiple stdio monitors */
8777 if (!strcmp(monitor_device,"stdio")) {
8778 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8779 const char *devname = serial_devices[i];
8780 if (devname && !strcmp(devname,"mon:stdio")) {
8781 monitor_device = NULL;
8782 break;
8783 } else if (devname && !strcmp(devname,"stdio")) {
8784 monitor_device = NULL;
8785 serial_devices[i] = "mon:stdio";
8786 break;
8787 }
8788 }
8789 }
8790 if (monitor_device) {
8791 monitor_hd = qemu_chr_open(monitor_device);
8792 if (!monitor_hd) {
8793 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8794 exit(1);
8795 }
8796 monitor_init(monitor_hd, !nographic);
8797 }
8798
8799 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8800 const char *devname = serial_devices[i];
8801 if (devname && strcmp(devname, "none")) {
8802 serial_hds[i] = qemu_chr_open(devname);
8803 if (!serial_hds[i]) {
8804 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8805 devname);
8806 exit(1);
8807 }
8808 if (strstart(devname, "vc", 0))
8809 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8810 }
8811 }
8812
8813 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8814 const char *devname = parallel_devices[i];
8815 if (devname && strcmp(devname, "none")) {
8816 parallel_hds[i] = qemu_chr_open(devname);
8817 if (!parallel_hds[i]) {
8818 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8819 devname);
8820 exit(1);
8821 }
8822 if (strstart(devname, "vc", 0))
8823 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8824 }
8825 }
8826
8827 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8828 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8829
8830 /* init USB devices */
8831 if (usb_enabled) {
8832 for(i = 0; i < usb_devices_index; i++) {
8833 if (usb_device_add(usb_devices[i]) < 0) {
8834 fprintf(stderr, "Warning: could not add USB device %s\n",
8835 usb_devices[i]);
8836 }
8837 }
8838 }
8839
8840 if (display_state.dpy_refresh) {
8841 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8842 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8843 }
8844
8845 #ifdef CONFIG_GDBSTUB
8846 if (use_gdbstub) {
8847 /* XXX: use standard host:port notation and modify options
8848 accordingly. */
8849 if (gdbserver_start(gdbstub_port) < 0) {
8850 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8851 gdbstub_port);
8852 exit(1);
8853 }
8854 }
8855 #endif
8856
8857 if (loadvm)
8858 do_loadvm(loadvm);
8859
8860 {
8861 /* XXX: simplify init */
8862 read_passwords();
8863 if (autostart) {
8864 vm_start();
8865 }
8866 }
8867
8868 if (daemonize) {
8869 uint8_t status = 0;
8870 ssize_t len;
8871 int fd;
8872
8873 again1:
8874 len = write(fds[1], &status, 1);
8875 if (len == -1 && (errno == EINTR))
8876 goto again1;
8877
8878 if (len != 1)
8879 exit(1);
8880
8881 TFR(fd = open("/dev/null", O_RDWR));
8882 if (fd == -1)
8883 exit(1);
8884
8885 dup2(fd, 0);
8886 dup2(fd, 1);
8887 dup2(fd, 2);
8888
8889 close(fd);
8890 }
8891
8892 main_loop();
8893 quit_timers();
8894
8895 #if !defined(_WIN32)
8896 /* close network clients */
8897 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8898 VLANClientState *vc;
8899
8900 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8901 if (vc->fd_read == tap_receive) {
8902 char ifname[64];
8903 TAPState *s = vc->opaque;
8904
8905 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8906 s->down_script[0])
8907 launch_script(s->down_script, ifname, s->fd);
8908 }
8909 }
8910 }
8911 #endif
8912 return 0;
8913 }