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