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