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