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