Statistics
| Branch: | Revision:

root / vl.c @ bee8d684

History | View | Annotate | Download (231.8 kB)

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

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

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

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

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

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

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

    
117
#include "qemu_socket.h"
118

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

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

    
130
#include "disas.h"
131

    
132
#include "exec-all.h"
133

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

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

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

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

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

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

    
161
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
162
const char *bios_name = NULL;
163
void *ioport_opaque[MAX_IOPORTS];
164
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
165
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
166
/* Note: 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
char drives_opt[MAX_DRIVES][1024];
235

    
236
static CPUState *cur_cpu;
237
static CPUState *next_cpu;
238
static int event_pending = 1;
239

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

    
242
/***********************************************************/
243
/* x86 ISA bus support */
244

    
245
target_phys_addr_t isa_mem_base = 0;
246
PicState2 *isa_pic;
247

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

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

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

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

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

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

    
295
static void init_ioports(void)
296
{
297
    int i;
298

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

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

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

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

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

    
359
void isa_unassign_ioport(int start, int length)
360
{
361
    int i;
362

    
363
    for(i = start; i < start + length; i++) {
364
        ioport_read_table[0][i] = default_ioport_readb;
365
        ioport_read_table[1][i] = default_ioport_readw;
366
        ioport_read_table[2][i] = default_ioport_readl;
367

    
368
        ioport_write_table[0][i] = default_ioport_writeb;
369
        ioport_write_table[1][i] = default_ioport_writew;
370
        ioport_write_table[2][i] = default_ioport_writel;
371
    }
372
}
373

    
374
/***********************************************************/
375

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

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

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

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

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

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

    
460
/***********************************************************/
461
void hw_error(const char *fmt, ...)
462
{
463
    va_list ap;
464
    CPUState *env;
465

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

    
482
/***********************************************************/
483
/* keyboard/mouse */
484

    
485
static QEMUPutKBDEvent *qemu_put_kbd_event;
486
static void *qemu_put_kbd_event_opaque;
487
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
488
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
489

    
490
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
491
{
492
    qemu_put_kbd_event_opaque = opaque;
493
    qemu_put_kbd_event = func;
494
}
495

    
496
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
497
                                                void *opaque, int absolute,
498
                                                const char *name)
499
{
500
    QEMUPutMouseEntry *s, *cursor;
501

    
502
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
503
    if (!s)
504
        return NULL;
505

    
506
    s->qemu_put_mouse_event = func;
507
    s->qemu_put_mouse_event_opaque = opaque;
508
    s->qemu_put_mouse_event_absolute = absolute;
509
    s->qemu_put_mouse_event_name = qemu_strdup(name);
510
    s->next = NULL;
511

    
512
    if (!qemu_put_mouse_event_head) {
513
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
514
        return s;
515
    }
516

    
517
    cursor = qemu_put_mouse_event_head;
518
    while (cursor->next != NULL)
519
        cursor = cursor->next;
520

    
521
    cursor->next = s;
522
    qemu_put_mouse_event_current = s;
523

    
524
    return s;
525
}
526

    
527
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
528
{
529
    QEMUPutMouseEntry *prev = NULL, *cursor;
530

    
531
    if (!qemu_put_mouse_event_head || entry == NULL)
532
        return;
533

    
534
    cursor = qemu_put_mouse_event_head;
535
    while (cursor != NULL && cursor != entry) {
536
        prev = cursor;
537
        cursor = cursor->next;
538
    }
539

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

    
551
    prev->next = entry->next;
552

    
553
    if (qemu_put_mouse_event_current == entry)
554
        qemu_put_mouse_event_current = prev;
555

    
556
    qemu_free(entry->qemu_put_mouse_event_name);
557
    qemu_free(entry);
558
}
559

    
560
void kbd_put_keycode(int keycode)
561
{
562
    if (qemu_put_kbd_event) {
563
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
564
    }
565
}
566

    
567
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
568
{
569
    QEMUPutMouseEvent *mouse_event;
570
    void *mouse_event_opaque;
571
    int width;
572

    
573
    if (!qemu_put_mouse_event_current) {
574
        return;
575
    }
576

    
577
    mouse_event =
578
        qemu_put_mouse_event_current->qemu_put_mouse_event;
579
    mouse_event_opaque =
580
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
581

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

    
596
int kbd_mouse_is_absolute(void)
597
{
598
    if (!qemu_put_mouse_event_current)
599
        return 0;
600

    
601
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
602
}
603

    
604
void do_info_mice(void)
605
{
606
    QEMUPutMouseEntry *cursor;
607
    int index = 0;
608

    
609
    if (!qemu_put_mouse_event_head) {
610
        term_printf("No mouse devices connected\n");
611
        return;
612
    }
613

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

    
625
void do_mouse_set(int index)
626
{
627
    QEMUPutMouseEntry *cursor;
628
    int i = 0;
629

    
630
    if (!qemu_put_mouse_event_head) {
631
        term_printf("No mouse devices connected\n");
632
        return;
633
    }
634

    
635
    cursor = qemu_put_mouse_event_head;
636
    while (cursor != NULL && index != i) {
637
        i++;
638
        cursor = cursor->next;
639
    }
640

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

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

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

    
671
/***********************************************************/
672
/* real time host monotonic timer */
673

    
674
#define QEMU_TIMER_BASE 1000000000LL
675

    
676
#ifdef WIN32
677

    
678
static int64_t clock_freq;
679

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

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

    
699
#else
700

    
701
static int use_rt_clock;
702

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

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

    
734
#endif
735

    
736
/***********************************************************/
737
/* guest cycle counter */
738

    
739
static int64_t cpu_ticks_prev;
740
static int64_t cpu_ticks_offset;
741
static int64_t cpu_clock_offset;
742
static int cpu_ticks_enabled;
743

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

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

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

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

    
795
/***********************************************************/
796
/* timers */
797

    
798
#define QEMU_TIMER_REALTIME 0
799
#define QEMU_TIMER_VIRTUAL  1
800

    
801
struct QEMUClock {
802
    int type;
803
    /* XXX: add frequency */
804
};
805

    
806
struct QEMUTimer {
807
    QEMUClock *clock;
808
    int64_t expire_time;
809
    QEMUTimerCB *cb;
810
    void *opaque;
811
    struct QEMUTimer *next;
812
};
813

    
814
struct qemu_alarm_timer {
815
    char const *name;
816
    unsigned int flags;
817

    
818
    int (*start)(struct qemu_alarm_timer *t);
819
    void (*stop)(struct qemu_alarm_timer *t);
820
    void (*rearm)(struct qemu_alarm_timer *t);
821
    void *priv;
822
};
823

    
824
#define ALARM_FLAG_DYNTICKS  0x1
825
#define ALARM_FLAG_MODIFIED  0x2
826

    
827
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
828
{
829
    return t->flags & ALARM_FLAG_DYNTICKS;
830
}
831

    
832
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
833
{
834
    if (!alarm_has_dynticks(t))
835
        return;
836

    
837
    if (!(t->flags & ALARM_FLAG_MODIFIED))
838
        return;
839

    
840
    t->flags &= ~(ALARM_FLAG_MODIFIED);
841

    
842
    t->rearm(t);
843
}
844

    
845
/* TODO: MIN_TIMER_REARM_US should be optimized */
846
#define MIN_TIMER_REARM_US 250
847

    
848
static struct qemu_alarm_timer *alarm_timer;
849

    
850
#ifdef _WIN32
851

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

    
858
static int win32_start_timer(struct qemu_alarm_timer *t);
859
static void win32_stop_timer(struct qemu_alarm_timer *t);
860
static void win32_rearm_timer(struct qemu_alarm_timer *t);
861

    
862
#else
863

    
864
static int unix_start_timer(struct qemu_alarm_timer *t);
865
static void unix_stop_timer(struct qemu_alarm_timer *t);
866

    
867
#ifdef __linux__
868

    
869
static int dynticks_start_timer(struct qemu_alarm_timer *t);
870
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
871
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
872

    
873
static int hpet_start_timer(struct qemu_alarm_timer *t);
874
static void hpet_stop_timer(struct qemu_alarm_timer *t);
875

    
876
static int rtc_start_timer(struct qemu_alarm_timer *t);
877
static void rtc_stop_timer(struct qemu_alarm_timer *t);
878

    
879
#endif /* __linux__ */
880

    
881
#endif /* _WIN32 */
882

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

    
903
static void show_available_alarms()
904
{
905
    int i;
906

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

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

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

    
925
    arg = strdup(opt);
926

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

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

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

    
942
        if (i < cur)
943
            /* Ignore */
944
            goto next;
945

    
946
        /* Swap */
947
        tmp = alarm_timers[i];
948
        alarm_timers[i] = alarm_timers[cur];
949
        alarm_timers[cur] = tmp;
950

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

    
956
    free(arg);
957

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

    
964
    /* debug */
965
    show_available_alarms();
966
}
967

    
968
QEMUClock *rt_clock;
969
QEMUClock *vm_clock;
970

    
971
static QEMUTimer *active_timers[2];
972

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

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

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

    
994
void qemu_free_timer(QEMUTimer *ts)
995
{
996
    qemu_free(ts);
997
}
998

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

    
1004
    alarm_timer->flags |= ALARM_FLAG_MODIFIED;
1005

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

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

    
1027
    qemu_del_timer(ts);
1028

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1231
    return nearest_delta_us;
1232
}
1233

    
1234
#ifndef _WIN32
1235

    
1236
#if defined(__linux__)
1237

    
1238
#define RTC_FREQ 1024
1239

    
1240
static void enable_sigio_timer(int fd)
1241
{
1242
    struct sigaction act;
1243

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

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

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

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

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

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

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

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

    
1287
    enable_sigio_timer(fd);
1288
    t->priv = (void *)(long)fd;
1289

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

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

    
1300
    close(fd);
1301
}
1302

    
1303
static int rtc_start_timer(struct qemu_alarm_timer *t)
1304
{
1305
    int rtc_fd;
1306

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

    
1322
    enable_sigio_timer(rtc_fd);
1323

    
1324
    t->priv = (void *)(long)rtc_fd;
1325

    
1326
    return 0;
1327
}
1328

    
1329
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1330
{
1331
    int rtc_fd = (long)t->priv;
1332

    
1333
    close(rtc_fd);
1334
}
1335

    
1336
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1337
{
1338
    struct sigevent ev;
1339
    timer_t host_timer;
1340
    struct sigaction act;
1341

    
1342
    sigfillset(&act.sa_mask);
1343
    act.sa_flags = 0;
1344
    act.sa_handler = host_alarm_handler;
1345

    
1346
    sigaction(SIGALRM, &act, NULL);
1347

    
1348
    ev.sigev_value.sival_int = 0;
1349
    ev.sigev_notify = SIGEV_SIGNAL;
1350
    ev.sigev_signo = SIGALRM;
1351

    
1352
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1353
        perror("timer_create");
1354

    
1355
        /* disable dynticks */
1356
        fprintf(stderr, "Dynamic Ticks disabled\n");
1357

    
1358
        return -1;
1359
    }
1360

    
1361
    t->priv = (void *)host_timer;
1362

    
1363
    return 0;
1364
}
1365

    
1366
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1367
{
1368
    timer_t host_timer = (timer_t)t->priv;
1369

    
1370
    timer_delete(host_timer);
1371
}
1372

    
1373
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1374
{
1375
    timer_t host_timer = (timer_t)t->priv;
1376
    struct itimerspec timeout;
1377
    int64_t nearest_delta_us = INT64_MAX;
1378
    int64_t current_us;
1379

    
1380
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1381
                !active_timers[QEMU_TIMER_VIRTUAL])
1382
            return;
1383

    
1384
    nearest_delta_us = qemu_next_deadline();
1385

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

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

    
1407
#endif /* defined(__linux__) */
1408

    
1409
static int unix_start_timer(struct qemu_alarm_timer *t)
1410
{
1411
    struct sigaction act;
1412
    struct itimerval itv;
1413
    int err;
1414

    
1415
    /* timer signal */
1416
    sigfillset(&act.sa_mask);
1417
    act.sa_flags = 0;
1418
    act.sa_handler = host_alarm_handler;
1419

    
1420
    sigaction(SIGALRM, &act, NULL);
1421

    
1422
    itv.it_interval.tv_sec = 0;
1423
    /* for i386 kernel 2.6 to get 1 ms */
1424
    itv.it_interval.tv_usec = 999;
1425
    itv.it_value.tv_sec = 0;
1426
    itv.it_value.tv_usec = 10 * 1000;
1427

    
1428
    err = setitimer(ITIMER_REAL, &itv, NULL);
1429
    if (err)
1430
        return -1;
1431

    
1432
    return 0;
1433
}
1434

    
1435
static void unix_stop_timer(struct qemu_alarm_timer *t)
1436
{
1437
    struct itimerval itv;
1438

    
1439
    memset(&itv, 0, sizeof(itv));
1440
    setitimer(ITIMER_REAL, &itv, NULL);
1441
}
1442

    
1443
#endif /* !defined(_WIN32) */
1444

    
1445
#ifdef _WIN32
1446

    
1447
static int win32_start_timer(struct qemu_alarm_timer *t)
1448
{
1449
    TIMECAPS tc;
1450
    struct qemu_alarm_win32 *data = t->priv;
1451
    UINT flags;
1452

    
1453
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1454
    if (!data->host_alarm) {
1455
        perror("Failed CreateEvent");
1456
        return -1;
1457
    }
1458

    
1459
    memset(&tc, 0, sizeof(tc));
1460
    timeGetDevCaps(&tc, sizeof(tc));
1461

    
1462
    if (data->period < tc.wPeriodMin)
1463
        data->period = tc.wPeriodMin;
1464

    
1465
    timeBeginPeriod(data->period);
1466

    
1467
    flags = TIME_CALLBACK_FUNCTION;
1468
    if (alarm_has_dynticks(t))
1469
        flags |= TIME_ONESHOT;
1470
    else
1471
        flags |= TIME_PERIODIC;
1472

    
1473
    data->timerId = timeSetEvent(1,         // interval (ms)
1474
                        data->period,       // resolution
1475
                        host_alarm_handler, // function
1476
                        (DWORD)t,           // parameter
1477
                        flags);
1478

    
1479
    if (!data->timerId) {
1480
        perror("Failed to initialize win32 alarm timer");
1481

    
1482
        timeEndPeriod(data->period);
1483
        CloseHandle(data->host_alarm);
1484
        return -1;
1485
    }
1486

    
1487
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1488

    
1489
    return 0;
1490
}
1491

    
1492
static void win32_stop_timer(struct qemu_alarm_timer *t)
1493
{
1494
    struct qemu_alarm_win32 *data = t->priv;
1495

    
1496
    timeKillEvent(data->timerId);
1497
    timeEndPeriod(data->period);
1498

    
1499
    CloseHandle(data->host_alarm);
1500
}
1501

    
1502
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1503
{
1504
    struct qemu_alarm_win32 *data = t->priv;
1505
    uint64_t nearest_delta_us;
1506

    
1507
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1508
                !active_timers[QEMU_TIMER_VIRTUAL])
1509
            return;
1510

    
1511
    nearest_delta_us = qemu_next_deadline();
1512
    nearest_delta_us /= 1000;
1513

    
1514
    timeKillEvent(data->timerId);
1515

    
1516
    data->timerId = timeSetEvent(1,
1517
                        data->period,
1518
                        host_alarm_handler,
1519
                        (DWORD)t,
1520
                        TIME_ONESHOT | TIME_PERIODIC);
1521

    
1522
    if (!data->timerId) {
1523
        perror("Failed to re-arm win32 alarm timer");
1524

    
1525
        timeEndPeriod(data->period);
1526
        CloseHandle(data->host_alarm);
1527
        exit(1);
1528
    }
1529
}
1530

    
1531
#endif /* _WIN32 */
1532

    
1533
static void init_timer_alarm(void)
1534
{
1535
    struct qemu_alarm_timer *t;
1536
    int i, err = -1;
1537

    
1538
    for (i = 0; alarm_timers[i].name; i++) {
1539
        t = &alarm_timers[i];
1540

    
1541
        err = t->start(t);
1542
        if (!err)
1543
            break;
1544
    }
1545

    
1546
    if (err) {
1547
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1548
        fprintf(stderr, "Terminating\n");
1549
        exit(1);
1550
    }
1551

    
1552
    alarm_timer = t;
1553
}
1554

    
1555
static void quit_timers(void)
1556
{
1557
    alarm_timer->stop(alarm_timer);
1558
    alarm_timer = NULL;
1559
}
1560

    
1561
/***********************************************************/
1562
/* character device */
1563

    
1564
static void qemu_chr_event(CharDriverState *s, int event)
1565
{
1566
    if (!s->chr_event)
1567
        return;
1568
    s->chr_event(s->handler_opaque, event);
1569
}
1570

    
1571
static void qemu_chr_reset_bh(void *opaque)
1572
{
1573
    CharDriverState *s = opaque;
1574
    qemu_chr_event(s, CHR_EVENT_RESET);
1575
    qemu_bh_delete(s->bh);
1576
    s->bh = NULL;
1577
}
1578

    
1579
void qemu_chr_reset(CharDriverState *s)
1580
{
1581
    if (s->bh == NULL) {
1582
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1583
        qemu_bh_schedule(s->bh);
1584
    }
1585
}
1586

    
1587
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1588
{
1589
    return s->chr_write(s, buf, len);
1590
}
1591

    
1592
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1593
{
1594
    if (!s->chr_ioctl)
1595
        return -ENOTSUP;
1596
    return s->chr_ioctl(s, cmd, arg);
1597
}
1598

    
1599
int qemu_chr_can_read(CharDriverState *s)
1600
{
1601
    if (!s->chr_can_read)
1602
        return 0;
1603
    return s->chr_can_read(s->handler_opaque);
1604
}
1605

    
1606
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1607
{
1608
    s->chr_read(s->handler_opaque, buf, len);
1609
}
1610

    
1611
void qemu_chr_accept_input(CharDriverState *s)
1612
{
1613
    if (s->chr_accept_input)
1614
        s->chr_accept_input(s);
1615
}
1616

    
1617
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1618
{
1619
    char buf[4096];
1620
    va_list ap;
1621
    va_start(ap, fmt);
1622
    vsnprintf(buf, sizeof(buf), fmt, ap);
1623
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1624
    va_end(ap);
1625
}
1626

    
1627
void qemu_chr_send_event(CharDriverState *s, int event)
1628
{
1629
    if (s->chr_send_event)
1630
        s->chr_send_event(s, event);
1631
}
1632

    
1633
void qemu_chr_add_handlers(CharDriverState *s,
1634
                           IOCanRWHandler *fd_can_read,
1635
                           IOReadHandler *fd_read,
1636
                           IOEventHandler *fd_event,
1637
                           void *opaque)
1638
{
1639
    s->chr_can_read = fd_can_read;
1640
    s->chr_read = fd_read;
1641
    s->chr_event = fd_event;
1642
    s->handler_opaque = opaque;
1643
    if (s->chr_update_read_handler)
1644
        s->chr_update_read_handler(s);
1645
}
1646

    
1647
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1648
{
1649
    return len;
1650
}
1651

    
1652
static CharDriverState *qemu_chr_open_null(void)
1653
{
1654
    CharDriverState *chr;
1655

    
1656
    chr = qemu_mallocz(sizeof(CharDriverState));
1657
    if (!chr)
1658
        return NULL;
1659
    chr->chr_write = null_chr_write;
1660
    return chr;
1661
}
1662

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

    
1683

    
1684
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1685
{
1686
    MuxDriver *d = chr->opaque;
1687
    int ret;
1688
    if (!term_timestamps) {
1689
        ret = d->drv->chr_write(d->drv, buf, len);
1690
    } else {
1691
        int i;
1692

    
1693
        ret = 0;
1694
        for(i = 0; i < len; i++) {
1695
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1696
            if (buf[i] == '\n') {
1697
                char buf1[64];
1698
                int64_t ti;
1699
                int secs;
1700

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

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

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

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

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

    
1804
static void mux_chr_accept_input(CharDriverState *chr)
1805
{
1806
    int m = chr->focus;
1807
    MuxDriver *d = chr->opaque;
1808

    
1809
    while (d->prod != d->cons &&
1810
           d->chr_can_read[m] &&
1811
           d->chr_can_read[m](d->ext_opaque[m])) {
1812
        d->chr_read[m](d->ext_opaque[m],
1813
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1814
    }
1815
}
1816

    
1817
static int mux_chr_can_read(void *opaque)
1818
{
1819
    CharDriverState *chr = opaque;
1820
    MuxDriver *d = chr->opaque;
1821

    
1822
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1823
        return 1;
1824
    if (d->chr_can_read[chr->focus])
1825
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1826
    return 0;
1827
}
1828

    
1829
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1830
{
1831
    CharDriverState *chr = opaque;
1832
    MuxDriver *d = chr->opaque;
1833
    int m = chr->focus;
1834
    int i;
1835

    
1836
    mux_chr_accept_input (opaque);
1837

    
1838
    for(i = 0; i < size; i++)
1839
        if (mux_proc_byte(chr, d, buf[i])) {
1840
            if (d->prod == d->cons &&
1841
                d->chr_can_read[m] &&
1842
                d->chr_can_read[m](d->ext_opaque[m]))
1843
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1844
            else
1845
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1846
        }
1847
}
1848

    
1849
static void mux_chr_event(void *opaque, int event)
1850
{
1851
    CharDriverState *chr = opaque;
1852
    MuxDriver *d = chr->opaque;
1853
    int i;
1854

    
1855
    /* Send the event to all registered listeners */
1856
    for (i = 0; i < d->mux_cnt; i++)
1857
        if (d->chr_event[i])
1858
            d->chr_event[i](d->ext_opaque[i], event);
1859
}
1860

    
1861
static void mux_chr_update_read_handler(CharDriverState *chr)
1862
{
1863
    MuxDriver *d = chr->opaque;
1864

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

    
1882
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1883
{
1884
    CharDriverState *chr;
1885
    MuxDriver *d;
1886

    
1887
    chr = qemu_mallocz(sizeof(CharDriverState));
1888
    if (!chr)
1889
        return NULL;
1890
    d = qemu_mallocz(sizeof(MuxDriver));
1891
    if (!d) {
1892
        free(chr);
1893
        return NULL;
1894
    }
1895

    
1896
    chr->opaque = d;
1897
    d->drv = drv;
1898
    chr->focus = -1;
1899
    chr->chr_write = mux_chr_write;
1900
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1901
    chr->chr_accept_input = mux_chr_accept_input;
1902
    return chr;
1903
}
1904

    
1905

    
1906
#ifdef _WIN32
1907

    
1908
static void socket_cleanup(void)
1909
{
1910
    WSACleanup();
1911
}
1912

    
1913
static int socket_init(void)
1914
{
1915
    WSADATA Data;
1916
    int ret, err;
1917

    
1918
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1919
    if (ret != 0) {
1920
        err = WSAGetLastError();
1921
        fprintf(stderr, "WSAStartup: %d\n", err);
1922
        return -1;
1923
    }
1924
    atexit(socket_cleanup);
1925
    return 0;
1926
}
1927

    
1928
static int send_all(int fd, const uint8_t *buf, int len1)
1929
{
1930
    int ret, len;
1931

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

    
1951
void socket_set_nonblock(int fd)
1952
{
1953
    unsigned long opt = 1;
1954
    ioctlsocket(fd, FIONBIO, &opt);
1955
}
1956

    
1957
#else
1958

    
1959
static int unix_write(int fd, const uint8_t *buf, int len1)
1960
{
1961
    int ret, len;
1962

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

    
1979
static inline int send_all(int fd, const uint8_t *buf, int len1)
1980
{
1981
    return unix_write(fd, buf, len1);
1982
}
1983

    
1984
void socket_set_nonblock(int fd)
1985
{
1986
    fcntl(fd, F_SETFL, O_NONBLOCK);
1987
}
1988
#endif /* !_WIN32 */
1989

    
1990
#ifndef _WIN32
1991

    
1992
typedef struct {
1993
    int fd_in, fd_out;
1994
    int max_size;
1995
} FDCharDriver;
1996

    
1997
#define STDIO_MAX_CLIENTS 1
1998
static int stdio_nb_clients = 0;
1999

    
2000
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2001
{
2002
    FDCharDriver *s = chr->opaque;
2003
    return unix_write(s->fd_out, buf, len);
2004
}
2005

    
2006
static int fd_chr_read_poll(void *opaque)
2007
{
2008
    CharDriverState *chr = opaque;
2009
    FDCharDriver *s = chr->opaque;
2010

    
2011
    s->max_size = qemu_chr_can_read(chr);
2012
    return s->max_size;
2013
}
2014

    
2015
static void fd_chr_read(void *opaque)
2016
{
2017
    CharDriverState *chr = opaque;
2018
    FDCharDriver *s = chr->opaque;
2019
    int size, len;
2020
    uint8_t buf[1024];
2021

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

    
2038
static void fd_chr_update_read_handler(CharDriverState *chr)
2039
{
2040
    FDCharDriver *s = chr->opaque;
2041

    
2042
    if (s->fd_in >= 0) {
2043
        if (nographic && s->fd_in == 0) {
2044
        } else {
2045
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2046
                                 fd_chr_read, NULL, chr);
2047
        }
2048
    }
2049
}
2050

    
2051
/* open a character device to a unix fd */
2052
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2053
{
2054
    CharDriverState *chr;
2055
    FDCharDriver *s;
2056

    
2057
    chr = qemu_mallocz(sizeof(CharDriverState));
2058
    if (!chr)
2059
        return NULL;
2060
    s = qemu_mallocz(sizeof(FDCharDriver));
2061
    if (!s) {
2062
        free(chr);
2063
        return NULL;
2064
    }
2065
    s->fd_in = fd_in;
2066
    s->fd_out = fd_out;
2067
    chr->opaque = s;
2068
    chr->chr_write = fd_chr_write;
2069
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2070

    
2071
    qemu_chr_reset(chr);
2072

    
2073
    return chr;
2074
}
2075

    
2076
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2077
{
2078
    int fd_out;
2079

    
2080
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2081
    if (fd_out < 0)
2082
        return NULL;
2083
    return qemu_chr_open_fd(-1, fd_out);
2084
}
2085

    
2086
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2087
{
2088
    int fd_in, fd_out;
2089
    char filename_in[256], filename_out[256];
2090

    
2091
    snprintf(filename_in, 256, "%s.in", filename);
2092
    snprintf(filename_out, 256, "%s.out", filename);
2093
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2094
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2095
    if (fd_in < 0 || fd_out < 0) {
2096
        if (fd_in >= 0)
2097
            close(fd_in);
2098
        if (fd_out >= 0)
2099
            close(fd_out);
2100
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2101
        if (fd_in < 0)
2102
            return NULL;
2103
    }
2104
    return qemu_chr_open_fd(fd_in, fd_out);
2105
}
2106

    
2107

    
2108
/* for STDIO, we handle the case where several clients use it
2109
   (nographic mode) */
2110

    
2111
#define TERM_FIFO_MAX_SIZE 1
2112

    
2113
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2114
static int term_fifo_size;
2115

    
2116
static int stdio_read_poll(void *opaque)
2117
{
2118
    CharDriverState *chr = opaque;
2119

    
2120
    /* try to flush the queue if needed */
2121
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2122
        qemu_chr_read(chr, term_fifo, 1);
2123
        term_fifo_size = 0;
2124
    }
2125
    /* see if we can absorb more chars */
2126
    if (term_fifo_size == 0)
2127
        return 1;
2128
    else
2129
        return 0;
2130
}
2131

    
2132
static void stdio_read(void *opaque)
2133
{
2134
    int size;
2135
    uint8_t buf[1];
2136
    CharDriverState *chr = opaque;
2137

    
2138
    size = read(0, buf, 1);
2139
    if (size == 0) {
2140
        /* stdin has been closed. Remove it from the active list.  */
2141
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2142
        return;
2143
    }
2144
    if (size > 0) {
2145
        if (qemu_chr_can_read(chr) > 0) {
2146
            qemu_chr_read(chr, buf, 1);
2147
        } else if (term_fifo_size == 0) {
2148
            term_fifo[term_fifo_size++] = buf[0];
2149
        }
2150
    }
2151
}
2152

    
2153
/* init terminal so that we can grab keys */
2154
static struct termios oldtty;
2155
static int old_fd0_flags;
2156

    
2157
static void term_exit(void)
2158
{
2159
    tcsetattr (0, TCSANOW, &oldtty);
2160
    fcntl(0, F_SETFL, old_fd0_flags);
2161
}
2162

    
2163
static void term_init(void)
2164
{
2165
    struct termios tty;
2166

    
2167
    tcgetattr (0, &tty);
2168
    oldtty = tty;
2169
    old_fd0_flags = fcntl(0, F_GETFL);
2170

    
2171
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2172
                          |INLCR|IGNCR|ICRNL|IXON);
2173
    tty.c_oflag |= OPOST;
2174
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2175
    /* if graphical mode, we allow Ctrl-C handling */
2176
    if (nographic)
2177
        tty.c_lflag &= ~ISIG;
2178
    tty.c_cflag &= ~(CSIZE|PARENB);
2179
    tty.c_cflag |= CS8;
2180
    tty.c_cc[VMIN] = 1;
2181
    tty.c_cc[VTIME] = 0;
2182

    
2183
    tcsetattr (0, TCSANOW, &tty);
2184

    
2185
    atexit(term_exit);
2186

    
2187
    fcntl(0, F_SETFL, O_NONBLOCK);
2188
}
2189

    
2190
static CharDriverState *qemu_chr_open_stdio(void)
2191
{
2192
    CharDriverState *chr;
2193

    
2194
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2195
        return NULL;
2196
    chr = qemu_chr_open_fd(0, 1);
2197
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2198
    stdio_nb_clients++;
2199
    term_init();
2200

    
2201
    return chr;
2202
}
2203

    
2204
#if defined(__linux__) || defined(__sun__)
2205
static CharDriverState *qemu_chr_open_pty(void)
2206
{
2207
    struct termios tty;
2208
    char slave_name[1024];
2209
    int master_fd, slave_fd;
2210

    
2211
#if defined(__linux__)
2212
    /* Not satisfying */
2213
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2214
        return NULL;
2215
    }
2216
#endif
2217

    
2218
    /* Disabling local echo and line-buffered output */
2219
    tcgetattr (master_fd, &tty);
2220
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2221
    tty.c_cc[VMIN] = 1;
2222
    tty.c_cc[VTIME] = 0;
2223
    tcsetattr (master_fd, TCSAFLUSH, &tty);
2224

    
2225
    fprintf(stderr, "char device redirected to %s\n", slave_name);
2226
    return qemu_chr_open_fd(master_fd, master_fd);
2227
}
2228

    
2229
static void tty_serial_init(int fd, int speed,
2230
                            int parity, int data_bits, int stop_bits)
2231
{
2232
    struct termios tty;
2233
    speed_t spd;
2234

    
2235
#if 0
2236
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2237
           speed, parity, data_bits, stop_bits);
2238
#endif
2239
    tcgetattr (fd, &tty);
2240

    
2241
    switch(speed) {
2242
    case 50:
2243
        spd = B50;
2244
        break;
2245
    case 75:
2246
        spd = B75;
2247
        break;
2248
    case 300:
2249
        spd = B300;
2250
        break;
2251
    case 600:
2252
        spd = B600;
2253
        break;
2254
    case 1200:
2255
        spd = B1200;
2256
        break;
2257
    case 2400:
2258
        spd = B2400;
2259
        break;
2260
    case 4800:
2261
        spd = B4800;
2262
        break;
2263
    case 9600:
2264
        spd = B9600;
2265
        break;
2266
    case 19200:
2267
        spd = B19200;
2268
        break;
2269
    case 38400:
2270
        spd = B38400;
2271
        break;
2272
    case 57600:
2273
        spd = B57600;
2274
        break;
2275
    default:
2276
    case 115200:
2277
        spd = B115200;
2278
        break;
2279
    }
2280

    
2281
    cfsetispeed(&tty, spd);
2282
    cfsetospeed(&tty, spd);
2283

    
2284
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2285
                          |INLCR|IGNCR|ICRNL|IXON);
2286
    tty.c_oflag |= OPOST;
2287
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2288
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2289
    switch(data_bits) {
2290
    default:
2291
    case 8:
2292
        tty.c_cflag |= CS8;
2293
        break;
2294
    case 7:
2295
        tty.c_cflag |= CS7;
2296
        break;
2297
    case 6:
2298
        tty.c_cflag |= CS6;
2299
        break;
2300
    case 5:
2301
        tty.c_cflag |= CS5;
2302
        break;
2303
    }
2304
    switch(parity) {
2305
    default:
2306
    case 'N':
2307
        break;
2308
    case 'E':
2309
        tty.c_cflag |= PARENB;
2310
        break;
2311
    case 'O':
2312
        tty.c_cflag |= PARENB | PARODD;
2313
        break;
2314
    }
2315
    if (stop_bits == 2)
2316
        tty.c_cflag |= CSTOPB;
2317

    
2318
    tcsetattr (fd, TCSANOW, &tty);
2319
}
2320

    
2321
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2322
{
2323
    FDCharDriver *s = chr->opaque;
2324

    
2325
    switch(cmd) {
2326
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2327
        {
2328
            QEMUSerialSetParams *ssp = arg;
2329
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2330
                            ssp->data_bits, ssp->stop_bits);
2331
        }
2332
        break;
2333
    case CHR_IOCTL_SERIAL_SET_BREAK:
2334
        {
2335
            int enable = *(int *)arg;
2336
            if (enable)
2337
                tcsendbreak(s->fd_in, 1);
2338
        }
2339
        break;
2340
    default:
2341
        return -ENOTSUP;
2342
    }
2343
    return 0;
2344
}
2345

    
2346
static CharDriverState *qemu_chr_open_tty(const char *filename)
2347
{
2348
    CharDriverState *chr;
2349
    int fd;
2350

    
2351
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2352
    fcntl(fd, F_SETFL, O_NONBLOCK);
2353
    tty_serial_init(fd, 115200, 'N', 8, 1);
2354
    chr = qemu_chr_open_fd(fd, fd);
2355
    if (!chr) {
2356
        close(fd);
2357
        return NULL;
2358
    }
2359
    chr->chr_ioctl = tty_serial_ioctl;
2360
    qemu_chr_reset(chr);
2361
    return chr;
2362
}
2363
#else  /* ! __linux__ && ! __sun__ */
2364
static CharDriverState *qemu_chr_open_pty(void)
2365
{
2366
    return NULL;
2367
}
2368
#endif /* __linux__ || __sun__ */
2369

    
2370
#if defined(__linux__)
2371
typedef struct {
2372
    int fd;
2373
    int mode;
2374
} ParallelCharDriver;
2375

    
2376
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2377
{
2378
    if (s->mode != mode) {
2379
        int m = mode;
2380
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2381
            return 0;
2382
        s->mode = mode;
2383
    }
2384
    return 1;
2385
}
2386

    
2387
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2388
{
2389
    ParallelCharDriver *drv = chr->opaque;
2390
    int fd = drv->fd;
2391
    uint8_t b;
2392

    
2393
    switch(cmd) {
2394
    case CHR_IOCTL_PP_READ_DATA:
2395
        if (ioctl(fd, PPRDATA, &b) < 0)
2396
            return -ENOTSUP;
2397
        *(uint8_t *)arg = b;
2398
        break;
2399
    case CHR_IOCTL_PP_WRITE_DATA:
2400
        b = *(uint8_t *)arg;
2401
        if (ioctl(fd, PPWDATA, &b) < 0)
2402
            return -ENOTSUP;
2403
        break;
2404
    case CHR_IOCTL_PP_READ_CONTROL:
2405
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2406
            return -ENOTSUP;
2407
        /* Linux gives only the lowest bits, and no way to know data
2408
           direction! For better compatibility set the fixed upper
2409
           bits. */
2410
        *(uint8_t *)arg = b | 0xc0;
2411
        break;
2412
    case CHR_IOCTL_PP_WRITE_CONTROL:
2413
        b = *(uint8_t *)arg;
2414
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2415
            return -ENOTSUP;
2416
        break;
2417
    case CHR_IOCTL_PP_READ_STATUS:
2418
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2419
            return -ENOTSUP;
2420
        *(uint8_t *)arg = b;
2421
        break;
2422
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2423
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2424
            struct ParallelIOArg *parg = arg;
2425
            int n = read(fd, parg->buffer, parg->count);
2426
            if (n != parg->count) {
2427
                return -EIO;
2428
            }
2429
        }
2430
        break;
2431
    case CHR_IOCTL_PP_EPP_READ:
2432
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2433
            struct ParallelIOArg *parg = arg;
2434
            int n = read(fd, parg->buffer, parg->count);
2435
            if (n != parg->count) {
2436
                return -EIO;
2437
            }
2438
        }
2439
        break;
2440
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2441
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2442
            struct ParallelIOArg *parg = arg;
2443
            int n = write(fd, parg->buffer, parg->count);
2444
            if (n != parg->count) {
2445
                return -EIO;
2446
            }
2447
        }
2448
        break;
2449
    case CHR_IOCTL_PP_EPP_WRITE:
2450
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2451
            struct ParallelIOArg *parg = arg;
2452
            int n = write(fd, parg->buffer, parg->count);
2453
            if (n != parg->count) {
2454
                return -EIO;
2455
            }
2456
        }
2457
        break;
2458
    default:
2459
        return -ENOTSUP;
2460
    }
2461
    return 0;
2462
}
2463

    
2464
static void pp_close(CharDriverState *chr)
2465
{
2466
    ParallelCharDriver *drv = chr->opaque;
2467
    int fd = drv->fd;
2468

    
2469
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2470
    ioctl(fd, PPRELEASE);
2471
    close(fd);
2472
    qemu_free(drv);
2473
}
2474

    
2475
static CharDriverState *qemu_chr_open_pp(const char *filename)
2476
{
2477
    CharDriverState *chr;
2478
    ParallelCharDriver *drv;
2479
    int fd;
2480

    
2481
    TFR(fd = open(filename, O_RDWR));
2482
    if (fd < 0)
2483
        return NULL;
2484

    
2485
    if (ioctl(fd, PPCLAIM) < 0) {
2486
        close(fd);
2487
        return NULL;
2488
    }
2489

    
2490
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2491
    if (!drv) {
2492
        close(fd);
2493
        return NULL;
2494
    }
2495
    drv->fd = fd;
2496
    drv->mode = IEEE1284_MODE_COMPAT;
2497

    
2498
    chr = qemu_mallocz(sizeof(CharDriverState));
2499
    if (!chr) {
2500
        qemu_free(drv);
2501
        close(fd);
2502
        return NULL;
2503
    }
2504
    chr->chr_write = null_chr_write;
2505
    chr->chr_ioctl = pp_ioctl;
2506
    chr->chr_close = pp_close;
2507
    chr->opaque = drv;
2508

    
2509
    qemu_chr_reset(chr);
2510

    
2511
    return chr;
2512
}
2513
#endif /* __linux__ */
2514

    
2515
#else /* _WIN32 */
2516

    
2517
typedef struct {
2518
    int max_size;
2519
    HANDLE hcom, hrecv, hsend;
2520
    OVERLAPPED orecv, osend;
2521
    BOOL fpipe;
2522
    DWORD len;
2523
} WinCharState;
2524

    
2525
#define NSENDBUF 2048
2526
#define NRECVBUF 2048
2527
#define MAXCONNECT 1
2528
#define NTIMEOUT 5000
2529

    
2530
static int win_chr_poll(void *opaque);
2531
static int win_chr_pipe_poll(void *opaque);
2532

    
2533
static void win_chr_close(CharDriverState *chr)
2534
{
2535
    WinCharState *s = chr->opaque;
2536

    
2537
    if (s->hsend) {
2538
        CloseHandle(s->hsend);
2539
        s->hsend = NULL;
2540
    }
2541
    if (s->hrecv) {
2542
        CloseHandle(s->hrecv);
2543
        s->hrecv = NULL;
2544
    }
2545
    if (s->hcom) {
2546
        CloseHandle(s->hcom);
2547
        s->hcom = NULL;
2548
    }
2549
    if (s->fpipe)
2550
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2551
    else
2552
        qemu_del_polling_cb(win_chr_poll, chr);
2553
}
2554

    
2555
static int win_chr_init(CharDriverState *chr, const char *filename)
2556
{
2557
    WinCharState *s = chr->opaque;
2558
    COMMCONFIG comcfg;
2559
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2560
    COMSTAT comstat;
2561
    DWORD size;
2562
    DWORD err;
2563

    
2564
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2565
    if (!s->hsend) {
2566
        fprintf(stderr, "Failed CreateEvent\n");
2567
        goto fail;
2568
    }
2569
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2570
    if (!s->hrecv) {
2571
        fprintf(stderr, "Failed CreateEvent\n");
2572
        goto fail;
2573
    }
2574

    
2575
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2576
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2577
    if (s->hcom == INVALID_HANDLE_VALUE) {
2578
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2579
        s->hcom = NULL;
2580
        goto fail;
2581
    }
2582

    
2583
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2584
        fprintf(stderr, "Failed SetupComm\n");
2585
        goto fail;
2586
    }
2587

    
2588
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2589
    size = sizeof(COMMCONFIG);
2590
    GetDefaultCommConfig(filename, &comcfg, &size);
2591
    comcfg.dcb.DCBlength = sizeof(DCB);
2592
    CommConfigDialog(filename, NULL, &comcfg);
2593

    
2594
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2595
        fprintf(stderr, "Failed SetCommState\n");
2596
        goto fail;
2597
    }
2598

    
2599
    if (!SetCommMask(s->hcom, EV_ERR)) {
2600
        fprintf(stderr, "Failed SetCommMask\n");
2601
        goto fail;
2602
    }
2603

    
2604
    cto.ReadIntervalTimeout = MAXDWORD;
2605
    if (!SetCommTimeouts(s->hcom, &cto)) {
2606
        fprintf(stderr, "Failed SetCommTimeouts\n");
2607
        goto fail;
2608
    }
2609

    
2610
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2611
        fprintf(stderr, "Failed ClearCommError\n");
2612
        goto fail;
2613
    }
2614
    qemu_add_polling_cb(win_chr_poll, chr);
2615
    return 0;
2616

    
2617
 fail:
2618
    win_chr_close(chr);
2619
    return -1;
2620
}
2621

    
2622
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2623
{
2624
    WinCharState *s = chr->opaque;
2625
    DWORD len, ret, size, err;
2626

    
2627
    len = len1;
2628
    ZeroMemory(&s->osend, sizeof(s->osend));
2629
    s->osend.hEvent = s->hsend;
2630
    while (len > 0) {
2631
        if (s->hsend)
2632
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2633
        else
2634
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2635
        if (!ret) {
2636
            err = GetLastError();
2637
            if (err == ERROR_IO_PENDING) {
2638
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2639
                if (ret) {
2640
                    buf += size;
2641
                    len -= size;
2642
                } else {
2643
                    break;
2644
                }
2645
            } else {
2646
                break;
2647
            }
2648
        } else {
2649
            buf += size;
2650
            len -= size;
2651
        }
2652
    }
2653
    return len1 - len;
2654
}
2655

    
2656
static int win_chr_read_poll(CharDriverState *chr)
2657
{
2658
    WinCharState *s = chr->opaque;
2659

    
2660
    s->max_size = qemu_chr_can_read(chr);
2661
    return s->max_size;
2662
}
2663

    
2664
static void win_chr_readfile(CharDriverState *chr)
2665
{
2666
    WinCharState *s = chr->opaque;
2667
    int ret, err;
2668
    uint8_t buf[1024];
2669
    DWORD size;
2670

    
2671
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2672
    s->orecv.hEvent = s->hrecv;
2673
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2674
    if (!ret) {
2675
        err = GetLastError();
2676
        if (err == ERROR_IO_PENDING) {
2677
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2678
        }
2679
    }
2680

    
2681
    if (size > 0) {
2682
        qemu_chr_read(chr, buf, size);
2683
    }
2684
}
2685

    
2686
static void win_chr_read(CharDriverState *chr)
2687
{
2688
    WinCharState *s = chr->opaque;
2689

    
2690
    if (s->len > s->max_size)
2691
        s->len = s->max_size;
2692
    if (s->len == 0)
2693
        return;
2694

    
2695
    win_chr_readfile(chr);
2696
}
2697

    
2698
static int win_chr_poll(void *opaque)
2699
{
2700
    CharDriverState *chr = opaque;
2701
    WinCharState *s = chr->opaque;
2702
    COMSTAT status;
2703
    DWORD comerr;
2704

    
2705
    ClearCommError(s->hcom, &comerr, &status);
2706
    if (status.cbInQue > 0) {
2707
        s->len = status.cbInQue;
2708
        win_chr_read_poll(chr);
2709
        win_chr_read(chr);
2710
        return 1;
2711
    }
2712
    return 0;
2713
}
2714

    
2715
static CharDriverState *qemu_chr_open_win(const char *filename)
2716
{
2717
    CharDriverState *chr;
2718
    WinCharState *s;
2719

    
2720
    chr = qemu_mallocz(sizeof(CharDriverState));
2721
    if (!chr)
2722
        return NULL;
2723
    s = qemu_mallocz(sizeof(WinCharState));
2724
    if (!s) {
2725
        free(chr);
2726
        return NULL;
2727
    }
2728
    chr->opaque = s;
2729
    chr->chr_write = win_chr_write;
2730
    chr->chr_close = win_chr_close;
2731

    
2732
    if (win_chr_init(chr, filename) < 0) {
2733
        free(s);
2734
        free(chr);
2735
        return NULL;
2736
    }
2737
    qemu_chr_reset(chr);
2738
    return chr;
2739
}
2740

    
2741
static int win_chr_pipe_poll(void *opaque)
2742
{
2743
    CharDriverState *chr = opaque;
2744
    WinCharState *s = chr->opaque;
2745
    DWORD size;
2746

    
2747
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2748
    if (size > 0) {
2749
        s->len = size;
2750
        win_chr_read_poll(chr);
2751
        win_chr_read(chr);
2752
        return 1;
2753
    }
2754
    return 0;
2755
}
2756

    
2757
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2758
{
2759
    WinCharState *s = chr->opaque;
2760
    OVERLAPPED ov;
2761
    int ret;
2762
    DWORD size;
2763
    char openname[256];
2764

    
2765
    s->fpipe = TRUE;
2766

    
2767
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2768
    if (!s->hsend) {
2769
        fprintf(stderr, "Failed CreateEvent\n");
2770
        goto fail;
2771
    }
2772
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2773
    if (!s->hrecv) {
2774
        fprintf(stderr, "Failed CreateEvent\n");
2775
        goto fail;
2776
    }
2777

    
2778
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2779
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2780
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2781
                              PIPE_WAIT,
2782
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2783
    if (s->hcom == INVALID_HANDLE_VALUE) {
2784
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2785
        s->hcom = NULL;
2786
        goto fail;
2787
    }
2788

    
2789
    ZeroMemory(&ov, sizeof(ov));
2790
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2791
    ret = ConnectNamedPipe(s->hcom, &ov);
2792
    if (ret) {
2793
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2794
        goto fail;
2795
    }
2796

    
2797
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2798
    if (!ret) {
2799
        fprintf(stderr, "Failed GetOverlappedResult\n");
2800
        if (ov.hEvent) {
2801
            CloseHandle(ov.hEvent);
2802
            ov.hEvent = NULL;
2803
        }
2804
        goto fail;
2805
    }
2806

    
2807
    if (ov.hEvent) {
2808
        CloseHandle(ov.hEvent);
2809
        ov.hEvent = NULL;
2810
    }
2811
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2812
    return 0;
2813

    
2814
 fail:
2815
    win_chr_close(chr);
2816
    return -1;
2817
}
2818

    
2819

    
2820
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2821
{
2822
    CharDriverState *chr;
2823
    WinCharState *s;
2824

    
2825
    chr = qemu_mallocz(sizeof(CharDriverState));
2826
    if (!chr)
2827
        return NULL;
2828
    s = qemu_mallocz(sizeof(WinCharState));
2829
    if (!s) {
2830
        free(chr);
2831
        return NULL;
2832
    }
2833
    chr->opaque = s;
2834
    chr->chr_write = win_chr_write;
2835
    chr->chr_close = win_chr_close;
2836

    
2837
    if (win_chr_pipe_init(chr, filename) < 0) {
2838
        free(s);
2839
        free(chr);
2840
        return NULL;
2841
    }
2842
    qemu_chr_reset(chr);
2843
    return chr;
2844
}
2845

    
2846
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2847
{
2848
    CharDriverState *chr;
2849
    WinCharState *s;
2850

    
2851
    chr = qemu_mallocz(sizeof(CharDriverState));
2852
    if (!chr)
2853
        return NULL;
2854
    s = qemu_mallocz(sizeof(WinCharState));
2855
    if (!s) {
2856
        free(chr);
2857
        return NULL;
2858
    }
2859
    s->hcom = fd_out;
2860
    chr->opaque = s;
2861
    chr->chr_write = win_chr_write;
2862
    qemu_chr_reset(chr);
2863
    return chr;
2864
}
2865

    
2866
static CharDriverState *qemu_chr_open_win_con(const char *filename)
2867
{
2868
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2869
}
2870

    
2871
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2872
{
2873
    HANDLE fd_out;
2874

    
2875
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2876
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2877
    if (fd_out == INVALID_HANDLE_VALUE)
2878
        return NULL;
2879

    
2880
    return qemu_chr_open_win_file(fd_out);
2881
}
2882
#endif /* !_WIN32 */
2883

    
2884
/***********************************************************/
2885
/* UDP Net console */
2886

    
2887
typedef struct {
2888
    int fd;
2889
    struct sockaddr_in daddr;
2890
    uint8_t buf[1024];
2891
    int bufcnt;
2892
    int bufptr;
2893
    int max_size;
2894
} NetCharDriver;
2895

    
2896
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2897
{
2898
    NetCharDriver *s = chr->opaque;
2899

    
2900
    return sendto(s->fd, buf, len, 0,
2901
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2902
}
2903

    
2904
static int udp_chr_read_poll(void *opaque)
2905
{
2906
    CharDriverState *chr = opaque;
2907
    NetCharDriver *s = chr->opaque;
2908

    
2909
    s->max_size = qemu_chr_can_read(chr);
2910

    
2911
    /* If there were any stray characters in the queue process them
2912
     * first
2913
     */
2914
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2915
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2916
        s->bufptr++;
2917
        s->max_size = qemu_chr_can_read(chr);
2918
    }
2919
    return s->max_size;
2920
}
2921

    
2922
static void udp_chr_read(void *opaque)
2923
{
2924
    CharDriverState *chr = opaque;
2925
    NetCharDriver *s = chr->opaque;
2926

    
2927
    if (s->max_size == 0)
2928
        return;
2929
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2930
    s->bufptr = s->bufcnt;
2931
    if (s->bufcnt <= 0)
2932
        return;
2933

    
2934
    s->bufptr = 0;
2935
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2936
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2937
        s->bufptr++;
2938
        s->max_size = qemu_chr_can_read(chr);
2939
    }
2940
}
2941

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

    
2946
    if (s->fd >= 0) {
2947
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2948
                             udp_chr_read, NULL, chr);
2949
    }
2950
}
2951

    
2952
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2953
#ifndef _WIN32
2954
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2955
#endif
2956
int parse_host_src_port(struct sockaddr_in *haddr,
2957
                        struct sockaddr_in *saddr,
2958
                        const char *str);
2959

    
2960
static CharDriverState *qemu_chr_open_udp(const char *def)
2961
{
2962
    CharDriverState *chr = NULL;
2963
    NetCharDriver *s = NULL;
2964
    int fd = -1;
2965
    struct sockaddr_in saddr;
2966

    
2967
    chr = qemu_mallocz(sizeof(CharDriverState));
2968
    if (!chr)
2969
        goto return_err;
2970
    s = qemu_mallocz(sizeof(NetCharDriver));
2971
    if (!s)
2972
        goto return_err;
2973

    
2974
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2975
    if (fd < 0) {
2976
        perror("socket(PF_INET, SOCK_DGRAM)");
2977
        goto return_err;
2978
    }
2979

    
2980
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2981
        printf("Could not parse: %s\n", def);
2982
        goto return_err;
2983
    }
2984

    
2985
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2986
    {
2987
        perror("bind");
2988
        goto return_err;
2989
    }
2990

    
2991
    s->fd = fd;
2992
    s->bufcnt = 0;
2993
    s->bufptr = 0;
2994
    chr->opaque = s;
2995
    chr->chr_write = udp_chr_write;
2996
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2997
    return chr;
2998

    
2999
return_err:
3000
    if (chr)
3001
        free(chr);
3002
    if (s)
3003
        free(s);
3004
    if (fd >= 0)
3005
        closesocket(fd);
3006
    return NULL;
3007
}
3008

    
3009
/***********************************************************/
3010
/* TCP Net console */
3011

    
3012
typedef struct {
3013
    int fd, listen_fd;
3014
    int connected;
3015
    int max_size;
3016
    int do_telnetopt;
3017
    int do_nodelay;
3018
    int is_unix;
3019
} TCPCharDriver;
3020

    
3021
static void tcp_chr_accept(void *opaque);
3022

    
3023
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3024
{
3025
    TCPCharDriver *s = chr->opaque;
3026
    if (s->connected) {
3027
        return send_all(s->fd, buf, len);
3028
    } else {
3029
        /* XXX: indicate an error ? */
3030
        return len;
3031
    }
3032
}
3033

    
3034
static int tcp_chr_read_poll(void *opaque)
3035
{
3036
    CharDriverState *chr = opaque;
3037
    TCPCharDriver *s = chr->opaque;
3038
    if (!s->connected)
3039
        return 0;
3040
    s->max_size = qemu_chr_can_read(chr);
3041
    return s->max_size;
3042
}
3043

    
3044
#define IAC 255
3045
#define IAC_BREAK 243
3046
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3047
                                      TCPCharDriver *s,
3048
                                      uint8_t *buf, int *size)
3049
{
3050
    /* Handle any telnet client's basic IAC options to satisfy char by
3051
     * char mode with no echo.  All IAC options will be removed from
3052
     * the buf and the do_telnetopt variable will be used to track the
3053
     * state of the width of the IAC information.
3054
     *
3055
     * IAC commands come in sets of 3 bytes with the exception of the
3056
     * "IAC BREAK" command and the double IAC.
3057
     */
3058

    
3059
    int i;
3060
    int j = 0;
3061

    
3062
    for (i = 0; i < *size; i++) {
3063
        if (s->do_telnetopt > 1) {
3064
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3065
                /* Double IAC means send an IAC */
3066
                if (j != i)
3067
                    buf[j] = buf[i];
3068
                j++;
3069
                s->do_telnetopt = 1;
3070
            } else {
3071
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3072
                    /* Handle IAC break commands by sending a serial break */
3073
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3074
                    s->do_telnetopt++;
3075
                }
3076
                s->do_telnetopt++;
3077
            }
3078
            if (s->do_telnetopt >= 4) {
3079
                s->do_telnetopt = 1;
3080
            }
3081
        } else {
3082
            if ((unsigned char)buf[i] == IAC) {
3083
                s->do_telnetopt = 2;
3084
            } else {
3085
                if (j != i)
3086
                    buf[j] = buf[i];
3087
                j++;
3088
            }
3089
        }
3090
    }
3091
    *size = j;
3092
}
3093

    
3094
static void tcp_chr_read(void *opaque)
3095
{
3096
    CharDriverState *chr = opaque;
3097
    TCPCharDriver *s = chr->opaque;
3098
    uint8_t buf[1024];
3099
    int len, size;
3100

    
3101
    if (!s->connected || s->max_size <= 0)
3102
        return;
3103
    len = sizeof(buf);
3104
    if (len > s->max_size)
3105
        len = s->max_size;
3106
    size = recv(s->fd, buf, len, 0);
3107
    if (size == 0) {
3108
        /* connection closed */
3109
        s->connected = 0;
3110
        if (s->listen_fd >= 0) {
3111
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3112
        }
3113
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3114
        closesocket(s->fd);
3115
        s->fd = -1;
3116
    } else if (size > 0) {
3117
        if (s->do_telnetopt)
3118
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3119
        if (size > 0)
3120
            qemu_chr_read(chr, buf, size);
3121
    }
3122
}
3123

    
3124
static void tcp_chr_connect(void *opaque)
3125
{
3126
    CharDriverState *chr = opaque;
3127
    TCPCharDriver *s = chr->opaque;
3128

    
3129
    s->connected = 1;
3130
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3131
                         tcp_chr_read, NULL, chr);
3132
    qemu_chr_reset(chr);
3133
}
3134

    
3135
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3136
static void tcp_chr_telnet_init(int fd)
3137
{
3138
    char buf[3];
3139
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3140
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3141
    send(fd, (char *)buf, 3, 0);
3142
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3143
    send(fd, (char *)buf, 3, 0);
3144
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3145
    send(fd, (char *)buf, 3, 0);
3146
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3147
    send(fd, (char *)buf, 3, 0);
3148
}
3149

    
3150
static void socket_set_nodelay(int fd)
3151
{
3152
    int val = 1;
3153
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3154
}
3155

    
3156
static void tcp_chr_accept(void *opaque)
3157
{
3158
    CharDriverState *chr = opaque;
3159
    TCPCharDriver *s = chr->opaque;
3160
    struct sockaddr_in saddr;
3161
#ifndef _WIN32
3162
    struct sockaddr_un uaddr;
3163
#endif
3164
    struct sockaddr *addr;
3165
    socklen_t len;
3166
    int fd;
3167

    
3168
    for(;;) {
3169
#ifndef _WIN32
3170
        if (s->is_unix) {
3171
            len = sizeof(uaddr);
3172
            addr = (struct sockaddr *)&uaddr;
3173
        } else
3174
#endif
3175
        {
3176
            len = sizeof(saddr);
3177
            addr = (struct sockaddr *)&saddr;
3178
        }
3179
        fd = accept(s->listen_fd, addr, &len);
3180
        if (fd < 0 && errno != EINTR) {
3181
            return;
3182
        } else if (fd >= 0) {
3183
            if (s->do_telnetopt)
3184
                tcp_chr_telnet_init(fd);
3185
            break;
3186
        }
3187
    }
3188
    socket_set_nonblock(fd);
3189
    if (s->do_nodelay)
3190
        socket_set_nodelay(fd);
3191
    s->fd = fd;
3192
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3193
    tcp_chr_connect(chr);
3194
}
3195

    
3196
static void tcp_chr_close(CharDriverState *chr)
3197
{
3198
    TCPCharDriver *s = chr->opaque;
3199
    if (s->fd >= 0)
3200
        closesocket(s->fd);
3201
    if (s->listen_fd >= 0)
3202
        closesocket(s->listen_fd);
3203
    qemu_free(s);
3204
}
3205

    
3206
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3207
                                          int is_telnet,
3208
                                          int is_unix)
3209
{
3210
    CharDriverState *chr = NULL;
3211
    TCPCharDriver *s = NULL;
3212
    int fd = -1, ret, err, val;
3213
    int is_listen = 0;
3214
    int is_waitconnect = 1;
3215
    int do_nodelay = 0;
3216
    const char *ptr;
3217
    struct sockaddr_in saddr;
3218
#ifndef _WIN32
3219
    struct sockaddr_un uaddr;
3220
#endif
3221
    struct sockaddr *addr;
3222
    socklen_t addrlen;
3223

    
3224
#ifndef _WIN32
3225
    if (is_unix) {
3226
        addr = (struct sockaddr *)&uaddr;
3227
        addrlen = sizeof(uaddr);
3228
        if (parse_unix_path(&uaddr, host_str) < 0)
3229
            goto fail;
3230
    } else
3231
#endif
3232
    {
3233
        addr = (struct sockaddr *)&saddr;
3234
        addrlen = sizeof(saddr);
3235
        if (parse_host_port(&saddr, host_str) < 0)
3236
            goto fail;
3237
    }
3238

    
3239
    ptr = host_str;
3240
    while((ptr = strchr(ptr,','))) {
3241
        ptr++;
3242
        if (!strncmp(ptr,"server",6)) {
3243
            is_listen = 1;
3244
        } else if (!strncmp(ptr,"nowait",6)) {
3245
            is_waitconnect = 0;
3246
        } else if (!strncmp(ptr,"nodelay",6)) {
3247
            do_nodelay = 1;
3248
        } else {
3249
            printf("Unknown option: %s\n", ptr);
3250
            goto fail;
3251
        }
3252
    }
3253
    if (!is_listen)
3254
        is_waitconnect = 0;
3255

    
3256
    chr = qemu_mallocz(sizeof(CharDriverState));
3257
    if (!chr)
3258
        goto fail;
3259
    s = qemu_mallocz(sizeof(TCPCharDriver));
3260
    if (!s)
3261
        goto fail;
3262

    
3263
#ifndef _WIN32
3264
    if (is_unix)
3265
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3266
    else
3267
#endif
3268
        fd = socket(PF_INET, SOCK_STREAM, 0);
3269

    
3270
    if (fd < 0)
3271
        goto fail;
3272

    
3273
    if (!is_waitconnect)
3274
        socket_set_nonblock(fd);
3275

    
3276
    s->connected = 0;
3277
    s->fd = -1;
3278
    s->listen_fd = -1;
3279
    s->is_unix = is_unix;
3280
    s->do_nodelay = do_nodelay && !is_unix;
3281

    
3282
    chr->opaque = s;
3283
    chr->chr_write = tcp_chr_write;
3284
    chr->chr_close = tcp_chr_close;
3285

    
3286
    if (is_listen) {
3287
        /* allow fast reuse */
3288
#ifndef _WIN32
3289
        if (is_unix) {
3290
            char path[109];
3291
            strncpy(path, uaddr.sun_path, 108);
3292
            path[108] = 0;
3293
            unlink(path);
3294
        } else
3295
#endif
3296
        {
3297
            val = 1;
3298
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3299
        }
3300

    
3301
        ret = bind(fd, addr, addrlen);
3302
        if (ret < 0)
3303
            goto fail;
3304

    
3305
        ret = listen(fd, 0);
3306
        if (ret < 0)
3307
            goto fail;
3308

    
3309
        s->listen_fd = fd;
3310
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3311
        if (is_telnet)
3312
            s->do_telnetopt = 1;
3313
    } else {
3314
        for(;;) {
3315
            ret = connect(fd, addr, addrlen);
3316
            if (ret < 0) {
3317
                err = socket_error();
3318
                if (err == EINTR || err == EWOULDBLOCK) {
3319
                } else if (err == EINPROGRESS) {
3320
                    break;
3321
#ifdef _WIN32
3322
                } else if (err == WSAEALREADY) {
3323
                    break;
3324
#endif
3325
                } else {
3326
                    goto fail;
3327
                }
3328
            } else {
3329
                s->connected = 1;
3330
                break;
3331
            }
3332
        }
3333
        s->fd = fd;
3334
        socket_set_nodelay(fd);
3335
        if (s->connected)
3336
            tcp_chr_connect(chr);
3337
        else
3338
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3339
    }
3340

    
3341
    if (is_listen && is_waitconnect) {
3342
        printf("QEMU waiting for connection on: %s\n", host_str);
3343
        tcp_chr_accept(chr);
3344
        socket_set_nonblock(s->listen_fd);
3345
    }
3346

    
3347
    return chr;
3348
 fail:
3349
    if (fd >= 0)
3350
        closesocket(fd);
3351
    qemu_free(s);
3352
    qemu_free(chr);
3353
    return NULL;
3354
}
3355

    
3356
CharDriverState *qemu_chr_open(const char *filename)
3357
{
3358
    const char *p;
3359

    
3360
    if (!strcmp(filename, "vc")) {
3361
        return text_console_init(&display_state, 0);
3362
    } else if (strstart(filename, "vc:", &p)) {
3363
        return text_console_init(&display_state, p);
3364
    } else if (!strcmp(filename, "null")) {
3365
        return qemu_chr_open_null();
3366
    } else
3367
    if (strstart(filename, "tcp:", &p)) {
3368
        return qemu_chr_open_tcp(p, 0, 0);
3369
    } else
3370
    if (strstart(filename, "telnet:", &p)) {
3371
        return qemu_chr_open_tcp(p, 1, 0);
3372
    } else
3373
    if (strstart(filename, "udp:", &p)) {
3374
        return qemu_chr_open_udp(p);
3375
    } else
3376
    if (strstart(filename, "mon:", &p)) {
3377
        CharDriverState *drv = qemu_chr_open(p);
3378
        if (drv) {
3379
            drv = qemu_chr_open_mux(drv);
3380
            monitor_init(drv, !nographic);
3381
            return drv;
3382
        }
3383
        printf("Unable to open driver: %s\n", p);
3384
        return 0;
3385
    } else
3386
#ifndef _WIN32
3387
    if (strstart(filename, "unix:", &p)) {
3388
        return qemu_chr_open_tcp(p, 0, 1);
3389
    } else if (strstart(filename, "file:", &p)) {
3390
        return qemu_chr_open_file_out(p);
3391
    } else if (strstart(filename, "pipe:", &p)) {
3392
        return qemu_chr_open_pipe(p);
3393
    } else if (!strcmp(filename, "pty")) {
3394
        return qemu_chr_open_pty();
3395
    } else if (!strcmp(filename, "stdio")) {
3396
        return qemu_chr_open_stdio();
3397
    } else
3398
#if defined(__linux__)
3399
    if (strstart(filename, "/dev/parport", NULL)) {
3400
        return qemu_chr_open_pp(filename);
3401
    } else
3402
#endif
3403
#if defined(__linux__) || defined(__sun__)
3404
    if (strstart(filename, "/dev/", NULL)) {
3405
        return qemu_chr_open_tty(filename);
3406
    } else
3407
#endif
3408
#else /* !_WIN32 */
3409
    if (strstart(filename, "COM", NULL)) {
3410
        return qemu_chr_open_win(filename);
3411
    } else
3412
    if (strstart(filename, "pipe:", &p)) {
3413
        return qemu_chr_open_win_pipe(p);
3414
    } else
3415
    if (strstart(filename, "con:", NULL)) {
3416
        return qemu_chr_open_win_con(filename);
3417
    } else
3418
    if (strstart(filename, "file:", &p)) {
3419
        return qemu_chr_open_win_file_out(p);
3420
    }
3421
#endif
3422
    {
3423
        return NULL;
3424
    }
3425
}
3426

    
3427
void qemu_chr_close(CharDriverState *chr)
3428
{
3429
    if (chr->chr_close)
3430
        chr->chr_close(chr);
3431
}
3432

    
3433
/***********************************************************/
3434
/* network device redirectors */
3435

    
3436
__attribute__ (( unused ))
3437
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3438
{
3439
    int len, i, j, c;
3440

    
3441
    for(i=0;i<size;i+=16) {
3442
        len = size - i;
3443
        if (len > 16)
3444
            len = 16;
3445
        fprintf(f, "%08x ", i);
3446
        for(j=0;j<16;j++) {
3447
            if (j < len)
3448
                fprintf(f, " %02x", buf[i+j]);
3449
            else
3450
                fprintf(f, "   ");
3451
        }
3452
        fprintf(f, " ");
3453
        for(j=0;j<len;j++) {
3454
            c = buf[i+j];
3455
            if (c < ' ' || c > '~')
3456
                c = '.';
3457
            fprintf(f, "%c", c);
3458
        }
3459
        fprintf(f, "\n");
3460
    }
3461
}
3462

    
3463
static int parse_macaddr(uint8_t *macaddr, const char *p)
3464
{
3465
    int i;
3466
    char *last_char;
3467
    long int offset;
3468

    
3469
    errno = 0;
3470
    offset = strtol(p, &last_char, 0);    
3471
    if (0 == errno && '\0' == *last_char &&
3472
            offset >= 0 && offset <= 0xFFFFFF) {
3473
        macaddr[3] = (offset & 0xFF0000) >> 16;
3474
        macaddr[4] = (offset & 0xFF00) >> 8;
3475
        macaddr[5] = offset & 0xFF;
3476
        return 0;
3477
    } else {
3478
        for(i = 0; i < 6; i++) {
3479
            macaddr[i] = strtol(p, (char **)&p, 16);
3480
            if (i == 5) {
3481
                if (*p != '\0')
3482
                    return -1;
3483
            } else {
3484
                if (*p != ':' && *p != '-')
3485
                    return -1;
3486
                p++;
3487
            }
3488
        }
3489
        return 0;    
3490
    }
3491

    
3492
    return -1;
3493
}
3494

    
3495
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3496
{
3497
    const char *p, *p1;
3498
    int len;
3499
    p = *pp;
3500
    p1 = strchr(p, sep);
3501
    if (!p1)
3502
        return -1;
3503
    len = p1 - p;
3504
    p1++;
3505
    if (buf_size > 0) {
3506
        if (len > buf_size - 1)
3507
            len = buf_size - 1;
3508
        memcpy(buf, p, len);
3509
        buf[len] = '\0';
3510
    }
3511
    *pp = p1;
3512
    return 0;
3513
}
3514

    
3515
int parse_host_src_port(struct sockaddr_in *haddr,
3516
                        struct sockaddr_in *saddr,
3517
                        const char *input_str)
3518
{
3519
    char *str = strdup(input_str);
3520
    char *host_str = str;
3521
    char *src_str;
3522
    char *ptr;
3523

    
3524
    /*
3525
     * Chop off any extra arguments at the end of the string which
3526
     * would start with a comma, then fill in the src port information
3527
     * if it was provided else use the "any address" and "any port".
3528
     */
3529
    if ((ptr = strchr(str,',')))
3530
        *ptr = '\0';
3531

    
3532
    if ((src_str = strchr(input_str,'@'))) {
3533
        *src_str = '\0';
3534
        src_str++;
3535
    }
3536

    
3537
    if (parse_host_port(haddr, host_str) < 0)
3538
        goto fail;
3539

    
3540
    if (!src_str || *src_str == '\0')
3541
        src_str = ":0";
3542

    
3543
    if (parse_host_port(saddr, src_str) < 0)
3544
        goto fail;
3545

    
3546
    free(str);
3547
    return(0);
3548

    
3549
fail:
3550
    free(str);
3551
    return -1;
3552
}
3553

    
3554
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3555
{
3556
    char buf[512];
3557
    struct hostent *he;
3558
    const char *p, *r;
3559
    int port;
3560

    
3561
    p = str;
3562
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3563
        return -1;
3564
    saddr->sin_family = AF_INET;
3565
    if (buf[0] == '\0') {
3566
        saddr->sin_addr.s_addr = 0;
3567
    } else {
3568
        if (isdigit(buf[0])) {
3569
            if (!inet_aton(buf, &saddr->sin_addr))
3570
                return -1;
3571
        } else {
3572
            if ((he = gethostbyname(buf)) == NULL)
3573
                return - 1;
3574
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3575
        }
3576
    }
3577
    port = strtol(p, (char **)&r, 0);
3578
    if (r == p)
3579
        return -1;
3580
    saddr->sin_port = htons(port);
3581
    return 0;
3582
}
3583

    
3584
#ifndef _WIN32
3585
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3586
{
3587
    const char *p;
3588
    int len;
3589

    
3590
    len = MIN(108, strlen(str));
3591
    p = strchr(str, ',');
3592
    if (p)
3593
        len = MIN(len, p - str);
3594

    
3595
    memset(uaddr, 0, sizeof(*uaddr));
3596

    
3597
    uaddr->sun_family = AF_UNIX;
3598
    memcpy(uaddr->sun_path, str, len);
3599

    
3600
    return 0;
3601
}
3602
#endif
3603

    
3604
/* find or alloc a new VLAN */
3605
VLANState *qemu_find_vlan(int id)
3606
{
3607
    VLANState **pvlan, *vlan;
3608
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3609
        if (vlan->id == id)
3610
            return vlan;
3611
    }
3612
    vlan = qemu_mallocz(sizeof(VLANState));
3613
    if (!vlan)
3614
        return NULL;
3615
    vlan->id = id;
3616
    vlan->next = NULL;
3617
    pvlan = &first_vlan;
3618
    while (*pvlan != NULL)
3619
        pvlan = &(*pvlan)->next;
3620
    *pvlan = vlan;
3621
    return vlan;
3622
}
3623

    
3624
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3625
                                      IOReadHandler *fd_read,
3626
                                      IOCanRWHandler *fd_can_read,
3627
                                      void *opaque)
3628
{
3629
    VLANClientState *vc, **pvc;
3630
    vc = qemu_mallocz(sizeof(VLANClientState));
3631
    if (!vc)
3632
        return NULL;
3633
    vc->fd_read = fd_read;
3634
    vc->fd_can_read = fd_can_read;
3635
    vc->opaque = opaque;
3636
    vc->vlan = vlan;
3637

    
3638
    vc->next = NULL;
3639
    pvc = &vlan->first_client;
3640
    while (*pvc != NULL)
3641
        pvc = &(*pvc)->next;
3642
    *pvc = vc;
3643
    return vc;
3644
}
3645

    
3646
int qemu_can_send_packet(VLANClientState *vc1)
3647
{
3648
    VLANState *vlan = vc1->vlan;
3649
    VLANClientState *vc;
3650

    
3651
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3652
        if (vc != vc1) {
3653
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3654
                return 1;
3655
        }
3656
    }
3657
    return 0;
3658
}
3659

    
3660
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3661
{
3662
    VLANState *vlan = vc1->vlan;
3663
    VLANClientState *vc;
3664

    
3665
#if 0
3666
    printf("vlan %d send:\n", vlan->id);
3667
    hex_dump(stdout, buf, size);
3668
#endif
3669
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3670
        if (vc != vc1) {
3671
            vc->fd_read(vc->opaque, buf, size);
3672
        }
3673
    }
3674
}
3675

    
3676
#if defined(CONFIG_SLIRP)
3677

    
3678
/* slirp network adapter */
3679

    
3680
static int slirp_inited;
3681
static VLANClientState *slirp_vc;
3682

    
3683
int slirp_can_output(void)
3684
{
3685
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3686
}
3687

    
3688
void slirp_output(const uint8_t *pkt, int pkt_len)
3689
{
3690
#if 0
3691
    printf("slirp output:\n");
3692
    hex_dump(stdout, pkt, pkt_len);
3693
#endif
3694
    if (!slirp_vc)
3695
        return;
3696
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3697
}
3698

    
3699
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3700
{
3701
#if 0
3702
    printf("slirp input:\n");
3703
    hex_dump(stdout, buf, size);
3704
#endif
3705
    slirp_input(buf, size);
3706
}
3707

    
3708
static int net_slirp_init(VLANState *vlan)
3709
{
3710
    if (!slirp_inited) {
3711
        slirp_inited = 1;
3712
        slirp_init();
3713
    }
3714
    slirp_vc = qemu_new_vlan_client(vlan,
3715
                                    slirp_receive, NULL, NULL);
3716
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3717
    return 0;
3718
}
3719

    
3720
static void net_slirp_redir(const char *redir_str)
3721
{
3722
    int is_udp;
3723
    char buf[256], *r;
3724
    const char *p;
3725
    struct in_addr guest_addr;
3726
    int host_port, guest_port;
3727

    
3728
    if (!slirp_inited) {
3729
        slirp_inited = 1;
3730
        slirp_init();
3731
    }
3732

    
3733
    p = redir_str;
3734
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3735
        goto fail;
3736
    if (!strcmp(buf, "tcp")) {
3737
        is_udp = 0;
3738
    } else if (!strcmp(buf, "udp")) {
3739
        is_udp = 1;
3740
    } else {
3741
        goto fail;
3742
    }
3743

    
3744
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3745
        goto fail;
3746
    host_port = strtol(buf, &r, 0);
3747
    if (r == buf)
3748
        goto fail;
3749

    
3750
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3751
        goto fail;
3752
    if (buf[0] == '\0') {
3753
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3754
    }
3755
    if (!inet_aton(buf, &guest_addr))
3756
        goto fail;
3757

    
3758
    guest_port = strtol(p, &r, 0);
3759
    if (r == p)
3760
        goto fail;
3761

    
3762
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3763
        fprintf(stderr, "qemu: could not set up redirection\n");
3764
        exit(1);
3765
    }
3766
    return;
3767
 fail:
3768
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3769
    exit(1);
3770
}
3771

    
3772
#ifndef _WIN32
3773

    
3774
char smb_dir[1024];
3775

    
3776
static void smb_exit(void)
3777
{
3778
    DIR *d;
3779
    struct dirent *de;
3780
    char filename[1024];
3781

    
3782
    /* erase all the files in the directory */
3783
    d = opendir(smb_dir);
3784
    for(;;) {
3785
        de = readdir(d);
3786
        if (!de)
3787
            break;
3788
        if (strcmp(de->d_name, ".") != 0 &&
3789
            strcmp(de->d_name, "..") != 0) {
3790
            snprintf(filename, sizeof(filename), "%s/%s",
3791
                     smb_dir, de->d_name);
3792
            unlink(filename);
3793
        }
3794
    }
3795
    closedir(d);
3796
    rmdir(smb_dir);
3797
}
3798

    
3799
/* automatic user mode samba server configuration */
3800
static void net_slirp_smb(const char *exported_dir)
3801
{
3802
    char smb_conf[1024];
3803
    char smb_cmdline[1024];
3804
    FILE *f;
3805

    
3806
    if (!slirp_inited) {
3807
        slirp_inited = 1;
3808
        slirp_init();
3809
    }
3810

    
3811
    /* XXX: better tmp dir construction */
3812
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3813
    if (mkdir(smb_dir, 0700) < 0) {
3814
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3815
        exit(1);
3816
    }
3817
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3818

    
3819
    f = fopen(smb_conf, "w");
3820
    if (!f) {
3821
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3822
        exit(1);
3823
    }
3824
    fprintf(f,
3825
            "[global]\n"
3826
            "private dir=%s\n"
3827
            "smb ports=0\n"
3828
            "socket address=127.0.0.1\n"
3829
            "pid directory=%s\n"
3830
            "lock directory=%s\n"
3831
            "log file=%s/log.smbd\n"
3832
            "smb passwd file=%s/smbpasswd\n"
3833
            "security = share\n"
3834
            "[qemu]\n"
3835
            "path=%s\n"
3836
            "read only=no\n"
3837
            "guest ok=yes\n",
3838
            smb_dir,
3839
            smb_dir,
3840
            smb_dir,
3841
            smb_dir,
3842
            smb_dir,
3843
            exported_dir
3844
            );
3845
    fclose(f);
3846
    atexit(smb_exit);
3847

    
3848
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3849
             SMBD_COMMAND, smb_conf);
3850

    
3851
    slirp_add_exec(0, smb_cmdline, 4, 139);
3852
}
3853

    
3854
#endif /* !defined(_WIN32) */
3855
void do_info_slirp(void)
3856
{
3857
    slirp_stats();
3858
}
3859

    
3860
#endif /* CONFIG_SLIRP */
3861

    
3862
#if !defined(_WIN32)
3863

    
3864
typedef struct TAPState {
3865
    VLANClientState *vc;
3866
    int fd;
3867
    char down_script[1024];
3868
} TAPState;
3869

    
3870
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3871
{
3872
    TAPState *s = opaque;
3873
    int ret;
3874
    for(;;) {
3875
        ret = write(s->fd, buf, size);
3876
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3877
        } else {
3878
            break;
3879
        }
3880
    }
3881
}
3882

    
3883
static void tap_send(void *opaque)
3884
{
3885
    TAPState *s = opaque;
3886
    uint8_t buf[4096];
3887
    int size;
3888

    
3889
#ifdef __sun__
3890
    struct strbuf sbuf;
3891
    int f = 0;
3892
    sbuf.maxlen = sizeof(buf);
3893
    sbuf.buf = buf;
3894
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3895
#else
3896
    size = read(s->fd, buf, sizeof(buf));
3897
#endif
3898
    if (size > 0) {
3899
        qemu_send_packet(s->vc, buf, size);
3900
    }
3901
}
3902

    
3903
/* fd support */
3904

    
3905
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3906
{
3907
    TAPState *s;
3908

    
3909
    s = qemu_mallocz(sizeof(TAPState));
3910
    if (!s)
3911
        return NULL;
3912
    s->fd = fd;
3913
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3914
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3915
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3916
    return s;
3917
}
3918

    
3919
#if defined (_BSD) || defined (__FreeBSD_kernel__)
3920
static int tap_open(char *ifname, int ifname_size)
3921
{
3922
    int fd;
3923
    char *dev;
3924
    struct stat s;
3925

    
3926
    TFR(fd = open("/dev/tap", O_RDWR));
3927
    if (fd < 0) {
3928
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3929
        return -1;
3930
    }
3931

    
3932
    fstat(fd, &s);
3933
    dev = devname(s.st_rdev, S_IFCHR);
3934
    pstrcpy(ifname, ifname_size, dev);
3935

    
3936
    fcntl(fd, F_SETFL, O_NONBLOCK);
3937
    return fd;
3938
}
3939
#elif defined(__sun__)
3940
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3941
/*
3942
 * Allocate TAP device, returns opened fd.
3943
 * Stores dev name in the first arg(must be large enough).
3944
 */
3945
int tap_alloc(char *dev)
3946
{
3947
    int tap_fd, if_fd, ppa = -1;
3948
    static int ip_fd = 0;
3949
    char *ptr;
3950

    
3951
    static int arp_fd = 0;
3952
    int ip_muxid, arp_muxid;
3953
    struct strioctl  strioc_if, strioc_ppa;
3954
    int link_type = I_PLINK;;
3955
    struct lifreq ifr;
3956
    char actual_name[32] = "";
3957

    
3958
    memset(&ifr, 0x0, sizeof(ifr));
3959

    
3960
    if( *dev ){
3961
       ptr = dev;
3962
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
3963
       ppa = atoi(ptr);
3964
    }
3965

    
3966
    /* Check if IP device was opened */
3967
    if( ip_fd )
3968
       close(ip_fd);
3969

    
3970
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3971
    if (ip_fd < 0) {
3972
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3973
       return -1;
3974
    }
3975

    
3976
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3977
    if (tap_fd < 0) {
3978
       syslog(LOG_ERR, "Can't open /dev/tap");
3979
       return -1;
3980
    }
3981

    
3982
    /* Assign a new PPA and get its unit number. */
3983
    strioc_ppa.ic_cmd = TUNNEWPPA;
3984
    strioc_ppa.ic_timout = 0;
3985
    strioc_ppa.ic_len = sizeof(ppa);
3986
    strioc_ppa.ic_dp = (char *)&ppa;
3987
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3988
       syslog (LOG_ERR, "Can't assign new interface");
3989

    
3990
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3991
    if (if_fd < 0) {
3992
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3993
       return -1;
3994
    }
3995
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3996
       syslog(LOG_ERR, "Can't push IP module");
3997
       return -1;
3998
    }
3999

    
4000
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4001
        syslog(LOG_ERR, "Can't get flags\n");
4002

    
4003
    snprintf (actual_name, 32, "tap%d", ppa);
4004
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4005

    
4006
    ifr.lifr_ppa = ppa;
4007
    /* Assign ppa according to the unit number returned by tun device */
4008

    
4009
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4010
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
4011
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4012
        syslog (LOG_ERR, "Can't get flags\n");
4013
    /* Push arp module to if_fd */
4014
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
4015
        syslog (LOG_ERR, "Can't push ARP module (2)");
4016

    
4017
    /* Push arp module to ip_fd */
4018
    if (ioctl (ip_fd, I_POP, NULL) < 0)
4019
        syslog (LOG_ERR, "I_POP failed\n");
4020
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4021
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
4022
    /* Open arp_fd */
4023
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4024
    if (arp_fd < 0)
4025
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4026

    
4027
    /* Set ifname to arp */
4028
    strioc_if.ic_cmd = SIOCSLIFNAME;
4029
    strioc_if.ic_timout = 0;
4030
    strioc_if.ic_len = sizeof(ifr);
4031
    strioc_if.ic_dp = (char *)&ifr;
4032
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4033
        syslog (LOG_ERR, "Can't set ifname to arp\n");
4034
    }
4035

    
4036
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4037
       syslog(LOG_ERR, "Can't link TAP device to IP");
4038
       return -1;
4039
    }
4040

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

    
4044
    close (if_fd);
4045

    
4046
    memset(&ifr, 0x0, sizeof(ifr));
4047
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4048
    ifr.lifr_ip_muxid  = ip_muxid;
4049
    ifr.lifr_arp_muxid = arp_muxid;
4050

    
4051
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4052
    {
4053
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4054
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4055
      syslog (LOG_ERR, "Can't set multiplexor id");
4056
    }
4057

    
4058
    sprintf(dev, "tap%d", ppa);
4059
    return tap_fd;
4060
}
4061

    
4062
static int tap_open(char *ifname, int ifname_size)
4063
{
4064
    char  dev[10]="";
4065
    int fd;
4066
    if( (fd = tap_alloc(dev)) < 0 ){
4067
       fprintf(stderr, "Cannot allocate TAP device\n");
4068
       return -1;
4069
    }
4070
    pstrcpy(ifname, ifname_size, dev);
4071
    fcntl(fd, F_SETFL, O_NONBLOCK);
4072
    return fd;
4073
}
4074
#else
4075
static int tap_open(char *ifname, int ifname_size)
4076
{
4077
    struct ifreq ifr;
4078
    int fd, ret;
4079

    
4080
    TFR(fd = open("/dev/net/tun", O_RDWR));
4081
    if (fd < 0) {
4082
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4083
        return -1;
4084
    }
4085
    memset(&ifr, 0, sizeof(ifr));
4086
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4087
    if (ifname[0] != '\0')
4088
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4089
    else
4090
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4091
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4092
    if (ret != 0) {
4093
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4094
        close(fd);
4095
        return -1;
4096
    }
4097
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4098
    fcntl(fd, F_SETFL, O_NONBLOCK);
4099
    return fd;
4100
}
4101
#endif
4102

    
4103
static int launch_script(const char *setup_script, const char *ifname, int fd)
4104
{
4105
    int pid, status;
4106
    char *args[3];
4107
    char **parg;
4108

    
4109
        /* try to launch network script */
4110
        pid = fork();
4111
        if (pid >= 0) {
4112
            if (pid == 0) {
4113
                int open_max = sysconf (_SC_OPEN_MAX), i;
4114
                for (i = 0; i < open_max; i++)
4115
                    if (i != STDIN_FILENO &&
4116
                        i != STDOUT_FILENO &&
4117
                        i != STDERR_FILENO &&
4118
                        i != fd)
4119
                        close(i);
4120

    
4121
                parg = args;
4122
                *parg++ = (char *)setup_script;
4123
                *parg++ = (char *)ifname;
4124
                *parg++ = NULL;
4125
                execv(setup_script, args);
4126
                _exit(1);
4127
            }
4128
            while (waitpid(pid, &status, 0) != pid);
4129
            if (!WIFEXITED(status) ||
4130
                WEXITSTATUS(status) != 0) {
4131
                fprintf(stderr, "%s: could not launch network script\n",
4132
                        setup_script);
4133
                return -1;
4134
            }
4135
        }
4136
    return 0;
4137
}
4138

    
4139
static int net_tap_init(VLANState *vlan, const char *ifname1,
4140
                        const char *setup_script, const char *down_script)
4141
{
4142
    TAPState *s;
4143
    int fd;
4144
    char ifname[128];
4145

    
4146
    if (ifname1 != NULL)
4147
        pstrcpy(ifname, sizeof(ifname), ifname1);
4148
    else
4149
        ifname[0] = '\0';
4150
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4151
    if (fd < 0)
4152
        return -1;
4153

    
4154
    if (!setup_script || !strcmp(setup_script, "no"))
4155
        setup_script = "";
4156
    if (setup_script[0] != '\0') {
4157
        if (launch_script(setup_script, ifname, fd))
4158
            return -1;
4159
    }
4160
    s = net_tap_fd_init(vlan, fd);
4161
    if (!s)
4162
        return -1;
4163
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4164
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4165
    if (down_script && strcmp(down_script, "no"))
4166
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4167
    return 0;
4168
}
4169

    
4170
#endif /* !_WIN32 */
4171

    
4172
/* network connection */
4173
typedef struct NetSocketState {
4174
    VLANClientState *vc;
4175
    int fd;
4176
    int state; /* 0 = getting length, 1 = getting data */
4177
    int index;
4178
    int packet_len;
4179
    uint8_t buf[4096];
4180
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4181
} NetSocketState;
4182

    
4183
typedef struct NetSocketListenState {
4184
    VLANState *vlan;
4185
    int fd;
4186
} NetSocketListenState;
4187

    
4188
/* XXX: we consider we can send the whole packet without blocking */
4189
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4190
{
4191
    NetSocketState *s = opaque;
4192
    uint32_t len;
4193
    len = htonl(size);
4194

    
4195
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4196
    send_all(s->fd, buf, size);
4197
}
4198

    
4199
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4200
{
4201
    NetSocketState *s = opaque;
4202
    sendto(s->fd, buf, size, 0,
4203
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4204
}
4205

    
4206
static void net_socket_send(void *opaque)
4207
{
4208
    NetSocketState *s = opaque;
4209
    int l, size, err;
4210
    uint8_t buf1[4096];
4211
    const uint8_t *buf;
4212

    
4213
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4214
    if (size < 0) {
4215
        err = socket_error();
4216
        if (err != EWOULDBLOCK)
4217
            goto eoc;
4218
    } else if (size == 0) {
4219
        /* end of connection */
4220
    eoc:
4221
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4222
        closesocket(s->fd);
4223
        return;
4224
    }
4225
    buf = buf1;
4226
    while (size > 0) {
4227
        /* reassemble a packet from the network */
4228
        switch(s->state) {
4229
        case 0:
4230
            l = 4 - s->index;
4231
            if (l > size)
4232
                l = size;
4233
            memcpy(s->buf + s->index, buf, l);
4234
            buf += l;
4235
            size -= l;
4236
            s->index += l;
4237
            if (s->index == 4) {
4238
                /* got length */
4239
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4240
                s->index = 0;
4241
                s->state = 1;
4242
            }
4243
            break;
4244
        case 1:
4245
            l = s->packet_len - s->index;
4246
            if (l > size)
4247
                l = size;
4248
            memcpy(s->buf + s->index, buf, l);
4249
            s->index += l;
4250
            buf += l;
4251
            size -= l;
4252
            if (s->index >= s->packet_len) {
4253
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4254
                s->index = 0;
4255
                s->state = 0;
4256
            }
4257
            break;
4258
        }
4259
    }
4260
}
4261

    
4262
static void net_socket_send_dgram(void *opaque)
4263
{
4264
    NetSocketState *s = opaque;
4265
    int size;
4266

    
4267
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4268
    if (size < 0)
4269
        return;
4270
    if (size == 0) {
4271
        /* end of connection */
4272
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4273
        return;
4274
    }
4275
    qemu_send_packet(s->vc, s->buf, size);
4276
}
4277

    
4278
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4279
{
4280
    struct ip_mreq imr;
4281
    int fd;
4282
    int val, ret;
4283
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4284
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4285
                inet_ntoa(mcastaddr->sin_addr),
4286
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4287
        return -1;
4288

    
4289
    }
4290
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4291
    if (fd < 0) {
4292
        perror("socket(PF_INET, SOCK_DGRAM)");
4293
        return -1;
4294
    }
4295

    
4296
    val = 1;
4297
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4298
                   (const char *)&val, sizeof(val));
4299
    if (ret < 0) {
4300
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4301
        goto fail;
4302
    }
4303

    
4304
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4305
    if (ret < 0) {
4306
        perror("bind");
4307
        goto fail;
4308
    }
4309

    
4310
    /* Add host to multicast group */
4311
    imr.imr_multiaddr = mcastaddr->sin_addr;
4312
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4313

    
4314
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4315
                     (const char *)&imr, sizeof(struct ip_mreq));
4316
    if (ret < 0) {
4317
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4318
        goto fail;
4319
    }
4320

    
4321
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4322
    val = 1;
4323
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4324
                   (const char *)&val, sizeof(val));
4325
    if (ret < 0) {
4326
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4327
        goto fail;
4328
    }
4329

    
4330
    socket_set_nonblock(fd);
4331
    return fd;
4332
fail:
4333
    if (fd >= 0)
4334
        closesocket(fd);
4335
    return -1;
4336
}
4337

    
4338
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4339
                                          int is_connected)
4340
{
4341
    struct sockaddr_in saddr;
4342
    int newfd;
4343
    socklen_t saddr_len;
4344
    NetSocketState *s;
4345

    
4346
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4347
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4348
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4349
     */
4350

    
4351
    if (is_connected) {
4352
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4353
            /* must be bound */
4354
            if (saddr.sin_addr.s_addr==0) {
4355
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4356
                        fd);
4357
                return NULL;
4358
            }
4359
            /* clone dgram socket */
4360
            newfd = net_socket_mcast_create(&saddr);
4361
            if (newfd < 0) {
4362
                /* error already reported by net_socket_mcast_create() */
4363
                close(fd);
4364
                return NULL;
4365
            }
4366
            /* clone newfd to fd, close newfd */
4367
            dup2(newfd, fd);
4368
            close(newfd);
4369

    
4370
        } else {
4371
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4372
                    fd, strerror(errno));
4373
            return NULL;
4374
        }
4375
    }
4376

    
4377
    s = qemu_mallocz(sizeof(NetSocketState));
4378
    if (!s)
4379
        return NULL;
4380
    s->fd = fd;
4381

    
4382
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4383
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4384

    
4385
    /* mcast: save bound address as dst */
4386
    if (is_connected) s->dgram_dst=saddr;
4387

    
4388
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4389
            "socket: fd=%d (%s mcast=%s:%d)",
4390
            fd, is_connected? "cloned" : "",
4391
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4392
    return s;
4393
}
4394

    
4395
static void net_socket_connect(void *opaque)
4396
{
4397
    NetSocketState *s = opaque;
4398
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4399
}
4400

    
4401
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4402
                                          int is_connected)
4403
{
4404
    NetSocketState *s;
4405
    s = qemu_mallocz(sizeof(NetSocketState));
4406
    if (!s)
4407
        return NULL;
4408
    s->fd = fd;
4409
    s->vc = qemu_new_vlan_client(vlan,
4410
                                 net_socket_receive, NULL, s);
4411
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4412
             "socket: fd=%d", fd);
4413
    if (is_connected) {
4414
        net_socket_connect(s);
4415
    } else {
4416
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4417
    }
4418
    return s;
4419
}
4420

    
4421
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4422
                                          int is_connected)
4423
{
4424
    int so_type=-1, optlen=sizeof(so_type);
4425

    
4426
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4427
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4428
        return NULL;
4429
    }
4430
    switch(so_type) {
4431
    case SOCK_DGRAM:
4432
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4433
    case SOCK_STREAM:
4434
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4435
    default:
4436
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4437
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4438
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4439
    }
4440
    return NULL;
4441
}
4442

    
4443
static void net_socket_accept(void *opaque)
4444
{
4445
    NetSocketListenState *s = opaque;
4446
    NetSocketState *s1;
4447
    struct sockaddr_in saddr;
4448
    socklen_t len;
4449
    int fd;
4450

    
4451
    for(;;) {
4452
        len = sizeof(saddr);
4453
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4454
        if (fd < 0 && errno != EINTR) {
4455
            return;
4456
        } else if (fd >= 0) {
4457
            break;
4458
        }
4459
    }
4460
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4461
    if (!s1) {
4462
        closesocket(fd);
4463
    } else {
4464
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4465
                 "socket: connection from %s:%d",
4466
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4467
    }
4468
}
4469

    
4470
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4471
{
4472
    NetSocketListenState *s;
4473
    int fd, val, ret;
4474
    struct sockaddr_in saddr;
4475

    
4476
    if (parse_host_port(&saddr, host_str) < 0)
4477
        return -1;
4478

    
4479
    s = qemu_mallocz(sizeof(NetSocketListenState));
4480
    if (!s)
4481
        return -1;
4482

    
4483
    fd = socket(PF_INET, SOCK_STREAM, 0);
4484
    if (fd < 0) {
4485
        perror("socket");
4486
        return -1;
4487
    }
4488
    socket_set_nonblock(fd);
4489

    
4490
    /* allow fast reuse */
4491
    val = 1;
4492
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4493

    
4494
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4495
    if (ret < 0) {
4496
        perror("bind");
4497
        return -1;
4498
    }
4499
    ret = listen(fd, 0);
4500
    if (ret < 0) {
4501
        perror("listen");
4502
        return -1;
4503
    }
4504
    s->vlan = vlan;
4505
    s->fd = fd;
4506
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4507
    return 0;
4508
}
4509

    
4510
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4511
{
4512
    NetSocketState *s;
4513
    int fd, connected, ret, err;
4514
    struct sockaddr_in saddr;
4515

    
4516
    if (parse_host_port(&saddr, host_str) < 0)
4517
        return -1;
4518

    
4519
    fd = socket(PF_INET, SOCK_STREAM, 0);
4520
    if (fd < 0) {
4521
        perror("socket");
4522
        return -1;
4523
    }
4524
    socket_set_nonblock(fd);
4525

    
4526
    connected = 0;
4527
    for(;;) {
4528
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4529
        if (ret < 0) {
4530
            err = socket_error();
4531
            if (err == EINTR || err == EWOULDBLOCK) {
4532
            } else if (err == EINPROGRESS) {
4533
                break;
4534
#ifdef _WIN32
4535
            } else if (err == WSAEALREADY) {
4536
                break;
4537
#endif
4538
            } else {
4539
                perror("connect");
4540
                closesocket(fd);
4541
                return -1;
4542
            }
4543
        } else {
4544
            connected = 1;
4545
            break;
4546
        }
4547
    }
4548
    s = net_socket_fd_init(vlan, fd, connected);
4549
    if (!s)
4550
        return -1;
4551
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4552
             "socket: connect to %s:%d",
4553
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4554
    return 0;
4555
}
4556

    
4557
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4558
{
4559
    NetSocketState *s;
4560
    int fd;
4561
    struct sockaddr_in saddr;
4562

    
4563
    if (parse_host_port(&saddr, host_str) < 0)
4564
        return -1;
4565

    
4566

    
4567
    fd = net_socket_mcast_create(&saddr);
4568
    if (fd < 0)
4569
        return -1;
4570

    
4571
    s = net_socket_fd_init(vlan, fd, 0);
4572
    if (!s)
4573
        return -1;
4574

    
4575
    s->dgram_dst = saddr;
4576

    
4577
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4578
             "socket: mcast=%s:%d",
4579
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4580
    return 0;
4581

    
4582
}
4583

    
4584
static const char *get_word(char *buf, int buf_size, const char *p)
4585
{
4586
    char *q;
4587
    int substring;
4588

    
4589
    substring = 0;
4590
    q = buf;
4591
    while (*p != '\0') {
4592
        if (*p == '\\') {
4593
            p++;
4594
            if (*p == '\0')
4595
                break;
4596
        } else if (*p == '\"') {
4597
            substring = !substring;
4598
            p++;
4599
            continue;
4600
        } else if (!substring && (*p == ',' || *p == '='))
4601
            break;
4602
        if (q && (q - buf) < buf_size - 1)
4603
            *q++ = *p;
4604
        p++;
4605
    }
4606
    if (q)
4607
        *q = '\0';
4608

    
4609
    return p;
4610
}
4611

    
4612
static int get_param_value(char *buf, int buf_size,
4613
                           const char *tag, const char *str)
4614
{
4615
    const char *p;
4616
    char option[128];
4617

    
4618
    p = str;
4619
    for(;;) {
4620
        p = get_word(option, sizeof(option), p);
4621
        if (*p != '=')
4622
            break;
4623
        p++;
4624
        if (!strcmp(tag, option)) {
4625
            (void)get_word(buf, buf_size, p);
4626
            return strlen(buf);
4627
        } else {
4628
            p = get_word(NULL, 0, p);
4629
        }
4630
        if (*p != ',')
4631
            break;
4632
        p++;
4633
    }
4634
    return 0;
4635
}
4636

    
4637
static int check_params(char *buf, int buf_size,
4638
                        char **params, const char *str)
4639
{
4640
    const char *p;
4641
    int i;
4642

    
4643
    p = str;
4644
    for(;;) {
4645
        p = get_word(buf, buf_size, p);
4646
        if (*p != '=')
4647
            return -1;
4648
        p++;
4649
        for(i = 0; params[i] != NULL; i++)
4650
            if (!strcmp(params[i], buf))
4651
                break;
4652
        if (params[i] == NULL)
4653
            return -1;
4654
        p = get_word(NULL, 0, p);
4655
        if (*p != ',')
4656
            break;
4657
        p++;
4658
    }
4659
    return 0;
4660
}
4661

    
4662

    
4663
static int net_client_init(const char *str)
4664
{
4665
    const char *p;
4666
    char *q;
4667
    char device[64];
4668
    char buf[1024];
4669
    int vlan_id, ret;
4670
    VLANState *vlan;
4671

    
4672
    p = str;
4673
    q = device;
4674
    while (*p != '\0' && *p != ',') {
4675
        if ((q - device) < sizeof(device) - 1)
4676
            *q++ = *p;
4677
        p++;
4678
    }
4679
    *q = '\0';
4680
    if (*p == ',')
4681
        p++;
4682
    vlan_id = 0;
4683
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4684
        vlan_id = strtol(buf, NULL, 0);
4685
    }
4686
    vlan = qemu_find_vlan(vlan_id);
4687
    if (!vlan) {
4688
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4689
        return -1;
4690
    }
4691
    if (!strcmp(device, "nic")) {
4692
        NICInfo *nd;
4693
        uint8_t *macaddr;
4694

    
4695
        if (nb_nics >= MAX_NICS) {
4696
            fprintf(stderr, "Too Many NICs\n");
4697
            return -1;
4698
        }
4699
        nd = &nd_table[nb_nics];
4700
        macaddr = nd->macaddr;
4701
        macaddr[0] = 0x52;
4702
        macaddr[1] = 0x54;
4703
        macaddr[2] = 0x00;
4704
        macaddr[3] = 0x12;
4705
        macaddr[4] = 0x34;
4706
        macaddr[5] = 0x56 + nb_nics;
4707

    
4708
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4709
            if (parse_macaddr(macaddr, buf) < 0) {
4710
                fprintf(stderr, "invalid syntax for ethernet address\n");
4711
                return -1;
4712
            }
4713
        }
4714
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4715
            nd->model = strdup(buf);
4716
        }
4717
        nd->vlan = vlan;
4718
        nb_nics++;
4719
        vlan->nb_guest_devs++;
4720
        ret = 0;
4721
    } else
4722
    if (!strcmp(device, "none")) {
4723
        /* does nothing. It is needed to signal that no network cards
4724
           are wanted */
4725
        ret = 0;
4726
    } else
4727
#ifdef CONFIG_SLIRP
4728
    if (!strcmp(device, "user")) {
4729
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4730
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4731
        }
4732
        vlan->nb_host_devs++;
4733
        ret = net_slirp_init(vlan);
4734
    } else
4735
#endif
4736
#ifdef _WIN32
4737
    if (!strcmp(device, "tap")) {
4738
        char ifname[64];
4739
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4740
            fprintf(stderr, "tap: no interface name\n");
4741
            return -1;
4742
        }
4743
        vlan->nb_host_devs++;
4744
        ret = tap_win32_init(vlan, ifname);
4745
    } else
4746
#else
4747
    if (!strcmp(device, "tap")) {
4748
        char ifname[64];
4749
        char setup_script[1024], down_script[1024];
4750
        int fd;
4751
        vlan->nb_host_devs++;
4752
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4753
            fd = strtol(buf, NULL, 0);
4754
            ret = -1;
4755
            if (net_tap_fd_init(vlan, fd))
4756
                ret = 0;
4757
        } else {
4758
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4759
                ifname[0] = '\0';
4760
            }
4761
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4762
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4763
            }
4764
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4765
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4766
            }
4767
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
4768
        }
4769
    } else
4770
#endif
4771
    if (!strcmp(device, "socket")) {
4772
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4773
            int fd;
4774
            fd = strtol(buf, NULL, 0);
4775
            ret = -1;
4776
            if (net_socket_fd_init(vlan, fd, 1))
4777
                ret = 0;
4778
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4779
            ret = net_socket_listen_init(vlan, buf);
4780
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4781
            ret = net_socket_connect_init(vlan, buf);
4782
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4783
            ret = net_socket_mcast_init(vlan, buf);
4784
        } else {
4785
            fprintf(stderr, "Unknown socket options: %s\n", p);
4786
            return -1;
4787
        }
4788
        vlan->nb_host_devs++;
4789
    } else
4790
    {
4791
        fprintf(stderr, "Unknown network device: %s\n", device);
4792
        return -1;
4793
    }
4794
    if (ret < 0) {
4795
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4796
    }
4797

    
4798
    return ret;
4799
}
4800

    
4801
void do_info_network(void)
4802
{
4803
    VLANState *vlan;
4804
    VLANClientState *vc;
4805

    
4806
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4807
        term_printf("VLAN %d devices:\n", vlan->id);
4808
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4809
            term_printf("  %s\n", vc->info_str);
4810
    }
4811
}
4812

    
4813
#define HD_ALIAS "file=\"%s\",index=%d,media=disk"
4814
#ifdef TARGET_PPC
4815
#define CDROM_ALIAS "index=1,media=cdrom"
4816
#else
4817
#define CDROM_ALIAS "index=2,media=cdrom"
4818
#endif
4819
#define FD_ALIAS "index=%d,if=floppy"
4820
#define PFLASH_ALIAS "file=\"%s\",if=pflash"
4821
#define MTD_ALIAS "file=\"%s\",if=mtd"
4822
#define SD_ALIAS "index=0,if=sd"
4823

    
4824
static int drive_add(const char *fmt, ...)
4825
{
4826
    va_list ap;
4827

    
4828
    if (nb_drives_opt >= MAX_DRIVES) {
4829
        fprintf(stderr, "qemu: too many drives\n");
4830
        exit(1);
4831
    }
4832

    
4833
    va_start(ap, fmt);
4834
    vsnprintf(drives_opt[nb_drives_opt], sizeof(drives_opt[0]), fmt, ap);
4835
    va_end(ap);
4836

    
4837
    return nb_drives_opt++;
4838
}
4839

    
4840
int drive_get_index(BlockInterfaceType interface, int bus, int unit)
4841
{
4842
    int index;
4843

    
4844
    /* seek interface, bus and unit */
4845

    
4846
    for (index = 0; index < nb_drives; index++)
4847
        if (drives_table[index].interface == interface &&
4848
            drives_table[index].bus == bus &&
4849
            drives_table[index].unit == unit)
4850
        return index;
4851

    
4852
    return -1;
4853
}
4854

    
4855
int drive_get_max_bus(BlockInterfaceType interface)
4856
{
4857
    int max_bus;
4858
    int index;
4859

    
4860
    max_bus = -1;
4861
    for (index = 0; index < nb_drives; index++) {
4862
        if(drives_table[index].interface == interface &&
4863
           drives_table[index].bus > max_bus)
4864
            max_bus = drives_table[index].bus;
4865
    }
4866
    return max_bus;
4867
}
4868

    
4869
static int drive_init(const char *str, int snapshot, QEMUMachine *machine)
4870
{
4871
    char buf[128];
4872
    char file[1024];
4873
    char devname[128];
4874
    const char *mediastr = "";
4875
    BlockInterfaceType interface;
4876
    enum { MEDIA_DISK, MEDIA_CDROM } media;
4877
    int bus_id, unit_id;
4878
    int cyls, heads, secs, translation;
4879
    BlockDriverState *bdrv;
4880
    int max_devs;
4881
    int index;
4882
    char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4883
                       "secs", "trans", "media", "snapshot", "file", NULL };
4884

    
4885
    if (check_params(buf, sizeof(buf), params, str) < 0) {
4886
         fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4887
                         buf, str);
4888
         return -1;
4889
    }
4890

    
4891
    file[0] = 0;
4892
    cyls = heads = secs = 0;
4893
    bus_id = 0;
4894
    unit_id = -1;
4895
    translation = BIOS_ATA_TRANSLATION_AUTO;
4896
    index = -1;
4897

    
4898
    if (!strcmp(machine->name, "realview") ||
4899
        !strcmp(machine->name, "SS-5") ||
4900
        !strcmp(machine->name, "SS-10") ||
4901
        !strcmp(machine->name, "SS-600MP") ||
4902
        !strcmp(machine->name, "versatilepb") ||
4903
        !strcmp(machine->name, "versatileab")) {
4904
        interface = IF_SCSI;
4905
        max_devs = MAX_SCSI_DEVS;
4906
        strcpy(devname, "scsi");
4907
    } else {
4908
        interface = IF_IDE;
4909
        max_devs = MAX_IDE_DEVS;
4910
        strcpy(devname, "ide");
4911
    }
4912
    media = MEDIA_DISK;
4913

    
4914
    /* extract parameters */
4915

    
4916
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
4917
        bus_id = strtol(buf, NULL, 0);
4918
        if (bus_id < 0) {
4919
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4920
            return -1;
4921
        }
4922
    }
4923

    
4924
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
4925
        unit_id = strtol(buf, NULL, 0);
4926
        if (unit_id < 0) {
4927
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4928
            return -1;
4929
        }
4930
    }
4931

    
4932
    if (get_param_value(buf, sizeof(buf), "if", str)) {
4933
        strncpy(devname, buf, sizeof(devname));
4934
        if (!strcmp(buf, "ide")) {
4935
            interface = IF_IDE;
4936
            max_devs = MAX_IDE_DEVS;
4937
        } else if (!strcmp(buf, "scsi")) {
4938
            interface = IF_SCSI;
4939
            max_devs = MAX_SCSI_DEVS;
4940
        } else if (!strcmp(buf, "floppy")) {
4941
            interface = IF_FLOPPY;
4942
            max_devs = 0;
4943
        } else if (!strcmp(buf, "pflash")) {
4944
            interface = IF_PFLASH;
4945
            max_devs = 0;
4946
        } else if (!strcmp(buf, "mtd")) {
4947
            interface = IF_MTD;
4948
            max_devs = 0;
4949
        } else if (!strcmp(buf, "sd")) {
4950
            interface = IF_SD;
4951
            max_devs = 0;
4952
        } else {
4953
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
4954
            return -1;
4955
        }
4956
    }
4957

    
4958
    if (get_param_value(buf, sizeof(buf), "index", str)) {
4959
        index = strtol(buf, NULL, 0);
4960
        if (index < 0) {
4961
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
4962
            return -1;
4963
        }
4964
    }
4965

    
4966
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
4967
        cyls = strtol(buf, NULL, 0);
4968
    }
4969

    
4970
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
4971
        heads = strtol(buf, NULL, 0);
4972
    }
4973

    
4974
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
4975
        secs = strtol(buf, NULL, 0);
4976
    }
4977

    
4978
    if (cyls || heads || secs) {
4979
        if (cyls < 1 || cyls > 16383) {
4980
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
4981
            return -1;
4982
        }
4983
        if (heads < 1 || heads > 16) {
4984
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
4985
            return -1;
4986
        }
4987
        if (secs < 1 || secs > 63) {
4988
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
4989
            return -1;
4990
        }
4991
    }
4992

    
4993
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
4994
        if (!cyls) {
4995
            fprintf(stderr,
4996
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
4997
                    str);
4998
            return -1;
4999
        }
5000
        if (!strcmp(buf, "none"))
5001
            translation = BIOS_ATA_TRANSLATION_NONE;
5002
        else if (!strcmp(buf, "lba"))
5003
            translation = BIOS_ATA_TRANSLATION_LBA;
5004
        else if (!strcmp(buf, "auto"))
5005
            translation = BIOS_ATA_TRANSLATION_AUTO;
5006
        else {
5007
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5008
            return -1;
5009
        }
5010
    }
5011

    
5012
    if (get_param_value(buf, sizeof(buf), "media", str)) {
5013
        if (!strcmp(buf, "disk")) {
5014
            media = MEDIA_DISK;
5015
        } else if (!strcmp(buf, "cdrom")) {
5016
            if (cyls || secs || heads) {
5017
                fprintf(stderr,
5018
                        "qemu: '%s' invalid physical CHS format\n", str);
5019
                return -1;
5020
            }
5021
            media = MEDIA_CDROM;
5022
        } else {
5023
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
5024
            return -1;
5025
        }
5026
    }
5027

    
5028
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5029
        if (!strcmp(buf, "on"))
5030
            snapshot = 1;
5031
        else if (!strcmp(buf, "off"))
5032
            snapshot = 0;
5033
        else {
5034
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5035
            return -1;
5036
        }
5037
    }
5038

    
5039
    get_param_value(file, sizeof(file), "file", str);
5040

    
5041
    /* compute bus and unit according index */
5042

    
5043
    if (index != -1) {
5044
        if (bus_id != 0 || unit_id != -1) {
5045
            fprintf(stderr,
5046
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
5047
            return -1;
5048
        }
5049
        if (max_devs == 0)
5050
        {
5051
            unit_id = index;
5052
            bus_id = 0;
5053
        } else {
5054
            unit_id = index % max_devs;
5055
            bus_id = index / max_devs;
5056
        }
5057
    }
5058

    
5059
    /* if user doesn't specify a unit_id,
5060
     * try to find the first free
5061
     */
5062

    
5063
    if (unit_id == -1) {
5064
       unit_id = 0;
5065
       while (drive_get_index(interface, bus_id, unit_id) != -1) {
5066
           unit_id++;
5067
           if (max_devs && unit_id >= max_devs) {
5068
               unit_id -= max_devs;
5069
               bus_id++;
5070
           }
5071
       }
5072
    }
5073

    
5074
    /* check unit id */
5075

    
5076
    if (max_devs && unit_id >= max_devs) {
5077
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5078
                        str, unit_id, max_devs - 1);
5079
        return -1;
5080
    }
5081

    
5082
    /*
5083
     * ignore multiple definitions
5084
     */
5085

    
5086
    if (drive_get_index(interface, bus_id, unit_id) != -1)
5087
        return 0;
5088

    
5089
    /* init */
5090

    
5091
    if (interface == IF_IDE || interface == IF_SCSI)
5092
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5093
    snprintf(buf, sizeof(buf), max_devs ? "%1$s%4$i%2$s%3$i" : "%s%s%i",
5094
             devname, mediastr, unit_id, bus_id);
5095
    bdrv = bdrv_new(buf);
5096
    drives_table[nb_drives].bdrv = bdrv;
5097
    drives_table[nb_drives].interface = interface;
5098
    drives_table[nb_drives].bus = bus_id;
5099
    drives_table[nb_drives].unit = unit_id;
5100
    nb_drives++;
5101

    
5102
    switch(interface) {
5103
    case IF_IDE:
5104
    case IF_SCSI:
5105
        switch(media) {
5106
        case MEDIA_DISK:
5107
            if (cyls != 0) {
5108
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5109
                bdrv_set_translation_hint(bdrv, translation);
5110
            }
5111
            break;
5112
        case MEDIA_CDROM:
5113
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5114
            break;
5115
        }
5116
        break;
5117
    case IF_SD:
5118
        /* FIXME: This isn't really a floppy, but it's a reasonable
5119
           approximation.  */
5120
    case IF_FLOPPY:
5121
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5122
        break;
5123
    case IF_PFLASH:
5124
    case IF_MTD:
5125
        break;
5126
    }
5127
    if (!file[0])
5128
        return 0;
5129
    if (bdrv_open(bdrv, file, snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
5130
        qemu_key_check(bdrv, file)) {
5131
        fprintf(stderr, "qemu: could not open disk image %s\n",
5132
                        file);
5133
        return -1;
5134
    }
5135
    return 0;
5136
}
5137

    
5138
/***********************************************************/
5139
/* USB devices */
5140

    
5141
static USBPort *used_usb_ports;
5142
static USBPort *free_usb_ports;
5143

    
5144
/* ??? Maybe change this to register a hub to keep track of the topology.  */
5145
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5146
                            usb_attachfn attach)
5147
{
5148
    port->opaque = opaque;
5149
    port->index = index;
5150
    port->attach = attach;
5151
    port->next = free_usb_ports;
5152
    free_usb_ports = port;
5153
}
5154

    
5155
static int usb_device_add(const char *devname)
5156
{
5157
    const char *p;
5158
    USBDevice *dev;
5159
    USBPort *port;
5160

    
5161
    if (!free_usb_ports)
5162
        return -1;
5163

    
5164
    if (strstart(devname, "host:", &p)) {
5165
        dev = usb_host_device_open(p);
5166
    } else if (!strcmp(devname, "mouse")) {
5167
        dev = usb_mouse_init();
5168
    } else if (!strcmp(devname, "tablet")) {
5169
        dev = usb_tablet_init();
5170
    } else if (!strcmp(devname, "keyboard")) {
5171
        dev = usb_keyboard_init();
5172
    } else if (strstart(devname, "disk:", &p)) {
5173
        dev = usb_msd_init(p);
5174
    } else if (!strcmp(devname, "wacom-tablet")) {
5175
        dev = usb_wacom_init();
5176
    } else {
5177
        return -1;
5178
    }
5179
    if (!dev)
5180
        return -1;
5181

    
5182
    /* Find a USB port to add the device to.  */
5183
    port = free_usb_ports;
5184
    if (!port->next) {
5185
        USBDevice *hub;
5186

    
5187
        /* Create a new hub and chain it on.  */
5188
        free_usb_ports = NULL;
5189
        port->next = used_usb_ports;
5190
        used_usb_ports = port;
5191

    
5192
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5193
        usb_attach(port, hub);
5194
        port = free_usb_ports;
5195
    }
5196

    
5197
    free_usb_ports = port->next;
5198
    port->next = used_usb_ports;
5199
    used_usb_ports = port;
5200
    usb_attach(port, dev);
5201
    return 0;
5202
}
5203

    
5204
static int usb_device_del(const char *devname)
5205
{
5206
    USBPort *port;
5207
    USBPort **lastp;
5208
    USBDevice *dev;
5209
    int bus_num, addr;
5210
    const char *p;
5211

    
5212
    if (!used_usb_ports)
5213
        return -1;
5214

    
5215
    p = strchr(devname, '.');
5216
    if (!p)
5217
        return -1;
5218
    bus_num = strtoul(devname, NULL, 0);
5219
    addr = strtoul(p + 1, NULL, 0);
5220
    if (bus_num != 0)
5221
        return -1;
5222

    
5223
    lastp = &used_usb_ports;
5224
    port = used_usb_ports;
5225
    while (port && port->dev->addr != addr) {
5226
        lastp = &port->next;
5227
        port = port->next;
5228
    }
5229

    
5230
    if (!port)
5231
        return -1;
5232

    
5233
    dev = port->dev;
5234
    *lastp = port->next;
5235
    usb_attach(port, NULL);
5236
    dev->handle_destroy(dev);
5237
    port->next = free_usb_ports;
5238
    free_usb_ports = port;
5239
    return 0;
5240
}
5241

    
5242
void do_usb_add(const char *devname)
5243
{
5244
    int ret;
5245
    ret = usb_device_add(devname);
5246
    if (ret < 0)
5247
        term_printf("Could not add USB device '%s'\n", devname);
5248
}
5249

    
5250
void do_usb_del(const char *devname)
5251
{
5252
    int ret;
5253
    ret = usb_device_del(devname);
5254
    if (ret < 0)
5255
        term_printf("Could not remove USB device '%s'\n", devname);
5256
}
5257

    
5258
void usb_info(void)
5259
{
5260
    USBDevice *dev;
5261
    USBPort *port;
5262
    const char *speed_str;
5263

    
5264
    if (!usb_enabled) {
5265
        term_printf("USB support not enabled\n");
5266
        return;
5267
    }
5268

    
5269
    for (port = used_usb_ports; port; port = port->next) {
5270
        dev = port->dev;
5271
        if (!dev)
5272
            continue;
5273
        switch(dev->speed) {
5274
        case USB_SPEED_LOW:
5275
            speed_str = "1.5";
5276
            break;
5277
        case USB_SPEED_FULL:
5278
            speed_str = "12";
5279
            break;
5280
        case USB_SPEED_HIGH:
5281
            speed_str = "480";
5282
            break;
5283
        default:
5284
            speed_str = "?";
5285
            break;
5286
        }
5287
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
5288
                    0, dev->addr, speed_str, dev->devname);
5289
    }
5290
}
5291

    
5292
/***********************************************************/
5293
/* PCMCIA/Cardbus */
5294

    
5295
static struct pcmcia_socket_entry_s {
5296
    struct pcmcia_socket_s *socket;
5297
    struct pcmcia_socket_entry_s *next;
5298
} *pcmcia_sockets = 0;
5299

    
5300
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5301
{
5302
    struct pcmcia_socket_entry_s *entry;
5303

    
5304
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5305
    entry->socket = socket;
5306
    entry->next = pcmcia_sockets;
5307
    pcmcia_sockets = entry;
5308
}
5309

    
5310
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5311
{
5312
    struct pcmcia_socket_entry_s *entry, **ptr;
5313

    
5314
    ptr = &pcmcia_sockets;
5315
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5316
        if (entry->socket == socket) {
5317
            *ptr = entry->next;
5318
            qemu_free(entry);
5319
        }
5320
}
5321

    
5322
void pcmcia_info(void)
5323
{
5324
    struct pcmcia_socket_entry_s *iter;
5325
    if (!pcmcia_sockets)
5326
        term_printf("No PCMCIA sockets\n");
5327

    
5328
    for (iter = pcmcia_sockets; iter; iter = iter->next)
5329
        term_printf("%s: %s\n", iter->socket->slot_string,
5330
                    iter->socket->attached ? iter->socket->card_string :
5331
                    "Empty");
5332
}
5333

    
5334
/***********************************************************/
5335
/* dumb display */
5336

    
5337
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5338
{
5339
}
5340

    
5341
static void dumb_resize(DisplayState *ds, int w, int h)
5342
{
5343
}
5344

    
5345
static void dumb_refresh(DisplayState *ds)
5346
{
5347
#if defined(CONFIG_SDL)
5348
    vga_hw_update();
5349
#endif
5350
}
5351

    
5352
static void dumb_display_init(DisplayState *ds)
5353
{
5354
    ds->data = NULL;
5355
    ds->linesize = 0;
5356
    ds->depth = 0;
5357
    ds->dpy_update = dumb_update;
5358
    ds->dpy_resize = dumb_resize;
5359
    ds->dpy_refresh = dumb_refresh;
5360
}
5361

    
5362
/***********************************************************/
5363
/* I/O handling */
5364

    
5365
#define MAX_IO_HANDLERS 64
5366

    
5367
typedef struct IOHandlerRecord {
5368
    int fd;
5369
    IOCanRWHandler *fd_read_poll;
5370
    IOHandler *fd_read;
5371
    IOHandler *fd_write;
5372
    int deleted;
5373
    void *opaque;
5374
    /* temporary data */
5375
    struct pollfd *ufd;
5376
    struct IOHandlerRecord *next;
5377
} IOHandlerRecord;
5378

    
5379
static IOHandlerRecord *first_io_handler;
5380

    
5381
/* XXX: fd_read_poll should be suppressed, but an API change is
5382
   necessary in the character devices to suppress fd_can_read(). */
5383
int qemu_set_fd_handler2(int fd,
5384
                         IOCanRWHandler *fd_read_poll,
5385
                         IOHandler *fd_read,
5386
                         IOHandler *fd_write,
5387
                         void *opaque)
5388
{
5389
    IOHandlerRecord **pioh, *ioh;
5390

    
5391
    if (!fd_read && !fd_write) {
5392
        pioh = &first_io_handler;
5393
        for(;;) {
5394
            ioh = *pioh;
5395
            if (ioh == NULL)
5396
                break;
5397
            if (ioh->fd == fd) {
5398
                ioh->deleted = 1;
5399
                break;
5400
            }
5401
            pioh = &ioh->next;
5402
        }
5403
    } else {
5404
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5405
            if (ioh->fd == fd)
5406
                goto found;
5407
        }
5408
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5409
        if (!ioh)
5410
            return -1;
5411
        ioh->next = first_io_handler;
5412
        first_io_handler = ioh;
5413
    found:
5414
        ioh->fd = fd;
5415
        ioh->fd_read_poll = fd_read_poll;
5416
        ioh->fd_read = fd_read;
5417
        ioh->fd_write = fd_write;
5418
        ioh->opaque = opaque;
5419
        ioh->deleted = 0;
5420
    }
5421
    return 0;
5422
}
5423

    
5424
int qemu_set_fd_handler(int fd,
5425
                        IOHandler *fd_read,
5426
                        IOHandler *fd_write,
5427
                        void *opaque)
5428
{
5429
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5430
}
5431

    
5432
/***********************************************************/
5433
/* Polling handling */
5434

    
5435
typedef struct PollingEntry {
5436
    PollingFunc *func;
5437
    void *opaque;
5438
    struct PollingEntry *next;
5439
} PollingEntry;
5440

    
5441
static PollingEntry *first_polling_entry;
5442

    
5443
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5444
{
5445
    PollingEntry **ppe, *pe;
5446
    pe = qemu_mallocz(sizeof(PollingEntry));
5447
    if (!pe)
5448
        return -1;
5449
    pe->func = func;
5450
    pe->opaque = opaque;
5451
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5452
    *ppe = pe;
5453
    return 0;
5454
}
5455

    
5456
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5457
{
5458
    PollingEntry **ppe, *pe;
5459
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5460
        pe = *ppe;
5461
        if (pe->func == func && pe->opaque == opaque) {
5462
            *ppe = pe->next;
5463
            qemu_free(pe);
5464
            break;
5465
        }
5466
    }
5467
}
5468

    
5469
#ifdef _WIN32
5470
/***********************************************************/
5471
/* Wait objects support */
5472
typedef struct WaitObjects {
5473
    int num;
5474
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5475
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5476
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5477
} WaitObjects;
5478

    
5479
static WaitObjects wait_objects = {0};
5480

    
5481
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5482
{
5483
    WaitObjects *w = &wait_objects;
5484

    
5485
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
5486
        return -1;
5487
    w->events[w->num] = handle;
5488
    w->func[w->num] = func;
5489
    w->opaque[w->num] = opaque;
5490
    w->num++;
5491
    return 0;
5492
}
5493

    
5494
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5495
{
5496
    int i, found;
5497
    WaitObjects *w = &wait_objects;
5498

    
5499
    found = 0;
5500
    for (i = 0; i < w->num; i++) {
5501
        if (w->events[i] == handle)
5502
            found = 1;
5503
        if (found) {
5504
            w->events[i] = w->events[i + 1];
5505
            w->func[i] = w->func[i + 1];
5506
            w->opaque[i] = w->opaque[i + 1];
5507
        }
5508
    }
5509
    if (found)
5510
        w->num--;
5511
}
5512
#endif
5513

    
5514
/***********************************************************/
5515
/* savevm/loadvm support */
5516

    
5517
#define IO_BUF_SIZE 32768
5518

    
5519
struct QEMUFile {
5520
    FILE *outfile;
5521
    BlockDriverState *bs;
5522
    int is_file;
5523
    int is_writable;
5524
    int64_t base_offset;
5525
    int64_t buf_offset; /* start of buffer when writing, end of buffer
5526
                           when reading */
5527
    int buf_index;
5528
    int buf_size; /* 0 when writing */
5529
    uint8_t buf[IO_BUF_SIZE];
5530
};
5531

    
5532
QEMUFile *qemu_fopen(const char *filename, const char *mode)
5533
{
5534
    QEMUFile *f;
5535

    
5536
    f = qemu_mallocz(sizeof(QEMUFile));
5537
    if (!f)
5538
        return NULL;
5539
    if (!strcmp(mode, "wb")) {
5540
        f->is_writable = 1;
5541
    } else if (!strcmp(mode, "rb")) {
5542
        f->is_writable = 0;
5543
    } else {
5544
        goto fail;
5545
    }
5546
    f->outfile = fopen(filename, mode);
5547
    if (!f->outfile)
5548
        goto fail;
5549
    f->is_file = 1;
5550
    return f;
5551
 fail:
5552
    if (f->outfile)
5553
        fclose(f->outfile);
5554
    qemu_free(f);
5555
    return NULL;
5556
}
5557

    
5558
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5559
{
5560
    QEMUFile *f;
5561

    
5562
    f = qemu_mallocz(sizeof(QEMUFile));
5563
    if (!f)
5564
        return NULL;
5565
    f->is_file = 0;
5566
    f->bs = bs;
5567
    f->is_writable = is_writable;
5568
    f->base_offset = offset;
5569
    return f;
5570
}
5571

    
5572
void qemu_fflush(QEMUFile *f)
5573
{
5574
    if (!f->is_writable)
5575
        return;
5576
    if (f->buf_index > 0) {
5577
        if (f->is_file) {
5578
            fseek(f->outfile, f->buf_offset, SEEK_SET);
5579
            fwrite(f->buf, 1, f->buf_index, f->outfile);
5580
        } else {
5581
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5582
                        f->buf, f->buf_index);
5583
        }
5584
        f->buf_offset += f->buf_index;
5585
        f->buf_index = 0;
5586
    }
5587
}
5588

    
5589
static void qemu_fill_buffer(QEMUFile *f)
5590
{
5591
    int len;
5592

    
5593
    if (f->is_writable)
5594
        return;
5595
    if (f->is_file) {
5596
        fseek(f->outfile, f->buf_offset, SEEK_SET);
5597
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5598
        if (len < 0)
5599
            len = 0;
5600
    } else {
5601
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5602
                         f->buf, IO_BUF_SIZE);
5603
        if (len < 0)
5604
            len = 0;
5605
    }
5606
    f->buf_index = 0;
5607
    f->buf_size = len;
5608
    f->buf_offset += len;
5609
}
5610

    
5611
void qemu_fclose(QEMUFile *f)
5612
{
5613
    if (f->is_writable)
5614
        qemu_fflush(f);
5615
    if (f->is_file) {
5616
        fclose(f->outfile);
5617
    }
5618
    qemu_free(f);
5619
}
5620

    
5621
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5622
{
5623
    int l;
5624
    while (size > 0) {
5625
        l = IO_BUF_SIZE - f->buf_index;
5626
        if (l > size)
5627
            l = size;
5628
        memcpy(f->buf + f->buf_index, buf, l);
5629
        f->buf_index += l;
5630
        buf += l;
5631
        size -= l;
5632
        if (f->buf_index >= IO_BUF_SIZE)
5633
            qemu_fflush(f);
5634
    }
5635
}
5636

    
5637
void qemu_put_byte(QEMUFile *f, int v)
5638
{
5639
    f->buf[f->buf_index++] = v;
5640
    if (f->buf_index >= IO_BUF_SIZE)
5641
        qemu_fflush(f);
5642
}
5643

    
5644
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5645
{
5646
    int size, l;
5647

    
5648
    size = size1;
5649
    while (size > 0) {
5650
        l = f->buf_size - f->buf_index;
5651
        if (l == 0) {
5652
            qemu_fill_buffer(f);
5653
            l = f->buf_size - f->buf_index;
5654
            if (l == 0)
5655
                break;
5656
        }
5657
        if (l > size)
5658
            l = size;
5659
        memcpy(buf, f->buf + f->buf_index, l);
5660
        f->buf_index += l;
5661
        buf += l;
5662
        size -= l;
5663
    }
5664
    return size1 - size;
5665
}
5666

    
5667
int qemu_get_byte(QEMUFile *f)
5668
{
5669
    if (f->buf_index >= f->buf_size) {
5670
        qemu_fill_buffer(f);
5671
        if (f->buf_index >= f->buf_size)
5672
            return 0;
5673
    }
5674
    return f->buf[f->buf_index++];
5675
}
5676

    
5677
int64_t qemu_ftell(QEMUFile *f)
5678
{
5679
    return f->buf_offset - f->buf_size + f->buf_index;
5680
}
5681

    
5682
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5683
{
5684
    if (whence == SEEK_SET) {
5685
        /* nothing to do */
5686
    } else if (whence == SEEK_CUR) {
5687
        pos += qemu_ftell(f);
5688
    } else {
5689
        /* SEEK_END not supported */
5690
        return -1;
5691
    }
5692
    if (f->is_writable) {
5693
        qemu_fflush(f);
5694
        f->buf_offset = pos;
5695
    } else {
5696
        f->buf_offset = pos;
5697
        f->buf_index = 0;
5698
        f->buf_size = 0;
5699
    }
5700
    return pos;
5701
}
5702

    
5703
void qemu_put_be16(QEMUFile *f, unsigned int v)
5704
{
5705
    qemu_put_byte(f, v >> 8);
5706
    qemu_put_byte(f, v);
5707
}
5708

    
5709
void qemu_put_be32(QEMUFile *f, unsigned int v)
5710
{
5711
    qemu_put_byte(f, v >> 24);
5712
    qemu_put_byte(f, v >> 16);
5713
    qemu_put_byte(f, v >> 8);
5714
    qemu_put_byte(f, v);
5715
}
5716

    
5717
void qemu_put_be64(QEMUFile *f, uint64_t v)
5718
{
5719
    qemu_put_be32(f, v >> 32);
5720
    qemu_put_be32(f, v);
5721
}
5722

    
5723
unsigned int qemu_get_be16(QEMUFile *f)
5724
{
5725
    unsigned int v;
5726
    v = qemu_get_byte(f) << 8;
5727
    v |= qemu_get_byte(f);
5728
    return v;
5729
}
5730

    
5731
unsigned int qemu_get_be32(QEMUFile *f)
5732
{
5733
    unsigned int v;
5734
    v = qemu_get_byte(f) << 24;
5735
    v |= qemu_get_byte(f) << 16;
5736
    v |= qemu_get_byte(f) << 8;
5737
    v |= qemu_get_byte(f);
5738
    return v;
5739
}
5740

    
5741
uint64_t qemu_get_be64(QEMUFile *f)
5742
{
5743
    uint64_t v;
5744
    v = (uint64_t)qemu_get_be32(f) << 32;
5745
    v |= qemu_get_be32(f);
5746
    return v;
5747
}
5748

    
5749
typedef struct SaveStateEntry {
5750
    char idstr[256];
5751
    int instance_id;
5752
    int version_id;
5753
    SaveStateHandler *save_state;
5754
    LoadStateHandler *load_state;
5755
    void *opaque;
5756
    struct SaveStateEntry *next;
5757
} SaveStateEntry;
5758

    
5759
static SaveStateEntry *first_se;
5760

    
5761
int register_savevm(const char *idstr,
5762
                    int instance_id,
5763
                    int version_id,
5764
                    SaveStateHandler *save_state,
5765
                    LoadStateHandler *load_state,
5766
                    void *opaque)
5767
{
5768
    SaveStateEntry *se, **pse;
5769

    
5770
    se = qemu_malloc(sizeof(SaveStateEntry));
5771
    if (!se)
5772
        return -1;
5773
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5774
    se->instance_id = instance_id;
5775
    se->version_id = version_id;
5776
    se->save_state = save_state;
5777
    se->load_state = load_state;
5778
    se->opaque = opaque;
5779
    se->next = NULL;
5780

    
5781
    /* add at the end of list */
5782
    pse = &first_se;
5783
    while (*pse != NULL)
5784
        pse = &(*pse)->next;
5785
    *pse = se;
5786
    return 0;
5787
}
5788

    
5789
#define QEMU_VM_FILE_MAGIC   0x5145564d
5790
#define QEMU_VM_FILE_VERSION 0x00000002
5791

    
5792
static int qemu_savevm_state(QEMUFile *f)
5793
{
5794
    SaveStateEntry *se;
5795
    int len, ret;
5796
    int64_t cur_pos, len_pos, total_len_pos;
5797

    
5798
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5799
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5800
    total_len_pos = qemu_ftell(f);
5801
    qemu_put_be64(f, 0); /* total size */
5802

    
5803
    for(se = first_se; se != NULL; se = se->next) {
5804
        /* ID string */
5805
        len = strlen(se->idstr);
5806
        qemu_put_byte(f, len);
5807
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5808

    
5809
        qemu_put_be32(f, se->instance_id);
5810
        qemu_put_be32(f, se->version_id);
5811

    
5812
        /* record size: filled later */
5813
        len_pos = qemu_ftell(f);
5814
        qemu_put_be32(f, 0);
5815
        se->save_state(f, se->opaque);
5816

    
5817
        /* fill record size */
5818
        cur_pos = qemu_ftell(f);
5819
        len = cur_pos - len_pos - 4;
5820
        qemu_fseek(f, len_pos, SEEK_SET);
5821
        qemu_put_be32(f, len);
5822
        qemu_fseek(f, cur_pos, SEEK_SET);
5823
    }
5824
    cur_pos = qemu_ftell(f);
5825
    qemu_fseek(f, total_len_pos, SEEK_SET);
5826
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
5827
    qemu_fseek(f, cur_pos, SEEK_SET);
5828

    
5829
    ret = 0;
5830
    return ret;
5831
}
5832

    
5833
static SaveStateEntry *find_se(const char *idstr, int instance_id)
5834
{
5835
    SaveStateEntry *se;
5836

    
5837
    for(se = first_se; se != NULL; se = se->next) {
5838
        if (!strcmp(se->idstr, idstr) &&
5839
            instance_id == se->instance_id)
5840
            return se;
5841
    }
5842
    return NULL;
5843
}
5844

    
5845
static int qemu_loadvm_state(QEMUFile *f)
5846
{
5847
    SaveStateEntry *se;
5848
    int len, ret, instance_id, record_len, version_id;
5849
    int64_t total_len, end_pos, cur_pos;
5850
    unsigned int v;
5851
    char idstr[256];
5852

    
5853
    v = qemu_get_be32(f);
5854
    if (v != QEMU_VM_FILE_MAGIC)
5855
        goto fail;
5856
    v = qemu_get_be32(f);
5857
    if (v != QEMU_VM_FILE_VERSION) {
5858
    fail:
5859
        ret = -1;
5860
        goto the_end;
5861
    }
5862
    total_len = qemu_get_be64(f);
5863
    end_pos = total_len + qemu_ftell(f);
5864
    for(;;) {
5865
        if (qemu_ftell(f) >= end_pos)
5866
            break;
5867
        len = qemu_get_byte(f);
5868
        qemu_get_buffer(f, (uint8_t *)idstr, len);
5869
        idstr[len] = '\0';
5870
        instance_id = qemu_get_be32(f);
5871
        version_id = qemu_get_be32(f);
5872
        record_len = qemu_get_be32(f);
5873
#if 0
5874
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
5875
               idstr, instance_id, version_id, record_len);
5876
#endif
5877
        cur_pos = qemu_ftell(f);
5878
        se = find_se(idstr, instance_id);
5879
        if (!se) {
5880
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5881
                    instance_id, idstr);
5882
        } else {
5883
            ret = se->load_state(f, se->opaque, version_id);
5884
            if (ret < 0) {
5885
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5886
                        instance_id, idstr);
5887
            }
5888
        }
5889
        /* always seek to exact end of record */
5890
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5891
    }
5892
    ret = 0;
5893
 the_end:
5894
    return ret;
5895
}
5896

    
5897
/* device can contain snapshots */
5898
static int bdrv_can_snapshot(BlockDriverState *bs)
5899
{
5900
    return (bs &&
5901
            !bdrv_is_removable(bs) &&
5902
            !bdrv_is_read_only(bs));
5903
}
5904

    
5905
/* device must be snapshots in order to have a reliable snapshot */
5906
static int bdrv_has_snapshot(BlockDriverState *bs)
5907
{
5908
    return (bs &&
5909
            !bdrv_is_removable(bs) &&
5910
            !bdrv_is_read_only(bs));
5911
}
5912

    
5913
static BlockDriverState *get_bs_snapshots(void)
5914
{
5915
    BlockDriverState *bs;
5916
    int i;
5917

    
5918
    if (bs_snapshots)
5919
        return bs_snapshots;
5920
    for(i = 0; i <= nb_drives; i++) {
5921
        bs = drives_table[i].bdrv;
5922
        if (bdrv_can_snapshot(bs))
5923
            goto ok;
5924
    }
5925
    return NULL;
5926
 ok:
5927
    bs_snapshots = bs;
5928
    return bs;
5929
}
5930

    
5931
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5932
                              const char *name)
5933
{
5934
    QEMUSnapshotInfo *sn_tab, *sn;
5935
    int nb_sns, i, ret;
5936

    
5937
    ret = -ENOENT;
5938
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5939
    if (nb_sns < 0)
5940
        return ret;
5941
    for(i = 0; i < nb_sns; i++) {
5942
        sn = &sn_tab[i];
5943
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5944
            *sn_info = *sn;
5945
            ret = 0;
5946
            break;
5947
        }
5948
    }
5949
    qemu_free(sn_tab);
5950
    return ret;
5951
}
5952

    
5953
void do_savevm(const char *name)
5954
{
5955
    BlockDriverState *bs, *bs1;
5956
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5957
    int must_delete, ret, i;
5958
    BlockDriverInfo bdi1, *bdi = &bdi1;
5959
    QEMUFile *f;
5960
    int saved_vm_running;
5961
#ifdef _WIN32
5962
    struct _timeb tb;
5963
#else
5964
    struct timeval tv;
5965
#endif
5966

    
5967
    bs = get_bs_snapshots();
5968
    if (!bs) {
5969
        term_printf("No block device can accept snapshots\n");
5970
        return;
5971
    }
5972

    
5973
    /* ??? Should this occur after vm_stop?  */
5974
    qemu_aio_flush();
5975

    
5976
    saved_vm_running = vm_running;
5977
    vm_stop(0);
5978

    
5979
    must_delete = 0;
5980
    if (name) {
5981
        ret = bdrv_snapshot_find(bs, old_sn, name);
5982
        if (ret >= 0) {
5983
            must_delete = 1;
5984
        }
5985
    }
5986
    memset(sn, 0, sizeof(*sn));
5987
    if (must_delete) {
5988
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5989
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5990
    } else {
5991
        if (name)
5992
            pstrcpy(sn->name, sizeof(sn->name), name);
5993
    }
5994

    
5995
    /* fill auxiliary fields */
5996
#ifdef _WIN32
5997
    _ftime(&tb);
5998
    sn->date_sec = tb.time;
5999
    sn->date_nsec = tb.millitm * 1000000;
6000
#else
6001
    gettimeofday(&tv, NULL);
6002
    sn->date_sec = tv.tv_sec;
6003
    sn->date_nsec = tv.tv_usec * 1000;
6004
#endif
6005
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6006

    
6007
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6008
        term_printf("Device %s does not support VM state snapshots\n",
6009
                    bdrv_get_device_name(bs));
6010
        goto the_end;
6011
    }
6012

    
6013
    /* save the VM state */
6014
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6015
    if (!f) {
6016
        term_printf("Could not open VM state file\n");
6017
        goto the_end;
6018
    }
6019
    ret = qemu_savevm_state(f);
6020
    sn->vm_state_size = qemu_ftell(f);
6021
    qemu_fclose(f);
6022
    if (ret < 0) {
6023
        term_printf("Error %d while writing VM\n", ret);
6024
        goto the_end;
6025
    }
6026

    
6027
    /* create the snapshots */
6028

    
6029
    for(i = 0; i < nb_drives; i++) {
6030
        bs1 = drives_table[i].bdrv;
6031
        if (bdrv_has_snapshot(bs1)) {
6032
            if (must_delete) {
6033
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6034
                if (ret < 0) {
6035
                    term_printf("Error while deleting snapshot on '%s'\n",
6036
                                bdrv_get_device_name(bs1));
6037
                }
6038
            }
6039
            ret = bdrv_snapshot_create(bs1, sn);
6040
            if (ret < 0) {
6041
                term_printf("Error while creating snapshot on '%s'\n",
6042
                            bdrv_get_device_name(bs1));
6043
            }
6044
        }
6045
    }
6046

    
6047
 the_end:
6048
    if (saved_vm_running)
6049
        vm_start();
6050
}
6051

    
6052
void do_loadvm(const char *name)
6053
{
6054
    BlockDriverState *bs, *bs1;
6055
    BlockDriverInfo bdi1, *bdi = &bdi1;
6056
    QEMUFile *f;
6057
    int i, ret;
6058
    int saved_vm_running;
6059

    
6060
    bs = get_bs_snapshots();
6061
    if (!bs) {
6062
        term_printf("No block device supports snapshots\n");
6063
        return;
6064
    }
6065

    
6066
    /* Flush all IO requests so they don't interfere with the new state.  */
6067
    qemu_aio_flush();
6068

    
6069
    saved_vm_running = vm_running;
6070
    vm_stop(0);
6071

    
6072
    for(i = 0; i <= nb_drives; i++) {
6073
        bs1 = drives_table[i].bdrv;
6074
        if (bdrv_has_snapshot(bs1)) {
6075
            ret = bdrv_snapshot_goto(bs1, name);
6076
            if (ret < 0) {
6077
                if (bs != bs1)
6078
                    term_printf("Warning: ");
6079
                switch(ret) {
6080
                case -ENOTSUP:
6081
                    term_printf("Snapshots not supported on device '%s'\n",
6082
                                bdrv_get_device_name(bs1));
6083
                    break;
6084
                case -ENOENT:
6085
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
6086
                                name, bdrv_get_device_name(bs1));
6087
                    break;
6088
                default:
6089
                    term_printf("Error %d while activating snapshot on '%s'\n",
6090
                                ret, bdrv_get_device_name(bs1));
6091
                    break;
6092
                }
6093
                /* fatal on snapshot block device */
6094
                if (bs == bs1)
6095
                    goto the_end;
6096
            }
6097
        }
6098
    }
6099

    
6100
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6101
        term_printf("Device %s does not support VM state snapshots\n",
6102
                    bdrv_get_device_name(bs));
6103
        return;
6104
    }
6105

    
6106
    /* restore the VM state */
6107
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6108
    if (!f) {
6109
        term_printf("Could not open VM state file\n");
6110
        goto the_end;
6111
    }
6112
    ret = qemu_loadvm_state(f);
6113
    qemu_fclose(f);
6114
    if (ret < 0) {
6115
        term_printf("Error %d while loading VM state\n", ret);
6116
    }
6117
 the_end:
6118
    if (saved_vm_running)
6119
        vm_start();
6120
}
6121

    
6122
void do_delvm(const char *name)
6123
{
6124
    BlockDriverState *bs, *bs1;
6125
    int i, ret;
6126

    
6127
    bs = get_bs_snapshots();
6128
    if (!bs) {
6129
        term_printf("No block device supports snapshots\n");
6130
        return;
6131
    }
6132

    
6133
    for(i = 0; i <= nb_drives; i++) {
6134
        bs1 = drives_table[i].bdrv;
6135
        if (bdrv_has_snapshot(bs1)) {
6136
            ret = bdrv_snapshot_delete(bs1, name);
6137
            if (ret < 0) {
6138
                if (ret == -ENOTSUP)
6139
                    term_printf("Snapshots not supported on device '%s'\n",
6140
                                bdrv_get_device_name(bs1));
6141
                else
6142
                    term_printf("Error %d while deleting snapshot on '%s'\n",
6143
                                ret, bdrv_get_device_name(bs1));
6144
            }
6145
        }
6146
    }
6147
}
6148

    
6149
void do_info_snapshots(void)
6150
{
6151
    BlockDriverState *bs, *bs1;
6152
    QEMUSnapshotInfo *sn_tab, *sn;
6153
    int nb_sns, i;
6154
    char buf[256];
6155

    
6156
    bs = get_bs_snapshots();
6157
    if (!bs) {
6158
        term_printf("No available block device supports snapshots\n");
6159
        return;
6160
    }
6161
    term_printf("Snapshot devices:");
6162
    for(i = 0; i <= nb_drives; i++) {
6163
        bs1 = drives_table[i].bdrv;
6164
        if (bdrv_has_snapshot(bs1)) {
6165
            if (bs == bs1)
6166
                term_printf(" %s", bdrv_get_device_name(bs1));
6167
        }
6168
    }
6169
    term_printf("\n");
6170

    
6171
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6172
    if (nb_sns < 0) {
6173
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6174
        return;
6175
    }
6176
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6177
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6178
    for(i = 0; i < nb_sns; i++) {
6179
        sn = &sn_tab[i];
6180
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6181
    }
6182
    qemu_free(sn_tab);
6183
}
6184

    
6185
/***********************************************************/
6186
/* cpu save/restore */
6187

    
6188
#if defined(TARGET_I386)
6189

    
6190
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6191
{
6192
    qemu_put_be32(f, dt->selector);
6193
    qemu_put_betl(f, dt->base);
6194
    qemu_put_be32(f, dt->limit);
6195
    qemu_put_be32(f, dt->flags);
6196
}
6197

    
6198
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6199
{
6200
    dt->selector = qemu_get_be32(f);
6201
    dt->base = qemu_get_betl(f);
6202
    dt->limit = qemu_get_be32(f);
6203
    dt->flags = qemu_get_be32(f);
6204
}
6205

    
6206
void cpu_save(QEMUFile *f, void *opaque)
6207
{
6208
    CPUState *env = opaque;
6209
    uint16_t fptag, fpus, fpuc, fpregs_format;
6210
    uint32_t hflags;
6211
    int i;
6212

    
6213
    for(i = 0; i < CPU_NB_REGS; i++)
6214
        qemu_put_betls(f, &env->regs[i]);
6215
    qemu_put_betls(f, &env->eip);
6216
    qemu_put_betls(f, &env->eflags);
6217
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6218
    qemu_put_be32s(f, &hflags);
6219

    
6220
    /* FPU */
6221
    fpuc = env->fpuc;
6222
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6223
    fptag = 0;
6224
    for(i = 0; i < 8; i++) {
6225
        fptag |= ((!env->fptags[i]) << i);
6226
    }
6227

    
6228
    qemu_put_be16s(f, &fpuc);
6229
    qemu_put_be16s(f, &fpus);
6230
    qemu_put_be16s(f, &fptag);
6231

    
6232
#ifdef USE_X86LDOUBLE
6233
    fpregs_format = 0;
6234
#else
6235
    fpregs_format = 1;
6236
#endif
6237
    qemu_put_be16s(f, &fpregs_format);
6238

    
6239
    for(i = 0; i < 8; i++) {
6240
#ifdef USE_X86LDOUBLE
6241
        {
6242
            uint64_t mant;
6243
            uint16_t exp;
6244
            /* we save the real CPU data (in case of MMX usage only 'mant'
6245
               contains the MMX register */
6246
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6247
            qemu_put_be64(f, mant);
6248
            qemu_put_be16(f, exp);
6249
        }
6250
#else
6251
        /* if we use doubles for float emulation, we save the doubles to
6252
           avoid losing information in case of MMX usage. It can give
6253
           problems if the image is restored on a CPU where long
6254
           doubles are used instead. */
6255
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6256
#endif
6257
    }
6258

    
6259
    for(i = 0; i < 6; i++)
6260
        cpu_put_seg(f, &env->segs[i]);
6261
    cpu_put_seg(f, &env->ldt);
6262
    cpu_put_seg(f, &env->tr);
6263
    cpu_put_seg(f, &env->gdt);
6264
    cpu_put_seg(f, &env->idt);
6265

    
6266
    qemu_put_be32s(f, &env->sysenter_cs);
6267
    qemu_put_be32s(f, &env->sysenter_esp);
6268
    qemu_put_be32s(f, &env->sysenter_eip);
6269

    
6270
    qemu_put_betls(f, &env->cr[0]);
6271
    qemu_put_betls(f, &env->cr[2]);
6272
    qemu_put_betls(f, &env->cr[3]);
6273
    qemu_put_betls(f, &env->cr[4]);
6274

    
6275
    for(i = 0; i < 8; i++)
6276
        qemu_put_betls(f, &env->dr[i]);
6277

    
6278
    /* MMU */
6279
    qemu_put_be32s(f, &env->a20_mask);
6280

    
6281
    /* XMM */
6282
    qemu_put_be32s(f, &env->mxcsr);
6283
    for(i = 0; i < CPU_NB_REGS; i++) {
6284
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6285
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6286
    }
6287

    
6288
#ifdef TARGET_X86_64
6289
    qemu_put_be64s(f, &env->efer);
6290
    qemu_put_be64s(f, &env->star);
6291
    qemu_put_be64s(f, &env->lstar);
6292
    qemu_put_be64s(f, &env->cstar);
6293
    qemu_put_be64s(f, &env->fmask);
6294
    qemu_put_be64s(f, &env->kernelgsbase);
6295
#endif
6296
    qemu_put_be32s(f, &env->smbase);
6297
}
6298

    
6299
#ifdef USE_X86LDOUBLE
6300
/* XXX: add that in a FPU generic layer */
6301
union x86_longdouble {
6302
    uint64_t mant;
6303
    uint16_t exp;
6304
};
6305

    
6306
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
6307
#define EXPBIAS1 1023
6308
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
6309
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
6310

    
6311
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6312
{
6313
    int e;
6314
    /* mantissa */
6315
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6316
    /* exponent + sign */
6317
    e = EXPD1(temp) - EXPBIAS1 + 16383;
6318
    e |= SIGND1(temp) >> 16;
6319
    p->exp = e;
6320
}
6321
#endif
6322

    
6323
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6324
{
6325
    CPUState *env = opaque;
6326
    int i, guess_mmx;
6327
    uint32_t hflags;
6328
    uint16_t fpus, fpuc, fptag, fpregs_format;
6329

    
6330
    if (version_id != 3 && version_id != 4)
6331
        return -EINVAL;
6332
    for(i = 0; i < CPU_NB_REGS; i++)
6333
        qemu_get_betls(f, &env->regs[i]);
6334
    qemu_get_betls(f, &env->eip);
6335
    qemu_get_betls(f, &env->eflags);
6336
    qemu_get_be32s(f, &hflags);
6337

    
6338
    qemu_get_be16s(f, &fpuc);
6339
    qemu_get_be16s(f, &fpus);
6340
    qemu_get_be16s(f, &fptag);
6341
    qemu_get_be16s(f, &fpregs_format);
6342

    
6343
    /* NOTE: we cannot always restore the FPU state if the image come
6344
       from a host with a different 'USE_X86LDOUBLE' define. We guess
6345
       if we are in an MMX state to restore correctly in that case. */
6346
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6347
    for(i = 0; i < 8; i++) {
6348
        uint64_t mant;
6349
        uint16_t exp;
6350

    
6351
        switch(fpregs_format) {
6352
        case 0:
6353
            mant = qemu_get_be64(f);
6354
            exp = qemu_get_be16(f);
6355
#ifdef USE_X86LDOUBLE
6356
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
6357
#else
6358
            /* difficult case */
6359
            if (guess_mmx)
6360
                env->fpregs[i].mmx.MMX_Q(0) = mant;
6361
            else
6362
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
6363
#endif
6364
            break;
6365
        case 1:
6366
            mant = qemu_get_be64(f);
6367
#ifdef USE_X86LDOUBLE
6368
            {
6369
                union x86_longdouble *p;
6370
                /* difficult case */
6371
                p = (void *)&env->fpregs[i];
6372
                if (guess_mmx) {
6373
                    p->mant = mant;
6374
                    p->exp = 0xffff;
6375
                } else {
6376
                    fp64_to_fp80(p, mant);
6377
                }
6378
            }
6379
#else
6380
            env->fpregs[i].mmx.MMX_Q(0) = mant;
6381
#endif
6382
            break;
6383
        default:
6384
            return -EINVAL;
6385
        }
6386
    }
6387

    
6388
    env->fpuc = fpuc;
6389
    /* XXX: restore FPU round state */
6390
    env->fpstt = (fpus >> 11) & 7;
6391
    env->fpus = fpus & ~0x3800;
6392
    fptag ^= 0xff;
6393
    for(i = 0; i < 8; i++) {
6394
        env->fptags[i] = (fptag >> i) & 1;
6395
    }
6396

    
6397
    for(i = 0; i < 6; i++)
6398
        cpu_get_seg(f, &env->segs[i]);
6399
    cpu_get_seg(f, &env->ldt);
6400
    cpu_get_seg(f, &env->tr);
6401
    cpu_get_seg(f, &env->gdt);
6402
    cpu_get_seg(f, &env->idt);
6403

    
6404
    qemu_get_be32s(f, &env->sysenter_cs);
6405
    qemu_get_be32s(f, &env->sysenter_esp);
6406
    qemu_get_be32s(f, &env->sysenter_eip);
6407

    
6408
    qemu_get_betls(f, &env->cr[0]);
6409
    qemu_get_betls(f, &env->cr[2]);
6410
    qemu_get_betls(f, &env->cr[3]);
6411
    qemu_get_betls(f, &env->cr[4]);
6412

    
6413
    for(i = 0; i < 8; i++)
6414
        qemu_get_betls(f, &env->dr[i]);
6415

    
6416
    /* MMU */
6417
    qemu_get_be32s(f, &env->a20_mask);
6418

    
6419
    qemu_get_be32s(f, &env->mxcsr);
6420
    for(i = 0; i < CPU_NB_REGS; i++) {
6421
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6422
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6423
    }
6424

    
6425
#ifdef TARGET_X86_64
6426
    qemu_get_be64s(f, &env->efer);
6427
    qemu_get_be64s(f, &env->star);
6428
    qemu_get_be64s(f, &env->lstar);
6429
    qemu_get_be64s(f, &env->cstar);
6430
    qemu_get_be64s(f, &env->fmask);
6431
    qemu_get_be64s(f, &env->kernelgsbase);
6432
#endif
6433
    if (version_id >= 4)
6434
        qemu_get_be32s(f, &env->smbase);
6435

    
6436
    /* XXX: compute hflags from scratch, except for CPL and IIF */
6437
    env->hflags = hflags;
6438
    tlb_flush(env, 1);
6439
    return 0;
6440
}
6441

    
6442
#elif defined(TARGET_PPC)
6443
void cpu_save(QEMUFile *f, void *opaque)
6444
{
6445
}
6446

    
6447
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6448
{
6449
    return 0;
6450
}
6451

    
6452
#elif defined(TARGET_MIPS)
6453
void cpu_save(QEMUFile *f, void *opaque)
6454
{
6455
}
6456

    
6457
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6458
{
6459
    return 0;
6460
}
6461

    
6462
#elif defined(TARGET_SPARC)
6463
void cpu_save(QEMUFile *f, void *opaque)
6464
{
6465
    CPUState *env = opaque;
6466
    int i;
6467
    uint32_t tmp;
6468

    
6469
    for(i = 0; i < 8; i++)
6470
        qemu_put_betls(f, &env->gregs[i]);
6471
    for(i = 0; i < NWINDOWS * 16; i++)
6472
        qemu_put_betls(f, &env->regbase[i]);
6473

    
6474
    /* FPU */
6475
    for(i = 0; i < TARGET_FPREGS; i++) {
6476
        union {
6477
            float32 f;
6478
            uint32_t i;
6479
        } u;
6480
        u.f = env->fpr[i];
6481
        qemu_put_be32(f, u.i);
6482
    }
6483

    
6484
    qemu_put_betls(f, &env->pc);
6485
    qemu_put_betls(f, &env->npc);
6486
    qemu_put_betls(f, &env->y);
6487
    tmp = GET_PSR(env);
6488
    qemu_put_be32(f, tmp);
6489
    qemu_put_betls(f, &env->fsr);
6490
    qemu_put_betls(f, &env->tbr);
6491
#ifndef TARGET_SPARC64
6492
    qemu_put_be32s(f, &env->wim);
6493
    /* MMU */
6494
    for(i = 0; i < 16; i++)
6495
        qemu_put_be32s(f, &env->mmuregs[i]);
6496
#endif
6497
}
6498

    
6499
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6500
{
6501
    CPUState *env = opaque;
6502
    int i;
6503
    uint32_t tmp;
6504

    
6505
    for(i = 0; i < 8; i++)
6506
        qemu_get_betls(f, &env->gregs[i]);
6507
    for(i = 0; i < NWINDOWS * 16; i++)
6508
        qemu_get_betls(f, &env->regbase[i]);
6509

    
6510
    /* FPU */
6511
    for(i = 0; i < TARGET_FPREGS; i++) {
6512
        union {
6513
            float32 f;
6514
            uint32_t i;
6515
        } u;
6516
        u.i = qemu_get_be32(f);
6517
        env->fpr[i] = u.f;
6518
    }
6519

    
6520
    qemu_get_betls(f, &env->pc);
6521
    qemu_get_betls(f, &env->npc);
6522
    qemu_get_betls(f, &env->y);
6523
    tmp = qemu_get_be32(f);
6524
    env->cwp = 0; /* needed to ensure that the wrapping registers are
6525
                     correctly updated */
6526
    PUT_PSR(env, tmp);
6527
    qemu_get_betls(f, &env->fsr);
6528
    qemu_get_betls(f, &env->tbr);
6529
#ifndef TARGET_SPARC64
6530
    qemu_get_be32s(f, &env->wim);
6531
    /* MMU */
6532
    for(i = 0; i < 16; i++)
6533
        qemu_get_be32s(f, &env->mmuregs[i]);
6534
#endif
6535
    tlb_flush(env, 1);
6536
    return 0;
6537
}
6538

    
6539
#elif defined(TARGET_ARM)
6540

    
6541
void cpu_save(QEMUFile *f, void *opaque)
6542
{
6543
    int i;
6544
    CPUARMState *env = (CPUARMState *)opaque;
6545

    
6546
    for (i = 0; i < 16; i++) {
6547
        qemu_put_be32(f, env->regs[i]);
6548
    }
6549
    qemu_put_be32(f, cpsr_read(env));
6550
    qemu_put_be32(f, env->spsr);
6551
    for (i = 0; i < 6; i++) {
6552
        qemu_put_be32(f, env->banked_spsr[i]);
6553
        qemu_put_be32(f, env->banked_r13[i]);
6554
        qemu_put_be32(f, env->banked_r14[i]);
6555
    }
6556
    for (i = 0; i < 5; i++) {
6557
        qemu_put_be32(f, env->usr_regs[i]);
6558
        qemu_put_be32(f, env->fiq_regs[i]);
6559
    }
6560
    qemu_put_be32(f, env->cp15.c0_cpuid);
6561
    qemu_put_be32(f, env->cp15.c0_cachetype);
6562
    qemu_put_be32(f, env->cp15.c1_sys);
6563
    qemu_put_be32(f, env->cp15.c1_coproc);
6564
    qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6565
    qemu_put_be32(f, env->cp15.c2_base0);
6566
    qemu_put_be32(f, env->cp15.c2_base1);
6567
    qemu_put_be32(f, env->cp15.c2_mask);
6568
    qemu_put_be32(f, env->cp15.c2_data);
6569
    qemu_put_be32(f, env->cp15.c2_insn);
6570
    qemu_put_be32(f, env->cp15.c3);
6571
    qemu_put_be32(f, env->cp15.c5_insn);
6572
    qemu_put_be32(f, env->cp15.c5_data);
6573
    for (i = 0; i < 8; i++) {
6574
        qemu_put_be32(f, env->cp15.c6_region[i]);
6575
    }
6576
    qemu_put_be32(f, env->cp15.c6_insn);
6577
    qemu_put_be32(f, env->cp15.c6_data);
6578
    qemu_put_be32(f, env->cp15.c9_insn);
6579
    qemu_put_be32(f, env->cp15.c9_data);
6580
    qemu_put_be32(f, env->cp15.c13_fcse);
6581
    qemu_put_be32(f, env->cp15.c13_context);
6582
    qemu_put_be32(f, env->cp15.c13_tls1);
6583
    qemu_put_be32(f, env->cp15.c13_tls2);
6584
    qemu_put_be32(f, env->cp15.c13_tls3);
6585
    qemu_put_be32(f, env->cp15.c15_cpar);
6586

    
6587
    qemu_put_be32(f, env->features);
6588

    
6589
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6590
        for (i = 0;  i < 16; i++) {
6591
            CPU_DoubleU u;
6592
            u.d = env->vfp.regs[i];
6593
            qemu_put_be32(f, u.l.upper);
6594
            qemu_put_be32(f, u.l.lower);
6595
        }
6596
        for (i = 0; i < 16; i++) {
6597
            qemu_put_be32(f, env->vfp.xregs[i]);
6598
        }
6599

    
6600
        /* TODO: Should use proper FPSCR access functions.  */
6601
        qemu_put_be32(f, env->vfp.vec_len);
6602
        qemu_put_be32(f, env->vfp.vec_stride);
6603

    
6604
        if (arm_feature(env, ARM_FEATURE_VFP3)) {
6605
            for (i = 16;  i < 32; i++) {
6606
                CPU_DoubleU u;
6607
                u.d = env->vfp.regs[i];
6608
                qemu_put_be32(f, u.l.upper);
6609
                qemu_put_be32(f, u.l.lower);
6610
            }
6611
        }
6612
    }
6613

    
6614
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6615
        for (i = 0; i < 16; i++) {
6616
            qemu_put_be64(f, env->iwmmxt.regs[i]);
6617
        }
6618
        for (i = 0; i < 16; i++) {
6619
            qemu_put_be32(f, env->iwmmxt.cregs[i]);
6620
        }
6621
    }
6622

    
6623
    if (arm_feature(env, ARM_FEATURE_M)) {
6624
        qemu_put_be32(f, env->v7m.other_sp);
6625
        qemu_put_be32(f, env->v7m.vecbase);
6626
        qemu_put_be32(f, env->v7m.basepri);
6627
        qemu_put_be32(f, env->v7m.control);
6628
        qemu_put_be32(f, env->v7m.current_sp);
6629
        qemu_put_be32(f, env->v7m.exception);
6630
    }
6631
}
6632

    
6633
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6634
{
6635
    CPUARMState *env = (CPUARMState *)opaque;
6636
    int i;
6637

    
6638
    if (version_id != ARM_CPU_SAVE_VERSION)
6639
        return -EINVAL;
6640

    
6641
    for (i = 0; i < 16; i++) {
6642
        env->regs[i] = qemu_get_be32(f);
6643
    }
6644
    cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6645
    env->spsr = qemu_get_be32(f);
6646
    for (i = 0; i < 6; i++) {
6647
        env->banked_spsr[i] = qemu_get_be32(f);
6648
        env->banked_r13[i] = qemu_get_be32(f);
6649
        env->banked_r14[i] = qemu_get_be32(f);
6650
    }
6651
    for (i = 0; i < 5; i++) {
6652
        env->usr_regs[i] = qemu_get_be32(f);
6653
        env->fiq_regs[i] = qemu_get_be32(f);
6654
    }
6655
    env->cp15.c0_cpuid = qemu_get_be32(f);
6656
    env->cp15.c0_cachetype = qemu_get_be32(f);
6657
    env->cp15.c1_sys = qemu_get_be32(f);
6658
    env->cp15.c1_coproc = qemu_get_be32(f);
6659
    env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6660
    env->cp15.c2_base0 = qemu_get_be32(f);
6661
    env->cp15.c2_base1 = qemu_get_be32(f);
6662
    env->cp15.c2_mask = qemu_get_be32(f);
6663
    env->cp15.c2_data = qemu_get_be32(f);
6664
    env->cp15.c2_insn = qemu_get_be32(f);
6665
    env->cp15.c3 = qemu_get_be32(f);
6666
    env->cp15.c5_insn = qemu_get_be32(f);
6667
    env->cp15.c5_data = qemu_get_be32(f);
6668
    for (i = 0; i < 8; i++) {
6669
        env->cp15.c6_region[i] = qemu_get_be32(f);
6670
    }
6671
    env->cp15.c6_insn = qemu_get_be32(f);
6672
    env->cp15.c6_data = qemu_get_be32(f);
6673
    env->cp15.c9_insn = qemu_get_be32(f);
6674
    env->cp15.c9_data = qemu_get_be32(f);
6675
    env->cp15.c13_fcse = qemu_get_be32(f);
6676
    env->cp15.c13_context = qemu_get_be32(f);
6677
    env->cp15.c13_tls1 = qemu_get_be32(f);
6678
    env->cp15.c13_tls2 = qemu_get_be32(f);
6679
    env->cp15.c13_tls3 = qemu_get_be32(f);
6680
    env->cp15.c15_cpar = qemu_get_be32(f);
6681

    
6682
    env->features = qemu_get_be32(f);
6683

    
6684
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6685
        for (i = 0;  i < 16; i++) {
6686
            CPU_DoubleU u;
6687
            u.l.upper = qemu_get_be32(f);
6688
            u.l.lower = qemu_get_be32(f);
6689
            env->vfp.regs[i] = u.d;
6690
        }
6691
        for (i = 0; i < 16; i++) {
6692
            env->vfp.xregs[i] = qemu_get_be32(f);
6693
        }
6694

    
6695
        /* TODO: Should use proper FPSCR access functions.  */
6696
        env->vfp.vec_len = qemu_get_be32(f);
6697
        env->vfp.vec_stride = qemu_get_be32(f);
6698

    
6699
        if (arm_feature(env, ARM_FEATURE_VFP3)) {
6700
            for (i = 0;  i < 16; i++) {
6701
                CPU_DoubleU u;
6702
                u.l.upper = qemu_get_be32(f);
6703
                u.l.lower = qemu_get_be32(f);
6704
                env->vfp.regs[i] = u.d;
6705
            }
6706
        }
6707
    }
6708

    
6709
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6710
        for (i = 0; i < 16; i++) {
6711
            env->iwmmxt.regs[i] = qemu_get_be64(f);
6712
        }
6713
        for (i = 0; i < 16; i++) {
6714
            env->iwmmxt.cregs[i] = qemu_get_be32(f);
6715
        }
6716
    }
6717

    
6718
    if (arm_feature(env, ARM_FEATURE_M)) {
6719
        env->v7m.other_sp = qemu_get_be32(f);
6720
        env->v7m.vecbase = qemu_get_be32(f);
6721
        env->v7m.basepri = qemu_get_be32(f);
6722
        env->v7m.control = qemu_get_be32(f);
6723
        env->v7m.current_sp = qemu_get_be32(f);
6724
        env->v7m.exception = qemu_get_be32(f);
6725
    }
6726

    
6727
    return 0;
6728
}
6729

    
6730
#else
6731

    
6732
//#warning No CPU save/restore functions
6733

    
6734
#endif
6735

    
6736
/***********************************************************/
6737
/* ram save/restore */
6738

    
6739
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6740
{
6741
    int v;
6742

    
6743
    v = qemu_get_byte(f);
6744
    switch(v) {
6745
    case 0:
6746
        if (qemu_get_buffer(f, buf, len) != len)
6747
            return -EIO;
6748
        break;
6749
    case 1:
6750
        v = qemu_get_byte(f);
6751
        memset(buf, v, len);
6752
        break;
6753
    default:
6754
        return -EINVAL;
6755
    }
6756
    return 0;
6757
}
6758

    
6759
static int ram_load_v1(QEMUFile *f, void *opaque)
6760
{
6761
    int i, ret;
6762

    
6763
    if (qemu_get_be32(f) != phys_ram_size)
6764
        return -EINVAL;
6765
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6766
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6767
        if (ret)
6768
            return ret;
6769
    }
6770
    return 0;
6771
}
6772

    
6773
#define BDRV_HASH_BLOCK_SIZE 1024
6774
#define IOBUF_SIZE 4096
6775
#define RAM_CBLOCK_MAGIC 0xfabe
6776

    
6777
typedef struct RamCompressState {
6778
    z_stream zstream;
6779
    QEMUFile *f;
6780
    uint8_t buf[IOBUF_SIZE];
6781
} RamCompressState;
6782

    
6783
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6784
{
6785
    int ret;
6786
    memset(s, 0, sizeof(*s));
6787
    s->f = f;
6788
    ret = deflateInit2(&s->zstream, 1,
6789
                       Z_DEFLATED, 15,
6790
                       9, Z_DEFAULT_STRATEGY);
6791
    if (ret != Z_OK)
6792
        return -1;
6793
    s->zstream.avail_out = IOBUF_SIZE;
6794
    s->zstream.next_out = s->buf;
6795
    return 0;
6796
}
6797

    
6798
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6799
{
6800
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6801
    qemu_put_be16(s->f, len);
6802
    qemu_put_buffer(s->f, buf, len);
6803
}
6804

    
6805
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6806
{
6807
    int ret;
6808

    
6809
    s->zstream.avail_in = len;
6810
    s->zstream.next_in = (uint8_t *)buf;
6811
    while (s->zstream.avail_in > 0) {
6812
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6813
        if (ret != Z_OK)
6814
            return -1;
6815
        if (s->zstream.avail_out == 0) {
6816
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6817
            s->zstream.avail_out = IOBUF_SIZE;
6818
            s->zstream.next_out = s->buf;
6819
        }
6820
    }
6821
    return 0;
6822
}
6823

    
6824
static void ram_compress_close(RamCompressState *s)
6825
{
6826
    int len, ret;
6827

    
6828
    /* compress last bytes */
6829
    for(;;) {
6830
        ret = deflate(&s->zstream, Z_FINISH);
6831
        if (ret == Z_OK || ret == Z_STREAM_END) {
6832
            len = IOBUF_SIZE - s->zstream.avail_out;
6833
            if (len > 0) {
6834
                ram_put_cblock(s, s->buf, len);
6835
            }
6836
            s->zstream.avail_out = IOBUF_SIZE;
6837
            s->zstream.next_out = s->buf;
6838
            if (ret == Z_STREAM_END)
6839
                break;
6840
        } else {
6841
            goto fail;
6842
        }
6843
    }
6844
fail:
6845
    deflateEnd(&s->zstream);
6846
}
6847

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

    
6854
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6855
{
6856
    int ret;
6857
    memset(s, 0, sizeof(*s));
6858
    s->f = f;
6859
    ret = inflateInit(&s->zstream);
6860
    if (ret != Z_OK)
6861
        return -1;
6862
    return 0;
6863
}
6864

    
6865
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6866
{
6867
    int ret, clen;
6868

    
6869
    s->zstream.avail_out = len;
6870
    s->zstream.next_out = buf;
6871
    while (s->zstream.avail_out > 0) {
6872
        if (s->zstream.avail_in == 0) {
6873
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6874
                return -1;
6875
            clen = qemu_get_be16(s->f);
6876
            if (clen > IOBUF_SIZE)
6877
                return -1;
6878
            qemu_get_buffer(s->f, s->buf, clen);
6879
            s->zstream.avail_in = clen;
6880
            s->zstream.next_in = s->buf;
6881
        }
6882
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6883
        if (ret != Z_OK && ret != Z_STREAM_END) {
6884
            return -1;
6885
        }
6886
    }
6887
    return 0;
6888
}
6889

    
6890
static void ram_decompress_close(RamDecompressState *s)
6891
{
6892
    inflateEnd(&s->zstream);
6893
}
6894

    
6895
static void ram_save(QEMUFile *f, void *opaque)
6896
{
6897
    int i;
6898
    RamCompressState s1, *s = &s1;
6899
    uint8_t buf[10];
6900

    
6901
    qemu_put_be32(f, phys_ram_size);
6902
    if (ram_compress_open(s, f) < 0)
6903
        return;
6904
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6905
#if 0
6906
        if (tight_savevm_enabled) {
6907
            int64_t sector_num;
6908
            int j;
6909

6910
            /* find if the memory block is available on a virtual
6911
               block device */
6912
            sector_num = -1;
6913
            for(j = 0; j < nb_drives; j++) {
6914
                sector_num = bdrv_hash_find(drives_table[j].bdrv,
6915
                                            phys_ram_base + i,
6916
                                            BDRV_HASH_BLOCK_SIZE);
6917
                if (sector_num >= 0)
6918
                    break;
6919
            }
6920
            if (j == nb_drives)
6921
                goto normal_compress;
6922
            buf[0] = 1;
6923
            buf[1] = j;
6924
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6925
            ram_compress_buf(s, buf, 10);
6926
        } else
6927
#endif
6928
        {
6929
            //        normal_compress:
6930
            buf[0] = 0;
6931
            ram_compress_buf(s, buf, 1);
6932
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6933
        }
6934
    }
6935
    ram_compress_close(s);
6936
}
6937

    
6938
static int ram_load(QEMUFile *f, void *opaque, int version_id)
6939
{
6940
    RamDecompressState s1, *s = &s1;
6941
    uint8_t buf[10];
6942
    int i;
6943

    
6944
    if (version_id == 1)
6945
        return ram_load_v1(f, opaque);
6946
    if (version_id != 2)
6947
        return -EINVAL;
6948
    if (qemu_get_be32(f) != phys_ram_size)
6949
        return -EINVAL;
6950
    if (ram_decompress_open(s, f) < 0)
6951
        return -EINVAL;
6952
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6953
        if (ram_decompress_buf(s, buf, 1) < 0) {
6954
            fprintf(stderr, "Error while reading ram block header\n");
6955
            goto error;
6956
        }
6957
        if (buf[0] == 0) {
6958
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6959
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6960
                goto error;
6961
            }
6962
        } else
6963
#if 0
6964
        if (buf[0] == 1) {
6965
            int bs_index;
6966
            int64_t sector_num;
6967

6968
            ram_decompress_buf(s, buf + 1, 9);
6969
            bs_index = buf[1];
6970
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6971
            if (bs_index >= nb_drives) {
6972
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
6973
                goto error;
6974
            }
6975
            if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6976
                          phys_ram_base + i,
6977
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6978
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6979
                        bs_index, sector_num);
6980
                goto error;
6981
            }
6982
        } else
6983
#endif
6984
        {
6985
        error:
6986
            printf("Error block header\n");
6987
            return -EINVAL;
6988
        }
6989
    }
6990
    ram_decompress_close(s);
6991
    return 0;
6992
}
6993

    
6994
/***********************************************************/
6995
/* bottom halves (can be seen as timers which expire ASAP) */
6996

    
6997
struct QEMUBH {
6998
    QEMUBHFunc *cb;
6999
    void *opaque;
7000
    int scheduled;
7001
    QEMUBH *next;
7002
};
7003

    
7004
static QEMUBH *first_bh = NULL;
7005

    
7006
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7007
{
7008
    QEMUBH *bh;
7009
    bh = qemu_mallocz(sizeof(QEMUBH));
7010
    if (!bh)
7011
        return NULL;
7012
    bh->cb = cb;
7013
    bh->opaque = opaque;
7014
    return bh;
7015
}
7016

    
7017
int qemu_bh_poll(void)
7018
{
7019
    QEMUBH *bh, **pbh;
7020
    int ret;
7021

    
7022
    ret = 0;
7023
    for(;;) {
7024
        pbh = &first_bh;
7025
        bh = *pbh;
7026
        if (!bh)
7027
            break;
7028
        ret = 1;
7029
        *pbh = bh->next;
7030
        bh->scheduled = 0;
7031
        bh->cb(bh->opaque);
7032
    }
7033
    return ret;
7034
}
7035

    
7036
void qemu_bh_schedule(QEMUBH *bh)
7037
{
7038
    CPUState *env = cpu_single_env;
7039
    if (bh->scheduled)
7040
        return;
7041
    bh->scheduled = 1;
7042
    bh->next = first_bh;
7043
    first_bh = bh;
7044

    
7045
    /* stop the currently executing CPU to execute the BH ASAP */
7046
    if (env) {
7047
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7048
    }
7049
}
7050

    
7051
void qemu_bh_cancel(QEMUBH *bh)
7052
{
7053
    QEMUBH **pbh;
7054
    if (bh->scheduled) {
7055
        pbh = &first_bh;
7056
        while (*pbh != bh)
7057
            pbh = &(*pbh)->next;
7058
        *pbh = bh->next;
7059
        bh->scheduled = 0;
7060
    }
7061
}
7062

    
7063
void qemu_bh_delete(QEMUBH *bh)
7064
{
7065
    qemu_bh_cancel(bh);
7066
    qemu_free(bh);
7067
}
7068

    
7069
/***********************************************************/
7070
/* machine registration */
7071

    
7072
QEMUMachine *first_machine = NULL;
7073

    
7074
int qemu_register_machine(QEMUMachine *m)
7075
{
7076
    QEMUMachine **pm;
7077
    pm = &first_machine;
7078
    while (*pm != NULL)
7079
        pm = &(*pm)->next;
7080
    m->next = NULL;
7081
    *pm = m;
7082
    return 0;
7083
}
7084

    
7085
static QEMUMachine *find_machine(const char *name)
7086
{
7087
    QEMUMachine *m;
7088

    
7089
    for(m = first_machine; m != NULL; m = m->next) {
7090
        if (!strcmp(m->name, name))
7091
            return m;
7092
    }
7093
    return NULL;
7094
}
7095

    
7096
/***********************************************************/
7097
/* main execution loop */
7098

    
7099
static void gui_update(void *opaque)
7100
{
7101
    DisplayState *ds = opaque;
7102
    ds->dpy_refresh(ds);
7103
    qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7104
}
7105

    
7106
struct vm_change_state_entry {
7107
    VMChangeStateHandler *cb;
7108
    void *opaque;
7109
    LIST_ENTRY (vm_change_state_entry) entries;
7110
};
7111

    
7112
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7113

    
7114
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7115
                                                     void *opaque)
7116
{
7117
    VMChangeStateEntry *e;
7118

    
7119
    e = qemu_mallocz(sizeof (*e));
7120
    if (!e)
7121
        return NULL;
7122

    
7123
    e->cb = cb;
7124
    e->opaque = opaque;
7125
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7126
    return e;
7127
}
7128

    
7129
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7130
{
7131
    LIST_REMOVE (e, entries);
7132
    qemu_free (e);
7133
}
7134

    
7135
static void vm_state_notify(int running)
7136
{
7137
    VMChangeStateEntry *e;
7138

    
7139
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7140
        e->cb(e->opaque, running);
7141
    }
7142
}
7143

    
7144
/* XXX: support several handlers */
7145
static VMStopHandler *vm_stop_cb;
7146
static void *vm_stop_opaque;
7147

    
7148
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7149
{
7150
    vm_stop_cb = cb;
7151
    vm_stop_opaque = opaque;
7152
    return 0;
7153
}
7154

    
7155
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7156
{
7157
    vm_stop_cb = NULL;
7158
}
7159

    
7160
void vm_start(void)
7161
{
7162
    if (!vm_running) {
7163
        cpu_enable_ticks();
7164
        vm_running = 1;
7165
        vm_state_notify(1);
7166
        qemu_rearm_alarm_timer(alarm_timer);
7167
    }
7168
}
7169

    
7170
void vm_stop(int reason)
7171
{
7172
    if (vm_running) {
7173
        cpu_disable_ticks();
7174
        vm_running = 0;
7175
        if (reason != 0) {
7176
            if (vm_stop_cb) {
7177
                vm_stop_cb(vm_stop_opaque, reason);
7178
            }
7179
        }
7180
        vm_state_notify(0);
7181
    }
7182
}
7183

    
7184
/* reset/shutdown handler */
7185

    
7186
typedef struct QEMUResetEntry {
7187
    QEMUResetHandler *func;
7188
    void *opaque;
7189
    struct QEMUResetEntry *next;
7190
} QEMUResetEntry;
7191

    
7192
static QEMUResetEntry *first_reset_entry;
7193
static int reset_requested;
7194
static int shutdown_requested;
7195
static int powerdown_requested;
7196

    
7197
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7198
{
7199
    QEMUResetEntry **pre, *re;
7200

    
7201
    pre = &first_reset_entry;
7202
    while (*pre != NULL)
7203
        pre = &(*pre)->next;
7204
    re = qemu_mallocz(sizeof(QEMUResetEntry));
7205
    re->func = func;
7206
    re->opaque = opaque;
7207
    re->next = NULL;
7208
    *pre = re;
7209
}
7210

    
7211
static void qemu_system_reset(void)
7212
{
7213
    QEMUResetEntry *re;
7214

    
7215
    /* reset all devices */
7216
    for(re = first_reset_entry; re != NULL; re = re->next) {
7217
        re->func(re->opaque);
7218
    }
7219
}
7220

    
7221
void qemu_system_reset_request(void)
7222
{
7223
    if (no_reboot) {
7224
        shutdown_requested = 1;
7225
    } else {
7226
        reset_requested = 1;
7227
    }
7228
    if (cpu_single_env)
7229
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7230
}
7231

    
7232
void qemu_system_shutdown_request(void)
7233
{
7234
    shutdown_requested = 1;
7235
    if (cpu_single_env)
7236
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7237
}
7238

    
7239
void qemu_system_powerdown_request(void)
7240
{
7241
    powerdown_requested = 1;
7242
    if (cpu_single_env)
7243
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7244
}
7245

    
7246
void main_loop_wait(int timeout)
7247
{
7248
    IOHandlerRecord *ioh;
7249
    fd_set rfds, wfds, xfds;
7250
    int ret, nfds;
7251
#ifdef _WIN32
7252
    int ret2, i;
7253
#endif
7254
    struct timeval tv;
7255
    PollingEntry *pe;
7256

    
7257

    
7258
    /* XXX: need to suppress polling by better using win32 events */
7259
    ret = 0;
7260
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7261
        ret |= pe->func(pe->opaque);
7262
    }
7263
#ifdef _WIN32
7264
    if (ret == 0) {
7265
        int err;
7266
        WaitObjects *w = &wait_objects;
7267

    
7268
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7269
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7270
            if (w->func[ret - WAIT_OBJECT_0])
7271
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7272

    
7273
            /* Check for additional signaled events */
7274
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7275

    
7276
                /* Check if event is signaled */
7277
                ret2 = WaitForSingleObject(w->events[i], 0);
7278
                if(ret2 == WAIT_OBJECT_0) {
7279
                    if (w->func[i])
7280
                        w->func[i](w->opaque[i]);
7281
                } else if (ret2 == WAIT_TIMEOUT) {
7282
                } else {
7283
                    err = GetLastError();
7284
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7285
                }
7286
            }
7287
        } else if (ret == WAIT_TIMEOUT) {
7288
        } else {
7289
            err = GetLastError();
7290
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7291
        }
7292
    }
7293
#endif
7294
    /* poll any events */
7295
    /* XXX: separate device handlers from system ones */
7296
    nfds = -1;
7297
    FD_ZERO(&rfds);
7298
    FD_ZERO(&wfds);
7299
    FD_ZERO(&xfds);
7300
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7301
        if (ioh->deleted)
7302
            continue;
7303
        if (ioh->fd_read &&
7304
            (!ioh->fd_read_poll ||
7305
             ioh->fd_read_poll(ioh->opaque) != 0)) {
7306
            FD_SET(ioh->fd, &rfds);
7307
            if (ioh->fd > nfds)
7308
                nfds = ioh->fd;
7309
        }
7310
        if (ioh->fd_write) {
7311
            FD_SET(ioh->fd, &wfds);
7312
            if (ioh->fd > nfds)
7313
                nfds = ioh->fd;
7314
        }
7315
    }
7316

    
7317
    tv.tv_sec = 0;
7318
#ifdef _WIN32
7319
    tv.tv_usec = 0;
7320
#else
7321
    tv.tv_usec = timeout * 1000;
7322
#endif
7323
#if defined(CONFIG_SLIRP)
7324
    if (slirp_inited) {
7325
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7326
    }
7327
#endif
7328
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7329
    if (ret > 0) {
7330
        IOHandlerRecord **pioh;
7331

    
7332
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7333
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7334
                ioh->fd_read(ioh->opaque);
7335
            }
7336
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7337
                ioh->fd_write(ioh->opaque);
7338
            }
7339
        }
7340

    
7341
        /* remove deleted IO handlers */
7342
        pioh = &first_io_handler;
7343
        while (*pioh) {
7344
            ioh = *pioh;
7345
            if (ioh->deleted) {
7346
                *pioh = ioh->next;
7347
                qemu_free(ioh);
7348
            } else
7349
                pioh = &ioh->next;
7350
        }
7351
    }
7352
#if defined(CONFIG_SLIRP)
7353
    if (slirp_inited) {
7354
        if (ret < 0) {
7355
            FD_ZERO(&rfds);
7356
            FD_ZERO(&wfds);
7357
            FD_ZERO(&xfds);
7358
        }
7359
        slirp_select_poll(&rfds, &wfds, &xfds);
7360
    }
7361
#endif
7362
    qemu_aio_poll();
7363

    
7364
    if (vm_running) {
7365
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7366
                        qemu_get_clock(vm_clock));
7367
        /* run dma transfers, if any */
7368
        DMA_run();
7369
    }
7370

    
7371
    /* real time timers */
7372
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7373
                    qemu_get_clock(rt_clock));
7374

    
7375
    qemu_rearm_alarm_timer(alarm_timer);
7376

    
7377
    /* Check bottom-halves last in case any of the earlier events triggered
7378
       them.  */
7379
    qemu_bh_poll();
7380

    
7381
}
7382

    
7383
static int main_loop(void)
7384
{
7385
    int ret, timeout;
7386
#ifdef CONFIG_PROFILER
7387
    int64_t ti;
7388
#endif
7389
    CPUState *env;
7390

    
7391
    cur_cpu = first_cpu;
7392
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7393
    for(;;) {
7394
        if (vm_running) {
7395

    
7396
            for(;;) {
7397
                /* get next cpu */
7398
                env = next_cpu;
7399
#ifdef CONFIG_PROFILER
7400
                ti = profile_getclock();
7401
#endif
7402
                ret = cpu_exec(env);
7403
#ifdef CONFIG_PROFILER
7404
                qemu_time += profile_getclock() - ti;
7405
#endif
7406
                next_cpu = env->next_cpu ?: first_cpu;
7407
                if (event_pending) {
7408
                    ret = EXCP_INTERRUPT;
7409
                    event_pending = 0;
7410
                    break;
7411
                }
7412
                if (ret == EXCP_HLT) {
7413
                    /* Give the next CPU a chance to run.  */
7414
                    cur_cpu = env;
7415
                    continue;
7416
                }
7417
                if (ret != EXCP_HALTED)
7418
                    break;
7419
                /* all CPUs are halted ? */
7420
                if (env == cur_cpu)
7421
                    break;
7422
            }
7423
            cur_cpu = env;
7424

    
7425
            if (shutdown_requested) {
7426
                ret = EXCP_INTERRUPT;
7427
                break;
7428
            }
7429
            if (reset_requested) {
7430
                reset_requested = 0;
7431
                qemu_system_reset();
7432
                ret = EXCP_INTERRUPT;
7433
            }
7434
            if (powerdown_requested) {
7435
                powerdown_requested = 0;
7436
                qemu_system_powerdown();
7437
                ret = EXCP_INTERRUPT;
7438
            }
7439
            if (ret == EXCP_DEBUG) {
7440
                vm_stop(EXCP_DEBUG);
7441
            }
7442
            /* If all cpus are halted then wait until the next IRQ */
7443
            /* XXX: use timeout computed from timers */
7444
            if (ret == EXCP_HALTED)
7445
                timeout = 10;
7446
            else
7447
                timeout = 0;
7448
        } else {
7449
            timeout = 10;
7450
        }
7451
#ifdef CONFIG_PROFILER
7452
        ti = profile_getclock();
7453
#endif
7454
        main_loop_wait(timeout);
7455
#ifdef CONFIG_PROFILER
7456
        dev_time += profile_getclock() - ti;
7457
#endif
7458
    }
7459
    cpu_disable_ticks();
7460
    return ret;
7461
}
7462

    
7463
static void help(int exitcode)
7464
{
7465
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7466
           "usage: %s [options] [disk_image]\n"
7467
           "\n"
7468
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7469
           "\n"
7470
           "Standard options:\n"
7471
           "-M machine      select emulated machine (-M ? for list)\n"
7472
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7473
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7474
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7475
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7476
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7477
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7478
           "       [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7479
           "                use 'file' as a drive image\n"
7480
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7481
           "-sd file        use 'file' as SecureDigital card image\n"
7482
           "-pflash file    use 'file' as a parallel flash image\n"
7483
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7484
           "-snapshot       write to temporary files instead of disk image files\n"
7485
#ifdef CONFIG_SDL
7486
           "-no-frame       open SDL window without a frame and window decorations\n"
7487
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7488
           "-no-quit        disable SDL window close capability\n"
7489
#endif
7490
#ifdef TARGET_I386
7491
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7492
#endif
7493
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7494
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7495
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7496
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7497
#ifndef _WIN32
7498
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7499
#endif
7500
#ifdef HAS_AUDIO
7501
           "-audio-help     print list of audio drivers and their options\n"
7502
           "-soundhw c1,... enable audio support\n"
7503
           "                and only specified sound cards (comma separated list)\n"
7504
           "                use -soundhw ? to get the list of supported cards\n"
7505
           "                use -soundhw all to enable all of them\n"
7506
#endif
7507
           "-localtime      set the real time clock to local time [default=utc]\n"
7508
           "-full-screen    start in full screen\n"
7509
#ifdef TARGET_I386
7510
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7511
#endif
7512
           "-usb            enable the USB driver (will be the default soon)\n"
7513
           "-usbdevice name add the host or guest USB device 'name'\n"
7514
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7515
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7516
#endif
7517
           "-name string    set the name of the guest\n"
7518
           "\n"
7519
           "Network options:\n"
7520
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7521
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7522
#ifdef CONFIG_SLIRP
7523
           "-net user[,vlan=n][,hostname=host]\n"
7524
           "                connect the user mode network stack to VLAN 'n' and send\n"
7525
           "                hostname 'host' to DHCP clients\n"
7526
#endif
7527
#ifdef _WIN32
7528
           "-net tap[,vlan=n],ifname=name\n"
7529
           "                connect the host TAP network interface to VLAN 'n'\n"
7530
#else
7531
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7532
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7533
           "                network scripts 'file' (default=%s)\n"
7534
           "                and 'dfile' (default=%s);\n"
7535
           "                use '[down]script=no' to disable script execution;\n"
7536
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7537
#endif
7538
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7539
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7540
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7541
           "                connect the vlan 'n' to multicast maddr and port\n"
7542
           "-net none       use it alone to have zero network devices; if no -net option\n"
7543
           "                is provided, the default is '-net nic -net user'\n"
7544
           "\n"
7545
#ifdef CONFIG_SLIRP
7546
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7547
           "-bootp file     advertise file in BOOTP replies\n"
7548
#ifndef _WIN32
7549
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7550
#endif
7551
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7552
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7553
#endif
7554
           "\n"
7555
           "Linux boot specific:\n"
7556
           "-kernel bzImage use 'bzImage' as kernel image\n"
7557
           "-append cmdline use 'cmdline' as kernel command line\n"
7558
           "-initrd file    use 'file' as initial ram disk\n"
7559
           "\n"
7560
           "Debug/Expert options:\n"
7561
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7562
           "-serial dev     redirect the serial port to char device 'dev'\n"
7563
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7564
           "-pidfile file   Write PID to 'file'\n"
7565
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7566
           "-s              wait gdb connection to port\n"
7567
           "-p port         set gdb connection port [default=%s]\n"
7568
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7569
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7570
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7571
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7572
#ifdef USE_KQEMU
7573
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7574
           "-no-kqemu       disable KQEMU kernel module usage\n"
7575
#endif
7576
#ifdef TARGET_I386
7577
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7578
           "                (default is CL-GD5446 PCI VGA)\n"
7579
           "-no-acpi        disable ACPI\n"
7580
#endif
7581
           "-no-reboot      exit instead of rebooting\n"
7582
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
7583
           "-vnc display    start a VNC server on display\n"
7584
#ifndef _WIN32
7585
           "-daemonize      daemonize QEMU after initializing\n"
7586
#endif
7587
           "-option-rom rom load a file, rom, into the option ROM space\n"
7588
#ifdef TARGET_SPARC
7589
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7590
#endif
7591
           "-clock          force the use of the given methods for timer alarm.\n"
7592
           "                To see what timers are available use -clock help\n"
7593
           "\n"
7594
           "During emulation, the following keys are useful:\n"
7595
           "ctrl-alt-f      toggle full screen\n"
7596
           "ctrl-alt-n      switch to virtual console 'n'\n"
7597
           "ctrl-alt        toggle mouse and keyboard grab\n"
7598
           "\n"
7599
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7600
           ,
7601
           "qemu",
7602
           DEFAULT_RAM_SIZE,
7603
#ifndef _WIN32
7604
           DEFAULT_NETWORK_SCRIPT,
7605
           DEFAULT_NETWORK_DOWN_SCRIPT,
7606
#endif
7607
           DEFAULT_GDBSTUB_PORT,
7608
           "/tmp/qemu.log");
7609
    exit(exitcode);
7610
}
7611

    
7612
#define HAS_ARG 0x0001
7613

    
7614
enum {
7615
    QEMU_OPTION_h,
7616

    
7617
    QEMU_OPTION_M,
7618
    QEMU_OPTION_cpu,
7619
    QEMU_OPTION_fda,
7620
    QEMU_OPTION_fdb,
7621
    QEMU_OPTION_hda,
7622
    QEMU_OPTION_hdb,
7623
    QEMU_OPTION_hdc,
7624
    QEMU_OPTION_hdd,
7625
    QEMU_OPTION_drive,
7626
    QEMU_OPTION_cdrom,
7627
    QEMU_OPTION_mtdblock,
7628
    QEMU_OPTION_sd,
7629
    QEMU_OPTION_pflash,
7630
    QEMU_OPTION_boot,
7631
    QEMU_OPTION_snapshot,
7632
#ifdef TARGET_I386
7633
    QEMU_OPTION_no_fd_bootchk,
7634
#endif
7635
    QEMU_OPTION_m,
7636
    QEMU_OPTION_nographic,
7637
    QEMU_OPTION_portrait,
7638
#ifdef HAS_AUDIO
7639
    QEMU_OPTION_audio_help,
7640
    QEMU_OPTION_soundhw,
7641
#endif
7642

    
7643
    QEMU_OPTION_net,
7644
    QEMU_OPTION_tftp,
7645
    QEMU_OPTION_bootp,
7646
    QEMU_OPTION_smb,
7647
    QEMU_OPTION_redir,
7648

    
7649
    QEMU_OPTION_kernel,
7650
    QEMU_OPTION_append,
7651
    QEMU_OPTION_initrd,
7652

    
7653
    QEMU_OPTION_S,
7654
    QEMU_OPTION_s,
7655
    QEMU_OPTION_p,
7656
    QEMU_OPTION_d,
7657
    QEMU_OPTION_hdachs,
7658
    QEMU_OPTION_L,
7659
    QEMU_OPTION_bios,
7660
    QEMU_OPTION_no_code_copy,
7661
    QEMU_OPTION_k,
7662
    QEMU_OPTION_localtime,
7663
    QEMU_OPTION_cirrusvga,
7664
    QEMU_OPTION_vmsvga,
7665
    QEMU_OPTION_g,
7666
    QEMU_OPTION_std_vga,
7667
    QEMU_OPTION_echr,
7668
    QEMU_OPTION_monitor,
7669
    QEMU_OPTION_serial,
7670
    QEMU_OPTION_parallel,
7671
    QEMU_OPTION_loadvm,
7672
    QEMU_OPTION_full_screen,
7673
    QEMU_OPTION_no_frame,
7674
    QEMU_OPTION_alt_grab,
7675
    QEMU_OPTION_no_quit,
7676
    QEMU_OPTION_pidfile,
7677
    QEMU_OPTION_no_kqemu,
7678
    QEMU_OPTION_kernel_kqemu,
7679
    QEMU_OPTION_win2k_hack,
7680
    QEMU_OPTION_usb,
7681
    QEMU_OPTION_usbdevice,
7682
    QEMU_OPTION_smp,
7683
    QEMU_OPTION_vnc,
7684
    QEMU_OPTION_no_acpi,
7685
    QEMU_OPTION_no_reboot,
7686
    QEMU_OPTION_show_cursor,
7687
    QEMU_OPTION_daemonize,
7688
    QEMU_OPTION_option_rom,
7689
    QEMU_OPTION_semihosting,
7690
    QEMU_OPTION_name,
7691
    QEMU_OPTION_prom_env,
7692
    QEMU_OPTION_old_param,
7693
    QEMU_OPTION_clock,
7694
    QEMU_OPTION_startdate,
7695
};
7696

    
7697
typedef struct QEMUOption {
7698
    const char *name;
7699
    int flags;
7700
    int index;
7701
} QEMUOption;
7702

    
7703
const QEMUOption qemu_options[] = {
7704
    { "h", 0, QEMU_OPTION_h },
7705
    { "help", 0, QEMU_OPTION_h },
7706

    
7707
    { "M", HAS_ARG, QEMU_OPTION_M },
7708
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7709
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7710
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7711
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7712
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7713
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7714
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7715
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7716
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7717
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7718
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7719
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7720
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7721
    { "snapshot", 0, QEMU_OPTION_snapshot },
7722
#ifdef TARGET_I386
7723
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7724
#endif
7725
    { "m", HAS_ARG, QEMU_OPTION_m },
7726
    { "nographic", 0, QEMU_OPTION_nographic },
7727
    { "portrait", 0, QEMU_OPTION_portrait },
7728
    { "k", HAS_ARG, QEMU_OPTION_k },
7729
#ifdef HAS_AUDIO
7730
    { "audio-help", 0, QEMU_OPTION_audio_help },
7731
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7732
#endif
7733

    
7734
    { "net", HAS_ARG, QEMU_OPTION_net},
7735
#ifdef CONFIG_SLIRP
7736
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7737
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7738
#ifndef _WIN32
7739
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7740
#endif
7741
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7742
#endif
7743

    
7744
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7745
    { "append", HAS_ARG, QEMU_OPTION_append },
7746
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7747

    
7748
    { "S", 0, QEMU_OPTION_S },
7749
    { "s", 0, QEMU_OPTION_s },
7750
    { "p", HAS_ARG, QEMU_OPTION_p },
7751
    { "d", HAS_ARG, QEMU_OPTION_d },
7752
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7753
    { "L", HAS_ARG, QEMU_OPTION_L },
7754
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7755
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7756
#ifdef USE_KQEMU
7757
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7758
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7759
#endif
7760
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7761
    { "g", 1, QEMU_OPTION_g },
7762
#endif
7763
    { "localtime", 0, QEMU_OPTION_localtime },
7764
    { "std-vga", 0, QEMU_OPTION_std_vga },
7765
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7766
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7767
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7768
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7769
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7770
    { "full-screen", 0, QEMU_OPTION_full_screen },
7771
#ifdef CONFIG_SDL
7772
    { "no-frame", 0, QEMU_OPTION_no_frame },
7773
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7774
    { "no-quit", 0, QEMU_OPTION_no_quit },
7775
#endif
7776
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7777
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7778
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7779
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7780
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7781

    
7782
    /* temporary options */
7783
    { "usb", 0, QEMU_OPTION_usb },
7784
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7785
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7786
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7787
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7788
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7789
    { "daemonize", 0, QEMU_OPTION_daemonize },
7790
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7791
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7792
    { "semihosting", 0, QEMU_OPTION_semihosting },
7793
#endif
7794
    { "name", HAS_ARG, QEMU_OPTION_name },
7795
#if defined(TARGET_SPARC)
7796
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7797
#endif
7798
#if defined(TARGET_ARM)
7799
    { "old-param", 0, QEMU_OPTION_old_param },
7800
#endif
7801
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7802
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7803
    { NULL },
7804
};
7805

    
7806
/* password input */
7807

    
7808
int qemu_key_check(BlockDriverState *bs, const char *name)
7809
{
7810
    char password[256];
7811
    int i;
7812

    
7813
    if (!bdrv_is_encrypted(bs))
7814
        return 0;
7815

    
7816
    term_printf("%s is encrypted.\n", name);
7817
    for(i = 0; i < 3; i++) {
7818
        monitor_readline("Password: ", 1, password, sizeof(password));
7819
        if (bdrv_set_key(bs, password) == 0)
7820
            return 0;
7821
        term_printf("invalid password\n");
7822
    }
7823
    return -EPERM;
7824
}
7825

    
7826
static BlockDriverState *get_bdrv(int index)
7827
{
7828
    if (index > nb_drives)
7829
        return NULL;
7830
    return drives_table[index].bdrv;
7831
}
7832

    
7833
static void read_passwords(void)
7834
{
7835
    BlockDriverState *bs;
7836
    int i;
7837

    
7838
    for(i = 0; i < 6; i++) {
7839
        bs = get_bdrv(i);
7840
        if (bs)
7841
            qemu_key_check(bs, bdrv_get_device_name(bs));
7842
    }
7843
}
7844

    
7845
/* XXX: currently we cannot use simultaneously different CPUs */
7846
static void register_machines(void)
7847
{
7848
#if defined(TARGET_I386)
7849
    qemu_register_machine(&pc_machine);
7850
    qemu_register_machine(&isapc_machine);
7851
#elif defined(TARGET_PPC)
7852
    qemu_register_machine(&heathrow_machine);
7853
    qemu_register_machine(&core99_machine);
7854
    qemu_register_machine(&prep_machine);
7855
    qemu_register_machine(&ref405ep_machine);
7856
    qemu_register_machine(&taihu_machine);
7857
#elif defined(TARGET_MIPS)
7858
    qemu_register_machine(&mips_machine);
7859
    qemu_register_machine(&mips_malta_machine);
7860
    qemu_register_machine(&mips_pica61_machine);
7861
    qemu_register_machine(&mips_mipssim_machine);
7862
#elif defined(TARGET_SPARC)
7863
#ifdef TARGET_SPARC64
7864
    qemu_register_machine(&sun4u_machine);
7865
#else
7866
    qemu_register_machine(&ss5_machine);
7867
    qemu_register_machine(&ss10_machine);
7868
    qemu_register_machine(&ss600mp_machine);
7869
    qemu_register_machine(&ss20_machine);
7870
#endif
7871
#elif defined(TARGET_ARM)
7872
    qemu_register_machine(&integratorcp_machine);
7873
    qemu_register_machine(&versatilepb_machine);
7874
    qemu_register_machine(&versatileab_machine);
7875
    qemu_register_machine(&realview_machine);
7876
    qemu_register_machine(&akitapda_machine);
7877
    qemu_register_machine(&spitzpda_machine);
7878
    qemu_register_machine(&borzoipda_machine);
7879
    qemu_register_machine(&terrierpda_machine);
7880
    qemu_register_machine(&palmte_machine);
7881
    qemu_register_machine(&lm3s811evb_machine);
7882
    qemu_register_machine(&lm3s6965evb_machine);
7883
    qemu_register_machine(&connex_machine);
7884
    qemu_register_machine(&verdex_machine);
7885
    qemu_register_machine(&mainstone2_machine);
7886
#elif defined(TARGET_SH4)
7887
    qemu_register_machine(&shix_machine);
7888
    qemu_register_machine(&r2d_machine);
7889
#elif defined(TARGET_ALPHA)
7890
    /* XXX: TODO */
7891
#elif defined(TARGET_M68K)
7892
    qemu_register_machine(&mcf5208evb_machine);
7893
    qemu_register_machine(&an5206_machine);
7894
    qemu_register_machine(&dummy_m68k_machine);
7895
#elif defined(TARGET_CRIS)
7896
    qemu_register_machine(&bareetraxfs_machine);
7897
#else
7898
#error unsupported CPU
7899
#endif
7900
}
7901

    
7902
#ifdef HAS_AUDIO
7903
struct soundhw soundhw[] = {
7904
#ifdef HAS_AUDIO_CHOICE
7905
#ifdef TARGET_I386
7906
    {
7907
        "pcspk",
7908
        "PC speaker",
7909
        0,
7910
        1,
7911
        { .init_isa = pcspk_audio_init }
7912
    },
7913
#endif
7914
    {
7915
        "sb16",
7916
        "Creative Sound Blaster 16",
7917
        0,
7918
        1,
7919
        { .init_isa = SB16_init }
7920
    },
7921

    
7922
#ifdef CONFIG_ADLIB
7923
    {
7924
        "adlib",
7925
#ifdef HAS_YMF262
7926
        "Yamaha YMF262 (OPL3)",
7927
#else
7928
        "Yamaha YM3812 (OPL2)",
7929
#endif
7930
        0,
7931
        1,
7932
        { .init_isa = Adlib_init }
7933
    },
7934
#endif
7935

    
7936
#ifdef CONFIG_GUS
7937
    {
7938
        "gus",
7939
        "Gravis Ultrasound GF1",
7940
        0,
7941
        1,
7942
        { .init_isa = GUS_init }
7943
    },
7944
#endif
7945

    
7946
    {
7947
        "es1370",
7948
        "ENSONIQ AudioPCI ES1370",
7949
        0,
7950
        0,
7951
        { .init_pci = es1370_init }
7952
    },
7953
#endif
7954

    
7955
    { NULL, NULL, 0, 0, { NULL } }
7956
};
7957

    
7958
static void select_soundhw (const char *optarg)
7959
{
7960
    struct soundhw *c;
7961

    
7962
    if (*optarg == '?') {
7963
    show_valid_cards:
7964

    
7965
        printf ("Valid sound card names (comma separated):\n");
7966
        for (c = soundhw; c->name; ++c) {
7967
            printf ("%-11s %s\n", c->name, c->descr);
7968
        }
7969
        printf ("\n-soundhw all will enable all of the above\n");
7970
        exit (*optarg != '?');
7971
    }
7972
    else {
7973
        size_t l;
7974
        const char *p;
7975
        char *e;
7976
        int bad_card = 0;
7977

    
7978
        if (!strcmp (optarg, "all")) {
7979
            for (c = soundhw; c->name; ++c) {
7980
                c->enabled = 1;
7981
            }
7982
            return;
7983
        }
7984

    
7985
        p = optarg;
7986
        while (*p) {
7987
            e = strchr (p, ',');
7988
            l = !e ? strlen (p) : (size_t) (e - p);
7989

    
7990
            for (c = soundhw; c->name; ++c) {
7991
                if (!strncmp (c->name, p, l)) {
7992
                    c->enabled = 1;
7993
                    break;
7994
                }
7995
            }
7996

    
7997
            if (!c->name) {
7998
                if (l > 80) {
7999
                    fprintf (stderr,
8000
                             "Unknown sound card name (too big to show)\n");
8001
                }
8002
                else {
8003
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
8004
                             (int) l, p);
8005
                }
8006
                bad_card = 1;
8007
            }
8008
            p += l + (e != NULL);
8009
        }
8010

    
8011
        if (bad_card)
8012
            goto show_valid_cards;
8013
    }
8014
}
8015
#endif
8016

    
8017
#ifdef _WIN32
8018
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8019
{
8020
    exit(STATUS_CONTROL_C_EXIT);
8021
    return TRUE;
8022
}
8023
#endif
8024

    
8025
#define MAX_NET_CLIENTS 32
8026

    
8027
int main(int argc, char **argv)
8028
{
8029
#ifdef CONFIG_GDBSTUB
8030
    int use_gdbstub;
8031
    const char *gdbstub_port;
8032
#endif
8033
    uint32_t boot_devices_bitmap = 0;
8034
    int i;
8035
    int snapshot, linux_boot, net_boot;
8036
    const char *initrd_filename;
8037
    const char *kernel_filename, *kernel_cmdline;
8038
    const char *boot_devices = "";
8039
    DisplayState *ds = &display_state;
8040
    int cyls, heads, secs, translation;
8041
    char net_clients[MAX_NET_CLIENTS][256];
8042
    int nb_net_clients;
8043
    int hda_index;
8044
    int optind;
8045
    const char *r, *optarg;
8046
    CharDriverState *monitor_hd;
8047
    char monitor_device[128];
8048
    char serial_devices[MAX_SERIAL_PORTS][128];
8049
    int serial_device_index;
8050
    char parallel_devices[MAX_PARALLEL_PORTS][128];
8051
    int parallel_device_index;
8052
    const char *loadvm = NULL;
8053
    QEMUMachine *machine;
8054
    const char *cpu_model;
8055
    char usb_devices[MAX_USB_CMDLINE][128];
8056
    int usb_devices_index;
8057
    int fds[2];
8058
    const char *pid_file = NULL;
8059
    VLANState *vlan;
8060

    
8061
    LIST_INIT (&vm_change_state_head);
8062
#ifndef _WIN32
8063
    {
8064
        struct sigaction act;
8065
        sigfillset(&act.sa_mask);
8066
        act.sa_flags = 0;
8067
        act.sa_handler = SIG_IGN;
8068
        sigaction(SIGPIPE, &act, NULL);
8069
    }
8070
#else
8071
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8072
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
8073
       QEMU to run on a single CPU */
8074
    {
8075
        HANDLE h;
8076
        DWORD mask, smask;
8077
        int i;
8078
        h = GetCurrentProcess();
8079
        if (GetProcessAffinityMask(h, &mask, &smask)) {
8080
            for(i = 0; i < 32; i++) {
8081
                if (mask & (1 << i))
8082
                    break;
8083
            }
8084
            if (i != 32) {
8085
                mask = 1 << i;
8086
                SetProcessAffinityMask(h, mask);
8087
            }
8088
        }
8089
    }
8090
#endif
8091

    
8092
    register_machines();
8093
    machine = first_machine;
8094
    cpu_model = NULL;
8095
    initrd_filename = NULL;
8096
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8097
    vga_ram_size = VGA_RAM_SIZE;
8098
#ifdef CONFIG_GDBSTUB
8099
    use_gdbstub = 0;
8100
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
8101
#endif
8102
    snapshot = 0;
8103
    nographic = 0;
8104
    kernel_filename = NULL;
8105
    kernel_cmdline = "";
8106
    cyls = heads = secs = 0;
8107
    translation = BIOS_ATA_TRANSLATION_AUTO;
8108
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8109

    
8110
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8111
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
8112
        serial_devices[i][0] = '\0';
8113
    serial_device_index = 0;
8114

    
8115
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8116
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8117
        parallel_devices[i][0] = '\0';
8118
    parallel_device_index = 0;
8119

    
8120
    usb_devices_index = 0;
8121

    
8122
    nb_net_clients = 0;
8123
    nb_drives = 0;
8124
    nb_drives_opt = 0;
8125
    hda_index = -1;
8126

    
8127
    nb_nics = 0;
8128
    /* default mac address of the first network interface */
8129

    
8130
    optind = 1;
8131
    for(;;) {
8132
        if (optind >= argc)
8133
            break;
8134
        r = argv[optind];
8135
        if (r[0] != '-') {
8136
            hda_index = drive_add(HD_ALIAS, argv[optind++], 0);
8137
        } else {
8138
            const QEMUOption *popt;
8139

    
8140
            optind++;
8141
            /* Treat --foo the same as -foo.  */
8142
            if (r[1] == '-')
8143
                r++;
8144
            popt = qemu_options;
8145
            for(;;) {
8146
                if (!popt->name) {
8147
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
8148
                            argv[0], r);
8149
                    exit(1);
8150
                }
8151
                if (!strcmp(popt->name, r + 1))
8152
                    break;
8153
                popt++;
8154
            }
8155
            if (popt->flags & HAS_ARG) {
8156
                if (optind >= argc) {
8157
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
8158
                            argv[0], r);
8159
                    exit(1);
8160
                }
8161
                optarg = argv[optind++];
8162
            } else {
8163
                optarg = NULL;
8164
            }
8165

    
8166
            switch(popt->index) {
8167
            case QEMU_OPTION_M:
8168
                machine = find_machine(optarg);
8169
                if (!machine) {
8170
                    QEMUMachine *m;
8171
                    printf("Supported machines are:\n");
8172
                    for(m = first_machine; m != NULL; m = m->next) {
8173
                        printf("%-10s %s%s\n",
8174
                               m->name, m->desc,
8175
                               m == first_machine ? " (default)" : "");
8176
                    }
8177
                    exit(*optarg != '?');
8178
                }
8179
                break;
8180
            case QEMU_OPTION_cpu:
8181
                /* hw initialization will check this */
8182
                if (*optarg == '?') {
8183
/* XXX: implement xxx_cpu_list for targets that still miss it */
8184
#if defined(cpu_list)
8185
                    cpu_list(stdout, &fprintf);
8186
#endif
8187
                    exit(0);
8188
                } else {
8189
                    cpu_model = optarg;
8190
                }
8191
                break;
8192
            case QEMU_OPTION_initrd:
8193
                initrd_filename = optarg;
8194
                break;
8195
            case QEMU_OPTION_hda:
8196
                if (cyls == 0)
8197
                    hda_index = drive_add(HD_ALIAS, optarg, 0);
8198
                else
8199
                    hda_index = drive_add(HD_ALIAS
8200
                             ",cyls=%d,heads=%d,secs=%d%s",
8201
                             optarg, 0, cyls, heads, secs,
8202
                             translation == BIOS_ATA_TRANSLATION_LBA ?
8203
                                 ",trans=lba" :
8204
                             translation == BIOS_ATA_TRANSLATION_NONE ?
8205
                                 ",trans=none" : "");
8206
                 break;
8207
            case QEMU_OPTION_hdb:
8208
            case QEMU_OPTION_hdc:
8209
            case QEMU_OPTION_hdd:
8210
                drive_add(HD_ALIAS, optarg, popt->index - QEMU_OPTION_hda);
8211
                break;
8212
            case QEMU_OPTION_drive:
8213
                drive_add("%s", optarg);
8214
                break;
8215
            case QEMU_OPTION_mtdblock:
8216
                drive_add(MTD_ALIAS, optarg);
8217
                break;
8218
            case QEMU_OPTION_sd:
8219
                drive_add("file=\"%s\"," SD_ALIAS, optarg);
8220
                break;
8221
            case QEMU_OPTION_pflash:
8222
                drive_add(PFLASH_ALIAS, optarg);
8223
                break;
8224
            case QEMU_OPTION_snapshot:
8225
                snapshot = 1;
8226
                break;
8227
            case QEMU_OPTION_hdachs:
8228
                {
8229
                    const char *p;
8230
                    p = optarg;
8231
                    cyls = strtol(p, (char **)&p, 0);
8232
                    if (cyls < 1 || cyls > 16383)
8233
                        goto chs_fail;
8234
                    if (*p != ',')
8235
                        goto chs_fail;
8236
                    p++;
8237
                    heads = strtol(p, (char **)&p, 0);
8238
                    if (heads < 1 || heads > 16)
8239
                        goto chs_fail;
8240
                    if (*p != ',')
8241
                        goto chs_fail;
8242
                    p++;
8243
                    secs = strtol(p, (char **)&p, 0);
8244
                    if (secs < 1 || secs > 63)
8245
                        goto chs_fail;
8246
                    if (*p == ',') {
8247
                        p++;
8248
                        if (!strcmp(p, "none"))
8249
                            translation = BIOS_ATA_TRANSLATION_NONE;
8250
                        else if (!strcmp(p, "lba"))
8251
                            translation = BIOS_ATA_TRANSLATION_LBA;
8252
                        else if (!strcmp(p, "auto"))
8253
                            translation = BIOS_ATA_TRANSLATION_AUTO;
8254
                        else
8255
                            goto chs_fail;
8256
                    } else if (*p != '\0') {
8257
                    chs_fail:
8258
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
8259
                        exit(1);
8260
                    }
8261
                    if (hda_index != -1)
8262
                        snprintf(drives_opt[hda_index] +
8263
                                 strlen(drives_opt[hda_index]),
8264
                                 sizeof(drives_opt[0]) -
8265
                                 strlen(drives_opt[hda_index]),
8266
                                 ",cyls=%d,heads=%d,secs=%d%s",
8267
                                 cyls, heads, secs,
8268
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
8269
                                         ",trans=lba" :
8270
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
8271
                                     ",trans=none" : "");
8272
                }
8273
                break;
8274
            case QEMU_OPTION_nographic:
8275
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8276
                pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8277
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8278
                nographic = 1;
8279
                break;
8280
            case QEMU_OPTION_portrait:
8281
                graphic_rotate = 1;
8282
                break;
8283
            case QEMU_OPTION_kernel:
8284
                kernel_filename = optarg;
8285
                break;
8286
            case QEMU_OPTION_append:
8287
                kernel_cmdline = optarg;
8288
                break;
8289
            case QEMU_OPTION_cdrom:
8290
                drive_add("file=\"%s\"," CDROM_ALIAS, optarg);
8291
                break;
8292
            case QEMU_OPTION_boot:
8293
                boot_devices = optarg;
8294
                /* We just do some generic consistency checks */
8295
                {
8296
                    /* Could easily be extended to 64 devices if needed */
8297
                    const char *p;
8298
                    
8299
                    boot_devices_bitmap = 0;
8300
                    for (p = boot_devices; *p != '\0'; p++) {
8301
                        /* Allowed boot devices are:
8302
                         * a b     : floppy disk drives
8303
                         * c ... f : IDE disk drives
8304
                         * g ... m : machine implementation dependant drives
8305
                         * n ... p : network devices
8306
                         * It's up to each machine implementation to check
8307
                         * if the given boot devices match the actual hardware
8308
                         * implementation and firmware features.
8309
                         */
8310
                        if (*p < 'a' || *p > 'q') {
8311
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
8312
                            exit(1);
8313
                        }
8314
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8315
                            fprintf(stderr,
8316
                                    "Boot device '%c' was given twice\n",*p);
8317
                            exit(1);
8318
                        }
8319
                        boot_devices_bitmap |= 1 << (*p - 'a');
8320
                    }
8321
                }
8322
                break;
8323
            case QEMU_OPTION_fda:
8324
            case QEMU_OPTION_fdb:
8325
                drive_add("file=\"%s\"," FD_ALIAS, optarg,
8326
                          popt->index - QEMU_OPTION_fda);
8327
                break;
8328
#ifdef TARGET_I386
8329
            case QEMU_OPTION_no_fd_bootchk:
8330
                fd_bootchk = 0;
8331
                break;
8332
#endif
8333
            case QEMU_OPTION_no_code_copy:
8334
                code_copy_enabled = 0;
8335
                break;
8336
            case QEMU_OPTION_net:
8337
                if (nb_net_clients >= MAX_NET_CLIENTS) {
8338
                    fprintf(stderr, "qemu: too many network clients\n");
8339
                    exit(1);
8340
                }
8341
                pstrcpy(net_clients[nb_net_clients],
8342
                        sizeof(net_clients[0]),
8343
                        optarg);
8344
                nb_net_clients++;
8345
                break;
8346
#ifdef CONFIG_SLIRP
8347
            case QEMU_OPTION_tftp:
8348
                tftp_prefix = optarg;
8349
                break;
8350
            case QEMU_OPTION_bootp:
8351
                bootp_filename = optarg;
8352
                break;
8353
#ifndef _WIN32
8354
            case QEMU_OPTION_smb:
8355
                net_slirp_smb(optarg);
8356
                break;
8357
#endif
8358
            case QEMU_OPTION_redir:
8359
                net_slirp_redir(optarg);
8360
                break;
8361
#endif
8362
#ifdef HAS_AUDIO
8363
            case QEMU_OPTION_audio_help:
8364
                AUD_help ();
8365
                exit (0);
8366
                break;
8367
            case QEMU_OPTION_soundhw:
8368
                select_soundhw (optarg);
8369
                break;
8370
#endif
8371
            case QEMU_OPTION_h:
8372
                help(0);
8373
                break;
8374
            case QEMU_OPTION_m:
8375
                ram_size = atoi(optarg) * 1024 * 1024;
8376
                if (ram_size <= 0)
8377
                    help(1);
8378
                if (ram_size > PHYS_RAM_MAX_SIZE) {
8379
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8380
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
8381
                    exit(1);
8382
                }
8383
                break;
8384
            case QEMU_OPTION_d:
8385
                {
8386
                    int mask;
8387
                    CPULogItem *item;
8388

    
8389
                    mask = cpu_str_to_log_mask(optarg);
8390
                    if (!mask) {
8391
                        printf("Log items (comma separated):\n");
8392
                    for(item = cpu_log_items; item->mask != 0; item++) {
8393
                        printf("%-10s %s\n", item->name, item->help);
8394
                    }
8395
                    exit(1);
8396
                    }
8397
                    cpu_set_log(mask);
8398
                }
8399
                break;
8400
#ifdef CONFIG_GDBSTUB
8401
            case QEMU_OPTION_s:
8402
                use_gdbstub = 1;
8403
                break;
8404
            case QEMU_OPTION_p:
8405
                gdbstub_port = optarg;
8406
                break;
8407
#endif
8408
            case QEMU_OPTION_L:
8409
                bios_dir = optarg;
8410
                break;
8411
            case QEMU_OPTION_bios:
8412
                bios_name = optarg;
8413
                break;
8414
            case QEMU_OPTION_S:
8415
                autostart = 0;
8416
                break;
8417
            case QEMU_OPTION_k:
8418
                keyboard_layout = optarg;
8419
                break;
8420
            case QEMU_OPTION_localtime:
8421
                rtc_utc = 0;
8422
                break;
8423
            case QEMU_OPTION_cirrusvga:
8424
                cirrus_vga_enabled = 1;
8425
                vmsvga_enabled = 0;
8426
                break;
8427
            case QEMU_OPTION_vmsvga:
8428
                cirrus_vga_enabled = 0;
8429
                vmsvga_enabled = 1;
8430
                break;
8431
            case QEMU_OPTION_std_vga:
8432
                cirrus_vga_enabled = 0;
8433
                vmsvga_enabled = 0;
8434
                break;
8435
            case QEMU_OPTION_g:
8436
                {
8437
                    const char *p;
8438
                    int w, h, depth;
8439
                    p = optarg;
8440
                    w = strtol(p, (char **)&p, 10);
8441
                    if (w <= 0) {
8442
                    graphic_error:
8443
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8444
                        exit(1);
8445
                    }
8446
                    if (*p != 'x')
8447
                        goto graphic_error;
8448
                    p++;
8449
                    h = strtol(p, (char **)&p, 10);
8450
                    if (h <= 0)
8451
                        goto graphic_error;
8452
                    if (*p == 'x') {
8453
                        p++;
8454
                        depth = strtol(p, (char **)&p, 10);
8455
                        if (depth != 8 && depth != 15 && depth != 16 &&
8456
                            depth != 24 && depth != 32)
8457
                            goto graphic_error;
8458
                    } else if (*p == '\0') {
8459
                        depth = graphic_depth;
8460
                    } else {
8461
                        goto graphic_error;
8462
                    }
8463

    
8464
                    graphic_width = w;
8465
                    graphic_height = h;
8466
                    graphic_depth = depth;
8467
                }
8468
                break;
8469
            case QEMU_OPTION_echr:
8470
                {
8471
                    char *r;
8472
                    term_escape_char = strtol(optarg, &r, 0);
8473
                    if (r == optarg)
8474
                        printf("Bad argument to echr\n");
8475
                    break;
8476
                }
8477
            case QEMU_OPTION_monitor:
8478
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8479
                break;
8480
            case QEMU_OPTION_serial:
8481
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8482
                    fprintf(stderr, "qemu: too many serial ports\n");
8483
                    exit(1);
8484
                }
8485
                pstrcpy(serial_devices[serial_device_index],
8486
                        sizeof(serial_devices[0]), optarg);
8487
                serial_device_index++;
8488
                break;
8489
            case QEMU_OPTION_parallel:
8490
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8491
                    fprintf(stderr, "qemu: too many parallel ports\n");
8492
                    exit(1);
8493
                }
8494
                pstrcpy(parallel_devices[parallel_device_index],
8495
                        sizeof(parallel_devices[0]), optarg);
8496
                parallel_device_index++;
8497
                break;
8498
            case QEMU_OPTION_loadvm:
8499
                loadvm = optarg;
8500
                break;
8501
            case QEMU_OPTION_full_screen:
8502
                full_screen = 1;
8503
                break;
8504
#ifdef CONFIG_SDL
8505
            case QEMU_OPTION_no_frame:
8506
                no_frame = 1;
8507
                break;
8508
            case QEMU_OPTION_alt_grab:
8509
                alt_grab = 1;
8510
                break;
8511
            case QEMU_OPTION_no_quit:
8512
                no_quit = 1;
8513
                break;
8514
#endif
8515
            case QEMU_OPTION_pidfile:
8516
                pid_file = optarg;
8517
                break;
8518
#ifdef TARGET_I386
8519
            case QEMU_OPTION_win2k_hack:
8520
                win2k_install_hack = 1;
8521
                break;
8522
#endif
8523
#ifdef USE_KQEMU
8524
            case QEMU_OPTION_no_kqemu:
8525
                kqemu_allowed = 0;
8526
                break;
8527
            case QEMU_OPTION_kernel_kqemu:
8528
                kqemu_allowed = 2;
8529
                break;
8530
#endif
8531
            case QEMU_OPTION_usb:
8532
                usb_enabled = 1;
8533
                break;
8534
            case QEMU_OPTION_usbdevice:
8535
                usb_enabled = 1;
8536
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8537
                    fprintf(stderr, "Too many USB devices\n");
8538
                    exit(1);
8539
                }
8540
                pstrcpy(usb_devices[usb_devices_index],
8541
                        sizeof(usb_devices[usb_devices_index]),
8542
                        optarg);
8543
                usb_devices_index++;
8544
                break;
8545
            case QEMU_OPTION_smp:
8546
                smp_cpus = atoi(optarg);
8547
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8548
                    fprintf(stderr, "Invalid number of CPUs\n");
8549
                    exit(1);
8550
                }
8551
                break;
8552
            case QEMU_OPTION_vnc:
8553
                vnc_display = optarg;
8554
                break;
8555
            case QEMU_OPTION_no_acpi:
8556
                acpi_enabled = 0;
8557
                break;
8558
            case QEMU_OPTION_no_reboot:
8559
                no_reboot = 1;
8560
                break;
8561
            case QEMU_OPTION_show_cursor:
8562
                cursor_hide = 0;
8563
                break;
8564
            case QEMU_OPTION_daemonize:
8565
                daemonize = 1;
8566
                break;
8567
            case QEMU_OPTION_option_rom:
8568
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8569
                    fprintf(stderr, "Too many option ROMs\n");
8570
                    exit(1);
8571
                }
8572
                option_rom[nb_option_roms] = optarg;
8573
                nb_option_roms++;
8574
                break;
8575
            case QEMU_OPTION_semihosting:
8576
                semihosting_enabled = 1;
8577
                break;
8578
            case QEMU_OPTION_name:
8579
                qemu_name = optarg;
8580
                break;
8581
#ifdef TARGET_SPARC
8582
            case QEMU_OPTION_prom_env:
8583
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8584
                    fprintf(stderr, "Too many prom variables\n");
8585
                    exit(1);
8586
                }
8587
                prom_envs[nb_prom_envs] = optarg;
8588
                nb_prom_envs++;
8589
                break;
8590
#endif
8591
#ifdef TARGET_ARM
8592
            case QEMU_OPTION_old_param:
8593
                old_param = 1;
8594
#endif
8595
            case QEMU_OPTION_clock:
8596
                configure_alarms(optarg);
8597
                break;
8598
            case QEMU_OPTION_startdate:
8599
                {
8600
                    struct tm tm;
8601
                    if (!strcmp(optarg, "now")) {
8602
                        rtc_start_date = -1;
8603
                    } else {
8604
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8605
                               &tm.tm_year,
8606
                               &tm.tm_mon,
8607
                               &tm.tm_mday,
8608
                               &tm.tm_hour,
8609
                               &tm.tm_min,
8610
                               &tm.tm_sec) == 6) {
8611
                            /* OK */
8612
                        } else if (sscanf(optarg, "%d-%d-%d",
8613
                                          &tm.tm_year,
8614
                                          &tm.tm_mon,
8615
                                          &tm.tm_mday) == 3) {
8616
                            tm.tm_hour = 0;
8617
                            tm.tm_min = 0;
8618
                            tm.tm_sec = 0;
8619
                        } else {
8620
                            goto date_fail;
8621
                        }
8622
                        tm.tm_year -= 1900;
8623
                        tm.tm_mon--;
8624
                        rtc_start_date = mktimegm(&tm);
8625
                        if (rtc_start_date == -1) {
8626
                        date_fail:
8627
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8628
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8629
                            exit(1);
8630
                        }
8631
                    }
8632
                }
8633
                break;
8634
            }
8635
        }
8636
    }
8637

    
8638
#ifndef _WIN32
8639
    if (daemonize && !nographic && vnc_display == NULL) {
8640
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8641
        daemonize = 0;
8642
    }
8643

    
8644
    if (daemonize) {
8645
        pid_t pid;
8646

    
8647
        if (pipe(fds) == -1)
8648
            exit(1);
8649

    
8650
        pid = fork();
8651
        if (pid > 0) {
8652
            uint8_t status;
8653
            ssize_t len;
8654

    
8655
            close(fds[1]);
8656

    
8657
        again:
8658
            len = read(fds[0], &status, 1);
8659
            if (len == -1 && (errno == EINTR))
8660
                goto again;
8661

    
8662
            if (len != 1)
8663
                exit(1);
8664
            else if (status == 1) {
8665
                fprintf(stderr, "Could not acquire pidfile\n");
8666
                exit(1);
8667
            } else
8668
                exit(0);
8669
        } else if (pid < 0)
8670
            exit(1);
8671

    
8672
        setsid();
8673

    
8674
        pid = fork();
8675
        if (pid > 0)
8676
            exit(0);
8677
        else if (pid < 0)
8678
            exit(1);
8679

    
8680
        umask(027);
8681
        chdir("/");
8682

    
8683
        signal(SIGTSTP, SIG_IGN);
8684
        signal(SIGTTOU, SIG_IGN);
8685
        signal(SIGTTIN, SIG_IGN);
8686
    }
8687
#endif
8688

    
8689
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8690
        if (daemonize) {
8691
            uint8_t status = 1;
8692
            write(fds[1], &status, 1);
8693
        } else
8694
            fprintf(stderr, "Could not acquire pid file\n");
8695
        exit(1);
8696
    }
8697

    
8698
#ifdef USE_KQEMU
8699
    if (smp_cpus > 1)
8700
        kqemu_allowed = 0;
8701
#endif
8702
    linux_boot = (kernel_filename != NULL);
8703
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8704

    
8705
    /* XXX: this should not be: some embedded targets just have flash */
8706
    if (!linux_boot && net_boot == 0 &&
8707
        nb_drives_opt == 0)
8708
        help(1);
8709

    
8710
    /* boot to floppy or the default cd if no hard disk defined yet */
8711
    if (!boot_devices[0]) {
8712
        boot_devices = "cad";
8713
    }
8714
    setvbuf(stdout, NULL, _IOLBF, 0);
8715

    
8716
    init_timers();
8717
    init_timer_alarm();
8718
    qemu_aio_init();
8719

    
8720
#ifdef _WIN32
8721
    socket_init();
8722
#endif
8723

    
8724
    /* init network clients */
8725
    if (nb_net_clients == 0) {
8726
        /* if no clients, we use a default config */
8727
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
8728
                "nic");
8729
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
8730
                "user");
8731
        nb_net_clients = 2;
8732
    }
8733

    
8734
    for(i = 0;i < nb_net_clients; i++) {
8735
        if (net_client_init(net_clients[i]) < 0)
8736
            exit(1);
8737
    }
8738
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8739
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8740
            continue;
8741
        if (vlan->nb_guest_devs == 0) {
8742
            fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8743
            exit(1);
8744
        }
8745
        if (vlan->nb_host_devs == 0)
8746
            fprintf(stderr,
8747
                    "Warning: vlan %d is not connected to host network\n",
8748
                    vlan->id);
8749
    }
8750

    
8751
#ifdef TARGET_I386
8752
    /* XXX: this should be moved in the PC machine instantiation code */
8753
    if (net_boot != 0) {
8754
        int netroms = 0;
8755
        for (i = 0; i < nb_nics && i < 4; i++) {
8756
            const char *model = nd_table[i].model;
8757
            char buf[1024];
8758
            if (net_boot & (1 << i)) {
8759
                if (model == NULL)
8760
                    model = "ne2k_pci";
8761
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8762
                if (get_image_size(buf) > 0) {
8763
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8764
                        fprintf(stderr, "Too many option ROMs\n");
8765
                        exit(1);
8766
                    }
8767
                    option_rom[nb_option_roms] = strdup(buf);
8768
                    nb_option_roms++;
8769
                    netroms++;
8770
                }
8771
            }
8772
        }
8773
        if (netroms == 0) {
8774
            fprintf(stderr, "No valid PXE rom found for network device\n");
8775
            exit(1);
8776
        }
8777
    }
8778
#endif
8779

    
8780
    /* init the memory */
8781
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8782

    
8783
    phys_ram_base = qemu_vmalloc(phys_ram_size);
8784
    if (!phys_ram_base) {
8785
        fprintf(stderr, "Could not allocate physical memory\n");
8786
        exit(1);
8787
    }
8788

    
8789
    bdrv_init();
8790

    
8791
    /* we always create the cdrom drive, even if no disk is there */
8792

    
8793
    if (nb_drives_opt < MAX_DRIVES)
8794
        drive_add(CDROM_ALIAS);
8795

    
8796
    /* we always create at least one floppy */
8797

    
8798
    if (nb_drives_opt < MAX_DRIVES)
8799
        drive_add(FD_ALIAS, 0);
8800

    
8801
    /* we always create one sd slot, even if no card is in it */
8802

    
8803
    if (nb_drives_opt < MAX_DRIVES)
8804
        drive_add(SD_ALIAS);
8805

    
8806
    /* open the virtual block devices */
8807

    
8808
    for(i = 0; i < nb_drives_opt; i++)
8809
        if (drive_init(drives_opt[i], snapshot, machine) == -1)
8810
            exit(1);
8811

    
8812
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8813
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8814

    
8815
    init_ioports();
8816

    
8817
    /* terminal init */
8818
    memset(&display_state, 0, sizeof(display_state));
8819
    if (nographic) {
8820
        /* nearly nothing to do */
8821
        dumb_display_init(ds);
8822
    } else if (vnc_display != NULL) {
8823
        vnc_display_init(ds);
8824
        if (vnc_display_open(ds, vnc_display) < 0)
8825
            exit(1);
8826
    } else {
8827
#if defined(CONFIG_SDL)
8828
        sdl_display_init(ds, full_screen, no_frame);
8829
#elif defined(CONFIG_COCOA)
8830
        cocoa_display_init(ds, full_screen);
8831
#else
8832
        dumb_display_init(ds);
8833
#endif
8834
    }
8835

    
8836
    /* Maintain compatibility with multiple stdio monitors */
8837
    if (!strcmp(monitor_device,"stdio")) {
8838
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8839
            if (!strcmp(serial_devices[i],"mon:stdio")) {
8840
                monitor_device[0] = '\0';
8841
                break;
8842
            } else if (!strcmp(serial_devices[i],"stdio")) {
8843
                monitor_device[0] = '\0';
8844
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8845
                break;
8846
            }
8847
        }
8848
    }
8849
    if (monitor_device[0] != '\0') {
8850
        monitor_hd = qemu_chr_open(monitor_device);
8851
        if (!monitor_hd) {
8852
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8853
            exit(1);
8854
        }
8855
        monitor_init(monitor_hd, !nographic);
8856
    }
8857

    
8858
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8859
        const char *devname = serial_devices[i];
8860
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8861
            serial_hds[i] = qemu_chr_open(devname);
8862
            if (!serial_hds[i]) {
8863
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
8864
                        devname);
8865
                exit(1);
8866
            }
8867
            if (strstart(devname, "vc", 0))
8868
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8869
        }
8870
    }
8871

    
8872
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8873
        const char *devname = parallel_devices[i];
8874
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8875
            parallel_hds[i] = qemu_chr_open(devname);
8876
            if (!parallel_hds[i]) {
8877
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8878
                        devname);
8879
                exit(1);
8880
            }
8881
            if (strstart(devname, "vc", 0))
8882
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8883
        }
8884
    }
8885

    
8886
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
8887
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8888

    
8889
    /* init USB devices */
8890
    if (usb_enabled) {
8891
        for(i = 0; i < usb_devices_index; i++) {
8892
            if (usb_device_add(usb_devices[i]) < 0) {
8893
                fprintf(stderr, "Warning: could not add USB device %s\n",
8894
                        usb_devices[i]);
8895
            }
8896
        }
8897
    }
8898

    
8899
    if (display_state.dpy_refresh) {
8900
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8901
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8902
    }
8903

    
8904
#ifdef CONFIG_GDBSTUB
8905
    if (use_gdbstub) {
8906
        /* XXX: use standard host:port notation and modify options
8907
           accordingly. */
8908
        if (gdbserver_start(gdbstub_port) < 0) {
8909
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8910
                    gdbstub_port);
8911
            exit(1);
8912
        }
8913
    }
8914
#endif
8915

    
8916
    if (loadvm)
8917
        do_loadvm(loadvm);
8918

    
8919
    {
8920
        /* XXX: simplify init */
8921
        read_passwords();
8922
        if (autostart) {
8923
            vm_start();
8924
        }
8925
    }
8926

    
8927
    if (daemonize) {
8928
        uint8_t status = 0;
8929
        ssize_t len;
8930
        int fd;
8931

    
8932
    again1:
8933
        len = write(fds[1], &status, 1);
8934
        if (len == -1 && (errno == EINTR))
8935
            goto again1;
8936

    
8937
        if (len != 1)
8938
            exit(1);
8939

    
8940
        TFR(fd = open("/dev/null", O_RDWR));
8941
        if (fd == -1)
8942
            exit(1);
8943

    
8944
        dup2(fd, 0);
8945
        dup2(fd, 1);
8946
        dup2(fd, 2);
8947

    
8948
        close(fd);
8949
    }
8950

    
8951
    main_loop();
8952
    quit_timers();
8953

    
8954
#if !defined(_WIN32)
8955
    /* close network clients */
8956
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8957
        VLANClientState *vc;
8958

    
8959
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8960
            if (vc->fd_read == tap_receive) {
8961
                char ifname[64];
8962
                TAPState *s = vc->opaque;
8963

    
8964
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8965
                    s->down_script[0])
8966
                    launch_script(s->down_script, ifname, s->fd);
8967
            }
8968
    }
8969
    }
8970
#endif
8971
    return 0;
8972
}