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