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