Statistics
| Branch: | Revision:

root / vl.c @ 3c6b2088

History | View | Annotate | Download (219.5 kB)

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

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

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

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

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

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

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

    
102
#include "qemu_socket.h"
103

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

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

    
115
#include "disas.h"
116

    
117
#include "exec-all.h"
118

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
512
    return s;
513
}
514

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

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

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

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

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

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

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

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

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

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

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

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

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

    
589
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
590
}
591

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

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

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

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

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

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

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

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

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

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

    
662
#define QEMU_TIMER_BASE 1000000000LL
663

    
664
#ifdef WIN32
665

    
666
static int64_t clock_freq;
667

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

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

    
687
#else
688

    
689
static int use_rt_clock;
690

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

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

    
722
#endif
723

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

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

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

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

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

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

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

    
786
#define QEMU_TIMER_REALTIME 0
787
#define QEMU_TIMER_VIRTUAL  1
788

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

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

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

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

    
812
#define ALARM_FLAG_DYNTICKS  0x1
813

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

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

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

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

    
830
static struct qemu_alarm_timer *alarm_timer;
831

    
832
#ifdef _WIN32
833

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

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

    
844
#else
845

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

    
849
#ifdef __linux__
850

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

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

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

    
861
#endif /* __linux__ */
862

    
863
#endif /* _WIN32 */
864

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

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

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

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

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

    
907
    arg = strdup(opt);
908

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

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

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

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

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

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

    
938
    free(arg);
939

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

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

    
950
QEMUClock *rt_clock;
951
QEMUClock *vm_clock;
952

    
953
static QEMUTimer *active_timers[2];
954

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

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

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

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

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

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

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

    
1007
    qemu_del_timer(ts);
1008

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1209
    return nearest_delta_us;
1210
}
1211

    
1212
#ifndef _WIN32
1213

    
1214
#if defined(__linux__)
1215

    
1216
#define RTC_FREQ 1024
1217

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

    
1222
    /* timer signal */
1223
    sigfillset(&act.sa_mask);
1224
    act.sa_flags = 0;
1225
    act.sa_handler = host_alarm_handler;
1226

    
1227
    sigaction(SIGIO, &act, NULL);
1228
    fcntl(fd, F_SETFL, O_ASYNC);
1229
    fcntl(fd, F_SETOWN, getpid());
1230
}
1231

    
1232
static int hpet_start_timer(struct qemu_alarm_timer *t)
1233
{
1234
    struct hpet_info info;
1235
    int r, fd;
1236

    
1237
    fd = open("/dev/hpet", O_RDONLY);
1238
    if (fd < 0)
1239
        return -1;
1240

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

    
1250
    /* Check capabilities */
1251
    r = ioctl(fd, HPET_INFO, &info);
1252
    if (r < 0)
1253
        goto fail;
1254

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

    
1260
    /* Enable interrupt */
1261
    r = ioctl(fd, HPET_IE_ON, 0);
1262
    if (r < 0)
1263
        goto fail;
1264

    
1265
    enable_sigio_timer(fd);
1266
    t->priv = (void *)(long)fd;
1267

    
1268
    return 0;
1269
fail:
1270
    close(fd);
1271
    return -1;
1272
}
1273

    
1274
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1275
{
1276
    int fd = (long)t->priv;
1277

    
1278
    close(fd);
1279
}
1280

    
1281
static int rtc_start_timer(struct qemu_alarm_timer *t)
1282
{
1283
    int rtc_fd;
1284

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

    
1300
    enable_sigio_timer(rtc_fd);
1301

    
1302
    t->priv = (void *)(long)rtc_fd;
1303

    
1304
    return 0;
1305
}
1306

    
1307
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1308
{
1309
    int rtc_fd = (long)t->priv;
1310

    
1311
    close(rtc_fd);
1312
}
1313

    
1314
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1315
{
1316
    struct sigevent ev;
1317
    timer_t host_timer;
1318
    struct sigaction act;
1319

    
1320
    sigfillset(&act.sa_mask);
1321
    act.sa_flags = 0;
1322
    act.sa_handler = host_alarm_handler;
1323

    
1324
    sigaction(SIGALRM, &act, NULL);
1325

    
1326
    ev.sigev_value.sival_int = 0;
1327
    ev.sigev_notify = SIGEV_SIGNAL;
1328
    ev.sigev_signo = SIGALRM;
1329

    
1330
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1331
        perror("timer_create");
1332

    
1333
        /* disable dynticks */
1334
        fprintf(stderr, "Dynamic Ticks disabled\n");
1335

    
1336
        return -1;
1337
    }
1338

    
1339
    t->priv = (void *)host_timer;
1340

    
1341
    return 0;
1342
}
1343

    
1344
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1345
{
1346
    timer_t host_timer = (timer_t)t->priv;
1347

    
1348
    timer_delete(host_timer);
1349
}
1350

    
1351
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1352
{
1353
    timer_t host_timer = (timer_t)t->priv;
1354
    struct itimerspec timeout;
1355
    int64_t nearest_delta_us = INT64_MAX;
1356
    int64_t current_us;
1357

    
1358
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1359
                !active_timers[QEMU_TIMER_VIRTUAL])
1360
            return;
1361

    
1362
    nearest_delta_us = qemu_next_deadline();
1363

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

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

    
1385
#endif /* defined(__linux__) */
1386

    
1387
static int unix_start_timer(struct qemu_alarm_timer *t)
1388
{
1389
    struct sigaction act;
1390
    struct itimerval itv;
1391
    int err;
1392

    
1393
    /* timer signal */
1394
    sigfillset(&act.sa_mask);
1395
    act.sa_flags = 0;
1396
    act.sa_handler = host_alarm_handler;
1397

    
1398
    sigaction(SIGALRM, &act, NULL);
1399

    
1400
    itv.it_interval.tv_sec = 0;
1401
    /* for i386 kernel 2.6 to get 1 ms */
1402
    itv.it_interval.tv_usec = 999;
1403
    itv.it_value.tv_sec = 0;
1404
    itv.it_value.tv_usec = 10 * 1000;
1405

    
1406
    err = setitimer(ITIMER_REAL, &itv, NULL);
1407
    if (err)
1408
        return -1;
1409

    
1410
    return 0;
1411
}
1412

    
1413
static void unix_stop_timer(struct qemu_alarm_timer *t)
1414
{
1415
    struct itimerval itv;
1416

    
1417
    memset(&itv, 0, sizeof(itv));
1418
    setitimer(ITIMER_REAL, &itv, NULL);
1419
}
1420

    
1421
#endif /* !defined(_WIN32) */
1422

    
1423
#ifdef _WIN32
1424

    
1425
static int win32_start_timer(struct qemu_alarm_timer *t)
1426
{
1427
    TIMECAPS tc;
1428
    struct qemu_alarm_win32 *data = t->priv;
1429
    UINT flags;
1430

    
1431
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1432
    if (!data->host_alarm) {
1433
        perror("Failed CreateEvent");
1434
        return -1;
1435
    }
1436

    
1437
    memset(&tc, 0, sizeof(tc));
1438
    timeGetDevCaps(&tc, sizeof(tc));
1439

    
1440
    if (data->period < tc.wPeriodMin)
1441
        data->period = tc.wPeriodMin;
1442

    
1443
    timeBeginPeriod(data->period);
1444

    
1445
    flags = TIME_CALLBACK_FUNCTION;
1446
    if (alarm_has_dynticks(t))
1447
        flags |= TIME_ONESHOT;
1448
    else
1449
        flags |= TIME_PERIODIC;
1450

    
1451
    data->timerId = timeSetEvent(1,         // interval (ms)
1452
                        data->period,       // resolution
1453
                        host_alarm_handler, // function
1454
                        (DWORD)t,           // parameter
1455
                        flags);
1456

    
1457
    if (!data->timerId) {
1458
        perror("Failed to initialize win32 alarm timer");
1459

    
1460
        timeEndPeriod(data->period);
1461
        CloseHandle(data->host_alarm);
1462
        return -1;
1463
    }
1464

    
1465
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1466

    
1467
    return 0;
1468
}
1469

    
1470
static void win32_stop_timer(struct qemu_alarm_timer *t)
1471
{
1472
    struct qemu_alarm_win32 *data = t->priv;
1473

    
1474
    timeKillEvent(data->timerId);
1475
    timeEndPeriod(data->period);
1476

    
1477
    CloseHandle(data->host_alarm);
1478
}
1479

    
1480
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1481
{
1482
    struct qemu_alarm_win32 *data = t->priv;
1483
    uint64_t nearest_delta_us;
1484

    
1485
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1486
                !active_timers[QEMU_TIMER_VIRTUAL])
1487
            return;
1488

    
1489
    nearest_delta_us = qemu_next_deadline();
1490
    nearest_delta_us /= 1000;
1491

    
1492
    timeKillEvent(data->timerId);
1493

    
1494
    data->timerId = timeSetEvent(1,
1495
                        data->period,
1496
                        host_alarm_handler,
1497
                        (DWORD)t,
1498
                        TIME_ONESHOT | TIME_PERIODIC);
1499

    
1500
    if (!data->timerId) {
1501
        perror("Failed to re-arm win32 alarm timer");
1502

    
1503
        timeEndPeriod(data->period);
1504
        CloseHandle(data->host_alarm);
1505
        exit(1);
1506
    }
1507
}
1508

    
1509
#endif /* _WIN32 */
1510

    
1511
static void init_timer_alarm(void)
1512
{
1513
    struct qemu_alarm_timer *t;
1514
    int i, err = -1;
1515

    
1516
    for (i = 0; alarm_timers[i].name; i++) {
1517
        t = &alarm_timers[i];
1518

    
1519
        err = t->start(t);
1520
        if (!err)
1521
            break;
1522
    }
1523

    
1524
    if (err) {
1525
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1526
        fprintf(stderr, "Terminating\n");
1527
        exit(1);
1528
    }
1529

    
1530
    alarm_timer = t;
1531
}
1532

    
1533
void quit_timers(void)
1534
{
1535
    alarm_timer->stop(alarm_timer);
1536
    alarm_timer = NULL;
1537
}
1538

    
1539
/***********************************************************/
1540
/* character device */
1541

    
1542
static void qemu_chr_event(CharDriverState *s, int event)
1543
{
1544
    if (!s->chr_event)
1545
        return;
1546
    s->chr_event(s->handler_opaque, event);
1547
}
1548

    
1549
static void qemu_chr_reset_bh(void *opaque)
1550
{
1551
    CharDriverState *s = opaque;
1552
    qemu_chr_event(s, CHR_EVENT_RESET);
1553
    qemu_bh_delete(s->bh);
1554
    s->bh = NULL;
1555
}
1556

    
1557
void qemu_chr_reset(CharDriverState *s)
1558
{
1559
    if (s->bh == NULL) {
1560
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1561
        qemu_bh_schedule(s->bh);
1562
    }
1563
}
1564

    
1565
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1566
{
1567
    return s->chr_write(s, buf, len);
1568
}
1569

    
1570
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1571
{
1572
    if (!s->chr_ioctl)
1573
        return -ENOTSUP;
1574
    return s->chr_ioctl(s, cmd, arg);
1575
}
1576

    
1577
int qemu_chr_can_read(CharDriverState *s)
1578
{
1579
    if (!s->chr_can_read)
1580
        return 0;
1581
    return s->chr_can_read(s->handler_opaque);
1582
}
1583

    
1584
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1585
{
1586
    s->chr_read(s->handler_opaque, buf, len);
1587
}
1588

    
1589

    
1590
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1591
{
1592
    char buf[4096];
1593
    va_list ap;
1594
    va_start(ap, fmt);
1595
    vsnprintf(buf, sizeof(buf), fmt, ap);
1596
    qemu_chr_write(s, buf, strlen(buf));
1597
    va_end(ap);
1598
}
1599

    
1600
void qemu_chr_send_event(CharDriverState *s, int event)
1601
{
1602
    if (s->chr_send_event)
1603
        s->chr_send_event(s, event);
1604
}
1605

    
1606
void qemu_chr_add_handlers(CharDriverState *s,
1607
                           IOCanRWHandler *fd_can_read,
1608
                           IOReadHandler *fd_read,
1609
                           IOEventHandler *fd_event,
1610
                           void *opaque)
1611
{
1612
    s->chr_can_read = fd_can_read;
1613
    s->chr_read = fd_read;
1614
    s->chr_event = fd_event;
1615
    s->handler_opaque = opaque;
1616
    if (s->chr_update_read_handler)
1617
        s->chr_update_read_handler(s);
1618
}
1619

    
1620
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1621
{
1622
    return len;
1623
}
1624

    
1625
static CharDriverState *qemu_chr_open_null(void)
1626
{
1627
    CharDriverState *chr;
1628

    
1629
    chr = qemu_mallocz(sizeof(CharDriverState));
1630
    if (!chr)
1631
        return NULL;
1632
    chr->chr_write = null_chr_write;
1633
    return chr;
1634
}
1635

    
1636
/* MUX driver for serial I/O splitting */
1637
static int term_timestamps;
1638
static int64_t term_timestamps_start;
1639
#define MAX_MUX 4
1640
typedef struct {
1641
    IOCanRWHandler *chr_can_read[MAX_MUX];
1642
    IOReadHandler *chr_read[MAX_MUX];
1643
    IOEventHandler *chr_event[MAX_MUX];
1644
    void *ext_opaque[MAX_MUX];
1645
    CharDriverState *drv;
1646
    int mux_cnt;
1647
    int term_got_escape;
1648
    int max_size;
1649
} MuxDriver;
1650

    
1651

    
1652
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1653
{
1654
    MuxDriver *d = chr->opaque;
1655
    int ret;
1656
    if (!term_timestamps) {
1657
        ret = d->drv->chr_write(d->drv, buf, len);
1658
    } else {
1659
        int i;
1660

    
1661
        ret = 0;
1662
        for(i = 0; i < len; i++) {
1663
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1664
            if (buf[i] == '\n') {
1665
                char buf1[64];
1666
                int64_t ti;
1667
                int secs;
1668

    
1669
                ti = get_clock();
1670
                if (term_timestamps_start == -1)
1671
                    term_timestamps_start = ti;
1672
                ti -= term_timestamps_start;
1673
                secs = ti / 1000000000;
1674
                snprintf(buf1, sizeof(buf1),
1675
                         "[%02d:%02d:%02d.%03d] ",
1676
                         secs / 3600,
1677
                         (secs / 60) % 60,
1678
                         secs % 60,
1679
                         (int)((ti / 1000000) % 1000));
1680
                d->drv->chr_write(d->drv, buf1, strlen(buf1));
1681
            }
1682
        }
1683
    }
1684
    return ret;
1685
}
1686

    
1687
static char *mux_help[] = {
1688
    "% h    print this help\n\r",
1689
    "% x    exit emulator\n\r",
1690
    "% s    save disk data back to file (if -snapshot)\n\r",
1691
    "% t    toggle console timestamps\n\r"
1692
    "% b    send break (magic sysrq)\n\r",
1693
    "% c    switch between console and monitor\n\r",
1694
    "% %  sends %\n\r",
1695
    NULL
1696
};
1697

    
1698
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1699
static void mux_print_help(CharDriverState *chr)
1700
{
1701
    int i, j;
1702
    char ebuf[15] = "Escape-Char";
1703
    char cbuf[50] = "\n\r";
1704

    
1705
    if (term_escape_char > 0 && term_escape_char < 26) {
1706
        sprintf(cbuf,"\n\r");
1707
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1708
    } else {
1709
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1710
    }
1711
    chr->chr_write(chr, cbuf, strlen(cbuf));
1712
    for (i = 0; mux_help[i] != NULL; i++) {
1713
        for (j=0; mux_help[i][j] != '\0'; j++) {
1714
            if (mux_help[i][j] == '%')
1715
                chr->chr_write(chr, ebuf, strlen(ebuf));
1716
            else
1717
                chr->chr_write(chr, &mux_help[i][j], 1);
1718
        }
1719
    }
1720
}
1721

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

    
1774
static int mux_chr_can_read(void *opaque)
1775
{
1776
    CharDriverState *chr = opaque;
1777
    MuxDriver *d = chr->opaque;
1778
    if (d->chr_can_read[chr->focus])
1779
       return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1780
    return 0;
1781
}
1782

    
1783
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1784
{
1785
    CharDriverState *chr = opaque;
1786
    MuxDriver *d = chr->opaque;
1787
    int i;
1788
    for(i = 0; i < size; i++)
1789
        if (mux_proc_byte(chr, d, buf[i]))
1790
            d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1791
}
1792

    
1793
static void mux_chr_event(void *opaque, int event)
1794
{
1795
    CharDriverState *chr = opaque;
1796
    MuxDriver *d = chr->opaque;
1797
    int i;
1798

    
1799
    /* Send the event to all registered listeners */
1800
    for (i = 0; i < d->mux_cnt; i++)
1801
        if (d->chr_event[i])
1802
            d->chr_event[i](d->ext_opaque[i], event);
1803
}
1804

    
1805
static void mux_chr_update_read_handler(CharDriverState *chr)
1806
{
1807
    MuxDriver *d = chr->opaque;
1808

    
1809
    if (d->mux_cnt >= MAX_MUX) {
1810
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1811
        return;
1812
    }
1813
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1814
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1815
    d->chr_read[d->mux_cnt] = chr->chr_read;
1816
    d->chr_event[d->mux_cnt] = chr->chr_event;
1817
    /* Fix up the real driver with mux routines */
1818
    if (d->mux_cnt == 0) {
1819
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1820
                              mux_chr_event, chr);
1821
    }
1822
    chr->focus = d->mux_cnt;
1823
    d->mux_cnt++;
1824
}
1825

    
1826
CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1827
{
1828
    CharDriverState *chr;
1829
    MuxDriver *d;
1830

    
1831
    chr = qemu_mallocz(sizeof(CharDriverState));
1832
    if (!chr)
1833
        return NULL;
1834
    d = qemu_mallocz(sizeof(MuxDriver));
1835
    if (!d) {
1836
        free(chr);
1837
        return NULL;
1838
    }
1839

    
1840
    chr->opaque = d;
1841
    d->drv = drv;
1842
    chr->focus = -1;
1843
    chr->chr_write = mux_chr_write;
1844
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1845
    return chr;
1846
}
1847

    
1848

    
1849
#ifdef _WIN32
1850

    
1851
static void socket_cleanup(void)
1852
{
1853
    WSACleanup();
1854
}
1855

    
1856
static int socket_init(void)
1857
{
1858
    WSADATA Data;
1859
    int ret, err;
1860

    
1861
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1862
    if (ret != 0) {
1863
        err = WSAGetLastError();
1864
        fprintf(stderr, "WSAStartup: %d\n", err);
1865
        return -1;
1866
    }
1867
    atexit(socket_cleanup);
1868
    return 0;
1869
}
1870

    
1871
static int send_all(int fd, const uint8_t *buf, int len1)
1872
{
1873
    int ret, len;
1874

    
1875
    len = len1;
1876
    while (len > 0) {
1877
        ret = send(fd, buf, len, 0);
1878
        if (ret < 0) {
1879
            int errno;
1880
            errno = WSAGetLastError();
1881
            if (errno != WSAEWOULDBLOCK) {
1882
                return -1;
1883
            }
1884
        } else if (ret == 0) {
1885
            break;
1886
        } else {
1887
            buf += ret;
1888
            len -= ret;
1889
        }
1890
    }
1891
    return len1 - len;
1892
}
1893

    
1894
void socket_set_nonblock(int fd)
1895
{
1896
    unsigned long opt = 1;
1897
    ioctlsocket(fd, FIONBIO, &opt);
1898
}
1899

    
1900
#else
1901

    
1902
static int unix_write(int fd, const uint8_t *buf, int len1)
1903
{
1904
    int ret, len;
1905

    
1906
    len = len1;
1907
    while (len > 0) {
1908
        ret = write(fd, buf, len);
1909
        if (ret < 0) {
1910
            if (errno != EINTR && errno != EAGAIN)
1911
                return -1;
1912
        } else if (ret == 0) {
1913
            break;
1914
        } else {
1915
            buf += ret;
1916
            len -= ret;
1917
        }
1918
    }
1919
    return len1 - len;
1920
}
1921

    
1922
static inline int send_all(int fd, const uint8_t *buf, int len1)
1923
{
1924
    return unix_write(fd, buf, len1);
1925
}
1926

    
1927
void socket_set_nonblock(int fd)
1928
{
1929
    fcntl(fd, F_SETFL, O_NONBLOCK);
1930
}
1931
#endif /* !_WIN32 */
1932

    
1933
#ifndef _WIN32
1934

    
1935
typedef struct {
1936
    int fd_in, fd_out;
1937
    int max_size;
1938
} FDCharDriver;
1939

    
1940
#define STDIO_MAX_CLIENTS 1
1941
static int stdio_nb_clients = 0;
1942

    
1943
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1944
{
1945
    FDCharDriver *s = chr->opaque;
1946
    return unix_write(s->fd_out, buf, len);
1947
}
1948

    
1949
static int fd_chr_read_poll(void *opaque)
1950
{
1951
    CharDriverState *chr = opaque;
1952
    FDCharDriver *s = chr->opaque;
1953

    
1954
    s->max_size = qemu_chr_can_read(chr);
1955
    return s->max_size;
1956
}
1957

    
1958
static void fd_chr_read(void *opaque)
1959
{
1960
    CharDriverState *chr = opaque;
1961
    FDCharDriver *s = chr->opaque;
1962
    int size, len;
1963
    uint8_t buf[1024];
1964

    
1965
    len = sizeof(buf);
1966
    if (len > s->max_size)
1967
        len = s->max_size;
1968
    if (len == 0)
1969
        return;
1970
    size = read(s->fd_in, buf, len);
1971
    if (size == 0) {
1972
        /* FD has been closed. Remove it from the active list.  */
1973
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1974
        return;
1975
    }
1976
    if (size > 0) {
1977
        qemu_chr_read(chr, buf, size);
1978
    }
1979
}
1980

    
1981
static void fd_chr_update_read_handler(CharDriverState *chr)
1982
{
1983
    FDCharDriver *s = chr->opaque;
1984

    
1985
    if (s->fd_in >= 0) {
1986
        if (nographic && s->fd_in == 0) {
1987
        } else {
1988
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1989
                                 fd_chr_read, NULL, chr);
1990
        }
1991
    }
1992
}
1993

    
1994
/* open a character device to a unix fd */
1995
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1996
{
1997
    CharDriverState *chr;
1998
    FDCharDriver *s;
1999

    
2000
    chr = qemu_mallocz(sizeof(CharDriverState));
2001
    if (!chr)
2002
        return NULL;
2003
    s = qemu_mallocz(sizeof(FDCharDriver));
2004
    if (!s) {
2005
        free(chr);
2006
        return NULL;
2007
    }
2008
    s->fd_in = fd_in;
2009
    s->fd_out = fd_out;
2010
    chr->opaque = s;
2011
    chr->chr_write = fd_chr_write;
2012
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2013

    
2014
    qemu_chr_reset(chr);
2015

    
2016
    return chr;
2017
}
2018

    
2019
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2020
{
2021
    int fd_out;
2022

    
2023
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2024
    if (fd_out < 0)
2025
        return NULL;
2026
    return qemu_chr_open_fd(-1, fd_out);
2027
}
2028

    
2029
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2030
{
2031
    int fd_in, fd_out;
2032
    char filename_in[256], filename_out[256];
2033

    
2034
    snprintf(filename_in, 256, "%s.in", filename);
2035
    snprintf(filename_out, 256, "%s.out", filename);
2036
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2037
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2038
    if (fd_in < 0 || fd_out < 0) {
2039
        if (fd_in >= 0)
2040
            close(fd_in);
2041
        if (fd_out >= 0)
2042
            close(fd_out);
2043
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2044
        if (fd_in < 0)
2045
            return NULL;
2046
    }
2047
    return qemu_chr_open_fd(fd_in, fd_out);
2048
}
2049

    
2050

    
2051
/* for STDIO, we handle the case where several clients use it
2052
   (nographic mode) */
2053

    
2054
#define TERM_FIFO_MAX_SIZE 1
2055

    
2056
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2057
static int term_fifo_size;
2058

    
2059
static int stdio_read_poll(void *opaque)
2060
{
2061
    CharDriverState *chr = opaque;
2062

    
2063
    /* try to flush the queue if needed */
2064
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2065
        qemu_chr_read(chr, term_fifo, 1);
2066
        term_fifo_size = 0;
2067
    }
2068
    /* see if we can absorb more chars */
2069
    if (term_fifo_size == 0)
2070
        return 1;
2071
    else
2072
        return 0;
2073
}
2074

    
2075
static void stdio_read(void *opaque)
2076
{
2077
    int size;
2078
    uint8_t buf[1];
2079
    CharDriverState *chr = opaque;
2080

    
2081
    size = read(0, buf, 1);
2082
    if (size == 0) {
2083
        /* stdin has been closed. Remove it from the active list.  */
2084
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2085
        return;
2086
    }
2087
    if (size > 0) {
2088
        if (qemu_chr_can_read(chr) > 0) {
2089
            qemu_chr_read(chr, buf, 1);
2090
        } else if (term_fifo_size == 0) {
2091
            term_fifo[term_fifo_size++] = buf[0];
2092
        }
2093
    }
2094
}
2095

    
2096
/* init terminal so that we can grab keys */
2097
static struct termios oldtty;
2098
static int old_fd0_flags;
2099

    
2100
static void term_exit(void)
2101
{
2102
    tcsetattr (0, TCSANOW, &oldtty);
2103
    fcntl(0, F_SETFL, old_fd0_flags);
2104
}
2105

    
2106
static void term_init(void)
2107
{
2108
    struct termios tty;
2109

    
2110
    tcgetattr (0, &tty);
2111
    oldtty = tty;
2112
    old_fd0_flags = fcntl(0, F_GETFL);
2113

    
2114
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2115
                          |INLCR|IGNCR|ICRNL|IXON);
2116
    tty.c_oflag |= OPOST;
2117
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2118
    /* if graphical mode, we allow Ctrl-C handling */
2119
    if (nographic)
2120
        tty.c_lflag &= ~ISIG;
2121
    tty.c_cflag &= ~(CSIZE|PARENB);
2122
    tty.c_cflag |= CS8;
2123
    tty.c_cc[VMIN] = 1;
2124
    tty.c_cc[VTIME] = 0;
2125

    
2126
    tcsetattr (0, TCSANOW, &tty);
2127

    
2128
    atexit(term_exit);
2129

    
2130
    fcntl(0, F_SETFL, O_NONBLOCK);
2131
}
2132

    
2133
static CharDriverState *qemu_chr_open_stdio(void)
2134
{
2135
    CharDriverState *chr;
2136

    
2137
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2138
        return NULL;
2139
    chr = qemu_chr_open_fd(0, 1);
2140
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2141
    stdio_nb_clients++;
2142
    term_init();
2143

    
2144
    return chr;
2145
}
2146

    
2147
#if defined(__linux__) || defined(__sun__)
2148
static CharDriverState *qemu_chr_open_pty(void)
2149
{
2150
    struct termios tty;
2151
    char slave_name[1024];
2152
    int master_fd, slave_fd;
2153

    
2154
#if defined(__linux__)
2155
    /* Not satisfying */
2156
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2157
        return NULL;
2158
    }
2159
#endif
2160

    
2161
    /* Disabling local echo and line-buffered output */
2162
    tcgetattr (master_fd, &tty);
2163
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2164
    tty.c_cc[VMIN] = 1;
2165
    tty.c_cc[VTIME] = 0;
2166
    tcsetattr (master_fd, TCSAFLUSH, &tty);
2167

    
2168
    fprintf(stderr, "char device redirected to %s\n", slave_name);
2169
    return qemu_chr_open_fd(master_fd, master_fd);
2170
}
2171

    
2172
static void tty_serial_init(int fd, int speed,
2173
                            int parity, int data_bits, int stop_bits)
2174
{
2175
    struct termios tty;
2176
    speed_t spd;
2177

    
2178
#if 0
2179
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2180
           speed, parity, data_bits, stop_bits);
2181
#endif
2182
    tcgetattr (fd, &tty);
2183

    
2184
    switch(speed) {
2185
    case 50:
2186
        spd = B50;
2187
        break;
2188
    case 75:
2189
        spd = B75;
2190
        break;
2191
    case 300:
2192
        spd = B300;
2193
        break;
2194
    case 600:
2195
        spd = B600;
2196
        break;
2197
    case 1200:
2198
        spd = B1200;
2199
        break;
2200
    case 2400:
2201
        spd = B2400;
2202
        break;
2203
    case 4800:
2204
        spd = B4800;
2205
        break;
2206
    case 9600:
2207
        spd = B9600;
2208
        break;
2209
    case 19200:
2210
        spd = B19200;
2211
        break;
2212
    case 38400:
2213
        spd = B38400;
2214
        break;
2215
    case 57600:
2216
        spd = B57600;
2217
        break;
2218
    default:
2219
    case 115200:
2220
        spd = B115200;
2221
        break;
2222
    }
2223

    
2224
    cfsetispeed(&tty, spd);
2225
    cfsetospeed(&tty, spd);
2226

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

    
2261
    tcsetattr (fd, TCSANOW, &tty);
2262
}
2263

    
2264
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2265
{
2266
    FDCharDriver *s = chr->opaque;
2267

    
2268
    switch(cmd) {
2269
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2270
        {
2271
            QEMUSerialSetParams *ssp = arg;
2272
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2273
                            ssp->data_bits, ssp->stop_bits);
2274
        }
2275
        break;
2276
    case CHR_IOCTL_SERIAL_SET_BREAK:
2277
        {
2278
            int enable = *(int *)arg;
2279
            if (enable)
2280
                tcsendbreak(s->fd_in, 1);
2281
        }
2282
        break;
2283
    default:
2284
        return -ENOTSUP;
2285
    }
2286
    return 0;
2287
}
2288

    
2289
static CharDriverState *qemu_chr_open_tty(const char *filename)
2290
{
2291
    CharDriverState *chr;
2292
    int fd;
2293

    
2294
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2295
    fcntl(fd, F_SETFL, O_NONBLOCK);
2296
    tty_serial_init(fd, 115200, 'N', 8, 1);
2297
    chr = qemu_chr_open_fd(fd, fd);
2298
    if (!chr) {
2299
        close(fd);
2300
        return NULL;
2301
    }
2302
    chr->chr_ioctl = tty_serial_ioctl;
2303
    qemu_chr_reset(chr);
2304
    return chr;
2305
}
2306
#else  /* ! __linux__ && ! __sun__ */
2307
static CharDriverState *qemu_chr_open_pty(void)
2308
{
2309
    return NULL;
2310
}
2311
#endif /* __linux__ || __sun__ */
2312

    
2313
#if defined(__linux__)
2314
typedef struct {
2315
    int fd;
2316
    int mode;
2317
} ParallelCharDriver;
2318

    
2319
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2320
{
2321
    if (s->mode != mode) {
2322
        int m = mode;
2323
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2324
            return 0;
2325
        s->mode = mode;
2326
    }
2327
    return 1;
2328
}
2329

    
2330
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2331
{
2332
    ParallelCharDriver *drv = chr->opaque;
2333
    int fd = drv->fd;
2334
    uint8_t b;
2335

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

    
2407
static void pp_close(CharDriverState *chr)
2408
{
2409
    ParallelCharDriver *drv = chr->opaque;
2410
    int fd = drv->fd;
2411

    
2412
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2413
    ioctl(fd, PPRELEASE);
2414
    close(fd);
2415
    qemu_free(drv);
2416
}
2417

    
2418
static CharDriverState *qemu_chr_open_pp(const char *filename)
2419
{
2420
    CharDriverState *chr;
2421
    ParallelCharDriver *drv;
2422
    int fd;
2423

    
2424
    TFR(fd = open(filename, O_RDWR));
2425
    if (fd < 0)
2426
        return NULL;
2427

    
2428
    if (ioctl(fd, PPCLAIM) < 0) {
2429
        close(fd);
2430
        return NULL;
2431
    }
2432

    
2433
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2434
    if (!drv) {
2435
        close(fd);
2436
        return NULL;
2437
    }
2438
    drv->fd = fd;
2439
    drv->mode = IEEE1284_MODE_COMPAT;
2440

    
2441
    chr = qemu_mallocz(sizeof(CharDriverState));
2442
    if (!chr) {
2443
        qemu_free(drv);
2444
        close(fd);
2445
        return NULL;
2446
    }
2447
    chr->chr_write = null_chr_write;
2448
    chr->chr_ioctl = pp_ioctl;
2449
    chr->chr_close = pp_close;
2450
    chr->opaque = drv;
2451

    
2452
    qemu_chr_reset(chr);
2453

    
2454
    return chr;
2455
}
2456
#endif /* __linux__ */
2457

    
2458
#else /* _WIN32 */
2459

    
2460
typedef struct {
2461
    int max_size;
2462
    HANDLE hcom, hrecv, hsend;
2463
    OVERLAPPED orecv, osend;
2464
    BOOL fpipe;
2465
    DWORD len;
2466
} WinCharState;
2467

    
2468
#define NSENDBUF 2048
2469
#define NRECVBUF 2048
2470
#define MAXCONNECT 1
2471
#define NTIMEOUT 5000
2472

    
2473
static int win_chr_poll(void *opaque);
2474
static int win_chr_pipe_poll(void *opaque);
2475

    
2476
static void win_chr_close(CharDriverState *chr)
2477
{
2478
    WinCharState *s = chr->opaque;
2479

    
2480
    if (s->hsend) {
2481
        CloseHandle(s->hsend);
2482
        s->hsend = NULL;
2483
    }
2484
    if (s->hrecv) {
2485
        CloseHandle(s->hrecv);
2486
        s->hrecv = NULL;
2487
    }
2488
    if (s->hcom) {
2489
        CloseHandle(s->hcom);
2490
        s->hcom = NULL;
2491
    }
2492
    if (s->fpipe)
2493
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2494
    else
2495
        qemu_del_polling_cb(win_chr_poll, chr);
2496
}
2497

    
2498
static int win_chr_init(CharDriverState *chr, const char *filename)
2499
{
2500
    WinCharState *s = chr->opaque;
2501
    COMMCONFIG comcfg;
2502
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2503
    COMSTAT comstat;
2504
    DWORD size;
2505
    DWORD err;
2506

    
2507
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2508
    if (!s->hsend) {
2509
        fprintf(stderr, "Failed CreateEvent\n");
2510
        goto fail;
2511
    }
2512
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2513
    if (!s->hrecv) {
2514
        fprintf(stderr, "Failed CreateEvent\n");
2515
        goto fail;
2516
    }
2517

    
2518
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2519
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2520
    if (s->hcom == INVALID_HANDLE_VALUE) {
2521
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2522
        s->hcom = NULL;
2523
        goto fail;
2524
    }
2525

    
2526
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2527
        fprintf(stderr, "Failed SetupComm\n");
2528
        goto fail;
2529
    }
2530

    
2531
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2532
    size = sizeof(COMMCONFIG);
2533
    GetDefaultCommConfig(filename, &comcfg, &size);
2534
    comcfg.dcb.DCBlength = sizeof(DCB);
2535
    CommConfigDialog(filename, NULL, &comcfg);
2536

    
2537
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2538
        fprintf(stderr, "Failed SetCommState\n");
2539
        goto fail;
2540
    }
2541

    
2542
    if (!SetCommMask(s->hcom, EV_ERR)) {
2543
        fprintf(stderr, "Failed SetCommMask\n");
2544
        goto fail;
2545
    }
2546

    
2547
    cto.ReadIntervalTimeout = MAXDWORD;
2548
    if (!SetCommTimeouts(s->hcom, &cto)) {
2549
        fprintf(stderr, "Failed SetCommTimeouts\n");
2550
        goto fail;
2551
    }
2552

    
2553
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2554
        fprintf(stderr, "Failed ClearCommError\n");
2555
        goto fail;
2556
    }
2557
    qemu_add_polling_cb(win_chr_poll, chr);
2558
    return 0;
2559

    
2560
 fail:
2561
    win_chr_close(chr);
2562
    return -1;
2563
}
2564

    
2565
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2566
{
2567
    WinCharState *s = chr->opaque;
2568
    DWORD len, ret, size, err;
2569

    
2570
    len = len1;
2571
    ZeroMemory(&s->osend, sizeof(s->osend));
2572
    s->osend.hEvent = s->hsend;
2573
    while (len > 0) {
2574
        if (s->hsend)
2575
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2576
        else
2577
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2578
        if (!ret) {
2579
            err = GetLastError();
2580
            if (err == ERROR_IO_PENDING) {
2581
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2582
                if (ret) {
2583
                    buf += size;
2584
                    len -= size;
2585
                } else {
2586
                    break;
2587
                }
2588
            } else {
2589
                break;
2590
            }
2591
        } else {
2592
            buf += size;
2593
            len -= size;
2594
        }
2595
    }
2596
    return len1 - len;
2597
}
2598

    
2599
static int win_chr_read_poll(CharDriverState *chr)
2600
{
2601
    WinCharState *s = chr->opaque;
2602

    
2603
    s->max_size = qemu_chr_can_read(chr);
2604
    return s->max_size;
2605
}
2606

    
2607
static void win_chr_readfile(CharDriverState *chr)
2608
{
2609
    WinCharState *s = chr->opaque;
2610
    int ret, err;
2611
    uint8_t buf[1024];
2612
    DWORD size;
2613

    
2614
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2615
    s->orecv.hEvent = s->hrecv;
2616
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2617
    if (!ret) {
2618
        err = GetLastError();
2619
        if (err == ERROR_IO_PENDING) {
2620
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2621
        }
2622
    }
2623

    
2624
    if (size > 0) {
2625
        qemu_chr_read(chr, buf, size);
2626
    }
2627
}
2628

    
2629
static void win_chr_read(CharDriverState *chr)
2630
{
2631
    WinCharState *s = chr->opaque;
2632

    
2633
    if (s->len > s->max_size)
2634
        s->len = s->max_size;
2635
    if (s->len == 0)
2636
        return;
2637

    
2638
    win_chr_readfile(chr);
2639
}
2640

    
2641
static int win_chr_poll(void *opaque)
2642
{
2643
    CharDriverState *chr = opaque;
2644
    WinCharState *s = chr->opaque;
2645
    COMSTAT status;
2646
    DWORD comerr;
2647

    
2648
    ClearCommError(s->hcom, &comerr, &status);
2649
    if (status.cbInQue > 0) {
2650
        s->len = status.cbInQue;
2651
        win_chr_read_poll(chr);
2652
        win_chr_read(chr);
2653
        return 1;
2654
    }
2655
    return 0;
2656
}
2657

    
2658
static CharDriverState *qemu_chr_open_win(const char *filename)
2659
{
2660
    CharDriverState *chr;
2661
    WinCharState *s;
2662

    
2663
    chr = qemu_mallocz(sizeof(CharDriverState));
2664
    if (!chr)
2665
        return NULL;
2666
    s = qemu_mallocz(sizeof(WinCharState));
2667
    if (!s) {
2668
        free(chr);
2669
        return NULL;
2670
    }
2671
    chr->opaque = s;
2672
    chr->chr_write = win_chr_write;
2673
    chr->chr_close = win_chr_close;
2674

    
2675
    if (win_chr_init(chr, filename) < 0) {
2676
        free(s);
2677
        free(chr);
2678
        return NULL;
2679
    }
2680
    qemu_chr_reset(chr);
2681
    return chr;
2682
}
2683

    
2684
static int win_chr_pipe_poll(void *opaque)
2685
{
2686
    CharDriverState *chr = opaque;
2687
    WinCharState *s = chr->opaque;
2688
    DWORD size;
2689

    
2690
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2691
    if (size > 0) {
2692
        s->len = size;
2693
        win_chr_read_poll(chr);
2694
        win_chr_read(chr);
2695
        return 1;
2696
    }
2697
    return 0;
2698
}
2699

    
2700
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2701
{
2702
    WinCharState *s = chr->opaque;
2703
    OVERLAPPED ov;
2704
    int ret;
2705
    DWORD size;
2706
    char openname[256];
2707

    
2708
    s->fpipe = TRUE;
2709

    
2710
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2711
    if (!s->hsend) {
2712
        fprintf(stderr, "Failed CreateEvent\n");
2713
        goto fail;
2714
    }
2715
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2716
    if (!s->hrecv) {
2717
        fprintf(stderr, "Failed CreateEvent\n");
2718
        goto fail;
2719
    }
2720

    
2721
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2722
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2723
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2724
                              PIPE_WAIT,
2725
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2726
    if (s->hcom == INVALID_HANDLE_VALUE) {
2727
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2728
        s->hcom = NULL;
2729
        goto fail;
2730
    }
2731

    
2732
    ZeroMemory(&ov, sizeof(ov));
2733
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2734
    ret = ConnectNamedPipe(s->hcom, &ov);
2735
    if (ret) {
2736
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2737
        goto fail;
2738
    }
2739

    
2740
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2741
    if (!ret) {
2742
        fprintf(stderr, "Failed GetOverlappedResult\n");
2743
        if (ov.hEvent) {
2744
            CloseHandle(ov.hEvent);
2745
            ov.hEvent = NULL;
2746
        }
2747
        goto fail;
2748
    }
2749

    
2750
    if (ov.hEvent) {
2751
        CloseHandle(ov.hEvent);
2752
        ov.hEvent = NULL;
2753
    }
2754
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2755
    return 0;
2756

    
2757
 fail:
2758
    win_chr_close(chr);
2759
    return -1;
2760
}
2761

    
2762

    
2763
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2764
{
2765
    CharDriverState *chr;
2766
    WinCharState *s;
2767

    
2768
    chr = qemu_mallocz(sizeof(CharDriverState));
2769
    if (!chr)
2770
        return NULL;
2771
    s = qemu_mallocz(sizeof(WinCharState));
2772
    if (!s) {
2773
        free(chr);
2774
        return NULL;
2775
    }
2776
    chr->opaque = s;
2777
    chr->chr_write = win_chr_write;
2778
    chr->chr_close = win_chr_close;
2779

    
2780
    if (win_chr_pipe_init(chr, filename) < 0) {
2781
        free(s);
2782
        free(chr);
2783
        return NULL;
2784
    }
2785
    qemu_chr_reset(chr);
2786
    return chr;
2787
}
2788

    
2789
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2790
{
2791
    CharDriverState *chr;
2792
    WinCharState *s;
2793

    
2794
    chr = qemu_mallocz(sizeof(CharDriverState));
2795
    if (!chr)
2796
        return NULL;
2797
    s = qemu_mallocz(sizeof(WinCharState));
2798
    if (!s) {
2799
        free(chr);
2800
        return NULL;
2801
    }
2802
    s->hcom = fd_out;
2803
    chr->opaque = s;
2804
    chr->chr_write = win_chr_write;
2805
    qemu_chr_reset(chr);
2806
    return chr;
2807
}
2808

    
2809
static CharDriverState *qemu_chr_open_win_con(const char *filename)
2810
{
2811
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2812
}
2813

    
2814
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2815
{
2816
    HANDLE fd_out;
2817

    
2818
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2819
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2820
    if (fd_out == INVALID_HANDLE_VALUE)
2821
        return NULL;
2822

    
2823
    return qemu_chr_open_win_file(fd_out);
2824
}
2825
#endif /* !_WIN32 */
2826

    
2827
/***********************************************************/
2828
/* UDP Net console */
2829

    
2830
typedef struct {
2831
    int fd;
2832
    struct sockaddr_in daddr;
2833
    char buf[1024];
2834
    int bufcnt;
2835
    int bufptr;
2836
    int max_size;
2837
} NetCharDriver;
2838

    
2839
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2840
{
2841
    NetCharDriver *s = chr->opaque;
2842

    
2843
    return sendto(s->fd, buf, len, 0,
2844
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2845
}
2846

    
2847
static int udp_chr_read_poll(void *opaque)
2848
{
2849
    CharDriverState *chr = opaque;
2850
    NetCharDriver *s = chr->opaque;
2851

    
2852
    s->max_size = qemu_chr_can_read(chr);
2853

    
2854
    /* If there were any stray characters in the queue process them
2855
     * first
2856
     */
2857
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2858
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2859
        s->bufptr++;
2860
        s->max_size = qemu_chr_can_read(chr);
2861
    }
2862
    return s->max_size;
2863
}
2864

    
2865
static void udp_chr_read(void *opaque)
2866
{
2867
    CharDriverState *chr = opaque;
2868
    NetCharDriver *s = chr->opaque;
2869

    
2870
    if (s->max_size == 0)
2871
        return;
2872
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2873
    s->bufptr = s->bufcnt;
2874
    if (s->bufcnt <= 0)
2875
        return;
2876

    
2877
    s->bufptr = 0;
2878
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2879
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2880
        s->bufptr++;
2881
        s->max_size = qemu_chr_can_read(chr);
2882
    }
2883
}
2884

    
2885
static void udp_chr_update_read_handler(CharDriverState *chr)
2886
{
2887
    NetCharDriver *s = chr->opaque;
2888

    
2889
    if (s->fd >= 0) {
2890
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2891
                             udp_chr_read, NULL, chr);
2892
    }
2893
}
2894

    
2895
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2896
#ifndef _WIN32
2897
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2898
#endif
2899
int parse_host_src_port(struct sockaddr_in *haddr,
2900
                        struct sockaddr_in *saddr,
2901
                        const char *str);
2902

    
2903
static CharDriverState *qemu_chr_open_udp(const char *def)
2904
{
2905
    CharDriverState *chr = NULL;
2906
    NetCharDriver *s = NULL;
2907
    int fd = -1;
2908
    struct sockaddr_in saddr;
2909

    
2910
    chr = qemu_mallocz(sizeof(CharDriverState));
2911
    if (!chr)
2912
        goto return_err;
2913
    s = qemu_mallocz(sizeof(NetCharDriver));
2914
    if (!s)
2915
        goto return_err;
2916

    
2917
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2918
    if (fd < 0) {
2919
        perror("socket(PF_INET, SOCK_DGRAM)");
2920
        goto return_err;
2921
    }
2922

    
2923
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2924
        printf("Could not parse: %s\n", def);
2925
        goto return_err;
2926
    }
2927

    
2928
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2929
    {
2930
        perror("bind");
2931
        goto return_err;
2932
    }
2933

    
2934
    s->fd = fd;
2935
    s->bufcnt = 0;
2936
    s->bufptr = 0;
2937
    chr->opaque = s;
2938
    chr->chr_write = udp_chr_write;
2939
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2940
    return chr;
2941

    
2942
return_err:
2943
    if (chr)
2944
        free(chr);
2945
    if (s)
2946
        free(s);
2947
    if (fd >= 0)
2948
        closesocket(fd);
2949
    return NULL;
2950
}
2951

    
2952
/***********************************************************/
2953
/* TCP Net console */
2954

    
2955
typedef struct {
2956
    int fd, listen_fd;
2957
    int connected;
2958
    int max_size;
2959
    int do_telnetopt;
2960
    int do_nodelay;
2961
    int is_unix;
2962
} TCPCharDriver;
2963

    
2964
static void tcp_chr_accept(void *opaque);
2965

    
2966
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2967
{
2968
    TCPCharDriver *s = chr->opaque;
2969
    if (s->connected) {
2970
        return send_all(s->fd, buf, len);
2971
    } else {
2972
        /* XXX: indicate an error ? */
2973
        return len;
2974
    }
2975
}
2976

    
2977
static int tcp_chr_read_poll(void *opaque)
2978
{
2979
    CharDriverState *chr = opaque;
2980
    TCPCharDriver *s = chr->opaque;
2981
    if (!s->connected)
2982
        return 0;
2983
    s->max_size = qemu_chr_can_read(chr);
2984
    return s->max_size;
2985
}
2986

    
2987
#define IAC 255
2988
#define IAC_BREAK 243
2989
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2990
                                      TCPCharDriver *s,
2991
                                      char *buf, int *size)
2992
{
2993
    /* Handle any telnet client's basic IAC options to satisfy char by
2994
     * char mode with no echo.  All IAC options will be removed from
2995
     * the buf and the do_telnetopt variable will be used to track the
2996
     * state of the width of the IAC information.
2997
     *
2998
     * IAC commands come in sets of 3 bytes with the exception of the
2999
     * "IAC BREAK" command and the double IAC.
3000
     */
3001

    
3002
    int i;
3003
    int j = 0;
3004

    
3005
    for (i = 0; i < *size; i++) {
3006
        if (s->do_telnetopt > 1) {
3007
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3008
                /* Double IAC means send an IAC */
3009
                if (j != i)
3010
                    buf[j] = buf[i];
3011
                j++;
3012
                s->do_telnetopt = 1;
3013
            } else {
3014
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3015
                    /* Handle IAC break commands by sending a serial break */
3016
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3017
                    s->do_telnetopt++;
3018
                }
3019
                s->do_telnetopt++;
3020
            }
3021
            if (s->do_telnetopt >= 4) {
3022
                s->do_telnetopt = 1;
3023
            }
3024
        } else {
3025
            if ((unsigned char)buf[i] == IAC) {
3026
                s->do_telnetopt = 2;
3027
            } else {
3028
                if (j != i)
3029
                    buf[j] = buf[i];
3030
                j++;
3031
            }
3032
        }
3033
    }
3034
    *size = j;
3035
}
3036

    
3037
static void tcp_chr_read(void *opaque)
3038
{
3039
    CharDriverState *chr = opaque;
3040
    TCPCharDriver *s = chr->opaque;
3041
    uint8_t buf[1024];
3042
    int len, size;
3043

    
3044
    if (!s->connected || s->max_size <= 0)
3045
        return;
3046
    len = sizeof(buf);
3047
    if (len > s->max_size)
3048
        len = s->max_size;
3049
    size = recv(s->fd, buf, len, 0);
3050
    if (size == 0) {
3051
        /* connection closed */
3052
        s->connected = 0;
3053
        if (s->listen_fd >= 0) {
3054
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3055
        }
3056
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3057
        closesocket(s->fd);
3058
        s->fd = -1;
3059
    } else if (size > 0) {
3060
        if (s->do_telnetopt)
3061
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3062
        if (size > 0)
3063
            qemu_chr_read(chr, buf, size);
3064
    }
3065
}
3066

    
3067
static void tcp_chr_connect(void *opaque)
3068
{
3069
    CharDriverState *chr = opaque;
3070
    TCPCharDriver *s = chr->opaque;
3071

    
3072
    s->connected = 1;
3073
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3074
                         tcp_chr_read, NULL, chr);
3075
    qemu_chr_reset(chr);
3076
}
3077

    
3078
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3079
static void tcp_chr_telnet_init(int fd)
3080
{
3081
    char buf[3];
3082
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3083
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3084
    send(fd, (char *)buf, 3, 0);
3085
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3086
    send(fd, (char *)buf, 3, 0);
3087
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3088
    send(fd, (char *)buf, 3, 0);
3089
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3090
    send(fd, (char *)buf, 3, 0);
3091
}
3092

    
3093
static void socket_set_nodelay(int fd)
3094
{
3095
    int val = 1;
3096
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3097
}
3098

    
3099
static void tcp_chr_accept(void *opaque)
3100
{
3101
    CharDriverState *chr = opaque;
3102
    TCPCharDriver *s = chr->opaque;
3103
    struct sockaddr_in saddr;
3104
#ifndef _WIN32
3105
    struct sockaddr_un uaddr;
3106
#endif
3107
    struct sockaddr *addr;
3108
    socklen_t len;
3109
    int fd;
3110

    
3111
    for(;;) {
3112
#ifndef _WIN32
3113
        if (s->is_unix) {
3114
            len = sizeof(uaddr);
3115
            addr = (struct sockaddr *)&uaddr;
3116
        } else
3117
#endif
3118
        {
3119
            len = sizeof(saddr);
3120
            addr = (struct sockaddr *)&saddr;
3121
        }
3122
        fd = accept(s->listen_fd, addr, &len);
3123
        if (fd < 0 && errno != EINTR) {
3124
            return;
3125
        } else if (fd >= 0) {
3126
            if (s->do_telnetopt)
3127
                tcp_chr_telnet_init(fd);
3128
            break;
3129
        }
3130
    }
3131
    socket_set_nonblock(fd);
3132
    if (s->do_nodelay)
3133
        socket_set_nodelay(fd);
3134
    s->fd = fd;
3135
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3136
    tcp_chr_connect(chr);
3137
}
3138

    
3139
static void tcp_chr_close(CharDriverState *chr)
3140
{
3141
    TCPCharDriver *s = chr->opaque;
3142
    if (s->fd >= 0)
3143
        closesocket(s->fd);
3144
    if (s->listen_fd >= 0)
3145
        closesocket(s->listen_fd);
3146
    qemu_free(s);
3147
}
3148

    
3149
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3150
                                          int is_telnet,
3151
                                          int is_unix)
3152
{
3153
    CharDriverState *chr = NULL;
3154
    TCPCharDriver *s = NULL;
3155
    int fd = -1, ret, err, val;
3156
    int is_listen = 0;
3157
    int is_waitconnect = 1;
3158
    int do_nodelay = 0;
3159
    const char *ptr;
3160
    struct sockaddr_in saddr;
3161
#ifndef _WIN32
3162
    struct sockaddr_un uaddr;
3163
#endif
3164
    struct sockaddr *addr;
3165
    socklen_t addrlen;
3166

    
3167
#ifndef _WIN32
3168
    if (is_unix) {
3169
        addr = (struct sockaddr *)&uaddr;
3170
        addrlen = sizeof(uaddr);
3171
        if (parse_unix_path(&uaddr, host_str) < 0)
3172
            goto fail;
3173
    } else
3174
#endif
3175
    {
3176
        addr = (struct sockaddr *)&saddr;
3177
        addrlen = sizeof(saddr);
3178
        if (parse_host_port(&saddr, host_str) < 0)
3179
            goto fail;
3180
    }
3181

    
3182
    ptr = host_str;
3183
    while((ptr = strchr(ptr,','))) {
3184
        ptr++;
3185
        if (!strncmp(ptr,"server",6)) {
3186
            is_listen = 1;
3187
        } else if (!strncmp(ptr,"nowait",6)) {
3188
            is_waitconnect = 0;
3189
        } else if (!strncmp(ptr,"nodelay",6)) {
3190
            do_nodelay = 1;
3191
        } else {
3192
            printf("Unknown option: %s\n", ptr);
3193
            goto fail;
3194
        }
3195
    }
3196
    if (!is_listen)
3197
        is_waitconnect = 0;
3198

    
3199
    chr = qemu_mallocz(sizeof(CharDriverState));
3200
    if (!chr)
3201
        goto fail;
3202
    s = qemu_mallocz(sizeof(TCPCharDriver));
3203
    if (!s)
3204
        goto fail;
3205

    
3206
#ifndef _WIN32
3207
    if (is_unix)
3208
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3209
    else
3210
#endif
3211
        fd = socket(PF_INET, SOCK_STREAM, 0);
3212

    
3213
    if (fd < 0)
3214
        goto fail;
3215

    
3216
    if (!is_waitconnect)
3217
        socket_set_nonblock(fd);
3218

    
3219
    s->connected = 0;
3220
    s->fd = -1;
3221
    s->listen_fd = -1;
3222
    s->is_unix = is_unix;
3223
    s->do_nodelay = do_nodelay && !is_unix;
3224

    
3225
    chr->opaque = s;
3226
    chr->chr_write = tcp_chr_write;
3227
    chr->chr_close = tcp_chr_close;
3228

    
3229
    if (is_listen) {
3230
        /* allow fast reuse */
3231
#ifndef _WIN32
3232
        if (is_unix) {
3233
            char path[109];
3234
            strncpy(path, uaddr.sun_path, 108);
3235
            path[108] = 0;
3236
            unlink(path);
3237
        } else
3238
#endif
3239
        {
3240
            val = 1;
3241
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3242
        }
3243

    
3244
        ret = bind(fd, addr, addrlen);
3245
        if (ret < 0)
3246
            goto fail;
3247

    
3248
        ret = listen(fd, 0);
3249
        if (ret < 0)
3250
            goto fail;
3251

    
3252
        s->listen_fd = fd;
3253
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3254
        if (is_telnet)
3255
            s->do_telnetopt = 1;
3256
    } else {
3257
        for(;;) {
3258
            ret = connect(fd, addr, addrlen);
3259
            if (ret < 0) {
3260
                err = socket_error();
3261
                if (err == EINTR || err == EWOULDBLOCK) {
3262
                } else if (err == EINPROGRESS) {
3263
                    break;
3264
#ifdef _WIN32
3265
                } else if (err == WSAEALREADY) {
3266
                    break;
3267
#endif
3268
                } else {
3269
                    goto fail;
3270
                }
3271
            } else {
3272
                s->connected = 1;
3273
                break;
3274
            }
3275
        }
3276
        s->fd = fd;
3277
        socket_set_nodelay(fd);
3278
        if (s->connected)
3279
            tcp_chr_connect(chr);
3280
        else
3281
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3282
    }
3283

    
3284
    if (is_listen && is_waitconnect) {
3285
        printf("QEMU waiting for connection on: %s\n", host_str);
3286
        tcp_chr_accept(chr);
3287
        socket_set_nonblock(s->listen_fd);
3288
    }
3289

    
3290
    return chr;
3291
 fail:
3292
    if (fd >= 0)
3293
        closesocket(fd);
3294
    qemu_free(s);
3295
    qemu_free(chr);
3296
    return NULL;
3297
}
3298

    
3299
CharDriverState *qemu_chr_open(const char *filename)
3300
{
3301
    const char *p;
3302

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

    
3370
void qemu_chr_close(CharDriverState *chr)
3371
{
3372
    if (chr->chr_close)
3373
        chr->chr_close(chr);
3374
}
3375

    
3376
/***********************************************************/
3377
/* network device redirectors */
3378

    
3379
void hex_dump(FILE *f, const uint8_t *buf, int size)
3380
{
3381
    int len, i, j, c;
3382

    
3383
    for(i=0;i<size;i+=16) {
3384
        len = size - i;
3385
        if (len > 16)
3386
            len = 16;
3387
        fprintf(f, "%08x ", i);
3388
        for(j=0;j<16;j++) {
3389
            if (j < len)
3390
                fprintf(f, " %02x", buf[i+j]);
3391
            else
3392
                fprintf(f, "   ");
3393
        }
3394
        fprintf(f, " ");
3395
        for(j=0;j<len;j++) {
3396
            c = buf[i+j];
3397
            if (c < ' ' || c > '~')
3398
                c = '.';
3399
            fprintf(f, "%c", c);
3400
        }
3401
        fprintf(f, "\n");
3402
    }
3403
}
3404

    
3405
static int parse_macaddr(uint8_t *macaddr, const char *p)
3406
{
3407
    int i;
3408
    for(i = 0; i < 6; i++) {
3409
        macaddr[i] = strtol(p, (char **)&p, 16);
3410
        if (i == 5) {
3411
            if (*p != '\0')
3412
                return -1;
3413
        } else {
3414
            if (*p != ':')
3415
                return -1;
3416
            p++;
3417
        }
3418
    }
3419
    return 0;
3420
}
3421

    
3422
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3423
{
3424
    const char *p, *p1;
3425
    int len;
3426
    p = *pp;
3427
    p1 = strchr(p, sep);
3428
    if (!p1)
3429
        return -1;
3430
    len = p1 - p;
3431
    p1++;
3432
    if (buf_size > 0) {
3433
        if (len > buf_size - 1)
3434
            len = buf_size - 1;
3435
        memcpy(buf, p, len);
3436
        buf[len] = '\0';
3437
    }
3438
    *pp = p1;
3439
    return 0;
3440
}
3441

    
3442
int parse_host_src_port(struct sockaddr_in *haddr,
3443
                        struct sockaddr_in *saddr,
3444
                        const char *input_str)
3445
{
3446
    char *str = strdup(input_str);
3447
    char *host_str = str;
3448
    char *src_str;
3449
    char *ptr;
3450

    
3451
    /*
3452
     * Chop off any extra arguments at the end of the string which
3453
     * would start with a comma, then fill in the src port information
3454
     * if it was provided else use the "any address" and "any port".
3455
     */
3456
    if ((ptr = strchr(str,',')))
3457
        *ptr = '\0';
3458

    
3459
    if ((src_str = strchr(input_str,'@'))) {
3460
        *src_str = '\0';
3461
        src_str++;
3462
    }
3463

    
3464
    if (parse_host_port(haddr, host_str) < 0)
3465
        goto fail;
3466

    
3467
    if (!src_str || *src_str == '\0')
3468
        src_str = ":0";
3469

    
3470
    if (parse_host_port(saddr, src_str) < 0)
3471
        goto fail;
3472

    
3473
    free(str);
3474
    return(0);
3475

    
3476
fail:
3477
    free(str);
3478
    return -1;
3479
}
3480

    
3481
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3482
{
3483
    char buf[512];
3484
    struct hostent *he;
3485
    const char *p, *r;
3486
    int port;
3487

    
3488
    p = str;
3489
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3490
        return -1;
3491
    saddr->sin_family = AF_INET;
3492
    if (buf[0] == '\0') {
3493
        saddr->sin_addr.s_addr = 0;
3494
    } else {
3495
        if (isdigit(buf[0])) {
3496
            if (!inet_aton(buf, &saddr->sin_addr))
3497
                return -1;
3498
        } else {
3499
            if ((he = gethostbyname(buf)) == NULL)
3500
                return - 1;
3501
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3502
        }
3503
    }
3504
    port = strtol(p, (char **)&r, 0);
3505
    if (r == p)
3506
        return -1;
3507
    saddr->sin_port = htons(port);
3508
    return 0;
3509
}
3510

    
3511
#ifndef _WIN32
3512
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3513
{
3514
    const char *p;
3515
    int len;
3516

    
3517
    len = MIN(108, strlen(str));
3518
    p = strchr(str, ',');
3519
    if (p)
3520
        len = MIN(len, p - str);
3521

    
3522
    memset(uaddr, 0, sizeof(*uaddr));
3523

    
3524
    uaddr->sun_family = AF_UNIX;
3525
    memcpy(uaddr->sun_path, str, len);
3526

    
3527
    return 0;
3528
}
3529
#endif
3530

    
3531
/* find or alloc a new VLAN */
3532
VLANState *qemu_find_vlan(int id)
3533
{
3534
    VLANState **pvlan, *vlan;
3535
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3536
        if (vlan->id == id)
3537
            return vlan;
3538
    }
3539
    vlan = qemu_mallocz(sizeof(VLANState));
3540
    if (!vlan)
3541
        return NULL;
3542
    vlan->id = id;
3543
    vlan->next = NULL;
3544
    pvlan = &first_vlan;
3545
    while (*pvlan != NULL)
3546
        pvlan = &(*pvlan)->next;
3547
    *pvlan = vlan;
3548
    return vlan;
3549
}
3550

    
3551
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3552
                                      IOReadHandler *fd_read,
3553
                                      IOCanRWHandler *fd_can_read,
3554
                                      void *opaque)
3555
{
3556
    VLANClientState *vc, **pvc;
3557
    vc = qemu_mallocz(sizeof(VLANClientState));
3558
    if (!vc)
3559
        return NULL;
3560
    vc->fd_read = fd_read;
3561
    vc->fd_can_read = fd_can_read;
3562
    vc->opaque = opaque;
3563
    vc->vlan = vlan;
3564

    
3565
    vc->next = NULL;
3566
    pvc = &vlan->first_client;
3567
    while (*pvc != NULL)
3568
        pvc = &(*pvc)->next;
3569
    *pvc = vc;
3570
    return vc;
3571
}
3572

    
3573
int qemu_can_send_packet(VLANClientState *vc1)
3574
{
3575
    VLANState *vlan = vc1->vlan;
3576
    VLANClientState *vc;
3577

    
3578
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3579
        if (vc != vc1) {
3580
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3581
                return 1;
3582
        }
3583
    }
3584
    return 0;
3585
}
3586

    
3587
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3588
{
3589
    VLANState *vlan = vc1->vlan;
3590
    VLANClientState *vc;
3591

    
3592
#if 0
3593
    printf("vlan %d send:\n", vlan->id);
3594
    hex_dump(stdout, buf, size);
3595
#endif
3596
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3597
        if (vc != vc1) {
3598
            vc->fd_read(vc->opaque, buf, size);
3599
        }
3600
    }
3601
}
3602

    
3603
#if defined(CONFIG_SLIRP)
3604

    
3605
/* slirp network adapter */
3606

    
3607
static int slirp_inited;
3608
static VLANClientState *slirp_vc;
3609

    
3610
int slirp_can_output(void)
3611
{
3612
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3613
}
3614

    
3615
void slirp_output(const uint8_t *pkt, int pkt_len)
3616
{
3617
#if 0
3618
    printf("slirp output:\n");
3619
    hex_dump(stdout, pkt, pkt_len);
3620
#endif
3621
    if (!slirp_vc)
3622
        return;
3623
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3624
}
3625

    
3626
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3627
{
3628
#if 0
3629
    printf("slirp input:\n");
3630
    hex_dump(stdout, buf, size);
3631
#endif
3632
    slirp_input(buf, size);
3633
}
3634

    
3635
static int net_slirp_init(VLANState *vlan)
3636
{
3637
    if (!slirp_inited) {
3638
        slirp_inited = 1;
3639
        slirp_init();
3640
    }
3641
    slirp_vc = qemu_new_vlan_client(vlan,
3642
                                    slirp_receive, NULL, NULL);
3643
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3644
    return 0;
3645
}
3646

    
3647
static void net_slirp_redir(const char *redir_str)
3648
{
3649
    int is_udp;
3650
    char buf[256], *r;
3651
    const char *p;
3652
    struct in_addr guest_addr;
3653
    int host_port, guest_port;
3654

    
3655
    if (!slirp_inited) {
3656
        slirp_inited = 1;
3657
        slirp_init();
3658
    }
3659

    
3660
    p = redir_str;
3661
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3662
        goto fail;
3663
    if (!strcmp(buf, "tcp")) {
3664
        is_udp = 0;
3665
    } else if (!strcmp(buf, "udp")) {
3666
        is_udp = 1;
3667
    } else {
3668
        goto fail;
3669
    }
3670

    
3671
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3672
        goto fail;
3673
    host_port = strtol(buf, &r, 0);
3674
    if (r == buf)
3675
        goto fail;
3676

    
3677
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3678
        goto fail;
3679
    if (buf[0] == '\0') {
3680
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3681
    }
3682
    if (!inet_aton(buf, &guest_addr))
3683
        goto fail;
3684

    
3685
    guest_port = strtol(p, &r, 0);
3686
    if (r == p)
3687
        goto fail;
3688

    
3689
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3690
        fprintf(stderr, "qemu: could not set up redirection\n");
3691
        exit(1);
3692
    }
3693
    return;
3694
 fail:
3695
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3696
    exit(1);
3697
}
3698

    
3699
#ifndef _WIN32
3700

    
3701
char smb_dir[1024];
3702

    
3703
static void smb_exit(void)
3704
{
3705
    DIR *d;
3706
    struct dirent *de;
3707
    char filename[1024];
3708

    
3709
    /* erase all the files in the directory */
3710
    d = opendir(smb_dir);
3711
    for(;;) {
3712
        de = readdir(d);
3713
        if (!de)
3714
            break;
3715
        if (strcmp(de->d_name, ".") != 0 &&
3716
            strcmp(de->d_name, "..") != 0) {
3717
            snprintf(filename, sizeof(filename), "%s/%s",
3718
                     smb_dir, de->d_name);
3719
            unlink(filename);
3720
        }
3721
    }
3722
    closedir(d);
3723
    rmdir(smb_dir);
3724
}
3725

    
3726
/* automatic user mode samba server configuration */
3727
void net_slirp_smb(const char *exported_dir)
3728
{
3729
    char smb_conf[1024];
3730
    char smb_cmdline[1024];
3731
    FILE *f;
3732

    
3733
    if (!slirp_inited) {
3734
        slirp_inited = 1;
3735
        slirp_init();
3736
    }
3737

    
3738
    /* XXX: better tmp dir construction */
3739
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3740
    if (mkdir(smb_dir, 0700) < 0) {
3741
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3742
        exit(1);
3743
    }
3744
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3745

    
3746
    f = fopen(smb_conf, "w");
3747
    if (!f) {
3748
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3749
        exit(1);
3750
    }
3751
    fprintf(f,
3752
            "[global]\n"
3753
            "private dir=%s\n"
3754
            "smb ports=0\n"
3755
            "socket address=127.0.0.1\n"
3756
            "pid directory=%s\n"
3757
            "lock directory=%s\n"
3758
            "log file=%s/log.smbd\n"
3759
            "smb passwd file=%s/smbpasswd\n"
3760
            "security = share\n"
3761
            "[qemu]\n"
3762
            "path=%s\n"
3763
            "read only=no\n"
3764
            "guest ok=yes\n",
3765
            smb_dir,
3766
            smb_dir,
3767
            smb_dir,
3768
            smb_dir,
3769
            smb_dir,
3770
            exported_dir
3771
            );
3772
    fclose(f);
3773
    atexit(smb_exit);
3774

    
3775
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3776
             SMBD_COMMAND, smb_conf);
3777

    
3778
    slirp_add_exec(0, smb_cmdline, 4, 139);
3779
}
3780

    
3781
#endif /* !defined(_WIN32) */
3782
void do_info_slirp(void)
3783
{
3784
    slirp_stats();
3785
}
3786

    
3787
#endif /* CONFIG_SLIRP */
3788

    
3789
#if !defined(_WIN32)
3790

    
3791
typedef struct TAPState {
3792
    VLANClientState *vc;
3793
    int fd;
3794
    char down_script[1024];
3795
} TAPState;
3796

    
3797
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3798
{
3799
    TAPState *s = opaque;
3800
    int ret;
3801
    for(;;) {
3802
        ret = write(s->fd, buf, size);
3803
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3804
        } else {
3805
            break;
3806
        }
3807
    }
3808
}
3809

    
3810
static void tap_send(void *opaque)
3811
{
3812
    TAPState *s = opaque;
3813
    uint8_t buf[4096];
3814
    int size;
3815

    
3816
#ifdef __sun__
3817
    struct strbuf sbuf;
3818
    int f = 0;
3819
    sbuf.maxlen = sizeof(buf);
3820
    sbuf.buf = buf;
3821
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3822
#else
3823
    size = read(s->fd, buf, sizeof(buf));
3824
#endif
3825
    if (size > 0) {
3826
        qemu_send_packet(s->vc, buf, size);
3827
    }
3828
}
3829

    
3830
/* fd support */
3831

    
3832
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3833
{
3834
    TAPState *s;
3835

    
3836
    s = qemu_mallocz(sizeof(TAPState));
3837
    if (!s)
3838
        return NULL;
3839
    s->fd = fd;
3840
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3841
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3842
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3843
    return s;
3844
}
3845

    
3846
#if defined (_BSD) || defined (__FreeBSD_kernel__)
3847
static int tap_open(char *ifname, int ifname_size)
3848
{
3849
    int fd;
3850
    char *dev;
3851
    struct stat s;
3852

    
3853
    TFR(fd = open("/dev/tap", O_RDWR));
3854
    if (fd < 0) {
3855
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3856
        return -1;
3857
    }
3858

    
3859
    fstat(fd, &s);
3860
    dev = devname(s.st_rdev, S_IFCHR);
3861
    pstrcpy(ifname, ifname_size, dev);
3862

    
3863
    fcntl(fd, F_SETFL, O_NONBLOCK);
3864
    return fd;
3865
}
3866
#elif defined(__sun__)
3867
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3868
/*
3869
 * Allocate TAP device, returns opened fd.
3870
 * Stores dev name in the first arg(must be large enough).
3871
 */
3872
int tap_alloc(char *dev)
3873
{
3874
    int tap_fd, if_fd, ppa = -1;
3875
    static int ip_fd = 0;
3876
    char *ptr;
3877

    
3878
    static int arp_fd = 0;
3879
    int ip_muxid, arp_muxid;
3880
    struct strioctl  strioc_if, strioc_ppa;
3881
    int link_type = I_PLINK;;
3882
    struct lifreq ifr;
3883
    char actual_name[32] = "";
3884

    
3885
    memset(&ifr, 0x0, sizeof(ifr));
3886

    
3887
    if( *dev ){
3888
       ptr = dev;
3889
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
3890
       ppa = atoi(ptr);
3891
    }
3892

    
3893
    /* Check if IP device was opened */
3894
    if( ip_fd )
3895
       close(ip_fd);
3896

    
3897
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3898
    if (ip_fd < 0) {
3899
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3900
       return -1;
3901
    }
3902

    
3903
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3904
    if (tap_fd < 0) {
3905
       syslog(LOG_ERR, "Can't open /dev/tap");
3906
       return -1;
3907
    }
3908

    
3909
    /* Assign a new PPA and get its unit number. */
3910
    strioc_ppa.ic_cmd = TUNNEWPPA;
3911
    strioc_ppa.ic_timout = 0;
3912
    strioc_ppa.ic_len = sizeof(ppa);
3913
    strioc_ppa.ic_dp = (char *)&ppa;
3914
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3915
       syslog (LOG_ERR, "Can't assign new interface");
3916

    
3917
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3918
    if (if_fd < 0) {
3919
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3920
       return -1;
3921
    }
3922
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3923
       syslog(LOG_ERR, "Can't push IP module");
3924
       return -1;
3925
    }
3926

    
3927
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3928
        syslog(LOG_ERR, "Can't get flags\n");
3929

    
3930
    snprintf (actual_name, 32, "tap%d", ppa);
3931
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3932

    
3933
    ifr.lifr_ppa = ppa;
3934
    /* Assign ppa according to the unit number returned by tun device */
3935

    
3936
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3937
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
3938
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3939
        syslog (LOG_ERR, "Can't get flags\n");
3940
    /* Push arp module to if_fd */
3941
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
3942
        syslog (LOG_ERR, "Can't push ARP module (2)");
3943

    
3944
    /* Push arp module to ip_fd */
3945
    if (ioctl (ip_fd, I_POP, NULL) < 0)
3946
        syslog (LOG_ERR, "I_POP failed\n");
3947
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3948
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
3949
    /* Open arp_fd */
3950
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3951
    if (arp_fd < 0)
3952
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3953

    
3954
    /* Set ifname to arp */
3955
    strioc_if.ic_cmd = SIOCSLIFNAME;
3956
    strioc_if.ic_timout = 0;
3957
    strioc_if.ic_len = sizeof(ifr);
3958
    strioc_if.ic_dp = (char *)&ifr;
3959
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3960
        syslog (LOG_ERR, "Can't set ifname to arp\n");
3961
    }
3962

    
3963
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3964
       syslog(LOG_ERR, "Can't link TAP device to IP");
3965
       return -1;
3966
    }
3967

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

    
3971
    close (if_fd);
3972

    
3973
    memset(&ifr, 0x0, sizeof(ifr));
3974
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3975
    ifr.lifr_ip_muxid  = ip_muxid;
3976
    ifr.lifr_arp_muxid = arp_muxid;
3977

    
3978
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3979
    {
3980
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
3981
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
3982
      syslog (LOG_ERR, "Can't set multiplexor id");
3983
    }
3984

    
3985
    sprintf(dev, "tap%d", ppa);
3986
    return tap_fd;
3987
}
3988

    
3989
static int tap_open(char *ifname, int ifname_size)
3990
{
3991
    char  dev[10]="";
3992
    int fd;
3993
    if( (fd = tap_alloc(dev)) < 0 ){
3994
       fprintf(stderr, "Cannot allocate TAP device\n");
3995
       return -1;
3996
    }
3997
    pstrcpy(ifname, ifname_size, dev);
3998
    fcntl(fd, F_SETFL, O_NONBLOCK);
3999
    return fd;
4000
}
4001
#else
4002
static int tap_open(char *ifname, int ifname_size)
4003
{
4004
    struct ifreq ifr;
4005
    int fd, ret;
4006

    
4007
    TFR(fd = open("/dev/net/tun", O_RDWR));
4008
    if (fd < 0) {
4009
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4010
        return -1;
4011
    }
4012
    memset(&ifr, 0, sizeof(ifr));
4013
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4014
    if (ifname[0] != '\0')
4015
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4016
    else
4017
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4018
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4019
    if (ret != 0) {
4020
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4021
        close(fd);
4022
        return -1;
4023
    }
4024
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4025
    fcntl(fd, F_SETFL, O_NONBLOCK);
4026
    return fd;
4027
}
4028
#endif
4029

    
4030
static int launch_script(const char *setup_script, const char *ifname, int fd)
4031
{
4032
    int pid, status;
4033
    char *args[3];
4034
    char **parg;
4035

    
4036
        /* try to launch network script */
4037
        pid = fork();
4038
        if (pid >= 0) {
4039
            if (pid == 0) {
4040
                int open_max = sysconf (_SC_OPEN_MAX), i;
4041
                for (i = 0; i < open_max; i++)
4042
                    if (i != STDIN_FILENO &&
4043
                        i != STDOUT_FILENO &&
4044
                        i != STDERR_FILENO &&
4045
                        i != fd)
4046
                        close(i);
4047

    
4048
                parg = args;
4049
                *parg++ = (char *)setup_script;
4050
                *parg++ = (char *)ifname;
4051
                *parg++ = NULL;
4052
                execv(setup_script, args);
4053
                _exit(1);
4054
            }
4055
            while (waitpid(pid, &status, 0) != pid);
4056
            if (!WIFEXITED(status) ||
4057
                WEXITSTATUS(status) != 0) {
4058
                fprintf(stderr, "%s: could not launch network script\n",
4059
                        setup_script);
4060
                return -1;
4061
            }
4062
        }
4063
    return 0;
4064
}
4065

    
4066
static int net_tap_init(VLANState *vlan, const char *ifname1,
4067
                        const char *setup_script, const char *down_script)
4068
{
4069
    TAPState *s;
4070
    int fd;
4071
    char ifname[128];
4072

    
4073
    if (ifname1 != NULL)
4074
        pstrcpy(ifname, sizeof(ifname), ifname1);
4075
    else
4076
        ifname[0] = '\0';
4077
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4078
    if (fd < 0)
4079
        return -1;
4080

    
4081
    if (!setup_script || !strcmp(setup_script, "no"))
4082
        setup_script = "";
4083
    if (setup_script[0] != '\0') {
4084
        if (launch_script(setup_script, ifname, fd))
4085
            return -1;
4086
    }
4087
    s = net_tap_fd_init(vlan, fd);
4088
    if (!s)
4089
        return -1;
4090
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4091
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4092
    if (down_script && strcmp(down_script, "no"))
4093
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4094
    return 0;
4095
}
4096

    
4097
#endif /* !_WIN32 */
4098

    
4099
/* network connection */
4100
typedef struct NetSocketState {
4101
    VLANClientState *vc;
4102
    int fd;
4103
    int state; /* 0 = getting length, 1 = getting data */
4104
    int index;
4105
    int packet_len;
4106
    uint8_t buf[4096];
4107
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4108
} NetSocketState;
4109

    
4110
typedef struct NetSocketListenState {
4111
    VLANState *vlan;
4112
    int fd;
4113
} NetSocketListenState;
4114

    
4115
/* XXX: we consider we can send the whole packet without blocking */
4116
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4117
{
4118
    NetSocketState *s = opaque;
4119
    uint32_t len;
4120
    len = htonl(size);
4121

    
4122
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4123
    send_all(s->fd, buf, size);
4124
}
4125

    
4126
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4127
{
4128
    NetSocketState *s = opaque;
4129
    sendto(s->fd, buf, size, 0,
4130
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4131
}
4132

    
4133
static void net_socket_send(void *opaque)
4134
{
4135
    NetSocketState *s = opaque;
4136
    int l, size, err;
4137
    uint8_t buf1[4096];
4138
    const uint8_t *buf;
4139

    
4140
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4141
    if (size < 0) {
4142
        err = socket_error();
4143
        if (err != EWOULDBLOCK)
4144
            goto eoc;
4145
    } else if (size == 0) {
4146
        /* end of connection */
4147
    eoc:
4148
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4149
        closesocket(s->fd);
4150
        return;
4151
    }
4152
    buf = buf1;
4153
    while (size > 0) {
4154
        /* reassemble a packet from the network */
4155
        switch(s->state) {
4156
        case 0:
4157
            l = 4 - s->index;
4158
            if (l > size)
4159
                l = size;
4160
            memcpy(s->buf + s->index, buf, l);
4161
            buf += l;
4162
            size -= l;
4163
            s->index += l;
4164
            if (s->index == 4) {
4165
                /* got length */
4166
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4167
                s->index = 0;
4168
                s->state = 1;
4169
            }
4170
            break;
4171
        case 1:
4172
            l = s->packet_len - s->index;
4173
            if (l > size)
4174
                l = size;
4175
            memcpy(s->buf + s->index, buf, l);
4176
            s->index += l;
4177
            buf += l;
4178
            size -= l;
4179
            if (s->index >= s->packet_len) {
4180
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4181
                s->index = 0;
4182
                s->state = 0;
4183
            }
4184
            break;
4185
        }
4186
    }
4187
}
4188

    
4189
static void net_socket_send_dgram(void *opaque)
4190
{
4191
    NetSocketState *s = opaque;
4192
    int size;
4193

    
4194
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4195
    if (size < 0)
4196
        return;
4197
    if (size == 0) {
4198
        /* end of connection */
4199
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4200
        return;
4201
    }
4202
    qemu_send_packet(s->vc, s->buf, size);
4203
}
4204

    
4205
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4206
{
4207
    struct ip_mreq imr;
4208
    int fd;
4209
    int val, ret;
4210
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4211
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4212
                inet_ntoa(mcastaddr->sin_addr),
4213
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4214
        return -1;
4215

    
4216
    }
4217
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4218
    if (fd < 0) {
4219
        perror("socket(PF_INET, SOCK_DGRAM)");
4220
        return -1;
4221
    }
4222

    
4223
    val = 1;
4224
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4225
                   (const char *)&val, sizeof(val));
4226
    if (ret < 0) {
4227
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4228
        goto fail;
4229
    }
4230

    
4231
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4232
    if (ret < 0) {
4233
        perror("bind");
4234
        goto fail;
4235
    }
4236

    
4237
    /* Add host to multicast group */
4238
    imr.imr_multiaddr = mcastaddr->sin_addr;
4239
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4240

    
4241
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4242
                     (const char *)&imr, sizeof(struct ip_mreq));
4243
    if (ret < 0) {
4244
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4245
        goto fail;
4246
    }
4247

    
4248
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4249
    val = 1;
4250
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4251
                   (const char *)&val, sizeof(val));
4252
    if (ret < 0) {
4253
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4254
        goto fail;
4255
    }
4256

    
4257
    socket_set_nonblock(fd);
4258
    return fd;
4259
fail:
4260
    if (fd >= 0)
4261
        closesocket(fd);
4262
    return -1;
4263
}
4264

    
4265
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4266
                                          int is_connected)
4267
{
4268
    struct sockaddr_in saddr;
4269
    int newfd;
4270
    socklen_t saddr_len;
4271
    NetSocketState *s;
4272

    
4273
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4274
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4275
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4276
     */
4277

    
4278
    if (is_connected) {
4279
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4280
            /* must be bound */
4281
            if (saddr.sin_addr.s_addr==0) {
4282
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4283
                        fd);
4284
                return NULL;
4285
            }
4286
            /* clone dgram socket */
4287
            newfd = net_socket_mcast_create(&saddr);
4288
            if (newfd < 0) {
4289
                /* error already reported by net_socket_mcast_create() */
4290
                close(fd);
4291
                return NULL;
4292
            }
4293
            /* clone newfd to fd, close newfd */
4294
            dup2(newfd, fd);
4295
            close(newfd);
4296

    
4297
        } else {
4298
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4299
                    fd, strerror(errno));
4300
            return NULL;
4301
        }
4302
    }
4303

    
4304
    s = qemu_mallocz(sizeof(NetSocketState));
4305
    if (!s)
4306
        return NULL;
4307
    s->fd = fd;
4308

    
4309
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4310
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4311

    
4312
    /* mcast: save bound address as dst */
4313
    if (is_connected) s->dgram_dst=saddr;
4314

    
4315
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4316
            "socket: fd=%d (%s mcast=%s:%d)",
4317
            fd, is_connected? "cloned" : "",
4318
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4319
    return s;
4320
}
4321

    
4322
static void net_socket_connect(void *opaque)
4323
{
4324
    NetSocketState *s = opaque;
4325
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4326
}
4327

    
4328
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4329
                                          int is_connected)
4330
{
4331
    NetSocketState *s;
4332
    s = qemu_mallocz(sizeof(NetSocketState));
4333
    if (!s)
4334
        return NULL;
4335
    s->fd = fd;
4336
    s->vc = qemu_new_vlan_client(vlan,
4337
                                 net_socket_receive, NULL, s);
4338
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4339
             "socket: fd=%d", fd);
4340
    if (is_connected) {
4341
        net_socket_connect(s);
4342
    } else {
4343
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4344
    }
4345
    return s;
4346
}
4347

    
4348
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4349
                                          int is_connected)
4350
{
4351
    int so_type=-1, optlen=sizeof(so_type);
4352

    
4353
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4354
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4355
        return NULL;
4356
    }
4357
    switch(so_type) {
4358
    case SOCK_DGRAM:
4359
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4360
    case SOCK_STREAM:
4361
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4362
    default:
4363
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4364
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4365
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4366
    }
4367
    return NULL;
4368
}
4369

    
4370
static void net_socket_accept(void *opaque)
4371
{
4372
    NetSocketListenState *s = opaque;
4373
    NetSocketState *s1;
4374
    struct sockaddr_in saddr;
4375
    socklen_t len;
4376
    int fd;
4377

    
4378
    for(;;) {
4379
        len = sizeof(saddr);
4380
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4381
        if (fd < 0 && errno != EINTR) {
4382
            return;
4383
        } else if (fd >= 0) {
4384
            break;
4385
        }
4386
    }
4387
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4388
    if (!s1) {
4389
        closesocket(fd);
4390
    } else {
4391
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4392
                 "socket: connection from %s:%d",
4393
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4394
    }
4395
}
4396

    
4397
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4398
{
4399
    NetSocketListenState *s;
4400
    int fd, val, ret;
4401
    struct sockaddr_in saddr;
4402

    
4403
    if (parse_host_port(&saddr, host_str) < 0)
4404
        return -1;
4405

    
4406
    s = qemu_mallocz(sizeof(NetSocketListenState));
4407
    if (!s)
4408
        return -1;
4409

    
4410
    fd = socket(PF_INET, SOCK_STREAM, 0);
4411
    if (fd < 0) {
4412
        perror("socket");
4413
        return -1;
4414
    }
4415
    socket_set_nonblock(fd);
4416

    
4417
    /* allow fast reuse */
4418
    val = 1;
4419
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4420

    
4421
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4422
    if (ret < 0) {
4423
        perror("bind");
4424
        return -1;
4425
    }
4426
    ret = listen(fd, 0);
4427
    if (ret < 0) {
4428
        perror("listen");
4429
        return -1;
4430
    }
4431
    s->vlan = vlan;
4432
    s->fd = fd;
4433
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4434
    return 0;
4435
}
4436

    
4437
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4438
{
4439
    NetSocketState *s;
4440
    int fd, connected, ret, err;
4441
    struct sockaddr_in saddr;
4442

    
4443
    if (parse_host_port(&saddr, host_str) < 0)
4444
        return -1;
4445

    
4446
    fd = socket(PF_INET, SOCK_STREAM, 0);
4447
    if (fd < 0) {
4448
        perror("socket");
4449
        return -1;
4450
    }
4451
    socket_set_nonblock(fd);
4452

    
4453
    connected = 0;
4454
    for(;;) {
4455
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4456
        if (ret < 0) {
4457
            err = socket_error();
4458
            if (err == EINTR || err == EWOULDBLOCK) {
4459
            } else if (err == EINPROGRESS) {
4460
                break;
4461
#ifdef _WIN32
4462
            } else if (err == WSAEALREADY) {
4463
                break;
4464
#endif
4465
            } else {
4466
                perror("connect");
4467
                closesocket(fd);
4468
                return -1;
4469
            }
4470
        } else {
4471
            connected = 1;
4472
            break;
4473
        }
4474
    }
4475
    s = net_socket_fd_init(vlan, fd, connected);
4476
    if (!s)
4477
        return -1;
4478
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4479
             "socket: connect to %s:%d",
4480
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4481
    return 0;
4482
}
4483

    
4484
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4485
{
4486
    NetSocketState *s;
4487
    int fd;
4488
    struct sockaddr_in saddr;
4489

    
4490
    if (parse_host_port(&saddr, host_str) < 0)
4491
        return -1;
4492

    
4493

    
4494
    fd = net_socket_mcast_create(&saddr);
4495
    if (fd < 0)
4496
        return -1;
4497

    
4498
    s = net_socket_fd_init(vlan, fd, 0);
4499
    if (!s)
4500
        return -1;
4501

    
4502
    s->dgram_dst = saddr;
4503

    
4504
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4505
             "socket: mcast=%s:%d",
4506
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4507
    return 0;
4508

    
4509
}
4510

    
4511
static int get_param_value(char *buf, int buf_size,
4512
                           const char *tag, const char *str)
4513
{
4514
    const char *p;
4515
    char *q;
4516
    char option[128];
4517

    
4518
    p = str;
4519
    for(;;) {
4520
        q = option;
4521
        while (*p != '\0' && *p != '=') {
4522
            if ((q - option) < sizeof(option) - 1)
4523
                *q++ = *p;
4524
            p++;
4525
        }
4526
        *q = '\0';
4527
        if (*p != '=')
4528
            break;
4529
        p++;
4530
        if (!strcmp(tag, option)) {
4531
            q = buf;
4532
            while (*p != '\0' && *p != ',') {
4533
                if ((q - buf) < buf_size - 1)
4534
                    *q++ = *p;
4535
                p++;
4536
            }
4537
            *q = '\0';
4538
            return q - buf;
4539
        } else {
4540
            while (*p != '\0' && *p != ',') {
4541
                p++;
4542
            }
4543
        }
4544
        if (*p != ',')
4545
            break;
4546
        p++;
4547
    }
4548
    return 0;
4549
}
4550

    
4551
static int net_client_init(const char *str)
4552
{
4553
    const char *p;
4554
    char *q;
4555
    char device[64];
4556
    char buf[1024];
4557
    int vlan_id, ret;
4558
    VLANState *vlan;
4559

    
4560
    p = str;
4561
    q = device;
4562
    while (*p != '\0' && *p != ',') {
4563
        if ((q - device) < sizeof(device) - 1)
4564
            *q++ = *p;
4565
        p++;
4566
    }
4567
    *q = '\0';
4568
    if (*p == ',')
4569
        p++;
4570
    vlan_id = 0;
4571
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4572
        vlan_id = strtol(buf, NULL, 0);
4573
    }
4574
    vlan = qemu_find_vlan(vlan_id);
4575
    if (!vlan) {
4576
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4577
        return -1;
4578
    }
4579
    if (!strcmp(device, "nic")) {
4580
        NICInfo *nd;
4581
        uint8_t *macaddr;
4582

    
4583
        if (nb_nics >= MAX_NICS) {
4584
            fprintf(stderr, "Too Many NICs\n");
4585
            return -1;
4586
        }
4587
        nd = &nd_table[nb_nics];
4588
        macaddr = nd->macaddr;
4589
        macaddr[0] = 0x52;
4590
        macaddr[1] = 0x54;
4591
        macaddr[2] = 0x00;
4592
        macaddr[3] = 0x12;
4593
        macaddr[4] = 0x34;
4594
        macaddr[5] = 0x56 + nb_nics;
4595

    
4596
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4597
            if (parse_macaddr(macaddr, buf) < 0) {
4598
                fprintf(stderr, "invalid syntax for ethernet address\n");
4599
                return -1;
4600
            }
4601
        }
4602
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4603
            nd->model = strdup(buf);
4604
        }
4605
        nd->vlan = vlan;
4606
        nb_nics++;
4607
        vlan->nb_guest_devs++;
4608
        ret = 0;
4609
    } else
4610
    if (!strcmp(device, "none")) {
4611
        /* does nothing. It is needed to signal that no network cards
4612
           are wanted */
4613
        ret = 0;
4614
    } else
4615
#ifdef CONFIG_SLIRP
4616
    if (!strcmp(device, "user")) {
4617
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4618
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4619
        }
4620
        vlan->nb_host_devs++;
4621
        ret = net_slirp_init(vlan);
4622
    } else
4623
#endif
4624
#ifdef _WIN32
4625
    if (!strcmp(device, "tap")) {
4626
        char ifname[64];
4627
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4628
            fprintf(stderr, "tap: no interface name\n");
4629
            return -1;
4630
        }
4631
        vlan->nb_host_devs++;
4632
        ret = tap_win32_init(vlan, ifname);
4633
    } else
4634
#else
4635
    if (!strcmp(device, "tap")) {
4636
        char ifname[64];
4637
        char setup_script[1024], down_script[1024];
4638
        int fd;
4639
        vlan->nb_host_devs++;
4640
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4641
            fd = strtol(buf, NULL, 0);
4642
            ret = -1;
4643
            if (net_tap_fd_init(vlan, fd))
4644
                ret = 0;
4645
        } else {
4646
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4647
                ifname[0] = '\0';
4648
            }
4649
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4650
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4651
            }
4652
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4653
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4654
            }
4655
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
4656
        }
4657
    } else
4658
#endif
4659
    if (!strcmp(device, "socket")) {
4660
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4661
            int fd;
4662
            fd = strtol(buf, NULL, 0);
4663
            ret = -1;
4664
            if (net_socket_fd_init(vlan, fd, 1))
4665
                ret = 0;
4666
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4667
            ret = net_socket_listen_init(vlan, buf);
4668
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4669
            ret = net_socket_connect_init(vlan, buf);
4670
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4671
            ret = net_socket_mcast_init(vlan, buf);
4672
        } else {
4673
            fprintf(stderr, "Unknown socket options: %s\n", p);
4674
            return -1;
4675
        }
4676
        vlan->nb_host_devs++;
4677
    } else
4678
    {
4679
        fprintf(stderr, "Unknown network device: %s\n", device);
4680
        return -1;
4681
    }
4682
    if (ret < 0) {
4683
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4684
    }
4685

    
4686
    return ret;
4687
}
4688

    
4689
void do_info_network(void)
4690
{
4691
    VLANState *vlan;
4692
    VLANClientState *vc;
4693

    
4694
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4695
        term_printf("VLAN %d devices:\n", vlan->id);
4696
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4697
            term_printf("  %s\n", vc->info_str);
4698
    }
4699
}
4700

    
4701
/***********************************************************/
4702
/* USB devices */
4703

    
4704
static USBPort *used_usb_ports;
4705
static USBPort *free_usb_ports;
4706

    
4707
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4708
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4709
                            usb_attachfn attach)
4710
{
4711
    port->opaque = opaque;
4712
    port->index = index;
4713
    port->attach = attach;
4714
    port->next = free_usb_ports;
4715
    free_usb_ports = port;
4716
}
4717

    
4718
static int usb_device_add(const char *devname)
4719
{
4720
    const char *p;
4721
    USBDevice *dev;
4722
    USBPort *port;
4723

    
4724
    if (!free_usb_ports)
4725
        return -1;
4726

    
4727
    if (strstart(devname, "host:", &p)) {
4728
        dev = usb_host_device_open(p);
4729
    } else if (!strcmp(devname, "mouse")) {
4730
        dev = usb_mouse_init();
4731
    } else if (!strcmp(devname, "tablet")) {
4732
        dev = usb_tablet_init();
4733
    } else if (!strcmp(devname, "keyboard")) {
4734
        dev = usb_keyboard_init();
4735
    } else if (strstart(devname, "disk:", &p)) {
4736
        dev = usb_msd_init(p);
4737
    } else if (!strcmp(devname, "wacom-tablet")) {
4738
        dev = usb_wacom_init();
4739
    } else {
4740
        return -1;
4741
    }
4742
    if (!dev)
4743
        return -1;
4744

    
4745
    /* Find a USB port to add the device to.  */
4746
    port = free_usb_ports;
4747
    if (!port->next) {
4748
        USBDevice *hub;
4749

    
4750
        /* Create a new hub and chain it on.  */
4751
        free_usb_ports = NULL;
4752
        port->next = used_usb_ports;
4753
        used_usb_ports = port;
4754

    
4755
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4756
        usb_attach(port, hub);
4757
        port = free_usb_ports;
4758
    }
4759

    
4760
    free_usb_ports = port->next;
4761
    port->next = used_usb_ports;
4762
    used_usb_ports = port;
4763
    usb_attach(port, dev);
4764
    return 0;
4765
}
4766

    
4767
static int usb_device_del(const char *devname)
4768
{
4769
    USBPort *port;
4770
    USBPort **lastp;
4771
    USBDevice *dev;
4772
    int bus_num, addr;
4773
    const char *p;
4774

    
4775
    if (!used_usb_ports)
4776
        return -1;
4777

    
4778
    p = strchr(devname, '.');
4779
    if (!p)
4780
        return -1;
4781
    bus_num = strtoul(devname, NULL, 0);
4782
    addr = strtoul(p + 1, NULL, 0);
4783
    if (bus_num != 0)
4784
        return -1;
4785

    
4786
    lastp = &used_usb_ports;
4787
    port = used_usb_ports;
4788
    while (port && port->dev->addr != addr) {
4789
        lastp = &port->next;
4790
        port = port->next;
4791
    }
4792

    
4793
    if (!port)
4794
        return -1;
4795

    
4796
    dev = port->dev;
4797
    *lastp = port->next;
4798
    usb_attach(port, NULL);
4799
    dev->handle_destroy(dev);
4800
    port->next = free_usb_ports;
4801
    free_usb_ports = port;
4802
    return 0;
4803
}
4804

    
4805
void do_usb_add(const char *devname)
4806
{
4807
    int ret;
4808
    ret = usb_device_add(devname);
4809
    if (ret < 0)
4810
        term_printf("Could not add USB device '%s'\n", devname);
4811
}
4812

    
4813
void do_usb_del(const char *devname)
4814
{
4815
    int ret;
4816
    ret = usb_device_del(devname);
4817
    if (ret < 0)
4818
        term_printf("Could not remove USB device '%s'\n", devname);
4819
}
4820

    
4821
void usb_info(void)
4822
{
4823
    USBDevice *dev;
4824
    USBPort *port;
4825
    const char *speed_str;
4826

    
4827
    if (!usb_enabled) {
4828
        term_printf("USB support not enabled\n");
4829
        return;
4830
    }
4831

    
4832
    for (port = used_usb_ports; port; port = port->next) {
4833
        dev = port->dev;
4834
        if (!dev)
4835
            continue;
4836
        switch(dev->speed) {
4837
        case USB_SPEED_LOW:
4838
            speed_str = "1.5";
4839
            break;
4840
        case USB_SPEED_FULL:
4841
            speed_str = "12";
4842
            break;
4843
        case USB_SPEED_HIGH:
4844
            speed_str = "480";
4845
            break;
4846
        default:
4847
            speed_str = "?";
4848
            break;
4849
        }
4850
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
4851
                    0, dev->addr, speed_str, dev->devname);
4852
    }
4853
}
4854

    
4855
/***********************************************************/
4856
/* PCMCIA/Cardbus */
4857

    
4858
static struct pcmcia_socket_entry_s {
4859
    struct pcmcia_socket_s *socket;
4860
    struct pcmcia_socket_entry_s *next;
4861
} *pcmcia_sockets = 0;
4862

    
4863
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4864
{
4865
    struct pcmcia_socket_entry_s *entry;
4866

    
4867
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4868
    entry->socket = socket;
4869
    entry->next = pcmcia_sockets;
4870
    pcmcia_sockets = entry;
4871
}
4872

    
4873
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4874
{
4875
    struct pcmcia_socket_entry_s *entry, **ptr;
4876

    
4877
    ptr = &pcmcia_sockets;
4878
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4879
        if (entry->socket == socket) {
4880
            *ptr = entry->next;
4881
            qemu_free(entry);
4882
        }
4883
}
4884

    
4885
void pcmcia_info(void)
4886
{
4887
    struct pcmcia_socket_entry_s *iter;
4888
    if (!pcmcia_sockets)
4889
        term_printf("No PCMCIA sockets\n");
4890

    
4891
    for (iter = pcmcia_sockets; iter; iter = iter->next)
4892
        term_printf("%s: %s\n", iter->socket->slot_string,
4893
                    iter->socket->attached ? iter->socket->card_string :
4894
                    "Empty");
4895
}
4896

    
4897
/***********************************************************/
4898
/* dumb display */
4899

    
4900
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4901
{
4902
}
4903

    
4904
static void dumb_resize(DisplayState *ds, int w, int h)
4905
{
4906
}
4907

    
4908
static void dumb_refresh(DisplayState *ds)
4909
{
4910
#if defined(CONFIG_SDL)
4911
    vga_hw_update();
4912
#endif
4913
}
4914

    
4915
static void dumb_display_init(DisplayState *ds)
4916
{
4917
    ds->data = NULL;
4918
    ds->linesize = 0;
4919
    ds->depth = 0;
4920
    ds->dpy_update = dumb_update;
4921
    ds->dpy_resize = dumb_resize;
4922
    ds->dpy_refresh = dumb_refresh;
4923
}
4924

    
4925
/***********************************************************/
4926
/* I/O handling */
4927

    
4928
#define MAX_IO_HANDLERS 64
4929

    
4930
typedef struct IOHandlerRecord {
4931
    int fd;
4932
    IOCanRWHandler *fd_read_poll;
4933
    IOHandler *fd_read;
4934
    IOHandler *fd_write;
4935
    int deleted;
4936
    void *opaque;
4937
    /* temporary data */
4938
    struct pollfd *ufd;
4939
    struct IOHandlerRecord *next;
4940
} IOHandlerRecord;
4941

    
4942
static IOHandlerRecord *first_io_handler;
4943

    
4944
/* XXX: fd_read_poll should be suppressed, but an API change is
4945
   necessary in the character devices to suppress fd_can_read(). */
4946
int qemu_set_fd_handler2(int fd,
4947
                         IOCanRWHandler *fd_read_poll,
4948
                         IOHandler *fd_read,
4949
                         IOHandler *fd_write,
4950
                         void *opaque)
4951
{
4952
    IOHandlerRecord **pioh, *ioh;
4953

    
4954
    if (!fd_read && !fd_write) {
4955
        pioh = &first_io_handler;
4956
        for(;;) {
4957
            ioh = *pioh;
4958
            if (ioh == NULL)
4959
                break;
4960
            if (ioh->fd == fd) {
4961
                ioh->deleted = 1;
4962
                break;
4963
            }
4964
            pioh = &ioh->next;
4965<