]> git.proxmox.com Git - qemu.git/blame - vl.c
Update TNF bit in I2C status register, original patch by Juergen Lock.
[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 2925 if (!strcmp(filename, "vc")) {
af3a9031
TS
2926 return text_console_init(&display_state, 0);
2927 } else if (strstart(filename, "vc:", &p)) {
2928 return text_console_init(&display_state, p);
82c643ff
FB
2929 } else if (!strcmp(filename, "null")) {
2930 return qemu_chr_open_null();
7664728b 2931 } else
0bab00f3 2932 if (strstart(filename, "tcp:", &p)) {
ffd843bc 2933 return qemu_chr_open_tcp(p, 0, 0);
0bab00f3 2934 } else
951f1351 2935 if (strstart(filename, "telnet:", &p)) {
ffd843bc 2936 return qemu_chr_open_tcp(p, 1, 0);
0bab00f3
FB
2937 } else
2938 if (strstart(filename, "udp:", &p)) {
2939 return qemu_chr_open_udp(p);
2940 } else
20d8a3ed
TS
2941 if (strstart(filename, "mon:", &p)) {
2942 CharDriverState *drv = qemu_chr_open(p);
2943 if (drv) {
2944 drv = qemu_chr_open_mux(drv);
2945 monitor_init(drv, !nographic);
2946 return drv;
2947 }
2948 printf("Unable to open driver: %s\n", p);
2949 return 0;
2950 } else
7664728b 2951#ifndef _WIN32
ffd843bc
TS
2952 if (strstart(filename, "unix:", &p)) {
2953 return qemu_chr_open_tcp(p, 0, 1);
2954 } else if (strstart(filename, "file:", &p)) {
f8d179e3
FB
2955 return qemu_chr_open_file_out(p);
2956 } else if (strstart(filename, "pipe:", &p)) {
2957 return qemu_chr_open_pipe(p);
7664728b 2958 } else if (!strcmp(filename, "pty")) {
82c643ff
FB
2959 return qemu_chr_open_pty();
2960 } else if (!strcmp(filename, "stdio")) {
2961 return qemu_chr_open_stdio();
2962 } else
f8d179e3 2963#if defined(__linux__)
e57a8c0e
FB
2964 if (strstart(filename, "/dev/parport", NULL)) {
2965 return qemu_chr_open_pp(filename);
2966 } else
aec62507 2967#endif
3fda388a 2968#if defined(__linux__) || defined(__sun__)
f8d179e3
FB
2969 if (strstart(filename, "/dev/", NULL)) {
2970 return qemu_chr_open_tty(filename);
3fda388a
TS
2971 } else
2972#endif
aec62507 2973#else /* !_WIN32 */
f331110f
FB
2974 if (strstart(filename, "COM", NULL)) {
2975 return qemu_chr_open_win(filename);
2976 } else
2977 if (strstart(filename, "pipe:", &p)) {
2978 return qemu_chr_open_win_pipe(p);
2979 } else
72d46479
TS
2980 if (strstart(filename, "con:", NULL)) {
2981 return qemu_chr_open_win_con(filename);
2982 } else
f331110f
FB
2983 if (strstart(filename, "file:", &p)) {
2984 return qemu_chr_open_win_file_out(p);
2985 }
82c643ff
FB
2986#endif
2987 {
2988 return NULL;
2989 }
2990}
2991
f331110f
FB
2992void qemu_chr_close(CharDriverState *chr)
2993{
2994 if (chr->chr_close)
2995 chr->chr_close(chr);
2996}
2997
80cabfad 2998/***********************************************************/
7c9d8e07 2999/* network device redirectors */
330d0414 3000
c20709aa
FB
3001void hex_dump(FILE *f, const uint8_t *buf, int size)
3002{
3003 int len, i, j, c;
3004
3005 for(i=0;i<size;i+=16) {
3006 len = size - i;
3007 if (len > 16)
3008 len = 16;
3009 fprintf(f, "%08x ", i);
3010 for(j=0;j<16;j++) {
3011 if (j < len)
3012 fprintf(f, " %02x", buf[i+j]);
3013 else
3014 fprintf(f, " ");
3015 }
3016 fprintf(f, " ");
3017 for(j=0;j<len;j++) {
3018 c = buf[i+j];
3019 if (c < ' ' || c > '~')
3020 c = '.';
3021 fprintf(f, "%c", c);
3022 }
3023 fprintf(f, "\n");
3024 }
3025}
3026
7c9d8e07 3027static int parse_macaddr(uint8_t *macaddr, const char *p)
c20709aa 3028{
7c9d8e07
FB
3029 int i;
3030 for(i = 0; i < 6; i++) {
3031 macaddr[i] = strtol(p, (char **)&p, 16);
3032 if (i == 5) {
3033 if (*p != '\0')
3034 return -1;
3035 } else {
3036 if (*p != ':')
3037 return -1;
3038 p++;
3039 }
3040 }
3041 return 0;
c20709aa 3042}
67b915a5 3043
7c9d8e07 3044static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
67b915a5 3045{
7c9d8e07
FB
3046 const char *p, *p1;
3047 int len;
3048 p = *pp;
3049 p1 = strchr(p, sep);
3050 if (!p1)
3051 return -1;
3052 len = p1 - p;
3053 p1++;
3054 if (buf_size > 0) {
3055 if (len > buf_size - 1)
3056 len = buf_size - 1;
3057 memcpy(buf, p, len);
3058 buf[len] = '\0';
3059 }
3060 *pp = p1;
3061 return 0;
c20709aa
FB
3062}
3063
951f1351
FB
3064int parse_host_src_port(struct sockaddr_in *haddr,
3065 struct sockaddr_in *saddr,
3066 const char *input_str)
3067{
3068 char *str = strdup(input_str);
3069 char *host_str = str;
3070 char *src_str;
3071 char *ptr;
3072
3073 /*
3074 * Chop off any extra arguments at the end of the string which
3075 * would start with a comma, then fill in the src port information
3076 * if it was provided else use the "any address" and "any port".
3077 */
3078 if ((ptr = strchr(str,',')))
3079 *ptr = '\0';
3080
3081 if ((src_str = strchr(input_str,'@'))) {
3082 *src_str = '\0';
3083 src_str++;
3084 }
3085
3086 if (parse_host_port(haddr, host_str) < 0)
3087 goto fail;
3088
3089 if (!src_str || *src_str == '\0')
3090 src_str = ":0";
3091
3092 if (parse_host_port(saddr, src_str) < 0)
3093 goto fail;
3094
3095 free(str);
3096 return(0);
3097
3098fail:
3099 free(str);
3100 return -1;
3101}
3102
7c9d8e07
FB
3103int parse_host_port(struct sockaddr_in *saddr, const char *str)
3104{
3105 char buf[512];
3106 struct hostent *he;
3107 const char *p, *r;
3108 int port;
3109
3110 p = str;
3111 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3112 return -1;
3113 saddr->sin_family = AF_INET;
3114 if (buf[0] == '\0') {
3115 saddr->sin_addr.s_addr = 0;
3116 } else {
3117 if (isdigit(buf[0])) {
3118 if (!inet_aton(buf, &saddr->sin_addr))
3119 return -1;
3120 } else {
7c9d8e07
FB
3121 if ((he = gethostbyname(buf)) == NULL)
3122 return - 1;
3123 saddr->sin_addr = *(struct in_addr *)he->h_addr;
7c9d8e07
FB
3124 }
3125 }
3126 port = strtol(p, (char **)&r, 0);
3127 if (r == p)
3128 return -1;
3129 saddr->sin_port = htons(port);
3130 return 0;
3131}
c20709aa 3132
52f61fde
TS
3133#ifndef _WIN32
3134static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
ffd843bc
TS
3135{
3136 const char *p;
3137 int len;
3138
3139 len = MIN(108, strlen(str));
3140 p = strchr(str, ',');
3141 if (p)
3142 len = MIN(len, p - str);
3143
3144 memset(uaddr, 0, sizeof(*uaddr));
3145
3146 uaddr->sun_family = AF_UNIX;
3147 memcpy(uaddr->sun_path, str, len);
3148
3149 return 0;
3150}
52f61fde 3151#endif
ffd843bc 3152
7c9d8e07
FB
3153/* find or alloc a new VLAN */
3154VLANState *qemu_find_vlan(int id)
c20709aa 3155{
7c9d8e07
FB
3156 VLANState **pvlan, *vlan;
3157 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3158 if (vlan->id == id)
3159 return vlan;
3160 }
3161 vlan = qemu_mallocz(sizeof(VLANState));
3162 if (!vlan)
3163 return NULL;
3164 vlan->id = id;
3165 vlan->next = NULL;
3166 pvlan = &first_vlan;
3167 while (*pvlan != NULL)
3168 pvlan = &(*pvlan)->next;
3169 *pvlan = vlan;
3170 return vlan;
c20709aa
FB
3171}
3172
7c9d8e07 3173VLANClientState *qemu_new_vlan_client(VLANState *vlan,
d861b05e
PB
3174 IOReadHandler *fd_read,
3175 IOCanRWHandler *fd_can_read,
3176 void *opaque)
c20709aa 3177{
7c9d8e07
FB
3178 VLANClientState *vc, **pvc;
3179 vc = qemu_mallocz(sizeof(VLANClientState));
3180 if (!vc)
3181 return NULL;
3182 vc->fd_read = fd_read;
d861b05e 3183 vc->fd_can_read = fd_can_read;
7c9d8e07
FB
3184 vc->opaque = opaque;
3185 vc->vlan = vlan;
3186
3187 vc->next = NULL;
3188 pvc = &vlan->first_client;
3189 while (*pvc != NULL)
3190 pvc = &(*pvc)->next;
3191 *pvc = vc;
3192 return vc;
c20709aa
FB
3193}
3194
d861b05e
PB
3195int qemu_can_send_packet(VLANClientState *vc1)
3196{
3197 VLANState *vlan = vc1->vlan;
3198 VLANClientState *vc;
3199
3200 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3201 if (vc != vc1) {
fbd1711d
AZ
3202 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3203 return 1;
d861b05e
PB
3204 }
3205 }
fbd1711d 3206 return 0;
d861b05e
PB
3207}
3208
7c9d8e07 3209void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
c20709aa 3210{
7c9d8e07
FB
3211 VLANState *vlan = vc1->vlan;
3212 VLANClientState *vc;
3213
3214#if 0
3215 printf("vlan %d send:\n", vlan->id);
3216 hex_dump(stdout, buf, size);
3217#endif
3218 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3219 if (vc != vc1) {
3220 vc->fd_read(vc->opaque, buf, size);
3221 }
3222 }
67b915a5
FB
3223}
3224
c20709aa
FB
3225#if defined(CONFIG_SLIRP)
3226
3227/* slirp network adapter */
3228
c20709aa 3229static int slirp_inited;
7c9d8e07 3230static VLANClientState *slirp_vc;
c20709aa
FB
3231
3232int slirp_can_output(void)
3233{
3b7f5d47 3234 return !slirp_vc || qemu_can_send_packet(slirp_vc);
c20709aa
FB
3235}
3236
3237void slirp_output(const uint8_t *pkt, int pkt_len)
67b915a5 3238{
c20709aa 3239#if 0
7c9d8e07 3240 printf("slirp output:\n");
c20709aa
FB
3241 hex_dump(stdout, pkt, pkt_len);
3242#endif
3b7f5d47
PB
3243 if (!slirp_vc)
3244 return;
7c9d8e07 3245 qemu_send_packet(slirp_vc, pkt, pkt_len);
67b915a5
FB
3246}
3247
7c9d8e07 3248static void slirp_receive(void *opaque, const uint8_t *buf, int size)
c20709aa
FB
3249{
3250#if 0
7c9d8e07 3251 printf("slirp input:\n");
c20709aa
FB
3252 hex_dump(stdout, buf, size);
3253#endif
3254 slirp_input(buf, size);
3255}
3256
7c9d8e07 3257static int net_slirp_init(VLANState *vlan)
c20709aa
FB
3258{
3259 if (!slirp_inited) {
3260 slirp_inited = 1;
3261 slirp_init();
3262 }
7c9d8e07 3263 slirp_vc = qemu_new_vlan_client(vlan,
d861b05e 3264 slirp_receive, NULL, NULL);
7c9d8e07 3265 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
9bf05444
FB
3266 return 0;
3267}
3268
3269static void net_slirp_redir(const char *redir_str)
3270{
3271 int is_udp;
3272 char buf[256], *r;
3273 const char *p;
3274 struct in_addr guest_addr;
3275 int host_port, guest_port;
3276
3277 if (!slirp_inited) {
3278 slirp_inited = 1;
3279 slirp_init();
3280 }
3281
3282 p = redir_str;
3283 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3284 goto fail;
3285 if (!strcmp(buf, "tcp")) {
3286 is_udp = 0;
3287 } else if (!strcmp(buf, "udp")) {
3288 is_udp = 1;
3289 } else {
3290 goto fail;
3291 }
3292
3293 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3294 goto fail;
3295 host_port = strtol(buf, &r, 0);
3296 if (r == buf)
3297 goto fail;
3298
3299 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3300 goto fail;
3301 if (buf[0] == '\0') {
3302 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3303 }
3304 if (!inet_aton(buf, &guest_addr))
3305 goto fail;
3306
3307 guest_port = strtol(p, &r, 0);
3308 if (r == p)
3309 goto fail;
3310
3311 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3312 fprintf(stderr, "qemu: could not set up redirection\n");
3313 exit(1);
3314 }
3315 return;
3316 fail:
3317 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3318 exit(1);
3319}
9d728e8c 3320
c94c8d64
FB
3321#ifndef _WIN32
3322
9d728e8c
FB
3323char smb_dir[1024];
3324
3325static void smb_exit(void)
3326{
3327 DIR *d;
3328 struct dirent *de;
3329 char filename[1024];
3330
3331 /* erase all the files in the directory */
3332 d = opendir(smb_dir);
3333 for(;;) {
3334 de = readdir(d);
3335 if (!de)
3336 break;
3337 if (strcmp(de->d_name, ".") != 0 &&
3338 strcmp(de->d_name, "..") != 0) {
3339 snprintf(filename, sizeof(filename), "%s/%s",
3340 smb_dir, de->d_name);
3341 unlink(filename);
3342 }
3343 }
03ffbb69 3344 closedir(d);
9d728e8c
FB
3345 rmdir(smb_dir);
3346}
3347
3348/* automatic user mode samba server configuration */
3349void net_slirp_smb(const char *exported_dir)
3350{
3351 char smb_conf[1024];
3352 char smb_cmdline[1024];
3353 FILE *f;
3354
3355 if (!slirp_inited) {
3356 slirp_inited = 1;
3357 slirp_init();
3358 }
3359
3360 /* XXX: better tmp dir construction */
3361 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3362 if (mkdir(smb_dir, 0700) < 0) {
3363 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3364 exit(1);
3365 }
3366 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3367
3368 f = fopen(smb_conf, "w");
3369 if (!f) {
3370 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3371 exit(1);
3372 }
3373 fprintf(f,
3374 "[global]\n"
157777ef
FB
3375 "private dir=%s\n"
3376 "smb ports=0\n"
3377 "socket address=127.0.0.1\n"
9d728e8c
FB
3378 "pid directory=%s\n"
3379 "lock directory=%s\n"
3380 "log file=%s/log.smbd\n"
3381 "smb passwd file=%s/smbpasswd\n"
03ffbb69 3382 "security = share\n"
9d728e8c
FB
3383 "[qemu]\n"
3384 "path=%s\n"
3385 "read only=no\n"
3386 "guest ok=yes\n",
3387 smb_dir,
157777ef 3388 smb_dir,
9d728e8c
FB
3389 smb_dir,
3390 smb_dir,
3391 smb_dir,
3392 exported_dir
3393 );
3394 fclose(f);
3395 atexit(smb_exit);
3396
a14d6c8c
PB
3397 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3398 SMBD_COMMAND, smb_conf);
9d728e8c
FB
3399
3400 slirp_add_exec(0, smb_cmdline, 4, 139);
3401}
9bf05444 3402
c94c8d64
FB
3403#endif /* !defined(_WIN32) */
3404
c20709aa
FB
3405#endif /* CONFIG_SLIRP */
3406
3407#if !defined(_WIN32)
7c9d8e07
FB
3408
3409typedef struct TAPState {
3410 VLANClientState *vc;
3411 int fd;
3412} TAPState;
3413
3414static void tap_receive(void *opaque, const uint8_t *buf, int size)
3415{
3416 TAPState *s = opaque;
3417 int ret;
3418 for(;;) {
3419 ret = write(s->fd, buf, size);
3420 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3421 } else {
3422 break;
3423 }
3424 }
3425}
3426
3427static void tap_send(void *opaque)
3428{
3429 TAPState *s = opaque;
3430 uint8_t buf[4096];
3431 int size;
3432
d5d10bc3
TS
3433#ifdef __sun__
3434 struct strbuf sbuf;
3435 int f = 0;
3436 sbuf.maxlen = sizeof(buf);
3437 sbuf.buf = buf;
3438 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3439#else
7c9d8e07 3440 size = read(s->fd, buf, sizeof(buf));
d5d10bc3 3441#endif
7c9d8e07
FB
3442 if (size > 0) {
3443 qemu_send_packet(s->vc, buf, size);
3444 }
3445}
3446
3447/* fd support */
3448
3449static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3450{
3451 TAPState *s;
3452
3453 s = qemu_mallocz(sizeof(TAPState));
3454 if (!s)
3455 return NULL;
3456 s->fd = fd;
d861b05e 3457 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
7c9d8e07
FB
3458 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3459 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3460 return s;
3461}
3462
5c40d2bd 3463#if defined (_BSD) || defined (__FreeBSD_kernel__)
7c9d8e07 3464static int tap_open(char *ifname, int ifname_size)
7d3505c5
FB
3465{
3466 int fd;
3467 char *dev;
3468 struct stat s;
67b915a5 3469
aeb30be6 3470 TFR(fd = open("/dev/tap", O_RDWR));
7d3505c5
FB
3471 if (fd < 0) {
3472 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3473 return -1;
3474 }
3475
3476 fstat(fd, &s);
3477 dev = devname(s.st_rdev, S_IFCHR);
3478 pstrcpy(ifname, ifname_size, dev);
3479
3480 fcntl(fd, F_SETFL, O_NONBLOCK);
3481 return fd;
3482}
ec530c81 3483#elif defined(__sun__)
d5d10bc3
TS
3484#define TUNNEWPPA (('T'<<16) | 0x0001)
3485/*
3486 * Allocate TAP device, returns opened fd.
3487 * Stores dev name in the first arg(must be large enough).
3488 */
3489int tap_alloc(char *dev)
3490{
3491 int tap_fd, if_fd, ppa = -1;
3492 static int ip_fd = 0;
3493 char *ptr;
3494
3495 static int arp_fd = 0;
3496 int ip_muxid, arp_muxid;
3497 struct strioctl strioc_if, strioc_ppa;
3498 int link_type = I_PLINK;;
3499 struct lifreq ifr;
3500 char actual_name[32] = "";
3501
3502 memset(&ifr, 0x0, sizeof(ifr));
3503
3504 if( *dev ){
3505 ptr = dev;
3506 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3507 ppa = atoi(ptr);
3508 }
3509
3510 /* Check if IP device was opened */
3511 if( ip_fd )
3512 close(ip_fd);
3513
aeb30be6
AZ
3514 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3515 if (ip_fd < 0) {
d5d10bc3
TS
3516 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3517 return -1;
3518 }
3519
aeb30be6
AZ
3520 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3521 if (tap_fd < 0) {
d5d10bc3
TS
3522 syslog(LOG_ERR, "Can't open /dev/tap");
3523 return -1;
3524 }
3525
3526 /* Assign a new PPA and get its unit number. */
3527 strioc_ppa.ic_cmd = TUNNEWPPA;
3528 strioc_ppa.ic_timout = 0;
3529 strioc_ppa.ic_len = sizeof(ppa);
3530 strioc_ppa.ic_dp = (char *)&ppa;
3531 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3532 syslog (LOG_ERR, "Can't assign new interface");
3533
aeb30be6
AZ
3534 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3535 if (if_fd < 0) {
d5d10bc3
TS
3536 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3537 return -1;
3538 }
3539 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3540 syslog(LOG_ERR, "Can't push IP module");
3541 return -1;
3542 }
3543
3544 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3545 syslog(LOG_ERR, "Can't get flags\n");
3546
3547 snprintf (actual_name, 32, "tap%d", ppa);
3548 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3549
3550 ifr.lifr_ppa = ppa;
3551 /* Assign ppa according to the unit number returned by tun device */
3552
3553 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3554 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3555 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3556 syslog (LOG_ERR, "Can't get flags\n");
3557 /* Push arp module to if_fd */
3558 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3559 syslog (LOG_ERR, "Can't push ARP module (2)");
3560
3561 /* Push arp module to ip_fd */
3562 if (ioctl (ip_fd, I_POP, NULL) < 0)
3563 syslog (LOG_ERR, "I_POP failed\n");
3564 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3565 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3566 /* Open arp_fd */
aeb30be6
AZ
3567 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3568 if (arp_fd < 0)
d5d10bc3
TS
3569 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3570
3571 /* Set ifname to arp */
3572 strioc_if.ic_cmd = SIOCSLIFNAME;
3573 strioc_if.ic_timout = 0;
3574 strioc_if.ic_len = sizeof(ifr);
3575 strioc_if.ic_dp = (char *)&ifr;
3576 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3577 syslog (LOG_ERR, "Can't set ifname to arp\n");
3578 }
3579
3580 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3581 syslog(LOG_ERR, "Can't link TAP device to IP");
3582 return -1;
3583 }
3584
3585 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3586 syslog (LOG_ERR, "Can't link TAP device to ARP");
3587
3588 close (if_fd);
3589
3590 memset(&ifr, 0x0, sizeof(ifr));
3591 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3592 ifr.lifr_ip_muxid = ip_muxid;
3593 ifr.lifr_arp_muxid = arp_muxid;
3594
3595 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3596 {
3597 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3598 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3599 syslog (LOG_ERR, "Can't set multiplexor id");
3600 }
3601
3602 sprintf(dev, "tap%d", ppa);
3603 return tap_fd;
3604}
3605
ec530c81
FB
3606static int tap_open(char *ifname, int ifname_size)
3607{
d5d10bc3
TS
3608 char dev[10]="";
3609 int fd;
3610 if( (fd = tap_alloc(dev)) < 0 ){
3611 fprintf(stderr, "Cannot allocate TAP device\n");
3612 return -1;
3613 }
3614 pstrcpy(ifname, ifname_size, dev);
3615 fcntl(fd, F_SETFL, O_NONBLOCK);
3616 return fd;
ec530c81 3617}
7d3505c5 3618#else
7c9d8e07 3619static int tap_open(char *ifname, int ifname_size)
330d0414 3620{
80cabfad 3621 struct ifreq ifr;
c4b1fcc0 3622 int fd, ret;
80cabfad 3623
aeb30be6 3624 TFR(fd = open("/dev/net/tun", O_RDWR));
80cabfad
FB
3625 if (fd < 0) {
3626 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3627 return -1;
330d0414 3628 }
80cabfad
FB
3629 memset(&ifr, 0, sizeof(ifr));
3630 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
7c9d8e07
FB
3631 if (ifname[0] != '\0')
3632 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3633 else
3634 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
80cabfad
FB
3635 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3636 if (ret != 0) {
3637 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3638 close(fd);
3639 return -1;
3640 }
c4b1fcc0 3641 pstrcpy(ifname, ifname_size, ifr.ifr_name);
80cabfad 3642 fcntl(fd, F_SETFL, O_NONBLOCK);
c4b1fcc0
FB
3643 return fd;
3644}
7d3505c5 3645#endif
330d0414 3646
7c9d8e07
FB
3647static int net_tap_init(VLANState *vlan, const char *ifname1,
3648 const char *setup_script)
3649{
3650 TAPState *s;
3651 int pid, status, fd;
3652 char *args[3];
3653 char **parg;
3654 char ifname[128];
3655
3656 if (ifname1 != NULL)
3657 pstrcpy(ifname, sizeof(ifname), ifname1);
3658 else
3659 ifname[0] = '\0';
aeb30be6 3660 TFR(fd = tap_open(ifname, sizeof(ifname)));
7c9d8e07
FB
3661 if (fd < 0)
3662 return -1;
3663
6a1cbf68 3664 if (!setup_script || !strcmp(setup_script, "no"))
7c9d8e07
FB
3665 setup_script = "";
3666 if (setup_script[0] != '\0') {
3667 /* try to launch network init script */
3668 pid = fork();
3669 if (pid >= 0) {
3670 if (pid == 0) {
50d3eeae
TS
3671 int open_max = sysconf (_SC_OPEN_MAX), i;
3672 for (i = 0; i < open_max; i++)
3673 if (i != STDIN_FILENO &&
3674 i != STDOUT_FILENO &&
3675 i != STDERR_FILENO &&
3676 i != fd)
3677 close(i);
3678
7c9d8e07
FB
3679 parg = args;
3680 *parg++ = (char *)setup_script;
3681 *parg++ = ifname;
3682 *parg++ = NULL;
3683 execv(setup_script, args);
4a38940d 3684 _exit(1);
7c9d8e07
FB
3685 }
3686 while (waitpid(pid, &status, 0) != pid);
3687 if (!WIFEXITED(status) ||
3688 WEXITSTATUS(status) != 0) {
3689 fprintf(stderr, "%s: could not launch network script\n",
3690 setup_script);
3691 return -1;
3692 }
3693 }
3694 }
3695 s = net_tap_fd_init(vlan, fd);
3696 if (!s)
3697 return -1;
3698 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3699 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3700 return 0;
3701}
3702
fd1dff4b
FB
3703#endif /* !_WIN32 */
3704
7c9d8e07
FB
3705/* network connection */
3706typedef struct NetSocketState {
3707 VLANClientState *vc;
3708 int fd;
3709 int state; /* 0 = getting length, 1 = getting data */
3710 int index;
3711 int packet_len;
3712 uint8_t buf[4096];
3d830459 3713 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
7c9d8e07
FB
3714} NetSocketState;
3715
3716typedef struct NetSocketListenState {
3717 VLANState *vlan;
3718 int fd;
3719} NetSocketListenState;
3720
3721/* XXX: we consider we can send the whole packet without blocking */
3722static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
c20709aa 3723{
7c9d8e07
FB
3724 NetSocketState *s = opaque;
3725 uint32_t len;
3726 len = htonl(size);
3727
fd1dff4b
FB
3728 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3729 send_all(s->fd, buf, size);
c20709aa
FB
3730}
3731
3d830459
FB
3732static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3733{
3734 NetSocketState *s = opaque;
3735 sendto(s->fd, buf, size, 0,
3736 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3737}
3738
7c9d8e07 3739static void net_socket_send(void *opaque)
c4b1fcc0 3740{
7c9d8e07 3741 NetSocketState *s = opaque;
fd1dff4b 3742 int l, size, err;
7c9d8e07
FB
3743 uint8_t buf1[4096];
3744 const uint8_t *buf;
3745
fd1dff4b
FB
3746 size = recv(s->fd, buf1, sizeof(buf1), 0);
3747 if (size < 0) {
3748 err = socket_error();
3749 if (err != EWOULDBLOCK)
3750 goto eoc;
3751 } else if (size == 0) {
7c9d8e07 3752 /* end of connection */
fd1dff4b 3753 eoc:
7c9d8e07 3754 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
fd1dff4b 3755 closesocket(s->fd);
7c9d8e07
FB
3756 return;
3757 }
3758 buf = buf1;
3759 while (size > 0) {
3760 /* reassemble a packet from the network */
3761 switch(s->state) {
3762 case 0:
3763 l = 4 - s->index;
3764 if (l > size)
3765 l = size;
3766 memcpy(s->buf + s->index, buf, l);
3767 buf += l;
3768 size -= l;
3769 s->index += l;
3770 if (s->index == 4) {
3771 /* got length */
3772 s->packet_len = ntohl(*(uint32_t *)s->buf);
3773 s->index = 0;
3774 s->state = 1;
3775 }
3776 break;
3777 case 1:
3778 l = s->packet_len - s->index;
3779 if (l > size)
3780 l = size;
3781 memcpy(s->buf + s->index, buf, l);
3782 s->index += l;
3783 buf += l;
3784 size -= l;
3785 if (s->index >= s->packet_len) {
3786 qemu_send_packet(s->vc, s->buf, s->packet_len);
3787 s->index = 0;
3788 s->state = 0;
3789 }
3790 break;
3791 }
3792 }
c20709aa
FB
3793}
3794
3d830459
FB
3795static void net_socket_send_dgram(void *opaque)
3796{
3797 NetSocketState *s = opaque;
3798 int size;
3799
3800 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3801 if (size < 0)
3802 return;
3803 if (size == 0) {
3804 /* end of connection */
3805 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3806 return;
3807 }
3808 qemu_send_packet(s->vc, s->buf, size);
3809}
3810
3811static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3812{
3813 struct ip_mreq imr;
3814 int fd;
3815 int val, ret;
3816 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3817 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
fd1dff4b
FB
3818 inet_ntoa(mcastaddr->sin_addr),
3819 (int)ntohl(mcastaddr->sin_addr.s_addr));
3d830459
FB
3820 return -1;
3821
3822 }
3823 fd = socket(PF_INET, SOCK_DGRAM, 0);
3824 if (fd < 0) {
3825 perror("socket(PF_INET, SOCK_DGRAM)");
3826 return -1;
3827 }
3828
fd1dff4b
FB
3829 val = 1;
3830 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3831 (const char *)&val, sizeof(val));
3832 if (ret < 0) {
3833 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3834 goto fail;
3835 }
3836
3837 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3838 if (ret < 0) {
3839 perror("bind");
3840 goto fail;
3841 }
3842
3d830459
FB
3843 /* Add host to multicast group */
3844 imr.imr_multiaddr = mcastaddr->sin_addr;
3845 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3846
fd1dff4b
FB
3847 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3848 (const char *)&imr, sizeof(struct ip_mreq));
3d830459
FB
3849 if (ret < 0) {
3850 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3851 goto fail;
3852 }
3853
3854 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3855 val = 1;
fd1dff4b
FB
3856 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3857 (const char *)&val, sizeof(val));
3d830459
FB
3858 if (ret < 0) {
3859 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3860 goto fail;
3861 }
3862
fd1dff4b 3863 socket_set_nonblock(fd);
3d830459
FB
3864 return fd;
3865fail:
0bab00f3
FB
3866 if (fd >= 0)
3867 closesocket(fd);
3d830459
FB
3868 return -1;
3869}
3870
3871static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3872 int is_connected)
3873{
3874 struct sockaddr_in saddr;
3875 int newfd;
3876 socklen_t saddr_len;
3877 NetSocketState *s;
3878
3879 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3880 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3881 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3882 */
3883
3884 if (is_connected) {
3885 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3886 /* must be bound */
3887 if (saddr.sin_addr.s_addr==0) {
3888 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3889 fd);
3890 return NULL;
3891 }
3892 /* clone dgram socket */
3893 newfd = net_socket_mcast_create(&saddr);
3894 if (newfd < 0) {
3895 /* error already reported by net_socket_mcast_create() */
3896 close(fd);
3897 return NULL;
3898 }
3899 /* clone newfd to fd, close newfd */
3900 dup2(newfd, fd);
3901 close(newfd);
3902
3903 } else {
3904 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3905 fd, strerror(errno));
3906 return NULL;
3907 }
3908 }
3909
3910 s = qemu_mallocz(sizeof(NetSocketState));
3911 if (!s)
3912 return NULL;
3913 s->fd = fd;
3914
d861b05e 3915 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3d830459
FB
3916 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3917
3918 /* mcast: save bound address as dst */
3919 if (is_connected) s->dgram_dst=saddr;
3920
3921 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3922 "socket: fd=%d (%s mcast=%s:%d)",
3923 fd, is_connected? "cloned" : "",
3924 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3925 return s;
3926}
3927
7c9d8e07 3928static void net_socket_connect(void *opaque)
c20709aa 3929{
7c9d8e07
FB
3930 NetSocketState *s = opaque;
3931 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3932}
c4b1fcc0 3933
3d830459 3934static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
7c9d8e07
FB
3935 int is_connected)
3936{
3937 NetSocketState *s;
3938 s = qemu_mallocz(sizeof(NetSocketState));
3939 if (!s)
3940 return NULL;
3941 s->fd = fd;
3942 s->vc = qemu_new_vlan_client(vlan,
d861b05e 3943 net_socket_receive, NULL, s);
7c9d8e07
FB
3944 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3945 "socket: fd=%d", fd);
3946 if (is_connected) {
3947 net_socket_connect(s);
3948 } else {
3949 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3950 }
3951 return s;
3952}
c4b1fcc0 3953
3d830459
FB
3954static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3955 int is_connected)
3956{
3957 int so_type=-1, optlen=sizeof(so_type);
3958
fd1dff4b 3959 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
931f03ee 3960 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3d830459
FB
3961 return NULL;
3962 }
3963 switch(so_type) {
3964 case SOCK_DGRAM:
3965 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3966 case SOCK_STREAM:
3967 return net_socket_fd_init_stream(vlan, fd, is_connected);
3968 default:
3969 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3970 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3971 return net_socket_fd_init_stream(vlan, fd, is_connected);
3972 }
3973 return NULL;
3974}
3975
7c9d8e07
FB
3976static void net_socket_accept(void *opaque)
3977{
3978 NetSocketListenState *s = opaque;
3979 NetSocketState *s1;
3980 struct sockaddr_in saddr;
3981 socklen_t len;
3982 int fd;
3983
3984 for(;;) {
3985 len = sizeof(saddr);
3986 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3987 if (fd < 0 && errno != EINTR) {
3988 return;
3989 } else if (fd >= 0) {
3990 break;
80cabfad 3991 }
330d0414 3992 }
7c9d8e07
FB
3993 s1 = net_socket_fd_init(s->vlan, fd, 1);
3994 if (!s1) {
0bab00f3 3995 closesocket(fd);
7c9d8e07
FB
3996 } else {
3997 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3998 "socket: connection from %s:%d",
3999 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4000 }
4001}
4002
4003static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4004{
4005 NetSocketListenState *s;
4006 int fd, val, ret;
4007 struct sockaddr_in saddr;
4008
4009 if (parse_host_port(&saddr, host_str) < 0)
4010 return -1;
4011
4012 s = qemu_mallocz(sizeof(NetSocketListenState));
4013 if (!s)
4014 return -1;
4015
4016 fd = socket(PF_INET, SOCK_STREAM, 0);
4017 if (fd < 0) {
4018 perror("socket");
4019 return -1;
4020 }
fd1dff4b 4021 socket_set_nonblock(fd);
7c9d8e07
FB
4022
4023 /* allow fast reuse */
4024 val = 1;
fd1dff4b 4025 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
7c9d8e07
FB
4026
4027 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4028 if (ret < 0) {
4029 perror("bind");
4030 return -1;
4031 }
4032 ret = listen(fd, 0);
4033 if (ret < 0) {
4034 perror("listen");
4035 return -1;
4036 }
4037 s->vlan = vlan;
4038 s->fd = fd;
4039 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
80cabfad 4040 return 0;
330d0414
FB
4041}
4042
7c9d8e07 4043static int net_socket_connect_init(VLANState *vlan, const char *host_str)
330d0414 4044{
7c9d8e07 4045 NetSocketState *s;
fd1dff4b 4046 int fd, connected, ret, err;
7c9d8e07
FB
4047 struct sockaddr_in saddr;
4048
4049 if (parse_host_port(&saddr, host_str) < 0)
4050 return -1;
4051
4052 fd = socket(PF_INET, SOCK_STREAM, 0);
4053 if (fd < 0) {
4054 perror("socket");
4055 return -1;
4056 }
fd1dff4b 4057 socket_set_nonblock(fd);
7c9d8e07
FB
4058
4059 connected = 0;
4060 for(;;) {
4061 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4062 if (ret < 0) {
fd1dff4b
FB
4063 err = socket_error();
4064 if (err == EINTR || err == EWOULDBLOCK) {
4065 } else if (err == EINPROGRESS) {
7c9d8e07 4066 break;
f5b12268
TS
4067#ifdef _WIN32
4068 } else if (err == WSAEALREADY) {
4069 break;
4070#endif
7c9d8e07
FB
4071 } else {
4072 perror("connect");
fd1dff4b 4073 closesocket(fd);
7c9d8e07
FB
4074 return -1;
4075 }
4076 } else {
4077 connected = 1;
4078 break;
4079 }
4080 }
4081 s = net_socket_fd_init(vlan, fd, connected);
4082 if (!s)
4083 return -1;
4084 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4085 "socket: connect to %s:%d",
4086 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
c20709aa 4087 return 0;
80cabfad 4088}
330d0414 4089
3d830459
FB
4090static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4091{
4092 NetSocketState *s;
4093 int fd;
4094 struct sockaddr_in saddr;
4095
4096 if (parse_host_port(&saddr, host_str) < 0)
4097 return -1;
4098
4099
4100 fd = net_socket_mcast_create(&saddr);
4101 if (fd < 0)
4102 return -1;
4103
4104 s = net_socket_fd_init(vlan, fd, 0);
4105 if (!s)
4106 return -1;
4107
4108 s->dgram_dst = saddr;
4109
4110 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4111 "socket: mcast=%s:%d",
4112 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4113 return 0;
4114
4115}
4116
7c9d8e07
FB
4117static int get_param_value(char *buf, int buf_size,
4118 const char *tag, const char *str)
4119{
4120 const char *p;
4121 char *q;
4122 char option[128];
4123
4124 p = str;
4125 for(;;) {
4126 q = option;
4127 while (*p != '\0' && *p != '=') {
4128 if ((q - option) < sizeof(option) - 1)
4129 *q++ = *p;
4130 p++;
4131 }
4132 *q = '\0';
4133 if (*p != '=')
4134 break;
4135 p++;
4136 if (!strcmp(tag, option)) {
4137 q = buf;
4138 while (*p != '\0' && *p != ',') {
4139 if ((q - buf) < buf_size - 1)
4140 *q++ = *p;
4141 p++;
4142 }
4143 *q = '\0';
4144 return q - buf;
4145 } else {
4146 while (*p != '\0' && *p != ',') {
4147 p++;
4148 }
4149 }
4150 if (*p != ',')
4151 break;
4152 p++;
4153 }
4154 return 0;
4155}
4156
52f61fde 4157static int net_client_init(const char *str)
7c9d8e07
FB
4158{
4159 const char *p;
4160 char *q;
4161 char device[64];
4162 char buf[1024];
4163 int vlan_id, ret;
4164 VLANState *vlan;
4165
4166 p = str;
4167 q = device;
4168 while (*p != '\0' && *p != ',') {
4169 if ((q - device) < sizeof(device) - 1)
4170 *q++ = *p;
4171 p++;
4172 }
4173 *q = '\0';
4174 if (*p == ',')
4175 p++;
4176 vlan_id = 0;
4177 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4178 vlan_id = strtol(buf, NULL, 0);
4179 }
4180 vlan = qemu_find_vlan(vlan_id);
4181 if (!vlan) {
4182 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4183 return -1;
4184 }
4185 if (!strcmp(device, "nic")) {
4186 NICInfo *nd;
4187 uint8_t *macaddr;
4188
4189 if (nb_nics >= MAX_NICS) {
4190 fprintf(stderr, "Too Many NICs\n");
4191 return -1;
4192 }
4193 nd = &nd_table[nb_nics];
4194 macaddr = nd->macaddr;
4195 macaddr[0] = 0x52;
4196 macaddr[1] = 0x54;
4197 macaddr[2] = 0x00;
4198 macaddr[3] = 0x12;
4199 macaddr[4] = 0x34;
4200 macaddr[5] = 0x56 + nb_nics;
4201
4202 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4203 if (parse_macaddr(macaddr, buf) < 0) {
4204 fprintf(stderr, "invalid syntax for ethernet address\n");
4205 return -1;
4206 }
4207 }
a41b2ff2
PB
4208 if (get_param_value(buf, sizeof(buf), "model", p)) {
4209 nd->model = strdup(buf);
4210 }
7c9d8e07
FB
4211 nd->vlan = vlan;
4212 nb_nics++;
833c7174 4213 vlan->nb_guest_devs++;
7c9d8e07
FB
4214 ret = 0;
4215 } else
4216 if (!strcmp(device, "none")) {
4217 /* does nothing. It is needed to signal that no network cards
4218 are wanted */
4219 ret = 0;
4220 } else
4221#ifdef CONFIG_SLIRP
4222 if (!strcmp(device, "user")) {
115defd1 4223 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3f423c9c 4224 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
115defd1 4225 }
833c7174 4226 vlan->nb_host_devs++;
7c9d8e07
FB
4227 ret = net_slirp_init(vlan);
4228 } else
4229#endif
7fb843f8
FB
4230#ifdef _WIN32
4231 if (!strcmp(device, "tap")) {
4232 char ifname[64];
4233 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4234 fprintf(stderr, "tap: no interface name\n");
4235 return -1;
4236 }
833c7174 4237 vlan->nb_host_devs++;
7fb843f8
FB
4238 ret = tap_win32_init(vlan, ifname);
4239 } else
4240#else
7c9d8e07
FB
4241 if (!strcmp(device, "tap")) {
4242 char ifname[64];
4243 char setup_script[1024];
4244 int fd;
4f01035f 4245 vlan->nb_host_devs++;
7c9d8e07
FB
4246 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4247 fd = strtol(buf, NULL, 0);
4248 ret = -1;
4249 if (net_tap_fd_init(vlan, fd))
4250 ret = 0;
4251 } else {
bf8c5342
FB
4252 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4253 ifname[0] = '\0';
4254 }
7c9d8e07
FB
4255 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4256 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4257 }
4258 ret = net_tap_init(vlan, ifname, setup_script);
4259 }
4260 } else
fd1dff4b 4261#endif
7c9d8e07
FB
4262 if (!strcmp(device, "socket")) {
4263 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4264 int fd;
4265 fd = strtol(buf, NULL, 0);
4266 ret = -1;
4267 if (net_socket_fd_init(vlan, fd, 1))
4268 ret = 0;
4269 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4270 ret = net_socket_listen_init(vlan, buf);
4271 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4272 ret = net_socket_connect_init(vlan, buf);
3d830459
FB
4273 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4274 ret = net_socket_mcast_init(vlan, buf);
7c9d8e07
FB
4275 } else {
4276 fprintf(stderr, "Unknown socket options: %s\n", p);
4277 return -1;
4278 }
833c7174 4279 vlan->nb_host_devs++;
7c9d8e07 4280 } else
7c9d8e07
FB
4281 {
4282 fprintf(stderr, "Unknown network device: %s\n", device);
4283 return -1;
4284 }
4285 if (ret < 0) {
4286 fprintf(stderr, "Could not initialize device '%s'\n", device);
4287 }
4288
4289 return ret;
4290}
4291
4292void do_info_network(void)
4293{
4294 VLANState *vlan;
4295 VLANClientState *vc;
4296
4297 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4298 term_printf("VLAN %d devices:\n", vlan->id);
4299 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4300 term_printf(" %s\n", vc->info_str);
4301 }
4302}
42550fde 4303
a594cfbf
FB
4304/***********************************************************/
4305/* USB devices */
4306
0d92ed30
PB
4307static USBPort *used_usb_ports;
4308static USBPort *free_usb_ports;
4309
4310/* ??? Maybe change this to register a hub to keep track of the topology. */
4311void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4312 usb_attachfn attach)
4313{
4314 port->opaque = opaque;
4315 port->index = index;
4316 port->attach = attach;
4317 port->next = free_usb_ports;
4318 free_usb_ports = port;
4319}
4320
a594cfbf
FB
4321static int usb_device_add(const char *devname)
4322{
4323 const char *p;
4324 USBDevice *dev;
0d92ed30 4325 USBPort *port;
a594cfbf 4326
0d92ed30 4327 if (!free_usb_ports)
a594cfbf
FB
4328 return -1;
4329
4330 if (strstart(devname, "host:", &p)) {
4331 dev = usb_host_device_open(p);
a594cfbf
FB
4332 } else if (!strcmp(devname, "mouse")) {
4333 dev = usb_mouse_init();
09b26c5e 4334 } else if (!strcmp(devname, "tablet")) {
47b2d338
AZ
4335 dev = usb_tablet_init();
4336 } else if (!strcmp(devname, "keyboard")) {
4337 dev = usb_keyboard_init();
2e5d83bb
PB
4338 } else if (strstart(devname, "disk:", &p)) {
4339 dev = usb_msd_init(p);
f6d2a316
AZ
4340 } else if (!strcmp(devname, "wacom-tablet")) {
4341 dev = usb_wacom_init();
a594cfbf
FB
4342 } else {
4343 return -1;
4344 }
0d92ed30
PB
4345 if (!dev)
4346 return -1;
4347
4348 /* Find a USB port to add the device to. */
4349 port = free_usb_ports;
4350 if (!port->next) {
4351 USBDevice *hub;
4352
4353 /* Create a new hub and chain it on. */
4354 free_usb_ports = NULL;
4355 port->next = used_usb_ports;
4356 used_usb_ports = port;
4357
4358 hub = usb_hub_init(VM_USB_HUB_SIZE);
4359 usb_attach(port, hub);
4360 port = free_usb_ports;
4361 }
4362
4363 free_usb_ports = port->next;
4364 port->next = used_usb_ports;
4365 used_usb_ports = port;
4366 usb_attach(port, dev);
a594cfbf
FB
4367 return 0;
4368}
4369
4370static int usb_device_del(const char *devname)
4371{
0d92ed30
PB
4372 USBPort *port;
4373 USBPort **lastp;
059809e4 4374 USBDevice *dev;
0d92ed30 4375 int bus_num, addr;
a594cfbf
FB
4376 const char *p;
4377
0d92ed30 4378 if (!used_usb_ports)
a594cfbf
FB
4379 return -1;
4380
4381 p = strchr(devname, '.');
4382 if (!p)
4383 return -1;
4384 bus_num = strtoul(devname, NULL, 0);
4385 addr = strtoul(p + 1, NULL, 0);
4386 if (bus_num != 0)
4387 return -1;
0d92ed30
PB
4388
4389 lastp = &used_usb_ports;
4390 port = used_usb_ports;
4391 while (port && port->dev->addr != addr) {
4392 lastp = &port->next;
4393 port = port->next;
a594cfbf 4394 }
0d92ed30
PB
4395
4396 if (!port)
a594cfbf 4397 return -1;
0d92ed30 4398
059809e4 4399 dev = port->dev;
0d92ed30
PB
4400 *lastp = port->next;
4401 usb_attach(port, NULL);
059809e4 4402 dev->handle_destroy(dev);
0d92ed30
PB
4403 port->next = free_usb_ports;
4404 free_usb_ports = port;
a594cfbf
FB
4405 return 0;
4406}
4407
4408void do_usb_add(const char *devname)
4409{
4410 int ret;
4411 ret = usb_device_add(devname);
4412 if (ret < 0)
4413 term_printf("Could not add USB device '%s'\n", devname);
4414}
4415
4416void do_usb_del(const char *devname)
4417{
4418 int ret;
4419 ret = usb_device_del(devname);
4420 if (ret < 0)
4421 term_printf("Could not remove USB device '%s'\n", devname);
4422}
4423
4424void usb_info(void)
4425{
4426 USBDevice *dev;
0d92ed30 4427 USBPort *port;
a594cfbf
FB
4428 const char *speed_str;
4429
0d92ed30 4430 if (!usb_enabled) {
a594cfbf
FB
4431 term_printf("USB support not enabled\n");
4432 return;
4433 }
4434
0d92ed30
PB
4435 for (port = used_usb_ports; port; port = port->next) {
4436 dev = port->dev;
4437 if (!dev)
4438 continue;
4439 switch(dev->speed) {
4440 case USB_SPEED_LOW:
4441 speed_str = "1.5";
4442 break;
4443 case USB_SPEED_FULL:
4444 speed_str = "12";
4445 break;
4446 case USB_SPEED_HIGH:
4447 speed_str = "480";
4448 break;
4449 default:
4450 speed_str = "?";
4451 break;
a594cfbf 4452 }
1f6e24e7
FB
4453 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4454 0, dev->addr, speed_str, dev->devname);
a594cfbf
FB
4455 }
4456}
4457
201a51fc
AZ
4458/***********************************************************/
4459/* PCMCIA/Cardbus */
4460
4461static struct pcmcia_socket_entry_s {
4462 struct pcmcia_socket_s *socket;
4463 struct pcmcia_socket_entry_s *next;
4464} *pcmcia_sockets = 0;
4465
4466void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4467{
4468 struct pcmcia_socket_entry_s *entry;
4469
4470 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4471 entry->socket = socket;
4472 entry->next = pcmcia_sockets;
4473 pcmcia_sockets = entry;
4474}
4475
4476void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4477{
4478 struct pcmcia_socket_entry_s *entry, **ptr;
4479
4480 ptr = &pcmcia_sockets;
4481 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4482 if (entry->socket == socket) {
4483 *ptr = entry->next;
4484 qemu_free(entry);
4485 }
4486}
4487
4488void pcmcia_info(void)
4489{
4490 struct pcmcia_socket_entry_s *iter;
4491 if (!pcmcia_sockets)
4492 term_printf("No PCMCIA sockets\n");
4493
4494 for (iter = pcmcia_sockets; iter; iter = iter->next)
4495 term_printf("%s: %s\n", iter->socket->slot_string,
4496 iter->socket->attached ? iter->socket->card_string :
4497 "Empty");
4498}
4499
2ff89790
TS
4500/***********************************************************/
4501/* dumb display */
4502
4503static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4504{
4505}
4506
4507static void dumb_resize(DisplayState *ds, int w, int h)
4508{
4509}
4510
4511static void dumb_refresh(DisplayState *ds)
4512{
4513#if defined(CONFIG_SDL)
4514 vga_hw_update();
4515#endif
4516}
4517
4518static void dumb_display_init(DisplayState *ds)
4519{
4520 ds->data = NULL;
4521 ds->linesize = 0;
4522 ds->depth = 0;
4523 ds->dpy_update = dumb_update;
4524 ds->dpy_resize = dumb_resize;
4525 ds->dpy_refresh = dumb_refresh;
4526}
4527
8a7ddc38
FB
4528/***********************************************************/
4529/* I/O handling */
0824d6fc 4530
c4b1fcc0
FB
4531#define MAX_IO_HANDLERS 64
4532
4533typedef struct IOHandlerRecord {
4534 int fd;
7c9d8e07
FB
4535 IOCanRWHandler *fd_read_poll;
4536 IOHandler *fd_read;
4537 IOHandler *fd_write;
cafffd40 4538 int deleted;
c4b1fcc0
FB
4539 void *opaque;
4540 /* temporary data */
4541 struct pollfd *ufd;
8a7ddc38 4542 struct IOHandlerRecord *next;
c4b1fcc0
FB
4543} IOHandlerRecord;
4544
8a7ddc38 4545static IOHandlerRecord *first_io_handler;
c4b1fcc0 4546
7c9d8e07
FB
4547/* XXX: fd_read_poll should be suppressed, but an API change is
4548 necessary in the character devices to suppress fd_can_read(). */
4549int qemu_set_fd_handler2(int fd,
4550 IOCanRWHandler *fd_read_poll,
4551 IOHandler *fd_read,
4552 IOHandler *fd_write,
4553 void *opaque)
c4b1fcc0 4554{
7c9d8e07 4555 IOHandlerRecord **pioh, *ioh;
c4b1fcc0 4556
7c9d8e07
FB
4557 if (!fd_read && !fd_write) {
4558 pioh = &first_io_handler;
4559 for(;;) {
4560 ioh = *pioh;
4561 if (ioh == NULL)
4562 break;
4563 if (ioh->fd == fd) {
cafffd40 4564 ioh->deleted = 1;
7c9d8e07
FB
4565 break;
4566 }
4567 pioh = &ioh->next;
4568 }
4569 } else {
4570 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4571 if (ioh->fd == fd)
4572 goto found;
4573 }
4574 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4575 if (!ioh)
4576 return -1;
4577 ioh->next = first_io_handler;
4578 first_io_handler = ioh;
4579 found:
4580 ioh->fd = fd;
4581 ioh->fd_read_poll = fd_read_poll;
4582 ioh->fd_read = fd_read;
4583 ioh->fd_write = fd_write;
4584 ioh->opaque = opaque;
cafffd40 4585 ioh->deleted = 0;
7c9d8e07 4586 }
c4b1fcc0
FB
4587 return 0;
4588}
4589
7c9d8e07
FB
4590int qemu_set_fd_handler(int fd,
4591 IOHandler *fd_read,
4592 IOHandler *fd_write,
4593 void *opaque)
8a7ddc38 4594{
7c9d8e07 4595 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
8a7ddc38
FB
4596}
4597
f331110f
FB
4598/***********************************************************/
4599/* Polling handling */
4600
4601typedef struct PollingEntry {
4602 PollingFunc *func;
4603 void *opaque;
4604 struct PollingEntry *next;
4605} PollingEntry;
4606
4607static PollingEntry *first_polling_entry;
4608
4609int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4610{
4611 PollingEntry **ppe, *pe;
4612 pe = qemu_mallocz(sizeof(PollingEntry));
4613 if (!pe)
4614 return -1;
4615 pe->func = func;
4616 pe->opaque = opaque;
4617 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4618 *ppe = pe;
4619 return 0;
4620}
4621
4622void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4623{
4624 PollingEntry **ppe, *pe;
4625 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4626 pe = *ppe;
4627 if (pe->func == func && pe->opaque == opaque) {
4628 *ppe = pe->next;
4629 qemu_free(pe);
4630 break;
4631 }
4632 }
4633}
4634
a18e524a
FB
4635#ifdef _WIN32
4636/***********************************************************/
4637/* Wait objects support */
4638typedef struct WaitObjects {
4639 int num;
4640 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4641 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4642 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4643} WaitObjects;
4644
4645static WaitObjects wait_objects = {0};
4646
4647int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4648{
4649 WaitObjects *w = &wait_objects;
4650
4651 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4652 return -1;
4653 w->events[w->num] = handle;
4654 w->func[w->num] = func;
4655 w->opaque[w->num] = opaque;
4656 w->num++;
4657 return 0;
4658}
4659
4660void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4661{
4662 int i, found;
4663 WaitObjects *w = &wait_objects;
4664
4665 found = 0;
4666 for (i = 0; i < w->num; i++) {
4667 if (w->events[i] == handle)
4668 found = 1;
4669 if (found) {
4670 w->events[i] = w->events[i + 1];
4671 w->func[i] = w->func[i + 1];
4672 w->opaque[i] = w->opaque[i + 1];
4673 }
4674 }
4675 if (found)
4676 w->num--;
4677}
4678#endif
4679
8a7ddc38
FB
4680/***********************************************************/
4681/* savevm/loadvm support */
4682
faea38e7
FB
4683#define IO_BUF_SIZE 32768
4684
4685struct QEMUFile {
4686 FILE *outfile;
4687 BlockDriverState *bs;
4688 int is_file;
4689 int is_writable;
4690 int64_t base_offset;
4691 int64_t buf_offset; /* start of buffer when writing, end of buffer
4692 when reading */
4693 int buf_index;
4694 int buf_size; /* 0 when writing */
4695 uint8_t buf[IO_BUF_SIZE];
4696};
4697
4698QEMUFile *qemu_fopen(const char *filename, const char *mode)
4699{
4700 QEMUFile *f;
4701
4702 f = qemu_mallocz(sizeof(QEMUFile));
4703 if (!f)
4704 return NULL;
4705 if (!strcmp(mode, "wb")) {
4706 f->is_writable = 1;
4707 } else if (!strcmp(mode, "rb")) {
4708 f->is_writable = 0;
4709 } else {
4710 goto fail;
4711 }
4712 f->outfile = fopen(filename, mode);
4713 if (!f->outfile)
4714 goto fail;
4715 f->is_file = 1;
4716 return f;
4717 fail:
4718 if (f->outfile)
4719 fclose(f->outfile);
4720 qemu_free(f);
4721 return NULL;
4722}
4723
4724QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4725{
4726 QEMUFile *f;
4727
4728 f = qemu_mallocz(sizeof(QEMUFile));
4729 if (!f)
4730 return NULL;
4731 f->is_file = 0;
4732 f->bs = bs;
4733 f->is_writable = is_writable;
4734 f->base_offset = offset;
4735 return f;
4736}
4737
4738void qemu_fflush(QEMUFile *f)
4739{
4740 if (!f->is_writable)
4741 return;
4742 if (f->buf_index > 0) {
4743 if (f->is_file) {
4744 fseek(f->outfile, f->buf_offset, SEEK_SET);
4745 fwrite(f->buf, 1, f->buf_index, f->outfile);
4746 } else {
4747 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4748 f->buf, f->buf_index);
4749 }
4750 f->buf_offset += f->buf_index;
4751 f->buf_index = 0;
4752 }
4753}
4754
4755static void qemu_fill_buffer(QEMUFile *f)
4756{
4757 int len;
4758
4759 if (f->is_writable)
4760 return;
4761 if (f->is_file) {
4762 fseek(f->outfile, f->buf_offset, SEEK_SET);
4763 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4764 if (len < 0)
4765 len = 0;
4766 } else {
4767 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4768 f->buf, IO_BUF_SIZE);
4769 if (len < 0)
4770 len = 0;
4771 }
4772 f->buf_index = 0;
4773 f->buf_size = len;
4774 f->buf_offset += len;
4775}
4776
4777void qemu_fclose(QEMUFile *f)
4778{
4779 if (f->is_writable)
4780 qemu_fflush(f);
4781 if (f->is_file) {
4782 fclose(f->outfile);
4783 }
4784 qemu_free(f);
4785}
4786
8a7ddc38 4787void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
b4608c04 4788{
faea38e7
FB
4789 int l;
4790 while (size > 0) {
4791 l = IO_BUF_SIZE - f->buf_index;
4792 if (l > size)
4793 l = size;
4794 memcpy(f->buf + f->buf_index, buf, l);
4795 f->buf_index += l;
4796 buf += l;
4797 size -= l;
4798 if (f->buf_index >= IO_BUF_SIZE)
4799 qemu_fflush(f);
4800 }
b4608c04
FB
4801}
4802
8a7ddc38 4803void qemu_put_byte(QEMUFile *f, int v)
b4608c04 4804{
faea38e7
FB
4805 f->buf[f->buf_index++] = v;
4806 if (f->buf_index >= IO_BUF_SIZE)
4807 qemu_fflush(f);
4808}
4809
4810int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4811{
4812 int size, l;
4813
4814 size = size1;
4815 while (size > 0) {
4816 l = f->buf_size - f->buf_index;
4817 if (l == 0) {
4818 qemu_fill_buffer(f);
4819 l = f->buf_size - f->buf_index;
4820 if (l == 0)
4821 break;
4822 }
4823 if (l > size)
4824 l = size;
4825 memcpy(buf, f->buf + f->buf_index, l);
4826 f->buf_index += l;
4827 buf += l;
4828 size -= l;
4829 }
4830 return size1 - size;
4831}
4832
4833int qemu_get_byte(QEMUFile *f)
4834{
4835 if (f->buf_index >= f->buf_size) {
4836 qemu_fill_buffer(f);
4837 if (f->buf_index >= f->buf_size)
4838 return 0;
4839 }
4840 return f->buf[f->buf_index++];
4841}
4842
4843int64_t qemu_ftell(QEMUFile *f)
4844{
4845 return f->buf_offset - f->buf_size + f->buf_index;
4846}
4847
4848int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4849{
4850 if (whence == SEEK_SET) {
4851 /* nothing to do */
4852 } else if (whence == SEEK_CUR) {
4853 pos += qemu_ftell(f);
4854 } else {
4855 /* SEEK_END not supported */
4856 return -1;
4857 }
4858 if (f->is_writable) {
4859 qemu_fflush(f);
4860 f->buf_offset = pos;
4861 } else {
4862 f->buf_offset = pos;
4863 f->buf_index = 0;
4864 f->buf_size = 0;
4865 }
4866 return pos;
8a7ddc38
FB
4867}
4868
4869void qemu_put_be16(QEMUFile *f, unsigned int v)
4870{
4871 qemu_put_byte(f, v >> 8);
4872 qemu_put_byte(f, v);
4873}
4874
4875void qemu_put_be32(QEMUFile *f, unsigned int v)
4876{
4877 qemu_put_byte(f, v >> 24);
4878 qemu_put_byte(f, v >> 16);
4879 qemu_put_byte(f, v >> 8);
4880 qemu_put_byte(f, v);
4881}
4882
4883void qemu_put_be64(QEMUFile *f, uint64_t v)
4884{
4885 qemu_put_be32(f, v >> 32);
4886 qemu_put_be32(f, v);
4887}
4888
8a7ddc38
FB
4889unsigned int qemu_get_be16(QEMUFile *f)
4890{
4891 unsigned int v;
4892 v = qemu_get_byte(f) << 8;
4893 v |= qemu_get_byte(f);
4894 return v;
4895}
4896
4897unsigned int qemu_get_be32(QEMUFile *f)
4898{
4899 unsigned int v;
4900 v = qemu_get_byte(f) << 24;
4901 v |= qemu_get_byte(f) << 16;
4902 v |= qemu_get_byte(f) << 8;
4903 v |= qemu_get_byte(f);
4904 return v;
4905}
4906
4907uint64_t qemu_get_be64(QEMUFile *f)
4908{
4909 uint64_t v;
4910 v = (uint64_t)qemu_get_be32(f) << 32;
4911 v |= qemu_get_be32(f);
4912 return v;
4913}
4914
8a7ddc38
FB
4915typedef struct SaveStateEntry {
4916 char idstr[256];
4917 int instance_id;
4918 int version_id;
4919 SaveStateHandler *save_state;
4920 LoadStateHandler *load_state;
4921 void *opaque;
4922 struct SaveStateEntry *next;
4923} SaveStateEntry;
b4608c04 4924
8a7ddc38
FB
4925static SaveStateEntry *first_se;
4926
4927int register_savevm(const char *idstr,
4928 int instance_id,
4929 int version_id,
4930 SaveStateHandler *save_state,
4931 LoadStateHandler *load_state,
4932 void *opaque)
4933{
4934 SaveStateEntry *se, **pse;
4935
4936 se = qemu_malloc(sizeof(SaveStateEntry));
4937 if (!se)
4938 return -1;
4939 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4940 se->instance_id = instance_id;
4941 se->version_id = version_id;
4942 se->save_state = save_state;
4943 se->load_state = load_state;
4944 se->opaque = opaque;
4945 se->next = NULL;
4946
4947 /* add at the end of list */
4948 pse = &first_se;
4949 while (*pse != NULL)
4950 pse = &(*pse)->next;
4951 *pse = se;
4952 return 0;
4953}
4954
4955#define QEMU_VM_FILE_MAGIC 0x5145564d
faea38e7 4956#define QEMU_VM_FILE_VERSION 0x00000002
8a7ddc38 4957
faea38e7 4958int qemu_savevm_state(QEMUFile *f)
8a7ddc38
FB
4959{
4960 SaveStateEntry *se;
faea38e7
FB
4961 int len, ret;
4962 int64_t cur_pos, len_pos, total_len_pos;
313aa567 4963
8a7ddc38
FB
4964 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4965 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
faea38e7
FB
4966 total_len_pos = qemu_ftell(f);
4967 qemu_put_be64(f, 0); /* total size */
8a7ddc38
FB
4968
4969 for(se = first_se; se != NULL; se = se->next) {
4970 /* ID string */
4971 len = strlen(se->idstr);
4972 qemu_put_byte(f, len);
4973 qemu_put_buffer(f, se->idstr, len);
4974
4975 qemu_put_be32(f, se->instance_id);
4976 qemu_put_be32(f, se->version_id);
4977
4978 /* record size: filled later */
faea38e7 4979 len_pos = qemu_ftell(f);
8a7ddc38
FB
4980 qemu_put_be32(f, 0);
4981
4982 se->save_state(f, se->opaque);
4983
4984 /* fill record size */
faea38e7
FB
4985 cur_pos = qemu_ftell(f);
4986 len = cur_pos - len_pos - 4;
4987 qemu_fseek(f, len_pos, SEEK_SET);
8a7ddc38 4988 qemu_put_be32(f, len);
faea38e7 4989 qemu_fseek(f, cur_pos, SEEK_SET);
8a7ddc38 4990 }
faea38e7
FB
4991 cur_pos = qemu_ftell(f);
4992 qemu_fseek(f, total_len_pos, SEEK_SET);
4993 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4994 qemu_fseek(f, cur_pos, SEEK_SET);
8a7ddc38 4995
8a7ddc38 4996 ret = 0;
8a7ddc38
FB
4997 return ret;
4998}
4999
5000static SaveStateEntry *find_se(const char *idstr, int instance_id)
5001{
5002 SaveStateEntry *se;
5003
5004 for(se = first_se; se != NULL; se = se->next) {
5005 if (!strcmp(se->idstr, idstr) &&
5006 instance_id == se->instance_id)
5007 return se;
5008 }
5009 return NULL;
5010}
5011
faea38e7 5012int qemu_loadvm_state(QEMUFile *f)
8a7ddc38
FB
5013{
5014 SaveStateEntry *se;
faea38e7
FB
5015 int len, ret, instance_id, record_len, version_id;
5016 int64_t total_len, end_pos, cur_pos;
8a7ddc38
FB
5017 unsigned int v;
5018 char idstr[256];
5019
8a7ddc38
FB
5020 v = qemu_get_be32(f);
5021 if (v != QEMU_VM_FILE_MAGIC)
5022 goto fail;
5023 v = qemu_get_be32(f);
5024 if (v != QEMU_VM_FILE_VERSION) {
5025 fail:
8a7ddc38
FB
5026 ret = -1;
5027 goto the_end;
5028 }
faea38e7
FB
5029 total_len = qemu_get_be64(f);
5030 end_pos = total_len + qemu_ftell(f);
b4608c04 5031 for(;;) {
faea38e7 5032 if (qemu_ftell(f) >= end_pos)
cd4c3e88 5033 break;
faea38e7 5034 len = qemu_get_byte(f);
8a7ddc38
FB
5035 qemu_get_buffer(f, idstr, len);
5036 idstr[len] = '\0';
5037 instance_id = qemu_get_be32(f);
5038 version_id = qemu_get_be32(f);
5039 record_len = qemu_get_be32(f);
5040#if 0
5041 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5042 idstr, instance_id, version_id, record_len);
5043#endif
faea38e7 5044 cur_pos = qemu_ftell(f);
8a7ddc38
FB
5045 se = find_se(idstr, instance_id);
5046 if (!se) {
5047 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5048 instance_id, idstr);
5049 } else {
5050 ret = se->load_state(f, se->opaque, version_id);
5051 if (ret < 0) {
5052 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5053 instance_id, idstr);
5054 }
34865134 5055 }
8a7ddc38
FB
5056 /* always seek to exact end of record */
5057 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5058 }
8a7ddc38 5059 ret = 0;
faea38e7
FB
5060 the_end:
5061 return ret;
5062}
5063
5064/* device can contain snapshots */
5065static int bdrv_can_snapshot(BlockDriverState *bs)
5066{
5067 return (bs &&
5068 !bdrv_is_removable(bs) &&
5069 !bdrv_is_read_only(bs));
5070}
5071
5072/* device must be snapshots in order to have a reliable snapshot */
5073static int bdrv_has_snapshot(BlockDriverState *bs)
5074{
5075 return (bs &&
5076 !bdrv_is_removable(bs) &&
5077 !bdrv_is_read_only(bs));
5078}
5079
5080static BlockDriverState *get_bs_snapshots(void)
5081{
5082 BlockDriverState *bs;
5083 int i;
5084
5085 if (bs_snapshots)
5086 return bs_snapshots;
5087 for(i = 0; i <= MAX_DISKS; i++) {
5088 bs = bs_table[i];
5089 if (bdrv_can_snapshot(bs))
5090 goto ok;
5091 }
5092 return NULL;
5093 ok:
5094 bs_snapshots = bs;
5095 return bs;
5096}
5097
5098static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5099 const char *name)
5100{
5101 QEMUSnapshotInfo *sn_tab, *sn;
5102 int nb_sns, i, ret;
5103
5104 ret = -ENOENT;
5105 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5106 if (nb_sns < 0)
5107 return ret;
5108 for(i = 0; i < nb_sns; i++) {
5109 sn = &sn_tab[i];
5110 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5111 *sn_info = *sn;
5112 ret = 0;
5113 break;
5114 }
5115 }
5116 qemu_free(sn_tab);
5117 return ret;
5118}
5119
5120void do_savevm(const char *name)
5121{
5122 BlockDriverState *bs, *bs1;
5123 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5124 int must_delete, ret, i;
5125 BlockDriverInfo bdi1, *bdi = &bdi1;
5126 QEMUFile *f;
5127 int saved_vm_running;
4c279bdf
FB
5128#ifdef _WIN32
5129 struct _timeb tb;
5130#else
faea38e7 5131 struct timeval tv;
4c279bdf 5132#endif
faea38e7
FB
5133
5134 bs = get_bs_snapshots();
5135 if (!bs) {
5136 term_printf("No block device can accept snapshots\n");
5137 return;
5138 }
5139
6192bc37
PB
5140 /* ??? Should this occur after vm_stop? */
5141 qemu_aio_flush();
5142
faea38e7
FB
5143 saved_vm_running = vm_running;
5144 vm_stop(0);
5145
5146 must_delete = 0;
5147 if (name) {
5148 ret = bdrv_snapshot_find(bs, old_sn, name);
5149 if (ret >= 0) {
5150 must_delete = 1;
5151 }
5152 }
5153 memset(sn, 0, sizeof(*sn));
5154 if (must_delete) {
5155 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5156 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5157 } else {
5158 if (name)
5159 pstrcpy(sn->name, sizeof(sn->name), name);
5160 }
5161
5162 /* fill auxiliary fields */
4c279bdf
FB
5163#ifdef _WIN32
5164 _ftime(&tb);
5165 sn->date_sec = tb.time;
5166 sn->date_nsec = tb.millitm * 1000000;
5167#else
faea38e7
FB
5168 gettimeofday(&tv, NULL);
5169 sn->date_sec = tv.tv_sec;
5170 sn->date_nsec = tv.tv_usec * 1000;
4c279bdf 5171#endif
faea38e7
FB
5172 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5173
5174 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5175 term_printf("Device %s does not support VM state snapshots\n",
5176 bdrv_get_device_name(bs));
5177 goto the_end;
5178 }
5179
5180 /* save the VM state */
5181 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5182 if (!f) {
5183 term_printf("Could not open VM state file\n");
5184 goto the_end;
5185 }
5186 ret = qemu_savevm_state(f);
5187 sn->vm_state_size = qemu_ftell(f);
5188 qemu_fclose(f);
5189 if (ret < 0) {
5190 term_printf("Error %d while writing VM\n", ret);
5191 goto the_end;
5192 }
5193
5194 /* create the snapshots */
5195
5196 for(i = 0; i < MAX_DISKS; i++) {
5197 bs1 = bs_table[i];
5198 if (bdrv_has_snapshot(bs1)) {
5199 if (must_delete) {
5200 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5201 if (ret < 0) {
5202 term_printf("Error while deleting snapshot on '%s'\n",
5203 bdrv_get_device_name(bs1));
5204 }
5205 }
5206 ret = bdrv_snapshot_create(bs1, sn);
5207 if (ret < 0) {
5208 term_printf("Error while creating snapshot on '%s'\n",
5209 bdrv_get_device_name(bs1));
5210 }
5211 }
5212 }
5213
8a7ddc38
FB
5214 the_end:
5215 if (saved_vm_running)
5216 vm_start();
faea38e7
FB
5217}
5218
5219void do_loadvm(const char *name)
5220{
5221 BlockDriverState *bs, *bs1;
5222 BlockDriverInfo bdi1, *bdi = &bdi1;
5223 QEMUFile *f;
5224 int i, ret;
5225 int saved_vm_running;
5226
5227 bs = get_bs_snapshots();
5228 if (!bs) {
5229 term_printf("No block device supports snapshots\n");
5230 return;
5231 }
5232
6192bc37
PB
5233 /* Flush all IO requests so they don't interfere with the new state. */
5234 qemu_aio_flush();
5235
faea38e7
FB
5236 saved_vm_running = vm_running;
5237 vm_stop(0);
5238
5239 for(i = 0; i <= MAX_DISKS; i++) {
5240 bs1 = bs_table[i];
5241 if (bdrv_has_snapshot(bs1)) {
5242 ret = bdrv_snapshot_goto(bs1, name);
5243 if (ret < 0) {
5244 if (bs != bs1)
5245 term_printf("Warning: ");
5246 switch(ret) {
5247 case -ENOTSUP:
5248 term_printf("Snapshots not supported on device '%s'\n",
5249 bdrv_get_device_name(bs1));
5250 break;
5251 case -ENOENT:
5252 term_printf("Could not find snapshot '%s' on device '%s'\n",
5253 name, bdrv_get_device_name(bs1));
5254 break;
5255 default:
5256 term_printf("Error %d while activating snapshot on '%s'\n",
5257 ret, bdrv_get_device_name(bs1));
5258 break;
5259 }
5260 /* fatal on snapshot block device */
5261 if (bs == bs1)
5262 goto the_end;
5263 }
5264 }
5265 }
5266
5267 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5268 term_printf("Device %s does not support VM state snapshots\n",
5269 bdrv_get_device_name(bs));
5270 return;
5271 }
5272
5273 /* restore the VM state */
5274 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5275 if (!f) {
5276 term_printf("Could not open VM state file\n");
5277 goto the_end;
5278 }
5279 ret = qemu_loadvm_state(f);
5280 qemu_fclose(f);
5281 if (ret < 0) {
5282 term_printf("Error %d while loading VM state\n", ret);
5283 }
5284 the_end:
5285 if (saved_vm_running)
5286 vm_start();
5287}
5288
5289void do_delvm(const char *name)
5290{
5291 BlockDriverState *bs, *bs1;
5292 int i, ret;
5293
5294 bs = get_bs_snapshots();
5295 if (!bs) {
5296 term_printf("No block device supports snapshots\n");
5297 return;
5298 }
5299
5300 for(i = 0; i <= MAX_DISKS; i++) {
5301 bs1 = bs_table[i];
5302 if (bdrv_has_snapshot(bs1)) {
5303 ret = bdrv_snapshot_delete(bs1, name);
5304 if (ret < 0) {
5305 if (ret == -ENOTSUP)
5306 term_printf("Snapshots not supported on device '%s'\n",
5307 bdrv_get_device_name(bs1));
5308 else
5309 term_printf("Error %d while deleting snapshot on '%s'\n",
5310 ret, bdrv_get_device_name(bs1));
5311 }
5312 }
5313 }
5314}
5315
5316void do_info_snapshots(void)
5317{
5318 BlockDriverState *bs, *bs1;
5319 QEMUSnapshotInfo *sn_tab, *sn;
5320 int nb_sns, i;
5321 char buf[256];
5322
5323 bs = get_bs_snapshots();
5324 if (!bs) {
5325 term_printf("No available block device supports snapshots\n");
5326 return;
5327 }
5328 term_printf("Snapshot devices:");
5329 for(i = 0; i <= MAX_DISKS; i++) {
5330 bs1 = bs_table[i];
5331 if (bdrv_has_snapshot(bs1)) {
5332 if (bs == bs1)
5333 term_printf(" %s", bdrv_get_device_name(bs1));
5334 }
5335 }
5336 term_printf("\n");
5337
5338 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5339 if (nb_sns < 0) {
5340 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5341 return;
5342 }
5343 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5344 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5345 for(i = 0; i < nb_sns; i++) {
5346 sn = &sn_tab[i];
5347 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5348 }
5349 qemu_free(sn_tab);
8a7ddc38
FB
5350}
5351
5352/***********************************************************/
5353/* cpu save/restore */
5354
5355#if defined(TARGET_I386)
5356
5357static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5358{
02ba45c5 5359 qemu_put_be32(f, dt->selector);
20f32282 5360 qemu_put_betl(f, dt->base);
8a7ddc38
FB
5361 qemu_put_be32(f, dt->limit);
5362 qemu_put_be32(f, dt->flags);
5363}
5364
5365static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5366{
02ba45c5 5367 dt->selector = qemu_get_be32(f);
20f32282 5368 dt->base = qemu_get_betl(f);
8a7ddc38
FB
5369 dt->limit = qemu_get_be32(f);
5370 dt->flags = qemu_get_be32(f);
5371}
5372
5373void cpu_save(QEMUFile *f, void *opaque)
5374{
5375 CPUState *env = opaque;
664e0f19 5376 uint16_t fptag, fpus, fpuc, fpregs_format;
8a7ddc38
FB
5377 uint32_t hflags;
5378 int i;
664e0f19 5379
20f32282
FB
5380 for(i = 0; i < CPU_NB_REGS; i++)
5381 qemu_put_betls(f, &env->regs[i]);
5382 qemu_put_betls(f, &env->eip);
5383 qemu_put_betls(f, &env->eflags);
8a7ddc38
FB
5384 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5385 qemu_put_be32s(f, &hflags);
5386
5387 /* FPU */
5388 fpuc = env->fpuc;
5389 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5390 fptag = 0;
664e0f19
FB
5391 for(i = 0; i < 8; i++) {
5392 fptag |= ((!env->fptags[i]) << i);
8a7ddc38
FB
5393 }
5394
5395 qemu_put_be16s(f, &fpuc);
5396 qemu_put_be16s(f, &fpus);
5397 qemu_put_be16s(f, &fptag);
5398
664e0f19
FB
5399#ifdef USE_X86LDOUBLE
5400 fpregs_format = 0;
5401#else
5402 fpregs_format = 1;
5403#endif
5404 qemu_put_be16s(f, &fpregs_format);
5405
8a7ddc38 5406 for(i = 0; i < 8; i++) {
664e0f19 5407#ifdef USE_X86LDOUBLE
8636b5d8
FB
5408 {
5409 uint64_t mant;
5410 uint16_t exp;
5411 /* we save the real CPU data (in case of MMX usage only 'mant'
5412 contains the MMX register */
5413 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5414 qemu_put_be64(f, mant);
5415 qemu_put_be16(f, exp);
5416 }
664e0f19
FB
5417#else
5418 /* if we use doubles for float emulation, we save the doubles to
5419 avoid losing information in case of MMX usage. It can give
5420 problems if the image is restored on a CPU where long
5421 doubles are used instead. */
8636b5d8 5422 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
664e0f19 5423#endif
8a7ddc38
FB
5424 }
5425
5426 for(i = 0; i < 6; i++)
5427 cpu_put_seg(f, &env->segs[i]);
5428 cpu_put_seg(f, &env->ldt);
5429 cpu_put_seg(f, &env->tr);
5430 cpu_put_seg(f, &env->gdt);
5431 cpu_put_seg(f, &env->idt);
5432
5433 qemu_put_be32s(f, &env->sysenter_cs);
5434 qemu_put_be32s(f, &env->sysenter_esp);
5435 qemu_put_be32s(f, &env->sysenter_eip);
5436
20f32282
FB
5437 qemu_put_betls(f, &env->cr[0]);
5438 qemu_put_betls(f, &env->cr[2]);
5439 qemu_put_betls(f, &env->cr[3]);
5440 qemu_put_betls(f, &env->cr[4]);
8a7ddc38
FB
5441
5442 for(i = 0; i < 8; i++)
20f32282 5443 qemu_put_betls(f, &env->dr[i]);
8a7ddc38
FB
5444
5445 /* MMU */
5446 qemu_put_be32s(f, &env->a20_mask);
02536f8b 5447
664e0f19
FB
5448 /* XMM */
5449 qemu_put_be32s(f, &env->mxcsr);
02536f8b
FB
5450 for(i = 0; i < CPU_NB_REGS; i++) {
5451 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5452 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5453 }
5454
664e0f19 5455#ifdef TARGET_X86_64
02536f8b
FB
5456 qemu_put_be64s(f, &env->efer);
5457 qemu_put_be64s(f, &env->star);
5458 qemu_put_be64s(f, &env->lstar);
5459 qemu_put_be64s(f, &env->cstar);
5460 qemu_put_be64s(f, &env->fmask);
5461 qemu_put_be64s(f, &env->kernelgsbase);
5462#endif
3b21e03e 5463 qemu_put_be32s(f, &env->smbase);
8a7ddc38
FB
5464}
5465
8636b5d8 5466#ifdef USE_X86LDOUBLE
664e0f19
FB
5467/* XXX: add that in a FPU generic layer */
5468union x86_longdouble {
5469 uint64_t mant;
5470 uint16_t exp;
5471};
5472
5473#define MANTD1(fp) (fp & ((1LL << 52) - 1))
5474#define EXPBIAS1 1023
5475#define EXPD1(fp) ((fp >> 52) & 0x7FF)
5476#define SIGND1(fp) ((fp >> 32) & 0x80000000)
5477
5478static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5479{
5480 int e;
5481 /* mantissa */
5482 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5483 /* exponent + sign */
5484 e = EXPD1(temp) - EXPBIAS1 + 16383;
5485 e |= SIGND1(temp) >> 16;
5486 p->exp = e;
5487}
8636b5d8 5488#endif
664e0f19 5489
8a7ddc38
FB
5490int cpu_load(QEMUFile *f, void *opaque, int version_id)
5491{
5492 CPUState *env = opaque;
664e0f19 5493 int i, guess_mmx;
8a7ddc38 5494 uint32_t hflags;
664e0f19 5495 uint16_t fpus, fpuc, fptag, fpregs_format;
8a7ddc38 5496
3b21e03e 5497 if (version_id != 3 && version_id != 4)
8a7ddc38 5498 return -EINVAL;
20f32282
FB
5499 for(i = 0; i < CPU_NB_REGS; i++)
5500 qemu_get_betls(f, &env->regs[i]);
5501 qemu_get_betls(f, &env->eip);
5502 qemu_get_betls(f, &env->eflags);
8a7ddc38
FB
5503 qemu_get_be32s(f, &hflags);
5504
5505 qemu_get_be16s(f, &fpuc);
5506 qemu_get_be16s(f, &fpus);
5507 qemu_get_be16s(f, &fptag);
664e0f19
FB
5508 qemu_get_be16s(f, &fpregs_format);
5509
5510 /* NOTE: we cannot always restore the FPU state if the image come
5511 from a host with a different 'USE_X86LDOUBLE' define. We guess
5512 if we are in an MMX state to restore correctly in that case. */
5513 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
8a7ddc38
FB
5514 for(i = 0; i < 8; i++) {
5515 uint64_t mant;
5516 uint16_t exp;
664e0f19
FB
5517
5518 switch(fpregs_format) {
5519 case 0:
5520 mant = qemu_get_be64(f);
5521 exp = qemu_get_be16(f);
5522#ifdef USE_X86LDOUBLE
5523 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5524#else
5525 /* difficult case */
5526 if (guess_mmx)
8636b5d8 5527 env->fpregs[i].mmx.MMX_Q(0) = mant;
664e0f19
FB
5528 else
5529 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5530#endif
5531 break;
5532 case 1:
5533 mant = qemu_get_be64(f);
5534#ifdef USE_X86LDOUBLE
8636b5d8
FB
5535 {
5536 union x86_longdouble *p;
5537 /* difficult case */
5538 p = (void *)&env->fpregs[i];
5539 if (guess_mmx) {
5540 p->mant = mant;
5541 p->exp = 0xffff;
5542 } else {
5543 fp64_to_fp80(p, mant);
5544 }
664e0f19
FB
5545 }
5546#else
8636b5d8 5547 env->fpregs[i].mmx.MMX_Q(0) = mant;
664e0f19
FB
5548#endif
5549 break;
5550 default:
5551 return -EINVAL;
5552 }
8a7ddc38
FB
5553 }
5554
5555 env->fpuc = fpuc;
7a0e1f41 5556 /* XXX: restore FPU round state */
8a7ddc38
FB
5557 env->fpstt = (fpus >> 11) & 7;
5558 env->fpus = fpus & ~0x3800;
664e0f19 5559 fptag ^= 0xff;
8a7ddc38 5560 for(i = 0; i < 8; i++) {
664e0f19 5561 env->fptags[i] = (fptag >> i) & 1;
8a7ddc38
FB
5562 }
5563
5564 for(i = 0; i < 6; i++)
5565 cpu_get_seg(f, &env->segs[i]);
5566 cpu_get_seg(f, &env->ldt);
5567 cpu_get_seg(f, &env->tr);
5568 cpu_get_seg(f, &env->gdt);
5569 cpu_get_seg(f, &env->idt);
5570
5571 qemu_get_be32s(f, &env->sysenter_cs);
5572 qemu_get_be32s(f, &env->sysenter_esp);
5573 qemu_get_be32s(f, &env->sysenter_eip);
5574
20f32282
FB
5575 qemu_get_betls(f, &env->cr[0]);
5576 qemu_get_betls(f, &env->cr[2]);
5577 qemu_get_betls(f, &env->cr[3]);
5578 qemu_get_betls(f, &env->cr[4]);
8a7ddc38
FB
5579
5580 for(i = 0; i < 8; i++)
20f32282 5581 qemu_get_betls(f, &env->dr[i]);
8a7ddc38
FB
5582
5583 /* MMU */
5584 qemu_get_be32s(f, &env->a20_mask);
5585
664e0f19 5586 qemu_get_be32s(f, &env->mxcsr);
02536f8b
FB
5587 for(i = 0; i < CPU_NB_REGS; i++) {
5588 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5589 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5590 }
5591
664e0f19 5592#ifdef TARGET_X86_64
02536f8b
FB
5593 qemu_get_be64s(f, &env->efer);
5594 qemu_get_be64s(f, &env->star);
5595 qemu_get_be64s(f, &env->lstar);
5596 qemu_get_be64s(f, &env->cstar);
5597 qemu_get_be64s(f, &env->fmask);
5598 qemu_get_be64s(f, &env->kernelgsbase);
5599#endif
3b21e03e
FB
5600 if (version_id >= 4)
5601 qemu_get_be32s(f, &env->smbase);
02536f8b 5602
8a7ddc38
FB
5603 /* XXX: compute hflags from scratch, except for CPL and IIF */
5604 env->hflags = hflags;
5605 tlb_flush(env, 1);
5606 return 0;
5607}
5608
a541f297
FB
5609#elif defined(TARGET_PPC)
5610void cpu_save(QEMUFile *f, void *opaque)
5611{
5612}
5613
e95c8d51
FB
5614int cpu_load(QEMUFile *f, void *opaque, int version_id)
5615{
5616 return 0;
5617}
6af0bf9c
FB
5618
5619#elif defined(TARGET_MIPS)
5620void cpu_save(QEMUFile *f, void *opaque)
5621{
5622}
5623
5624int cpu_load(QEMUFile *f, void *opaque, int version_id)
5625{
5626 return 0;
5627}
5628
e95c8d51
FB
5629#elif defined(TARGET_SPARC)
5630void cpu_save(QEMUFile *f, void *opaque)
5631{
e80cfcfc
FB
5632 CPUState *env = opaque;
5633 int i;
5634 uint32_t tmp;
5635
4fa5d772
FB
5636 for(i = 0; i < 8; i++)
5637 qemu_put_betls(f, &env->gregs[i]);
5638 for(i = 0; i < NWINDOWS * 16; i++)
5639 qemu_put_betls(f, &env->regbase[i]);
e80cfcfc
FB
5640
5641 /* FPU */
4fa5d772
FB
5642 for(i = 0; i < TARGET_FPREGS; i++) {
5643 union {
1bdb68ea
FB
5644 float32 f;
5645 uint32_t i;
4fa5d772
FB
5646 } u;
5647 u.f = env->fpr[i];
1bdb68ea 5648 qemu_put_be32(f, u.i);
4fa5d772
FB
5649 }
5650
5651 qemu_put_betls(f, &env->pc);
5652 qemu_put_betls(f, &env->npc);
5653 qemu_put_betls(f, &env->y);
e80cfcfc 5654 tmp = GET_PSR(env);
4fa5d772 5655 qemu_put_be32(f, tmp);
3475187d
FB
5656 qemu_put_betls(f, &env->fsr);
5657 qemu_put_betls(f, &env->tbr);
5658#ifndef TARGET_SPARC64
e80cfcfc 5659 qemu_put_be32s(f, &env->wim);
e80cfcfc
FB
5660 /* MMU */
5661 for(i = 0; i < 16; i++)
5662 qemu_put_be32s(f, &env->mmuregs[i]);
3475187d 5663#endif
e95c8d51
FB
5664}
5665
a541f297
FB
5666int cpu_load(QEMUFile *f, void *opaque, int version_id)
5667{
e80cfcfc
FB
5668 CPUState *env = opaque;
5669 int i;
5670 uint32_t tmp;
5671
4fa5d772
FB
5672 for(i = 0; i < 8; i++)
5673 qemu_get_betls(f, &env->gregs[i]);
5674 for(i = 0; i < NWINDOWS * 16; i++)
5675 qemu_get_betls(f, &env->regbase[i]);
e80cfcfc
FB
5676
5677 /* FPU */
4fa5d772
FB
5678 for(i = 0; i < TARGET_FPREGS; i++) {
5679 union {
1bdb68ea
FB
5680 float32 f;
5681 uint32_t i;
4fa5d772 5682 } u;
1bdb68ea 5683 u.i = qemu_get_be32(f);
4fa5d772
FB
5684 env->fpr[i] = u.f;
5685 }
5686
5687 qemu_get_betls(f, &env->pc);
5688 qemu_get_betls(f, &env->npc);
5689 qemu_get_betls(f, &env->y);
5690 tmp = qemu_get_be32(f);
5691 env->cwp = 0; /* needed to ensure that the wrapping registers are
5692 correctly updated */
e80cfcfc 5693 PUT_PSR(env, tmp);
3475187d
FB
5694 qemu_get_betls(f, &env->fsr);
5695 qemu_get_betls(f, &env->tbr);
5696#ifndef TARGET_SPARC64
e80cfcfc 5697 qemu_get_be32s(f, &env->wim);
e80cfcfc
FB
5698 /* MMU */
5699 for(i = 0; i < 16; i++)
5700 qemu_get_be32s(f, &env->mmuregs[i]);
3475187d 5701#endif
e80cfcfc 5702 tlb_flush(env, 1);
a541f297
FB
5703 return 0;
5704}
b5ff1b31
FB
5705
5706#elif defined(TARGET_ARM)
5707
b5ff1b31
FB
5708void cpu_save(QEMUFile *f, void *opaque)
5709{
aa941b94
AZ
5710 int i;
5711 CPUARMState *env = (CPUARMState *)opaque;
5712
5713 for (i = 0; i < 16; i++) {
5714 qemu_put_be32(f, env->regs[i]);
5715 }
5716 qemu_put_be32(f, cpsr_read(env));
5717 qemu_put_be32(f, env->spsr);
5718 for (i = 0; i < 6; i++) {
5719 qemu_put_be32(f, env->banked_spsr[i]);
5720 qemu_put_be32(f, env->banked_r13[i]);
5721 qemu_put_be32(f, env->banked_r14[i]);
5722 }
5723 for (i = 0; i < 5; i++) {
5724 qemu_put_be32(f, env->usr_regs[i]);
5725 qemu_put_be32(f, env->fiq_regs[i]);
5726 }
5727 qemu_put_be32(f, env->cp15.c0_cpuid);
5728 qemu_put_be32(f, env->cp15.c0_cachetype);
5729 qemu_put_be32(f, env->cp15.c1_sys);
5730 qemu_put_be32(f, env->cp15.c1_coproc);
610c3c8a 5731 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
aa941b94
AZ
5732 qemu_put_be32(f, env->cp15.c2_base);
5733 qemu_put_be32(f, env->cp15.c2_data);
5734 qemu_put_be32(f, env->cp15.c2_insn);
5735 qemu_put_be32(f, env->cp15.c3);
5736 qemu_put_be32(f, env->cp15.c5_insn);
5737 qemu_put_be32(f, env->cp15.c5_data);
5738 for (i = 0; i < 8; i++) {
5739 qemu_put_be32(f, env->cp15.c6_region[i]);
5740 }
5741 qemu_put_be32(f, env->cp15.c6_insn);
5742 qemu_put_be32(f, env->cp15.c6_data);
5743 qemu_put_be32(f, env->cp15.c9_insn);
5744 qemu_put_be32(f, env->cp15.c9_data);
5745 qemu_put_be32(f, env->cp15.c13_fcse);
5746 qemu_put_be32(f, env->cp15.c13_context);
5747 qemu_put_be32(f, env->cp15.c15_cpar);
5748
5749 qemu_put_be32(f, env->features);
5750
5751 if (arm_feature(env, ARM_FEATURE_VFP)) {
5752 for (i = 0; i < 16; i++) {
5753 CPU_DoubleU u;
5754 u.d = env->vfp.regs[i];
5755 qemu_put_be32(f, u.l.upper);
5756 qemu_put_be32(f, u.l.lower);
5757 }
5758 for (i = 0; i < 16; i++) {
5759 qemu_put_be32(f, env->vfp.xregs[i]);
5760 }
5761
5762 /* TODO: Should use proper FPSCR access functions. */
5763 qemu_put_be32(f, env->vfp.vec_len);
5764 qemu_put_be32(f, env->vfp.vec_stride);
5765 }
5766
5767 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5768 for (i = 0; i < 16; i++) {
5769 qemu_put_be64(f, env->iwmmxt.regs[i]);
5770 }
5771 for (i = 0; i < 16; i++) {
5772 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5773 }
5774 }
b5ff1b31
FB
5775}
5776
5777int cpu_load(QEMUFile *f, void *opaque, int version_id)
5778{
aa941b94
AZ
5779 CPUARMState *env = (CPUARMState *)opaque;
5780 int i;
5781
5782 if (version_id != 0)
5783 return -EINVAL;
5784
5785 for (i = 0; i < 16; i++) {
5786 env->regs[i] = qemu_get_be32(f);
5787 }
5788 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5789 env->spsr = qemu_get_be32(f);
5790 for (i = 0; i < 6; i++) {
5791 env->banked_spsr[i] = qemu_get_be32(f);
5792 env->banked_r13[i] = qemu_get_be32(f);
5793 env->banked_r14[i] = qemu_get_be32(f);
5794 }
5795 for (i = 0; i < 5; i++) {
5796 env->usr_regs[i] = qemu_get_be32(f);
5797 env->fiq_regs[i] = qemu_get_be32(f);
5798 }
5799 env->cp15.c0_cpuid = qemu_get_be32(f);
5800 env->cp15.c0_cachetype = qemu_get_be32(f);
5801 env->cp15.c1_sys = qemu_get_be32(f);
5802 env->cp15.c1_coproc = qemu_get_be32(f);
610c3c8a 5803 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
aa941b94
AZ
5804 env->cp15.c2_base = qemu_get_be32(f);
5805 env->cp15.c2_data = qemu_get_be32(f);
5806 env->cp15.c2_insn = qemu_get_be32(f);
5807 env->cp15.c3 = qemu_get_be32(f);
5808 env->cp15.c5_insn = qemu_get_be32(f);
5809 env->cp15.c5_data = qemu_get_be32(f);
5810 for (i = 0; i < 8; i++) {
5811 env->cp15.c6_region[i] = qemu_get_be32(f);
5812 }
5813 env->cp15.c6_insn = qemu_get_be32(f);
5814 env->cp15.c6_data = qemu_get_be32(f);
5815 env->cp15.c9_insn = qemu_get_be32(f);
5816 env->cp15.c9_data = qemu_get_be32(f);
5817 env->cp15.c13_fcse = qemu_get_be32(f);
5818 env->cp15.c13_context = qemu_get_be32(f);
5819 env->cp15.c15_cpar = qemu_get_be32(f);
5820
5821 env->features = qemu_get_be32(f);
5822
5823 if (arm_feature(env, ARM_FEATURE_VFP)) {
5824 for (i = 0; i < 16; i++) {
5825 CPU_DoubleU u;
5826 u.l.upper = qemu_get_be32(f);
5827 u.l.lower = qemu_get_be32(f);
5828 env->vfp.regs[i] = u.d;
5829 }
5830 for (i = 0; i < 16; i++) {
5831 env->vfp.xregs[i] = qemu_get_be32(f);
5832 }
5833
5834 /* TODO: Should use proper FPSCR access functions. */
5835 env->vfp.vec_len = qemu_get_be32(f);
5836 env->vfp.vec_stride = qemu_get_be32(f);
5837 }
5838
5839 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5840 for (i = 0; i < 16; i++) {
5841 env->iwmmxt.regs[i] = qemu_get_be64(f);
5842 }
5843 for (i = 0; i < 16; i++) {
5844 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5845 }
5846 }
5847
b5ff1b31
FB
5848 return 0;
5849}
5850
8a7ddc38
FB
5851#else
5852
5853#warning No CPU save/restore functions
5854
5855#endif
5856
5857/***********************************************************/
5858/* ram save/restore */
5859
8a7ddc38
FB
5860static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5861{
5862 int v;
5863
5864 v = qemu_get_byte(f);
5865 switch(v) {
5866 case 0:
5867 if (qemu_get_buffer(f, buf, len) != len)
5868 return -EIO;
5869 break;
5870 case 1:
5871 v = qemu_get_byte(f);
5872 memset(buf, v, len);
5873 break;
5874 default:
5875 return -EINVAL;
5876 }
5877 return 0;
5878}
5879
c88676f8
FB
5880static int ram_load_v1(QEMUFile *f, void *opaque)
5881{
5882 int i, ret;
5883
5884 if (qemu_get_be32(f) != phys_ram_size)
5885 return -EINVAL;
5886 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5887 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5888 if (ret)
5889 return ret;
5890 }
5891 return 0;
5892}
5893
5894#define BDRV_HASH_BLOCK_SIZE 1024
5895#define IOBUF_SIZE 4096
5896#define RAM_CBLOCK_MAGIC 0xfabe
5897
5898typedef struct RamCompressState {
5899 z_stream zstream;
5900 QEMUFile *f;
5901 uint8_t buf[IOBUF_SIZE];
5902} RamCompressState;
5903
5904static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5905{
5906 int ret;
5907 memset(s, 0, sizeof(*s));
5908 s->f = f;
5909 ret = deflateInit2(&s->zstream, 1,
5910 Z_DEFLATED, 15,
5911 9, Z_DEFAULT_STRATEGY);
5912 if (ret != Z_OK)
5913 return -1;
5914 s->zstream.avail_out = IOBUF_SIZE;
5915 s->zstream.next_out = s->buf;
5916 return 0;
5917}
5918
5919static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5920{
5921 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5922 qemu_put_be16(s->f, len);
5923 qemu_put_buffer(s->f, buf, len);
5924}
5925
5926static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5927{
5928 int ret;
5929
5930 s->zstream.avail_in = len;
5931 s->zstream.next_in = (uint8_t *)buf;
5932 while (s->zstream.avail_in > 0) {
5933 ret = deflate(&s->zstream, Z_NO_FLUSH);
5934 if (ret != Z_OK)
5935 return -1;
5936 if (s->zstream.avail_out == 0) {
5937 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5938 s->zstream.avail_out = IOBUF_SIZE;
5939 s->zstream.next_out = s->buf;
5940 }
5941 }
5942 return 0;
5943}
5944
5945static void ram_compress_close(RamCompressState *s)
5946{
5947 int len, ret;
5948
5949 /* compress last bytes */
5950 for(;;) {
5951 ret = deflate(&s->zstream, Z_FINISH);
5952 if (ret == Z_OK || ret == Z_STREAM_END) {
5953 len = IOBUF_SIZE - s->zstream.avail_out;
5954 if (len > 0) {
5955 ram_put_cblock(s, s->buf, len);
5956 }
5957 s->zstream.avail_out = IOBUF_SIZE;
5958 s->zstream.next_out = s->buf;
5959 if (ret == Z_STREAM_END)
5960 break;
5961 } else {
5962 goto fail;
5963 }
5964 }
5965fail:
5966 deflateEnd(&s->zstream);
5967}
5968
5969typedef struct RamDecompressState {
5970 z_stream zstream;
5971 QEMUFile *f;
5972 uint8_t buf[IOBUF_SIZE];
5973} RamDecompressState;
5974
5975static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5976{
5977 int ret;
5978 memset(s, 0, sizeof(*s));
5979 s->f = f;
5980 ret = inflateInit(&s->zstream);
5981 if (ret != Z_OK)
5982 return -1;
5983 return 0;
5984}
5985
5986static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5987{
5988 int ret, clen;
5989
5990 s->zstream.avail_out = len;
5991 s->zstream.next_out = buf;
5992 while (s->zstream.avail_out > 0) {
5993 if (s->zstream.avail_in == 0) {
5994 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5995 return -1;
5996 clen = qemu_get_be16(s->f);
5997 if (clen > IOBUF_SIZE)
5998 return -1;
5999 qemu_get_buffer(s->f, s->buf, clen);
6000 s->zstream.avail_in = clen;
6001 s->zstream.next_in = s->buf;
6002 }
6003 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6004 if (ret != Z_OK && ret != Z_STREAM_END) {
6005 return -1;
6006 }
6007 }
6008 return 0;
6009}
6010
6011static void ram_decompress_close(RamDecompressState *s)
6012{
6013 inflateEnd(&s->zstream);
6014}
6015
8a7ddc38
FB
6016static void ram_save(QEMUFile *f, void *opaque)
6017{
6018 int i;
c88676f8
FB
6019 RamCompressState s1, *s = &s1;
6020 uint8_t buf[10];
6021
8a7ddc38 6022 qemu_put_be32(f, phys_ram_size);
c88676f8
FB
6023 if (ram_compress_open(s, f) < 0)
6024 return;
6025 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6026#if 0
6027 if (tight_savevm_enabled) {
6028 int64_t sector_num;
6029 int j;
6030
6031 /* find if the memory block is available on a virtual
6032 block device */
6033 sector_num = -1;
6034 for(j = 0; j < MAX_DISKS; j++) {
6035 if (bs_table[j]) {
6036 sector_num = bdrv_hash_find(bs_table[j],
6037 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6038 if (sector_num >= 0)
6039 break;
6040 }
6041 }
6042 if (j == MAX_DISKS)
6043 goto normal_compress;
6044 buf[0] = 1;
6045 buf[1] = j;
6046 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6047 ram_compress_buf(s, buf, 10);
6048 } else
6049#endif
6050 {
6051 // normal_compress:
6052 buf[0] = 0;
6053 ram_compress_buf(s, buf, 1);
6054 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6055 }
8a7ddc38 6056 }
c88676f8 6057 ram_compress_close(s);
8a7ddc38
FB
6058}
6059
6060static int ram_load(QEMUFile *f, void *opaque, int version_id)
6061{
c88676f8
FB
6062 RamDecompressState s1, *s = &s1;
6063 uint8_t buf[10];
6064 int i;
8a7ddc38 6065
c88676f8
FB
6066 if (version_id == 1)
6067 return ram_load_v1(f, opaque);
6068 if (version_id != 2)
8a7ddc38
FB
6069 return -EINVAL;
6070 if (qemu_get_be32(f) != phys_ram_size)
6071 return -EINVAL;
c88676f8
FB
6072 if (ram_decompress_open(s, f) < 0)
6073 return -EINVAL;
6074 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6075 if (ram_decompress_buf(s, buf, 1) < 0) {
6076 fprintf(stderr, "Error while reading ram block header\n");
6077 goto error;
6078 }
6079 if (buf[0] == 0) {
6080 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6081 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6082 goto error;
6083 }
6084 } else
6085#if 0
6086 if (buf[0] == 1) {
6087 int bs_index;
6088 int64_t sector_num;
6089
6090 ram_decompress_buf(s, buf + 1, 9);
6091 bs_index = buf[1];
6092 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6093 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6094 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6095 goto error;
6096 }
6097 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6098 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6099 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6100 bs_index, sector_num);
6101 goto error;
6102 }
6103 } else
6104#endif
6105 {
6106 error:
6107 printf("Error block header\n");
6108 return -EINVAL;
6109 }
8a7ddc38 6110 }
c88676f8 6111 ram_decompress_close(s);
8a7ddc38
FB
6112 return 0;
6113}
6114
83f64091
FB
6115/***********************************************************/
6116/* bottom halves (can be seen as timers which expire ASAP) */
6117
6118struct QEMUBH {
6119 QEMUBHFunc *cb;
6120 void *opaque;
6121 int scheduled;
6122 QEMUBH *next;
6123};
6124
6125static QEMUBH *first_bh = NULL;
6126
6127QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6128{
6129 QEMUBH *bh;
6130 bh = qemu_mallocz(sizeof(QEMUBH));
6131 if (!bh)
6132 return NULL;
6133 bh->cb = cb;
6134 bh->opaque = opaque;
6135 return bh;
6136}
6137
6eb5733a 6138int qemu_bh_poll(void)
83f64091
FB
6139{
6140 QEMUBH *bh, **pbh;
6eb5733a 6141 int ret;
83f64091 6142
6eb5733a 6143 ret = 0;
83f64091
FB
6144 for(;;) {
6145 pbh = &first_bh;
6146 bh = *pbh;
6147 if (!bh)
6148 break;
6eb5733a 6149 ret = 1;
83f64091
FB
6150 *pbh = bh->next;
6151 bh->scheduled = 0;
6152 bh->cb(bh->opaque);
6153 }
6eb5733a 6154 return ret;
83f64091
FB
6155}
6156
6157void qemu_bh_schedule(QEMUBH *bh)
6158{
6159 CPUState *env = cpu_single_env;
6160 if (bh->scheduled)
6161 return;
6162 bh->scheduled = 1;
6163 bh->next = first_bh;
6164 first_bh = bh;
6165
6166 /* stop the currently executing CPU to execute the BH ASAP */
6167 if (env) {
6168 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6169 }
6170}
6171
6172void qemu_bh_cancel(QEMUBH *bh)
6173{
6174 QEMUBH **pbh;
6175 if (bh->scheduled) {
6176 pbh = &first_bh;
6177 while (*pbh != bh)
6178 pbh = &(*pbh)->next;
6179 *pbh = bh->next;
6180 bh->scheduled = 0;
6181 }
6182}
6183
6184void qemu_bh_delete(QEMUBH *bh)
6185{
6186 qemu_bh_cancel(bh);
6187 qemu_free(bh);
6188}
6189
cc1daa40
FB
6190/***********************************************************/
6191/* machine registration */
6192
6193QEMUMachine *first_machine = NULL;
6194
6195int qemu_register_machine(QEMUMachine *m)
6196{
6197 QEMUMachine **pm;
6198 pm = &first_machine;
6199 while (*pm != NULL)
6200 pm = &(*pm)->next;
6201 m->next = NULL;
6202 *pm = m;
6203 return 0;
6204}
6205
6206QEMUMachine *find_machine(const char *name)
6207{
6208 QEMUMachine *m;
6209
6210 for(m = first_machine; m != NULL; m = m->next) {
6211 if (!strcmp(m->name, name))
6212 return m;
6213 }
6214 return NULL;
6215}
6216
8a7ddc38
FB
6217/***********************************************************/
6218/* main execution loop */
6219
6220void gui_update(void *opaque)
6221{
740733bb
TS
6222 DisplayState *ds = opaque;
6223 ds->dpy_refresh(ds);
6224 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
8a7ddc38
FB
6225}
6226
0bd48850
FB
6227struct vm_change_state_entry {
6228 VMChangeStateHandler *cb;
6229 void *opaque;
6230 LIST_ENTRY (vm_change_state_entry) entries;
6231};
6232
6233static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6234
6235VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6236 void *opaque)
6237{
6238 VMChangeStateEntry *e;
6239
6240 e = qemu_mallocz(sizeof (*e));
6241 if (!e)
6242 return NULL;
6243
6244 e->cb = cb;
6245 e->opaque = opaque;
6246 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6247 return e;
6248}
6249
6250void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6251{
6252 LIST_REMOVE (e, entries);
6253 qemu_free (e);
6254}
6255
6256static void vm_state_notify(int running)
6257{
6258 VMChangeStateEntry *e;
6259
6260 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6261 e->cb(e->opaque, running);
6262 }
6263}
6264
8a7ddc38 6265/* XXX: support several handlers */
0bd48850
FB
6266static VMStopHandler *vm_stop_cb;
6267static void *vm_stop_opaque;
8a7ddc38
FB
6268
6269int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6270{
6271 vm_stop_cb = cb;
6272 vm_stop_opaque = opaque;
6273 return 0;
6274}
6275
6276void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6277{
6278 vm_stop_cb = NULL;
6279}
6280
6281void vm_start(void)
6282{
6283 if (!vm_running) {
6284 cpu_enable_ticks();
6285 vm_running = 1;
0bd48850 6286 vm_state_notify(1);
8a7ddc38
FB
6287 }
6288}
6289
6290void vm_stop(int reason)
6291{
6292 if (vm_running) {
6293 cpu_disable_ticks();
6294 vm_running = 0;
6295 if (reason != 0) {
6296 if (vm_stop_cb) {
6297 vm_stop_cb(vm_stop_opaque, reason);
6298 }
34865134 6299 }
0bd48850 6300 vm_state_notify(0);
8a7ddc38
FB
6301 }
6302}
6303
bb0c6722
FB
6304/* reset/shutdown handler */
6305
6306typedef struct QEMUResetEntry {
6307 QEMUResetHandler *func;
6308 void *opaque;
6309 struct QEMUResetEntry *next;
6310} QEMUResetEntry;
6311
6312static QEMUResetEntry *first_reset_entry;
6313static int reset_requested;
6314static int shutdown_requested;
3475187d 6315static int powerdown_requested;
bb0c6722
FB
6316
6317void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6318{
6319 QEMUResetEntry **pre, *re;
6320
6321 pre = &first_reset_entry;
6322 while (*pre != NULL)
6323 pre = &(*pre)->next;
6324 re = qemu_mallocz(sizeof(QEMUResetEntry));
6325 re->func = func;
6326 re->opaque = opaque;
6327 re->next = NULL;
6328 *pre = re;
6329}
6330
52f61fde 6331static void qemu_system_reset(void)
bb0c6722
FB
6332{
6333 QEMUResetEntry *re;
6334
6335 /* reset all devices */
6336 for(re = first_reset_entry; re != NULL; re = re->next) {
6337 re->func(re->opaque);
6338 }
6339}
6340
6341void qemu_system_reset_request(void)
6342{
d1beab82
FB
6343 if (no_reboot) {
6344 shutdown_requested = 1;
6345 } else {
6346 reset_requested = 1;
6347 }
6a00d601
FB
6348 if (cpu_single_env)
6349 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
6350}
6351
6352void qemu_system_shutdown_request(void)
6353{
6354 shutdown_requested = 1;
6a00d601
FB
6355 if (cpu_single_env)
6356 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
6357}
6358
3475187d
FB
6359void qemu_system_powerdown_request(void)
6360{
6361 powerdown_requested = 1;
6a00d601
FB
6362 if (cpu_single_env)
6363 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
bb0c6722
FB
6364}
6365
5905b2e5 6366void main_loop_wait(int timeout)
8a7ddc38 6367{
cafffd40 6368 IOHandlerRecord *ioh;
e035649e 6369 fd_set rfds, wfds, xfds;
877cf882
TS
6370 int ret, nfds;
6371#ifdef _WIN32
6372 int ret2, i;
6373#endif
fd1dff4b 6374 struct timeval tv;
f331110f
FB
6375 PollingEntry *pe;
6376
c4b1fcc0 6377
f331110f
FB
6378 /* XXX: need to suppress polling by better using win32 events */
6379 ret = 0;
6380 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6381 ret |= pe->func(pe->opaque);
6382 }
38e205a2 6383#ifdef _WIN32
e6b1e558 6384 if (ret == 0) {
a18e524a
FB
6385 int err;
6386 WaitObjects *w = &wait_objects;
6387
6388 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6389 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6390 if (w->func[ret - WAIT_OBJECT_0])
6391 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
e6b1e558
TS
6392
6393 /* Check for additional signaled events */
6394 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6395
6396 /* Check if event is signaled */
6397 ret2 = WaitForSingleObject(w->events[i], 0);
6398 if(ret2 == WAIT_OBJECT_0) {
6399 if (w->func[i])
6400 w->func[i](w->opaque[i]);
6401 } else if (ret2 == WAIT_TIMEOUT) {
6402 } else {
6403 err = GetLastError();
6404 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6405 }
6406 }
a18e524a
FB
6407 } else if (ret == WAIT_TIMEOUT) {
6408 } else {
6409 err = GetLastError();
e6b1e558 6410 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
a18e524a 6411 }
f331110f 6412 }
fd1dff4b
FB
6413#endif
6414 /* poll any events */
6415 /* XXX: separate device handlers from system ones */
6416 nfds = -1;
6417 FD_ZERO(&rfds);
6418 FD_ZERO(&wfds);
e035649e 6419 FD_ZERO(&xfds);
fd1dff4b 6420 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
cafffd40
TS
6421 if (ioh->deleted)
6422 continue;
fd1dff4b
FB
6423 if (ioh->fd_read &&
6424 (!ioh->fd_read_poll ||
6425 ioh->fd_read_poll(ioh->opaque) != 0)) {
6426 FD_SET(ioh->fd, &rfds);
6427 if (ioh->fd > nfds)
6428 nfds = ioh->fd;
6429 }
6430 if (ioh->fd_write) {
6431 FD_SET(ioh->fd, &wfds);
6432 if (ioh->fd > nfds)
6433 nfds = ioh->fd;
6434 }
6435 }
6436
6437 tv.tv_sec = 0;
6438#ifdef _WIN32
6439 tv.tv_usec = 0;
38e205a2 6440#else
fd1dff4b
FB
6441 tv.tv_usec = timeout * 1000;
6442#endif
e035649e
FB
6443#if defined(CONFIG_SLIRP)
6444 if (slirp_inited) {
6445 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6446 }
6447#endif
6448 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
fd1dff4b 6449 if (ret > 0) {
cafffd40
TS
6450 IOHandlerRecord **pioh;
6451
6452 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6453 if (ioh->deleted)
6454 continue;
fd1dff4b
FB
6455 if (FD_ISSET(ioh->fd, &rfds)) {
6456 ioh->fd_read(ioh->opaque);
7c9d8e07 6457 }
fd1dff4b
FB
6458 if (FD_ISSET(ioh->fd, &wfds)) {
6459 ioh->fd_write(ioh->opaque);
c4b1fcc0 6460 }
b4608c04 6461 }
cafffd40
TS
6462
6463 /* remove deleted IO handlers */
6464 pioh = &first_io_handler;
6465 while (*pioh) {
6466 ioh = *pioh;
6467 if (ioh->deleted) {
6468 *pioh = ioh->next;
6469 qemu_free(ioh);
6470 } else
6471 pioh = &ioh->next;
6472 }
fd1dff4b 6473 }
c20709aa 6474#if defined(CONFIG_SLIRP)
fd1dff4b 6475 if (slirp_inited) {
e035649e
FB
6476 if (ret < 0) {
6477 FD_ZERO(&rfds);
6478 FD_ZERO(&wfds);
6479 FD_ZERO(&xfds);
c20709aa 6480 }
e035649e 6481 slirp_select_poll(&rfds, &wfds, &xfds);
fd1dff4b 6482 }
e035649e 6483#endif
83f64091 6484 qemu_aio_poll();
b4608c04 6485
fd1dff4b
FB
6486 if (vm_running) {
6487 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6488 qemu_get_clock(vm_clock));
6489 /* run dma transfers, if any */
6490 DMA_run();
6491 }
423f0742 6492
fd1dff4b
FB
6493 /* real time timers */
6494 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6495 qemu_get_clock(rt_clock));
423f0742
PB
6496
6497 /* Check bottom-halves last in case any of the earlier events triggered
6498 them. */
6499 qemu_bh_poll();
6500
5905b2e5
FB
6501}
6502
6a00d601
FB
6503static CPUState *cur_cpu;
6504
5905b2e5
FB
6505int main_loop(void)
6506{
6507 int ret, timeout;
89bfc105
FB
6508#ifdef CONFIG_PROFILER
6509 int64_t ti;
6510#endif
6a00d601 6511 CPUState *env;
5905b2e5 6512
6a00d601 6513 cur_cpu = first_cpu;
5905b2e5
FB
6514 for(;;) {
6515 if (vm_running) {
15a76449
FB
6516
6517 env = cur_cpu;
6518 for(;;) {
6519 /* get next cpu */
6520 env = env->next_cpu;
6521 if (!env)
6522 env = first_cpu;
89bfc105
FB
6523#ifdef CONFIG_PROFILER
6524 ti = profile_getclock();
6525#endif
6a00d601 6526 ret = cpu_exec(env);
89bfc105
FB
6527#ifdef CONFIG_PROFILER
6528 qemu_time += profile_getclock() - ti;
6529#endif
bd967e05
PB
6530 if (ret == EXCP_HLT) {
6531 /* Give the next CPU a chance to run. */
6532 cur_cpu = env;
6533 continue;
6534 }
15a76449
FB
6535 if (ret != EXCP_HALTED)
6536 break;
6537 /* all CPUs are halted ? */
bd967e05 6538 if (env == cur_cpu)
15a76449 6539 break;
15a76449
FB
6540 }
6541 cur_cpu = env;
6542
5905b2e5 6543 if (shutdown_requested) {
3475187d 6544 ret = EXCP_INTERRUPT;
5905b2e5
FB
6545 break;
6546 }
6547 if (reset_requested) {
6548 reset_requested = 0;
6549 qemu_system_reset();
3475187d
FB
6550 ret = EXCP_INTERRUPT;
6551 }
6552 if (powerdown_requested) {
6553 powerdown_requested = 0;
6554 qemu_system_powerdown();
6555 ret = EXCP_INTERRUPT;
5905b2e5
FB
6556 }
6557 if (ret == EXCP_DEBUG) {
6558 vm_stop(EXCP_DEBUG);
6559 }
bd967e05 6560 /* If all cpus are halted then wait until the next IRQ */
5905b2e5 6561 /* XXX: use timeout computed from timers */
bd967e05 6562 if (ret == EXCP_HALTED)
5905b2e5
FB
6563 timeout = 10;
6564 else
6565 timeout = 0;
6566 } else {
6567 timeout = 10;
6568 }
89bfc105
FB
6569#ifdef CONFIG_PROFILER
6570 ti = profile_getclock();
6571#endif
5905b2e5 6572 main_loop_wait(timeout);
89bfc105
FB
6573#ifdef CONFIG_PROFILER
6574 dev_time += profile_getclock() - ti;
6575#endif
b4608c04 6576 }
34865134
FB
6577 cpu_disable_ticks();
6578 return ret;
b4608c04
FB
6579}
6580
15f82208 6581static void help(int exitcode)
0824d6fc 6582{
84f2e8ef 6583 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
0db63474 6584 "usage: %s [options] [disk_image]\n"
0824d6fc 6585 "\n"
a20dd508 6586 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
fc01f7e7 6587 "\n"
a20dd508 6588 "Standard options:\n"
cc1daa40 6589 "-M machine select emulated machine (-M ? for list)\n"
5adb4839 6590 "-cpu cpu select CPU (-cpu ? for list)\n"
c45886db 6591 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
36b486bb
FB
6592 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6593 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
c4b1fcc0 6594 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3e3d5815 6595 "-mtdblock file use 'file' as on-board Flash memory image\n"
a1bb27b1 6596 "-sd file use 'file' as SecureDigital card image\n"
86f55663 6597 "-pflash file use 'file' as a parallel flash image\n"
eec85c2a 6598 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
667accab
TS
6599 "-snapshot write to temporary files instead of disk image files\n"
6600#ifdef CONFIG_SDL
43523e93 6601 "-no-frame open SDL window without a frame and window decorations\n"
3780e197 6602 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
667accab
TS
6603 "-no-quit disable SDL window close capability\n"
6604#endif
52ca8d6a
FB
6605#ifdef TARGET_I386
6606 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6607#endif
a00bad7e 6608 "-m megs set virtual RAM size to megs MB [default=%d]\n"
91fc2119 6609 "-smp n set the number of CPUs to 'n' [default=1]\n"
c4b1fcc0 6610 "-nographic disable graphical output and redirect serial I/Os to console\n"
a171fe39 6611 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
4ca0074c 6612#ifndef _WIN32
667accab 6613 "-k language use keyboard layout (for example \"fr\" for French)\n"
4ca0074c 6614#endif
1d14ffa9 6615#ifdef HAS_AUDIO
1d14ffa9 6616 "-audio-help print list of audio drivers and their options\n"
c0fe3827
FB
6617 "-soundhw c1,... enable audio support\n"
6618 " and only specified sound cards (comma separated list)\n"
6619 " use -soundhw ? to get the list of supported cards\n"
6a36d84e 6620 " use -soundhw all to enable all of them\n"
1d14ffa9 6621#endif
89980284 6622 "-localtime set the real time clock to local time [default=utc]\n"
d63d307f 6623 "-full-screen start in full screen\n"
a09db21f
FB
6624#ifdef TARGET_I386
6625 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6626#endif
b389dbfb
FB
6627 "-usb enable the USB driver (will be the default soon)\n"
6628 "-usbdevice name add the host or guest USB device 'name'\n"
6f7e9aec
FB
6629#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6630 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
bb0c6722 6631#endif
c35734b2 6632 "-name string set the name of the guest\n"
c4b1fcc0
FB
6633 "\n"
6634 "Network options:\n"
a41b2ff2 6635 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7c9d8e07 6636 " create a new Network Interface Card and connect it to VLAN 'n'\n"
c20709aa 6637#ifdef CONFIG_SLIRP
115defd1
PB
6638 "-net user[,vlan=n][,hostname=host]\n"
6639 " connect the user mode network stack to VLAN 'n' and send\n"
6640 " hostname 'host' to DHCP clients\n"
7c9d8e07 6641#endif
7fb843f8
FB
6642#ifdef _WIN32
6643 "-net tap[,vlan=n],ifname=name\n"
6644 " connect the host TAP network interface to VLAN 'n'\n"
6645#else
7c9d8e07
FB
6646 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6647 " connect the host TAP network interface to VLAN 'n' and use\n"
6648 " the network script 'file' (default=%s);\n"
6a1cbf68 6649 " use 'script=no' to disable script execution;\n"
7c9d8e07 6650 " use 'fd=h' to connect to an already opened TAP interface\n"
7fb843f8 6651#endif
6a00d601 6652 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7c9d8e07 6653 " connect the vlan 'n' to another VLAN using a socket connection\n"
3d830459
FB
6654 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6655 " connect the vlan 'n' to multicast maddr and port\n"
7c9d8e07
FB
6656 "-net none use it alone to have zero network devices; if no -net option\n"
6657 " is provided, the default is '-net nic -net user'\n"
6658 "\n"
6659#ifdef CONFIG_SLIRP
0db1137d 6660 "-tftp dir allow tftp access to files in dir [-net user]\n"
47d5d01a 6661 "-bootp file advertise file in BOOTP replies\n"
7c9d8e07
FB
6662#ifndef _WIN32
6663 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
c94c8d64 6664#endif
9bf05444 6665 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7c9d8e07 6666 " redirect TCP or UDP connections from host to guest [-net user]\n"
c20709aa 6667#endif
a20dd508 6668 "\n"
c4b1fcc0 6669 "Linux boot specific:\n"
a20dd508
FB
6670 "-kernel bzImage use 'bzImage' as kernel image\n"
6671 "-append cmdline use 'cmdline' as kernel command line\n"
6672 "-initrd file use 'file' as initial ram disk\n"
fc01f7e7 6673 "\n"
330d0414 6674 "Debug/Expert options:\n"
82c643ff
FB
6675 "-monitor dev redirect the monitor to char device 'dev'\n"
6676 "-serial dev redirect the serial port to char device 'dev'\n"
6508fe59 6677 "-parallel dev redirect the parallel port to char device 'dev'\n"
f7cce898 6678 "-pidfile file Write PID to 'file'\n"
cd6f1169 6679 "-S freeze CPU at startup (use 'c' to start execution)\n"
cfc3475a
PB
6680 "-s wait gdb connection to port\n"
6681 "-p port set gdb connection port [default=%s]\n"
f193c797 6682 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
46d4767d
FB
6683 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6684 " translation (t=none or lba) (usually qemu can guess them)\n"
87b47350 6685 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
d993e026 6686#ifdef USE_KQEMU
6515b203 6687 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
d993e026
FB
6688 "-no-kqemu disable KQEMU kernel module usage\n"
6689#endif
77fef8c1
FB
6690#ifdef USE_CODE_COPY
6691 "-no-code-copy disable code copy acceleration\n"
6692#endif
bb0c6722 6693#ifdef TARGET_I386
1bfe856e
FB
6694 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6695 " (default is CL-GD5446 PCI VGA)\n"
6515b203 6696 "-no-acpi disable ACPI\n"
bb0c6722 6697#endif
d1beab82 6698 "-no-reboot exit instead of rebooting\n"
d63d307f 6699 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
24236869 6700 "-vnc display start a VNC server on display\n"
71e3ceb8
TS
6701#ifndef _WIN32
6702 "-daemonize daemonize QEMU after initializing\n"
6703#endif
9ae02555 6704 "-option-rom rom load a file, rom, into the option ROM space\n"
66508601
BS
6705#ifdef TARGET_SPARC
6706 "-prom-env variable=value set OpenBIOS nvram variables\n"
6707#endif
0824d6fc 6708 "\n"
82c643ff 6709 "During emulation, the following keys are useful:\n"
032a8c9e
FB
6710 "ctrl-alt-f toggle full screen\n"
6711 "ctrl-alt-n switch to virtual console 'n'\n"
6712 "ctrl-alt toggle mouse and keyboard grab\n"
82c643ff
FB
6713 "\n"
6714 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6715 ,
0db63474 6716 "qemu",
a00bad7e 6717 DEFAULT_RAM_SIZE,
7c9d8e07 6718#ifndef _WIN32
a00bad7e 6719 DEFAULT_NETWORK_SCRIPT,
7c9d8e07 6720#endif
6e44ba7f
FB
6721 DEFAULT_GDBSTUB_PORT,
6722 "/tmp/qemu.log");
15f82208 6723 exit(exitcode);
0824d6fc
FB
6724}
6725
cd6f1169
FB
6726#define HAS_ARG 0x0001
6727
6728enum {
6729 QEMU_OPTION_h,
6730
cc1daa40 6731 QEMU_OPTION_M,
94fc95cd 6732 QEMU_OPTION_cpu,
cd6f1169
FB
6733 QEMU_OPTION_fda,
6734 QEMU_OPTION_fdb,
6735 QEMU_OPTION_hda,
6736 QEMU_OPTION_hdb,
6737 QEMU_OPTION_hdc,
6738 QEMU_OPTION_hdd,
6739 QEMU_OPTION_cdrom,
3e3d5815 6740 QEMU_OPTION_mtdblock,
a1bb27b1 6741 QEMU_OPTION_sd,
86f55663 6742 QEMU_OPTION_pflash,
cd6f1169
FB
6743 QEMU_OPTION_boot,
6744 QEMU_OPTION_snapshot,
52ca8d6a
FB
6745#ifdef TARGET_I386
6746 QEMU_OPTION_no_fd_bootchk,
6747#endif
cd6f1169
FB
6748 QEMU_OPTION_m,
6749 QEMU_OPTION_nographic,
a171fe39 6750 QEMU_OPTION_portrait,
1d14ffa9 6751#ifdef HAS_AUDIO
1d14ffa9
FB
6752 QEMU_OPTION_audio_help,
6753 QEMU_OPTION_soundhw,
6754#endif
cd6f1169 6755
7c9d8e07 6756 QEMU_OPTION_net,
c7f74643 6757 QEMU_OPTION_tftp,
47d5d01a 6758 QEMU_OPTION_bootp,
9d728e8c 6759 QEMU_OPTION_smb,
9bf05444 6760 QEMU_OPTION_redir,
cd6f1169
FB
6761
6762 QEMU_OPTION_kernel,
6763 QEMU_OPTION_append,
6764 QEMU_OPTION_initrd,
6765
6766 QEMU_OPTION_S,
6767 QEMU_OPTION_s,
6768 QEMU_OPTION_p,
6769 QEMU_OPTION_d,
6770 QEMU_OPTION_hdachs,
6771 QEMU_OPTION_L,
6772 QEMU_OPTION_no_code_copy,
3d11d0eb 6773 QEMU_OPTION_k,
ee22c2f7 6774 QEMU_OPTION_localtime,
1f04275e 6775 QEMU_OPTION_cirrusvga,
d34cab9f 6776 QEMU_OPTION_vmsvga,
e9b137c2 6777 QEMU_OPTION_g,
1bfe856e 6778 QEMU_OPTION_std_vga,
20d8a3ed 6779 QEMU_OPTION_echr,
82c643ff
FB
6780 QEMU_OPTION_monitor,
6781 QEMU_OPTION_serial,
6508fe59 6782 QEMU_OPTION_parallel,
d63d307f
FB
6783 QEMU_OPTION_loadvm,
6784 QEMU_OPTION_full_screen,
43523e93 6785 QEMU_OPTION_no_frame,
3780e197 6786 QEMU_OPTION_alt_grab,
667accab 6787 QEMU_OPTION_no_quit,
f7cce898 6788 QEMU_OPTION_pidfile,
d993e026 6789 QEMU_OPTION_no_kqemu,
89bfc105 6790 QEMU_OPTION_kernel_kqemu,
a09db21f 6791 QEMU_OPTION_win2k_hack,
bb36d470 6792 QEMU_OPTION_usb,
a594cfbf 6793 QEMU_OPTION_usbdevice,
6a00d601 6794 QEMU_OPTION_smp,
24236869 6795 QEMU_OPTION_vnc,
6515b203 6796 QEMU_OPTION_no_acpi,
d1beab82 6797 QEMU_OPTION_no_reboot,
9467cd46 6798 QEMU_OPTION_show_cursor,
71e3ceb8 6799 QEMU_OPTION_daemonize,
9ae02555 6800 QEMU_OPTION_option_rom,
c35734b2
TS
6801 QEMU_OPTION_semihosting,
6802 QEMU_OPTION_name,
66508601 6803 QEMU_OPTION_prom_env,
cd6f1169
FB
6804};
6805
6806typedef struct QEMUOption {
6807 const char *name;
6808 int flags;
6809 int index;
6810} QEMUOption;
6811
6812const QEMUOption qemu_options[] = {
6813 { "h", 0, QEMU_OPTION_h },
64423fb2 6814 { "help", 0, QEMU_OPTION_h },
cd6f1169 6815
cc1daa40 6816 { "M", HAS_ARG, QEMU_OPTION_M },
94fc95cd 6817 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
cd6f1169
FB
6818 { "fda", HAS_ARG, QEMU_OPTION_fda },
6819 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6820 { "hda", HAS_ARG, QEMU_OPTION_hda },
6821 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6822 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6823 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6824 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
3e3d5815 6825 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
a1bb27b1 6826 { "sd", HAS_ARG, QEMU_OPTION_sd },
86f55663 6827 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
cd6f1169
FB
6828 { "boot", HAS_ARG, QEMU_OPTION_boot },
6829 { "snapshot", 0, QEMU_OPTION_snapshot },
52ca8d6a
FB
6830#ifdef TARGET_I386
6831 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6832#endif
cd6f1169
FB
6833 { "m", HAS_ARG, QEMU_OPTION_m },
6834 { "nographic", 0, QEMU_OPTION_nographic },
a171fe39 6835 { "portrait", 0, QEMU_OPTION_portrait },
3d11d0eb 6836 { "k", HAS_ARG, QEMU_OPTION_k },
1d14ffa9 6837#ifdef HAS_AUDIO
1d14ffa9
FB
6838 { "audio-help", 0, QEMU_OPTION_audio_help },
6839 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6840#endif
cd6f1169 6841
7c9d8e07 6842 { "net", HAS_ARG, QEMU_OPTION_net},
158156d1 6843#ifdef CONFIG_SLIRP
c7f74643 6844 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
47d5d01a 6845 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
c94c8d64 6846#ifndef _WIN32
9d728e8c 6847 { "smb", HAS_ARG, QEMU_OPTION_smb },
c94c8d64 6848#endif
9bf05444 6849 { "redir", HAS_ARG, QEMU_OPTION_redir },
158156d1 6850#endif
cd6f1169
FB
6851
6852 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6853 { "append", HAS_ARG, QEMU_OPTION_append },
6854 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6855
6856 { "S", 0, QEMU_OPTION_S },
6857 { "s", 0, QEMU_OPTION_s },
6858 { "p", HAS_ARG, QEMU_OPTION_p },
6859 { "d", HAS_ARG, QEMU_OPTION_d },
6860 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6861 { "L", HAS_ARG, QEMU_OPTION_L },
6862 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
d993e026
FB
6863#ifdef USE_KQEMU
6864 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
89bfc105 6865 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
d993e026 6866#endif
6f7e9aec 6867#if defined(TARGET_PPC) || defined(TARGET_SPARC)
e9b137c2 6868 { "g", 1, QEMU_OPTION_g },
77d4bc34 6869#endif
ee22c2f7 6870 { "localtime", 0, QEMU_OPTION_localtime },
1bfe856e 6871 { "std-vga", 0, QEMU_OPTION_std_vga },
8b6e0729
AZ
6872 { "echr", HAS_ARG, QEMU_OPTION_echr },
6873 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6874 { "serial", HAS_ARG, QEMU_OPTION_serial },
6875 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
d63d307f
FB
6876 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6877 { "full-screen", 0, QEMU_OPTION_full_screen },
667accab 6878#ifdef CONFIG_SDL
43523e93 6879 { "no-frame", 0, QEMU_OPTION_no_frame },
3780e197 6880 { "alt-grab", 0, QEMU_OPTION_alt_grab },
667accab
TS
6881 { "no-quit", 0, QEMU_OPTION_no_quit },
6882#endif
f7cce898 6883 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
a09db21f 6884 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
a594cfbf 6885 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6a00d601 6886 { "smp", HAS_ARG, QEMU_OPTION_smp },
24236869 6887 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
96d30e48 6888
1f04275e 6889 /* temporary options */
a594cfbf 6890 { "usb", 0, QEMU_OPTION_usb },
1f04275e 6891 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
d34cab9f 6892 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6515b203 6893 { "no-acpi", 0, QEMU_OPTION_no_acpi },
d1beab82 6894 { "no-reboot", 0, QEMU_OPTION_no_reboot },
9467cd46 6895 { "show-cursor", 0, QEMU_OPTION_show_cursor },
71e3ceb8 6896 { "daemonize", 0, QEMU_OPTION_daemonize },
9ae02555 6897 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
a87295e8 6898#if defined(TARGET_ARM) || defined(TARGET_M68K)
8e71621f
PB
6899 { "semihosting", 0, QEMU_OPTION_semihosting },
6900#endif
c35734b2 6901 { "name", HAS_ARG, QEMU_OPTION_name },
66508601
BS
6902#if defined(TARGET_SPARC)
6903 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6904#endif
cd6f1169 6905 { NULL },
fc01f7e7
FB
6906};
6907
77fef8c1
FB
6908#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6909
6910/* this stack is only used during signal handling */
6911#define SIGNAL_STACK_SIZE 32768
6912
6913static uint8_t *signal_stack;
6914
6915#endif
6916
5905b2e5
FB
6917/* password input */
6918
2bac6019
AZ
6919int qemu_key_check(BlockDriverState *bs, const char *name)
6920{
6921 char password[256];
6922 int i;
6923
6924 if (!bdrv_is_encrypted(bs))
6925 return 0;
6926
6927 term_printf("%s is encrypted.\n", name);
6928 for(i = 0; i < 3; i++) {
6929 monitor_readline("Password: ", 1, password, sizeof(password));
6930 if (bdrv_set_key(bs, password) == 0)
6931 return 0;
6932 term_printf("invalid password\n");
6933 }
6934 return -EPERM;
6935}
6936
5905b2e5
FB
6937static BlockDriverState *get_bdrv(int index)
6938{
6939 BlockDriverState *bs;
6940
6941 if (index < 4) {
6942 bs = bs_table[index];
6943 } else if (index < 6) {
6944 bs = fd_table[index - 4];
6945 } else {
6946 bs = NULL;
6947 }
6948 return bs;
6949}
6950
6951static void read_passwords(void)
6952{
6953 BlockDriverState *bs;
2bac6019 6954 int i;
5905b2e5
FB
6955
6956 for(i = 0; i < 6; i++) {
6957 bs = get_bdrv(i);
2bac6019
AZ
6958 if (bs)
6959 qemu_key_check(bs, bdrv_get_device_name(bs));
5905b2e5
FB
6960 }
6961}
6962
cc1daa40
FB
6963/* XXX: currently we cannot use simultaneously different CPUs */
6964void register_machines(void)
6965{
6966#if defined(TARGET_I386)
6967 qemu_register_machine(&pc_machine);
3dbbdc25 6968 qemu_register_machine(&isapc_machine);
cc1daa40
FB
6969#elif defined(TARGET_PPC)
6970 qemu_register_machine(&heathrow_machine);
6971 qemu_register_machine(&core99_machine);
6972 qemu_register_machine(&prep_machine);
1a6c0886
JM
6973 qemu_register_machine(&ref405ep_machine);
6974 qemu_register_machine(&taihu_machine);
6af0bf9c
FB
6975#elif defined(TARGET_MIPS)
6976 qemu_register_machine(&mips_machine);
5856de80 6977 qemu_register_machine(&mips_malta_machine);
ad6fe1d2 6978 qemu_register_machine(&mips_pica61_machine);
cc1daa40 6979#elif defined(TARGET_SPARC)
3475187d
FB
6980#ifdef TARGET_SPARC64
6981 qemu_register_machine(&sun4u_machine);
6982#else
36cd9210 6983 qemu_register_machine(&ss5_machine);
e0353fe2 6984 qemu_register_machine(&ss10_machine);
cc1daa40 6985#endif
b5ff1b31 6986#elif defined(TARGET_ARM)
3371d272 6987 qemu_register_machine(&integratorcp_machine);
cdbdb648 6988 qemu_register_machine(&versatilepb_machine);
16406950 6989 qemu_register_machine(&versatileab_machine);
e69954b9 6990 qemu_register_machine(&realview_machine);
b00052e4
AZ
6991 qemu_register_machine(&akitapda_machine);
6992 qemu_register_machine(&spitzpda_machine);
6993 qemu_register_machine(&borzoipda_machine);
6994 qemu_register_machine(&terrierpda_machine);
27c7ca7e
FB
6995#elif defined(TARGET_SH4)
6996 qemu_register_machine(&shix_machine);
eddf68a6
JM
6997#elif defined(TARGET_ALPHA)
6998 /* XXX: TODO */
0633879f 6999#elif defined(TARGET_M68K)
20dcee94 7000 qemu_register_machine(&mcf5208evb_machine);
0633879f 7001 qemu_register_machine(&an5206_machine);
b5ff1b31
FB
7002#else
7003#error unsupported CPU
3475187d 7004#endif
cc1daa40
FB
7005}
7006
1d14ffa9 7007#ifdef HAS_AUDIO
6a36d84e 7008struct soundhw soundhw[] = {
b00052e4 7009#ifdef HAS_AUDIO_CHOICE
fd06c375
FB
7010#ifdef TARGET_I386
7011 {
7012 "pcspk",
7013 "PC speaker",
7014 0,
7015 1,
7016 { .init_isa = pcspk_audio_init }
7017 },
7018#endif
6a36d84e
FB
7019 {
7020 "sb16",
7021 "Creative Sound Blaster 16",
7022 0,
7023 1,
7024 { .init_isa = SB16_init }
7025 },
7026
1d14ffa9 7027#ifdef CONFIG_ADLIB
6a36d84e
FB
7028 {
7029 "adlib",
1d14ffa9 7030#ifdef HAS_YMF262
6a36d84e 7031 "Yamaha YMF262 (OPL3)",
1d14ffa9 7032#else
6a36d84e 7033 "Yamaha YM3812 (OPL2)",
1d14ffa9 7034#endif
6a36d84e
FB
7035 0,
7036 1,
7037 { .init_isa = Adlib_init }
7038 },
1d14ffa9 7039#endif
6a36d84e 7040
1d14ffa9 7041#ifdef CONFIG_GUS
6a36d84e
FB
7042 {
7043 "gus",
7044 "Gravis Ultrasound GF1",
7045 0,
7046 1,
7047 { .init_isa = GUS_init }
7048 },
1d14ffa9 7049#endif
6a36d84e
FB
7050
7051 {
7052 "es1370",
7053 "ENSONIQ AudioPCI ES1370",
7054 0,
7055 0,
7056 { .init_pci = es1370_init }
7057 },
b00052e4 7058#endif
6a36d84e
FB
7059
7060 { NULL, NULL, 0, 0, { NULL } }
7061};
7062
7063static void select_soundhw (const char *optarg)
7064{
7065 struct soundhw *c;
7066
7067 if (*optarg == '?') {
7068 show_valid_cards:
7069
7070 printf ("Valid sound card names (comma separated):\n");
7071 for (c = soundhw; c->name; ++c) {
7072 printf ("%-11s %s\n", c->name, c->descr);
7073 }
7074 printf ("\n-soundhw all will enable all of the above\n");
1d14ffa9
FB
7075 exit (*optarg != '?');
7076 }
7077 else {
6a36d84e 7078 size_t l;
1d14ffa9
FB
7079 const char *p;
7080 char *e;
7081 int bad_card = 0;
7082
6a36d84e
FB
7083 if (!strcmp (optarg, "all")) {
7084 for (c = soundhw; c->name; ++c) {
7085 c->enabled = 1;
7086 }
7087 return;
7088 }
1d14ffa9 7089
6a36d84e 7090 p = optarg;
1d14ffa9
FB
7091 while (*p) {
7092 e = strchr (p, ',');
7093 l = !e ? strlen (p) : (size_t) (e - p);
6a36d84e
FB
7094
7095 for (c = soundhw; c->name; ++c) {
7096 if (!strncmp (c->name, p, l)) {
7097 c->enabled = 1;
1d14ffa9
FB
7098 break;
7099 }
7100 }
6a36d84e
FB
7101
7102 if (!c->name) {
1d14ffa9
FB
7103 if (l > 80) {
7104 fprintf (stderr,
7105 "Unknown sound card name (too big to show)\n");
7106 }
7107 else {
7108 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7109 (int) l, p);
7110 }
7111 bad_card = 1;
7112 }
7113 p += l + (e != NULL);
7114 }
7115
7116 if (bad_card)
7117 goto show_valid_cards;
7118 }
7119}
7120#endif
7121
3587d7e6
FB
7122#ifdef _WIN32
7123static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7124{
7125 exit(STATUS_CONTROL_C_EXIT);
7126 return TRUE;
7127}
7128#endif
7129
7c9d8e07 7130#define MAX_NET_CLIENTS 32
c20709aa 7131
0824d6fc
FB
7132int main(int argc, char **argv)
7133{
67b915a5 7134#ifdef CONFIG_GDBSTUB
cfc3475a
PB
7135 int use_gdbstub;
7136 const char *gdbstub_port;
67b915a5 7137#endif
86f55663 7138 int i, cdrom_index, pflash_index;
1ccde1cb 7139 int snapshot, linux_boot;
7f7f9873 7140 const char *initrd_filename;
96d30e48 7141 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
86f55663 7142 const char *pflash_filename[MAX_PFLASH];
a1bb27b1 7143 const char *sd_filename;
3e3d5815 7144 const char *mtd_filename;
a20dd508 7145 const char *kernel_filename, *kernel_cmdline;
313aa567 7146 DisplayState *ds = &display_state;
46d4767d 7147 int cyls, heads, secs, translation;
7c9d8e07
FB
7148 char net_clients[MAX_NET_CLIENTS][256];
7149 int nb_net_clients;
cd6f1169
FB
7150 int optind;
7151 const char *r, *optarg;
82c643ff
FB
7152 CharDriverState *monitor_hd;
7153 char monitor_device[128];
8d11df9e
FB
7154 char serial_devices[MAX_SERIAL_PORTS][128];
7155 int serial_device_index;
6508fe59
FB
7156 char parallel_devices[MAX_PARALLEL_PORTS][128];
7157 int parallel_device_index;
d63d307f 7158 const char *loadvm = NULL;
cc1daa40 7159 QEMUMachine *machine;
94fc95cd 7160 const char *cpu_model;
0d92ed30 7161 char usb_devices[MAX_USB_CMDLINE][128];
a594cfbf 7162 int usb_devices_index;
71e3ceb8 7163 int fds[2];
93815bc2 7164 const char *pid_file = NULL;
833c7174 7165 VLANState *vlan;
0bd48850
FB
7166
7167 LIST_INIT (&vm_change_state_head);
be995c27
FB
7168#ifndef _WIN32
7169 {
7170 struct sigaction act;
7171 sigfillset(&act.sa_mask);
7172 act.sa_flags = 0;
7173 act.sa_handler = SIG_IGN;
7174 sigaction(SIGPIPE, &act, NULL);
7175 }
3587d7e6
FB
7176#else
7177 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
a8e5ac33
FB
7178 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7179 QEMU to run on a single CPU */
7180 {
7181 HANDLE h;
7182 DWORD mask, smask;
7183 int i;
7184 h = GetCurrentProcess();
7185 if (GetProcessAffinityMask(h, &mask, &smask)) {
7186 for(i = 0; i < 32; i++) {
7187 if (mask & (1 << i))
7188 break;
7189 }
7190 if (i != 32) {
7191 mask = 1 << i;
7192 SetProcessAffinityMask(h, mask);
7193 }
7194 }
7195 }
67b915a5 7196#endif
be995c27 7197
cc1daa40
FB
7198 register_machines();
7199 machine = first_machine;
94fc95cd 7200 cpu_model = NULL;
fc01f7e7 7201 initrd_filename = NULL;
c45886db
FB
7202 for(i = 0; i < MAX_FD; i++)
7203 fd_filename[i] = NULL;
96d30e48
TS
7204 for(i = 0; i < MAX_DISKS; i++)
7205 hd_filename[i] = NULL;
86f55663
JM
7206 for(i = 0; i < MAX_PFLASH; i++)
7207 pflash_filename[i] = NULL;
7208 pflash_index = 0;
a1bb27b1 7209 sd_filename = NULL;
3e3d5815 7210 mtd_filename = NULL;
a00bad7e 7211 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
313aa567 7212 vga_ram_size = VGA_RAM_SIZE;
67b915a5 7213#ifdef CONFIG_GDBSTUB
b4608c04 7214 use_gdbstub = 0;
c636bb66 7215 gdbstub_port = DEFAULT_GDBSTUB_PORT;
67b915a5 7216#endif
33e3963e 7217 snapshot = 0;
a20dd508
FB
7218 nographic = 0;
7219 kernel_filename = NULL;
7220 kernel_cmdline = "";
cc1daa40
FB
7221#ifdef TARGET_PPC
7222 cdrom_index = 1;
7223#else
7224 cdrom_index = 2;
7225#endif
c4b1fcc0 7226 cyls = heads = secs = 0;
46d4767d 7227 translation = BIOS_ATA_TRANSLATION_AUTO;
82c643ff 7228 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
c4b1fcc0 7229
8d11df9e
FB
7230 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7231 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7232 serial_devices[i][0] = '\0';
7233 serial_device_index = 0;
7234
6508fe59
FB
7235 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7236 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7237 parallel_devices[i][0] = '\0';
7238 parallel_device_index = 0;
7239
a594cfbf
FB
7240 usb_devices_index = 0;
7241
7c9d8e07
FB
7242 nb_net_clients = 0;
7243
7244 nb_nics = 0;
702c651c 7245 /* default mac address of the first network interface */
82c643ff 7246
cd6f1169 7247 optind = 1;
0824d6fc 7248 for(;;) {
cd6f1169 7249 if (optind >= argc)
0824d6fc 7250 break;
cd6f1169
FB
7251 r = argv[optind];
7252 if (r[0] != '-') {
96d30e48 7253 hd_filename[0] = argv[optind++];
cd6f1169
FB
7254 } else {
7255 const QEMUOption *popt;
7256
7257 optind++;
dff5efc8
PB
7258 /* Treat --foo the same as -foo. */
7259 if (r[1] == '-')
7260 r++;
cd6f1169
FB
7261 popt = qemu_options;
7262 for(;;) {
7263 if (!popt->name) {
7264 fprintf(stderr, "%s: invalid option -- '%s'\n",
7265 argv[0], r);
7266 exit(1);
7267 }
7268 if (!strcmp(popt->name, r + 1))
7269 break;
7270 popt++;
7271 }
7272 if (popt->flags & HAS_ARG) {
7273 if (optind >= argc) {
7274 fprintf(stderr, "%s: option '%s' requires an argument\n",
7275 argv[0], r);
7276 exit(1);
7277 }
7278 optarg = argv[optind++];
7279 } else {
7280 optarg = NULL;
7281 }
7282
7283 switch(popt->index) {
cc1daa40
FB
7284 case QEMU_OPTION_M:
7285 machine = find_machine(optarg);
7286 if (!machine) {
7287 QEMUMachine *m;
7288 printf("Supported machines are:\n");
7289 for(m = first_machine; m != NULL; m = m->next) {
7290 printf("%-10s %s%s\n",
7291 m->name, m->desc,
7292 m == first_machine ? " (default)" : "");
7293 }
15f82208 7294 exit(*optarg != '?');
cc1daa40
FB
7295 }
7296 break;
94fc95cd
JM
7297 case QEMU_OPTION_cpu:
7298 /* hw initialization will check this */
15f82208 7299 if (*optarg == '?') {
94fc95cd
JM
7300#if defined(TARGET_PPC)
7301 ppc_cpu_list(stdout, &fprintf);
5adb4839
PB
7302#elif defined(TARGET_ARM)
7303 arm_cpu_list();
33d68b5f
TS
7304#elif defined(TARGET_MIPS)
7305 mips_cpu_list(stdout, &fprintf);
62724a37
BS
7306#elif defined(TARGET_SPARC)
7307 sparc_cpu_list(stdout, &fprintf);
94fc95cd 7308#endif
15f82208 7309 exit(0);
94fc95cd
JM
7310 } else {
7311 cpu_model = optarg;
7312 }
7313 break;
cd6f1169 7314 case QEMU_OPTION_initrd:
fc01f7e7
FB
7315 initrd_filename = optarg;
7316 break;
cd6f1169 7317 case QEMU_OPTION_hda:
cd6f1169 7318 case QEMU_OPTION_hdb:
cc1daa40
FB
7319 case QEMU_OPTION_hdc:
7320 case QEMU_OPTION_hdd:
7321 {
7322 int hd_index;
7323 hd_index = popt->index - QEMU_OPTION_hda;
96d30e48
TS
7324 hd_filename[hd_index] = optarg;
7325 if (hd_index == cdrom_index)
7326 cdrom_index = -1;
cc1daa40 7327 }
fc01f7e7 7328 break;
3e3d5815
AZ
7329 case QEMU_OPTION_mtdblock:
7330 mtd_filename = optarg;
7331 break;
a1bb27b1
PB
7332 case QEMU_OPTION_sd:
7333 sd_filename = optarg;
7334 break;
86f55663
JM
7335 case QEMU_OPTION_pflash:
7336 if (pflash_index >= MAX_PFLASH) {
7337 fprintf(stderr, "qemu: too many parallel flash images\n");
7338 exit(1);
7339 }
7340 pflash_filename[pflash_index++] = optarg;
7341 break;
cd6f1169 7342 case QEMU_OPTION_snapshot:
33e3963e
FB
7343 snapshot = 1;
7344 break;
cd6f1169 7345 case QEMU_OPTION_hdachs:
330d0414 7346 {
330d0414
FB
7347 const char *p;
7348 p = optarg;
7349 cyls = strtol(p, (char **)&p, 0);
46d4767d
FB
7350 if (cyls < 1 || cyls > 16383)
7351 goto chs_fail;
330d0414
FB
7352 if (*p != ',')
7353 goto chs_fail;
7354 p++;
7355 heads = strtol(p, (char **)&p, 0);
46d4767d
FB
7356 if (heads < 1 || heads > 16)
7357 goto chs_fail;
330d0414
FB
7358 if (*p != ',')
7359 goto chs_fail;
7360 p++;
7361 secs = strtol(p, (char **)&p, 0);
46d4767d
FB
7362 if (secs < 1 || secs > 63)
7363 goto chs_fail;
7364 if (*p == ',') {
7365 p++;
7366 if (!strcmp(p, "none"))
7367 translation = BIOS_ATA_TRANSLATION_NONE;
7368 else if (!strcmp(p, "lba"))
7369 translation = BIOS_ATA_TRANSLATION_LBA;
7370 else if (!strcmp(p, "auto"))
7371 translation = BIOS_ATA_TRANSLATION_AUTO;
7372 else
7373 goto chs_fail;
7374 } else if (*p != '\0') {
c4b1fcc0 7375 chs_fail:
46d4767d
FB
7376 fprintf(stderr, "qemu: invalid physical CHS format\n");
7377 exit(1);
c4b1fcc0 7378 }
330d0414
FB
7379 }
7380 break;
cd6f1169 7381 case QEMU_OPTION_nographic:
8d11df9e 7382 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
a39437aa 7383 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
20d8a3ed 7384 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
a20dd508
FB
7385 nographic = 1;
7386 break;
a171fe39
AZ
7387 case QEMU_OPTION_portrait:
7388 graphic_rotate = 1;
7389 break;
cd6f1169 7390 case QEMU_OPTION_kernel:
a20dd508
FB
7391 kernel_filename = optarg;
7392 break;
cd6f1169 7393 case QEMU_OPTION_append:
a20dd508 7394 kernel_cmdline = optarg;
313aa567 7395 break;
cd6f1169 7396 case QEMU_OPTION_cdrom:
96d30e48
TS
7397 if (cdrom_index >= 0) {
7398 hd_filename[cdrom_index] = optarg;
fa1fb14c 7399 }
36b486bb 7400 break;
cd6f1169 7401 case QEMU_OPTION_boot:
36b486bb 7402 boot_device = optarg[0];
9e89a4be 7403 if (boot_device != 'a' &&
eec85c2a 7404#if defined(TARGET_SPARC) || defined(TARGET_I386)
6f7e9aec
FB
7405 // Network boot
7406 boot_device != 'n' &&
7407#endif
c45886db 7408 boot_device != 'c' && boot_device != 'd') {
36b486bb
FB
7409 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7410 exit(1);
7411 }
7412 break;
cd6f1169 7413 case QEMU_OPTION_fda:
c45886db
FB
7414 fd_filename[0] = optarg;
7415 break;
cd6f1169 7416 case QEMU_OPTION_fdb:
c45886db
FB
7417 fd_filename[1] = optarg;
7418 break;
52ca8d6a
FB
7419#ifdef TARGET_I386
7420 case QEMU_OPTION_no_fd_bootchk:
7421 fd_bootchk = 0;
7422 break;
7423#endif
cd6f1169 7424 case QEMU_OPTION_no_code_copy:
77fef8c1
FB
7425 code_copy_enabled = 0;
7426 break;
7c9d8e07
FB
7427 case QEMU_OPTION_net:
7428 if (nb_net_clients >= MAX_NET_CLIENTS) {
7429 fprintf(stderr, "qemu: too many network clients\n");
c4b1fcc0
FB
7430 exit(1);
7431 }
7c9d8e07
FB
7432 pstrcpy(net_clients[nb_net_clients],
7433 sizeof(net_clients[0]),
7434 optarg);
7435 nb_net_clients++;
702c651c 7436 break;
c7f74643
FB
7437#ifdef CONFIG_SLIRP
7438 case QEMU_OPTION_tftp:
c7f74643 7439 tftp_prefix = optarg;
9bf05444 7440 break;
47d5d01a
TS
7441 case QEMU_OPTION_bootp:
7442 bootp_filename = optarg;
7443 break;
c94c8d64 7444#ifndef _WIN32
9d728e8c
FB
7445 case QEMU_OPTION_smb:
7446 net_slirp_smb(optarg);
7447 break;
c94c8d64 7448#endif
9bf05444
FB
7449 case QEMU_OPTION_redir:
7450 net_slirp_redir(optarg);
7451 break;
c7f74643 7452#endif
1d14ffa9 7453#ifdef HAS_AUDIO
1d14ffa9
FB
7454 case QEMU_OPTION_audio_help:
7455 AUD_help ();
7456 exit (0);
7457 break;
7458 case QEMU_OPTION_soundhw:
7459 select_soundhw (optarg);
7460 break;
7461#endif
cd6f1169 7462 case QEMU_OPTION_h:
15f82208 7463 help(0);
cd6f1169
FB
7464 break;
7465 case QEMU_OPTION_m:
7466 ram_size = atoi(optarg) * 1024 * 1024;
7467 if (ram_size <= 0)
15f82208 7468 help(1);
cd6f1169
FB
7469 if (ram_size > PHYS_RAM_MAX_SIZE) {
7470 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7471 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7472 exit(1);
7473 }
7474 break;
7475 case QEMU_OPTION_d:
7476 {
7477 int mask;
7478 CPULogItem *item;
7479
7480 mask = cpu_str_to_log_mask(optarg);
7481 if (!mask) {
7482 printf("Log items (comma separated):\n");
f193c797
FB
7483 for(item = cpu_log_items; item->mask != 0; item++) {
7484 printf("%-10s %s\n", item->name, item->help);
7485 }
7486 exit(1);
cd6f1169
FB
7487 }
7488 cpu_set_log(mask);
f193c797 7489 }
cd6f1169 7490 break;
67b915a5 7491#ifdef CONFIG_GDBSTUB
cd6f1169
FB
7492 case QEMU_OPTION_s:
7493 use_gdbstub = 1;
7494 break;
7495 case QEMU_OPTION_p:
cfc3475a 7496 gdbstub_port = optarg;
cd6f1169 7497 break;
67b915a5 7498#endif
cd6f1169
FB
7499 case QEMU_OPTION_L:
7500 bios_dir = optarg;
7501 break;
7502 case QEMU_OPTION_S:
3c07f8e8 7503 autostart = 0;
cd6f1169 7504 break;
3d11d0eb
FB
7505 case QEMU_OPTION_k:
7506 keyboard_layout = optarg;
7507 break;
ee22c2f7
FB
7508 case QEMU_OPTION_localtime:
7509 rtc_utc = 0;
7510 break;
1f04275e
FB
7511 case QEMU_OPTION_cirrusvga:
7512 cirrus_vga_enabled = 1;
d34cab9f
TS
7513 vmsvga_enabled = 0;
7514 break;
7515 case QEMU_OPTION_vmsvga:
7516 cirrus_vga_enabled = 0;
7517 vmsvga_enabled = 1;
1f04275e 7518 break;
1bfe856e
FB
7519 case QEMU_OPTION_std_vga:
7520 cirrus_vga_enabled = 0;
d34cab9f 7521 vmsvga_enabled = 0;
1bfe856e 7522 break;
e9b137c2
FB
7523 case QEMU_OPTION_g:
7524 {
7525 const char *p;
7526 int w, h, depth;
7527 p = optarg;
7528 w = strtol(p, (char **)&p, 10);
7529 if (w <= 0) {
7530 graphic_error:
7531 fprintf(stderr, "qemu: invalid resolution or depth\n");
7532 exit(1);
7533 }
7534 if (*p != 'x')
7535 goto graphic_error;
7536 p++;
7537 h = strtol(p, (char **)&p, 10);
7538 if (h <= 0)
7539 goto graphic_error;
7540 if (*p == 'x') {
7541 p++;
7542 depth = strtol(p, (char **)&p, 10);
7543 if (depth != 8 && depth != 15 && depth != 16 &&
7544 depth != 24 && depth != 32)
7545 goto graphic_error;
7546 } else if (*p == '\0') {
7547 depth = graphic_depth;
7548 } else {
7549 goto graphic_error;
7550 }
7551
7552 graphic_width = w;
7553 graphic_height = h;
7554 graphic_depth = depth;
7555 }
7556 break;
20d8a3ed
TS
7557 case QEMU_OPTION_echr:
7558 {
7559 char *r;
7560 term_escape_char = strtol(optarg, &r, 0);
7561 if (r == optarg)
7562 printf("Bad argument to echr\n");
7563 break;
7564 }
82c643ff
FB
7565 case QEMU_OPTION_monitor:
7566 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7567 break;
7568 case QEMU_OPTION_serial:
8d11df9e
FB
7569 if (serial_device_index >= MAX_SERIAL_PORTS) {
7570 fprintf(stderr, "qemu: too many serial ports\n");
7571 exit(1);
7572 }
7573 pstrcpy(serial_devices[serial_device_index],
7574 sizeof(serial_devices[0]), optarg);
7575 serial_device_index++;
82c643ff 7576 break;
6508fe59
FB
7577 case QEMU_OPTION_parallel:
7578 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7579 fprintf(stderr, "qemu: too many parallel ports\n");
7580 exit(1);
7581 }
7582 pstrcpy(parallel_devices[parallel_device_index],
7583 sizeof(parallel_devices[0]), optarg);
7584 parallel_device_index++;
7585 break;
d63d307f
FB
7586 case QEMU_OPTION_loadvm:
7587 loadvm = optarg;
7588 break;
7589 case QEMU_OPTION_full_screen:
7590 full_screen = 1;
7591 break;
667accab 7592#ifdef CONFIG_SDL
43523e93
TS
7593 case QEMU_OPTION_no_frame:
7594 no_frame = 1;
7595 break;
3780e197
TS
7596 case QEMU_OPTION_alt_grab:
7597 alt_grab = 1;
7598 break;
667accab
TS
7599 case QEMU_OPTION_no_quit:
7600 no_quit = 1;
7601 break;
7602#endif
f7cce898 7603 case QEMU_OPTION_pidfile:
93815bc2 7604 pid_file = optarg;
f7cce898 7605 break;
a09db21f
FB
7606#ifdef TARGET_I386
7607 case QEMU_OPTION_win2k_hack:
7608 win2k_install_hack = 1;
7609 break;
7610#endif
d993e026
FB
7611#ifdef USE_KQEMU
7612 case QEMU_OPTION_no_kqemu:
7613 kqemu_allowed = 0;
7614 break;
89bfc105
FB
7615 case QEMU_OPTION_kernel_kqemu:
7616 kqemu_allowed = 2;
7617 break;
d993e026 7618#endif
bb36d470
FB
7619 case QEMU_OPTION_usb:
7620 usb_enabled = 1;
7621 break;
a594cfbf
FB
7622 case QEMU_OPTION_usbdevice:
7623 usb_enabled = 1;
0d92ed30 7624 if (usb_devices_index >= MAX_USB_CMDLINE) {
a594cfbf
FB
7625 fprintf(stderr, "Too many USB devices\n");
7626 exit(1);
7627 }
7628 pstrcpy(usb_devices[usb_devices_index],
7629 sizeof(usb_devices[usb_devices_index]),
7630 optarg);
7631 usb_devices_index++;
7632 break;
6a00d601
FB
7633 case QEMU_OPTION_smp:
7634 smp_cpus = atoi(optarg);
ba3c64fb 7635 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6a00d601
FB
7636 fprintf(stderr, "Invalid number of CPUs\n");
7637 exit(1);
7638 }
7639 break;
24236869 7640 case QEMU_OPTION_vnc:
73fc9742 7641 vnc_display = optarg;
24236869 7642 break;
6515b203
FB
7643 case QEMU_OPTION_no_acpi:
7644 acpi_enabled = 0;
7645 break;
d1beab82
FB
7646 case QEMU_OPTION_no_reboot:
7647 no_reboot = 1;
7648 break;
9467cd46
AZ
7649 case QEMU_OPTION_show_cursor:
7650 cursor_hide = 0;
7651 break;
71e3ceb8
TS
7652 case QEMU_OPTION_daemonize:
7653 daemonize = 1;
7654 break;
9ae02555
TS
7655 case QEMU_OPTION_option_rom:
7656 if (nb_option_roms >= MAX_OPTION_ROMS) {
7657 fprintf(stderr, "Too many option ROMs\n");
7658 exit(1);
7659 }
7660 option_rom[nb_option_roms] = optarg;
7661 nb_option_roms++;
7662 break;
8e71621f
PB
7663 case QEMU_OPTION_semihosting:
7664 semihosting_enabled = 1;
7665 break;
c35734b2
TS
7666 case QEMU_OPTION_name:
7667 qemu_name = optarg;
7668 break;
66508601
BS
7669#ifdef TARGET_SPARC
7670 case QEMU_OPTION_prom_env:
7671 if (nb_prom_envs >= MAX_PROM_ENVS) {
7672 fprintf(stderr, "Too many prom variables\n");
7673 exit(1);
7674 }
7675 prom_envs[nb_prom_envs] = optarg;
7676 nb_prom_envs++;
7677 break;
7678#endif
cd6f1169 7679 }
0824d6fc
FB
7680 }
7681 }
330d0414 7682
71e3ceb8
TS
7683#ifndef _WIN32
7684 if (daemonize && !nographic && vnc_display == NULL) {
7685 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7686 daemonize = 0;
7687 }
7688
7689 if (daemonize) {
7690 pid_t pid;
7691
7692 if (pipe(fds) == -1)
7693 exit(1);
7694
7695 pid = fork();
7696 if (pid > 0) {
7697 uint8_t status;
7698 ssize_t len;
7699
7700 close(fds[1]);
7701
7702 again:
93815bc2
TS
7703 len = read(fds[0], &status, 1);
7704 if (len == -1 && (errno == EINTR))
7705 goto again;
7706
7707 if (len != 1)
7708 exit(1);
7709 else if (status == 1) {
7710 fprintf(stderr, "Could not acquire pidfile\n");
7711 exit(1);
7712 } else
7713 exit(0);
71e3ceb8 7714 } else if (pid < 0)
93815bc2 7715 exit(1);
71e3ceb8
TS
7716
7717 setsid();
7718
7719 pid = fork();
7720 if (pid > 0)
7721 exit(0);
7722 else if (pid < 0)
7723 exit(1);
7724
7725 umask(027);
7726 chdir("/");
7727
7728 signal(SIGTSTP, SIG_IGN);
7729 signal(SIGTTOU, SIG_IGN);
7730 signal(SIGTTIN, SIG_IGN);
7731 }
7732#endif
7733
aa26bb2d 7734 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
93815bc2
TS
7735 if (daemonize) {
7736 uint8_t status = 1;
7737 write(fds[1], &status, 1);
7738 } else
7739 fprintf(stderr, "Could not acquire pid file\n");
7740 exit(1);
7741 }
7742
ff3fbb30
FB
7743#ifdef USE_KQEMU
7744 if (smp_cpus > 1)
7745 kqemu_allowed = 0;
7746#endif
a20dd508 7747 linux_boot = (kernel_filename != NULL);
42550fde
TS
7748
7749 if (!linux_boot &&
d84fe7ae 7750 boot_device != 'n' &&
96d30e48
TS
7751 hd_filename[0] == '\0' &&
7752 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
c45886db 7753 fd_filename[0] == '\0')
15f82208 7754 help(1);
0824d6fc 7755
96d30e48
TS
7756 /* boot to floppy or the default cd if no hard disk defined yet */
7757 if (hd_filename[0] == '\0' && boot_device == 'c') {
7758 if (fd_filename[0] != '\0')
7759 boot_device = 'a';
7760 else
7761 boot_device = 'd';
7762 }
7763
b118d61e 7764 setvbuf(stdout, NULL, _IOLBF, 0);
7c9d8e07 7765
634fce96
PB
7766 init_timers();
7767 init_timer_alarm();
83f64091 7768 qemu_aio_init();
634fce96 7769
fd1dff4b
FB
7770#ifdef _WIN32
7771 socket_init();
7772#endif
7773
7c9d8e07
FB
7774 /* init network clients */
7775 if (nb_net_clients == 0) {
7776 /* if no clients, we use a default config */
7777 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7778 "nic");
7779 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7780 "user");
7781 nb_net_clients = 2;
c20709aa
FB
7782 }
7783
7c9d8e07
FB
7784 for(i = 0;i < nb_net_clients; i++) {
7785 if (net_client_init(net_clients[i]) < 0)
7786 exit(1);
702c651c 7787 }
833c7174
BS
7788 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7789 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7790 continue;
7791 if (vlan->nb_guest_devs == 0) {
7792 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7793 exit(1);
7794 }
7795 if (vlan->nb_host_devs == 0)
7796 fprintf(stderr,
7797 "Warning: vlan %d is not connected to host network\n",
7798 vlan->id);
7799 }
f1510b2c 7800
eec85c2a
TS
7801#ifdef TARGET_I386
7802 if (boot_device == 'n') {
7803 for (i = 0; i < nb_nics; i++) {
7804 const char *model = nd_table[i].model;
7805 char buf[1024];
7806 if (model == NULL)
7807 model = "ne2k_pci";
7808 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7809 if (get_image_size(buf) > 0) {
7810 option_rom[nb_option_roms] = strdup(buf);
7811 nb_option_roms++;
7812 break;
7813 }
7814 }
7815 if (i == nb_nics) {
7816 fprintf(stderr, "No valid PXE rom found for network device\n");
7817 exit(1);
7818 }
7819 boot_device = 'c'; /* to prevent confusion by the BIOS */
7820 }
7821#endif
7822
0824d6fc 7823 /* init the memory */
970ac5a3 7824 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
9ae02555 7825
d993e026 7826 phys_ram_base = qemu_vmalloc(phys_ram_size);
7f7f9873
FB
7827 if (!phys_ram_base) {
7828 fprintf(stderr, "Could not allocate physical memory\n");
0824d6fc
FB
7829 exit(1);
7830 }
7831
96d30e48 7832 /* we always create the cdrom drive, even if no disk is there */
5905b2e5 7833 bdrv_init();
96d30e48
TS
7834 if (cdrom_index >= 0) {
7835 bs_table[cdrom_index] = bdrv_new("cdrom");
7836 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
c4b1fcc0
FB
7837 }
7838
96d30e48
TS
7839 /* open the virtual block devices */
7840 for(i = 0; i < MAX_DISKS; i++) {
7841 if (hd_filename[i]) {
7842 if (!bs_table[i]) {
7843 char buf[64];
7844 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7845 bs_table[i] = bdrv_new(buf);
7846 }
7847 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7848 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7849 hd_filename[i]);
7850 exit(1);
7851 }
7852 if (i == 0 && cyls != 0) {
7853 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7854 bdrv_set_translation_hint(bs_table[i], translation);
7855 }
7856 }
c4b1fcc0
FB
7857 }
7858
7859 /* we always create at least one floppy disk */
7860 fd_table[0] = bdrv_new("fda");
7861 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7862
7863 for(i = 0; i < MAX_FD; i++) {
7864 if (fd_filename[i]) {
7865 if (!fd_table[i]) {
7866 char buf[64];
7867 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7868 fd_table[i] = bdrv_new(buf);
7869 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7870 }
a1bb27b1 7871 if (fd_filename[i][0] != '\0') {
83f64091
FB
7872 if (bdrv_open(fd_table[i], fd_filename[i],
7873 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
c20709aa 7874 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
c4b1fcc0
FB
7875 fd_filename[i]);
7876 exit(1);
7877 }
7878 }
33e3963e
FB
7879 }
7880 }
7881
2bac6019 7882 /* Open the virtual parallel flash block devices */
86f55663
JM
7883 for(i = 0; i < MAX_PFLASH; i++) {
7884 if (pflash_filename[i]) {
7885 if (!pflash_table[i]) {
7886 char buf[64];
7887 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7888 pflash_table[i] = bdrv_new(buf);
7889 }
7890 if (bdrv_open(pflash_table[i], pflash_filename[i],
7891 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7892 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7893 pflash_filename[i]);
7894 exit(1);
7895 }
7896 }
7897 }
7898
a1bb27b1
PB
7899 sd_bdrv = bdrv_new ("sd");
7900 /* FIXME: This isn't really a floppy, but it's a reasonable
7901 approximation. */
7902 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7903 if (sd_filename) {
7904 if (bdrv_open(sd_bdrv, sd_filename,
7905 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7906 fprintf(stderr, "qemu: could not open SD card image %s\n",
7907 sd_filename);
2bac6019 7908 } else
a171fe39 7909 qemu_key_check(sd_bdrv, sd_filename);
a1bb27b1
PB
7910 }
7911
3e3d5815
AZ
7912 if (mtd_filename) {
7913 mtd_bdrv = bdrv_new ("mtd");
7914 if (bdrv_open(mtd_bdrv, mtd_filename,
7915 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7916 qemu_key_check(mtd_bdrv, mtd_filename)) {
7917 fprintf(stderr, "qemu: could not open Flash image %s\n",
7918 mtd_filename);
7919 bdrv_delete(mtd_bdrv);
7920 mtd_bdrv = 0;
7921 }
7922 }
7923
c88676f8
FB
7924 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7925 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8a7ddc38 7926
330d0414 7927 init_ioports();
0824d6fc 7928
313aa567 7929 /* terminal init */
740733bb 7930 memset(&display_state, 0, sizeof(display_state));
a20dd508 7931 if (nographic) {
2ff89790
TS
7932 /* nearly nothing to do */
7933 dumb_display_init(ds);
73fc9742 7934 } else if (vnc_display != NULL) {
740733bb 7935 vnc_display_init(ds, vnc_display);
313aa567 7936 } else {
5b0753e0 7937#if defined(CONFIG_SDL)
43523e93 7938 sdl_display_init(ds, full_screen, no_frame);
5b0753e0
FB
7939#elif defined(CONFIG_COCOA)
7940 cocoa_display_init(ds, full_screen);
313aa567
FB
7941#endif
7942 }
0824d6fc 7943
20d8a3ed
TS
7944 /* Maintain compatibility with multiple stdio monitors */
7945 if (!strcmp(monitor_device,"stdio")) {
7946 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7947 if (!strcmp(serial_devices[i],"mon:stdio")) {
7948 monitor_device[0] = '\0';
7949 break;
7950 } else if (!strcmp(serial_devices[i],"stdio")) {
7951 monitor_device[0] = '\0';
7952 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7953 break;
7954 }
7955 }
7956 }
7957 if (monitor_device[0] != '\0') {
7958 monitor_hd = qemu_chr_open(monitor_device);
7959 if (!monitor_hd) {
7960 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7961 exit(1);
7962 }
7963 monitor_init(monitor_hd, !nographic);
82c643ff 7964 }
82c643ff 7965
8d11df9e 7966 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
c03b0f0f
FB
7967 const char *devname = serial_devices[i];
7968 if (devname[0] != '\0' && strcmp(devname, "none")) {
7969 serial_hds[i] = qemu_chr_open(devname);
8d11df9e
FB
7970 if (!serial_hds[i]) {
7971 fprintf(stderr, "qemu: could not open serial device '%s'\n",
c03b0f0f 7972 devname);
8d11df9e
FB
7973 exit(1);
7974 }
af3a9031 7975 if (strstart(devname, "vc", 0))
7ba1260a 7976 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8d11df9e 7977 }
82c643ff 7978 }
82c643ff 7979
6508fe59 7980 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
c03b0f0f
FB
7981 const char *devname = parallel_devices[i];
7982 if (devname[0] != '\0' && strcmp(devname, "none")) {
7983 parallel_hds[i] = qemu_chr_open(devname);
6508fe59
FB
7984 if (!parallel_hds[i]) {
7985 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
c03b0f0f 7986 devname);
6508fe59
FB
7987 exit(1);
7988 }
af3a9031 7989 if (strstart(devname, "vc", 0))
7ba1260a 7990 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6508fe59
FB
7991 }
7992 }
7993
cc1daa40
FB
7994 machine->init(ram_size, vga_ram_size, boot_device,
7995 ds, fd_filename, snapshot,
94fc95cd 7996 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
73332e5c 7997
0d92ed30
PB
7998 /* init USB devices */
7999 if (usb_enabled) {
8000 for(i = 0; i < usb_devices_index; i++) {
8001 if (usb_device_add(usb_devices[i]) < 0) {
8002 fprintf(stderr, "Warning: could not add USB device %s\n",
8003 usb_devices[i]);
8004 }
8005 }
8006 }
8007
740733bb
TS
8008 if (display_state.dpy_refresh) {
8009 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8010 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8011 }
7f7f9873 8012
67b915a5 8013#ifdef CONFIG_GDBSTUB
b4608c04 8014 if (use_gdbstub) {
c636bb66
FB
8015 /* XXX: use standard host:port notation and modify options
8016 accordingly. */
cfc3475a
PB
8017 if (gdbserver_start(gdbstub_port) < 0) {
8018 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
c636bb66 8019 gdbstub_port);
8a7ddc38 8020 exit(1);
8a7ddc38 8021 }
45669e00 8022 }
67b915a5 8023#endif
45669e00 8024
d63d307f 8025 if (loadvm)
faea38e7 8026 do_loadvm(loadvm);
d63d307f 8027
67b915a5 8028 {
5905b2e5
FB
8029 /* XXX: simplify init */
8030 read_passwords();
3c07f8e8 8031 if (autostart) {
5905b2e5
FB
8032 vm_start();
8033 }
0824d6fc 8034 }
ffd843bc 8035
71e3ceb8
TS
8036 if (daemonize) {
8037 uint8_t status = 0;
8038 ssize_t len;
8039 int fd;
8040
8041 again1:
8042 len = write(fds[1], &status, 1);
8043 if (len == -1 && (errno == EINTR))
8044 goto again1;
8045
8046 if (len != 1)
8047 exit(1);
8048
aeb30be6 8049 TFR(fd = open("/dev/null", O_RDWR));
71e3ceb8
TS
8050 if (fd == -1)
8051 exit(1);
8052
8053 dup2(fd, 0);
8054 dup2(fd, 1);
8055 dup2(fd, 2);
8056
8057 close(fd);
8058 }
8059
8a7ddc38 8060 main_loop();
40c3bac3 8061 quit_timers();
0824d6fc
FB
8062 return 0;
8063}