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