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