Statistics
| Branch: | Revision:

root / vl.c @ 3e3f6754

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
370
/***********************************************************/
371

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

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

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

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

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

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

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

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

    
478
/***********************************************************/
479
/* keyboard/mouse */
480

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

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

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

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

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

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

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

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

    
520
    return s;
521
}
522

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

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

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

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

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

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

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

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

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

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

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

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

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

    
597
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
598
}
599

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

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

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

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

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

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

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

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

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

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

    
670
#define QEMU_TIMER_BASE 1000000000LL
671

    
672
#ifdef WIN32
673

    
674
static int64_t clock_freq;
675

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

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

    
695
#else
696

    
697
static int use_rt_clock;
698

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

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

    
730
#endif
731

    
732
/***********************************************************/
733
/* guest cycle counter */
734

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

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

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

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

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

    
791
/***********************************************************/
792
/* timers */
793

    
794
#define QEMU_TIMER_REALTIME 0
795
#define QEMU_TIMER_VIRTUAL  1
796

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

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

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

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

    
820
#define ALARM_FLAG_DYNTICKS  0x1
821

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

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

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

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

    
838
static struct qemu_alarm_timer *alarm_timer;
839

    
840
#ifdef _WIN32
841

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

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

    
852
#else
853

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

    
857
#ifdef __linux__
858

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

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

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

    
869
#endif /* __linux__ */
870

    
871
#endif /* _WIN32 */
872

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

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

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

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

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

    
915
    arg = strdup(opt);
916

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

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

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

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

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

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

    
946
    free(arg);
947

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

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

    
958
QEMUClock *rt_clock;
959
QEMUClock *vm_clock;
960

    
961
static QEMUTimer *active_timers[2];
962

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

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

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

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

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

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

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

    
1015
    qemu_del_timer(ts);
1016

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1217
    return nearest_delta_us;
1218
}
1219

    
1220
#ifndef _WIN32
1221

    
1222
#if defined(__linux__)
1223

    
1224
#define RTC_FREQ 1024
1225

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

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

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

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

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

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

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

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

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

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

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

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

    
1286
    close(fd);
1287
}
1288

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

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

    
1308
    enable_sigio_timer(rtc_fd);
1309

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

    
1312
    return 0;
1313
}
1314

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

    
1319
    close(rtc_fd);
1320
}
1321

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

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

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

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

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

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

    
1344
        return -1;
1345
    }
1346

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

    
1349
    return 0;
1350
}
1351

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

    
1356
    timer_delete(host_timer);
1357
}
1358

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

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

    
1370
    nearest_delta_us = qemu_next_deadline();
1371

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

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

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

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

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

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

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

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

    
1418
    return 0;
1419
}
1420

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

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

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

    
1431
#ifdef _WIN32
1432

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

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

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

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

    
1451
    timeBeginPeriod(data->period);
1452

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

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

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

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

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

    
1475
    return 0;
1476
}
1477

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

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

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

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

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

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

    
1500
    timeKillEvent(data->timerId);
1501

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

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

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

    
1517
#endif /* _WIN32 */
1518

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

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

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

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

    
1538
    alarm_timer = t;
1539
}
1540

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

    
1547
/***********************************************************/
1548
/* character device */
1549

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

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

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

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

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

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

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

    
1597

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

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

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

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

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

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

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

    
1659

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1856

    
1857
#ifdef _WIN32
1858

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

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

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

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

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

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

    
1908
#else
1909

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

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

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

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

    
1941
#ifndef _WIN32
1942

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

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

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

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

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

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

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

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

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

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

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

    
2022
    qemu_chr_reset(chr);
2023

    
2024
    return chr;
2025
}
2026

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

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

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

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

    
2058

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

    
2062
#define TERM_FIFO_MAX_SIZE 1
2063

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

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

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

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

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

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

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

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

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

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

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

    
2136
    atexit(term_exit);
2137

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

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

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

    
2152
    return chr;
2153
}
2154

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2460
    qemu_chr_reset(chr);
2461

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

    
2466
#else /* _WIN32 */
2467

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2646
    win_chr_readfile(chr);
2647
}
2648

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

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

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

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

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

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

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

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

    
2716
    s->fpipe = TRUE;
2717

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

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

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

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

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

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

    
2770

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

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

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

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

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

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

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

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

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

    
2835
/***********************************************************/
2836
/* UDP Net console */
2837

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2960
/***********************************************************/
2961
/* TCP Net console */
2962

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

    
2972
static void tcp_chr_accept(void *opaque);
2973

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

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

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

    
3010
    int i;
3011
    int j = 0;
3012

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3384
/***********************************************************/
3385
/* network device redirectors */
3386

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3536
    return 0;
3537
}
3538
#endif
3539

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

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

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

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

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

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

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

    
3612
#if defined(CONFIG_SLIRP)
3613

    
3614
/* slirp network adapter */
3615

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

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

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

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

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

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

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

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

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

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

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

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

    
3708
#ifndef _WIN32
3709

    
3710
char smb_dir[1024];
3711

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

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

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

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

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

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

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

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

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

    
3796
#endif /* CONFIG_SLIRP */
3797

    
3798
#if !defined(_WIN32)
3799

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

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

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

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

    
3839
/* fd support */
3840

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3980
    close (if_fd);
3981

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

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

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

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

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

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

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

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

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

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

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

    
4106
#endif /* !_WIN32 */
4107

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4502

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

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

    
4511
    s->dgram_dst = saddr;
4512

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

    
4518
}
4519

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

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

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

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

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

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

    
4695
    return ret;
4696
}
4697

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

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

    
4710
/***********************************************************/
4711
/* USB devices */
4712

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4864
/***********************************************************/
4865
/* PCMCIA/Cardbus */
4866

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

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

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

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

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

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

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

    
4906
/***********************************************************/
4907
/* dumb display */
4908

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

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

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

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

    
4934
/***********************************************************/
4935
/* I/O handling */
4936

    
4937
#define MAX_IO_HANDLERS 64
4938

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

    
4951
static IOHandlerRecord *first_io_handler;
4952

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

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

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

    
5004
/***********************************************************/
5005
/* Polling handling */
5006

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

    
5013
static PollingEntry *first_polling_entry;
5014

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

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

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

    
5051
static WaitObjects wait_objects = {0};
5052

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

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

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

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

    
5086
/***********************************************************/
5087
/* savevm/loadvm support */
5088

    
5089
#define IO_BUF_SIZE 32768
5090

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5331
static SaveStateEntry *first_se;
5332

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5599
    /* create the snapshots */
5600

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5757
/***********************************************************/
5758
/* cpu save/restore */
5759

    
5760
#if defined(TARGET_I386)
5761

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
6111
#elif defined(TARGET_ARM)
6112

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
6299
    return 0;
6300
}
6301

    
6302
#else
6303

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

    
6306
#endif
6307

    
6308
/***********************************************************/
6309
/* ram save/restore */
6310

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
6576
static QEMUBH *first_bh = NULL;
6577

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

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

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

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

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

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

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

    
6641
/***********************************************************/
6642
/* machine registration */
6643

    
6644
QEMUMachine *first_machine = NULL;
6645

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

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

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

    
6668
/***********************************************************/
6669
/* main execution loop */
6670

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

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

    
6684
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6685

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

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

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

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

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

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

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

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

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

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

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

    
6756
/* reset/shutdown handler */
6757

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

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

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

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

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

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

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

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

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

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

    
6829

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

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

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

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

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

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

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

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

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

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

    
6951
}
6952

    
6953
static CPUState *cur_cpu;
6954

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

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

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

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

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

    
7177
#define HAS_ARG 0x0001
7178

    
7179
enum {
7180
    QEMU_OPTION_h,
7181

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

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

    
7213
    QEMU_OPTION_kernel,
7214
    QEMU_OPTION_append,
7215
    QEMU_OPTION_initrd,
7216

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

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

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

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

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

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

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

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

    
7369
/* password input */
7370

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

    
7376
    if (!bdrv_is_encrypted(bs))
7377
        return 0;
7378

    
7379
    term_printf("%s is encrypted.\n", name);
7380
    for(i = 0; i < 3; i++) {
7381
        monitor_readline("Password: ", 1, password, sizeof(password));
7382
        if (bdrv_set_key(bs, password) == 0)
7383
            return 0;
7384
        term_printf("invalid password\n");
7385
    }
7386
    return -EPERM;
7387
}
7388

    
7389
static BlockDriverState *get_bdrv(int index)
7390
{
7391
    BlockDriverState *bs;
7392

    
7393
    if (index < 4) {
7394
        bs = bs_table[index];
7395
    } else if (index < 6) {
7396
        bs = fd_table[index - 4];
7397
    } else {
7398
        bs = NULL;
7399
    }
7400
    return bs;
7401
}
7402

    
7403
static void read_passwords(void)
7404
{
7405
    BlockDriverState *bs;
7406
    int i;
7407

    
7408
    for(i = 0; i < 6; i++) {
7409
        bs = get_bdrv(i);
7410
        if (bs)
7411
            qemu_key_check(bs, bdrv_get_device_name(bs));
7412
    }
7413
}
7414

    
7415
/* XXX: currently we cannot use simultaneously different CPUs */
7416
static void register_machines(void)
7417
{
7418
#if defined(TARGET_I386)
7419
    qemu_register_machine(&pc_machine);
7420
    qemu_register_machine(&isapc_machine);
7421
#elif defined(TARGET_PPC)
7422
    qemu_register_machine(&heathrow_machine);
7423
    qemu_register_machine(&core99_machine);
7424
    qemu_register_machine(&prep_machine);
7425
    qemu_register_machine(&ref405ep_machine);
7426
    qemu_register_machine(&taihu_machine);
7427
#elif defined(TARGET_MIPS)
7428
    qemu_register_machine(&mips_machine);
7429
    qemu_register_machine(&mips_malta_machine);
7430
    qemu_register_machine(&mips_pica61_machine);
7431
    qemu_register_machine(&mips_mipssim_machine);
7432
#elif defined(TARGET_SPARC)
7433
#ifdef TARGET_SPARC64
7434
    qemu_register_machine(&sun4u_machine);
7435
#else
7436
    qemu_register_machine(&ss5_machine);
7437
    qemu_register_machine(&ss10_machine);
7438
    qemu_register_machine(&ss600mp_machine);
7439
#endif
7440
#elif defined(TARGET_ARM)
7441
    qemu_register_machine(&integratorcp_machine);
7442
    qemu_register_machine(&versatilepb_machine);
7443
    qemu_register_machine(&versatileab_machine);
7444
    qemu_register_machine(&realview_machine);
7445
    qemu_register_machine(&akitapda_machine);
7446
    qemu_register_machine(&spitzpda_machine);
7447
    qemu_register_machine(&borzoipda_machine);
7448
    qemu_register_machine(&terrierpda_machine);
7449
    qemu_register_machine(&palmte_machine);
7450
    qemu_register_machine(&lm3s811evb_machine);
7451
    qemu_register_machine(&lm3s6965evb_machine);
7452
    qemu_register_machine(&connex_machine);
7453
    qemu_register_machine(&verdex_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
}