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