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