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