Statistics
| Branch: | Revision:

root / vl.c @ b5a23ad4

History | View | Annotate | Download (234.3 kB)

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

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

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

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

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

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

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

    
117
#include "qemu_socket.h"
118

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

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

    
130
#include "disas.h"
131

    
132
#include "exec-all.h"
133

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

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

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

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

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

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

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

    
239
static CPUState *cur_cpu;
240
static CPUState *next_cpu;
241
static int event_pending = 1;
242

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

    
245
/***********************************************************/
246
/* x86 ISA bus support */
247

    
248
target_phys_addr_t isa_mem_base = 0;
249
PicState2 *isa_pic;
250

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

    
259
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
260
{
261
#ifdef DEBUG_UNUSED_IOPORT
262
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
263
#endif
264
}
265

    
266
/* default is to make two byte accesses */
267
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
268
{
269
    uint32_t data;
270
    data = ioport_read_table[0][address](ioport_opaque[address], address);
271
    address = (address + 1) & (MAX_IOPORTS - 1);
272
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
273
    return data;
274
}
275

    
276
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
277
{
278
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
279
    address = (address + 1) & (MAX_IOPORTS - 1);
280
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
281
}
282

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

    
291
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
292
{
293
#ifdef DEBUG_UNUSED_IOPORT
294
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
295
#endif
296
}
297

    
298
static void init_ioports(void)
299
{
300
    int i;
301

    
302
    for(i = 0; i < MAX_IOPORTS; i++) {
303
        ioport_read_table[0][i] = default_ioport_readb;
304
        ioport_write_table[0][i] = default_ioport_writeb;
305
        ioport_read_table[1][i] = default_ioport_readw;
306
        ioport_write_table[1][i] = default_ioport_writew;
307
        ioport_read_table[2][i] = default_ioport_readl;
308
        ioport_write_table[2][i] = default_ioport_writel;
309
    }
310
}
311

    
312
/* size is the word size in byte */
313
int register_ioport_read(int start, int length, int size,
314
                         IOPortReadFunc *func, void *opaque)
315
{
316
    int i, bsize;
317

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

    
337
/* size is the word size in byte */
338
int register_ioport_write(int start, int length, int size,
339
                          IOPortWriteFunc *func, void *opaque)
340
{
341
    int i, bsize;
342

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

    
362
void isa_unassign_ioport(int start, int length)
363
{
364
    int i;
365

    
366
    for(i = start; i < start + length; i++) {
367
        ioport_read_table[0][i] = default_ioport_readb;
368
        ioport_read_table[1][i] = default_ioport_readw;
369
        ioport_read_table[2][i] = default_ioport_readl;
370

    
371
        ioport_write_table[0][i] = default_ioport_writeb;
372
        ioport_write_table[1][i] = default_ioport_writew;
373
        ioport_write_table[2][i] = default_ioport_writel;
374
    }
375
}
376

    
377
/***********************************************************/
378

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

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

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

    
418
int cpu_inb(CPUState *env, int addr)
419
{
420
    int val;
421
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
422
#ifdef DEBUG_IOPORT
423
    if (loglevel & CPU_LOG_IOPORT)
424
        fprintf(logfile, "inb : %04x %02x\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_inw(CPUState *env, int addr)
434
{
435
    int val;
436
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
437
#ifdef DEBUG_IOPORT
438
    if (loglevel & CPU_LOG_IOPORT)
439
        fprintf(logfile, "inw : %04x %04x\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
int cpu_inl(CPUState *env, int addr)
449
{
450
    int val;
451
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
452
#ifdef DEBUG_IOPORT
453
    if (loglevel & CPU_LOG_IOPORT)
454
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
455
#endif
456
#ifdef USE_KQEMU
457
    if (env)
458
        env->last_io_time = cpu_get_time_fast();
459
#endif
460
    return val;
461
}
462

    
463
/***********************************************************/
464
void hw_error(const char *fmt, ...)
465
{
466
    va_list ap;
467
    CPUState *env;
468

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

    
485
/***********************************************************/
486
/* keyboard/mouse */
487

    
488
static QEMUPutKBDEvent *qemu_put_kbd_event;
489
static void *qemu_put_kbd_event_opaque;
490
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
491
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
492

    
493
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
494
{
495
    qemu_put_kbd_event_opaque = opaque;
496
    qemu_put_kbd_event = func;
497
}
498

    
499
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
500
                                                void *opaque, int absolute,
501
                                                const char *name)
502
{
503
    QEMUPutMouseEntry *s, *cursor;
504

    
505
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
506
    if (!s)
507
        return NULL;
508

    
509
    s->qemu_put_mouse_event = func;
510
    s->qemu_put_mouse_event_opaque = opaque;
511
    s->qemu_put_mouse_event_absolute = absolute;
512
    s->qemu_put_mouse_event_name = qemu_strdup(name);
513
    s->next = NULL;
514

    
515
    if (!qemu_put_mouse_event_head) {
516
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
517
        return s;
518
    }
519

    
520
    cursor = qemu_put_mouse_event_head;
521
    while (cursor->next != NULL)
522
        cursor = cursor->next;
523

    
524
    cursor->next = s;
525
    qemu_put_mouse_event_current = s;
526

    
527
    return s;
528
}
529

    
530
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
531
{
532
    QEMUPutMouseEntry *prev = NULL, *cursor;
533

    
534
    if (!qemu_put_mouse_event_head || entry == NULL)
535
        return;
536

    
537
    cursor = qemu_put_mouse_event_head;
538
    while (cursor != NULL && cursor != entry) {
539
        prev = cursor;
540
        cursor = cursor->next;
541
    }
542

    
543
    if (cursor == NULL) // does not exist or list empty
544
        return;
545
    else if (prev == NULL) { // entry is head
546
        qemu_put_mouse_event_head = cursor->next;
547
        if (qemu_put_mouse_event_current == entry)
548
            qemu_put_mouse_event_current = cursor->next;
549
        qemu_free(entry->qemu_put_mouse_event_name);
550
        qemu_free(entry);
551
        return;
552
    }
553

    
554
    prev->next = entry->next;
555

    
556
    if (qemu_put_mouse_event_current == entry)
557
        qemu_put_mouse_event_current = prev;
558

    
559
    qemu_free(entry->qemu_put_mouse_event_name);
560
    qemu_free(entry);
561
}
562

    
563
void kbd_put_keycode(int keycode)
564
{
565
    if (qemu_put_kbd_event) {
566
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
567
    }
568
}
569

    
570
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
571
{
572
    QEMUPutMouseEvent *mouse_event;
573
    void *mouse_event_opaque;
574
    int width;
575

    
576
    if (!qemu_put_mouse_event_current) {
577
        return;
578
    }
579

    
580
    mouse_event =
581
        qemu_put_mouse_event_current->qemu_put_mouse_event;
582
    mouse_event_opaque =
583
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
584

    
585
    if (mouse_event) {
586
        if (graphic_rotate) {
587
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
588
                width = 0x7fff;
589
            else
590
                width = graphic_width;
591
            mouse_event(mouse_event_opaque,
592
                                 width - dy, dx, dz, buttons_state);
593
        } else
594
            mouse_event(mouse_event_opaque,
595
                                 dx, dy, dz, buttons_state);
596
    }
597
}
598

    
599
int kbd_mouse_is_absolute(void)
600
{
601
    if (!qemu_put_mouse_event_current)
602
        return 0;
603

    
604
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
605
}
606

    
607
void do_info_mice(void)
608
{
609
    QEMUPutMouseEntry *cursor;
610
    int index = 0;
611

    
612
    if (!qemu_put_mouse_event_head) {
613
        term_printf("No mouse devices connected\n");
614
        return;
615
    }
616

    
617
    term_printf("Mouse devices available:\n");
618
    cursor = qemu_put_mouse_event_head;
619
    while (cursor != NULL) {
620
        term_printf("%c Mouse #%d: %s\n",
621
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
622
                    index, cursor->qemu_put_mouse_event_name);
623
        index++;
624
        cursor = cursor->next;
625
    }
626
}
627

    
628
void do_mouse_set(int index)
629
{
630
    QEMUPutMouseEntry *cursor;
631
    int i = 0;
632

    
633
    if (!qemu_put_mouse_event_head) {
634
        term_printf("No mouse devices connected\n");
635
        return;
636
    }
637

    
638
    cursor = qemu_put_mouse_event_head;
639
    while (cursor != NULL && index != i) {
640
        i++;
641
        cursor = cursor->next;
642
    }
643

    
644
    if (cursor != NULL)
645
        qemu_put_mouse_event_current = cursor;
646
    else
647
        term_printf("Mouse at given index not found\n");
648
}
649

    
650
/* compute with 96 bit intermediate result: (a*b)/c */
651
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
652
{
653
    union {
654
        uint64_t ll;
655
        struct {
656
#ifdef WORDS_BIGENDIAN
657
            uint32_t high, low;
658
#else
659
            uint32_t low, high;
660
#endif
661
        } l;
662
    } u, res;
663
    uint64_t rl, rh;
664

    
665
    u.ll = a;
666
    rl = (uint64_t)u.l.low * (uint64_t)b;
667
    rh = (uint64_t)u.l.high * (uint64_t)b;
668
    rh += (rl >> 32);
669
    res.l.high = rh / c;
670
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
671
    return res.ll;
672
}
673

    
674
/***********************************************************/
675
/* real time host monotonic timer */
676

    
677
#define QEMU_TIMER_BASE 1000000000LL
678

    
679
#ifdef WIN32
680

    
681
static int64_t clock_freq;
682

    
683
static void init_get_clock(void)
684
{
685
    LARGE_INTEGER freq;
686
    int ret;
687
    ret = QueryPerformanceFrequency(&freq);
688
    if (ret == 0) {
689
        fprintf(stderr, "Could not calibrate ticks\n");
690
        exit(1);
691
    }
692
    clock_freq = freq.QuadPart;
693
}
694

    
695
static int64_t get_clock(void)
696
{
697
    LARGE_INTEGER ti;
698
    QueryPerformanceCounter(&ti);
699
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
700
}
701

    
702
#else
703

    
704
static int use_rt_clock;
705

    
706
static void init_get_clock(void)
707
{
708
    use_rt_clock = 0;
709
#if defined(__linux__)
710
    {
711
        struct timespec ts;
712
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
713
            use_rt_clock = 1;
714
        }
715
    }
716
#endif
717
}
718

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

    
737
#endif
738

    
739
/***********************************************************/
740
/* guest cycle counter */
741

    
742
static int64_t cpu_ticks_prev;
743
static int64_t cpu_ticks_offset;
744
static int64_t cpu_clock_offset;
745
static int cpu_ticks_enabled;
746

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

    
765
/* return the host CPU monotonic timer and handle stop/restart */
766
static int64_t cpu_get_clock(void)
767
{
768
    int64_t ti;
769
    if (!cpu_ticks_enabled) {
770
        return cpu_clock_offset;
771
    } else {
772
        ti = get_clock();
773
        return ti + cpu_clock_offset;
774
    }
775
}
776

    
777
/* enable cpu_get_ticks() */
778
void cpu_enable_ticks(void)
779
{
780
    if (!cpu_ticks_enabled) {
781
        cpu_ticks_offset -= cpu_get_real_ticks();
782
        cpu_clock_offset -= get_clock();
783
        cpu_ticks_enabled = 1;
784
    }
785
}
786

    
787
/* disable cpu_get_ticks() : the clock is stopped. You must not call
788
   cpu_get_ticks() after that.  */
789
void cpu_disable_ticks(void)
790
{
791
    if (cpu_ticks_enabled) {
792
        cpu_ticks_offset = cpu_get_ticks();
793
        cpu_clock_offset = cpu_get_clock();
794
        cpu_ticks_enabled = 0;
795
    }
796
}
797

    
798
/***********************************************************/
799
/* timers */
800

    
801
#define QEMU_TIMER_REALTIME 0
802
#define QEMU_TIMER_VIRTUAL  1
803

    
804
struct QEMUClock {
805
    int type;
806
    /* XXX: add frequency */
807
};
808

    
809
struct QEMUTimer {
810
    QEMUClock *clock;
811
    int64_t expire_time;
812
    QEMUTimerCB *cb;
813
    void *opaque;
814
    struct QEMUTimer *next;
815
};
816

    
817
struct qemu_alarm_timer {
818
    char const *name;
819
    unsigned int flags;
820

    
821
    int (*start)(struct qemu_alarm_timer *t);
822
    void (*stop)(struct qemu_alarm_timer *t);
823
    void (*rearm)(struct qemu_alarm_timer *t);
824
    void *priv;
825
};
826

    
827
#define ALARM_FLAG_DYNTICKS  0x1
828
#define ALARM_FLAG_EXPIRED   0x2
829

    
830
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
831
{
832
    return t->flags & ALARM_FLAG_DYNTICKS;
833
}
834

    
835
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
836
{
837
    if (!alarm_has_dynticks(t))
838
        return;
839

    
840
    t->rearm(t);
841
}
842

    
843
/* TODO: MIN_TIMER_REARM_US should be optimized */
844
#define MIN_TIMER_REARM_US 250
845

    
846
static struct qemu_alarm_timer *alarm_timer;
847

    
848
#ifdef _WIN32
849

    
850
struct qemu_alarm_win32 {
851
    MMRESULT timerId;
852
    HANDLE host_alarm;
853
    unsigned int period;
854
} alarm_win32_data = {0, NULL, -1};
855

    
856
static int win32_start_timer(struct qemu_alarm_timer *t);
857
static void win32_stop_timer(struct qemu_alarm_timer *t);
858
static void win32_rearm_timer(struct qemu_alarm_timer *t);
859

    
860
#else
861

    
862
static int unix_start_timer(struct qemu_alarm_timer *t);
863
static void unix_stop_timer(struct qemu_alarm_timer *t);
864

    
865
#ifdef __linux__
866

    
867
static int dynticks_start_timer(struct qemu_alarm_timer *t);
868
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
869
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
870

    
871
static int hpet_start_timer(struct qemu_alarm_timer *t);
872
static void hpet_stop_timer(struct qemu_alarm_timer *t);
873

    
874
static int rtc_start_timer(struct qemu_alarm_timer *t);
875
static void rtc_stop_timer(struct qemu_alarm_timer *t);
876

    
877
#endif /* __linux__ */
878

    
879
#endif /* _WIN32 */
880

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

    
901
static void show_available_alarms()
902
{
903
    int i;
904

    
905
    printf("Available alarm timers, in order of precedence:\n");
906
    for (i = 0; alarm_timers[i].name; i++)
907
        printf("%s\n", alarm_timers[i].name);
908
}
909

    
910
static void configure_alarms(char const *opt)
911
{
912
    int i;
913
    int cur = 0;
914
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
915
    char *arg;
916
    char *name;
917

    
918
    if (!strcmp(opt, "help")) {
919
        show_available_alarms();
920
        exit(0);
921
    }
922

    
923
    arg = strdup(opt);
924

    
925
    /* Reorder the array */
926
    name = strtok(arg, ",");
927
    while (name) {
928
        struct qemu_alarm_timer tmp;
929

    
930
        for (i = 0; i < count && alarm_timers[i].name; i++) {
931
            if (!strcmp(alarm_timers[i].name, name))
932
                break;
933
        }
934

    
935
        if (i == count) {
936
            fprintf(stderr, "Unknown clock %s\n", name);
937
            goto next;
938
        }
939

    
940
        if (i < cur)
941
            /* Ignore */
942
            goto next;
943

    
944
        /* Swap */
945
        tmp = alarm_timers[i];
946
        alarm_timers[i] = alarm_timers[cur];
947
        alarm_timers[cur] = tmp;
948

    
949
        cur++;
950
next:
951
        name = strtok(NULL, ",");
952
    }
953

    
954
    free(arg);
955

    
956
    if (cur) {
957
        /* Disable remaining timers */
958
        for (i = cur; i < count; i++)
959
            alarm_timers[i].name = NULL;
960
    }
961

    
962
    /* debug */
963
    show_available_alarms();
964
}
965

    
966
QEMUClock *rt_clock;
967
QEMUClock *vm_clock;
968

    
969
static QEMUTimer *active_timers[2];
970

    
971
static QEMUClock *qemu_new_clock(int type)
972
{
973
    QEMUClock *clock;
974
    clock = qemu_mallocz(sizeof(QEMUClock));
975
    if (!clock)
976
        return NULL;
977
    clock->type = type;
978
    return clock;
979
}
980

    
981
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
982
{
983
    QEMUTimer *ts;
984

    
985
    ts = qemu_mallocz(sizeof(QEMUTimer));
986
    ts->clock = clock;
987
    ts->cb = cb;
988
    ts->opaque = opaque;
989
    return ts;
990
}
991

    
992
void qemu_free_timer(QEMUTimer *ts)
993
{
994
    qemu_free(ts);
995
}
996

    
997
/* stop a timer, but do not dealloc it */
998
void qemu_del_timer(QEMUTimer *ts)
999
{
1000
    QEMUTimer **pt, *t;
1001

    
1002
    /* NOTE: this code must be signal safe because
1003
       qemu_timer_expired() can be called from a signal. */
1004
    pt = &active_timers[ts->clock->type];
1005
    for(;;) {
1006
        t = *pt;
1007
        if (!t)
1008
            break;
1009
        if (t == ts) {
1010
            *pt = t->next;
1011
            break;
1012
        }
1013
        pt = &t->next;
1014
    }
1015
}
1016

    
1017
/* modify the current timer so that it will be fired when current_time
1018
   >= expire_time. The corresponding callback will be called. */
1019
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1020
{
1021
    QEMUTimer **pt, *t;
1022

    
1023
    qemu_del_timer(ts);
1024

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

    
1041
    /* Rearm if necessary  */
1042
    if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1043
        pt == &active_timers[ts->clock->type])
1044
        qemu_rearm_alarm_timer(alarm_timer);
1045
}
1046

    
1047
int qemu_timer_pending(QEMUTimer *ts)
1048
{
1049
    QEMUTimer *t;
1050
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1051
        if (t == ts)
1052
            return 1;
1053
    }
1054
    return 0;
1055
}
1056

    
1057
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1058
{
1059
    if (!timer_head)
1060
        return 0;
1061
    return (timer_head->expire_time <= current_time);
1062
}
1063

    
1064
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1065
{
1066
    QEMUTimer *ts;
1067

    
1068
    for(;;) {
1069
        ts = *ptimer_head;
1070
        if (!ts || ts->expire_time > current_time)
1071
            break;
1072
        /* remove timer from the list before calling the callback */
1073
        *ptimer_head = ts->next;
1074
        ts->next = NULL;
1075

    
1076
        /* run the callback (the timer list can be modified) */
1077
        ts->cb(ts->opaque);
1078
    }
1079
}
1080

    
1081
int64_t qemu_get_clock(QEMUClock *clock)
1082
{
1083
    switch(clock->type) {
1084
    case QEMU_TIMER_REALTIME:
1085
        return get_clock() / 1000000;
1086
    default:
1087
    case QEMU_TIMER_VIRTUAL:
1088
        return cpu_get_clock();
1089
    }
1090
}
1091

    
1092
static void init_timers(void)
1093
{
1094
    init_get_clock();
1095
    ticks_per_sec = QEMU_TIMER_BASE;
1096
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1097
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1098
}
1099

    
1100
/* save a timer */
1101
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1102
{
1103
    uint64_t expire_time;
1104

    
1105
    if (qemu_timer_pending(ts)) {
1106
        expire_time = ts->expire_time;
1107
    } else {
1108
        expire_time = -1;
1109
    }
1110
    qemu_put_be64(f, expire_time);
1111
}
1112

    
1113
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1114
{
1115
    uint64_t expire_time;
1116

    
1117
    expire_time = qemu_get_be64(f);
1118
    if (expire_time != -1) {
1119
        qemu_mod_timer(ts, expire_time);
1120
    } else {
1121
        qemu_del_timer(ts);
1122
    }
1123
}
1124

    
1125
static void timer_save(QEMUFile *f, void *opaque)
1126
{
1127
    if (cpu_ticks_enabled) {
1128
        hw_error("cannot save state if virtual timers are running");
1129
    }
1130
    qemu_put_be64(f, cpu_ticks_offset);
1131
    qemu_put_be64(f, ticks_per_sec);
1132
    qemu_put_be64(f, cpu_clock_offset);
1133
}
1134

    
1135
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1136
{
1137
    if (version_id != 1 && version_id != 2)
1138
        return -EINVAL;
1139
    if (cpu_ticks_enabled) {
1140
        return -EINVAL;
1141
    }
1142
    cpu_ticks_offset=qemu_get_be64(f);
1143
    ticks_per_sec=qemu_get_be64(f);
1144
    if (version_id == 2) {
1145
        cpu_clock_offset=qemu_get_be64(f);
1146
    }
1147
    return 0;
1148
}
1149

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

    
1197
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1198

    
1199
        if (env) {
1200
            /* stop the currently executing cpu because a timer occured */
1201
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1202
#ifdef USE_KQEMU
1203
            if (env->kqemu_enabled) {
1204
                kqemu_cpu_interrupt(env);
1205
            }
1206
#endif
1207
        }
1208
        event_pending = 1;
1209
    }
1210
}
1211

    
1212
static uint64_t qemu_next_deadline(void)
1213
{
1214
    int64_t nearest_delta_us = INT64_MAX;
1215
    int64_t vmdelta_us;
1216

    
1217
    if (active_timers[QEMU_TIMER_REALTIME])
1218
        nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1219
                            qemu_get_clock(rt_clock))*1000;
1220

    
1221
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1222
        /* round up */
1223
        vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1224
                      qemu_get_clock(vm_clock)+999)/1000;
1225
        if (vmdelta_us < nearest_delta_us)
1226
            nearest_delta_us = vmdelta_us;
1227
    }
1228

    
1229
    /* Avoid arming the timer to negative, zero, or too low values */
1230
    if (nearest_delta_us <= MIN_TIMER_REARM_US)
1231
        nearest_delta_us = MIN_TIMER_REARM_US;
1232

    
1233
    return nearest_delta_us;
1234
}
1235

    
1236
#ifndef _WIN32
1237

    
1238
#if defined(__linux__)
1239

    
1240
#define RTC_FREQ 1024
1241

    
1242
static void enable_sigio_timer(int fd)
1243
{
1244
    struct sigaction act;
1245

    
1246
    /* timer signal */
1247
    sigfillset(&act.sa_mask);
1248
    act.sa_flags = 0;
1249
    act.sa_handler = host_alarm_handler;
1250

    
1251
    sigaction(SIGIO, &act, NULL);
1252
    fcntl(fd, F_SETFL, O_ASYNC);
1253
    fcntl(fd, F_SETOWN, getpid());
1254
}
1255

    
1256
static int hpet_start_timer(struct qemu_alarm_timer *t)
1257
{
1258
    struct hpet_info info;
1259
    int r, fd;
1260

    
1261
    fd = open("/dev/hpet", O_RDONLY);
1262
    if (fd < 0)
1263
        return -1;
1264

    
1265
    /* Set frequency */
1266
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1267
    if (r < 0) {
1268
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1269
                "error, but for better emulation accuracy type:\n"
1270
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1271
        goto fail;
1272
    }
1273

    
1274
    /* Check capabilities */
1275
    r = ioctl(fd, HPET_INFO, &info);
1276
    if (r < 0)
1277
        goto fail;
1278

    
1279
    /* Enable periodic mode */
1280
    r = ioctl(fd, HPET_EPI, 0);
1281
    if (info.hi_flags && (r < 0))
1282
        goto fail;
1283

    
1284
    /* Enable interrupt */
1285
    r = ioctl(fd, HPET_IE_ON, 0);
1286
    if (r < 0)
1287
        goto fail;
1288

    
1289
    enable_sigio_timer(fd);
1290
    t->priv = (void *)(long)fd;
1291

    
1292
    return 0;
1293
fail:
1294
    close(fd);
1295
    return -1;
1296
}
1297

    
1298
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1299
{
1300
    int fd = (long)t->priv;
1301

    
1302
    close(fd);
1303
}
1304

    
1305
static int rtc_start_timer(struct qemu_alarm_timer *t)
1306
{
1307
    int rtc_fd;
1308
    unsigned long current_rtc_freq = 0;
1309

    
1310
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1311
    if (rtc_fd < 0)
1312
        return -1;
1313
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1314
    if (current_rtc_freq != RTC_FREQ &&
1315
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1316
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1317
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1318
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1319
        goto fail;
1320
    }
1321
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1322
    fail:
1323
        close(rtc_fd);
1324
        return -1;
1325
    }
1326

    
1327
    enable_sigio_timer(rtc_fd);
1328

    
1329
    t->priv = (void *)(long)rtc_fd;
1330

    
1331
    return 0;
1332
}
1333

    
1334
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1335
{
1336
    int rtc_fd = (long)t->priv;
1337

    
1338
    close(rtc_fd);
1339
}
1340

    
1341
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1342
{
1343
    struct sigevent ev;
1344
    timer_t host_timer;
1345
    struct sigaction act;
1346

    
1347
    sigfillset(&act.sa_mask);
1348
    act.sa_flags = 0;
1349
    act.sa_handler = host_alarm_handler;
1350

    
1351
    sigaction(SIGALRM, &act, NULL);
1352

    
1353
    ev.sigev_value.sival_int = 0;
1354
    ev.sigev_notify = SIGEV_SIGNAL;
1355
    ev.sigev_signo = SIGALRM;
1356

    
1357
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1358
        perror("timer_create");
1359

    
1360
        /* disable dynticks */
1361
        fprintf(stderr, "Dynamic Ticks disabled\n");
1362

    
1363
        return -1;
1364
    }
1365

    
1366
    t->priv = (void *)host_timer;
1367

    
1368
    return 0;
1369
}
1370

    
1371
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1372
{
1373
    timer_t host_timer = (timer_t)t->priv;
1374

    
1375
    timer_delete(host_timer);
1376
}
1377

    
1378
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1379
{
1380
    timer_t host_timer = (timer_t)t->priv;
1381
    struct itimerspec timeout;
1382
    int64_t nearest_delta_us = INT64_MAX;
1383
    int64_t current_us;
1384

    
1385
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1386
                !active_timers[QEMU_TIMER_VIRTUAL])
1387
        return;
1388

    
1389
    nearest_delta_us = qemu_next_deadline();
1390

    
1391
    /* check whether a timer is already running */
1392
    if (timer_gettime(host_timer, &timeout)) {
1393
        perror("gettime");
1394
        fprintf(stderr, "Internal timer error: aborting\n");
1395
        exit(1);
1396
    }
1397
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1398
    if (current_us && current_us <= nearest_delta_us)
1399
        return;
1400

    
1401
    timeout.it_interval.tv_sec = 0;
1402
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1403
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1404
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1405
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1406
        perror("settime");
1407
        fprintf(stderr, "Internal timer error: aborting\n");
1408
        exit(1);
1409
    }
1410
}
1411

    
1412
#endif /* defined(__linux__) */
1413

    
1414
static int unix_start_timer(struct qemu_alarm_timer *t)
1415
{
1416
    struct sigaction act;
1417
    struct itimerval itv;
1418
    int err;
1419

    
1420
    /* timer signal */
1421
    sigfillset(&act.sa_mask);
1422
    act.sa_flags = 0;
1423
    act.sa_handler = host_alarm_handler;
1424

    
1425
    sigaction(SIGALRM, &act, NULL);
1426

    
1427
    itv.it_interval.tv_sec = 0;
1428
    /* for i386 kernel 2.6 to get 1 ms */
1429
    itv.it_interval.tv_usec = 999;
1430
    itv.it_value.tv_sec = 0;
1431
    itv.it_value.tv_usec = 10 * 1000;
1432

    
1433
    err = setitimer(ITIMER_REAL, &itv, NULL);
1434
    if (err)
1435
        return -1;
1436

    
1437
    return 0;
1438
}
1439

    
1440
static void unix_stop_timer(struct qemu_alarm_timer *t)
1441
{
1442
    struct itimerval itv;
1443

    
1444
    memset(&itv, 0, sizeof(itv));
1445
    setitimer(ITIMER_REAL, &itv, NULL);
1446
}
1447

    
1448
#endif /* !defined(_WIN32) */
1449

    
1450
#ifdef _WIN32
1451

    
1452
static int win32_start_timer(struct qemu_alarm_timer *t)
1453
{
1454
    TIMECAPS tc;
1455
    struct qemu_alarm_win32 *data = t->priv;
1456
    UINT flags;
1457

    
1458
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1459
    if (!data->host_alarm) {
1460
        perror("Failed CreateEvent");
1461
        return -1;
1462
    }
1463

    
1464
    memset(&tc, 0, sizeof(tc));
1465
    timeGetDevCaps(&tc, sizeof(tc));
1466

    
1467
    if (data->period < tc.wPeriodMin)
1468
        data->period = tc.wPeriodMin;
1469

    
1470
    timeBeginPeriod(data->period);
1471

    
1472
    flags = TIME_CALLBACK_FUNCTION;
1473
    if (alarm_has_dynticks(t))
1474
        flags |= TIME_ONESHOT;
1475
    else
1476
        flags |= TIME_PERIODIC;
1477

    
1478
    data->timerId = timeSetEvent(1,         // interval (ms)
1479
                        data->period,       // resolution
1480
                        host_alarm_handler, // function
1481
                        (DWORD)t,           // parameter
1482
                        flags);
1483

    
1484
    if (!data->timerId) {
1485
        perror("Failed to initialize win32 alarm timer");
1486

    
1487
        timeEndPeriod(data->period);
1488
        CloseHandle(data->host_alarm);
1489
        return -1;
1490
    }
1491

    
1492
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1493

    
1494
    return 0;
1495
}
1496

    
1497
static void win32_stop_timer(struct qemu_alarm_timer *t)
1498
{
1499
    struct qemu_alarm_win32 *data = t->priv;
1500

    
1501
    timeKillEvent(data->timerId);
1502
    timeEndPeriod(data->period);
1503

    
1504
    CloseHandle(data->host_alarm);
1505
}
1506

    
1507
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1508
{
1509
    struct qemu_alarm_win32 *data = t->priv;
1510
    uint64_t nearest_delta_us;
1511

    
1512
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1513
                !active_timers[QEMU_TIMER_VIRTUAL])
1514
        return;
1515

    
1516
    nearest_delta_us = qemu_next_deadline();
1517
    nearest_delta_us /= 1000;
1518

    
1519
    timeKillEvent(data->timerId);
1520

    
1521
    data->timerId = timeSetEvent(1,
1522
                        data->period,
1523
                        host_alarm_handler,
1524
                        (DWORD)t,
1525
                        TIME_ONESHOT | TIME_PERIODIC);
1526

    
1527
    if (!data->timerId) {
1528
        perror("Failed to re-arm win32 alarm timer");
1529

    
1530
        timeEndPeriod(data->period);
1531
        CloseHandle(data->host_alarm);
1532
        exit(1);
1533
    }
1534
}
1535

    
1536
#endif /* _WIN32 */
1537

    
1538
static void init_timer_alarm(void)
1539
{
1540
    struct qemu_alarm_timer *t;
1541
    int i, err = -1;
1542

    
1543
    for (i = 0; alarm_timers[i].name; i++) {
1544
        t = &alarm_timers[i];
1545

    
1546
        err = t->start(t);
1547
        if (!err)
1548
            break;
1549
    }
1550

    
1551
    if (err) {
1552
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1553
        fprintf(stderr, "Terminating\n");
1554
        exit(1);
1555
    }
1556

    
1557
    alarm_timer = t;
1558
}
1559

    
1560
static void quit_timers(void)
1561
{
1562
    alarm_timer->stop(alarm_timer);
1563
    alarm_timer = NULL;
1564
}
1565

    
1566
/***********************************************************/
1567
/* character device */
1568

    
1569
static void qemu_chr_event(CharDriverState *s, int event)
1570
{
1571
    if (!s->chr_event)
1572
        return;
1573
    s->chr_event(s->handler_opaque, event);
1574
}
1575

    
1576
static void qemu_chr_reset_bh(void *opaque)
1577
{
1578
    CharDriverState *s = opaque;
1579
    qemu_chr_event(s, CHR_EVENT_RESET);
1580
    qemu_bh_delete(s->bh);
1581
    s->bh = NULL;
1582
}
1583

    
1584
void qemu_chr_reset(CharDriverState *s)
1585
{
1586
    if (s->bh == NULL) {
1587
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1588
        qemu_bh_schedule(s->bh);
1589
    }
1590
}
1591

    
1592
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1593
{
1594
    return s->chr_write(s, buf, len);
1595
}
1596

    
1597
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1598
{
1599
    if (!s->chr_ioctl)
1600
        return -ENOTSUP;
1601
    return s->chr_ioctl(s, cmd, arg);
1602
}
1603

    
1604
int qemu_chr_can_read(CharDriverState *s)
1605
{
1606
    if (!s->chr_can_read)
1607
        return 0;
1608
    return s->chr_can_read(s->handler_opaque);
1609
}
1610

    
1611
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1612
{
1613
    s->chr_read(s->handler_opaque, buf, len);
1614
}
1615

    
1616
void qemu_chr_accept_input(CharDriverState *s)
1617
{
1618
    if (s->chr_accept_input)
1619
        s->chr_accept_input(s);
1620
}
1621

    
1622
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1623
{
1624
    char buf[4096];
1625
    va_list ap;
1626
    va_start(ap, fmt);
1627
    vsnprintf(buf, sizeof(buf), fmt, ap);
1628
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1629
    va_end(ap);
1630
}
1631

    
1632
void qemu_chr_send_event(CharDriverState *s, int event)
1633
{
1634
    if (s->chr_send_event)
1635
        s->chr_send_event(s, event);
1636
}
1637

    
1638
void qemu_chr_add_handlers(CharDriverState *s,
1639
                           IOCanRWHandler *fd_can_read,
1640
                           IOReadHandler *fd_read,
1641
                           IOEventHandler *fd_event,
1642
                           void *opaque)
1643
{
1644
    s->chr_can_read = fd_can_read;
1645
    s->chr_read = fd_read;
1646
    s->chr_event = fd_event;
1647
    s->handler_opaque = opaque;
1648
    if (s->chr_update_read_handler)
1649
        s->chr_update_read_handler(s);
1650
}
1651

    
1652
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1653
{
1654
    return len;
1655
}
1656

    
1657
static CharDriverState *qemu_chr_open_null(void)
1658
{
1659
    CharDriverState *chr;
1660

    
1661
    chr = qemu_mallocz(sizeof(CharDriverState));
1662
    if (!chr)
1663
        return NULL;
1664
    chr->chr_write = null_chr_write;
1665
    return chr;
1666
}
1667

    
1668
/* MUX driver for serial I/O splitting */
1669
static int term_timestamps;
1670
static int64_t term_timestamps_start;
1671
#define MAX_MUX 4
1672
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
1673
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1674
typedef struct {
1675
    IOCanRWHandler *chr_can_read[MAX_MUX];
1676
    IOReadHandler *chr_read[MAX_MUX];
1677
    IOEventHandler *chr_event[MAX_MUX];
1678
    void *ext_opaque[MAX_MUX];
1679
    CharDriverState *drv;
1680
    unsigned char buffer[MUX_BUFFER_SIZE];
1681
    int prod;
1682
    int cons;
1683
    int mux_cnt;
1684
    int term_got_escape;
1685
    int max_size;
1686
} MuxDriver;
1687

    
1688

    
1689
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1690
{
1691
    MuxDriver *d = chr->opaque;
1692
    int ret;
1693
    if (!term_timestamps) {
1694
        ret = d->drv->chr_write(d->drv, buf, len);
1695
    } else {
1696
        int i;
1697

    
1698
        ret = 0;
1699
        for(i = 0; i < len; i++) {
1700
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1701
            if (buf[i] == '\n') {
1702
                char buf1[64];
1703
                int64_t ti;
1704
                int secs;
1705

    
1706
                ti = get_clock();
1707
                if (term_timestamps_start == -1)
1708
                    term_timestamps_start = ti;
1709
                ti -= term_timestamps_start;
1710
                secs = ti / 1000000000;
1711
                snprintf(buf1, sizeof(buf1),
1712
                         "[%02d:%02d:%02d.%03d] ",
1713
                         secs / 3600,
1714
                         (secs / 60) % 60,
1715
                         secs % 60,
1716
                         (int)((ti / 1000000) % 1000));
1717
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1718
            }
1719
        }
1720
    }
1721
    return ret;
1722
}
1723

    
1724
static char *mux_help[] = {
1725
    "% h    print this help\n\r",
1726
    "% x    exit emulator\n\r",
1727
    "% s    save disk data back to file (if -snapshot)\n\r",
1728
    "% t    toggle console timestamps\n\r"
1729
    "% b    send break (magic sysrq)\n\r",
1730
    "% c    switch between console and monitor\n\r",
1731
    "% %  sends %\n\r",
1732
    NULL
1733
};
1734

    
1735
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1736
static void mux_print_help(CharDriverState *chr)
1737
{
1738
    int i, j;
1739
    char ebuf[15] = "Escape-Char";
1740
    char cbuf[50] = "\n\r";
1741

    
1742
    if (term_escape_char > 0 && term_escape_char < 26) {
1743
        sprintf(cbuf,"\n\r");
1744
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1745
    } else {
1746
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1747
            term_escape_char);
1748
    }
1749
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1750
    for (i = 0; mux_help[i] != NULL; i++) {
1751
        for (j=0; mux_help[i][j] != '\0'; j++) {
1752
            if (mux_help[i][j] == '%')
1753
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1754
            else
1755
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1756
        }
1757
    }
1758
}
1759

    
1760
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1761
{
1762
    if (d->term_got_escape) {
1763
        d->term_got_escape = 0;
1764
        if (ch == term_escape_char)
1765
            goto send_char;
1766
        switch(ch) {
1767
        case '?':
1768
        case 'h':
1769
            mux_print_help(chr);
1770
            break;
1771
        case 'x':
1772
            {
1773
                 char *term =  "QEMU: Terminated\n\r";
1774
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1775
                 exit(0);
1776
                 break;
1777
            }
1778
        case 's':
1779
            {
1780
                int i;
1781
                for (i = 0; i < nb_drives; i++) {
1782
                        bdrv_commit(drives_table[i].bdrv);
1783
                }
1784
            }
1785
            break;
1786
        case 'b':
1787
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1788
            break;
1789
        case 'c':
1790
            /* Switch to the next registered device */
1791
            chr->focus++;
1792
            if (chr->focus >= d->mux_cnt)
1793
                chr->focus = 0;
1794
            break;
1795
       case 't':
1796
           term_timestamps = !term_timestamps;
1797
           term_timestamps_start = -1;
1798
           break;
1799
        }
1800
    } else if (ch == term_escape_char) {
1801
        d->term_got_escape = 1;
1802
    } else {
1803
    send_char:
1804
        return 1;
1805
    }
1806
    return 0;
1807
}
1808

    
1809
static void mux_chr_accept_input(CharDriverState *chr)
1810
{
1811
    int m = chr->focus;
1812
    MuxDriver *d = chr->opaque;
1813

    
1814
    while (d->prod != d->cons &&
1815
           d->chr_can_read[m] &&
1816
           d->chr_can_read[m](d->ext_opaque[m])) {
1817
        d->chr_read[m](d->ext_opaque[m],
1818
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1819
    }
1820
}
1821

    
1822
static int mux_chr_can_read(void *opaque)
1823
{
1824
    CharDriverState *chr = opaque;
1825
    MuxDriver *d = chr->opaque;
1826

    
1827
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1828
        return 1;
1829
    if (d->chr_can_read[chr->focus])
1830
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1831
    return 0;
1832
}
1833

    
1834
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1835
{
1836
    CharDriverState *chr = opaque;
1837
    MuxDriver *d = chr->opaque;
1838
    int m = chr->focus;
1839
    int i;
1840

    
1841
    mux_chr_accept_input (opaque);
1842

    
1843
    for(i = 0; i < size; i++)
1844
        if (mux_proc_byte(chr, d, buf[i])) {
1845
            if (d->prod == d->cons &&
1846
                d->chr_can_read[m] &&
1847
                d->chr_can_read[m](d->ext_opaque[m]))
1848
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1849
            else
1850
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1851
        }
1852
}
1853

    
1854
static void mux_chr_event(void *opaque, int event)
1855
{
1856
    CharDriverState *chr = opaque;
1857
    MuxDriver *d = chr->opaque;
1858
    int i;
1859

    
1860
    /* Send the event to all registered listeners */
1861
    for (i = 0; i < d->mux_cnt; i++)
1862
        if (d->chr_event[i])
1863
            d->chr_event[i](d->ext_opaque[i], event);
1864
}
1865

    
1866
static void mux_chr_update_read_handler(CharDriverState *chr)
1867
{
1868
    MuxDriver *d = chr->opaque;
1869

    
1870
    if (d->mux_cnt >= MAX_MUX) {
1871
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1872
        return;
1873
    }
1874
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1875
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1876
    d->chr_read[d->mux_cnt] = chr->chr_read;
1877
    d->chr_event[d->mux_cnt] = chr->chr_event;
1878
    /* Fix up the real driver with mux routines */
1879
    if (d->mux_cnt == 0) {
1880
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1881
                              mux_chr_event, chr);
1882
    }
1883
    chr->focus = d->mux_cnt;
1884
    d->mux_cnt++;
1885
}
1886

    
1887
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1888
{
1889
    CharDriverState *chr;
1890
    MuxDriver *d;
1891

    
1892
    chr = qemu_mallocz(sizeof(CharDriverState));
1893
    if (!chr)
1894
        return NULL;
1895
    d = qemu_mallocz(sizeof(MuxDriver));
1896
    if (!d) {
1897
        free(chr);
1898
        return NULL;
1899
    }
1900

    
1901
    chr->opaque = d;
1902
    d->drv = drv;
1903
    chr->focus = -1;
1904
    chr->chr_write = mux_chr_write;
1905
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1906
    chr->chr_accept_input = mux_chr_accept_input;
1907
    return chr;
1908
}
1909

    
1910

    
1911
#ifdef _WIN32
1912

    
1913
static void socket_cleanup(void)
1914
{
1915
    WSACleanup();
1916
}
1917

    
1918
static int socket_init(void)
1919
{
1920
    WSADATA Data;
1921
    int ret, err;
1922

    
1923
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1924
    if (ret != 0) {
1925
        err = WSAGetLastError();
1926
        fprintf(stderr, "WSAStartup: %d\n", err);
1927
        return -1;
1928
    }
1929
    atexit(socket_cleanup);
1930
    return 0;
1931
}
1932

    
1933
static int send_all(int fd, const uint8_t *buf, int len1)
1934
{
1935
    int ret, len;
1936

    
1937
    len = len1;
1938
    while (len > 0) {
1939
        ret = send(fd, buf, len, 0);
1940
        if (ret < 0) {
1941
            int errno;
1942
            errno = WSAGetLastError();
1943
            if (errno != WSAEWOULDBLOCK) {
1944
                return -1;
1945
            }
1946
        } else if (ret == 0) {
1947
            break;
1948
        } else {
1949
            buf += ret;
1950
            len -= ret;
1951
        }
1952
    }
1953
    return len1 - len;
1954
}
1955

    
1956
void socket_set_nonblock(int fd)
1957
{
1958
    unsigned long opt = 1;
1959
    ioctlsocket(fd, FIONBIO, &opt);
1960
}
1961

    
1962
#else
1963

    
1964
static int unix_write(int fd, const uint8_t *buf, int len1)
1965
{
1966
    int ret, len;
1967

    
1968
    len = len1;
1969
    while (len > 0) {
1970
        ret = write(fd, buf, len);
1971
        if (ret < 0) {
1972
            if (errno != EINTR && errno != EAGAIN)
1973
                return -1;
1974
        } else if (ret == 0) {
1975
            break;
1976
        } else {
1977
            buf += ret;
1978
            len -= ret;
1979
        }
1980
    }
1981
    return len1 - len;
1982
}
1983

    
1984
static inline int send_all(int fd, const uint8_t *buf, int len1)
1985
{
1986
    return unix_write(fd, buf, len1);
1987
}
1988

    
1989
void socket_set_nonblock(int fd)
1990
{
1991
    fcntl(fd, F_SETFL, O_NONBLOCK);
1992
}
1993
#endif /* !_WIN32 */
1994

    
1995
#ifndef _WIN32
1996

    
1997
typedef struct {
1998
    int fd_in, fd_out;
1999
    int max_size;
2000
} FDCharDriver;
2001

    
2002
#define STDIO_MAX_CLIENTS 1
2003
static int stdio_nb_clients = 0;
2004

    
2005
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2006
{
2007
    FDCharDriver *s = chr->opaque;
2008
    return unix_write(s->fd_out, buf, len);
2009
}
2010

    
2011
static int fd_chr_read_poll(void *opaque)
2012
{
2013
    CharDriverState *chr = opaque;
2014
    FDCharDriver *s = chr->opaque;
2015

    
2016
    s->max_size = qemu_chr_can_read(chr);
2017
    return s->max_size;
2018
}
2019

    
2020
static void fd_chr_read(void *opaque)
2021
{
2022
    CharDriverState *chr = opaque;
2023
    FDCharDriver *s = chr->opaque;
2024
    int size, len;
2025
    uint8_t buf[1024];
2026

    
2027
    len = sizeof(buf);
2028
    if (len > s->max_size)
2029
        len = s->max_size;
2030
    if (len == 0)
2031
        return;
2032
    size = read(s->fd_in, buf, len);
2033
    if (size == 0) {
2034
        /* FD has been closed. Remove it from the active list.  */
2035
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2036
        return;
2037
    }
2038
    if (size > 0) {
2039
        qemu_chr_read(chr, buf, size);
2040
    }
2041
}
2042

    
2043
static void fd_chr_update_read_handler(CharDriverState *chr)
2044
{
2045
    FDCharDriver *s = chr->opaque;
2046

    
2047
    if (s->fd_in >= 0) {
2048
        if (nographic && s->fd_in == 0) {
2049
        } else {
2050
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2051
                                 fd_chr_read, NULL, chr);
2052
        }
2053
    }
2054
}
2055

    
2056
static void fd_chr_close(struct CharDriverState *chr)
2057
{
2058
    FDCharDriver *s = chr->opaque;
2059

    
2060
    if (s->fd_in >= 0) {
2061
        if (nographic && s->fd_in == 0) {
2062
        } else {
2063
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2064
        }
2065
    }
2066

    
2067
    qemu_free(s);
2068
}
2069

    
2070
/* open a character device to a unix fd */
2071
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2072
{
2073
    CharDriverState *chr;
2074
    FDCharDriver *s;
2075

    
2076
    chr = qemu_mallocz(sizeof(CharDriverState));
2077
    if (!chr)
2078
        return NULL;
2079
    s = qemu_mallocz(sizeof(FDCharDriver));
2080
    if (!s) {
2081
        free(chr);
2082
        return NULL;
2083
    }
2084
    s->fd_in = fd_in;
2085
    s->fd_out = fd_out;
2086
    chr->opaque = s;
2087
    chr->chr_write = fd_chr_write;
2088
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2089
    chr->chr_close = fd_chr_close;
2090

    
2091
    qemu_chr_reset(chr);
2092

    
2093
    return chr;
2094
}
2095

    
2096
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2097
{
2098
    int fd_out;
2099

    
2100
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2101
    if (fd_out < 0)
2102
        return NULL;
2103
    return qemu_chr_open_fd(-1, fd_out);
2104
}
2105

    
2106
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2107
{
2108
    int fd_in, fd_out;
2109
    char filename_in[256], filename_out[256];
2110

    
2111
    snprintf(filename_in, 256, "%s.in", filename);
2112
    snprintf(filename_out, 256, "%s.out", filename);
2113
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2114
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2115
    if (fd_in < 0 || fd_out < 0) {
2116
        if (fd_in >= 0)
2117
            close(fd_in);
2118
        if (fd_out >= 0)
2119
            close(fd_out);
2120
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2121
        if (fd_in < 0)
2122
            return NULL;
2123
    }
2124
    return qemu_chr_open_fd(fd_in, fd_out);
2125
}
2126

    
2127

    
2128
/* for STDIO, we handle the case where several clients use it
2129
   (nographic mode) */
2130

    
2131
#define TERM_FIFO_MAX_SIZE 1
2132

    
2133
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2134
static int term_fifo_size;
2135

    
2136
static int stdio_read_poll(void *opaque)
2137
{
2138
    CharDriverState *chr = opaque;
2139

    
2140
    /* try to flush the queue if needed */
2141
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2142
        qemu_chr_read(chr, term_fifo, 1);
2143
        term_fifo_size = 0;
2144
    }
2145
    /* see if we can absorb more chars */
2146
    if (term_fifo_size == 0)
2147
        return 1;
2148
    else
2149
        return 0;
2150
}
2151

    
2152
static void stdio_read(void *opaque)
2153
{
2154
    int size;
2155
    uint8_t buf[1];
2156
    CharDriverState *chr = opaque;
2157

    
2158
    size = read(0, buf, 1);
2159
    if (size == 0) {
2160
        /* stdin has been closed. Remove it from the active list.  */
2161
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2162
        return;
2163
    }
2164
    if (size > 0) {
2165
        if (qemu_chr_can_read(chr) > 0) {
2166
            qemu_chr_read(chr, buf, 1);
2167
        } else if (term_fifo_size == 0) {
2168
            term_fifo[term_fifo_size++] = buf[0];
2169
        }
2170
    }
2171
}
2172

    
2173
/* init terminal so that we can grab keys */
2174
static struct termios oldtty;
2175
static int old_fd0_flags;
2176
static int term_atexit_done;
2177

    
2178
static void term_exit(void)
2179
{
2180
    tcsetattr (0, TCSANOW, &oldtty);
2181
    fcntl(0, F_SETFL, old_fd0_flags);
2182
}
2183

    
2184
static void term_init(void)
2185
{
2186
    struct termios tty;
2187

    
2188
    tcgetattr (0, &tty);
2189
    oldtty = tty;
2190
    old_fd0_flags = fcntl(0, F_GETFL);
2191

    
2192
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2193
                          |INLCR|IGNCR|ICRNL|IXON);
2194
    tty.c_oflag |= OPOST;
2195
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2196
    /* if graphical mode, we allow Ctrl-C handling */
2197
    if (nographic)
2198
        tty.c_lflag &= ~ISIG;
2199
    tty.c_cflag &= ~(CSIZE|PARENB);
2200
    tty.c_cflag |= CS8;
2201
    tty.c_cc[VMIN] = 1;
2202
    tty.c_cc[VTIME] = 0;
2203

    
2204
    tcsetattr (0, TCSANOW, &tty);
2205

    
2206
    if (!term_atexit_done++)
2207
        atexit(term_exit);
2208

    
2209
    fcntl(0, F_SETFL, O_NONBLOCK);
2210
}
2211

    
2212
static void qemu_chr_close_stdio(struct CharDriverState *chr)
2213
{
2214
    term_exit();
2215
    stdio_nb_clients--;
2216
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2217
    fd_chr_close(chr);
2218
}
2219

    
2220
static CharDriverState *qemu_chr_open_stdio(void)
2221
{
2222
    CharDriverState *chr;
2223

    
2224
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2225
        return NULL;
2226
    chr = qemu_chr_open_fd(0, 1);
2227
    chr->chr_close = qemu_chr_close_stdio;
2228
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2229
    stdio_nb_clients++;
2230
    term_init();
2231

    
2232
    return chr;
2233
}
2234

    
2235
#if defined(__linux__) || defined(__sun__)
2236
static CharDriverState *qemu_chr_open_pty(void)
2237
{
2238
    struct termios tty;
2239
    char slave_name[1024];
2240
    int master_fd, slave_fd;
2241

    
2242
#if defined(__linux__)
2243
    /* Not satisfying */
2244
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2245
        return NULL;
2246
    }
2247
#endif
2248

    
2249
    /* Disabling local echo and line-buffered output */
2250
    tcgetattr (master_fd, &tty);
2251
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2252
    tty.c_cc[VMIN] = 1;
2253
    tty.c_cc[VTIME] = 0;
2254
    tcsetattr (master_fd, TCSAFLUSH, &tty);
2255

    
2256
    fprintf(stderr, "char device redirected to %s\n", slave_name);
2257
    return qemu_chr_open_fd(master_fd, master_fd);
2258
}
2259

    
2260
static void tty_serial_init(int fd, int speed,
2261
                            int parity, int data_bits, int stop_bits)
2262
{
2263
    struct termios tty;
2264
    speed_t spd;
2265

    
2266
#if 0
2267
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2268
           speed, parity, data_bits, stop_bits);
2269
#endif
2270
    tcgetattr (fd, &tty);
2271

    
2272
#define MARGIN 1.1
2273
    if (speed <= 50 * MARGIN)
2274
        spd = B50;
2275
    else if (speed <= 75 * MARGIN)
2276
        spd = B75;
2277
    else if (speed <= 300 * MARGIN)
2278
        spd = B300;
2279
    else if (speed <= 600 * MARGIN)
2280
        spd = B600;
2281
    else if (speed <= 1200 * MARGIN)
2282
        spd = B1200;
2283
    else if (speed <= 2400 * MARGIN)
2284
        spd = B2400;
2285
    else if (speed <= 4800 * MARGIN)
2286
        spd = B4800;
2287
    else if (speed <= 9600 * MARGIN)
2288
        spd = B9600;
2289
    else if (speed <= 19200 * MARGIN)
2290
        spd = B19200;
2291
    else if (speed <= 38400 * MARGIN)
2292
        spd = B38400;
2293
    else if (speed <= 57600 * MARGIN)
2294
        spd = B57600;
2295
    else if (speed <= 115200 * MARGIN)
2296
        spd = B115200;
2297
    else
2298
        spd = B115200;
2299

    
2300
    cfsetispeed(&tty, spd);
2301
    cfsetospeed(&tty, spd);
2302

    
2303
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2304
                          |INLCR|IGNCR|ICRNL|IXON);
2305
    tty.c_oflag |= OPOST;
2306
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2307
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2308
    switch(data_bits) {
2309
    default:
2310
    case 8:
2311
        tty.c_cflag |= CS8;
2312
        break;
2313
    case 7:
2314
        tty.c_cflag |= CS7;
2315
        break;
2316
    case 6:
2317
        tty.c_cflag |= CS6;
2318
        break;
2319
    case 5:
2320
        tty.c_cflag |= CS5;
2321
        break;
2322
    }
2323
    switch(parity) {
2324
    default:
2325
    case 'N':
2326
        break;
2327
    case 'E':
2328
        tty.c_cflag |= PARENB;
2329
        break;
2330
    case 'O':
2331
        tty.c_cflag |= PARENB | PARODD;
2332
        break;
2333
    }
2334
    if (stop_bits == 2)
2335
        tty.c_cflag |= CSTOPB;
2336

    
2337
    tcsetattr (fd, TCSANOW, &tty);
2338
}
2339

    
2340
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2341
{
2342
    FDCharDriver *s = chr->opaque;
2343

    
2344
    switch(cmd) {
2345
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2346
        {
2347
            QEMUSerialSetParams *ssp = arg;
2348
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2349
                            ssp->data_bits, ssp->stop_bits);
2350
        }
2351
        break;
2352
    case CHR_IOCTL_SERIAL_SET_BREAK:
2353
        {
2354
            int enable = *(int *)arg;
2355
            if (enable)
2356
                tcsendbreak(s->fd_in, 1);
2357
        }
2358
        break;
2359
    default:
2360
        return -ENOTSUP;
2361
    }
2362
    return 0;
2363
}
2364

    
2365
static CharDriverState *qemu_chr_open_tty(const char *filename)
2366
{
2367
    CharDriverState *chr;
2368
    int fd;
2369

    
2370
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2371
    fcntl(fd, F_SETFL, O_NONBLOCK);
2372
    tty_serial_init(fd, 115200, 'N', 8, 1);
2373
    chr = qemu_chr_open_fd(fd, fd);
2374
    if (!chr) {
2375
        close(fd);
2376
        return NULL;
2377
    }
2378
    chr->chr_ioctl = tty_serial_ioctl;
2379
    qemu_chr_reset(chr);
2380
    return chr;
2381
}
2382
#else  /* ! __linux__ && ! __sun__ */
2383
static CharDriverState *qemu_chr_open_pty(void)
2384
{
2385
    return NULL;
2386
}
2387
#endif /* __linux__ || __sun__ */
2388

    
2389
#if defined(__linux__)
2390
typedef struct {
2391
    int fd;
2392
    int mode;
2393
} ParallelCharDriver;
2394

    
2395
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2396
{
2397
    if (s->mode != mode) {
2398
        int m = mode;
2399
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2400
            return 0;
2401
        s->mode = mode;
2402
    }
2403
    return 1;
2404
}
2405

    
2406
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2407
{
2408
    ParallelCharDriver *drv = chr->opaque;
2409
    int fd = drv->fd;
2410
    uint8_t b;
2411

    
2412
    switch(cmd) {
2413
    case CHR_IOCTL_PP_READ_DATA:
2414
        if (ioctl(fd, PPRDATA, &b) < 0)
2415
            return -ENOTSUP;
2416
        *(uint8_t *)arg = b;
2417
        break;
2418
    case CHR_IOCTL_PP_WRITE_DATA:
2419
        b = *(uint8_t *)arg;
2420
        if (ioctl(fd, PPWDATA, &b) < 0)
2421
            return -ENOTSUP;
2422
        break;
2423
    case CHR_IOCTL_PP_READ_CONTROL:
2424
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2425
            return -ENOTSUP;
2426
        /* Linux gives only the lowest bits, and no way to know data
2427
           direction! For better compatibility set the fixed upper
2428
           bits. */
2429
        *(uint8_t *)arg = b | 0xc0;
2430
        break;
2431
    case CHR_IOCTL_PP_WRITE_CONTROL:
2432
        b = *(uint8_t *)arg;
2433
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2434
            return -ENOTSUP;
2435
        break;
2436
    case CHR_IOCTL_PP_READ_STATUS:
2437
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2438
            return -ENOTSUP;
2439
        *(uint8_t *)arg = b;
2440
        break;
2441
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2442
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2443
            struct ParallelIOArg *parg = arg;
2444
            int n = read(fd, parg->buffer, parg->count);
2445
            if (n != parg->count) {
2446
                return -EIO;
2447
            }
2448
        }
2449
        break;
2450
    case CHR_IOCTL_PP_EPP_READ:
2451
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2452
            struct ParallelIOArg *parg = arg;
2453
            int n = read(fd, parg->buffer, parg->count);
2454
            if (n != parg->count) {
2455
                return -EIO;
2456
            }
2457
        }
2458
        break;
2459
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2460
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2461
            struct ParallelIOArg *parg = arg;
2462
            int n = write(fd, parg->buffer, parg->count);
2463
            if (n != parg->count) {
2464
                return -EIO;
2465
            }
2466
        }
2467
        break;
2468
    case CHR_IOCTL_PP_EPP_WRITE:
2469
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2470
            struct ParallelIOArg *parg = arg;
2471
            int n = write(fd, parg->buffer, parg->count);
2472
            if (n != parg->count) {
2473
                return -EIO;
2474
            }
2475
        }
2476
        break;
2477
    default:
2478
        return -ENOTSUP;
2479
    }
2480
    return 0;
2481
}
2482

    
2483
static void pp_close(CharDriverState *chr)
2484
{
2485
    ParallelCharDriver *drv = chr->opaque;
2486
    int fd = drv->fd;
2487

    
2488
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2489
    ioctl(fd, PPRELEASE);
2490
    close(fd);
2491
    qemu_free(drv);
2492
}
2493

    
2494
static CharDriverState *qemu_chr_open_pp(const char *filename)
2495
{
2496
    CharDriverState *chr;
2497
    ParallelCharDriver *drv;
2498
    int fd;
2499

    
2500
    TFR(fd = open(filename, O_RDWR));
2501
    if (fd < 0)
2502
        return NULL;
2503

    
2504
    if (ioctl(fd, PPCLAIM) < 0) {
2505
        close(fd);
2506
        return NULL;
2507
    }
2508

    
2509
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2510
    if (!drv) {
2511
        close(fd);
2512
        return NULL;
2513
    }
2514
    drv->fd = fd;
2515
    drv->mode = IEEE1284_MODE_COMPAT;
2516

    
2517
    chr = qemu_mallocz(sizeof(CharDriverState));
2518
    if (!chr) {
2519
        qemu_free(drv);
2520
        close(fd);
2521
        return NULL;
2522
    }
2523
    chr->chr_write = null_chr_write;
2524
    chr->chr_ioctl = pp_ioctl;
2525
    chr->chr_close = pp_close;
2526
    chr->opaque = drv;
2527

    
2528
    qemu_chr_reset(chr);
2529

    
2530
    return chr;
2531
}
2532
#endif /* __linux__ */
2533

    
2534
#else /* _WIN32 */
2535

    
2536
typedef struct {
2537
    int max_size;
2538
    HANDLE hcom, hrecv, hsend;
2539
    OVERLAPPED orecv, osend;
2540
    BOOL fpipe;
2541
    DWORD len;
2542
} WinCharState;
2543

    
2544
#define NSENDBUF 2048
2545
#define NRECVBUF 2048
2546
#define MAXCONNECT 1
2547
#define NTIMEOUT 5000
2548

    
2549
static int win_chr_poll(void *opaque);
2550
static int win_chr_pipe_poll(void *opaque);
2551

    
2552
static void win_chr_close(CharDriverState *chr)
2553
{
2554
    WinCharState *s = chr->opaque;
2555

    
2556
    if (s->hsend) {
2557
        CloseHandle(s->hsend);
2558
        s->hsend = NULL;
2559
    }
2560
    if (s->hrecv) {
2561
        CloseHandle(s->hrecv);
2562
        s->hrecv = NULL;
2563
    }
2564
    if (s->hcom) {
2565
        CloseHandle(s->hcom);
2566
        s->hcom = NULL;
2567
    }
2568
    if (s->fpipe)
2569
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2570
    else
2571
        qemu_del_polling_cb(win_chr_poll, chr);
2572
}
2573

    
2574
static int win_chr_init(CharDriverState *chr, const char *filename)
2575
{
2576
    WinCharState *s = chr->opaque;
2577
    COMMCONFIG comcfg;
2578
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2579
    COMSTAT comstat;
2580
    DWORD size;
2581
    DWORD err;
2582

    
2583
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2584
    if (!s->hsend) {
2585
        fprintf(stderr, "Failed CreateEvent\n");
2586
        goto fail;
2587
    }
2588
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2589
    if (!s->hrecv) {
2590
        fprintf(stderr, "Failed CreateEvent\n");
2591
        goto fail;
2592
    }
2593

    
2594
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2595
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2596
    if (s->hcom == INVALID_HANDLE_VALUE) {
2597
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2598
        s->hcom = NULL;
2599
        goto fail;
2600
    }
2601

    
2602
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2603
        fprintf(stderr, "Failed SetupComm\n");
2604
        goto fail;
2605
    }
2606

    
2607
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2608
    size = sizeof(COMMCONFIG);
2609
    GetDefaultCommConfig(filename, &comcfg, &size);
2610
    comcfg.dcb.DCBlength = sizeof(DCB);
2611
    CommConfigDialog(filename, NULL, &comcfg);
2612

    
2613
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2614
        fprintf(stderr, "Failed SetCommState\n");
2615
        goto fail;
2616
    }
2617

    
2618
    if (!SetCommMask(s->hcom, EV_ERR)) {
2619
        fprintf(stderr, "Failed SetCommMask\n");
2620
        goto fail;
2621
    }
2622

    
2623
    cto.ReadIntervalTimeout = MAXDWORD;
2624
    if (!SetCommTimeouts(s->hcom, &cto)) {
2625
        fprintf(stderr, "Failed SetCommTimeouts\n");
2626
        goto fail;
2627
    }
2628

    
2629
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2630
        fprintf(stderr, "Failed ClearCommError\n");
2631
        goto fail;
2632
    }
2633
    qemu_add_polling_cb(win_chr_poll, chr);
2634
    return 0;
2635

    
2636
 fail:
2637
    win_chr_close(chr);
2638
    return -1;
2639
}
2640

    
2641
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2642
{
2643
    WinCharState *s = chr->opaque;
2644
    DWORD len, ret, size, err;
2645

    
2646
    len = len1;
2647
    ZeroMemory(&s->osend, sizeof(s->osend));
2648
    s->osend.hEvent = s->hsend;
2649
    while (len > 0) {
2650
        if (s->hsend)
2651
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2652
        else
2653
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2654
        if (!ret) {
2655
            err = GetLastError();
2656
            if (err == ERROR_IO_PENDING) {
2657
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2658
                if (ret) {
2659
                    buf += size;
2660
                    len -= size;
2661
                } else {
2662
                    break;
2663
                }
2664
            } else {
2665
                break;
2666
            }
2667
        } else {
2668
            buf += size;
2669
            len -= size;
2670
        }
2671
    }
2672
    return len1 - len;
2673
}
2674

    
2675
static int win_chr_read_poll(CharDriverState *chr)
2676
{
2677
    WinCharState *s = chr->opaque;
2678

    
2679
    s->max_size = qemu_chr_can_read(chr);
2680
    return s->max_size;
2681
}
2682

    
2683
static void win_chr_readfile(CharDriverState *chr)
2684
{
2685
    WinCharState *s = chr->opaque;
2686
    int ret, err;
2687
    uint8_t buf[1024];
2688
    DWORD size;
2689

    
2690
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2691
    s->orecv.hEvent = s->hrecv;
2692
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2693
    if (!ret) {
2694
        err = GetLastError();
2695
        if (err == ERROR_IO_PENDING) {
2696
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2697
        }
2698
    }
2699

    
2700
    if (size > 0) {
2701
        qemu_chr_read(chr, buf, size);
2702
    }
2703
}
2704

    
2705
static void win_chr_read(CharDriverState *chr)
2706
{
2707
    WinCharState *s = chr->opaque;
2708

    
2709
    if (s->len > s->max_size)
2710
        s->len = s->max_size;
2711
    if (s->len == 0)
2712
        return;
2713

    
2714
    win_chr_readfile(chr);
2715
}
2716

    
2717
static int win_chr_poll(void *opaque)
2718
{
2719
    CharDriverState *chr = opaque;
2720
    WinCharState *s = chr->opaque;
2721
    COMSTAT status;
2722
    DWORD comerr;
2723

    
2724
    ClearCommError(s->hcom, &comerr, &status);
2725
    if (status.cbInQue > 0) {
2726
        s->len = status.cbInQue;
2727
        win_chr_read_poll(chr);
2728
        win_chr_read(chr);
2729
        return 1;
2730
    }
2731
    return 0;
2732
}
2733

    
2734
static CharDriverState *qemu_chr_open_win(const char *filename)
2735
{
2736
    CharDriverState *chr;
2737
    WinCharState *s;
2738

    
2739
    chr = qemu_mallocz(sizeof(CharDriverState));
2740
    if (!chr)
2741
        return NULL;
2742
    s = qemu_mallocz(sizeof(WinCharState));
2743
    if (!s) {
2744
        free(chr);
2745
        return NULL;
2746
    }
2747
    chr->opaque = s;
2748
    chr->chr_write = win_chr_write;
2749
    chr->chr_close = win_chr_close;
2750

    
2751
    if (win_chr_init(chr, filename) < 0) {
2752
        free(s);
2753
        free(chr);
2754
        return NULL;
2755
    }
2756
    qemu_chr_reset(chr);
2757
    return chr;
2758
}
2759

    
2760
static int win_chr_pipe_poll(void *opaque)
2761
{
2762
    CharDriverState *chr = opaque;
2763
    WinCharState *s = chr->opaque;
2764
    DWORD size;
2765

    
2766
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2767
    if (size > 0) {
2768
        s->len = size;
2769
        win_chr_read_poll(chr);
2770
        win_chr_read(chr);
2771
        return 1;
2772
    }
2773
    return 0;
2774
}
2775

    
2776
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2777
{
2778
    WinCharState *s = chr->opaque;
2779
    OVERLAPPED ov;
2780
    int ret;
2781
    DWORD size;
2782
    char openname[256];
2783

    
2784
    s->fpipe = TRUE;
2785

    
2786
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2787
    if (!s->hsend) {
2788
        fprintf(stderr, "Failed CreateEvent\n");
2789
        goto fail;
2790
    }
2791
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2792
    if (!s->hrecv) {
2793
        fprintf(stderr, "Failed CreateEvent\n");
2794
        goto fail;
2795
    }
2796

    
2797
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2798
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2799
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2800
                              PIPE_WAIT,
2801
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2802
    if (s->hcom == INVALID_HANDLE_VALUE) {
2803
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2804
        s->hcom = NULL;
2805
        goto fail;
2806
    }
2807

    
2808
    ZeroMemory(&ov, sizeof(ov));
2809
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2810
    ret = ConnectNamedPipe(s->hcom, &ov);
2811
    if (ret) {
2812
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2813
        goto fail;
2814
    }
2815

    
2816
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2817
    if (!ret) {
2818
        fprintf(stderr, "Failed GetOverlappedResult\n");
2819
        if (ov.hEvent) {
2820
            CloseHandle(ov.hEvent);
2821
            ov.hEvent = NULL;
2822
        }
2823
        goto fail;
2824
    }
2825

    
2826
    if (ov.hEvent) {
2827
        CloseHandle(ov.hEvent);
2828
        ov.hEvent = NULL;
2829
    }
2830
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2831
    return 0;
2832

    
2833
 fail:
2834
    win_chr_close(chr);
2835
    return -1;
2836
}
2837

    
2838

    
2839
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2840
{
2841
    CharDriverState *chr;
2842
    WinCharState *s;
2843

    
2844
    chr = qemu_mallocz(sizeof(CharDriverState));
2845
    if (!chr)
2846
        return NULL;
2847
    s = qemu_mallocz(sizeof(WinCharState));
2848
    if (!s) {
2849
        free(chr);
2850
        return NULL;
2851
    }
2852
    chr->opaque = s;
2853
    chr->chr_write = win_chr_write;
2854
    chr->chr_close = win_chr_close;
2855

    
2856
    if (win_chr_pipe_init(chr, filename) < 0) {
2857
        free(s);
2858
        free(chr);
2859
        return NULL;
2860
    }
2861
    qemu_chr_reset(chr);
2862
    return chr;
2863
}
2864

    
2865
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2866
{
2867
    CharDriverState *chr;
2868
    WinCharState *s;
2869

    
2870
    chr = qemu_mallocz(sizeof(CharDriverState));
2871
    if (!chr)
2872
        return NULL;
2873
    s = qemu_mallocz(sizeof(WinCharState));
2874
    if (!s) {
2875
        free(chr);
2876
        return NULL;
2877
    }
2878
    s->hcom = fd_out;
2879
    chr->opaque = s;
2880
    chr->chr_write = win_chr_write;
2881
    qemu_chr_reset(chr);
2882
    return chr;
2883
}
2884

    
2885
static CharDriverState *qemu_chr_open_win_con(const char *filename)
2886
{
2887
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2888
}
2889

    
2890
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2891
{
2892
    HANDLE fd_out;
2893

    
2894
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2895
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2896
    if (fd_out == INVALID_HANDLE_VALUE)
2897
        return NULL;
2898

    
2899
    return qemu_chr_open_win_file(fd_out);
2900
}
2901
#endif /* !_WIN32 */
2902

    
2903
/***********************************************************/
2904
/* UDP Net console */
2905

    
2906
typedef struct {
2907
    int fd;
2908
    struct sockaddr_in daddr;
2909
    uint8_t buf[1024];
2910
    int bufcnt;
2911
    int bufptr;
2912
    int max_size;
2913
} NetCharDriver;
2914

    
2915
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2916
{
2917
    NetCharDriver *s = chr->opaque;
2918

    
2919
    return sendto(s->fd, buf, len, 0,
2920
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2921
}
2922

    
2923
static int udp_chr_read_poll(void *opaque)
2924
{
2925
    CharDriverState *chr = opaque;
2926
    NetCharDriver *s = chr->opaque;
2927

    
2928
    s->max_size = qemu_chr_can_read(chr);
2929

    
2930
    /* If there were any stray characters in the queue process them
2931
     * first
2932
     */
2933
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2934
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2935
        s->bufptr++;
2936
        s->max_size = qemu_chr_can_read(chr);
2937
    }
2938
    return s->max_size;
2939
}
2940

    
2941
static void udp_chr_read(void *opaque)
2942
{
2943
    CharDriverState *chr = opaque;
2944
    NetCharDriver *s = chr->opaque;
2945

    
2946
    if (s->max_size == 0)
2947
        return;
2948
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2949
    s->bufptr = s->bufcnt;
2950
    if (s->bufcnt <= 0)
2951
        return;
2952

    
2953
    s->bufptr = 0;
2954
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2955
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2956
        s->bufptr++;
2957
        s->max_size = qemu_chr_can_read(chr);
2958
    }
2959
}
2960

    
2961
static void udp_chr_update_read_handler(CharDriverState *chr)
2962
{
2963
    NetCharDriver *s = chr->opaque;
2964

    
2965
    if (s->fd >= 0) {
2966
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2967
                             udp_chr_read, NULL, chr);
2968
    }
2969
}
2970

    
2971
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2972
#ifndef _WIN32
2973
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2974
#endif
2975
int parse_host_src_port(struct sockaddr_in *haddr,
2976
                        struct sockaddr_in *saddr,
2977
                        const char *str);
2978

    
2979
static CharDriverState *qemu_chr_open_udp(const char *def)
2980
{
2981
    CharDriverState *chr = NULL;
2982
    NetCharDriver *s = NULL;
2983
    int fd = -1;
2984
    struct sockaddr_in saddr;
2985

    
2986
    chr = qemu_mallocz(sizeof(CharDriverState));
2987
    if (!chr)
2988
        goto return_err;
2989
    s = qemu_mallocz(sizeof(NetCharDriver));
2990
    if (!s)
2991
        goto return_err;
2992

    
2993
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2994
    if (fd < 0) {
2995
        perror("socket(PF_INET, SOCK_DGRAM)");
2996
        goto return_err;
2997
    }
2998

    
2999
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3000
        printf("Could not parse: %s\n", def);
3001
        goto return_err;
3002
    }
3003

    
3004
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3005
    {
3006
        perror("bind");
3007
        goto return_err;
3008
    }
3009

    
3010
    s->fd = fd;
3011
    s->bufcnt = 0;
3012
    s->bufptr = 0;
3013
    chr->opaque = s;
3014
    chr->chr_write = udp_chr_write;
3015
    chr->chr_update_read_handler = udp_chr_update_read_handler;
3016
    return chr;
3017

    
3018
return_err:
3019
    if (chr)
3020
        free(chr);
3021
    if (s)
3022
        free(s);
3023
    if (fd >= 0)
3024
        closesocket(fd);
3025
    return NULL;
3026
}
3027

    
3028
/***********************************************************/
3029
/* TCP Net console */
3030

    
3031
typedef struct {
3032
    int fd, listen_fd;
3033
    int connected;
3034
    int max_size;
3035
    int do_telnetopt;
3036
    int do_nodelay;
3037
    int is_unix;
3038
} TCPCharDriver;
3039

    
3040
static void tcp_chr_accept(void *opaque);
3041

    
3042
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3043
{
3044
    TCPCharDriver *s = chr->opaque;
3045
    if (s->connected) {
3046
        return send_all(s->fd, buf, len);
3047
    } else {
3048
        /* XXX: indicate an error ? */
3049
        return len;
3050
    }
3051
}
3052

    
3053
static int tcp_chr_read_poll(void *opaque)
3054
{
3055
    CharDriverState *chr = opaque;
3056
    TCPCharDriver *s = chr->opaque;
3057
    if (!s->connected)
3058
        return 0;
3059
    s->max_size = qemu_chr_can_read(chr);
3060
    return s->max_size;
3061
}
3062

    
3063
#define IAC 255
3064
#define IAC_BREAK 243
3065
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3066
                                      TCPCharDriver *s,
3067
                                      uint8_t *buf, int *size)
3068
{
3069
    /* Handle any telnet client's basic IAC options to satisfy char by
3070
     * char mode with no echo.  All IAC options will be removed from
3071
     * the buf and the do_telnetopt variable will be used to track the
3072
     * state of the width of the IAC information.
3073
     *
3074
     * IAC commands come in sets of 3 bytes with the exception of the
3075
     * "IAC BREAK" command and the double IAC.
3076
     */
3077

    
3078
    int i;
3079
    int j = 0;
3080

    
3081
    for (i = 0; i < *size; i++) {
3082
        if (s->do_telnetopt > 1) {
3083
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3084
                /* Double IAC means send an IAC */
3085
                if (j != i)
3086
                    buf[j] = buf[i];
3087
                j++;
3088
                s->do_telnetopt = 1;
3089
            } else {
3090
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3091
                    /* Handle IAC break commands by sending a serial break */
3092
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3093
                    s->do_telnetopt++;
3094
                }
3095
                s->do_telnetopt++;
3096
            }
3097
            if (s->do_telnetopt >= 4) {
3098
                s->do_telnetopt = 1;
3099
            }
3100
        } else {
3101
            if ((unsigned char)buf[i] == IAC) {
3102
                s->do_telnetopt = 2;
3103
            } else {
3104
                if (j != i)
3105
                    buf[j] = buf[i];
3106
                j++;
3107
            }
3108
        }
3109
    }
3110
    *size = j;
3111
}
3112

    
3113
static void tcp_chr_read(void *opaque)
3114
{
3115
    CharDriverState *chr = opaque;
3116
    TCPCharDriver *s = chr->opaque;
3117
    uint8_t buf[1024];
3118
    int len, size;
3119

    
3120
    if (!s->connected || s->max_size <= 0)
3121
        return;
3122
    len = sizeof(buf);
3123
    if (len > s->max_size)
3124
        len = s->max_size;
3125
    size = recv(s->fd, buf, len, 0);
3126
    if (size == 0) {
3127
        /* connection closed */
3128
        s->connected = 0;
3129
        if (s->listen_fd >= 0) {
3130
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3131
        }
3132
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3133
        closesocket(s->fd);
3134
        s->fd = -1;
3135
    } else if (size > 0) {
3136
        if (s->do_telnetopt)
3137
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3138
        if (size > 0)
3139
            qemu_chr_read(chr, buf, size);
3140
    }
3141
}
3142

    
3143
static void tcp_chr_connect(void *opaque)
3144
{
3145
    CharDriverState *chr = opaque;
3146
    TCPCharDriver *s = chr->opaque;
3147

    
3148
    s->connected = 1;
3149
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3150
                         tcp_chr_read, NULL, chr);
3151
    qemu_chr_reset(chr);
3152
}
3153

    
3154
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3155
static void tcp_chr_telnet_init(int fd)
3156
{
3157
    char buf[3];
3158
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3159
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3160
    send(fd, (char *)buf, 3, 0);
3161
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3162
    send(fd, (char *)buf, 3, 0);
3163
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3164
    send(fd, (char *)buf, 3, 0);
3165
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3166
    send(fd, (char *)buf, 3, 0);
3167
}
3168

    
3169
static void socket_set_nodelay(int fd)
3170
{
3171
    int val = 1;
3172
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3173
}
3174

    
3175
static void tcp_chr_accept(void *opaque)
3176
{
3177
    CharDriverState *chr = opaque;
3178
    TCPCharDriver *s = chr->opaque;
3179
    struct sockaddr_in saddr;
3180
#ifndef _WIN32
3181
    struct sockaddr_un uaddr;
3182
#endif
3183
    struct sockaddr *addr;
3184
    socklen_t len;
3185
    int fd;
3186

    
3187
    for(;;) {
3188
#ifndef _WIN32
3189
        if (s->is_unix) {
3190
            len = sizeof(uaddr);
3191
            addr = (struct sockaddr *)&uaddr;
3192
        } else
3193
#endif
3194
        {
3195
            len = sizeof(saddr);
3196
            addr = (struct sockaddr *)&saddr;
3197
        }
3198
        fd = accept(s->listen_fd, addr, &len);
3199
        if (fd < 0 && errno != EINTR) {
3200
            return;
3201
        } else if (fd >= 0) {
3202
            if (s->do_telnetopt)
3203
                tcp_chr_telnet_init(fd);
3204
            break;
3205
        }
3206
    }
3207
    socket_set_nonblock(fd);
3208
    if (s->do_nodelay)
3209
        socket_set_nodelay(fd);
3210
    s->fd = fd;
3211
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3212
    tcp_chr_connect(chr);
3213
}
3214

    
3215
static void tcp_chr_close(CharDriverState *chr)
3216
{
3217
    TCPCharDriver *s = chr->opaque;
3218
    if (s->fd >= 0)
3219
        closesocket(s->fd);
3220
    if (s->listen_fd >= 0)
3221
        closesocket(s->listen_fd);
3222
    qemu_free(s);
3223
}
3224

    
3225
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3226
                                          int is_telnet,
3227
                                          int is_unix)
3228
{
3229
    CharDriverState *chr = NULL;
3230
    TCPCharDriver *s = NULL;
3231
    int fd = -1, ret, err, val;
3232
    int is_listen = 0;
3233
    int is_waitconnect = 1;
3234
    int do_nodelay = 0;
3235
    const char *ptr;
3236
    struct sockaddr_in saddr;
3237
#ifndef _WIN32
3238
    struct sockaddr_un uaddr;
3239
#endif
3240
    struct sockaddr *addr;
3241
    socklen_t addrlen;
3242

    
3243
#ifndef _WIN32
3244
    if (is_unix) {
3245
        addr = (struct sockaddr *)&uaddr;
3246
        addrlen = sizeof(uaddr);
3247
        if (parse_unix_path(&uaddr, host_str) < 0)
3248
            goto fail;
3249
    } else
3250
#endif
3251
    {
3252
        addr = (struct sockaddr *)&saddr;
3253
        addrlen = sizeof(saddr);
3254
        if (parse_host_port(&saddr, host_str) < 0)
3255
            goto fail;
3256
    }
3257

    
3258
    ptr = host_str;
3259
    while((ptr = strchr(ptr,','))) {
3260
        ptr++;
3261
        if (!strncmp(ptr,"server",6)) {
3262
            is_listen = 1;
3263
        } else if (!strncmp(ptr,"nowait",6)) {
3264
            is_waitconnect = 0;
3265
        } else if (!strncmp(ptr,"nodelay",6)) {
3266
            do_nodelay = 1;
3267
        } else {
3268
            printf("Unknown option: %s\n", ptr);
3269
            goto fail;
3270
        }
3271
    }
3272
    if (!is_listen)
3273
        is_waitconnect = 0;
3274

    
3275
    chr = qemu_mallocz(sizeof(CharDriverState));
3276
    if (!chr)
3277
        goto fail;
3278
    s = qemu_mallocz(sizeof(TCPCharDriver));
3279
    if (!s)
3280
        goto fail;
3281

    
3282
#ifndef _WIN32
3283
    if (is_unix)
3284
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3285
    else
3286
#endif
3287
        fd = socket(PF_INET, SOCK_STREAM, 0);
3288

    
3289
    if (fd < 0)
3290
        goto fail;
3291

    
3292
    if (!is_waitconnect)
3293
        socket_set_nonblock(fd);
3294

    
3295
    s->connected = 0;
3296
    s->fd = -1;
3297
    s->listen_fd = -1;
3298
    s->is_unix = is_unix;
3299
    s->do_nodelay = do_nodelay && !is_unix;
3300

    
3301
    chr->opaque = s;
3302
    chr->chr_write = tcp_chr_write;
3303
    chr->chr_close = tcp_chr_close;
3304

    
3305
    if (is_listen) {
3306
        /* allow fast reuse */
3307
#ifndef _WIN32
3308
        if (is_unix) {
3309
            char path[109];
3310
            strncpy(path, uaddr.sun_path, 108);
3311
            path[108] = 0;
3312
            unlink(path);
3313
        } else
3314
#endif
3315
        {
3316
            val = 1;
3317
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3318
        }
3319

    
3320
        ret = bind(fd, addr, addrlen);
3321
        if (ret < 0)
3322
            goto fail;
3323

    
3324
        ret = listen(fd, 0);
3325
        if (ret < 0)
3326
            goto fail;
3327

    
3328
        s->listen_fd = fd;
3329
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3330
        if (is_telnet)
3331
            s->do_telnetopt = 1;
3332
    } else {
3333
        for(;;) {
3334
            ret = connect(fd, addr, addrlen);
3335
            if (ret < 0) {
3336
                err = socket_error();
3337
                if (err == EINTR || err == EWOULDBLOCK) {
3338
                } else if (err == EINPROGRESS) {
3339
                    break;
3340
#ifdef _WIN32
3341
                } else if (err == WSAEALREADY) {
3342
                    break;
3343
#endif
3344
                } else {
3345
                    goto fail;
3346
                }
3347
            } else {
3348
                s->connected = 1;
3349
                break;
3350
            }
3351
        }
3352
        s->fd = fd;
3353
        socket_set_nodelay(fd);
3354
        if (s->connected)
3355
            tcp_chr_connect(chr);
3356
        else
3357
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3358
    }
3359

    
3360
    if (is_listen && is_waitconnect) {
3361
        printf("QEMU waiting for connection on: %s\n", host_str);
3362
        tcp_chr_accept(chr);
3363
        socket_set_nonblock(s->listen_fd);
3364
    }
3365

    
3366
    return chr;
3367
 fail:
3368
    if (fd >= 0)
3369
        closesocket(fd);
3370
    qemu_free(s);
3371
    qemu_free(chr);
3372
    return NULL;
3373
}
3374

    
3375
CharDriverState *qemu_chr_open(const char *filename)
3376
{
3377
    const char *p;
3378

    
3379
    if (!strcmp(filename, "vc")) {
3380
        return text_console_init(&display_state, 0);
3381
    } else if (strstart(filename, "vc:", &p)) {
3382
        return text_console_init(&display_state, p);
3383
    } else if (!strcmp(filename, "null")) {
3384
        return qemu_chr_open_null();
3385
    } else
3386
    if (strstart(filename, "tcp:", &p)) {
3387
        return qemu_chr_open_tcp(p, 0, 0);
3388
    } else
3389
    if (strstart(filename, "telnet:", &p)) {
3390
        return qemu_chr_open_tcp(p, 1, 0);
3391
    } else
3392
    if (strstart(filename, "udp:", &p)) {
3393
        return qemu_chr_open_udp(p);
3394
    } else
3395
    if (strstart(filename, "mon:", &p)) {
3396
        CharDriverState *drv = qemu_chr_open(p);
3397
        if (drv) {
3398
            drv = qemu_chr_open_mux(drv);
3399
            monitor_init(drv, !nographic);
3400
            return drv;
3401
        }
3402
        printf("Unable to open driver: %s\n", p);
3403
        return 0;
3404
    } else
3405
#ifndef _WIN32
3406
    if (strstart(filename, "unix:", &p)) {
3407
        return qemu_chr_open_tcp(p, 0, 1);
3408
    } else if (strstart(filename, "file:", &p)) {
3409
        return qemu_chr_open_file_out(p);
3410
    } else if (strstart(filename, "pipe:", &p)) {
3411
        return qemu_chr_open_pipe(p);
3412
    } else if (!strcmp(filename, "pty")) {
3413
        return qemu_chr_open_pty();
3414
    } else if (!strcmp(filename, "stdio")) {
3415
        return qemu_chr_open_stdio();
3416
    } else
3417
#if defined(__linux__)
3418
    if (strstart(filename, "/dev/parport", NULL)) {
3419
        return qemu_chr_open_pp(filename);
3420
    } else
3421
#endif
3422
#if defined(__linux__) || defined(__sun__)
3423
    if (strstart(filename, "/dev/", NULL)) {
3424
        return qemu_chr_open_tty(filename);
3425
    } else
3426
#endif
3427
#else /* !_WIN32 */
3428
    if (strstart(filename, "COM", NULL)) {
3429
        return qemu_chr_open_win(filename);
3430
    } else
3431
    if (strstart(filename, "pipe:", &p)) {
3432
        return qemu_chr_open_win_pipe(p);
3433
    } else
3434
    if (strstart(filename, "con:", NULL)) {
3435
        return qemu_chr_open_win_con(filename);
3436
    } else
3437
    if (strstart(filename, "file:", &p)) {
3438
        return qemu_chr_open_win_file_out(p);
3439
    }
3440
#endif
3441
    {
3442
        return NULL;
3443
    }
3444
}
3445

    
3446
void qemu_chr_close(CharDriverState *chr)
3447
{
3448
    if (chr->chr_close)
3449
        chr->chr_close(chr);
3450
    qemu_free(chr);
3451
}
3452

    
3453
/***********************************************************/
3454
/* network device redirectors */
3455

    
3456
__attribute__ (( unused ))
3457
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3458
{
3459
    int len, i, j, c;
3460

    
3461
    for(i=0;i<size;i+=16) {
3462
        len = size - i;
3463
        if (len > 16)
3464
            len = 16;
3465
        fprintf(f, "%08x ", i);
3466
        for(j=0;j<16;j++) {
3467
            if (j < len)
3468
                fprintf(f, " %02x", buf[i+j]);
3469
            else
3470
                fprintf(f, "   ");
3471
        }
3472
        fprintf(f, " ");
3473
        for(j=0;j<len;j++) {
3474
            c = buf[i+j];
3475
            if (c < ' ' || c > '~')
3476
                c = '.';
3477
            fprintf(f, "%c", c);
3478
        }
3479
        fprintf(f, "\n");
3480
    }
3481
}
3482

    
3483
static int parse_macaddr(uint8_t *macaddr, const char *p)
3484
{
3485
    int i;
3486
    char *last_char;
3487
    long int offset;
3488

    
3489
    errno = 0;
3490
    offset = strtol(p, &last_char, 0);    
3491
    if (0 == errno && '\0' == *last_char &&
3492
            offset >= 0 && offset <= 0xFFFFFF) {
3493
        macaddr[3] = (offset & 0xFF0000) >> 16;
3494
        macaddr[4] = (offset & 0xFF00) >> 8;
3495
        macaddr[5] = offset & 0xFF;
3496
        return 0;
3497
    } else {
3498
        for(i = 0; i < 6; i++) {
3499
            macaddr[i] = strtol(p, (char **)&p, 16);
3500
            if (i == 5) {
3501
                if (*p != '\0')
3502
                    return -1;
3503
            } else {
3504
                if (*p != ':' && *p != '-')
3505
                    return -1;
3506
                p++;
3507
            }
3508
        }
3509
        return 0;    
3510
    }
3511

    
3512
    return -1;
3513
}
3514

    
3515
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3516
{
3517
    const char *p, *p1;
3518
    int len;
3519
    p = *pp;
3520
    p1 = strchr(p, sep);
3521
    if (!p1)
3522
        return -1;
3523
    len = p1 - p;
3524
    p1++;
3525
    if (buf_size > 0) {
3526
        if (len > buf_size - 1)
3527
            len = buf_size - 1;
3528
        memcpy(buf, p, len);
3529
        buf[len] = '\0';
3530
    }
3531
    *pp = p1;
3532
    return 0;
3533
}
3534

    
3535
int parse_host_src_port(struct sockaddr_in *haddr,
3536
                        struct sockaddr_in *saddr,
3537
                        const char *input_str)
3538
{
3539
    char *str = strdup(input_str);
3540
    char *host_str = str;
3541
    char *src_str;
3542
    char *ptr;
3543

    
3544
    /*
3545
     * Chop off any extra arguments at the end of the string which
3546
     * would start with a comma, then fill in the src port information
3547
     * if it was provided else use the "any address" and "any port".
3548
     */
3549
    if ((ptr = strchr(str,',')))
3550
        *ptr = '\0';
3551

    
3552
    if ((src_str = strchr(input_str,'@'))) {
3553
        *src_str = '\0';
3554
        src_str++;
3555
    }
3556

    
3557
    if (parse_host_port(haddr, host_str) < 0)
3558
        goto fail;
3559

    
3560
    if (!src_str || *src_str == '\0')
3561
        src_str = ":0";
3562

    
3563
    if (parse_host_port(saddr, src_str) < 0)
3564
        goto fail;
3565

    
3566
    free(str);
3567
    return(0);
3568

    
3569
fail:
3570
    free(str);
3571
    return -1;
3572
}
3573

    
3574
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3575
{
3576
    char buf[512];
3577
    struct hostent *he;
3578
    const char *p, *r;
3579
    int port;
3580

    
3581
    p = str;
3582
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3583
        return -1;
3584
    saddr->sin_family = AF_INET;
3585
    if (buf[0] == '\0') {
3586
        saddr->sin_addr.s_addr = 0;
3587
    } else {
3588
        if (isdigit(buf[0])) {
3589
            if (!inet_aton(buf, &saddr->sin_addr))
3590
                return -1;
3591
        } else {
3592
            if ((he = gethostbyname(buf)) == NULL)
3593
                return - 1;
3594
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3595
        }
3596
    }
3597
    port = strtol(p, (char **)&r, 0);
3598
    if (r == p)
3599
        return -1;
3600
    saddr->sin_port = htons(port);
3601
    return 0;
3602
}
3603

    
3604
#ifndef _WIN32
3605
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3606
{
3607
    const char *p;
3608
    int len;
3609

    
3610
    len = MIN(108, strlen(str));
3611
    p = strchr(str, ',');
3612
    if (p)
3613
        len = MIN(len, p - str);
3614

    
3615
    memset(uaddr, 0, sizeof(*uaddr));
3616

    
3617
    uaddr->sun_family = AF_UNIX;
3618
    memcpy(uaddr->sun_path, str, len);
3619

    
3620
    return 0;
3621
}
3622
#endif
3623

    
3624
/* find or alloc a new VLAN */
3625
VLANState *qemu_find_vlan(int id)
3626
{
3627
    VLANState **pvlan, *vlan;
3628
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3629
        if (vlan->id == id)
3630
            return vlan;
3631
    }
3632
    vlan = qemu_mallocz(sizeof(VLANState));
3633
    if (!vlan)
3634
        return NULL;
3635
    vlan->id = id;
3636
    vlan->next = NULL;
3637
    pvlan = &first_vlan;
3638
    while (*pvlan != NULL)
3639
        pvlan = &(*pvlan)->next;
3640
    *pvlan = vlan;
3641
    return vlan;
3642
}
3643

    
3644
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3645
                                      IOReadHandler *fd_read,
3646
                                      IOCanRWHandler *fd_can_read,
3647
                                      void *opaque)
3648
{
3649
    VLANClientState *vc, **pvc;
3650
    vc = qemu_mallocz(sizeof(VLANClientState));
3651
    if (!vc)
3652
        return NULL;
3653
    vc->fd_read = fd_read;
3654
    vc->fd_can_read = fd_can_read;
3655
    vc->opaque = opaque;
3656
    vc->vlan = vlan;
3657

    
3658
    vc->next = NULL;
3659
    pvc = &vlan->first_client;
3660
    while (*pvc != NULL)
3661
        pvc = &(*pvc)->next;
3662
    *pvc = vc;
3663
    return vc;
3664
}
3665

    
3666
int qemu_can_send_packet(VLANClientState *vc1)
3667
{
3668
    VLANState *vlan = vc1->vlan;
3669
    VLANClientState *vc;
3670

    
3671
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3672
        if (vc != vc1) {
3673
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3674
                return 1;
3675
        }
3676
    }
3677
    return 0;
3678
}
3679

    
3680
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3681
{
3682
    VLANState *vlan = vc1->vlan;
3683
    VLANClientState *vc;
3684

    
3685
#if 0
3686
    printf("vlan %d send:\n", vlan->id);
3687
    hex_dump(stdout, buf, size);
3688
#endif
3689
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3690
        if (vc != vc1) {
3691
            vc->fd_read(vc->opaque, buf, size);
3692
        }
3693
    }
3694
}
3695

    
3696
#if defined(CONFIG_SLIRP)
3697

    
3698
/* slirp network adapter */
3699

    
3700
static int slirp_inited;
3701
static VLANClientState *slirp_vc;
3702

    
3703
int slirp_can_output(void)
3704
{
3705
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3706
}
3707

    
3708
void slirp_output(const uint8_t *pkt, int pkt_len)
3709
{
3710
#if 0
3711
    printf("slirp output:\n");
3712
    hex_dump(stdout, pkt, pkt_len);
3713
#endif
3714
    if (!slirp_vc)
3715
        return;
3716
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3717
}
3718

    
3719
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3720
{
3721
#if 0
3722
    printf("slirp input:\n");
3723
    hex_dump(stdout, buf, size);
3724
#endif
3725
    slirp_input(buf, size);
3726
}
3727

    
3728
static int net_slirp_init(VLANState *vlan)
3729
{
3730
    if (!slirp_inited) {
3731
        slirp_inited = 1;
3732
        slirp_init();
3733
    }
3734
    slirp_vc = qemu_new_vlan_client(vlan,
3735
                                    slirp_receive, NULL, NULL);
3736
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3737
    return 0;
3738
}
3739

    
3740
static void net_slirp_redir(const char *redir_str)
3741
{
3742
    int is_udp;
3743
    char buf[256], *r;
3744
    const char *p;
3745
    struct in_addr guest_addr;
3746
    int host_port, guest_port;
3747

    
3748
    if (!slirp_inited) {
3749
        slirp_inited = 1;
3750
        slirp_init();
3751
    }
3752

    
3753
    p = redir_str;
3754
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3755
        goto fail;
3756
    if (!strcmp(buf, "tcp")) {
3757
        is_udp = 0;
3758
    } else if (!strcmp(buf, "udp")) {
3759
        is_udp = 1;
3760
    } else {
3761
        goto fail;
3762
    }
3763

    
3764
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3765
        goto fail;
3766
    host_port = strtol(buf, &r, 0);
3767
    if (r == buf)
3768
        goto fail;
3769

    
3770
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3771
        goto fail;
3772
    if (buf[0] == '\0') {
3773
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3774
    }
3775
    if (!inet_aton(buf, &guest_addr))
3776
        goto fail;
3777

    
3778
    guest_port = strtol(p, &r, 0);
3779
    if (r == p)
3780
        goto fail;
3781

    
3782
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3783
        fprintf(stderr, "qemu: could not set up redirection\n");
3784
        exit(1);
3785
    }
3786
    return;
3787
 fail:
3788
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3789
    exit(1);
3790
}
3791

    
3792
#ifndef _WIN32
3793

    
3794
char smb_dir[1024];
3795

    
3796
static void erase_dir(char *dir_name)
3797
{
3798
    DIR *d;
3799
    struct dirent *de;
3800
    char filename[1024];
3801

    
3802
    /* erase all the files in the directory */
3803
    if ((d = opendir(dir_name)) != 0) {
3804
        for(;;) {
3805
            de = readdir(d);
3806
            if (!de)
3807
                break;
3808
            if (strcmp(de->d_name, ".") != 0 &&
3809
                strcmp(de->d_name, "..") != 0) {
3810
                snprintf(filename, sizeof(filename), "%s/%s",
3811
                         smb_dir, de->d_name);
3812
                if (unlink(filename) != 0)  /* is it a directory? */
3813
                    erase_dir(filename);
3814
            }
3815
        }
3816
        closedir(d);
3817
        rmdir(dir_name);
3818
    }
3819
}
3820

    
3821
/* automatic user mode samba server configuration */
3822
static void smb_exit(void)
3823
{
3824
    erase_dir(smb_dir);
3825
}
3826

    
3827
/* automatic user mode samba server configuration */
3828
static void net_slirp_smb(const char *exported_dir)
3829
{
3830
    char smb_conf[1024];
3831
    char smb_cmdline[1024];
3832
    FILE *f;
3833

    
3834
    if (!slirp_inited) {
3835
        slirp_inited = 1;
3836
        slirp_init();
3837
    }
3838

    
3839
    /* XXX: better tmp dir construction */
3840
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3841
    if (mkdir(smb_dir, 0700) < 0) {
3842
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3843
        exit(1);
3844
    }
3845
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3846

    
3847
    f = fopen(smb_conf, "w");
3848
    if (!f) {
3849
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3850
        exit(1);
3851
    }
3852
    fprintf(f,
3853
            "[global]\n"
3854
            "private dir=%s\n"
3855
            "smb ports=0\n"
3856
            "socket address=127.0.0.1\n"
3857
            "pid directory=%s\n"
3858
            "lock directory=%s\n"
3859
            "log file=%s/log.smbd\n"
3860
            "smb passwd file=%s/smbpasswd\n"
3861
            "security = share\n"
3862
            "[qemu]\n"
3863
            "path=%s\n"
3864
            "read only=no\n"
3865
            "guest ok=yes\n",
3866
            smb_dir,
3867
            smb_dir,
3868
            smb_dir,
3869
            smb_dir,
3870
            smb_dir,
3871
            exported_dir
3872
            );
3873
    fclose(f);
3874
    atexit(smb_exit);
3875

    
3876
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3877
             SMBD_COMMAND, smb_conf);
3878

    
3879
    slirp_add_exec(0, smb_cmdline, 4, 139);
3880
}
3881

    
3882
#endif /* !defined(_WIN32) */
3883
void do_info_slirp(void)
3884
{
3885
    slirp_stats();
3886
}
3887

    
3888
#endif /* CONFIG_SLIRP */
3889

    
3890
#if !defined(_WIN32)
3891

    
3892
typedef struct TAPState {
3893
    VLANClientState *vc;
3894
    int fd;
3895
    char down_script[1024];
3896
} TAPState;
3897

    
3898
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3899
{
3900
    TAPState *s = opaque;
3901
    int ret;
3902
    for(;;) {
3903
        ret = write(s->fd, buf, size);
3904
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3905
        } else {
3906
            break;
3907
        }
3908
    }
3909
}
3910

    
3911
static void tap_send(void *opaque)
3912
{
3913
    TAPState *s = opaque;
3914
    uint8_t buf[4096];
3915
    int size;
3916

    
3917
#ifdef __sun__
3918
    struct strbuf sbuf;
3919
    int f = 0;
3920
    sbuf.maxlen = sizeof(buf);
3921
    sbuf.buf = buf;
3922
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3923
#else
3924
    size = read(s->fd, buf, sizeof(buf));
3925
#endif
3926
    if (size > 0) {
3927
        qemu_send_packet(s->vc, buf, size);
3928
    }
3929
}
3930

    
3931
/* fd support */
3932

    
3933
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3934
{
3935
    TAPState *s;
3936

    
3937
    s = qemu_mallocz(sizeof(TAPState));
3938
    if (!s)
3939
        return NULL;
3940
    s->fd = fd;
3941
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3942
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3943
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3944
    return s;
3945
}
3946

    
3947
#if defined (_BSD) || defined (__FreeBSD_kernel__)
3948
static int tap_open(char *ifname, int ifname_size)
3949
{
3950
    int fd;
3951
    char *dev;
3952
    struct stat s;
3953

    
3954
    TFR(fd = open("/dev/tap", O_RDWR));
3955
    if (fd < 0) {
3956
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3957
        return -1;
3958
    }
3959

    
3960
    fstat(fd, &s);
3961
    dev = devname(s.st_rdev, S_IFCHR);
3962
    pstrcpy(ifname, ifname_size, dev);
3963

    
3964
    fcntl(fd, F_SETFL, O_NONBLOCK);
3965
    return fd;
3966
}
3967
#elif defined(__sun__)
3968
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3969
/*
3970
 * Allocate TAP device, returns opened fd.
3971
 * Stores dev name in the first arg(must be large enough).
3972
 */
3973
int tap_alloc(char *dev)
3974
{
3975
    int tap_fd, if_fd, ppa = -1;
3976
    static int ip_fd = 0;
3977
    char *ptr;
3978

    
3979
    static int arp_fd = 0;
3980
    int ip_muxid, arp_muxid;
3981
    struct strioctl  strioc_if, strioc_ppa;
3982
    int link_type = I_PLINK;;
3983
    struct lifreq ifr;
3984
    char actual_name[32] = "";
3985

    
3986
    memset(&ifr, 0x0, sizeof(ifr));
3987

    
3988
    if( *dev ){
3989
       ptr = dev;
3990
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
3991
       ppa = atoi(ptr);
3992
    }
3993

    
3994
    /* Check if IP device was opened */
3995
    if( ip_fd )
3996
       close(ip_fd);
3997

    
3998
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3999
    if (ip_fd < 0) {
4000
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4001
       return -1;
4002
    }
4003

    
4004
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4005
    if (tap_fd < 0) {
4006
       syslog(LOG_ERR, "Can't open /dev/tap");
4007
       return -1;
4008
    }
4009

    
4010
    /* Assign a new PPA and get its unit number. */
4011
    strioc_ppa.ic_cmd = TUNNEWPPA;
4012
    strioc_ppa.ic_timout = 0;
4013
    strioc_ppa.ic_len = sizeof(ppa);
4014
    strioc_ppa.ic_dp = (char *)&ppa;
4015
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4016
       syslog (LOG_ERR, "Can't assign new interface");
4017

    
4018
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4019
    if (if_fd < 0) {
4020
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
4021
       return -1;
4022
    }
4023
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
4024
       syslog(LOG_ERR, "Can't push IP module");
4025
       return -1;
4026
    }
4027

    
4028
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4029
        syslog(LOG_ERR, "Can't get flags\n");
4030

    
4031
    snprintf (actual_name, 32, "tap%d", ppa);
4032
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4033

    
4034
    ifr.lifr_ppa = ppa;
4035
    /* Assign ppa according to the unit number returned by tun device */
4036

    
4037
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4038
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
4039
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4040
        syslog (LOG_ERR, "Can't get flags\n");
4041
    /* Push arp module to if_fd */
4042
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
4043
        syslog (LOG_ERR, "Can't push ARP module (2)");
4044

    
4045
    /* Push arp module to ip_fd */
4046
    if (ioctl (ip_fd, I_POP, NULL) < 0)
4047
        syslog (LOG_ERR, "I_POP failed\n");
4048
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4049
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
4050
    /* Open arp_fd */
4051
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4052
    if (arp_fd < 0)
4053
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4054

    
4055
    /* Set ifname to arp */
4056
    strioc_if.ic_cmd = SIOCSLIFNAME;
4057
    strioc_if.ic_timout = 0;
4058
    strioc_if.ic_len = sizeof(ifr);
4059
    strioc_if.ic_dp = (char *)&ifr;
4060
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4061
        syslog (LOG_ERR, "Can't set ifname to arp\n");
4062
    }
4063

    
4064
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4065
       syslog(LOG_ERR, "Can't link TAP device to IP");
4066
       return -1;
4067
    }
4068

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

    
4072
    close (if_fd);
4073

    
4074
    memset(&ifr, 0x0, sizeof(ifr));
4075
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4076
    ifr.lifr_ip_muxid  = ip_muxid;
4077
    ifr.lifr_arp_muxid = arp_muxid;
4078

    
4079
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4080
    {
4081
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4082
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4083
      syslog (LOG_ERR, "Can't set multiplexor id");
4084
    }
4085

    
4086
    sprintf(dev, "tap%d", ppa);
4087
    return tap_fd;
4088
}
4089

    
4090
static int tap_open(char *ifname, int ifname_size)
4091
{
4092
    char  dev[10]="";
4093
    int fd;
4094
    if( (fd = tap_alloc(dev)) < 0 ){
4095
       fprintf(stderr, "Cannot allocate TAP device\n");
4096
       return -1;
4097
    }
4098
    pstrcpy(ifname, ifname_size, dev);
4099
    fcntl(fd, F_SETFL, O_NONBLOCK);
4100
    return fd;
4101
}
4102
#else
4103
static int tap_open(char *ifname, int ifname_size)
4104
{
4105
    struct ifreq ifr;
4106
    int fd, ret;
4107

    
4108
    TFR(fd = open("/dev/net/tun", O_RDWR));
4109
    if (fd < 0) {
4110
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4111
        return -1;
4112
    }
4113
    memset(&ifr, 0, sizeof(ifr));
4114
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4115
    if (ifname[0] != '\0')
4116
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4117
    else
4118
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4119
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4120
    if (ret != 0) {
4121
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4122
        close(fd);
4123
        return -1;
4124
    }
4125
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4126
    fcntl(fd, F_SETFL, O_NONBLOCK);
4127
    return fd;
4128
}
4129
#endif
4130

    
4131
static int launch_script(const char *setup_script, const char *ifname, int fd)
4132
{
4133
    int pid, status;
4134
    char *args[3];
4135
    char **parg;
4136

    
4137
        /* try to launch network script */
4138
        pid = fork();
4139
        if (pid >= 0) {
4140
            if (pid == 0) {
4141
                int open_max = sysconf (_SC_OPEN_MAX), i;
4142
                for (i = 0; i < open_max; i++)
4143
                    if (i != STDIN_FILENO &&
4144
                        i != STDOUT_FILENO &&
4145
                        i != STDERR_FILENO &&
4146
                        i != fd)
4147
                        close(i);
4148

    
4149
                parg = args;
4150
                *parg++ = (char *)setup_script;
4151
                *parg++ = (char *)ifname;
4152
                *parg++ = NULL;
4153
                execv(setup_script, args);
4154
                _exit(1);
4155
            }
4156
            while (waitpid(pid, &status, 0) != pid);
4157
            if (!WIFEXITED(status) ||
4158
                WEXITSTATUS(status) != 0) {
4159
                fprintf(stderr, "%s: could not launch network script\n",
4160
                        setup_script);
4161
                return -1;
4162
            }
4163
        }
4164
    return 0;
4165
}
4166

    
4167
static int net_tap_init(VLANState *vlan, const char *ifname1,
4168
                        const char *setup_script, const char *down_script)
4169
{
4170
    TAPState *s;
4171
    int fd;
4172
    char ifname[128];
4173

    
4174
    if (ifname1 != NULL)
4175
        pstrcpy(ifname, sizeof(ifname), ifname1);
4176
    else
4177
        ifname[0] = '\0';
4178
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4179
    if (fd < 0)
4180
        return -1;
4181

    
4182
    if (!setup_script || !strcmp(setup_script, "no"))
4183
        setup_script = "";
4184
    if (setup_script[0] != '\0') {
4185
        if (launch_script(setup_script, ifname, fd))
4186
            return -1;
4187
    }
4188
    s = net_tap_fd_init(vlan, fd);
4189
    if (!s)
4190
        return -1;
4191
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4192
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4193
    if (down_script && strcmp(down_script, "no"))
4194
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4195
    return 0;
4196
}
4197

    
4198
#endif /* !_WIN32 */
4199

    
4200
/* network connection */
4201
typedef struct NetSocketState {
4202
    VLANClientState *vc;
4203
    int fd;
4204
    int state; /* 0 = getting length, 1 = getting data */
4205
    int index;
4206
    int packet_len;
4207
    uint8_t buf[4096];
4208
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4209
} NetSocketState;
4210

    
4211
typedef struct NetSocketListenState {
4212
    VLANState *vlan;
4213
    int fd;
4214
} NetSocketListenState;
4215

    
4216
/* XXX: we consider we can send the whole packet without blocking */
4217
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4218
{
4219
    NetSocketState *s = opaque;
4220
    uint32_t len;
4221
    len = htonl(size);
4222

    
4223
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4224
    send_all(s->fd, buf, size);
4225
}
4226

    
4227
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4228
{
4229
    NetSocketState *s = opaque;
4230
    sendto(s->fd, buf, size, 0,
4231
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4232
}
4233

    
4234
static void net_socket_send(void *opaque)
4235
{
4236
    NetSocketState *s = opaque;
4237
    int l, size, err;
4238
    uint8_t buf1[4096];
4239
    const uint8_t *buf;
4240

    
4241
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4242
    if (size < 0) {
4243
        err = socket_error();
4244
        if (err != EWOULDBLOCK)
4245
            goto eoc;
4246
    } else if (size == 0) {
4247
        /* end of connection */
4248
    eoc:
4249
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4250
        closesocket(s->fd);
4251
        return;
4252
    }
4253
    buf = buf1;
4254
    while (size > 0) {
4255
        /* reassemble a packet from the network */
4256
        switch(s->state) {
4257
        case 0:
4258
            l = 4 - s->index;
4259
            if (l > size)
4260
                l = size;
4261
            memcpy(s->buf + s->index, buf, l);
4262
            buf += l;
4263
            size -= l;
4264
            s->index += l;
4265
            if (s->index == 4) {
4266
                /* got length */
4267
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4268
                s->index = 0;
4269
                s->state = 1;
4270
            }
4271
            break;
4272
        case 1:
4273
            l = s->packet_len - s->index;
4274
            if (l > size)
4275
                l = size;
4276
            memcpy(s->buf + s->index, buf, l);
4277
            s->index += l;
4278
            buf += l;
4279
            size -= l;
4280
            if (s->index >= s->packet_len) {
4281
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4282
                s->index = 0;
4283
                s->state = 0;
4284
            }
4285
            break;
4286
        }
4287
    }
4288
}
4289

    
4290
static void net_socket_send_dgram(void *opaque)
4291
{
4292
    NetSocketState *s = opaque;
4293
    int size;
4294

    
4295
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4296
    if (size < 0)
4297
        return;
4298
    if (size == 0) {
4299
        /* end of connection */
4300
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4301
        return;
4302
    }
4303
    qemu_send_packet(s->vc, s->buf, size);
4304
}
4305

    
4306
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4307
{
4308
    struct ip_mreq imr;
4309
    int fd;
4310
    int val, ret;
4311
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4312
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4313
                inet_ntoa(mcastaddr->sin_addr),
4314
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4315
        return -1;
4316

    
4317
    }
4318
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4319
    if (fd < 0) {
4320
        perror("socket(PF_INET, SOCK_DGRAM)");
4321
        return -1;
4322
    }
4323

    
4324
    val = 1;
4325
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4326
                   (const char *)&val, sizeof(val));
4327
    if (ret < 0) {
4328
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4329
        goto fail;
4330
    }
4331

    
4332
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4333
    if (ret < 0) {
4334
        perror("bind");
4335
        goto fail;
4336
    }
4337

    
4338
    /* Add host to multicast group */
4339
    imr.imr_multiaddr = mcastaddr->sin_addr;
4340
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4341

    
4342
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4343
                     (const char *)&imr, sizeof(struct ip_mreq));
4344
    if (ret < 0) {
4345
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4346
        goto fail;
4347
    }
4348

    
4349
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4350
    val = 1;
4351
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4352
                   (const char *)&val, sizeof(val));
4353
    if (ret < 0) {
4354
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4355
        goto fail;
4356
    }
4357

    
4358
    socket_set_nonblock(fd);
4359
    return fd;
4360
fail:
4361
    if (fd >= 0)
4362
        closesocket(fd);
4363
    return -1;
4364
}
4365

    
4366
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4367
                                          int is_connected)
4368
{
4369
    struct sockaddr_in saddr;
4370
    int newfd;
4371
    socklen_t saddr_len;
4372
    NetSocketState *s;
4373

    
4374
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4375
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4376
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4377
     */
4378

    
4379
    if (is_connected) {
4380
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4381
            /* must be bound */
4382
            if (saddr.sin_addr.s_addr==0) {
4383
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4384
                        fd);
4385
                return NULL;
4386
            }
4387
            /* clone dgram socket */
4388
            newfd = net_socket_mcast_create(&saddr);
4389
            if (newfd < 0) {
4390
                /* error already reported by net_socket_mcast_create() */
4391
                close(fd);
4392
                return NULL;
4393
            }
4394
            /* clone newfd to fd, close newfd */
4395
            dup2(newfd, fd);
4396
            close(newfd);
4397

    
4398
        } else {
4399
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4400
                    fd, strerror(errno));
4401
            return NULL;
4402
        }
4403
    }
4404

    
4405
    s = qemu_mallocz(sizeof(NetSocketState));
4406
    if (!s)
4407
        return NULL;
4408
    s->fd = fd;
4409

    
4410
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4411
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4412

    
4413
    /* mcast: save bound address as dst */
4414
    if (is_connected) s->dgram_dst=saddr;
4415

    
4416
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4417
            "socket: fd=%d (%s mcast=%s:%d)",
4418
            fd, is_connected? "cloned" : "",
4419
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4420
    return s;
4421
}
4422

    
4423
static void net_socket_connect(void *opaque)
4424
{
4425
    NetSocketState *s = opaque;
4426
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4427
}
4428

    
4429
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4430
                                          int is_connected)
4431
{
4432
    NetSocketState *s;
4433
    s = qemu_mallocz(sizeof(NetSocketState));
4434
    if (!s)
4435
        return NULL;
4436
    s->fd = fd;
4437
    s->vc = qemu_new_vlan_client(vlan,
4438
                                 net_socket_receive, NULL, s);
4439
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4440
             "socket: fd=%d", fd);
4441
    if (is_connected) {
4442
        net_socket_connect(s);
4443
    } else {
4444
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4445
    }
4446
    return s;
4447
}
4448

    
4449
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4450
                                          int is_connected)
4451
{
4452
    int so_type=-1, optlen=sizeof(so_type);
4453

    
4454
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4455
        (socklen_t *)&optlen)< 0) {
4456
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4457
        return NULL;
4458
    }
4459
    switch(so_type) {
4460
    case SOCK_DGRAM:
4461
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4462
    case SOCK_STREAM:
4463
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4464
    default:
4465
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4466
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4467
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4468
    }
4469
    return NULL;
4470
}
4471

    
4472
static void net_socket_accept(void *opaque)
4473
{
4474
    NetSocketListenState *s = opaque;
4475
    NetSocketState *s1;
4476
    struct sockaddr_in saddr;
4477
    socklen_t len;
4478
    int fd;
4479

    
4480
    for(;;) {
4481
        len = sizeof(saddr);
4482
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4483
        if (fd < 0 && errno != EINTR) {
4484
            return;
4485
        } else if (fd >= 0) {
4486
            break;
4487
        }
4488
    }
4489
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4490
    if (!s1) {
4491
        closesocket(fd);
4492
    } else {
4493
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4494
                 "socket: connection from %s:%d",
4495
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4496
    }
4497
}
4498

    
4499
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4500
{
4501
    NetSocketListenState *s;
4502
    int fd, val, ret;
4503
    struct sockaddr_in saddr;
4504

    
4505
    if (parse_host_port(&saddr, host_str) < 0)
4506
        return -1;
4507

    
4508
    s = qemu_mallocz(sizeof(NetSocketListenState));
4509
    if (!s)
4510
        return -1;
4511

    
4512
    fd = socket(PF_INET, SOCK_STREAM, 0);
4513
    if (fd < 0) {
4514
        perror("socket");
4515
        return -1;
4516
    }
4517
    socket_set_nonblock(fd);
4518

    
4519
    /* allow fast reuse */
4520
    val = 1;
4521
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4522

    
4523
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4524
    if (ret < 0) {
4525
        perror("bind");
4526
        return -1;
4527
    }
4528
    ret = listen(fd, 0);
4529
    if (ret < 0) {
4530
        perror("listen");
4531
        return -1;
4532
    }
4533
    s->vlan = vlan;
4534
    s->fd = fd;
4535
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4536
    return 0;
4537
}
4538

    
4539
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4540
{
4541
    NetSocketState *s;
4542
    int fd, connected, ret, err;
4543
    struct sockaddr_in saddr;
4544

    
4545
    if (parse_host_port(&saddr, host_str) < 0)
4546
        return -1;
4547

    
4548
    fd = socket(PF_INET, SOCK_STREAM, 0);
4549
    if (fd < 0) {
4550
        perror("socket");
4551
        return -1;
4552
    }
4553
    socket_set_nonblock(fd);
4554

    
4555
    connected = 0;
4556
    for(;;) {
4557
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4558
        if (ret < 0) {
4559
            err = socket_error();
4560
            if (err == EINTR || err == EWOULDBLOCK) {
4561
            } else if (err == EINPROGRESS) {
4562
                break;
4563
#ifdef _WIN32
4564
            } else if (err == WSAEALREADY) {
4565
                break;
4566
#endif
4567
            } else {
4568
                perror("connect");
4569
                closesocket(fd);
4570
                return -1;
4571
            }
4572
        } else {
4573
            connected = 1;
4574
            break;
4575
        }
4576
    }
4577
    s = net_socket_fd_init(vlan, fd, connected);
4578
    if (!s)
4579
        return -1;
4580
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4581
             "socket: connect to %s:%d",
4582
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4583
    return 0;
4584
}
4585

    
4586
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4587
{
4588
    NetSocketState *s;
4589
    int fd;
4590
    struct sockaddr_in saddr;
4591

    
4592
    if (parse_host_port(&saddr, host_str) < 0)
4593
        return -1;
4594

    
4595

    
4596
    fd = net_socket_mcast_create(&saddr);
4597
    if (fd < 0)
4598
        return -1;
4599

    
4600
    s = net_socket_fd_init(vlan, fd, 0);
4601
    if (!s)
4602
        return -1;
4603

    
4604
    s->dgram_dst = saddr;
4605

    
4606
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4607
             "socket: mcast=%s:%d",
4608
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4609
    return 0;
4610

    
4611
}
4612

    
4613
static const char *get_opt_name(char *buf, int buf_size, const char *p)
4614
{
4615
    char *q;
4616

    
4617
    q = buf;
4618
    while (*p != '\0' && *p != '=') {
4619
        if (q && (q - buf) < buf_size - 1)
4620
            *q++ = *p;
4621
        p++;
4622
    }
4623
    if (q)
4624
        *q = '\0';
4625

    
4626
    return p;
4627
}
4628

    
4629
static const char *get_opt_value(char *buf, int buf_size, const char *p)
4630
{
4631
    char *q;
4632

    
4633
    q = buf;
4634
    while (*p != '\0') {
4635
        if (*p == ',') {
4636
            if (*(p + 1) != ',')
4637
                break;
4638
            p++;
4639
        }
4640
        if (q && (q - buf) < buf_size - 1)
4641
            *q++ = *p;
4642
        p++;
4643
    }
4644
    if (q)
4645
        *q = '\0';
4646

    
4647
    return p;
4648
}
4649

    
4650
static int get_param_value(char *buf, int buf_size,
4651
                           const char *tag, const char *str)
4652
{
4653
    const char *p;
4654
    char option[128];
4655

    
4656
    p = str;
4657
    for(;;) {
4658
        p = get_opt_name(option, sizeof(option), p);
4659
        if (*p != '=')
4660
            break;
4661
        p++;
4662
        if (!strcmp(tag, option)) {
4663
            (void)get_opt_value(buf, buf_size, p);
4664
            return strlen(buf);
4665
        } else {
4666
            p = get_opt_value(NULL, 0, p);
4667
        }
4668
        if (*p != ',')
4669
            break;
4670
        p++;
4671
    }
4672
    return 0;
4673
}
4674

    
4675
static int check_params(char *buf, int buf_size,
4676
                        char **params, const char *str)
4677
{
4678
    const char *p;
4679
    int i;
4680

    
4681
    p = str;
4682
    for(;;) {
4683
        p = get_opt_name(buf, buf_size, p);
4684
        if (*p != '=')
4685
            return -1;
4686
        p++;
4687
        for(i = 0; params[i] != NULL; i++)
4688
            if (!strcmp(params[i], buf))
4689
                break;
4690
        if (params[i] == NULL)
4691
            return -1;
4692
        p = get_opt_value(NULL, 0, p);
4693
        if (*p != ',')
4694
            break;
4695
        p++;
4696
    }
4697
    return 0;
4698
}
4699

    
4700

    
4701
static int net_client_init(const char *str)
4702
{
4703
    const char *p;
4704
    char *q;
4705
    char device[64];
4706
    char buf[1024];
4707
    int vlan_id, ret;
4708
    VLANState *vlan;
4709

    
4710
    p = str;
4711
    q = device;
4712
    while (*p != '\0' && *p != ',') {
4713
        if ((q - device) < sizeof(device) - 1)
4714
            *q++ = *p;
4715
        p++;
4716
    }
4717
    *q = '\0';
4718
    if (*p == ',')
4719
        p++;
4720
    vlan_id = 0;
4721
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4722
        vlan_id = strtol(buf, NULL, 0);
4723
    }
4724
    vlan = qemu_find_vlan(vlan_id);
4725
    if (!vlan) {
4726
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4727
        return -1;
4728
    }
4729
    if (!strcmp(device, "nic")) {
4730
        NICInfo *nd;
4731
        uint8_t *macaddr;
4732

    
4733
        if (nb_nics >= MAX_NICS) {
4734
            fprintf(stderr, "Too Many NICs\n");
4735
            return -1;
4736
        }
4737
        nd = &nd_table[nb_nics];
4738
        macaddr = nd->macaddr;
4739
        macaddr[0] = 0x52;
4740
        macaddr[1] = 0x54;
4741
        macaddr[2] = 0x00;
4742
        macaddr[3] = 0x12;
4743
        macaddr[4] = 0x34;
4744
        macaddr[5] = 0x56 + nb_nics;
4745

    
4746
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4747
            if (parse_macaddr(macaddr, buf) < 0) {
4748
                fprintf(stderr, "invalid syntax for ethernet address\n");
4749
                return -1;
4750
            }
4751
        }
4752
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4753
            nd->model = strdup(buf);
4754
        }
4755
        nd->vlan = vlan;
4756
        nb_nics++;
4757
        vlan->nb_guest_devs++;
4758
        ret = 0;
4759
    } else
4760
    if (!strcmp(device, "none")) {
4761
        /* does nothing. It is needed to signal that no network cards
4762
           are wanted */
4763
        ret = 0;
4764
    } else
4765
#ifdef CONFIG_SLIRP
4766
    if (!strcmp(device, "user")) {
4767
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4768
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4769
        }
4770
        vlan->nb_host_devs++;
4771
        ret = net_slirp_init(vlan);
4772
    } else
4773
#endif
4774
#ifdef _WIN32
4775
    if (!strcmp(device, "tap")) {
4776
        char ifname[64];
4777
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4778
            fprintf(stderr, "tap: no interface name\n");
4779
            return -1;
4780
        }
4781
        vlan->nb_host_devs++;
4782
        ret = tap_win32_init(vlan, ifname);
4783
    } else
4784
#else
4785
    if (!strcmp(device, "tap")) {
4786
        char ifname[64];
4787
        char setup_script[1024], down_script[1024];
4788
        int fd;
4789
        vlan->nb_host_devs++;
4790
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4791
            fd = strtol(buf, NULL, 0);
4792
            ret = -1;
4793
            if (net_tap_fd_init(vlan, fd))
4794
                ret = 0;
4795
        } else {
4796
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4797
                ifname[0] = '\0';
4798
            }
4799
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4800
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4801
            }
4802
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4803
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4804
            }
4805
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
4806
        }
4807
    } else
4808
#endif
4809
    if (!strcmp(device, "socket")) {
4810
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4811
            int fd;
4812
            fd = strtol(buf, NULL, 0);
4813
            ret = -1;
4814
            if (net_socket_fd_init(vlan, fd, 1))
4815
                ret = 0;
4816
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4817
            ret = net_socket_listen_init(vlan, buf);
4818
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4819
            ret = net_socket_connect_init(vlan, buf);
4820
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4821
            ret = net_socket_mcast_init(vlan, buf);
4822
        } else {
4823
            fprintf(stderr, "Unknown socket options: %s\n", p);
4824
            return -1;
4825
        }
4826
        vlan->nb_host_devs++;
4827
    } else
4828
    {
4829
        fprintf(stderr, "Unknown network device: %s\n", device);
4830
        return -1;
4831
    }
4832
    if (ret < 0) {
4833
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4834
    }
4835

    
4836
    return ret;
4837
}
4838

    
4839
void do_info_network(void)
4840
{
4841
    VLANState *vlan;
4842
    VLANClientState *vc;
4843

    
4844
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4845
        term_printf("VLAN %d devices:\n", vlan->id);
4846
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4847
            term_printf("  %s\n", vc->info_str);
4848
    }
4849
}
4850

    
4851
#define HD_ALIAS "index=%d,media=disk"
4852
#ifdef TARGET_PPC
4853
#define CDROM_ALIAS "index=1,media=cdrom"
4854
#else
4855
#define CDROM_ALIAS "index=2,media=cdrom"
4856
#endif
4857
#define FD_ALIAS "index=%d,if=floppy"
4858
#define PFLASH_ALIAS "if=pflash"
4859
#define MTD_ALIAS "if=mtd"
4860
#define SD_ALIAS "index=0,if=sd"
4861

    
4862
static int drive_add(const char *file, const char *fmt, ...)
4863
{
4864
    va_list ap;
4865

    
4866
    if (nb_drives_opt >= MAX_DRIVES) {
4867
        fprintf(stderr, "qemu: too many drives\n");
4868
        exit(1);
4869
    }
4870

    
4871
    drives_opt[nb_drives_opt].file = file;
4872
    va_start(ap, fmt);
4873
    vsnprintf(drives_opt[nb_drives_opt].opt,
4874
              sizeof(drives_opt[0].opt), fmt, ap);
4875
    va_end(ap);
4876

    
4877
    return nb_drives_opt++;
4878
}
4879

    
4880
int drive_get_index(BlockInterfaceType type, int bus, int unit)
4881
{
4882
    int index;
4883

    
4884
    /* seek interface, bus and unit */
4885

    
4886
    for (index = 0; index < nb_drives; index++)
4887
        if (drives_table[index].type == type &&
4888
            drives_table[index].bus == bus &&
4889
            drives_table[index].unit == unit)
4890
        return index;
4891

    
4892
    return -1;
4893
}
4894

    
4895
int drive_get_max_bus(BlockInterfaceType type)
4896
{
4897
    int max_bus;
4898
    int index;
4899

    
4900
    max_bus = -1;
4901
    for (index = 0; index < nb_drives; index++) {
4902
        if(drives_table[index].type == type &&
4903
           drives_table[index].bus > max_bus)
4904
            max_bus = drives_table[index].bus;
4905
    }
4906
    return max_bus;
4907
}
4908

    
4909
static int drive_init(struct drive_opt *arg, int snapshot,
4910
                      QEMUMachine *machine)
4911
{
4912
    char buf[128];
4913
    char file[1024];
4914
    char devname[128];
4915
    const char *mediastr = "";
4916
    BlockInterfaceType type;
4917
    enum { MEDIA_DISK, MEDIA_CDROM } media;
4918
    int bus_id, unit_id;
4919
    int cyls, heads, secs, translation;
4920
    BlockDriverState *bdrv;
4921
    int max_devs;
4922
    int index;
4923
    int cache;
4924
    int bdrv_flags;
4925
    char *str = arg->opt;
4926
    char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4927
                       "secs", "trans", "media", "snapshot", "file",
4928
                       "cache", NULL };
4929

    
4930
    if (check_params(buf, sizeof(buf), params, str) < 0) {
4931
         fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4932
                         buf, str);
4933
         return -1;
4934
    }
4935

    
4936
    file[0] = 0;
4937
    cyls = heads = secs = 0;
4938
    bus_id = 0;
4939
    unit_id = -1;
4940
    translation = BIOS_ATA_TRANSLATION_AUTO;
4941
    index = -1;
4942
    cache = 1;
4943

    
4944
    if (!strcmp(machine->name, "realview") ||
4945
        !strcmp(machine->name, "SS-5") ||
4946
        !strcmp(machine->name, "SS-10") ||
4947
        !strcmp(machine->name, "SS-600MP") ||
4948
        !strcmp(machine->name, "versatilepb") ||
4949
        !strcmp(machine->name, "versatileab")) {
4950
        type = IF_SCSI;
4951
        max_devs = MAX_SCSI_DEVS;
4952
        strcpy(devname, "scsi");
4953
    } else {
4954
        type = IF_IDE;
4955
        max_devs = MAX_IDE_DEVS;
4956
        strcpy(devname, "ide");
4957
    }
4958
    media = MEDIA_DISK;
4959

    
4960
    /* extract parameters */
4961

    
4962
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
4963
        bus_id = strtol(buf, NULL, 0);
4964
        if (bus_id < 0) {
4965
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4966
            return -1;
4967
        }
4968
    }
4969

    
4970
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
4971
        unit_id = strtol(buf, NULL, 0);
4972
        if (unit_id < 0) {
4973
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4974
            return -1;
4975
        }
4976
    }
4977

    
4978
    if (get_param_value(buf, sizeof(buf), "if", str)) {
4979
        strncpy(devname, buf, sizeof(devname));
4980
        if (!strcmp(buf, "ide")) {
4981
            type = IF_IDE;
4982
            max_devs = MAX_IDE_DEVS;
4983
        } else if (!strcmp(buf, "scsi")) {
4984
            type = IF_SCSI;
4985
            max_devs = MAX_SCSI_DEVS;
4986
        } else if (!strcmp(buf, "floppy")) {
4987
            type = IF_FLOPPY;
4988
            max_devs = 0;
4989
        } else if (!strcmp(buf, "pflash")) {
4990
            type = IF_PFLASH;
4991
            max_devs = 0;
4992
        } else if (!strcmp(buf, "mtd")) {
4993
            type = IF_MTD;
4994
            max_devs = 0;
4995
        } else if (!strcmp(buf, "sd")) {
4996
            type = IF_SD;
4997
            max_devs = 0;
4998
        } else {
4999
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5000
            return -1;
5001
        }
5002
    }
5003

    
5004
    if (get_param_value(buf, sizeof(buf), "index", str)) {
5005
        index = strtol(buf, NULL, 0);
5006
        if (index < 0) {
5007
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
5008
            return -1;
5009
        }
5010
    }
5011

    
5012
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5013
        cyls = strtol(buf, NULL, 0);
5014
    }
5015

    
5016
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
5017
        heads = strtol(buf, NULL, 0);
5018
    }
5019

    
5020
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
5021
        secs = strtol(buf, NULL, 0);
5022
    }
5023

    
5024
    if (cyls || heads || secs) {
5025
        if (cyls < 1 || cyls > 16383) {
5026
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5027
            return -1;
5028
        }
5029
        if (heads < 1 || heads > 16) {
5030
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5031
            return -1;
5032
        }
5033
        if (secs < 1 || secs > 63) {
5034
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5035
            return -1;
5036
        }
5037
    }
5038

    
5039
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
5040
        if (!cyls) {
5041
            fprintf(stderr,
5042
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
5043
                    str);
5044
            return -1;
5045
        }
5046
        if (!strcmp(buf, "none"))
5047
            translation = BIOS_ATA_TRANSLATION_NONE;
5048
        else if (!strcmp(buf, "lba"))
5049
            translation = BIOS_ATA_TRANSLATION_LBA;
5050
        else if (!strcmp(buf, "auto"))
5051
            translation = BIOS_ATA_TRANSLATION_AUTO;
5052
        else {
5053
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5054
            return -1;
5055
        }
5056
    }
5057

    
5058
    if (get_param_value(buf, sizeof(buf), "media", str)) {
5059
        if (!strcmp(buf, "disk")) {
5060
            media = MEDIA_DISK;
5061
        } else if (!strcmp(buf, "cdrom")) {
5062
            if (cyls || secs || heads) {
5063
                fprintf(stderr,
5064
                        "qemu: '%s' invalid physical CHS format\n", str);
5065
                return -1;
5066
            }
5067
            media = MEDIA_CDROM;
5068
        } else {
5069
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
5070
            return -1;
5071
        }
5072
    }
5073

    
5074
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5075
        if (!strcmp(buf, "on"))
5076
            snapshot = 1;
5077
        else if (!strcmp(buf, "off"))
5078
            snapshot = 0;
5079
        else {
5080
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5081
            return -1;
5082
        }
5083
    }
5084

    
5085
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
5086
        if (!strcmp(buf, "off"))
5087
            cache = 0;
5088
        else if (!strcmp(buf, "on"))
5089
            cache = 1;
5090
        else {
5091
           fprintf(stderr, "qemu: invalid cache option\n");
5092
           return -1;
5093
        }
5094
    }
5095

    
5096
    if (arg->file == NULL)
5097
        get_param_value(file, sizeof(file), "file", str);
5098
    else
5099
        pstrcpy(file, sizeof(file), arg->file);
5100

    
5101
    /* compute bus and unit according index */
5102

    
5103
    if (index != -1) {
5104
        if (bus_id != 0 || unit_id != -1) {
5105
            fprintf(stderr,
5106
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
5107
            return -1;
5108
        }
5109
        if (max_devs == 0)
5110
        {
5111
            unit_id = index;
5112
            bus_id = 0;
5113
        } else {
5114
            unit_id = index % max_devs;
5115
            bus_id = index / max_devs;
5116
        }
5117
    }
5118

    
5119
    /* if user doesn't specify a unit_id,
5120
     * try to find the first free
5121
     */
5122

    
5123
    if (unit_id == -1) {
5124
       unit_id = 0;
5125
       while (drive_get_index(type, bus_id, unit_id) != -1) {
5126
           unit_id++;
5127
           if (max_devs && unit_id >= max_devs) {
5128
               unit_id -= max_devs;
5129
               bus_id++;
5130
           }
5131
       }
5132
    }
5133

    
5134
    /* check unit id */
5135

    
5136
    if (max_devs && unit_id >= max_devs) {
5137
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5138
                        str, unit_id, max_devs - 1);
5139
        return -1;
5140
    }
5141

    
5142
    /*
5143
     * ignore multiple definitions
5144
     */
5145

    
5146
    if (drive_get_index(type, bus_id, unit_id) != -1)
5147
        return 0;
5148

    
5149
    /* init */
5150

    
5151
    if (type == IF_IDE || type == IF_SCSI)
5152
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5153
    if (max_devs)
5154
        snprintf(buf, sizeof(buf), "%s%i%s%i",
5155
                 devname, bus_id, mediastr, unit_id);
5156
    else
5157
        snprintf(buf, sizeof(buf), "%s%s%i",
5158
                 devname, mediastr, unit_id);
5159
    bdrv = bdrv_new(buf);
5160
    drives_table[nb_drives].bdrv = bdrv;
5161
    drives_table[nb_drives].type = type;
5162
    drives_table[nb_drives].bus = bus_id;
5163
    drives_table[nb_drives].unit = unit_id;
5164
    nb_drives++;
5165

    
5166
    switch(type) {
5167
    case IF_IDE:
5168
    case IF_SCSI:
5169
        switch(media) {
5170
        case MEDIA_DISK:
5171
            if (cyls != 0) {
5172
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5173
                bdrv_set_translation_hint(bdrv, translation);
5174
            }
5175
            break;
5176
        case MEDIA_CDROM:
5177
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5178
            break;
5179
        }
5180
        break;
5181
    case IF_SD:
5182
        /* FIXME: This isn't really a floppy, but it's a reasonable
5183
           approximation.  */
5184
    case IF_FLOPPY:
5185
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5186
        break;
5187
    case IF_PFLASH:
5188
    case IF_MTD:
5189
        break;
5190
    }
5191
    if (!file[0])
5192
        return 0;
5193
    bdrv_flags = 0;
5194
    if (snapshot)
5195
        bdrv_flags |= BDRV_O_SNAPSHOT;
5196
    if (!cache)
5197
        bdrv_flags |= BDRV_O_DIRECT;
5198
    if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5199
        fprintf(stderr, "qemu: could not open disk image %s\n",
5200
                        file);
5201
        return -1;
5202
    }
5203
    return 0;
5204
}
5205

    
5206
/***********************************************************/
5207
/* USB devices */
5208

    
5209
static USBPort *used_usb_ports;
5210
static USBPort *free_usb_ports;
5211

    
5212
/* ??? Maybe change this to register a hub to keep track of the topology.  */
5213
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5214
                            usb_attachfn attach)
5215
{
5216
    port->opaque = opaque;
5217
    port->index = index;
5218
    port->attach = attach;
5219
    port->next = free_usb_ports;
5220
    free_usb_ports = port;
5221
}
5222

    
5223
static int usb_device_add(const char *devname)
5224
{
5225
    const char *p;
5226
    USBDevice *dev;
5227
    USBPort *port;
5228

    
5229
    if (!free_usb_ports)
5230
        return -1;
5231

    
5232
    if (strstart(devname, "host:", &p)) {
5233
        dev = usb_host_device_open(p);
5234
    } else if (!strcmp(devname, "mouse")) {
5235
        dev = usb_mouse_init();
5236
    } else if (!strcmp(devname, "tablet")) {
5237
        dev = usb_tablet_init();
5238
    } else if (!strcmp(devname, "keyboard")) {
5239
        dev = usb_keyboard_init();
5240
    } else if (strstart(devname, "disk:", &p)) {
5241
        dev = usb_msd_init(p);
5242
    } else if (!strcmp(devname, "wacom-tablet")) {
5243
        dev = usb_wacom_init();
5244
    } else if (strstart(devname, "serial:", &p)) {
5245
        dev = usb_serial_init(p);
5246
    } else {
5247
        return -1;
5248
    }
5249
    if (!dev)
5250
        return -1;
5251

    
5252
    /* Find a USB port to add the device to.  */
5253
    port = free_usb_ports;
5254
    if (!port->next) {
5255
        USBDevice *hub;
5256

    
5257
        /* Create a new hub and chain it on.  */
5258
        free_usb_ports = NULL;
5259
        port->next = used_usb_ports;
5260
        used_usb_ports = port;
5261

    
5262
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5263
        usb_attach(port, hub);
5264
        port = free_usb_ports;
5265
    }
5266

    
5267
    free_usb_ports = port->next;
5268
    port->next = used_usb_ports;
5269
    used_usb_ports = port;
5270
    usb_attach(port, dev);
5271
    return 0;
5272
}
5273

    
5274
static int usb_device_del(const char *devname)
5275
{
5276
    USBPort *port;
5277
    USBPort **lastp;
5278
    USBDevice *dev;
5279
    int bus_num, addr;
5280
    const char *p;
5281

    
5282
    if (!used_usb_ports)
5283
        return -1;
5284

    
5285
    p = strchr(devname, '.');
5286
    if (!p)
5287
        return -1;
5288
    bus_num = strtoul(devname, NULL, 0);
5289
    addr = strtoul(p + 1, NULL, 0);
5290
    if (bus_num != 0)
5291
        return -1;
5292

    
5293
    lastp = &used_usb_ports;
5294
    port = used_usb_ports;
5295
    while (port && port->dev->addr != addr) {
5296
        lastp = &port->next;
5297
        port = port->next;
5298
    }
5299

    
5300
    if (!port)
5301
        return -1;
5302

    
5303
    dev = port->dev;
5304
    *lastp = port->next;
5305
    usb_attach(port, NULL);
5306
    dev->handle_destroy(dev);
5307
    port->next = free_usb_ports;
5308
    free_usb_ports = port;
5309
    return 0;
5310
}
5311

    
5312
void do_usb_add(const char *devname)
5313
{
5314
    int ret;
5315
    ret = usb_device_add(devname);
5316
    if (ret < 0)
5317
        term_printf("Could not add USB device '%s'\n", devname);
5318
}
5319

    
5320
void do_usb_del(const char *devname)
5321
{
5322
    int ret;
5323
    ret = usb_device_del(devname);
5324
    if (ret < 0)
5325
        term_printf("Could not remove USB device '%s'\n", devname);
5326
}
5327

    
5328
void usb_info(void)
5329
{
5330
    USBDevice *dev;
5331
    USBPort *port;
5332
    const char *speed_str;
5333

    
5334
    if (!usb_enabled) {
5335
        term_printf("USB support not enabled\n");
5336
        return;
5337
    }
5338

    
5339
    for (port = used_usb_ports; port; port = port->next) {
5340
        dev = port->dev;
5341
        if (!dev)
5342
            continue;
5343
        switch(dev->speed) {
5344
        case USB_SPEED_LOW:
5345
            speed_str = "1.5";
5346
            break;
5347
        case USB_SPEED_FULL:
5348
            speed_str = "12";
5349
            break;
5350
        case USB_SPEED_HIGH:
5351
            speed_str = "480";
5352
            break;
5353
        default:
5354
            speed_str = "?";
5355
            break;
5356
        }
5357
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
5358
                    0, dev->addr, speed_str, dev->devname);
5359
    }
5360
}
5361

    
5362
/***********************************************************/
5363
/* PCMCIA/Cardbus */
5364

    
5365
static struct pcmcia_socket_entry_s {
5366
    struct pcmcia_socket_s *socket;
5367
    struct pcmcia_socket_entry_s *next;
5368
} *pcmcia_sockets = 0;
5369

    
5370
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5371
{
5372
    struct pcmcia_socket_entry_s *entry;
5373

    
5374
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5375
    entry->socket = socket;
5376
    entry->next = pcmcia_sockets;
5377
    pcmcia_sockets = entry;
5378
}
5379

    
5380
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5381
{
5382
    struct pcmcia_socket_entry_s *entry, **ptr;
5383

    
5384
    ptr = &pcmcia_sockets;
5385
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5386
        if (entry->socket == socket) {
5387
            *ptr = entry->next;
5388
            qemu_free(entry);
5389
        }
5390
}
5391

    
5392
void pcmcia_info(void)
5393
{
5394
    struct pcmcia_socket_entry_s *iter;
5395
    if (!pcmcia_sockets)
5396
        term_printf("No PCMCIA sockets\n");
5397

    
5398
    for (iter = pcmcia_sockets; iter; iter = iter->next)
5399
        term_printf("%s: %s\n", iter->socket->slot_string,
5400
                    iter->socket->attached ? iter->socket->card_string :
5401
                    "Empty");
5402
}
5403

    
5404
/***********************************************************/
5405
/* dumb display */
5406

    
5407
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5408
{
5409
}
5410

    
5411
static void dumb_resize(DisplayState *ds, int w, int h)
5412
{
5413
}
5414

    
5415
static void dumb_refresh(DisplayState *ds)
5416
{
5417
#if defined(CONFIG_SDL)
5418
    vga_hw_update();
5419
#endif
5420
}
5421

    
5422
static void dumb_display_init(DisplayState *ds)
5423
{
5424
    ds->data = NULL;
5425
    ds->linesize = 0;
5426
    ds->depth = 0;
5427
    ds->dpy_update = dumb_update;
5428
    ds->dpy_resize = dumb_resize;
5429
    ds->dpy_refresh = dumb_refresh;
5430
}
5431

    
5432
/***********************************************************/
5433
/* I/O handling */
5434

    
5435
#define MAX_IO_HANDLERS 64
5436

    
5437
typedef struct IOHandlerRecord {
5438
    int fd;
5439
    IOCanRWHandler *fd_read_poll;
5440
    IOHandler *fd_read;
5441
    IOHandler *fd_write;
5442
    int deleted;
5443
    void *opaque;
5444
    /* temporary data */
5445
    struct pollfd *ufd;
5446
    struct IOHandlerRecord *next;
5447
} IOHandlerRecord;
5448

    
5449
static IOHandlerRecord *first_io_handler;
5450

    
5451
/* XXX: fd_read_poll should be suppressed, but an API change is
5452
   necessary in the character devices to suppress fd_can_read(). */
5453
int qemu_set_fd_handler2(int fd,
5454
                         IOCanRWHandler *fd_read_poll,
5455
                         IOHandler *fd_read,
5456
                         IOHandler *fd_write,
5457
                         void *opaque)
5458
{
5459
    IOHandlerRecord **pioh, *ioh;
5460

    
5461
    if (!fd_read && !fd_write) {
5462
        pioh = &first_io_handler;
5463
        for(;;) {
5464
            ioh = *pioh;
5465
            if (ioh == NULL)
5466
                break;
5467
            if (ioh->fd == fd) {
5468
                ioh->deleted = 1;
5469
                break;
5470
            }
5471
            pioh = &ioh->next;
5472
        }
5473
    } else {
5474
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5475
            if (ioh->fd == fd)
5476
                goto found;
5477
        }
5478
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5479
        if (!ioh)
5480
            return -1;
5481
        ioh->next = first_io_handler;
5482
        first_io_handler = ioh;
5483
    found:
5484
        ioh->fd = fd;
5485
        ioh->fd_read_poll = fd_read_poll;
5486
        ioh->fd_read = fd_read;
5487
        ioh->fd_write = fd_write;
5488
        ioh->opaque = opaque;
5489
        ioh->deleted = 0;
5490
    }
5491
    return 0;
5492
}
5493

    
5494
int qemu_set_fd_handler(int fd,
5495
                        IOHandler *fd_read,
5496
                        IOHandler *fd_write,
5497
                        void *opaque)
5498
{
5499
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5500
}
5501

    
5502
/***********************************************************/
5503
/* Polling handling */
5504

    
5505
typedef struct PollingEntry {
5506
    PollingFunc *func;
5507
    void *opaque;
5508
    struct PollingEntry *next;
5509
} PollingEntry;
5510

    
5511
static PollingEntry *first_polling_entry;
5512

    
5513
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5514
{
5515
    PollingEntry **ppe, *pe;
5516
    pe = qemu_mallocz(sizeof(PollingEntry));
5517
    if (!pe)
5518
        return -1;
5519
    pe->func = func;
5520
    pe->opaque = opaque;
5521
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5522
    *ppe = pe;
5523
    return 0;
5524
}
5525

    
5526
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5527
{
5528
    PollingEntry **ppe, *pe;
5529
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5530
        pe = *ppe;
5531
        if (pe->func == func && pe->opaque == opaque) {
5532
            *ppe = pe->next;
5533
            qemu_free(pe);
5534
            break;
5535
        }
5536
    }
5537
}
5538

    
5539
#ifdef _WIN32
5540
/***********************************************************/
5541
/* Wait objects support */
5542
typedef struct WaitObjects {
5543
    int num;
5544
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5545
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5546
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5547
} WaitObjects;
5548

    
5549
static WaitObjects wait_objects = {0};
5550

    
5551
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5552
{
5553
    WaitObjects *w = &wait_objects;
5554

    
5555
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
5556
        return -1;
5557
    w->events[w->num] = handle;
5558
    w->func[w->num] = func;
5559
    w->opaque[w->num] = opaque;
5560
    w->num++;
5561
    return 0;
5562
}
5563

    
5564
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5565
{
5566
    int i, found;
5567
    WaitObjects *w = &wait_objects;
5568

    
5569
    found = 0;
5570
    for (i = 0; i < w->num; i++) {
5571
        if (w->events[i] == handle)
5572
            found = 1;
5573
        if (found) {
5574
            w->events[i] = w->events[i + 1];
5575
            w->func[i] = w->func[i + 1];
5576
            w->opaque[i] = w->opaque[i + 1];
5577
        }
5578
    }
5579
    if (found)
5580
        w->num--;
5581
}
5582
#endif
5583

    
5584
/***********************************************************/
5585
/* savevm/loadvm support */
5586

    
5587
#define IO_BUF_SIZE 32768
5588

    
5589
struct QEMUFile {
5590
    FILE *outfile;
5591
    BlockDriverState *bs;
5592
    int is_file;
5593
    int is_writable;
5594
    int64_t base_offset;
5595
    int64_t buf_offset; /* start of buffer when writing, end of buffer
5596
                           when reading */
5597
    int buf_index;
5598
    int buf_size; /* 0 when writing */
5599
    uint8_t buf[IO_BUF_SIZE];
5600
};
5601

    
5602
QEMUFile *qemu_fopen(const char *filename, const char *mode)
5603
{
5604
    QEMUFile *f;
5605

    
5606
    f = qemu_mallocz(sizeof(QEMUFile));
5607
    if (!f)
5608
        return NULL;
5609
    if (!strcmp(mode, "wb")) {
5610
        f->is_writable = 1;
5611
    } else if (!strcmp(mode, "rb")) {
5612
        f->is_writable = 0;
5613
    } else {
5614
        goto fail;
5615
    }
5616
    f->outfile = fopen(filename, mode);
5617
    if (!f->outfile)
5618
        goto fail;
5619
    f->is_file = 1;
5620
    return f;
5621
 fail:
5622
    if (f->outfile)
5623
        fclose(f->outfile);
5624
    qemu_free(f);
5625
    return NULL;
5626
}
5627

    
5628
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5629
{
5630
    QEMUFile *f;
5631

    
5632
    f = qemu_mallocz(sizeof(QEMUFile));
5633
    if (!f)
5634
        return NULL;
5635
    f->is_file = 0;
5636
    f->bs = bs;
5637
    f->is_writable = is_writable;
5638
    f->base_offset = offset;
5639
    return f;
5640
}
5641

    
5642
void qemu_fflush(QEMUFile *f)
5643
{
5644
    if (!f->is_writable)
5645
        return;
5646
    if (f->buf_index > 0) {
5647
        if (f->is_file) {
5648
            fseek(f->outfile, f->buf_offset, SEEK_SET);
5649
            fwrite(f->buf, 1, f->buf_index, f->outfile);
5650
        } else {
5651
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5652
                        f->buf, f->buf_index);
5653
        }
5654
        f->buf_offset += f->buf_index;
5655
        f->buf_index = 0;
5656
    }
5657
}
5658

    
5659
static void qemu_fill_buffer(QEMUFile *f)
5660
{
5661
    int len;
5662

    
5663
    if (f->is_writable)
5664
        return;
5665
    if (f->is_file) {
5666
        fseek(f->outfile, f->buf_offset, SEEK_SET);
5667
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5668
        if (len < 0)
5669
            len = 0;
5670
    } else {
5671
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5672
                         f->buf, IO_BUF_SIZE);
5673
        if (len < 0)
5674
            len = 0;
5675
    }
5676
    f->buf_index = 0;
5677
    f->buf_size = len;
5678
    f->buf_offset += len;
5679
}
5680

    
5681
void qemu_fclose(QEMUFile *f)
5682
{
5683
    if (f->is_writable)
5684
        qemu_fflush(f);
5685
    if (f->is_file) {
5686
        fclose(f->outfile);
5687
    }
5688
    qemu_free(f);
5689
}
5690

    
5691
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5692
{
5693
    int l;
5694
    while (size > 0) {
5695
        l = IO_BUF_SIZE - f->buf_index;
5696
        if (l > size)
5697
            l = size;
5698
        memcpy(f->buf + f->buf_index, buf, l);
5699
        f->buf_index += l;
5700
        buf += l;
5701
        size -= l;
5702
        if (f->buf_index >= IO_BUF_SIZE)
5703
            qemu_fflush(f);
5704
    }
5705
}
5706

    
5707
void qemu_put_byte(QEMUFile *f, int v)
5708
{
5709
    f->buf[f->buf_index++] = v;
5710
    if (f->buf_index >= IO_BUF_SIZE)
5711
        qemu_fflush(f);
5712
}
5713

    
5714
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5715
{
5716
    int size, l;
5717

    
5718
    size = size1;
5719
    while (size > 0) {
5720
        l = f->buf_size - f->buf_index;
5721
        if (l == 0) {
5722
            qemu_fill_buffer(f);
5723
            l = f->buf_size - f->buf_index;
5724
            if (l == 0)
5725
                break;
5726
        }
5727
        if (l > size)
5728
            l = size;
5729
        memcpy(buf, f->buf + f->buf_index, l);
5730
        f->buf_index += l;
5731
        buf += l;
5732
        size -= l;
5733
    }
5734
    return size1 - size;
5735
}
5736

    
5737
int qemu_get_byte(QEMUFile *f)
5738
{
5739
    if (f->buf_index >= f->buf_size) {
5740
        qemu_fill_buffer(f);
5741
        if (f->buf_index >= f->buf_size)
5742
            return 0;
5743
    }
5744
    return f->buf[f->buf_index++];
5745
}
5746

    
5747
int64_t qemu_ftell(QEMUFile *f)
5748
{
5749
    return f->buf_offset - f->buf_size + f->buf_index;
5750
}
5751

    
5752
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5753
{
5754
    if (whence == SEEK_SET) {
5755
        /* nothing to do */
5756
    } else if (whence == SEEK_CUR) {
5757
        pos += qemu_ftell(f);
5758
    } else {
5759
        /* SEEK_END not supported */
5760
        return -1;
5761
    }
5762
    if (f->is_writable) {
5763
        qemu_fflush(f);
5764
        f->buf_offset = pos;
5765
    } else {
5766
        f->buf_offset = pos;
5767
        f->buf_index = 0;
5768
        f->buf_size = 0;
5769
    }
5770
    return pos;
5771
}
5772

    
5773
void qemu_put_be16(QEMUFile *f, unsigned int v)
5774
{
5775
    qemu_put_byte(f, v >> 8);
5776
    qemu_put_byte(f, v);
5777
}
5778

    
5779
void qemu_put_be32(QEMUFile *f, unsigned int v)
5780
{
5781
    qemu_put_byte(f, v >> 24);
5782
    qemu_put_byte(f, v >> 16);
5783
    qemu_put_byte(f, v >> 8);
5784
    qemu_put_byte(f, v);
5785
}
5786

    
5787
void qemu_put_be64(QEMUFile *f, uint64_t v)
5788
{
5789
    qemu_put_be32(f, v >> 32);
5790
    qemu_put_be32(f, v);
5791
}
5792

    
5793
unsigned int qemu_get_be16(QEMUFile *f)
5794
{
5795
    unsigned int v;
5796
    v = qemu_get_byte(f) << 8;
5797
    v |= qemu_get_byte(f);
5798
    return v;
5799
}
5800

    
5801
unsigned int qemu_get_be32(QEMUFile *f)
5802
{
5803
    unsigned int v;
5804
    v = qemu_get_byte(f) << 24;
5805
    v |= qemu_get_byte(f) << 16;
5806
    v |= qemu_get_byte(f) << 8;
5807
    v |= qemu_get_byte(f);
5808
    return v;
5809
}
5810

    
5811
uint64_t qemu_get_be64(QEMUFile *f)
5812
{
5813
    uint64_t v;
5814
    v = (uint64_t)qemu_get_be32(f) << 32;
5815
    v |= qemu_get_be32(f);
5816
    return v;
5817
}
5818

    
5819
typedef struct SaveStateEntry {
5820
    char idstr[256];
5821
    int instance_id;
5822
    int version_id;
5823
    SaveStateHandler *save_state;
5824
    LoadStateHandler *load_state;
5825
    void *opaque;
5826
    struct SaveStateEntry *next;
5827
} SaveStateEntry;
5828

    
5829
static SaveStateEntry *first_se;
5830

    
5831
int register_savevm(const char *idstr,
5832
                    int instance_id,
5833
                    int version_id,
5834
                    SaveStateHandler *save_state,
5835
                    LoadStateHandler *load_state,
5836
                    void *opaque)
5837
{
5838
    SaveStateEntry *se, **pse;
5839

    
5840
    se = qemu_malloc(sizeof(SaveStateEntry));
5841
    if (!se)
5842
        return -1;
5843
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5844
    se->instance_id = instance_id;
5845
    se->version_id = version_id;
5846
    se->save_state = save_state;
5847
    se->load_state = load_state;
5848
    se->opaque = opaque;
5849
    se->next = NULL;
5850

    
5851
    /* add at the end of list */
5852
    pse = &first_se;
5853
    while (*pse != NULL)
5854
        pse = &(*pse)->next;
5855
    *pse = se;
5856
    return 0;
5857
}
5858

    
5859
#define QEMU_VM_FILE_MAGIC   0x5145564d
5860
#define QEMU_VM_FILE_VERSION 0x00000002
5861

    
5862
static int qemu_savevm_state(QEMUFile *f)
5863
{
5864
    SaveStateEntry *se;
5865
    int len, ret;
5866
    int64_t cur_pos, len_pos, total_len_pos;
5867

    
5868
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5869
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5870
    total_len_pos = qemu_ftell(f);
5871
    qemu_put_be64(f, 0); /* total size */
5872

    
5873
    for(se = first_se; se != NULL; se = se->next) {
5874
        /* ID string */
5875
        len = strlen(se->idstr);
5876
        qemu_put_byte(f, len);
5877
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5878

    
5879
        qemu_put_be32(f, se->instance_id);
5880
        qemu_put_be32(f, se->version_id);
5881

    
5882
        /* record size: filled later */
5883
        len_pos = qemu_ftell(f);
5884
        qemu_put_be32(f, 0);
5885
        se->save_state(f, se->opaque);
5886

    
5887
        /* fill record size */
5888
        cur_pos = qemu_ftell(f);
5889
        len = cur_pos - len_pos - 4;
5890
        qemu_fseek(f, len_pos, SEEK_SET);
5891
        qemu_put_be32(f, len);
5892
        qemu_fseek(f, cur_pos, SEEK_SET);
5893
    }
5894
    cur_pos = qemu_ftell(f);
5895
    qemu_fseek(f, total_len_pos, SEEK_SET);
5896
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
5897
    qemu_fseek(f, cur_pos, SEEK_SET);
5898

    
5899
    ret = 0;
5900
    return ret;
5901
}
5902

    
5903
static SaveStateEntry *find_se(const char *idstr, int instance_id)
5904
{
5905
    SaveStateEntry *se;
5906

    
5907
    for(se = first_se; se != NULL; se = se->next) {
5908
        if (!strcmp(se->idstr, idstr) &&
5909
            instance_id == se->instance_id)
5910
            return se;
5911
    }
5912
    return NULL;
5913
}
5914

    
5915
static int qemu_loadvm_state(QEMUFile *f)
5916
{
5917
    SaveStateEntry *se;
5918
    int len, ret, instance_id, record_len, version_id;
5919
    int64_t total_len, end_pos, cur_pos;
5920
    unsigned int v;
5921
    char idstr[256];
5922

    
5923
    v = qemu_get_be32(f);
5924
    if (v != QEMU_VM_FILE_MAGIC)
5925
        goto fail;
5926
    v = qemu_get_be32(f);
5927
    if (v != QEMU_VM_FILE_VERSION) {
5928
    fail:
5929
        ret = -1;
5930
        goto the_end;
5931
    }
5932
    total_len = qemu_get_be64(f);
5933
    end_pos = total_len + qemu_ftell(f);
5934
    for(;;) {
5935
        if (qemu_ftell(f) >= end_pos)
5936
            break;
5937
        len = qemu_get_byte(f);
5938
        qemu_get_buffer(f, (uint8_t *)idstr, len);
5939
        idstr[len] = '\0';
5940
        instance_id = qemu_get_be32(f);
5941
        version_id = qemu_get_be32(f);
5942
        record_len = qemu_get_be32(f);
5943
#if 0
5944
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
5945
               idstr, instance_id, version_id, record_len);
5946
#endif
5947
        cur_pos = qemu_ftell(f);
5948
        se = find_se(idstr, instance_id);
5949
        if (!se) {
5950
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5951
                    instance_id, idstr);
5952
        } else {
5953
            ret = se->load_state(f, se->opaque, version_id);
5954
            if (ret < 0) {
5955
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5956
                        instance_id, idstr);
5957
            }
5958
        }
5959
        /* always seek to exact end of record */
5960
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5961
    }
5962
    ret = 0;
5963
 the_end:
5964
    return ret;
5965
}
5966

    
5967
/* device can contain snapshots */
5968
static int bdrv_can_snapshot(BlockDriverState *bs)
5969
{
5970
    return (bs &&
5971
            !bdrv_is_removable(bs) &&
5972
            !bdrv_is_read_only(bs));
5973
}
5974

    
5975
/* device must be snapshots in order to have a reliable snapshot */
5976
static int bdrv_has_snapshot(BlockDriverState *bs)
5977
{
5978
    return (bs &&
5979
            !bdrv_is_removable(bs) &&
5980
            !bdrv_is_read_only(bs));
5981
}
5982

    
5983
static BlockDriverState *get_bs_snapshots(void)
5984
{
5985
    BlockDriverState *bs;
5986
    int i;
5987

    
5988
    if (bs_snapshots)
5989
        return bs_snapshots;
5990
    for(i = 0; i <= nb_drives; i++) {
5991
        bs = drives_table[i].bdrv;
5992
        if (bdrv_can_snapshot(bs))
5993
            goto ok;
5994
    }
5995
    return NULL;
5996
 ok:
5997
    bs_snapshots = bs;
5998
    return bs;
5999
}
6000

    
6001
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6002
                              const char *name)
6003
{
6004
    QEMUSnapshotInfo *sn_tab, *sn;
6005
    int nb_sns, i, ret;
6006

    
6007
    ret = -ENOENT;
6008
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6009
    if (nb_sns < 0)
6010
        return ret;
6011
    for(i = 0; i < nb_sns; i++) {
6012
        sn = &sn_tab[i];
6013
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6014
            *sn_info = *sn;
6015
            ret = 0;
6016
            break;
6017
        }
6018
    }
6019
    qemu_free(sn_tab);
6020
    return ret;
6021
}
6022

    
6023
void do_savevm(const char *name)
6024
{
6025
    BlockDriverState *bs, *bs1;
6026
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6027
    int must_delete, ret, i;
6028
    BlockDriverInfo bdi1, *bdi = &bdi1;
6029
    QEMUFile *f;
6030
    int saved_vm_running;
6031
#ifdef _WIN32
6032
    struct _timeb tb;
6033
#else
6034
    struct timeval tv;
6035
#endif
6036

    
6037
    bs = get_bs_snapshots();
6038
    if (!bs) {
6039
        term_printf("No block device can accept snapshots\n");
6040
        return;
6041
    }
6042

    
6043
    /* ??? Should this occur after vm_stop?  */
6044
    qemu_aio_flush();
6045

    
6046
    saved_vm_running = vm_running;
6047
    vm_stop(0);
6048

    
6049
    must_delete = 0;
6050
    if (name) {
6051
        ret = bdrv_snapshot_find(bs, old_sn, name);
6052
        if (ret >= 0) {
6053
            must_delete = 1;
6054
        }
6055
    }
6056
    memset(sn, 0, sizeof(*sn));
6057
    if (must_delete) {
6058
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6059
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6060
    } else {
6061
        if (name)
6062
            pstrcpy(sn->name, sizeof(sn->name), name);
6063
    }
6064

    
6065
    /* fill auxiliary fields */
6066
#ifdef _WIN32
6067
    _ftime(&tb);
6068
    sn->date_sec = tb.time;
6069
    sn->date_nsec = tb.millitm * 1000000;
6070
#else
6071
    gettimeofday(&tv, NULL);
6072
    sn->date_sec = tv.tv_sec;
6073
    sn->date_nsec = tv.tv_usec * 1000;
6074
#endif
6075
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6076

    
6077
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6078
        term_printf("Device %s does not support VM state snapshots\n",
6079
                    bdrv_get_device_name(bs));
6080
        goto the_end;
6081
    }
6082

    
6083
    /* save the VM state */
6084
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6085
    if (!f) {
6086
        term_printf("Could not open VM state file\n");
6087
        goto the_end;
6088
    }
6089
    ret = qemu_savevm_state(f);
6090
    sn->vm_state_size = qemu_ftell(f);
6091
    qemu_fclose(f);
6092
    if (ret < 0) {
6093
        term_printf("Error %d while writing VM\n", ret);
6094
        goto the_end;
6095
    }
6096

    
6097
    /* create the snapshots */
6098

    
6099
    for(i = 0; i < nb_drives; i++) {
6100
        bs1 = drives_table[i].bdrv;
6101
        if (bdrv_has_snapshot(bs1)) {
6102
            if (must_delete) {
6103
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6104
                if (ret < 0) {
6105
                    term_printf("Error while deleting snapshot on '%s'\n",
6106
                                bdrv_get_device_name(bs1));
6107
                }
6108
            }
6109
            ret = bdrv_snapshot_create(bs1, sn);
6110
            if (ret < 0) {
6111
                term_printf("Error while creating snapshot on '%s'\n",
6112
                            bdrv_get_device_name(bs1));
6113
            }
6114
        }
6115
    }
6116

    
6117
 the_end:
6118
    if (saved_vm_running)
6119
        vm_start();
6120
}
6121

    
6122
void do_loadvm(const char *name)
6123
{
6124
    BlockDriverState *bs, *bs1;
6125
    BlockDriverInfo bdi1, *bdi = &bdi1;
6126
    QEMUFile *f;
6127
    int i, ret;
6128
    int saved_vm_running;
6129

    
6130
    bs = get_bs_snapshots();
6131
    if (!bs) {
6132
        term_printf("No block device supports snapshots\n");
6133
        return;
6134
    }
6135

    
6136
    /* Flush all IO requests so they don't interfere with the new state.  */
6137
    qemu_aio_flush();
6138

    
6139
    saved_vm_running = vm_running;
6140
    vm_stop(0);
6141

    
6142
    for(i = 0; i <= nb_drives; i++) {
6143
        bs1 = drives_table[i].bdrv;
6144
        if (bdrv_has_snapshot(bs1)) {
6145
            ret = bdrv_snapshot_goto(bs1, name);
6146
            if (ret < 0) {
6147
                if (bs != bs1)
6148
                    term_printf("Warning: ");
6149
                switch(ret) {
6150
                case -ENOTSUP:
6151
                    term_printf("Snapshots not supported on device '%s'\n",
6152
                                bdrv_get_device_name(bs1));
6153
                    break;
6154
                case -ENOENT:
6155
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
6156
                                name, bdrv_get_device_name(bs1));
6157
                    break;
6158
                default:
6159
                    term_printf("Error %d while activating snapshot on '%s'\n",
6160
                                ret, bdrv_get_device_name(bs1));
6161
                    break;
6162
                }
6163
                /* fatal on snapshot block device */
6164
                if (bs == bs1)
6165
                    goto the_end;
6166
            }
6167
        }
6168
    }
6169

    
6170
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6171
        term_printf("Device %s does not support VM state snapshots\n",
6172
                    bdrv_get_device_name(bs));
6173
        return;
6174
    }
6175

    
6176
    /* restore the VM state */
6177
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6178
    if (!f) {
6179
        term_printf("Could not open VM state file\n");
6180
        goto the_end;
6181
    }
6182
    ret = qemu_loadvm_state(f);
6183
    qemu_fclose(f);
6184
    if (ret < 0) {
6185
        term_printf("Error %d while loading VM state\n", ret);
6186
    }
6187
 the_end:
6188
    if (saved_vm_running)
6189
        vm_start();
6190
}
6191

    
6192
void do_delvm(const char *name)
6193
{
6194
    BlockDriverState *bs, *bs1;
6195
    int i, ret;
6196

    
6197
    bs = get_bs_snapshots();
6198
    if (!bs) {
6199
        term_printf("No block device supports snapshots\n");
6200
        return;
6201
    }
6202

    
6203
    for(i = 0; i <= nb_drives; i++) {
6204
        bs1 = drives_table[i].bdrv;
6205
        if (bdrv_has_snapshot(bs1)) {
6206
            ret = bdrv_snapshot_delete(bs1, name);
6207
            if (ret < 0) {
6208
                if (ret == -ENOTSUP)
6209
                    term_printf("Snapshots not supported on device '%s'\n",
6210
                                bdrv_get_device_name(bs1));
6211
                else
6212
                    term_printf("Error %d while deleting snapshot on '%s'\n",
6213
                                ret, bdrv_get_device_name(bs1));
6214
            }
6215
        }
6216
    }
6217
}
6218

    
6219
void do_info_snapshots(void)
6220
{
6221
    BlockDriverState *bs, *bs1;
6222
    QEMUSnapshotInfo *sn_tab, *sn;
6223
    int nb_sns, i;
6224
    char buf[256];
6225

    
6226
    bs = get_bs_snapshots();
6227
    if (!bs) {
6228
        term_printf("No available block device supports snapshots\n");
6229
        return;
6230
    }
6231
    term_printf("Snapshot devices:");
6232
    for(i = 0; i <= nb_drives; i++) {
6233
        bs1 = drives_table[i].bdrv;
6234
        if (bdrv_has_snapshot(bs1)) {
6235
            if (bs == bs1)
6236
                term_printf(" %s", bdrv_get_device_name(bs1));
6237
        }
6238
    }
6239
    term_printf("\n");
6240

    
6241
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6242
    if (nb_sns < 0) {
6243
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6244
        return;
6245
    }
6246
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6247
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6248
    for(i = 0; i < nb_sns; i++) {
6249
        sn = &sn_tab[i];
6250
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6251
    }
6252
    qemu_free(sn_tab);
6253
}
6254

    
6255
/***********************************************************/
6256
/* cpu save/restore */
6257

    
6258
#if defined(TARGET_I386)
6259

    
6260
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6261
{
6262
    qemu_put_be32(f, dt->selector);
6263
    qemu_put_betl(f, dt->base);
6264
    qemu_put_be32(f, dt->limit);
6265
    qemu_put_be32(f, dt->flags);
6266
}
6267

    
6268
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6269
{
6270
    dt->selector = qemu_get_be32(f);
6271
    dt->base = qemu_get_betl(f);
6272
    dt->limit = qemu_get_be32(f);
6273
    dt->flags = qemu_get_be32(f);
6274
}
6275

    
6276
void cpu_save(QEMUFile *f, void *opaque)
6277
{
6278
    CPUState *env = opaque;
6279
    uint16_t fptag, fpus, fpuc, fpregs_format;
6280
    uint32_t hflags;
6281
    int i;
6282

    
6283
    for(i = 0; i < CPU_NB_REGS; i++)
6284
        qemu_put_betls(f, &env->regs[i]);
6285
    qemu_put_betls(f, &env->eip);
6286
    qemu_put_betls(f, &env->eflags);
6287
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6288
    qemu_put_be32s(f, &hflags);
6289

    
6290
    /* FPU */
6291
    fpuc = env->fpuc;
6292
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6293
    fptag = 0;
6294
    for(i = 0; i < 8; i++) {
6295
        fptag |= ((!env->fptags[i]) << i);
6296
    }
6297

    
6298
    qemu_put_be16s(f, &fpuc);
6299
    qemu_put_be16s(f, &fpus);
6300
    qemu_put_be16s(f, &fptag);
6301

    
6302
#ifdef USE_X86LDOUBLE
6303
    fpregs_format = 0;
6304
#else
6305
    fpregs_format = 1;
6306
#endif
6307
    qemu_put_be16s(f, &fpregs_format);
6308

    
6309
    for(i = 0; i < 8; i++) {
6310
#ifdef USE_X86LDOUBLE
6311
        {
6312
            uint64_t mant;
6313
            uint16_t exp;
6314
            /* we save the real CPU data (in case of MMX usage only 'mant'
6315
               contains the MMX register */
6316
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6317
            qemu_put_be64(f, mant);
6318
            qemu_put_be16(f, exp);
6319
        }
6320
#else
6321
        /* if we use doubles for float emulation, we save the doubles to
6322
           avoid losing information in case of MMX usage. It can give
6323
           problems if the image is restored on a CPU where long
6324
           doubles are used instead. */
6325
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6326
#endif
6327
    }
6328

    
6329
    for(i = 0; i < 6; i++)
6330
        cpu_put_seg(f, &env->segs[i]);
6331
    cpu_put_seg(f, &env->ldt);
6332
    cpu_put_seg(f, &env->tr);
6333
    cpu_put_seg(f, &env->gdt);
6334
    cpu_put_seg(f, &env->idt);
6335

    
6336
    qemu_put_be32s(f, &env->sysenter_cs);
6337
    qemu_put_be32s(f, &env->sysenter_esp);
6338
    qemu_put_be32s(f, &env->sysenter_eip);
6339

    
6340
    qemu_put_betls(f, &env->cr[0]);
6341
    qemu_put_betls(f, &env->cr[2]);
6342
    qemu_put_betls(f, &env->cr[3]);
6343
    qemu_put_betls(f, &env->cr[4]);
6344

    
6345
    for(i = 0; i < 8; i++)
6346
        qemu_put_betls(f, &env->dr[i]);
6347

    
6348
    /* MMU */
6349
    qemu_put_be32s(f, &env->a20_mask);
6350

    
6351
    /* XMM */
6352
    qemu_put_be32s(f, &env->mxcsr);
6353
    for(i = 0; i < CPU_NB_REGS; i++) {
6354
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6355
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6356
    }
6357

    
6358
#ifdef TARGET_X86_64
6359
    qemu_put_be64s(f, &env->efer);
6360
    qemu_put_be64s(f, &env->star);
6361
    qemu_put_be64s(f, &env->lstar);
6362
    qemu_put_be64s(f, &env->cstar);
6363
    qemu_put_be64s(f, &env->fmask);
6364
    qemu_put_be64s(f, &env->kernelgsbase);
6365
#endif
6366
    qemu_put_be32s(f, &env->smbase);
6367
}
6368

    
6369
#ifdef USE_X86LDOUBLE
6370
/* XXX: add that in a FPU generic layer */
6371
union x86_longdouble {
6372
    uint64_t mant;
6373
    uint16_t exp;
6374
};
6375

    
6376
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
6377
#define EXPBIAS1 1023
6378
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
6379
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
6380

    
6381
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6382
{
6383
    int e;
6384
    /* mantissa */
6385
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6386
    /* exponent + sign */
6387
    e = EXPD1(temp) - EXPBIAS1 + 16383;
6388
    e |= SIGND1(temp) >> 16;
6389
    p->exp = e;
6390
}
6391
#endif
6392

    
6393
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6394
{
6395
    CPUState *env = opaque;
6396
    int i, guess_mmx;
6397
    uint32_t hflags;
6398
    uint16_t fpus, fpuc, fptag, fpregs_format;
6399

    
6400
    if (version_id != 3 && version_id != 4)
6401
        return -EINVAL;
6402
    for(i = 0; i < CPU_NB_REGS; i++)
6403
        qemu_get_betls(f, &env->regs[i]);
6404
    qemu_get_betls(f, &env->eip);
6405
    qemu_get_betls(f, &env->eflags);
6406
    qemu_get_be32s(f, &hflags);
6407

    
6408
    qemu_get_be16s(f, &fpuc);
6409
    qemu_get_be16s(f, &fpus);
6410
    qemu_get_be16s(f, &fptag);
6411
    qemu_get_be16s(f, &fpregs_format);
6412

    
6413
    /* NOTE: we cannot always restore the FPU state if the image come
6414
       from a host with a different 'USE_X86LDOUBLE' define. We guess
6415
       if we are in an MMX state to restore correctly in that case. */
6416
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6417
    for(i = 0; i < 8; i++) {
6418
        uint64_t mant;
6419
        uint16_t exp;
6420

    
6421
        switch(fpregs_format) {
6422
        case 0:
6423
            mant = qemu_get_be64(f);
6424
            exp = qemu_get_be16(f);
6425
#ifdef USE_X86LDOUBLE
6426
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
6427
#else
6428
            /* difficult case */
6429
            if (guess_mmx)
6430
                env->fpregs[i].mmx.MMX_Q(0) = mant;
6431
            else
6432
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
6433
#endif
6434
            break;
6435
        case 1:
6436
            mant = qemu_get_be64(f);
6437
#ifdef USE_X86LDOUBLE
6438
            {
6439
                union x86_longdouble *p;
6440
                /* difficult case */
6441
                p = (void *)&env->fpregs[i];
6442
                if (guess_mmx) {
6443
                    p->mant = mant;
6444
                    p->exp = 0xffff;
6445
                } else {
6446
                    fp64_to_fp80(p, mant);
6447
                }
6448
            }
6449
#else
6450
            env->fpregs[i].mmx.MMX_Q(0) = mant;
6451
#endif
6452
            break;
6453
        default:
6454
            return -EINVAL;
6455
        }
6456
    }
6457

    
6458
    env->fpuc = fpuc;
6459
    /* XXX: restore FPU round state */
6460
    env->fpstt = (fpus >> 11) & 7;
6461
    env->fpus = fpus & ~0x3800;
6462
    fptag ^= 0xff;
6463
    for(i = 0; i < 8; i++) {
6464
        env->fptags[i] = (fptag >> i) & 1;
6465
    }
6466

    
6467
    for(i = 0; i < 6; i++)
6468
        cpu_get_seg(f, &env->segs[i]);
6469
    cpu_get_seg(f, &env->ldt);
6470
    cpu_get_seg(f, &env->tr);
6471
    cpu_get_seg(f, &env->gdt);
6472
    cpu_get_seg(f, &env->idt);
6473

    
6474
    qemu_get_be32s(f, &env->sysenter_cs);
6475
    qemu_get_be32s(f, &env->sysenter_esp);
6476
    qemu_get_be32s(f, &env->sysenter_eip);
6477

    
6478
    qemu_get_betls(f, &env->cr[0]);
6479
    qemu_get_betls(f, &env->cr[2]);
6480
    qemu_get_betls(f, &env->cr[3]);
6481
    qemu_get_betls(f, &env->cr[4]);
6482

    
6483
    for(i = 0; i < 8; i++)
6484
        qemu_get_betls(f, &env->dr[i]);
6485

    
6486
    /* MMU */
6487
    qemu_get_be32s(f, &env->a20_mask);
6488

    
6489
    qemu_get_be32s(f, &env->mxcsr);
6490
    for(i = 0; i < CPU_NB_REGS; i++) {
6491
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6492
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6493
    }
6494

    
6495
#ifdef TARGET_X86_64
6496
    qemu_get_be64s(f, &env->efer);
6497
    qemu_get_be64s(f, &env->star);
6498
    qemu_get_be64s(f, &env->lstar);
6499
    qemu_get_be64s(f, &env->cstar);
6500
    qemu_get_be64s(f, &env->fmask);
6501
    qemu_get_be64s(f, &env->kernelgsbase);
6502
#endif
6503
    if (version_id >= 4)
6504
        qemu_get_be32s(f, &env->smbase);
6505

    
6506
    /* XXX: compute hflags from scratch, except for CPL and IIF */
6507
    env->hflags = hflags;
6508
    tlb_flush(env, 1);
6509
    return 0;
6510
}
6511

    
6512
#elif defined(TARGET_PPC)
6513
void cpu_save(QEMUFile *f, void *opaque)
6514
{
6515
}
6516

    
6517
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6518
{
6519
    return 0;
6520
}
6521

    
6522
#elif defined(TARGET_MIPS)
6523
void cpu_save(QEMUFile *f, void *opaque)
6524
{
6525
}
6526

    
6527
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6528
{
6529
    return 0;
6530
}
6531

    
6532
#elif defined(TARGET_SPARC)
6533
void cpu_save(QEMUFile *f, void *opaque)
6534
{
6535
    CPUState *env = opaque;
6536
    int i;
6537
    uint32_t tmp;
6538

    
6539
    for(i = 0; i < 8; i++)
6540
        qemu_put_betls(f, &env->gregs[i]);
6541
    for(i = 0; i < NWINDOWS * 16; i++)
6542
        qemu_put_betls(f, &env->regbase[i]);
6543

    
6544
    /* FPU */
6545
    for(i = 0; i < TARGET_FPREGS; i++) {
6546
        union {
6547
            float32 f;
6548
            uint32_t i;
6549
        } u;
6550
        u.f = env->fpr[i];
6551
        qemu_put_be32(f, u.i);
6552
    }
6553

    
6554
    qemu_put_betls(f, &env->pc);
6555
    qemu_put_betls(f, &env->npc);
6556
    qemu_put_betls(f, &env->y);
6557
    tmp = GET_PSR(env);
6558
    qemu_put_be32(f, tmp);
6559
    qemu_put_betls(f, &env->fsr);
6560
    qemu_put_betls(f, &env->tbr);
6561
#ifndef TARGET_SPARC64
6562
    qemu_put_be32s(f, &env->wim);
6563
    /* MMU */
6564
    for(i = 0; i < 16; i++)
6565
        qemu_put_be32s(f, &env->mmuregs[i]);
6566
#endif
6567
}
6568

    
6569
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6570
{
6571
    CPUState *env = opaque;
6572
    int i;
6573
    uint32_t tmp;
6574

    
6575
    for(i = 0; i < 8; i++)
6576
        qemu_get_betls(f, &env->gregs[i]);
6577
    for(i = 0; i < NWINDOWS * 16; i++)
6578
        qemu_get_betls(f, &env->regbase[i]);
6579

    
6580
    /* FPU */
6581
    for(i = 0; i < TARGET_FPREGS; i++) {
6582
        union {
6583
            float32 f;
6584
            uint32_t i;
6585
        } u;
6586
        u.i = qemu_get_be32(f);
6587
        env->fpr[i] = u.f;
6588
    }
6589

    
6590
    qemu_get_betls(f, &env->pc);
6591
    qemu_get_betls(f, &env->npc);
6592
    qemu_get_betls(f, &env->y);
6593
    tmp = qemu_get_be32(f);
6594
    env->cwp = 0; /* needed to ensure that the wrapping registers are
6595
                     correctly updated */
6596
    PUT_PSR(env, tmp);
6597
    qemu_get_betls(f, &env->fsr);
6598
    qemu_get_betls(f, &env->tbr);
6599
#ifndef TARGET_SPARC64
6600
    qemu_get_be32s(f, &env->wim);
6601
    /* MMU */
6602
    for(i = 0; i < 16; i++)
6603
        qemu_get_be32s(f, &env->mmuregs[i]);
6604
#endif
6605
    tlb_flush(env, 1);
6606
    return 0;
6607
}
6608

    
6609
#elif defined(TARGET_ARM)
6610

    
6611
void cpu_save(QEMUFile *f, void *opaque)
6612
{
6613
    int i;
6614
    CPUARMState *env = (CPUARMState *)opaque;
6615

    
6616
    for (i = 0; i < 16; i++) {
6617
        qemu_put_be32(f, env->regs[i]);
6618
    }
6619
    qemu_put_be32(f, cpsr_read(env));
6620
    qemu_put_be32(f, env->spsr);
6621
    for (i = 0; i < 6; i++) {
6622
        qemu_put_be32(f, env->banked_spsr[i]);
6623
        qemu_put_be32(f, env->banked_r13[i]);
6624
        qemu_put_be32(f, env->banked_r14[i]);
6625
    }
6626
    for (i = 0; i < 5; i++) {
6627
        qemu_put_be32(f, env->usr_regs[i]);
6628
        qemu_put_be32(f, env->fiq_regs[i]);
6629
    }
6630
    qemu_put_be32(f, env->cp15.c0_cpuid);
6631
    qemu_put_be32(f, env->cp15.c0_cachetype);
6632
    qemu_put_be32(f, env->cp15.c1_sys);
6633
    qemu_put_be32(f, env->cp15.c1_coproc);
6634
    qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6635
    qemu_put_be32(f, env->cp15.c2_base0);
6636
    qemu_put_be32(f, env->cp15.c2_base1);
6637
    qemu_put_be32(f, env->cp15.c2_mask);
6638
    qemu_put_be32(f, env->cp15.c2_data);
6639
    qemu_put_be32(f, env->cp15.c2_insn);
6640
    qemu_put_be32(f, env->cp15.c3);
6641
    qemu_put_be32(f, env->cp15.c5_insn);
6642
    qemu_put_be32(f, env->cp15.c5_data);
6643
    for (i = 0; i < 8; i++) {
6644
        qemu_put_be32(f, env->cp15.c6_region[i]);
6645
    }
6646
    qemu_put_be32(f, env->cp15.c6_insn);
6647
    qemu_put_be32(f, env->cp15.c6_data);
6648
    qemu_put_be32(f, env->cp15.c9_insn);
6649
    qemu_put_be32(f, env->cp15.c9_data);
6650
    qemu_put_be32(f, env->cp15.c13_fcse);
6651
    qemu_put_be32(f, env->cp15.c13_context);
6652
    qemu_put_be32(f, env->cp15.c13_tls1);
6653
    qemu_put_be32(f, env->cp15.c13_tls2);
6654
    qemu_put_be32(f, env->cp15.c13_tls3);
6655
    qemu_put_be32(f, env->cp15.c15_cpar);
6656

    
6657
    qemu_put_be32(f, env->features);
6658

    
6659
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6660
        for (i = 0;  i < 16; i++) {
6661
            CPU_DoubleU u;
6662
            u.d = env->vfp.regs[i];
6663
            qemu_put_be32(f, u.l.upper);
6664
            qemu_put_be32(f, u.l.lower);
6665
        }
6666
        for (i = 0; i < 16; i++) {
6667
            qemu_put_be32(f, env->vfp.xregs[i]);
6668
        }
6669

    
6670
        /* TODO: Should use proper FPSCR access functions.  */
6671
        qemu_put_be32(f, env->vfp.vec_len);
6672
        qemu_put_be32(f, env->vfp.vec_stride);
6673

    
6674
        if (arm_feature(env, ARM_FEATURE_VFP3)) {
6675
            for (i = 16;  i < 32; i++) {
6676
                CPU_DoubleU u;
6677
                u.d = env->vfp.regs[i];
6678
                qemu_put_be32(f, u.l.upper);
6679
                qemu_put_be32(f, u.l.lower);
6680
            }
6681
        }
6682
    }
6683

    
6684
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6685
        for (i = 0; i < 16; i++) {
6686
            qemu_put_be64(f, env->iwmmxt.regs[i]);
6687
        }
6688
        for (i = 0; i < 16; i++) {
6689
            qemu_put_be32(f, env->iwmmxt.cregs[i]);
6690
        }
6691
    }
6692

    
6693
    if (arm_feature(env, ARM_FEATURE_M)) {
6694
        qemu_put_be32(f, env->v7m.other_sp);
6695
        qemu_put_be32(f, env->v7m.vecbase);
6696
        qemu_put_be32(f, env->v7m.basepri);
6697
        qemu_put_be32(f, env->v7m.control);
6698
        qemu_put_be32(f, env->v7m.current_sp);
6699
        qemu_put_be32(f, env->v7m.exception);
6700
    }
6701
}
6702

    
6703
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6704
{
6705
    CPUARMState *env = (CPUARMState *)opaque;
6706
    int i;
6707

    
6708
    if (version_id != ARM_CPU_SAVE_VERSION)
6709
        return -EINVAL;
6710

    
6711
    for (i = 0; i < 16; i++) {
6712
        env->regs[i] = qemu_get_be32(f);
6713
    }
6714
    cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6715
    env->spsr = qemu_get_be32(f);
6716
    for (i = 0; i < 6; i++) {
6717
        env->banked_spsr[i] = qemu_get_be32(f);
6718
        env->banked_r13[i] = qemu_get_be32(f);
6719
        env->banked_r14[i] = qemu_get_be32(f);
6720
    }
6721
    for (i = 0; i < 5; i++) {
6722
        env->usr_regs[i] = qemu_get_be32(f);
6723
        env->fiq_regs[i] = qemu_get_be32(f);
6724
    }
6725
    env->cp15.c0_cpuid = qemu_get_be32(f);
6726
    env->cp15.c0_cachetype = qemu_get_be32(f);
6727
    env->cp15.c1_sys = qemu_get_be32(f);
6728
    env->cp15.c1_coproc = qemu_get_be32(f);
6729
    env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6730
    env->cp15.c2_base0 = qemu_get_be32(f);
6731
    env->cp15.c2_base1 = qemu_get_be32(f);
6732
    env->cp15.c2_mask = qemu_get_be32(f);
6733
    env->cp15.c2_data = qemu_get_be32(f);
6734
    env->cp15.c2_insn = qemu_get_be32(f);
6735
    env->cp15.c3 = qemu_get_be32(f);
6736
    env->cp15.c5_insn = qemu_get_be32(f);
6737
    env->cp15.c5_data = qemu_get_be32(f);
6738
    for (i = 0; i < 8; i++) {
6739
        env->cp15.c6_region[i] = qemu_get_be32(f);
6740
    }
6741
    env->cp15.c6_insn = qemu_get_be32(f);
6742
    env->cp15.c6_data = qemu_get_be32(f);
6743
    env->cp15.c9_insn = qemu_get_be32(f);
6744
    env->cp15.c9_data = qemu_get_be32(f);
6745
    env->cp15.c13_fcse = qemu_get_be32(f);
6746
    env->cp15.c13_context = qemu_get_be32(f);
6747
    env->cp15.c13_tls1 = qemu_get_be32(f);
6748
    env->cp15.c13_tls2 = qemu_get_be32(f);
6749
    env->cp15.c13_tls3 = qemu_get_be32(f);
6750
    env->cp15.c15_cpar = qemu_get_be32(f);
6751

    
6752
    env->features = qemu_get_be32(f);
6753

    
6754
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6755
        for (i = 0;  i < 16; i++) {
6756
            CPU_DoubleU u;
6757
            u.l.upper = qemu_get_be32(f);
6758
            u.l.lower = qemu_get_be32(f);
6759
            env->vfp.regs[i] = u.d;
6760
        }
6761
        for (i = 0; i < 16; i++) {
6762
            env->vfp.xregs[i] = qemu_get_be32(f);
6763
        }
6764

    
6765
        /* TODO: Should use proper FPSCR access functions.  */
6766
        env->vfp.vec_len = qemu_get_be32(f);
6767
        env->vfp.vec_stride = qemu_get_be32(f);
6768

    
6769
        if (arm_feature(env, ARM_FEATURE_VFP3)) {
6770
            for (i = 0;  i < 16; i++) {
6771
                CPU_DoubleU u;
6772
                u.l.upper = qemu_get_be32(f);
6773
                u.l.lower = qemu_get_be32(f);
6774
                env->vfp.regs[i] = u.d;
6775
            }
6776
        }
6777
    }
6778

    
6779
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6780
        for (i = 0; i < 16; i++) {
6781
            env->iwmmxt.regs[i] = qemu_get_be64(f);
6782
        }
6783
        for (i = 0; i < 16; i++) {
6784
            env->iwmmxt.cregs[i] = qemu_get_be32(f);
6785
        }
6786
    }
6787

    
6788
    if (arm_feature(env, ARM_FEATURE_M)) {
6789
        env->v7m.other_sp = qemu_get_be32(f);
6790
        env->v7m.vecbase = qemu_get_be32(f);
6791
        env->v7m.basepri = qemu_get_be32(f);
6792
        env->v7m.control = qemu_get_be32(f);
6793
        env->v7m.current_sp = qemu_get_be32(f);
6794
        env->v7m.exception = qemu_get_be32(f);
6795
    }
6796

    
6797
    return 0;
6798
}
6799

    
6800
#else
6801

    
6802
//#warning No CPU save/restore functions
6803

    
6804
#endif
6805

    
6806
/***********************************************************/
6807
/* ram save/restore */
6808

    
6809
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6810
{
6811
    int v;
6812

    
6813
    v = qemu_get_byte(f);
6814
    switch(v) {
6815
    case 0:
6816
        if (qemu_get_buffer(f, buf, len) != len)
6817
            return -EIO;
6818
        break;
6819
    case 1:
6820
        v = qemu_get_byte(f);
6821
        memset(buf, v, len);
6822
        break;
6823
    default:
6824
        return -EINVAL;
6825
    }
6826
    return 0;
6827
}
6828

    
6829
static int ram_load_v1(QEMUFile *f, void *opaque)
6830
{
6831
    int i, ret;
6832

    
6833
    if (qemu_get_be32(f) != phys_ram_size)
6834
        return -EINVAL;
6835
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6836
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6837
        if (ret)
6838
            return ret;
6839
    }
6840
    return 0;
6841
}
6842

    
6843
#define BDRV_HASH_BLOCK_SIZE 1024
6844
#define IOBUF_SIZE 4096
6845
#define RAM_CBLOCK_MAGIC 0xfabe
6846

    
6847
typedef struct RamCompressState {
6848
    z_stream zstream;
6849
    QEMUFile *f;
6850
    uint8_t buf[IOBUF_SIZE];
6851
} RamCompressState;
6852

    
6853
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6854
{
6855
    int ret;
6856
    memset(s, 0, sizeof(*s));
6857
    s->f = f;
6858
    ret = deflateInit2(&s->zstream, 1,
6859
                       Z_DEFLATED, 15,
6860
                       9, Z_DEFAULT_STRATEGY);
6861
    if (ret != Z_OK)
6862
        return -1;
6863
    s->zstream.avail_out = IOBUF_SIZE;
6864
    s->zstream.next_out = s->buf;
6865
    return 0;
6866
}
6867

    
6868
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6869
{
6870
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6871
    qemu_put_be16(s->f, len);
6872
    qemu_put_buffer(s->f, buf, len);
6873
}
6874

    
6875
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6876
{
6877
    int ret;
6878

    
6879
    s->zstream.avail_in = len;
6880
    s->zstream.next_in = (uint8_t *)buf;
6881
    while (s->zstream.avail_in > 0) {
6882
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6883
        if (ret != Z_OK)
6884
            return -1;
6885
        if (s->zstream.avail_out == 0) {
6886
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6887
            s->zstream.avail_out = IOBUF_SIZE;
6888
            s->zstream.next_out = s->buf;
6889
        }
6890
    }
6891
    return 0;
6892
}
6893

    
6894
static void ram_compress_close(RamCompressState *s)
6895
{
6896
    int len, ret;
6897

    
6898
    /* compress last bytes */
6899
    for(;;) {
6900
        ret = deflate(&s->zstream, Z_FINISH);
6901
        if (ret == Z_OK || ret == Z_STREAM_END) {
6902
            len = IOBUF_SIZE - s->zstream.avail_out;
6903
            if (len > 0) {
6904
                ram_put_cblock(s, s->buf, len);
6905
            }
6906
            s->zstream.avail_out = IOBUF_SIZE;
6907
            s->zstream.next_out = s->buf;
6908
            if (ret == Z_STREAM_END)
6909
                break;
6910
        } else {
6911
            goto fail;
6912
        }
6913
    }
6914
fail:
6915
    deflateEnd(&s->zstream);
6916
}
6917

    
6918
typedef struct RamDecompressState {
6919
    z_stream zstream;
6920
    QEMUFile *f;
6921
    uint8_t buf[IOBUF_SIZE];
6922
} RamDecompressState;
6923

    
6924
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6925
{
6926
    int ret;
6927
    memset(s, 0, sizeof(*s));
6928
    s->f = f;
6929
    ret = inflateInit(&s->zstream);
6930
    if (ret != Z_OK)
6931
        return -1;
6932
    return 0;
6933
}
6934

    
6935
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6936
{
6937
    int ret, clen;
6938

    
6939
    s->zstream.avail_out = len;
6940
    s->zstream.next_out = buf;
6941
    while (s->zstream.avail_out > 0) {
6942
        if (s->zstream.avail_in == 0) {
6943
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6944
                return -1;
6945
            clen = qemu_get_be16(s->f);
6946
            if (clen > IOBUF_SIZE)
6947
                return -1;
6948
            qemu_get_buffer(s->f, s->buf, clen);
6949
            s->zstream.avail_in = clen;
6950
            s->zstream.next_in = s->buf;
6951
        }
6952
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6953
        if (ret != Z_OK && ret != Z_STREAM_END) {
6954
            return -1;
6955
        }
6956
    }
6957
    return 0;
6958
}
6959

    
6960
static void ram_decompress_close(RamDecompressState *s)
6961
{
6962
    inflateEnd(&s->zstream);
6963
}
6964

    
6965
static void ram_save(QEMUFile *f, void *opaque)
6966
{
6967
    int i;
6968
    RamCompressState s1, *s = &s1;
6969
    uint8_t buf[10];
6970

    
6971
    qemu_put_be32(f, phys_ram_size);
6972
    if (ram_compress_open(s, f) < 0)
6973
        return;
6974
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6975
#if 0
6976
        if (tight_savevm_enabled) {
6977
            int64_t sector_num;
6978
            int j;
6979

6980
            /* find if the memory block is available on a virtual
6981
               block device */
6982
            sector_num = -1;
6983
            for(j = 0; j < nb_drives; j++) {
6984
                sector_num = bdrv_hash_find(drives_table[j].bdrv,
6985
                                            phys_ram_base + i,
6986
                                            BDRV_HASH_BLOCK_SIZE);
6987
                if (sector_num >= 0)
6988
                    break;
6989
            }
6990
            if (j == nb_drives)
6991
                goto normal_compress;
6992
            buf[0] = 1;
6993
            buf[1] = j;
6994
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6995
            ram_compress_buf(s, buf, 10);
6996
        } else
6997
#endif
6998
        {
6999
            //        normal_compress:
7000
            buf[0] = 0;
7001
            ram_compress_buf(s, buf, 1);
7002
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7003
        }
7004
    }
7005
    ram_compress_close(s);
7006
}
7007

    
7008
static int ram_load(QEMUFile *f, void *opaque, int version_id)
7009
{
7010
    RamDecompressState s1, *s = &s1;
7011
    uint8_t buf[10];
7012
    int i;
7013

    
7014
    if (version_id == 1)
7015
        return ram_load_v1(f, opaque);
7016
    if (version_id != 2)
7017
        return -EINVAL;
7018
    if (qemu_get_be32(f) != phys_ram_size)
7019
        return -EINVAL;
7020
    if (ram_decompress_open(s, f) < 0)
7021
        return -EINVAL;
7022
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7023
        if (ram_decompress_buf(s, buf, 1) < 0) {
7024
            fprintf(stderr, "Error while reading ram block header\n");
7025
            goto error;
7026
        }
7027
        if (buf[0] == 0) {
7028
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7029
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7030
                goto error;
7031
            }
7032
        } else
7033
#if 0
7034
        if (buf[0] == 1) {
7035
            int bs_index;
7036
            int64_t sector_num;
7037

7038
            ram_decompress_buf(s, buf + 1, 9);
7039
            bs_index = buf[1];
7040
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7041
            if (bs_index >= nb_drives) {
7042
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
7043
                goto error;
7044
            }
7045
            if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7046
                          phys_ram_base + i,
7047
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7048
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7049
                        bs_index, sector_num);
7050
                goto error;
7051
            }
7052
        } else
7053
#endif
7054
        {
7055
        error:
7056
            printf("Error block header\n");
7057
            return -EINVAL;
7058
        }
7059
    }
7060
    ram_decompress_close(s);
7061
    return 0;
7062
}
7063

    
7064
/***********************************************************/
7065
/* bottom halves (can be seen as timers which expire ASAP) */
7066

    
7067
struct QEMUBH {
7068
    QEMUBHFunc *cb;
7069
    void *opaque;
7070
    int scheduled;
7071
    QEMUBH *next;
7072
};
7073

    
7074
static QEMUBH *first_bh = NULL;
7075

    
7076
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7077
{
7078
    QEMUBH *bh;
7079
    bh = qemu_mallocz(sizeof(QEMUBH));
7080
    if (!bh)
7081
        return NULL;
7082
    bh->cb = cb;
7083
    bh->opaque = opaque;
7084
    return bh;
7085
}
7086

    
7087
int qemu_bh_poll(void)
7088
{
7089
    QEMUBH *bh, **pbh;
7090
    int ret;
7091

    
7092
    ret = 0;
7093
    for(;;) {
7094
        pbh = &first_bh;
7095
        bh = *pbh;
7096
        if (!bh)
7097
            break;
7098
        ret = 1;
7099
        *pbh = bh->next;
7100
        bh->scheduled = 0;
7101
        bh->cb(bh->opaque);
7102
    }
7103
    return ret;
7104
}
7105

    
7106
void qemu_bh_schedule(QEMUBH *bh)
7107
{
7108
    CPUState *env = cpu_single_env;
7109
    if (bh->scheduled)
7110
        return;
7111
    bh->scheduled = 1;
7112
    bh->next = first_bh;
7113
    first_bh = bh;
7114

    
7115
    /* stop the currently executing CPU to execute the BH ASAP */
7116
    if (env) {
7117
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7118
    }
7119
}
7120

    
7121
void qemu_bh_cancel(QEMUBH *bh)
7122
{
7123
    QEMUBH **pbh;
7124
    if (bh->scheduled) {
7125
        pbh = &first_bh;
7126
        while (*pbh != bh)
7127
            pbh = &(*pbh)->next;
7128
        *pbh = bh->next;
7129
        bh->scheduled = 0;
7130
    }
7131
}
7132

    
7133
void qemu_bh_delete(QEMUBH *bh)
7134
{
7135
    qemu_bh_cancel(bh);
7136
    qemu_free(bh);
7137
}
7138

    
7139
/***********************************************************/
7140
/* machine registration */
7141

    
7142
QEMUMachine *first_machine = NULL;
7143

    
7144
int qemu_register_machine(QEMUMachine *m)
7145
{
7146
    QEMUMachine **pm;
7147
    pm = &first_machine;
7148
    while (*pm != NULL)
7149
        pm = &(*pm)->next;
7150
    m->next = NULL;
7151
    *pm = m;
7152
    return 0;
7153
}
7154

    
7155
static QEMUMachine *find_machine(const char *name)
7156
{
7157
    QEMUMachine *m;
7158

    
7159
    for(m = first_machine; m != NULL; m = m->next) {
7160
        if (!strcmp(m->name, name))
7161
            return m;
7162
    }
7163
    return NULL;
7164
}
7165

    
7166
/***********************************************************/
7167
/* main execution loop */
7168

    
7169
static void gui_update(void *opaque)
7170
{
7171
    DisplayState *ds = opaque;
7172
    ds->dpy_refresh(ds);
7173
    qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7174
}
7175

    
7176
struct vm_change_state_entry {
7177
    VMChangeStateHandler *cb;
7178
    void *opaque;
7179
    LIST_ENTRY (vm_change_state_entry) entries;
7180
};
7181

    
7182
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7183

    
7184
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7185
                                                     void *opaque)
7186
{
7187
    VMChangeStateEntry *e;
7188

    
7189
    e = qemu_mallocz(sizeof (*e));
7190
    if (!e)
7191
        return NULL;
7192

    
7193
    e->cb = cb;
7194
    e->opaque = opaque;
7195
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7196
    return e;
7197
}
7198

    
7199
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7200
{
7201
    LIST_REMOVE (e, entries);
7202
    qemu_free (e);
7203
}
7204

    
7205
static void vm_state_notify(int running)
7206
{
7207
    VMChangeStateEntry *e;
7208

    
7209
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7210
        e->cb(e->opaque, running);
7211
    }
7212
}
7213

    
7214
/* XXX: support several handlers */
7215
static VMStopHandler *vm_stop_cb;
7216
static void *vm_stop_opaque;
7217

    
7218
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7219
{
7220
    vm_stop_cb = cb;
7221
    vm_stop_opaque = opaque;
7222
    return 0;
7223
}
7224

    
7225
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7226
{
7227
    vm_stop_cb = NULL;
7228
}
7229

    
7230
void vm_start(void)
7231
{
7232
    if (!vm_running) {
7233
        cpu_enable_ticks();
7234
        vm_running = 1;
7235
        vm_state_notify(1);
7236
        qemu_rearm_alarm_timer(alarm_timer);
7237
    }
7238
}
7239

    
7240
void vm_stop(int reason)
7241
{
7242
    if (vm_running) {
7243
        cpu_disable_ticks();
7244
        vm_running = 0;
7245
        if (reason != 0) {
7246
            if (vm_stop_cb) {
7247
                vm_stop_cb(vm_stop_opaque, reason);
7248
            }
7249
        }
7250
        vm_state_notify(0);
7251
    }
7252
}
7253

    
7254
/* reset/shutdown handler */
7255

    
7256
typedef struct QEMUResetEntry {
7257
    QEMUResetHandler *func;
7258
    void *opaque;
7259
    struct QEMUResetEntry *next;
7260
} QEMUResetEntry;
7261

    
7262
static QEMUResetEntry *first_reset_entry;
7263
static int reset_requested;
7264
static int shutdown_requested;
7265
static int powerdown_requested;
7266

    
7267
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7268
{
7269
    QEMUResetEntry **pre, *re;
7270

    
7271
    pre = &first_reset_entry;
7272
    while (*pre != NULL)
7273
        pre = &(*pre)->next;
7274
    re = qemu_mallocz(sizeof(QEMUResetEntry));
7275
    re->func = func;
7276
    re->opaque = opaque;
7277
    re->next = NULL;
7278
    *pre = re;
7279
}
7280

    
7281
static void qemu_system_reset(void)
7282
{
7283
    QEMUResetEntry *re;
7284

    
7285
    /* reset all devices */
7286
    for(re = first_reset_entry; re != NULL; re = re->next) {
7287
        re->func(re->opaque);
7288
    }
7289
}
7290

    
7291
void qemu_system_reset_request(void)
7292
{
7293
    if (no_reboot) {
7294
        shutdown_requested = 1;
7295
    } else {
7296
        reset_requested = 1;
7297
    }
7298
    if (cpu_single_env)
7299
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7300
}
7301

    
7302
void qemu_system_shutdown_request(void)
7303
{
7304
    shutdown_requested = 1;
7305
    if (cpu_single_env)
7306
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7307
}
7308

    
7309
void qemu_system_powerdown_request(void)
7310
{
7311
    powerdown_requested = 1;
7312
    if (cpu_single_env)
7313
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7314
}
7315

    
7316
void main_loop_wait(int timeout)
7317
{
7318
    IOHandlerRecord *ioh;
7319
    fd_set rfds, wfds, xfds;
7320
    int ret, nfds;
7321
#ifdef _WIN32
7322
    int ret2, i;
7323
#endif
7324
    struct timeval tv;
7325
    PollingEntry *pe;
7326

    
7327

    
7328
    /* XXX: need to suppress polling by better using win32 events */
7329
    ret = 0;
7330
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7331
        ret |= pe->func(pe->opaque);
7332
    }
7333
#ifdef _WIN32
7334
    if (ret == 0) {
7335
        int err;
7336
        WaitObjects *w = &wait_objects;
7337

    
7338
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7339
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7340
            if (w->func[ret - WAIT_OBJECT_0])
7341
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7342

    
7343
            /* Check for additional signaled events */
7344
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7345

    
7346
                /* Check if event is signaled */
7347
                ret2 = WaitForSingleObject(w->events[i], 0);
7348
                if(ret2 == WAIT_OBJECT_0) {
7349
                    if (w->func[i])
7350
                        w->func[i](w->opaque[i]);
7351
                } else if (ret2 == WAIT_TIMEOUT) {
7352
                } else {
7353
                    err = GetLastError();
7354
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7355
                }
7356
            }
7357
        } else if (ret == WAIT_TIMEOUT) {
7358
        } else {
7359
            err = GetLastError();
7360
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7361
        }
7362
    }
7363
#endif
7364
    /* poll any events */
7365
    /* XXX: separate device handlers from system ones */
7366
    nfds = -1;
7367
    FD_ZERO(&rfds);
7368
    FD_ZERO(&wfds);
7369
    FD_ZERO(&xfds);
7370
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7371
        if (ioh->deleted)
7372
            continue;
7373
        if (ioh->fd_read &&
7374
            (!ioh->fd_read_poll ||
7375
             ioh->fd_read_poll(ioh->opaque) != 0)) {
7376
            FD_SET(ioh->fd, &rfds);
7377
            if (ioh->fd > nfds)
7378
                nfds = ioh->fd;
7379
        }
7380
        if (ioh->fd_write) {
7381
            FD_SET(ioh->fd, &wfds);
7382
            if (ioh->fd > nfds)
7383
                nfds = ioh->fd;
7384
        }
7385
    }
7386

    
7387
    tv.tv_sec = 0;
7388
#ifdef _WIN32
7389
    tv.tv_usec = 0;
7390
#else
7391
    tv.tv_usec = timeout * 1000;
7392
#endif
7393
#if defined(CONFIG_SLIRP)
7394
    if (slirp_inited) {
7395
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7396
    }
7397
#endif
7398
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7399
    if (ret > 0) {
7400
        IOHandlerRecord **pioh;
7401

    
7402
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7403
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7404
                ioh->fd_read(ioh->opaque);
7405
            }
7406
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7407
                ioh->fd_write(ioh->opaque);
7408
            }
7409
        }
7410

    
7411
        /* remove deleted IO handlers */
7412
        pioh = &first_io_handler;
7413
        while (*pioh) {
7414
            ioh = *pioh;
7415
            if (ioh->deleted) {
7416
                *pioh = ioh->next;
7417
                qemu_free(ioh);
7418
            } else
7419
                pioh = &ioh->next;
7420
        }
7421
    }
7422
#if defined(CONFIG_SLIRP)
7423
    if (slirp_inited) {
7424
        if (ret < 0) {
7425
            FD_ZERO(&rfds);
7426
            FD_ZERO(&wfds);
7427
            FD_ZERO(&xfds);
7428
        }
7429
        slirp_select_poll(&rfds, &wfds, &xfds);
7430
    }
7431
#endif
7432
    qemu_aio_poll();
7433

    
7434
    if (vm_running) {
7435
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7436
                        qemu_get_clock(vm_clock));
7437
        /* run dma transfers, if any */
7438
        DMA_run();
7439
    }
7440

    
7441
    /* real time timers */
7442
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7443
                    qemu_get_clock(rt_clock));
7444

    
7445
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7446
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7447
        qemu_rearm_alarm_timer(alarm_timer);
7448
    }
7449

    
7450
    /* Check bottom-halves last in case any of the earlier events triggered
7451
       them.  */
7452
    qemu_bh_poll();
7453

    
7454
}
7455

    
7456
static int main_loop(void)
7457
{
7458
    int ret, timeout;
7459
#ifdef CONFIG_PROFILER
7460
    int64_t ti;
7461
#endif
7462
    CPUState *env;
7463

    
7464
    cur_cpu = first_cpu;
7465
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7466
    for(;;) {
7467
        if (vm_running) {
7468

    
7469
            for(;;) {
7470
                /* get next cpu */
7471
                env = next_cpu;
7472
#ifdef CONFIG_PROFILER
7473
                ti = profile_getclock();
7474
#endif
7475
                ret = cpu_exec(env);
7476
#ifdef CONFIG_PROFILER
7477
                qemu_time += profile_getclock() - ti;
7478
#endif
7479
                next_cpu = env->next_cpu ?: first_cpu;
7480
                if (event_pending) {
7481
                    ret = EXCP_INTERRUPT;
7482
                    event_pending = 0;
7483
                    break;
7484
                }
7485
                if (ret == EXCP_HLT) {
7486
                    /* Give the next CPU a chance to run.  */
7487
                    cur_cpu = env;
7488
                    continue;
7489
                }
7490
                if (ret != EXCP_HALTED)
7491
                    break;
7492
                /* all CPUs are halted ? */
7493
                if (env == cur_cpu)
7494
                    break;
7495
            }
7496
            cur_cpu = env;
7497

    
7498
            if (shutdown_requested) {
7499
                ret = EXCP_INTERRUPT;
7500
                break;
7501
            }
7502
            if (reset_requested) {
7503
                reset_requested = 0;
7504
                qemu_system_reset();
7505
                ret = EXCP_INTERRUPT;
7506
            }
7507
            if (powerdown_requested) {
7508
                powerdown_requested = 0;
7509
                qemu_system_powerdown();
7510
                ret = EXCP_INTERRUPT;
7511
            }
7512
            if (ret == EXCP_DEBUG) {
7513
                vm_stop(EXCP_DEBUG);
7514
            }
7515
            /* If all cpus are halted then wait until the next IRQ */
7516
            /* XXX: use timeout computed from timers */
7517
            if (ret == EXCP_HALTED)
7518
                timeout = 10;
7519
            else
7520
                timeout = 0;
7521
        } else {
7522
            timeout = 10;
7523
        }
7524
#ifdef CONFIG_PROFILER
7525
        ti = profile_getclock();
7526
#endif
7527
        main_loop_wait(timeout);
7528
#ifdef CONFIG_PROFILER
7529
        dev_time += profile_getclock() - ti;
7530
#endif
7531
    }
7532
    cpu_disable_ticks();
7533
    return ret;
7534
}
7535

    
7536
static void help(int exitcode)
7537
{
7538
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7539
           "usage: %s [options] [disk_image]\n"
7540
           "\n"
7541
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7542
           "\n"
7543
           "Standard options:\n"
7544
           "-M machine      select emulated machine (-M ? for list)\n"
7545
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7546
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7547
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7548
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7549
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7550
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7551
           "       [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7552
           "       [,cache=on|off]\n"
7553
           "                use 'file' as a drive image\n"
7554
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7555
           "-sd file        use 'file' as SecureDigital card image\n"
7556
           "-pflash file    use 'file' as a parallel flash image\n"
7557
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7558
           "-snapshot       write to temporary files instead of disk image files\n"
7559
#ifdef CONFIG_SDL
7560
           "-no-frame       open SDL window without a frame and window decorations\n"
7561
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7562
           "-no-quit        disable SDL window close capability\n"
7563
#endif
7564
#ifdef TARGET_I386
7565
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7566
#endif
7567
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7568
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7569
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7570
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7571
#ifndef _WIN32
7572
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7573
#endif
7574
#ifdef HAS_AUDIO
7575
           "-audio-help     print list of audio drivers and their options\n"
7576
           "-soundhw c1,... enable audio support\n"
7577
           "                and only specified sound cards (comma separated list)\n"
7578
           "                use -soundhw ? to get the list of supported cards\n"
7579
           "                use -soundhw all to enable all of them\n"
7580
#endif
7581
           "-localtime      set the real time clock to local time [default=utc]\n"
7582
           "-full-screen    start in full screen\n"
7583
#ifdef TARGET_I386
7584
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7585
#endif
7586
           "-usb            enable the USB driver (will be the default soon)\n"
7587
           "-usbdevice name add the host or guest USB device 'name'\n"
7588
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7589
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7590
#endif
7591
           "-name string    set the name of the guest\n"
7592
           "\n"
7593
           "Network options:\n"
7594
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7595
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7596
#ifdef CONFIG_SLIRP
7597
           "-net user[,vlan=n][,hostname=host]\n"
7598
           "                connect the user mode network stack to VLAN 'n' and send\n"
7599
           "                hostname 'host' to DHCP clients\n"
7600
#endif
7601
#ifdef _WIN32
7602
           "-net tap[,vlan=n],ifname=name\n"
7603
           "                connect the host TAP network interface to VLAN 'n'\n"
7604
#else
7605
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7606
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7607
           "                network scripts 'file' (default=%s)\n"
7608
           "                and 'dfile' (default=%s);\n"
7609
           "                use '[down]script=no' to disable script execution;\n"
7610
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7611
#endif
7612
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7613
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7614
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7615
           "                connect the vlan 'n' to multicast maddr and port\n"
7616
           "-net none       use it alone to have zero network devices; if no -net option\n"
7617
           "                is provided, the default is '-net nic -net user'\n"
7618
           "\n"
7619
#ifdef CONFIG_SLIRP
7620
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7621
           "-bootp file     advertise file in BOOTP replies\n"
7622
#ifndef _WIN32
7623
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7624
#endif
7625
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7626
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7627
#endif
7628
           "\n"
7629
           "Linux boot specific:\n"
7630
           "-kernel bzImage use 'bzImage' as kernel image\n"
7631
           "-append cmdline use 'cmdline' as kernel command line\n"
7632
           "-initrd file    use 'file' as initial ram disk\n"
7633
           "\n"
7634
           "Debug/Expert options:\n"
7635
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7636
           "-serial dev     redirect the serial port to char device 'dev'\n"
7637
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7638
           "-pidfile file   Write PID to 'file'\n"
7639
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7640
           "-s              wait gdb connection to port\n"
7641
           "-p port         set gdb connection port [default=%s]\n"
7642
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7643
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7644
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7645
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7646
#ifdef USE_KQEMU
7647
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7648
           "-no-kqemu       disable KQEMU kernel module usage\n"
7649
#endif
7650
#ifdef TARGET_I386
7651
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7652
           "                (default is CL-GD5446 PCI VGA)\n"
7653
           "-no-acpi        disable ACPI\n"
7654
#endif
7655
           "-no-reboot      exit instead of rebooting\n"
7656
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
7657
           "-vnc display    start a VNC server on display\n"
7658
#ifndef _WIN32
7659
           "-daemonize      daemonize QEMU after initializing\n"
7660
#endif
7661
           "-option-rom rom load a file, rom, into the option ROM space\n"
7662
#ifdef TARGET_SPARC
7663
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7664
#endif
7665
           "-clock          force the use of the given methods for timer alarm.\n"
7666
           "                To see what timers are available use -clock help\n"
7667
           "-startdate      select initial date of the clock\n"
7668
           "\n"
7669
           "During emulation, the following keys are useful:\n"
7670
           "ctrl-alt-f      toggle full screen\n"
7671
           "ctrl-alt-n      switch to virtual console 'n'\n"
7672
           "ctrl-alt        toggle mouse and keyboard grab\n"
7673
           "\n"
7674
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7675
           ,
7676
           "qemu",
7677
           DEFAULT_RAM_SIZE,
7678
#ifndef _WIN32
7679
           DEFAULT_NETWORK_SCRIPT,
7680
           DEFAULT_NETWORK_DOWN_SCRIPT,
7681
#endif
7682
           DEFAULT_GDBSTUB_PORT,
7683
           "/tmp/qemu.log");
7684
    exit(exitcode);
7685
}
7686

    
7687
#define HAS_ARG 0x0001
7688

    
7689
enum {
7690
    QEMU_OPTION_h,
7691

    
7692
    QEMU_OPTION_M,
7693
    QEMU_OPTION_cpu,
7694
    QEMU_OPTION_fda,
7695
    QEMU_OPTION_fdb,
7696
    QEMU_OPTION_hda,
7697
    QEMU_OPTION_hdb,
7698
    QEMU_OPTION_hdc,
7699
    QEMU_OPTION_hdd,
7700
    QEMU_OPTION_drive,
7701
    QEMU_OPTION_cdrom,
7702
    QEMU_OPTION_mtdblock,
7703
    QEMU_OPTION_sd,
7704
    QEMU_OPTION_pflash,
7705
    QEMU_OPTION_boot,
7706
    QEMU_OPTION_snapshot,
7707
#ifdef TARGET_I386
7708
    QEMU_OPTION_no_fd_bootchk,
7709
#endif
7710
    QEMU_OPTION_m,
7711
    QEMU_OPTION_nographic,
7712
    QEMU_OPTION_portrait,
7713
#ifdef HAS_AUDIO
7714
    QEMU_OPTION_audio_help,
7715
    QEMU_OPTION_soundhw,
7716
#endif
7717

    
7718
    QEMU_OPTION_net,
7719
    QEMU_OPTION_tftp,
7720
    QEMU_OPTION_bootp,
7721
    QEMU_OPTION_smb,
7722
    QEMU_OPTION_redir,
7723

    
7724
    QEMU_OPTION_kernel,
7725
    QEMU_OPTION_append,
7726
    QEMU_OPTION_initrd,
7727

    
7728
    QEMU_OPTION_S,
7729
    QEMU_OPTION_s,
7730
    QEMU_OPTION_p,
7731
    QEMU_OPTION_d,
7732
    QEMU_OPTION_hdachs,
7733
    QEMU_OPTION_L,
7734
    QEMU_OPTION_bios,
7735
    QEMU_OPTION_no_code_copy,
7736
    QEMU_OPTION_k,
7737
    QEMU_OPTION_localtime,
7738
    QEMU_OPTION_cirrusvga,
7739
    QEMU_OPTION_vmsvga,
7740
    QEMU_OPTION_g,
7741
    QEMU_OPTION_std_vga,
7742
    QEMU_OPTION_echr,
7743
    QEMU_OPTION_monitor,
7744
    QEMU_OPTION_serial,
7745
    QEMU_OPTION_parallel,
7746
    QEMU_OPTION_loadvm,
7747
    QEMU_OPTION_full_screen,
7748
    QEMU_OPTION_no_frame,
7749
    QEMU_OPTION_alt_grab,
7750
    QEMU_OPTION_no_quit,
7751
    QEMU_OPTION_pidfile,
7752
    QEMU_OPTION_no_kqemu,
7753
    QEMU_OPTION_kernel_kqemu,
7754
    QEMU_OPTION_win2k_hack,
7755
    QEMU_OPTION_usb,
7756
    QEMU_OPTION_usbdevice,
7757
    QEMU_OPTION_smp,
7758
    QEMU_OPTION_vnc,
7759
    QEMU_OPTION_no_acpi,
7760
    QEMU_OPTION_no_reboot,
7761
    QEMU_OPTION_show_cursor,
7762
    QEMU_OPTION_daemonize,
7763
    QEMU_OPTION_option_rom,
7764
    QEMU_OPTION_semihosting,
7765
    QEMU_OPTION_name,
7766
    QEMU_OPTION_prom_env,
7767
    QEMU_OPTION_old_param,
7768
    QEMU_OPTION_clock,
7769
    QEMU_OPTION_startdate,
7770
};
7771

    
7772
typedef struct QEMUOption {
7773
    const char *name;
7774
    int flags;
7775
    int index;
7776
} QEMUOption;
7777

    
7778
const QEMUOption qemu_options[] = {
7779
    { "h", 0, QEMU_OPTION_h },
7780
    { "help", 0, QEMU_OPTION_h },
7781

    
7782
    { "M", HAS_ARG, QEMU_OPTION_M },
7783
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7784
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7785
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7786
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7787
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7788
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7789
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7790
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7791
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7792
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7793
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7794
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7795
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7796
    { "snapshot", 0, QEMU_OPTION_snapshot },
7797
#ifdef TARGET_I386
7798
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7799
#endif
7800
    { "m", HAS_ARG, QEMU_OPTION_m },
7801
    { "nographic", 0, QEMU_OPTION_nographic },
7802
    { "portrait", 0, QEMU_OPTION_portrait },
7803
    { "k", HAS_ARG, QEMU_OPTION_k },
7804
#ifdef HAS_AUDIO
7805
    { "audio-help", 0, QEMU_OPTION_audio_help },
7806
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7807
#endif
7808

    
7809
    { "net", HAS_ARG, QEMU_OPTION_net},
7810
#ifdef CONFIG_SLIRP
7811
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7812
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7813
#ifndef _WIN32
7814
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7815
#endif
7816
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7817
#endif
7818

    
7819
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7820
    { "append", HAS_ARG, QEMU_OPTION_append },
7821
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7822

    
7823
    { "S", 0, QEMU_OPTION_S },
7824
    { "s", 0, QEMU_OPTION_s },
7825
    { "p", HAS_ARG, QEMU_OPTION_p },
7826
    { "d", HAS_ARG, QEMU_OPTION_d },
7827
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7828
    { "L", HAS_ARG, QEMU_OPTION_L },
7829
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7830
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7831
#ifdef USE_KQEMU
7832
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7833
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7834
#endif
7835
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7836
    { "g", 1, QEMU_OPTION_g },
7837
#endif
7838
    { "localtime", 0, QEMU_OPTION_localtime },
7839
    { "std-vga", 0, QEMU_OPTION_std_vga },
7840
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7841
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7842
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7843
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7844
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7845
    { "full-screen", 0, QEMU_OPTION_full_screen },
7846
#ifdef CONFIG_SDL
7847
    { "no-frame", 0, QEMU_OPTION_no_frame },
7848
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7849
    { "no-quit", 0, QEMU_OPTION_no_quit },
7850
#endif
7851
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7852
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7853
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7854
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7855
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7856

    
7857
    /* temporary options */
7858
    { "usb", 0, QEMU_OPTION_usb },
7859
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7860
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7861
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7862
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7863
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7864
    { "daemonize", 0, QEMU_OPTION_daemonize },
7865
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7866
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7867
    { "semihosting", 0, QEMU_OPTION_semihosting },
7868
#endif
7869
    { "name", HAS_ARG, QEMU_OPTION_name },
7870
#if defined(TARGET_SPARC)
7871
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7872
#endif
7873
#if defined(TARGET_ARM)
7874
    { "old-param", 0, QEMU_OPTION_old_param },
7875
#endif
7876
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7877
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7878
    { NULL },
7879
};
7880

    
7881
/* password input */
7882

    
7883
int qemu_key_check(BlockDriverState *bs, const char *name)
7884
{
7885
    char password[256];
7886
    int i;
7887

    
7888
    if (!bdrv_is_encrypted(bs))
7889
        return 0;
7890

    
7891
    term_printf("%s is encrypted.\n", name);
7892
    for(i = 0; i < 3; i++) {
7893
        monitor_readline("Password: ", 1, password, sizeof(password));
7894
        if (bdrv_set_key(bs, password) == 0)
7895
            return 0;
7896
        term_printf("invalid password\n");
7897
    }
7898
    return -EPERM;
7899
}
7900

    
7901
static BlockDriverState *get_bdrv(int index)
7902
{
7903
    if (index > nb_drives)
7904
        return NULL;
7905
    return drives_table[index].bdrv;
7906
}
7907

    
7908
static void read_passwords(void)
7909
{
7910
    BlockDriverState *bs;
7911
    int i;
7912

    
7913
    for(i = 0; i < 6; i++) {
7914
        bs = get_bdrv(i);
7915
        if (bs)
7916
            qemu_key_check(bs, bdrv_get_device_name(bs));
7917
    }
7918
}
7919

    
7920
/* XXX: currently we cannot use simultaneously different CPUs */
7921
static void register_machines(void)
7922
{
7923
#if defined(TARGET_I386)
7924
    qemu_register_machine(&pc_machine);
7925
    qemu_register_machine(&isapc_machine);
7926
#elif defined(TARGET_PPC)
7927
    qemu_register_machine(&heathrow_machine);
7928
    qemu_register_machine(&core99_machine);
7929
    qemu_register_machine(&prep_machine);
7930
    qemu_register_machine(&ref405ep_machine);
7931
    qemu_register_machine(&taihu_machine);
7932
#elif defined(TARGET_MIPS)
7933
    qemu_register_machine(&mips_machine);
7934
    qemu_register_machine(&mips_malta_machine);
7935
    qemu_register_machine(&mips_pica61_machine);
7936
    qemu_register_machine(&mips_mipssim_machine);
7937
#elif defined(TARGET_SPARC)
7938
#ifdef TARGET_SPARC64
7939
    qemu_register_machine(&sun4u_machine);
7940
#else
7941
    qemu_register_machine(&ss5_machine);
7942
    qemu_register_machine(&ss10_machine);
7943
    qemu_register_machine(&ss600mp_machine);
7944
    qemu_register_machine(&ss20_machine);
7945
    qemu_register_machine(&ss2_machine);
7946
    qemu_register_machine(&ss1000_machine);
7947
    qemu_register_machine(&ss2000_machine);
7948
#endif
7949
#elif defined(TARGET_ARM)
7950
    qemu_register_machine(&integratorcp_machine);
7951
    qemu_register_machine(&versatilepb_machine);
7952
    qemu_register_machine(&versatileab_machine);
7953
    qemu_register_machine(&realview_machine);
7954
    qemu_register_machine(&akitapda_machine);
7955
    qemu_register_machine(&spitzpda_machine);
7956
    qemu_register_machine(&borzoipda_machine);
7957
    qemu_register_machine(&terrierpda_machine);
7958
    qemu_register_machine(&palmte_machine);
7959
    qemu_register_machine(&lm3s811evb_machine);
7960
    qemu_register_machine(&lm3s6965evb_machine);
7961
    qemu_register_machine(&connex_machine);
7962
    qemu_register_machine(&verdex_machine);
7963
    qemu_register_machine(&mainstone2_machine);
7964
#elif defined(TARGET_SH4)
7965
    qemu_register_machine(&shix_machine);
7966
    qemu_register_machine(&r2d_machine);
7967
#elif defined(TARGET_ALPHA)
7968
    /* XXX: TODO */
7969
#elif defined(TARGET_M68K)
7970
    qemu_register_machine(&mcf5208evb_machine);
7971
    qemu_register_machine(&an5206_machine);
7972
    qemu_register_machine(&dummy_m68k_machine);
7973
#elif defined(TARGET_CRIS)
7974
    qemu_register_machine(&bareetraxfs_machine);
7975
#else
7976
#error unsupported CPU
7977
#endif
7978
}
7979

    
7980
#ifdef HAS_AUDIO
7981
struct soundhw soundhw[] = {
7982
#ifdef HAS_AUDIO_CHOICE
7983
#ifdef TARGET_I386
7984
    {
7985
        "pcspk",
7986
        "PC speaker",
7987
        0,
7988
        1,
7989
        { .init_isa = pcspk_audio_init }
7990
    },
7991
#endif
7992
    {
7993
        "sb16",
7994
        "Creative Sound Blaster 16",
7995
        0,
7996
        1,
7997
        { .init_isa = SB16_init }
7998
    },
7999

    
8000
#ifdef CONFIG_ADLIB
8001
    {
8002
        "adlib",
8003
#ifdef HAS_YMF262
8004
        "Yamaha YMF262 (OPL3)",
8005
#else
8006
        "Yamaha YM3812 (OPL2)",
8007
#endif
8008
        0,
8009
        1,
8010
        { .init_isa = Adlib_init }
8011
    },
8012
#endif
8013

    
8014
#ifdef CONFIG_GUS
8015
    {
8016
        "gus",
8017
        "Gravis Ultrasound GF1",
8018
        0,
8019
        1,
8020
        { .init_isa = GUS_init }
8021
    },
8022
#endif
8023

    
8024
#ifdef CONFIG_AC97
8025
    {
8026
        "ac97",
8027
        "Intel 82801AA AC97 Audio",
8028
        0,
8029
        0,
8030
        { .init_pci = ac97_init }
8031
    },
8032
#endif
8033

    
8034
    {
8035
        "es1370",
8036
        "ENSONIQ AudioPCI ES1370",
8037
        0,
8038
        0,
8039
        { .init_pci = es1370_init }
8040
    },
8041
#endif
8042

    
8043
    { NULL, NULL, 0, 0, { NULL } }
8044
};
8045

    
8046
static void select_soundhw (const char *optarg)
8047
{
8048
    struct soundhw *c;
8049

    
8050
    if (*optarg == '?') {
8051
    show_valid_cards:
8052

    
8053
        printf ("Valid sound card names (comma separated):\n");
8054
        for (c = soundhw; c->name; ++c) {
8055
            printf ("%-11s %s\n", c->name, c->descr);
8056
        }
8057
        printf ("\n-soundhw all will enable all of the above\n");
8058
        exit (*optarg != '?');
8059
    }
8060
    else {
8061
        size_t l;
8062
        const char *p;
8063
        char *e;
8064
        int bad_card = 0;
8065

    
8066
        if (!strcmp (optarg, "all")) {
8067
            for (c = soundhw; c->name; ++c) {
8068
                c->enabled = 1;
8069
            }
8070
            return;
8071
        }
8072

    
8073
        p = optarg;
8074
        while (*p) {
8075
            e = strchr (p, ',');
8076
            l = !e ? strlen (p) : (size_t) (e - p);
8077

    
8078
            for (c = soundhw; c->name; ++c) {
8079
                if (!strncmp (c->name, p, l)) {
8080
                    c->enabled = 1;
8081
                    break;
8082
                }
8083
            }
8084

    
8085
            if (!c->name) {
8086
                if (l > 80) {
8087
                    fprintf (stderr,
8088
                             "Unknown sound card name (too big to show)\n");
8089
                }
8090
                else {
8091
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
8092
                             (int) l, p);
8093
                }
8094
                bad_card = 1;
8095
            }
8096
            p += l + (e != NULL);
8097
        }
8098

    
8099
        if (bad_card)
8100
            goto show_valid_cards;
8101
    }
8102
}
8103
#endif
8104

    
8105
#ifdef _WIN32
8106
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8107
{
8108
    exit(STATUS_CONTROL_C_EXIT);
8109
    return TRUE;
8110
}
8111
#endif
8112

    
8113
#define MAX_NET_CLIENTS 32
8114

    
8115
int main(int argc, char **argv)
8116
{
8117
#ifdef CONFIG_GDBSTUB
8118
    int use_gdbstub;
8119
    const char *gdbstub_port;
8120
#endif
8121
    uint32_t boot_devices_bitmap = 0;
8122
    int i;
8123
    int snapshot, linux_boot, net_boot;
8124
    const char *initrd_filename;
8125
    const char *kernel_filename, *kernel_cmdline;
8126
    const char *boot_devices = "";
8127
    DisplayState *ds = &display_state;
8128
    int cyls, heads, secs, translation;
8129
    char net_clients[MAX_NET_CLIENTS][256];
8130
    int nb_net_clients;
8131
    int hda_index;
8132
    int optind;
8133
    const char *r, *optarg;
8134
    CharDriverState *monitor_hd;
8135
    char monitor_device[128];
8136
    char serial_devices[MAX_SERIAL_PORTS][128];
8137
    int serial_device_index;
8138
    char parallel_devices[MAX_PARALLEL_PORTS][128];
8139
    int parallel_device_index;
8140
    const char *loadvm = NULL;
8141
    QEMUMachine *machine;
8142
    const char *cpu_model;
8143
    char usb_devices[MAX_USB_CMDLINE][128];
8144
    int usb_devices_index;
8145
    int fds[2];
8146
    const char *pid_file = NULL;
8147
    VLANState *vlan;
8148

    
8149
    LIST_INIT (&vm_change_state_head);
8150
#ifndef _WIN32
8151
    {
8152
        struct sigaction act;
8153
        sigfillset(&act.sa_mask);
8154
        act.sa_flags = 0;
8155
        act.sa_handler = SIG_IGN;
8156
        sigaction(SIGPIPE, &act, NULL);
8157
    }
8158
#else
8159
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8160
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
8161
       QEMU to run on a single CPU */
8162
    {
8163
        HANDLE h;
8164
        DWORD mask, smask;
8165
        int i;
8166
        h = GetCurrentProcess();
8167
        if (GetProcessAffinityMask(h, &mask, &smask)) {
8168
            for(i = 0; i < 32; i++) {
8169
                if (mask & (1 << i))
8170
                    break;
8171
            }
8172
            if (i != 32) {
8173
                mask = 1 << i;
8174
                SetProcessAffinityMask(h, mask);
8175
            }
8176
        }
8177
    }
8178
#endif
8179

    
8180
    register_machines();
8181
    machine = first_machine;
8182
    cpu_model = NULL;
8183
    initrd_filename = NULL;
8184
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8185
    vga_ram_size = VGA_RAM_SIZE;
8186
#ifdef CONFIG_GDBSTUB
8187
    use_gdbstub = 0;
8188
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
8189
#endif
8190
    snapshot = 0;
8191
    nographic = 0;
8192
    kernel_filename = NULL;
8193
    kernel_cmdline = "";
8194
    cyls = heads = secs = 0;
8195
    translation = BIOS_ATA_TRANSLATION_AUTO;
8196
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8197

    
8198
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8199
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
8200
        serial_devices[i][0] = '\0';
8201
    serial_device_index = 0;
8202

    
8203
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8204
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8205
        parallel_devices[i][0] = '\0';
8206
    parallel_device_index = 0;
8207

    
8208
    usb_devices_index = 0;
8209

    
8210
    nb_net_clients = 0;
8211
    nb_drives = 0;
8212
    nb_drives_opt = 0;
8213
    hda_index = -1;
8214

    
8215
    nb_nics = 0;
8216
    /* default mac address of the first network interface */
8217

    
8218
    optind = 1;
8219
    for(;;) {
8220
        if (optind >= argc)
8221
            break;
8222
        r = argv[optind];
8223
        if (r[0] != '-') {
8224
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8225
        } else {
8226
            const QEMUOption *popt;
8227

    
8228
            optind++;
8229
            /* Treat --foo the same as -foo.  */
8230
            if (r[1] == '-')
8231
                r++;
8232
            popt = qemu_options;
8233
            for(;;) {
8234
                if (!popt->name) {
8235
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
8236
                            argv[0], r);
8237
                    exit(1);
8238
                }
8239
                if (!strcmp(popt->name, r + 1))
8240
                    break;
8241
                popt++;
8242
            }
8243
            if (popt->flags & HAS_ARG) {
8244
                if (optind >= argc) {
8245
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
8246
                            argv[0], r);
8247
                    exit(1);
8248
                }
8249
                optarg = argv[optind++];
8250
            } else {
8251
                optarg = NULL;
8252
            }
8253

    
8254
            switch(popt->index) {
8255
            case QEMU_OPTION_M:
8256
                machine = find_machine(optarg);
8257
                if (!machine) {
8258
                    QEMUMachine *m;
8259
                    printf("Supported machines are:\n");
8260
                    for(m = first_machine; m != NULL; m = m->next) {
8261
                        printf("%-10s %s%s\n",
8262
                               m->name, m->desc,
8263
                               m == first_machine ? " (default)" : "");
8264
                    }
8265
                    exit(*optarg != '?');
8266
                }
8267
                break;
8268
            case QEMU_OPTION_cpu:
8269
                /* hw initialization will check this */
8270
                if (*optarg == '?') {
8271
/* XXX: implement xxx_cpu_list for targets that still miss it */
8272
#if defined(cpu_list)
8273
                    cpu_list(stdout, &fprintf);
8274
#endif
8275
                    exit(0);
8276
                } else {
8277
                    cpu_model = optarg;
8278
                }
8279
                break;
8280
            case QEMU_OPTION_initrd:
8281
                initrd_filename = optarg;
8282
                break;
8283
            case QEMU_OPTION_hda:
8284
                if (cyls == 0)
8285
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
8286
                else
8287
                    hda_index = drive_add(optarg, HD_ALIAS
8288
                             ",cyls=%d,heads=%d,secs=%d%s",
8289
                             0, cyls, heads, secs,
8290
                             translation == BIOS_ATA_TRANSLATION_LBA ?
8291
                                 ",trans=lba" :
8292
                             translation == BIOS_ATA_TRANSLATION_NONE ?
8293
                                 ",trans=none" : "");
8294
                 break;
8295
            case QEMU_OPTION_hdb:
8296
            case QEMU_OPTION_hdc:
8297
            case QEMU_OPTION_hdd:
8298
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8299
                break;
8300
            case QEMU_OPTION_drive:
8301
                drive_add(NULL, "%s", optarg);
8302
                break;
8303
            case QEMU_OPTION_mtdblock:
8304
                drive_add(optarg, MTD_ALIAS);
8305
                break;
8306
            case QEMU_OPTION_sd:
8307
                drive_add(optarg, SD_ALIAS);
8308
                break;
8309
            case QEMU_OPTION_pflash:
8310
                drive_add(optarg, PFLASH_ALIAS);
8311
                break;
8312
            case QEMU_OPTION_snapshot:
8313
                snapshot = 1;
8314
                break;
8315
            case QEMU_OPTION_hdachs:
8316
                {
8317
                    const char *p;
8318
                    p = optarg;
8319
                    cyls = strtol(p, (char **)&p, 0);
8320
                    if (cyls < 1 || cyls > 16383)
8321
                        goto chs_fail;
8322
                    if (*p != ',')
8323
                        goto chs_fail;
8324
                    p++;
8325
                    heads = strtol(p, (char **)&p, 0);
8326
                    if (heads < 1 || heads > 16)
8327
                        goto chs_fail;
8328
                    if (*p != ',')
8329
                        goto chs_fail;
8330
                    p++;
8331
                    secs = strtol(p, (char **)&p, 0);
8332
                    if (secs < 1 || secs > 63)
8333
                        goto chs_fail;
8334
                    if (*p == ',') {
8335
                        p++;
8336
                        if (!strcmp(p, "none"))
8337
                            translation = BIOS_ATA_TRANSLATION_NONE;
8338
                        else if (!strcmp(p, "lba"))
8339
                            translation = BIOS_ATA_TRANSLATION_LBA;
8340
                        else if (!strcmp(p, "auto"))
8341
                            translation = BIOS_ATA_TRANSLATION_AUTO;
8342
                        else
8343
                            goto chs_fail;
8344
                    } else if (*p != '\0') {
8345
                    chs_fail:
8346
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
8347
                        exit(1);
8348
                    }
8349
                    if (hda_index != -1)
8350
                        snprintf(drives_opt[hda_index].opt,
8351
                                 sizeof(drives_opt[hda_index].opt),
8352
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8353
                                 0, cyls, heads, secs,
8354
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
8355
                                         ",trans=lba" :
8356
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
8357
                                     ",trans=none" : "");
8358
                }
8359
                break;
8360
            case QEMU_OPTION_nographic:
8361
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8362
                pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8363
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8364
                nographic = 1;
8365
                break;
8366
            case QEMU_OPTION_portrait:
8367
                graphic_rotate = 1;
8368
                break;
8369
            case QEMU_OPTION_kernel:
8370
                kernel_filename = optarg;
8371
                break;
8372
            case QEMU_OPTION_append:
8373
                kernel_cmdline = optarg;
8374
                break;
8375
            case QEMU_OPTION_cdrom:
8376
                drive_add(optarg, CDROM_ALIAS);
8377
                break;
8378
            case QEMU_OPTION_boot:
8379
                boot_devices = optarg;
8380
                /* We just do some generic consistency checks */
8381
                {
8382
                    /* Could easily be extended to 64 devices if needed */
8383
                    const char *p;
8384
                    
8385
                    boot_devices_bitmap = 0;
8386
                    for (p = boot_devices; *p != '\0'; p++) {
8387
                        /* Allowed boot devices are:
8388
                         * a b     : floppy disk drives
8389
                         * c ... f : IDE disk drives
8390
                         * g ... m : machine implementation dependant drives
8391
                         * n ... p : network devices
8392
                         * It's up to each machine implementation to check
8393
                         * if the given boot devices match the actual hardware
8394
                         * implementation and firmware features.
8395
                         */
8396
                        if (*p < 'a' || *p > 'q') {
8397
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
8398
                            exit(1);
8399
                        }
8400
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8401
                            fprintf(stderr,
8402
                                    "Boot device '%c' was given twice\n",*p);
8403
                            exit(1);
8404
                        }
8405
                        boot_devices_bitmap |= 1 << (*p - 'a');
8406
                    }
8407
                }
8408
                break;
8409
            case QEMU_OPTION_fda:
8410
            case QEMU_OPTION_fdb:
8411
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8412
                break;
8413
#ifdef TARGET_I386
8414
            case QEMU_OPTION_no_fd_bootchk:
8415
                fd_bootchk = 0;
8416
                break;
8417
#endif
8418
            case QEMU_OPTION_no_code_copy:
8419
                code_copy_enabled = 0;
8420
                break;
8421
            case QEMU_OPTION_net:
8422
                if (nb_net_clients >= MAX_NET_CLIENTS) {
8423
                    fprintf(stderr, "qemu: too many network clients\n");
8424
                    exit(1);
8425
                }
8426
                pstrcpy(net_clients[nb_net_clients],
8427
                        sizeof(net_clients[0]),
8428
                        optarg);
8429
                nb_net_clients++;
8430
                break;
8431
#ifdef CONFIG_SLIRP
8432
            case QEMU_OPTION_tftp:
8433
                tftp_prefix = optarg;
8434
                break;
8435
            case QEMU_OPTION_bootp:
8436
                bootp_filename = optarg;
8437
                break;
8438
#ifndef _WIN32
8439
            case QEMU_OPTION_smb:
8440
                net_slirp_smb(optarg);
8441
                break;
8442
#endif
8443
            case QEMU_OPTION_redir:
8444
                net_slirp_redir(optarg);
8445
                break;
8446
#endif
8447
#ifdef HAS_AUDIO
8448
            case QEMU_OPTION_audio_help:
8449
                AUD_help ();
8450
                exit (0);
8451
                break;
8452
            case QEMU_OPTION_soundhw:
8453
                select_soundhw (optarg);
8454
                break;
8455
#endif
8456
            case QEMU_OPTION_h:
8457
                help(0);
8458
                break;
8459
            case QEMU_OPTION_m:
8460
                ram_size = atoi(optarg) * 1024 * 1024;
8461
                if (ram_size <= 0)
8462
                    help(1);
8463
                if (ram_size > PHYS_RAM_MAX_SIZE) {
8464
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8465
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
8466
                    exit(1);
8467
                }
8468
                break;
8469
            case QEMU_OPTION_d:
8470
                {
8471
                    int mask;
8472
                    CPULogItem *item;
8473

    
8474
                    mask = cpu_str_to_log_mask(optarg);
8475
                    if (!mask) {
8476
                        printf("Log items (comma separated):\n");
8477
                    for(item = cpu_log_items; item->mask != 0; item++) {
8478
                        printf("%-10s %s\n", item->name, item->help);
8479
                    }
8480
                    exit(1);
8481
                    }
8482
                    cpu_set_log(mask);
8483
                }
8484
                break;
8485
#ifdef CONFIG_GDBSTUB
8486
            case QEMU_OPTION_s:
8487
                use_gdbstub = 1;
8488
                break;
8489
            case QEMU_OPTION_p:
8490
                gdbstub_port = optarg;
8491
                break;
8492
#endif
8493
            case QEMU_OPTION_L:
8494
                bios_dir = optarg;
8495
                break;
8496
            case QEMU_OPTION_bios:
8497
                bios_name = optarg;
8498
                break;
8499
            case QEMU_OPTION_S:
8500
                autostart = 0;
8501
                break;
8502
            case QEMU_OPTION_k:
8503
                keyboard_layout = optarg;
8504
                break;
8505
            case QEMU_OPTION_localtime:
8506
                rtc_utc = 0;
8507
                break;
8508
            case QEMU_OPTION_cirrusvga:
8509
                cirrus_vga_enabled = 1;
8510
                vmsvga_enabled = 0;
8511
                break;
8512
            case QEMU_OPTION_vmsvga:
8513
                cirrus_vga_enabled = 0;
8514
                vmsvga_enabled = 1;
8515
                break;
8516
            case QEMU_OPTION_std_vga:
8517
                cirrus_vga_enabled = 0;
8518
                vmsvga_enabled = 0;
8519
                break;
8520
            case QEMU_OPTION_g:
8521
                {
8522
                    const char *p;
8523
                    int w, h, depth;
8524
                    p = optarg;
8525
                    w = strtol(p, (char **)&p, 10);
8526
                    if (w <= 0) {
8527
                    graphic_error:
8528
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8529
                        exit(1);
8530
                    }
8531
                    if (*p != 'x')
8532
                        goto graphic_error;
8533
                    p++;
8534
                    h = strtol(p, (char **)&p, 10);
8535
                    if (h <= 0)
8536
                        goto graphic_error;
8537
                    if (*p == 'x') {
8538
                        p++;
8539
                        depth = strtol(p, (char **)&p, 10);
8540
                        if (depth != 8 && depth != 15 && depth != 16 &&
8541
                            depth != 24 && depth != 32)
8542
                            goto graphic_error;
8543
                    } else if (*p == '\0') {
8544
                        depth = graphic_depth;
8545
                    } else {
8546
                        goto graphic_error;
8547
                    }
8548

    
8549
                    graphic_width = w;
8550
                    graphic_height = h;
8551
                    graphic_depth = depth;
8552
                }
8553
                break;
8554
            case QEMU_OPTION_echr:
8555
                {
8556
                    char *r;
8557
                    term_escape_char = strtol(optarg, &r, 0);
8558
                    if (r == optarg)
8559
                        printf("Bad argument to echr\n");
8560
                    break;
8561
                }
8562
            case QEMU_OPTION_monitor:
8563
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8564
                break;
8565
            case QEMU_OPTION_serial:
8566
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8567
                    fprintf(stderr, "qemu: too many serial ports\n");
8568
                    exit(1);
8569
                }
8570
                pstrcpy(serial_devices[serial_device_index],
8571
                        sizeof(serial_devices[0]), optarg);
8572
                serial_device_index++;
8573
                break;
8574
            case QEMU_OPTION_parallel:
8575
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8576
                    fprintf(stderr, "qemu: too many parallel ports\n");
8577
                    exit(1);
8578
                }
8579
                pstrcpy(parallel_devices[parallel_device_index],
8580
                        sizeof(parallel_devices[0]), optarg);
8581
                parallel_device_index++;
8582
                break;
8583
            case QEMU_OPTION_loadvm:
8584
                loadvm = optarg;
8585
                break;
8586
            case QEMU_OPTION_full_screen:
8587
                full_screen = 1;
8588
                break;
8589
#ifdef CONFIG_SDL
8590
            case QEMU_OPTION_no_frame:
8591
                no_frame = 1;
8592
                break;
8593
            case QEMU_OPTION_alt_grab:
8594
                alt_grab = 1;
8595
                break;
8596
            case QEMU_OPTION_no_quit:
8597
                no_quit = 1;
8598
                break;
8599
#endif
8600
            case QEMU_OPTION_pidfile:
8601
                pid_file = optarg;
8602
                break;
8603
#ifdef TARGET_I386
8604
            case QEMU_OPTION_win2k_hack:
8605
                win2k_install_hack = 1;
8606
                break;
8607
#endif
8608
#ifdef USE_KQEMU
8609
            case QEMU_OPTION_no_kqemu:
8610
                kqemu_allowed = 0;
8611
                break;
8612
            case QEMU_OPTION_kernel_kqemu:
8613
                kqemu_allowed = 2;
8614
                break;
8615
#endif
8616
            case QEMU_OPTION_usb:
8617
                usb_enabled = 1;
8618
                break;
8619
            case QEMU_OPTION_usbdevice:
8620
                usb_enabled = 1;
8621
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8622
                    fprintf(stderr, "Too many USB devices\n");
8623
                    exit(1);
8624
                }
8625
                pstrcpy(usb_devices[usb_devices_index],
8626
                        sizeof(usb_devices[usb_devices_index]),
8627
                        optarg);
8628
                usb_devices_index++;
8629
                break;
8630
            case QEMU_OPTION_smp:
8631
                smp_cpus = atoi(optarg);
8632
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8633
                    fprintf(stderr, "Invalid number of CPUs\n");
8634
                    exit(1);
8635
                }
8636
                break;
8637
            case QEMU_OPTION_vnc:
8638
                vnc_display = optarg;
8639
                break;
8640
            case QEMU_OPTION_no_acpi:
8641
                acpi_enabled = 0;
8642
                break;
8643
            case QEMU_OPTION_no_reboot:
8644
                no_reboot = 1;
8645
                break;
8646
            case QEMU_OPTION_show_cursor:
8647
                cursor_hide = 0;
8648
                break;
8649
            case QEMU_OPTION_daemonize:
8650
                daemonize = 1;
8651
                break;
8652
            case QEMU_OPTION_option_rom:
8653
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8654
                    fprintf(stderr, "Too many option ROMs\n");
8655
                    exit(1);
8656
                }
8657
                option_rom[nb_option_roms] = optarg;
8658
                nb_option_roms++;
8659
                break;
8660
            case QEMU_OPTION_semihosting:
8661
                semihosting_enabled = 1;
8662
                break;
8663
            case QEMU_OPTION_name:
8664
                qemu_name = optarg;
8665
                break;
8666
#ifdef TARGET_SPARC
8667
            case QEMU_OPTION_prom_env:
8668
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8669
                    fprintf(stderr, "Too many prom variables\n");
8670
                    exit(1);
8671
                }
8672
                prom_envs[nb_prom_envs] = optarg;
8673
                nb_prom_envs++;
8674
                break;
8675
#endif
8676
#ifdef TARGET_ARM
8677
            case QEMU_OPTION_old_param:
8678
                old_param = 1;
8679
                break;
8680
#endif
8681
            case QEMU_OPTION_clock:
8682
                configure_alarms(optarg);
8683
                break;
8684
            case QEMU_OPTION_startdate:
8685
                {
8686
                    struct tm tm;
8687
                    if (!strcmp(optarg, "now")) {
8688
                        rtc_start_date = -1;
8689
                    } else {
8690
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8691
                               &tm.tm_year,
8692
                               &tm.tm_mon,
8693
                               &tm.tm_mday,
8694
                               &tm.tm_hour,
8695
                               &tm.tm_min,
8696
                               &tm.tm_sec) == 6) {
8697
                            /* OK */
8698
                        } else if (sscanf(optarg, "%d-%d-%d",
8699
                                          &tm.tm_year,
8700
                                          &tm.tm_mon,
8701
                                          &tm.tm_mday) == 3) {
8702
                            tm.tm_hour = 0;
8703
                            tm.tm_min = 0;
8704
                            tm.tm_sec = 0;
8705
                        } else {
8706
                            goto date_fail;
8707
                        }
8708
                        tm.tm_year -= 1900;
8709
                        tm.tm_mon--;
8710
                        rtc_start_date = mktimegm(&tm);
8711
                        if (rtc_start_date == -1) {
8712
                        date_fail:
8713
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8714
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8715
                            exit(1);
8716
                        }
8717
                    }
8718
                }
8719
                break;
8720
            }
8721
        }
8722
    }
8723

    
8724
#ifndef _WIN32
8725
    if (daemonize && !nographic && vnc_display == NULL) {
8726
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8727
        daemonize = 0;
8728
    }
8729

    
8730
    if (daemonize) {
8731
        pid_t pid;
8732

    
8733
        if (pipe(fds) == -1)
8734
            exit(1);
8735

    
8736
        pid = fork();
8737
        if (pid > 0) {
8738
            uint8_t status;
8739
            ssize_t len;
8740

    
8741
            close(fds[1]);
8742

    
8743
        again:
8744
            len = read(fds[0], &status, 1);
8745
            if (len == -1 && (errno == EINTR))
8746
                goto again;
8747

    
8748
            if (len != 1)
8749
                exit(1);
8750
            else if (status == 1) {
8751
                fprintf(stderr, "Could not acquire pidfile\n");
8752
                exit(1);
8753
            } else
8754
                exit(0);
8755
        } else if (pid < 0)
8756
            exit(1);
8757

    
8758
        setsid();
8759

    
8760
        pid = fork();
8761
        if (pid > 0)
8762
            exit(0);
8763
        else if (pid < 0)
8764
            exit(1);
8765

    
8766
        umask(027);
8767
        chdir("/");
8768

    
8769
        signal(SIGTSTP, SIG_IGN);
8770
        signal(SIGTTOU, SIG_IGN);
8771
        signal(SIGTTIN, SIG_IGN);
8772
    }
8773
#endif
8774

    
8775
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8776
        if (daemonize) {
8777
            uint8_t status = 1;
8778
            write(fds[1], &status, 1);
8779
        } else
8780
            fprintf(stderr, "Could not acquire pid file\n");
8781
        exit(1);
8782
    }
8783

    
8784
#ifdef USE_KQEMU
8785
    if (smp_cpus > 1)
8786
        kqemu_allowed = 0;
8787
#endif
8788
    linux_boot = (kernel_filename != NULL);
8789
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8790

    
8791
    /* XXX: this should not be: some embedded targets just have flash */
8792
    if (!linux_boot && net_boot == 0 &&
8793
        nb_drives_opt == 0)
8794
        help(1);
8795

    
8796
    /* boot to floppy or the default cd if no hard disk defined yet */
8797
    if (!boot_devices[0]) {
8798
        boot_devices = "cad";
8799
    }
8800
    setvbuf(stdout, NULL, _IOLBF, 0);
8801

    
8802
    init_timers();
8803
    init_timer_alarm();
8804
    qemu_aio_init();
8805

    
8806
#ifdef _WIN32
8807
    socket_init();
8808
#endif
8809

    
8810
    /* init network clients */
8811
    if (nb_net_clients == 0) {
8812
        /* if no clients, we use a default config */
8813
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
8814
                "nic");
8815
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
8816
                "user");
8817
        nb_net_clients = 2;
8818
    }
8819

    
8820
    for(i = 0;i < nb_net_clients; i++) {
8821
        if (net_client_init(net_clients[i]) < 0)
8822
            exit(1);
8823
    }
8824
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8825
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8826
            continue;
8827
        if (vlan->nb_guest_devs == 0) {
8828
            fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8829
            exit(1);
8830
        }
8831
        if (vlan->nb_host_devs == 0)
8832
            fprintf(stderr,
8833
                    "Warning: vlan %d is not connected to host network\n",
8834
                    vlan->id);
8835
    }
8836

    
8837
#ifdef TARGET_I386
8838
    /* XXX: this should be moved in the PC machine instantiation code */
8839
    if (net_boot != 0) {
8840
        int netroms = 0;
8841
        for (i = 0; i < nb_nics && i < 4; i++) {
8842
            const char *model = nd_table[i].model;
8843
            char buf[1024];
8844
            if (net_boot & (1 << i)) {
8845
                if (model == NULL)
8846
                    model = "ne2k_pci";
8847
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8848
                if (get_image_size(buf) > 0) {
8849
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8850
                        fprintf(stderr, "Too many option ROMs\n");
8851
                        exit(1);
8852
                    }
8853
                    option_rom[nb_option_roms] = strdup(buf);
8854
                    nb_option_roms++;
8855
                    netroms++;
8856
                }
8857
            }
8858
        }
8859
        if (netroms == 0) {
8860
            fprintf(stderr, "No valid PXE rom found for network device\n");
8861
            exit(1);
8862
        }
8863
    }
8864
#endif
8865

    
8866
    /* init the memory */
8867
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8868

    
8869
    phys_ram_base = qemu_vmalloc(phys_ram_size);
8870
    if (!phys_ram_base) {
8871
        fprintf(stderr, "Could not allocate physical memory\n");
8872
        exit(1);
8873
    }
8874

    
8875
    bdrv_init();
8876

    
8877
    /* we always create the cdrom drive, even if no disk is there */
8878

    
8879
    if (nb_drives_opt < MAX_DRIVES)
8880
        drive_add(NULL, CDROM_ALIAS);
8881

    
8882
    /* we always create at least one floppy */
8883

    
8884
    if (nb_drives_opt < MAX_DRIVES)
8885
        drive_add(NULL, FD_ALIAS, 0);
8886

    
8887
    /* we always create one sd slot, even if no card is in it */
8888

    
8889
    if (nb_drives_opt < MAX_DRIVES)
8890
        drive_add(NULL, SD_ALIAS);
8891

    
8892
    /* open the virtual block devices */
8893

    
8894
    for(i = 0; i < nb_drives_opt; i++)
8895
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8896
            exit(1);
8897

    
8898
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8899
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8900

    
8901
    init_ioports();
8902

    
8903
    /* terminal init */
8904
    memset(&display_state, 0, sizeof(display_state));
8905
    if (nographic) {
8906
        /* nearly nothing to do */
8907
        dumb_display_init(ds);
8908
    } else if (vnc_display != NULL) {
8909
        vnc_display_init(ds);
8910
        if (vnc_display_open(ds, vnc_display) < 0)
8911
            exit(1);
8912
    } else {
8913
#if defined(CONFIG_SDL)
8914
        sdl_display_init(ds, full_screen, no_frame);
8915
#elif defined(CONFIG_COCOA)
8916
        cocoa_display_init(ds, full_screen);
8917
#else
8918
        dumb_display_init(ds);
8919
#endif
8920
    }
8921

    
8922
    /* Maintain compatibility with multiple stdio monitors */
8923
    if (!strcmp(monitor_device,"stdio")) {
8924
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8925
            if (!strcmp(serial_devices[i],"mon:stdio")) {
8926
                monitor_device[0] = '\0';
8927
                break;
8928
            } else if (!strcmp(serial_devices[i],"stdio")) {
8929
                monitor_device[0] = '\0';
8930
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8931
                break;
8932
            }
8933
        }
8934
    }
8935
    if (monitor_device[0] != '\0') {
8936
        monitor_hd = qemu_chr_open(monitor_device);
8937
        if (!monitor_hd) {
8938
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8939
            exit(1);
8940
        }
8941
        monitor_init(monitor_hd, !nographic);
8942
    }
8943

    
8944
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8945
        const char *devname = serial_devices[i];
8946
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8947
            serial_hds[i] = qemu_chr_open(devname);
8948
            if (!serial_hds[i]) {
8949
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
8950
                        devname);
8951
                exit(1);
8952
            }
8953
            if (strstart(devname, "vc", 0))
8954
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8955
        }
8956
    }
8957

    
8958
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8959
        const char *devname = parallel_devices[i];
8960
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8961
            parallel_hds[i] = qemu_chr_open(devname);
8962
            if (!parallel_hds[i]) {
8963
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8964
                        devname);
8965
                exit(1);
8966
            }
8967
            if (strstart(devname, "vc", 0))
8968
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8969
        }
8970
    }
8971

    
8972
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
8973
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8974

    
8975
    /* init USB devices */
8976
    if (usb_enabled) {
8977
        for(i = 0; i < usb_devices_index; i++) {
8978
            if (usb_device_add(usb_devices[i]) < 0) {
8979
                fprintf(stderr, "Warning: could not add USB device %s\n",
8980
                        usb_devices[i]);
8981
            }
8982
        }
8983
    }
8984

    
8985
    if (display_state.dpy_refresh) {
8986
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8987
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8988
    }
8989

    
8990
#ifdef CONFIG_GDBSTUB
8991
    if (use_gdbstub) {
8992
        /* XXX: use standard host:port notation and modify options
8993
           accordingly. */
8994
        if (gdbserver_start(gdbstub_port) < 0) {
8995
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8996
                    gdbstub_port);
8997
            exit(1);
8998
        }
8999
    }
9000
#endif
9001

    
9002
    if (loadvm)
9003
        do_loadvm(loadvm);
9004

    
9005
    {
9006
        /* XXX: simplify init */
9007
        read_passwords();
9008
        if (autostart) {
9009
            vm_start();
9010
        }
9011
    }
9012

    
9013
    if (daemonize) {
9014
        uint8_t status = 0;
9015
        ssize_t len;
9016
        int fd;
9017

    
9018
    again1:
9019
        len = write(fds[1], &status, 1);
9020
        if (len == -1 && (errno == EINTR))
9021
            goto again1;
9022

    
9023
        if (len != 1)
9024
            exit(1);
9025

    
9026
        TFR(fd = open("/dev/null", O_RDWR));
9027
        if (fd == -1)
9028
            exit(1);
9029

    
9030
        dup2(fd, 0);
9031
        dup2(fd, 1);
9032
        dup2(fd, 2);
9033

    
9034
        close(fd);
9035
    }
9036

    
9037
    main_loop();
9038
    quit_timers();
9039

    
9040
#if !defined(_WIN32)
9041
    /* close network clients */
9042
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9043
        VLANClientState *vc;
9044

    
9045
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9046
            if (vc->fd_read == tap_receive) {
9047
                char ifname[64];
9048
                TAPState *s = vc->opaque;
9049

    
9050
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9051
                    s->down_script[0])
9052
                    launch_script(s->down_script, ifname, s->fd);
9053
            }
9054
        }
9055
    }
9056
#endif
9057
    return 0;
9058
}