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