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