Statistics
| Branch: | Revision:

root / vl.c @ 7e0af5d0

History | View | Annotate | Download (220 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 "vl.h"
25

    
26
#include <unistd.h>
27
#include <fcntl.h>
28
#include <signal.h>
29
#include <time.h>
30
#include <errno.h>
31
#include <sys/time.h>
32
#include <zlib.h>
33

    
34
#ifndef _WIN32
35
#include <sys/times.h>
36
#include <sys/wait.h>
37
#include <termios.h>
38
#include <sys/poll.h>
39
#include <sys/mman.h>
40
#include <sys/ioctl.h>
41
#include <sys/socket.h>
42
#include <netinet/in.h>
43
#include <dirent.h>
44
#include <netdb.h>
45
#include <sys/select.h>
46
#include <arpa/inet.h>
47
#ifdef _BSD
48
#include <sys/stat.h>
49
#ifndef __APPLE__
50
#include <libutil.h>
51
#endif
52
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
53
#include <freebsd/stdlib.h>
54
#else
55
#ifndef __sun__
56
#include <linux/if.h>
57
#include <linux/if_tun.h>
58
#include <pty.h>
59
#include <malloc.h>
60
#include <linux/rtc.h>
61

    
62
/* For the benefit of older linux systems which don't supply it,
63
   we use a local copy of hpet.h. */
64
/* #include <linux/hpet.h> */
65
#include "hpet.h"
66

    
67
#include <linux/ppdev.h>
68
#include <linux/parport.h>
69
#else
70
#include <sys/stat.h>
71
#include <sys/ethernet.h>
72
#include <sys/sockio.h>
73
#include <netinet/arp.h>
74
#include <netinet/in.h>
75
#include <netinet/in_systm.h>
76
#include <netinet/ip.h>
77
#include <netinet/ip_icmp.h> // must come after ip.h
78
#include <netinet/udp.h>
79
#include <netinet/tcp.h>
80
#include <net/if.h>
81
#include <syslog.h>
82
#include <stropts.h>
83
#endif
84
#endif
85
#else
86
#include <winsock2.h>
87
int inet_aton(const char *cp, struct in_addr *ia);
88
#endif
89

    
90
#if defined(CONFIG_SLIRP)
91
#include "libslirp.h"
92
#endif
93

    
94
#ifdef _WIN32
95
#include <malloc.h>
96
#include <sys/timeb.h>
97
#include <windows.h>
98
#define getopt_long_only getopt_long
99
#define memalign(align, size) malloc(size)
100
#endif
101

    
102
#include "qemu_socket.h"
103

    
104
#ifdef CONFIG_SDL
105
#ifdef __APPLE__
106
#include <SDL/SDL.h>
107
#endif
108
#endif /* CONFIG_SDL */
109

    
110
#ifdef CONFIG_COCOA
111
#undef main
112
#define main qemu_main
113
#endif /* CONFIG_COCOA */
114

    
115
#include "disas.h"
116

    
117
#include "exec-all.h"
118

    
119
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
120
#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
121
#ifdef __sun__
122
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
123
#else
124
#define SMBD_COMMAND "/usr/sbin/smbd"
125
#endif
126

    
127
//#define DEBUG_UNUSED_IOPORT
128
//#define DEBUG_IOPORT
129

    
130
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
131

    
132
#ifdef TARGET_PPC
133
#define DEFAULT_RAM_SIZE 144
134
#else
135
#define DEFAULT_RAM_SIZE 128
136
#endif
137
/* in ms */
138
#define GUI_REFRESH_INTERVAL 30
139

    
140
/* Max number of USB devices that can be specified on the commandline.  */
141
#define MAX_USB_CMDLINE 8
142

    
143
/* XXX: use a two level table to limit memory usage */
144
#define MAX_IOPORTS 65536
145

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

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

    
230
/***********************************************************/
231
/* x86 ISA bus support */
232

    
233
target_phys_addr_t isa_mem_base = 0;
234
PicState2 *isa_pic;
235

    
236
uint32_t default_ioport_readb(void *opaque, uint32_t address)
237
{
238
#ifdef DEBUG_UNUSED_IOPORT
239
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
240
#endif
241
    return 0xff;
242
}
243

    
244
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
245
{
246
#ifdef DEBUG_UNUSED_IOPORT
247
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
248
#endif
249
}
250

    
251
/* default is to make two byte accesses */
252
uint32_t default_ioport_readw(void *opaque, uint32_t address)
253
{
254
    uint32_t data;
255
    data = ioport_read_table[0][address](ioport_opaque[address], address);
256
    address = (address + 1) & (MAX_IOPORTS - 1);
257
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
258
    return data;
259
}
260

    
261
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
262
{
263
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
264
    address = (address + 1) & (MAX_IOPORTS - 1);
265
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
266
}
267

    
268
uint32_t default_ioport_readl(void *opaque, uint32_t address)
269
{
270
#ifdef DEBUG_UNUSED_IOPORT
271
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
272
#endif
273
    return 0xffffffff;
274
}
275

    
276
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
277
{
278
#ifdef DEBUG_UNUSED_IOPORT
279
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
280
#endif
281
}
282

    
283
void init_ioports(void)
284
{
285
    int i;
286

    
287
    for(i = 0; i < MAX_IOPORTS; i++) {
288
        ioport_read_table[0][i] = default_ioport_readb;
289
        ioport_write_table[0][i] = default_ioport_writeb;
290
        ioport_read_table[1][i] = default_ioport_readw;
291
        ioport_write_table[1][i] = default_ioport_writew;
292
        ioport_read_table[2][i] = default_ioport_readl;
293
        ioport_write_table[2][i] = default_ioport_writel;
294
    }
295
}
296

    
297
/* size is the word size in byte */
298
int register_ioport_read(int start, int length, int size,
299
                         IOPortReadFunc *func, void *opaque)
300
{
301
    int i, bsize;
302

    
303
    if (size == 1) {
304
        bsize = 0;
305
    } else if (size == 2) {
306
        bsize = 1;
307
    } else if (size == 4) {
308
        bsize = 2;
309
    } else {
310
        hw_error("register_ioport_read: invalid size");
311
        return -1;
312
    }
313
    for(i = start; i < start + length; i += size) {
314
        ioport_read_table[bsize][i] = func;
315
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
316
            hw_error("register_ioport_read: invalid opaque");
317
        ioport_opaque[i] = opaque;
318
    }
319
    return 0;
320
}
321

    
322
/* size is the word size in byte */
323
int register_ioport_write(int start, int length, int size,
324
                          IOPortWriteFunc *func, void *opaque)
325
{
326
    int i, bsize;
327

    
328
    if (size == 1) {
329
        bsize = 0;
330
    } else if (size == 2) {
331
        bsize = 1;
332
    } else if (size == 4) {
333
        bsize = 2;
334
    } else {
335
        hw_error("register_ioport_write: invalid size");
336
        return -1;
337
    }
338
    for(i = start; i < start + length; i += size) {
339
        ioport_write_table[bsize][i] = func;
340
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
341
            hw_error("register_ioport_write: invalid opaque");
342
        ioport_opaque[i] = opaque;
343
    }
344
    return 0;
345
}
346

    
347
void isa_unassign_ioport(int start, int length)
348
{
349
    int i;
350

    
351
    for(i = start; i < start + length; i++) {
352
        ioport_read_table[0][i] = default_ioport_readb;
353
        ioport_read_table[1][i] = default_ioport_readw;
354
        ioport_read_table[2][i] = default_ioport_readl;
355

    
356
        ioport_write_table[0][i] = default_ioport_writeb;
357
        ioport_write_table[1][i] = default_ioport_writew;
358
        ioport_write_table[2][i] = default_ioport_writel;
359
    }
360
}
361

    
362
/***********************************************************/
363

    
364
void cpu_outb(CPUState *env, int addr, int val)
365
{
366
#ifdef DEBUG_IOPORT
367
    if (loglevel & CPU_LOG_IOPORT)
368
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
369
#endif
370
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
371
#ifdef USE_KQEMU
372
    if (env)
373
        env->last_io_time = cpu_get_time_fast();
374
#endif
375
}
376

    
377
void cpu_outw(CPUState *env, int addr, int val)
378
{
379
#ifdef DEBUG_IOPORT
380
    if (loglevel & CPU_LOG_IOPORT)
381
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
382
#endif
383
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
384
#ifdef USE_KQEMU
385
    if (env)
386
        env->last_io_time = cpu_get_time_fast();
387
#endif
388
}
389

    
390
void cpu_outl(CPUState *env, int addr, int val)
391
{
392
#ifdef DEBUG_IOPORT
393
    if (loglevel & CPU_LOG_IOPORT)
394
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
395
#endif
396
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
397
#ifdef USE_KQEMU
398
    if (env)
399
        env->last_io_time = cpu_get_time_fast();
400
#endif
401
}
402

    
403
int cpu_inb(CPUState *env, int addr)
404
{
405
    int val;
406
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
407
#ifdef DEBUG_IOPORT
408
    if (loglevel & CPU_LOG_IOPORT)
409
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
410
#endif
411
#ifdef USE_KQEMU
412
    if (env)
413
        env->last_io_time = cpu_get_time_fast();
414
#endif
415
    return val;
416
}
417

    
418
int cpu_inw(CPUState *env, int addr)
419
{
420
    int val;
421
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
422
#ifdef DEBUG_IOPORT
423
    if (loglevel & CPU_LOG_IOPORT)
424
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
425
#endif
426
#ifdef USE_KQEMU
427
    if (env)
428
        env->last_io_time = cpu_get_time_fast();
429
#endif
430
    return val;
431
}
432

    
433
int cpu_inl(CPUState *env, int addr)
434
{
435
    int val;
436
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
437
#ifdef DEBUG_IOPORT
438
    if (loglevel & CPU_LOG_IOPORT)
439
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
440
#endif
441
#ifdef USE_KQEMU
442
    if (env)
443
        env->last_io_time = cpu_get_time_fast();
444
#endif
445
    return val;
446
}
447

    
448
/***********************************************************/
449
void hw_error(const char *fmt, ...)
450
{
451
    va_list ap;
452
    CPUState *env;
453

    
454
    va_start(ap, fmt);
455
    fprintf(stderr, "qemu: hardware error: ");
456
    vfprintf(stderr, fmt, ap);
457
    fprintf(stderr, "\n");
458
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
459
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
460
#ifdef TARGET_I386
461
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
462
#else
463
        cpu_dump_state(env, stderr, fprintf, 0);
464
#endif
465
    }
466
    va_end(ap);
467
    abort();
468
}
469

    
470
/***********************************************************/
471
/* keyboard/mouse */
472

    
473
static QEMUPutKBDEvent *qemu_put_kbd_event;
474
static void *qemu_put_kbd_event_opaque;
475
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
476
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
477

    
478
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
479
{
480
    qemu_put_kbd_event_opaque = opaque;
481
    qemu_put_kbd_event = func;
482
}
483

    
484
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
485
                                                void *opaque, int absolute,
486
                                                const char *name)
487
{
488
    QEMUPutMouseEntry *s, *cursor;
489

    
490
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
491
    if (!s)
492
        return NULL;
493

    
494
    s->qemu_put_mouse_event = func;
495
    s->qemu_put_mouse_event_opaque = opaque;
496
    s->qemu_put_mouse_event_absolute = absolute;
497
    s->qemu_put_mouse_event_name = qemu_strdup(name);
498
    s->next = NULL;
499

    
500
    if (!qemu_put_mouse_event_head) {
501
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
502
        return s;
503
    }
504

    
505
    cursor = qemu_put_mouse_event_head;
506
    while (cursor->next != NULL)
507
        cursor = cursor->next;
508

    
509
    cursor->next = s;
510
    qemu_put_mouse_event_current = s;
511

    
512
    return s;
513
}
514

    
515
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
516
{
517
    QEMUPutMouseEntry *prev = NULL, *cursor;
518

    
519
    if (!qemu_put_mouse_event_head || entry == NULL)
520
        return;
521

    
522
    cursor = qemu_put_mouse_event_head;
523
    while (cursor != NULL && cursor != entry) {
524
        prev = cursor;
525
        cursor = cursor->next;
526
    }
527

    
528
    if (cursor == NULL) // does not exist or list empty
529
        return;
530
    else if (prev == NULL) { // entry is head
531
        qemu_put_mouse_event_head = cursor->next;
532
        if (qemu_put_mouse_event_current == entry)
533
            qemu_put_mouse_event_current = cursor->next;
534
        qemu_free(entry->qemu_put_mouse_event_name);
535
        qemu_free(entry);
536
        return;
537
    }
538

    
539
    prev->next = entry->next;
540

    
541
    if (qemu_put_mouse_event_current == entry)
542
        qemu_put_mouse_event_current = prev;
543

    
544
    qemu_free(entry->qemu_put_mouse_event_name);
545
    qemu_free(entry);
546
}
547

    
548
void kbd_put_keycode(int keycode)
549
{
550
    if (qemu_put_kbd_event) {
551
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
552
    }
553
}
554

    
555
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
556
{
557
    QEMUPutMouseEvent *mouse_event;
558
    void *mouse_event_opaque;
559
    int width;
560

    
561
    if (!qemu_put_mouse_event_current) {
562
        return;
563
    }
564

    
565
    mouse_event =
566
        qemu_put_mouse_event_current->qemu_put_mouse_event;
567
    mouse_event_opaque =
568
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
569

    
570
    if (mouse_event) {
571
        if (graphic_rotate) {
572
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
573
                width = 0x7fff;
574
            else
575
                width = graphic_width;
576
            mouse_event(mouse_event_opaque,
577
                                 width - dy, dx, dz, buttons_state);
578
        } else
579
            mouse_event(mouse_event_opaque,
580
                                 dx, dy, dz, buttons_state);
581
    }
582
}
583

    
584
int kbd_mouse_is_absolute(void)
585
{
586
    if (!qemu_put_mouse_event_current)
587
        return 0;
588

    
589
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
590
}
591

    
592
void do_info_mice(void)
593
{
594
    QEMUPutMouseEntry *cursor;
595
    int index = 0;
596

    
597
    if (!qemu_put_mouse_event_head) {
598
        term_printf("No mouse devices connected\n");
599
        return;
600
    }
601

    
602
    term_printf("Mouse devices available:\n");
603
    cursor = qemu_put_mouse_event_head;
604
    while (cursor != NULL) {
605
        term_printf("%c Mouse #%d: %s\n",
606
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
607
                    index, cursor->qemu_put_mouse_event_name);
608
        index++;
609
        cursor = cursor->next;
610
    }
611
}
612

    
613
void do_mouse_set(int index)
614
{
615
    QEMUPutMouseEntry *cursor;
616
    int i = 0;
617

    
618
    if (!qemu_put_mouse_event_head) {
619
        term_printf("No mouse devices connected\n");
620
        return;
621
    }
622

    
623
    cursor = qemu_put_mouse_event_head;
624
    while (cursor != NULL && index != i) {
625
        i++;
626
        cursor = cursor->next;
627
    }
628

    
629
    if (cursor != NULL)
630
        qemu_put_mouse_event_current = cursor;
631
    else
632
        term_printf("Mouse at given index not found\n");
633
}
634

    
635
/* compute with 96 bit intermediate result: (a*b)/c */
636
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
637
{
638
    union {
639
        uint64_t ll;
640
        struct {
641
#ifdef WORDS_BIGENDIAN
642
            uint32_t high, low;
643
#else
644
            uint32_t low, high;
645
#endif
646
        } l;
647
    } u, res;
648
    uint64_t rl, rh;
649

    
650
    u.ll = a;
651
    rl = (uint64_t)u.l.low * (uint64_t)b;
652
    rh = (uint64_t)u.l.high * (uint64_t)b;
653
    rh += (rl >> 32);
654
    res.l.high = rh / c;
655
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
656
    return res.ll;
657
}
658

    
659
/***********************************************************/
660
/* real time host monotonic timer */
661

    
662
#define QEMU_TIMER_BASE 1000000000LL
663

    
664
#ifdef WIN32
665

    
666
static int64_t clock_freq;
667

    
668
static void init_get_clock(void)
669
{
670
    LARGE_INTEGER freq;
671
    int ret;
672
    ret = QueryPerformanceFrequency(&freq);
673
    if (ret == 0) {
674
        fprintf(stderr, "Could not calibrate ticks\n");
675
        exit(1);
676
    }
677
    clock_freq = freq.QuadPart;
678
}
679

    
680
static int64_t get_clock(void)
681
{
682
    LARGE_INTEGER ti;
683
    QueryPerformanceCounter(&ti);
684
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
685
}
686

    
687
#else
688

    
689
static int use_rt_clock;
690

    
691
static void init_get_clock(void)
692
{
693
    use_rt_clock = 0;
694
#if defined(__linux__)
695
    {
696
        struct timespec ts;
697
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
698
            use_rt_clock = 1;
699
        }
700
    }
701
#endif
702
}
703

    
704
static int64_t get_clock(void)
705
{
706
#if defined(__linux__)
707
    if (use_rt_clock) {
708
        struct timespec ts;
709
        clock_gettime(CLOCK_MONOTONIC, &ts);
710
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
711
    } else
712
#endif
713
    {
714
        /* XXX: using gettimeofday leads to problems if the date
715
           changes, so it should be avoided. */
716
        struct timeval tv;
717
        gettimeofday(&tv, NULL);
718
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
719
    }
720
}
721

    
722
#endif
723

    
724
/***********************************************************/
725
/* guest cycle counter */
726

    
727
static int64_t cpu_ticks_prev;
728
static int64_t cpu_ticks_offset;
729
static int64_t cpu_clock_offset;
730
static int cpu_ticks_enabled;
731

    
732
/* return the host CPU cycle counter and handle stop/restart */
733
int64_t cpu_get_ticks(void)
734
{
735
    if (!cpu_ticks_enabled) {
736
        return cpu_ticks_offset;
737
    } else {
738
        int64_t ticks;
739
        ticks = cpu_get_real_ticks();
740
        if (cpu_ticks_prev > ticks) {
741
            /* Note: non increasing ticks may happen if the host uses
742
               software suspend */
743
            cpu_ticks_offset += cpu_ticks_prev - ticks;
744
        }
745
        cpu_ticks_prev = ticks;
746
        return ticks + cpu_ticks_offset;
747
    }
748
}
749

    
750
/* return the host CPU monotonic timer and handle stop/restart */
751
static int64_t cpu_get_clock(void)
752
{
753
    int64_t ti;
754
    if (!cpu_ticks_enabled) {
755
        return cpu_clock_offset;
756
    } else {
757
        ti = get_clock();
758
        return ti + cpu_clock_offset;
759
    }
760
}
761

    
762
/* enable cpu_get_ticks() */
763
void cpu_enable_ticks(void)
764
{
765
    if (!cpu_ticks_enabled) {
766
        cpu_ticks_offset -= cpu_get_real_ticks();
767
        cpu_clock_offset -= get_clock();
768
        cpu_ticks_enabled = 1;
769
    }
770
}
771

    
772
/* disable cpu_get_ticks() : the clock is stopped. You must not call
773
   cpu_get_ticks() after that.  */
774
void cpu_disable_ticks(void)
775
{
776
    if (cpu_ticks_enabled) {
777
        cpu_ticks_offset = cpu_get_ticks();
778
        cpu_clock_offset = cpu_get_clock();
779
        cpu_ticks_enabled = 0;
780
    }
781
}
782

    
783
/***********************************************************/
784
/* timers */
785

    
786
#define QEMU_TIMER_REALTIME 0
787
#define QEMU_TIMER_VIRTUAL  1
788

    
789
struct QEMUClock {
790
    int type;
791
    /* XXX: add frequency */
792
};
793

    
794
struct QEMUTimer {
795
    QEMUClock *clock;
796
    int64_t expire_time;
797
    QEMUTimerCB *cb;
798
    void *opaque;
799
    struct QEMUTimer *next;
800
};
801

    
802
struct qemu_alarm_timer {
803
    char const *name;
804
    unsigned int flags;
805

    
806
    int (*start)(struct qemu_alarm_timer *t);
807
    void (*stop)(struct qemu_alarm_timer *t);
808
    void (*rearm)(struct qemu_alarm_timer *t);
809
    void *priv;
810
};
811

    
812
#define ALARM_FLAG_DYNTICKS  0x1
813

    
814
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
815
{
816
    return t->flags & ALARM_FLAG_DYNTICKS;
817
}
818

    
819
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
820
{
821
    if (!alarm_has_dynticks(t))
822
        return;
823

    
824
    t->rearm(t);
825
}
826

    
827
/* TODO: MIN_TIMER_REARM_US should be optimized */
828
#define MIN_TIMER_REARM_US 250
829

    
830
static struct qemu_alarm_timer *alarm_timer;
831

    
832
#ifdef _WIN32
833

    
834
struct qemu_alarm_win32 {
835
    MMRESULT timerId;
836
    HANDLE host_alarm;
837
    unsigned int period;
838
} alarm_win32_data = {0, NULL, -1};
839

    
840
static int win32_start_timer(struct qemu_alarm_timer *t);
841
static void win32_stop_timer(struct qemu_alarm_timer *t);
842
static void win32_rearm_timer(struct qemu_alarm_timer *t);
843

    
844
#else
845

    
846
static int unix_start_timer(struct qemu_alarm_timer *t);
847
static void unix_stop_timer(struct qemu_alarm_timer *t);
848

    
849
#ifdef __linux__
850

    
851
static int dynticks_start_timer(struct qemu_alarm_timer *t);
852
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
853
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
854

    
855
static int hpet_start_timer(struct qemu_alarm_timer *t);
856
static void hpet_stop_timer(struct qemu_alarm_timer *t);
857

    
858
static int rtc_start_timer(struct qemu_alarm_timer *t);
859
static void rtc_stop_timer(struct qemu_alarm_timer *t);
860

    
861
#endif /* __linux__ */
862

    
863
#endif /* _WIN32 */
864

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

    
885
static void show_available_alarms()
886
{
887
    int i;
888

    
889
    printf("Available alarm timers, in order of precedence:\n");
890
    for (i = 0; alarm_timers[i].name; i++)
891
        printf("%s\n", alarm_timers[i].name);
892
}
893

    
894
static void configure_alarms(char const *opt)
895
{
896
    int i;
897
    int cur = 0;
898
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
899
    char *arg;
900
    char *name;
901

    
902
    if (!strcmp(opt, "help")) {
903
        show_available_alarms();
904
        exit(0);
905
    }
906

    
907
    arg = strdup(opt);
908

    
909
    /* Reorder the array */
910
    name = strtok(arg, ",");
911
    while (name) {
912
        struct qemu_alarm_timer tmp;
913

    
914
        for (i = 0; i < count && alarm_timers[i].name; i++) {
915
            if (!strcmp(alarm_timers[i].name, name))
916
                break;
917
        }
918

    
919
        if (i == count) {
920
            fprintf(stderr, "Unknown clock %s\n", name);
921
            goto next;
922
        }
923

    
924
        if (i < cur)
925
            /* Ignore */
926
            goto next;
927

    
928
        /* Swap */
929
        tmp = alarm_timers[i];
930
        alarm_timers[i] = alarm_timers[cur];
931
        alarm_timers[cur] = tmp;
932

    
933
        cur++;
934
next:
935
        name = strtok(NULL, ",");
936
    }
937

    
938
    free(arg);
939

    
940
    if (cur) {
941
        /* Disable remaining timers */
942
        for (i = cur; i < count; i++)
943
            alarm_timers[i].name = NULL;
944
    }
945

    
946
    /* debug */
947
    show_available_alarms();
948
}
949

    
950
QEMUClock *rt_clock;
951
QEMUClock *vm_clock;
952

    
953
static QEMUTimer *active_timers[2];
954

    
955
QEMUClock *qemu_new_clock(int type)
956
{
957
    QEMUClock *clock;
958
    clock = qemu_mallocz(sizeof(QEMUClock));
959
    if (!clock)
960
        return NULL;
961
    clock->type = type;
962
    return clock;
963
}
964

    
965
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
966
{
967
    QEMUTimer *ts;
968

    
969
    ts = qemu_mallocz(sizeof(QEMUTimer));
970
    ts->clock = clock;
971
    ts->cb = cb;
972
    ts->opaque = opaque;
973
    return ts;
974
}
975

    
976
void qemu_free_timer(QEMUTimer *ts)
977
{
978
    qemu_free(ts);
979
}
980

    
981
/* stop a timer, but do not dealloc it */
982
void qemu_del_timer(QEMUTimer *ts)
983
{
984
    QEMUTimer **pt, *t;
985

    
986
    /* NOTE: this code must be signal safe because
987
       qemu_timer_expired() can be called from a signal. */
988
    pt = &active_timers[ts->clock->type];
989
    for(;;) {
990
        t = *pt;
991
        if (!t)
992
            break;
993
        if (t == ts) {
994
            *pt = t->next;
995
            break;
996
        }
997
        pt = &t->next;
998
    }
999
}
1000

    
1001
/* modify the current timer so that it will be fired when current_time
1002
   >= expire_time. The corresponding callback will be called. */
1003
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1004
{
1005
    QEMUTimer **pt, *t;
1006

    
1007
    qemu_del_timer(ts);
1008

    
1009
    /* add the timer in the sorted list */
1010
    /* NOTE: this code must be signal safe because
1011
       qemu_timer_expired() can be called from a signal. */
1012
    pt = &active_timers[ts->clock->type];
1013
    for(;;) {
1014
        t = *pt;
1015
        if (!t)
1016
            break;
1017
        if (t->expire_time > expire_time)
1018
            break;
1019
        pt = &t->next;
1020
    }
1021
    ts->expire_time = expire_time;
1022
    ts->next = *pt;
1023
    *pt = ts;
1024
}
1025

    
1026
int qemu_timer_pending(QEMUTimer *ts)
1027
{
1028
    QEMUTimer *t;
1029
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1030
        if (t == ts)
1031
            return 1;
1032
    }
1033
    return 0;
1034
}
1035

    
1036
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1037
{
1038
    if (!timer_head)
1039
        return 0;
1040
    return (timer_head->expire_time <= current_time);
1041
}
1042

    
1043
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1044
{
1045
    QEMUTimer *ts;
1046

    
1047
    for(;;) {
1048
        ts = *ptimer_head;
1049
        if (!ts || ts->expire_time > current_time)
1050
            break;
1051
        /* remove timer from the list before calling the callback */
1052
        *ptimer_head = ts->next;
1053
        ts->next = NULL;
1054

    
1055
        /* run the callback (the timer list can be modified) */
1056
        ts->cb(ts->opaque);
1057
    }
1058
    qemu_rearm_alarm_timer(alarm_timer);
1059
}
1060

    
1061
int64_t qemu_get_clock(QEMUClock *clock)
1062
{
1063
    switch(clock->type) {
1064
    case QEMU_TIMER_REALTIME:
1065
        return get_clock() / 1000000;
1066
    default:
1067
    case QEMU_TIMER_VIRTUAL:
1068
        return cpu_get_clock();
1069
    }
1070
}
1071

    
1072
static void init_timers(void)
1073
{
1074
    init_get_clock();
1075
    ticks_per_sec = QEMU_TIMER_BASE;
1076
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1077
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1078
}
1079

    
1080
/* save a timer */
1081
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1082
{
1083
    uint64_t expire_time;
1084

    
1085
    if (qemu_timer_pending(ts)) {
1086
        expire_time = ts->expire_time;
1087
    } else {
1088
        expire_time = -1;
1089
    }
1090
    qemu_put_be64(f, expire_time);
1091
}
1092

    
1093
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1094
{
1095
    uint64_t expire_time;
1096

    
1097
    expire_time = qemu_get_be64(f);
1098
    if (expire_time != -1) {
1099
        qemu_mod_timer(ts, expire_time);
1100
    } else {
1101
        qemu_del_timer(ts);
1102
    }
1103
}
1104

    
1105
static void timer_save(QEMUFile *f, void *opaque)
1106
{
1107
    if (cpu_ticks_enabled) {
1108
        hw_error("cannot save state if virtual timers are running");
1109
    }
1110
    qemu_put_be64s(f, &cpu_ticks_offset);
1111
    qemu_put_be64s(f, &ticks_per_sec);
1112
    qemu_put_be64s(f, &cpu_clock_offset);
1113
}
1114

    
1115
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1116
{
1117
    if (version_id != 1 && version_id != 2)
1118
        return -EINVAL;
1119
    if (cpu_ticks_enabled) {
1120
        return -EINVAL;
1121
    }
1122
    qemu_get_be64s(f, &cpu_ticks_offset);
1123
    qemu_get_be64s(f, &ticks_per_sec);
1124
    if (version_id == 2) {
1125
        qemu_get_be64s(f, &cpu_clock_offset);
1126
    }
1127
    return 0;
1128
}
1129

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

    
1188
static uint64_t qemu_next_deadline(void)
1189
{
1190
    int64_t nearest_delta_us = INT64_MAX;
1191
    int64_t vmdelta_us;
1192

    
1193
    if (active_timers[QEMU_TIMER_REALTIME])
1194
        nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1195
                            qemu_get_clock(rt_clock))*1000;
1196

    
1197
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1198
        /* round up */
1199
        vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1200
                      qemu_get_clock(vm_clock)+999)/1000;
1201
        if (vmdelta_us < nearest_delta_us)
1202
            nearest_delta_us = vmdelta_us;
1203
    }
1204

    
1205
    /* Avoid arming the timer to negative, zero, or too low values */
1206
    if (nearest_delta_us <= MIN_TIMER_REARM_US)
1207
        nearest_delta_us = MIN_TIMER_REARM_US;
1208

    
1209
    return nearest_delta_us;
1210
}
1211

    
1212
#ifndef _WIN32
1213

    
1214
#if defined(__linux__)
1215

    
1216
#define RTC_FREQ 1024
1217

    
1218
static void enable_sigio_timer(int fd)
1219
{
1220
    struct sigaction act;
1221

    
1222
    /* timer signal */
1223
    sigfillset(&act.sa_mask);
1224
    act.sa_flags = 0;
1225
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1226
    act.sa_flags |= SA_ONSTACK;
1227
#endif
1228
    act.sa_handler = host_alarm_handler;
1229

    
1230
    sigaction(SIGIO, &act, NULL);
1231
    fcntl(fd, F_SETFL, O_ASYNC);
1232
    fcntl(fd, F_SETOWN, getpid());
1233
}
1234

    
1235
static int hpet_start_timer(struct qemu_alarm_timer *t)
1236
{
1237
    struct hpet_info info;
1238
    int r, fd;
1239

    
1240
    fd = open("/dev/hpet", O_RDONLY);
1241
    if (fd < 0)
1242
        return -1;
1243

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

    
1253
    /* Check capabilities */
1254
    r = ioctl(fd, HPET_INFO, &info);
1255
    if (r < 0)
1256
        goto fail;
1257

    
1258
    /* Enable periodic mode */
1259
    r = ioctl(fd, HPET_EPI, 0);
1260
    if (info.hi_flags && (r < 0))
1261
        goto fail;
1262

    
1263
    /* Enable interrupt */
1264
    r = ioctl(fd, HPET_IE_ON, 0);
1265
    if (r < 0)
1266
        goto fail;
1267

    
1268
    enable_sigio_timer(fd);
1269
    t->priv = (void *)(long)fd;
1270

    
1271
    return 0;
1272
fail:
1273
    close(fd);
1274
    return -1;
1275
}
1276

    
1277
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1278
{
1279
    int fd = (long)t->priv;
1280

    
1281
    close(fd);
1282
}
1283

    
1284
static int rtc_start_timer(struct qemu_alarm_timer *t)
1285
{
1286
    int rtc_fd;
1287

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

    
1303
    enable_sigio_timer(rtc_fd);
1304

    
1305
    t->priv = (void *)(long)rtc_fd;
1306

    
1307
    return 0;
1308
}
1309

    
1310
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1311
{
1312
    int rtc_fd = (long)t->priv;
1313

    
1314
    close(rtc_fd);
1315
}
1316

    
1317
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1318
{
1319
    struct sigevent ev;
1320
    timer_t host_timer;
1321
    struct sigaction act;
1322

    
1323
    sigfillset(&act.sa_mask);
1324
    act.sa_flags = 0;
1325
#if defined(TARGET_I386) && defined(USE_CODE_COPY)
1326
    act.sa_flags |= SA_ONSTACK;
1327
#endif
1328
    act.sa_handler = host_alarm_handler;
1329

    
1330
    sigaction(SIGALRM, &act, NULL);
1331

    
1332
    ev.sigev_value.sival_int = 0;
1333
    ev.sigev_notify = SIGEV_SIGNAL;
1334
    ev.sigev_signo = SIGALRM;
1335

    
1336
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1337
        perror("timer_create");
1338

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

    
1342
        return -1;
1343
    }
1344

    
1345
    t->priv = (void *)host_timer;
1346

    
1347
    return 0;
1348
}
1349

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

    
1354
    timer_delete(host_timer);
1355
}
1356

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

    
1364
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1365
                !active_timers[QEMU_TIMER_VIRTUAL])
1366
            return;
1367

    
1368
    nearest_delta_us = qemu_next_deadline();
1369

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

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

    
1391
#endif /* defined(__linux__) */
1392

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

    
1399
    /* timer signal */
1400
    sigfillset(&act.sa_mask);
1401
    act.sa_flags = 0;
1402
#if defined(TARGET_I386) && defined(USE_CODE_COPY)
1403
    act.sa_flags |= SA_ONSTACK;
1404
#endif
1405
    act.sa_handler = host_alarm_handler;
1406

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

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

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

    
1419
    return 0;
1420
}
1421

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

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

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

    
1432
#ifdef _WIN32
1433

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

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

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

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

    
1452
    timeBeginPeriod(data->period);
1453

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

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

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

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

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

    
1476
    return 0;
1477
}
1478

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

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

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

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

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

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

    
1501
    timeKillEvent(data->timerId);
1502

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

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

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

    
1518
#endif /* _WIN32 */
1519

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

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

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

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

    
1539
    alarm_timer = t;
1540
}
1541

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

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

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

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

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

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

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

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

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

    
1598

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

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

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

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

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

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

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

    
1660

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1857

    
1858
#ifdef _WIN32
1859

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

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

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

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

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

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

    
1909
#else
1910

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

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

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

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

    
1942
#ifndef _WIN32
1943

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

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

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

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

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

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

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

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

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

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

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

    
2023
    qemu_chr_reset(chr);
2024

    
2025
    return chr;
2026
}
2027

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

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

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

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

    
2059

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

    
2063
#define TERM_FIFO_MAX_SIZE 1
2064

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

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

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

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

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

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

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

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

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

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

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

    
2137
    atexit(term_exit);
2138

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

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

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

    
2153
    return chr;
2154
}
2155

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2461
    qemu_chr_reset(chr);
2462

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

    
2467
#else /* _WIN32 */
2468

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2647
    win_chr_readfile(chr);
2648
}
2649

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

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

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

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

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

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

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

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

    
2717
    s->fpipe = TRUE;
2718

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

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

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

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

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

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

    
2771

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2973
static void tcp_chr_accept(void *opaque);
2974

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

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

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

    
3011
    int i;
3012
    int j = 0;
3013

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3388
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
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
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
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

    
5388
        se->save_state(f, se->opaque);
5389

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5600
    /* create the snapshots */
5601

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5761
#if defined(TARGET_I386)
5762

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
6112
#elif defined(TARGET_ARM)
6113

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

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

    
6155
    qemu_put_be32(f, env->features);
6156

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

    
6168
        /* TODO: Should use proper FPSCR access functions.  */
6169
        qemu_put_be32(f, env->vfp.vec_len);
6170
        qemu_put_be32(f, env->vfp.vec_stride);
6171
    }
6172

    
6173
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6174
        for (i = 0; i < 16; i++) {
6175
            qemu_put_be64(f, env->iwmmxt.regs[i]);
6176
        }
6177
        for (i = 0; i < 16; i++) {
6178
            qemu_put_be32(f, env->iwmmxt.cregs[i]);
6179
        }
6180
    }
6181
}
6182

    
6183
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6184
{
6185
    CPUARMState *env = (CPUARMState *)opaque;
6186
    int i;
6187

    
6188
    if (version_id != 0)
6189
        return -EINVAL;
6190

    
6191
    for (i = 0; i < 16; i++) {
6192
        env->regs[i] = qemu_get_be32(f);
6193
    }
6194
    cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6195
    env->spsr = qemu_get_be32(f);
6196
    for (i = 0; i < 6; i++) {
6197
        env->banked_spsr[i] = qemu_get_be32(f);
6198
        env->banked_r13[i] = qemu_get_be32(f);
6199
        env->banked_r14[i] = qemu_get_be32(f);
6200
    }
6201
    for (i = 0; i < 5; i++) {
6202
        env->usr_regs[i] = qemu_get_be32(f);
6203
        env->fiq_regs[i] = qemu_get_be32(f);
6204
    }
6205
    env->cp15.c0_cpuid = qemu_get_be32(f);
6206
    env->cp15.c0_cachetype = qemu_get_be32(f);
6207
    env->cp15.c1_sys = qemu_get_be32(f);
6208
    env->cp15.c1_coproc = qemu_get_be32(f);
6209
    env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6210
    env->cp15.c2_base = qemu_get_be32(f);
6211
    env->cp15.c2_data = qemu_get_be32(f);
6212
    env->cp15.c2_insn = qemu_get_be32(f);
6213
    env->cp15.c3 = qemu_get_be32(f);
6214
    env->cp15.c5_insn = qemu_get_be32(f);
6215
    env->cp15.c5_data = qemu_get_be32(f);
6216
    for (i = 0; i < 8; i++) {
6217
        env->cp15.c6_region[i] = qemu_get_be32(f);
6218
    }
6219
    env->cp15.c6_insn = qemu_get_be32(f);
6220
    env->cp15.c6_data = qemu_get_be32(f);
6221
    env->cp15.c9_insn = qemu_get_be32(f);
6222
    env->cp15.c9_data = qemu_get_be32(f);
6223
    env->cp15.c13_fcse = qemu_get_be32(f);
6224
    env->cp15.c13_context = qemu_get_be32(f);
6225
    env->cp15.c15_cpar = qemu_get_be32(f);
6226

    
6227
    env->features = qemu_get_be32(f);
6228

    
6229
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6230
        for (i = 0;  i < 16; i++) {
6231
            CPU_DoubleU u;
6232
            u.l.upper = qemu_get_be32(f);
6233
            u.l.lower = qemu_get_be32(f);
6234
            env->vfp.regs[i] = u.d;
6235
        }
6236
        for (i = 0; i < 16; i++) {
6237
            env->vfp.xregs[i] = qemu_get_be32(f);
6238
        }
6239

    
6240
        /* TODO: Should use proper FPSCR access functions.  */
6241
        env->vfp.vec_len = qemu_get_be32(f);
6242
        env->vfp.vec_stride = qemu_get_be32(f);
6243
    }
6244

    
6245
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6246
        for (i = 0; i < 16; i++) {
6247
            env->iwmmxt.regs[i] = qemu_get_be64(f);
6248
        }
6249
        for (i = 0; i < 16; i++) {
6250
            env->iwmmxt.cregs[i] = qemu_get_be32(f);
6251
        }
6252
    }
6253

    
6254
    return 0;
6255
}
6256

    
6257
#else
6258

    
6259
#warning No CPU save/restore functions
6260

    
6261
#endif
6262

    
6263
/***********************************************************/
6264
/* ram save/restore */
6265

    
6266
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6267
{
6268
    int v;
6269

    
6270
    v = qemu_get_byte(f);
6271
    switch(v) {
6272
    case 0:
6273
        if (qemu_get_buffer(f, buf, len) != len)
6274
            return -EIO;
6275
        break;
6276
    case 1:
6277
        v = qemu_get_byte(f);
6278
        memset(buf, v, len);
6279
        break;
6280
    default:
6281
        return -EINVAL;
6282
    }
6283
    return 0;
6284
}
6285

    
6286
static int ram_load_v1(QEMUFile *f, void *opaque)
6287
{
6288
    int i, ret;
6289

    
6290
    if (qemu_get_be32(f) != phys_ram_size)
6291
        return -EINVAL;
6292
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6293
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6294
        if (ret)
6295
            return ret;
6296
    }
6297
    return 0;
6298
}
6299

    
6300
#define BDRV_HASH_BLOCK_SIZE 1024
6301
#define IOBUF_SIZE 4096
6302
#define RAM_CBLOCK_MAGIC 0xfabe
6303

    
6304
typedef struct RamCompressState {
6305
    z_stream zstream;
6306
    QEMUFile *f;
6307
    uint8_t buf[IOBUF_SIZE];
6308
} RamCompressState;
6309

    
6310
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6311
{
6312
    int ret;
6313
    memset(s, 0, sizeof(*s));
6314
    s->f = f;
6315
    ret = deflateInit2(&s->zstream, 1,
6316
                       Z_DEFLATED, 15,
6317
                       9, Z_DEFAULT_STRATEGY);
6318
    if (ret != Z_OK)
6319
        return -1;
6320
    s->zstream.avail_out = IOBUF_SIZE;
6321
    s->zstream.next_out = s->buf;
6322
    return 0;
6323
}
6324

    
6325
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6326
{
6327
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6328
    qemu_put_be16(s->f, len);
6329
    qemu_put_buffer(s->f, buf, len);
6330
}
6331

    
6332
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6333
{
6334
    int ret;
6335

    
6336
    s->zstream.avail_in = len;
6337
    s->zstream.next_in = (uint8_t *)buf;
6338
    while (s->zstream.avail_in > 0) {
6339
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6340
        if (ret != Z_OK)
6341
            return -1;
6342
        if (s->zstream.avail_out == 0) {
6343
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6344
            s->zstream.avail_out = IOBUF_SIZE;
6345
            s->zstream.next_out = s->buf;
6346
        }
6347
    }
6348
    return 0;
6349
}
6350

    
6351
static void ram_compress_close(RamCompressState *s)
6352
{
6353
    int len, ret;
6354

    
6355
    /* compress last bytes */
6356
    for(;;) {
6357
        ret = deflate(&s->zstream, Z_FINISH);
6358
        if (ret == Z_OK || ret == Z_STREAM_END) {
6359
            len = IOBUF_SIZE - s->zstream.avail_out;
6360
            if (len > 0) {
6361
                ram_put_cblock(s, s->buf, len);
6362
            }
6363
            s->zstream.avail_out = IOBUF_SIZE;
6364
            s->zstream.next_out = s->buf;
6365
            if (ret == Z_STREAM_END)
6366
                break;
6367
        } else {
6368
            goto fail;
6369
        }
6370
    }
6371
fail:
6372
    deflateEnd(&s->zstream);
6373
}
6374

    
6375
typedef struct RamDecompressState {
6376
    z_stream zstream;
6377
    QEMUFile *f;
6378
    uint8_t buf[IOBUF_SIZE];
6379
} RamDecompressState;
6380

    
6381
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6382
{
6383
    int ret;
6384
    memset(s, 0, sizeof(*s));
6385
    s->f = f;
6386
    ret = inflateInit(&s->zstream);
6387
    if (ret != Z_OK)
6388
        return -1;
6389
    return 0;
6390
}
6391

    
6392
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6393
{
6394
    int ret, clen;
6395

    
6396
    s->zstream.avail_out = len;
6397
    s->zstream.next_out = buf;
6398
    while (s->zstream.avail_out > 0) {
6399
        if (s->zstream.avail_in == 0) {
6400
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6401
                return -1;
6402
            clen = qemu_get_be16(s->f);
6403
            if (clen > IOBUF_SIZE)
6404
                return -1;
6405
            qemu_get_buffer(s->f, s->buf, clen);
6406
            s->zstream.avail_in = clen;
6407
            s->zstream.next_in = s->buf;
6408
        }
6409
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6410
        if (ret != Z_OK && ret != Z_STREAM_END) {
6411
            return -1;
6412
        }
6413
    }
6414
    return 0;
6415
}
6416

    
6417
static void ram_decompress_close(RamDecompressState *s)
6418
{
6419
    inflateEnd(&s->zstream);
6420
}
6421

    
6422
static void ram_save(QEMUFile *f, void *opaque)
6423
{
6424
    int i;
6425
    RamCompressState s1, *s = &s1;
6426
    uint8_t buf[10];
6427

    
6428
    qemu_put_be32(f, phys_ram_size);
6429
    if (ram_compress_open(s, f) < 0)
6430
        return;
6431
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6432
#if 0
6433
        if (tight_savevm_enabled) {
6434
            int64_t sector_num;
6435
            int j;
6436

6437
            /* find if the memory block is available on a virtual
6438
               block device */
6439
            sector_num = -1;
6440
            for(j = 0; j < MAX_DISKS; j++) {
6441
                if (bs_table[j]) {
6442
                    sector_num = bdrv_hash_find(bs_table[j],
6443
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6444
                    if (sector_num >= 0)
6445
                        break;
6446
                }
6447
            }
6448
            if (j == MAX_DISKS)
6449
                goto normal_compress;
6450
            buf[0] = 1;
6451
            buf[1] = j;
6452
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6453
            ram_compress_buf(s, buf, 10);
6454
        } else
6455
#endif
6456
        {
6457
            //        normal_compress:
6458
            buf[0] = 0;
6459
            ram_compress_buf(s, buf, 1);
6460
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6461
        }
6462
    }
6463
    ram_compress_close(s);
6464
}
6465

    
6466
static int ram_load(QEMUFile *f, void *opaque, int version_id)
6467
{
6468
    RamDecompressState s1, *s = &s1;
6469
    uint8_t buf[10];
6470
    int i;
6471

    
6472
    if (version_id == 1)
6473
        return ram_load_v1(f, opaque);
6474
    if (version_id != 2)
6475
        return -EINVAL;
6476
    if (qemu_get_be32(f) != phys_ram_size)
6477
        return -EINVAL;
6478
    if (ram_decompress_open(s, f) < 0)
6479
        return -EINVAL;
6480
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6481
        if (ram_decompress_buf(s, buf, 1) < 0) {
6482
            fprintf(stderr, "Error while reading ram block header\n");
6483
            goto error;
6484
        }
6485
        if (buf[0] == 0) {
6486
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6487
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6488
                goto error;
6489
            }
6490
        } else
6491
#if 0
6492
        if (buf[0] == 1) {
6493
            int bs_index;
6494
            int64_t sector_num;
6495

6496
            ram_decompress_buf(s, buf + 1, 9);
6497
            bs_index = buf[1];
6498
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6499
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6500
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
6501
                goto error;
6502
            }
6503
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6504
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6505
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6506
                        bs_index, sector_num);
6507
                goto error;
6508
            }
6509
        } else
6510
#endif
6511
        {
6512
        error:
6513
            printf("Error block header\n");
6514
            return -EINVAL;
6515
        }
6516
    }
6517
    ram_decompress_close(s);
6518
    return 0;
6519
}
6520

    
6521
/***********************************************************/
6522
/* bottom halves (can be seen as timers which expire ASAP) */
6523

    
6524
struct QEMUBH {
6525
    QEMUBHFunc *cb;
6526
    void *opaque;
6527
    int scheduled;
6528
    QEMUBH *next;
6529
};
6530

    
6531
static QEMUBH *first_bh = NULL;
6532

    
6533
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6534
{
6535
    QEMUBH *bh;
6536
    bh = qemu_mallocz(sizeof(QEMUBH));
6537
    if (!bh)
6538
        return NULL;
6539
    bh->cb = cb;
6540
    bh->opaque = opaque;
6541
    return bh;
6542
}
6543

    
6544
int qemu_bh_poll(void)
6545
{
6546
    QEMUBH *bh, **pbh;
6547
    int ret;
6548

    
6549
    ret = 0;
6550
    for(;;) {
6551
        pbh = &first_bh;
6552
        bh = *pbh;
6553
        if (!bh)
6554
            break;
6555
        ret = 1;
6556
        *pbh = bh->next;
6557
        bh->scheduled = 0;
6558
        bh->cb(bh->opaque);
6559
    }
6560
    return ret;
6561
}
6562

    
6563
void qemu_bh_schedule(QEMUBH *bh)
6564
{
6565
    CPUState *env = cpu_single_env;
6566
    if (bh->scheduled)
6567
        return;
6568
    bh->scheduled = 1;
6569
    bh->next = first_bh;
6570
    first_bh = bh;
6571

    
6572
    /* stop the currently executing CPU to execute the BH ASAP */
6573
    if (env) {
6574
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6575
    }
6576
}
6577

    
6578
void qemu_bh_cancel(QEMUBH *bh)
6579
{
6580
    QEMUBH **pbh;
6581
    if (bh->scheduled) {
6582
        pbh = &first_bh;
6583
        while (*pbh != bh)
6584
            pbh = &(*pbh)->next;
6585
        *pbh = bh->next;
6586
        bh->scheduled = 0;
6587
    }
6588
}
6589

    
6590
void qemu_bh_delete(QEMUBH *bh)
6591
{
6592
    qemu_bh_cancel(bh);
6593
    qemu_free(bh);
6594
}
6595

    
6596
/***********************************************************/
6597
/* machine registration */
6598

    
6599
QEMUMachine *first_machine = NULL;
6600

    
6601
int qemu_register_machine(QEMUMachine *m)
6602
{
6603
    QEMUMachine **pm;
6604
    pm = &first_machine;
6605
    while (*pm != NULL)
6606
        pm = &(*pm)->next;
6607
    m->next = NULL;
6608
    *pm = m;
6609
    return 0;
6610
}
6611

    
6612
QEMUMachine *find_machine(const char *name)
6613
{
6614
    QEMUMachine *m;
6615

    
6616
    for(m = first_machine; m != NULL; m = m->next) {
6617
        if (!strcmp(m->name, name))
6618
            return m;
6619
    }
6620
    return NULL;
6621
}
6622

    
6623
/***********************************************************/
6624
/* main execution loop */
6625

    
6626
void gui_update(void *opaque)
6627
{
6628
    DisplayState *ds = opaque;
6629
    ds->dpy_refresh(ds);
6630
    qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6631
}
6632

    
6633
struct vm_change_state_entry {
6634
    VMChangeStateHandler *cb;
6635
    void *opaque;
6636
    LIST_ENTRY (vm_change_state_entry) entries;
6637
};
6638

    
6639
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6640

    
6641
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6642
                                                     void *opaque)
6643
{
6644
    VMChangeStateEntry *e;
6645

    
6646
    e = qemu_mallocz(sizeof (*e));
6647
    if (!e)
6648
        return NULL;
6649

    
6650
    e->cb = cb;
6651
    e->opaque = opaque;
6652
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6653
    return e;
6654
}
6655

    
6656
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6657
{
6658
    LIST_REMOVE (e, entries);
6659
    qemu_free (e);
6660
}
6661

    
6662
static void vm_state_notify(int running)
6663
{
6664
    VMChangeStateEntry *e;
6665

    
6666
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6667
        e->cb(e->opaque, running);
6668
    }
6669
}
6670

    
6671
/* XXX: support several handlers */
6672
static VMStopHandler *vm_stop_cb;
6673
static void *vm_stop_opaque;
6674

    
6675
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6676
{
6677
    vm_stop_cb = cb;
6678
    vm_stop_opaque = opaque;
6679
    return 0;
6680
}
6681

    
6682
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6683
{
6684
    vm_stop_cb = NULL;
6685
}
6686

    
6687
void vm_start(void)
6688
{
6689
    if (!vm_running) {
6690
        cpu_enable_ticks();
6691
        vm_running = 1;
6692
        vm_state_notify(1);
6693
        qemu_rearm_alarm_timer(alarm_timer);
6694
    }
6695
}
6696

    
6697
void vm_stop(int reason)
6698
{
6699
    if (vm_running) {
6700
        cpu_disable_ticks();
6701
        vm_running = 0;
6702
        if (reason != 0) {
6703
            if (vm_stop_cb) {
6704
                vm_stop_cb(vm_stop_opaque, reason);
6705
            }
6706
        }
6707
        vm_state_notify(0);
6708
    }
6709
}
6710

    
6711
/* reset/shutdown handler */
6712

    
6713
typedef struct QEMUResetEntry {
6714
    QEMUResetHandler *func;
6715
    void *opaque;
6716
    struct QEMUResetEntry *next;
6717
} QEMUResetEntry;
6718

    
6719
static QEMUResetEntry *first_reset_entry;
6720
static int reset_requested;
6721
static int shutdown_requested;
6722
static int powerdown_requested;
6723

    
6724
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6725
{
6726
    QEMUResetEntry **pre, *re;
6727

    
6728
    pre = &first_reset_entry;
6729
    while (*pre != NULL)
6730
        pre = &(*pre)->next;
6731
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6732
    re->func = func;
6733
    re->opaque = opaque;
6734
    re->next = NULL;
6735
    *pre = re;
6736
}
6737

    
6738
static void qemu_system_reset(void)
6739
{
6740
    QEMUResetEntry *re;
6741

    
6742
    /* reset all devices */
6743
    for(re = first_reset_entry; re != NULL; re = re->next) {
6744
        re->func(re->opaque);
6745
    }
6746
}
6747

    
6748
void qemu_system_reset_request(void)
6749
{
6750
    if (no_reboot) {
6751
        shutdown_requested = 1;
6752
    } else {
6753
        reset_requested = 1;
6754
    }
6755
    if (cpu_single_env)
6756
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6757
}
6758

    
6759
void qemu_system_shutdown_request(void)
6760
{
6761
    shutdown_requested = 1;
6762
    if (cpu_single_env)
6763
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6764
}
6765

    
6766
void qemu_system_powerdown_request(void)
6767
{
6768
    powerdown_requested = 1;
6769
    if (cpu_single_env)
6770
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6771
}
6772

    
6773
void main_loop_wait(int timeout)
6774
{
6775
    IOHandlerRecord *ioh;
6776
    fd_set rfds, wfds, xfds;
6777
    int ret, nfds;
6778
#ifdef _WIN32
6779
    int ret2, i;
6780
#endif
6781
    struct timeval tv;
6782
    PollingEntry *pe;
6783

    
6784

    
6785
    /* XXX: need to suppress polling by better using win32 events */
6786
    ret = 0;
6787
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6788
        ret |= pe->func(pe->opaque);
6789
    }
6790
#ifdef _WIN32
6791
    if (ret == 0) {
6792
        int err;
6793
        WaitObjects *w = &wait_objects;
6794

    
6795
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6796
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6797
            if (w->func[ret - WAIT_OBJECT_0])
6798
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6799

    
6800
            /* Check for additional signaled events */
6801
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6802

    
6803
                /* Check if event is signaled */
6804
                ret2 = WaitForSingleObject(w->events[i], 0);
6805
                if(ret2 == WAIT_OBJECT_0) {
6806
                    if (w->func[i])
6807
                        w->func[i](w->opaque[i]);
6808
                } else if (ret2 == WAIT_TIMEOUT) {
6809
                } else {
6810
                    err = GetLastError();
6811
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6812
                }
6813
            }
6814
        } else if (ret == WAIT_TIMEOUT) {
6815
        } else {
6816
            err = GetLastError();
6817
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6818
        }
6819
    }
6820
#endif
6821
    /* poll any events */
6822
    /* XXX: separate device handlers from system ones */
6823
    nfds = -1;
6824
    FD_ZERO(&rfds);
6825
    FD_ZERO(&wfds);
6826
    FD_ZERO(&xfds);
6827
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6828
        if (ioh->deleted)
6829
            continue;
6830
        if (ioh->fd_read &&
6831
            (!ioh->fd_read_poll ||
6832
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6833
            FD_SET(ioh->fd, &rfds);
6834
            if (ioh->fd > nfds)
6835
                nfds = ioh->fd;
6836
        }
6837
        if (ioh->fd_write) {
6838
            FD_SET(ioh->fd, &wfds);
6839
            if (ioh->fd > nfds)
6840
                nfds = ioh->fd;
6841
        }
6842
    }
6843

    
6844
    tv.tv_sec = 0;
6845
#ifdef _WIN32
6846
    tv.tv_usec = 0;
6847
#else
6848
    tv.tv_usec = timeout * 1000;
6849
#endif
6850
#if defined(CONFIG_SLIRP)
6851
    if (slirp_inited) {
6852
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6853
    }
6854
#endif
6855
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6856
    if (ret > 0) {
6857
        IOHandlerRecord **pioh;
6858

    
6859
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6860
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6861
                ioh->fd_read(ioh->opaque);
6862
            }
6863
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6864
                ioh->fd_write(ioh->opaque);
6865
            }
6866
        }
6867

    
6868
        /* remove deleted IO handlers */
6869
        pioh = &first_io_handler;
6870
        while (*pioh) {
6871
            ioh = *pioh;
6872
            if (ioh->deleted) {
6873
                *pioh = ioh->next;
6874
                qemu_free(ioh);
6875
            } else
6876
                pioh = &ioh->next;
6877
        }
6878
    }
6879
#if defined(CONFIG_SLIRP)
6880
    if (slirp_inited) {
6881
        if (ret < 0) {
6882
            FD_ZERO(&rfds);
6883
            FD_ZERO(&wfds);
6884
            FD_ZERO(&xfds);
6885
        }
6886
        slirp_select_poll(&rfds, &wfds, &xfds);
6887
    }
6888
#endif
6889
    qemu_aio_poll();
6890

    
6891
    if (vm_running) {
6892
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6893
                        qemu_get_clock(vm_clock));
6894
        /* run dma transfers, if any */
6895
        DMA_run();
6896
    }
6897

    
6898
    /* real time timers */
6899
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6900
                    qemu_get_clock(rt_clock));
6901

    
6902
    /* Check bottom-halves last in case any of the earlier events triggered
6903
       them.  */
6904
    qemu_bh_poll();
6905

    
6906
}
6907

    
6908
static CPUState *cur_cpu;
6909

    
6910
int main_loop(void)
6911
{
6912
    int ret, timeout;
6913
#ifdef CONFIG_PROFILER
6914
    int64_t ti;
6915
#endif
6916
    CPUState *env;
6917

    
6918
    cur_cpu = first_cpu;
6919
    for(;;) {
6920
        if (vm_running) {
6921

    
6922
            env = cur_cpu;
6923
            for(;;) {
6924
                /* get next cpu */
6925
                env = env->next_cpu;
6926
                if (!env)
6927
                    env = first_cpu;
6928
#ifdef CONFIG_PROFILER
6929
                ti = profile_getclock();
6930
#endif
6931
                ret = cpu_exec(env);
6932
#ifdef CONFIG_PROFILER
6933
                qemu_time += profile_getclock() - ti;
6934
#endif
6935
                if (ret == EXCP_HLT) {
6936
                    /* Give the next CPU a chance to run.  */
6937
                    cur_cpu = env;
6938
                    continue;
6939
                }
6940
                if (ret != EXCP_HALTED)
6941
                    break;
6942
                /* all CPUs are halted ? */
6943
                if (env == cur_cpu)
6944
                    break;
6945
            }
6946
            cur_cpu = env;
6947

    
6948
            if (shutdown_requested) {
6949
                ret = EXCP_INTERRUPT;
6950
                break;
6951
            }
6952
            if (reset_requested) {
6953
                reset_requested = 0;
6954
                qemu_system_reset();
6955
                ret = EXCP_INTERRUPT;
6956
            }
6957
            if (powerdown_requested) {
6958
                powerdown_requested = 0;
6959
                qemu_system_powerdown();
6960
                ret = EXCP_INTERRUPT;
6961
            }
6962
            if (ret == EXCP_DEBUG) {
6963
                vm_stop(EXCP_DEBUG);
6964
            }
6965
            /* If all cpus are halted then wait until the next IRQ */
6966
            /* XXX: use timeout computed from timers */
6967
            if (ret == EXCP_HALTED)
6968
                timeout = 10;
6969
            else
6970
                timeout = 0;
6971
        } else {
6972
            timeout = 10;
6973
        }
6974
#ifdef CONFIG_PROFILER
6975
        ti = profile_getclock();
6976
#endif
6977
        main_loop_wait(timeout);
6978
#ifdef CONFIG_PROFILER
6979
        dev_time += profile_getclock() - ti;
6980
#endif
6981
    }
6982
    cpu_disable_ticks();
6983
    return ret;
6984
}
6985

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

    
7135
#define HAS_ARG 0x0001
7136

    
7137
enum {
7138
    QEMU_OPTION_h,
7139

    
7140
    QEMU_OPTION_M,
7141
    QEMU_OPTION_cpu,
7142
    QEMU_OPTION_fda,
7143
    QEMU_OPTION_fdb,
7144
    QEMU_OPTION_hda,
7145
    QEMU_OPTION_hdb,
7146
    QEMU_OPTION_hdc,
7147
    QEMU_OPTION_hdd,
7148
    QEMU_OPTION_cdrom,
7149
    QEMU_OPTION_mtdblock,
7150
    QEMU_OPTION_sd,
7151
    QEMU_OPTION_pflash,
7152
    QEMU_OPTION_boot,
7153
    QEMU_OPTION_snapshot,
7154
#ifdef TARGET_I386
7155
    QEMU_OPTION_no_fd_bootchk,
7156
#endif
7157
    QEMU_OPTION_m,
7158
    QEMU_OPTION_nographic,
7159
    QEMU_OPTION_portrait,
7160
#ifdef HAS_AUDIO
7161
    QEMU_OPTION_audio_help,
7162
    QEMU_OPTION_soundhw,
7163
#endif
7164

    
7165
    QEMU_OPTION_net,
7166
    QEMU_OPTION_tftp,
7167
    QEMU_OPTION_bootp,
7168
    QEMU_OPTION_smb,
7169
    QEMU_OPTION_redir,
7170

    
7171
    QEMU_OPTION_kernel,
7172
    QEMU_OPTION_append,
7173
    QEMU_OPTION_initrd,
7174

    
7175
    QEMU_OPTION_S,
7176
    QEMU_OPTION_s,
7177
    QEMU_OPTION_p,
7178
    QEMU_OPTION_d,
7179
    QEMU_OPTION_hdachs,
7180
    QEMU_OPTION_L,
7181
    QEMU_OPTION_bios,
7182
    QEMU_OPTION_no_code_copy,
7183
    QEMU_OPTION_k,
7184
    QEMU_OPTION_localtime,
7185
    QEMU_OPTION_cirrusvga,
7186
    QEMU_OPTION_vmsvga,
7187
    QEMU_OPTION_g,
7188
    QEMU_OPTION_std_vga,
7189
    QEMU_OPTION_echr,
7190
    QEMU_OPTION_monitor,
7191
    QEMU_OPTION_serial,
7192
    QEMU_OPTION_parallel,
7193
    QEMU_OPTION_loadvm,
7194
    QEMU_OPTION_full_screen,
7195
    QEMU_OPTION_no_frame,
7196
    QEMU_OPTION_alt_grab,
7197
    QEMU_OPTION_no_quit,
7198
    QEMU_OPTION_pidfile,
7199
    QEMU_OPTION_no_kqemu,
7200
    QEMU_OPTION_kernel_kqemu,
7201
    QEMU_OPTION_win2k_hack,
7202
    QEMU_OPTION_usb,
7203
    QEMU_OPTION_usbdevice,
7204
    QEMU_OPTION_smp,
7205
    QEMU_OPTION_vnc,
7206
    QEMU_OPTION_no_acpi,
7207
    QEMU_OPTION_no_reboot,
7208
    QEMU_OPTION_show_cursor,
7209
    QEMU_OPTION_daemonize,
7210
    QEMU_OPTION_option_rom,
7211
    QEMU_OPTION_semihosting,
7212
    QEMU_OPTION_name,
7213
    QEMU_OPTION_prom_env,
7214
    QEMU_OPTION_old_param,
7215
    QEMU_OPTION_clock,
7216
    QEMU_OPTION_startdate,
7217
};
7218

    
7219
typedef struct QEMUOption {
7220
    const char *name;
7221
    int flags;
7222
    int index;
7223
} QEMUOption;
7224

    
7225
const QEMUOption qemu_options[] = {
7226
    { "h", 0, QEMU_OPTION_h },
7227
    { "help", 0, QEMU_OPTION_h },
7228

    
7229
    { "M", HAS_ARG, QEMU_OPTION_M },
7230
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7231
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7232
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7233
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7234
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7235
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7236
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7237
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7238
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7239
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7240
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7241
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7242
    { "snapshot", 0, QEMU_OPTION_snapshot },
7243
#ifdef TARGET_I386
7244
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7245
#endif
7246
    { "m", HAS_ARG, QEMU_OPTION_m },
7247
    { "nographic", 0, QEMU_OPTION_nographic },
7248
    { "portrait", 0, QEMU_OPTION_portrait },
7249
    { "k", HAS_ARG, QEMU_OPTION_k },
7250
#ifdef HAS_AUDIO
7251
    { "audio-help", 0, QEMU_OPTION_audio_help },
7252
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7253
#endif
7254

    
7255
    { "net", HAS_ARG, QEMU_OPTION_net},
7256
#ifdef CONFIG_SLIRP
7257
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7258
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7259
#ifndef _WIN32
7260
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7261
#endif
7262
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7263
#endif
7264

    
7265
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7266
    { "append", HAS_ARG, QEMU_OPTION_append },
7267
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7268

    
7269
    { "S", 0, QEMU_OPTION_S },
7270
    { "s", 0, QEMU_OPTION_s },
7271
    { "p", HAS_ARG, QEMU_OPTION_p },
7272
    { "d", HAS_ARG, QEMU_OPTION_d },
7273
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7274
    { "L", HAS_ARG, QEMU_OPTION_L },
7275
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7276
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7277
#ifdef USE_KQEMU
7278
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7279
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7280
#endif
7281
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7282
    { "g", 1, QEMU_OPTION_g },
7283
#endif
7284
    { "localtime", 0, QEMU_OPTION_localtime },
7285
    { "std-vga", 0, QEMU_OPTION_std_vga },
7286
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7287
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7288
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7289
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7290
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7291
    { "full-screen", 0, QEMU_OPTION_full_screen },
7292
#ifdef CONFIG_SDL
7293
    { "no-frame", 0, QEMU_OPTION_no_frame },
7294
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7295
    { "no-quit", 0, QEMU_OPTION_no_quit },
7296
#endif
7297
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7298
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7299
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7300
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7301
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7302

    
7303
    /* temporary options */
7304
    { "usb", 0, QEMU_OPTION_usb },
7305
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7306
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7307
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7308
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7309
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7310
    { "daemonize", 0, QEMU_OPTION_daemonize },
7311
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7312
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7313
    { "semihosting", 0, QEMU_OPTION_semihosting },
7314
#endif
7315
    { "name", HAS_ARG, QEMU_OPTION_name },
7316
#if defined(TARGET_SPARC)
7317
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7318
#endif
7319
#if defined(TARGET_ARM)
7320
    { "old-param", 0, QEMU_OPTION_old_param },
7321
#endif
7322
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7323
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7324
    { NULL },
7325
};
7326

    
7327
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
7328

    
7329
/* this stack is only used during signal handling */
7330
#define SIGNAL_STACK_SIZE 32768
7331

    
7332
static uint8_t *signal_stack;
7333

    
7334
#endif
7335

    
7336
/* password input */
7337

    
7338
int qemu_key_check(BlockDriverState *bs, const char *name)
7339
{
7340
    char password[256];
7341
    int i;
7342

    
7343
    if (!bdrv_is_encrypted(bs))
7344
        return 0;
7345

    
7346
    term_printf("%s is encrypted.\n", name);
7347
    for(i = 0; i < 3; i++) {
7348
        monitor_readline("Password: ", 1, password, sizeof(password));
7349
        if (bdrv_set_key(bs, password) == 0)
7350
            return 0;
7351
        term_printf("invalid password\n");
7352
    }
7353
    return -EPERM;
7354
}
7355

    
7356
static BlockDriverState *get_bdrv(int index)
7357
{
7358
    BlockDriverState *bs;
7359

    
7360
    if (index < 4) {
7361
        bs = bs_table[index];
7362
    } else if (index < 6) {
7363
        bs = fd_table[index - 4];
7364
    } else {
7365
        bs = NULL;
7366
    }
7367
    return bs;
7368
}
7369

    
7370
static void read_passwords(void)
7371
{
7372
    BlockDriverState *bs;
7373
    int i;
7374

    
7375
    for(i = 0; i < 6; i++) {
7376
        bs = get_bdrv(i);
7377
        if (bs)
7378
            qemu_key_check(bs, bdrv_get_device_name(bs));
7379
    }
7380
}
7381

    
7382
/* XXX: currently we cannot use simultaneously different CPUs */
7383
void register_machines(void)
7384
{
7385
#if defined(TARGET_I386)
7386
    qemu_register_machine(&pc_machine);
7387
    qemu_register_machine(&isapc_machine);
7388
#elif defined(TARGET_PPC)
7389
    qemu_register_machine(&heathrow_machine);
7390
    qemu_register_machine(&core99_machine);
7391
    qemu_register_machine(&prep_machine);
7392
    qemu_register_machine(&ref405ep_machine);
7393
    qemu_register_machine(&taihu_machine);
7394
#elif defined(TARGET_MIPS)
7395
    qemu_register_machine(&mips_machine);
7396
    qemu_register_machine(&mips_malta_machine);
7397
    qemu_register_machine(&mips_pica61_machine);
7398
    qemu_register_machine(&mips_mipssim_machine);
7399
#elif defined(TARGET_SPARC)
7400
#ifdef TARGET_SPARC64
7401
    qemu_register_machine(&sun4u_machine);
7402
#else
7403
    qemu_register_machine(&ss5_machine);
7404
    qemu_register_machine(&ss10_machine);
7405
#endif
7406
#elif defined(TARGET_ARM)
7407
    qemu_register_machine(&integratorcp_machine);
7408
    qemu_register_machine(&versatilepb_machine);
7409
    qemu_register_machine(&versatileab_machine);
7410
    qemu_register_machine(&realview_machine);
7411
    qemu_register_machine(&akitapda_machine);
7412
    qemu_register_machine(&spitzpda_machine);
7413
    qemu_register_machine(&borzoipda_machine);
7414
    qemu_register_machine(&terrierpda_machine);
7415
    qemu_register_machine(&palmte_machine);
7416
#elif defined(TARGET_SH4)
7417
    qemu_register_machine(&shix_machine);
7418
    qemu_register_machine(&r2d_machine);
7419
#elif defined(TARGET_ALPHA)
7420
    /* XXX: TODO */
7421
#elif defined(TARGET_M68K)
7422
    qemu_register_machine(&mcf5208evb_machine);
7423
    qemu_register_machine(&an5206_machine);
7424
#elif defined(TARGET_CRIS)
7425
    qemu_register_machine(&bareetraxfs_machine);
7426
#else
7427
#error unsupported CPU
7428
#endif
7429
}
7430

    
7431
#ifdef HAS_AUDIO
7432
struct soundhw soundhw[] = {
7433
#ifdef HAS_AUDIO_CHOICE
7434
#ifdef TARGET_I386
7435
    {
7436
        "pcspk",
7437
        "PC speaker",
7438
        0,
7439
        1,
7440
        { .init_isa = pcspk_audio_init }
7441
    },
7442
#endif
7443
    {
7444
        "sb16",
7445
        "Creative Sound Blaster 16",
7446
        0,
7447
        1,
7448
        { .init_isa = SB16_init }
7449
    },
7450

    
7451
#ifdef CONFIG_ADLIB
7452
    {
7453
        "adlib",
7454
#ifdef HAS_YMF262
7455
        "Yamaha YMF262 (OPL3)",
7456
#else
7457
        "Yamaha YM3812 (OPL2)",
7458
#endif
7459
        0,
7460
        1,
7461
        { .init_isa = Adlib_init }
7462
    },
7463
#endif
7464

    
7465
#ifdef CONFIG_GUS
7466
    {
7467
        "gus",
7468
        "Gravis Ultrasound GF1",
7469
        0,
7470
        1,
7471
        { .init_isa = GUS_init }
7472
    },
7473
#endif
7474

    
7475
    {
7476
        "es1370",
7477
        "ENSONIQ AudioPCI ES1370",
7478
        0,
7479
        0,
7480
        { .init_pci = es1370_init }
7481
    },
7482
#endif
7483

    
7484
    { NULL, NULL, 0, 0, { NULL } }
7485
};
7486

    
7487
static void select_soundhw (const char *optarg)
7488
{
7489
    struct soundhw *c;
7490

    
7491
    if (*optarg == '?') {
7492
    show_valid_cards:
7493

    
7494
        printf ("Valid sound card names (comma separated):\n");
7495
        for (c = soundhw; c->name; ++c) {
7496
            printf ("%-11s %s\n", c->name, c->descr);
7497
        }
7498
        printf ("\n-soundhw all will enable all of the above\n");
7499
        exit (*optarg != '?');
7500
    }
7501
    else {
7502
        size_t l;
7503
        const char *p;
7504
        char *e;
7505
        int bad_card = 0;
7506

    
7507
        if (!strcmp (optarg, "all")) {
7508
            for (c = soundhw; c->name; ++c) {
7509
                c->enabled = 1;
7510
            }
7511
            return;
7512
        }
7513

    
7514
        p = optarg;
7515
        while (*p) {
7516
            e = strchr (p, ',');
7517
            l = !e ? strlen (p) : (size_t) (e - p);
7518

    
7519
            for (c = soundhw; c->name; ++c) {
7520
                if (!strncmp (c->name, p, l)) {
7521
                    c->enabled = 1;
7522
                    break;
7523
                }
7524
            }
7525

    
7526
            if (!c->name) {
7527
                if (l > 80) {
7528
                    fprintf (stderr,
7529
                             "Unknown sound card name (too big to show)\n");
7530
                }
7531
                else {
7532
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
7533
                             (int) l, p);
7534
                }
7535
                bad_card = 1;
7536
            }
7537
            p += l + (e != NULL);
7538
        }
7539

    
7540
        if (bad_card)
7541
            goto show_valid_cards;
7542
    }
7543
}
7544
#endif
7545

    
7546
#ifdef _WIN32
7547
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7548
{
7549
    exit(STATUS_CONTROL_C_EXIT);
7550
    return TRUE;
7551
}
7552
#endif
7553

    
7554
#define MAX_NET_CLIENTS 32
7555

    
7556
int main(int argc, char **argv)
7557
{
7558
#ifdef CONFIG_GDBSTUB
7559
    int use_gdbstub;
7560
    const char *gdbstub_port;
7561
#endif
7562
    int i, cdrom_index, pflash_index;
7563
    int snapshot, linux_boot;
7564
    const char *initrd_filename;
7565
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7566
    const char *pflash_filename[MAX_PFLASH];
7567
    const char *sd_filename;
7568
    const char *mtd_filename;
7569
    const char *kernel_filename, *kernel_cmdline;
7570
    DisplayState *ds = &display_state;
7571
    int cyls, heads, secs, translation;
7572
    char net_clients[MAX_NET_CLIENTS][256];
7573
    int nb_net_clients;
7574
    int optind;
7575
    const char *r, *optarg;
7576
    CharDriverState *monitor_hd;
7577
    char monitor_device[128];
7578
    char serial_devices[MAX_SERIAL_PORTS][128];
7579
    int serial_device_index;
7580
    char parallel_devices[MAX_PARALLEL_PORTS][128];
7581
    int parallel_device_index;
7582
    const char *loadvm = NULL;
7583
    QEMUMachine *machine;
7584
    const char *cpu_model;
7585
    char usb_devices[MAX_USB_CMDLINE][128];
7586
    int usb_devices_index;
7587
    int fds[2];
7588
    const char *pid_file = NULL;
7589
    VLANState *vlan;
7590

    
7591
    LIST_INIT (&vm_change_state_head);
7592
#ifndef _WIN32
7593
    {
7594
        struct sigaction act;
7595
        sigfillset(&act.sa_mask);
7596
        act.sa_flags = 0;
7597
        act.sa_handler = SIG_IGN;
7598
        sigaction(SIGPIPE, &act, NULL);
7599
    }
7600
#else
7601
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7602
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
7603
       QEMU to run on a single CPU */
7604
    {
7605
        HANDLE h;
7606
        DWORD mask, smask;
7607
        int i;
7608
        h = GetCurrentProcess();
7609
        if (GetProcessAffinityMask(h, &mask, &smask)) {
7610
            for(i = 0; i < 32; i++) {
7611
                if (mask & (1 << i))
7612
                    break;
7613
            }
7614
            if (i != 32) {
7615
                mask = 1 << i;
7616
                SetProcessAffinityMask(h, mask);
7617
            }
7618
        }
7619
    }
7620
#endif
7621

    
7622
    register_machines();
7623
    machine = first_machine;
7624
    cpu_model = NULL;
7625
    initrd_filename = NULL;
7626
    for(i = 0; i < MAX_FD; i++)
7627
        fd_filename[i] = NULL;
7628
    for(i = 0; i < MAX_DISKS; i++)
7629
        hd_filename[i] = NULL;
7630
    for(i = 0; i < MAX_PFLASH; i++)
7631
        pflash_filename[i] = NULL;
7632
    pflash_index = 0;
7633
    sd_filename = NULL;
7634
    mtd_filename = NULL;
7635
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7636
    vga_ram_size = VGA_RAM_SIZE;
7637
#ifdef CONFIG_GDBSTUB
7638
    use_gdbstub = 0;
7639
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
7640
#endif
7641
    snapshot = 0;
7642
    nographic = 0;
7643
    kernel_filename = NULL;
7644
    kernel_cmdline = "";
7645
#ifdef TARGET_PPC
7646
    cdrom_index = 1;
7647
#else
7648
    cdrom_index = 2;
7649
#endif
7650
    cyls = heads = secs = 0;
7651
    translation = BIOS_ATA_TRANSLATION_AUTO;
7652
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7653

    
7654
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7655
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
7656
        serial_devices[i][0] = '\0';
7657
    serial_device_index = 0;
7658

    
7659
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7660
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7661
        parallel_devices[i][0] = '\0';
7662
    parallel_device_index = 0;
7663

    
7664
    usb_devices_index = 0;
7665

    
7666
    nb_net_clients = 0;
7667

    
7668
    nb_nics = 0;
7669
    /* default mac address of the first network interface */
7670

    
7671
    optind = 1;
7672
    for(;;) {
7673
        if (optind >= argc)
7674
            break;
7675
        r = argv[optind];
7676
        if (r[0] != '-') {
7677
            hd_filename[0] = argv[optind++];
7678
        } else {
7679
            const QEMUOption *popt;
7680

    
7681
            optind++;
7682
            /* Treat --foo the same as -foo.  */
7683
            if (r[1] == '-')
7684
                r++;
7685
            popt = qemu_options;
7686
            for(;;) {
7687
                if (!popt->name) {
7688
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
7689
                            argv[0], r);
7690
                    exit(1);
7691
                }
7692
                if (!strcmp(popt->name, r + 1))
7693
                    break;
7694
                popt++;
7695
            }
7696
            if (popt->flags & HAS_ARG) {
7697
                if (optind >= argc) {
7698
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
7699
                            argv[0], r);
7700
                    exit(1);
7701
                }
7702
                optarg = argv[optind++];
7703
            } else {
7704
                optarg = NULL;
7705
            }
7706

    
7707
            switch(popt->index) {
7708
            case QEMU_OPTION_M:
7709
                machine = find_machine(optarg);
7710
                if (!machine) {
7711
                    QEMUMachine *m;
7712
                    printf("Supported machines are:\n");
7713
                    for(m = first_machine; m != NULL; m = m->next) {
7714
                        printf("%-10s %s%s\n",
7715
                               m->name, m->desc,
7716
                               m == first_machine ? " (default)" : "");
7717
                    }
7718
                    exit(*optarg != '?');
7719
                }
7720
                break;
7721
            case QEMU_OPTION_cpu:
7722
                /* hw initialization will check this */
7723
                if (*optarg == '?') {
7724
/* XXX: implement xxx_cpu_list for targets that still miss it */
7725
#if defined(cpu_list)
7726
                    cpu_list(stdout, &fprintf);
7727
#endif
7728
                    exit(0);
7729
                } else {
7730
                    cpu_model = optarg;
7731
                }
7732
                break;
7733
            case QEMU_OPTION_initrd:
7734
                initrd_filename = optarg;
7735
                break;
7736
            case QEMU_OPTION_hda:
7737
            case QEMU_OPTION_hdb:
7738
            case QEMU_OPTION_hdc:
7739
            case QEMU_OPTION_hdd:
7740
                {
7741
                    int hd_index;
7742
                    hd_index = popt->index - QEMU_OPTION_hda;
7743
                    hd_filename[hd_index] = optarg;
7744
                    if (hd_index == cdrom_index)
7745
                        cdrom_index = -1;
7746
                }
7747
                break;
7748
            case QEMU_OPTION_mtdblock:
7749
                mtd_filename = optarg;
7750
                break;
7751
            case QEMU_OPTION_sd:
7752
                sd_filename = optarg;
7753
                break;
7754
            case QEMU_OPTION_pflash:
7755
                if (pflash_index >= MAX_PFLASH) {
7756
                    fprintf(stderr, "qemu: too many parallel flash images\n");
7757
                    exit(1);
7758
                }
7759
                pflash_filename[pflash_index++] = optarg;
7760
                break;
7761
            case QEMU_OPTION_snapshot:
7762
                snapshot = 1;
7763
                break;
7764
            case QEMU_OPTION_hdachs:
7765
                {
7766
                    const char *p;
7767
                    p = optarg;
7768
                    cyls = strtol(p, (char **)&p, 0);
7769
                    if (cyls < 1 || cyls > 16383)
7770
                        goto chs_fail;
7771
                    if (*p != ',')
7772
                        goto chs_fail;
7773
                    p++;
7774
                    heads = strtol(p, (char **)&p, 0);
7775
                    if (heads < 1 || heads > 16)
7776
                        goto chs_fail;
7777
                    if (*p != ',')
7778
                        goto chs_fail;
7779
                    p++;
7780
                    secs = strtol(p, (char **)&p, 0);
7781
                    if (secs < 1 || secs > 63)
7782
                        goto chs_fail;
7783
                    if (*p == ',') {
7784
                        p++;
7785
                        if (!strcmp(p, "none"))
7786
                            translation = BIOS_ATA_TRANSLATION_NONE;
7787
                        else if (!strcmp(p, "lba"))
7788
                            translation = BIOS_ATA_TRANSLATION_LBA;
7789
                        else if (!strcmp(p, "auto"))
7790
                            translation = BIOS_ATA_TRANSLATION_AUTO;
7791
                        else
7792
                            goto chs_fail;
7793
                    } else if (*p != '\0') {
7794
                    chs_fail:
7795
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
7796
                        exit(1);
7797
                    }
7798
                }
7799
                break;
7800
            case QEMU_OPTION_nographic:
7801
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7802
                pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7803
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7804
                nographic = 1;
7805
                break;
7806
            case QEMU_OPTION_portrait:
7807
                graphic_rotate = 1;
7808
                break;
7809
            case QEMU_OPTION_kernel:
7810
                kernel_filename = optarg;
7811
                break;
7812
            case QEMU_OPTION_append:
7813
                kernel_cmdline = optarg;
7814
                break;
7815
            case QEMU_OPTION_cdrom:
7816
                if (cdrom_index >= 0) {
7817
                    hd_filename[cdrom_index] = optarg;
7818
                }
7819
                break;
7820
            case QEMU_OPTION_boot:
7821
                if (strlen(optarg) > MAX_BOOT_DEVICES) {
7822
                    fprintf(stderr, "qemu: too many boot devices\n");
7823
                    exit(1);
7824
                }
7825
                strncpy(boot_device, optarg, MAX_BOOT_DEVICES);
7826
#if defined(TARGET_SPARC) || defined(TARGET_I386)
7827
#define BOOTCHARS "acdn"
7828
#else
7829
#define BOOTCHARS "acd"
7830
#endif
7831
                if (strlen(boot_device) != strspn(boot_device, BOOTCHARS)) {
7832
                    fprintf(stderr, "qemu: invalid boot device "
7833
                                    "sequence '%s'\n", boot_device);
7834
                    exit(1);
7835
                }
7836
                break;
7837
            case QEMU_OPTION_fda:
7838
                fd_filename[0] = optarg;
7839
                break;
7840
            case QEMU_OPTION_fdb:
7841
                fd_filename[1] = optarg;
7842
                break;
7843
#ifdef TARGET_I386
7844
            case QEMU_OPTION_no_fd_bootchk:
7845
                fd_bootchk = 0;
7846
                break;
7847
#endif
7848
            case QEMU_OPTION_no_code_copy:
7849
                code_copy_enabled = 0;
7850
                break;
7851
            case QEMU_OPTION_net:
7852
                if (nb_net_clients >= MAX_NET_CLIENTS) {
7853
                    fprintf(stderr, "qemu: too many network clients\n");
7854
                    exit(1);
7855
                }
7856
                pstrcpy(net_clients[nb_net_clients],
7857
                        sizeof(net_clients[0]),
7858
                        optarg);
7859
                nb_net_clients++;
7860
                break;
7861
#ifdef CONFIG_SLIRP
7862
            case QEMU_OPTION_tftp:
7863
                tftp_prefix = optarg;
7864
                break;
7865
            case QEMU_OPTION_bootp:
7866
                bootp_filename = optarg;
7867
                break;
7868
#ifndef _WIN32
7869
            case QEMU_OPTION_smb:
7870
                net_slirp_smb(optarg);
7871
                break;
7872
#endif
7873
            case QEMU_OPTION_redir:
7874
                net_slirp_redir(optarg);
7875
                break;
7876
#endif
7877
#ifdef HAS_AUDIO
7878
            case QEMU_OPTION_audio_help:
7879
                AUD_help ();
7880
                exit (0);
7881
                break;
7882
            case QEMU_OPTION_soundhw:
7883
                select_soundhw (optarg);
7884
                break;
7885
#endif
7886
            case QEMU_OPTION_h:
7887
                help(0);
7888
                break;
7889
            case QEMU_OPTION_m:
7890
                ram_size = atoi(optarg) * 1024 * 1024;
7891
                if (ram_size <= 0)
7892
                    help(1);
7893
                if (ram_size > PHYS_RAM_MAX_SIZE) {
7894
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7895
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
7896
                    exit(1);
7897
                }
7898
                break;
7899
            case QEMU_OPTION_d:
7900
                {
7901
                    int mask;
7902
                    CPULogItem *item;
7903

    
7904
                    mask = cpu_str_to_log_mask(optarg);
7905
                    if (!mask) {
7906
                        printf("Log items (comma separated):\n");
7907
                    for(item = cpu_log_items; item->mask != 0; item++) {
7908
                        printf("%-10s %s\n", item->name, item->help);
7909
                    }
7910
                    exit(1);
7911
                    }
7912
                    cpu_set_log(mask);
7913
                }
7914
                break;
7915
#ifdef CONFIG_GDBSTUB
7916
            case QEMU_OPTION_s:
7917
                use_gdbstub = 1;
7918
                break;
7919
            case QEMU_OPTION_p:
7920
                gdbstub_port = optarg;
7921
                break;
7922
#endif
7923
            case QEMU_OPTION_L:
7924
                bios_dir = optarg;
7925
                break;
7926
            case QEMU_OPTION_bios:
7927
                bios_name = optarg;
7928
                break;
7929
            case QEMU_OPTION_S:
7930
                autostart = 0;
7931
                break;
7932
            case QEMU_OPTION_k:
7933
                keyboard_layout = optarg;
7934
                break;
7935
            case QEMU_OPTION_localtime:
7936
                rtc_utc = 0;
7937
                break;
7938
            case QEMU_OPTION_cirrusvga:
7939
                cirrus_vga_enabled = 1;
7940
                vmsvga_enabled = 0;
7941
                break;
7942
            case QEMU_OPTION_vmsvga:
7943
                cirrus_vga_enabled = 0;
7944
                vmsvga_enabled = 1;
7945
                break;
7946
            case QEMU_OPTION_std_vga:
7947
                cirrus_vga_enabled = 0;
7948
                vmsvga_enabled = 0;
7949
                break;
7950
            case QEMU_OPTION_g:
7951
                {
7952
                    const char *p;
7953
                    int w, h, depth;
7954
                    p = optarg;
7955
                    w = strtol(p, (char **)&p, 10);
7956
                    if (w <= 0) {
7957
                    graphic_error:
7958
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
7959
                        exit(1);
7960
                    }
7961
                    if (*p != 'x')
7962
                        goto graphic_error;
7963
                    p++;
7964
                    h = strtol(p, (char **)&p, 10);
7965
                    if (h <= 0)
7966
                        goto graphic_error;
7967
                    if (*p == 'x') {
7968
                        p++;
7969
                        depth = strtol(p, (char **)&p, 10);
7970
                        if (depth != 8 && depth != 15 && depth != 16 &&
7971
                            depth != 24 && depth != 32)
7972
                            goto graphic_error;
7973
                    } else if (*p == '\0') {
7974
                        depth = graphic_depth;
7975
                    } else {
7976
                        goto graphic_error;
7977
                    }
7978

    
7979
                    graphic_width = w;
7980
                    graphic_height = h;
7981
                    graphic_depth = depth;
7982
                }
7983
                break;
7984
            case QEMU_OPTION_echr:
7985
                {
7986
                    char *r;
7987
                    term_escape_char = strtol(optarg, &r, 0);
7988
                    if (r == optarg)
7989
                        printf("Bad argument to echr\n");
7990
                    break;
7991
                }
7992
            case QEMU_OPTION_monitor:
7993
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7994
                break;
7995
            case QEMU_OPTION_serial:
7996
                if (serial_device_index >= MAX_SERIAL_PORTS) {
7997
                    fprintf(stderr, "qemu: too many serial ports\n");
7998
                    exit(1);
7999
                }
8000
                pstrcpy(serial_devices[serial_device_index],
8001
                        sizeof(serial_devices[0]), optarg);
8002
                serial_device_index++;
8003
                break;
8004
            case QEMU_OPTION_parallel:
8005
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8006
                    fprintf(stderr, "qemu: too many parallel ports\n");
8007
                    exit(1);
8008
                }
8009
                pstrcpy(parallel_devices[parallel_device_index],
8010
                        sizeof(parallel_devices[0]), optarg);
8011
                parallel_device_index++;
8012
                break;
8013
            case QEMU_OPTION_loadvm:
8014
                loadvm = optarg;
8015
                break;
8016
            case QEMU_OPTION_full_screen:
8017
                full_screen = 1;
8018
                break;
8019
#ifdef CONFIG_SDL
8020
            case QEMU_OPTION_no_frame:
8021
                no_frame = 1;
8022
                break;
8023
            case QEMU_OPTION_alt_grab:
8024
                alt_grab = 1;
8025
                break;
8026
            case QEMU_OPTION_no_quit:
8027
                no_quit = 1;
8028
                break;
8029
#endif
8030
            case QEMU_OPTION_pidfile:
8031
                pid_file = optarg;
8032
                break;
8033
#ifdef TARGET_I386
8034
            case QEMU_OPTION_win2k_hack:
8035
                win2k_install_hack = 1;
8036
                break;
8037
#endif
8038
#ifdef USE_KQEMU
8039
            case QEMU_OPTION_no_kqemu:
8040
                kqemu_allowed = 0;
8041
                break;
8042
            case QEMU_OPTION_kernel_kqemu:
8043
                kqemu_allowed = 2;
8044
                break;
8045
#endif
8046
            case QEMU_OPTION_usb:
8047
                usb_enabled = 1;
8048
                break;
8049
            case QEMU_OPTION_usbdevice:
8050
                usb_enabled = 1;
8051
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8052
                    fprintf(stderr, "Too many USB devices\n");
8053
                    exit(1);
8054
                }
8055
                pstrcpy(usb_devices[usb_devices_index],
8056
                        sizeof(usb_devices[usb_devices_index]),
8057
                        optarg);
8058
                usb_devices_index++;
8059
                break;
8060
            case QEMU_OPTION_smp:
8061
                smp_cpus = atoi(optarg);
8062
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8063
                    fprintf(stderr, "Invalid number of CPUs\n");
8064
                    exit(1);
8065
                }
8066
                break;
8067
            case QEMU_OPTION_vnc:
8068
                vnc_display = optarg;
8069
                break;
8070
            case QEMU_OPTION_no_acpi:
8071
                acpi_enabled = 0;
8072
                break;
8073
            case QEMU_OPTION_no_reboot:
8074
                no_reboot = 1;
8075
                break;
8076
            case QEMU_OPTION_show_cursor:
8077
                cursor_hide = 0;
8078
                break;
8079
            case QEMU_OPTION_daemonize:
8080
                daemonize = 1;
8081
                break;
8082
            case QEMU_OPTION_option_rom:
8083
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8084
                    fprintf(stderr, "Too many option ROMs\n");
8085
                    exit(1);
8086
                }
8087
                option_rom[nb_option_roms] = optarg;
8088
                nb_option_roms++;
8089
                break;
8090
            case QEMU_OPTION_semihosting:
8091
                semihosting_enabled = 1;
8092
                break;
8093
            case QEMU_OPTION_name:
8094
                qemu_name = optarg;
8095
                break;
8096
#ifdef TARGET_SPARC
8097
            case QEMU_OPTION_prom_env:
8098
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8099
                    fprintf(stderr, "Too many prom variables\n");
8100
                    exit(1);
8101
                }
8102
                prom_envs[nb_prom_envs] = optarg;
8103
                nb_prom_envs++;
8104
                break;
8105
#endif
8106
#ifdef TARGET_ARM
8107
            case QEMU_OPTION_old_param:
8108
                old_param = 1;
8109
#endif
8110
            case QEMU_OPTION_clock:
8111
                configure_alarms(optarg);
8112
                break;
8113
            case QEMU_OPTION_startdate:
8114
                {
8115
                    struct tm tm;
8116
                    if (!strcmp(optarg, "now")) {
8117
                        rtc_start_date = -1;
8118
                    } else {
8119
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8120
                               &tm.tm_year,
8121
                               &tm.tm_mon,
8122
                               &tm.tm_mday,
8123
                               &tm.tm_hour,
8124
                               &tm.tm_min,
8125
                               &tm.tm_sec) == 6) {
8126
                            /* OK */
8127
                        } else if (sscanf(optarg, "%d-%d-%d",
8128
                                          &tm.tm_year,
8129
                                          &tm.tm_mon,
8130
                                          &tm.tm_mday) == 3) {
8131
                            tm.tm_hour = 0;
8132
                            tm.tm_min = 0;
8133
                            tm.tm_sec = 0;
8134
                        } else {
8135
                            goto date_fail;
8136
                        }
8137
                        tm.tm_year -= 1900;
8138
                        tm.tm_mon--;
8139
                        rtc_start_date = timegm(&tm);
8140
                        if (rtc_start_date == -1) {
8141
                        date_fail:
8142
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8143
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8144
                            exit(1);
8145
                        }
8146
                    }
8147
                }
8148
                break;
8149
            }
8150
        }
8151
    }
8152

    
8153
#ifndef _WIN32
8154
    if (daemonize && !nographic && vnc_display == NULL) {
8155
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8156
        daemonize = 0;
8157
    }
8158

    
8159
    if (daemonize) {
8160
        pid_t pid;
8161

    
8162
        if (pipe(fds) == -1)
8163
            exit(1);
8164

    
8165
        pid = fork();
8166
        if (pid > 0) {
8167
            uint8_t status;
8168
            ssize_t len;
8169

    
8170
            close(fds[1]);
8171

    
8172
        again:
8173
            len = read(fds[0], &status, 1);
8174
            if (len == -1 && (errno == EINTR))
8175
                goto again;
8176

    
8177
            if (len != 1)
8178
                exit(1);
8179
            else if (status == 1) {
8180
                fprintf(stderr, "Could not acquire pidfile\n");
8181
                exit(1);
8182
            } else
8183
                exit(0);
8184
        } else if (pid < 0)
8185
            exit(1);
8186

    
8187
        setsid();
8188

    
8189
        pid = fork();
8190
        if (pid > 0)
8191
            exit(0);
8192
        else if (pid < 0)
8193
            exit(1);
8194

    
8195
        umask(027);
8196
        chdir("/");
8197

    
8198
        signal(SIGTSTP, SIG_IGN);
8199
        signal(SIGTTOU, SIG_IGN);
8200
        signal(SIGTTIN, SIG_IGN);
8201
    }
8202
#endif
8203

    
8204
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8205
        if (daemonize) {
8206
            uint8_t status = 1;
8207
            write(fds[1], &status, 1);
8208
        } else
8209
            fprintf(stderr, "Could not acquire pid file\n");
8210
        exit(1);
8211
    }
8212

    
8213
#ifdef USE_KQEMU
8214
    if (smp_cpus > 1)
8215
        kqemu_allowed = 0;
8216
#endif
8217
    linux_boot = (kernel_filename != NULL);
8218

    
8219
    if (!linux_boot &&
8220
        (!strchr(boot_device, 'n')) &&
8221
        hd_filename[0] == '\0' &&
8222
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
8223
        fd_filename[0] == '\0')
8224
        help(1);
8225

    
8226
    /* boot to floppy or the default cd if no hard disk defined yet */
8227
    if (!boot_device[0]) {
8228
        if (hd_filename[0] != '\0')
8229
            boot_device[0] = 'c';
8230
        else if (fd_filename[0] != '\0')
8231
            boot_device[0] = 'a';
8232
        else
8233
            boot_device[0] = 'd';
8234
        boot_device[1] = 0;
8235
    }
8236
    setvbuf(stdout, NULL, _IOLBF, 0);
8237

    
8238
    init_timers();
8239
    init_timer_alarm();
8240
    qemu_aio_init();
8241

    
8242
#ifdef _WIN32
8243
    socket_init();
8244
#endif
8245

    
8246
    /* init network clients */
8247
    if (nb_net_clients == 0) {
8248
        /* if no clients, we use a default config */
8249
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
8250
                "nic");
8251
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
8252
                "user");
8253
        nb_net_clients = 2;
8254
    }
8255

    
8256
    for(i = 0;i < nb_net_clients; i++) {
8257
        if (net_client_init(net_clients[i]) < 0)
8258
            exit(1);
8259
    }
8260
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8261
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8262
            continue;
8263
        if (vlan->nb_guest_devs == 0) {
8264
            fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8265
            exit(1);
8266
        }
8267
        if (vlan->nb_host_devs == 0)
8268
            fprintf(stderr,
8269
                    "Warning: vlan %d is not connected to host network\n",
8270
                    vlan->id);
8271
    }
8272

    
8273
#ifdef TARGET_I386
8274
    if (strchr(boot_device, 'n')) {
8275
        for (i = 0; i < nb_nics; i++) {
8276
            const char *model = nd_table[i].model;
8277
            char buf[1024];
8278
            if (model == NULL)
8279
                model = "ne2k_pci";
8280
            snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8281
            if (get_image_size(buf) > 0) {
8282
                option_rom[nb_option_roms] = strdup(buf);
8283
                nb_option_roms++;
8284
                break;
8285
            }
8286
        }
8287
        if (i == nb_nics) {
8288
            fprintf(stderr, "No valid PXE rom found for network device\n");
8289
            exit(1);
8290
        }
8291
    }
8292
#endif
8293

    
8294
    /* init the memory */
8295
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8296

    
8297
    phys_ram_base = qemu_vmalloc(phys_ram_size);
8298
    if (!phys_ram_base) {
8299
        fprintf(stderr, "Could not allocate physical memory\n");
8300
        exit(1);
8301
    }
8302

    
8303
    /* we always create the cdrom drive, even if no disk is there */
8304
    bdrv_init();
8305
    if (cdrom_index >= 0) {
8306
        bs_table[cdrom_index] = bdrv_new("cdrom");
8307
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8308
    }
8309

    
8310
    /* open the virtual block devices */
8311
    for(i = 0; i < MAX_DISKS; i++) {
8312
        if (hd_filename[i]) {
8313
            if (!bs_table[i]) {
8314
                char buf[64];
8315
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8316
                bs_table[i] = bdrv_new(buf);
8317
            }
8318
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8319
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8320
                        hd_filename[i]);
8321
                exit(1);
8322
            }
8323
            if (i == 0 && cyls != 0) {
8324
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8325
                bdrv_set_translation_hint(bs_table[i], translation);
8326
            }
8327
        }
8328
    }
8329

    
8330
    /* we always create at least one floppy disk */
8331
    fd_table[0] = bdrv_new("fda");
8332
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8333

    
8334
    for(i = 0; i < MAX_FD; i++) {
8335
        if (fd_filename[i]) {
8336
            if (!fd_table[i]) {
8337
                char buf[64];
8338
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8339
                fd_table[i] = bdrv_new(buf);
8340
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8341
            }
8342
            if (fd_filename[i][0] != '\0') {
8343
                if (bdrv_open(fd_table[i], fd_filename[i],
8344
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8345
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8346
                            fd_filename[i]);
8347
                    exit(1);
8348
                }
8349
            }
8350
        }
8351
    }
8352

    
8353
    /* Open the virtual parallel flash block devices */
8354
    for(i = 0; i < MAX_PFLASH; i++) {
8355
        if (pflash_filename[i]) {
8356
            if (!pflash_table[i]) {
8357
                char buf[64];
8358
                snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8359
                pflash_table[i] = bdrv_new(buf);
8360
            }
8361
            if (bdrv_open(pflash_table[i], pflash_filename[i],
8362
                          snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8363
                fprintf(stderr, "qemu: could not open flash image '%s'\n",
8364
                        pflash_filename[i]);
8365
                exit(1);
8366
            }
8367
        }
8368
    }
8369

    
8370
    sd_bdrv = bdrv_new ("sd");
8371
    /* FIXME: This isn't really a floppy, but it's a reasonable
8372
       approximation.  */
8373
    bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8374
    if (sd_filename) {
8375
        if (bdrv_open(sd_bdrv, sd_filename,
8376
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8377
            fprintf(stderr, "qemu: could not open SD card image %s\n",
8378
                    sd_filename);
8379
        } else
8380
            qemu_key_check(sd_bdrv, sd_filename);
8381
    }
8382

    
8383
    if (mtd_filename) {
8384
        mtd_bdrv = bdrv_new ("mtd");
8385
        if (bdrv_open(mtd_bdrv, mtd_filename,
8386
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8387
            qemu_key_check(mtd_bdrv, mtd_filename)) {
8388
            fprintf(stderr, "qemu: could not open Flash image %s\n",
8389
                    mtd_filename);
8390
            bdrv_delete(mtd_bdrv);
8391
            mtd_bdrv = 0;
8392
        }
8393
    }
8394

    
8395
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8396
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8397

    
8398
    init_ioports();
8399

    
8400
    /* terminal init */
8401
    memset(&display_state, 0, sizeof(display_state));
8402
    if (nographic) {
8403
        /* nearly nothing to do */
8404
        dumb_display_init(ds);
8405
    } else if (vnc_display != NULL) {
8406
        vnc_display_init(ds);
8407
        if (vnc_display_open(ds, vnc_display) < 0)
8408
            exit(1);
8409
    } else {
8410
#if defined(CONFIG_SDL)
8411
        sdl_display_init(ds, full_screen, no_frame);
8412
#elif defined(CONFIG_COCOA)
8413
        cocoa_display_init(ds, full_screen);
8414
#endif
8415
    }
8416

    
8417
    /* Maintain compatibility with multiple stdio monitors */
8418
    if (!strcmp(monitor_device,"stdio")) {
8419
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8420
            if (!strcmp(serial_devices[i],"mon:stdio")) {
8421
                monitor_device[0] = '\0';
8422
                break;
8423
            } else if (!strcmp(serial_devices[i],"stdio")) {
8424
                monitor_device[0] = '\0';
8425
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8426
                break;
8427
            }
8428
        }
8429
    }
8430
    if (monitor_device[0] != '\0') {
8431
        monitor_hd = qemu_chr_open(monitor_device);
8432
        if (!monitor_hd) {
8433
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8434
            exit(1);
8435
        }
8436
        monitor_init(monitor_hd, !nographic);
8437
    }
8438

    
8439
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8440
        const char *devname = serial_devices[i];
8441
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8442
            serial_hds[i] = qemu_chr_open(devname);
8443
            if (!serial_hds[i]) {
8444
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
8445
                        devname);
8446
                exit(1);
8447
            }
8448
            if (strstart(devname, "vc", 0))
8449
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8450
        }
8451
    }
8452

    
8453
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8454
        const char *devname = parallel_devices[i];
8455
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8456
            parallel_hds[i] = qemu_chr_open(devname);
8457
            if (!parallel_hds[i]) {
8458
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8459
                        devname);
8460
                exit(1);
8461
            }
8462
            if (strstart(devname, "vc", 0))
8463
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8464
        }
8465
    }
8466

    
8467
    machine->init(ram_size, vga_ram_size, boot_device,
8468
                  ds, fd_filename, snapshot,
8469
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8470

    
8471
    /* init USB devices */
8472
    if (usb_enabled) {
8473
        for(i = 0; i < usb_devices_index; i++) {
8474
            if (usb_device_add(usb_devices[i]) < 0) {
8475
                fprintf(stderr, "Warning: could not add USB device %s\n",
8476
                        usb_devices[i]);
8477
            }
8478
        }
8479
    }
8480

    
8481
    if (display_state.dpy_refresh) {
8482
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8483
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8484
    }
8485

    
8486
#ifdef CONFIG_GDBSTUB
8487
    if (use_gdbstub) {
8488
        /* XXX: use standard host:port notation and modify options
8489
           accordingly. */
8490
        if (gdbserver_start(gdbstub_port) < 0) {
8491
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8492
                    gdbstub_port);
8493
            exit(1);
8494
        }
8495
    }
8496
#endif
8497

    
8498
    if (loadvm)
8499
        do_loadvm(loadvm);
8500

    
8501
    {
8502
        /* XXX: simplify init */
8503
        read_passwords();
8504
        if (autostart) {
8505
            vm_start();
8506
        }
8507
    }
8508

    
8509
    if (daemonize) {
8510
        uint8_t status = 0;
8511
        ssize_t len;
8512
        int fd;
8513

    
8514
    again1:
8515
        len = write(fds[1], &status, 1);
8516
        if (len == -1 && (errno == EINTR))
8517
            goto again1;
8518

    
8519
        if (len != 1)
8520
            exit(1);
8521

    
8522
        TFR(fd = open("/dev/null", O_RDWR));
8523
        if (fd == -1)
8524
            exit(1);
8525

    
8526
        dup2(fd, 0);
8527
        dup2(fd, 1);
8528
        dup2(fd, 2);
8529

    
8530
        close(fd);
8531
    }
8532

    
8533
    main_loop();
8534
    quit_timers();
8535

    
8536
#if !defined(_WIN32)
8537
    /* close network clients */
8538
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8539
        VLANClientState *vc;
8540

    
8541
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8542
            if (vc->fd_read == tap_receive) {
8543
                char ifname[64];
8544
                TAPState *s = vc->opaque;
8545

    
8546
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8547
                    s->down_script[0])
8548
                    launch_script(s->down_script, ifname, s->fd);
8549
            }
8550
    }
8551
    }
8552
#endif
8553
    return 0;
8554
}