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