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