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