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