Statistics
| Branch: | Revision:

root / vl.c @ f442e08b

History | View | Annotate | Download (236 kB)

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

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

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

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

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

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

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

    
117
#include "qemu_socket.h"
118

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

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

    
130
#include "disas.h"
131

    
132
#include "exec-all.h"
133

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
378
/***********************************************************/
379

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

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

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

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

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

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

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

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

    
486
/***********************************************************/
487
/* keyboard/mouse */
488

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

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

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

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

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

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

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

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

    
528
    return s;
529
}
530

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

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

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

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

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

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

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

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

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

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

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

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

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

    
605
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
606
}
607

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

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

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

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

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

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

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

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

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

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

    
678
#define QEMU_TIMER_BASE 1000000000LL
679

    
680
#ifdef WIN32
681

    
682
static int64_t clock_freq;
683

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

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

    
703
#else
704

    
705
static int use_rt_clock;
706

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

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

    
738
#endif
739

    
740
/***********************************************************/
741
/* guest cycle counter */
742

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

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

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

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

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

    
799
/***********************************************************/
800
/* timers */
801

    
802
#define QEMU_TIMER_REALTIME 0
803
#define QEMU_TIMER_VIRTUAL  1
804

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

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

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

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

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

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

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

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

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

    
847
static struct qemu_alarm_timer *alarm_timer;
848

    
849
#ifdef _WIN32
850

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

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

    
861
#else
862

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

    
866
#ifdef __linux__
867

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

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

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

    
878
#endif /* __linux__ */
879

    
880
#endif /* _WIN32 */
881

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

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

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

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

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

    
924
    arg = strdup(opt);
925

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

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

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

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

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

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

    
955
    free(arg);
956

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

    
967
QEMUClock *rt_clock;
968
QEMUClock *vm_clock;
969

    
970
static QEMUTimer *active_timers[2];
971

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

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

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

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

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

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

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

    
1024
    qemu_del_timer(ts);
1025

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1198
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1199

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

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

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

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

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

    
1234
    return nearest_delta_us;
1235
}
1236

    
1237
#ifndef _WIN32
1238

    
1239
#if defined(__linux__)
1240

    
1241
#define RTC_FREQ 1024
1242

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

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

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

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

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

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

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

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

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

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

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

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

    
1303
    close(fd);
1304
}
1305

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

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

    
1328
    enable_sigio_timer(rtc_fd);
1329

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

    
1332
    return 0;
1333
}
1334

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

    
1339
    close(rtc_fd);
1340
}
1341

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

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

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

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

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

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

    
1364
        return -1;
1365
    }
1366

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

    
1369
    return 0;
1370
}
1371

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

    
1376
    timer_delete(host_timer);
1377
}
1378

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

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

    
1390
    nearest_delta_us = qemu_next_deadline();
1391

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

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

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

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

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

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

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

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

    
1438
    return 0;
1439
}
1440

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

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

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

    
1451
#ifdef _WIN32
1452

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

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

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

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

    
1471
    timeBeginPeriod(data->period);
1472

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

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

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

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

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

    
1495
    return 0;
1496
}
1497

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

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

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

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

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

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

    
1520
    timeKillEvent(data->timerId);
1521

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

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

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

    
1537
#endif /* _WIN32 */
1538

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

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

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

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

    
1558
    alarm_timer = t;
1559
}
1560

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

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

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

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

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

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

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

    
1604
/***********************************************************/
1605
/* character device */
1606

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1726

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

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

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

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

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

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

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

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

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

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

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

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

    
1879
    mux_chr_accept_input (opaque);
1880

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

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

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

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

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

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

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

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

    
1948

    
1949
#ifdef _WIN32
1950

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

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

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

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

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

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

    
2000
#else
2001

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

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

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

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

    
2033
#ifndef _WIN32
2034

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

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

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

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

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

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

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

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

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

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

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

    
2105
    qemu_free(s);
2106
}
2107

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

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

    
2129
    qemu_chr_reset(chr);
2130

    
2131
    return chr;
2132
}
2133

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

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

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

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

    
2165

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

    
2169
#define TERM_FIFO_MAX_SIZE 1
2170

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2270
    return chr;
2271
}
2272

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2566
    qemu_chr_reset(chr);
2567

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

    
2572
#else /* _WIN32 */
2573

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2752
    win_chr_readfile(chr);
2753
}
2754

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

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

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

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

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

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

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

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

    
2822
    s->fpipe = TRUE;
2823

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

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

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

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

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

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

    
2876

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

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

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

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

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

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

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

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

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

    
2941
/***********************************************************/
2942
/* UDP Net console */
2943

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3066
/***********************************************************/
3067
/* TCP Net console */
3068

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

    
3078
static void tcp_chr_accept(void *opaque);
3079

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

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

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

    
3116
    int i;
3117
    int j = 0;
3118

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3484
void qemu_chr_close(CharDriverState *chr)
3485
{
3486
    if (chr->chr_close)
3487
        chr->chr_close(chr);
3488
    qemu_free(chr);
3489
}
3490

    
3491
/***********************************************************/
3492
/* network device redirectors */
3493

    
3494
__attribute__ (( unused ))
3495
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3496
{
3497
    int len, i, j, c;
3498

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

    
3521
static int parse_macaddr(uint8_t *macaddr, const char *p)
3522
{
3523
    int i;
3524
    char *last_char;
3525
    long int offset;
3526

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

    
3550
    return -1;
3551
}
3552

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

    
3573
int parse_host_src_port(struct sockaddr_in *haddr,
3574
                        struct sockaddr_in *saddr,
3575
                        const char *input_str)
3576
{
3577
    char *str = strdup(input_str);
3578
    char *host_str = str;
3579
    char *src_str;
3580
    char *ptr;
3581

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

    
3590
    if ((src_str = strchr(input_str,'@'))) {
3591
        *src_str = '\0';
3592
        src_str++;
3593
    }
3594

    
3595
    if (parse_host_port(haddr, host_str) < 0)
3596
        goto fail;
3597

    
3598
    if (!src_str || *src_str == '\0')
3599
        src_str = ":0";
3600

    
3601
    if (parse_host_port(saddr, src_str) < 0)
3602
        goto fail;
3603

    
3604
    free(str);
3605
    return(0);
3606

    
3607
fail:
3608
    free(str);
3609
    return -1;
3610
}
3611

    
3612
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3613
{
3614
    char buf[512];
3615
    struct hostent *he;
3616
    const char *p, *r;
3617
    int port;
3618

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

    
3642
#ifndef _WIN32
3643
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3644
{
3645
    const char *p;
3646
    int len;
3647

    
3648
    len = MIN(108, strlen(str));
3649
    p = strchr(str, ',');
3650
    if (p)
3651
        len = MIN(len, p - str);
3652

    
3653
    memset(uaddr, 0, sizeof(*uaddr));
3654

    
3655
    uaddr->sun_family = AF_UNIX;
3656
    memcpy(uaddr->sun_path, str, len);
3657

    
3658
    return 0;
3659
}
3660
#endif
3661

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

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

    
3696
    vc->next = NULL;
3697
    pvc = &vlan->first_client;
3698
    while (*pvc != NULL)
3699
        pvc = &(*pvc)->next;
3700
    *pvc = vc;
3701
    return vc;
3702
}
3703

    
3704
int qemu_can_send_packet(VLANClientState *vc1)
3705
{
3706
    VLANState *vlan = vc1->vlan;
3707
    VLANClientState *vc;
3708

    
3709
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3710
        if (vc != vc1) {
3711
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3712
                return 1;
3713
        }
3714
    }
3715
    return 0;
3716
}
3717

    
3718
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3719
{
3720
    VLANState *vlan = vc1->vlan;
3721
    VLANClientState *vc;
3722

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

    
3734
#if defined(CONFIG_SLIRP)
3735

    
3736
/* slirp network adapter */
3737

    
3738
static int slirp_inited;
3739
static VLANClientState *slirp_vc;
3740

    
3741
int slirp_can_output(void)
3742
{
3743
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3744
}
3745

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

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

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

    
3778
static void net_slirp_redir(const char *redir_str)
3779
{
3780
    int is_udp;
3781
    char buf[256], *r;
3782
    const char *p;
3783
    struct in_addr guest_addr;
3784
    int host_port, guest_port;
3785

    
3786
    if (!slirp_inited) {
3787
        slirp_inited = 1;
3788
        slirp_init();
3789
    }
3790

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

    
3802
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3803
        goto fail;
3804
    host_port = strtol(buf, &r, 0);
3805
    if (r == buf)
3806
        goto fail;
3807

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

    
3816
    guest_port = strtol(p, &r, 0);
3817
    if (r == p)
3818
        goto fail;
3819

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

    
3830
#ifndef _WIN32
3831

    
3832
char smb_dir[1024];
3833

    
3834
static void erase_dir(char *dir_name)
3835
{
3836
    DIR *d;
3837
    struct dirent *de;
3838
    char filename[1024];
3839

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

    
3859
/* automatic user mode samba server configuration */
3860
static void smb_exit(void)
3861
{
3862
    erase_dir(smb_dir);
3863
}
3864

    
3865
/* automatic user mode samba server configuration */
3866
static void net_slirp_smb(const char *exported_dir)
3867
{
3868
    char smb_conf[1024];
3869
    char smb_cmdline[1024];
3870
    FILE *f;
3871

    
3872
    if (!slirp_inited) {
3873
        slirp_inited = 1;
3874
        slirp_init();
3875
    }
3876

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

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

    
3914
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3915
             SMBD_COMMAND, smb_conf);
3916

    
3917
    slirp_add_exec(0, smb_cmdline, 4, 139);
3918
}
3919

    
3920
#endif /* !defined(_WIN32) */
3921
void do_info_slirp(void)
3922
{
3923
    slirp_stats();
3924
}
3925

    
3926
#endif /* CONFIG_SLIRP */
3927

    
3928
#if !defined(_WIN32)
3929

    
3930
typedef struct TAPState {
3931
    VLANClientState *vc;
3932
    int fd;
3933
    char down_script[1024];
3934
} TAPState;
3935

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

    
3949
static void tap_send(void *opaque)
3950
{
3951
    TAPState *s = opaque;
3952
    uint8_t buf[4096];
3953
    int size;
3954

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

    
3969
/* fd support */
3970

    
3971
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3972
{
3973
    TAPState *s;
3974

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

    
3985
#if defined (_BSD) || defined (__FreeBSD_kernel__)
3986
static int tap_open(char *ifname, int ifname_size)
3987
{
3988
    int fd;
3989
    char *dev;
3990
    struct stat s;
3991

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

    
3998
    fstat(fd, &s);
3999
    dev = devname(s.st_rdev, S_IFCHR);
4000
    pstrcpy(ifname, ifname_size, dev);
4001

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

    
4017
    static int arp_fd = 0;
4018
    int ip_muxid, arp_muxid;
4019
    struct strioctl  strioc_if, strioc_ppa;
4020
    int link_type = I_PLINK;;
4021
    struct lifreq ifr;
4022
    char actual_name[32] = "";
4023

    
4024
    memset(&ifr, 0x0, sizeof(ifr));
4025

    
4026
    if( *dev ){
4027
       ptr = dev;
4028
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
4029
       ppa = atoi(ptr);
4030
    }
4031

    
4032
    /* Check if IP device was opened */
4033
    if( ip_fd )
4034
       close(ip_fd);
4035

    
4036
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4037
    if (ip_fd < 0) {
4038
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4039
       return -1;
4040
    }
4041

    
4042
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4043
    if (tap_fd < 0) {
4044
       syslog(LOG_ERR, "Can't open /dev/tap");
4045
       return -1;
4046
    }
4047

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

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

    
4066
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4067
        syslog(LOG_ERR, "Can't get flags\n");
4068

    
4069
    snprintf (actual_name, 32, "tap%d", ppa);
4070
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4071

    
4072
    ifr.lifr_ppa = ppa;
4073
    /* Assign ppa according to the unit number returned by tun device */
4074

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

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

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

    
4102
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4103
       syslog(LOG_ERR, "Can't link TAP device to IP");
4104
       return -1;
4105
    }
4106

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

    
4110
    close (if_fd);
4111

    
4112
    memset(&ifr, 0x0, sizeof(ifr));
4113
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4114
    ifr.lifr_ip_muxid  = ip_muxid;
4115
    ifr.lifr_arp_muxid = arp_muxid;
4116

    
4117
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4118
    {
4119
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4120
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4121
      syslog (LOG_ERR, "Can't set multiplexor id");
4122
    }
4123

    
4124
    sprintf(dev, "tap%d", ppa);
4125
    return tap_fd;
4126
}
4127

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

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

    
4169
static int launch_script(const char *setup_script, const char *ifname, int fd)
4170
{
4171
    int pid, status;
4172
    char *args[3];
4173
    char **parg;
4174

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

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

    
4205
static int net_tap_init(VLANState *vlan, const char *ifname1,
4206
                        const char *setup_script, const char *down_script)
4207
{
4208
    TAPState *s;
4209
    int fd;
4210
    char ifname[128];
4211

    
4212
    if (ifname1 != NULL)
4213
        pstrcpy(ifname, sizeof(ifname), ifname1);
4214
    else
4215
        ifname[0] = '\0';
4216
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4217
    if (fd < 0)
4218
        return -1;
4219

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

    
4236
#endif /* !_WIN32 */
4237

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

    
4249
typedef struct NetSocketListenState {
4250
    VLANState *vlan;
4251
    int fd;
4252
} NetSocketListenState;
4253

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

    
4261
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4262
    send_all(s->fd, buf, size);
4263
}
4264

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

    
4272
static void net_socket_send(void *opaque)
4273
{
4274
    NetSocketState *s = opaque;
4275
    int l, size, err;
4276
    uint8_t buf1[4096];
4277
    const uint8_t *buf;
4278

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

    
4328
static void net_socket_send_dgram(void *opaque)
4329
{
4330
    NetSocketState *s = opaque;
4331
    int size;
4332

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

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

    
4355
    }
4356
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4357
    if (fd < 0) {
4358
        perror("socket(PF_INET, SOCK_DGRAM)");
4359
        return -1;
4360
    }
4361

    
4362
    val = 1;
4363
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4364
                   (const char *)&val, sizeof(val));
4365
    if (ret < 0) {
4366
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4367
        goto fail;
4368
    }
4369

    
4370
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4371
    if (ret < 0) {
4372
        perror("bind");
4373
        goto fail;
4374
    }
4375

    
4376
    /* Add host to multicast group */
4377
    imr.imr_multiaddr = mcastaddr->sin_addr;
4378
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4379

    
4380
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4381
                     (const char *)&imr, sizeof(struct ip_mreq));
4382
    if (ret < 0) {
4383
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4384
        goto fail;
4385
    }
4386

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

    
4396
    socket_set_nonblock(fd);
4397
    return fd;
4398
fail:
4399
    if (fd >= 0)
4400
        closesocket(fd);
4401
    return -1;
4402
}
4403

    
4404
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4405
                                          int is_connected)
4406
{
4407
    struct sockaddr_in saddr;
4408
    int newfd;
4409
    socklen_t saddr_len;
4410
    NetSocketState *s;
4411

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

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

    
4436
        } else {
4437
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4438
                    fd, strerror(errno));
4439
            return NULL;
4440
        }
4441
    }
4442

    
4443
    s = qemu_mallocz(sizeof(NetSocketState));
4444
    if (!s)
4445
        return NULL;
4446
    s->fd = fd;
4447

    
4448
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4449
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4450

    
4451
    /* mcast: save bound address as dst */
4452
    if (is_connected) s->dgram_dst=saddr;
4453

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

    
4461
static void net_socket_connect(void *opaque)
4462
{
4463
    NetSocketState *s = opaque;
4464
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4465
}
4466

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

    
4487
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4488
                                          int is_connected)
4489
{
4490
    int so_type=-1, optlen=sizeof(so_type);
4491

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

    
4510
static void net_socket_accept(void *opaque)
4511
{
4512
    NetSocketListenState *s = opaque;
4513
    NetSocketState *s1;
4514
    struct sockaddr_in saddr;
4515
    socklen_t len;
4516
    int fd;
4517

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

    
4537
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4538
{
4539
    NetSocketListenState *s;
4540
    int fd, val, ret;
4541
    struct sockaddr_in saddr;
4542

    
4543
    if (parse_host_port(&saddr, host_str) < 0)
4544
        return -1;
4545

    
4546
    s = qemu_mallocz(sizeof(NetSocketListenState));
4547
    if (!s)
4548
        return -1;
4549

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

    
4557
    /* allow fast reuse */
4558
    val = 1;
4559
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4560

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

    
4577
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4578
{
4579
    NetSocketState *s;
4580
    int fd, connected, ret, err;
4581
    struct sockaddr_in saddr;
4582

    
4583
    if (parse_host_port(&saddr, host_str) < 0)
4584
        return -1;
4585

    
4586
    fd = socket(PF_INET, SOCK_STREAM, 0);
4587
    if (fd < 0) {
4588
        perror("socket");
4589
        return -1;
4590
    }
4591
    socket_set_nonblock(fd);
4592

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

    
4624
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4625
{
4626
    NetSocketState *s;
4627
    int fd;
4628
    struct sockaddr_in saddr;
4629

    
4630
    if (parse_host_port(&saddr, host_str) < 0)
4631
        return -1;
4632

    
4633

    
4634
    fd = net_socket_mcast_create(&saddr);
4635
    if (fd < 0)
4636
        return -1;
4637

    
4638
    s = net_socket_fd_init(vlan, fd, 0);
4639
    if (!s)
4640
        return -1;
4641

    
4642
    s->dgram_dst = saddr;
4643

    
4644
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4645
             "socket: mcast=%s:%d",
4646
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4647
    return 0;
4648

    
4649
}
4650

    
4651
static const char *get_opt_name(char *buf, int buf_size, const char *p)
4652
{
4653
    char *q;
4654

    
4655
    q = buf;
4656
    while (*p != '\0' && *p != '=') {
4657
        if (q && (q - buf) < buf_size - 1)
4658
            *q++ = *p;
4659
        p++;
4660
    }
4661
    if (q)
4662
        *q = '\0';
4663

    
4664
    return p;
4665
}
4666

    
4667
static const char *get_opt_value(char *buf, int buf_size, const char *p)
4668
{
4669
    char *q;
4670

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

    
4685
    return p;
4686
}
4687

    
4688
static int get_param_value(char *buf, int buf_size,
4689
                           const char *tag, const char *str)
4690
{
4691
    const char *p;
4692
    char option[128];
4693

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

    
4713
static int check_params(char *buf, int buf_size,
4714
                        char **params, const char *str)
4715
{
4716
    const char *p;
4717
    int i;
4718

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

    
4738

    
4739
static int net_client_init(const char *str)
4740
{
4741
    const char *p;
4742
    char *q;
4743
    char device[64];
4744
    char buf[1024];
4745
    int vlan_id, ret;
4746
    VLANState *vlan;
4747

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

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

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

    
4874
    return ret;
4875
}
4876

    
4877
void do_info_network(void)
4878
{
4879
    VLANState *vlan;
4880
    VLANClientState *vc;
4881

    
4882
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4883
        term_printf("VLAN %d devices:\n", vlan->id);
4884
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4885
            term_printf("  %s\n", vc->info_str);
4886
    }
4887
}
4888

    
4889
#define HD_ALIAS "index=%d,media=disk"
4890
#ifdef TARGET_PPC
4891
#define CDROM_ALIAS "index=1,media=cdrom"
4892
#else
4893
#define CDROM_ALIAS "index=2,media=cdrom"
4894
#endif
4895
#define FD_ALIAS "index=%d,if=floppy"
4896
#define PFLASH_ALIAS "if=pflash"
4897
#define MTD_ALIAS "if=mtd"
4898
#define SD_ALIAS "index=0,if=sd"
4899

    
4900
static int drive_add(const char *file, const char *fmt, ...)
4901
{
4902
    va_list ap;
4903

    
4904
    if (nb_drives_opt >= MAX_DRIVES) {
4905
        fprintf(stderr, "qemu: too many drives\n");
4906
        exit(1);
4907
    }
4908

    
4909
    drives_opt[nb_drives_opt].file = file;
4910
    va_start(ap, fmt);
4911
    vsnprintf(drives_opt[nb_drives_opt].opt,
4912
              sizeof(drives_opt[0].opt), fmt, ap);
4913
    va_end(ap);
4914

    
4915
    return nb_drives_opt++;
4916
}
4917

    
4918
int drive_get_index(BlockInterfaceType type, int bus, int unit)
4919
{
4920
    int index;
4921

    
4922
    /* seek interface, bus and unit */
4923

    
4924
    for (index = 0; index < nb_drives; index++)
4925
        if (drives_table[index].type == type &&
4926
            drives_table[index].bus == bus &&
4927
            drives_table[index].unit == unit)
4928
        return index;
4929

    
4930
    return -1;
4931
}
4932

    
4933
int drive_get_max_bus(BlockInterfaceType type)
4934
{
4935
    int max_bus;
4936
    int index;
4937

    
4938
    max_bus = -1;
4939
    for (index = 0; index < nb_drives; index++) {
4940
        if(drives_table[index].type == type &&
4941
           drives_table[index].bus > max_bus)
4942
            max_bus = drives_table[index].bus;
4943
    }
4944
    return max_bus;
4945
}
4946

    
4947
static int drive_init(struct drive_opt *arg, int snapshot,
4948
                      QEMUMachine *machine)
4949
{
4950
    char buf[128];
4951
    char file[1024];
4952
    char devname[128];