Statistics
| Branch: | Revision:

root / vl.c @ 8dd3dca3

History | View | Annotate | Download (220.9 kB)

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

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

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

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

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

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

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

    
117
#include "qemu_socket.h"
118

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

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

    
130
#include "disas.h"
131

    
132
#include "exec-all.h"
133

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
527
    return s;
528
}
529

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

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

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

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

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

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

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

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

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

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

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

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

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

    
604
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
605
}
606

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

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

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

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

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

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

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

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

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

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

    
677
#define QEMU_TIMER_BASE 1000000000LL
678

    
679
#ifdef WIN32
680

    
681
static int64_t clock_freq;
682

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

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

    
702
#else
703

    
704
static int use_rt_clock;
705

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

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

    
737
#endif
738

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

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

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

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

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

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

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

    
801
#define QEMU_TIMER_REALTIME 0
802
#define QEMU_TIMER_VIRTUAL  1
803

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

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

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

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

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

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

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

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

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

    
846
static struct qemu_alarm_timer *alarm_timer;
847

    
848
#ifdef _WIN32
849

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

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

    
860
#else
861

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

    
865
#ifdef __linux__
866

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

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

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

    
877
#endif /* __linux__ */
878

    
879
#endif /* _WIN32 */
880

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

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

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

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

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

    
923
    arg = strdup(opt);
924

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

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

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

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

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

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

    
954
    free(arg);
955

    
956
    if (cur) {
957
        /* Disable remaining timers */
958
        for (i = cur; i < count; i++)
959
            alarm_timers[i].name = NULL;
960
    } else {
961
        show_available_alarms();
962
        exit(1);
963
    }
964
}
965

    
966
QEMUClock *rt_clock;
967
QEMUClock *vm_clock;
968

    
969
static QEMUTimer *active_timers[2];
970

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

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

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

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

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

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

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

    
1023
    qemu_del_timer(ts);
1024

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1197
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1198

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

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

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

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

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

    
1233
    return nearest_delta_us;
1234
}
1235

    
1236
#ifndef _WIN32
1237

    
1238
#if defined(__linux__)
1239

    
1240
#define RTC_FREQ 1024
1241

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

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

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

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

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

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

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

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

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

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

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

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

    
1302
    close(fd);
1303
}
1304

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

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

    
1327
    enable_sigio_timer(rtc_fd);
1328

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

    
1331
    return 0;
1332
}
1333

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

    
1338
    close(rtc_fd);
1339
}
1340

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

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

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

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

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

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

    
1363
        return -1;
1364
    }
1365

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

    
1368
    return 0;
1369
}
1370

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

    
1375
    timer_delete(host_timer);
1376
}
1377

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

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

    
1389
    nearest_delta_us = qemu_next_deadline();
1390

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

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

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

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

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

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

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

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

    
1437
    return 0;
1438
}
1439

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

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

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

    
1450
#ifdef _WIN32
1451

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

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

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

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

    
1470
    timeBeginPeriod(data->period);
1471

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

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

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

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

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

    
1494
    return 0;
1495
}
1496

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

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

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

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

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

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

    
1519
    timeKillEvent(data->timerId);
1520

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

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

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

    
1536
#endif /* _WIN32 */
1537

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

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

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

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

    
1557
    alarm_timer = t;
1558
}
1559

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

    
1566
/***********************************************************/
1567
/* host time/date access */
1568
void qemu_get_timedate(struct tm *tm, int offset)
1569
{
1570
    time_t ti;
1571
    struct tm *ret;
1572

    
1573
    time(&ti);
1574
    ti += offset;
1575
    if (rtc_date_offset == -1) {
1576
        if (rtc_utc)
1577
            ret = gmtime(&ti);
1578
        else
1579
            ret = localtime(&ti);
1580
    } else {
1581
        ti -= rtc_date_offset;
1582
        ret = gmtime(&ti);
1583
    }
1584

    
1585
    memcpy(tm, ret, sizeof(struct tm));
1586
}
1587

    
1588
int qemu_timedate_diff(struct tm *tm)
1589
{
1590
    time_t seconds;
1591

    
1592
    if (rtc_date_offset == -1)
1593
        if (rtc_utc)
1594
            seconds = mktimegm(tm);
1595
        else
1596
            seconds = mktime(tm);
1597
    else
1598
        seconds = mktimegm(tm) + rtc_date_offset;
1599

    
1600
    return seconds - time(NULL);
1601
}
1602

    
1603
/***********************************************************/
1604
/* character device */
1605

    
1606
static void qemu_chr_event(CharDriverState *s, int event)
1607
{
1608
    if (!s->chr_event)
1609
        return;
1610
    s->chr_event(s->handler_opaque, event);
1611
}
1612

    
1613
static void qemu_chr_reset_bh(void *opaque)
1614
{
1615
    CharDriverState *s = opaque;
1616
    qemu_chr_event(s, CHR_EVENT_RESET);
1617
    qemu_bh_delete(s->bh);
1618
    s->bh = NULL;
1619
}
1620

    
1621
void qemu_chr_reset(CharDriverState *s)
1622
{
1623
    if (s->bh == NULL) {
1624
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1625
        qemu_bh_schedule(s->bh);
1626
    }
1627
}
1628

    
1629
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1630
{
1631
    return s->chr_write(s, buf, len);
1632
}
1633

    
1634
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1635
{
1636
    if (!s->chr_ioctl)
1637
        return -ENOTSUP;
1638
    return s->chr_ioctl(s, cmd, arg);
1639
}
1640

    
1641
int qemu_chr_can_read(CharDriverState *s)
1642
{
1643
    if (!s->chr_can_read)
1644
        return 0;
1645
    return s->chr_can_read(s->handler_opaque);
1646
}
1647

    
1648
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1649
{
1650
    s->chr_read(s->handler_opaque, buf, len);
1651
}
1652

    
1653
void qemu_chr_accept_input(CharDriverState *s)
1654
{
1655
    if (s->chr_accept_input)
1656
        s->chr_accept_input(s);
1657
}
1658

    
1659
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1660
{
1661
    char buf[4096];
1662
    va_list ap;
1663
    va_start(ap, fmt);
1664
    vsnprintf(buf, sizeof(buf), fmt, ap);
1665
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1666
    va_end(ap);
1667
}
1668

    
1669
void qemu_chr_send_event(CharDriverState *s, int event)
1670
{
1671
    if (s->chr_send_event)
1672
        s->chr_send_event(s, event);
1673
}
1674

    
1675
void qemu_chr_add_handlers(CharDriverState *s,
1676
                           IOCanRWHandler *fd_can_read,
1677
                           IOReadHandler *fd_read,
1678
                           IOEventHandler *fd_event,
1679
                           void *opaque)
1680
{
1681
    s->chr_can_read = fd_can_read;
1682
    s->chr_read = fd_read;
1683
    s->chr_event = fd_event;
1684
    s->handler_opaque = opaque;
1685
    if (s->chr_update_read_handler)
1686
        s->chr_update_read_handler(s);
1687
}
1688

    
1689
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1690
{
1691
    return len;
1692
}
1693

    
1694
static CharDriverState *qemu_chr_open_null(void)
1695
{
1696
    CharDriverState *chr;
1697

    
1698
    chr = qemu_mallocz(sizeof(CharDriverState));
1699
    if (!chr)
1700
        return NULL;
1701
    chr->chr_write = null_chr_write;
1702
    return chr;
1703
}
1704

    
1705
/* MUX driver for serial I/O splitting */
1706
static int term_timestamps;
1707
static int64_t term_timestamps_start;
1708
#define MAX_MUX 4
1709
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
1710
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1711
typedef struct {
1712
    IOCanRWHandler *chr_can_read[MAX_MUX];
1713
    IOReadHandler *chr_read[MAX_MUX];
1714
    IOEventHandler *chr_event[MAX_MUX];
1715
    void *ext_opaque[MAX_MUX];
1716
    CharDriverState *drv;
1717
    unsigned char buffer[MUX_BUFFER_SIZE];
1718
    int prod;
1719
    int cons;
1720
    int mux_cnt;
1721
    int term_got_escape;
1722
    int max_size;
1723
} MuxDriver;
1724

    
1725

    
1726
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1727
{
1728
    MuxDriver *d = chr->opaque;
1729
    int ret;
1730
    if (!term_timestamps) {
1731
        ret = d->drv->chr_write(d->drv, buf, len);
1732
    } else {
1733
        int i;
1734

    
1735
        ret = 0;
1736
        for(i = 0; i < len; i++) {
1737
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1738
            if (buf[i] == '\n') {
1739
                char buf1[64];
1740
                int64_t ti;
1741
                int secs;
1742

    
1743
                ti = get_clock();
1744
                if (term_timestamps_start == -1)
1745
                    term_timestamps_start = ti;
1746
                ti -= term_timestamps_start;
1747
                secs = ti / 1000000000;
1748
                snprintf(buf1, sizeof(buf1),
1749
                         "[%02d:%02d:%02d.%03d] ",
1750
                         secs / 3600,
1751
                         (secs / 60) % 60,
1752
                         secs % 60,
1753
                         (int)((ti / 1000000) % 1000));
1754
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1755
            }
1756
        }
1757
    }
1758
    return ret;
1759
}
1760

    
1761
static char *mux_help[] = {
1762
    "% h    print this help\n\r",
1763
    "% x    exit emulator\n\r",
1764
    "% s    save disk data back to file (if -snapshot)\n\r",
1765
    "% t    toggle console timestamps\n\r"
1766
    "% b    send break (magic sysrq)\n\r",
1767
    "% c    switch between console and monitor\n\r",
1768
    "% %  sends %\n\r",
1769
    NULL
1770
};
1771

    
1772
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1773
static void mux_print_help(CharDriverState *chr)
1774
{
1775
    int i, j;
1776
    char ebuf[15] = "Escape-Char";
1777
    char cbuf[50] = "\n\r";
1778

    
1779
    if (term_escape_char > 0 && term_escape_char < 26) {
1780
        sprintf(cbuf,"\n\r");
1781
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1782
    } else {
1783
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1784
            term_escape_char);
1785
    }
1786
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1787
    for (i = 0; mux_help[i] != NULL; i++) {
1788
        for (j=0; mux_help[i][j] != '\0'; j++) {
1789
            if (mux_help[i][j] == '%')
1790
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1791
            else
1792
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1793
        }
1794
    }
1795
}
1796

    
1797
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1798
{
1799
    if (d->term_got_escape) {
1800
        d->term_got_escape = 0;
1801
        if (ch == term_escape_char)
1802
            goto send_char;
1803
        switch(ch) {
1804
        case '?':
1805
        case 'h':
1806
            mux_print_help(chr);
1807
            break;
1808
        case 'x':
1809
            {
1810
                 char *term =  "QEMU: Terminated\n\r";
1811
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1812
                 exit(0);
1813
                 break;
1814
            }
1815
        case 's':
1816
            {
1817
                int i;
1818
                for (i = 0; i < nb_drives; i++) {
1819
                        bdrv_commit(drives_table[i].bdrv);
1820
                }
1821
            }
1822
            break;
1823
        case 'b':
1824
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1825
            break;
1826
        case 'c':
1827
            /* Switch to the next registered device */
1828
            chr->focus++;
1829
            if (chr->focus >= d->mux_cnt)
1830
                chr->focus = 0;
1831
            break;
1832
       case 't':
1833
           term_timestamps = !term_timestamps;
1834
           term_timestamps_start = -1;
1835
           break;
1836
        }
1837
    } else if (ch == term_escape_char) {
1838
        d->term_got_escape = 1;
1839
    } else {
1840
    send_char:
1841
        return 1;
1842
    }
1843
    return 0;
1844
}
1845

    
1846
static void mux_chr_accept_input(CharDriverState *chr)
1847
{
1848
    int m = chr->focus;
1849
    MuxDriver *d = chr->opaque;
1850

    
1851
    while (d->prod != d->cons &&
1852
           d->chr_can_read[m] &&
1853
           d->chr_can_read[m](d->ext_opaque[m])) {
1854
        d->chr_read[m](d->ext_opaque[m],
1855
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1856
    }
1857
}
1858

    
1859
static int mux_chr_can_read(void *opaque)
1860
{
1861
    CharDriverState *chr = opaque;
1862
    MuxDriver *d = chr->opaque;
1863

    
1864
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1865
        return 1;
1866
    if (d->chr_can_read[chr->focus])
1867
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1868
    return 0;
1869
}
1870

    
1871
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1872
{
1873
    CharDriverState *chr = opaque;
1874
    MuxDriver *d = chr->opaque;
1875
    int m = chr->focus;
1876
    int i;
1877

    
1878
    mux_chr_accept_input (opaque);
1879

    
1880
    for(i = 0; i < size; i++)
1881
        if (mux_proc_byte(chr, d, buf[i])) {
1882
            if (d->prod == d->cons &&
1883
                d->chr_can_read[m] &&
1884
                d->chr_can_read[m](d->ext_opaque[m]))
1885
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1886
            else
1887
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1888
        }
1889
}
1890

    
1891
static void mux_chr_event(void *opaque, int event)
1892
{
1893
    CharDriverState *chr = opaque;
1894
    MuxDriver *d = chr->opaque;
1895
    int i;
1896

    
1897
    /* Send the event to all registered listeners */
1898
    for (i = 0; i < d->mux_cnt; i++)
1899
        if (d->chr_event[i])
1900
            d->chr_event[i](d->ext_opaque[i], event);
1901
}
1902

    
1903
static void mux_chr_update_read_handler(CharDriverState *chr)
1904
{
1905
    MuxDriver *d = chr->opaque;
1906

    
1907
    if (d->mux_cnt >= MAX_MUX) {
1908
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1909
        return;
1910
    }
1911
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1912
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1913
    d->chr_read[d->mux_cnt] = chr->chr_read;
1914
    d->chr_event[d->mux_cnt] = chr->chr_event;
1915
    /* Fix up the real driver with mux routines */
1916
    if (d->mux_cnt == 0) {
1917
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1918
                              mux_chr_event, chr);
1919
    }
1920
    chr->focus = d->mux_cnt;
1921
    d->mux_cnt++;
1922
}
1923

    
1924
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1925
{
1926
    CharDriverState *chr;
1927
    MuxDriver *d;
1928

    
1929
    chr = qemu_mallocz(sizeof(CharDriverState));
1930
    if (!chr)
1931
        return NULL;
1932
    d = qemu_mallocz(sizeof(MuxDriver));
1933
    if (!d) {
1934
        free(chr);
1935
        return NULL;
1936
    }
1937

    
1938
    chr->opaque = d;
1939
    d->drv = drv;
1940
    chr->focus = -1;
1941
    chr->chr_write = mux_chr_write;
1942
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1943
    chr->chr_accept_input = mux_chr_accept_input;
1944
    return chr;
1945
}
1946

    
1947

    
1948
#ifdef _WIN32
1949

    
1950
static void socket_cleanup(void)
1951
{
1952
    WSACleanup();
1953
}
1954

    
1955
static int socket_init(void)
1956
{
1957
    WSADATA Data;
1958
    int ret, err;
1959

    
1960
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1961
    if (ret != 0) {
1962
        err = WSAGetLastError();
1963
        fprintf(stderr, "WSAStartup: %d\n", err);
1964
        return -1;
1965
    }
1966
    atexit(socket_cleanup);
1967
    return 0;
1968
}
1969

    
1970
static int send_all(int fd, const uint8_t *buf, int len1)
1971
{
1972
    int ret, len;
1973

    
1974
    len = len1;
1975
    while (len > 0) {
1976
        ret = send(fd, buf, len, 0);
1977
        if (ret < 0) {
1978
            int errno;
1979
            errno = WSAGetLastError();
1980
            if (errno != WSAEWOULDBLOCK) {
1981
                return -1;
1982
            }
1983
        } else if (ret == 0) {
1984
            break;
1985
        } else {
1986
            buf += ret;
1987
            len -= ret;
1988
        }
1989
    }
1990
    return len1 - len;
1991
}
1992

    
1993
void socket_set_nonblock(int fd)
1994
{
1995
    unsigned long opt = 1;
1996
    ioctlsocket(fd, FIONBIO, &opt);
1997
}
1998

    
1999
#else
2000

    
2001
static int unix_write(int fd, const uint8_t *buf, int len1)
2002
{
2003
    int ret, len;
2004

    
2005
    len = len1;
2006
    while (len > 0) {
2007
        ret = write(fd, buf, len);
2008
        if (ret < 0) {
2009
            if (errno != EINTR && errno != EAGAIN)
2010
                return -1;
2011
        } else if (ret == 0) {
2012
            break;
2013
        } else {
2014
            buf += ret;
2015
            len -= ret;
2016
        }
2017
    }
2018
    return len1 - len;
2019
}
2020

    
2021
static inline int send_all(int fd, const uint8_t *buf, int len1)
2022
{
2023
    return unix_write(fd, buf, len1);
2024
}
2025

    
2026
void socket_set_nonblock(int fd)
2027
{
2028
    fcntl(fd, F_SETFL, O_NONBLOCK);
2029
}
2030
#endif /* !_WIN32 */
2031

    
2032
#ifndef _WIN32
2033

    
2034
typedef struct {
2035
    int fd_in, fd_out;
2036
    int max_size;
2037
} FDCharDriver;
2038

    
2039
#define STDIO_MAX_CLIENTS 1
2040
static int stdio_nb_clients = 0;
2041

    
2042
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2043
{
2044
    FDCharDriver *s = chr->opaque;
2045
    return unix_write(s->fd_out, buf, len);
2046
}
2047

    
2048
static int fd_chr_read_poll(void *opaque)
2049
{
2050
    CharDriverState *chr = opaque;
2051
    FDCharDriver *s = chr->opaque;
2052

    
2053
    s->max_size = qemu_chr_can_read(chr);
2054
    return s->max_size;
2055
}
2056

    
2057
static void fd_chr_read(void *opaque)
2058
{
2059
    CharDriverState *chr = opaque;
2060
    FDCharDriver *s = chr->opaque;
2061
    int size, len;
2062
    uint8_t buf[1024];
2063

    
2064
    len = sizeof(buf);
2065
    if (len > s->max_size)
2066
        len = s->max_size;
2067
    if (len == 0)
2068
        return;
2069
    size = read(s->fd_in, buf, len);
2070
    if (size == 0) {
2071
        /* FD has been closed. Remove it from the active list.  */
2072
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2073
        return;
2074
    }
2075
    if (size > 0) {
2076
        qemu_chr_read(chr, buf, size);
2077
    }
2078
}
2079

    
2080
static void fd_chr_update_read_handler(CharDriverState *chr)
2081
{
2082
    FDCharDriver *s = chr->opaque;
2083

    
2084
    if (s->fd_in >= 0) {
2085
        if (nographic && s->fd_in == 0) {
2086
        } else {
2087
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2088
                                 fd_chr_read, NULL, chr);
2089
        }
2090
    }
2091
}
2092

    
2093
static void fd_chr_close(struct CharDriverState *chr)
2094
{
2095
    FDCharDriver *s = chr->opaque;
2096

    
2097
    if (s->fd_in >= 0) {
2098
        if (nographic && s->fd_in == 0) {
2099
        } else {
2100
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2101
        }
2102
    }
2103

    
2104
    qemu_free(s);
2105
}
2106

    
2107
/* open a character device to a unix fd */
2108
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2109
{
2110
    CharDriverState *chr;
2111
    FDCharDriver *s;
2112

    
2113
    chr = qemu_mallocz(sizeof(CharDriverState));
2114
    if (!chr)
2115
        return NULL;
2116
    s = qemu_mallocz(sizeof(FDCharDriver));
2117
    if (!s) {
2118
        free(chr);
2119
        return NULL;
2120
    }
2121
    s->fd_in = fd_in;
2122
    s->fd_out = fd_out;
2123
    chr->opaque = s;
2124
    chr->chr_write = fd_chr_write;
2125
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2126
    chr->chr_close = fd_chr_close;
2127

    
2128
    qemu_chr_reset(chr);
2129

    
2130
    return chr;
2131
}
2132

    
2133
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2134
{
2135
    int fd_out;
2136

    
2137
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2138
    if (fd_out < 0)
2139
        return NULL;
2140
    return qemu_chr_open_fd(-1, fd_out);
2141
}
2142

    
2143
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2144
{
2145
    int fd_in, fd_out;
2146
    char filename_in[256], filename_out[256];
2147

    
2148
    snprintf(filename_in, 256, "%s.in", filename);
2149
    snprintf(filename_out, 256, "%s.out", filename);
2150
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2151
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2152
    if (fd_in < 0 || fd_out < 0) {
2153
        if (fd_in >= 0)
2154
            close(fd_in);
2155
        if (fd_out >= 0)
2156
            close(fd_out);
2157
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2158
        if (fd_in < 0)
2159
            return NULL;
2160
    }
2161
    return qemu_chr_open_fd(fd_in, fd_out);
2162
}
2163

    
2164

    
2165
/* for STDIO, we handle the case where several clients use it
2166
   (nographic mode) */
2167

    
2168
#define TERM_FIFO_MAX_SIZE 1
2169

    
2170
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2171
static int term_fifo_size;
2172

    
2173
static int stdio_read_poll(void *opaque)
2174
{
2175
    CharDriverState *chr = opaque;
2176

    
2177
    /* try to flush the queue if needed */
2178
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2179
        qemu_chr_read(chr, term_fifo, 1);
2180
        term_fifo_size = 0;
2181
    }
2182
    /* see if we can absorb more chars */
2183
    if (term_fifo_size == 0)
2184
        return 1;
2185
    else
2186
        return 0;
2187
}
2188

    
2189
static void stdio_read(void *opaque)
2190
{
2191
    int size;
2192
    uint8_t buf[1];
2193
    CharDriverState *chr = opaque;
2194

    
2195
    size = read(0, buf, 1);
2196
    if (size == 0) {
2197
        /* stdin has been closed. Remove it from the active list.  */
2198
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2199
        return;
2200
    }
2201
    if (size > 0) {
2202
        if (qemu_chr_can_read(chr) > 0) {
2203
            qemu_chr_read(chr, buf, 1);
2204
        } else if (term_fifo_size == 0) {
2205
            term_fifo[term_fifo_size++] = buf[0];
2206
        }
2207
    }
2208
}
2209

    
2210
/* init terminal so that we can grab keys */
2211
static struct termios oldtty;
2212
static int old_fd0_flags;
2213
static int term_atexit_done;
2214

    
2215
static void term_exit(void)
2216
{
2217
    tcsetattr (0, TCSANOW, &oldtty);
2218
    fcntl(0, F_SETFL, old_fd0_flags);
2219
}
2220

    
2221
static void term_init(void)
2222
{
2223
    struct termios tty;
2224

    
2225
    tcgetattr (0, &tty);
2226
    oldtty = tty;
2227
    old_fd0_flags = fcntl(0, F_GETFL);
2228

    
2229
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2230
                          |INLCR|IGNCR|ICRNL|IXON);
2231
    tty.c_oflag |= OPOST;
2232
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2233
    /* if graphical mode, we allow Ctrl-C handling */
2234
    if (nographic)
2235
        tty.c_lflag &= ~ISIG;
2236
    tty.c_cflag &= ~(CSIZE|PARENB);
2237
    tty.c_cflag |= CS8;
2238
    tty.c_cc[VMIN] = 1;
2239
    tty.c_cc[VTIME] = 0;
2240

    
2241
    tcsetattr (0, TCSANOW, &tty);
2242

    
2243
    if (!term_atexit_done++)
2244
        atexit(term_exit);
2245

    
2246
    fcntl(0, F_SETFL, O_NONBLOCK);
2247
}
2248

    
2249
static void qemu_chr_close_stdio(struct CharDriverState *chr)
2250
{
2251
    term_exit();
2252
    stdio_nb_clients--;
2253
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2254
    fd_chr_close(chr);
2255
}
2256

    
2257
static CharDriverState *qemu_chr_open_stdio(void)
2258
{
2259
    CharDriverState *chr;
2260

    
2261
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2262
        return NULL;
2263
    chr = qemu_chr_open_fd(0, 1);
2264
    chr->chr_close = qemu_chr_close_stdio;
2265
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2266
    stdio_nb_clients++;
2267
    term_init();
2268

    
2269
    return chr;
2270
}
2271

    
2272
#if defined(__linux__) || defined(__sun__)
2273
static CharDriverState *qemu_chr_open_pty(void)
2274
{
2275
    struct termios tty;
2276
    char slave_name[1024];
2277
    int master_fd, slave_fd;
2278

    
2279
#if defined(__linux__)
2280
    /* Not satisfying */
2281
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2282
        return NULL;
2283
    }
2284
#endif
2285

    
2286
    /* Disabling local echo and line-buffered output */
2287
    tcgetattr (master_fd, &tty);
2288
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2289
    tty.c_cc[VMIN] = 1;
2290
    tty.c_cc[VTIME] = 0;
2291
    tcsetattr (master_fd, TCSAFLUSH, &tty);
2292

    
2293
    fprintf(stderr, "char device redirected to %s\n", slave_name);
2294
    return qemu_chr_open_fd(master_fd, master_fd);
2295
}
2296

    
2297
static void tty_serial_init(int fd, int speed,
2298
                            int parity, int data_bits, int stop_bits)
2299
{
2300
    struct termios tty;
2301
    speed_t spd;
2302

    
2303
#if 0
2304
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2305
           speed, parity, data_bits, stop_bits);
2306
#endif
2307
    tcgetattr (fd, &tty);
2308

    
2309
#define MARGIN 1.1
2310
    if (speed <= 50 * MARGIN)
2311
        spd = B50;
2312
    else if (speed <= 75 * MARGIN)
2313
        spd = B75;
2314
    else if (speed <= 300 * MARGIN)
2315
        spd = B300;
2316
    else if (speed <= 600 * MARGIN)
2317
        spd = B600;
2318
    else if (speed <= 1200 * MARGIN)
2319
        spd = B1200;
2320
    else if (speed <= 2400 * MARGIN)
2321
        spd = B2400;
2322
    else if (speed <= 4800 * MARGIN)
2323
        spd = B4800;
2324
    else if (speed <= 9600 * MARGIN)
2325
        spd = B9600;
2326
    else if (speed <= 19200 * MARGIN)
2327
        spd = B19200;
2328
    else if (speed <= 38400 * MARGIN)
2329
        spd = B38400;
2330
    else if (speed <= 57600 * MARGIN)
2331
        spd = B57600;
2332
    else if (speed <= 115200 * MARGIN)
2333
        spd = B115200;
2334
    else
2335
        spd = B115200;
2336

    
2337
    cfsetispeed(&tty, spd);
2338
    cfsetospeed(&tty, spd);
2339

    
2340
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2341
                          |INLCR|IGNCR|ICRNL|IXON);
2342
    tty.c_oflag |= OPOST;
2343
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2344
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2345
    switch(data_bits) {
2346
    default:
2347
    case 8:
2348
        tty.c_cflag |= CS8;
2349
        break;
2350
    case 7:
2351
        tty.c_cflag |= CS7;
2352
        break;
2353
    case 6:
2354
        tty.c_cflag |= CS6;
2355
        break;
2356
    case 5:
2357
        tty.c_cflag |= CS5;
2358
        break;
2359
    }
2360
    switch(parity) {
2361
    default:
2362
    case 'N':
2363
        break;
2364
    case 'E':
2365
        tty.c_cflag |= PARENB;
2366
        break;
2367
    case 'O':
2368
        tty.c_cflag |= PARENB | PARODD;
2369
        break;
2370
    }
2371
    if (stop_bits == 2)
2372
        tty.c_cflag |= CSTOPB;
2373

    
2374
    tcsetattr (fd, TCSANOW, &tty);
2375
}
2376

    
2377
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2378
{
2379
    FDCharDriver *s = chr->opaque;
2380

    
2381
    switch(cmd) {
2382
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2383
        {
2384
            QEMUSerialSetParams *ssp = arg;
2385
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2386
                            ssp->data_bits, ssp->stop_bits);
2387
        }
2388
        break;
2389
    case CHR_IOCTL_SERIAL_SET_BREAK:
2390
        {
2391
            int enable = *(int *)arg;
2392
            if (enable)
2393
                tcsendbreak(s->fd_in, 1);
2394
        }
2395
        break;
2396
    default:
2397
        return -ENOTSUP;
2398
    }
2399
    return 0;
2400
}
2401

    
2402
static CharDriverState *qemu_chr_open_tty(const char *filename)
2403
{
2404
    CharDriverState *chr;
2405
    int fd;
2406

    
2407
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2408
    fcntl(fd, F_SETFL, O_NONBLOCK);
2409
    tty_serial_init(fd, 115200, 'N', 8, 1);
2410
    chr = qemu_chr_open_fd(fd, fd);
2411
    if (!chr) {
2412
        close(fd);
2413
        return NULL;
2414
    }
2415
    chr->chr_ioctl = tty_serial_ioctl;
2416
    qemu_chr_reset(chr);
2417
    return chr;
2418
}
2419
#else  /* ! __linux__ && ! __sun__ */
2420
static CharDriverState *qemu_chr_open_pty(void)
2421
{
2422
    return NULL;
2423
}
2424
#endif /* __linux__ || __sun__ */
2425

    
2426
#if defined(__linux__)
2427
typedef struct {
2428
    int fd;
2429
    int mode;
2430
} ParallelCharDriver;
2431

    
2432
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2433
{
2434
    if (s->mode != mode) {
2435
        int m = mode;
2436
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2437
            return 0;
2438
        s->mode = mode;
2439
    }
2440
    return 1;
2441
}
2442

    
2443
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2444
{
2445
    ParallelCharDriver *drv = chr->opaque;
2446
    int fd = drv->fd;
2447
    uint8_t b;
2448

    
2449
    switch(cmd) {
2450
    case CHR_IOCTL_PP_READ_DATA:
2451
        if (ioctl(fd, PPRDATA, &b) < 0)
2452
            return -ENOTSUP;
2453
        *(uint8_t *)arg = b;
2454
        break;
2455
    case CHR_IOCTL_PP_WRITE_DATA:
2456
        b = *(uint8_t *)arg;
2457
        if (ioctl(fd, PPWDATA, &b) < 0)
2458
            return -ENOTSUP;
2459
        break;
2460
    case CHR_IOCTL_PP_READ_CONTROL:
2461
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2462
            return -ENOTSUP;
2463
        /* Linux gives only the lowest bits, and no way to know data
2464
           direction! For better compatibility set the fixed upper
2465
           bits. */
2466
        *(uint8_t *)arg = b | 0xc0;
2467
        break;
2468
    case CHR_IOCTL_PP_WRITE_CONTROL:
2469
        b = *(uint8_t *)arg;
2470
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2471
            return -ENOTSUP;
2472
        break;
2473
    case CHR_IOCTL_PP_READ_STATUS:
2474
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2475
            return -ENOTSUP;
2476
        *(uint8_t *)arg = b;
2477
        break;
2478
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2479
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2480
            struct ParallelIOArg *parg = arg;
2481
            int n = read(fd, parg->buffer, parg->count);
2482
            if (n != parg->count) {
2483
                return -EIO;
2484
            }
2485
        }
2486
        break;
2487
    case CHR_IOCTL_PP_EPP_READ:
2488
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2489
            struct ParallelIOArg *parg = arg;
2490
            int n = read(fd, parg->buffer, parg->count);
2491
            if (n != parg->count) {
2492
                return -EIO;
2493
            }
2494
        }
2495
        break;
2496
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2497
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2498
            struct ParallelIOArg *parg = arg;
2499
            int n = write(fd, parg->buffer, parg->count);
2500
            if (n != parg->count) {
2501
                return -EIO;
2502
            }
2503
        }
2504
        break;
2505
    case CHR_IOCTL_PP_EPP_WRITE:
2506
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2507
            struct ParallelIOArg *parg = arg;
2508
            int n = write(fd, parg->buffer, parg->count);
2509
            if (n != parg->count) {
2510
                return -EIO;
2511
            }
2512
        }
2513
        break;
2514
    default:
2515
        return -ENOTSUP;
2516
    }
2517
    return 0;
2518
}
2519

    
2520
static void pp_close(CharDriverState *chr)
2521
{
2522
    ParallelCharDriver *drv = chr->opaque;
2523
    int fd = drv->fd;
2524

    
2525
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2526
    ioctl(fd, PPRELEASE);
2527
    close(fd);
2528
    qemu_free(drv);
2529
}
2530

    
2531
static CharDriverState *qemu_chr_open_pp(const char *filename)
2532
{
2533
    CharDriverState *chr;
2534
    ParallelCharDriver *drv;
2535
    int fd;
2536

    
2537
    TFR(fd = open(filename, O_RDWR));
2538
    if (fd < 0)
2539
        return NULL;
2540

    
2541
    if (ioctl(fd, PPCLAIM) < 0) {
2542
        close(fd);
2543
        return NULL;
2544
    }
2545

    
2546
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2547
    if (!drv) {
2548
        close(fd);
2549
        return NULL;
2550
    }
2551
    drv->fd = fd;
2552
    drv->mode = IEEE1284_MODE_COMPAT;
2553

    
2554
    chr = qemu_mallocz(sizeof(CharDriverState));
2555
    if (!chr) {
2556
        qemu_free(drv);
2557
        close(fd);
2558
        return NULL;
2559
    }
2560
    chr->chr_write = null_chr_write;
2561
    chr->chr_ioctl = pp_ioctl;
2562
    chr->chr_close = pp_close;
2563
    chr->opaque = drv;
2564

    
2565
    qemu_chr_reset(chr);
2566

    
2567
    return chr;
2568
}
2569
#endif /* __linux__ */
2570

    
2571
#else /* _WIN32 */
2572

    
2573
typedef struct {
2574
    int max_size;
2575
    HANDLE hcom, hrecv, hsend;
2576
    OVERLAPPED orecv, osend;
2577
    BOOL fpipe;
2578
    DWORD len;
2579
} WinCharState;
2580

    
2581
#define NSENDBUF 2048
2582
#define NRECVBUF 2048
2583
#define MAXCONNECT 1
2584
#define NTIMEOUT 5000
2585

    
2586
static int win_chr_poll(void *opaque);
2587
static int win_chr_pipe_poll(void *opaque);
2588

    
2589
static void win_chr_close(CharDriverState *chr)
2590
{
2591
    WinCharState *s = chr->opaque;
2592

    
2593
    if (s->hsend) {
2594
        CloseHandle(s->hsend);
2595
        s->hsend = NULL;
2596
    }
2597
    if (s->hrecv) {
2598
        CloseHandle(s->hrecv);
2599
        s->hrecv = NULL;
2600
    }
2601
    if (s->hcom) {
2602
        CloseHandle(s->hcom);
2603
        s->hcom = NULL;
2604
    }
2605
    if (s->fpipe)
2606
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2607
    else
2608
        qemu_del_polling_cb(win_chr_poll, chr);
2609
}
2610

    
2611
static int win_chr_init(CharDriverState *chr, const char *filename)
2612
{
2613
    WinCharState *s = chr->opaque;
2614
    COMMCONFIG comcfg;
2615
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2616
    COMSTAT comstat;
2617
    DWORD size;
2618
    DWORD err;
2619

    
2620
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2621
    if (!s->hsend) {
2622
        fprintf(stderr, "Failed CreateEvent\n");
2623
        goto fail;
2624
    }
2625
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2626
    if (!s->hrecv) {
2627
        fprintf(stderr, "Failed CreateEvent\n");
2628
        goto fail;
2629
    }
2630

    
2631
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2632
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2633
    if (s->hcom == INVALID_HANDLE_VALUE) {
2634
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2635
        s->hcom = NULL;
2636
        goto fail;
2637
    }
2638

    
2639
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2640
        fprintf(stderr, "Failed SetupComm\n");
2641
        goto fail;
2642
    }
2643

    
2644
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2645
    size = sizeof(COMMCONFIG);
2646
    GetDefaultCommConfig(filename, &comcfg, &size);
2647
    comcfg.dcb.DCBlength = sizeof(DCB);
2648
    CommConfigDialog(filename, NULL, &comcfg);
2649

    
2650
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2651
        fprintf(stderr, "Failed SetCommState\n");
2652
        goto fail;
2653
    }
2654

    
2655
    if (!SetCommMask(s->hcom, EV_ERR)) {
2656
        fprintf(stderr, "Failed SetCommMask\n");
2657
        goto fail;
2658
    }
2659

    
2660
    cto.ReadIntervalTimeout = MAXDWORD;
2661
    if (!SetCommTimeouts(s->hcom, &cto)) {
2662
        fprintf(stderr, "Failed SetCommTimeouts\n");
2663
        goto fail;
2664
    }
2665

    
2666
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2667
        fprintf(stderr, "Failed ClearCommError\n");
2668
        goto fail;
2669
    }
2670
    qemu_add_polling_cb(win_chr_poll, chr);
2671
    return 0;
2672

    
2673
 fail:
2674
    win_chr_close(chr);
2675
    return -1;
2676
}
2677

    
2678
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2679
{
2680
    WinCharState *s = chr->opaque;
2681
    DWORD len, ret, size, err;
2682

    
2683
    len = len1;
2684
    ZeroMemory(&s->osend, sizeof(s->osend));
2685
    s->osend.hEvent = s->hsend;
2686
    while (len > 0) {
2687
        if (s->hsend)
2688
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2689
        else
2690
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2691
        if (!ret) {
2692
            err = GetLastError();
2693
            if (err == ERROR_IO_PENDING) {
2694
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2695
                if (ret) {
2696
                    buf += size;
2697
                    len -= size;
2698
                } else {
2699
                    break;
2700
                }
2701
            } else {
2702
                break;
2703
            }
2704
        } else {
2705
            buf += size;
2706
            len -= size;
2707
        }
2708
    }
2709
    return len1 - len;
2710
}
2711

    
2712
static int win_chr_read_poll(CharDriverState *chr)
2713
{
2714
    WinCharState *s = chr->opaque;
2715

    
2716
    s->max_size = qemu_chr_can_read(chr);
2717
    return s->max_size;
2718
}
2719

    
2720
static void win_chr_readfile(CharDriverState *chr)
2721
{
2722
    WinCharState *s = chr->opaque;
2723
    int ret, err;
2724
    uint8_t buf[1024];
2725
    DWORD size;
2726

    
2727
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2728
    s->orecv.hEvent = s->hrecv;
2729
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2730
    if (!ret) {
2731
        err = GetLastError();
2732
        if (err == ERROR_IO_PENDING) {
2733
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2734
        }
2735
    }
2736

    
2737
    if (size > 0) {
2738
        qemu_chr_read(chr, buf, size);
2739
    }
2740
}
2741

    
2742
static void win_chr_read(CharDriverState *chr)
2743
{
2744
    WinCharState *s = chr->opaque;
2745

    
2746
    if (s->len > s->max_size)
2747
        s->len = s->max_size;
2748
    if (s->len == 0)
2749
        return;
2750

    
2751
    win_chr_readfile(chr);
2752
}
2753

    
2754
static int win_chr_poll(void *opaque)
2755
{
2756
    CharDriverState *chr = opaque;
2757
    WinCharState *s = chr->opaque;
2758
    COMSTAT status;
2759
    DWORD comerr;
2760

    
2761
    ClearCommError(s->hcom, &comerr, &status);
2762
    if (status.cbInQue > 0) {
2763
        s->len = status.cbInQue;
2764
        win_chr_read_poll(chr);
2765
        win_chr_read(chr);
2766
        return 1;
2767
    }
2768
    return 0;
2769
}
2770

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

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

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

    
2797
static int win_chr_pipe_poll(void *opaque)
2798
{
2799
    CharDriverState *chr = opaque;
2800
    WinCharState *s = chr->opaque;
2801
    DWORD size;
2802

    
2803
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2804
    if (size > 0) {
2805
        s->len = size;
2806
        win_chr_read_poll(chr);
2807
        win_chr_read(chr);
2808
        return 1;
2809
    }
2810
    return 0;
2811
}
2812

    
2813
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2814
{
2815
    WinCharState *s = chr->opaque;
2816
    OVERLAPPED ov;
2817
    int ret;
2818
    DWORD size;
2819
    char openname[256];
2820

    
2821
    s->fpipe = TRUE;
2822

    
2823
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2824
    if (!s->hsend) {
2825
        fprintf(stderr, "Failed CreateEvent\n");
2826
        goto fail;
2827
    }
2828
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2829
    if (!s->hrecv) {
2830
        fprintf(stderr, "Failed CreateEvent\n");
2831
        goto fail;
2832
    }
2833

    
2834
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2835
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2836
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2837
                              PIPE_WAIT,
2838
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2839
    if (s->hcom == INVALID_HANDLE_VALUE) {
2840
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2841
        s->hcom = NULL;
2842
        goto fail;
2843
    }
2844

    
2845
    ZeroMemory(&ov, sizeof(ov));
2846
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2847
    ret = ConnectNamedPipe(s->hcom, &ov);
2848
    if (ret) {
2849
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2850
        goto fail;
2851
    }
2852

    
2853
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2854
    if (!ret) {
2855
        fprintf(stderr, "Failed GetOverlappedResult\n");
2856
        if (ov.hEvent) {
2857
            CloseHandle(ov.hEvent);
2858
            ov.hEvent = NULL;
2859
        }
2860
        goto fail;
2861
    }
2862

    
2863
    if (ov.hEvent) {
2864
        CloseHandle(ov.hEvent);
2865
        ov.hEvent = NULL;
2866
    }
2867
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2868
    return 0;
2869

    
2870
 fail:
2871
    win_chr_close(chr);
2872
    return -1;
2873
}
2874

    
2875

    
2876
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2877
{
2878
    CharDriverState *chr;
2879
    WinCharState *s;
2880

    
2881
    chr = qemu_mallocz(sizeof(CharDriverState));
2882
    if (!chr)
2883
        return NULL;
2884
    s = qemu_mallocz(sizeof(WinCharState));
2885
    if (!s) {
2886
        free(chr);
2887
        return NULL;
2888
    }
2889
    chr->opaque = s;
2890
    chr->chr_write = win_chr_write;
2891
    chr->chr_close = win_chr_close;
2892

    
2893
    if (win_chr_pipe_init(chr, filename) < 0) {
2894
        free(s);
2895
        free(chr);
2896
        return NULL;
2897
    }
2898
    qemu_chr_reset(chr);
2899
    return chr;
2900
}
2901

    
2902
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2903
{
2904
    CharDriverState *chr;
2905
    WinCharState *s;
2906

    
2907
    chr = qemu_mallocz(sizeof(CharDriverState));
2908
    if (!chr)
2909
        return NULL;
2910
    s = qemu_mallocz(sizeof(WinCharState));
2911
    if (!s) {
2912
        free(chr);
2913
        return NULL;
2914
    }
2915
    s->hcom = fd_out;
2916
    chr->opaque = s;
2917
    chr->chr_write = win_chr_write;
2918
    qemu_chr_reset(chr);
2919
    return chr;
2920
}
2921

    
2922
static CharDriverState *qemu_chr_open_win_con(const char *filename)
2923
{
2924
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2925
}
2926

    
2927
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2928
{
2929
    HANDLE fd_out;
2930

    
2931
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2932
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2933
    if (fd_out == INVALID_HANDLE_VALUE)
2934
        return NULL;
2935

    
2936
    return qemu_chr_open_win_file(fd_out);
2937
}
2938
#endif /* !_WIN32 */
2939

    
2940
/***********************************************************/
2941
/* UDP Net console */
2942

    
2943
typedef struct {
2944
    int fd;
2945
    struct sockaddr_in daddr;
2946
    uint8_t buf[1024];
2947
    int bufcnt;
2948
    int bufptr;
2949
    int max_size;
2950
} NetCharDriver;
2951

    
2952
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2953
{
2954
    NetCharDriver *s = chr->opaque;
2955

    
2956
    return sendto(s->fd, buf, len, 0,
2957
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2958
}
2959

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

    
2965
    s->max_size = qemu_chr_can_read(chr);
2966

    
2967
    /* If there were any stray characters in the queue process them
2968
     * first
2969
     */
2970
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2971
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2972
        s->bufptr++;
2973
        s->max_size = qemu_chr_can_read(chr);
2974
    }
2975
    return s->max_size;
2976
}
2977

    
2978
static void udp_chr_read(void *opaque)
2979
{
2980
    CharDriverState *chr = opaque;
2981
    NetCharDriver *s = chr->opaque;
2982

    
2983
    if (s->max_size == 0)
2984
        return;
2985
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2986
    s->bufptr = s->bufcnt;
2987
    if (s->bufcnt <= 0)
2988
        return;
2989

    
2990
    s->bufptr = 0;
2991
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2992
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2993
        s->bufptr++;
2994
        s->max_size = qemu_chr_can_read(chr);
2995
    }
2996
}
2997

    
2998
static void udp_chr_update_read_handler(CharDriverState *chr)
2999
{
3000
    NetCharDriver *s = chr->opaque;
3001

    
3002
    if (s->fd >= 0) {
3003
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3004
                             udp_chr_read, NULL, chr);
3005
    }
3006
}
3007

    
3008
int parse_host_port(struct sockaddr_in *saddr, const char *str);
3009
#ifndef _WIN32
3010
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3011
#endif
3012
int parse_host_src_port(struct sockaddr_in *haddr,
3013
                        struct sockaddr_in *saddr,
3014
                        const char *str);
3015

    
3016
static CharDriverState *qemu_chr_open_udp(const char *def)
3017
{
3018
    CharDriverState *chr = NULL;
3019
    NetCharDriver *s = NULL;
3020
    int fd = -1;
3021
    struct sockaddr_in saddr;
3022

    
3023
    chr = qemu_mallocz(sizeof(CharDriverState));
3024
    if (!chr)
3025
        goto return_err;
3026
    s = qemu_mallocz(sizeof(NetCharDriver));
3027
    if (!s)
3028
        goto return_err;
3029

    
3030
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3031
    if (fd < 0) {
3032
        perror("socket(PF_INET, SOCK_DGRAM)");
3033
        goto return_err;
3034
    }
3035

    
3036
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3037
        printf("Could not parse: %s\n", def);
3038
        goto return_err;
3039
    }
3040

    
3041
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3042
    {
3043
        perror("bind");
3044
        goto return_err;
3045
    }
3046

    
3047
    s->fd = fd;
3048
    s->bufcnt = 0;
3049
    s->bufptr = 0;
3050
    chr->opaque = s;
3051
    chr->chr_write = udp_chr_write;
3052
    chr->chr_update_read_handler = udp_chr_update_read_handler;
3053
    return chr;
3054

    
3055
return_err:
3056
    if (chr)
3057
        free(chr);
3058
    if (s)
3059
        free(s);
3060
    if (fd >= 0)
3061
        closesocket(fd);
3062
    return NULL;
3063
}
3064

    
3065
/***********************************************************/
3066
/* TCP Net console */
3067

    
3068
typedef struct {
3069
    int fd, listen_fd;
3070
    int connected;
3071
    int max_size;
3072
    int do_telnetopt;
3073
    int do_nodelay;
3074
    int is_unix;
3075
} TCPCharDriver;
3076

    
3077
static void tcp_chr_accept(void *opaque);
3078

    
3079
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3080
{
3081
    TCPCharDriver *s = chr->opaque;
3082
    if (s->connected) {
3083
        return send_all(s->fd, buf, len);
3084
    } else {
3085
        /* XXX: indicate an error ? */
3086
        return len;
3087
    }
3088
}
3089

    
3090
static int tcp_chr_read_poll(void *opaque)
3091
{
3092
    CharDriverState *chr = opaque;
3093
    TCPCharDriver *s = chr->opaque;
3094
    if (!s->connected)
3095
        return 0;
3096
    s->max_size = qemu_chr_can_read(chr);
3097
    return s->max_size;
3098
}
3099

    
3100
#define IAC 255
3101
#define IAC_BREAK 243
3102
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3103
                                      TCPCharDriver *s,
3104
                                      uint8_t *buf, int *size)
3105
{
3106
    /* Handle any telnet client's basic IAC options to satisfy char by
3107
     * char mode with no echo.  All IAC options will be removed from
3108
     * the buf and the do_telnetopt variable will be used to track the
3109
     * state of the width of the IAC information.
3110
     *
3111
     * IAC commands come in sets of 3 bytes with the exception of the
3112
     * "IAC BREAK" command and the double IAC.
3113
     */
3114

    
3115
    int i;
3116
    int j = 0;
3117

    
3118
    for (i = 0; i < *size; i++) {
3119
        if (s->do_telnetopt > 1) {
3120
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3121
                /* Double IAC means send an IAC */
3122
                if (j != i)
3123
                    buf[j] = buf[i];
3124
                j++;
3125
                s->do_telnetopt = 1;
3126
            } else {
3127
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3128
                    /* Handle IAC break commands by sending a serial break */
3129
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3130
                    s->do_telnetopt++;
3131
                }
3132
                s->do_telnetopt++;
3133
            }
3134
            if (s->do_telnetopt >= 4) {
3135
                s->do_telnetopt = 1;
3136
            }
3137
        } else {
3138
            if ((unsigned char)buf[i] == IAC) {
3139
                s->do_telnetopt = 2;
3140
            } else {
3141
                if (j != i)
3142
                    buf[j] = buf[i];
3143
                j++;
3144
            }
3145
        }
3146
    }
3147
    *size = j;
3148
}
3149

    
3150
static void tcp_chr_read(void *opaque)
3151
{
3152
    CharDriverState *chr = opaque;
3153
    TCPCharDriver *s = chr->opaque;
3154
    uint8_t buf[1024];
3155
    int len, size;
3156

    
3157
    if (!s->connected || s->max_size <= 0)
3158
        return;
3159
    len = sizeof(buf);
3160
    if (len > s->max_size)
3161
        len = s->max_size;
3162
    size = recv(s->fd, buf, len, 0);
3163
    if (size == 0) {
3164
        /* connection closed */
3165
        s->connected = 0;
3166
        if (s->listen_fd >= 0) {
3167
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3168
        }
3169
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3170
        closesocket(s->fd);
3171
        s->fd = -1;
3172
    } else if (size > 0) {
3173
        if (s->do_telnetopt)
3174
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3175
        if (size > 0)
3176
            qemu_chr_read(chr, buf, size);
3177
    }
3178
}
3179

    
3180
static void tcp_chr_connect(void *opaque)
3181
{
3182
    CharDriverState *chr = opaque;
3183
    TCPCharDriver *s = chr->opaque;
3184

    
3185
    s->connected = 1;
3186
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3187
                         tcp_chr_read, NULL, chr);
3188
    qemu_chr_reset(chr);
3189
}
3190

    
3191
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3192
static void tcp_chr_telnet_init(int fd)
3193
{
3194
    char buf[3];
3195
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3196
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3197
    send(fd, (char *)buf, 3, 0);
3198
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3199
    send(fd, (char *)buf, 3, 0);
3200
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3201
    send(fd, (char *)buf, 3, 0);
3202
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3203
    send(fd, (char *)buf, 3, 0);
3204
}
3205

    
3206
static void socket_set_nodelay(int fd)
3207
{
3208
    int val = 1;
3209
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3210
}
3211

    
3212
static void tcp_chr_accept(void *opaque)
3213
{
3214
    CharDriverState *chr = opaque;
3215
    TCPCharDriver *s = chr->opaque;
3216
    struct sockaddr_in saddr;
3217
#ifndef _WIN32
3218
    struct sockaddr_un uaddr;
3219
#endif
3220
    struct sockaddr *addr;
3221
    socklen_t len;
3222
    int fd;
3223

    
3224
    for(;;) {
3225
#ifndef _WIN32
3226
        if (s->is_unix) {
3227
            len = sizeof(uaddr);
3228
            addr = (struct sockaddr *)&uaddr;
3229
        } else
3230
#endif
3231
        {
3232
            len = sizeof(saddr);
3233
            addr = (struct sockaddr *)&saddr;
3234
        }
3235
        fd = accept(s->listen_fd, addr, &len);
3236
        if (fd < 0 && errno != EINTR) {
3237
            return;
3238
        } else if (fd >= 0) {
3239
            if (s->do_telnetopt)
3240
                tcp_chr_telnet_init(fd);
3241
            break;
3242
        }
3243
    }
3244
    socket_set_nonblock(fd);
3245
    if (s->do_nodelay)
3246
        socket_set_nodelay(fd);
3247
    s->fd = fd;
3248
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3249
    tcp_chr_connect(chr);
3250
}
3251

    
3252
static void tcp_chr_close(CharDriverState *chr)
3253
{
3254
    TCPCharDriver *s = chr->opaque;
3255
    if (s->fd >= 0)
3256
        closesocket(s->fd);
3257
    if (s->listen_fd >= 0)
3258
        closesocket(s->listen_fd);
3259
    qemu_free(s);
3260
}
3261

    
3262
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3263
                                          int is_telnet,
3264
                                          int is_unix)
3265
{
3266
    CharDriverState *chr = NULL;
3267
    TCPCharDriver *s = NULL;
3268
    int fd = -1, ret, err, val;
3269
    int is_listen = 0;
3270
    int is_waitconnect = 1;
3271
    int do_nodelay = 0;
3272
    const char *ptr;
3273
    struct sockaddr_in saddr;
3274
#ifndef _WIN32
3275
    struct sockaddr_un uaddr;
3276
#endif
3277
    struct sockaddr *addr;
3278
    socklen_t addrlen;
3279

    
3280
#ifndef _WIN32
3281
    if (is_unix) {
3282
        addr = (struct sockaddr *)&uaddr;
3283
        addrlen = sizeof(uaddr);
3284
        if (parse_unix_path(&uaddr, host_str) < 0)
3285
            goto fail;
3286
    } else
3287
#endif
3288
    {
3289
        addr = (struct sockaddr *)&saddr;
3290
        addrlen = sizeof(saddr);
3291
        if (parse_host_port(&saddr, host_str) < 0)
3292
            goto fail;
3293
    }
3294

    
3295
    ptr = host_str;
3296
    while((ptr = strchr(ptr,','))) {
3297
        ptr++;
3298
        if (!strncmp(ptr,"server",6)) {
3299
            is_listen = 1;
3300
        } else if (!strncmp(ptr,"nowait",6)) {
3301
            is_waitconnect = 0;
3302
        } else if (!strncmp(ptr,"nodelay",6)) {
3303
            do_nodelay = 1;
3304
        } else {
3305
            printf("Unknown option: %s\n", ptr);
3306
            goto fail;
3307
        }
3308
    }
3309
    if (!is_listen)
3310
        is_waitconnect = 0;
3311

    
3312
    chr = qemu_mallocz(sizeof(CharDriverState));
3313
    if (!chr)
3314
        goto fail;
3315
    s = qemu_mallocz(sizeof(TCPCharDriver));
3316
    if (!s)
3317
        goto fail;
3318

    
3319
#ifndef _WIN32
3320
    if (is_unix)
3321
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3322
    else
3323
#endif
3324
        fd = socket(PF_INET, SOCK_STREAM, 0);
3325

    
3326
    if (fd < 0)
3327
        goto fail;
3328

    
3329
    if (!is_waitconnect)
3330
        socket_set_nonblock(fd);
3331

    
3332
    s->connected = 0;
3333
    s->fd = -1;
3334
    s->listen_fd = -1;
3335
    s->is_unix = is_unix;
3336
    s->do_nodelay = do_nodelay && !is_unix;
3337

    
3338
    chr->opaque = s;
3339
    chr->chr_write = tcp_chr_write;
3340
    chr->chr_close = tcp_chr_close;
3341

    
3342
    if (is_listen) {
3343
        /* allow fast reuse */
3344
#ifndef _WIN32
3345
        if (is_unix) {
3346
            char path[109];
3347
            strncpy(path, uaddr.sun_path, 108);
3348
            path[108] = 0;
3349
            unlink(path);
3350
        } else
3351
#endif
3352
        {
3353
            val = 1;
3354
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3355
        }
3356

    
3357
        ret = bind(fd, addr, addrlen);
3358
        if (ret < 0)
3359
            goto fail;
3360

    
3361
        ret = listen(fd, 0);
3362
        if (ret < 0)
3363
            goto fail;
3364

    
3365
        s->listen_fd = fd;
3366
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3367
        if (is_telnet)
3368
            s->do_telnetopt = 1;
3369
    } else {
3370
        for(;;) {
3371
            ret = connect(fd, addr, addrlen);
3372
            if (ret < 0) {
3373
                err = socket_error();
3374
                if (err == EINTR || err == EWOULDBLOCK) {
3375
                } else if (err == EINPROGRESS) {
3376
                    break;
3377
#ifdef _WIN32
3378
                } else if (err == WSAEALREADY) {
3379
                    break;
3380
#endif
3381
                } else {
3382
                    goto fail;
3383
                }
3384
            } else {
3385
                s->connected = 1;
3386
                break;
3387
            }
3388
        }
3389
        s->fd = fd;
3390
        socket_set_nodelay(fd);
3391
        if (s->connected)
3392
            tcp_chr_connect(chr);
3393
        else
3394
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3395
    }
3396

    
3397
    if (is_listen && is_waitconnect) {
3398
        printf("QEMU waiting for connection on: %s\n", host_str);
3399
        tcp_chr_accept(chr);
3400
        socket_set_nonblock(s->listen_fd);
3401
    }
3402

    
3403
    return chr;
3404
 fail:
3405
    if (fd >= 0)
3406
        closesocket(fd);
3407
    qemu_free(s);
3408
    qemu_free(chr);
3409
    return NULL;
3410
}
3411

    
3412
CharDriverState *qemu_chr_open(const char *filename)
3413
{
3414
    const char *p;
3415

    
3416
    if (!strcmp(filename, "vc")) {
3417
        return text_console_init(&display_state, 0);
3418
    } else if (strstart(filename, "vc:", &p)) {
3419
        return text_console_init(&display_state, p);
3420
    } else if (!strcmp(filename, "null")) {
3421
        return qemu_chr_open_null();
3422
    } else
3423
    if (strstart(filename, "tcp:", &p)) {
3424
        return qemu_chr_open_tcp(p, 0, 0);
3425
    } else
3426
    if (strstart(filename, "telnet:", &p)) {
3427
        return qemu_chr_open_tcp(p, 1, 0);
3428
    } else
3429
    if (strstart(filename, "udp:", &p)) {
3430
        return qemu_chr_open_udp(p);
3431
    } else
3432
    if (strstart(filename, "mon:", &p)) {
3433
        CharDriverState *drv = qemu_chr_open(p);
3434
        if (drv) {
3435
            drv = qemu_chr_open_mux(drv);
3436
            monitor_init(drv, !nographic);
3437
            return drv;
3438
        }
3439
        printf("Unable to open driver: %s\n", p);
3440
        return 0;
3441
    } else
3442
#ifndef _WIN32
3443
    if (strstart(filename, "unix:", &p)) {
3444
        return qemu_chr_open_tcp(p, 0, 1);
3445
    } else if (strstart(filename, "file:", &p)) {
3446
        return qemu_chr_open_file_out(p);
3447
    } else if (strstart(filename, "pipe:", &p)) {
3448
        return qemu_chr_open_pipe(p);
3449
    } else if (!strcmp(filename, "pty")) {
3450
        return qemu_chr_open_pty();
3451
    } else if (!strcmp(filename, "stdio")) {
3452
        return qemu_chr_open_stdio();
3453
    } else
3454
#if defined(__linux__)
3455
    if (strstart(filename, "/dev/parport", NULL)) {
3456
        return qemu_chr_open_pp(filename);
3457
    } else
3458
#endif
3459
#if defined(__linux__) || defined(__sun__)
3460
    if (strstart(filename, "/dev/", NULL)) {
3461
        return qemu_chr_open_tty(filename);
3462
    } else
3463
#endif
3464
#else /* !_WIN32 */
3465
    if (strstart(filename, "COM", NULL)) {
3466
        return qemu_chr_open_win(filename);
3467
    } else
3468
    if (strstart(filename, "pipe:", &p)) {
3469
        return qemu_chr_open_win_pipe(p);
3470
    } else
3471
    if (strstart(filename, "con:", NULL)) {
3472
        return qemu_chr_open_win_con(filename);
3473
    } else
3474
    if (strstart(filename, "file:", &p)) {
3475
        return qemu_chr_open_win_file_out(p);
3476
    } else
3477
#endif
3478
#ifdef CONFIG_BRLAPI
3479
    if (!strcmp(filename, "braille")) {
3480
        return chr_baum_init();
3481
    } else
3482
#endif
3483
    {
3484
        return NULL;
3485
    }
3486
}
3487

    
3488
void qemu_chr_close(CharDriverState *chr)
3489
{
3490
    if (chr->chr_close)
3491
        chr->chr_close(chr);
3492
    qemu_free(chr);
3493
}
3494

    
3495
/***********************************************************/
3496
/* network device redirectors */
3497

    
3498
__attribute__ (( unused ))
3499
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3500
{
3501
    int len, i, j, c;
3502

    
3503
    for(i=0;i<size;i+=16) {
3504
        len = size - i;
3505
        if (len > 16)
3506
            len = 16;
3507
        fprintf(f, "%08x ", i);
3508
        for(j=0;j<16;j++) {
3509
            if (j < len)
3510
                fprintf(f, " %02x", buf[i+j]);
3511
            else
3512
                fprintf(f, "   ");
3513
        }
3514
        fprintf(f, " ");
3515
        for(j=0;j<len;j++) {
3516
            c = buf[i+j];
3517
            if (c < ' ' || c > '~')
3518
                c = '.';
3519
            fprintf(f, "%c", c);
3520
        }
3521
        fprintf(f, "\n");
3522
    }
3523
}
3524

    
3525
static int parse_macaddr(uint8_t *macaddr, const char *p)
3526
{
3527
    int i;
3528
    char *last_char;
3529
    long int offset;
3530

    
3531
    errno = 0;
3532
    offset = strtol(p, &last_char, 0);    
3533
    if (0 == errno && '\0' == *last_char &&
3534
            offset >= 0 && offset <= 0xFFFFFF) {
3535
        macaddr[3] = (offset & 0xFF0000) >> 16;
3536
        macaddr[4] = (offset & 0xFF00) >> 8;
3537
        macaddr[5] = offset & 0xFF;
3538
        return 0;
3539
    } else {
3540
        for(i = 0; i < 6; i++) {
3541
            macaddr[i] = strtol(p, (char **)&p, 16);
3542
            if (i == 5) {
3543
                if (*p != '\0')
3544
                    return -1;
3545
            } else {
3546
                if (*p != ':' && *p != '-')
3547
                    return -1;
3548
                p++;
3549
            }
3550
        }
3551
        return 0;    
3552
    }
3553

    
3554
    return -1;
3555
}
3556

    
3557
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3558
{
3559
    const char *p, *p1;
3560
    int len;
3561
    p = *pp;
3562
    p1 = strchr(p, sep);
3563
    if (!p1)
3564
        return -1;
3565
    len = p1 - p;
3566
    p1++;
3567
    if (buf_size > 0) {
3568
        if (len > buf_size - 1)
3569
            len = buf_size - 1;
3570
        memcpy(buf, p, len);
3571
        buf[len] = '\0';
3572
    }
3573
    *pp = p1;
3574
    return 0;
3575
}
3576

    
3577
int parse_host_src_port(struct sockaddr_in *haddr,
3578
                        struct sockaddr_in *saddr,
3579
                        const char *input_str)
3580
{
3581
    char *str = strdup(input_str);
3582
    char *host_str = str;
3583
    char *src_str;
3584
    char *ptr;
3585

    
3586
    /*
3587
     * Chop off any extra arguments at the end of the string which
3588
     * would start with a comma, then fill in the src port information
3589
     * if it was provided else use the "any address" and "any port".
3590
     */
3591
    if ((ptr = strchr(str,',')))
3592
        *ptr = '\0';
3593

    
3594
    if ((src_str = strchr(input_str,'@'))) {
3595
        *src_str = '\0';
3596
        src_str++;
3597
    }
3598

    
3599
    if (parse_host_port(haddr, host_str) < 0)
3600
        goto fail;
3601

    
3602
    if (!src_str || *src_str == '\0')
3603
        src_str = ":0";
3604

    
3605
    if (parse_host_port(saddr, src_str) < 0)
3606
        goto fail;
3607

    
3608
    free(str);
3609
    return(0);
3610

    
3611
fail:
3612
    free(str);
3613
    return -1;
3614
}
3615

    
3616
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3617
{
3618
    char buf[512];
3619
    struct hostent *he;
3620
    const char *p, *r;
3621
    int port;
3622

    
3623
    p = str;
3624
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3625
        return -1;
3626
    saddr->sin_family = AF_INET;
3627
    if (buf[0] == '\0') {
3628
        saddr->sin_addr.s_addr = 0;
3629
    } else {
3630
        if (isdigit(buf[0])) {
3631
            if (!inet_aton(buf, &saddr->sin_addr))
3632
                return -1;
3633
        } else {
3634
            if ((he = gethostbyname(buf)) == NULL)
3635
                return - 1;
3636
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3637
        }
3638
    }
3639
    port = strtol(p, (char **)&r, 0);
3640
    if (r == p)
3641
        return -1;
3642
    saddr->sin_port = htons(port);
3643
    return 0;
3644
}
3645

    
3646
#ifndef _WIN32
3647
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3648
{
3649
    const char *p;
3650
    int len;
3651

    
3652
    len = MIN(108, strlen(str));
3653
    p = strchr(str, ',');
3654
    if (p)
3655
        len = MIN(len, p - str);
3656

    
3657
    memset(uaddr, 0, sizeof(*uaddr));
3658

    
3659
    uaddr->sun_family = AF_UNIX;
3660
    memcpy(uaddr->sun_path, str, len);
3661

    
3662
    return 0;
3663
}
3664
#endif
3665

    
3666
/* find or alloc a new VLAN */
3667
VLANState *qemu_find_vlan(int id)
3668
{
3669
    VLANState **pvlan, *vlan;
3670
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3671
        if (vlan->id == id)
3672
            return vlan;
3673
    }
3674
    vlan = qemu_mallocz(sizeof(VLANState));
3675
    if (!vlan)
3676
        return NULL;
3677
    vlan->id = id;
3678
    vlan->next = NULL;
3679
    pvlan = &first_vlan;
3680
    while (*pvlan != NULL)
3681
        pvlan = &(*pvlan)->next;
3682
    *pvlan = vlan;
3683
    return vlan;
3684
}
3685

    
3686
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3687
                                      IOReadHandler *fd_read,
3688
                                      IOCanRWHandler *fd_can_read,
3689
                                      void *opaque)
3690
{
3691
    VLANClientState *vc, **pvc;
3692
    vc = qemu_mallocz(sizeof(VLANClientState));
3693
    if (!vc)
3694
        return NULL;
3695
    vc->fd_read = fd_read;
3696
    vc->fd_can_read = fd_can_read;
3697
    vc->opaque = opaque;
3698
    vc->vlan = vlan;
3699

    
3700
    vc->next = NULL;
3701
    pvc = &vlan->first_client;
3702
    while (*pvc != NULL)
3703
        pvc = &(*pvc)->next;
3704
    *pvc = vc;
3705
    return vc;
3706
}
3707

    
3708
int qemu_can_send_packet(VLANClientState *vc1)
3709
{
3710
    VLANState *vlan = vc1->vlan;
3711
    VLANClientState *vc;
3712

    
3713
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3714
        if (vc != vc1) {
3715
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3716
                return 1;
3717
        }
3718
    }
3719
    return 0;
3720
}
3721

    
3722
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3723
{
3724
    VLANState *vlan = vc1->vlan;
3725
    VLANClientState *vc;
3726

    
3727
#if 0
3728
    printf("vlan %d send:\n", vlan->id);
3729
    hex_dump(stdout, buf, size);
3730
#endif
3731
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3732
        if (vc != vc1) {
3733
            vc->fd_read(vc->opaque, buf, size);
3734
        }
3735
    }
3736
}
3737

    
3738
#if defined(CONFIG_SLIRP)
3739

    
3740
/* slirp network adapter */
3741

    
3742
static int slirp_inited;
3743
static VLANClientState *slirp_vc;
3744

    
3745
int slirp_can_output(void)
3746
{
3747
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3748
}
3749

    
3750
void slirp_output(const uint8_t *pkt, int pkt_len)
3751
{
3752
#if 0
3753
    printf("slirp output:\n");
3754
    hex_dump(stdout, pkt, pkt_len);
3755
#endif
3756
    if (!slirp_vc)
3757
        return;
3758
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3759
}
3760

    
3761
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3762
{
3763
#if 0
3764
    printf("slirp input:\n");
3765
    hex_dump(stdout, buf, size);
3766
#endif
3767
    slirp_input(buf, size);
3768
}
3769

    
3770
static int net_slirp_init(VLANState *vlan)
3771
{
3772
    if (!slirp_inited) {
3773
        slirp_inited = 1;
3774
        slirp_init();
3775
    }
3776
    slirp_vc = qemu_new_vlan_client(vlan,
3777
                                    slirp_receive, NULL, NULL);
3778
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3779
    return 0;
3780
}
3781

    
3782
static void net_slirp_redir(const char *redir_str)
3783
{
3784
    int is_udp;
3785
    char buf[256], *r;
3786
    const char *p;
3787
    struct in_addr guest_addr;
3788
    int host_port, guest_port;
3789

    
3790
    if (!slirp_inited) {
3791
        slirp_inited = 1;
3792
        slirp_init();
3793
    }
3794

    
3795
    p = redir_str;
3796
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3797
        goto fail;
3798
    if (!strcmp(buf, "tcp")) {
3799
        is_udp = 0;
3800
    } else if (!strcmp(buf, "udp")) {
3801
        is_udp = 1;
3802
    } else {
3803
        goto fail;
3804
    }
3805

    
3806
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3807
        goto fail;
3808
    host_port = strtol(buf, &r, 0);
3809
    if (r == buf)
3810
        goto fail;
3811

    
3812
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3813
        goto fail;
3814
    if (buf[0] == '\0') {
3815
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3816
    }
3817
    if (!inet_aton(buf, &guest_addr))
3818
        goto fail;
3819

    
3820
    guest_port = strtol(p, &r, 0);
3821
    if (r == p)
3822
        goto fail;
3823

    
3824
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3825
        fprintf(stderr, "qemu: could not set up redirection\n");
3826
        exit(1);
3827
    }
3828
    return;
3829
 fail:
3830
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3831
    exit(1);
3832
}
3833

    
3834
#ifndef _WIN32
3835

    
3836
char smb_dir[1024];
3837

    
3838
static void erase_dir(char *dir_name)
3839
{
3840
    DIR *d;
3841
    struct dirent *de;
3842
    char filename[1024];
3843

    
3844
    /* erase all the files in the directory */
3845
    if ((d = opendir(dir_name)) != 0) {
3846
        for(;;) {
3847
            de = readdir(d);
3848
            if (!de)
3849
                break;
3850
            if (strcmp(de->d_name, ".") != 0 &&
3851
                strcmp(de->d_name, "..") != 0) {
3852
                snprintf(filename, sizeof(filename), "%s/%s",
3853
                         smb_dir, de->d_name);
3854
                if (unlink(filename) != 0)  /* is it a directory? */
3855
                    erase_dir(filename);
3856
            }
3857
        }
3858
        closedir(d);
3859
        rmdir(dir_name);
3860
    }
3861
}
3862

    
3863
/* automatic user mode samba server configuration */
3864
static void smb_exit(void)
3865
{
3866
    erase_dir(smb_dir);
3867
}
3868

    
3869
/* automatic user mode samba server configuration */
3870
static void net_slirp_smb(const char *exported_dir)
3871
{
3872
    char smb_conf[1024];
3873
    char smb_cmdline[1024];
3874
    FILE *f;
3875

    
3876
    if (!slirp_inited) {
3877
        slirp_inited = 1;
3878
        slirp_init();
3879
    }
3880

    
3881
    /* XXX: better tmp dir construction */
3882
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3883
    if (mkdir(smb_dir, 0700) < 0) {
3884
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3885
        exit(1);
3886
    }
3887
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3888

    
3889
    f = fopen(smb_conf, "w");
3890
    if (!f) {
3891
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3892
        exit(1);
3893
    }
3894
    fprintf(f,
3895
            "[global]\n"
3896
            "private dir=%s\n"
3897
            "smb ports=0\n"
3898
            "socket address=127.0.0.1\n"
3899
            "pid directory=%s\n"
3900
            "lock directory=%s\n"
3901
            "log file=%s/log.smbd\n"
3902
            "smb passwd file=%s/smbpasswd\n"
3903
            "security = share\n"
3904
            "[qemu]\n"
3905
            "path=%s\n"
3906
            "read only=no\n"
3907
            "guest ok=yes\n",
3908
            smb_dir,
3909
            smb_dir,
3910
            smb_dir,
3911
            smb_dir,
3912
            smb_dir,
3913
            exported_dir
3914
            );
3915
    fclose(f);
3916
    atexit(smb_exit);
3917

    
3918
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3919
             SMBD_COMMAND, smb_conf);
3920

    
3921
    slirp_add_exec(0, smb_cmdline, 4, 139);
3922
}
3923

    
3924
#endif /* !defined(_WIN32) */
3925
void do_info_slirp(void)
3926
{
3927
    slirp_stats();
3928
}
3929

    
3930
#endif /* CONFIG_SLIRP */
3931

    
3932
#if !defined(_WIN32)
3933

    
3934
typedef struct TAPState {
3935
    VLANClientState *vc;
3936
    int fd;
3937
    char down_script[1024];
3938
} TAPState;
3939

    
3940
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3941
{
3942
    TAPState *s = opaque;
3943
    int ret;
3944
    for(;;) {
3945
        ret = write(s->fd, buf, size);
3946
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3947
        } else {
3948
            break;
3949
        }
3950
    }
3951
}
3952

    
3953
static void tap_send(void *opaque)
3954
{
3955
    TAPState *s = opaque;
3956
    uint8_t buf[4096];
3957
    int size;
3958

    
3959
#ifdef __sun__
3960
    struct strbuf sbuf;
3961
    int f = 0;
3962
    sbuf.maxlen = sizeof(buf);
3963
    sbuf.buf = buf;
3964
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3965
#else
3966
    size = read(s->fd, buf, sizeof(buf));
3967
#endif
3968
    if (size > 0) {
3969
        qemu_send_packet(s->vc, buf, size);
3970
    }
3971
}
3972

    
3973
/* fd support */
3974

    
3975
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3976
{
3977
    TAPState *s;
3978

    
3979
    s = qemu_mallocz(sizeof(TAPState));
3980
    if (!s)
3981
        return NULL;
3982
    s->fd = fd;
3983
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3984
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3985
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3986
    return s;
3987
}
3988

    
3989
#if defined (_BSD) || defined (__FreeBSD_kernel__)
3990
static int tap_open(char *ifname, int ifname_size)
3991
{
3992
    int fd;
3993
    char *dev;
3994
    struct stat s;
3995

    
3996
    TFR(fd = open("/dev/tap", O_RDWR));
3997
    if (fd < 0) {
3998
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3999
        return -1;
4000
    }
4001

    
4002
    fstat(fd, &s);
4003
    dev = devname(s.st_rdev, S_IFCHR);
4004
    pstrcpy(ifname, ifname_size, dev);
4005

    
4006
    fcntl(fd, F_SETFL, O_NONBLOCK);
4007
    return fd;
4008
}
4009
#elif defined(__sun__)
4010
#define TUNNEWPPA       (('T'<<16) | 0x0001)
4011
/*
4012
 * Allocate TAP device, returns opened fd.
4013
 * Stores dev name in the first arg(must be large enough).
4014
 */
4015
int tap_alloc(char *dev)
4016
{
4017
    int tap_fd, if_fd, ppa = -1;
4018
    static int ip_fd = 0;
4019
    char *ptr;
4020

    
4021
    static int arp_fd = 0;
4022
    int ip_muxid, arp_muxid;
4023
    struct strioctl  strioc_if, strioc_ppa;
4024
    int link_type = I_PLINK;;
4025
    struct lifreq ifr;
4026
    char actual_name[32] = "";
4027

    
4028
    memset(&ifr, 0x0, sizeof(ifr));
4029

    
4030
    if( *dev ){
4031
       ptr = dev;
4032
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
4033
       ppa = atoi(ptr);
4034
    }
4035

    
4036
    /* Check if IP device was opened */
4037
    if( ip_fd )
4038
       close(ip_fd);
4039

    
4040
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4041
    if (ip_fd < 0) {
4042
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4043
       return -1;
4044
    }
4045

    
4046
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4047
    if (tap_fd < 0) {
4048
       syslog(LOG_ERR, "Can't open /dev/tap");
4049
       return -1;
4050
    }
4051

    
4052
    /* Assign a new PPA and get its unit number. */
4053
    strioc_ppa.ic_cmd = TUNNEWPPA;
4054
    strioc_ppa.ic_timout = 0;
4055
    strioc_ppa.ic_len = sizeof(ppa);
4056
    strioc_ppa.ic_dp = (char *)&ppa;
4057
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4058
       syslog (LOG_ERR, "Can't assign new interface");
4059

    
4060
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4061
    if (if_fd < 0) {
4062
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
4063
       return -1;
4064
    }
4065
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
4066
       syslog(LOG_ERR, "Can't push IP module");
4067
       return -1;
4068
    }
4069

    
4070
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4071
        syslog(LOG_ERR, "Can't get flags\n");
4072

    
4073
    snprintf (actual_name, 32, "tap%d", ppa);
4074
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4075

    
4076
    ifr.lifr_ppa = ppa;
4077
    /* Assign ppa according to the unit number returned by tun device */
4078

    
4079
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4080
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
4081
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4082
        syslog (LOG_ERR, "Can't get flags\n");
4083
    /* Push arp module to if_fd */
4084
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
4085
        syslog (LOG_ERR, "Can't push ARP module (2)");
4086

    
4087
    /* Push arp module to ip_fd */
4088
    if (ioctl (ip_fd, I_POP, NULL) < 0)
4089
        syslog (LOG_ERR, "I_POP failed\n");
4090
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4091
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
4092
    /* Open arp_fd */
4093
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4094
    if (arp_fd < 0)
4095
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4096

    
4097
    /* Set ifname to arp */
4098
    strioc_if.ic_cmd = SIOCSLIFNAME;
4099
    strioc_if.ic_timout = 0;
4100
    strioc_if.ic_len = sizeof(ifr);
4101
    strioc_if.ic_dp = (char *)&ifr;
4102
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4103
        syslog (LOG_ERR, "Can't set ifname to arp\n");
4104
    }
4105

    
4106
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4107
       syslog(LOG_ERR, "Can't link TAP device to IP");
4108
       return -1;
4109
    }
4110

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

    
4114
    close (if_fd);
4115

    
4116
    memset(&ifr, 0x0, sizeof(ifr));
4117
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4118
    ifr.lifr_ip_muxid  = ip_muxid;
4119
    ifr.lifr_arp_muxid = arp_muxid;
4120

    
4121
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4122
    {
4123
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4124
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4125
      syslog (LOG_ERR, "Can't set multiplexor id");
4126
    }
4127

    
4128
    sprintf(dev, "tap%d", ppa);
4129
    return tap_fd;
4130
}
4131

    
4132
static int tap_open(char *ifname, int ifname_size)
4133
{
4134
    char  dev[10]="";
4135
    int fd;
4136
    if( (fd = tap_alloc(dev)) < 0 ){
4137
       fprintf(stderr, "Cannot allocate TAP device\n");
4138
       return -1;
4139
    }
4140
    pstrcpy(ifname, ifname_size, dev);
4141
    fcntl(fd, F_SETFL, O_NONBLOCK);
4142
    return fd;
4143
}
4144
#else
4145
static int tap_open(char *ifname, int ifname_size)
4146
{
4147
    struct ifreq ifr;
4148
    int fd, ret;
4149

    
4150
    TFR(fd = open("/dev/net/tun", O_RDWR));
4151
    if (fd < 0) {
4152
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4153
        return -1;
4154
    }
4155
    memset(&ifr, 0, sizeof(ifr));
4156
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4157
    if (ifname[0] != '\0')
4158
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4159
    else
4160
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4161
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4162
    if (ret != 0) {
4163
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4164
        close(fd);
4165
        return -1;
4166
    }
4167
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4168
    fcntl(fd, F_SETFL, O_NONBLOCK);
4169
    return fd;
4170
}
4171
#endif
4172

    
4173
static int launch_script(const char *setup_script, const char *ifname, int fd)
4174
{
4175
    int pid, status;
4176
    char *args[3];
4177
    char **parg;
4178

    
4179
        /* try to launch network script */
4180
        pid = fork();
4181
        if (pid >= 0) {
4182
            if (pid == 0) {
4183
                int open_max = sysconf (_SC_OPEN_MAX), i;
4184
                for (i = 0; i < open_max; i++)
4185
                    if (i != STDIN_FILENO &&
4186
                        i != STDOUT_FILENO &&
4187
                        i != STDERR_FILENO &&
4188
                        i != fd)
4189
                        close(i);
4190

    
4191
                parg = args;
4192
                *parg++ = (char *)setup_script;
4193
                *parg++ = (char *)ifname;
4194
                *parg++ = NULL;
4195
                execv(setup_script, args);
4196
                _exit(1);
4197
            }
4198
            while (waitpid(pid, &status, 0) != pid);
4199
            if (!WIFEXITED(status) ||
4200
                WEXITSTATUS(status) != 0) {
4201
                fprintf(stderr, "%s: could not launch network script\n",
4202
                        setup_script);
4203
                return -1;
4204
            }
4205
        }
4206
    return 0;
4207
}
4208

    
4209
static int net_tap_init(VLANState *vlan, const char *ifname1,
4210
                        const char *setup_script, const char *down_script)
4211
{
4212
    TAPState *s;
4213
    int fd;
4214
    char ifname[128];
4215

    
4216
    if (ifname1 != NULL)
4217
        pstrcpy(ifname, sizeof(ifname), ifname1);
4218
    else
4219
        ifname[0] = '\0';
4220
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4221
    if (fd < 0)
4222
        return -1;
4223

    
4224
    if (!setup_script || !strcmp(setup_script, "no"))
4225
        setup_script = "";
4226
    if (setup_script[0] != '\0') {
4227
        if (launch_script(setup_script, ifname, fd))
4228
            return -1;
4229
    }
4230
    s = net_tap_fd_init(vlan, fd);
4231
    if (!s)
4232
        return -1;
4233
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4234
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4235
    if (down_script && strcmp(down_script, "no"))
4236
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4237
    return 0;
4238
}
4239

    
4240
#endif /* !_WIN32 */
4241

    
4242
/* network connection */
4243
typedef struct NetSocketState {
4244
    VLANClientState *vc;
4245
    int fd;
4246
    int state; /* 0 = getting length, 1 = getting data */
4247
    int index;
4248
    int packet_len;
4249
    uint8_t buf[4096];
4250
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4251
} NetSocketState;
4252

    
4253
typedef struct NetSocketListenState {
4254
    VLANState *vlan;
4255
    int fd;
4256
} NetSocketListenState;
4257

    
4258
/* XXX: we consider we can send the whole packet without blocking */
4259
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4260
{
4261
    NetSocketState *s = opaque;
4262
    uint32_t len;
4263
    len = htonl(size);
4264

    
4265
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4266
    send_all(s->fd, buf, size);
4267
}
4268

    
4269
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4270
{
4271
    NetSocketState *s = opaque;
4272
    sendto(s->fd, buf, size, 0,
4273
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4274
}
4275

    
4276
static void net_socket_send(void *opaque)
4277
{
4278
    NetSocketState *s = opaque;
4279
    int l, size, err;
4280
    uint8_t buf1[4096];
4281
    const uint8_t *buf;
4282

    
4283
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4284
    if (size < 0) {
4285
        err = socket_error();
4286
        if (err != EWOULDBLOCK)
4287
            goto eoc;
4288
    } else if (size == 0) {
4289
        /* end of connection */
4290
    eoc:
4291
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4292
        closesocket(s->fd);
4293
        return;
4294
    }
4295
    buf = buf1;
4296
    while (size > 0) {
4297
        /* reassemble a packet from the network */
4298
        switch(s->state) {
4299
        case 0:
4300
            l = 4 - s->index;
4301
            if (l > size)
4302
                l = size;
4303
            memcpy(s->buf + s->index, buf, l);
4304
            buf += l;
4305
            size -= l;
4306
            s->index += l;
4307
            if (s->index == 4) {
4308
                /* got length */
4309
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4310
                s->index = 0;
4311
                s->state = 1;
4312
            }
4313
            break;
4314
        case 1:
4315
            l = s->packet_len - s->index;
4316
            if (l > size)
4317
                l = size;
4318
            memcpy(s->buf + s->index, buf, l);
4319
            s->index += l;
4320
            buf += l;
4321
            size -= l;
4322
            if (s->index >= s->packet_len) {
4323
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4324
                s->index = 0;
4325
                s->state = 0;
4326
            }
4327
            break;
4328
        }
4329
    }
4330
}
4331

    
4332
static void net_socket_send_dgram(void *opaque)
4333
{
4334
    NetSocketState *s = opaque;
4335
    int size;
4336

    
4337
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4338
    if (size < 0)
4339
        return;
4340
    if (size == 0) {
4341
        /* end of connection */
4342
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4343
        return;
4344
    }
4345
    qemu_send_packet(s->vc, s->buf, size);
4346
}
4347

    
4348
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4349
{
4350
    struct ip_mreq imr;
4351
    int fd;
4352
    int val, ret;
4353
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4354
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4355
                inet_ntoa(mcastaddr->sin_addr),
4356
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4357
        return -1;
4358

    
4359
    }
4360
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4361
    if (fd < 0) {
4362
        perror("socket(PF_INET, SOCK_DGRAM)");
4363
        return -1;
4364
    }
4365

    
4366
    val = 1;
4367
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4368
                   (const char *)&val, sizeof(val));
4369
    if (ret < 0) {
4370
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4371
        goto fail;
4372
    }
4373

    
4374
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4375
    if (ret < 0) {
4376
        perror("bind");
4377
        goto fail;
4378
    }
4379

    
4380
    /* Add host to multicast group */
4381
    imr.imr_multiaddr = mcastaddr->sin_addr;
4382
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4383

    
4384
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4385
                     (const char *)&imr, sizeof(struct ip_mreq));
4386
    if (ret < 0) {
4387
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4388
        goto fail;
4389
    }
4390

    
4391
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4392
    val = 1;
4393
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4394
                   (const char *)&val, sizeof(val));
4395
    if (ret < 0) {
4396
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4397
        goto fail;
4398
    }
4399

    
4400
    socket_set_nonblock(fd);
4401
    return fd;
4402
fail:
4403
    if (fd >= 0)
4404
        closesocket(fd);
4405
    return -1;
4406
}
4407

    
4408
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4409
                                          int is_connected)
4410
{
4411
    struct sockaddr_in saddr;
4412
    int newfd;
4413
    socklen_t saddr_len;
4414
    NetSocketState *s;
4415

    
4416
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4417
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4418
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4419
     */
4420

    
4421
    if (is_connected) {
4422
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4423
            /* must be bound */
4424
            if (saddr.sin_addr.s_addr==0) {
4425
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4426
                        fd);
4427
                return NULL;
4428
            }
4429
            /* clone dgram socket */
4430
            newfd = net_socket_mcast_create(&saddr);
4431
            if (newfd < 0) {
4432
                /* error already reported by net_socket_mcast_create() */
4433
                close(fd);
4434
                return NULL;
4435
            }
4436
            /* clone newfd to fd, close newfd */
4437
            dup2(newfd, fd);
4438
            close(newfd);
4439

    
4440
        } else {
4441
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4442
                    fd, strerror(errno));
4443
            return NULL;
4444
        }
4445
    }
4446

    
4447
    s = qemu_mallocz(sizeof(NetSocketState));
4448
    if (!s)
4449
        return NULL;
4450
    s->fd = fd;
4451

    
4452
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4453
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4454

    
4455
    /* mcast: save bound address as dst */
4456
    if (is_connected) s->dgram_dst=saddr;
4457

    
4458
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4459
            "socket: fd=%d (%s mcast=%s:%d)",
4460
            fd, is_connected? "cloned" : "",
4461
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4462
    return s;
4463
}
4464

    
4465
static void net_socket_connect(void *opaque)
4466
{
4467
    NetSocketState *s = opaque;
4468
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4469
}
4470

    
4471
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4472
                                          int is_connected)
4473
{
4474
    NetSocketState *s;
4475
    s = qemu_mallocz(sizeof(NetSocketState));
4476
    if (!s)
4477
        return NULL;
4478
    s->fd = fd;
4479
    s->vc = qemu_new_vlan_client(vlan,
4480
                                 net_socket_receive, NULL, s);
4481
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4482
             "socket: fd=%d", fd);
4483
    if (is_connected) {
4484
        net_socket_connect(s);
4485
    } else {
4486
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4487
    }
4488
    return s;
4489
}
4490

    
4491
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4492
                                          int is_connected)
4493
{
4494
    int so_type=-1, optlen=sizeof(so_type);
4495

    
4496
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4497
        (socklen_t *)&optlen)< 0) {
4498
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4499
        return NULL;
4500
    }
4501
    switch(so_type) {
4502
    case SOCK_DGRAM:
4503
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4504
    case SOCK_STREAM:
4505
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4506
    default:
4507
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4508
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4509
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4510
    }
4511
    return NULL;
4512
}
4513

    
4514
static void net_socket_accept(void *opaque)
4515
{
4516
    NetSocketListenState *s = opaque;
4517
    NetSocketState *s1;
4518
    struct sockaddr_in saddr;
4519
    socklen_t len;
4520
    int fd;
4521

    
4522
    for(;;) {
4523
        len = sizeof(saddr);
4524
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4525
        if (fd < 0 && errno != EINTR) {
4526
            return;
4527
        } else if (fd >= 0) {
4528
            break;
4529
        }
4530
    }
4531
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4532
    if (!s1) {
4533
        closesocket(fd);
4534
    } else {
4535
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4536
                 "socket: connection from %s:%d",
4537
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4538
    }
4539
}
4540

    
4541
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4542
{
4543
    NetSocketListenState *s;
4544
    int fd, val, ret;
4545
    struct sockaddr_in saddr;
4546

    
4547
    if (parse_host_port(&saddr, host_str) < 0)
4548
        return -1;
4549

    
4550
    s = qemu_mallocz(sizeof(NetSocketListenState));
4551
    if (!s)
4552
        return -1;
4553

    
4554
    fd = socket(PF_INET, SOCK_STREAM, 0);
4555
    if (fd < 0) {
4556
        perror("socket");
4557
        return -1;
4558
    }
4559
    socket_set_nonblock(fd);
4560

    
4561
    /* allow fast reuse */
4562
    val = 1;
4563
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4564

    
4565
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4566
    if (ret < 0) {
4567
        perror("bind");
4568
        return -1;
4569
    }
4570
    ret = listen(fd, 0);
4571
    if (ret < 0) {
4572
        perror("listen");
4573
        return -1;
4574
    }
4575
    s->vlan = vlan;
4576
    s->fd = fd;
4577
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4578
    return 0;
4579
}
4580

    
4581
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4582
{
4583
    NetSocketState *s;
4584
    int fd, connected, ret, err;
4585
    struct sockaddr_in saddr;
4586

    
4587
    if (parse_host_port(&saddr, host_str) < 0)
4588
        return -1;
4589

    
4590
    fd = socket(PF_INET, SOCK_STREAM, 0);
4591
    if (fd < 0) {
4592
        perror("socket");
4593
        return -1;
4594
    }
4595
    socket_set_nonblock(fd);
4596

    
4597
    connected = 0;
4598
    for(;;) {
4599
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4600
        if (ret < 0) {
4601
            err = socket_error();
4602
            if (err == EINTR || err == EWOULDBLOCK) {
4603
            } else if (err == EINPROGRESS) {
4604
                break;
4605
#ifdef _WIN32
4606
            } else if (err == WSAEALREADY) {
4607
                break;
4608
#endif
4609
            } else {
4610
                perror("connect");
4611
                closesocket(fd);
4612
                return -1;
4613
            }
4614
        } else {
4615
            connected = 1;
4616
            break;
4617
        }
4618
    }
4619
    s = net_socket_fd_init(vlan, fd, connected);
4620
    if (!s)
4621
        return -1;
4622
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4623
             "socket: connect to %s:%d",
4624
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4625
    return 0;
4626
}
4627

    
4628
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4629
{
4630
    NetSocketState *s;
4631
    int fd;
4632
    struct sockaddr_in saddr;
4633

    
4634
    if (parse_host_port(&saddr, host_str) < 0)
4635
        return -1;
4636

    
4637

    
4638
    fd = net_socket_mcast_create(&saddr);
4639
    if (fd < 0)
4640
        return -1;
4641

    
4642
    s = net_socket_fd_init(vlan, fd, 0);
4643
    if (!s)
4644
        return -1;
4645

    
4646
    s->dgram_dst = saddr;
4647

    
4648
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4649
             "socket: mcast=%s:%d",
4650
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4651
    return 0;
4652

    
4653
}
4654

    
4655
static const char *get_opt_name(char *buf, int buf_size, const char *p)
4656
{
4657
    char *q;
4658

    
4659
    q = buf;
4660
    while (*p != '\0' && *p != '=') {
4661
        if (q && (q - buf) < buf_size - 1)
4662
            *q++ = *p;
4663
        p++;
4664
    }
4665
    if (q)
4666
        *q = '\0';
4667

    
4668
    return p;
4669
}
4670

    
4671
static const char *get_opt_value(char *buf, int buf_size, const char *p)
4672
{
4673
    char *q;
4674

    
4675
    q = buf;
4676
    while (*p != '\0') {
4677
        if (*p == ',') {
4678
            if (*(p + 1) != ',')
4679
                break;
4680
            p++;
4681
        }
4682
        if (q && (q - buf) < buf_size - 1)
4683
            *q++ = *p;
4684
        p++;
4685
    }
4686
    if (q)
4687
        *q = '\0';
4688

    
4689
    return p;
4690
}
4691

    
4692
static int get_param_value(char *buf, int buf_size,
4693
                           const char *tag, const char *str)
4694
{
4695
    const char *p;
4696
    char option[128];
4697

    
4698
    p = str;
4699
    for(;;) {
4700
        p = get_opt_name(option, sizeof(option), p);
4701
        if (*p != '=')
4702
            break;
4703
        p++;
4704
        if (!strcmp(tag, option)) {
4705
            (void)get_opt_value(buf, buf_size, p);
4706
            return strlen(buf);
4707
        } else {
4708
            p = get_opt_value(NULL, 0, p);
4709
        }
4710
        if (*p != ',')
4711
            break;
4712
        p++;
4713
    }
4714
    return 0;
4715
}
4716

    
4717
static int check_params(char *buf, int buf_size,
4718
                        char **params, const char *str)
4719
{
4720
    const char *p;
4721
    int i;
4722

    
4723
    p = str;
4724
    for(;;) {
4725
        p = get_opt_name(buf, buf_size, p);
4726
        if (*p != '=')
4727
            return -1;
4728
        p++;
4729
        for(i = 0; params[i] != NULL; i++)
4730
            if (!strcmp(params[i], buf))
4731
                break;
4732
        if (params[i] == NULL)
4733
            return -1;
4734
        p = get_opt_value(NULL, 0, p);
4735
        if (*p != ',')
4736
            break;
4737
        p++;
4738
    }
4739
    return 0;
4740
}
4741

    
4742

    
4743
static int net_client_init(const char *str)
4744
{
4745
    const char *p;
4746
    char *q;
4747
    char device[64];
4748
    char buf[1024];
4749
    int vlan_id, ret;
4750
    VLANState *vlan;
4751

    
4752
    p = str;
4753
    q = device;
4754
    while (*p != '\0' && *p != ',') {
4755
        if ((q - device) < sizeof(device) - 1)
4756
            *q++ = *p;
4757
        p++;
4758
    }
4759
    *q = '\0';
4760
    if (*p == ',')
4761
        p++;
4762
    vlan_id = 0;
4763
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4764
        vlan_id = strtol(buf, NULL, 0);
4765
    }
4766
    vlan = qemu_find_vlan(vlan_id);
4767
    if (!vlan) {
4768
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4769
        return -1;
4770
    }
4771
    if (!strcmp(device, "nic")) {
4772
        NICInfo *nd;
4773
        uint8_t *macaddr;
4774

    
4775
        if (nb_nics >= MAX_NICS) {
4776
            fprintf(stderr, "Too Many NICs\n");
4777
            return -1;
4778
        }
4779
        nd = &nd_table[nb_nics];
4780
        macaddr = nd->macaddr;
4781
        macaddr[0] = 0x52;
4782
        macaddr[1] = 0x54;
4783
        macaddr[2] = 0x00;
4784
        macaddr[3] = 0x12;
4785
        macaddr[4] = 0x34;
4786
        macaddr[5] = 0x56 + nb_nics;
4787

    
4788
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4789
            if (parse_macaddr(macaddr, buf) < 0) {
4790
                fprintf(stderr, "invalid syntax for ethernet address\n");
4791
                return -1;
4792
            }
4793
        }
4794
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4795
            nd->model = strdup(buf);
4796
        }
4797
        nd->vlan = vlan;
4798
        nb_nics++;
4799
        vlan->nb_guest_devs++;
4800
        ret = 0;
4801
    } else
4802
    if (!strcmp(device, "none")) {
4803
        /* does nothing. It is needed to signal that no network cards
4804
           are wanted */
4805
        ret = 0;
4806
    } else
4807
#ifdef CONFIG_SLIRP
4808
    if (!strcmp(device, "user")) {
4809
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4810
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4811
        }
4812
        vlan->nb_host_devs++;
4813
        ret = net_slirp_init(vlan);
4814
    } else
4815
#endif
4816
#ifdef _WIN32
4817
    if (!strcmp(device, "tap")) {
4818
        char ifname[64];
4819
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4820
            fprintf(stderr, "tap: no interface name\n");
4821
            return -1;
4822
        }
4823
        vlan->nb_host_devs++;
4824
        ret = tap_win32_init(vlan, ifname);
4825
    } else
4826
#else
4827
    if (!strcmp(device, "tap")) {
4828
        char ifname[64];
4829
        char setup_script[1024], down_script[1024];
4830
        int fd;
4831
        vlan->nb_host_devs++;
4832
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4833
            fd = strtol(buf, NULL, 0);
4834
            fcntl(fd, F_SETFL, O_NONBLOCK);
4835
            ret = -1;
4836
            if (net_tap_fd_init(vlan, fd))
4837
                ret = 0;
4838
        } else {
4839
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4840
                ifname[0] = '\0';
4841
            }
4842
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4843
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4844
            }
4845
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4846
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4847
            }
4848
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
4849
        }
4850
    } else
4851
#endif
4852
    if (!strcmp(device, "socket")) {
4853
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4854
            int fd;
4855
            fd = strtol(buf, NULL, 0);
4856
            ret = -1;
4857
            if (net_socket_fd_init(vlan, fd, 1))
4858
                ret = 0;
4859
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4860
            ret = net_socket_listen_init(vlan, buf);
4861
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4862
            ret = net_socket_connect_init(vlan, buf);
4863
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4864
            ret = net_socket_mcast_init(vlan, buf);
4865
        } else {
4866
            fprintf(stderr, "Unknown socket options: %s\n", p);
4867
            return -1;
4868
        }
4869
        vlan->nb_host_devs++;
4870
    } else
4871
    {
4872
        fprintf(stderr, "Unknown network device: %s\n", device);
4873
        return -1;
4874
    }
4875
    if (ret < 0) {
4876
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4877
    }
4878

    
4879
    return ret;
4880
}
4881

    
4882
void do_info_network(void)
4883
{
4884
    VLANState *vlan;
4885
    VLANClientState *vc;
4886

    
4887
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4888
        term_printf("VLAN %d devices:\n", vlan->id);
4889
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4890
            term_printf("  %s\n", vc->info_str);
4891
    }
4892
}
4893

    
4894
#define HD_ALIAS "index=%d,media=disk"
4895
#ifdef TARGET_PPC
4896
#define CDROM_ALIAS "index=1,media=cdrom"
4897
#else
4898
#define CDROM_ALIAS "index=2,media=cdrom"
4899
#endif
4900
#define FD_ALIAS "index=%d,if=floppy"
4901
#define PFLASH_ALIAS "if=pflash"
4902
#define MTD_ALIAS "if=mtd"
4903
#define SD_ALIAS "index=0,if=sd"
4904

    
4905
static int drive_add(const char *file, const char *fmt, ...)
4906
{
4907
    va_list ap;
4908

    
4909
    if (nb_drives_opt >= MAX_DRIVES) {
4910
        fprintf(stderr, "qemu: too many drives\n");
4911
        exit(1);
4912
    }
4913

    
4914
    drives_opt[nb_drives_opt].file = file;
4915
    va_start(ap, fmt);
4916
    vsnprintf(drives_opt[nb_drives_opt].opt,
4917
              sizeof(drives_opt[0].opt), fmt, ap);
4918
    va_end(ap);
4919

    
4920
    return nb_drives_opt++;
4921
}
4922

    
4923
int drive_get_index(BlockInterfaceType type, int bus, int unit)
4924
{
4925
    int index;
4926

    
4927
    /* seek interface, bus and unit */
4928

    
4929
    for (index = 0; index < nb_drives; index++)
4930
        if (drives_table[index].type == type &&
4931
            drives_table[index].bus == bus &&
4932
            drives_table[index].unit == unit)
4933
        return index;
4934

    
4935
    return -1;
4936
}
4937

    
4938
int drive_get_max_bus(BlockInterfaceType type)
4939
{
4940
    int max_bus;
4941
    int index;
4942

    
4943
    max_bus = -1;
4944
    for (index = 0; index < nb_drives; index++) {
4945
        if(drives_table[index].type == type &&
4946
           drives_table[index].bus > max_bus)
4947
            max_bus = drives_table[index].bus;
4948
    }
4949
    return max_bus;
4950
}
4951

    
4952
static void bdrv_format_print(void *opaque, const char *name)
4953
{
4954
    fprintf(stderr, " %s", name);
4955
}
4956

    
4957
static int drive_init(struct drive_opt *arg, int snapshot,
4958
                      QEMUMachine *machine)
4959
{
4960
    char buf[128];
4961
    char file[1024];
4962
    char devname[128];
4963
    const char *mediastr = "";
4964
    BlockInterfaceType type;
4965
    enum { MEDIA_DISK, MEDIA_CDROM } media;
4966
    int bus_id, unit_id;
4967
    int cyls, heads, secs, translation;
4968
    BlockDriverState *bdrv;
4969
    BlockDriver *drv = NULL;
4970
    int max_devs;
4971
    int index;
4972
    int cache;
4973
    int bdrv_flags;
4974
    char *str = arg->opt;
4975
    char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4976
                       "secs", "trans", "media", "snapshot", "file",
4977
                       "cache", "format", NULL };
4978

    
4979
    if (check_params(buf, sizeof(buf), params, str) < 0) {
4980
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
4981
                         buf, str);
4982
         return -1;
4983
    }
4984

    
4985
    file[0] = 0;
4986
    cyls = heads = secs = 0;
4987
    bus_id = 0;
4988
    unit_id = -1;
4989
    translation = BIOS_ATA_TRANSLATION_AUTO;
4990
    index = -1;
4991
    cache = 1;
4992

    
4993
    if (!strcmp(machine->name, "realview") ||
4994
        !strcmp(machine->name, "SS-5") ||
4995
        !strcmp(machine->name, "SS-10") ||
4996
        !strcmp(machine->name, "SS-600MP") ||
4997
        !strcmp(machine->name, "versatilepb") ||
4998
        !strcmp(machine->name, "versatileab")) {
4999
        type = IF_SCSI;
5000
        max_devs = MAX_SCSI_DEVS;
5001
        strcpy(devname, "scsi");
5002
    } else {
5003
        type = IF_IDE;
5004
        max_devs = MAX_IDE_DEVS;
5005
        strcpy(devname, "ide");
5006
    }
5007
    media = MEDIA_DISK;
5008

    
5009
    /* extract parameters */
5010

    
5011
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
5012
        bus_id = strtol(buf, NULL, 0);
5013
        if (bus_id < 0) {
5014
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5015
            return -1;
5016
        }
5017
    }
5018

    
5019
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
5020
        unit_id = strtol(buf, NULL, 0);
5021
        if (unit_id < 0) {
5022
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5023
            return -1;
5024
        }
5025
    }
5026

    
5027
    if (get_param_value(buf, sizeof(buf), "if", str)) {
5028
        strncpy(devname, buf, sizeof(devname));
5029
        if (!strcmp(buf, "ide")) {
5030
            type = IF_IDE;
5031
            max_devs = MAX_IDE_DEVS;
5032
        } else if (!strcmp(buf, "scsi")) {
5033
            type = IF_SCSI;
5034
            max_devs = MAX_SCSI_DEVS;
5035
        } else if (!strcmp(buf, "floppy")) {
5036
            type = IF_FLOPPY;
5037
            max_devs = 0;
5038
        } else if (!strcmp(buf, "pflash")) {
5039
            type = IF_PFLASH;
5040
            max_devs = 0;
5041
        } else if (!strcmp(buf, "mtd")) {
5042
            type = IF_MTD;
5043
            max_devs = 0;
5044
        } else if (!strcmp(buf, "sd")) {
5045
            type = IF_SD;
5046
            max_devs = 0;
5047
        } else {
5048
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5049
            return -1;
5050
        }
5051
    }
5052

    
5053
    if (get_param_value(buf, sizeof(buf), "index", str)) {
5054
        index = strtol(buf, NULL, 0);
5055
        if (index < 0) {
5056
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
5057
            return -1;
5058
        }
5059
    }
5060

    
5061
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5062
        cyls = strtol(buf, NULL, 0);
5063
    }
5064

    
5065
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
5066
        heads = strtol(buf, NULL, 0);
5067
    }
5068

    
5069
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
5070
        secs = strtol(buf, NULL, 0);
5071
    }
5072

    
5073
    if (cyls || heads || secs) {
5074
        if (cyls < 1 || cyls > 16383) {
5075
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5076
            return -1;
5077
        }
5078
        if (heads < 1 || heads > 16) {
5079
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5080
            return -1;
5081
        }
5082
        if (secs < 1 || secs > 63) {
5083
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5084
            return -1;
5085
        }
5086
    }
5087

    
5088
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
5089
        if (!cyls) {
5090
            fprintf(stderr,
5091
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
5092
                    str);
5093
            return -1;
5094
        }
5095
        if (!strcmp(buf, "none"))
5096
            translation = BIOS_ATA_TRANSLATION_NONE;
5097
        else if (!strcmp(buf, "lba"))
5098
            translation = BIOS_ATA_TRANSLATION_LBA;
5099
        else if (!strcmp(buf, "auto"))
5100
            translation = BIOS_ATA_TRANSLATION_AUTO;
5101
        else {
5102
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5103
            return -1;
5104
        }
5105
    }
5106

    
5107
    if (get_param_value(buf, sizeof(buf), "media", str)) {
5108
        if (!strcmp(buf, "disk")) {
5109
            media = MEDIA_DISK;
5110
        } else if (!strcmp(buf, "cdrom")) {
5111
            if (cyls || secs || heads) {
5112
                fprintf(stderr,
5113
                        "qemu: '%s' invalid physical CHS format\n", str);
5114
                return -1;
5115
            }
5116
            media = MEDIA_CDROM;
5117
        } else {
5118
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
5119
            return -1;
5120
        }
5121
    }
5122

    
5123
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5124
        if (!strcmp(buf, "on"))
5125
            snapshot = 1;
5126
        else if (!strcmp(buf, "off"))
5127
            snapshot = 0;
5128
        else {
5129
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5130
            return -1;
5131
        }
5132
    }
5133

    
5134
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
5135
        if (!strcmp(buf, "off"))
5136
            cache = 0;
5137
        else if (!strcmp(buf, "on"))
5138
            cache = 1;
5139
        else {
5140
           fprintf(stderr, "qemu: invalid cache option\n");
5141
           return -1;
5142
        }
5143
    }
5144

    
5145
    if (get_param_value(buf, sizeof(buf), "format", str)) {
5146
       if (strcmp(buf, "?") == 0) {
5147
            fprintf(stderr, "qemu: Supported formats:");
5148
            bdrv_iterate_format(bdrv_format_print, NULL);
5149
            fprintf(stderr, "\n");
5150
            return -1;
5151
        }
5152
        drv = bdrv_find_format(buf);
5153
        if (!drv) {
5154
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5155
            return -1;
5156
        }
5157
    }
5158

    
5159
    if (arg->file == NULL)
5160
        get_param_value(file, sizeof(file), "file", str);
5161
    else
5162
        pstrcpy(file, sizeof(file), arg->file);
5163

    
5164
    /* compute bus and unit according index */
5165

    
5166
    if (index != -1) {
5167
        if (bus_id != 0 || unit_id != -1) {
5168
            fprintf(stderr,
5169
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
5170
            return -1;
5171
        }
5172
        if (max_devs == 0)
5173
        {
5174
            unit_id = index;
5175
            bus_id = 0;
5176
        } else {
5177
            unit_id = index % max_devs;
5178
            bus_id = index / max_devs;
5179
        }
5180
    }
5181

    
5182
    /* if user doesn't specify a unit_id,
5183
     * try to find the first free
5184
     */
5185

    
5186
    if (unit_id == -1) {
5187
       unit_id = 0;
5188
       while (drive_get_index(type, bus_id, unit_id) != -1) {
5189
           unit_id++;
5190
           if (max_devs && unit_id >= max_devs) {
5191
               unit_id -= max_devs;
5192
               bus_id++;
5193
           }
5194
       }
5195
    }
5196

    
5197
    /* check unit id */
5198

    
5199
    if (max_devs && unit_id >= max_devs) {
5200
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5201
                        str, unit_id, max_devs - 1);
5202
        return -1;
5203
    }
5204

    
5205
    /*
5206
     * ignore multiple definitions
5207
     */
5208

    
5209
    if (drive_get_index(type, bus_id, unit_id) != -1)
5210
        return 0;
5211

    
5212
    /* init */
5213

    
5214
    if (type == IF_IDE || type == IF_SCSI)
5215
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5216
    if (max_devs)
5217
        snprintf(buf, sizeof(buf), "%s%i%s%i",
5218
                 devname, bus_id, mediastr, unit_id);
5219
    else
5220
        snprintf(buf, sizeof(buf), "%s%s%i",
5221
                 devname, mediastr, unit_id);
5222
    bdrv = bdrv_new(buf);
5223
    drives_table[nb_drives].bdrv = bdrv;
5224
    drives_table[nb_drives].type = type;
5225
    drives_table[nb_drives].bus = bus_id;
5226
    drives_table[nb_drives].unit = unit_id;
5227
    nb_drives++;
5228

    
5229
    switch(type) {
5230
    case IF_IDE:
5231
    case IF_SCSI:
5232
        switch(media) {
5233
        case MEDIA_DISK:
5234
            if (cyls != 0) {
5235
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5236
                bdrv_set_translation_hint(bdrv, translation);
5237
            }
5238
            break;
5239
        case MEDIA_CDROM:
5240
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5241
            break;
5242
        }
5243
        break;
5244
    case IF_SD:
5245
        /* FIXME: This isn't really a floppy, but it's a reasonable
5246
           approximation.  */
5247
    case IF_FLOPPY:
5248
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5249
        break;
5250
    case IF_PFLASH:
5251
    case IF_MTD:
5252
        break;
5253
    }
5254
    if (!file[0])
5255
        return 0;
5256
    bdrv_flags = 0;
5257
    if (snapshot)
5258
        bdrv_flags |= BDRV_O_SNAPSHOT;
5259
    if (!cache)
5260
        bdrv_flags |= BDRV_O_DIRECT;
5261
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5262
        fprintf(stderr, "qemu: could not open disk image %s\n",
5263
                        file);
5264
        return -1;
5265
    }
5266
    return 0;
5267
}
5268

    
5269
/***********************************************************/
5270
/* USB devices */
5271

    
5272
static USBPort *used_usb_ports;
5273
static USBPort *free_usb_ports;
5274

    
5275
/* ??? Maybe change this to register a hub to keep track of the topology.  */
5276
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5277
                            usb_attachfn attach)
5278
{
5279
    port->opaque = opaque;
5280
    port->index = index;
5281
    port->attach = attach;
5282
    port->next = free_usb_ports;
5283
    free_usb_ports = port;
5284
}
5285

    
5286
static int usb_device_add(const char *devname)
5287
{
5288
    const char *p;
5289
    USBDevice *dev;
5290
    USBPort *port;
5291

    
5292
    if (!free_usb_ports)
5293
        return -1;
5294

    
5295
    if (strstart(devname, "host:", &p)) {
5296
        dev = usb_host_device_open(p);
5297
    } else if (!strcmp(devname, "mouse")) {
5298
        dev = usb_mouse_init();
5299
    } else if (!strcmp(devname, "tablet")) {
5300
        dev = usb_tablet_init();
5301
    } else if (!strcmp(devname, "keyboard")) {
5302
        dev = usb_keyboard_init();
5303
    } else if (strstart(devname, "disk:", &p)) {
5304
        dev = usb_msd_init(p);
5305
    } else if (!strcmp(devname, "wacom-tablet")) {
5306
        dev = usb_wacom_init();
5307
    } else if (strstart(devname, "serial:", &p)) {
5308
        dev = usb_serial_init(p);
5309
#ifdef CONFIG_BRLAPI
5310
    } else if (!strcmp(devname, "braille")) {
5311
        dev = usb_baum_init();
5312
#endif
5313
    } else {
5314
        return -1;
5315
    }
5316
    if (!dev)
5317
        return -1;
5318

    
5319
    /* Find a USB port to add the device to.  */
5320
    port = free_usb_ports;
5321
    if (!port->next) {
5322
        USBDevice *hub;
5323

    
5324
        /* Create a new hub and chain it on.  */
5325
        free_usb_ports = NULL;
5326
        port->next = used_usb_ports;
5327
        used_usb_ports = port;
5328

    
5329
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5330
        usb_attach(port, hub);
5331
        port = free_usb_ports;
5332
    }
5333

    
5334
    free_usb_ports = port->next;
5335
    port->next = used_usb_ports;
5336
    used_usb_ports = port;
5337
    usb_attach(port, dev);
5338
    return 0;
5339
}
5340

    
5341
static int usb_device_del(const char *devname)
5342
{
5343
    USBPort *port;
5344
    USBPort **lastp;
5345
    USBDevice *dev;
5346
    int bus_num, addr;
5347
    const char *p;
5348

    
5349
    if (!used_usb_ports)
5350
        return -1;
5351

    
5352
    p = strchr(devname, '.');
5353
    if (!p)
5354
        return -1;
5355
    bus_num = strtoul(devname, NULL, 0);
5356
    addr = strtoul(p + 1, NULL, 0);
5357
    if (bus_num != 0)
5358
        return -1;
5359

    
5360
    lastp = &used_usb_ports;
5361
    port = used_usb_ports;
5362
    while (port && port->dev->addr != addr) {
5363
        lastp = &port->next;
5364
        port = port->next;
5365
    }
5366

    
5367
    if (!port)
5368
        return -1;
5369

    
5370
    dev = port->dev;
5371
    *lastp = port->next;
5372
    usb_attach(port, NULL);
5373
    dev->handle_destroy(dev);
5374
    port->next = free_usb_ports;
5375
    free_usb_ports = port;
5376
    return 0;
5377
}
5378

    
5379
void do_usb_add(const char *devname)
5380
{
5381
    int ret;
5382
    ret = usb_device_add(devname);
5383
    if (ret < 0)
5384
        term_printf("Could not add USB device '%s'\n", devname);
5385
}
5386

    
5387
void do_usb_del(const char *devname)
5388
{
5389
    int ret;
5390
    ret = usb_device_del(devname);
5391
    if (ret < 0)
5392
        term_printf("Could not remove USB device '%s'\n", devname);
5393
}
5394

    
5395
void usb_info(void)
5396
{
5397
    USBDevice *dev;
5398
    USBPort *port;
5399
    const char *speed_str;
5400

    
5401
    if (!usb_enabled) {
5402
        term_printf("USB support not enabled\n");
5403
        return;
5404
    }
5405

    
5406
    for (port = used_usb_ports; port; port = port->next) {
5407
        dev = port->dev;
5408
        if (!dev)
5409
            continue;
5410
        switch(dev->speed) {
5411
        case USB_SPEED_LOW:
5412
            speed_str = "1.5";
5413
            break;
5414
        case USB_SPEED_FULL:
5415
            speed_str = "12";
5416
            break;
5417
        case USB_SPEED_HIGH:
5418
            speed_str = "480";
5419
            break;
5420
        default:
5421
            speed_str = "?";
5422
            break;
5423
        }
5424
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
5425
                    0, dev->addr, speed_str, dev->devname);
5426
    }
5427
}
5428

    
5429
/***********************************************************/
5430
/* PCMCIA/Cardbus */
5431

    
5432
static struct pcmcia_socket_entry_s {
5433
    struct pcmcia_socket_s *socket;
5434
    struct pcmcia_socket_entry_s *next;
5435
} *pcmcia_sockets = 0;
5436

    
5437
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5438
{
5439
    struct pcmcia_socket_entry_s *entry;
5440

    
5441
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5442
    entry->socket = socket;
5443
    entry->next = pcmcia_sockets;
5444
    pcmcia_sockets = entry;
5445
}
5446

    
5447
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5448
{
5449
    struct pcmcia_socket_entry_s *entry, **ptr;
5450

    
5451
    ptr = &pcmcia_sockets;
5452
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5453
        if (entry->socket == socket) {
5454
            *ptr = entry->next;
5455
            qemu_free(entry);
5456
        }
5457
}
5458

    
5459
void pcmcia_info(void)
5460
{
5461
    struct pcmcia_socket_entry_s *iter;
5462
    if (!pcmcia_sockets)
5463
        term_printf("No PCMCIA sockets\n");
5464

    
5465
    for (iter = pcmcia_sockets; iter; iter = iter->next)
5466
        term_printf("%s: %s\n", iter->socket->slot_string,
5467
                    iter->socket->attached ? iter->socket->card_string :
5468
                    "Empty");
5469
}
5470

    
5471
/***********************************************************/
5472
/* dumb display */
5473

    
5474
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5475
{
5476
}
5477

    
5478
static void dumb_resize(DisplayState *ds, int w, int h)
5479
{
5480
}
5481

    
5482
static void dumb_refresh(DisplayState *ds)
5483
{
5484
#if defined(CONFIG_SDL)
5485
    vga_hw_update();
5486
#endif
5487
}
5488

    
5489
static void dumb_display_init(DisplayState *ds)
5490
{
5491
    ds->data = NULL;
5492
    ds->linesize = 0;
5493
    ds->depth = 0;
5494
    ds->dpy_update = dumb_update;
5495
    ds->dpy_resize = dumb_resize;
5496
    ds->dpy_refresh = dumb_refresh;
5497
}
5498

    
5499
/***********************************************************/
5500
/* I/O handling */
5501

    
5502
#define MAX_IO_HANDLERS 64
5503

    
5504
typedef struct IOHandlerRecord {
5505
    int fd;
5506
    IOCanRWHandler *fd_read_poll;
5507
    IOHandler *fd_read;
5508
    IOHandler *fd_write;
5509
    int deleted;
5510
    void *opaque;
5511
    /* temporary data */
5512
    struct pollfd *ufd;
5513
    struct IOHandlerRecord *next;
5514
} IOHandlerRecord;
5515

    
5516
static IOHandlerRecord *first_io_handler;
5517

    
5518
/* XXX: fd_read_poll should be suppressed, but an API change is
5519
   necessary in the character devices to suppress fd_can_read(). */
5520
int qemu_set_fd_handler2(int fd,
5521
                         IOCanRWHandler *fd_read_poll,
5522
                         IOHandler *fd_read,
5523
                         IOHandler *fd_write,
5524
                         void *opaque)
5525
{
5526
    IOHandlerRecord **pioh, *ioh;
5527

    
5528
    if (!fd_read && !fd_write) {
5529
        pioh = &first_io_handler;
5530
        for(;;) {
5531
            ioh = *pioh;
5532
            if (ioh == NULL)
5533
                break;
5534
            if (ioh->fd == fd) {
5535
                ioh->deleted = 1;
5536
                break;
5537
            }
5538
            pioh = &ioh->next;
5539
        }
5540
    } else {
5541
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5542
            if (ioh->fd == fd)
5543
                goto found;
5544
        }
5545
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5546
        if (!ioh)
5547
            return -1;
5548
        ioh->next = first_io_handler;
5549
        first_io_handler = ioh;
5550
    found:
5551
        ioh->fd = fd;
5552
        ioh->fd_read_poll = fd_read_poll;
5553
        ioh->fd_read = fd_read;
5554
        ioh->fd_write = fd_write;
5555
        ioh->opaque = opaque;
5556
        ioh->deleted = 0;
5557
    }
5558
    return 0;
5559
}
5560

    
5561
int qemu_set_fd_handler(int fd,
5562
                        IOHandler *fd_read,
5563
                        IOHandler *fd_write,
5564
                        void *opaque)
5565
{
5566
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5567
}
5568

    
5569
/***********************************************************/
5570
/* Polling handling */
5571

    
5572
typedef struct PollingEntry {
5573
    PollingFunc *func;
5574
    void *opaque;
5575
    struct PollingEntry *next;
5576
} PollingEntry;
5577

    
5578
static PollingEntry *first_polling_entry;
5579

    
5580
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5581
{
5582
    PollingEntry **ppe, *pe;
5583
    pe = qemu_mallocz(sizeof(PollingEntry));
5584
    if (!pe)
5585
        return -1;
5586
    pe->func = func;
5587
    pe->opaque = opaque;
5588
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5589
    *ppe = pe;
5590
    return 0;
5591
}
5592

    
5593
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5594
{
5595
    PollingEntry **ppe, *pe;
5596
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5597
        pe = *ppe;
5598
        if (pe->func == func && pe->opaque == opaque) {
5599
            *ppe = pe->next;
5600
            qemu_free(pe);
5601
            break;
5602
        }
5603
    }
5604
}
5605

    
5606
#ifdef _WIN32
5607
/***********************************************************/
5608
/* Wait objects support */
5609
typedef struct WaitObjects {
5610
    int num;
5611
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5612
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5613
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5614
} WaitObjects;
5615

    
5616
static WaitObjects wait_objects = {0};
5617

    
5618
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5619
{
5620
    WaitObjects *w = &wait_objects;
5621

    
5622
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
5623
        return -1;
5624
    w->events[w->num] = handle;
5625
    w->func[w->num] = func;
5626
    w->opaque[w->num] = opaque;
5627
    w->num++;
5628
    return 0;
5629
}
5630

    
5631
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5632
{
5633
    int i, found;
5634
    WaitObjects *w = &wait_objects;
5635

    
5636
    found = 0;
5637
    for (i = 0; i < w->num; i++) {
5638
        if (w->events[i] == handle)
5639
            found = 1;
5640
        if (found) {
5641
            w->events[i] = w->events[i + 1];
5642
            w->func[i] = w->func[i + 1];
5643
            w->opaque[i] = w->opaque[i + 1];
5644
        }
5645
    }
5646
    if (found)
5647
        w->num--;
5648
}
5649
#endif
5650

    
5651
/***********************************************************/
5652
/* savevm/loadvm support */
5653

    
5654
#define IO_BUF_SIZE 32768
5655

    
5656
struct QEMUFile {
5657
    FILE *outfile;
5658
    BlockDriverState *bs;
5659
    int is_file;
5660
    int is_writable;
5661
    int64_t base_offset;
5662
    int64_t buf_offset; /* start of buffer when writing, end of buffer
5663
                           when reading */
5664
    int buf_index;
5665
    int buf_size; /* 0 when writing */
5666
    uint8_t buf[IO_BUF_SIZE];
5667
};
5668

    
5669
QEMUFile *qemu_fopen(const char *filename, const char *mode)
5670
{
5671
    QEMUFile *f;
5672

    
5673
    f = qemu_mallocz(sizeof(QEMUFile));
5674
    if (!f)
5675
        return NULL;
5676
    if (!strcmp(mode, "wb")) {
5677
        f->is_writable = 1;
5678
    } else if (!strcmp(mode, "rb")) {
5679
        f->is_writable = 0;
5680
    } else {
5681
        goto fail;
5682
    }
5683
    f->outfile = fopen(filename, mode);
5684
    if (!f->outfile)
5685
        goto fail;
5686
    f->is_file = 1;
5687
    return f;
5688
 fail:
5689
    if (f->outfile)
5690
        fclose(f->outfile);
5691
    qemu_free(f);
5692
    return NULL;
5693
}
5694

    
5695
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5696
{
5697
    QEMUFile *f;
5698

    
5699
    f = qemu_mallocz(sizeof(QEMUFile));
5700
    if (!f)
5701
        return NULL;
5702
    f->is_file = 0;
5703
    f->bs = bs;
5704
    f->is_writable = is_writable;
5705
    f->base_offset = offset;
5706
    return f;
5707
}
5708

    
5709
void qemu_fflush(QEMUFile *f)
5710
{
5711
    if (!f->is_writable)
5712
        return;
5713
    if (f->buf_index > 0) {
5714
        if (f->is_file) {
5715
            fseek(f->outfile, f->buf_offset, SEEK_SET);
5716
            fwrite(f->buf, 1, f->buf_index, f->outfile);
5717
        } else {
5718
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5719
                        f->buf, f->buf_index);
5720
        }
5721
        f->buf_offset += f->buf_index;
5722
        f->buf_index = 0;
5723
    }
5724
}
5725

    
5726
static void qemu_fill_buffer(QEMUFile *f)
5727
{
5728
    int len;
5729

    
5730
    if (f->is_writable)
5731
        return;
5732
    if (f->is_file) {
5733
        fseek(f->outfile, f->buf_offset, SEEK_SET);
5734
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5735
        if (len < 0)
5736
            len = 0;
5737
    } else {
5738
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5739
                         f->buf, IO_BUF_SIZE);
5740
        if (len < 0)
5741
            len = 0;
5742
    }
5743
    f->buf_index = 0;
5744
    f->buf_size = len;
5745
    f->buf_offset += len;
5746
}
5747

    
5748
void qemu_fclose(QEMUFile *f)
5749
{
5750
    if (f->is_writable)
5751
        qemu_fflush(f);
5752
    if (f->is_file) {
5753
        fclose(f->outfile);
5754
    }
5755
    qemu_free(f);
5756
}
5757

    
5758
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5759
{
5760
    int l;
5761
    while (size > 0) {
5762
        l = IO_BUF_SIZE - f->buf_index;
5763
        if (l > size)
5764
            l = size;
5765
        memcpy(f->buf + f->buf_index, buf, l);
5766
        f->buf_index += l;
5767
        buf += l;
5768
        size -= l;
5769
        if (f->buf_index >= IO_BUF_SIZE)
5770
            qemu_fflush(f);
5771
    }
5772
}
5773

    
5774
void qemu_put_byte(QEMUFile *f, int v)
5775
{
5776
    f->buf[f->buf_index++] = v;
5777
    if (f->buf_index >= IO_BUF_SIZE)
5778
        qemu_fflush(f);
5779
}
5780

    
5781
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5782
{
5783
    int size, l;
5784

    
5785
    size = size1;
5786
    while (size > 0) {
5787
        l = f->buf_size - f->buf_index;
5788
        if (l == 0) {
5789
            qemu_fill_buffer(f);
5790
            l = f->buf_size - f->buf_index;
5791
            if (l == 0)
5792
                break;
5793
        }
5794
        if (l > size)
5795
            l = size;
5796
        memcpy(buf, f->buf + f->buf_index, l);
5797
        f->buf_index += l;
5798
        buf += l;
5799
        size -= l;
5800
    }
5801
    return size1 - size;
5802
}
5803

    
5804
int qemu_get_byte(QEMUFile *f)
5805
{
5806
    if (f->buf_index >= f->buf_size) {
5807
        qemu_fill_buffer(f);
5808
        if (f->buf_index >= f->buf_size)
5809
            return 0;
5810
    }
5811
    return f->buf[f->buf_index++];
5812
}
5813

    
5814
int64_t qemu_ftell(QEMUFile *f)
5815
{
5816
    return f->buf_offset - f->buf_size + f->buf_index;
5817
}
5818

    
5819
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5820
{
5821
    if (whence == SEEK_SET) {
5822
        /* nothing to do */
5823
    } else if (whence == SEEK_CUR) {
5824
        pos += qemu_ftell(f);
5825
    } else {
5826
        /* SEEK_END not supported */
5827
        return -1;
5828
    }
5829
    if (f->is_writable) {
5830
        qemu_fflush(f);
5831
        f->buf_offset = pos;
5832
    } else {
5833
        f->buf_offset = pos;
5834
        f->buf_index = 0;
5835
        f->buf_size = 0;
5836
    }
5837
    return pos;
5838
}
5839

    
5840
void qemu_put_be16(QEMUFile *f, unsigned int v)
5841
{
5842
    qemu_put_byte(f, v >> 8);
5843
    qemu_put_byte(f, v);
5844
}
5845

    
5846
void qemu_put_be32(QEMUFile *f, unsigned int v)
5847
{
5848
    qemu_put_byte(f, v >> 24);
5849
    qemu_put_byte(f, v >> 16);
5850
    qemu_put_byte(f, v >> 8);
5851
    qemu_put_byte(f, v);
5852
}
5853

    
5854
void qemu_put_be64(QEMUFile *f, uint64_t v)
5855
{
5856
    qemu_put_be32(f, v >> 32);
5857
    qemu_put_be32(f, v);
5858
}
5859

    
5860
unsigned int qemu_get_be16(QEMUFile *f)
5861
{
5862
    unsigned int v;
5863
    v = qemu_get_byte(f) << 8;
5864
    v |= qemu_get_byte(f);
5865
    return v;
5866
}
5867

    
5868
unsigned int qemu_get_be32(QEMUFile *f)
5869
{
5870
    unsigned int v;
5871
    v = qemu_get_byte(f) << 24;
5872
    v |= qemu_get_byte(f) << 16;
5873
    v |= qemu_get_byte(f) << 8;
5874
    v |= qemu_get_byte(f);
5875
    return v;
5876
}
5877

    
5878
uint64_t qemu_get_be64(QEMUFile *f)
5879
{
5880
    uint64_t v;
5881
    v = (uint64_t)qemu_get_be32(f) << 32;
5882
    v |= qemu_get_be32(f);
5883
    return v;
5884
}
5885

    
5886
typedef struct SaveStateEntry {
5887
    char idstr[256];
5888
    int instance_id;
5889
    int version_id;
5890
    SaveStateHandler *save_state;
5891
    LoadStateHandler *load_state;
5892
    void *opaque;
5893
    struct SaveStateEntry *next;
5894
} SaveStateEntry;
5895

    
5896
static SaveStateEntry *first_se;
5897

    
5898
int register_savevm(const char *idstr,
5899
                    int instance_id,
5900
                    int version_id,
5901
                    SaveStateHandler *save_state,
5902
                    LoadStateHandler *load_state,
5903
                    void *opaque)
5904
{
5905
    SaveStateEntry *se, **pse;
5906

    
5907
    se = qemu_malloc(sizeof(SaveStateEntry));
5908
    if (!se)
5909
        return -1;
5910
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5911
    se->instance_id = instance_id;
5912
    se->version_id = version_id;
5913
    se->save_state = save_state;
5914
    se->load_state = load_state;
5915
    se->opaque = opaque;
5916
    se->next = NULL;
5917

    
5918
    /* add at the end of list */
5919
    pse = &first_se;
5920
    while (*pse != NULL)
5921
        pse = &(*pse)->next;
5922
    *pse = se;
5923
    return 0;
5924
}
5925

    
5926
#define QEMU_VM_FILE_MAGIC   0x5145564d
5927
#define QEMU_VM_FILE_VERSION 0x00000002
5928

    
5929
static int qemu_savevm_state(QEMUFile *f)
5930
{
5931
    SaveStateEntry *se;
5932
    int len, ret;
5933
    int64_t cur_pos, len_pos, total_len_pos;
5934

    
5935
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5936
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5937
    total_len_pos = qemu_ftell(f);
5938
    qemu_put_be64(f, 0); /* total size */
5939

    
5940
    for(se = first_se; se != NULL; se = se->next) {
5941
        /* ID string */
5942
        len = strlen(se->idstr);
5943
        qemu_put_byte(f, len);
5944
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5945

    
5946
        qemu_put_be32(f, se->instance_id);
5947
        qemu_put_be32(f, se->version_id);
5948

    
5949
        /* record size: filled later */
5950
        len_pos = qemu_ftell(f);
5951
        qemu_put_be32(f, 0);
5952
        se->save_state(f, se->opaque);
5953

    
5954
        /* fill record size */
5955
        cur_pos = qemu_ftell(f);
5956
        len = cur_pos - len_pos - 4;
5957
        qemu_fseek(f, len_pos, SEEK_SET);
5958
        qemu_put_be32(f, len);
5959
        qemu_fseek(f, cur_pos, SEEK_SET);
5960
    }
5961
    cur_pos = qemu_ftell(f);
5962
    qemu_fseek(f, total_len_pos, SEEK_SET);
5963
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
5964
    qemu_fseek(f, cur_pos, SEEK_SET);
5965

    
5966
    ret = 0;
5967
    return ret;
5968
}
5969

    
5970
static SaveStateEntry *find_se(const char *idstr, int instance_id)
5971
{
5972
    SaveStateEntry *se;
5973

    
5974
    for(se = first_se; se != NULL; se = se->next) {
5975
        if (!strcmp(se->idstr, idstr) &&
5976
            instance_id == se->instance_id)
5977
            return se;
5978
    }
5979
    return NULL;
5980
}
5981

    
5982
static int qemu_loadvm_state(QEMUFile *f)
5983
{
5984
    SaveStateEntry *se;
5985
    int len, ret, instance_id, record_len, version_id;
5986
    int64_t total_len, end_pos, cur_pos;
5987
    unsigned int v;
5988
    char idstr[256];
5989

    
5990
    v = qemu_get_be32(f);
5991
    if (v != QEMU_VM_FILE_MAGIC)
5992
        goto fail;
5993
    v = qemu_get_be32(f);
5994
    if (v != QEMU_VM_FILE_VERSION) {
5995
    fail:
5996
        ret = -1;
5997
        goto the_end;
5998
    }
5999
    total_len = qemu_get_be64(f);
6000
    end_pos = total_len + qemu_ftell(f);
6001
    for(;;) {
6002
        if (qemu_ftell(f) >= end_pos)
6003
            break;
6004
        len = qemu_get_byte(f);
6005
        qemu_get_buffer(f, (uint8_t *)idstr, len);
6006
        idstr[len] = '\0';
6007
        instance_id = qemu_get_be32(f);
6008
        version_id = qemu_get_be32(f);
6009
        record_len = qemu_get_be32(f);
6010
#if 0
6011
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
6012
               idstr, instance_id, version_id, record_len);
6013
#endif
6014
        cur_pos = qemu_ftell(f);
6015
        se = find_se(idstr, instance_id);
6016
        if (!se) {
6017
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6018
                    instance_id, idstr);
6019
        } else {
6020
            ret = se->load_state(f, se->opaque, version_id);
6021
            if (ret < 0) {
6022
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6023
                        instance_id, idstr);
6024
            }
6025
        }
6026
        /* always seek to exact end of record */
6027
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6028
    }
6029
    ret = 0;
6030
 the_end:
6031
    return ret;
6032
}
6033

    
6034
/* device can contain snapshots */
6035
static int bdrv_can_snapshot(BlockDriverState *bs)
6036
{
6037
    return (bs &&
6038
            !bdrv_is_removable(bs) &&
6039
            !bdrv_is_read_only(bs));
6040
}
6041

    
6042
/* device must be snapshots in order to have a reliable snapshot */
6043
static int bdrv_has_snapshot(BlockDriverState *bs)
6044
{
6045
    return (bs &&
6046
            !bdrv_is_removable(bs) &&
6047
            !bdrv_is_read_only(bs));
6048
}
6049

    
6050
static BlockDriverState *get_bs_snapshots(void)
6051
{
6052
    BlockDriverState *bs;
6053
    int i;
6054

    
6055
    if (bs_snapshots)
6056
        return bs_snapshots;
6057
    for(i = 0; i <= nb_drives; i++) {
6058
        bs = drives_table[i].bdrv;
6059
        if (bdrv_can_snapshot(bs))
6060
            goto ok;
6061
    }
6062
    return NULL;
6063
 ok:
6064
    bs_snapshots = bs;
6065
    return bs;
6066
}
6067

    
6068
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6069
                              const char *name)
6070
{
6071
    QEMUSnapshotInfo *sn_tab, *sn;
6072
    int nb_sns, i, ret;
6073

    
6074
    ret = -ENOENT;
6075
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6076
    if (nb_sns < 0)
6077
        return ret;
6078
    for(i = 0; i < nb_sns; i++) {
6079
        sn = &sn_tab[i];
6080
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6081
            *sn_info = *sn;
6082
            ret = 0;
6083
            break;
6084
        }
6085
    }
6086
    qemu_free(sn_tab);
6087
    return ret;
6088
}
6089

    
6090
void do_savevm(const char *name)
6091
{
6092
    BlockDriverState *bs, *bs1;
6093
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6094
    int must_delete, ret, i;
6095
    BlockDriverInfo bdi1, *bdi = &bdi1;
6096
    QEMUFile *f;
6097
    int saved_vm_running;
6098
#ifdef _WIN32
6099
    struct _timeb tb;
6100
#else
6101
    struct timeval tv;
6102
#endif
6103

    
6104
    bs = get_bs_snapshots();
6105
    if (!bs) {
6106
        term_printf("No block device can accept snapshots\n");
6107
        return;
6108
    }
6109

    
6110
    /* ??? Should this occur after vm_stop?  */
6111
    qemu_aio_flush();
6112

    
6113
    saved_vm_running = vm_running;
6114
    vm_stop(0);
6115

    
6116
    must_delete = 0;
6117
    if (name) {
6118
        ret = bdrv_snapshot_find(bs, old_sn, name);
6119
        if (ret >= 0) {
6120
            must_delete = 1;
6121
        }
6122
    }
6123
    memset(sn, 0, sizeof(*sn));
6124
    if (must_delete) {
6125
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6126
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6127
    } else {
6128
        if (name)
6129
            pstrcpy(sn->name, sizeof(sn->name), name);
6130
    }
6131

    
6132
    /* fill auxiliary fields */
6133
#ifdef _WIN32
6134
    _ftime(&tb);
6135
    sn->date_sec = tb.time;
6136
    sn->date_nsec = tb.millitm * 1000000;
6137
#else
6138
    gettimeofday(&tv, NULL);
6139
    sn->date_sec = tv.tv_sec;
6140
    sn->date_nsec = tv.tv_usec * 1000;
6141
#endif
6142
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6143

    
6144
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6145
        term_printf("Device %s does not support VM state snapshots\n",
6146
                    bdrv_get_device_name(bs));
6147
        goto the_end;
6148
    }
6149

    
6150
    /* save the VM state */
6151
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6152
    if (!f) {
6153
        term_printf("Could not open VM state file\n");
6154
        goto the_end;
6155
    }
6156
    ret = qemu_savevm_state(f);
6157
    sn->vm_state_size = qemu_ftell(f);
6158
    qemu_fclose(f);
6159
    if (ret < 0) {
6160
        term_printf("Error %d while writing VM\n", ret);
6161
        goto the_end;
6162
    }
6163

    
6164
    /* create the snapshots */
6165

    
6166
    for(i = 0; i < nb_drives; i++) {
6167
        bs1 = drives_table[i].bdrv;
6168
        if (bdrv_has_snapshot(bs1)) {
6169
            if (must_delete) {
6170
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6171
                if (ret < 0) {
6172
                    term_printf("Error while deleting snapshot on '%s'\n",
6173
                                bdrv_get_device_name(bs1));
6174
                }
6175
            }
6176
            ret = bdrv_snapshot_create(bs1, sn);
6177
            if (ret < 0) {
6178
                term_printf("Error while creating snapshot on '%s'\n",
6179
                            bdrv_get_device_name(bs1));
6180
            }
6181
        }
6182
    }
6183

    
6184
 the_end:
6185
    if (saved_vm_running)
6186
        vm_start();
6187
}
6188

    
6189
void do_loadvm(const char *name)
6190
{
6191
    BlockDriverState *bs, *bs1;
6192
    BlockDriverInfo bdi1, *bdi = &bdi1;
6193
    QEMUFile *f;
6194
    int i, ret;
6195
    int saved_vm_running;
6196

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

    
6203
    /* Flush all IO requests so they don't interfere with the new state.  */
6204
    qemu_aio_flush();
6205

    
6206
    saved_vm_running = vm_running;
6207
    vm_stop(0);
6208

    
6209
    for(i = 0; i <= nb_drives; i++) {
6210
        bs1 = drives_table[i].bdrv;
6211
        if (bdrv_has_snapshot(bs1)) {
6212
            ret = bdrv_snapshot_goto(bs1, name);
6213
            if (ret < 0) {
6214
                if (bs != bs1)
6215
                    term_printf("Warning: ");
6216
                switch(ret) {
6217
                case -ENOTSUP:
6218
                    term_printf("Snapshots not supported on device '%s'\n",
6219
                                bdrv_get_device_name(bs1));
6220
                    break;
6221
                case -ENOENT:
6222
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
6223
                                name, bdrv_get_device_name(bs1));
6224
                    break;
6225
                default:
6226
                    term_printf("Error %d while activating snapshot on '%s'\n",
6227
                                ret, bdrv_get_device_name(bs1));
6228
                    break;
6229
                }
6230
                /* fatal on snapshot block device */
6231
                if (bs == bs1)
6232
                    goto the_end;
6233
            }
6234
        }
6235
    }
6236

    
6237
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6238
        term_printf("Device %s does not support VM state snapshots\n",
6239
                    bdrv_get_device_name(bs));
6240
        return;
6241
    }
6242

    
6243
    /* restore the VM state */
6244
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6245
    if (!f) {
6246
        term_printf("Could not open VM state file\n");
6247
        goto the_end;
6248
    }
6249
    ret = qemu_loadvm_state(f);
6250
    qemu_fclose(f);
6251
    if (ret < 0) {
6252
        term_printf("Error %d while loading VM state\n", ret);
6253
    }
6254
 the_end:
6255
    if (saved_vm_running)
6256
        vm_start();
6257
}
6258

    
6259
void do_delvm(const char *name)
6260
{
6261
    BlockDriverState *bs, *bs1;
6262
    int i, ret;
6263

    
6264
    bs = get_bs_snapshots();
6265
    if (!bs) {
6266
        term_printf("No block device supports snapshots\n");
6267
        return;
6268
    }
6269

    
6270
    for(i = 0; i <= nb_drives; i++) {
6271
        bs1 = drives_table[i].bdrv;
6272
        if (bdrv_has_snapshot(bs1)) {
6273
            ret = bdrv_snapshot_delete(bs1, name);
6274
            if (ret < 0) {
6275
                if (ret == -ENOTSUP)
6276
                    term_printf("Snapshots not supported on device '%s'\n",
6277
                                bdrv_get_device_name(bs1));
6278
                else
6279
                    term_printf("Error %d while deleting snapshot on '%s'\n",
6280
                                ret, bdrv_get_device_name(bs1));
6281
            }
6282
        }
6283
    }
6284
}
6285

    
6286
void do_info_snapshots(void)
6287
{
6288
    BlockDriverState *bs, *bs1;
6289
    QEMUSnapshotInfo *sn_tab, *sn;
6290
    int nb_sns, i;
6291
    char buf[256];
6292

    
6293
    bs = get_bs_snapshots();
6294
    if (!bs) {
6295
        term_printf("No available block device supports snapshots\n");
6296
        return;
6297
    }
6298
    term_printf("Snapshot devices:");
6299
    for(i = 0; i <= nb_drives; i++) {
6300
        bs1 = drives_table[i].bdrv;
6301
        if (bdrv_has_snapshot(bs1)) {
6302
            if (bs == bs1)
6303
                term_printf(" %s", bdrv_get_device_name(bs1));
6304
        }
6305
    }
6306
    term_printf("\n");
6307

    
6308
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6309
    if (nb_sns < 0) {
6310
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6311
        return;
6312
    }
6313
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6314
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6315
    for(i = 0; i < nb_sns; i++) {
6316
        sn = &sn_tab[i];
6317
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6318
    }
6319
    qemu_free(sn_tab);
6320
}
6321

    
6322
/***********************************************************/
6323
/* ram save/restore */
6324

    
6325
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6326
{
6327
    int v;
6328

    
6329
    v = qemu_get_byte(f);
6330
    switch(v) {
6331
    case 0:
6332
        if (qemu_get_buffer(f, buf, len) != len)
6333
            return -EIO;
6334
        break;
6335
    case 1:
6336
        v = qemu_get_byte(f);
6337
        memset(buf, v, len);
6338
        break;
6339
    default:
6340
        return -EINVAL;
6341
    }
6342
    return 0;
6343
}
6344

    
6345
static int ram_load_v1(QEMUFile *f, void *opaque)
6346
{
6347
    int ret;
6348
    ram_addr_t i;
6349

    
6350
    if (qemu_get_be32(f) != phys_ram_size)
6351
        return -EINVAL;
6352
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6353
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6354
        if (ret)
6355
            return ret;
6356
    }
6357
    return 0;
6358
}
6359

    
6360
#define BDRV_HASH_BLOCK_SIZE 1024
6361
#define IOBUF_SIZE 4096
6362
#define RAM_CBLOCK_MAGIC 0xfabe
6363

    
6364
typedef struct RamCompressState {
6365
    z_stream zstream;
6366
    QEMUFile *f;
6367
    uint8_t buf[IOBUF_SIZE];
6368
} RamCompressState;
6369

    
6370
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6371
{
6372
    int ret;
6373
    memset(s, 0, sizeof(*s));
6374
    s->f = f;
6375
    ret = deflateInit2(&s->zstream, 1,
6376
                       Z_DEFLATED, 15,
6377
                       9, Z_DEFAULT_STRATEGY);
6378
    if (ret != Z_OK)
6379
        return -1;
6380
    s->zstream.avail_out = IOBUF_SIZE;
6381
    s->zstream.next_out = s->buf;
6382
    return 0;
6383
}
6384

    
6385
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6386
{
6387
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6388
    qemu_put_be16(s->f, len);
6389
    qemu_put_buffer(s->f, buf, len);
6390
}
6391

    
6392
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6393
{
6394
    int ret;
6395

    
6396
    s->zstream.avail_in = len;
6397
    s->zstream.next_in = (uint8_t *)buf;
6398
    while (s->zstream.avail_in > 0) {
6399
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6400
        if (ret != Z_OK)
6401
            return -1;
6402
        if (s->zstream.avail_out == 0) {
6403
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6404
            s->zstream.avail_out = IOBUF_SIZE;
6405
            s->zstream.next_out = s->buf;
6406
        }
6407
    }
6408
    return 0;
6409
}
6410

    
6411
static void ram_compress_close(RamCompressState *s)
6412
{
6413
    int len, ret;
6414

    
6415
    /* compress last bytes */
6416
    for(;;) {
6417
        ret = deflate(&s->zstream, Z_FINISH);
6418
        if (ret == Z_OK || ret == Z_STREAM_END) {
6419
            len = IOBUF_SIZE - s->zstream.avail_out;
6420
            if (len > 0) {
6421
                ram_put_cblock(s, s->buf, len);
6422
            }
6423
            s->zstream.avail_out = IOBUF_SIZE;
6424
            s->zstream.next_out = s->buf;
6425
            if (ret == Z_STREAM_END)
6426
                break;
6427
        } else {
6428
            goto fail;
6429
        }
6430
    }
6431
fail:
6432
    deflateEnd(&s->zstream);
6433
}
6434

    
6435
typedef struct RamDecompressState {
6436
    z_stream zstream;
6437
    QEMUFile *f;
6438
    uint8_t buf[IOBUF_SIZE];
6439
} RamDecompressState;
6440

    
6441
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6442
{
6443
    int ret;
6444
    memset(s, 0, sizeof(*s));
6445
    s->f = f;
6446
    ret = inflateInit(&s->zstream);
6447
    if (ret != Z_OK)
6448
        return -1;
6449
    return 0;
6450
}
6451

    
6452
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6453
{
6454
    int ret, clen;
6455

    
6456
    s->zstream.avail_out = len;
6457
    s->zstream.next_out = buf;
6458
    while (s->zstream.avail_out > 0) {
6459
        if (s->zstream.avail_in == 0) {
6460
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6461
                return -1;
6462
            clen = qemu_get_be16(s->f);
6463
            if (clen > IOBUF_SIZE)
6464
                return -1;
6465
            qemu_get_buffer(s->f, s->buf, clen);
6466
            s->zstream.avail_in = clen;
6467
            s->zstream.next_in = s->buf;
6468
        }
6469
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6470
        if (ret != Z_OK && ret != Z_STREAM_END) {
6471
            return -1;
6472
        }
6473
    }
6474
    return 0;
6475
}
6476

    
6477
static void ram_decompress_close(RamDecompressState *s)
6478
{
6479
    inflateEnd(&s->zstream);
6480
}
6481

    
6482
static void ram_save(QEMUFile *f, void *opaque)
6483
{
6484
    ram_addr_t i;
6485
    RamCompressState s1, *s = &s1;
6486
    uint8_t buf[10];
6487

    
6488
    qemu_put_be32(f, phys_ram_size);
6489
    if (ram_compress_open(s, f) < 0)
6490
        return;
6491
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6492
#if 0
6493
        if (tight_savevm_enabled) {
6494
            int64_t sector_num;
6495
            int j;
6496

6497
            /* find if the memory block is available on a virtual
6498
               block device */
6499
            sector_num = -1;
6500
            for(j = 0; j < nb_drives; j++) {
6501
                sector_num = bdrv_hash_find(drives_table[j].bdrv,
6502
                                            phys_ram_base + i,
6503
                                            BDRV_HASH_BLOCK_SIZE);
6504
                if (sector_num >= 0)
6505
                    break;
6506
            }
6507
            if (j == nb_drives)
6508
                goto normal_compress;
6509
            buf[0] = 1;
6510
            buf[1] = j;
6511
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6512
            ram_compress_buf(s, buf, 10);
6513
        } else
6514
#endif
6515
        {
6516
            //        normal_compress:
6517
            buf[0] = 0;
6518
            ram_compress_buf(s, buf, 1);
6519
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6520
        }
6521
    }
6522
    ram_compress_close(s);
6523
}
6524

    
6525
static int ram_load(QEMUFile *f, void *opaque, int version_id)
6526
{
6527
    RamDecompressState s1, *s = &s1;
6528
    uint8_t buf[10];
6529
    ram_addr_t i;
6530

    
6531
    if (version_id == 1)
6532
        return ram_load_v1(f, opaque);
6533
    if (version_id != 2)
6534
        return -EINVAL;
6535
    if (qemu_get_be32(f) != phys_ram_size)
6536
        return -EINVAL;
6537
    if (ram_decompress_open(s, f) < 0)
6538
        return -EINVAL;
6539
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6540
        if (ram_decompress_buf(s, buf, 1) < 0) {
6541
            fprintf(stderr, "Error while reading ram block header\n");
6542
            goto error;
6543
        }
6544
        if (buf[0] == 0) {
6545
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6546
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
6547
                goto error;
6548
            }
6549
        } else
6550
#if 0
6551
        if (buf[0] == 1) {
6552
            int bs_index;
6553
            int64_t sector_num;
6554

6555
            ram_decompress_buf(s, buf + 1, 9);
6556
            bs_index = buf[1];
6557
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6558
            if (bs_index >= nb_drives) {
6559
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
6560
                goto error;
6561
            }
6562
            if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6563
                          phys_ram_base + i,
6564
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6565
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6566
                        bs_index, sector_num);
6567
                goto error;
6568
            }
6569
        } else
6570
#endif
6571
        {
6572
        error:
6573
            printf("Error block header\n");
6574
            return -EINVAL;
6575
        }
6576
    }
6577
    ram_decompress_close(s);
6578
    return 0;
6579
}
6580

    
6581
/***********************************************************/
6582
/* bottom halves (can be seen as timers which expire ASAP) */
6583

    
6584
struct QEMUBH {
6585
    QEMUBHFunc *cb;
6586
    void *opaque;
6587
    int scheduled;
6588
    QEMUBH *next;
6589
};
6590

    
6591
static QEMUBH *first_bh = NULL;
6592

    
6593
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6594
{
6595
    QEMUBH *bh;
6596
    bh = qemu_mallocz(sizeof(QEMUBH));
6597
    if (!bh)
6598
        return NULL;
6599
    bh->cb = cb;
6600
    bh->opaque = opaque;
6601
    return bh;
6602
}
6603

    
6604
int qemu_bh_poll(void)
6605
{
6606
    QEMUBH *bh, **pbh;
6607
    int ret;
6608

    
6609
    ret = 0;
6610
    for(;;) {
6611
        pbh = &first_bh;
6612
        bh = *pbh;
6613
        if (!bh)
6614
            break;
6615
        ret = 1;
6616
        *pbh = bh->next;
6617
        bh->scheduled = 0;
6618
        bh->cb(bh->opaque);
6619
    }
6620
    return ret;
6621
}
6622

    
6623
void qemu_bh_schedule(QEMUBH *bh)
6624
{
6625
    CPUState *env = cpu_single_env;
6626
    if (bh->scheduled)
6627
        return;
6628
    bh->scheduled = 1;
6629
    bh->next = first_bh;
6630
    first_bh = bh;
6631

    
6632
    /* stop the currently executing CPU to execute the BH ASAP */
6633
    if (env) {
6634
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6635
    }
6636
}
6637

    
6638
void qemu_bh_cancel(QEMUBH *bh)
6639
{
6640
    QEMUBH **pbh;
6641
    if (bh->scheduled) {
6642
        pbh = &first_bh;
6643
        while (*pbh != bh)
6644
            pbh = &(*pbh)->next;
6645
        *pbh = bh->next;
6646
        bh->scheduled = 0;
6647
    }
6648
}
6649

    
6650
void qemu_bh_delete(QEMUBH *bh)
6651
{
6652
    qemu_bh_cancel(bh);
6653
    qemu_free(bh);
6654
}
6655

    
6656
/***********************************************************/
6657
/* machine registration */
6658

    
6659
QEMUMachine *first_machine = NULL;
6660

    
6661
int qemu_register_machine(QEMUMachine *m)
6662
{
6663
    QEMUMachine **pm;
6664
    pm = &first_machine;
6665
    while (*pm != NULL)
6666
        pm = &(*pm)->next;
6667
    m->next = NULL;
6668
    *pm = m;
6669
    return 0;
6670
}
6671

    
6672
static QEMUMachine *find_machine(const char *name)
6673
{
6674
    QEMUMachine *m;
6675

    
6676
    for(m = first_machine; m != NULL; m = m->next) {
6677
        if (!strcmp(m->name, name))
6678
            return m;
6679
    }
6680
    return NULL;
6681
}
6682

    
6683
/***********************************************************/
6684
/* main execution loop */
6685

    
6686
static void gui_update(void *opaque)
6687
{
6688
    DisplayState *ds = opaque;
6689
    ds->dpy_refresh(ds);
6690
    qemu_mod_timer(ds->gui_timer,
6691
        (ds->gui_timer_interval ?
6692
            ds->gui_timer_interval :
6693
            GUI_REFRESH_INTERVAL)
6694
        + qemu_get_clock(rt_clock));
6695
}
6696

    
6697
struct vm_change_state_entry {
6698
    VMChangeStateHandler *cb;
6699
    void *opaque;
6700
    LIST_ENTRY (vm_change_state_entry) entries;
6701
};
6702

    
6703
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6704

    
6705
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6706
                                                     void *opaque)
6707
{
6708
    VMChangeStateEntry *e;
6709

    
6710
    e = qemu_mallocz(sizeof (*e));
6711
    if (!e)
6712
        return NULL;
6713

    
6714
    e->cb = cb;
6715
    e->opaque = opaque;
6716
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6717
    return e;
6718
}
6719

    
6720
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6721
{
6722
    LIST_REMOVE (e, entries);
6723
    qemu_free (e);
6724
}
6725

    
6726
static void vm_state_notify(int running)
6727
{
6728
    VMChangeStateEntry *e;
6729

    
6730
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6731
        e->cb(e->opaque, running);
6732
    }
6733
}
6734

    
6735
/* XXX: support several handlers */
6736
static VMStopHandler *vm_stop_cb;
6737
static void *vm_stop_opaque;
6738

    
6739
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6740
{
6741
    vm_stop_cb = cb;
6742
    vm_stop_opaque = opaque;
6743
    return 0;
6744
}
6745

    
6746
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6747
{
6748
    vm_stop_cb = NULL;
6749
}
6750

    
6751
void vm_start(void)
6752
{
6753
    if (!vm_running) {
6754
        cpu_enable_ticks();
6755
        vm_running = 1;
6756
        vm_state_notify(1);
6757
        qemu_rearm_alarm_timer(alarm_timer);
6758
    }
6759
}
6760

    
6761
void vm_stop(int reason)
6762
{
6763
    if (vm_running) {
6764
        cpu_disable_ticks();
6765
        vm_running = 0;
6766
        if (reason != 0) {
6767
            if (vm_stop_cb) {
6768
                vm_stop_cb(vm_stop_opaque, reason);
6769
            }
6770
        }
6771
        vm_state_notify(0);
6772
    }
6773
}
6774

    
6775
/* reset/shutdown handler */
6776

    
6777
typedef struct QEMUResetEntry {
6778
    QEMUResetHandler *func;
6779
    void *opaque;
6780
    struct QEMUResetEntry *next;
6781
} QEMUResetEntry;
6782

    
6783
static QEMUResetEntry *first_reset_entry;
6784
static int reset_requested;
6785
static int shutdown_requested;
6786
static int powerdown_requested;
6787

    
6788
int qemu_shutdown_requested(void)
6789
{
6790
    int r = shutdown_requested;
6791
    shutdown_requested = 0;
6792
    return r;
6793
}
6794

    
6795
int qemu_reset_requested(void)
6796
{
6797
    int r = reset_requested;
6798
    reset_requested = 0;
6799
    return r;
6800
}
6801

    
6802
int qemu_powerdown_requested(void)
6803
{
6804
    int r = powerdown_requested;
6805
    powerdown_requested = 0;
6806
    return r;
6807
}
6808

    
6809
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6810
{
6811
    QEMUResetEntry **pre, *re;
6812

    
6813
    pre = &first_reset_entry;
6814
    while (*pre != NULL)
6815
        pre = &(*pre)->next;
6816
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6817
    re->func = func;
6818
    re->opaque = opaque;
6819
    re->next = NULL;
6820
    *pre = re;
6821
}
6822

    
6823
void qemu_system_reset(void)
6824
{
6825
    QEMUResetEntry *re;
6826

    
6827
    /* reset all devices */
6828
    for(re = first_reset_entry; re != NULL; re = re->next) {
6829
        re->func(re->opaque);
6830
    }
6831
}
6832

    
6833
void qemu_system_reset_request(void)
6834
{
6835
    if (no_reboot) {
6836
        shutdown_requested = 1;
6837
    } else {
6838
        reset_requested = 1;
6839
    }
6840
    if (cpu_single_env)
6841
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6842
}
6843

    
6844
void qemu_system_shutdown_request(void)
6845
{
6846
    shutdown_requested = 1;
6847
    if (cpu_single_env)
6848
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6849
}
6850

    
6851
void qemu_system_powerdown_request(void)
6852
{
6853
    powerdown_requested = 1;
6854
    if (cpu_single_env)
6855
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6856
}
6857

    
6858
void main_loop_wait(int timeout)
6859
{
6860
    IOHandlerRecord *ioh;
6861
    fd_set rfds, wfds, xfds;
6862
    int ret, nfds;
6863
#ifdef _WIN32
6864
    int ret2, i;
6865
#endif
6866
    struct timeval tv;
6867
    PollingEntry *pe;
6868

    
6869

    
6870
    /* XXX: need to suppress polling by better using win32 events */
6871
    ret = 0;
6872
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6873
        ret |= pe->func(pe->opaque);
6874
    }
6875
#ifdef _WIN32
6876
    if (ret == 0) {
6877
        int err;
6878
        WaitObjects *w = &wait_objects;
6879

    
6880
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6881
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6882
            if (w->func[ret - WAIT_OBJECT_0])
6883
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6884

    
6885
            /* Check for additional signaled events */
6886
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6887

    
6888
                /* Check if event is signaled */
6889
                ret2 = WaitForSingleObject(w->events[i], 0);
6890
                if(ret2 == WAIT_OBJECT_0) {
6891
                    if (w->func[i])
6892
                        w->func[i](w->opaque[i]);
6893
                } else if (ret2 == WAIT_TIMEOUT) {
6894
                } else {
6895
                    err = GetLastError();
6896
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6897
                }
6898
            }
6899
        } else if (ret == WAIT_TIMEOUT) {
6900
        } else {
6901
            err = GetLastError();
6902
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6903
        }
6904
    }
6905
#endif
6906
    /* poll any events */
6907
    /* XXX: separate device handlers from system ones */
6908
    nfds = -1;
6909
    FD_ZERO(&rfds);
6910
    FD_ZERO(&wfds);
6911
    FD_ZERO(&xfds);
6912
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6913
        if (ioh->deleted)
6914
            continue;
6915
        if (ioh->fd_read &&
6916
            (!ioh->fd_read_poll ||
6917
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6918
            FD_SET(ioh->fd, &rfds);
6919
            if (ioh->fd > nfds)
6920
                nfds = ioh->fd;
6921
        }
6922
        if (ioh->fd_write) {
6923
            FD_SET(ioh->fd, &wfds);
6924
            if (ioh->fd > nfds)
6925
                nfds = ioh->fd;
6926
        }
6927
    }
6928

    
6929
    tv.tv_sec = 0;
6930
#ifdef _WIN32
6931
    tv.tv_usec = 0;
6932
#else
6933
    tv.tv_usec = timeout * 1000;
6934
#endif
6935
#if defined(CONFIG_SLIRP)
6936
    if (slirp_inited) {
6937
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6938
    }
6939
#endif
6940
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6941
    if (ret > 0) {
6942
        IOHandlerRecord **pioh;
6943

    
6944
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6945
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6946
                ioh->fd_read(ioh->opaque);
6947
            }
6948
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6949
                ioh->fd_write(ioh->opaque);
6950
            }
6951
        }
6952

    
6953
        /* remove deleted IO handlers */
6954
        pioh = &first_io_handler;
6955
        while (*pioh) {
6956
            ioh = *pioh;
6957
            if (ioh->deleted) {
6958
                *pioh = ioh->next;
6959
                qemu_free(ioh);
6960
            } else
6961
                pioh = &ioh->next;
6962
        }
6963
    }
6964
#if defined(CONFIG_SLIRP)
6965
    if (slirp_inited) {
6966
        if (ret < 0) {
6967
            FD_ZERO(&rfds);
6968
            FD_ZERO(&wfds);
6969
            FD_ZERO(&xfds);
6970
        }
6971
        slirp_select_poll(&rfds, &wfds, &xfds);
6972
    }
6973
#endif
6974
    qemu_aio_poll();
6975

    
6976
    if (vm_running) {
6977
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6978
                        qemu_get_clock(vm_clock));
6979
        /* run dma transfers, if any */
6980
        DMA_run();
6981
    }
6982

    
6983
    /* real time timers */
6984
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6985
                    qemu_get_clock(rt_clock));
6986

    
6987
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
6988
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
6989
        qemu_rearm_alarm_timer(alarm_timer);
6990
    }
6991

    
6992
    /* Check bottom-halves last in case any of the earlier events triggered
6993
       them.  */
6994
    qemu_bh_poll();
6995

    
6996
}
6997

    
6998
static int main_loop(void)
6999
{
7000
    int ret, timeout;
7001
#ifdef CONFIG_PROFILER
7002
    int64_t ti;
7003
#endif
7004
    CPUState *env;
7005

    
7006
    cur_cpu = first_cpu;
7007
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7008
    for(;;) {
7009
        if (vm_running) {
7010

    
7011
            for(;;) {
7012
                /* get next cpu */
7013
                env = next_cpu;
7014
#ifdef CONFIG_PROFILER
7015
                ti = profile_getclock();
7016
#endif
7017
                ret = cpu_exec(env);
7018
#ifdef CONFIG_PROFILER
7019
                qemu_time += profile_getclock() - ti;
7020
#endif
7021
                next_cpu = env->next_cpu ?: first_cpu;
7022
                if (event_pending && likely(ret != EXCP_DEBUG)) {
7023
                    ret = EXCP_INTERRUPT;
7024
                    event_pending = 0;
7025
                    break;
7026
                }
7027
                if (ret == EXCP_HLT) {
7028
                    /* Give the next CPU a chance to run.  */
7029
                    cur_cpu = env;
7030
                    continue;
7031
                }
7032
                if (ret != EXCP_HALTED)
7033
                    break;
7034
                /* all CPUs are halted ? */
7035
                if (env == cur_cpu)
7036
                    break;
7037
            }
7038
            cur_cpu = env;
7039

    
7040
            if (shutdown_requested) {
7041
                ret = EXCP_INTERRUPT;
7042
                if (no_shutdown) {
7043
                    vm_stop(0);
7044
                    no_shutdown = 0;
7045
                }
7046
                else
7047
                    break;
7048
            }
7049
            if (reset_requested) {
7050
                reset_requested = 0;
7051
                qemu_system_reset();
7052
                ret = EXCP_INTERRUPT;
7053
            }
7054
            if (powerdown_requested) {
7055
                powerdown_requested = 0;
7056
                qemu_system_powerdown();
7057
                ret = EXCP_INTERRUPT;
7058
            }
7059
            if (unlikely(ret == EXCP_DEBUG)) {
7060
                vm_stop(EXCP_DEBUG);
7061
            }
7062
            /* If all cpus are halted then wait until the next IRQ */
7063
            /* XXX: use timeout computed from timers */
7064
            if (ret == EXCP_HALTED)
7065
                timeout = 10;
7066
            else
7067
                timeout = 0;
7068
        } else {
7069
            timeout = 10;
7070
        }
7071
#ifdef CONFIG_PROFILER
7072
        ti = profile_getclock();
7073
#endif
7074
        main_loop_wait(timeout);
7075
#ifdef CONFIG_PROFILER
7076
        dev_time += profile_getclock() - ti;
7077
#endif
7078
    }
7079
    cpu_disable_ticks();
7080
    return ret;
7081
}
7082

    
7083
static void help(int exitcode)
7084
{
7085
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7086
           "usage: %s [options] [disk_image]\n"
7087
           "\n"
7088
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7089
           "\n"
7090
           "Standard options:\n"
7091
           "-M machine      select emulated machine (-M ? for list)\n"
7092
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7093
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7094
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7095
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7096
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7097
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7098
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7099
           "       [,cache=on|off][,format=f]\n"
7100
           "                use 'file' as a drive image\n"
7101
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7102
           "-sd file        use 'file' as SecureDigital card image\n"
7103
           "-pflash file    use 'file' as a parallel flash image\n"
7104
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7105
           "-snapshot       write to temporary files instead of disk image files\n"
7106
#ifdef CONFIG_SDL
7107
           "-no-frame       open SDL window without a frame and window decorations\n"
7108
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7109
           "-no-quit        disable SDL window close capability\n"
7110
#endif
7111
#ifdef TARGET_I386
7112
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7113
#endif
7114
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7115
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7116
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7117
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7118
#ifndef _WIN32
7119
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7120
#endif
7121
#ifdef HAS_AUDIO
7122
           "-audio-help     print list of audio drivers and their options\n"
7123
           "-soundhw c1,... enable audio support\n"
7124
           "                and only specified sound cards (comma separated list)\n"
7125
           "                use -soundhw ? to get the list of supported cards\n"
7126
           "                use -soundhw all to enable all of them\n"
7127
#endif
7128
           "-localtime      set the real time clock to local time [default=utc]\n"
7129
           "-full-screen    start in full screen\n"
7130
#ifdef TARGET_I386
7131
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7132
#endif
7133
           "-usb            enable the USB driver (will be the default soon)\n"
7134
           "-usbdevice name add the host or guest USB device 'name'\n"
7135
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7136
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7137
#endif
7138
           "-name string    set the name of the guest\n"
7139
           "\n"
7140
           "Network options:\n"
7141
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7142
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7143
#ifdef CONFIG_SLIRP
7144
           "-net user[,vlan=n][,hostname=host]\n"
7145
           "                connect the user mode network stack to VLAN 'n' and send\n"
7146
           "                hostname 'host' to DHCP clients\n"
7147
#endif
7148
#ifdef _WIN32
7149
           "-net tap[,vlan=n],ifname=name\n"
7150
           "                connect the host TAP network interface to VLAN 'n'\n"
7151
#else
7152
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7153
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7154
           "                network scripts 'file' (default=%s)\n"
7155
           "                and 'dfile' (default=%s);\n"
7156
           "                use '[down]script=no' to disable script execution;\n"
7157
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7158
#endif
7159
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7160
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7161
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7162
           "                connect the vlan 'n' to multicast maddr and port\n"
7163
           "-net none       use it alone to have zero network devices; if no -net option\n"
7164
           "                is provided, the default is '-net nic -net user'\n"
7165
           "\n"
7166
#ifdef CONFIG_SLIRP
7167
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7168
           "-bootp file     advertise file in BOOTP replies\n"
7169
#ifndef _WIN32
7170
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7171
#endif
7172
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7173
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7174
#endif
7175
           "\n"
7176
           "Linux boot specific:\n"
7177
           "-kernel bzImage use 'bzImage' as kernel image\n"
7178
           "-append cmdline use 'cmdline' as kernel command line\n"
7179
           "-initrd file    use 'file' as initial ram disk\n"
7180
           "\n"
7181
           "Debug/Expert options:\n"
7182
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7183
           "-serial dev     redirect the serial port to char device 'dev'\n"
7184
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7185
           "-pidfile file   Write PID to 'file'\n"
7186
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7187
           "-s              wait gdb connection to port\n"
7188
           "-p port         set gdb connection port [default=%s]\n"
7189
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7190
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7191
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7192
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7193
#ifdef USE_KQEMU
7194
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7195
           "-no-kqemu       disable KQEMU kernel module usage\n"
7196
#endif
7197
#ifdef TARGET_I386
7198
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7199
           "                (default is CL-GD5446 PCI VGA)\n"
7200
           "-no-acpi        disable ACPI\n"
7201
#endif
7202
#ifdef CONFIG_CURSES
7203
           "-curses         use a curses/ncurses interface instead of SDL\n"
7204
#endif
7205
           "-no-reboot      exit instead of rebooting\n"
7206
           "-no-shutdown    stop before shutdown\n"
7207
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
7208
           "-vnc display    start a VNC server on display\n"
7209
#ifndef _WIN32
7210
           "-daemonize      daemonize QEMU after initializing\n"
7211
#endif
7212
           "-option-rom rom load a file, rom, into the option ROM space\n"
7213
#ifdef TARGET_SPARC
7214
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7215
#endif
7216
           "-clock          force the use of the given methods for timer alarm.\n"
7217
           "                To see what timers are available use -clock ?\n"
7218
           "-startdate      select initial date of the clock\n"
7219
           "\n"
7220
           "During emulation, the following keys are useful:\n"
7221
           "ctrl-alt-f      toggle full screen\n"
7222
           "ctrl-alt-n      switch to virtual console 'n'\n"
7223
           "ctrl-alt        toggle mouse and keyboard grab\n"
7224
           "\n"
7225
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7226
           ,
7227
           "qemu",
7228
           DEFAULT_RAM_SIZE,
7229
#ifndef _WIN32
7230
           DEFAULT_NETWORK_SCRIPT,
7231
           DEFAULT_NETWORK_DOWN_SCRIPT,
7232
#endif
7233
           DEFAULT_GDBSTUB_PORT,
7234
           "/tmp/qemu.log");
7235
    exit(exitcode);
7236
}
7237

    
7238
#define HAS_ARG 0x0001
7239

    
7240
enum {
7241
    QEMU_OPTION_h,
7242

    
7243
    QEMU_OPTION_M,
7244
    QEMU_OPTION_cpu,
7245
    QEMU_OPTION_fda,
7246
    QEMU_OPTION_fdb,
7247
    QEMU_OPTION_hda,
7248
    QEMU_OPTION_hdb,
7249
    QEMU_OPTION_hdc,
7250
    QEMU_OPTION_hdd,
7251
    QEMU_OPTION_drive,
7252
    QEMU_OPTION_cdrom,
7253
    QEMU_OPTION_mtdblock,
7254
    QEMU_OPTION_sd,
7255
    QEMU_OPTION_pflash,
7256
    QEMU_OPTION_boot,
7257
    QEMU_OPTION_snapshot,
7258
#ifdef TARGET_I386
7259
    QEMU_OPTION_no_fd_bootchk,
7260
#endif
7261
    QEMU_OPTION_m,
7262
    QEMU_OPTION_nographic,
7263
    QEMU_OPTION_portrait,
7264
#ifdef HAS_AUDIO
7265
    QEMU_OPTION_audio_help,
7266
    QEMU_OPTION_soundhw,
7267
#endif
7268

    
7269
    QEMU_OPTION_net,
7270
    QEMU_OPTION_tftp,
7271
    QEMU_OPTION_bootp,
7272
    QEMU_OPTION_smb,
7273
    QEMU_OPTION_redir,
7274

    
7275
    QEMU_OPTION_kernel,
7276
    QEMU_OPTION_append,
7277
    QEMU_OPTION_initrd,
7278

    
7279
    QEMU_OPTION_S,
7280
    QEMU_OPTION_s,
7281
    QEMU_OPTION_p,
7282
    QEMU_OPTION_d,
7283
    QEMU_OPTION_hdachs,
7284
    QEMU_OPTION_L,
7285
    QEMU_OPTION_bios,
7286
    QEMU_OPTION_no_code_copy,
7287
    QEMU_OPTION_k,
7288
    QEMU_OPTION_localtime,
7289
    QEMU_OPTION_cirrusvga,
7290
    QEMU_OPTION_vmsvga,
7291
    QEMU_OPTION_g,
7292
    QEMU_OPTION_std_vga,
7293
    QEMU_OPTION_echr,
7294
    QEMU_OPTION_monitor,
7295
    QEMU_OPTION_serial,
7296
    QEMU_OPTION_parallel,
7297
    QEMU_OPTION_loadvm,
7298
    QEMU_OPTION_full_screen,
7299
    QEMU_OPTION_no_frame,
7300
    QEMU_OPTION_alt_grab,
7301
    QEMU_OPTION_no_quit,
7302
    QEMU_OPTION_pidfile,
7303
    QEMU_OPTION_no_kqemu,
7304
    QEMU_OPTION_kernel_kqemu,
7305
    QEMU_OPTION_win2k_hack,
7306
    QEMU_OPTION_usb,
7307
    QEMU_OPTION_usbdevice,
7308
    QEMU_OPTION_smp,
7309
    QEMU_OPTION_vnc,
7310
    QEMU_OPTION_no_acpi,
7311
    QEMU_OPTION_curses,
7312
    QEMU_OPTION_no_reboot,
7313
    QEMU_OPTION_no_shutdown,
7314
    QEMU_OPTION_show_cursor,
7315
    QEMU_OPTION_daemonize,
7316
    QEMU_OPTION_option_rom,
7317
    QEMU_OPTION_semihosting,
7318
    QEMU_OPTION_name,
7319
    QEMU_OPTION_prom_env,
7320
    QEMU_OPTION_old_param,
7321
    QEMU_OPTION_clock,
7322
    QEMU_OPTION_startdate,
7323
};
7324

    
7325
typedef struct QEMUOption {
7326
    const char *name;
7327
    int flags;
7328
    int index;
7329
} QEMUOption;
7330

    
7331
const QEMUOption qemu_options[] = {
7332
    { "h", 0, QEMU_OPTION_h },
7333
    { "help", 0, QEMU_OPTION_h },
7334

    
7335
    { "M", HAS_ARG, QEMU_OPTION_M },
7336
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7337
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7338
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7339
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7340
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7341
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7342
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7343
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7344
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7345
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7346
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7347
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7348
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7349
    { "snapshot", 0, QEMU_OPTION_snapshot },
7350
#ifdef TARGET_I386
7351
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7352
#endif
7353
    { "m", HAS_ARG, QEMU_OPTION_m },
7354
    { "nographic", 0, QEMU_OPTION_nographic },
7355
    { "portrait", 0, QEMU_OPTION_portrait },
7356
    { "k", HAS_ARG, QEMU_OPTION_k },
7357
#ifdef HAS_AUDIO
7358
    { "audio-help", 0, QEMU_OPTION_audio_help },
7359
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7360
#endif
7361

    
7362
    { "net", HAS_ARG, QEMU_OPTION_net},
7363
#ifdef CONFIG_SLIRP
7364
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7365
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7366
#ifndef _WIN32
7367
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7368
#endif
7369
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7370
#endif
7371

    
7372
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7373
    { "append", HAS_ARG, QEMU_OPTION_append },
7374
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7375

    
7376
    { "S", 0, QEMU_OPTION_S },
7377
    { "s", 0, QEMU_OPTION_s },
7378
    { "p", HAS_ARG, QEMU_OPTION_p },
7379
    { "d", HAS_ARG, QEMU_OPTION_d },
7380
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7381
    { "L", HAS_ARG, QEMU_OPTION_L },
7382
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7383
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7384
#ifdef USE_KQEMU
7385
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7386
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7387
#endif
7388
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7389
    { "g", 1, QEMU_OPTION_g },
7390
#endif
7391
    { "localtime", 0, QEMU_OPTION_localtime },
7392
    { "std-vga", 0, QEMU_OPTION_std_vga },
7393
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7394
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7395
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7396
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7397
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7398
    { "full-screen", 0, QEMU_OPTION_full_screen },
7399
#ifdef CONFIG_SDL
7400
    { "no-frame", 0, QEMU_OPTION_no_frame },
7401
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7402
    { "no-quit", 0, QEMU_OPTION_no_quit },
7403
#endif
7404
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7405
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7406
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7407
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7408
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7409
#ifdef CONFIG_CURSES
7410
    { "curses", 0, QEMU_OPTION_curses },
7411
#endif
7412

    
7413
    /* temporary options */
7414
    { "usb", 0, QEMU_OPTION_usb },
7415
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7416
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7417
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7418
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7419
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7420
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7421
    { "daemonize", 0, QEMU_OPTION_daemonize },
7422
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7423
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7424
    { "semihosting", 0, QEMU_OPTION_semihosting },
7425
#endif
7426
    { "name", HAS_ARG, QEMU_OPTION_name },
7427
#if defined(TARGET_SPARC)
7428
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7429
#endif
7430
#if defined(TARGET_ARM)
7431
    { "old-param", 0, QEMU_OPTION_old_param },
7432
#endif
7433
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7434
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7435
    { NULL },
7436
};
7437

    
7438
/* password input */
7439

    
7440
int qemu_key_check(BlockDriverState *bs, const char *name)
7441
{
7442
    char password[256];
7443
    int i;
7444

    
7445
    if (!bdrv_is_encrypted(bs))
7446
        return 0;
7447

    
7448
    term_printf("%s is encrypted.\n", name);
7449
    for(i = 0; i < 3; i++) {
7450
        monitor_readline("Password: ", 1, password, sizeof(password));
7451
        if (bdrv_set_key(bs, password) == 0)
7452
            return 0;
7453
        term_printf("invalid password\n");
7454
    }
7455
    return -EPERM;
7456
}
7457

    
7458
static BlockDriverState *get_bdrv(int index)
7459
{
7460
    if (index > nb_drives)
7461
        return NULL;
7462
    return drives_table[index].bdrv;
7463
}
7464

    
7465
static void read_passwords(void)
7466
{
7467
    BlockDriverState *bs;
7468
    int i;
7469

    
7470
    for(i = 0; i < 6; i++) {
7471
        bs = get_bdrv(i);
7472
        if (bs)
7473
            qemu_key_check(bs, bdrv_get_device_name(bs));
7474
    }
7475
}
7476

    
7477
#ifdef HAS_AUDIO
7478
struct soundhw soundhw[] = {
7479
#ifdef HAS_AUDIO_CHOICE
7480
#if defined(TARGET_I386) || defined(TARGET_MIPS)
7481
    {
7482
        "pcspk",
7483
        "PC speaker",
7484
        0,
7485
        1,
7486
        { .init_isa = pcspk_audio_init }
7487
    },
7488
#endif
7489
    {
7490
        "sb16",
7491
        "Creative Sound Blaster 16",
7492
        0,
7493
        1,
7494
        { .init_isa = SB16_init }
7495
    },
7496

    
7497
#ifdef CONFIG_ADLIB
7498
    {
7499
        "adlib",
7500
#ifdef HAS_YMF262
7501
        "Yamaha YMF262 (OPL3)",
7502
#else
7503
        "Yamaha YM3812 (OPL2)",
7504
#endif
7505
        0,
7506
        1,
7507
        { .init_isa = Adlib_init }
7508
    },
7509
#endif
7510

    
7511
#ifdef CONFIG_GUS
7512
    {
7513
        "gus",
7514
        "Gravis Ultrasound GF1",
7515
        0,
7516
        1,
7517
        { .init_isa = GUS_init }
7518
    },
7519
#endif
7520

    
7521
#ifdef CONFIG_AC97
7522
    {
7523
        "ac97",
7524
        "Intel 82801AA AC97 Audio",
7525
        0,
7526
        0,
7527
        { .init_pci = ac97_init }
7528
    },
7529
#endif
7530

    
7531
    {
7532
        "es1370",
7533
        "ENSONIQ AudioPCI ES1370",
7534
        0,
7535
        0,
7536
        { .init_pci = es1370_init }
7537
    },
7538
#endif
7539

    
7540
    { NULL, NULL, 0, 0, { NULL } }
7541
};
7542

    
7543
static void select_soundhw (const char *optarg)
7544
{
7545
    struct soundhw *c;
7546

    
7547
    if (*optarg == '?') {
7548
    show_valid_cards:
7549

    
7550
        printf ("Valid sound card names (comma separated):\n");
7551
        for (c = soundhw; c->name; ++c) {
7552
            printf ("%-11s %s\n", c->name, c->descr);
7553
        }
7554
        printf ("\n-soundhw all will enable all of the above\n");
7555
        exit (*optarg != '?');
7556
    }
7557
    else {
7558
        size_t l;
7559
        const char *p;
7560
        char *e;
7561
        int bad_card = 0;
7562

    
7563
        if (!strcmp (optarg, "all")) {
7564
            for (c = soundhw; c->name; ++c) {
7565
                c->enabled = 1;
7566
            }
7567
            return;
7568
        }
7569

    
7570
        p = optarg;
7571
        while (*p) {
7572
            e = strchr (p, ',');
7573
            l = !e ? strlen (p) : (size_t) (e - p);
7574

    
7575
            for (c = soundhw; c->name; ++c) {
7576
                if (!strncmp (c->name, p, l)) {
7577
                    c->enabled = 1;
7578
                    break;
7579
                }
7580
            }
7581

    
7582
            if (!c->name) {
7583
                if (l > 80) {
7584
                    fprintf (stderr,
7585
                             "Unknown sound card name (too big to show)\n");
7586
                }
7587
                else {
7588
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
7589
                             (int) l, p);
7590
                }
7591
                bad_card = 1;
7592
            }
7593
            p += l + (e != NULL);
7594
        }
7595

    
7596
        if (bad_card)
7597
            goto show_valid_cards;
7598
    }
7599
}
7600
#endif
7601

    
7602
#ifdef _WIN32
7603
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7604
{
7605
    exit(STATUS_CONTROL_C_EXIT);
7606
    return TRUE;
7607
}
7608
#endif
7609

    
7610
#define MAX_NET_CLIENTS 32
7611

    
7612
int main(int argc, char **argv)
7613
{
7614
#ifdef CONFIG_GDBSTUB
7615
    int use_gdbstub;
7616
    const char *gdbstub_port;
7617
#endif
7618
    uint32_t boot_devices_bitmap = 0;
7619
    int i;
7620
    int snapshot, linux_boot, net_boot;
7621
    const char *initrd_filename;
7622
    const char *kernel_filename, *kernel_cmdline;
7623
    const char *boot_devices = "";
7624
    DisplayState *ds = &display_state;
7625
    int cyls, heads, secs, translation;
7626
    const char *net_clients[MAX_NET_CLIENTS];
7627
    int nb_net_clients;
7628
    int hda_index;
7629
    int optind;
7630
    const char *r, *optarg;
7631
    CharDriverState *monitor_hd;
7632
    const char *monitor_device;
7633
    const char *serial_devices[MAX_SERIAL_PORTS];
7634
    int serial_device_index;
7635
    const char *parallel_devices[MAX_PARALLEL_PORTS];
7636
    int parallel_device_index;
7637
    const char *loadvm = NULL;
7638
    QEMUMachine *machine;
7639
    const char *cpu_model;
7640
    const char *usb_devices[MAX_USB_CMDLINE];
7641
    int usb_devices_index;
7642
    int fds[2];
7643
    const char *pid_file = NULL;
7644
    VLANState *vlan;
7645

    
7646
    LIST_INIT (&vm_change_state_head);
7647
#ifndef _WIN32
7648
    {
7649
        struct sigaction act;
7650
        sigfillset(&act.sa_mask);
7651
        act.sa_flags = 0;
7652
        act.sa_handler = SIG_IGN;
7653
        sigaction(SIGPIPE, &act, NULL);
7654
    }
7655
#else
7656
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7657
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
7658
       QEMU to run on a single CPU */
7659
    {
7660
        HANDLE h;
7661
        DWORD mask, smask;
7662
        int i;
7663
        h = GetCurrentProcess();
7664
        if (GetProcessAffinityMask(h, &mask, &smask)) {
7665
            for(i = 0; i < 32; i++) {
7666
                if (mask & (1 << i))
7667
                    break;
7668
            }
7669
            if (i != 32) {
7670
                mask = 1 << i;
7671
                SetProcessAffinityMask(h, mask);
7672
            }
7673
        }
7674
    }
7675
#endif
7676

    
7677
    register_machines();
7678
    machine = first_machine;
7679
    cpu_model = NULL;
7680
    initrd_filename = NULL;
7681
    ram_size = 0;
7682
    vga_ram_size = VGA_RAM_SIZE;
7683
#ifdef CONFIG_GDBSTUB
7684
    use_gdbstub = 0;
7685
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
7686
#endif
7687
    snapshot = 0;
7688
    nographic = 0;
7689
    curses = 0;
7690
    kernel_filename = NULL;
7691
    kernel_cmdline = "";
7692
    cyls = heads = secs = 0;
7693
    translation = BIOS_ATA_TRANSLATION_AUTO;
7694
    monitor_device = "vc:800x600";
7695

    
7696
    serial_devices[0] = "vc:80Cx24C";
7697
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
7698
        serial_devices[i] = NULL;
7699
    serial_device_index = 0;
7700

    
7701
    parallel_devices[0] = "vc:640x480";
7702
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7703
        parallel_devices[i] = NULL;
7704
    parallel_device_index = 0;
7705

    
7706
    usb_devices_index = 0;
7707

    
7708
    nb_net_clients = 0;
7709
    nb_drives = 0;
7710
    nb_drives_opt = 0;
7711
    hda_index = -1;
7712

    
7713
    nb_nics = 0;
7714
    /* default mac address of the first network interface */
7715

    
7716
    optind = 1;
7717
    for(;;) {
7718
        if (optind >= argc)
7719
            break;
7720
        r = argv[optind];
7721
        if (r[0] != '-') {
7722
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
7723
        } else {
7724
            const QEMUOption *popt;
7725

    
7726
            optind++;
7727
            /* Treat --foo the same as -foo.  */
7728
            if (r[1] == '-')
7729
                r++;
7730
            popt = qemu_options;
7731
            for(;;) {
7732
                if (!popt->name) {
7733
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
7734
                            argv[0], r);
7735
                    exit(1);
7736
                }
7737
                if (!strcmp(popt->name, r + 1))
7738
                    break;
7739
                popt++;
7740
            }
7741
            if (popt->flags & HAS_ARG) {
7742
                if (optind >= argc) {
7743
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
7744
                            argv[0], r);
7745
                    exit(1);
7746
                }
7747
                optarg = argv[optind++];
7748
            } else {
7749
                optarg = NULL;
7750
            }
7751

    
7752
            switch(popt->index) {
7753
            case QEMU_OPTION_M:
7754
                machine = find_machine(optarg);
7755
                if (!machine) {
7756
                    QEMUMachine *m;
7757
                    printf("Supported machines are:\n");
7758
                    for(m = first_machine; m != NULL; m = m->next) {
7759
                        printf("%-10s %s%s\n",
7760
                               m->name, m->desc,
7761
                               m == first_machine ? " (default)" : "");
7762
                    }
7763
                    exit(*optarg != '?');
7764
                }
7765
                break;
7766
            case QEMU_OPTION_cpu:
7767
                /* hw initialization will check this */
7768
                if (*optarg == '?') {
7769
/* XXX: implement xxx_cpu_list for targets that still miss it */
7770
#if defined(cpu_list)
7771
                    cpu_list(stdout, &fprintf);
7772
#endif
7773
                    exit(0);
7774
                } else {
7775
                    cpu_model = optarg;
7776
                }
7777
                break;
7778
            case QEMU_OPTION_initrd:
7779
                initrd_filename = optarg;
7780
                break;
7781
            case QEMU_OPTION_hda:
7782
                if (cyls == 0)
7783
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
7784
                else
7785
                    hda_index = drive_add(optarg, HD_ALIAS
7786
                             ",cyls=%d,heads=%d,secs=%d%s",
7787
                             0, cyls, heads, secs,
7788
                             translation == BIOS_ATA_TRANSLATION_LBA ?
7789
                                 ",trans=lba" :
7790
                             translation == BIOS_ATA_TRANSLATION_NONE ?
7791
                                 ",trans=none" : "");
7792
                 break;
7793
            case QEMU_OPTION_hdb:
7794
            case QEMU_OPTION_hdc:
7795
            case QEMU_OPTION_hdd:
7796
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
7797
                break;
7798
            case QEMU_OPTION_drive:
7799
                drive_add(NULL, "%s", optarg);
7800
                break;
7801
            case QEMU_OPTION_mtdblock:
7802
                drive_add(optarg, MTD_ALIAS);
7803
                break;
7804
            case QEMU_OPTION_sd:
7805
                drive_add(optarg, SD_ALIAS);
7806
                break;
7807
            case QEMU_OPTION_pflash:
7808
                drive_add(optarg, PFLASH_ALIAS);
7809
                break;
7810
            case QEMU_OPTION_snapshot:
7811
                snapshot = 1;
7812
                break;
7813
            case QEMU_OPTION_hdachs:
7814
                {
7815
                    const char *p;
7816
                    p = optarg;
7817
                    cyls = strtol(p, (char **)&p, 0);
7818
                    if (cyls < 1 || cyls > 16383)
7819
                        goto chs_fail;
7820
                    if (*p != ',')
7821
                        goto chs_fail;
7822
                    p++;
7823
                    heads = strtol(p, (char **)&p, 0);
7824
                    if (heads < 1 || heads > 16)
7825
                        goto chs_fail;
7826
                    if (*p != ',')
7827
                        goto chs_fail;
7828
                    p++;
7829
                    secs = strtol(p, (char **)&p, 0);
7830
                    if (secs < 1 || secs > 63)
7831
                        goto chs_fail;
7832
                    if (*p == ',') {
7833
                        p++;
7834
                        if (!strcmp(p, "none"))
7835
                            translation = BIOS_ATA_TRANSLATION_NONE;
7836
                        else if (!strcmp(p, "lba"))
7837
                            translation = BIOS_ATA_TRANSLATION_LBA;
7838
                        else if (!strcmp(p, "auto"))
7839
                            translation = BIOS_ATA_TRANSLATION_AUTO;
7840
                        else
7841
                            goto chs_fail;
7842
                    } else if (*p != '\0') {
7843
                    chs_fail:
7844
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
7845
                        exit(1);
7846
                    }
7847
                    if (hda_index != -1)
7848
                        snprintf(drives_opt[hda_index].opt,
7849
                                 sizeof(drives_opt[hda_index].opt),
7850
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
7851
                                 0, cyls, heads, secs,
7852
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
7853
                                         ",trans=lba" :
7854
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
7855
                                     ",trans=none" : "");
7856
                }
7857
                break;
7858
            case QEMU_OPTION_nographic:
7859
                serial_devices[0] = "stdio";
7860
                parallel_devices[0] = "null";
7861
                monitor_device = "stdio";
7862
                nographic = 1;
7863
                break;
7864
#ifdef CONFIG_CURSES
7865
            case QEMU_OPTION_curses:
7866
                curses = 1;
7867
                break;
7868
#endif
7869
            case QEMU_OPTION_portrait:
7870
                graphic_rotate = 1;
7871
                break;
7872
            case QEMU_OPTION_kernel:
7873
                kernel_filename = optarg;
7874
                break;
7875
            case QEMU_OPTION_append:
7876
                kernel_cmdline = optarg;
7877
                break;
7878
            case QEMU_OPTION_cdrom:
7879
                drive_add(optarg, CDROM_ALIAS);
7880
                break;
7881
            case QEMU_OPTION_boot:
7882
                boot_devices = optarg;
7883
                /* We just do some generic consistency checks */
7884
                {
7885
                    /* Could easily be extended to 64 devices if needed */
7886
                    const char *p;
7887
                    
7888
                    boot_devices_bitmap = 0;
7889
                    for (p = boot_devices; *p != '\0'; p++) {
7890
                        /* Allowed boot devices are:
7891
                         * a b     : floppy disk drives
7892
                         * c ... f : IDE disk drives
7893
                         * g ... m : machine implementation dependant drives
7894
                         * n ... p : network devices
7895
                         * It's up to each machine implementation to check
7896
                         * if the given boot devices match the actual hardware
7897
                         * implementation and firmware features.
7898
                         */
7899
                        if (*p < 'a' || *p > 'q') {
7900
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
7901
                            exit(1);
7902
                        }
7903
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
7904
                            fprintf(stderr,
7905
                                    "Boot device '%c' was given twice\n",*p);
7906
                            exit(1);
7907
                        }
7908
                        boot_devices_bitmap |= 1 << (*p - 'a');
7909
                    }
7910
                }
7911
                break;
7912
            case QEMU_OPTION_fda:
7913
            case QEMU_OPTION_fdb:
7914
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
7915
                break;
7916
#ifdef TARGET_I386
7917
            case QEMU_OPTION_no_fd_bootchk:
7918
                fd_bootchk = 0;
7919
                break;
7920
#endif
7921
            case QEMU_OPTION_no_code_copy:
7922
                code_copy_enabled = 0;
7923
                break;
7924
            case QEMU_OPTION_net:
7925
                if (nb_net_clients >= MAX_NET_CLIENTS) {
7926
                    fprintf(stderr, "qemu: too many network clients\n");
7927
                    exit(1);
7928
                }
7929
                net_clients[nb_net_clients] = optarg;
7930
                nb_net_clients++;
7931
                break;
7932
#ifdef CONFIG_SLIRP
7933
            case QEMU_OPTION_tftp:
7934
                tftp_prefix = optarg;
7935
                break;
7936
            case QEMU_OPTION_bootp:
7937
                bootp_filename = optarg;
7938
                break;
7939
#ifndef _WIN32
7940
            case QEMU_OPTION_smb:
7941
                net_slirp_smb(optarg);
7942
                break;
7943
#endif
7944
            case QEMU_OPTION_redir:
7945
                net_slirp_redir(optarg);
7946
                break;
7947
#endif
7948
#ifdef HAS_AUDIO
7949
            case QEMU_OPTION_audio_help:
7950
                AUD_help ();
7951
                exit (0);
7952
                break;
7953
            case QEMU_OPTION_soundhw:
7954
                select_soundhw (optarg);
7955
                break;
7956
#endif
7957
            case QEMU_OPTION_h:
7958
                help(0);
7959
                break;
7960
            case QEMU_OPTION_m: {
7961
                uint64_t value;
7962
                char *ptr;
7963

    
7964
                value = strtoul(optarg, &ptr, 10);
7965
                switch (*ptr) {
7966
                case 0: case 'M': case 'm':
7967
                    value <<= 20;
7968
                    break;
7969
                case 'G': case 'g':
7970
                    value <<= 30;
7971
                    break;
7972
                default:
7973
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
7974
                    exit(1);
7975
                }
7976

    
7977
                /* On 32-bit hosts, QEMU is limited by virtual address space */
7978
                if (value > (2047 << 20)
7979
#ifndef USE_KQEMU
7980
                    && HOST_LONG_BITS == 32
7981
#endif
7982
                    ) {
7983
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
7984
                    exit(1);
7985
                }
7986
                if (value != (uint64_t)(ram_addr_t)value) {
7987
                    fprintf(stderr, "qemu: ram size too large\n");
7988
                    exit(1);
7989
                }
7990
                ram_size = value;
7991
                break;
7992
            }
7993
            case QEMU_OPTION_d:
7994
                {
7995
                    int mask;
7996
                    CPULogItem *item;
7997

    
7998
                    mask = cpu_str_to_log_mask(optarg);
7999
                    if (!mask) {
8000
                        printf("Log items (comma separated):\n");
8001
                    for(item = cpu_log_items; item->mask != 0; item++) {
8002
                        printf("%-10s %s\n", item->name, item->help);
8003
                    }
8004
                    exit(1);
8005
                    }
8006
                    cpu_set_log(mask);
8007
                }
8008
                break;
8009
#ifdef CONFIG_GDBSTUB
8010
            case QEMU_OPTION_s:
8011
                use_gdbstub = 1;
8012
                break;
8013
            case QEMU_OPTION_p:
8014
                gdbstub_port = optarg;
8015
                break;
8016
#endif
8017
            case QEMU_OPTION_L:
8018
                bios_dir = optarg;
8019
                break;
8020
            case QEMU_OPTION_bios:
8021
                bios_name = optarg;
8022
                break;
8023
            case QEMU_OPTION_S:
8024
                autostart = 0;
8025
                break;
8026
            case QEMU_OPTION_k:
8027
                keyboard_layout = optarg;
8028
                break;
8029
            case QEMU_OPTION_localtime:
8030
                rtc_utc = 0;
8031
                break;
8032
            case QEMU_OPTION_cirrusvga:
8033
                cirrus_vga_enabled = 1;
8034
                vmsvga_enabled = 0;
8035
                break;
8036
            case QEMU_OPTION_vmsvga:
8037
                cirrus_vga_enabled = 0;
8038
                vmsvga_enabled = 1;
8039
                break;
8040
            case QEMU_OPTION_std_vga:
8041
                cirrus_vga_enabled = 0;
8042
                vmsvga_enabled = 0;
8043
                break;
8044
            case QEMU_OPTION_g:
8045
                {
8046
                    const char *p;
8047
                    int w, h, depth;
8048
                    p = optarg;
8049
                    w = strtol(p, (char **)&p, 10);
8050
                    if (w <= 0) {
8051
                    graphic_error:
8052
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8053
                        exit(1);
8054
                    }
8055
                    if (*p != 'x')
8056
                        goto graphic_error;
8057
                    p++;
8058
                    h = strtol(p, (char **)&p, 10);
8059
                    if (h <= 0)
8060
                        goto graphic_error;
8061
                    if (*p == 'x') {
8062
                        p++;
8063
                        depth = strtol(p, (char **)&p, 10);
8064
                        if (depth != 8 && depth != 15 && depth != 16 &&
8065
                            depth != 24 && depth != 32)
8066
                            goto graphic_error;
8067
                    } else if (*p == '\0') {
8068
                        depth = graphic_depth;
8069
                    } else {
8070
                        goto graphic_error;
8071
                    }
8072

    
8073
                    graphic_width = w;
8074
                    graphic_height = h;
8075
                    graphic_depth = depth;
8076
                }
8077
                break;
8078
            case QEMU_OPTION_echr:
8079
                {
8080
                    char *r;
8081
                    term_escape_char = strtol(optarg, &r, 0);
8082
                    if (r == optarg)
8083
                        printf("Bad argument to echr\n");
8084
                    break;
8085
                }
8086
            case QEMU_OPTION_monitor:
8087
                monitor_device = optarg;
8088
                break;
8089
            case QEMU_OPTION_serial:
8090
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8091
                    fprintf(stderr, "qemu: too many serial ports\n");
8092
                    exit(1);
8093
                }
8094
                serial_devices[serial_device_index] = optarg;
8095
                serial_device_index++;
8096
                break;
8097
            case QEMU_OPTION_parallel:
8098
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8099
                    fprintf(stderr, "qemu: too many parallel ports\n");
8100
                    exit(1);
8101
                }
8102
                parallel_devices[parallel_device_index] = optarg;
8103
                parallel_device_index++;
8104
                break;
8105
            case QEMU_OPTION_loadvm:
8106
                loadvm = optarg;
8107
                break;
8108
            case QEMU_OPTION_full_screen:
8109
                full_screen = 1;
8110
                break;
8111
#ifdef CONFIG_SDL
8112
            case QEMU_OPTION_no_frame:
8113
                no_frame = 1;
8114
                break;
8115
            case QEMU_OPTION_alt_grab:
8116
                alt_grab = 1;
8117
                break;
8118
            case QEMU_OPTION_no_quit:
8119
                no_quit = 1;
8120
                break;
8121
#endif
8122
            case QEMU_OPTION_pidfile:
8123
                pid_file = optarg;
8124
                break;
8125
#ifdef TARGET_I386
8126
            case QEMU_OPTION_win2k_hack:
8127
                win2k_install_hack = 1;
8128
                break;
8129
#endif
8130
#ifdef USE_KQEMU
8131
            case QEMU_OPTION_no_kqemu:
8132
                kqemu_allowed = 0;
8133
                break;
8134
            case QEMU_OPTION_kernel_kqemu:
8135
                kqemu_allowed = 2;
8136
                break;
8137
#endif
8138
            case QEMU_OPTION_usb:
8139
                usb_enabled = 1;
8140
                break;
8141
            case QEMU_OPTION_usbdevice:
8142
                usb_enabled = 1;
8143
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8144
                    fprintf(stderr, "Too many USB devices\n");
8145
                    exit(1);
8146
                }
8147
                usb_devices[usb_devices_index] = optarg;
8148
                usb_devices_index++;
8149
                break;
8150
            case QEMU_OPTION_smp:
8151
                smp_cpus = atoi(optarg);
8152
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8153
                    fprintf(stderr, "Invalid number of CPUs\n");
8154
                    exit(1);
8155
                }
8156
                break;
8157
            case QEMU_OPTION_vnc:
8158
                vnc_display = optarg;
8159
                break;
8160
            case QEMU_OPTION_no_acpi:
8161
                acpi_enabled = 0;
8162
                break;
8163
            case QEMU_OPTION_no_reboot:
8164
                no_reboot = 1;
8165
                break;
8166
            case QEMU_OPTION_no_shutdown:
8167
                no_shutdown = 1;
8168
                break;
8169
            case QEMU_OPTION_show_cursor:
8170
                cursor_hide = 0;
8171
                break;
8172
            case QEMU_OPTION_daemonize:
8173
                daemonize = 1;
8174
                break;
8175
            case QEMU_OPTION_option_rom:
8176
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8177
                    fprintf(stderr, "Too many option ROMs\n");
8178
                    exit(1);
8179
                }
8180
                option_rom[nb_option_roms] = optarg;
8181
                nb_option_roms++;
8182
                break;
8183
            case QEMU_OPTION_semihosting:
8184
                semihosting_enabled = 1;
8185
                break;
8186
            case QEMU_OPTION_name:
8187
                qemu_name = optarg;
8188
                break;
8189
#ifdef TARGET_SPARC
8190
            case QEMU_OPTION_prom_env:
8191
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8192
                    fprintf(stderr, "Too many prom variables\n");
8193
                    exit(1);
8194
                }
8195
                prom_envs[nb_prom_envs] = optarg;
8196
                nb_prom_envs++;
8197
                break;
8198
#endif
8199
#ifdef TARGET_ARM
8200
            case QEMU_OPTION_old_param:
8201
                old_param = 1;
8202
                break;
8203
#endif
8204
            case QEMU_OPTION_clock:
8205
                configure_alarms(optarg);
8206
                break;
8207
            case QEMU_OPTION_startdate:
8208
                {
8209
                    struct tm tm;
8210
                    time_t rtc_start_date;
8211
                    if (!strcmp(optarg, "now")) {
8212
                        rtc_date_offset = -1;
8213
                    } else {
8214
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8215
                               &tm.tm_year,
8216
                               &tm.tm_mon,
8217
                               &tm.tm_mday,
8218
                               &tm.tm_hour,
8219
                               &tm.tm_min,
8220
                               &tm.tm_sec) == 6) {
8221
                            /* OK */
8222
                        } else if (sscanf(optarg, "%d-%d-%d",
8223
                                          &tm.tm_year,
8224
                                          &tm.tm_mon,
8225
                                          &tm.tm_mday) == 3) {
8226
                            tm.tm_hour = 0;
8227
                            tm.tm_min = 0;
8228
                            tm.tm_sec = 0;
8229
                        } else {
8230
                            goto date_fail;
8231
                        }
8232
                        tm.tm_year -= 1900;
8233
                        tm.tm_mon--;
8234
                        rtc_start_date = mktimegm(&tm);
8235
                        if (rtc_start_date == -1) {
8236
                        date_fail:
8237
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8238
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8239
                            exit(1);
8240
                        }
8241
                        rtc_date_offset = time(NULL) - rtc_start_date;
8242
                    }
8243
                }
8244
                break;
8245
            }
8246
        }
8247
    }
8248

    
8249
#ifndef _WIN32
8250
    if (daemonize && !nographic && vnc_display == NULL) {
8251
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8252
        daemonize = 0;
8253
    }
8254

    
8255
    if (daemonize) {
8256
        pid_t pid;
8257

    
8258
        if (pipe(fds) == -1)
8259
            exit(1);
8260

    
8261
        pid = fork();
8262
        if (pid > 0) {
8263
            uint8_t status;
8264
            ssize_t len;
8265

    
8266
            close(fds[1]);
8267

    
8268
        again:
8269
            len = read(fds[0], &status, 1);
8270
            if (len == -1 && (errno == EINTR))
8271
                goto again;
8272

    
8273
            if (len != 1)
8274
                exit(1);
8275
            else if (status == 1) {
8276
                fprintf(stderr, "Could not acquire pidfile\n");
8277
                exit(1);
8278
            } else
8279
                exit(0);
8280
        } else if (pid < 0)
8281
            exit(1);
8282

    
8283
        setsid();
8284

    
8285
        pid = fork();
8286
        if (pid > 0)
8287
            exit(0);
8288
        else if (pid < 0)
8289
            exit(1);
8290

    
8291
        umask(027);
8292
        chdir("/");
8293

    
8294
        signal(SIGTSTP, SIG_IGN);
8295
        signal(SIGTTOU, SIG_IGN);
8296
        signal(SIGTTIN, SIG_IGN);
8297
    }
8298
#endif
8299

    
8300
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8301
        if (daemonize) {
8302
            uint8_t status = 1;
8303
            write(fds[1], &status, 1);
8304
        } else
8305
            fprintf(stderr, "Could not acquire pid file\n");
8306
        exit(1);
8307
    }
8308

    
8309
#ifdef USE_KQEMU
8310
    if (smp_cpus > 1)
8311
        kqemu_allowed = 0;
8312
#endif
8313
    linux_boot = (kernel_filename != NULL);
8314
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8315

    
8316
    /* XXX: this should not be: some embedded targets just have flash */
8317
    if (!linux_boot && net_boot == 0 &&
8318
        nb_drives_opt == 0)
8319
        help(1);
8320

    
8321
    /* boot to floppy or the default cd if no hard disk defined yet */
8322
    if (!boot_devices[0]) {
8323
        boot_devices = "cad";
8324
    }
8325
    setvbuf(stdout, NULL, _IOLBF, 0);
8326

    
8327
    init_timers();
8328
    init_timer_alarm();
8329
    qemu_aio_init();
8330

    
8331
#ifdef _WIN32
8332
    socket_init();
8333
#endif
8334

    
8335
    /* init network clients */
8336
    if (nb_net_clients == 0) {
8337
        /* if no clients, we use a default config */
8338
        net_clients[0] = "nic";
8339
        net_clients[1] = "user";
8340
        nb_net_clients = 2;
8341
    }
8342

    
8343
    for(i = 0;i < nb_net_clients; i++) {
8344
        if (net_client_init(net_clients[i]) < 0)
8345
            exit(1);
8346
    }
8347
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8348
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8349
            continue;
8350
        if (vlan->nb_guest_devs == 0) {
8351
            fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8352
            exit(1);
8353
        }
8354
        if (vlan->nb_host_devs == 0)
8355
            fprintf(stderr,
8356
                    "Warning: vlan %d is not connected to host network\n",
8357
                    vlan->id);
8358
    }
8359

    
8360
#ifdef TARGET_I386
8361
    /* XXX: this should be moved in the PC machine instantiation code */
8362
    if (net_boot != 0) {
8363
        int netroms = 0;
8364
        for (i = 0; i < nb_nics && i < 4; i++) {
8365
            const char *model = nd_table[i].model;
8366
            char buf[1024];
8367
            if (net_boot & (1 << i)) {
8368
                if (model == NULL)
8369
                    model = "ne2k_pci";
8370
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8371
                if (get_image_size(buf) > 0) {
8372
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8373
                        fprintf(stderr, "Too many option ROMs\n");
8374
                        exit(1);
8375
                    }
8376
                    option_rom[nb_option_roms] = strdup(buf);
8377
                    nb_option_roms++;
8378
                    netroms++;
8379
                }
8380
            }
8381
        }
8382
        if (netroms == 0) {
8383
            fprintf(stderr, "No valid PXE rom found for network device\n");
8384
            exit(1);
8385
        }
8386
    }
8387
#endif
8388

    
8389
    /* init the memory */
8390
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
8391

    
8392
    if (machine->ram_require & RAMSIZE_FIXED) {
8393
        if (ram_size > 0) {
8394
            if (ram_size < phys_ram_size) {
8395
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
8396
                                machine->name, (unsigned long long) phys_ram_size);
8397
                exit(-1);
8398
            }
8399

    
8400
            phys_ram_size = ram_size;
8401
        } else
8402
            ram_size = phys_ram_size;
8403
    } else {
8404
        if (ram_size == 0)
8405
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8406

    
8407
        phys_ram_size += ram_size;
8408
    }
8409

    
8410
    phys_ram_base = qemu_vmalloc(phys_ram_size);
8411
    if (!phys_ram_base) {
8412
        fprintf(stderr, "Could not allocate physical memory\n");
8413
        exit(1);
8414
    }
8415

    
8416
    bdrv_init();
8417

    
8418
    /* we always create the cdrom drive, even if no disk is there */
8419

    
8420
    if (nb_drives_opt < MAX_DRIVES)
8421
        drive_add(NULL, CDROM_ALIAS);
8422

    
8423
    /* we always create at least one floppy */
8424

    
8425
    if (nb_drives_opt < MAX_DRIVES)
8426
        drive_add(NULL, FD_ALIAS, 0);
8427

    
8428
    /* we always create one sd slot, even if no card is in it */
8429

    
8430
    if (nb_drives_opt < MAX_DRIVES)
8431
        drive_add(NULL, SD_ALIAS);
8432

    
8433
    /* open the virtual block devices */
8434

    
8435
    for(i = 0; i < nb_drives_opt; i++)
8436
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8437
            exit(1);
8438

    
8439
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8440
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8441

    
8442
    init_ioports();
8443

    
8444
    /* terminal init */
8445
    memset(&display_state, 0, sizeof(display_state));
8446
    if (nographic) {
8447
        if (curses) {
8448
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
8449
            exit(1);
8450
        }
8451
        /* nearly nothing to do */
8452
        dumb_display_init(ds);
8453
    } else if (vnc_display != NULL) {
8454
        vnc_display_init(ds);
8455
        if (vnc_display_open(ds, vnc_display) < 0)
8456
            exit(1);
8457
    } else
8458
#if defined(CONFIG_CURSES)
8459
    if (curses) {
8460
        curses_display_init(ds, full_screen);
8461
    } else
8462
#endif
8463
    {
8464
#if defined(CONFIG_SDL)
8465
        sdl_display_init(ds, full_screen, no_frame);
8466
#elif defined(CONFIG_COCOA)
8467
        cocoa_display_init(ds, full_screen);
8468
#else
8469
        dumb_display_init(ds);
8470
#endif
8471
    }
8472

    
8473
    /* Maintain compatibility with multiple stdio monitors */
8474
    if (!strcmp(monitor_device,"stdio")) {
8475
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8476
            const char *devname = serial_devices[i];
8477
            if (devname && !strcmp(devname,"mon:stdio")) {
8478
                monitor_device = NULL;
8479
                break;
8480
            } else if (devname && !strcmp(devname,"stdio")) {
8481
                monitor_device = NULL;
8482
                serial_devices[i] = "mon:stdio";
8483
                break;
8484
            }
8485
        }
8486
    }
8487
    if (monitor_device) {
8488
        monitor_hd = qemu_chr_open(monitor_device);
8489
        if (!monitor_hd) {
8490
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8491
            exit(1);
8492
        }
8493
        monitor_init(monitor_hd, !nographic);
8494
    }
8495

    
8496
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8497
        const char *devname = serial_devices[i];
8498
        if (devname && strcmp(devname, "none")) {
8499
            serial_hds[i] = qemu_chr_open(devname);
8500
            if (!serial_hds[i]) {
8501
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
8502
                        devname);
8503
                exit(1);
8504
            }
8505
            if (strstart(devname, "vc", 0))
8506
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8507
        }
8508
    }
8509

    
8510
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8511
        const char *devname = parallel_devices[i];
8512
        if (devname && strcmp(devname, "none")) {
8513
            parallel_hds[i] = qemu_chr_open(devname);
8514
            if (!parallel_hds[i]) {
8515
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8516
                        devname);
8517
                exit(1);
8518
            }
8519
            if (strstart(devname, "vc", 0))
8520
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8521
        }
8522
    }
8523

    
8524
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
8525
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8526

    
8527
    /* init USB devices */
8528
    if (usb_enabled) {
8529
        for(i = 0; i < usb_devices_index; i++) {
8530
            if (usb_device_add(usb_devices[i]) < 0) {
8531
                fprintf(stderr, "Warning: could not add USB device %s\n",
8532
                        usb_devices[i]);
8533
            }
8534
        }
8535
    }
8536

    
8537
    if (display_state.dpy_refresh) {
8538
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8539
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8540
    }
8541

    
8542
#ifdef CONFIG_GDBSTUB
8543
    if (use_gdbstub) {
8544
        /* XXX: use standard host:port notation and modify options
8545
           accordingly. */
8546
        if (gdbserver_start(gdbstub_port) < 0) {
8547
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8548
                    gdbstub_port);
8549
            exit(1);
8550
        }
8551
    }
8552
#endif
8553

    
8554
    if (loadvm)
8555
        do_loadvm(loadvm);
8556

    
8557
    {
8558
        /* XXX: simplify init */
8559
        read_passwords();
8560
        if (autostart) {
8561
            vm_start();
8562
        }
8563
    }
8564

    
8565
    if (daemonize) {
8566
        uint8_t status = 0;
8567
        ssize_t len;
8568
        int fd;
8569

    
8570
    again1:
8571
        len = write(fds[1], &status, 1);
8572
        if (len == -1 && (errno == EINTR))
8573
            goto again1;
8574

    
8575
        if (len != 1)
8576
            exit(1);
8577

    
8578
        TFR(fd = open("/dev/null", O_RDWR));
8579
        if (fd == -1)
8580
            exit(1);
8581

    
8582
        dup2(fd, 0);
8583
        dup2(fd, 1);
8584
        dup2(fd, 2);
8585

    
8586
        close(fd);
8587
    }
8588

    
8589
    main_loop();
8590
    quit_timers();
8591

    
8592
#if !defined(_WIN32)
8593
    /* close network clients */
8594
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8595
        VLANClientState *vc;
8596

    
8597
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8598
            if (vc->fd_read == tap_receive) {
8599
                char ifname[64];
8600
                TAPState *s = vc->opaque;
8601

    
8602
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8603
                    s->down_script[0])
8604
                    launch_script(s->down_script, ifname, s->fd);
8605
            }
8606
        }
8607
    }
8608
#endif
8609
    return 0;
8610
}