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