Statistics
| Branch: | Revision:

root / vl.c @ 3f4afa14

History | View | Annotate | Download (223.1 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2007 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "hw/hw.h"
25
#include "hw/boards.h"
26
#include "hw/usb.h"
27
#include "hw/pcmcia.h"
28
#include "hw/pc.h"
29
#include "hw/fdc.h"
30
#include "hw/audiodev.h"
31
#include "hw/isa.h"
32
#include "net.h"
33
#include "console.h"
34
#include "sysemu.h"
35
#include "gdbstub.h"
36
#include "qemu-timer.h"
37
#include "qemu-char.h"
38
#include "block.h"
39
#include "audio/audio.h"
40

    
41
#include <unistd.h>
42
#include <fcntl.h>
43
#include <signal.h>
44
#include <time.h>
45
#include <errno.h>
46
#include <sys/time.h>
47
#include <zlib.h>
48

    
49
#ifndef _WIN32
50
#include <sys/times.h>
51
#include <sys/wait.h>
52
#include <termios.h>
53
#include <sys/poll.h>
54
#include <sys/mman.h>
55
#include <sys/ioctl.h>
56
#include <sys/socket.h>
57
#include <netinet/in.h>
58
#include <dirent.h>
59
#include <netdb.h>
60
#include <sys/select.h>
61
#include <arpa/inet.h>
62
#ifdef _BSD
63
#include <sys/stat.h>
64
#ifndef __APPLE__
65
#include <libutil.h>
66
#endif
67
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68
#include <freebsd/stdlib.h>
69
#else
70
#ifndef __sun__
71
#include <linux/if.h>
72
#include <linux/if_tun.h>
73
#include <pty.h>
74
#include <malloc.h>
75
#include <linux/rtc.h>
76

    
77
/* For the benefit of older linux systems which don't supply it,
78
   we use a local copy of hpet.h. */
79
/* #include <linux/hpet.h> */
80
#include "hpet.h"
81

    
82
#include <linux/ppdev.h>
83
#include <linux/parport.h>
84
#else
85
#include <sys/stat.h>
86
#include <sys/ethernet.h>
87
#include <sys/sockio.h>
88
#include <netinet/arp.h>
89
#include <netinet/in.h>
90
#include <netinet/in_systm.h>
91
#include <netinet/ip.h>
92
#include <netinet/ip_icmp.h> // must come after ip.h
93
#include <netinet/udp.h>
94
#include <netinet/tcp.h>
95
#include <net/if.h>
96
#include <syslog.h>
97
#include <stropts.h>
98
#endif
99
#endif
100
#else
101
#include <winsock2.h>
102
int inet_aton(const char *cp, struct in_addr *ia);
103
#endif
104

    
105
#if defined(CONFIG_SLIRP)
106
#include "libslirp.h"
107
#endif
108

    
109
#ifdef _WIN32
110
#include <malloc.h>
111
#include <sys/timeb.h>
112
#include <windows.h>
113
#define getopt_long_only getopt_long
114
#define memalign(align, size) malloc(size)
115
#endif
116

    
117
#include "qemu_socket.h"
118

    
119
#ifdef CONFIG_SDL
120
#ifdef __APPLE__
121
#include <SDL/SDL.h>
122
#endif
123
#endif /* CONFIG_SDL */
124

    
125
#ifdef CONFIG_COCOA
126
#undef main
127
#define main qemu_main
128
#endif /* CONFIG_COCOA */
129

    
130
#include "disas.h"
131

    
132
#include "exec-all.h"
133

    
134
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135
#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
136
#ifdef __sun__
137
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
138
#else
139
#define SMBD_COMMAND "/usr/sbin/smbd"
140
#endif
141

    
142
//#define DEBUG_UNUSED_IOPORT
143
//#define DEBUG_IOPORT
144

    
145
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
146

    
147
#ifdef TARGET_PPC
148
#define DEFAULT_RAM_SIZE 144
149
#else
150
#define DEFAULT_RAM_SIZE 128
151
#endif
152
/* in ms */
153
#define GUI_REFRESH_INTERVAL 30
154

    
155
/* Max number of USB devices that can be specified on the commandline.  */
156
#define MAX_USB_CMDLINE 8
157

    
158
/* XXX: use a two level table to limit memory usage */
159
#define MAX_IOPORTS 65536
160

    
161
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
162
const char *bios_name = NULL;
163
char phys_ram_file[1024];
164
void *ioport_opaque[MAX_IOPORTS];
165
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
166
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
167
/* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
168
   to store the VM snapshots */
169
BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
170
BlockDriverState *pflash_table[MAX_PFLASH];
171
BlockDriverState *sd_bdrv;
172
BlockDriverState *mtd_bdrv;
173
/* point to the block driver where the snapshots are managed */
174
BlockDriverState *bs_snapshots;
175
int vga_ram_size;
176
static DisplayState display_state;
177
int nographic;
178
const char* keyboard_layout = NULL;
179
int64_t ticks_per_sec;
180
int ram_size;
181
int pit_min_timer_count = 0;
182
int nb_nics;
183
NICInfo nd_table[MAX_NICS];
184
int vm_running;
185
int rtc_utc = 1;
186
int rtc_start_date = -1; /* -1 means now */
187
int cirrus_vga_enabled = 1;
188
int vmsvga_enabled = 0;
189
#ifdef TARGET_SPARC
190
int graphic_width = 1024;
191
int graphic_height = 768;
192
int graphic_depth = 8;
193
#else
194
int graphic_width = 800;
195
int graphic_height = 600;
196
int graphic_depth = 15;
197
#endif
198
int full_screen = 0;
199
int no_frame = 0;
200
int no_quit = 0;
201
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
202
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
203
#ifdef TARGET_I386
204
int win2k_install_hack = 0;
205
#endif
206
int usb_enabled = 0;
207
static VLANState *first_vlan;
208
int smp_cpus = 1;
209
const char *vnc_display;
210
#if defined(TARGET_SPARC)
211
#define MAX_CPUS 16
212
#elif defined(TARGET_I386)
213
#define MAX_CPUS 255
214
#else
215
#define MAX_CPUS 1
216
#endif
217
int acpi_enabled = 1;
218
int fd_bootchk = 1;
219
int no_reboot = 0;
220
int cursor_hide = 1;
221
int graphic_rotate = 0;
222
int daemonize = 0;
223
const char *option_rom[MAX_OPTION_ROMS];
224
int nb_option_roms;
225
int semihosting_enabled = 0;
226
int autostart = 1;
227
#ifdef TARGET_ARM
228
int old_param = 0;
229
#endif
230
const char *qemu_name;
231
int alt_grab = 0;
232
#ifdef TARGET_SPARC
233
unsigned int nb_prom_envs = 0;
234
const char *prom_envs[MAX_PROM_ENVS];
235
#endif
236

    
237
#define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
238

    
239
/***********************************************************/
240
/* x86 ISA bus support */
241

    
242
target_phys_addr_t isa_mem_base = 0;
243
PicState2 *isa_pic;
244

    
245
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
246
{
247
#ifdef DEBUG_UNUSED_IOPORT
248
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
249
#endif
250
    return 0xff;
251
}
252

    
253
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
254
{
255
#ifdef DEBUG_UNUSED_IOPORT
256
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
257
#endif
258
}
259

    
260
/* default is to make two byte accesses */
261
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
262
{
263
    uint32_t data;
264
    data = ioport_read_table[0][address](ioport_opaque[address], address);
265
    address = (address + 1) & (MAX_IOPORTS - 1);
266
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
267
    return data;
268
}
269

    
270
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
271
{
272
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
273
    address = (address + 1) & (MAX_IOPORTS - 1);
274
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
275
}
276

    
277
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
278
{
279
#ifdef DEBUG_UNUSED_IOPORT
280
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
281
#endif
282
    return 0xffffffff;
283
}
284

    
285
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
286
{
287
#ifdef DEBUG_UNUSED_IOPORT
288
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
289
#endif
290
}
291

    
292
static void init_ioports(void)
293
{
294
    int i;
295

    
296
    for(i = 0; i < MAX_IOPORTS; i++) {
297
        ioport_read_table[0][i] = default_ioport_readb;
298
        ioport_write_table[0][i] = default_ioport_writeb;
299
        ioport_read_table[1][i] = default_ioport_readw;
300
        ioport_write_table[1][i] = default_ioport_writew;
301
        ioport_read_table[2][i] = default_ioport_readl;
302
        ioport_write_table[2][i] = default_ioport_writel;
303
    }
304
}
305

    
306
/* size is the word size in byte */
307
int register_ioport_read(int start, int length, int size,
308
                         IOPortReadFunc *func, void *opaque)
309
{
310
    int i, bsize;
311

    
312
    if (size == 1) {
313
        bsize = 0;
314
    } else if (size == 2) {
315
        bsize = 1;
316
    } else if (size == 4) {
317
        bsize = 2;
318
    } else {
319
        hw_error("register_ioport_read: invalid size");
320
        return -1;
321
    }
322
    for(i = start; i < start + length; i += size) {
323
        ioport_read_table[bsize][i] = func;
324
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
325
            hw_error("register_ioport_read: invalid opaque");
326
        ioport_opaque[i] = opaque;
327
    }
328
    return 0;
329
}
330

    
331
/* size is the word size in byte */
332
int register_ioport_write(int start, int length, int size,
333
                          IOPortWriteFunc *func, void *opaque)
334
{
335
    int i, bsize;
336

    
337
    if (size == 1) {
338
        bsize = 0;
339
    } else if (size == 2) {
340
        bsize = 1;
341
    } else if (size == 4) {
342
        bsize = 2;
343
    } else {
344
        hw_error("register_ioport_write: invalid size");
345
        return -1;
346
    }
347
    for(i = start; i < start + length; i += size) {
348
        ioport_write_table[bsize][i] = func;
349
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
350
            hw_error("register_ioport_write: invalid opaque");
351
        ioport_opaque[i] = opaque;
352
    }
353
    return 0;
354
}
355

    
356
void isa_unassign_ioport(int start, int length)
357
{
358
    int i;
359

    
360
    for(i = start; i < start + length; i++) {
361
        ioport_read_table[0][i] = default_ioport_readb;
362
        ioport_read_table[1][i] = default_ioport_readw;
363
        ioport_read_table[2][i] = default_ioport_readl;
364

    
365
        ioport_write_table[0][i] = default_ioport_writeb;
366
        ioport_write_table[1][i] = default_ioport_writew;
367
        ioport_write_table[2][i] = default_ioport_writel;
368
    }
369
}
370

    
371
/***********************************************************/
372

    
373
void cpu_outb(CPUState *env, int addr, int val)
374
{
375
#ifdef DEBUG_IOPORT
376
    if (loglevel & CPU_LOG_IOPORT)
377
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
378
#endif
379
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
380
#ifdef USE_KQEMU
381
    if (env)
382
        env->last_io_time = cpu_get_time_fast();
383
#endif
384
}
385

    
386
void cpu_outw(CPUState *env, int addr, int val)
387
{
388
#ifdef DEBUG_IOPORT
389
    if (loglevel & CPU_LOG_IOPORT)
390
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
391
#endif
392
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
393
#ifdef USE_KQEMU
394
    if (env)
395
        env->last_io_time = cpu_get_time_fast();
396
#endif
397
}
398

    
399
void cpu_outl(CPUState *env, int addr, int val)
400
{
401
#ifdef DEBUG_IOPORT
402
    if (loglevel & CPU_LOG_IOPORT)
403
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
404
#endif
405
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
406
#ifdef USE_KQEMU
407
    if (env)
408
        env->last_io_time = cpu_get_time_fast();
409
#endif
410
}
411

    
412
int cpu_inb(CPUState *env, int addr)
413
{
414
    int val;
415
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
416
#ifdef DEBUG_IOPORT
417
    if (loglevel & CPU_LOG_IOPORT)
418
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
419
#endif
420
#ifdef USE_KQEMU
421
    if (env)
422
        env->last_io_time = cpu_get_time_fast();
423
#endif
424
    return val;
425
}
426

    
427
int cpu_inw(CPUState *env, int addr)
428
{
429
    int val;
430
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
431
#ifdef DEBUG_IOPORT
432
    if (loglevel & CPU_LOG_IOPORT)
433
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
434
#endif
435
#ifdef USE_KQEMU
436
    if (env)
437
        env->last_io_time = cpu_get_time_fast();
438
#endif
439
    return val;
440
}
441

    
442
int cpu_inl(CPUState *env, int addr)
443
{
444
    int val;
445
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
446
#ifdef DEBUG_IOPORT
447
    if (loglevel & CPU_LOG_IOPORT)
448
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
449
#endif
450
#ifdef USE_KQEMU
451
    if (env)
452
        env->last_io_time = cpu_get_time_fast();
453
#endif
454
    return val;
455
}
456

    
457
/***********************************************************/
458
void hw_error(const char *fmt, ...)
459
{
460
    va_list ap;
461
    CPUState *env;
462

    
463
    va_start(ap, fmt);
464
    fprintf(stderr, "qemu: hardware error: ");
465
    vfprintf(stderr, fmt, ap);
466
    fprintf(stderr, "\n");
467
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
468
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
469
#ifdef TARGET_I386
470
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
471
#else
472
        cpu_dump_state(env, stderr, fprintf, 0);
473
#endif
474
    }
475
    va_end(ap);
476
    abort();
477
}
478

    
479
/***********************************************************/
480
/* keyboard/mouse */
481

    
482
static QEMUPutKBDEvent *qemu_put_kbd_event;
483
static void *qemu_put_kbd_event_opaque;
484
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
485
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
486

    
487
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
488
{
489
    qemu_put_kbd_event_opaque = opaque;
490
    qemu_put_kbd_event = func;
491
}
492

    
493
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
494
                                                void *opaque, int absolute,
495
                                                const char *name)
496
{
497
    QEMUPutMouseEntry *s, *cursor;
498

    
499
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
500
    if (!s)
501
        return NULL;
502

    
503
    s->qemu_put_mouse_event = func;
504
    s->qemu_put_mouse_event_opaque = opaque;
505
    s->qemu_put_mouse_event_absolute = absolute;
506
    s->qemu_put_mouse_event_name = qemu_strdup(name);
507
    s->next = NULL;
508

    
509
    if (!qemu_put_mouse_event_head) {
510
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
511
        return s;
512
    }
513

    
514
    cursor = qemu_put_mouse_event_head;
515
    while (cursor->next != NULL)
516
        cursor = cursor->next;
517

    
518
    cursor->next = s;
519
    qemu_put_mouse_event_current = s;
520

    
521
    return s;
522
}
523

    
524
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
525
{
526
    QEMUPutMouseEntry *prev = NULL, *cursor;
527

    
528
    if (!qemu_put_mouse_event_head || entry == NULL)
529
        return;
530

    
531
    cursor = qemu_put_mouse_event_head;
532
    while (cursor != NULL && cursor != entry) {
533
        prev = cursor;
534
        cursor = cursor->next;
535
    }
536

    
537
    if (cursor == NULL) // does not exist or list empty
538
        return;
539
    else if (prev == NULL) { // entry is head
540
        qemu_put_mouse_event_head = cursor->next;
541
        if (qemu_put_mouse_event_current == entry)
542
            qemu_put_mouse_event_current = cursor->next;
543
        qemu_free(entry->qemu_put_mouse_event_name);
544
        qemu_free(entry);
545
        return;
546
    }
547

    
548
    prev->next = entry->next;
549

    
550
    if (qemu_put_mouse_event_current == entry)
551
        qemu_put_mouse_event_current = prev;
552

    
553
    qemu_free(entry->qemu_put_mouse_event_name);
554
    qemu_free(entry);
555
}
556

    
557
void kbd_put_keycode(int keycode)
558
{
559
    if (qemu_put_kbd_event) {
560
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
561
    }
562
}
563

    
564
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
565
{
566
    QEMUPutMouseEvent *mouse_event;
567
    void *mouse_event_opaque;
568
    int width;
569

    
570
    if (!qemu_put_mouse_event_current) {
571
        return;
572
    }
573

    
574
    mouse_event =
575
        qemu_put_mouse_event_current->qemu_put_mouse_event;
576
    mouse_event_opaque =
577
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
578

    
579
    if (mouse_event) {
580
        if (graphic_rotate) {
581
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
582
                width = 0x7fff;
583
            else
584
                width = graphic_width;
585
            mouse_event(mouse_event_opaque,
586
                                 width - dy, dx, dz, buttons_state);
587
        } else
588
            mouse_event(mouse_event_opaque,
589
                                 dx, dy, dz, buttons_state);
590
    }
591
}
592

    
593
int kbd_mouse_is_absolute(void)
594
{
595
    if (!qemu_put_mouse_event_current)
596
        return 0;
597

    
598
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
599
}
600

    
601
void do_info_mice(void)
602
{
603
    QEMUPutMouseEntry *cursor;
604
    int index = 0;
605

    
606
    if (!qemu_put_mouse_event_head) {
607
        term_printf("No mouse devices connected\n");
608
        return;
609
    }
610

    
611
    term_printf("Mouse devices available:\n");
612
    cursor = qemu_put_mouse_event_head;
613
    while (cursor != NULL) {
614
        term_printf("%c Mouse #%d: %s\n",
615
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
616
                    index, cursor->qemu_put_mouse_event_name);
617
        index++;
618
        cursor = cursor->next;
619
    }
620
}
621

    
622
void do_mouse_set(int index)
623
{
624
    QEMUPutMouseEntry *cursor;
625
    int i = 0;
626

    
627
    if (!qemu_put_mouse_event_head) {
628
        term_printf("No mouse devices connected\n");
629
        return;
630
    }
631

    
632
    cursor = qemu_put_mouse_event_head;
633
    while (cursor != NULL && index != i) {
634
        i++;
635
        cursor = cursor->next;
636
    }
637

    
638
    if (cursor != NULL)
639
        qemu_put_mouse_event_current = cursor;
640
    else
641
        term_printf("Mouse at given index not found\n");
642
}
643

    
644
/* compute with 96 bit intermediate result: (a*b)/c */
645
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
646
{
647
    union {
648
        uint64_t ll;
649
        struct {
650
#ifdef WORDS_BIGENDIAN
651
            uint32_t high, low;
652
#else
653
            uint32_t low, high;
654
#endif
655
        } l;
656
    } u, res;
657
    uint64_t rl, rh;
658

    
659
    u.ll = a;
660
    rl = (uint64_t)u.l.low * (uint64_t)b;
661
    rh = (uint64_t)u.l.high * (uint64_t)b;
662
    rh += (rl >> 32);
663
    res.l.high = rh / c;
664
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
665
    return res.ll;
666
}
667

    
668
/***********************************************************/
669
/* real time host monotonic timer */
670

    
671
#define QEMU_TIMER_BASE 1000000000LL
672

    
673
#ifdef WIN32
674

    
675
static int64_t clock_freq;
676

    
677
static void init_get_clock(void)
678
{
679
    LARGE_INTEGER freq;
680
    int ret;
681
    ret = QueryPerformanceFrequency(&freq);
682
    if (ret == 0) {
683
        fprintf(stderr, "Could not calibrate ticks\n");
684
        exit(1);
685
    }
686
    clock_freq = freq.QuadPart;
687
}
688

    
689
static int64_t get_clock(void)
690
{
691
    LARGE_INTEGER ti;
692
    QueryPerformanceCounter(&ti);
693
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
694
}
695

    
696
#else
697

    
698
static int use_rt_clock;
699

    
700
static void init_get_clock(void)
701
{
702
    use_rt_clock = 0;
703
#if defined(__linux__)
704
    {
705
        struct timespec ts;
706
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
707
            use_rt_clock = 1;
708
        }
709
    }
710
#endif
711
}
712

    
713
static int64_t get_clock(void)
714
{
715
#if defined(__linux__)
716
    if (use_rt_clock) {
717
        struct timespec ts;
718
        clock_gettime(CLOCK_MONOTONIC, &ts);
719
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
720
    } else
721
#endif
722
    {
723
        /* XXX: using gettimeofday leads to problems if the date
724
           changes, so it should be avoided. */
725
        struct timeval tv;
726
        gettimeofday(&tv, NULL);
727
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
728
    }
729
}
730

    
731
#endif
732

    
733
/***********************************************************/
734
/* guest cycle counter */
735

    
736
static int64_t cpu_ticks_prev;
737
static int64_t cpu_ticks_offset;
738
static int64_t cpu_clock_offset;
739
static int cpu_ticks_enabled;
740

    
741
/* return the host CPU cycle counter and handle stop/restart */
742
int64_t cpu_get_ticks(void)
743
{
744
    if (!cpu_ticks_enabled) {
745
        return cpu_ticks_offset;
746
    } else {
747
        int64_t ticks;
748
        ticks = cpu_get_real_ticks();
749
        if (cpu_ticks_prev > ticks) {
750
            /* Note: non increasing ticks may happen if the host uses
751
               software suspend */
752
            cpu_ticks_offset += cpu_ticks_prev - ticks;
753
        }
754
        cpu_ticks_prev = ticks;
755
        return ticks + cpu_ticks_offset;
756
    }
757
}
758

    
759
/* return the host CPU monotonic timer and handle stop/restart */
760
static int64_t cpu_get_clock(void)
761
{
762
    int64_t ti;
763
    if (!cpu_ticks_enabled) {
764
        return cpu_clock_offset;
765
    } else {
766
        ti = get_clock();
767
        return ti + cpu_clock_offset;
768
    }
769
}
770

    
771
/* enable cpu_get_ticks() */
772
void cpu_enable_ticks(void)
773
{
774
    if (!cpu_ticks_enabled) {
775
        cpu_ticks_offset -= cpu_get_real_ticks();
776
        cpu_clock_offset -= get_clock();
777
        cpu_ticks_enabled = 1;
778
    }
779
}
780

    
781
/* disable cpu_get_ticks() : the clock is stopped. You must not call
782
   cpu_get_ticks() after that.  */
783
void cpu_disable_ticks(void)
784
{
785
    if (cpu_ticks_enabled) {
786
        cpu_ticks_offset = cpu_get_ticks();
787
        cpu_clock_offset = cpu_get_clock();
788
        cpu_ticks_enabled = 0;
789
    }
790
}
791

    
792
/***********************************************************/
793
/* timers */
794

    
795
#define QEMU_TIMER_REALTIME 0
796
#define QEMU_TIMER_VIRTUAL  1
797

    
798
struct QEMUClock {
799
    int type;
800
    /* XXX: add frequency */
801
};
802

    
803
struct QEMUTimer {
804
    QEMUClock *clock;
805
    int64_t expire_time;
806
    QEMUTimerCB *cb;
807
    void *opaque;
808
    struct QEMUTimer *next;
809
};
810

    
811
struct qemu_alarm_timer {
812
    char const *name;
813
    unsigned int flags;
814

    
815
    int (*start)(struct qemu_alarm_timer *t);
816
    void (*stop)(struct qemu_alarm_timer *t);
817
    void (*rearm)(struct qemu_alarm_timer *t);
818
    void *priv;
819
};
820

    
821
#define ALARM_FLAG_DYNTICKS  0x1
822

    
823
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
824
{
825
    return t->flags & ALARM_FLAG_DYNTICKS;
826
}
827

    
828
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
829
{
830
    if (!alarm_has_dynticks(t))
831
        return;
832

    
833
    t->rearm(t);
834
}
835

    
836
/* TODO: MIN_TIMER_REARM_US should be optimized */
837
#define MIN_TIMER_REARM_US 250
838

    
839
static struct qemu_alarm_timer *alarm_timer;
840

    
841
#ifdef _WIN32
842

    
843
struct qemu_alarm_win32 {
844
    MMRESULT timerId;
845
    HANDLE host_alarm;
846
    unsigned int period;
847
} alarm_win32_data = {0, NULL, -1};
848

    
849
static int win32_start_timer(struct qemu_alarm_timer *t);
850
static void win32_stop_timer(struct qemu_alarm_timer *t);
851
static void win32_rearm_timer(struct qemu_alarm_timer *t);
852

    
853
#else
854

    
855
static int unix_start_timer(struct qemu_alarm_timer *t);
856
static void unix_stop_timer(struct qemu_alarm_timer *t);
857

    
858
#ifdef __linux__
859

    
860
static int dynticks_start_timer(struct qemu_alarm_timer *t);
861
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
862
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
863

    
864
static int hpet_start_timer(struct qemu_alarm_timer *t);
865
static void hpet_stop_timer(struct qemu_alarm_timer *t);
866

    
867
static int rtc_start_timer(struct qemu_alarm_timer *t);
868
static void rtc_stop_timer(struct qemu_alarm_timer *t);
869

    
870
#endif /* __linux__ */
871

    
872
#endif /* _WIN32 */
873

    
874
static struct qemu_alarm_timer alarm_timers[] = {
875
#ifndef _WIN32
876
#ifdef __linux__
877
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
878
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
879
    /* HPET - if available - is preferred */
880
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
881
    /* ...otherwise try RTC */
882
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
883
#endif
884
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
885
#else
886
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
887
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
888
    {"win32", 0, win32_start_timer,
889
     win32_stop_timer, NULL, &alarm_win32_data},
890
#endif
891
    {NULL, }
892
};
893

    
894
static void show_available_alarms()
895
{
896
    int i;
897

    
898
    printf("Available alarm timers, in order of precedence:\n");
899
    for (i = 0; alarm_timers[i].name; i++)
900
        printf("%s\n", alarm_timers[i].name);
901
}
902

    
903
static void configure_alarms(char const *opt)
904
{
905
    int i;
906
    int cur = 0;
907
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
908
    char *arg;
909
    char *name;
910

    
911
    if (!strcmp(opt, "help")) {
912
        show_available_alarms();
913
        exit(0);
914
    }
915

    
916
    arg = strdup(opt);
917

    
918
    /* Reorder the array */
919
    name = strtok(arg, ",");
920
    while (name) {
921
        struct qemu_alarm_timer tmp;
922

    
923
        for (i = 0; i < count && alarm_timers[i].name; i++) {
924
            if (!strcmp(alarm_timers[i].name, name))
925
                break;
926
        }
927

    
928
        if (i == count) {
929
            fprintf(stderr, "Unknown clock %s\n", name);
930
            goto next;
931
        }
932

    
933
        if (i < cur)
934
            /* Ignore */
935
            goto next;
936

    
937
        /* Swap */
938
        tmp = alarm_timers[i];
939
        alarm_timers[i] = alarm_timers[cur];
940
        alarm_timers[cur] = tmp;
941

    
942
        cur++;
943
next:
944
        name = strtok(NULL, ",");
945
    }
946

    
947
    free(arg);
948

    
949
    if (cur) {
950
        /* Disable remaining timers */
951
        for (i = cur; i < count; i++)
952
            alarm_timers[i].name = NULL;
953
    }
954

    
955
    /* debug */
956
    show_available_alarms();
957
}
958

    
959
QEMUClock *rt_clock;
960
QEMUClock *vm_clock;
961

    
962
static QEMUTimer *active_timers[2];
963

    
964
static QEMUClock *qemu_new_clock(int type)
965
{
966
    QEMUClock *clock;
967
    clock = qemu_mallocz(sizeof(QEMUClock));
968
    if (!clock)
969
        return NULL;
970
    clock->type = type;
971
    return clock;
972
}
973

    
974
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
975
{
976
    QEMUTimer *ts;
977

    
978
    ts = qemu_mallocz(sizeof(QEMUTimer));
979
    ts->clock = clock;
980
    ts->cb = cb;
981
    ts->opaque = opaque;
982
    return ts;
983
}
984

    
985
void qemu_free_timer(QEMUTimer *ts)
986
{
987
    qemu_free(ts);
988
}
989

    
990
/* stop a timer, but do not dealloc it */
991
void qemu_del_timer(QEMUTimer *ts)
992
{
993
    QEMUTimer **pt, *t;
994

    
995
    /* NOTE: this code must be signal safe because
996
       qemu_timer_expired() can be called from a signal. */
997
    pt = &active_timers[ts->clock->type];
998
    for(;;) {
999
        t = *pt;
1000
        if (!t)
1001
            break;
1002
        if (t == ts) {
1003
            *pt = t->next;
1004
            break;
1005
        }
1006
        pt = &t->next;
1007
    }
1008
}
1009

    
1010
/* modify the current timer so that it will be fired when current_time
1011
   >= expire_time. The corresponding callback will be called. */
1012
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1013
{
1014
    QEMUTimer **pt, *t;
1015

    
1016
    qemu_del_timer(ts);
1017

    
1018
    /* add the timer in the sorted list */
1019
    /* NOTE: this code must be signal safe because
1020
       qemu_timer_expired() can be called from a signal. */
1021
    pt = &active_timers[ts->clock->type];
1022
    for(;;) {
1023
        t = *pt;
1024
        if (!t)
1025
            break;
1026
        if (t->expire_time > expire_time)
1027
            break;
1028
        pt = &t->next;
1029
    }
1030
    ts->expire_time = expire_time;
1031
    ts->next = *pt;
1032
    *pt = ts;
1033
}
1034

    
1035
int qemu_timer_pending(QEMUTimer *ts)
1036
{
1037
    QEMUTimer *t;
1038
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1039
        if (t == ts)
1040
            return 1;
1041
    }
1042
    return 0;
1043
}
1044

    
1045
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1046
{
1047
    if (!timer_head)
1048
        return 0;
1049
    return (timer_head->expire_time <= current_time);
1050
}
1051

    
1052
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1053
{
1054
    QEMUTimer *ts;
1055

    
1056
    for(;;) {
1057
        ts = *ptimer_head;
1058
        if (!ts || ts->expire_time > current_time)
1059
            break;
1060
        /* remove timer from the list before calling the callback */
1061
        *ptimer_head = ts->next;
1062
        ts->next = NULL;
1063

    
1064
        /* run the callback (the timer list can be modified) */
1065
        ts->cb(ts->opaque);
1066
    }
1067
    qemu_rearm_alarm_timer(alarm_timer);
1068
}
1069

    
1070
int64_t qemu_get_clock(QEMUClock *clock)
1071
{
1072
    switch(clock->type) {
1073
    case QEMU_TIMER_REALTIME:
1074
        return get_clock() / 1000000;
1075
    default:
1076
    case QEMU_TIMER_VIRTUAL:
1077
        return cpu_get_clock();
1078
    }
1079
}
1080

    
1081
static void init_timers(void)
1082
{
1083
    init_get_clock();
1084
    ticks_per_sec = QEMU_TIMER_BASE;
1085
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1086
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1087
}
1088

    
1089
/* save a timer */
1090
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1091
{
1092
    uint64_t expire_time;
1093

    
1094
    if (qemu_timer_pending(ts)) {
1095
        expire_time = ts->expire_time;
1096
    } else {
1097
        expire_time = -1;
1098
    }
1099
    qemu_put_be64(f, expire_time);
1100
}
1101

    
1102
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1103
{
1104
    uint64_t expire_time;
1105

    
1106
    expire_time = qemu_get_be64(f);
1107
    if (expire_time != -1) {
1108
        qemu_mod_timer(ts, expire_time);
1109
    } else {
1110
        qemu_del_timer(ts);
1111
    }
1112
}
1113

    
1114
static void timer_save(QEMUFile *f, void *opaque)
1115
{
1116
    if (cpu_ticks_enabled) {
1117
        hw_error("cannot save state if virtual timers are running");
1118
    }
1119
    qemu_put_be64s(f, &cpu_ticks_offset);
1120
    qemu_put_be64s(f, &ticks_per_sec);
1121
    qemu_put_be64s(f, &cpu_clock_offset);
1122
}
1123

    
1124
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1125
{
1126
    if (version_id != 1 && version_id != 2)
1127
        return -EINVAL;
1128
    if (cpu_ticks_enabled) {
1129
        return -EINVAL;
1130
    }
1131
    qemu_get_be64s(f, &cpu_ticks_offset);
1132
    qemu_get_be64s(f, &ticks_per_sec);
1133
    if (version_id == 2) {
1134
        qemu_get_be64s(f, &cpu_clock_offset);
1135
    }
1136
    return 0;
1137
}
1138

    
1139
#ifdef _WIN32
1140
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1141
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1142
#else
1143
static void host_alarm_handler(int host_signum)
1144
#endif
1145
{
1146
#if 0
1147
#define DISP_FREQ 1000
1148
    {
1149
        static int64_t delta_min = INT64_MAX;
1150
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1151
        static int count;
1152
        ti = qemu_get_clock(vm_clock);
1153
        if (last_clock != 0) {
1154
            delta = ti - last_clock;
1155
            if (delta < delta_min)
1156
                delta_min = delta;
1157
            if (delta > delta_max)
1158
                delta_max = delta;
1159
            delta_cum += delta;
1160
            if (++count == DISP_FREQ) {
1161
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1162
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1163
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1164
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1165
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1166
                count = 0;
1167
                delta_min = INT64_MAX;
1168
                delta_max = 0;
1169
                delta_cum = 0;
1170
            }
1171
        }
1172
        last_clock = ti;
1173
    }
1174
#endif
1175
    if (alarm_has_dynticks(alarm_timer) ||
1176
        qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1177
                           qemu_get_clock(vm_clock)) ||
1178
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1179
                           qemu_get_clock(rt_clock))) {
1180
#ifdef _WIN32
1181
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1182
        SetEvent(data->host_alarm);
1183
#endif
1184
        CPUState *env = cpu_single_env;
1185
        if (env) {
1186
            /* stop the currently executing cpu because a timer occured */
1187
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1188
#ifdef USE_KQEMU
1189
            if (env->kqemu_enabled) {
1190
                kqemu_cpu_interrupt(env);
1191
            }
1192
#endif
1193
        }
1194
    }
1195
}
1196

    
1197
static uint64_t qemu_next_deadline(void)
1198
{
1199
    int64_t nearest_delta_us = INT64_MAX;
1200
    int64_t vmdelta_us;
1201

    
1202
    if (active_timers[QEMU_TIMER_REALTIME])
1203
        nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1204
                            qemu_get_clock(rt_clock))*1000;
1205

    
1206
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1207
        /* round up */
1208
        vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1209
                      qemu_get_clock(vm_clock)+999)/1000;
1210
        if (vmdelta_us < nearest_delta_us)
1211
            nearest_delta_us = vmdelta_us;
1212
    }
1213

    
1214
    /* Avoid arming the timer to negative, zero, or too low values */
1215
    if (nearest_delta_us <= MIN_TIMER_REARM_US)
1216
        nearest_delta_us = MIN_TIMER_REARM_US;
1217

    
1218
    return nearest_delta_us;
1219
}
1220

    
1221
#ifndef _WIN32
1222

    
1223
#if defined(__linux__)
1224

    
1225
#define RTC_FREQ 1024
1226

    
1227
static void enable_sigio_timer(int fd)
1228
{
1229
    struct sigaction act;
1230

    
1231
    /* timer signal */
1232
    sigfillset(&act.sa_mask);
1233
    act.sa_flags = 0;
1234
    act.sa_handler = host_alarm_handler;
1235

    
1236
    sigaction(SIGIO, &act, NULL);
1237
    fcntl(fd, F_SETFL, O_ASYNC);
1238
    fcntl(fd, F_SETOWN, getpid());
1239
}
1240

    
1241
static int hpet_start_timer(struct qemu_alarm_timer *t)
1242
{
1243
    struct hpet_info info;
1244
    int r, fd;
1245

    
1246
    fd = open("/dev/hpet", O_RDONLY);
1247
    if (fd < 0)
1248
        return -1;
1249

    
1250
    /* Set frequency */
1251
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1252
    if (r < 0) {
1253
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1254
                "error, but for better emulation accuracy type:\n"
1255
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1256
        goto fail;
1257
    }
1258

    
1259
    /* Check capabilities */
1260
    r = ioctl(fd, HPET_INFO, &info);
1261
    if (r < 0)
1262
        goto fail;
1263

    
1264
    /* Enable periodic mode */
1265
    r = ioctl(fd, HPET_EPI, 0);
1266
    if (info.hi_flags && (r < 0))
1267
        goto fail;
1268

    
1269
    /* Enable interrupt */
1270
    r = ioctl(fd, HPET_IE_ON, 0);
1271
    if (r < 0)
1272
        goto fail;
1273

    
1274
    enable_sigio_timer(fd);
1275
    t->priv = (void *)(long)fd;
1276

    
1277
    return 0;
1278
fail:
1279
    close(fd);
1280
    return -1;
1281
}
1282

    
1283
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1284
{
1285
    int fd = (long)t->priv;
1286

    
1287
    close(fd);
1288
}
1289

    
1290
static int rtc_start_timer(struct qemu_alarm_timer *t)
1291
{
1292
    int rtc_fd;
1293

    
1294
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1295
    if (rtc_fd < 0)
1296
        return -1;
1297
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1298
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1299
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1300
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1301
        goto fail;
1302
    }
1303
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1304
    fail:
1305
        close(rtc_fd);
1306
        return -1;
1307
    }
1308

    
1309
    enable_sigio_timer(rtc_fd);
1310

    
1311
    t->priv = (void *)(long)rtc_fd;
1312

    
1313
    return 0;
1314
}
1315

    
1316
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1317
{
1318
    int rtc_fd = (long)t->priv;
1319

    
1320
    close(rtc_fd);
1321
}
1322

    
1323
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1324
{
1325
    struct sigevent ev;
1326
    timer_t host_timer;
1327
    struct sigaction act;
1328

    
1329
    sigfillset(&act.sa_mask);
1330
    act.sa_flags = 0;
1331
    act.sa_handler = host_alarm_handler;
1332

    
1333
    sigaction(SIGALRM, &act, NULL);
1334

    
1335
    ev.sigev_value.sival_int = 0;
1336
    ev.sigev_notify = SIGEV_SIGNAL;
1337
    ev.sigev_signo = SIGALRM;
1338

    
1339
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1340
        perror("timer_create");
1341

    
1342
        /* disable dynticks */
1343
        fprintf(stderr, "Dynamic Ticks disabled\n");
1344

    
1345
        return -1;
1346
    }
1347

    
1348
    t->priv = (void *)host_timer;
1349

    
1350
    return 0;
1351
}
1352

    
1353
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1354
{
1355
    timer_t host_timer = (timer_t)t->priv;
1356

    
1357
    timer_delete(host_timer);
1358
}
1359

    
1360
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1361
{
1362
    timer_t host_timer = (timer_t)t->priv;
1363
    struct itimerspec timeout;
1364
    int64_t nearest_delta_us = INT64_MAX;
1365
    int64_t current_us;
1366

    
1367
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1368
                !active_timers[QEMU_TIMER_VIRTUAL])
1369
            return;
1370

    
1371
    nearest_delta_us = qemu_next_deadline();
1372

    
1373
    /* check whether a timer is already running */
1374
    if (timer_gettime(host_timer, &timeout)) {
1375
        perror("gettime");
1376
        fprintf(stderr, "Internal timer error: aborting\n");
1377
        exit(1);
1378
    }
1379
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1380
    if (current_us && current_us <= nearest_delta_us)
1381
        return;
1382

    
1383
    timeout.it_interval.tv_sec = 0;
1384
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1385
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1386
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1387
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1388
        perror("settime");
1389
        fprintf(stderr, "Internal timer error: aborting\n");
1390
        exit(1);
1391
    }
1392
}
1393

    
1394
#endif /* defined(__linux__) */
1395

    
1396
static int unix_start_timer(struct qemu_alarm_timer *t)
1397
{
1398
    struct sigaction act;
1399
    struct itimerval itv;
1400
    int err;
1401

    
1402
    /* timer signal */
1403
    sigfillset(&act.sa_mask);
1404
    act.sa_flags = 0;
1405
    act.sa_handler = host_alarm_handler;
1406

    
1407
    sigaction(SIGALRM, &act, NULL);
1408

    
1409
    itv.it_interval.tv_sec = 0;
1410
    /* for i386 kernel 2.6 to get 1 ms */
1411
    itv.it_interval.tv_usec = 999;
1412
    itv.it_value.tv_sec = 0;
1413
    itv.it_value.tv_usec = 10 * 1000;
1414

    
1415
    err = setitimer(ITIMER_REAL, &itv, NULL);
1416
    if (err)
1417
        return -1;
1418

    
1419
    return 0;
1420
}
1421

    
1422
static void unix_stop_timer(struct qemu_alarm_timer *t)
1423
{
1424
    struct itimerval itv;
1425

    
1426
    memset(&itv, 0, sizeof(itv));
1427
    setitimer(ITIMER_REAL, &itv, NULL);
1428
}
1429

    
1430
#endif /* !defined(_WIN32) */
1431

    
1432
#ifdef _WIN32
1433

    
1434
static int win32_start_timer(struct qemu_alarm_timer *t)
1435
{
1436
    TIMECAPS tc;
1437
    struct qemu_alarm_win32 *data = t->priv;
1438
    UINT flags;
1439

    
1440
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1441
    if (!data->host_alarm) {
1442
        perror("Failed CreateEvent");
1443
        return -1;
1444
    }
1445

    
1446
    memset(&tc, 0, sizeof(tc));
1447
    timeGetDevCaps(&tc, sizeof(tc));
1448

    
1449
    if (data->period < tc.wPeriodMin)
1450
        data->period = tc.wPeriodMin;
1451

    
1452
    timeBeginPeriod(data->period);
1453

    
1454
    flags = TIME_CALLBACK_FUNCTION;
1455
    if (alarm_has_dynticks(t))
1456
        flags |= TIME_ONESHOT;
1457
    else
1458
        flags |= TIME_PERIODIC;
1459

    
1460
    data->timerId = timeSetEvent(1,         // interval (ms)
1461
                        data->period,       // resolution
1462
                        host_alarm_handler, // function
1463
                        (DWORD)t,           // parameter
1464
                        flags);
1465

    
1466
    if (!data->timerId) {
1467
        perror("Failed to initialize win32 alarm timer");
1468

    
1469
        timeEndPeriod(data->period);
1470
        CloseHandle(data->host_alarm);
1471
        return -1;
1472
    }
1473

    
1474
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1475

    
1476
    return 0;
1477
}
1478

    
1479
static void win32_stop_timer(struct qemu_alarm_timer *t)
1480
{
1481
    struct qemu_alarm_win32 *data = t->priv;
1482

    
1483
    timeKillEvent(data->timerId);
1484
    timeEndPeriod(data->period);
1485

    
1486
    CloseHandle(data->host_alarm);
1487
}
1488

    
1489
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1490
{
1491
    struct qemu_alarm_win32 *data = t->priv;
1492
    uint64_t nearest_delta_us;
1493

    
1494
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1495
                !active_timers[QEMU_TIMER_VIRTUAL])
1496
            return;
1497

    
1498
    nearest_delta_us = qemu_next_deadline();
1499
    nearest_delta_us /= 1000;
1500

    
1501
    timeKillEvent(data->timerId);
1502

    
1503
    data->timerId = timeSetEvent(1,
1504
                        data->period,
1505
                        host_alarm_handler,
1506
                        (DWORD)t,
1507
                        TIME_ONESHOT | TIME_PERIODIC);
1508

    
1509
    if (!data->timerId) {
1510
        perror("Failed to re-arm win32 alarm timer");
1511

    
1512
        timeEndPeriod(data->period);
1513
        CloseHandle(data->host_alarm);
1514
        exit(1);
1515
    }
1516
}
1517

    
1518
#endif /* _WIN32 */
1519

    
1520
static void init_timer_alarm(void)
1521
{
1522
    struct qemu_alarm_timer *t;
1523
    int i, err = -1;
1524

    
1525
    for (i = 0; alarm_timers[i].name; i++) {
1526
        t = &alarm_timers[i];
1527

    
1528
        err = t->start(t);
1529
        if (!err)
1530
            break;
1531
    }
1532

    
1533
    if (err) {
1534
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1535
        fprintf(stderr, "Terminating\n");
1536
        exit(1);
1537
    }
1538

    
1539
    alarm_timer = t;
1540
}
1541

    
1542
static void quit_timers(void)
1543
{
1544
    alarm_timer->stop(alarm_timer);
1545
    alarm_timer = NULL;
1546
}
1547

    
1548
/***********************************************************/
1549
/* character device */
1550

    
1551
static void qemu_chr_event(CharDriverState *s, int event)
1552
{
1553
    if (!s->chr_event)
1554
        return;
1555
    s->chr_event(s->handler_opaque, event);
1556
}
1557

    
1558
static void qemu_chr_reset_bh(void *opaque)
1559
{
1560
    CharDriverState *s = opaque;
1561
    qemu_chr_event(s, CHR_EVENT_RESET);
1562
    qemu_bh_delete(s->bh);
1563
    s->bh = NULL;
1564
}
1565

    
1566
void qemu_chr_reset(CharDriverState *s)
1567
{
1568
    if (s->bh == NULL) {
1569
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1570
        qemu_bh_schedule(s->bh);
1571
    }
1572
}
1573

    
1574
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1575
{
1576
    return s->chr_write(s, buf, len);
1577
}
1578

    
1579
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1580
{
1581
    if (!s->chr_ioctl)
1582
        return -ENOTSUP;
1583
    return s->chr_ioctl(s, cmd, arg);
1584
}
1585

    
1586
int qemu_chr_can_read(CharDriverState *s)
1587
{
1588
    if (!s->chr_can_read)
1589
        return 0;
1590
    return s->chr_can_read(s->handler_opaque);
1591
}
1592

    
1593
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1594
{
1595
    s->chr_read(s->handler_opaque, buf, len);
1596
}
1597

    
1598

    
1599
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1600
{
1601
    char buf[4096];
1602
    va_list ap;
1603
    va_start(ap, fmt);
1604
    vsnprintf(buf, sizeof(buf), fmt, ap);
1605
    qemu_chr_write(s, buf, strlen(buf));
1606
    va_end(ap);
1607
}
1608

    
1609
void qemu_chr_send_event(CharDriverState *s, int event)
1610
{
1611
    if (s->chr_send_event)
1612
        s->chr_send_event(s, event);
1613
}
1614

    
1615
void qemu_chr_add_handlers(CharDriverState *s,
1616
                           IOCanRWHandler *fd_can_read,
1617
                           IOReadHandler *fd_read,
1618
                           IOEventHandler *fd_event,
1619
                           void *opaque)
1620
{
1621
    s->chr_can_read = fd_can_read;
1622
    s->chr_read = fd_read;
1623
    s->chr_event = fd_event;
1624
    s->handler_opaque = opaque;
1625
    if (s->chr_update_read_handler)
1626
        s->chr_update_read_handler(s);
1627
}
1628

    
1629
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1630
{
1631
    return len;
1632
}
1633

    
1634
static CharDriverState *qemu_chr_open_null(void)
1635
{
1636
    CharDriverState *chr;
1637

    
1638
    chr = qemu_mallocz(sizeof(CharDriverState));
1639
    if (!chr)
1640
        return NULL;
1641
    chr->chr_write = null_chr_write;
1642
    return chr;
1643
}
1644

    
1645
/* MUX driver for serial I/O splitting */
1646
static int term_timestamps;
1647
static int64_t term_timestamps_start;
1648
#define MAX_MUX 4
1649
typedef struct {
1650
    IOCanRWHandler *chr_can_read[MAX_MUX];
1651
    IOReadHandler *chr_read[MAX_MUX];
1652
    IOEventHandler *chr_event[MAX_MUX];
1653
    void *ext_opaque[MAX_MUX];
1654
    CharDriverState *drv;
1655
    int mux_cnt;
1656
    int term_got_escape;
1657
    int max_size;
1658
} MuxDriver;
1659

    
1660

    
1661
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1662
{
1663
    MuxDriver *d = chr->opaque;
1664
    int ret;
1665
    if (!term_timestamps) {
1666
        ret = d->drv->chr_write(d->drv, buf, len);
1667
    } else {
1668
        int i;
1669

    
1670
        ret = 0;
1671
        for(i = 0; i < len; i++) {
1672
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1673
            if (buf[i] == '\n') {
1674
                char buf1[64];
1675
                int64_t ti;
1676
                int secs;
1677

    
1678
                ti = get_clock();
1679
                if (term_timestamps_start == -1)
1680
                    term_timestamps_start = ti;
1681
                ti -= term_timestamps_start;
1682
                secs = ti / 1000000000;
1683
                snprintf(buf1, sizeof(buf1),
1684
                         "[%02d:%02d:%02d.%03d] ",
1685
                         secs / 3600,
1686
                         (secs / 60) % 60,
1687
                         secs % 60,
1688
                         (int)((ti / 1000000) % 1000));
1689
                d->drv->chr_write(d->drv, buf1, strlen(buf1));
1690
            }
1691
        }
1692
    }
1693
    return ret;
1694
}
1695

    
1696
static char *mux_help[] = {
1697
    "% h    print this help\n\r",
1698
    "% x    exit emulator\n\r",
1699
    "% s    save disk data back to file (if -snapshot)\n\r",
1700
    "% t    toggle console timestamps\n\r"
1701
    "% b    send break (magic sysrq)\n\r",
1702
    "% c    switch between console and monitor\n\r",
1703
    "% %  sends %\n\r",
1704
    NULL
1705
};
1706

    
1707
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1708
static void mux_print_help(CharDriverState *chr)
1709
{
1710
    int i, j;
1711
    char ebuf[15] = "Escape-Char";
1712
    char cbuf[50] = "\n\r";
1713

    
1714
    if (term_escape_char > 0 && term_escape_char < 26) {
1715
        sprintf(cbuf,"\n\r");
1716
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1717
    } else {
1718
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1719
    }
1720
    chr->chr_write(chr, cbuf, strlen(cbuf));
1721
    for (i = 0; mux_help[i] != NULL; i++) {
1722
        for (j=0; mux_help[i][j] != '\0'; j++) {
1723
            if (mux_help[i][j] == '%')
1724
                chr->chr_write(chr, ebuf, strlen(ebuf));
1725
            else
1726
                chr->chr_write(chr, &mux_help[i][j], 1);
1727
        }
1728
    }
1729
}
1730

    
1731
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1732
{
1733
    if (d->term_got_escape) {
1734
        d->term_got_escape = 0;
1735
        if (ch == term_escape_char)
1736
            goto send_char;
1737
        switch(ch) {
1738
        case '?':
1739
        case 'h':
1740
            mux_print_help(chr);
1741
            break;
1742
        case 'x':
1743
            {
1744
                 char *term =  "QEMU: Terminated\n\r";
1745
                 chr->chr_write(chr,term,strlen(term));
1746
                 exit(0);
1747
                 break;
1748
            }
1749
        case 's':
1750
            {
1751
                int i;
1752
                for (i = 0; i < MAX_DISKS; i++) {
1753
                    if (bs_table[i])
1754
                        bdrv_commit(bs_table[i]);
1755
                }
1756
                if (mtd_bdrv)
1757
                    bdrv_commit(mtd_bdrv);
1758
            }
1759
            break;
1760
        case 'b':
1761
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1762
            break;
1763
        case 'c':
1764
            /* Switch to the next registered device */
1765
            chr->focus++;
1766
            if (chr->focus >= d->mux_cnt)
1767
                chr->focus = 0;
1768
            break;
1769
       case 't':
1770
           term_timestamps = !term_timestamps;
1771
           term_timestamps_start = -1;
1772
           break;
1773
        }
1774
    } else if (ch == term_escape_char) {
1775
        d->term_got_escape = 1;
1776
    } else {
1777
    send_char:
1778
        return 1;
1779
    }
1780
    return 0;
1781
}
1782

    
1783
static int mux_chr_can_read(void *opaque)
1784
{
1785
    CharDriverState *chr = opaque;
1786
    MuxDriver *d = chr->opaque;
1787
    if (d->chr_can_read[chr->focus])
1788
       return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1789
    return 0;
1790
}
1791

    
1792
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1793
{
1794
    CharDriverState *chr = opaque;
1795
    MuxDriver *d = chr->opaque;
1796
    int i;
1797
    for(i = 0; i < size; i++)
1798
        if (mux_proc_byte(chr, d, buf[i]))
1799
            d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1800
}
1801

    
1802
static void mux_chr_event(void *opaque, int event)
1803
{
1804
    CharDriverState *chr = opaque;
1805
    MuxDriver *d = chr->opaque;
1806
    int i;
1807

    
1808
    /* Send the event to all registered listeners */
1809
    for (i = 0; i < d->mux_cnt; i++)
1810
        if (d->chr_event[i])
1811
            d->chr_event[i](d->ext_opaque[i], event);
1812
}
1813

    
1814
static void mux_chr_update_read_handler(CharDriverState *chr)
1815
{
1816
    MuxDriver *d = chr->opaque;
1817

    
1818
    if (d->mux_cnt >= MAX_MUX) {
1819
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1820
        return;
1821
    }
1822
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1823
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1824
    d->chr_read[d->mux_cnt] = chr->chr_read;
1825
    d->chr_event[d->mux_cnt] = chr->chr_event;
1826
    /* Fix up the real driver with mux routines */
1827
    if (d->mux_cnt == 0) {
1828
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1829
                              mux_chr_event, chr);
1830
    }
1831
    chr->focus = d->mux_cnt;
1832
    d->mux_cnt++;
1833
}
1834

    
1835
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1836
{
1837
    CharDriverState *chr;
1838
    MuxDriver *d;
1839

    
1840
    chr = qemu_mallocz(sizeof(CharDriverState));
1841
    if (!chr)
1842
        return NULL;
1843
    d = qemu_mallocz(sizeof(MuxDriver));
1844
    if (!d) {
1845
        free(chr);
1846
        return NULL;
1847
    }
1848

    
1849
    chr->opaque = d;
1850
    d->drv = drv;
1851
    chr->focus = -1;
1852
    chr->chr_write = mux_chr_write;
1853
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1854
    return chr;
1855
}
1856

    
1857

    
1858
#ifdef _WIN32
1859

    
1860
static void socket_cleanup(void)
1861
{
1862
    WSACleanup();
1863
}
1864

    
1865
static int socket_init(void)
1866
{
1867
    WSADATA Data;
1868
    int ret, err;
1869

    
1870
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1871
    if (ret != 0) {
1872
        err = WSAGetLastError();
1873
        fprintf(stderr, "WSAStartup: %d\n", err);
1874
        return -1;
1875
    }
1876
    atexit(socket_cleanup);
1877
    return 0;
1878
}
1879

    
1880
static int send_all(int fd, const uint8_t *buf, int len1)
1881
{
1882
    int ret, len;
1883

    
1884
    len = len1;
1885
    while (len > 0) {
1886
        ret = send(fd, buf, len, 0);
1887
        if (ret < 0) {
1888
            int errno;
1889
            errno = WSAGetLastError();
1890
            if (errno != WSAEWOULDBLOCK) {
1891
                return -1;
1892
            }
1893
        } else if (ret == 0) {
1894
            break;
1895
        } else {
1896
            buf += ret;
1897
            len -= ret;
1898
        }
1899
    }
1900
    return len1 - len;
1901
}
1902

    
1903
void socket_set_nonblock(int fd)
1904
{
1905
    unsigned long opt = 1;
1906
    ioctlsocket(fd, FIONBIO, &opt);
1907
}
1908

    
1909
#else
1910

    
1911
static int unix_write(int fd, const uint8_t *buf, int len1)
1912
{
1913
    int ret, len;
1914

    
1915
    len = len1;
1916
    while (len > 0) {
1917
        ret = write(fd, buf, len);
1918
        if (ret < 0) {
1919
            if (errno != EINTR && errno != EAGAIN)
1920
                return -1;
1921
        } else if (ret == 0) {
1922
            break;
1923
        } else {
1924
            buf += ret;
1925
            len -= ret;
1926
        }
1927
    }
1928
    return len1 - len;
1929
}
1930

    
1931
static inline int send_all(int fd, const uint8_t *buf, int len1)
1932
{
1933
    return unix_write(fd, buf, len1);
1934
}
1935

    
1936
void socket_set_nonblock(int fd)
1937
{
1938
    fcntl(fd, F_SETFL, O_NONBLOCK);
1939
}
1940
#endif /* !_WIN32 */
1941

    
1942
#ifndef _WIN32
1943

    
1944
typedef struct {
1945
    int fd_in, fd_out;
1946
    int max_size;
1947
} FDCharDriver;
1948

    
1949
#define STDIO_MAX_CLIENTS 1
1950
static int stdio_nb_clients = 0;
1951

    
1952
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1953
{
1954
    FDCharDriver *s = chr->opaque;
1955
    return unix_write(s->fd_out, buf, len);
1956
}
1957

    
1958
static int fd_chr_read_poll(void *opaque)
1959
{
1960
    CharDriverState *chr = opaque;
1961
    FDCharDriver *s = chr->opaque;
1962

    
1963
    s->max_size = qemu_chr_can_read(chr);
1964
    return s->max_size;
1965
}
1966

    
1967
static void fd_chr_read(void *opaque)
1968
{
1969
    CharDriverState *chr = opaque;
1970
    FDCharDriver *s = chr->opaque;
1971
    int size, len;
1972
    uint8_t buf[1024];
1973

    
1974
    len = sizeof(buf);
1975
    if (len > s->max_size)
1976
        len = s->max_size;
1977
    if (len == 0)
1978
        return;
1979
    size = read(s->fd_in, buf, len);
1980
    if (size == 0) {
1981
        /* FD has been closed. Remove it from the active list.  */
1982
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1983
        return;
1984
    }
1985
    if (size > 0) {
1986
        qemu_chr_read(chr, buf, size);
1987
    }
1988
}
1989

    
1990
static void fd_chr_update_read_handler(CharDriverState *chr)
1991
{
1992
    FDCharDriver *s = chr->opaque;
1993

    
1994
    if (s->fd_in >= 0) {
1995
        if (nographic && s->fd_in == 0) {
1996
        } else {
1997
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1998
                                 fd_chr_read, NULL, chr);
1999
        }
2000
    }
2001
}
2002

    
2003
/* open a character device to a unix fd */
2004
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2005
{
2006
    CharDriverState *chr;
2007
    FDCharDriver *s;
2008

    
2009
    chr = qemu_mallocz(sizeof(CharDriverState));
2010
    if (!chr)
2011
        return NULL;
2012
    s = qemu_mallocz(sizeof(FDCharDriver));
2013
    if (!s) {
2014
        free(chr);
2015
        return NULL;
2016
    }
2017
    s->fd_in = fd_in;
2018
    s->fd_out = fd_out;
2019
    chr->opaque = s;
2020
    chr->chr_write = fd_chr_write;
2021
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2022

    
2023
    qemu_chr_reset(chr);
2024

    
2025
    return chr;
2026
}
2027

    
2028
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2029
{
2030
    int fd_out;
2031

    
2032
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2033
    if (fd_out < 0)
2034
        return NULL;
2035
    return qemu_chr_open_fd(-1, fd_out);
2036
}
2037

    
2038
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2039
{
2040
    int fd_in, fd_out;
2041
    char filename_in[256], filename_out[256];
2042

    
2043
    snprintf(filename_in, 256, "%s.in", filename);
2044
    snprintf(filename_out, 256, "%s.out", filename);
2045
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2046
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2047
    if (fd_in < 0 || fd_out < 0) {
2048
        if (fd_in >= 0)
2049
            close(fd_in);
2050
        if (fd_out >= 0)
2051
            close(fd_out);
2052
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2053
        if (fd_in < 0)
2054
            return NULL;
2055
    }
2056
    return qemu_chr_open_fd(fd_in, fd_out);
2057
}
2058

    
2059

    
2060
/* for STDIO, we handle the case where several clients use it
2061
   (nographic mode) */
2062

    
2063
#define TERM_FIFO_MAX_SIZE 1
2064

    
2065
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2066
static int term_fifo_size;
2067

    
2068
static int stdio_read_poll(void *opaque)
2069
{
2070
    CharDriverState *chr = opaque;
2071

    
2072
    /* try to flush the queue if needed */
2073
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2074
        qemu_chr_read(chr, term_fifo, 1);
2075
        term_fifo_size = 0;
2076
    }
2077
    /* see if we can absorb more chars */
2078
    if (term_fifo_size == 0)
2079
        return 1;
2080
    else
2081
        return 0;
2082
}
2083

    
2084
static void stdio_read(void *opaque)
2085
{
2086
    int size;
2087
    uint8_t buf[1];
2088
    CharDriverState *chr = opaque;
2089

    
2090
    size = read(0, buf, 1);
2091
    if (size == 0) {
2092
        /* stdin has been closed. Remove it from the active list.  */
2093
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2094
        return;
2095
    }
2096
    if (size > 0) {
2097
        if (qemu_chr_can_read(chr) > 0) {
2098
            qemu_chr_read(chr, buf, 1);
2099
        } else if (term_fifo_size == 0) {
2100
            term_fifo[term_fifo_size++] = buf[0];
2101
        }
2102
    }
2103
}
2104

    
2105
/* init terminal so that we can grab keys */
2106
static struct termios oldtty;
2107
static int old_fd0_flags;
2108

    
2109
static void term_exit(void)
2110
{
2111
    tcsetattr (0, TCSANOW, &oldtty);
2112
    fcntl(0, F_SETFL, old_fd0_flags);
2113
}
2114

    
2115
static void term_init(void)
2116
{
2117
    struct termios tty;
2118

    
2119
    tcgetattr (0, &tty);
2120
    oldtty = tty;
2121
    old_fd0_flags = fcntl(0, F_GETFL);
2122

    
2123
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2124
                          |INLCR|IGNCR|ICRNL|IXON);
2125
    tty.c_oflag |= OPOST;
2126
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2127
    /* if graphical mode, we allow Ctrl-C handling */
2128
    if (nographic)
2129
        tty.c_lflag &= ~ISIG;
2130
    tty.c_cflag &= ~(CSIZE|PARENB);
2131
    tty.c_cflag |= CS8;
2132
    tty.c_cc[VMIN] = 1;
2133
    tty.c_cc[VTIME] = 0;
2134

    
2135
    tcsetattr (0, TCSANOW, &tty);
2136

    
2137
    atexit(term_exit);
2138

    
2139
    fcntl(0, F_SETFL, O_NONBLOCK);
2140
}
2141

    
2142
static CharDriverState *qemu_chr_open_stdio(void)
2143
{
2144
    CharDriverState *chr;
2145

    
2146
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2147
        return NULL;
2148
    chr = qemu_chr_open_fd(0, 1);
2149
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2150
    stdio_nb_clients++;
2151
    term_init();
2152

    
2153
    return chr;
2154
}
2155

    
2156
#if defined(__linux__) || defined(__sun__)
2157
static CharDriverState *qemu_chr_open_pty(void)
2158
{
2159
    struct termios tty;
2160
    char slave_name[1024];
2161
    int master_fd, slave_fd;
2162

    
2163
#if defined(__linux__)
2164
    /* Not satisfying */
2165
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2166
        return NULL;
2167
    }
2168
#endif
2169

    
2170
    /* Disabling local echo and line-buffered output */
2171
    tcgetattr (master_fd, &tty);
2172
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2173
    tty.c_cc[VMIN] = 1;
2174
    tty.c_cc[VTIME] = 0;
2175
    tcsetattr (master_fd, TCSAFLUSH, &tty);
2176

    
2177
    fprintf(stderr, "char device redirected to %s\n", slave_name);
2178
    return qemu_chr_open_fd(master_fd, master_fd);
2179
}
2180

    
2181
static void tty_serial_init(int fd, int speed,
2182
                            int parity, int data_bits, int stop_bits)
2183
{
2184
    struct termios tty;
2185
    speed_t spd;
2186

    
2187
#if 0
2188
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2189
           speed, parity, data_bits, stop_bits);
2190
#endif
2191
    tcgetattr (fd, &tty);
2192

    
2193
    switch(speed) {
2194
    case 50:
2195
        spd = B50;
2196
        break;
2197
    case 75:
2198
        spd = B75;
2199
        break;
2200
    case 300:
2201
        spd = B300;
2202
        break;
2203
    case 600:
2204
        spd = B600;
2205
        break;
2206
    case 1200:
2207
        spd = B1200;
2208
        break;
2209
    case 2400:
2210
        spd = B2400;
2211
        break;
2212
    case 4800:
2213
        spd = B4800;
2214
        break;
2215
    case 9600:
2216
        spd = B9600;
2217
        break;
2218
    case 19200:
2219
        spd = B19200;
2220
        break;
2221
    case 38400:
2222
        spd = B38400;
2223
        break;
2224
    case 57600:
2225
        spd = B57600;
2226
        break;
2227
    default:
2228
    case 115200:
2229
        spd = B115200;
2230
        break;
2231
    }
2232

    
2233
    cfsetispeed(&tty, spd);
2234
    cfsetospeed(&tty, spd);
2235

    
2236
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2237
                          |INLCR|IGNCR|ICRNL|IXON);
2238
    tty.c_oflag |= OPOST;
2239
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2240
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2241
    switch(data_bits) {
2242
    default:
2243
    case 8:
2244
        tty.c_cflag |= CS8;
2245
        break;
2246
    case 7:
2247
        tty.c_cflag |= CS7;
2248
        break;
2249
    case 6:
2250
        tty.c_cflag |= CS6;
2251
        break;
2252
    case 5:
2253
        tty.c_cflag |= CS5;
2254
        break;
2255
    }
2256
    switch(parity) {
2257
    default:
2258
    case 'N':
2259
        break;
2260
    case 'E':
2261
        tty.c_cflag |= PARENB;
2262
        break;
2263
    case 'O':
2264
        tty.c_cflag |= PARENB | PARODD;
2265
        break;
2266
    }
2267
    if (stop_bits == 2)
2268
        tty.c_cflag |= CSTOPB;
2269

    
2270
    tcsetattr (fd, TCSANOW, &tty);
2271
}
2272

    
2273
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2274
{
2275
    FDCharDriver *s = chr->opaque;
2276

    
2277
    switch(cmd) {
2278
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2279
        {
2280
            QEMUSerialSetParams *ssp = arg;
2281
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2282
                            ssp->data_bits, ssp->stop_bits);
2283
        }
2284
        break;
2285
    case CHR_IOCTL_SERIAL_SET_BREAK:
2286
        {
2287
            int enable = *(int *)arg;
2288
            if (enable)
2289
                tcsendbreak(s->fd_in, 1);
2290
        }
2291
        break;
2292
    default:
2293
        return -ENOTSUP;
2294
    }
2295
    return 0;
2296
}
2297

    
2298
static CharDriverState *qemu_chr_open_tty(const char *filename)
2299
{
2300
    CharDriverState *chr;
2301
    int fd;
2302

    
2303
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2304
    fcntl(fd, F_SETFL, O_NONBLOCK);
2305
    tty_serial_init(fd, 115200, 'N', 8, 1);
2306
    chr = qemu_chr_open_fd(fd, fd);
2307
    if (!chr) {
2308
        close(fd);
2309
        return NULL;
2310
    }
2311
    chr->chr_ioctl = tty_serial_ioctl;
2312
    qemu_chr_reset(chr);
2313
    return chr;
2314
}
2315
#else  /* ! __linux__ && ! __sun__ */
2316
static CharDriverState *qemu_chr_open_pty(void)
2317
{
2318
    return NULL;
2319
}
2320
#endif /* __linux__ || __sun__ */
2321

    
2322
#if defined(__linux__)
2323
typedef struct {
2324
    int fd;
2325
    int mode;
2326
} ParallelCharDriver;
2327

    
2328
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2329
{
2330
    if (s->mode != mode) {
2331
        int m = mode;
2332
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2333
            return 0;
2334
        s->mode = mode;
2335
    }
2336
    return 1;
2337
}
2338

    
2339
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2340
{
2341
    ParallelCharDriver *drv = chr->opaque;
2342
    int fd = drv->fd;
2343
    uint8_t b;
2344

    
2345
    switch(cmd) {
2346
    case CHR_IOCTL_PP_READ_DATA:
2347
        if (ioctl(fd, PPRDATA, &b) < 0)
2348
            return -ENOTSUP;
2349
        *(uint8_t *)arg = b;
2350
        break;
2351
    case CHR_IOCTL_PP_WRITE_DATA:
2352
        b = *(uint8_t *)arg;
2353
        if (ioctl(fd, PPWDATA, &b) < 0)
2354
            return -ENOTSUP;
2355
        break;
2356
    case CHR_IOCTL_PP_READ_CONTROL:
2357
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2358
            return -ENOTSUP;
2359
        /* Linux gives only the lowest bits, and no way to know data
2360
           direction! For better compatibility set the fixed upper
2361
           bits. */
2362
        *(uint8_t *)arg = b | 0xc0;
2363
        break;
2364
    case CHR_IOCTL_PP_WRITE_CONTROL:
2365
        b = *(uint8_t *)arg;
2366
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2367
            return -ENOTSUP;
2368
        break;
2369
    case CHR_IOCTL_PP_READ_STATUS:
2370
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2371
            return -ENOTSUP;
2372
        *(uint8_t *)arg = b;
2373
        break;
2374
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2375
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2376
            struct ParallelIOArg *parg = arg;
2377
            int n = read(fd, parg->buffer, parg->count);
2378
            if (n != parg->count) {
2379
                return -EIO;
2380
            }
2381
        }
2382
        break;
2383
    case CHR_IOCTL_PP_EPP_READ:
2384
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2385
            struct ParallelIOArg *parg = arg;
2386
            int n = read(fd, parg->buffer, parg->count);
2387
            if (n != parg->count) {
2388
                return -EIO;
2389
            }
2390
        }
2391
        break;
2392
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2393
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2394
            struct ParallelIOArg *parg = arg;
2395
            int n = write(fd, parg->buffer, parg->count);
2396
            if (n != parg->count) {
2397
                return -EIO;
2398
            }
2399
        }
2400
        break;
2401
    case CHR_IOCTL_PP_EPP_WRITE:
2402
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2403
            struct ParallelIOArg *parg = arg;
2404
            int n = write(fd, parg->buffer, parg->count);
2405
            if (n != parg->count) {
2406
                return -EIO;
2407
            }
2408
        }
2409
        break;
2410
    default:
2411
        return -ENOTSUP;
2412
    }
2413
    return 0;
2414
}
2415

    
2416
static void pp_close(CharDriverState *chr)
2417
{
2418
    ParallelCharDriver *drv = chr->opaque;
2419
    int fd = drv->fd;
2420

    
2421
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2422
    ioctl(fd, PPRELEASE);
2423
    close(fd);
2424
    qemu_free(drv);
2425
}
2426

    
2427
static CharDriverState *qemu_chr_open_pp(const char *filename)
2428
{
2429
    CharDriverState *chr;
2430
    ParallelCharDriver *drv;
2431
    int fd;
2432

    
2433
    TFR(fd = open(filename, O_RDWR));
2434
    if (fd < 0)
2435
        return NULL;
2436

    
2437
    if (ioctl(fd, PPCLAIM) < 0) {
2438
        close(fd);
2439
        return NULL;
2440
    }
2441

    
2442
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2443
    if (!drv) {
2444
        close(fd);
2445
        return NULL;
2446
    }
2447
    drv->fd = fd;
2448
    drv->mode = IEEE1284_MODE_COMPAT;
2449

    
2450
    chr = qemu_mallocz(sizeof(CharDriverState));
2451
    if (!chr) {
2452
        qemu_free(drv);
2453
        close(fd);
2454
        return NULL;
2455
    }
2456
    chr->chr_write = null_chr_write;
2457
    chr->chr_ioctl = pp_ioctl;
2458
    chr->chr_close = pp_close;
2459
    chr->opaque = drv;
2460

    
2461
    qemu_chr_reset(chr);
2462

    
2463
    return chr;
2464
}
2465
#endif /* __linux__ */
2466

    
2467
#else /* _WIN32 */
2468

    
2469
typedef struct {
2470
    int max_size;
2471
    HANDLE hcom, hrecv, hsend;
2472
    OVERLAPPED orecv, osend;
2473
    BOOL fpipe;
2474
    DWORD len;
2475
} WinCharState;
2476

    
2477
#define NSENDBUF 2048
2478
#define NRECVBUF 2048
2479
#define MAXCONNECT 1
2480
#define NTIMEOUT 5000
2481

    
2482
static int win_chr_poll(void *opaque);
2483
static int win_chr_pipe_poll(void *opaque);
2484

    
2485
static void win_chr_close(CharDriverState *chr)
2486
{
2487
    WinCharState *s = chr->opaque;
2488

    
2489
    if (s->hsend) {
2490
        CloseHandle(s->hsend);
2491
        s->hsend = NULL;
2492
    }
2493
    if (s->hrecv) {
2494
        CloseHandle(s->hrecv);
2495
        s->hrecv = NULL;
2496
    }
2497
    if (s->hcom) {
2498
        CloseHandle(s->hcom);
2499
        s->hcom = NULL;
2500
    }
2501
    if (s->fpipe)
2502
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2503
    else
2504
        qemu_del_polling_cb(win_chr_poll, chr);
2505
}
2506

    
2507
static int win_chr_init(CharDriverState *chr, const char *filename)
2508
{
2509
    WinCharState *s = chr->opaque;
2510
    COMMCONFIG comcfg;
2511
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2512
    COMSTAT comstat;
2513
    DWORD size;
2514
    DWORD err;
2515

    
2516
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2517
    if (!s->hsend) {
2518
        fprintf(stderr, "Failed CreateEvent\n");
2519
        goto fail;
2520
    }
2521
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2522
    if (!s->hrecv) {
2523
        fprintf(stderr, "Failed CreateEvent\n");
2524
        goto fail;
2525
    }
2526

    
2527
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2528
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2529
    if (s->hcom == INVALID_HANDLE_VALUE) {
2530
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2531
        s->hcom = NULL;
2532
        goto fail;
2533
    }
2534

    
2535
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2536
        fprintf(stderr, "Failed SetupComm\n");
2537
        goto fail;
2538
    }
2539

    
2540
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2541
    size = sizeof(COMMCONFIG);
2542
    GetDefaultCommConfig(filename, &comcfg, &size);
2543
    comcfg.dcb.DCBlength = sizeof(DCB);
2544
    CommConfigDialog(filename, NULL, &comcfg);
2545

    
2546
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2547
        fprintf(stderr, "Failed SetCommState\n");
2548
        goto fail;
2549
    }
2550

    
2551
    if (!SetCommMask(s->hcom, EV_ERR)) {
2552
        fprintf(stderr, "Failed SetCommMask\n");
2553
        goto fail;
2554
    }
2555

    
2556
    cto.ReadIntervalTimeout = MAXDWORD;
2557
    if (!SetCommTimeouts(s->hcom, &cto)) {
2558
        fprintf(stderr, "Failed SetCommTimeouts\n");
2559
        goto fail;
2560
    }
2561

    
2562
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2563
        fprintf(stderr, "Failed ClearCommError\n");
2564
        goto fail;
2565
    }
2566
    qemu_add_polling_cb(win_chr_poll, chr);
2567
    return 0;
2568

    
2569
 fail:
2570
    win_chr_close(chr);
2571
    return -1;
2572
}
2573

    
2574
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2575
{
2576
    WinCharState *s = chr->opaque;
2577
    DWORD len, ret, size, err;
2578

    
2579
    len = len1;
2580
    ZeroMemory(&s->osend, sizeof(s->osend));
2581
    s->osend.hEvent = s->hsend;
2582
    while (len > 0) {
2583
        if (s->hsend)
2584
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2585
        else
2586
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2587
        if (!ret) {
2588
            err = GetLastError();
2589
            if (err == ERROR_IO_PENDING) {
2590
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2591
                if (ret) {
2592
                    buf += size;
2593
                    len -= size;
2594
                } else {
2595
                    break;
2596
                }
2597
            } else {
2598
                break;
2599
            }
2600
        } else {
2601
            buf += size;
2602
            len -= size;
2603
        }
2604
    }
2605
    return len1 - len;
2606
}
2607

    
2608
static int win_chr_read_poll(CharDriverState *chr)
2609
{
2610
    WinCharState *s = chr->opaque;
2611

    
2612
    s->max_size = qemu_chr_can_read(chr);
2613
    return s->max_size;
2614
}
2615

    
2616
static void win_chr_readfile(CharDriverState *chr)
2617
{
2618
    WinCharState *s = chr->opaque;
2619
    int ret, err;
2620
    uint8_t buf[1024];
2621
    DWORD size;
2622

    
2623
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2624
    s->orecv.hEvent = s->hrecv;
2625
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2626
    if (!ret) {
2627
        err = GetLastError();
2628
        if (err == ERROR_IO_PENDING) {
2629
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2630
        }
2631
    }
2632

    
2633
    if (size > 0) {
2634
        qemu_chr_read(chr, buf, size);
2635
    }
2636
}
2637

    
2638
static void win_chr_read(CharDriverState *chr)
2639
{
2640
    WinCharState *s = chr->opaque;
2641

    
2642
    if (s->len > s->max_size)
2643
        s->len = s->max_size;
2644
    if (s->len == 0)
2645
        return;
2646

    
2647
    win_chr_readfile(chr);
2648
}
2649

    
2650
static int win_chr_poll(void *opaque)
2651
{
2652
    CharDriverState *chr = opaque;
2653
    WinCharState *s = chr->opaque;
2654
    COMSTAT status;
2655
    DWORD comerr;
2656

    
2657
    ClearCommError(s->hcom, &comerr, &status);
2658
    if (status.cbInQue > 0) {
2659
        s->len = status.cbInQue;
2660
        win_chr_read_poll(chr);
2661
        win_chr_read(chr);
2662
        return 1;
2663
    }
2664
    return 0;
2665
}
2666

    
2667
static CharDriverState *qemu_chr_open_win(const char *filename)
2668
{
2669
    CharDriverState *chr;
2670
    WinCharState *s;
2671

    
2672
    chr = qemu_mallocz(sizeof(CharDriverState));
2673
    if (!chr)
2674
        return NULL;
2675
    s = qemu_mallocz(sizeof(WinCharState));
2676
    if (!s) {
2677
        free(chr);
2678
        return NULL;
2679
    }
2680
    chr->opaque = s;
2681
    chr->chr_write = win_chr_write;
2682
    chr->chr_close = win_chr_close;
2683

    
2684
    if (win_chr_init(chr, filename) < 0) {
2685
        free(s);
2686
        free(chr);
2687
        return NULL;
2688
    }
2689
    qemu_chr_reset(chr);
2690
    return chr;
2691
}
2692

    
2693
static int win_chr_pipe_poll(void *opaque)
2694
{
2695
    CharDriverState *chr = opaque;
2696
    WinCharState *s = chr->opaque;
2697
    DWORD size;
2698

    
2699
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2700
    if (size > 0) {
2701
        s->len = size;
2702
        win_chr_read_poll(chr);
2703
        win_chr_read(chr);
2704
        return 1;
2705
    }
2706
    return 0;
2707
}
2708

    
2709
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2710
{
2711
    WinCharState *s = chr->opaque;
2712
    OVERLAPPED ov;
2713
    int ret;
2714
    DWORD size;
2715
    char openname[256];
2716

    
2717
    s->fpipe = TRUE;
2718

    
2719
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2720
    if (!s->hsend) {
2721
        fprintf(stderr, "Failed CreateEvent\n");
2722
        goto fail;
2723
    }
2724
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2725
    if (!s->hrecv) {
2726
        fprintf(stderr, "Failed CreateEvent\n");
2727
        goto fail;
2728
    }
2729

    
2730
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2731
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2732
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2733
                              PIPE_WAIT,
2734
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2735
    if (s->hcom == INVALID_HANDLE_VALUE) {
2736
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2737
        s->hcom = NULL;
2738
        goto fail;
2739
    }
2740

    
2741
    ZeroMemory(&ov, sizeof(ov));
2742
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2743
    ret = ConnectNamedPipe(s->hcom, &ov);
2744
    if (ret) {
2745
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2746
        goto fail;
2747
    }
2748

    
2749
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2750
    if (!ret) {
2751
        fprintf(stderr, "Failed GetOverlappedResult\n");
2752
        if (ov.hEvent) {
2753
            CloseHandle(ov.hEvent);
2754
            ov.hEvent = NULL;
2755
        }
2756
        goto fail;
2757
    }
2758

    
2759
    if (ov.hEvent) {
2760
        CloseHandle(ov.hEvent);
2761
        ov.hEvent = NULL;
2762
    }
2763
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2764
    return 0;
2765

    
2766
 fail:
2767
    win_chr_close(chr);
2768
    return -1;
2769
}
2770

    
2771

    
2772
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2773
{
2774
    CharDriverState *chr;
2775
    WinCharState *s;
2776

    
2777
    chr = qemu_mallocz(sizeof(CharDriverState));
2778
    if (!chr)
2779
        return NULL;
2780
    s = qemu_mallocz(sizeof(WinCharState));
2781
    if (!s) {
2782
        free(chr);
2783
        return NULL;
2784
    }
2785
    chr->opaque = s;
2786
    chr->chr_write = win_chr_write;
2787
    chr->chr_close = win_chr_close;
2788

    
2789
    if (win_chr_pipe_init(chr, filename) < 0) {
2790
        free(s);
2791
        free(chr);
2792
        return NULL;
2793
    }
2794
    qemu_chr_reset(chr);
2795
    return chr;
2796
}
2797

    
2798
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2799
{
2800
    CharDriverState *chr;
2801
    WinCharState *s;
2802

    
2803
    chr = qemu_mallocz(sizeof(CharDriverState));
2804
    if (!chr)
2805
        return NULL;
2806
    s = qemu_mallocz(sizeof(WinCharState));
2807
    if (!s) {
2808
        free(chr);
2809
        return NULL;
2810
    }
2811
    s->hcom = fd_out;
2812
    chr->opaque = s;
2813
    chr->chr_write = win_chr_write;
2814
    qemu_chr_reset(chr);
2815
    return chr;
2816
}
2817

    
2818
static CharDriverState *qemu_chr_open_win_con(const char *filename)
2819
{
2820
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2821
}
2822

    
2823
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2824
{
2825
    HANDLE fd_out;
2826

    
2827
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2828
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2829
    if (fd_out == INVALID_HANDLE_VALUE)
2830
        return NULL;
2831

    
2832
    return qemu_chr_open_win_file(fd_out);
2833
}
2834
#endif /* !_WIN32 */
2835

    
2836
/***********************************************************/
2837
/* UDP Net console */
2838

    
2839
typedef struct {
2840
    int fd;
2841
    struct sockaddr_in daddr;
2842
    char buf[1024];
2843
    int bufcnt;
2844
    int bufptr;
2845
    int max_size;
2846
} NetCharDriver;
2847

    
2848
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2849
{
2850
    NetCharDriver *s = chr->opaque;
2851

    
2852
    return sendto(s->fd, buf, len, 0,
2853
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2854
}
2855

    
2856
static int udp_chr_read_poll(void *opaque)
2857
{
2858
    CharDriverState *chr = opaque;
2859
    NetCharDriver *s = chr->opaque;
2860

    
2861
    s->max_size = qemu_chr_can_read(chr);
2862

    
2863
    /* If there were any stray characters in the queue process them
2864
     * first
2865
     */
2866
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2867
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2868
        s->bufptr++;
2869
        s->max_size = qemu_chr_can_read(chr);
2870
    }
2871
    return s->max_size;
2872
}
2873

    
2874
static void udp_chr_read(void *opaque)
2875
{
2876
    CharDriverState *chr = opaque;
2877
    NetCharDriver *s = chr->opaque;
2878

    
2879
    if (s->max_size == 0)
2880
        return;
2881
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2882
    s->bufptr = s->bufcnt;
2883
    if (s->bufcnt <= 0)
2884
        return;
2885

    
2886
    s->bufptr = 0;
2887
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2888
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2889
        s->bufptr++;
2890
        s->max_size = qemu_chr_can_read(chr);
2891
    }
2892
}
2893

    
2894
static void udp_chr_update_read_handler(CharDriverState *chr)
2895
{
2896
    NetCharDriver *s = chr->opaque;
2897

    
2898
    if (s->fd >= 0) {
2899
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2900
                             udp_chr_read, NULL, chr);
2901
    }
2902
}
2903

    
2904
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2905
#ifndef _WIN32
2906
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2907
#endif
2908
int parse_host_src_port(struct sockaddr_in *haddr,
2909
                        struct sockaddr_in *saddr,
2910
                        const char *str);
2911

    
2912
static CharDriverState *qemu_chr_open_udp(const char *def)
2913
{
2914
    CharDriverState *chr = NULL;
2915
    NetCharDriver *s = NULL;
2916
    int fd = -1;
2917
    struct sockaddr_in saddr;
2918

    
2919
    chr = qemu_mallocz(sizeof(CharDriverState));
2920
    if (!chr)
2921
        goto return_err;
2922
    s = qemu_mallocz(sizeof(NetCharDriver));
2923
    if (!s)
2924
        goto return_err;
2925

    
2926
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2927
    if (fd < 0) {
2928
        perror("socket(PF_INET, SOCK_DGRAM)");
2929
        goto return_err;
2930
    }
2931

    
2932
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2933
        printf("Could not parse: %s\n", def);
2934
        goto return_err;
2935
    }
2936

    
2937
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2938
    {
2939
        perror("bind");
2940
        goto return_err;
2941
    }
2942

    
2943
    s->fd = fd;
2944
    s->bufcnt = 0;
2945
    s->bufptr = 0;
2946
    chr->opaque = s;
2947
    chr->chr_write = udp_chr_write;
2948
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2949
    return chr;
2950

    
2951
return_err:
2952
    if (chr)
2953
        free(chr);
2954
    if (s)
2955
        free(s);
2956
    if (fd >= 0)
2957
        closesocket(fd);
2958
    return NULL;
2959
}
2960

    
2961
/***********************************************************/
2962
/* TCP Net console */
2963

    
2964
typedef struct {
2965
    int fd, listen_fd;
2966
    int connected;
2967
    int max_size;
2968
    int do_telnetopt;
2969
    int do_nodelay;
2970
    int is_unix;
2971
} TCPCharDriver;
2972

    
2973
static void tcp_chr_accept(void *opaque);
2974

    
2975
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2976
{
2977
    TCPCharDriver *s = chr->opaque;
2978
    if (s->connected) {
2979
        return send_all(s->fd, buf, len);
2980
    } else {
2981
        /* XXX: indicate an error ? */
2982
        return len;
2983
    }
2984
}
2985

    
2986
static int tcp_chr_read_poll(void *opaque)
2987
{
2988
    CharDriverState *chr = opaque;
2989
    TCPCharDriver *s = chr->opaque;
2990
    if (!s->connected)
2991
        return 0;
2992
    s->max_size = qemu_chr_can_read(chr);
2993
    return s->max_size;
2994
}
2995

    
2996
#define IAC 255
2997
#define IAC_BREAK 243
2998
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2999
                                      TCPCharDriver *s,
3000
                                      char *buf, int *size)
3001
{
3002
    /* Handle any telnet client's basic IAC options to satisfy char by
3003
     * char mode with no echo.  All IAC options will be removed from
3004
     * the buf and the do_telnetopt variable will be used to track the
3005
     * state of the width of the IAC information.
3006
     *
3007
     * IAC commands come in sets of 3 bytes with the exception of the
3008
     * "IAC BREAK" command and the double IAC.
3009
     */
3010

    
3011
    int i;
3012
    int j = 0;
3013

    
3014
    for (i = 0; i < *size; i++) {
3015
        if (s->do_telnetopt > 1) {
3016
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3017
                /* Double IAC means send an IAC */
3018
                if (j != i)
3019
                    buf[j] = buf[i];
3020
                j++;
3021
                s->do_telnetopt = 1;
3022
            } else {
3023
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3024
                    /* Handle IAC break commands by sending a serial break */
3025
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3026
                    s->do_telnetopt++;
3027
                }
3028
                s->do_telnetopt++;
3029
            }
3030
            if (s->do_telnetopt >= 4) {
3031
                s->do_telnetopt = 1;
3032
            }
3033
        } else {
3034
            if ((unsigned char)buf[i] == IAC) {
3035
                s->do_telnetopt = 2;
3036
            } else {
3037
                if (j != i)
3038
                    buf[j] = buf[i];
3039
                j++;
3040
            }
3041
        }
3042
    }
3043
    *size = j;
3044
}
3045

    
3046
static void tcp_chr_read(void *opaque)
3047
{
3048
    CharDriverState *chr = opaque;
3049
    TCPCharDriver *s = chr->opaque;
3050
    uint8_t buf[1024];
3051
    int len, size;
3052

    
3053
    if (!s->connected || s->max_size <= 0)
3054
        return;
3055
    len = sizeof(buf);
3056
    if (len > s->max_size)
3057
        len = s->max_size;
3058
    size = recv(s->fd, buf, len, 0);
3059
    if (size == 0) {
3060
        /* connection closed */
3061
        s->connected = 0;
3062
        if (s->listen_fd >= 0) {
3063
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3064
        }
3065
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3066
        closesocket(s->fd);
3067
        s->fd = -1;
3068
    } else if (size > 0) {
3069
        if (s->do_telnetopt)
3070
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3071
        if (size > 0)
3072
            qemu_chr_read(chr, buf, size);
3073
    }
3074
}
3075

    
3076
static void tcp_chr_connect(void *opaque)
3077
{
3078
    CharDriverState *chr = opaque;
3079
    TCPCharDriver *s = chr->opaque;
3080

    
3081
    s->connected = 1;
3082
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3083
                         tcp_chr_read, NULL, chr);
3084
    qemu_chr_reset(chr);
3085
}
3086

    
3087
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3088
static void tcp_chr_telnet_init(int fd)
3089
{
3090
    char buf[3];
3091
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3092
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3093
    send(fd, (char *)buf, 3, 0);
3094
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3095
    send(fd, (char *)buf, 3, 0);
3096
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3097
    send(fd, (char *)buf, 3, 0);
3098
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3099
    send(fd, (char *)buf, 3, 0);
3100
}
3101

    
3102
static void socket_set_nodelay(int fd)
3103
{
3104
    int val = 1;
3105
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3106
}
3107

    
3108
static void tcp_chr_accept(void *opaque)
3109
{
3110
    CharDriverState *chr = opaque;
3111
    TCPCharDriver *s = chr->opaque;
3112
    struct sockaddr_in saddr;
3113
#ifndef _WIN32
3114
    struct sockaddr_un uaddr;
3115
#endif
3116
    struct sockaddr *addr;
3117
    socklen_t len;
3118
    int fd;
3119

    
3120
    for(;;) {
3121
#ifndef _WIN32
3122
        if (s->is_unix) {
3123
            len = sizeof(uaddr);
3124
            addr = (struct sockaddr *)&uaddr;
3125
        } else
3126
#endif
3127
        {
3128
            len = sizeof(saddr);
3129
            addr = (struct sockaddr *)&saddr;
3130
        }
3131
        fd = accept(s->listen_fd, addr, &len);
3132
        if (fd < 0 && errno != EINTR) {
3133
            return;
3134
        } else if (fd >= 0) {
3135
            if (s->do_telnetopt)
3136
                tcp_chr_telnet_init(fd);
3137
            break;
3138
        }
3139
    }
3140
    socket_set_nonblock(fd);
3141
    if (s->do_nodelay)
3142
        socket_set_nodelay(fd);
3143
    s->fd = fd;
3144
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3145
    tcp_chr_connect(chr);
3146
}
3147

    
3148
static void tcp_chr_close(CharDriverState *chr)
3149
{
3150
    TCPCharDriver *s = chr->opaque;
3151
    if (s->fd >= 0)
3152
        closesocket(s->fd);
3153
    if (s->listen_fd >= 0)
3154
        closesocket(s->listen_fd);
3155
    qemu_free(s);
3156
}
3157

    
3158
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3159
                                          int is_telnet,
3160
                                          int is_unix)
3161
{
3162
    CharDriverState *chr = NULL;
3163
    TCPCharDriver *s = NULL;
3164
    int fd = -1, ret, err, val;
3165
    int is_listen = 0;
3166
    int is_waitconnect = 1;
3167
    int do_nodelay = 0;
3168
    const char *ptr;
3169
    struct sockaddr_in saddr;
3170
#ifndef _WIN32
3171
    struct sockaddr_un uaddr;
3172
#endif
3173
    struct sockaddr *addr;
3174
    socklen_t addrlen;
3175

    
3176
#ifndef _WIN32
3177
    if (is_unix) {
3178
        addr = (struct sockaddr *)&uaddr;
3179
        addrlen = sizeof(uaddr);
3180
        if (parse_unix_path(&uaddr, host_str) < 0)
3181
            goto fail;
3182
    } else
3183
#endif
3184
    {
3185
        addr = (struct sockaddr *)&saddr;
3186
        addrlen = sizeof(saddr);
3187
        if (parse_host_port(&saddr, host_str) < 0)
3188
            goto fail;
3189
    }
3190

    
3191
    ptr = host_str;
3192
    while((ptr = strchr(ptr,','))) {
3193
        ptr++;
3194
        if (!strncmp(ptr,"server",6)) {
3195
            is_listen = 1;
3196
        } else if (!strncmp(ptr,"nowait",6)) {
3197
            is_waitconnect = 0;
3198
        } else if (!strncmp(ptr,"nodelay",6)) {
3199
            do_nodelay = 1;
3200
        } else {
3201
            printf("Unknown option: %s\n", ptr);
3202
            goto fail;
3203
        }
3204
    }
3205
    if (!is_listen)
3206
        is_waitconnect = 0;
3207

    
3208
    chr = qemu_mallocz(sizeof(CharDriverState));
3209
    if (!chr)
3210
        goto fail;
3211
    s = qemu_mallocz(sizeof(TCPCharDriver));
3212
    if (!s)
3213
        goto fail;
3214

    
3215
#ifndef _WIN32
3216
    if (is_unix)
3217
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3218
    else
3219
#endif
3220
        fd = socket(PF_INET, SOCK_STREAM, 0);
3221

    
3222
    if (fd < 0)
3223
        goto fail;
3224

    
3225
    if (!is_waitconnect)
3226
        socket_set_nonblock(fd);
3227

    
3228
    s->connected = 0;
3229
    s->fd = -1;
3230
    s->listen_fd = -1;
3231
    s->is_unix = is_unix;
3232
    s->do_nodelay = do_nodelay && !is_unix;
3233

    
3234
    chr->opaque = s;
3235
    chr->chr_write = tcp_chr_write;
3236
    chr->chr_close = tcp_chr_close;
3237

    
3238
    if (is_listen) {
3239
        /* allow fast reuse */
3240
#ifndef _WIN32
3241
        if (is_unix) {
3242
            char path[109];
3243
            strncpy(path, uaddr.sun_path, 108);
3244
            path[108] = 0;
3245
            unlink(path);
3246
        } else
3247
#endif
3248
        {
3249
            val = 1;
3250
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3251
        }
3252

    
3253
        ret = bind(fd, addr, addrlen);
3254
        if (ret < 0)
3255
            goto fail;
3256

    
3257
        ret = listen(fd, 0);
3258
        if (ret < 0)
3259
            goto fail;
3260

    
3261
        s->listen_fd = fd;
3262
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3263
        if (is_telnet)
3264
            s->do_telnetopt = 1;
3265
    } else {
3266
        for(;;) {
3267
            ret = connect(fd, addr, addrlen);
3268
            if (ret < 0) {
3269
                err = socket_error();
3270
                if (err == EINTR || err == EWOULDBLOCK) {
3271
                } else if (err == EINPROGRESS) {
3272
                    break;
3273
#ifdef _WIN32
3274
                } else if (err == WSAEALREADY) {
3275
                    break;
3276
#endif
3277
                } else {
3278
                    goto fail;
3279
                }
3280
            } else {
3281
                s->connected = 1;
3282
                break;
3283
            }
3284
        }
3285
        s->fd = fd;
3286
        socket_set_nodelay(fd);
3287
        if (s->connected)
3288
            tcp_chr_connect(chr);
3289
        else
3290
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3291
    }
3292

    
3293
    if (is_listen && is_waitconnect) {
3294
        printf("QEMU waiting for connection on: %s\n", host_str);
3295
        tcp_chr_accept(chr);
3296
        socket_set_nonblock(s->listen_fd);
3297
    }
3298

    
3299
    return chr;
3300
 fail:
3301
    if (fd >= 0)
3302
        closesocket(fd);
3303
    qemu_free(s);
3304
    qemu_free(chr);
3305
    return NULL;
3306
}
3307

    
3308
CharDriverState *qemu_chr_open(const char *filename)
3309
{
3310
    const char *p;
3311

    
3312
    if (!strcmp(filename, "vc")) {
3313
        return text_console_init(&display_state, 0);
3314
    } else if (strstart(filename, "vc:", &p)) {
3315
        return text_console_init(&display_state, p);
3316
    } else if (!strcmp(filename, "null")) {
3317
        return qemu_chr_open_null();
3318
    } else
3319
    if (strstart(filename, "tcp:", &p)) {
3320
        return qemu_chr_open_tcp(p, 0, 0);
3321
    } else
3322
    if (strstart(filename, "telnet:", &p)) {
3323
        return qemu_chr_open_tcp(p, 1, 0);
3324
    } else
3325
    if (strstart(filename, "udp:", &p)) {
3326
        return qemu_chr_open_udp(p);
3327
    } else
3328
    if (strstart(filename, "mon:", &p)) {
3329
        CharDriverState *drv = qemu_chr_open(p);
3330
        if (drv) {
3331
            drv = qemu_chr_open_mux(drv);
3332
            monitor_init(drv, !nographic);
3333
            return drv;
3334
        }
3335
        printf("Unable to open driver: %s\n", p);
3336
        return 0;
3337
    } else
3338
#ifndef _WIN32
3339
    if (strstart(filename, "unix:", &p)) {
3340
        return qemu_chr_open_tcp(p, 0, 1);
3341
    } else if (strstart(filename, "file:", &p)) {
3342
        return qemu_chr_open_file_out(p);
3343
    } else if (strstart(filename, "pipe:", &p)) {
3344
        return qemu_chr_open_pipe(p);
3345
    } else if (!strcmp(filename, "pty")) {
3346
        return qemu_chr_open_pty();
3347
    } else if (!strcmp(filename, "stdio")) {
3348
        return qemu_chr_open_stdio();
3349
    } else
3350
#if defined(__linux__)
3351
    if (strstart(filename, "/dev/parport", NULL)) {
3352
        return qemu_chr_open_pp(filename);
3353
    } else
3354
#endif
3355
#if defined(__linux__) || defined(__sun__)
3356
    if (strstart(filename, "/dev/", NULL)) {
3357
        return qemu_chr_open_tty(filename);
3358
    } else
3359
#endif
3360
#else /* !_WIN32 */
3361
    if (strstart(filename, "COM", NULL)) {
3362
        return qemu_chr_open_win(filename);
3363
    } else
3364
    if (strstart(filename, "pipe:", &p)) {
3365
        return qemu_chr_open_win_pipe(p);
3366
    } else
3367
    if (strstart(filename, "con:", NULL)) {
3368
        return qemu_chr_open_win_con(filename);
3369
    } else
3370
    if (strstart(filename, "file:", &p)) {
3371
        return qemu_chr_open_win_file_out(p);
3372
    }
3373
#endif
3374
    {
3375
        return NULL;
3376
    }
3377
}
3378

    
3379
void qemu_chr_close(CharDriverState *chr)
3380
{
3381
    if (chr->chr_close)
3382
        chr->chr_close(chr);
3383
}
3384

    
3385
/***********************************************************/
3386
/* network device redirectors */
3387

    
3388
__attribute__ (( unused ))
3389
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3390
{
3391
    int len, i, j, c;
3392

    
3393
    for(i=0;i<size;i+=16) {
3394
        len = size - i;
3395
        if (len > 16)
3396
            len = 16;
3397
        fprintf(f, "%08x ", i);
3398
        for(j=0;j<16;j++) {
3399
            if (j < len)
3400
                fprintf(f, " %02x", buf[i+j]);
3401
            else
3402
                fprintf(f, "   ");
3403
        }
3404
        fprintf(f, " ");
3405
        for(j=0;j<len;j++) {
3406
            c = buf[i+j];
3407
            if (c < ' ' || c > '~')
3408
                c = '.';
3409
            fprintf(f, "%c", c);
3410
        }
3411
        fprintf(f, "\n");
3412
    }
3413
}
3414

    
3415
static int parse_macaddr(uint8_t *macaddr, const char *p)
3416
{
3417
    int i;
3418
    for(i = 0; i < 6; i++) {
3419
        macaddr[i] = strtol(p, (char **)&p, 16);
3420
        if (i == 5) {
3421
            if (*p != '\0')
3422
                return -1;
3423
        } else {
3424
            if (*p != ':')
3425
                return -1;
3426
            p++;
3427
        }
3428
    }
3429
    return 0;
3430
}
3431

    
3432
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3433
{
3434
    const char *p, *p1;
3435
    int len;
3436
    p = *pp;
3437
    p1 = strchr(p, sep);
3438
    if (!p1)
3439
        return -1;
3440
    len = p1 - p;
3441
    p1++;
3442
    if (buf_size > 0) {
3443
        if (len > buf_size - 1)
3444
            len = buf_size - 1;
3445
        memcpy(buf, p, len);
3446
        buf[len] = '\0';
3447
    }
3448
    *pp = p1;
3449
    return 0;
3450
}
3451

    
3452
int parse_host_src_port(struct sockaddr_in *haddr,
3453
                        struct sockaddr_in *saddr,
3454
                        const char *input_str)
3455
{
3456
    char *str = strdup(input_str);
3457
    char *host_str = str;
3458
    char *src_str;
3459
    char *ptr;
3460

    
3461
    /*
3462
     * Chop off any extra arguments at the end of the string which
3463
     * would start with a comma, then fill in the src port information
3464
     * if it was provided else use the "any address" and "any port".
3465
     */
3466
    if ((ptr = strchr(str,',')))
3467
        *ptr = '\0';
3468

    
3469
    if ((src_str = strchr(input_str,'@'))) {
3470
        *src_str = '\0';
3471
        src_str++;
3472
    }
3473

    
3474
    if (parse_host_port(haddr, host_str) < 0)
3475
        goto fail;
3476

    
3477
    if (!src_str || *src_str == '\0')
3478
        src_str = ":0";
3479

    
3480
    if (parse_host_port(saddr, src_str) < 0)
3481
        goto fail;
3482

    
3483
    free(str);
3484
    return(0);
3485

    
3486
fail:
3487
    free(str);
3488
    return -1;
3489
}
3490

    
3491
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3492
{
3493
    char buf[512];
3494
    struct hostent *he;
3495
    const char *p, *r;
3496
    int port;
3497

    
3498
    p = str;
3499
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3500
        return -1;
3501
    saddr->sin_family = AF_INET;
3502
    if (buf[0] == '\0') {
3503
        saddr->sin_addr.s_addr = 0;
3504
    } else {
3505
        if (isdigit(buf[0])) {
3506
            if (!inet_aton(buf, &saddr->sin_addr))
3507
                return -1;
3508
        } else {
3509
            if ((he = gethostbyname(buf)) == NULL)
3510
                return - 1;
3511
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3512
        }
3513
    }
3514
    port = strtol(p, (char **)&r, 0);
3515
    if (r == p)
3516
        return -1;
3517
    saddr->sin_port = htons(port);
3518
    return 0;
3519
}
3520

    
3521
#ifndef _WIN32
3522
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3523
{
3524
    const char *p;
3525
    int len;
3526

    
3527
    len = MIN(108, strlen(str));
3528
    p = strchr(str, ',');
3529
    if (p)
3530
        len = MIN(len, p - str);
3531

    
3532
    memset(uaddr, 0, sizeof(*uaddr));
3533

    
3534
    uaddr->sun_family = AF_UNIX;
3535
    memcpy(uaddr->sun_path, str, len);
3536

    
3537
    return 0;
3538
}
3539
#endif
3540

    
3541
/* find or alloc a new VLAN */
3542
VLANState *qemu_find_vlan(int id)
3543
{
3544
    VLANState **pvlan, *vlan;
3545
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3546
        if (vlan->id == id)
3547
            return vlan;
3548
    }
3549
    vlan = qemu_mallocz(sizeof(VLANState));
3550
    if (!vlan)
3551
        return NULL;
3552
    vlan->id = id;
3553
    vlan->next = NULL;
3554
    pvlan = &first_vlan;
3555
    while (*pvlan != NULL)
3556
        pvlan = &(*pvlan)->next;
3557
    *pvlan = vlan;
3558
    return vlan;
3559
}
3560

    
3561
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3562
                                      IOReadHandler *fd_read,
3563
                                      IOCanRWHandler *fd_can_read,
3564
                                      void *opaque)
3565
{
3566
    VLANClientState *vc, **pvc;
3567
    vc = qemu_mallocz(sizeof(VLANClientState));
3568
    if (!vc)
3569
        return NULL;
3570
    vc->fd_read = fd_read;
3571
    vc->fd_can_read = fd_can_read;
3572
    vc->opaque = opaque;
3573
    vc->vlan = vlan;
3574

    
3575
    vc->next = NULL;
3576
    pvc = &vlan->first_client;
3577
    while (*pvc != NULL)
3578
        pvc = &(*pvc)->next;
3579
    *pvc = vc;
3580
    return vc;
3581
}
3582

    
3583
int qemu_can_send_packet(VLANClientState *vc1)
3584
{
3585
    VLANState *vlan = vc1->vlan;
3586
    VLANClientState *vc;
3587

    
3588
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3589
        if (vc != vc1) {
3590
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3591
                return 1;
3592
        }
3593
    }
3594
    return 0;
3595
}
3596

    
3597
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3598
{
3599
    VLANState *vlan = vc1->vlan;
3600
    VLANClientState *vc;
3601

    
3602
#if 0
3603
    printf("vlan %d send:\n", vlan->id);
3604
    hex_dump(stdout, buf, size);
3605
#endif
3606
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3607
        if (vc != vc1) {
3608
            vc->fd_read(vc->opaque, buf, size);
3609
        }
3610
    }
3611
}
3612

    
3613
#if defined(CONFIG_SLIRP)
3614

    
3615
/* slirp network adapter */
3616

    
3617
static int slirp_inited;
3618
static VLANClientState *slirp_vc;
3619

    
3620
int slirp_can_output(void)
3621
{
3622
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3623
}
3624

    
3625
void slirp_output(const uint8_t *pkt, int pkt_len)
3626
{
3627
#if 0
3628
    printf("slirp output:\n");
3629
    hex_dump(stdout, pkt, pkt_len);
3630
#endif
3631
    if (!slirp_vc)
3632
        return;
3633
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3634
}
3635

    
3636
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3637
{
3638
#if 0
3639
    printf("slirp input:\n");
3640
    hex_dump(stdout, buf, size);
3641
#endif
3642
    slirp_input(buf, size);
3643
}
3644

    
3645
static int net_slirp_init(VLANState *vlan)
3646
{
3647
    if (!slirp_inited) {
3648
        slirp_inited = 1;
3649
        slirp_init();
3650
    }
3651
    slirp_vc = qemu_new_vlan_client(vlan,
3652
                                    slirp_receive, NULL, NULL);
3653
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3654
    return 0;
3655
}
3656

    
3657
static void net_slirp_redir(const char *redir_str)
3658
{
3659
    int is_udp;
3660
    char buf[256], *r;
3661
    const char *p;
3662
    struct in_addr guest_addr;
3663
    int host_port, guest_port;
3664

    
3665
    if (!slirp_inited) {
3666
        slirp_inited = 1;
3667
        slirp_init();
3668
    }
3669

    
3670
    p = redir_str;
3671
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3672
        goto fail;
3673
    if (!strcmp(buf, "tcp")) {
3674
        is_udp = 0;
3675
    } else if (!strcmp(buf, "udp")) {
3676
        is_udp = 1;
3677
    } else {
3678
        goto fail;
3679
    }
3680

    
3681
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3682
        goto fail;
3683
    host_port = strtol(buf, &r, 0);
3684
    if (r == buf)
3685
        goto fail;
3686

    
3687
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3688
        goto fail;
3689
    if (buf[0] == '\0') {
3690
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3691
    }
3692
    if (!inet_aton(buf, &guest_addr))
3693
        goto fail;
3694

    
3695
    guest_port = strtol(p, &r, 0);
3696
    if (r == p)
3697
        goto fail;
3698

    
3699
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3700
        fprintf(stderr, "qemu: could not set up redirection\n");
3701
        exit(1);
3702
    }
3703
    return;
3704
 fail:
3705
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3706
    exit(1);
3707
}
3708

    
3709
#ifndef _WIN32
3710

    
3711
char smb_dir[1024];
3712

    
3713
static void smb_exit(void)
3714
{
3715
    DIR *d;
3716
    struct dirent *de;
3717
    char filename[1024];
3718

    
3719
    /* erase all the files in the directory */
3720
    d = opendir(smb_dir);
3721
    for(;;) {
3722
        de = readdir(d);
3723
        if (!de)
3724
            break;
3725
        if (strcmp(de->d_name, ".") != 0 &&
3726
            strcmp(de->d_name, "..") != 0) {
3727
            snprintf(filename, sizeof(filename), "%s/%s",
3728
                     smb_dir, de->d_name);
3729
            unlink(filename);
3730
        }
3731
    }
3732
    closedir(d);
3733
    rmdir(smb_dir);
3734
}
3735

    
3736
/* automatic user mode samba server configuration */
3737
static void net_slirp_smb(const char *exported_dir)
3738
{
3739
    char smb_conf[1024];
3740
    char smb_cmdline[1024];
3741
    FILE *f;
3742

    
3743
    if (!slirp_inited) {
3744
        slirp_inited = 1;
3745
        slirp_init();
3746
    }
3747

    
3748
    /* XXX: better tmp dir construction */
3749
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3750
    if (mkdir(smb_dir, 0700) < 0) {
3751
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3752
        exit(1);
3753
    }
3754
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3755

    
3756
    f = fopen(smb_conf, "w");
3757
    if (!f) {
3758
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3759
        exit(1);
3760
    }
3761
    fprintf(f,
3762
            "[global]\n"
3763
            "private dir=%s\n"
3764
            "smb ports=0\n"
3765
            "socket address=127.0.0.1\n"
3766
            "pid directory=%s\n"
3767
            "lock directory=%s\n"
3768
            "log file=%s/log.smbd\n"
3769
            "smb passwd file=%s/smbpasswd\n"
3770
            "security = share\n"
3771
            "[qemu]\n"
3772
            "path=%s\n"
3773
            "read only=no\n"
3774
            "guest ok=yes\n",
3775
            smb_dir,
3776
            smb_dir,
3777
            smb_dir,
3778
            smb_dir,
3779
            smb_dir,
3780
            exported_dir
3781
            );
3782
    fclose(f);
3783
    atexit(smb_exit);
3784

    
3785
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3786
             SMBD_COMMAND, smb_conf);
3787

    
3788
    slirp_add_exec(0, smb_cmdline, 4, 139);
3789
}
3790

    
3791
#endif /* !defined(_WIN32) */
3792
void do_info_slirp(void)
3793
{
3794
    slirp_stats();
3795
}
3796

    
3797
#endif /* CONFIG_SLIRP */
3798

    
3799
#if !defined(_WIN32)
3800

    
3801
typedef struct TAPState {
3802
    VLANClientState *vc;
3803
    int fd;
3804
    char down_script[1024];
3805
} TAPState;
3806

    
3807
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3808
{
3809
    TAPState *s = opaque;
3810
    int ret;
3811
    for(;;) {
3812
        ret = write(s->fd, buf, size);
3813
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3814
        } else {
3815
            break;
3816
        }
3817
    }
3818
}
3819

    
3820
static void tap_send(void *opaque)
3821
{
3822
    TAPState *s = opaque;
3823
    uint8_t buf[4096];
3824
    int size;
3825

    
3826
#ifdef __sun__
3827
    struct strbuf sbuf;
3828
    int f = 0;
3829
    sbuf.maxlen = sizeof(buf);
3830
    sbuf.buf = buf;
3831
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3832
#else
3833
    size = read(s->fd, buf, sizeof(buf));
3834
#endif
3835
    if (size > 0) {
3836
        qemu_send_packet(s->vc, buf, size);
3837
    }
3838
}
3839

    
3840
/* fd support */
3841

    
3842
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3843
{
3844
    TAPState *s;
3845

    
3846
    s = qemu_mallocz(sizeof(TAPState));
3847
    if (!s)
3848
        return NULL;
3849
    s->fd = fd;
3850
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3851
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3852
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3853
    return s;
3854
}
3855

    
3856
#if defined (_BSD) || defined (__FreeBSD_kernel__)
3857
static int tap_open(char *ifname, int ifname_size)
3858
{
3859
    int fd;
3860
    char *dev;
3861
    struct stat s;
3862

    
3863
    TFR(fd = open("/dev/tap", O_RDWR));
3864
    if (fd < 0) {
3865
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3866
        return -1;
3867
    }
3868

    
3869
    fstat(fd, &s);
3870
    dev = devname(s.st_rdev, S_IFCHR);
3871
    pstrcpy(ifname, ifname_size, dev);
3872

    
3873
    fcntl(fd, F_SETFL, O_NONBLOCK);
3874
    return fd;
3875
}
3876
#elif defined(__sun__)
3877
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3878
/*
3879
 * Allocate TAP device, returns opened fd.
3880
 * Stores dev name in the first arg(must be large enough).
3881
 */
3882
int tap_alloc(char *dev)
3883
{
3884
    int tap_fd, if_fd, ppa = -1;
3885
    static int ip_fd = 0;
3886
    char *ptr;
3887

    
3888
    static int arp_fd = 0;
3889
    int ip_muxid, arp_muxid;
3890
    struct strioctl  strioc_if, strioc_ppa;
3891
    int link_type = I_PLINK;;
3892
    struct lifreq ifr;
3893
    char actual_name[32] = "";
3894

    
3895
    memset(&ifr, 0x0, sizeof(ifr));
3896

    
3897
    if( *dev ){
3898
       ptr = dev;
3899
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
3900
       ppa = atoi(ptr);
3901
    }
3902

    
3903
    /* Check if IP device was opened */
3904
    if( ip_fd )
3905
       close(ip_fd);
3906

    
3907
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3908
    if (ip_fd < 0) {
3909
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3910
       return -1;
3911
    }
3912

    
3913
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3914
    if (tap_fd < 0) {
3915
       syslog(LOG_ERR, "Can't open /dev/tap");
3916
       return -1;
3917
    }
3918

    
3919
    /* Assign a new PPA and get its unit number. */
3920
    strioc_ppa.ic_cmd = TUNNEWPPA;
3921
    strioc_ppa.ic_timout = 0;
3922
    strioc_ppa.ic_len = sizeof(ppa);
3923
    strioc_ppa.ic_dp = (char *)&ppa;
3924
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3925
       syslog (LOG_ERR, "Can't assign new interface");
3926

    
3927
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3928
    if (if_fd < 0) {
3929
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3930
       return -1;
3931
    }
3932
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3933
       syslog(LOG_ERR, "Can't push IP module");
3934
       return -1;
3935
    }
3936

    
3937
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3938
        syslog(LOG_ERR, "Can't get flags\n");
3939

    
3940
    snprintf (actual_name, 32, "tap%d", ppa);
3941
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3942

    
3943
    ifr.lifr_ppa = ppa;
3944
    /* Assign ppa according to the unit number returned by tun device */
3945

    
3946
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3947
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
3948
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3949
        syslog (LOG_ERR, "Can't get flags\n");
3950
    /* Push arp module to if_fd */
3951
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
3952
        syslog (LOG_ERR, "Can't push ARP module (2)");
3953

    
3954
    /* Push arp module to ip_fd */
3955
    if (ioctl (ip_fd, I_POP, NULL) < 0)
3956
        syslog (LOG_ERR, "I_POP failed\n");
3957
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3958
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
3959
    /* Open arp_fd */
3960
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3961
    if (arp_fd < 0)
3962
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3963

    
3964
    /* Set ifname to arp */
3965
    strioc_if.ic_cmd = SIOCSLIFNAME;
3966
    strioc_if.ic_timout = 0;
3967
    strioc_if.ic_len = sizeof(ifr);
3968
    strioc_if.ic_dp = (char *)&ifr;
3969
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3970
        syslog (LOG_ERR, "Can't set ifname to arp\n");
3971
    }
3972

    
3973
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3974
       syslog(LOG_ERR, "Can't link TAP device to IP");
3975
       return -1;
3976
    }
3977

    
3978
    if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3979
        syslog (LOG_ERR, "Can't link TAP device to ARP");
3980

    
3981
    close (if_fd);
3982

    
3983
    memset(&ifr, 0x0, sizeof(ifr));
3984
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3985
    ifr.lifr_ip_muxid  = ip_muxid;
3986
    ifr.lifr_arp_muxid = arp_muxid;
3987

    
3988
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3989
    {
3990
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
3991
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
3992
      syslog (LOG_ERR, "Can't set multiplexor id");
3993
    }
3994

    
3995
    sprintf(dev, "tap%d", ppa);
3996
    return tap_fd;
3997
}
3998

    
3999
static int tap_open(char *ifname, int ifname_size)
4000
{
4001
    char  dev[10]="";
4002
    int fd;
4003
    if( (fd = tap_alloc(dev)) < 0 ){
4004
       fprintf(stderr, "Cannot allocate TAP device\n");
4005
       return -1;
4006
    }
4007
    pstrcpy(ifname, ifname_size, dev);
4008
    fcntl(fd, F_SETFL, O_NONBLOCK);
4009
    return fd;
4010
}
4011
#else
4012
static int tap_open(char *ifname, int ifname_size)
4013
{
4014
    struct ifreq ifr;
4015
    int fd, ret;
4016

    
4017
    TFR(fd = open("/dev/net/tun", O_RDWR));
4018
    if (fd < 0) {
4019
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4020
        return -1;
4021
    }
4022
    memset(&ifr, 0, sizeof(ifr));
4023
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4024
    if (ifname[0] != '\0')
4025
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4026
    else
4027
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4028
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4029
    if (ret != 0) {
4030
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4031
        close(fd);
4032
        return -1;
4033
    }
4034
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4035
    fcntl(fd, F_SETFL, O_NONBLOCK);
4036
    return fd;
4037
}
4038
#endif
4039

    
4040
static int launch_script(const char *setup_script, const char *ifname, int fd)
4041
{
4042
    int pid, status;
4043
    char *args[3];
4044
    char **parg;
4045

    
4046
        /* try to launch network script */
4047
        pid = fork();
4048
        if (pid >= 0) {
4049
            if (pid == 0) {
4050
                int open_max = sysconf (_SC_OPEN_MAX), i;
4051
                for (i = 0; i < open_max; i++)
4052
                    if (i != STDIN_FILENO &&
4053
                        i != STDOUT_FILENO &&
4054
                        i != STDERR_FILENO &&
4055
                        i != fd)
4056
                        close(i);
4057

    
4058
                parg = args;
4059
                *parg++ = (char *)setup_script;
4060
                *parg++ = (char *)ifname;
4061
                *parg++ = NULL;
4062
                execv(setup_script, args);
4063
                _exit(1);
4064
            }
4065
            while (waitpid(pid, &status, 0) != pid);
4066
            if (!WIFEXITED(status) ||
4067
                WEXITSTATUS(status) != 0) {
4068
                fprintf(stderr, "%s: could not launch network script\n",
4069
                        setup_script);
4070
                return -1;
4071
            }
4072
        }
4073
    return 0;
4074
}
4075

    
4076
static int net_tap_init(VLANState *vlan, const char *ifname1,
4077
                        const char *setup_script, const char *down_script)
4078
{
4079
    TAPState *s;
4080
    int fd;
4081
    char ifname[128];
4082

    
4083
    if (ifname1 != NULL)
4084
        pstrcpy(ifname, sizeof(ifname), ifname1);
4085
    else
4086
        ifname[0] = '\0';
4087
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4088
    if (fd < 0)
4089
        return -1;
4090

    
4091
    if (!setup_script || !strcmp(setup_script, "no"))
4092
        setup_script = "";
4093
    if (setup_script[0] != '\0') {
4094
        if (launch_script(setup_script, ifname, fd))
4095
            return -1;
4096
    }
4097
    s = net_tap_fd_init(vlan, fd);
4098
    if (!s)
4099
        return -1;
4100
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4101
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4102
    if (down_script && strcmp(down_script, "no"))
4103
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4104
    return 0;
4105
}
4106

    
4107
#endif /* !_WIN32 */
4108

    
4109
/* network connection */
4110
typedef struct NetSocketState {
4111
    VLANClientState *vc;
4112
    int fd;
4113
    int state; /* 0 = getting length, 1 = getting data */
4114
    int index;
4115
    int packet_len;
4116
    uint8_t buf[4096];
4117
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4118
} NetSocketState;
4119

    
4120
typedef struct NetSocketListenState {
4121
    VLANState *vlan;
4122
    int fd;
4123
} NetSocketListenState;
4124

    
4125
/* XXX: we consider we can send the whole packet without blocking */
4126
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4127
{
4128
    NetSocketState *s = opaque;
4129
    uint32_t len;
4130
    len = htonl(size);
4131

    
4132
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4133
    send_all(s->fd, buf, size);
4134
}
4135

    
4136
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4137
{
4138
    NetSocketState *s = opaque;
4139
    sendto(s->fd, buf, size, 0,
4140
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4141
}
4142

    
4143
static void net_socket_send(void *opaque)
4144
{
4145
    NetSocketState *s = opaque;
4146
    int l, size, err;
4147
    uint8_t buf1[4096];
4148
    const uint8_t *buf;
4149

    
4150
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4151
    if (size < 0) {
4152
        err = socket_error();
4153
        if (err != EWOULDBLOCK)
4154
            goto eoc;
4155
    } else if (size == 0) {
4156
        /* end of connection */
4157
    eoc:
4158
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4159
        closesocket(s->fd);
4160
        return;
4161
    }
4162
    buf = buf1;
4163
    while (size > 0) {
4164
        /* reassemble a packet from the network */
4165
        switch(s->state) {
4166
        case 0:
4167
            l = 4 - s->index;
4168
            if (l > size)
4169
                l = size;
4170
            memcpy(s->buf + s->index, buf, l);
4171
            buf += l;
4172
            size -= l;
4173
            s->index += l;
4174
            if (s->index == 4) {
4175
                /* got length */
4176
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4177
                s->index = 0;
4178
                s->state = 1;
4179
            }
4180
            break;
4181
        case 1:
4182
            l = s->packet_len - s->index;
4183
            if (l > size)
4184
                l = size;
4185
            memcpy(s->buf + s->index, buf, l);
4186
            s->index += l;
4187
            buf += l;
4188
            size -= l;
4189
            if (s->index >= s->packet_len) {
4190
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4191
                s->index = 0;
4192
                s->state = 0;
4193
            }
4194
            break;
4195
        }
4196
    }
4197
}
4198

    
4199
static void net_socket_send_dgram(void *opaque)
4200
{
4201
    NetSocketState *s = opaque;
4202
    int size;
4203

    
4204
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4205
    if (size < 0)
4206
        return;
4207
    if (size == 0) {
4208
        /* end of connection */
4209
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4210
        return;
4211
    }
4212
    qemu_send_packet(s->vc, s->buf, size);
4213
}
4214

    
4215
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4216
{
4217
    struct ip_mreq imr;
4218
    int fd;
4219
    int val, ret;
4220
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4221
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4222
                inet_ntoa(mcastaddr->sin_addr),
4223
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4224
        return -1;
4225

    
4226
    }
4227
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4228
    if (fd < 0) {
4229
        perror("socket(PF_INET, SOCK_DGRAM)");
4230
        return -1;
4231
    }
4232

    
4233
    val = 1;
4234
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4235
                   (const char *)&val, sizeof(val));
4236
    if (ret < 0) {
4237
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4238
        goto fail;
4239
    }
4240

    
4241
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4242
    if (ret < 0) {
4243
        perror("bind");
4244
        goto fail;
4245
    }
4246

    
4247
    /* Add host to multicast group */
4248
    imr.imr_multiaddr = mcastaddr->sin_addr;
4249
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4250

    
4251
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4252
                     (const char *)&imr, sizeof(struct ip_mreq));
4253
    if (ret < 0) {
4254
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4255
        goto fail;
4256
    }
4257

    
4258
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4259
    val = 1;
4260
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4261
                   (const char *)&val, sizeof(val));
4262
    if (ret < 0) {
4263
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4264
        goto fail;
4265
    }
4266

    
4267
    socket_set_nonblock(fd);
4268
    return fd;
4269
fail:
4270
    if (fd >= 0)
4271
        closesocket(fd);
4272
    return -1;
4273
}
4274

    
4275
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4276
                                          int is_connected)
4277
{
4278
    struct sockaddr_in saddr;
4279
    int newfd;
4280
    socklen_t saddr_len;
4281
    NetSocketState *s;
4282

    
4283
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4284
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4285
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4286
     */
4287

    
4288
    if (is_connected) {
4289
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4290
            /* must be bound */
4291
            if (saddr.sin_addr.s_addr==0) {
4292
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4293
                        fd);
4294
                return NULL;
4295
            }
4296
            /* clone dgram socket */
4297
            newfd = net_socket_mcast_create(&saddr);
4298
            if (newfd < 0) {
4299
                /* error already reported by net_socket_mcast_create() */
4300
                close(fd);
4301
                return NULL;
4302
            }
4303
            /* clone newfd to fd, close newfd */
4304
            dup2(newfd, fd);
4305
            close(newfd);
4306

    
4307
        } else {
4308
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4309
                    fd, strerror(errno));
4310
            return NULL;
4311
        }
4312
    }
4313

    
4314
    s = qemu_mallocz(sizeof(NetSocketState));
4315
    if (!s)
4316
        return NULL;
4317
    s->fd = fd;
4318

    
4319
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4320
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4321

    
4322
    /* mcast: save bound address as dst */
4323
    if (is_connected) s->dgram_dst=saddr;
4324

    
4325
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4326
            "socket: fd=%d (%s mcast=%s:%d)",
4327
            fd, is_connected? "cloned" : "",
4328
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4329
    return s;
4330
}
4331

    
4332
static void net_socket_connect(void *opaque)
4333
{
4334
    NetSocketState *s = opaque;
4335
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4336
}
4337

    
4338
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4339
                                          int is_connected)
4340
{
4341
    NetSocketState *s;
4342
    s = qemu_mallocz(sizeof(NetSocketState));
4343
    if (!s)
4344
        return NULL;
4345
    s->fd = fd;
4346
    s->vc = qemu_new_vlan_client(vlan,
4347
                                 net_socket_receive, NULL, s);
4348
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4349
             "socket: fd=%d", fd);
4350
    if (is_connected) {
4351
        net_socket_connect(s);
4352
    } else {
4353
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4354
    }
4355
    return s;
4356
}
4357

    
4358
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4359
                                          int is_connected)
4360
{
4361
    int so_type=-1, optlen=sizeof(so_type);
4362

    
4363
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4364
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4365
        return NULL;
4366
    }
4367
    switch(so_type) {
4368
    case SOCK_DGRAM:
4369
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4370
    case SOCK_STREAM:
4371
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4372
    default:
4373
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4374
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4375
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4376
    }
4377
    return NULL;
4378
}
4379

    
4380
static void net_socket_accept(void *opaque)
4381
{
4382
    NetSocketListenState *s = opaque;
4383
    NetSocketState *s1;
4384
    struct sockaddr_in saddr;
4385
    socklen_t len;
4386
    int fd;
4387

    
4388
    for(;;) {
4389
        len = sizeof(saddr);
4390
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4391
        if (fd < 0 && errno != EINTR) {
4392
            return;
4393
        } else if (fd >= 0) {
4394
            break;
4395
        }
4396
    }
4397
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4398
    if (!s1) {
4399
        closesocket(fd);
4400
    } else {
4401
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4402
                 "socket: connection from %s:%d",
4403
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4404
    }
4405
}
4406

    
4407
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4408
{
4409
    NetSocketListenState *s;
4410
    int fd, val, ret;
4411
    struct sockaddr_in saddr;
4412

    
4413
    if (parse_host_port(&saddr, host_str) < 0)
4414
        return -1;
4415

    
4416
    s = qemu_mallocz(sizeof(NetSocketListenState));
4417
    if (!s)
4418
        return -1;
4419

    
4420
    fd = socket(PF_INET, SOCK_STREAM, 0);
4421
    if (fd < 0) {
4422
        perror("socket");
4423
        return -1;
4424
    }
4425
    socket_set_nonblock(fd);
4426

    
4427
    /* allow fast reuse */
4428
    val = 1;
4429
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4430

    
4431
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4432
    if (ret < 0) {
4433
        perror("bind");
4434
        return -1;
4435
    }
4436
    ret = listen(fd, 0);
4437
    if (ret < 0) {
4438
        perror("listen");
4439
        return -1;
4440
    }
4441
    s->vlan = vlan;
4442
    s->fd = fd;
4443
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4444
    return 0;
4445
}
4446

    
4447
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4448
{
4449
    NetSocketState *s;
4450
    int fd, connected, ret, err;
4451
    struct sockaddr_in saddr;
4452

    
4453
    if (parse_host_port(&saddr, host_str) < 0)
4454
        return -1;
4455

    
4456
    fd = socket(PF_INET, SOCK_STREAM, 0);
4457
    if (fd < 0) {
4458
        perror("socket");
4459
        return -1;
4460
    }
4461
    socket_set_nonblock(fd);
4462

    
4463
    connected = 0;
4464
    for(;;) {
4465
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4466
        if (ret < 0) {
4467
            err = socket_error();
4468
            if (err == EINTR || err == EWOULDBLOCK) {
4469
            } else if (err == EINPROGRESS) {
4470
                break;
4471
#ifdef _WIN32
4472
            } else if (err == WSAEALREADY) {
4473
                break;
4474
#endif
4475
            } else {
4476
                perror("connect");
4477
                closesocket(fd);
4478
                return -1;
4479
            }
4480
        } else {
4481
            connected = 1;
4482
            break;
4483
        }
4484
    }
4485
    s = net_socket_fd_init(vlan, fd, connected);
4486
    if (!s)
4487
        return -1;
4488
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4489
             "socket: connect to %s:%d",
4490
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4491
    return 0;
4492
}
4493

    
4494
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4495
{
4496
    NetSocketState *s;
4497
    int fd;
4498
    struct sockaddr_in saddr;
4499

    
4500
    if (parse_host_port(&saddr, host_str) < 0)
4501
        return -1;
4502

    
4503

    
4504
    fd = net_socket_mcast_create(&saddr);
4505
    if (fd < 0)
4506
        return -1;
4507

    
4508
    s = net_socket_fd_init(vlan, fd, 0);
4509
    if (!s)
4510
        return -1;
4511

    
4512
    s->dgram_dst = saddr;
4513

    
4514
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4515
             "socket: mcast=%s:%d",
4516
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4517
    return 0;
4518

    
4519
}
4520

    
4521
static int get_param_value(char *buf, int buf_size,
4522
                           const char *tag, const char *str)
4523
{
4524
    const char *p;
4525
    char *q;
4526
    char option[128];
4527

    
4528
    p = str;
4529
    for(;;) {
4530
        q = option;
4531
        while (*p != '\0' && *p != '=') {
4532
            if ((q - option) < sizeof(option) - 1)
4533
                *q++ = *p;
4534
            p++;
4535
        }
4536
        *q = '\0';
4537
        if (*p != '=')
4538
            break;
4539
        p++;
4540
        if (!strcmp(tag, option)) {
4541
            q = buf;
4542
            while (*p != '\0' && *p != ',') {
4543
                if ((q - buf) < buf_size - 1)
4544
                    *q++ = *p;
4545
                p++;
4546
            }
4547
            *q = '\0';
4548
            return q - buf;
4549
        } else {
4550
            while (*p != '\0' && *p != ',') {
4551
                p++;
4552
            }
4553
        }
4554
        if (*p != ',')
4555
            break;
4556
        p++;
4557
    }
4558
    return 0;
4559
}
4560

    
4561
static int net_client_init(const char *str)
4562
{
4563
    const char *p;
4564
    char *q;
4565
    char device[64];
4566
    char buf[1024];
4567
    int vlan_id, ret;
4568
    VLANState *vlan;
4569

    
4570
    p = str;
4571
    q = device;
4572
    while (*p != '\0' && *p != ',') {
4573
        if ((q - device) < sizeof(device) - 1)
4574
            *q++ = *p;
4575
        p++;
4576
    }
4577
    *q = '\0';
4578
    if (*p == ',')
4579
        p++;
4580
    vlan_id = 0;
4581
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4582
        vlan_id = strtol(buf, NULL, 0);
4583
    }
4584
    vlan = qemu_find_vlan(vlan_id);
4585
    if (!vlan) {
4586
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4587
        return -1;
4588
    }
4589
    if (!strcmp(device, "nic")) {
4590
        NICInfo *nd;
4591
        uint8_t *macaddr;
4592

    
4593
        if (nb_nics >= MAX_NICS) {
4594
            fprintf(stderr, "Too Many NICs\n");
4595
            return -1;
4596
        }
4597
        nd = &nd_table[nb_nics];
4598
        macaddr = nd->macaddr;
4599
        macaddr[0] = 0x52;
4600
        macaddr[1] = 0x54;
4601
        macaddr[2] = 0x00;
4602
        macaddr[3] = 0x12;
4603
        macaddr[4] = 0x34;
4604
        macaddr[5] = 0x56 + nb_nics;
4605

    
4606
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4607
            if (parse_macaddr(macaddr, buf) < 0) {
4608
                fprintf(stderr, "invalid syntax for ethernet address\n");
4609
                return -1;
4610
            }
4611
        }
4612
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4613
            nd->model = strdup(buf);
4614
        }
4615
        nd->vlan = vlan;
4616
        nb_nics++;
4617
        vlan->nb_guest_devs++;
4618
        ret = 0;
4619
    } else
4620
    if (!strcmp(device, "none")) {
4621
        /* does nothing. It is needed to signal that no network cards
4622
           are wanted */
4623
        ret = 0;
4624
    } else
4625
#ifdef CONFIG_SLIRP
4626
    if (!strcmp(device, "user")) {
4627
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4628
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4629
        }
4630
        vlan->nb_host_devs++;
4631
        ret = net_slirp_init(vlan);
4632
    } else
4633
#endif
4634
#ifdef _WIN32
4635
    if (!strcmp(device, "tap")) {
4636
        char ifname[64];
4637
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4638
            fprintf(stderr, "tap: no interface name\n");
4639
            return -1;
4640
        }
4641
        vlan->nb_host_devs++;
4642
        ret = tap_win32_init(vlan, ifname);
4643
    } else
4644
#else
4645
    if (!strcmp(device, "tap")) {
4646
        char ifname[64];
4647
        char setup_script[1024], down_script[1024];
4648
        int fd;
4649
        vlan->nb_host_devs++;
4650
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4651
            fd = strtol(buf, NULL, 0);
4652
            ret = -1;
4653
            if (net_tap_fd_init(vlan, fd))
4654
                ret = 0;
4655
        } else {
4656
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4657
                ifname[0] = '\0';
4658
            }
4659
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4660
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4661
            }
4662
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4663
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4664
            }
4665
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
4666
        }
4667
    } else
4668
#endif
4669
    if (!strcmp(device, "socket")) {
4670
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4671
            int fd;
4672
            fd = strtol(buf, NULL, 0);
4673
            ret = -1;
4674
            if (net_socket_fd_init(vlan, fd, 1))
4675
                ret = 0;
4676
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4677
            ret = net_socket_listen_init(vlan, buf);
4678
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4679
            ret = net_socket_connect_init(vlan, buf);
4680
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4681
            ret = net_socket_mcast_init(vlan, buf);
4682
        } else {
4683
            fprintf(stderr, "Unknown socket options: %s\n", p);
4684
            return -1;
4685
        }
4686
        vlan->nb_host_devs++;
4687
    } else
4688
    {
4689
        fprintf(stderr, "Unknown network device: %s\n", device);
4690
        return -1;
4691
    }
4692
    if (ret < 0) {
4693
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4694
    }
4695

    
4696
    return ret;
4697
}
4698

    
4699
void do_info_network(void)
4700
{
4701
    VLANState *vlan;
4702
    VLANClientState *vc;
4703

    
4704
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4705
        term_printf("VLAN %d devices:\n", vlan->id);
4706
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4707
            term_printf("  %s\n", vc->info_str);
4708
    }
4709
}
4710

    
4711
/***********************************************************/
4712
/* USB devices */
4713

    
4714
static USBPort *used_usb_ports;
4715
static USBPort *free_usb_ports;
4716

    
4717
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4718
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4719
                            usb_attachfn attach)
4720
{
4721
    port->opaque = opaque;
4722
    port->index = index;
4723
    port->attach = attach;
4724
    port->next = free_usb_ports;
4725
    free_usb_ports = port;
4726
}
4727

    
4728
static int usb_device_add(const char *devname)
4729
{
4730
    const char *p;
4731
    USBDevice *dev;
4732
    USBPort *port;
4733

    
4734
    if (!free_usb_ports)
4735
        return -1;
4736

    
4737
    if (strstart(devname, "host:", &p)) {
4738
        dev = usb_host_device_open(p);
4739
    } else if (!strcmp(devname, "mouse")) {
4740
        dev = usb_mouse_init();
4741
    } else if (!strcmp(devname, "tablet")) {
4742
        dev = usb_tablet_init();
4743
    } else if (!strcmp(devname, "keyboard")) {
4744
        dev = usb_keyboard_init();
4745
    } else if (strstart(devname, "disk:", &p)) {
4746
        dev = usb_msd_init(p);
4747
    } else if (!strcmp(devname, "wacom-tablet")) {
4748
        dev = usb_wacom_init();
4749
    } else {
4750
        return -1;
4751
    }
4752
    if (!dev)
4753
        return -1;
4754

    
4755
    /* Find a USB port to add the device to.  */
4756
    port = free_usb_ports;
4757
    if (!port->next) {
4758
        USBDevice *hub;
4759

    
4760
        /* Create a new hub and chain it on.  */
4761
        free_usb_ports = NULL;
4762
        port->next = used_usb_ports;
4763
        used_usb_ports = port;
4764

    
4765
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4766
        usb_attach(port, hub);
4767
        port = free_usb_ports;
4768
    }
4769

    
4770
    free_usb_ports = port->next;
4771
    port->next = used_usb_ports;
4772
    used_usb_ports = port;
4773
    usb_attach(port, dev);
4774
    return 0;
4775
}
4776

    
4777
static int usb_device_del(const char *devname)
4778
{
4779
    USBPort *port;
4780
    USBPort **lastp;
4781
    USBDevice *dev;
4782
    int bus_num, addr;
4783
    const char *p;
4784

    
4785
    if (!used_usb_ports)
4786
        return -1;
4787

    
4788
    p = strchr(devname, '.');
4789
    if (!p)
4790
        return -1;
4791
    bus_num = strtoul(devname, NULL, 0);
4792
    addr = strtoul(p + 1, NULL, 0);
4793
    if (bus_num != 0)
4794
        return -1;
4795

    
4796
    lastp = &used_usb_ports;
4797
    port = used_usb_ports;
4798
    while (port && port->dev->addr != addr) {
4799
        lastp = &port->next;
4800
        port = port->next;
4801
    }
4802

    
4803
    if (!port)
4804
        return -1;
4805

    
4806
    dev = port->dev;
4807
    *lastp = port->next;
4808
    usb_attach(port, NULL);
4809
    dev->handle_destroy(dev);
4810
    port->next = free_usb_ports;
4811
    free_usb_ports = port;
4812
    return 0;
4813
}
4814

    
4815
void do_usb_add(const char *devname)
4816
{
4817
    int ret;
4818
    ret = usb_device_add(devname);
4819
    if (ret < 0)
4820
        term_printf("Could not add USB device '%s'\n", devname);
4821
}
4822

    
4823
void do_usb_del(const char *devname)
4824
{
4825
    int ret;
4826
    ret = usb_device_del(devname);
4827
    if (ret < 0)
4828
        term_printf("Could not remove USB device '%s'\n", devname);
4829
}
4830

    
4831
void usb_info(void)
4832
{
4833
    USBDevice *dev;
4834
    USBPort *port;
4835
    const char *speed_str;
4836

    
4837
    if (!usb_enabled) {
4838
        term_printf("USB support not enabled\n");
4839
        return;
4840
    }
4841

    
4842
    for (port = used_usb_ports; port; port = port->next) {
4843
        dev = port->dev;
4844
        if (!dev)
4845
            continue;
4846
        switch(dev->speed) {
4847
        case USB_SPEED_LOW:
4848
            speed_str = "1.5";
4849
            break;
4850
        case USB_SPEED_FULL:
4851
            speed_str = "12";
4852
            break;
4853
        case USB_SPEED_HIGH:
4854
            speed_str = "480";
4855
            break;
4856
        default:
4857
            speed_str = "?";
4858
            break;
4859
        }
4860
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
4861
                    0, dev->addr, speed_str, dev->devname);
4862
    }
4863
}
4864

    
4865
/***********************************************************/
4866
/* PCMCIA/Cardbus */
4867

    
4868
static struct pcmcia_socket_entry_s {
4869
    struct pcmcia_socket_s *socket;
4870
    struct pcmcia_socket_entry_s *next;
4871
} *pcmcia_sockets = 0;
4872

    
4873
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4874
{
4875
    struct pcmcia_socket_entry_s *entry;
4876

    
4877
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4878
    entry->socket = socket;
4879
    entry->next = pcmcia_sockets;
4880
    pcmcia_sockets = entry;
4881
}
4882

    
4883
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4884
{
4885
    struct pcmcia_socket_entry_s *entry, **ptr;
4886

    
4887
    ptr = &pcmcia_sockets;
4888
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4889
        if (entry->socket == socket) {
4890
            *ptr = entry->next;
4891
            qemu_free(entry);
4892
        }
4893
}
4894

    
4895
void pcmcia_info(void)
4896
{
4897
    struct pcmcia_socket_entry_s *iter;
4898
    if (!pcmcia_sockets)
4899
        term_printf("No PCMCIA sockets\n");
4900

    
4901
    for (iter = pcmcia_sockets; iter; iter = iter->next)
4902
        term_printf("%s: %s\n", iter->socket->slot_string,
4903
                    iter->socket->attached ? iter->socket->card_string :
4904
                    "Empty");
4905
}
4906

    
4907
/***********************************************************/
4908
/* dumb display */
4909

    
4910
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4911
{
4912
}
4913

    
4914
static void dumb_resize(DisplayState *ds, int w, int h)
4915
{
4916
}
4917

    
4918
static void dumb_refresh(DisplayState *ds)
4919
{
4920
#if defined(CONFIG_SDL)
4921
    vga_hw_update();
4922
#endif
4923
}
4924

    
4925
static void dumb_display_init(DisplayState *ds)
4926
{
4927
    ds->data = NULL;
4928
    ds->linesize = 0;
4929
    ds->depth = 0;
4930
    ds->dpy_update = dumb_update;
4931
    ds->dpy_resize = dumb_resize;
4932
    ds->dpy_refresh = dumb_refresh;
4933
}
4934

    
4935
/***********************************************************/
4936
/* I/O handling */
4937

    
4938
#define MAX_IO_HANDLERS 64
4939

    
4940
typedef struct IOHandlerRecord {
4941
    int fd;
4942
    IOCanRWHandler *fd_read_poll;
4943
    IOHandler *fd_read;
4944
    IOHandler *fd_write;
4945
    int deleted;
4946
    void *opaque;
4947
    /* temporary data */
4948
    struct pollfd *ufd;
4949
    struct IOHandlerRecord *next;
4950
} IOHandlerRecord;
4951

    
4952
static IOHandlerRecord *first_io_handler;
4953

    
4954
/* XXX: fd_read_poll should be suppressed, but an API change is
4955
   necessary in the character devices to suppress fd_can_read(). */
4956
int qemu_set_fd_handler2(int fd,
4957
                         IOCanRWHandler *fd_read_poll,
4958
                         IOHandler *fd_read,
4959
                         IOHandler *fd_write,
4960
                         void *opaque)
4961
{
4962
    IOHandlerRecord **pioh, *ioh;
4963

    
4964
    if (!fd_read && !fd_write) {
4965
        pioh = &first_io_handler;
4966
        for(;;) {
4967
            ioh = *pioh;
4968
            if (ioh == NULL)
4969
                break;
4970
            if (ioh->fd == fd) {
4971
                ioh->deleted = 1;
4972
                break;
4973
            }
4974
            pioh = &ioh->next;
4975
        }
4976
    } else {
4977
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4978
            if (ioh->fd == fd)
4979
                goto found;
4980
        }
4981
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4982
        if (!ioh)
4983
            return -1;
4984
        ioh->next = first_io_handler;
4985
        first_io_handler = ioh;
4986
    found:
4987
        ioh->fd = fd;
4988
        ioh->fd_read_poll = fd_read_poll;
4989
        ioh->fd_read = fd_read;
4990
        ioh->fd_write = fd_write;
4991
        ioh->opaque = opaque;
4992
        ioh->deleted = 0;
4993
    }
4994
    return 0;
4995
}
4996

    
4997
int qemu_set_fd_handler(int fd,
4998
                        IOHandler *fd_read,
4999
                        IOHandler *fd_write,
5000
                        void *opaque)
5001
{
5002
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5003
}
5004

    
5005
/***********************************************************/
5006
/* Polling handling */
5007

    
5008
typedef struct PollingEntry {
5009
    PollingFunc *func;
5010
    void *opaque;
5011
    struct PollingEntry *next;
5012
} PollingEntry;
5013

    
5014
static PollingEntry *first_polling_entry;
5015

    
5016
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5017
{
5018
    PollingEntry **ppe, *pe;
5019
    pe = qemu_mallocz(sizeof(PollingEntry));
5020
    if (!pe)
5021
        return -1;
5022
    pe->func = func;
5023
    pe->opaque = opaque;
5024
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5025
    *ppe = pe;
5026
    return 0;
5027
}
5028

    
5029
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5030
{
5031
    PollingEntry **ppe, *pe;
5032
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5033
        pe = *ppe;
5034
        if (pe->func == func && pe->opaque == opaque) {
5035
            *ppe = pe->next;
5036
            qemu_free(pe);
5037
            break;
5038
        }
5039
    }
5040
}
5041

    
5042
#ifdef _WIN32
5043
/***********************************************************/
5044
/* Wait objects support */
5045
typedef struct WaitObjects {
5046
    int num;
5047
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5048
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5049
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5050
} WaitObjects;
5051

    
5052
static WaitObjects wait_objects = {0};
5053

    
5054
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5055
{
5056
    WaitObjects *w = &wait_objects;
5057

    
5058
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
5059
        return -1;
5060
    w->events[w->num] = handle;
5061
    w->func[w->num] = func;
5062
    w->opaque[w->num] = opaque;
5063
    w->num++;
5064
    return 0;
5065
}
5066

    
5067
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5068
{
5069
    int i, found;
5070
    WaitObjects *w = &wait_objects;
5071

    
5072
    found = 0;
5073
    for (i = 0; i < w->num; i++) {
5074
        if (w->events[i] == handle)
5075
            found = 1;
5076
        if (found) {
5077
            w->events[i] = w->events[i + 1];
5078
            w->func[i] = w->func[i + 1];
5079
            w->opaque[i] = w->opaque[i + 1];
5080
        }
5081
    }
5082
    if (found)
5083
        w->num--;
5084
}
5085
#endif
5086

    
5087
/***********************************************************/
5088
/* savevm/loadvm support */
5089

    
5090
#define IO_BUF_SIZE 32768
5091

    
5092
struct QEMUFile {
5093
    FILE *outfile;
5094
    BlockDriverState *bs;
5095
    int is_file;
5096
    int is_writable;
5097
    int64_t base_offset;
5098
    int64_t buf_offset; /* start of buffer when writing, end of buffer
5099
                           when reading */
5100
    int buf_index;
5101
    int buf_size; /* 0 when writing */
5102
    uint8_t buf[IO_BUF_SIZE];
5103
};
5104

    
5105
QEMUFile *qemu_fopen(const char *filename, const char *mode)
5106
{
5107
    QEMUFile *f;
5108

    
5109
    f = qemu_mallocz(sizeof(QEMUFile));
5110
    if (!f)
5111
        return NULL;
5112
    if (!strcmp(mode, "wb")) {
5113
        f->is_writable = 1;
5114
    } else if (!strcmp(mode, "rb")) {
5115
        f->is_writable = 0;
5116
    } else {
5117
        goto fail;
5118
    }
5119
    f->outfile = fopen(filename, mode);
5120
    if (!f->outfile)
5121
        goto fail;
5122
    f->is_file = 1;
5123
    return f;
5124
 fail:
5125
    if (f->outfile)
5126
        fclose(f->outfile);
5127
    qemu_free(f);
5128
    return NULL;
5129
}
5130

    
5131
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5132
{
5133
    QEMUFile *f;
5134

    
5135
    f = qemu_mallocz(sizeof(QEMUFile));
5136
    if (!f)
5137
        return NULL;
5138
    f->is_file = 0;
5139
    f->bs = bs;
5140
    f->is_writable = is_writable;
5141
    f->base_offset = offset;
5142
    return f;
5143
}
5144

    
5145
void qemu_fflush(QEMUFile *f)
5146
{
5147
    if (!f->is_writable)
5148
        return;
5149
    if (f->buf_index > 0) {
5150
        if (f->is_file) {
5151
            fseek(f->outfile, f->buf_offset, SEEK_SET);
5152
            fwrite(f->buf, 1, f->buf_index, f->outfile);
5153
        } else {
5154
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5155
                        f->buf, f->buf_index);
5156
        }
5157
        f->buf_offset += f->buf_index;
5158
        f->buf_index = 0;
5159
    }
5160
}
5161

    
5162
static void qemu_fill_buffer(QEMUFile *f)
5163
{
5164
    int len;
5165

    
5166
    if (f->is_writable)
5167
        return;
5168
    if (f->is_file) {
5169
        fseek(f->outfile, f->buf_offset, SEEK_SET);
5170
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5171
        if (len < 0)
5172
            len = 0;
5173
    } else {
5174
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5175
                         f->buf, IO_BUF_SIZE);
5176
        if (len < 0)
5177
            len = 0;
5178
    }
5179
    f->buf_index = 0;
5180
    f->buf_size = len;
5181
    f->buf_offset += len;
5182
}
5183

    
5184
void qemu_fclose(QEMUFile *f)
5185
{
5186
    if (f->is_writable)
5187
        qemu_fflush(f);
5188
    if (f->is_file) {
5189
        fclose(f->outfile);
5190
    }
5191
    qemu_free(f);
5192
}
5193

    
5194
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5195
{
5196
    int l;
5197
    while (size > 0) {
5198
        l = IO_BUF_SIZE - f->buf_index;
5199
        if (l > size)
5200
            l = size;
5201
        memcpy(f->buf + f->buf_index, buf, l);
5202
        f->buf_index += l;
5203
        buf += l;
5204
        size -= l;
5205
        if (f->buf_index >= IO_BUF_SIZE)
5206
            qemu_fflush(f);
5207
    }
5208
}
5209

    
5210
void qemu_put_byte(QEMUFile *f, int v)
5211
{
5212
    f->buf[f->buf_index++] = v;
5213
    if (f->buf_index >= IO_BUF_SIZE)
5214
        qemu_fflush(f);
5215
}
5216

    
5217
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5218
{
5219
    int size, l;
5220

    
5221
    size = size1;
5222
    while (size > 0) {
5223
        l = f->buf_size - f->buf_index;
5224
        if (l == 0) {
5225
            qemu_fill_buffer(f);
5226
            l = f->buf_size - f->buf_index;
5227
            if (l == 0)
5228
                break;
5229
        }
5230
        if (l > size)
5231
            l = size;
5232
        memcpy(buf, f->buf + f->buf_index, l);
5233
        f->buf_index += l;
5234
        buf += l;
5235
        size -= l;
5236
    }
5237
    return size1 - size;
5238
}
5239

    
5240
int qemu_get_byte(QEMUFile *f)
5241
{
5242
    if (f->buf_index >= f->buf_size) {
5243
        qemu_fill_buffer(f);
5244
        if (f->buf_index >= f->buf_size)
5245
            return 0;
5246
    }
5247
    return f->buf[f->buf_index++];
5248
}
5249

    
5250
int64_t qemu_ftell(QEMUFile *f)
5251
{
5252
    return f->buf_offset - f->buf_size + f->buf_index;
5253
}
5254

    
5255
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5256
{
5257
    if (whence == SEEK_SET) {
5258
        /* nothing to do */
5259
    } else if (whence == SEEK_CUR) {
5260
        pos += qemu_ftell(f);
5261
    } else {
5262
        /* SEEK_END not supported */
5263
        return -1;
5264
    }
5265
    if (f->is_writable) {
5266
        qemu_fflush(f);
5267
        f->buf_offset = pos;
5268
    } else {
5269
        f->buf_offset = pos;
5270
        f->buf_index = 0;
5271
        f->buf_size = 0;
5272
    }
5273
    return pos;
5274
}
5275

    
5276
void qemu_put_be16(QEMUFile *f, unsigned int v)
5277
{
5278
    qemu_put_byte(f, v >> 8);
5279
    qemu_put_byte(f, v);
5280
}
5281

    
5282
void qemu_put_be32(QEMUFile *f, unsigned int v)
5283
{
5284
    qemu_put_byte(f, v >> 24);
5285
    qemu_put_byte(f, v >> 16);
5286
    qemu_put_byte(f, v >> 8);
5287
    qemu_put_byte(f, v);
5288
}
5289

    
5290
void qemu_put_be64(QEMUFile *f, uint64_t v)
5291
{
5292
    qemu_put_be32(f, v >> 32);
5293
    qemu_put_be32(f, v);
5294
}
5295

    
5296
unsigned int qemu_get_be16(QEMUFile *f)
5297
{
5298
    unsigned int v;
5299
    v = qemu_get_byte(f) << 8;
5300
    v |= qemu_get_byte(f);
5301
    return v;
5302
}
5303

    
5304
unsigned int qemu_get_be32(QEMUFile *f)
5305
{
5306
    unsigned int v;
5307
    v = qemu_get_byte(f) << 24;
5308
    v |= qemu_get_byte(f) << 16;
5309
    v |= qemu_get_byte(f) << 8;
5310
    v |= qemu_get_byte(f);
5311
    return v;
5312
}
5313

    
5314
uint64_t qemu_get_be64(QEMUFile *f)
5315
{
5316
    uint64_t v;
5317
    v = (uint64_t)qemu_get_be32(f) << 32;
5318
    v |= qemu_get_be32(f);
5319
    return v;
5320
}
5321

    
5322
typedef struct SaveStateEntry {
5323
    char idstr[256];
5324
    int instance_id;
5325
    int version_id;
5326
    SaveStateHandler *save_state;
5327
    LoadStateHandler *load_state;
5328
    void *opaque;
5329
    struct SaveStateEntry *next;
5330
} SaveStateEntry;
5331

    
5332
static SaveStateEntry *first_se;
5333

    
5334
int register_savevm(const char *idstr,
5335
                    int instance_id,
5336
                    int version_id,
5337
                    SaveStateHandler *save_state,
5338
                    LoadStateHandler *load_state,
5339
                    void *opaque)
5340
{
5341
    SaveStateEntry *se, **pse;
5342

    
5343
    se = qemu_malloc(sizeof(SaveStateEntry));
5344
    if (!se)
5345
        return -1;
5346
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5347
    se->instance_id = instance_id;
5348
    se->version_id = version_id;
5349
    se->save_state = save_state;
5350
    se->load_state = load_state;
5351
    se->opaque = opaque;
5352
    se->next = NULL;
5353

    
5354
    /* add at the end of list */
5355
    pse = &first_se;
5356
    while (*pse != NULL)
5357
        pse = &(*pse)->next;
5358
    *pse = se;
5359
    return 0;
5360
}
5361

    
5362
#define QEMU_VM_FILE_MAGIC   0x5145564d
5363
#define QEMU_VM_FILE_VERSION 0x00000002
5364

    
5365
static int qemu_savevm_state(QEMUFile *f)
5366
{
5367
    SaveStateEntry *se;
5368
    int len, ret;
5369
    int64_t cur_pos, len_pos, total_len_pos;
5370

    
5371
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5372
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5373
    total_len_pos = qemu_ftell(f);
5374
    qemu_put_be64(f, 0); /* total size */
5375

    
5376
    for(se = first_se; se != NULL; se = se->next) {
5377
        /* ID string */
5378
        len = strlen(se->idstr);
5379
        qemu_put_byte(f, len);
5380
        qemu_put_buffer(f, se->idstr, len);
5381

    
5382
        qemu_put_be32(f, se->instance_id);
5383
        qemu_put_be32(f, se->version_id);
5384

    
5385
        /* record size: filled later */
5386
        len_pos = qemu_ftell(f);
5387
        qemu_put_be32(f, 0);
5388
        se->save_state(f, se->opaque);
5389

    
5390
        /* fill record size */
5391
        cur_pos = qemu_ftell(f);
5392
        len = cur_pos - len_pos - 4;
5393
        qemu_fseek(f, len_pos, SEEK_SET);
5394
        qemu_put_be32(f, len);
5395
        qemu_fseek(f, cur_pos, SEEK_SET);
5396
    }
5397
    cur_pos = qemu_ftell(f);
5398
    qemu_fseek(f, total_len_pos, SEEK_SET);
5399
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
5400
    qemu_fseek(f, cur_pos, SEEK_SET);
5401

    
5402
    ret = 0;
5403
    return ret;
5404
}
5405

    
5406
static SaveStateEntry *find_se(const char *idstr, int instance_id)
5407
{
5408
    SaveStateEntry *se;
5409

    
5410
    for(se = first_se; se != NULL; se = se->next) {
5411
        if (!strcmp(se->idstr, idstr) &&
5412
            instance_id == se->instance_id)
5413
            return se;
5414
    }
5415
    return NULL;
5416
}
5417

    
5418
static int qemu_loadvm_state(QEMUFile *f)
5419
{
5420
    SaveStateEntry *se;
5421
    int len, ret, instance_id, record_len, version_id;
5422
    int64_t total_len, end_pos, cur_pos;
5423
    unsigned int v;
5424
    char idstr[256];
5425

    
5426
    v = qemu_get_be32(f);
5427
    if (v != QEMU_VM_FILE_MAGIC)
5428
        goto fail;
5429
    v = qemu_get_be32(f);
5430
    if (v != QEMU_VM_FILE_VERSION) {
5431
    fail:
5432
        ret = -1;
5433
        goto the_end;
5434
    }
5435
    total_len = qemu_get_be64(f);
5436
    end_pos = total_len + qemu_ftell(f);
5437
    for(;;) {
5438
        if (qemu_ftell(f) >= end_pos)
5439
            break;
5440
        len = qemu_get_byte(f);
5441
        qemu_get_buffer(f, idstr, len);
5442
        idstr[len] = '\0';
5443
        instance_id = qemu_get_be32(f);
5444
        version_id = qemu_get_be32(f);
5445
        record_len = qemu_get_be32(f);
5446
#if 0
5447
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
5448
               idstr, instance_id, version_id, record_len);
5449
#endif
5450
        cur_pos = qemu_ftell(f);
5451
        se = find_se(idstr, instance_id);
5452
        if (!se) {
5453
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5454
                    instance_id, idstr);
5455
        } else {
5456
            ret = se->load_state(f, se->opaque, version_id);
5457
            if (ret < 0) {
5458
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5459
                        instance_id, idstr);
5460
            }
5461
        }
5462
        /* always seek to exact end of record */
5463
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5464
    }
5465
    ret = 0;
5466
 the_end:
5467
    return ret;
5468
}
5469

    
5470
/* device can contain snapshots */
5471
static int bdrv_can_snapshot(BlockDriverState *bs)
5472
{
5473
    return (bs &&
5474
            !bdrv_is_removable(bs) &&
5475
            !bdrv_is_read_only(bs));
5476
}
5477

    
5478
/* device must be snapshots in order to have a reliable snapshot */
5479
static int bdrv_has_snapshot(BlockDriverState *bs)
5480
{
5481
    return (bs &&
5482
            !bdrv_is_removable(bs) &&
5483
            !bdrv_is_read_only(bs));
5484
}
5485

    
5486
static BlockDriverState *get_bs_snapshots(void)
5487
{
5488
    BlockDriverState *bs;
5489
    int i;
5490

    
5491
    if (bs_snapshots)
5492
        return bs_snapshots;
5493
    for(i = 0; i <= MAX_DISKS; i++) {
5494
        bs = bs_table[i];
5495
        if (bdrv_can_snapshot(bs))
5496
            goto ok;
5497
    }
5498
    return NULL;
5499
 ok:
5500
    bs_snapshots = bs;
5501
    return bs;
5502
}
5503

    
5504
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5505
                              const char *name)
5506
{
5507
    QEMUSnapshotInfo *sn_tab, *sn;
5508
    int nb_sns, i, ret;
5509

    
5510
    ret = -ENOENT;
5511
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5512
    if (nb_sns < 0)
5513
        return ret;
5514
    for(i = 0; i < nb_sns; i++) {
5515
        sn = &sn_tab[i];
5516
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5517
            *sn_info = *sn;
5518
            ret = 0;
5519
            break;
5520
        }
5521
    }
5522
    qemu_free(sn_tab);
5523
    return ret;
5524
}
5525

    
5526
void do_savevm(const char *name)
5527
{
5528
    BlockDriverState *bs, *bs1;
5529
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5530
    int must_delete, ret, i;
5531
    BlockDriverInfo bdi1, *bdi = &bdi1;
5532
    QEMUFile *f;
5533
    int saved_vm_running;
5534
#ifdef _WIN32
5535
    struct _timeb tb;
5536
#else
5537
    struct timeval tv;
5538
#endif
5539

    
5540
    bs = get_bs_snapshots();
5541
    if (!bs) {
5542
        term_printf("No block device can accept snapshots\n");
5543
        return;
5544
    }
5545

    
5546
    /* ??? Should this occur after vm_stop?  */
5547
    qemu_aio_flush();
5548

    
5549
    saved_vm_running = vm_running;
5550
    vm_stop(0);
5551

    
5552
    must_delete = 0;
5553
    if (name) {
5554
        ret = bdrv_snapshot_find(bs, old_sn, name);
5555
        if (ret >= 0) {
5556
            must_delete = 1;
5557
        }
5558
    }
5559
    memset(sn, 0, sizeof(*sn));
5560
    if (must_delete) {
5561
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5562
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5563
    } else {
5564
        if (name)
5565
            pstrcpy(sn->name, sizeof(sn->name), name);
5566
    }
5567

    
5568
    /* fill auxiliary fields */
5569
#ifdef _WIN32
5570
    _ftime(&tb);
5571
    sn->date_sec = tb.time;
5572
    sn->date_nsec = tb.millitm * 1000000;
5573
#else
5574
    gettimeofday(&tv, NULL);
5575
    sn->date_sec = tv.tv_sec;
5576
    sn->date_nsec = tv.tv_usec * 1000;
5577
#endif
5578
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5579

    
5580
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5581
        term_printf("Device %s does not support VM state snapshots\n",
5582
                    bdrv_get_device_name(bs));
5583
        goto the_end;
5584
    }
5585

    
5586
    /* save the VM state */
5587
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5588
    if (!f) {
5589
        term_printf("Could not open VM state file\n");
5590
        goto the_end;
5591
    }
5592
    ret = qemu_savevm_state(f);
5593
    sn->vm_state_size = qemu_ftell(f);
5594
    qemu_fclose(f);
5595
    if (ret < 0) {
5596
        term_printf("Error %d while writing VM\n", ret);
5597
        goto the_end;
5598
    }
5599

    
5600
    /* create the snapshots */
5601

    
5602
    for(i = 0; i < MAX_DISKS; i++) {
5603
        bs1 = bs_table[i];
5604
        if (bdrv_has_snapshot(bs1)) {
5605
            if (must_delete) {
5606
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5607
                if (ret < 0) {
5608
                    term_printf("Error while deleting snapshot on '%s'\n",
5609
                                bdrv_get_device_name(bs1));
5610
                }
5611
            }
5612
            ret = bdrv_snapshot_create(bs1, sn);
5613
            if (ret < 0) {
5614
                term_printf("Error while creating snapshot on '%s'\n",
5615
                            bdrv_get_device_name(bs1));
5616
            }
5617
        }
5618
    }
5619

    
5620
 the_end:
5621
    if (saved_vm_running)
5622
        vm_start();
5623
}
5624

    
5625
void do_loadvm(const char *name)
5626
{
5627
    BlockDriverState *bs, *bs1;
5628
    BlockDriverInfo bdi1, *bdi = &bdi1;
5629
    QEMUFile *f;
5630
    int i, ret;
5631
    int saved_vm_running;
5632

    
5633
    bs = get_bs_snapshots();
5634
    if (!bs) {
5635
        term_printf("No block device supports snapshots\n");
5636
        return;
5637
    }
5638

    
5639
    /* Flush all IO requests so they don't interfere with the new state.  */
5640
    qemu_aio_flush();
5641

    
5642
    saved_vm_running = vm_running;
5643
    vm_stop(0);
5644

    
5645
    for(i = 0; i <= MAX_DISKS; i++) {
5646
        bs1 = bs_table[i];
5647
        if (bdrv_has_snapshot(bs1)) {
5648
            ret = bdrv_snapshot_goto(bs1, name);
5649
            if (ret < 0) {
5650
                if (bs != bs1)
5651
                    term_printf("Warning: ");
5652
                switch(ret) {
5653
                case -ENOTSUP:
5654
                    term_printf("Snapshots not supported on device '%s'\n",
5655
                                bdrv_get_device_name(bs1));
5656
                    break;
5657
                case -ENOENT:
5658
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
5659
                                name, bdrv_get_device_name(bs1));
5660
                    break;
5661
                default:
5662
                    term_printf("Error %d while activating snapshot on '%s'\n",
5663
                                ret, bdrv_get_device_name(bs1));
5664
                    break;
5665
                }
5666
                /* fatal on snapshot block device */
5667
                if (bs == bs1)
5668
                    goto the_end;
5669
            }
5670
        }
5671
    }
5672

    
5673
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5674
        term_printf("Device %s does not support VM state snapshots\n",
5675
                    bdrv_get_device_name(bs));
5676
        return;
5677
    }
5678

    
5679
    /* restore the VM state */
5680
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5681
    if (!f) {
5682
        term_printf("Could not open VM state file\n");
5683
        goto the_end;
5684
    }
5685
    ret = qemu_loadvm_state(f);
5686
    qemu_fclose(f);
5687
    if (ret < 0) {
5688
        term_printf("Error %d while loading VM state\n", ret);
5689
    }
5690
 the_end:
5691
    if (saved_vm_running)
5692
        vm_start();
5693
}
5694

    
5695
void do_delvm(const char *name)
5696
{
5697
    BlockDriverState *bs, *bs1;
5698
    int i, ret;
5699

    
5700
    bs = get_bs_snapshots();
5701
    if (!bs) {
5702
        term_printf("No block device supports snapshots\n");
5703
        return;
5704
    }
5705

    
5706
    for(i = 0; i <= MAX_DISKS; i++) {
5707
        bs1 = bs_table[i];
5708
        if (bdrv_has_snapshot(bs1)) {
5709
            ret = bdrv_snapshot_delete(bs1, name);
5710
            if (ret < 0) {
5711
                if (ret == -ENOTSUP)
5712
                    term_printf("Snapshots not supported on device '%s'\n",
5713
                                bdrv_get_device_name(bs1));
5714
                else
5715
                    term_printf("Error %d while deleting snapshot on '%s'\n",
5716
                                ret, bdrv_get_device_name(bs1));
5717
            }
5718
        }
5719
    }
5720
}
5721

    
5722
void do_info_snapshots(void)
5723
{
5724
    BlockDriverState *bs, *bs1;
5725
    QEMUSnapshotInfo *sn_tab, *sn;
5726
    int nb_sns, i;
5727
    char buf[256];
5728

    
5729
    bs = get_bs_snapshots();
5730
    if (!bs) {
5731
        term_printf("No available block device supports snapshots\n");
5732
        return;
5733
    }
5734
    term_printf("Snapshot devices:");
5735
    for(i = 0; i <= MAX_DISKS; i++) {
5736
        bs1 = bs_table[i];
5737
        if (bdrv_has_snapshot(bs1)) {
5738
            if (bs == bs1)
5739
                term_printf(" %s", bdrv_get_device_name(bs1));
5740
        }
5741
    }
5742
    term_printf("\n");
5743

    
5744
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5745
    if (nb_sns < 0) {
5746
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5747
        return;
5748
    }
5749
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5750
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5751
    for(i = 0; i < nb_sns; i++) {
5752
        sn = &sn_tab[i];
5753
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5754
    }
5755
    qemu_free(sn_tab);
5756
}
5757

    
5758
/***********************************************************/
5759
/* cpu save/restore */
5760

    
5761
#if defined(TARGET_I386)
5762

    
5763
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5764
{
5765
    qemu_put_be32(f, dt->selector);
5766
    qemu_put_betl(f, dt->base);
5767
    qemu_put_be32(f, dt->limit);
5768
    qemu_put_be32(f, dt->flags);
5769
}
5770

    
5771
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5772
{
5773
    dt->selector = qemu_get_be32(f);
5774
    dt->base = qemu_get_betl(f);
5775
    dt->limit = qemu_get_be32(f);
5776
    dt->flags = qemu_get_be32(f);
5777
}
5778

    
5779
void cpu_save(QEMUFile *f, void *opaque)
5780
{
5781
    CPUState *env = opaque;
5782
    uint16_t fptag, fpus, fpuc, fpregs_format;
5783
    uint32_t hflags;
5784
    int i;
5785

    
5786
    for(i = 0; i < CPU_NB_REGS; i++)
5787
        qemu_put_betls(f, &env->regs[i]);
5788
    qemu_put_betls(f, &env->eip);
5789
    qemu_put_betls(f, &env->eflags);
5790
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5791
    qemu_put_be32s(f, &hflags);
5792

    
5793
    /* FPU */
5794
    fpuc = env->fpuc;
5795
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5796
    fptag = 0;
5797
    for(i = 0; i < 8; i++) {
5798
        fptag |= ((!env->fptags[i]) << i);
5799
    }
5800

    
5801
    qemu_put_be16s(f, &fpuc);
5802
    qemu_put_be16s(f, &fpus);
5803
    qemu_put_be16s(f, &fptag);
5804

    
5805
#ifdef USE_X86LDOUBLE
5806
    fpregs_format = 0;
5807
#else
5808
    fpregs_format = 1;
5809
#endif
5810
    qemu_put_be16s(f, &fpregs_format);
5811

    
5812
    for(i = 0; i < 8; i++) {
5813
#ifdef USE_X86LDOUBLE
5814
        {
5815
            uint64_t mant;
5816
            uint16_t exp;
5817
            /* we save the real CPU data (in case of MMX usage only 'mant'
5818
               contains the MMX register */
5819
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5820
            qemu_put_be64(f, mant);
5821
            qemu_put_be16(f, exp);
5822
        }
5823
#else
5824
        /* if we use doubles for float emulation, we save the doubles to
5825
           avoid losing information in case of MMX usage. It can give
5826
           problems if the image is restored on a CPU where long
5827
           doubles are used instead. */
5828
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5829
#endif
5830
    }
5831

    
5832
    for(i = 0; i < 6; i++)
5833
        cpu_put_seg(f, &env->segs[i]);
5834
    cpu_put_seg(f, &env->ldt);
5835
    cpu_put_seg(f, &env->tr);
5836
    cpu_put_seg(f, &env->gdt);
5837
    cpu_put_seg(f, &env->idt);
5838

    
5839
    qemu_put_be32s(f, &env->sysenter_cs);
5840
    qemu_put_be32s(f, &env->sysenter_esp);
5841
    qemu_put_be32s(f, &env->sysenter_eip);
5842

    
5843
    qemu_put_betls(f, &env->cr[0]);
5844
    qemu_put_betls(f, &env->cr[2]);
5845
    qemu_put_betls(f, &env->cr[3]);
5846
    qemu_put_betls(f, &env->cr[4]);
5847

    
5848
    for(i = 0; i < 8; i++)
5849
        qemu_put_betls(f, &env->dr[i]);
5850

    
5851
    /* MMU */
5852
    qemu_put_be32s(f, &env->a20_mask);
5853

    
5854
    /* XMM */
5855
    qemu_put_be32s(f, &env->mxcsr);
5856
    for(i = 0; i < CPU_NB_REGS; i++) {
5857
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5858
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5859
    }
5860

    
5861
#ifdef TARGET_X86_64
5862
    qemu_put_be64s(f, &env->efer);
5863
    qemu_put_be64s(f, &env->star);
5864
    qemu_put_be64s(f, &env->lstar);
5865
    qemu_put_be64s(f, &env->cstar);
5866
    qemu_put_be64s(f, &env->fmask);
5867
    qemu_put_be64s(f, &env->kernelgsbase);
5868
#endif
5869
    qemu_put_be32s(f, &env->smbase);
5870
}
5871

    
5872
#ifdef USE_X86LDOUBLE
5873
/* XXX: add that in a FPU generic layer */
5874
union x86_longdouble {
5875
    uint64_t mant;
5876
    uint16_t exp;
5877
};
5878

    
5879
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5880
#define EXPBIAS1 1023
5881
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5882
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5883

    
5884
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5885
{
5886
    int e;
5887
    /* mantissa */
5888
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5889
    /* exponent + sign */
5890
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5891
    e |= SIGND1(temp) >> 16;
5892
    p->exp = e;
5893
}
5894
#endif
5895

    
5896
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5897
{
5898
    CPUState *env = opaque;
5899
    int i, guess_mmx;
5900
    uint32_t hflags;
5901
    uint16_t fpus, fpuc, fptag, fpregs_format;
5902

    
5903
    if (version_id != 3 && version_id != 4)
5904
        return -EINVAL;
5905
    for(i = 0; i < CPU_NB_REGS; i++)
5906
        qemu_get_betls(f, &env->regs[i]);
5907
    qemu_get_betls(f, &env->eip);
5908
    qemu_get_betls(f, &env->eflags);
5909
    qemu_get_be32s(f, &hflags);
5910

    
5911
    qemu_get_be16s(f, &fpuc);
5912
    qemu_get_be16s(f, &fpus);
5913
    qemu_get_be16s(f, &fptag);
5914
    qemu_get_be16s(f, &fpregs_format);
5915

    
5916
    /* NOTE: we cannot always restore the FPU state if the image come
5917
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5918
       if we are in an MMX state to restore correctly in that case. */
5919
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5920
    for(i = 0; i < 8; i++) {
5921
        uint64_t mant;
5922
        uint16_t exp;
5923

    
5924
        switch(fpregs_format) {
5925
        case 0:
5926
            mant = qemu_get_be64(f);
5927
            exp = qemu_get_be16(f);
5928
#ifdef USE_X86LDOUBLE
5929
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5930
#else
5931
            /* difficult case */
5932
            if (guess_mmx)
5933
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5934
            else
5935
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5936
#endif
5937
            break;
5938
        case 1:
5939
            mant = qemu_get_be64(f);
5940
#ifdef USE_X86LDOUBLE
5941
            {
5942
                union x86_longdouble *p;
5943
                /* difficult case */
5944
                p = (void *)&env->fpregs[i];
5945
                if (guess_mmx) {
5946
                    p->mant = mant;
5947
                    p->exp = 0xffff;
5948
                } else {
5949
                    fp64_to_fp80(p, mant);
5950
                }
5951
            }
5952
#else
5953
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5954
#endif
5955
            break;
5956
        default:
5957
            return -EINVAL;
5958
        }
5959
    }
5960

    
5961
    env->fpuc = fpuc;
5962
    /* XXX: restore FPU round state */
5963
    env->fpstt = (fpus >> 11) & 7;
5964
    env->fpus = fpus & ~0x3800;
5965
    fptag ^= 0xff;
5966
    for(i = 0; i < 8; i++) {
5967
        env->fptags[i] = (fptag >> i) & 1;
5968
    }
5969

    
5970
    for(i = 0; i < 6; i++)
5971
        cpu_get_seg(f, &env->segs[i]);
5972
    cpu_get_seg(f, &env->ldt);
5973
    cpu_get_seg(f, &env->tr);
5974
    cpu_get_seg(f, &env->gdt);
5975
    cpu_get_seg(f, &env->idt);
5976

    
5977
    qemu_get_be32s(f, &env->sysenter_cs);
5978
    qemu_get_be32s(f, &env->sysenter_esp);
5979
    qemu_get_be32s(f, &env->sysenter_eip);
5980

    
5981
    qemu_get_betls(f, &env->cr[0]);
5982
    qemu_get_betls(f, &env->cr[2]);
5983
    qemu_get_betls(f, &env->cr[3]);
5984
    qemu_get_betls(f, &env->cr[4]);
5985

    
5986
    for(i = 0; i < 8; i++)
5987
        qemu_get_betls(f, &env->dr[i]);
5988

    
5989
    /* MMU */
5990
    qemu_get_be32s(f, &env->a20_mask);
5991

    
5992
    qemu_get_be32s(f, &env->mxcsr);
5993
    for(i = 0; i < CPU_NB_REGS; i++) {
5994
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5995
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5996
    }
5997

    
5998
#ifdef TARGET_X86_64
5999
    qemu_get_be64s(f, &env->efer);
6000
    qemu_get_be64s(f, &env->star);
6001
    qemu_get_be64s(f, &env->lstar);
6002
    qemu_get_be64s(f, &env->cstar);
6003
    qemu_get_be64s(f, &env->fmask);
6004
    qemu_get_be64s(f, &env->kernelgsbase);
6005
#endif
6006
    if (version_id >= 4)
6007
        qemu_get_be32s(f, &env->smbase);
6008

    
6009
    /* XXX: compute hflags from scratch, except for CPL and IIF */
6010
    env->hflags = hflags;
6011
    tlb_flush(env, 1);
6012
    return 0;
6013
}
6014

    
6015
#elif defined(TARGET_PPC)
6016
void cpu_save(QEMUFile *f, void *opaque)
6017
{
6018
}
6019

    
6020
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6021
{
6022
    return 0;
6023
}
6024

    
6025
#elif defined(TARGET_MIPS)
6026
void cpu_save(QEMUFile *f, void *opaque)
6027
{
6028
}
6029

    
6030
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6031
{
6032
    return 0;
6033
}
6034

    
6035
#elif defined(TARGET_SPARC)
6036
void cpu_save(QEMUFile *f, void *opaque)
6037
{
6038
    CPUState *env = opaque;
6039
    int i;
6040
    uint32_t tmp;
6041

    
6042
    for(i = 0; i < 8; i++)
6043
        qemu_put_betls(f, &env->gregs[i]);
6044
    for(i = 0; i < NWINDOWS * 16; i++)
6045
        qemu_put_betls(f, &env->regbase[i]);
6046

    
6047
    /* FPU */
6048
    for(i = 0; i < TARGET_FPREGS; i++) {
6049
        union {
6050
            float32 f;
6051
            uint32_t i;
6052
        } u;
6053
        u.f = env->fpr[i];
6054
        qemu_put_be32(f, u.i);
6055
    }
6056

    
6057
    qemu_put_betls(f, &env->pc);
6058
    qemu_put_betls(f, &env->npc);
6059
    qemu_put_betls(f, &env->y);
6060
    tmp = GET_PSR(env);
6061
    qemu_put_be32(f, tmp);
6062
    qemu_put_betls(f, &env->fsr);
6063
    qemu_put_betls(f, &env->tbr);
6064
#ifndef TARGET_SPARC64
6065
    qemu_put_be32s(f, &env->wim);
6066
    /* MMU */
6067
    for(i = 0; i < 16; i++)
6068
        qemu_put_be32s(f, &env->mmuregs[i]);
6069
#endif
6070
}
6071

    
6072
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6073
{
6074
    CPUState *env = opaque;
6075
    int i;
6076
    uint32_t tmp;
6077

    
6078
    for(i = 0; i < 8; i++)
6079
        qemu_get_betls(f, &env->gregs[i]);
6080
    for(i = 0; i < NWINDOWS * 16; i++)
6081
        qemu_get_betls(f, &env->regbase[i]);
6082

    
6083
    /* FPU */
6084
    for(i = 0; i < TARGET_FPREGS; i++) {
6085
        union {
6086
            float32 f;
6087
            uint32_t i;
6088
        } u;
6089
        u.i = qemu_get_be32(f);
6090
        env->fpr[i] = u.f;
6091
    }
6092

    
6093
    qemu_get_betls(f, &env->pc);
6094
    qemu_get_betls(f, &env->npc);
6095
    qemu_get_betls(f, &env->y);
6096
    tmp = qemu_get_be32(f);
6097
    env->cwp = 0; /* needed to ensure that the wrapping registers are
6098
                     correctly updated */
6099
    PUT_PSR(env, tmp);
6100
    qemu_get_betls(f, &env->fsr);
6101
    qemu_get_betls(f, &env->tbr);
6102
#ifndef TARGET_SPARC64
6103
    qemu_get_be32s(f, &env->wim);
6104
    /* MMU */
6105
    for(i = 0; i < 16; i++)
6106
        qemu_get_be32s(f, &env->mmuregs[i]);
6107
#endif
6108
    tlb_flush(env, 1);
6109
    return 0;
6110
}
6111

    
6112
#elif defined(TARGET_ARM)
6113

    
6114
void cpu_save(QEMUFile *f, void *opaque)
6115
{
6116
    int i;
6117
    CPUARMState *env = (CPUARMState *)opaque;
6118

    
6119
    for (i = 0; i < 16; i++) {
6120
        qemu_put_be32(f, env->regs[i]);
6121
    }
6122
    qemu_put_be32(f, cpsr_read(env));
6123
    qemu_put_be32(f, env->spsr);
6124
    for (i = 0; i < 6; i++) {
6125
        qemu_put_be32(f, env->banked_spsr[i]);
6126
        qemu_put_be32(f, env->banked_r13[i]);
6127
        qemu_put_be32(f, env->banked_r14[i]);
6128
    }
6129
    for (i = 0; i < 5; i++) {
6130
        qemu_put_be32(f, env->usr_regs[i]);
6131
        qemu_put_be32(f, env->fiq_regs[i]);
6132
    }
6133
    qemu_put_be32(f, env->cp15.c0_cpuid);
6134
    qemu_put_be32(f, env->cp15.c0_cachetype);
6135
    qemu_put_be32(f, env->cp15.c1_sys);
6136
    qemu_put_be32(f, env->cp15.c1_coproc);
6137
    qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6138
    qemu_put_be32(f, env->cp15.c2_base0);
6139
    qemu_put_be32(f, env->cp15.c2_base1);
6140
    qemu_put_be32(f, env->cp15.c2_mask);
6141
    qemu_put_be32(f, env->cp15.c2_data);
6142
    qemu_put_be32(f, env->cp15.c2_insn);
6143
    qemu_put_be32(f, env->cp15.c3);
6144
    qemu_put_be32(f, env->cp15.c5_insn);
6145
    qemu_put_be32(f, env->cp15.c5_data);
6146
    for (i = 0; i < 8; i++) {
6147
        qemu_put_be32(f, env->cp15.c6_region[i]);
6148
    }
6149
    qemu_put_be32(f, env->cp15.c6_insn);
6150
    qemu_put_be32(f, env->cp15.c6_data);
6151
    qemu_put_be32(f, env->cp15.c9_insn);
6152
    qemu_put_be32(f, env->cp15.c9_data);
6153
    qemu_put_be32(f, env->cp15.c13_fcse);
6154
    qemu_put_be32(f, env->cp15.c13_context);
6155
    qemu_put_be32(f, env->cp15.c13_tls1);
6156
    qemu_put_be32(f, env->cp15.c13_tls2);
6157
    qemu_put_be32(f, env->cp15.c13_tls3);
6158
    qemu_put_be32(f, env->cp15.c15_cpar);
6159

    
6160
    qemu_put_be32(f, env->features);
6161

    
6162
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6163
        for (i = 0;  i < 16; i++) {
6164
            CPU_DoubleU u;
6165
            u.d = env->vfp.regs[i];
6166
            qemu_put_be32(f, u.l.upper);
6167
            qemu_put_be32(f, u.l.lower);
6168
        }
6169
        for (i = 0; i < 16; i++) {
6170
            qemu_put_be32(f, env->vfp.xregs[i]);
6171
        }
6172

    
6173
        /* TODO: Should use proper FPSCR access functions.  */
6174
        qemu_put_be32(f, env->vfp.vec_len);
6175
        qemu_put_be32(f, env->vfp.vec_stride);
6176

    
6177
        if (arm_feature(env, ARM_FEATURE_VFP3)) {
6178
            for (i = 16;  i < 32; i++) {
6179
                CPU_DoubleU u;
6180
                u.d = env->vfp.regs[i];
6181
                qemu_put_be32(f, u.l.upper);
6182
                qemu_put_be32(f, u.l.lower);
6183
            }
6184
        }
6185
    }
6186

    
6187
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6188
        for (i = 0; i < 16; i++) {
6189
            qemu_put_be64(f, env->iwmmxt.regs[i]);
6190
        }
6191
        for (i = 0; i < 16; i++) {
6192
            qemu_put_be32(f, env->iwmmxt.cregs[i]);
6193
        }
6194
    }
6195

    
6196
    if (arm_feature(env, ARM_FEATURE_M)) {
6197
        qemu_put_be32(f, env->v7m.other_sp);
6198
        qemu_put_be32(f, env->v7m.vecbase);
6199
        qemu_put_be32(f, env->v7m.basepri);
6200
        qemu_put_be32(f, env->v7m.control);
6201
        qemu_put_be32(f, env->v7m.current_sp);
6202
        qemu_put_be32(f, env->v7m.exception);
6203
    }
6204
}
6205

    
6206
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6207
{
6208
    CPUARMState *env = (CPUARMState *)opaque;
6209
    int i;
6210

    
6211
    if (version_id != ARM_CPU_SAVE_VERSION)
6212
        return -EINVAL;
6213

    
6214
    for (i = 0; i < 16; i++) {
6215
        env->regs[i] = qemu_get_be32(f);
6216
    }
6217
    cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6218
    env->spsr = qemu_get_be32(f);
6219
    for (i = 0; i < 6; i++) {
6220
        env->banked_spsr[i] = qemu_get_be32(f);
6221
        env->banked_r13[i] = qemu_get_be32(f);
6222
        env->banked_r14[i] = qemu_get_be32(f);
6223
    }
6224
    for (i = 0; i < 5; i++) {
6225
        env->usr_regs[i] = qemu_get_be32(f);
6226
        env->fiq_regs[i] = qemu_get_be32(f);
6227
    }
6228
    env->cp15.c0_cpuid = qemu_get_be32(f);
6229
    env->cp15.c0_cachetype = qemu_get_be32(f);
6230
    env->cp15.c1_sys = qemu_get_be32(f);
6231
    env->cp15.c1_coproc = qemu_get_be32(f);
6232
    env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6233
    env->cp15.c2_base0 = qemu_get_be32(f);
6234
    env->cp15.c2_base1 = qemu_get_be32(f);
6235
    env->cp15.c2_mask = qemu_get_be32(f);
6236
    env->cp15.c2_data = qemu_get_be32(f);
6237
    env->cp15.c2_insn = qemu_get_be32(f);
6238
    env->cp15.c3 = qemu_get_be32(f);
6239
    env->cp15.c5_insn = qemu_get_be32(f);
6240
    env->cp15.c5_data = qemu_get_be32(f);
6241
    for (i = 0; i < 8; i++) {
6242
        env->cp15.c6_region[i] = qemu_get_be32(f);
6243
    }
6244
    env->cp15.c6_insn = qemu_get_be32(f);
6245
    env->cp15.c6_data = qemu_get_be32(f);
6246
    env->cp15.c9_insn = qemu_get_be32(f);
6247
    env->cp15.c9_data = qemu_get_be32(f);
6248
    env->cp15.c13_fcse = qemu_get_be32(f);
6249
    env->cp15.c13_context = qemu_get_be32(f);
6250
    env->cp15.c13_tls1 = qemu_get_be32(f);
6251
    env->cp15.c13_tls2 = qemu_get_be32(f);
6252
    env->cp15.c13_tls3 = qemu_get_be32(f);
6253
    env->cp15.c15_cpar = qemu_get_be32(f);
6254

    
6255
    env->features = qemu_get_be32(f);
6256

    
6257
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6258
        for (i = 0;  i < 16; i++) {
6259
            CPU_DoubleU u;
6260
            u.l.upper = qemu_get_be32(f);
6261
            u.l.lower = qemu_get_be32(f);
6262
            env->vfp.regs[i] = u.d;
6263
        }
6264
        for (i = 0; i < 16; i++) {
6265
            env->vfp.xregs[i] = qemu_get_be32(f);
6266
        }
6267

    
6268
        /* TODO: Should use proper FPSCR access functions.  */
6269
        env->vfp.vec_len = qemu_get_be32(f);
6270
        env->vfp.vec_stride = qemu_get_be32(f);
6271

    
6272
        if (arm_feature(env, ARM_FEATURE_VFP3)) {
6273
            for (i = 0;  i < 16; i++) {
6274
                CPU_DoubleU u;
6275
                u.l.upper = qemu_get_be32(f);
6276
                u.l.lower = qemu_get_be32(f);
6277
                env->vfp.regs[i] = u.d;
6278
            }
6279
        }
6280
    }
6281

    
6282
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6283
        for (i = 0; i < 16; i++) {
6284
            env->iwmmxt.regs[i] = qemu_get_be64(f);
6285
        }
6286
        for (i = 0; i < 16; i++) {
6287
            env->iwmmxt.cregs[i] = qemu_get_be32(f);
6288
        }
6289
    }
6290

    
6291
    if (arm_feature(env, ARM_FEATURE_M)) {
6292
        env->v7m.other_sp = qemu_get_be32(f);
6293
        env->v7m.vecbase = qemu_get_be32(f);
6294
        env->v7m.basepri = qemu_get_be32(f);
6295
        env->v7m.control = qemu_get_be32(f);
6296
        env->v7m.current_sp = qemu_get_be32(f);
6297
        env->v7m.exception = qemu_get_be32(f);
6298
    }
6299

    
6300
    return 0;
6301
}
6302

    
6303
#else
6304

    
6305
//#warning No CPU save/restore functions
6306

    
6307
#endif
6308

    
6309
/***********************************************************/
6310
/* ram save/restore */
6311

    
6312
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6313
{
6314
    int v;
6315

    
6316
    v = qemu_get_byte(f);
6317
    switch(v) {
6318
    case 0:
6319
        if (qemu_get_buffer(f, buf, len) != len)
6320
            return -EIO;
6321
        break;
6322
    case 1:
6323
        v = qemu_get_byte(f);
6324
        memset(buf, v, len);
6325
        break;
6326
    default:
6327
        return -EINVAL;
6328
    }
6329
    return 0;
6330
}
6331

    
6332
static int ram_load_v1(QEMUFile *f, void *opaque)
6333
{
6334
    int i, ret;
6335

    
6336
    if (qemu_get_be32(f) != phys_ram_size)
6337
        return -EINVAL;
6338
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6339
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6340
        if (ret)
6341
            return ret;
6342
    }
6343
    return 0;
6344
}
6345

    
6346
#define BDRV_HASH_BLOCK_SIZE 1024
6347
#define IOBUF_SIZE 4096
6348
#define RAM_CBLOCK_MAGIC 0xfabe
6349

    
6350
typedef struct RamCompressState {
6351
    z_stream zstream;
6352
    QEMUFile *f;
6353
    uint8_t buf[IOBUF_SIZE];
6354
} RamCompressState;
6355

    
6356
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6357
{
6358
    int ret;
6359
    memset(s, 0, sizeof(*s));
6360
    s->f = f;
6361
    ret = deflateInit2(&s->zstream, 1,
6362
                       Z_DEFLATED, 15,
6363
                       9, Z_DEFAULT_STRATEGY);
6364
    if (ret != Z_OK)
6365
        return -1;
6366
    s->zstream.avail_out = IOBUF_SIZE;
6367
    s->zstream.next_out = s->buf;
6368
    return 0;
6369
}
6370

    
6371
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6372
{
6373
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6374
    qemu_put_be16(s->f, len);
6375
    qemu_put_buffer(s->f, buf, len);
6376
}
6377

    
6378
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6379
{
6380
    int ret;
6381

    
6382
    s->zstream.avail_in = len;
6383
    s->zstream.next_in = (uint8_t *)buf;
6384
    while (s->zstream.avail_in > 0) {
6385
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6386
        if (ret != Z_OK)
6387
            return -1;
6388
        if (s->zstream.avail_out == 0) {
6389
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6390
            s->zstream.avail_out = IOBUF_SIZE;
6391
            s->zstream.next_out = s->buf;
6392
        }
6393
    }
6394
    return 0;
6395
}
6396

    
6397
static void ram_compress_close(RamCompressState *s)
6398
{
6399
    int len, ret;
6400

    
6401
    /* compress last bytes */
6402
    for(;;) {
6403
        ret = deflate(&s->zstream, Z_FINISH);
6404
        if (ret == Z_OK || ret == Z_STREAM_END) {
6405
            len = IOBUF_SIZE - s->zstream.avail_out;
6406
            if (len > 0) {
6407
                ram_put_cblock(s, s->buf, len);
6408
            }
6409
            s->zstream.avail_out = IOBUF_SIZE;
6410
            s->zstream.next_out = s->buf;
6411
            if (ret == Z_STREAM_END)
6412
                break;
6413
        } else {
6414
            goto fail;
6415
        }
6416
    }
6417
fail:
6418
    deflateEnd(&s->zstream);
6419
}
6420

    
6421
typedef struct RamDecompressState {
6422
    z_stream zstream;
6423
    QEMUFile *f;
6424
    uint8_t buf[IOBUF_SIZE];
6425
} RamDecompressState;
6426

    
6427
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6428
{
6429
    int ret;
6430
    memset(s, 0, sizeof(*s));
6431
    s->f = f;
6432
    ret = inflateInit(&s->zstream);
6433
    if (ret != Z_OK)
6434
        return -1;
6435
    return 0;
6436
}
6437

    
6438
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6439
{
6440
    int ret, clen;
6441

    
6442
    s->zstream.avail_out = len;
6443
    s->zstream.next_out = buf;
6444
    while (s->zstream.avail_out > 0) {
6445
        if (s->zstream.avail_in == 0) {
6446
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6447
                return -1;
6448
            clen = qemu_get_be16(s->f);
6449
            if (clen > IOBUF_SIZE)
6450
                return -1;
6451
            qemu_get_buffer(s->f, s->buf, clen);
6452
            s->zstream.avail_in = clen;
6453
            s->zstream.next_in = s->buf;
6454
        }
6455
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6456
        if (ret != Z_OK && ret != Z_STREAM_END) {
6457
            return -1;
6458
        }
6459
    }
6460
    return 0;
6461
}
6462

    
6463
static void ram_decompress_close(RamDecompressState *s)
6464
{
6465
    inflateEnd(&s->zstream);
6466
}
6467

    
6468
static void ram_save(QEMUFile *f, void *opaque)
6469
{
6470
    int i;
6471
    RamCompressState s1, *s = &s1;
6472
    uint8_t buf[10];
6473

    
6474
    qemu_put_be32(f, phys_ram_size);
6475
    if (ram_compress_open(s, f) < 0)
6476
        return;
6477
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6478
#if 0
6479
        if (tight_savevm_enabled) {
6480
            int64_t sector_num;
6481
            int j;
6482

6483
            /* find if the memory block is available on a virtual
6484
               block device */
6485
            sector_num = -1;
6486
            for(j = 0; j < MAX_DISKS; j++) {
6487
                if (bs_table[j]) {
6488
                    sector_num = bdrv_hash_find(bs_table[j],
6489
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6490
                    if (sector_num >= 0)
6491
                        break;
6492
                }
6493
            }
6494
            if (j == MAX_DISKS)
6495
                goto normal_compress;
6496
            buf[0] = 1;
6497
            buf[1] = j;
6498
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6499
            ram_compress_buf(s, buf, 10);
6500
        } else
6501
#endif
6502
        {
6503
            //        normal_compress:
6504
            buf[0] = 0;
6505
            ram_compress_buf(s, buf, 1);
6506
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6507
        }
6508
    }
6509
    ram_compress_close(s);
6510
}
6511

    
6512
static int ram_load(QEMUFile *f, void *opaque, int version_id)
6513
{
6514
    RamDecompressState s1, *s = &s1;
6515
    uint8_t buf[10];
6516
    int i;
6517

    
6518
    if (version_id == 1)
6519
        return ram_load_v1(f, opaque);
6520
    if (version_id != 2)
6521
        return -EINVAL;
6522
    if (qemu_get_be32(f) != phys_ram_size)
6523
        return -EINVAL;
6524
    if (ram_decompress_open(s, f) < 0)
6525
        return -EINVAL;
6526
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6527
        if (ram_decompress_buf(s, buf, 1) < 0) {
6528
            fprintf(stderr, "Error while reading ram block header\n");
6529
            goto error;
6530
        }
6531
        if (buf[0] == 0) {
6532
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6533
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6534
                goto error;
6535
            }
6536
        } else
6537
#if 0
6538
        if (buf[0] == 1) {
6539
            int bs_index;
6540
            int64_t sector_num;
6541

6542
            ram_decompress_buf(s, buf + 1, 9);
6543
            bs_index = buf[1];
6544
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6545
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6546
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
6547
                goto error;
6548
            }
6549
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6550
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6551
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6552
                        bs_index, sector_num);
6553
                goto error;
6554
            }
6555
        } else
6556
#endif
6557
        {
6558
        error:
6559
            printf("Error block header\n");
6560
            return -EINVAL;
6561
        }
6562
    }
6563
    ram_decompress_close(s);
6564
    return 0;
6565
}
6566

    
6567
/***********************************************************/
6568
/* bottom halves (can be seen as timers which expire ASAP) */
6569

    
6570
struct QEMUBH {
6571
    QEMUBHFunc *cb;
6572
    void *opaque;
6573
    int scheduled;
6574
    QEMUBH *next;
6575
};
6576

    
6577
static QEMUBH *first_bh = NULL;
6578

    
6579
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6580
{
6581
    QEMUBH *bh;
6582
    bh = qemu_mallocz(sizeof(QEMUBH));
6583
    if (!bh)
6584
        return NULL;
6585
    bh->cb = cb;
6586
    bh->opaque = opaque;
6587
    return bh;
6588
}
6589

    
6590
int qemu_bh_poll(void)
6591
{
6592
    QEMUBH *bh, **pbh;
6593
    int ret;
6594

    
6595
    ret = 0;
6596
    for(;;) {
6597
        pbh = &first_bh;
6598
        bh = *pbh;
6599
        if (!bh)
6600
            break;
6601
        ret = 1;
6602
        *pbh = bh->next;
6603
        bh->scheduled = 0;
6604
        bh->cb(bh->opaque);
6605
    }
6606
    return ret;
6607
}
6608

    
6609
void qemu_bh_schedule(QEMUBH *bh)
6610
{
6611
    CPUState *env = cpu_single_env;
6612
    if (bh->scheduled)
6613
        return;
6614
    bh->scheduled = 1;
6615
    bh->next = first_bh;
6616
    first_bh = bh;
6617

    
6618
    /* stop the currently executing CPU to execute the BH ASAP */
6619
    if (env) {
6620
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6621
    }
6622
}
6623

    
6624
void qemu_bh_cancel(QEMUBH *bh)
6625
{
6626
    QEMUBH **pbh;
6627
    if (bh->scheduled) {
6628
        pbh = &first_bh;
6629
        while (*pbh != bh)
6630
            pbh = &(*pbh)->next;
6631
        *pbh = bh->next;
6632
        bh->scheduled = 0;
6633
    }
6634
}
6635

    
6636
void qemu_bh_delete(QEMUBH *bh)
6637
{
6638
    qemu_bh_cancel(bh);
6639
    qemu_free(bh);
6640
}
6641

    
6642
/***********************************************************/
6643
/* machine registration */
6644

    
6645
QEMUMachine *first_machine = NULL;
6646

    
6647
int qemu_register_machine(QEMUMachine *m)
6648
{
6649
    QEMUMachine **pm;
6650
    pm = &first_machine;
6651
    while (*pm != NULL)
6652
        pm = &(*pm)->next;
6653
    m->next = NULL;
6654
    *pm = m;
6655
    return 0;
6656
}
6657

    
6658
static QEMUMachine *find_machine(const char *name)
6659
{
6660
    QEMUMachine *m;
6661

    
6662
    for(m = first_machine; m != NULL; m = m->next) {
6663
        if (!strcmp(m->name, name))
6664
            return m;
6665
    }
6666
    return NULL;
6667
}
6668

    
6669
/***********************************************************/
6670
/* main execution loop */
6671

    
6672
static void gui_update(void *opaque)
6673
{
6674
    DisplayState *ds = opaque;
6675
    ds->dpy_refresh(ds);
6676
    qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6677
}
6678

    
6679
struct vm_change_state_entry {
6680
    VMChangeStateHandler *cb;
6681
    void *opaque;
6682
    LIST_ENTRY (vm_change_state_entry) entries;
6683
};
6684

    
6685
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6686

    
6687
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6688
                                                     void *opaque)
6689
{
6690
    VMChangeStateEntry *e;
6691

    
6692
    e = qemu_mallocz(sizeof (*e));
6693
    if (!e)
6694
        return NULL;
6695

    
6696
    e->cb = cb;
6697
    e->opaque = opaque;
6698
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6699
    return e;
6700
}
6701

    
6702
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6703
{
6704
    LIST_REMOVE (e, entries);
6705
    qemu_free (e);
6706
}
6707

    
6708
static void vm_state_notify(int running)
6709
{
6710
    VMChangeStateEntry *e;
6711

    
6712
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6713
        e->cb(e->opaque, running);
6714
    }
6715
}
6716

    
6717
/* XXX: support several handlers */
6718
static VMStopHandler *vm_stop_cb;
6719
static void *vm_stop_opaque;
6720

    
6721
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6722
{
6723
    vm_stop_cb = cb;
6724
    vm_stop_opaque = opaque;
6725
    return 0;
6726
}
6727

    
6728
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6729
{
6730
    vm_stop_cb = NULL;
6731
}
6732

    
6733
void vm_start(void)
6734
{
6735
    if (!vm_running) {
6736
        cpu_enable_ticks();
6737
        vm_running = 1;
6738
        vm_state_notify(1);
6739
        qemu_rearm_alarm_timer(alarm_timer);
6740
    }
6741
}
6742

    
6743
void vm_stop(int reason)
6744
{
6745
    if (vm_running) {
6746
        cpu_disable_ticks();
6747
        vm_running = 0;
6748
        if (reason != 0) {
6749
            if (vm_stop_cb) {
6750
                vm_stop_cb(vm_stop_opaque, reason);
6751
            }
6752
        }
6753
        vm_state_notify(0);
6754
    }
6755
}
6756

    
6757
/* reset/shutdown handler */
6758

    
6759
typedef struct QEMUResetEntry {
6760
    QEMUResetHandler *func;
6761
    void *opaque;
6762
    struct QEMUResetEntry *next;
6763
} QEMUResetEntry;
6764

    
6765
static QEMUResetEntry *first_reset_entry;
6766
static int reset_requested;
6767
static int shutdown_requested;
6768
static int powerdown_requested;
6769

    
6770
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6771
{
6772
    QEMUResetEntry **pre, *re;
6773

    
6774
    pre = &first_reset_entry;
6775
    while (*pre != NULL)
6776
        pre = &(*pre)->next;
6777
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6778
    re->func = func;
6779
    re->opaque = opaque;
6780
    re->next = NULL;
6781
    *pre = re;
6782
}
6783

    
6784
static void qemu_system_reset(void)
6785
{
6786
    QEMUResetEntry *re;
6787

    
6788
    /* reset all devices */
6789
    for(re = first_reset_entry; re != NULL; re = re->next) {
6790
        re->func(re->opaque);
6791
    }
6792
}
6793

    
6794
void qemu_system_reset_request(void)
6795
{
6796
    if (no_reboot) {
6797
        shutdown_requested = 1;
6798
    } else {
6799
        reset_requested = 1;
6800
    }
6801
    if (cpu_single_env)
6802
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6803
}
6804

    
6805
void qemu_system_shutdown_request(void)
6806
{
6807
    shutdown_requested = 1;
6808
    if (cpu_single_env)
6809
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6810
}
6811

    
6812
void qemu_system_powerdown_request(void)
6813
{
6814
    powerdown_requested = 1;
6815
    if (cpu_single_env)
6816
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6817
}
6818

    
6819
void main_loop_wait(int timeout)
6820
{
6821
    IOHandlerRecord *ioh;
6822
    fd_set rfds, wfds, xfds;
6823
    int ret, nfds;
6824
#ifdef _WIN32
6825
    int ret2, i;
6826
#endif
6827
    struct timeval tv;
6828
    PollingEntry *pe;
6829

    
6830

    
6831
    /* XXX: need to suppress polling by better using win32 events */
6832
    ret = 0;
6833
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6834
        ret |= pe->func(pe->opaque);
6835
    }
6836
#ifdef _WIN32
6837
    if (ret == 0) {
6838
        int err;
6839
        WaitObjects *w = &wait_objects;
6840

    
6841
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6842
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6843
            if (w->func[ret - WAIT_OBJECT_0])
6844
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6845

    
6846
            /* Check for additional signaled events */
6847
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6848

    
6849
                /* Check if event is signaled */
6850
                ret2 = WaitForSingleObject(w->events[i], 0);
6851
                if(ret2 == WAIT_OBJECT_0) {
6852
                    if (w->func[i])
6853
                        w->func[i](w->opaque[i]);
6854
                } else if (ret2 == WAIT_TIMEOUT) {
6855
                } else {
6856
                    err = GetLastError();
6857
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6858
                }
6859
            }
6860
        } else if (ret == WAIT_TIMEOUT) {
6861
        } else {
6862
            err = GetLastError();
6863
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6864
        }
6865
    }
6866
#endif
6867
    /* poll any events */
6868
    /* XXX: separate device handlers from system ones */
6869
    nfds = -1;
6870
    FD_ZERO(&rfds);
6871
    FD_ZERO(&wfds);
6872
    FD_ZERO(&xfds);
6873
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6874
        if (ioh->deleted)
6875
            continue;
6876
        if (ioh->fd_read &&
6877
            (!ioh->fd_read_poll ||
6878
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6879
            FD_SET(ioh->fd, &rfds);
6880
            if (ioh->fd > nfds)
6881
                nfds = ioh->fd;
6882
        }
6883
        if (ioh->fd_write) {
6884
            FD_SET(ioh->fd, &wfds);
6885
            if (ioh->fd > nfds)
6886
                nfds = ioh->fd;
6887
        }
6888
    }
6889

    
6890
    tv.tv_sec = 0;
6891
#ifdef _WIN32
6892
    tv.tv_usec = 0;
6893
#else
6894
    tv.tv_usec = timeout * 1000;
6895
#endif
6896
#if defined(CONFIG_SLIRP)
6897
    if (slirp_inited) {
6898
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6899
    }
6900
#endif
6901
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6902
    if (ret > 0) {
6903
        IOHandlerRecord **pioh;
6904

    
6905
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6906
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6907
                ioh->fd_read(ioh->opaque);
6908
            }
6909
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6910
                ioh->fd_write(ioh->opaque);
6911
            }
6912
        }
6913

    
6914
        /* remove deleted IO handlers */
6915
        pioh = &first_io_handler;
6916
        while (*pioh) {
6917
            ioh = *pioh;
6918
            if (ioh->deleted) {
6919
                *pioh = ioh->next;
6920
                qemu_free(ioh);
6921
            } else
6922
                pioh = &ioh->next;
6923
        }
6924
    }
6925
#if defined(CONFIG_SLIRP)
6926
    if (slirp_inited) {
6927
        if (ret < 0) {
6928
            FD_ZERO(&rfds);
6929
            FD_ZERO(&wfds);
6930
            FD_ZERO(&xfds);
6931
        }
6932
        slirp_select_poll(&rfds, &wfds, &xfds);
6933
    }
6934
#endif
6935
    qemu_aio_poll();
6936

    
6937
    if (vm_running) {
6938
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6939
                        qemu_get_clock(vm_clock));
6940
        /* run dma transfers, if any */
6941
        DMA_run();
6942
    }
6943

    
6944
    /* real time timers */
6945
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6946
                    qemu_get_clock(rt_clock));
6947

    
6948
    /* Check bottom-halves last in case any of the earlier events triggered
6949
       them.  */
6950
    qemu_bh_poll();
6951

    
6952
}
6953

    
6954
static CPUState *cur_cpu;
6955

    
6956
static int main_loop(void)
6957
{
6958
    int ret, timeout;
6959
#ifdef CONFIG_PROFILER
6960
    int64_t ti;
6961
#endif
6962
    CPUState *env;
6963

    
6964
    cur_cpu = first_cpu;
6965
    for(;;) {
6966
        if (vm_running) {
6967

    
6968
            env = cur_cpu;
6969
            for(;;) {
6970
                /* get next cpu */
6971
                env = env->next_cpu;
6972
                if (!env)
6973
                    env = first_cpu;
6974
#ifdef CONFIG_PROFILER
6975
                ti = profile_getclock();
6976
#endif
6977
                ret = cpu_exec(env);
6978
#ifdef CONFIG_PROFILER
6979
                qemu_time += profile_getclock() - ti;
6980
#endif
6981
                if (ret == EXCP_HLT) {
6982
                    /* Give the next CPU a chance to run.  */
6983
                    cur_cpu = env;
6984
                    continue;
6985
                }
6986
                if (ret != EXCP_HALTED)
6987
                    break;
6988
                /* all CPUs are halted ? */
6989
                if (env == cur_cpu)
6990
                    break;
6991
            }
6992
            cur_cpu = env;
6993

    
6994
            if (shutdown_requested) {
6995
                ret = EXCP_INTERRUPT;
6996
                break;
6997
            }
6998
            if (reset_requested) {
6999
                reset_requested = 0;
7000
                qemu_system_reset();
7001
                ret = EXCP_INTERRUPT;
7002
            }
7003
            if (powerdown_requested) {
7004
                powerdown_requested = 0;
7005
                qemu_system_powerdown();
7006
                ret = EXCP_INTERRUPT;
7007
            }
7008
            if (ret == EXCP_DEBUG) {
7009
                vm_stop(EXCP_DEBUG);
7010
            }
7011
            /* If all cpus are halted then wait until the next IRQ */
7012
            /* XXX: use timeout computed from timers */
7013
            if (ret == EXCP_HALTED)
7014
                timeout = 10;
7015
            else
7016
                timeout = 0;
7017
        } else {
7018
            timeout = 10;
7019
        }
7020
#ifdef CONFIG_PROFILER
7021
        ti = profile_getclock();
7022
#endif
7023
        main_loop_wait(timeout);
7024
#ifdef CONFIG_PROFILER
7025
        dev_time += profile_getclock() - ti;
7026
#endif
7027
    }
7028
    cpu_disable_ticks();
7029
    return ret;
7030
}
7031

    
7032
static void help(int exitcode)
7033
{
7034
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7035
           "usage: %s [options] [disk_image]\n"
7036
           "\n"
7037
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7038
           "\n"
7039
           "Standard options:\n"
7040
           "-M machine      select emulated machine (-M ? for list)\n"
7041
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7042
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7043
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7044
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7045
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7046
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7047
           "-sd file        use 'file' as SecureDigital card image\n"
7048
           "-pflash file    use 'file' as a parallel flash image\n"
7049
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7050
           "-snapshot       write to temporary files instead of disk image files\n"
7051
#ifdef CONFIG_SDL
7052
           "-no-frame       open SDL window without a frame and window decorations\n"
7053
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7054
           "-no-quit        disable SDL window close capability\n"
7055
#endif
7056
#ifdef TARGET_I386
7057
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7058
#endif
7059
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7060
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7061
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7062
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7063
#ifndef _WIN32
7064
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7065
#endif
7066
#ifdef HAS_AUDIO
7067
           "-audio-help     print list of audio drivers and their options\n"
7068
           "-soundhw c1,... enable audio support\n"
7069
           "                and only specified sound cards (comma separated list)\n"
7070
           "                use -soundhw ? to get the list of supported cards\n"
7071
           "                use -soundhw all to enable all of them\n"
7072
#endif
7073
           "-localtime      set the real time clock to local time [default=utc]\n"
7074
           "-full-screen    start in full screen\n"
7075
#ifdef TARGET_I386
7076
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7077
#endif
7078
           "-usb            enable the USB driver (will be the default soon)\n"
7079
           "-usbdevice name add the host or guest USB device 'name'\n"
7080
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7081
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7082
#endif
7083
           "-name string    set the name of the guest\n"
7084
           "\n"
7085
           "Network options:\n"
7086
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7087
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7088
#ifdef CONFIG_SLIRP
7089
           "-net user[,vlan=n][,hostname=host]\n"
7090
           "                connect the user mode network stack to VLAN 'n' and send\n"
7091
           "                hostname 'host' to DHCP clients\n"
7092
#endif
7093
#ifdef _WIN32
7094
           "-net tap[,vlan=n],ifname=name\n"
7095
           "                connect the host TAP network interface to VLAN 'n'\n"
7096
#else
7097
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7098
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7099
           "                network scripts 'file' (default=%s)\n"
7100
           "                and 'dfile' (default=%s);\n"
7101
           "                use '[down]script=no' to disable script execution;\n"
7102
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7103
#endif
7104
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7105
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7106
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7107
           "                connect the vlan 'n' to multicast maddr and port\n"
7108
           "-net none       use it alone to have zero network devices; if no -net option\n"
7109
           "                is provided, the default is '-net nic -net user'\n"
7110
           "\n"
7111
#ifdef CONFIG_SLIRP
7112
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7113
           "-bootp file     advertise file in BOOTP replies\n"
7114
#ifndef _WIN32
7115
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7116
#endif
7117
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7118
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7119
#endif
7120
           "\n"
7121
           "Linux boot specific:\n"
7122
           "-kernel bzImage use 'bzImage' as kernel image\n"
7123
           "-append cmdline use 'cmdline' as kernel command line\n"
7124
           "-initrd file    use 'file' as initial ram disk\n"
7125
           "\n"
7126
           "Debug/Expert options:\n"
7127
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7128
           "-serial dev     redirect the serial port to char device 'dev'\n"
7129
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7130
           "-pidfile file   Write PID to 'file'\n"
7131
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7132
           "-s              wait gdb connection to port\n"
7133
           "-p port         set gdb connection port [default=%s]\n"
7134
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7135
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7136
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7137
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7138
#ifdef USE_KQEMU
7139
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7140
           "-no-kqemu       disable KQEMU kernel module usage\n"
7141
#endif
7142
#ifdef TARGET_I386
7143
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7144
           "                (default is CL-GD5446 PCI VGA)\n"
7145
           "-no-acpi        disable ACPI\n"
7146
#endif
7147
           "-no-reboot      exit instead of rebooting\n"
7148
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
7149
           "-vnc display    start a VNC server on display\n"
7150
#ifndef _WIN32
7151
           "-daemonize      daemonize QEMU after initializing\n"
7152
#endif
7153
           "-option-rom rom load a file, rom, into the option ROM space\n"
7154
#ifdef TARGET_SPARC
7155
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7156
#endif
7157
           "-clock          force the use of the given methods for timer alarm.\n"
7158
           "                To see what timers are available use -clock help\n"
7159
           "\n"
7160
           "During emulation, the following keys are useful:\n"
7161
           "ctrl-alt-f      toggle full screen\n"
7162
           "ctrl-alt-n      switch to virtual console 'n'\n"
7163
           "ctrl-alt        toggle mouse and keyboard grab\n"
7164
           "\n"
7165
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7166
           ,
7167
           "qemu",
7168
           DEFAULT_RAM_SIZE,
7169
#ifndef _WIN32
7170
           DEFAULT_NETWORK_SCRIPT,
7171
           DEFAULT_NETWORK_DOWN_SCRIPT,
7172
#endif
7173
           DEFAULT_GDBSTUB_PORT,
7174
           "/tmp/qemu.log");
7175
    exit(exitcode);
7176
}
7177

    
7178
#define HAS_ARG 0x0001
7179

    
7180
enum {
7181
    QEMU_OPTION_h,
7182

    
7183
    QEMU_OPTION_M,
7184
    QEMU_OPTION_cpu,
7185
    QEMU_OPTION_fda,
7186
    QEMU_OPTION_fdb,
7187
    QEMU_OPTION_hda,
7188
    QEMU_OPTION_hdb,
7189
    QEMU_OPTION_hdc,
7190
    QEMU_OPTION_hdd,
7191
    QEMU_OPTION_cdrom,
7192
    QEMU_OPTION_mtdblock,
7193
    QEMU_OPTION_sd,
7194
    QEMU_OPTION_pflash,
7195
    QEMU_OPTION_boot,
7196
    QEMU_OPTION_snapshot,
7197
#ifdef TARGET_I386
7198
    QEMU_OPTION_no_fd_bootchk,
7199
#endif
7200
    QEMU_OPTION_m,
7201
    QEMU_OPTION_nographic,
7202
    QEMU_OPTION_portrait,
7203
#ifdef HAS_AUDIO
7204
    QEMU_OPTION_audio_help,
7205
    QEMU_OPTION_soundhw,
7206
#endif
7207

    
7208
    QEMU_OPTION_net,
7209
    QEMU_OPTION_tftp,
7210
    QEMU_OPTION_bootp,
7211
    QEMU_OPTION_smb,
7212
    QEMU_OPTION_redir,
7213

    
7214
    QEMU_OPTION_kernel,
7215
    QEMU_OPTION_append,
7216
    QEMU_OPTION_initrd,
7217

    
7218
    QEMU_OPTION_S,
7219
    QEMU_OPTION_s,
7220
    QEMU_OPTION_p,
7221
    QEMU_OPTION_d,
7222
    QEMU_OPTION_hdachs,
7223
    QEMU_OPTION_L,
7224
    QEMU_OPTION_bios,
7225
    QEMU_OPTION_no_code_copy,
7226
    QEMU_OPTION_k,
7227
    QEMU_OPTION_localtime,
7228
    QEMU_OPTION_cirrusvga,
7229
    QEMU_OPTION_vmsvga,
7230
    QEMU_OPTION_g,
7231
    QEMU_OPTION_std_vga,
7232
    QEMU_OPTION_echr,
7233
    QEMU_OPTION_monitor,
7234
    QEMU_OPTION_serial,
7235
    QEMU_OPTION_parallel,
7236
    QEMU_OPTION_loadvm,
7237
    QEMU_OPTION_full_screen,
7238
    QEMU_OPTION_no_frame,
7239
    QEMU_OPTION_alt_grab,
7240
    QEMU_OPTION_no_quit,
7241
    QEMU_OPTION_pidfile,
7242
    QEMU_OPTION_no_kqemu,
7243
    QEMU_OPTION_kernel_kqemu,
7244
    QEMU_OPTION_win2k_hack,
7245
    QEMU_OPTION_usb,
7246
    QEMU_OPTION_usbdevice,
7247
    QEMU_OPTION_smp,
7248
    QEMU_OPTION_vnc,
7249
    QEMU_OPTION_no_acpi,
7250
    QEMU_OPTION_no_reboot,
7251
    QEMU_OPTION_show_cursor,
7252
    QEMU_OPTION_daemonize,
7253
    QEMU_OPTION_option_rom,
7254
    QEMU_OPTION_semihosting,
7255
    QEMU_OPTION_name,
7256
    QEMU_OPTION_prom_env,
7257
    QEMU_OPTION_old_param,
7258
    QEMU_OPTION_clock,
7259
    QEMU_OPTION_startdate,
7260
};
7261

    
7262
typedef struct QEMUOption {
7263
    const char *name;
7264
    int flags;
7265
    int index;
7266
} QEMUOption;
7267

    
7268
const QEMUOption qemu_options[] = {
7269
    { "h", 0, QEMU_OPTION_h },
7270
    { "help", 0, QEMU_OPTION_h },
7271

    
7272
    { "M", HAS_ARG, QEMU_OPTION_M },
7273
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7274
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7275
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7276
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7277
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7278
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7279
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7280
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7281
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7282
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7283
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7284
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7285
    { "snapshot", 0, QEMU_OPTION_snapshot },
7286
#ifdef TARGET_I386
7287
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7288
#endif
7289
    { "m", HAS_ARG, QEMU_OPTION_m },
7290
    { "nographic", 0, QEMU_OPTION_nographic },
7291
    { "portrait", 0, QEMU_OPTION_portrait },
7292
    { "k", HAS_ARG, QEMU_OPTION_k },
7293
#ifdef HAS_AUDIO
7294
    { "audio-help", 0, QEMU_OPTION_audio_help },
7295
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7296
#endif
7297

    
7298
    { "net", HAS_ARG, QEMU_OPTION_net},
7299
#ifdef CONFIG_SLIRP
7300
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7301
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7302
#ifndef _WIN32
7303
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7304
#endif
7305
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7306
#endif
7307

    
7308
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7309
    { "append", HAS_ARG, QEMU_OPTION_append },
7310
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7311

    
7312
    { "S", 0, QEMU_OPTION_S },
7313
    { "s", 0, QEMU_OPTION_s },
7314
    { "p", HAS_ARG, QEMU_OPTION_p },
7315
    { "d", HAS_ARG, QEMU_OPTION_d },
7316
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7317
    { "L", HAS_ARG, QEMU_OPTION_L },
7318
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7319
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7320
#ifdef USE_KQEMU
7321
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7322
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7323
#endif
7324
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7325
    { "g", 1, QEMU_OPTION_g },
7326
#endif
7327
    { "localtime", 0, QEMU_OPTION_localtime },
7328
    { "std-vga", 0, QEMU_OPTION_std_vga },
7329
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7330
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7331
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7332
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7333
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7334
    { "full-screen", 0, QEMU_OPTION_full_screen },
7335
#ifdef CONFIG_SDL
7336
    { "no-frame", 0, QEMU_OPTION_no_frame },
7337
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7338
    { "no-quit", 0, QEMU_OPTION_no_quit },
7339
#endif
7340
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7341
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7342
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7343
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7344
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7345

    
7346
    /* temporary options */
7347
    { "usb", 0, QEMU_OPTION_usb },
7348
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7349
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7350
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7351
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7352
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7353
    { "daemonize", 0, QEMU_OPTION_daemonize },
7354
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7355
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7356
    { "semihosting", 0, QEMU_OPTION_semihosting },
7357
#endif
7358
    { "name", HAS_ARG, QEMU_OPTION_name },
7359
#if defined(TARGET_SPARC)
7360
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7361
#endif
7362
#if defined(TARGET_ARM)
7363
    { "old-param", 0, QEMU_OPTION_old_param },
7364
#endif
7365
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7366
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7367
    { NULL },
7368
};
7369

    
7370
/* password input */
7371

    
7372
int qemu_key_check(BlockDriverState *bs, const char *name)
7373
{
7374
    char password[256];
7375
    int i;
7376

    
7377
    if (!bdrv_is_encrypted(bs))
7378
        return 0;
7379

    
7380
    term_printf("%s is encrypted.\n", name);
7381
    for(i = 0; i < 3; i++) {
7382
        monitor_readline("Password: ", 1, password, sizeof(password));
7383
        if (bdrv_set_key(bs, password) == 0)
7384
            return 0;
7385
        term_printf("invalid password\n");
7386
    }
7387
    return -EPERM;
7388
}
7389

    
7390
static BlockDriverState *get_bdrv(int index)
7391
{
7392
    BlockDriverState *bs;
7393

    
7394
    if (index < 4) {
7395
        bs = bs_table[index];
7396
    } else if (index < 6) {
7397
        bs = fd_table[index - 4];
7398
    } else {
7399
        bs = NULL;
7400
    }
7401
    return bs;
7402
}
7403

    
7404
static void read_passwords(void)
7405
{
7406
    BlockDriverState *bs;
7407
    int i;
7408

    
7409
    for(i = 0; i < 6; i++) {
7410
        bs = get_bdrv(i);
7411
        if (bs)
7412
            qemu_key_check(bs, bdrv_get_device_name(bs));
7413
    }
7414
}
7415

    
7416
/* XXX: currently we cannot use simultaneously different CPUs */
7417
static void register_machines(void)
7418
{
7419
#if defined(TARGET_I386)
7420
    qemu_register_machine(&pc_machine);
7421
    qemu_register_machine(&isapc_machine);
7422
#elif defined(TARGET_PPC)
7423
    qemu_register_machine(&heathrow_machine);
7424
    qemu_register_machine(&core99_machine);
7425
    qemu_register_machine(&prep_machine);
7426
    qemu_register_machine(&ref405ep_machine);
7427
    qemu_register_machine(&taihu_machine);
7428
#elif defined(TARGET_MIPS)
7429
    qemu_register_machine(&mips_machine);
7430
    qemu_register_machine(&mips_malta_machine);
7431
    qemu_register_machine(&mips_pica61_machine);
7432
    qemu_register_machine(&mips_mipssim_machine);
7433
#elif defined(TARGET_SPARC)
7434
#ifdef TARGET_SPARC64
7435
    qemu_register_machine(&sun4u_machine);
7436
#else
7437
    qemu_register_machine(&ss5_machine);
7438
    qemu_register_machine(&ss10_machine);
7439
    qemu_register_machine(&ss600mp_machine);
7440
#endif
7441
#elif defined(TARGET_ARM)
7442
    qemu_register_machine(&integratorcp_machine);
7443
    qemu_register_machine(&versatilepb_machine);
7444
    qemu_register_machine(&versatileab_machine);
7445
    qemu_register_machine(&realview_machine);
7446
    qemu_register_machine(&akitapda_machine);
7447
    qemu_register_machine(&spitzpda_machine);
7448
    qemu_register_machine(&borzoipda_machine);
7449
    qemu_register_machine(&terrierpda_machine);
7450
    qemu_register_machine(&palmte_machine);
7451
    qemu_register_machine(&lm3s811evb_machine);
7452
    qemu_register_machine(&lm3s6965evb_machine);
7453
    qemu_register_machine(&connex_machine);
7454
#elif defined(TARGET_SH4)
7455
    qemu_register_machine(&shix_machine);
7456
    qemu_register_machine(&r2d_machine);
7457
#elif defined(TARGET_ALPHA)
7458
    /* XXX: TODO */
7459
#elif defined(TARGET_M68K)
7460
    qemu_register_machine(&mcf5208evb_machine);
7461
    qemu_register_machine(&an5206_machine);
7462
    qemu_register_machine(&dummy_m68k_machine);
7463
#elif defined(TARGET_CRIS)
7464
    qemu_register_machine(&bareetraxfs_machine);
7465
#else
7466
#error unsupported CPU
7467
#endif
7468
}
7469

    
7470
#ifdef HAS_AUDIO
7471
struct soundhw soundhw[] = {
7472
#ifdef HAS_AUDIO_CHOICE
7473
#ifdef TARGET_I386
7474
    {
7475
        "pcspk",
7476
        "PC speaker",
7477
        0,
7478
        1,
7479
        { .init_isa = pcspk_audio_init }
7480
    },
7481
#endif
7482
    {
7483
        "sb16",
7484
        "Creative Sound Blaster 16",
7485
        0,
7486
        1,
7487
        { .init_isa = SB16_init }
7488
    },
7489

    
7490
#ifdef CONFIG_ADLIB
7491
    {
7492
        "adlib",
7493
#ifdef HAS_YMF262
7494
        "Yamaha YMF262 (OPL3)",
7495
#else
7496
        "Yamaha YM3812 (OPL2)",
7497
#endif
7498
        0,
7499
        1,
7500
        { .init_isa = Adlib_init }
7501
    },
7502
#endif
7503

    
7504
#ifdef CONFIG_GUS
7505
    {
7506
        "gus",
7507
        "Gravis Ultrasound GF1",
7508
        0,
7509
        1,
7510
        { .init_isa = GUS_init }
7511
    },
7512
#endif
7513

    
7514
    {
7515
        "es1370",
7516
        "ENSONIQ AudioPCI ES1370",
7517
        0,
7518
        0,
7519
        { .init_pci = es1370_init }
7520
    },
7521
#endif
7522

    
7523
    { NULL, NULL, 0, 0, { NULL } }
7524
};
7525

    
7526
static void select_soundhw (const char *optarg)
7527
{
7528
    struct soundhw *c;
7529

    
7530
    if (*optarg == '?') {
7531
    show_valid_cards:
7532

    
7533
        printf ("Valid sound card names (comma separated):\n");
7534
        for (c = soundhw; c->name; ++c) {
7535
            printf ("%-11s %s\n", c->name, c->descr);
7536
        }
7537
        printf ("\n-soundhw all will enable all of the above\n");
7538
        exit (*optarg != '?');
7539
    }
7540
    else {
7541
        size_t l;
7542
        const char *p;
7543
        char *e;
7544
        int bad_card = 0;
7545

    
7546
        if (!strcmp (optarg, "all")) {
7547
            for (c = soundhw; c->name; ++c) {
7548
                c->enabled = 1;
7549
            }
7550
            return;
7551
        }
7552

    
7553
        p = optarg;
7554
        while (*p) {
7555
            e = strchr (p, ',');
7556
            l = !e ? strlen (p) : (size_t) (e - p);
7557

    
7558
            for (c = soundhw; c->name; ++c) {
7559
                if (!strncmp (c->name, p, l)) {
7560
                    c->enabled = 1;
7561
                    break;
7562
                }
7563
            }
7564

    
7565
            if (!c->name) {
7566
                if (l > 80) {
7567
                    fprintf (stderr,
7568
                             "Unknown sound card name (too big to show)\n");
7569
                }
7570
                else {
7571
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
7572
                             (int) l, p);
7573
                }
7574
                bad_card = 1;
7575
            }
7576
            p += l + (e != NULL);
7577
        }
7578

    
7579
        if (bad_card)
7580
            goto show_valid_cards;
7581
    }
7582
}
7583
#endif
7584

    
7585
#ifdef _WIN32
7586
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7587
{
7588
    exit(STATUS_CONTROL_C_EXIT);
7589
    return TRUE;
7590
}
7591
#endif
7592

    
7593
#define MAX_NET_CLIENTS 32
7594

    
7595
int main(int argc, char **argv)
7596
{
7597
#ifdef CONFIG_GDBSTUB
7598
    int use_gdbstub;
7599
    const char *gdbstub_port;
7600
#endif
7601
    uint32_t boot_devices_bitmap = 0;
7602
    int i, cdrom_index, pflash_index;
7603
    int snapshot, linux_boot, net_boot;
7604
    const char *initrd_filename;
7605
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7606
    const char *pflash_filename[MAX_PFLASH];
7607
    const char *sd_filename;
7608
    const char *mtd_filename;
7609
    const char *kernel_filename, *kernel_cmdline;
7610
    const char *boot_devices = "";
7611
    DisplayState *ds = &display_state;
7612
    int cyls, heads, secs, translation;
7613
    char net_clients[MAX_NET_CLIENTS][256];
7614
    int nb_net_clients;
7615
    int optind;
7616
    const char *r, *optarg;
7617
    CharDriverState *monitor_hd;
7618
    char monitor_device[128];
7619
    char serial_devices[MAX_SERIAL_PORTS][128];
7620
    int serial_device_index;
7621
    char parallel_devices[MAX_PARALLEL_PORTS][128];
7622
    int parallel_device_index;
7623
    const char *loadvm = NULL;
7624
    QEMUMachine *machine;
7625
    const char *cpu_model;
7626
    char usb_devices[MAX_USB_CMDLINE][128];
7627
    int usb_devices_index;
7628
    int fds[2];
7629
    const char *pid_file = NULL;
7630
    VLANState *vlan;
7631

    
7632
    LIST_INIT (&vm_change_state_head);
7633
#ifndef _WIN32
7634
    {
7635
        struct sigaction act;
7636
        sigfillset(&act.sa_mask);
7637
        act.sa_flags = 0;
7638
        act.sa_handler = SIG_IGN;
7639
        sigaction(SIGPIPE, &act, NULL);
7640
    }
7641
#else
7642
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7643
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
7644
       QEMU to run on a single CPU */
7645
    {
7646
        HANDLE h;
7647
        DWORD mask, smask;
7648
        int i;
7649
        h = GetCurrentProcess();
7650
        if (GetProcessAffinityMask(h, &mask, &smask)) {
7651
            for(i = 0; i < 32; i++) {
7652
                if (mask & (1 << i))
7653
                    break;
7654
            }
7655
            if (i != 32) {
7656
                mask = 1 << i;
7657
                SetProcessAffinityMask(h, mask);
7658
            }
7659
        }
7660
    }
7661
#endif
7662

    
7663
    register_machines();
7664
    machine = first_machine;
7665
    cpu_model = NULL;
7666
    initrd_filename = NULL;
7667
    for(i = 0; i < MAX_FD; i++)
7668
        fd_filename[i] = NULL;
7669
    for(i = 0; i < MAX_DISKS; i++)
7670
        hd_filename[i] = NULL;
7671
    for(i = 0; i < MAX_PFLASH; i++)
7672
        pflash_filename[i] = NULL;
7673
    pflash_index = 0;
7674
    sd_filename = NULL;
7675
    mtd_filename = NULL;
7676
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7677
    vga_ram_size = VGA_RAM_SIZE;
7678
#ifdef CONFIG_GDBSTUB
7679
    use_gdbstub = 0;
7680
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
7681
#endif
7682
    snapshot = 0;
7683
    nographic = 0;
7684
    kernel_filename = NULL;
7685
    kernel_cmdline = "";
7686
#ifdef TARGET_PPC
7687
    cdrom_index = 1;
7688
#else
7689
    cdrom_index = 2;
7690
#endif
7691
    cyls = heads = secs = 0;
7692
    translation = BIOS_ATA_TRANSLATION_AUTO;
7693
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7694

    
7695
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7696
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
7697
        serial_devices[i][0] = '\0';
7698
    serial_device_index = 0;
7699

    
7700
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7701
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7702
        parallel_devices[i][0] = '\0';
7703
    parallel_device_index = 0;
7704

    
7705
    usb_devices_index = 0;
7706

    
7707
    nb_net_clients = 0;
7708

    
7709
    nb_nics = 0;
7710
    /* default mac address of the first network interface */
7711

    
7712
    optind = 1;
7713
    for(;;) {
7714
        if (optind >= argc)
7715
            break;
7716
        r = argv[optind];
7717
        if (r[0] != '-') {
7718
            hd_filename[0] = argv[optind++];
7719
        } else {
7720
            const QEMUOption *popt;
7721

    
7722
            optind++;
7723
            /* Treat --foo the same as -foo.  */
7724
            if (r[1] == '-')
7725
                r++;
7726
            popt = qemu_options;
7727
            for(;;) {
7728
                if (!popt->name) {
7729
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
7730
                            argv[0], r);
7731
                    exit(1);
7732
                }
7733
                if (!strcmp(popt->name, r + 1))
7734
                    break;
7735
                popt++;
7736
            }
7737
            if (popt->flags & HAS_ARG) {
7738
                if (optind >= argc) {
7739
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
7740
                            argv[0], r);
7741
                    exit(1);
7742
                }
7743
                optarg = argv[optind++];
7744
            } else {
7745
                optarg = NULL;
7746
            }
7747

    
7748
            switch(popt->index) {
7749
            case QEMU_OPTION_M:
7750
                machine = find_machine(optarg);
7751
                if (!machine) {
7752
                    QEMUMachine *m;
7753
                    printf("Supported machines are:\n");
7754
                    for(m = first_machine; m != NULL; m = m->next) {
7755
                        printf("%-10s %s%s\n",
7756
                               m->name, m->desc,
7757
                               m == first_machine ? " (default)" : "");
7758
                    }
7759
                    exit(*optarg != '?');
7760
                }
7761
                break;
7762
            case QEMU_OPTION_cpu:
7763
                /* hw initialization will check this */
7764
                if (*optarg == '?') {
7765
/* XXX: implement xxx_cpu_list for targets that still miss it */
7766
#if defined(cpu_list)
7767
                    cpu_list(stdout, &fprintf);
7768
#endif
7769
                    exit(0);
7770
                } else {
7771
                    cpu_model = optarg;
7772
                }
7773
                break;
7774
            case QEMU_OPTION_initrd:
7775
                initrd_filename = optarg;
7776
                break;
7777
            case QEMU_OPTION_hda:
7778
            case QEMU_OPTION_hdb:
7779
            case QEMU_OPTION_hdc:
7780
            case QEMU_OPTION_hdd:
7781
                {
7782
                    int hd_index;
7783
                    hd_index = popt->index - QEMU_OPTION_hda;
7784
                    hd_filename[hd_index] = optarg;
7785
                    if (hd_index == cdrom_index)
7786
                        cdrom_index = -1;
7787
                }
7788
                break;
7789
            case QEMU_OPTION_mtdblock:
7790
                mtd_filename = optarg;
7791
                break;
7792
            case QEMU_OPTION_sd:
7793
                sd_filename = optarg;
7794
                break;
7795
            case QEMU_OPTION_pflash:
7796
                if (pflash_index >= MAX_PFLASH) {
7797
                    fprintf(stderr, "qemu: too many parallel flash images\n");
7798
                    exit(1);
7799
                }
7800
                pflash_filename[pflash_index++] = optarg;
7801
                break;
7802
            case QEMU_OPTION_snapshot:
7803
                snapshot = 1;
7804
                break;
7805
            case QEMU_OPTION_hdachs:
7806
                {
7807
                    const char *p;
7808
                    p = optarg;
7809
                    cyls = strtol(p, (char **)&p, 0);
7810
                    if (cyls < 1 || cyls > 16383)
7811
                        goto chs_fail;
7812
                    if (*p != ',')
7813
                        goto chs_fail;
7814
                    p++;
7815
                    heads = strtol(p, (char **)&p, 0);
7816
                    if (heads < 1 || heads > 16)
7817
                        goto chs_fail;
7818
                    if (*p != ',')
7819
                        goto chs_fail;
7820
                    p++;
7821
                    secs = strtol(p, (char **)&p, 0);
7822
                    if (secs < 1 || secs > 63)
7823
                        goto chs_fail;
7824
                    if (*p == ',') {
7825
                        p++;
7826
                        if (!strcmp(p, "none"))
7827
                            translation = BIOS_ATA_TRANSLATION_NONE;
7828
                        else if (!strcmp(p, "lba"))
7829
                            translation = BIOS_ATA_TRANSLATION_LBA;
7830
                        else if (!strcmp(p, "auto"))
7831
                            translation = BIOS_ATA_TRANSLATION_AUTO;
7832
                        else
7833
                            goto chs_fail;
7834
                    } else if (*p != '\0') {
7835
                    chs_fail:
7836
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
7837
                        exit(1);
7838
                    }
7839
                }
7840
                break;
7841
            case QEMU_OPTION_nographic:
7842
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7843
                pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7844
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7845
                nographic = 1;
7846
                break;
7847
            case QEMU_OPTION_portrait:
7848
                graphic_rotate = 1;
7849
                break;
7850
            case QEMU_OPTION_kernel:
7851
                kernel_filename = optarg;
7852
                break;
7853
            case QEMU_OPTION_append:
7854
                kernel_cmdline = optarg;
7855
                break;
7856
            case QEMU_OPTION_cdrom:
7857
                if (cdrom_index >= 0) {
7858
                    hd_filename[cdrom_index] = optarg;
7859
                }
7860
                break;
7861
            case QEMU_OPTION_boot:
7862
                boot_devices = optarg;
7863
                /* We just do some generic consistency checks */
7864
                {
7865
                    /* Could easily be extended to 64 devices if needed */
7866
                    const unsigned char *p;
7867
                    
7868
                    boot_devices_bitmap = 0;
7869
                    for (p = boot_devices; *p != '\0'; p++) {
7870
                        /* Allowed boot devices are:
7871
                         * a b     : floppy disk drives
7872
                         * c ... f : IDE disk drives
7873
                         * g ... m : machine implementation dependant drives
7874
                         * n ... p : network devices
7875
                         * It's up to each machine implementation to check
7876
                         * if the given boot devices match the actual hardware
7877
                         * implementation and firmware features.
7878
                         */
7879
                        if (*p < 'a' || *p > 'q') {
7880
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
7881
                            exit(1);
7882
                        }
7883
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
7884
                            fprintf(stderr,
7885
                                    "Boot device '%c' was given twice\n",*p);
7886
                            exit(1);
7887
                        }
7888
                        boot_devices_bitmap |= 1 << (*p - 'a');
7889
                    }
7890
                }
7891
                break;
7892
            case QEMU_OPTION_fda:
7893
                fd_filename[0] = optarg;
7894
                break;
7895
            case QEMU_OPTION_fdb:
7896
                fd_filename[1] = optarg;
7897
                break;
7898
#ifdef TARGET_I386
7899
            case QEMU_OPTION_no_fd_bootchk:
7900
                fd_bootchk = 0;
7901
                break;
7902
#endif
7903
            case QEMU_OPTION_no_code_copy:
7904
                code_copy_enabled = 0;
7905
                break;
7906
            case QEMU_OPTION_net:
7907
                if (nb_net_clients >= MAX_NET_CLIENTS) {
7908
                    fprintf(stderr, "qemu: too many network clients\n");
7909
                    exit(1);
7910
                }
7911
                pstrcpy(net_clients[nb_net_clients],
7912
                        sizeof(net_clients[0]),
7913
                        optarg);
7914
                nb_net_clients++;
7915
                break;
7916
#ifdef CONFIG_SLIRP
7917
            case QEMU_OPTION_tftp:
7918
                tftp_prefix = optarg;
7919
                break;
7920
            case QEMU_OPTION_bootp:
7921
                bootp_filename = optarg;
7922
                break;
7923
#ifndef _WIN32
7924
            case QEMU_OPTION_smb:
7925
                net_slirp_smb(optarg);
7926
                break;
7927
#endif
7928
            case QEMU_OPTION_redir:
7929
                net_slirp_redir(optarg);
7930
                break;
7931
#endif
7932
#ifdef HAS_AUDIO
7933
            case QEMU_OPTION_audio_help:
7934
                AUD_help ();
7935
                exit (0);
7936
                break;
7937
            case QEMU_OPTION_soundhw:
7938
                select_soundhw (optarg);
7939
                break;
7940
#endif
7941
            case QEMU_OPTION_h:
7942
                help(0);
7943
                break;
7944
            case QEMU_OPTION_m:
7945
                ram_size = atoi(optarg) * 1024 * 1024;
7946
                if (ram_size <= 0)
7947
                    help(1);
7948
                if (ram_size > PHYS_RAM_MAX_SIZE) {
7949
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7950
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
7951
                    exit(1);
7952
                }
7953
                break;
7954
            case QEMU_OPTION_d:
7955
                {
7956
                    int mask;
7957
                    CPULogItem *item;
7958

    
7959
                    mask = cpu_str_to_log_mask(optarg);
7960
                    if (!mask) {
7961
                        printf("Log items (comma separated):\n");
7962
                    for(item = cpu_log_items; item->mask != 0; item++) {
7963
                        printf("%-10s %s\n", item->name, item->help);
7964
                    }
7965
                    exit(1);
7966
                    }
7967
                    cpu_set_log(mask);
7968
                }
7969
                break;
7970
#ifdef CONFIG_GDBSTUB
7971
            case QEMU_OPTION_s:
7972
                use_gdbstub = 1;
7973
                break;
7974
            case QEMU_OPTION_p:
7975
                gdbstub_port = optarg;
7976
                break;
7977
#endif
7978
            case QEMU_OPTION_L:
7979
                bios_dir = optarg;
7980
                break;
7981
            case QEMU_OPTION_bios:
7982
                bios_name = optarg;
7983
                break;
7984
            case QEMU_OPTION_S:
7985
                autostart = 0;
7986
                break;
7987
            case QEMU_OPTION_k:
7988
                keyboard_layout = optarg;
7989
                break;
7990
            case QEMU_OPTION_localtime:
7991
                rtc_utc = 0;
7992
                break;
7993
            case QEMU_OPTION_cirrusvga:
7994
                cirrus_vga_enabled = 1;
7995
                vmsvga_enabled = 0;
7996
                break;
7997
            case QEMU_OPTION_vmsvga:
7998
                cirrus_vga_enabled = 0;
7999
                vmsvga_enabled = 1;
8000
                break;
8001
            case QEMU_OPTION_std_vga:
8002
                cirrus_vga_enabled = 0;
8003
                vmsvga_enabled = 0;
8004
                break;
8005
            case QEMU_OPTION_g:
8006
                {
8007
                    const char *p;
8008
                    int w, h, depth;
8009
                    p = optarg;
8010
                    w = strtol(p, (char **)&p, 10);
8011
                    if (w <= 0) {
8012
                    graphic_error:
8013
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8014
                        exit(1);
8015
                    }
8016
                    if (*p != 'x')
8017
                        goto graphic_error;
8018
                    p++;
8019
                    h = strtol(p, (char **)&p, 10);
8020
                    if (h <= 0)
8021
                        goto graphic_error;
8022
                    if (*p == 'x') {
8023
                        p++;
8024
                        depth = strtol(p, (char **)&p, 10);
8025
                        if (depth != 8 && depth != 15 && depth != 16 &&
8026
                            depth != 24 && depth != 32)
8027
                            goto graphic_error;
8028
                    } else if (*p == '\0') {
8029
                        depth = graphic_depth;
8030
                    } else {
8031
                        goto graphic_error;
8032
                    }
8033

    
8034
                    graphic_width = w;
8035
                    graphic_height = h;
8036
                    graphic_depth = depth;
8037
                }
8038
                break;
8039
            case QEMU_OPTION_echr:
8040
                {
8041
                    char *r;
8042
                    term_escape_char = strtol(optarg, &r, 0);
8043
                    if (r == optarg)
8044
                        printf("Bad argument to echr\n");
8045
                    break;
8046
                }
8047
            case QEMU_OPTION_monitor:
8048
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8049
                break;
8050
            case QEMU_OPTION_serial:
8051
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8052
                    fprintf(stderr, "qemu: too many serial ports\n");
8053
                    exit(1);
8054
                }
8055
                pstrcpy(serial_devices[serial_device_index],
8056
                        sizeof(serial_devices[0]), optarg);
8057
                serial_device_index++;
8058
                break;
8059
            case QEMU_OPTION_parallel:
8060
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8061
                    fprintf(stderr, "qemu: too many parallel ports\n");
8062
                    exit(1);
8063
                }
8064
                pstrcpy(parallel_devices[parallel_device_index],
8065
                        sizeof(parallel_devices[0]), optarg);
8066
                parallel_device_index++;
8067
                break;
8068
            case QEMU_OPTION_loadvm:
8069
                loadvm = optarg;
8070
                break;
8071
            case QEMU_OPTION_full_screen:
8072
                full_screen = 1;
8073
                break;
8074
#ifdef CONFIG_SDL
8075
            case QEMU_OPTION_no_frame:
8076
                no_frame = 1;
8077
                break;
8078
            case QEMU_OPTION_alt_grab:
8079
                alt_grab = 1;
8080
                break;
8081
            case QEMU_OPTION_no_quit:
8082
                no_quit = 1;
8083
                break;
8084
#endif
8085
            case QEMU_OPTION_pidfile:
8086
                pid_file = optarg;
8087
                break;
8088
#ifdef TARGET_I386
8089
            case QEMU_OPTION_win2k_hack:
8090
                win2k_install_hack = 1;
8091
                break;
8092
#endif
8093
#ifdef USE_KQEMU
8094
            case QEMU_OPTION_no_kqemu:
8095
                kqemu_allowed = 0;
8096
                break;
8097
            case QEMU_OPTION_kernel_kqemu:
8098
                kqemu_allowed = 2;
8099
                break;
8100
#endif
8101
            case QEMU_OPTION_usb:
8102
                usb_enabled = 1;
8103
                break;
8104
            case QEMU_OPTION_usbdevice:
8105
                usb_enabled = 1;
8106
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8107
                    fprintf(stderr, "Too many USB devices\n");
8108
                    exit(1);
8109
                }
8110
                pstrcpy(usb_devices[usb_devices_index],
8111
                        sizeof(usb_devices[usb_devices_index]),
8112
                        optarg);
8113
                usb_devices_index++;
8114
                break;
8115
            case QEMU_OPTION_smp:
8116
                smp_cpus = atoi(optarg);
8117
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8118
                    fprintf(stderr, "Invalid number of CPUs\n");
8119
                    exit(1);
8120
                }
8121
                break;
8122
            case QEMU_OPTION_vnc:
8123
                vnc_display = optarg;
8124
                break;
8125
            case QEMU_OPTION_no_acpi:
8126
                acpi_enabled = 0;
8127
                break;
8128
            case QEMU_OPTION_no_reboot:
8129
                no_reboot = 1;
8130
                break;
8131
            case QEMU_OPTION_show_cursor:
8132
                cursor_hide = 0;
8133
                break;
8134
            case QEMU_OPTION_daemonize:
8135
                daemonize = 1;
8136
                break;
8137
            case QEMU_OPTION_option_rom:
8138
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8139
                    fprintf(stderr, "Too many option ROMs\n");
8140
                    exit(1);
8141
                }
8142
                option_rom[nb_option_roms] = optarg;
8143
                nb_option_roms++;
8144
                break;
8145
            case QEMU_OPTION_semihosting:
8146
                semihosting_enabled = 1;
8147
                break;
8148
            case QEMU_OPTION_name:
8149
                qemu_name = optarg;
8150
                break;
8151
#ifdef TARGET_SPARC
8152
            case QEMU_OPTION_prom_env:
8153
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8154
                    fprintf(stderr, "Too many prom variables\n");
8155
                    exit(1);
8156
                }
8157
                prom_envs[nb_prom_envs] = optarg;
8158
                nb_prom_envs++;
8159
                break;
8160
#endif
8161
#ifdef TARGET_ARM
8162
            case QEMU_OPTION_old_param:
8163
                old_param = 1;
8164
#endif
8165
            case QEMU_OPTION_clock:
8166
                configure_alarms(optarg);
8167
                break;
8168
            case QEMU_OPTION_startdate:
8169
                {
8170
                    struct tm tm;
8171
                    if (!strcmp(optarg, "now")) {
8172
                        rtc_start_date = -1;
8173
                    } else {
8174
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8175
                               &tm.tm_year,
8176
                               &tm.tm_mon,
8177
                               &tm.tm_mday,
8178
                               &tm.tm_hour,
8179
                               &tm.tm_min,
8180
                               &tm.tm_sec) == 6) {
8181
                            /* OK */
8182
                        } else if (sscanf(optarg, "%d-%d-%d",
8183
                                          &tm.tm_year,
8184
                                          &tm.tm_mon,
8185
                                          &tm.tm_mday) == 3) {
8186
                            tm.tm_hour = 0;
8187
                            tm.tm_min = 0;
8188
                            tm.tm_sec = 0;
8189
                        } else {
8190
                            goto date_fail;
8191
                        }
8192
                        tm.tm_year -= 1900;
8193
                        tm.tm_mon--;
8194
                        rtc_start_date = mktimegm(&tm);
8195
                        if (rtc_start_date == -1) {
8196
                        date_fail:
8197
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8198
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8199
                            exit(1);
8200
                        }
8201
                    }
8202
                }
8203
                break;
8204
            }
8205
        }
8206
    }
8207

    
8208
#ifndef _WIN32
8209
    if (daemonize && !nographic && vnc_display == NULL) {
8210
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8211
        daemonize = 0;
8212
    }
8213

    
8214
    if (daemonize) {
8215
        pid_t pid;
8216

    
8217
        if (pipe(fds) == -1)
8218
            exit(1);
8219

    
8220
        pid = fork();
8221
        if (pid > 0) {
8222
            uint8_t status;
8223
            ssize_t len;
8224

    
8225
            close(fds[1]);
8226

    
8227
        again:
8228
            len = read(fds[0], &status, 1);
8229
            if (len == -1 && (errno == EINTR))
8230
                goto again;
8231

    
8232
            if (len != 1)
8233
                exit(1);
8234
            else if (status == 1) {
8235
                fprintf(stderr, "Could not acquire pidfile\n");
8236
                exit(1);
8237
            } else
8238
                exit(0);
8239
        } else if (pid < 0)
8240
            exit(1);
8241

    
8242
        setsid();
8243

    
8244
        pid = fork();
8245
        if (pid > 0)
8246
            exit(0);
8247
        else if (pid < 0)
8248
            exit(1);
8249

    
8250
        umask(027);
8251
        chdir("/");
8252

    
8253
        signal(SIGTSTP, SIG_IGN);
8254
        signal(SIGTTOU, SIG_IGN);
8255
        signal(SIGTTIN, SIG_IGN);
8256
    }
8257
#endif
8258

    
8259
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8260
        if (daemonize) {
8261
            uint8_t status = 1;
8262
            write(fds[1], &status, 1);
8263
        } else
8264
            fprintf(stderr, "Could not acquire pid file\n");
8265
        exit(1);
8266
    }
8267

    
8268
#ifdef USE_KQEMU
8269
    if (smp_cpus > 1)
8270
        kqemu_allowed = 0;
8271
#endif
8272
    linux_boot = (kernel_filename != NULL);
8273
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8274

    
8275
    /* XXX: this should not be: some embedded targets just have flash */
8276
    if (!linux_boot && net_boot == 0 &&
8277
        hd_filename[0] == NULL &&
8278
        (cdrom_index >= 0 && hd_filename[cdrom_index] == NULL) &&
8279
        fd_filename[0] == NULL &&
8280
        pflash_filename[0] == NULL)
8281
        help(1);
8282

    
8283
    /* boot to floppy or the default cd if no hard disk defined yet */
8284
    if (!boot_devices[0]) {
8285
        if (hd_filename[0] != NULL)
8286
            boot_devices = "c";
8287
        else if (fd_filename[0] != NULL)
8288
            boot_devices = "a";
8289
        else
8290
            boot_devices = "d";
8291
    }
8292
    setvbuf(stdout, NULL, _IOLBF, 0);
8293

    
8294
    init_timers();
8295
    init_timer_alarm();
8296
    qemu_aio_init();
8297

    
8298
#ifdef _WIN32
8299
    socket_init();
8300
#endif
8301

    
8302
    /* init network clients */
8303
    if (nb_net_clients == 0) {
8304
        /* if no clients, we use a default config */
8305
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
8306
                "nic");
8307
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
8308
                "user");
8309
        nb_net_clients = 2;
8310
    }
8311

    
8312
    for(i = 0;i < nb_net_clients; i++) {
8313
        if (net_client_init(net_clients[i]) < 0)
8314
            exit(1);
8315
    }
8316
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8317
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8318
            continue;
8319
        if (vlan->nb_guest_devs == 0) {
8320
            fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8321
            exit(1);
8322
        }
8323
        if (vlan->nb_host_devs == 0)
8324
            fprintf(stderr,
8325
                    "Warning: vlan %d is not connected to host network\n",
8326
                    vlan->id);
8327
    }
8328

    
8329
#ifdef TARGET_I386
8330
    /* XXX: this should be moved in the PC machine instanciation code */
8331
    if (net_boot != 0) {
8332
        int netroms = 0;
8333
        for (i = 0; i < nb_nics && i < 4; i++) {
8334
            const char *model = nd_table[i].model;
8335
            char buf[1024];
8336
            if (net_boot & (1 << i)) {
8337
                if (model == NULL)
8338
                    model = "ne2k_pci";
8339
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8340
                if (get_image_size(buf) > 0) {
8341
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8342
                        fprintf(stderr, "Too many option ROMs\n");
8343
                        exit(1);
8344
                    }
8345
                    option_rom[nb_option_roms] = strdup(buf);
8346
                    nb_option_roms++;
8347
                    netroms++;
8348
                }
8349
            }
8350
        }
8351
        if (netroms == 0) {
8352
            fprintf(stderr, "No valid PXE rom found for network device\n");
8353
            exit(1);
8354
        }
8355
    }
8356
#endif
8357

    
8358
    /* init the memory */
8359
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8360

    
8361
    phys_ram_base = qemu_vmalloc(phys_ram_size);
8362
    if (!phys_ram_base) {
8363
        fprintf(stderr, "Could not allocate physical memory\n");
8364
        exit(1);
8365
    }
8366

    
8367
    /* we always create the cdrom drive, even if no disk is there */
8368
    bdrv_init();
8369
    if (cdrom_index >= 0) {
8370
        bs_table[cdrom_index] = bdrv_new("cdrom");
8371
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8372
    }
8373

    
8374
    /* open the virtual block devices */
8375
    for(i = 0; i < MAX_DISKS; i++) {
8376
        if (hd_filename[i]) {
8377
            if (!bs_table[i]) {
8378
                char buf[64];
8379
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8380
                bs_table[i] = bdrv_new(buf);
8381
            }
8382
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8383
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8384
                        hd_filename[i]);
8385
                exit(1);
8386
            }
8387
            if (i == 0 && cyls != 0) {
8388
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8389
                bdrv_set_translation_hint(bs_table[i], translation);
8390
            }
8391
        }
8392
    }
8393

    
8394
    /* we always create at least one floppy disk */
8395
    fd_table[0] = bdrv_new("fda");
8396
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8397

    
8398
    for(i = 0; i < MAX_FD; i++) {
8399
        if (fd_filename[i]) {
8400
            if (!fd_table[i]) {
8401
                char buf[64];
8402
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8403
                fd_table[i] = bdrv_new(buf);
8404
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8405
            }
8406
            if (fd_filename[i][0] != '\0') {
8407
                if (bdrv_open(fd_table[i], fd_filename[i],
8408
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8409
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8410
                            fd_filename[i]);
8411
                    exit(1);
8412
                }
8413
            }
8414
        }
8415
    }
8416

    
8417
    /* Open the virtual parallel flash block devices */
8418
    for(i = 0; i < MAX_PFLASH; i++) {
8419
        if (pflash_filename[i]) {
8420
            if (!pflash_table[i]) {
8421
                char buf[64];
8422
                snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8423
                pflash_table[i] = bdrv_new(buf);
8424
            }
8425
            if (bdrv_open(pflash_table[i], pflash_filename[i],
8426
                          snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8427
                fprintf(stderr, "qemu: could not open flash image '%s'\n",
8428
                        pflash_filename[i]);
8429
                exit(1);
8430
            }
8431
        }
8432
    }
8433

    
8434
    sd_bdrv = bdrv_new ("sd");
8435
    /* FIXME: This isn't really a floppy, but it's a reasonable
8436
       approximation.  */
8437
    bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8438
    if (sd_filename) {
8439
        if (bdrv_open(sd_bdrv, sd_filename,
8440
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8441
            fprintf(stderr, "qemu: could not open SD card image %s\n",
8442
                    sd_filename);
8443
        } else
8444
            qemu_key_check(sd_bdrv, sd_filename);
8445
    }
8446

    
8447
    if (mtd_filename) {
8448
        mtd_bdrv = bdrv_new ("mtd");
8449
        if (bdrv_open(mtd_bdrv, mtd_filename,
8450
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8451
            qemu_key_check(mtd_bdrv, mtd_filename)) {
8452
            fprintf(stderr, "qemu: could not open Flash image %s\n",
8453
                    mtd_filename);
8454
            bdrv_delete(mtd_bdrv);
8455
            mtd_bdrv = 0;
8456
        }
8457
    }
8458

    
8459
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8460
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8461

    
8462
    init_ioports();
8463

    
8464
    /* terminal init */
8465
    memset(&display_state, 0, sizeof(display_state));
8466
    if (nographic) {
8467
        /* nearly nothing to do */
8468
        dumb_display_init(ds);
8469
    } else if (vnc_display != NULL) {
8470
        vnc_display_init(ds);
8471
        if (vnc_display_open(ds, vnc_display) < 0)
8472
            exit(1);
8473
    } else {
8474
#if defined(CONFIG_SDL)
8475
        sdl_display_init(ds, full_screen, no_frame);
8476
#elif defined(CONFIG_COCOA)
8477
        cocoa_display_init(ds, full_screen);
8478
#else
8479
        dumb_display_init(ds);
8480
#endif
8481
    }
8482

    
8483
    /* Maintain compatibility with multiple stdio monitors */
8484
    if (!strcmp(monitor_device,"stdio")) {
8485
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8486
            if (!strcmp(serial_devices[i],"mon:stdio")) {
8487
                monitor_device[0] = '\0';
8488
                break;
8489
            } else if (!strcmp(serial_devices[i],"stdio")) {
8490
                monitor_device[0] = '\0';
8491
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8492
                break;
8493
            }
8494
        }
8495
    }
8496
    if (monitor_device[0] != '\0') {
8497
        monitor_hd = qemu_chr_open(monitor_device);
8498
        if (!monitor_hd) {
8499
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8500
            exit(1);
8501
        }
8502
        monitor_init(monitor_hd, !nographic);
8503
    }
8504

    
8505
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8506
        const char *devname = serial_devices[i];
8507
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8508
            serial_hds[i] = qemu_chr_open(devname);
8509
            if (!serial_hds[i]) {
8510
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
8511
                        devname);
8512
                exit(1);
8513
            }
8514
            if (strstart(devname, "vc", 0))
8515
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8516
        }
8517
    }
8518

    
8519
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8520
        const char *devname = parallel_devices[i];
8521
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8522
            parallel_hds[i] = qemu_chr_open(devname);
8523
            if (!parallel_hds[i]) {
8524
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8525
                        devname);
8526
                exit(1);
8527
            }
8528
            if (strstart(devname, "vc", 0))
8529
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8530
        }
8531
    }
8532

    
8533
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
8534
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8535

    
8536
    /* init USB devices */
8537
    if (usb_enabled) {
8538
        for(i = 0; i < usb_devices_index; i++) {
8539
            if (usb_device_add(usb_devices[i]) < 0) {
8540
                fprintf(stderr, "Warning: could not add USB device %s\n",
8541
                        usb_devices[i]);
8542
            }
8543
        }
8544
    }
8545

    
8546
    if (display_state.dpy_refresh) {
8547
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8548
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8549
    }
8550

    
8551
#ifdef CONFIG_GDBSTUB
8552
    if (use_gdbstub) {
8553
        /* XXX: use standard host:port notation and modify options
8554
           accordingly. */
8555
        if (gdbserver_start(gdbstub_port) < 0) {
8556
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8557
                    gdbstub_port);
8558
            exit(1);
8559
        }
8560
    }
8561
#endif
8562

    
8563
    if (loadvm)
8564
        do_loadvm(loadvm);
8565

    
8566
    {
8567
        /* XXX: simplify init */
8568
        read_passwords();
8569
        if (autostart) {
8570
            vm_start();
8571
        }
8572
    }
8573

    
8574
    if (daemonize) {
8575
        uint8_t status = 0;
8576
        ssize_t len;
8577
        int fd;
8578

    
8579
    again1:
8580
        len = write(fds[1], &status, 1);
8581
        if (len == -1 && (errno == EINTR))
8582
            goto again1;
8583

    
8584
        if (len != 1)
8585
            exit(1);
8586

    
8587
        TFR(fd = open("/dev/null", O_RDWR));
8588
        if (fd == -1)
8589
            exit(1);
8590

    
8591
        dup2(fd, 0);
8592
        dup2(fd, 1);
8593
        dup2(fd, 2);
8594

    
8595
        close(fd);
8596
    }
8597

    
8598
    main_loop();
8599
    quit_timers();
8600

    
8601
#if !defined(_WIN32)
8602
    /* close network clients */
8603
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8604
        VLANClientState *vc;
8605

    
8606
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8607
            if (vc->fd_read == tap_receive) {
8608
                char ifname[64];
8609
                TAPState *s = vc->opaque;
8610

    
8611
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8612
                    s->down_script[0])
8613
                    launch_script(s->down_script, ifname, s->fd);
8614
            }
8615
    }
8616
    }
8617
#endif
8618
    return 0;
8619
}