Statistics
| Branch: | Revision:

root / vl.c @ 6bf5b4e8

History | View | Annotate | Download (216.6 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
#ifdef __sun__
121
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
122
#else
123
#define SMBD_COMMAND "/usr/sbin/smbd"
124
#endif
125

    
126
//#define DEBUG_UNUSED_IOPORT
127
//#define DEBUG_IOPORT
128

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

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

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

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

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

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

    
223
/***********************************************************/
224
/* x86 ISA bus support */
225

    
226
target_phys_addr_t isa_mem_base = 0;
227
PicState2 *isa_pic;
228

    
229
uint32_t default_ioport_readb(void *opaque, uint32_t address)
230
{
231
#ifdef DEBUG_UNUSED_IOPORT
232
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
233
#endif
234
    return 0xff;
235
}
236

    
237
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
238
{
239
#ifdef DEBUG_UNUSED_IOPORT
240
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
241
#endif
242
}
243

    
244
/* default is to make two byte accesses */
245
uint32_t default_ioport_readw(void *opaque, uint32_t address)
246
{
247
    uint32_t data;
248
    data = ioport_read_table[0][address](ioport_opaque[address], address);
249
    address = (address + 1) & (MAX_IOPORTS - 1);
250
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
251
    return data;
252
}
253

    
254
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
255
{
256
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
257
    address = (address + 1) & (MAX_IOPORTS - 1);
258
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
259
}
260

    
261
uint32_t default_ioport_readl(void *opaque, uint32_t address)
262
{
263
#ifdef DEBUG_UNUSED_IOPORT
264
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
265
#endif
266
    return 0xffffffff;
267
}
268

    
269
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
270
{
271
#ifdef DEBUG_UNUSED_IOPORT
272
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
273
#endif
274
}
275

    
276
void init_ioports(void)
277
{
278
    int i;
279

    
280
    for(i = 0; i < MAX_IOPORTS; i++) {
281
        ioport_read_table[0][i] = default_ioport_readb;
282
        ioport_write_table[0][i] = default_ioport_writeb;
283
        ioport_read_table[1][i] = default_ioport_readw;
284
        ioport_write_table[1][i] = default_ioport_writew;
285
        ioport_read_table[2][i] = default_ioport_readl;
286
        ioport_write_table[2][i] = default_ioport_writel;
287
    }
288
}
289

    
290
/* size is the word size in byte */
291
int register_ioport_read(int start, int length, int size,
292
                         IOPortReadFunc *func, void *opaque)
293
{
294
    int i, bsize;
295

    
296
    if (size == 1) {
297
        bsize = 0;
298
    } else if (size == 2) {
299
        bsize = 1;
300
    } else if (size == 4) {
301
        bsize = 2;
302
    } else {
303
        hw_error("register_ioport_read: invalid size");
304
        return -1;
305
    }
306
    for(i = start; i < start + length; i += size) {
307
        ioport_read_table[bsize][i] = func;
308
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
309
            hw_error("register_ioport_read: invalid opaque");
310
        ioport_opaque[i] = opaque;
311
    }
312
    return 0;
313
}
314

    
315
/* size is the word size in byte */
316
int register_ioport_write(int start, int length, int size,
317
                          IOPortWriteFunc *func, void *opaque)
318
{
319
    int i, bsize;
320

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

    
340
void isa_unassign_ioport(int start, int length)
341
{
342
    int i;
343

    
344
    for(i = start; i < start + length; i++) {
345
        ioport_read_table[0][i] = default_ioport_readb;
346
        ioport_read_table[1][i] = default_ioport_readw;
347
        ioport_read_table[2][i] = default_ioport_readl;
348

    
349
        ioport_write_table[0][i] = default_ioport_writeb;
350
        ioport_write_table[1][i] = default_ioport_writew;
351
        ioport_write_table[2][i] = default_ioport_writel;
352
    }
353
}
354

    
355
/***********************************************************/
356

    
357
void cpu_outb(CPUState *env, int addr, int val)
358
{
359
#ifdef DEBUG_IOPORT
360
    if (loglevel & CPU_LOG_IOPORT)
361
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
362
#endif
363
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
364
#ifdef USE_KQEMU
365
    if (env)
366
        env->last_io_time = cpu_get_time_fast();
367
#endif
368
}
369

    
370
void cpu_outw(CPUState *env, int addr, int val)
371
{
372
#ifdef DEBUG_IOPORT
373
    if (loglevel & CPU_LOG_IOPORT)
374
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
375
#endif
376
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
377
#ifdef USE_KQEMU
378
    if (env)
379
        env->last_io_time = cpu_get_time_fast();
380
#endif
381
}
382

    
383
void cpu_outl(CPUState *env, int addr, int val)
384
{
385
#ifdef DEBUG_IOPORT
386
    if (loglevel & CPU_LOG_IOPORT)
387
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
388
#endif
389
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
390
#ifdef USE_KQEMU
391
    if (env)
392
        env->last_io_time = cpu_get_time_fast();
393
#endif
394
}
395

    
396
int cpu_inb(CPUState *env, int addr)
397
{
398
    int val;
399
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
400
#ifdef DEBUG_IOPORT
401
    if (loglevel & CPU_LOG_IOPORT)
402
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
403
#endif
404
#ifdef USE_KQEMU
405
    if (env)
406
        env->last_io_time = cpu_get_time_fast();
407
#endif
408
    return val;
409
}
410

    
411
int cpu_inw(CPUState *env, int addr)
412
{
413
    int val;
414
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
415
#ifdef DEBUG_IOPORT
416
    if (loglevel & CPU_LOG_IOPORT)
417
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
418
#endif
419
#ifdef USE_KQEMU
420
    if (env)
421
        env->last_io_time = cpu_get_time_fast();
422
#endif
423
    return val;
424
}
425

    
426
int cpu_inl(CPUState *env, int addr)
427
{
428
    int val;
429
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
430
#ifdef DEBUG_IOPORT
431
    if (loglevel & CPU_LOG_IOPORT)
432
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
433
#endif
434
#ifdef USE_KQEMU
435
    if (env)
436
        env->last_io_time = cpu_get_time_fast();
437
#endif
438
    return val;
439
}
440

    
441
/***********************************************************/
442
void hw_error(const char *fmt, ...)
443
{
444
    va_list ap;
445
    CPUState *env;
446

    
447
    va_start(ap, fmt);
448
    fprintf(stderr, "qemu: hardware error: ");
449
    vfprintf(stderr, fmt, ap);
450
    fprintf(stderr, "\n");
451
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
452
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
453
#ifdef TARGET_I386
454
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
455
#else
456
        cpu_dump_state(env, stderr, fprintf, 0);
457
#endif
458
    }
459
    va_end(ap);
460
    abort();
461
}
462

    
463
/***********************************************************/
464
/* keyboard/mouse */
465

    
466
static QEMUPutKBDEvent *qemu_put_kbd_event;
467
static void *qemu_put_kbd_event_opaque;
468
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
469
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
470

    
471
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
472
{
473
    qemu_put_kbd_event_opaque = opaque;
474
    qemu_put_kbd_event = func;
475
}
476

    
477
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
478
                                                void *opaque, int absolute,
479
                                                const char *name)
480
{
481
    QEMUPutMouseEntry *s, *cursor;
482

    
483
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
484
    if (!s)
485
        return NULL;
486

    
487
    s->qemu_put_mouse_event = func;
488
    s->qemu_put_mouse_event_opaque = opaque;
489
    s->qemu_put_mouse_event_absolute = absolute;
490
    s->qemu_put_mouse_event_name = qemu_strdup(name);
491
    s->next = NULL;
492

    
493
    if (!qemu_put_mouse_event_head) {
494
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
495
        return s;
496
    }
497

    
498
    cursor = qemu_put_mouse_event_head;
499
    while (cursor->next != NULL)
500
        cursor = cursor->next;
501

    
502
    cursor->next = s;
503
    qemu_put_mouse_event_current = s;
504

    
505
    return s;
506
}
507

    
508
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
509
{
510
    QEMUPutMouseEntry *prev = NULL, *cursor;
511

    
512
    if (!qemu_put_mouse_event_head || entry == NULL)
513
        return;
514

    
515
    cursor = qemu_put_mouse_event_head;
516
    while (cursor != NULL && cursor != entry) {
517
        prev = cursor;
518
        cursor = cursor->next;
519
    }
520

    
521
    if (cursor == NULL) // does not exist or list empty
522
        return;
523
    else if (prev == NULL) { // entry is head
524
        qemu_put_mouse_event_head = cursor->next;
525
        if (qemu_put_mouse_event_current == entry)
526
            qemu_put_mouse_event_current = cursor->next;
527
        qemu_free(entry->qemu_put_mouse_event_name);
528
        qemu_free(entry);
529
        return;
530
    }
531

    
532
    prev->next = entry->next;
533

    
534
    if (qemu_put_mouse_event_current == entry)
535
        qemu_put_mouse_event_current = prev;
536

    
537
    qemu_free(entry->qemu_put_mouse_event_name);
538
    qemu_free(entry);
539
}
540

    
541
void kbd_put_keycode(int keycode)
542
{
543
    if (qemu_put_kbd_event) {
544
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
545
    }
546
}
547

    
548
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
549
{
550
    QEMUPutMouseEvent *mouse_event;
551
    void *mouse_event_opaque;
552
    int width;
553

    
554
    if (!qemu_put_mouse_event_current) {
555
        return;
556
    }
557

    
558
    mouse_event =
559
        qemu_put_mouse_event_current->qemu_put_mouse_event;
560
    mouse_event_opaque =
561
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
562

    
563
    if (mouse_event) {
564
        if (graphic_rotate) {
565
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
566
                width = 0x7fff;
567
            else
568
                width = graphic_width;
569
            mouse_event(mouse_event_opaque,
570
                                 width - dy, dx, dz, buttons_state);
571
        } else
572
            mouse_event(mouse_event_opaque,
573
                                 dx, dy, dz, buttons_state);
574
    }
575
}
576

    
577
int kbd_mouse_is_absolute(void)
578
{
579
    if (!qemu_put_mouse_event_current)
580
        return 0;
581

    
582
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
583
}
584

    
585
void do_info_mice(void)
586
{
587
    QEMUPutMouseEntry *cursor;
588
    int index = 0;
589

    
590
    if (!qemu_put_mouse_event_head) {
591
        term_printf("No mouse devices connected\n");
592
        return;
593
    }
594

    
595
    term_printf("Mouse devices available:\n");
596
    cursor = qemu_put_mouse_event_head;
597
    while (cursor != NULL) {
598
        term_printf("%c Mouse #%d: %s\n",
599
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
600
                    index, cursor->qemu_put_mouse_event_name);
601
        index++;
602
        cursor = cursor->next;
603
    }
604
}
605

    
606
void do_mouse_set(int index)
607
{
608
    QEMUPutMouseEntry *cursor;
609
    int i = 0;
610

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

    
616
    cursor = qemu_put_mouse_event_head;
617
    while (cursor != NULL && index != i) {
618
        i++;
619
        cursor = cursor->next;
620
    }
621

    
622
    if (cursor != NULL)
623
        qemu_put_mouse_event_current = cursor;
624
    else
625
        term_printf("Mouse at given index not found\n");
626
}
627

    
628
/* compute with 96 bit intermediate result: (a*b)/c */
629
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
630
{
631
    union {
632
        uint64_t ll;
633
        struct {
634
#ifdef WORDS_BIGENDIAN
635
            uint32_t high, low;
636
#else
637
            uint32_t low, high;
638
#endif
639
        } l;
640
    } u, res;
641
    uint64_t rl, rh;
642

    
643
    u.ll = a;
644
    rl = (uint64_t)u.l.low * (uint64_t)b;
645
    rh = (uint64_t)u.l.high * (uint64_t)b;
646
    rh += (rl >> 32);
647
    res.l.high = rh / c;
648
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
649
    return res.ll;
650
}
651

    
652
/***********************************************************/
653
/* real time host monotonic timer */
654

    
655
#define QEMU_TIMER_BASE 1000000000LL
656

    
657
#ifdef WIN32
658

    
659
static int64_t clock_freq;
660

    
661
static void init_get_clock(void)
662
{
663
    LARGE_INTEGER freq;
664
    int ret;
665
    ret = QueryPerformanceFrequency(&freq);
666
    if (ret == 0) {
667
        fprintf(stderr, "Could not calibrate ticks\n");
668
        exit(1);
669
    }
670
    clock_freq = freq.QuadPart;
671
}
672

    
673
static int64_t get_clock(void)
674
{
675
    LARGE_INTEGER ti;
676
    QueryPerformanceCounter(&ti);
677
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
678
}
679

    
680
#else
681

    
682
static int use_rt_clock;
683

    
684
static void init_get_clock(void)
685
{
686
    use_rt_clock = 0;
687
#if defined(__linux__)
688
    {
689
        struct timespec ts;
690
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
691
            use_rt_clock = 1;
692
        }
693
    }
694
#endif
695
}
696

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

    
715
#endif
716

    
717
/***********************************************************/
718
/* guest cycle counter */
719

    
720
static int64_t cpu_ticks_prev;
721
static int64_t cpu_ticks_offset;
722
static int64_t cpu_clock_offset;
723
static int cpu_ticks_enabled;
724

    
725
/* return the host CPU cycle counter and handle stop/restart */
726
int64_t cpu_get_ticks(void)
727
{
728
    if (!cpu_ticks_enabled) {
729
        return cpu_ticks_offset;
730
    } else {
731
        int64_t ticks;
732
        ticks = cpu_get_real_ticks();
733
        if (cpu_ticks_prev > ticks) {
734
            /* Note: non increasing ticks may happen if the host uses
735
               software suspend */
736
            cpu_ticks_offset += cpu_ticks_prev - ticks;
737
        }
738
        cpu_ticks_prev = ticks;
739
        return ticks + cpu_ticks_offset;
740
    }
741
}
742

    
743
/* return the host CPU monotonic timer and handle stop/restart */
744
static int64_t cpu_get_clock(void)
745
{
746
    int64_t ti;
747
    if (!cpu_ticks_enabled) {
748
        return cpu_clock_offset;
749
    } else {
750
        ti = get_clock();
751
        return ti + cpu_clock_offset;
752
    }
753
}
754

    
755
/* enable cpu_get_ticks() */
756
void cpu_enable_ticks(void)
757
{
758
    if (!cpu_ticks_enabled) {
759
        cpu_ticks_offset -= cpu_get_real_ticks();
760
        cpu_clock_offset -= get_clock();
761
        cpu_ticks_enabled = 1;
762
    }
763
}
764

    
765
/* disable cpu_get_ticks() : the clock is stopped. You must not call
766
   cpu_get_ticks() after that.  */
767
void cpu_disable_ticks(void)
768
{
769
    if (cpu_ticks_enabled) {
770
        cpu_ticks_offset = cpu_get_ticks();
771
        cpu_clock_offset = cpu_get_clock();
772
        cpu_ticks_enabled = 0;
773
    }
774
}
775

    
776
/***********************************************************/
777
/* timers */
778

    
779
#define QEMU_TIMER_REALTIME 0
780
#define QEMU_TIMER_VIRTUAL  1
781

    
782
struct QEMUClock {
783
    int type;
784
    /* XXX: add frequency */
785
};
786

    
787
struct QEMUTimer {
788
    QEMUClock *clock;
789
    int64_t expire_time;
790
    QEMUTimerCB *cb;
791
    void *opaque;
792
    struct QEMUTimer *next;
793
};
794

    
795
struct qemu_alarm_timer {
796
    char const *name;
797
    unsigned int flags;
798

    
799
    int (*start)(struct qemu_alarm_timer *t);
800
    void (*stop)(struct qemu_alarm_timer *t);
801
    void (*rearm)(struct qemu_alarm_timer *t);
802
    void *priv;
803
};
804

    
805
#define ALARM_FLAG_DYNTICKS  0x1
806

    
807
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
808
{
809
    return t->flags & ALARM_FLAG_DYNTICKS;
810
}
811

    
812
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
813
{
814
    if (!alarm_has_dynticks(t))
815
        return;
816

    
817
    t->rearm(t);
818
}
819

    
820
/* TODO: MIN_TIMER_REARM_US should be optimized */
821
#define MIN_TIMER_REARM_US 250
822

    
823
static struct qemu_alarm_timer *alarm_timer;
824

    
825
#ifdef _WIN32
826

    
827
struct qemu_alarm_win32 {
828
    MMRESULT timerId;
829
    HANDLE host_alarm;
830
    unsigned int period;
831
} alarm_win32_data = {0, NULL, -1};
832

    
833
static int win32_start_timer(struct qemu_alarm_timer *t);
834
static void win32_stop_timer(struct qemu_alarm_timer *t);
835
static void win32_rearm_timer(struct qemu_alarm_timer *t);
836

    
837
#else
838

    
839
static int unix_start_timer(struct qemu_alarm_timer *t);
840
static void unix_stop_timer(struct qemu_alarm_timer *t);
841

    
842
#ifdef __linux__
843

    
844
static int dynticks_start_timer(struct qemu_alarm_timer *t);
845
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
846
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
847

    
848
static int hpet_start_timer(struct qemu_alarm_timer *t);
849
static void hpet_stop_timer(struct qemu_alarm_timer *t);
850

    
851
static int rtc_start_timer(struct qemu_alarm_timer *t);
852
static void rtc_stop_timer(struct qemu_alarm_timer *t);
853

    
854
#endif /* __linux__ */
855

    
856
#endif /* _WIN32 */
857

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

    
878
static void show_available_alarms()
879
{
880
    int i;
881

    
882
    printf("Available alarm timers, in order of precedence:\n");
883
    for (i = 0; alarm_timers[i].name; i++)
884
        printf("%s\n", alarm_timers[i].name);
885
}
886

    
887
static void configure_alarms(char const *opt)
888
{
889
    int i;
890
    int cur = 0;
891
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
892
    char *arg;
893
    char *name;
894

    
895
    if (!strcmp(opt, "help")) {
896
        show_available_alarms();
897
        exit(0);
898
    }
899

    
900
    arg = strdup(opt);
901

    
902
    /* Reorder the array */
903
    name = strtok(arg, ",");
904
    while (name) {
905
        struct qemu_alarm_timer tmp;
906

    
907
        for (i = 0; i < count && alarm_timers[i].name; i++) {
908
            if (!strcmp(alarm_timers[i].name, name))
909
                break;
910
        }
911

    
912
        if (i == count) {
913
            fprintf(stderr, "Unknown clock %s\n", name);
914
            goto next;
915
        }
916

    
917
        if (i < cur)
918
            /* Ignore */
919
            goto next;
920

    
921
        /* Swap */
922
        tmp = alarm_timers[i];
923
        alarm_timers[i] = alarm_timers[cur];
924
        alarm_timers[cur] = tmp;
925

    
926
        cur++;
927
next:
928
        name = strtok(NULL, ",");
929
    }
930

    
931
    free(arg);
932

    
933
    if (cur) {
934
        /* Disable remaining timers */
935
        for (i = cur; i < count; i++)
936
            alarm_timers[i].name = NULL;
937
    }
938

    
939
    /* debug */
940
    show_available_alarms();
941
}
942

    
943
QEMUClock *rt_clock;
944
QEMUClock *vm_clock;
945

    
946
static QEMUTimer *active_timers[2];
947

    
948
QEMUClock *qemu_new_clock(int type)
949
{
950
    QEMUClock *clock;
951
    clock = qemu_mallocz(sizeof(QEMUClock));
952
    if (!clock)
953
        return NULL;
954
    clock->type = type;
955
    return clock;
956
}
957

    
958
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
959
{
960
    QEMUTimer *ts;
961

    
962
    ts = qemu_mallocz(sizeof(QEMUTimer));
963
    ts->clock = clock;
964
    ts->cb = cb;
965
    ts->opaque = opaque;
966
    return ts;
967
}
968

    
969
void qemu_free_timer(QEMUTimer *ts)
970
{
971
    qemu_free(ts);
972
}
973

    
974
/* stop a timer, but do not dealloc it */
975
void qemu_del_timer(QEMUTimer *ts)
976
{
977
    QEMUTimer **pt, *t;
978

    
979
    /* NOTE: this code must be signal safe because
980
       qemu_timer_expired() can be called from a signal. */
981
    pt = &active_timers[ts->clock->type];
982
    for(;;) {
983
        t = *pt;
984
        if (!t)
985
            break;
986
        if (t == ts) {
987
            *pt = t->next;
988
            break;
989
        }
990
        pt = &t->next;
991
    }
992
}
993

    
994
/* modify the current timer so that it will be fired when current_time
995
   >= expire_time. The corresponding callback will be called. */
996
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
997
{
998
    QEMUTimer **pt, *t;
999

    
1000
    qemu_del_timer(ts);
1001

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

    
1019
int qemu_timer_pending(QEMUTimer *ts)
1020
{
1021
    QEMUTimer *t;
1022
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1023
        if (t == ts)
1024
            return 1;
1025
    }
1026
    return 0;
1027
}
1028

    
1029
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1030
{
1031
    if (!timer_head)
1032
        return 0;
1033
    return (timer_head->expire_time <= current_time);
1034
}
1035

    
1036
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1037
{
1038
    QEMUTimer *ts;
1039

    
1040
    for(;;) {
1041
        ts = *ptimer_head;
1042
        if (!ts || ts->expire_time > current_time)
1043
            break;
1044
        /* remove timer from the list before calling the callback */
1045
        *ptimer_head = ts->next;
1046
        ts->next = NULL;
1047

    
1048
        /* run the callback (the timer list can be modified) */
1049
        ts->cb(ts->opaque);
1050
    }
1051
    qemu_rearm_alarm_timer(alarm_timer);
1052
}
1053

    
1054
int64_t qemu_get_clock(QEMUClock *clock)
1055
{
1056
    switch(clock->type) {
1057
    case QEMU_TIMER_REALTIME:
1058
        return get_clock() / 1000000;
1059
    default:
1060
    case QEMU_TIMER_VIRTUAL:
1061
        return cpu_get_clock();
1062
    }
1063
}
1064

    
1065
static void init_timers(void)
1066
{
1067
    init_get_clock();
1068
    ticks_per_sec = QEMU_TIMER_BASE;
1069
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1070
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1071
}
1072

    
1073
/* save a timer */
1074
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1075
{
1076
    uint64_t expire_time;
1077

    
1078
    if (qemu_timer_pending(ts)) {
1079
        expire_time = ts->expire_time;
1080
    } else {
1081
        expire_time = -1;
1082
    }
1083
    qemu_put_be64(f, expire_time);
1084
}
1085

    
1086
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1087
{
1088
    uint64_t expire_time;
1089

    
1090
    expire_time = qemu_get_be64(f);
1091
    if (expire_time != -1) {
1092
        qemu_mod_timer(ts, expire_time);
1093
    } else {
1094
        qemu_del_timer(ts);
1095
    }
1096
}
1097

    
1098
static void timer_save(QEMUFile *f, void *opaque)
1099
{
1100
    if (cpu_ticks_enabled) {
1101
        hw_error("cannot save state if virtual timers are running");
1102
    }
1103
    qemu_put_be64s(f, &cpu_ticks_offset);
1104
    qemu_put_be64s(f, &ticks_per_sec);
1105
    qemu_put_be64s(f, &cpu_clock_offset);
1106
}
1107

    
1108
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1109
{
1110
    if (version_id != 1 && version_id != 2)
1111
        return -EINVAL;
1112
    if (cpu_ticks_enabled) {
1113
        return -EINVAL;
1114
    }
1115
    qemu_get_be64s(f, &cpu_ticks_offset);
1116
    qemu_get_be64s(f, &ticks_per_sec);
1117
    if (version_id == 2) {
1118
        qemu_get_be64s(f, &cpu_clock_offset);
1119
    }
1120
    return 0;
1121
}
1122

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

    
1181
static uint64_t qemu_next_deadline(void)
1182
{
1183
    int64_t nearest_delta_us = INT64_MAX;
1184
    int64_t vmdelta_us;
1185

    
1186
    if (active_timers[QEMU_TIMER_REALTIME])
1187
        nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1188
                            qemu_get_clock(rt_clock))*1000;
1189

    
1190
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1191
        /* round up */
1192
        vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1193
                      qemu_get_clock(vm_clock)+999)/1000;
1194
        if (vmdelta_us < nearest_delta_us)
1195
            nearest_delta_us = vmdelta_us;
1196
    }
1197

    
1198
    /* Avoid arming the timer to negative, zero, or too low values */
1199
    if (nearest_delta_us <= MIN_TIMER_REARM_US)
1200
        nearest_delta_us = MIN_TIMER_REARM_US;
1201

    
1202
    return nearest_delta_us;
1203
}
1204

    
1205
#ifndef _WIN32
1206

    
1207
#if defined(__linux__)
1208

    
1209
#define RTC_FREQ 1024
1210

    
1211
static void enable_sigio_timer(int fd)
1212
{
1213
    struct sigaction act;
1214

    
1215
    /* timer signal */
1216
    sigfillset(&act.sa_mask);
1217
    act.sa_flags = 0;
1218
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1219
    act.sa_flags |= SA_ONSTACK;
1220
#endif
1221
    act.sa_handler = host_alarm_handler;
1222

    
1223
    sigaction(SIGIO, &act, NULL);
1224
    fcntl(fd, F_SETFL, O_ASYNC);
1225
    fcntl(fd, F_SETOWN, getpid());
1226
}
1227

    
1228
static int hpet_start_timer(struct qemu_alarm_timer *t)
1229
{
1230
    struct hpet_info info;
1231
    int r, fd;
1232

    
1233
    fd = open("/dev/hpet", O_RDONLY);
1234
    if (fd < 0)
1235
        return -1;
1236

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

    
1246
    /* Check capabilities */
1247
    r = ioctl(fd, HPET_INFO, &info);
1248
    if (r < 0)
1249
        goto fail;
1250

    
1251
    /* Enable periodic mode */
1252
    r = ioctl(fd, HPET_EPI, 0);
1253
    if (info.hi_flags && (r < 0))
1254
        goto fail;
1255

    
1256
    /* Enable interrupt */
1257
    r = ioctl(fd, HPET_IE_ON, 0);
1258
    if (r < 0)
1259
        goto fail;
1260

    
1261
    enable_sigio_timer(fd);
1262
    t->priv = (void *)(long)fd;
1263

    
1264
    return 0;
1265
fail:
1266
    close(fd);
1267
    return -1;
1268
}
1269

    
1270
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1271
{
1272
    int fd = (long)t->priv;
1273

    
1274
    close(fd);
1275
}
1276

    
1277
static int rtc_start_timer(struct qemu_alarm_timer *t)
1278
{
1279
    int rtc_fd;
1280

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

    
1296
    enable_sigio_timer(rtc_fd);
1297

    
1298
    t->priv = (void *)(long)rtc_fd;
1299

    
1300
    return 0;
1301
}
1302

    
1303
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1304
{
1305
    int rtc_fd = (long)t->priv;
1306

    
1307
    close(rtc_fd);
1308
}
1309

    
1310
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1311
{
1312
    struct sigevent ev;
1313
    timer_t host_timer;
1314
    struct sigaction act;
1315

    
1316
    sigfillset(&act.sa_mask);
1317
    act.sa_flags = 0;
1318
#if defined(TARGET_I386) && defined(USE_CODE_COPY)
1319
    act.sa_flags |= SA_ONSTACK;
1320
#endif
1321
    act.sa_handler = host_alarm_handler;
1322

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

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

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

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

    
1335
        return -1;
1336
    }
1337

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

    
1340
    return 0;
1341
}
1342

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

    
1347
    timer_delete(host_timer);
1348
}
1349

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

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

    
1361
    nearest_delta_us = qemu_next_deadline();
1362

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

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

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

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

    
1392
    /* timer signal */
1393
    sigfillset(&act.sa_mask);
1394
    act.sa_flags = 0;
1395
#if defined(TARGET_I386) && defined(USE_CODE_COPY)
1396
    act.sa_flags |= SA_ONSTACK;
1397
#endif
1398
    act.sa_handler = host_alarm_handler;
1399

    
1400
    sigaction(SIGALRM, &act, NULL);
1401

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

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

    
1412
    return 0;
1413
}
1414

    
1415
static void unix_stop_timer(struct qemu_alarm_timer *t)
1416
{
1417
    struct itimerval itv;
1418

    
1419
    memset(&itv, 0, sizeof(itv));
1420
    setitimer(ITIMER_REAL, &itv, NULL);
1421
}
1422

    
1423
#endif /* !defined(_WIN32) */
1424

    
1425
#ifdef _WIN32
1426

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

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

    
1439
    memset(&tc, 0, sizeof(tc));
1440
    timeGetDevCaps(&tc, sizeof(tc));
1441

    
1442
    if (data->period < tc.wPeriodMin)
1443
        data->period = tc.wPeriodMin;
1444

    
1445
    timeBeginPeriod(data->period);
1446

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

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

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

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

    
1467
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1468

    
1469
    return 0;
1470
}
1471

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

    
1476
    timeKillEvent(data->timerId);
1477
    timeEndPeriod(data->period);
1478

    
1479
    CloseHandle(data->host_alarm);
1480
}
1481

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

    
1487
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1488
                !active_timers[QEMU_TIMER_VIRTUAL])
1489
            return;
1490

    
1491
    nearest_delta_us = qemu_next_deadline();
1492
    nearest_delta_us /= 1000;
1493

    
1494
    timeKillEvent(data->timerId);
1495

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

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

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

    
1511
#endif /* _WIN32 */
1512

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

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

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

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

    
1532
    alarm_timer = t;
1533
}
1534

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

    
1541
/***********************************************************/
1542
/* character device */
1543

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

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

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

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

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

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

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

    
1591

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

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

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

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

    
1627
static CharDriverState *qemu_chr_open_null(void)
1628
{
1629
    CharDriverState *chr;
1630

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

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

    
1653

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1828
CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1829
{
1830
    CharDriverState *chr;
1831
    MuxDriver *d;
1832

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

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

    
1850

    
1851
#ifdef _WIN32
1852

    
1853
static void socket_cleanup(void)
1854
{
1855
    WSACleanup();
1856
}
1857

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

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

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

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

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

    
1902
#else
1903

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

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

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

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

    
1935
#ifndef _WIN32
1936

    
1937
typedef struct {
1938
    int fd_in, fd_out;
1939
    int max_size;
1940
} FDCharDriver;
1941

    
1942
#define STDIO_MAX_CLIENTS 1
1943
static int stdio_nb_clients = 0;
1944

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

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

    
1956
    s->max_size = qemu_chr_can_read(chr);
1957
    return s->max_size;
1958
}
1959

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

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

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

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

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

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

    
2016
    qemu_chr_reset(chr);
2017

    
2018
    return chr;
2019
}
2020

    
2021
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2022
{
2023
    int fd_out;
2024

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

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

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

    
2052

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

    
2056
#define TERM_FIFO_MAX_SIZE 1
2057

    
2058
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2059
static int term_fifo_size;
2060

    
2061
static int stdio_read_poll(void *opaque)
2062
{
2063
    CharDriverState *chr = opaque;
2064

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

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

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

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

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

    
2108
static void term_init(void)
2109
{
2110
    struct termios tty;
2111

    
2112
    tcgetattr (0, &tty);
2113
    oldtty = tty;
2114
    old_fd0_flags = fcntl(0, F_GETFL);
2115

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

    
2128
    tcsetattr (0, TCSANOW, &tty);
2129

    
2130
    atexit(term_exit);
2131

    
2132
    fcntl(0, F_SETFL, O_NONBLOCK);
2133
}
2134

    
2135
static CharDriverState *qemu_chr_open_stdio(void)
2136
{
2137
    CharDriverState *chr;
2138

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

    
2146
    return chr;
2147
}
2148

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

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

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

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

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

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

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

    
2226
    cfsetispeed(&tty, spd);
2227
    cfsetospeed(&tty, spd);
2228

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

    
2263
    tcsetattr (fd, TCSANOW, &tty);
2264
}
2265

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2454
    qemu_chr_reset(chr);
2455

    
2456
    return chr;
2457
}
2458
#endif /* __linux__ */
2459

    
2460
#else /* _WIN32 */
2461

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

    
2470
#define NSENDBUF 2048
2471
#define NRECVBUF 2048
2472
#define MAXCONNECT 1
2473
#define NTIMEOUT 5000
2474

    
2475
static int win_chr_poll(void *opaque);
2476
static int win_chr_pipe_poll(void *opaque);
2477

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

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

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

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

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

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

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

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

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

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

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

    
2562
 fail:
2563
    win_chr_close(chr);
2564
    return -1;
2565
}
2566

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

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

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

    
2605
    s->max_size = qemu_chr_can_read(chr);
2606
    return s->max_size;
2607
}
2608

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

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

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

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

    
2635
    if (s->len > s->max_size)
2636
        s->len = s->max_size;
2637
    if (s->len == 0)
2638
        return;
2639

    
2640
    win_chr_readfile(chr);
2641
}
2642

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

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

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

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

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

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

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

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

    
2710
    s->fpipe = TRUE;
2711

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

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

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

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

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

    
2759
 fail:
2760
    win_chr_close(chr);
2761
    return -1;
2762
}
2763

    
2764

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

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

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

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

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

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

    
2816
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2817
{
2818
    HANDLE fd_out;
2819

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

    
2825
    return qemu_chr_open_win_file(fd_out);
2826
}
2827
#endif /* !_WIN32 */
2828

    
2829
/***********************************************************/
2830
/* UDP Net console */
2831

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

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

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

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

    
2854
    s->max_size = qemu_chr_can_read(chr);
2855

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2954
/***********************************************************/
2955
/* TCP Net console */
2956

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

    
2966
static void tcp_chr_accept(void *opaque);
2967

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

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

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

    
3004
    int i;
3005
    int j = 0;
3006

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3215
    if (fd < 0)
3216
        goto fail;
3217

    
3218
    if (!is_waitconnect)
3219
        socket_set_nonblock(fd);
3220

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

    
3227
    chr->opaque = s;
3228
    chr->chr_write = tcp_chr_write;
3229
    chr->chr_close = tcp_chr_close;
3230

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

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

    
3250
        ret = listen(fd, 0);
3251
        if (ret < 0)
3252
            goto fail;
3253

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

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

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

    
3301
CharDriverState *qemu_chr_open(const char *filename)
3302
{
3303
    const char *p;
3304

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

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

    
3378
/***********************************************************/
3379
/* network device redirectors */
3380

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

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

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

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

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

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

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

    
3466
    if (parse_host_port(haddr, host_str) < 0)
3467
        goto fail;
3468

    
3469
    if (!src_str || *src_str == '\0')
3470
        src_str = ":0";
3471

    
3472
    if (parse_host_port(saddr, src_str) < 0)
3473
        goto fail;
3474

    
3475
    free(str);
3476
    return(0);
3477

    
3478
fail:
3479
    free(str);
3480
    return -1;
3481
}
3482

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

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

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

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

    
3524
    memset(uaddr, 0, sizeof(*uaddr));
3525

    
3526
    uaddr->sun_family = AF_UNIX;
3527
    memcpy(uaddr->sun_path, str, len);
3528

    
3529
    return 0;
3530
}
3531
#endif
3532

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

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

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

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

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

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

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

    
3605
#if defined(CONFIG_SLIRP)
3606

    
3607
/* slirp network adapter */
3608

    
3609
static int slirp_inited;
3610
static VLANClientState *slirp_vc;
3611

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

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

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

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

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

    
3657
    if (!slirp_inited) {
3658
        slirp_inited = 1;
3659
        slirp_init();
3660
    }
3661

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

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

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

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

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

    
3701
#ifndef _WIN32
3702

    
3703
char smb_dir[1024];
3704

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

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

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

    
3735
    if (!slirp_inited) {
3736
        slirp_inited = 1;
3737
        slirp_init();
3738
    }
3739

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

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

    
3777
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3778
             SMBD_COMMAND, smb_conf);
3779

    
3780
    slirp_add_exec(0, smb_cmdline, 4, 139);
3781
}
3782

    
3783
#endif /* !defined(_WIN32) */
3784

    
3785
#endif /* CONFIG_SLIRP */
3786

    
3787
#if !defined(_WIN32)
3788

    
3789
typedef struct TAPState {
3790
    VLANClientState *vc;
3791
    int fd;
3792
} TAPState;
3793

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

    
3807
static void tap_send(void *opaque)
3808
{
3809
    TAPState *s = opaque;
3810
    uint8_t buf[4096];
3811
    int size;
3812

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

    
3827
/* fd support */
3828

    
3829
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3830
{
3831
    TAPState *s;
3832

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

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

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

    
3856
    fstat(fd, &s);
3857
    dev = devname(s.st_rdev, S_IFCHR);
3858
    pstrcpy(ifname, ifname_size, dev);
3859

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

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

    
3882
    memset(&ifr, 0x0, sizeof(ifr));
3883

    
3884
    if( *dev ){
3885
       ptr = dev;
3886
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
3887
       ppa = atoi(ptr);
3888
    }
3889

    
3890
    /* Check if IP device was opened */
3891
    if( ip_fd )
3892
       close(ip_fd);
3893

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

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

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

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

    
3924
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3925
        syslog(LOG_ERR, "Can't get flags\n");
3926

    
3927
    snprintf (actual_name, 32, "tap%d", ppa);
3928
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3929

    
3930
    ifr.lifr_ppa = ppa;
3931
    /* Assign ppa according to the unit number returned by tun device */
3932

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

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

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

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

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

    
3968
    close (if_fd);
3969

    
3970
    memset(&ifr, 0x0, sizeof(ifr));
3971
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3972
    ifr.lifr_ip_muxid  = ip_muxid;
3973
    ifr.lifr_arp_muxid = arp_muxid;
3974

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

    
3982
    sprintf(dev, "tap%d", ppa);
3983
    return tap_fd;
3984
}
3985

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

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

    
4027
static int net_tap_init(VLANState *vlan, const char *ifname1,
4028
                        const char *setup_script)
4029
{
4030
    TAPState *s;
4031
    int pid, status, fd;
4032
    char *args[3];
4033
    char **parg;
4034
    char ifname[128];
4035

    
4036
    if (ifname1 != NULL)
4037
        pstrcpy(ifname, sizeof(ifname), ifname1);
4038
    else
4039
        ifname[0] = '\0';
4040
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4041
    if (fd < 0)
4042
        return -1;
4043

    
4044
    if (!setup_script || !strcmp(setup_script, "no"))
4045
        setup_script = "";
4046
    if (setup_script[0] != '\0') {
4047
        /* try to launch network init script */
4048
        pid = fork();
4049
        if (pid >= 0) {
4050
            if (pid == 0) {
4051
                int open_max = sysconf (_SC_OPEN_MAX), i;
4052
                for (i = 0; i < open_max; i++)
4053
                    if (i != STDIN_FILENO &&
4054
                        i != STDOUT_FILENO &&
4055
                        i != STDERR_FILENO &&
4056
                        i != fd)
4057
                        close(i);
4058

    
4059
                parg = args;
4060
                *parg++ = (char *)setup_script;
4061
                *parg++ = ifname;
4062
                *parg++ = NULL;
4063
                execv(setup_script, args);
4064
                _exit(1);
4065
            }
4066
            while (waitpid(pid, &status, 0) != pid);
4067
            if (!WIFEXITED(status) ||
4068
                WEXITSTATUS(status) != 0) {
4069
                fprintf(stderr, "%s: could not launch network script\n",
4070
                        setup_script);
4071
                return -1;
4072
            }
4073
        }
4074
    }
4075
    s = net_tap_fd_init(vlan, fd);
4076
    if (!s)
4077
        return -1;
4078
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4079
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4080
    return 0;
4081
}
4082

    
4083
#endif /* !_WIN32 */
4084

    
4085
/* network connection */
4086
typedef struct NetSocketState {
4087
    VLANClientState *vc;
4088
    int fd;
4089
    int state; /* 0 = getting length, 1 = getting data */
4090
    int index;
4091
    int packet_len;
4092
    uint8_t buf[4096];
4093
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4094
} NetSocketState;
4095

    
4096
typedef struct NetSocketListenState {
4097
    VLANState *vlan;
4098
    int fd;
4099
} NetSocketListenState;
4100

    
4101
/* XXX: we consider we can send the whole packet without blocking */
4102
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4103
{
4104
    NetSocketState *s = opaque;
4105
    uint32_t len;
4106
    len = htonl(size);
4107

    
4108
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4109
    send_all(s->fd, buf, size);
4110
}
4111

    
4112
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4113
{
4114
    NetSocketState *s = opaque;
4115
    sendto(s->fd, buf, size, 0,
4116
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4117
}
4118

    
4119
static void net_socket_send(void *opaque)
4120
{
4121
    NetSocketState *s = opaque;
4122
    int l, size, err;
4123
    uint8_t buf1[4096];
4124
    const uint8_t *buf;
4125

    
4126
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4127
    if (size < 0) {
4128
        err = socket_error();
4129
        if (err != EWOULDBLOCK)
4130
            goto eoc;
4131
    } else if (size == 0) {
4132
        /* end of connection */
4133
    eoc:
4134
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4135
        closesocket(s->fd);
4136
        return;
4137
    }
4138
    buf = buf1;
4139
    while (size > 0) {
4140
        /* reassemble a packet from the network */
4141
        switch(s->state) {
4142
        case 0:
4143
            l = 4 - s->index;
4144
            if (l > size)
4145
                l = size;
4146
            memcpy(s->buf + s->index, buf, l);
4147
            buf += l;
4148
            size -= l;
4149
            s->index += l;
4150
            if (s->index == 4) {
4151
                /* got length */
4152
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4153
                s->index = 0;
4154
                s->state = 1;
4155
            }
4156
            break;
4157
        case 1:
4158
            l = s->packet_len - s->index;
4159
            if (l > size)
4160
                l = size;
4161
            memcpy(s->buf + s->index, buf, l);
4162
            s->index += l;
4163
            buf += l;
4164
            size -= l;
4165
            if (s->index >= s->packet_len) {
4166
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4167
                s->index = 0;
4168
                s->state = 0;
4169
            }
4170
            break;
4171
        }
4172
    }
4173
}
4174

    
4175
static void net_socket_send_dgram(void *opaque)
4176
{
4177
    NetSocketState *s = opaque;
4178
    int size;
4179

    
4180
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4181
    if (size < 0)
4182
        return;
4183
    if (size == 0) {
4184
        /* end of connection */
4185
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4186
        return;
4187
    }
4188
    qemu_send_packet(s->vc, s->buf, size);
4189
}
4190

    
4191
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4192
{
4193
    struct ip_mreq imr;
4194
    int fd;
4195
    int val, ret;
4196
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4197
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4198
                inet_ntoa(mcastaddr->sin_addr),
4199
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4200
        return -1;
4201

    
4202
    }
4203
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4204
    if (fd < 0) {
4205
        perror("socket(PF_INET, SOCK_DGRAM)");
4206
        return -1;
4207
    }
4208

    
4209
    val = 1;
4210
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4211
                   (const char *)&val, sizeof(val));
4212
    if (ret < 0) {
4213
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4214
        goto fail;
4215
    }
4216

    
4217
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4218
    if (ret < 0) {
4219
        perror("bind");
4220
        goto fail;
4221
    }
4222

    
4223
    /* Add host to multicast group */
4224
    imr.imr_multiaddr = mcastaddr->sin_addr;
4225
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4226

    
4227
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4228
                     (const char *)&imr, sizeof(struct ip_mreq));
4229
    if (ret < 0) {
4230
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4231
        goto fail;
4232
    }
4233

    
4234
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4235
    val = 1;
4236
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4237
                   (const char *)&val, sizeof(val));
4238
    if (ret < 0) {
4239
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4240
        goto fail;
4241
    }
4242

    
4243
    socket_set_nonblock(fd);
4244
    return fd;
4245
fail:
4246
    if (fd >= 0)
4247
        closesocket(fd);
4248
    return -1;
4249
}
4250

    
4251
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4252
                                          int is_connected)
4253
{
4254
    struct sockaddr_in saddr;
4255
    int newfd;
4256
    socklen_t saddr_len;
4257
    NetSocketState *s;
4258

    
4259
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4260
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4261
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4262
     */
4263

    
4264
    if (is_connected) {
4265
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4266
            /* must be bound */
4267
            if (saddr.sin_addr.s_addr==0) {
4268
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4269
                        fd);
4270
                return NULL;
4271
            }
4272
            /* clone dgram socket */
4273
            newfd = net_socket_mcast_create(&saddr);
4274
            if (newfd < 0) {
4275
                /* error already reported by net_socket_mcast_create() */
4276
                close(fd);
4277
                return NULL;
4278
            }
4279
            /* clone newfd to fd, close newfd */
4280
            dup2(newfd, fd);
4281
            close(newfd);
4282

    
4283
        } else {
4284
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4285
                    fd, strerror(errno));
4286
            return NULL;
4287
        }
4288
    }
4289

    
4290
    s = qemu_mallocz(sizeof(NetSocketState));
4291
    if (!s)
4292
        return NULL;
4293
    s->fd = fd;
4294

    
4295
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4296
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4297

    
4298
    /* mcast: save bound address as dst */
4299
    if (is_connected) s->dgram_dst=saddr;
4300

    
4301
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4302
            "socket: fd=%d (%s mcast=%s:%d)",
4303
            fd, is_connected? "cloned" : "",
4304
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4305
    return s;
4306
}
4307

    
4308
static void net_socket_connect(void *opaque)
4309
{
4310
    NetSocketState *s = opaque;
4311
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4312
}
4313

    
4314
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4315
                                          int is_connected)
4316
{
4317
    NetSocketState *s;
4318
    s = qemu_mallocz(sizeof(NetSocketState));
4319
    if (!s)
4320
        return NULL;
4321
    s->fd = fd;
4322
    s->vc = qemu_new_vlan_client(vlan,
4323
                                 net_socket_receive, NULL, s);
4324
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4325
             "socket: fd=%d", fd);
4326
    if (is_connected) {
4327
        net_socket_connect(s);
4328
    } else {
4329
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4330
    }
4331
    return s;
4332
}
4333

    
4334
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4335
                                          int is_connected)
4336
{
4337
    int so_type=-1, optlen=sizeof(so_type);
4338

    
4339
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4340
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4341
        return NULL;
4342
    }
4343
    switch(so_type) {
4344
    case SOCK_DGRAM:
4345
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4346
    case SOCK_STREAM:
4347
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4348
    default:
4349
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4350
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4351
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4352
    }
4353
    return NULL;
4354
}
4355

    
4356
static void net_socket_accept(void *opaque)
4357
{
4358
    NetSocketListenState *s = opaque;
4359
    NetSocketState *s1;
4360
    struct sockaddr_in saddr;
4361
    socklen_t len;
4362
    int fd;
4363

    
4364
    for(;;) {
4365
        len = sizeof(saddr);
4366
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4367
        if (fd < 0 && errno != EINTR) {
4368
            return;
4369
        } else if (fd >= 0) {
4370
            break;
4371
        }
4372
    }
4373
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4374
    if (!s1) {
4375
        closesocket(fd);
4376
    } else {
4377
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4378
                 "socket: connection from %s:%d",
4379
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4380
    }
4381
}
4382

    
4383
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4384
{
4385
    NetSocketListenState *s;
4386
    int fd, val, ret;
4387
    struct sockaddr_in saddr;
4388

    
4389
    if (parse_host_port(&saddr, host_str) < 0)
4390
        return -1;
4391

    
4392
    s = qemu_mallocz(sizeof(NetSocketListenState));
4393
    if (!s)
4394
        return -1;
4395

    
4396
    fd = socket(PF_INET, SOCK_STREAM, 0);
4397
    if (fd < 0) {
4398
        perror("socket");
4399
        return -1;
4400
    }
4401
    socket_set_nonblock(fd);
4402

    
4403
    /* allow fast reuse */
4404
    val = 1;
4405
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4406

    
4407
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4408
    if (ret < 0) {
4409
        perror("bind");
4410
        return -1;
4411
    }
4412
    ret = listen(fd, 0);
4413
    if (ret < 0) {
4414
        perror("listen");
4415
        return -1;
4416
    }
4417
    s->vlan = vlan;
4418
    s->fd = fd;
4419
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4420
    return 0;
4421
}
4422

    
4423
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4424
{
4425
    NetSocketState *s;
4426
    int fd, connected, ret, err;
4427
    struct sockaddr_in saddr;
4428

    
4429
    if (parse_host_port(&saddr, host_str) < 0)
4430
        return -1;
4431

    
4432
    fd = socket(PF_INET, SOCK_STREAM, 0);
4433
    if (fd < 0) {
4434
        perror("socket");
4435
        return -1;
4436
    }
4437
    socket_set_nonblock(fd);
4438

    
4439
    connected = 0;
4440
    for(;;) {
4441
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4442
        if (ret < 0) {
4443
            err = socket_error();
4444
            if (err == EINTR || err == EWOULDBLOCK) {
4445
            } else if (err == EINPROGRESS) {
4446
                break;
4447
#ifdef _WIN32
4448
            } else if (err == WSAEALREADY) {
4449
                break;
4450
#endif
4451
            } else {
4452
                perror("connect");
4453
                closesocket(fd);
4454
                return -1;
4455
            }
4456
        } else {
4457
            connected = 1;
4458
            break;
4459
        }
4460
    }
4461
    s = net_socket_fd_init(vlan, fd, connected);
4462
    if (!s)
4463
        return -1;
4464
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4465
             "socket: connect to %s:%d",
4466
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4467
    return 0;
4468
}
4469

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

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

    
4479

    
4480
    fd = net_socket_mcast_create(&saddr);
4481
    if (fd < 0)
4482
        return -1;
4483

    
4484
    s = net_socket_fd_init(vlan, fd, 0);
4485
    if (!s)
4486
        return -1;
4487

    
4488
    s->dgram_dst = saddr;
4489

    
4490
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4491
             "socket: mcast=%s:%d",
4492
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4493
    return 0;
4494

    
4495
}
4496

    
4497
static int get_param_value(char *buf, int buf_size,
4498
                           const char *tag, const char *str)
4499
{
4500
    const char *p;
4501
    char *q;
4502
    char option[128];
4503

    
4504
    p = str;
4505
    for(;;) {
4506
        q = option;
4507
        while (*p != '\0' && *p != '=') {
4508
            if ((q - option) < sizeof(option) - 1)
4509
                *q++ = *p;
4510
            p++;
4511
        }
4512
        *q = '\0';
4513
        if (*p != '=')
4514
            break;
4515
        p++;
4516
        if (!strcmp(tag, option)) {
4517
            q = buf;
4518
            while (*p != '\0' && *p != ',') {
4519
                if ((q - buf) < buf_size - 1)
4520
                    *q++ = *p;
4521
                p++;
4522
            }
4523
            *q = '\0';
4524
            return q - buf;
4525
        } else {
4526
            while (*p != '\0' && *p != ',') {
4527
                p++;
4528
            }
4529
        }
4530
        if (*p != ',')
4531
            break;
4532
        p++;
4533
    }
4534
    return 0;
4535
}
4536

    
4537
static int net_client_init(const char *str)
4538
{
4539
    const char *p;
4540
    char *q;
4541
    char device[64];
4542
    char buf[1024];
4543
    int vlan_id, ret;
4544
    VLANState *vlan;
4545

    
4546
    p = str;
4547
    q = device;
4548
    while (*p != '\0' && *p != ',') {
4549
        if ((q - device) < sizeof(device) - 1)
4550
            *q++ = *p;
4551
        p++;
4552
    }
4553
    *q = '\0';
4554
    if (*p == ',')
4555
        p++;
4556
    vlan_id = 0;
4557
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4558
        vlan_id = strtol(buf, NULL, 0);
4559
    }
4560
    vlan = qemu_find_vlan(vlan_id);
4561
    if (!vlan) {
4562
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4563
        return -1;
4564
    }
4565
    if (!strcmp(device, "nic")) {
4566
        NICInfo *nd;
4567
        uint8_t *macaddr;
4568

    
4569
        if (nb_nics >= MAX_NICS) {
4570
            fprintf(stderr, "Too Many NICs\n");
4571
            return -1;
4572
        }
4573
        nd = &nd_table[nb_nics];
4574
        macaddr = nd->macaddr;
4575
        macaddr[0] = 0x52;
4576
        macaddr[1] = 0x54;
4577
        macaddr[2] = 0x00;
4578
        macaddr[3] = 0x12;
4579
        macaddr[4] = 0x34;
4580
        macaddr[5] = 0x56 + nb_nics;
4581

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

    
4669
    return ret;
4670
}
4671

    
4672
void do_info_network(void)
4673
{
4674
    VLANState *vlan;
4675
    VLANClientState *vc;
4676

    
4677
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4678
        term_printf("VLAN %d devices:\n", vlan->id);
4679
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4680
            term_printf("  %s\n", vc->info_str);
4681
    }
4682
}
4683

    
4684
/***********************************************************/
4685
/* USB devices */
4686

    
4687
static USBPort *used_usb_ports;
4688
static USBPort *free_usb_ports;
4689

    
4690
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4691
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4692
                            usb_attachfn attach)
4693
{
4694
    port->opaque = opaque;
4695
    port->index = index;
4696
    port->attach = attach;
4697
    port->next = free_usb_ports;
4698
    free_usb_ports = port;
4699
}
4700

    
4701
static int usb_device_add(const char *devname)
4702
{
4703
    const char *p;
4704
    USBDevice *dev;
4705
    USBPort *port;
4706

    
4707
    if (!free_usb_ports)
4708
        return -1;
4709

    
4710
    if (strstart(devname, "host:", &p)) {
4711
        dev = usb_host_device_open(p);
4712
    } else if (!strcmp(devname, "mouse")) {
4713
        dev = usb_mouse_init();
4714
    } else if (!strcmp(devname, "tablet")) {
4715
        dev = usb_tablet_init();
4716
    } else if (!strcmp(devname, "keyboard")) {
4717
        dev = usb_keyboard_init();
4718
    } else if (strstart(devname, "disk:", &p)) {
4719
        dev = usb_msd_init(p);
4720
    } else if (!strcmp(devname, "wacom-tablet")) {
4721
        dev = usb_wacom_init();
4722
    } else {
4723
        return -1;
4724
    }
4725
    if (!dev)
4726
        return -1;
4727

    
4728
    /* Find a USB port to add the device to.  */
4729
    port = free_usb_ports;
4730
    if (!port->next) {
4731
        USBDevice *hub;
4732

    
4733
        /* Create a new hub and chain it on.  */
4734
        free_usb_ports = NULL;
4735
        port->next = used_usb_ports;
4736
        used_usb_ports = port;
4737

    
4738
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4739
        usb_attach(port, hub);
4740
        port = free_usb_ports;
4741
    }
4742

    
4743
    free_usb_ports = port->next;
4744
    port->next = used_usb_ports;
4745
    used_usb_ports = port;
4746
    usb_attach(port, dev);
4747
    return 0;
4748
}
4749

    
4750
static int usb_device_del(const char *devname)
4751
{
4752
    USBPort *port;
4753
    USBPort **lastp;
4754
    USBDevice *dev;
4755
    int bus_num, addr;
4756
    const char *p;
4757

    
4758
    if (!used_usb_ports)
4759
        return -1;
4760

    
4761
    p = strchr(devname, '.');
4762
    if (!p)
4763
        return -1;
4764
    bus_num = strtoul(devname, NULL, 0);
4765
    addr = strtoul(p + 1, NULL, 0);
4766
    if (bus_num != 0)
4767
        return -1;
4768

    
4769
    lastp = &used_usb_ports;
4770
    port = used_usb_ports;
4771
    while (port && port->dev->addr != addr) {
4772
        lastp = &port->next;
4773
        port = port->next;
4774
    }
4775

    
4776
    if (!port)
4777
        return -1;
4778

    
4779
    dev = port->dev;
4780
    *lastp = port->next;
4781
    usb_attach(port, NULL);
4782
    dev->handle_destroy(dev);
4783
    port->next = free_usb_ports;
4784
    free_usb_ports = port;
4785
    return 0;
4786
}
4787

    
4788
void do_usb_add(const char *devname)
4789
{
4790
    int ret;
4791
    ret = usb_device_add(devname);
4792
    if (ret < 0)
4793
        term_printf("Could not add USB device '%s'\n", devname);
4794
}
4795

    
4796
void do_usb_del(const char *devname)
4797
{
4798
    int ret;
4799
    ret = usb_device_del(devname);
4800
    if (ret < 0)
4801
        term_printf("Could not remove USB device '%s'\n", devname);
4802
}
4803

    
4804
void usb_info(void)
4805
{
4806
    USBDevice *dev;
4807
    USBPort *port;
4808
    const char *speed_str;
4809

    
4810
    if (!usb_enabled) {
4811
        term_printf("USB support not enabled\n");
4812
        return;
4813
    }
4814

    
4815
    for (port = used_usb_ports; port; port = port->next) {
4816
        dev = port->dev;
4817
        if (!dev)
4818
            continue;
4819
        switch(dev->speed) {
4820
        case USB_SPEED_LOW:
4821
            speed_str = "1.5";
4822
            break;
4823
        case USB_SPEED_FULL:
4824
            speed_str = "12";
4825
            break;
4826
        case USB_SPEED_HIGH:
4827
            speed_str = "480";
4828
            break;
4829
        default:
4830
            speed_str = "?";
4831
            break;
4832
        }
4833
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
4834
                    0, dev->addr, speed_str, dev->devname);
4835
    }
4836
}
4837

    
4838
/***********************************************************/
4839
/* PCMCIA/Cardbus */
4840

    
4841
static struct pcmcia_socket_entry_s {
4842
    struct pcmcia_socket_s *socket;
4843
    struct pcmcia_socket_entry_s *next;
4844
} *pcmcia_sockets = 0;
4845

    
4846
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4847
{
4848
    struct pcmcia_socket_entry_s *entry;
4849

    
4850
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4851
    entry->socket = socket;
4852
    entry->next = pcmcia_sockets;
4853
    pcmcia_sockets = entry;
4854
}
4855

    
4856
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4857
{
4858
    struct pcmcia_socket_entry_s *entry, **ptr;
4859

    
4860
    ptr = &pcmcia_sockets;
4861
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4862
        if (entry->socket == socket) {
4863
            *ptr = entry->next;
4864
            qemu_free(entry);
4865
        }
4866
}
4867

    
4868
void pcmcia_info(void)
4869
{
4870
    struct pcmcia_socket_entry_s *iter;
4871
    if (!pcmcia_sockets)
4872
        term_printf("No PCMCIA sockets\n");
4873

    
4874
    for (iter = pcmcia_sockets; iter; iter = iter->next)
4875
        term_printf("%s: %s\n", iter->socket->slot_string,
4876
                    iter->socket->attached ? iter->socket->card_string :
4877
                    "Empty");
4878
}
4879

    
4880
/***********************************************************/
4881
/* dumb display */
4882

    
4883
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4884
{
4885
}
4886

    
4887
static void dumb_resize(DisplayState *ds, int w, int h)
4888
{
4889
}
4890

    
4891
static void dumb_refresh(DisplayState *ds)
4892
{
4893
#if defined(CONFIG_SDL)
4894
    vga_hw_update();
4895
#endif
4896
}
4897

    
4898
static void dumb_display_init(DisplayState *ds)
4899
{
4900
    ds->data = NULL;
4901
    ds->linesize = 0;
4902
    ds->depth = 0;
4903
    ds->dpy_update = dumb_update;
4904
    ds->dpy_resize = dumb_resize;
4905
    ds->dpy_refresh = dumb_refresh;
4906
}
4907

    
4908
/***********************************************************/
4909
/* I/O handling */
4910

    
4911
#define MAX_IO_HANDLERS 64
4912

    
4913
typedef struct IOHandlerRecord {
4914
    int fd;
4915
    IOCanRWHandler *fd_read_poll;
4916
    IOHandler *fd_read;
4917
    IOHandler *fd_write;
4918
    int deleted;
4919
    void *opaque;
4920
    /* temporary data */
4921
    struct pollfd *ufd;
4922
    struct IOHandlerRecord *next;
4923
} IOHandlerRecord;
4924

    
4925
static IOHandlerRecord *first_io_handler;
4926

    
4927
/* XXX: fd_read_poll should be suppressed, but an API change is
4928
   necessary in the character devices to suppress fd_can_read(). */
4929
int qemu_set_fd_handler2(int fd,
4930
                         IOCanRWHandler *fd_read_poll,
4931
                         IOHandler *fd_read,
4932
                         IOHandler *fd_write,
4933
                         void *opaque)
4934
{
4935
    IOHandlerRecord **pioh, *ioh;
4936

    
4937
    if (!fd_read && !fd_write) {
4938
        pioh = &first_io_handler;
4939
        for(;;) {
4940
            ioh = *pioh;
4941
            if (ioh == NULL)
4942
                break;
4943
            if (ioh->fd == fd) {
4944
                ioh->deleted = 1;
4945
                break;
4946
            }
4947
            pioh = &ioh->next;
4948
        }
4949
    } else {
4950
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4951
            if (ioh->fd == fd)
4952
                goto found;
4953
        }
4954
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4955
        if (!ioh)
4956
            return -1;
4957
        ioh->next = first_io_handler;
4958
        first_io_handler = ioh;
4959
    found:
4960
        ioh->fd = fd;
4961
        ioh->fd_read_poll = fd_read_poll;
4962
        ioh->fd_read = fd_read;
4963
        ioh->fd_write = fd_write;
4964
        ioh->opaque = opaque;
4965
        ioh->deleted = 0;
4966
    }
4967
    return 0;
4968
}
4969

    
4970
int qemu_set_fd_handler(int fd,
4971
                        IOHandler *fd_read,