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