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