Statistics
| Branch: | Revision:

root / vl.c @ 48d7c50f

History | View | Annotate | Download (240.2 kB)

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

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

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

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

    
85
#include <linux/ppdev.h>
86
#include <linux/parport.h>
87
#else
88
#include <sys/stat.h>
89
#include <sys/ethernet.h>
90
#include <sys/sockio.h>
91
#include <netinet/arp.h>
92
#include <netinet/in.h>
93
#include <netinet/in_systm.h>
94
#include <netinet/ip.h>
95
#include <netinet/ip_icmp.h> // must come after ip.h
96
#include <netinet/udp.h>
97
#include <netinet/tcp.h>
98
#include <net/if.h>
99
#include <syslog.h>
100
#include <stropts.h>
101
#endif
102
#endif
103
#endif
104

    
105
#include "qemu_socket.h"
106

    
107
#if defined(CONFIG_SLIRP)
108
#include "libslirp.h"
109
#endif
110

    
111
#if defined(__OpenBSD__)
112
#include <util.h>
113
#endif
114

    
115
#if defined(CONFIG_VDE)
116
#include <libvdeplug.h>
117
#endif
118

    
119
#ifdef _WIN32
120
#include <malloc.h>
121
#include <sys/timeb.h>
122
#include <mmsystem.h>
123
#define getopt_long_only getopt_long
124
#define memalign(align, size) malloc(size)
125
#endif
126

    
127
#ifdef CONFIG_SDL
128
#ifdef __APPLE__
129
#include <SDL/SDL.h>
130
#endif
131
#endif /* CONFIG_SDL */
132

    
133
#ifdef CONFIG_COCOA
134
#undef main
135
#define main qemu_main
136
#endif /* CONFIG_COCOA */
137

    
138
#include "disas.h"
139

    
140
#include "exec-all.h"
141

    
142
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
143
#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
144
#ifdef __sun__
145
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
146
#else
147
#define SMBD_COMMAND "/usr/sbin/smbd"
148
#endif
149

    
150
//#define DEBUG_UNUSED_IOPORT
151
//#define DEBUG_IOPORT
152

    
153
#ifdef TARGET_PPC
154
#define DEFAULT_RAM_SIZE 144
155
#else
156
#define DEFAULT_RAM_SIZE 128
157
#endif
158

    
159
/* Max number of USB devices that can be specified on the commandline.  */
160
#define MAX_USB_CMDLINE 8
161

    
162
/* XXX: use a two level table to limit memory usage */
163
#define MAX_IOPORTS 65536
164

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

    
245
static CPUState *cur_cpu;
246
static CPUState *next_cpu;
247
static int event_pending = 1;
248
/* Conversion factor from emulated instructions to virtual clock ticks.  */
249
static int icount_time_shift;
250
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
251
#define MAX_ICOUNT_SHIFT 10
252
/* Compensate for varying guest execution speed.  */
253
static int64_t qemu_icount_bias;
254
QEMUTimer *icount_rt_timer;
255
QEMUTimer *icount_vm_timer;
256

    
257
uint8_t qemu_uuid[16];
258

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

    
261
/***********************************************************/
262
/* x86 ISA bus support */
263

    
264
target_phys_addr_t isa_mem_base = 0;
265
PicState2 *isa_pic;
266

    
267
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
268
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
269

    
270
static uint32_t ioport_read(int index, uint32_t address)
271
{
272
    static IOPortReadFunc *default_func[3] = {
273
        default_ioport_readb,
274
        default_ioport_readw,
275
        default_ioport_readl
276
    };
277
    IOPortReadFunc *func = ioport_read_table[index][address];
278
    if (!func)
279
        func = default_func[index];
280
    return func(ioport_opaque[address], address);
281
}
282

    
283
static void ioport_write(int index, uint32_t address, uint32_t data)
284
{
285
    static IOPortWriteFunc *default_func[3] = {
286
        default_ioport_writeb,
287
        default_ioport_writew,
288
        default_ioport_writel
289
    };
290
    IOPortWriteFunc *func = ioport_write_table[index][address];
291
    if (!func)
292
        func = default_func[index];
293
    func(ioport_opaque[address], address, data);
294
}
295

    
296
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
297
{
298
#ifdef DEBUG_UNUSED_IOPORT
299
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
300
#endif
301
    return 0xff;
302
}
303

    
304
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
305
{
306
#ifdef DEBUG_UNUSED_IOPORT
307
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
308
#endif
309
}
310

    
311
/* default is to make two byte accesses */
312
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
313
{
314
    uint32_t data;
315
    data = ioport_read(0, address);
316
    address = (address + 1) & (MAX_IOPORTS - 1);
317
    data |= ioport_read(0, address) << 8;
318
    return data;
319
}
320

    
321
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
322
{
323
    ioport_write(0, address, data & 0xff);
324
    address = (address + 1) & (MAX_IOPORTS - 1);
325
    ioport_write(0, address, (data >> 8) & 0xff);
326
}
327

    
328
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
329
{
330
#ifdef DEBUG_UNUSED_IOPORT
331
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
332
#endif
333
    return 0xffffffff;
334
}
335

    
336
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
337
{
338
#ifdef DEBUG_UNUSED_IOPORT
339
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
340
#endif
341
}
342

    
343
/* size is the word size in byte */
344
int register_ioport_read(int start, int length, int size,
345
                         IOPortReadFunc *func, void *opaque)
346
{
347
    int i, bsize;
348

    
349
    if (size == 1) {
350
        bsize = 0;
351
    } else if (size == 2) {
352
        bsize = 1;
353
    } else if (size == 4) {
354
        bsize = 2;
355
    } else {
356
        hw_error("register_ioport_read: invalid size");
357
        return -1;
358
    }
359
    for(i = start; i < start + length; i += size) {
360
        ioport_read_table[bsize][i] = func;
361
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
362
            hw_error("register_ioport_read: invalid opaque");
363
        ioport_opaque[i] = opaque;
364
    }
365
    return 0;
366
}
367

    
368
/* size is the word size in byte */
369
int register_ioport_write(int start, int length, int size,
370
                          IOPortWriteFunc *func, void *opaque)
371
{
372
    int i, bsize;
373

    
374
    if (size == 1) {
375
        bsize = 0;
376
    } else if (size == 2) {
377
        bsize = 1;
378
    } else if (size == 4) {
379
        bsize = 2;
380
    } else {
381
        hw_error("register_ioport_write: invalid size");
382
        return -1;
383
    }
384
    for(i = start; i < start + length; i += size) {
385
        ioport_write_table[bsize][i] = func;
386
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
387
            hw_error("register_ioport_write: invalid opaque");
388
        ioport_opaque[i] = opaque;
389
    }
390
    return 0;
391
}
392

    
393
void isa_unassign_ioport(int start, int length)
394
{
395
    int i;
396

    
397
    for(i = start; i < start + length; i++) {
398
        ioport_read_table[0][i] = default_ioport_readb;
399
        ioport_read_table[1][i] = default_ioport_readw;
400
        ioport_read_table[2][i] = default_ioport_readl;
401

    
402
        ioport_write_table[0][i] = default_ioport_writeb;
403
        ioport_write_table[1][i] = default_ioport_writew;
404
        ioport_write_table[2][i] = default_ioport_writel;
405
    }
406
}
407

    
408
/***********************************************************/
409

    
410
void cpu_outb(CPUState *env, int addr, int val)
411
{
412
#ifdef DEBUG_IOPORT
413
    if (loglevel & CPU_LOG_IOPORT)
414
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
415
#endif
416
    ioport_write(0, addr, val);
417
#ifdef USE_KQEMU
418
    if (env)
419
        env->last_io_time = cpu_get_time_fast();
420
#endif
421
}
422

    
423
void cpu_outw(CPUState *env, int addr, int val)
424
{
425
#ifdef DEBUG_IOPORT
426
    if (loglevel & CPU_LOG_IOPORT)
427
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
428
#endif
429
    ioport_write(1, addr, val);
430
#ifdef USE_KQEMU
431
    if (env)
432
        env->last_io_time = cpu_get_time_fast();
433
#endif
434
}
435

    
436
void cpu_outl(CPUState *env, int addr, int val)
437
{
438
#ifdef DEBUG_IOPORT
439
    if (loglevel & CPU_LOG_IOPORT)
440
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
441
#endif
442
    ioport_write(2, addr, val);
443
#ifdef USE_KQEMU
444
    if (env)
445
        env->last_io_time = cpu_get_time_fast();
446
#endif
447
}
448

    
449
int cpu_inb(CPUState *env, int addr)
450
{
451
    int val;
452
    val = ioport_read(0, addr);
453
#ifdef DEBUG_IOPORT
454
    if (loglevel & CPU_LOG_IOPORT)
455
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
456
#endif
457
#ifdef USE_KQEMU
458
    if (env)
459
        env->last_io_time = cpu_get_time_fast();
460
#endif
461
    return val;
462
}
463

    
464
int cpu_inw(CPUState *env, int addr)
465
{
466
    int val;
467
    val = ioport_read(1, addr);
468
#ifdef DEBUG_IOPORT
469
    if (loglevel & CPU_LOG_IOPORT)
470
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
471
#endif
472
#ifdef USE_KQEMU
473
    if (env)
474
        env->last_io_time = cpu_get_time_fast();
475
#endif
476
    return val;
477
}
478

    
479
int cpu_inl(CPUState *env, int addr)
480
{
481
    int val;
482
    val = ioport_read(2, addr);
483
#ifdef DEBUG_IOPORT
484
    if (loglevel & CPU_LOG_IOPORT)
485
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
486
#endif
487
#ifdef USE_KQEMU
488
    if (env)
489
        env->last_io_time = cpu_get_time_fast();
490
#endif
491
    return val;
492
}
493

    
494
/***********************************************************/
495
void hw_error(const char *fmt, ...)
496
{
497
    va_list ap;
498
    CPUState *env;
499

    
500
    va_start(ap, fmt);
501
    fprintf(stderr, "qemu: hardware error: ");
502
    vfprintf(stderr, fmt, ap);
503
    fprintf(stderr, "\n");
504
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
505
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
506
#ifdef TARGET_I386
507
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
508
#else
509
        cpu_dump_state(env, stderr, fprintf, 0);
510
#endif
511
    }
512
    va_end(ap);
513
    abort();
514
}
515

    
516
/***********************************************************/
517
/* keyboard/mouse */
518

    
519
static QEMUPutKBDEvent *qemu_put_kbd_event;
520
static void *qemu_put_kbd_event_opaque;
521
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
522
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
523

    
524
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
525
{
526
    qemu_put_kbd_event_opaque = opaque;
527
    qemu_put_kbd_event = func;
528
}
529

    
530
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
531
                                                void *opaque, int absolute,
532
                                                const char *name)
533
{
534
    QEMUPutMouseEntry *s, *cursor;
535

    
536
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
537
    if (!s)
538
        return NULL;
539

    
540
    s->qemu_put_mouse_event = func;
541
    s->qemu_put_mouse_event_opaque = opaque;
542
    s->qemu_put_mouse_event_absolute = absolute;
543
    s->qemu_put_mouse_event_name = qemu_strdup(name);
544
    s->next = NULL;
545

    
546
    if (!qemu_put_mouse_event_head) {
547
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
548
        return s;
549
    }
550

    
551
    cursor = qemu_put_mouse_event_head;
552
    while (cursor->next != NULL)
553
        cursor = cursor->next;
554

    
555
    cursor->next = s;
556
    qemu_put_mouse_event_current = s;
557

    
558
    return s;
559
}
560

    
561
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
562
{
563
    QEMUPutMouseEntry *prev = NULL, *cursor;
564

    
565
    if (!qemu_put_mouse_event_head || entry == NULL)
566
        return;
567

    
568
    cursor = qemu_put_mouse_event_head;
569
    while (cursor != NULL && cursor != entry) {
570
        prev = cursor;
571
        cursor = cursor->next;
572
    }
573

    
574
    if (cursor == NULL) // does not exist or list empty
575
        return;
576
    else if (prev == NULL) { // entry is head
577
        qemu_put_mouse_event_head = cursor->next;
578
        if (qemu_put_mouse_event_current == entry)
579
            qemu_put_mouse_event_current = cursor->next;
580
        qemu_free(entry->qemu_put_mouse_event_name);
581
        qemu_free(entry);
582
        return;
583
    }
584

    
585
    prev->next = entry->next;
586

    
587
    if (qemu_put_mouse_event_current == entry)
588
        qemu_put_mouse_event_current = prev;
589

    
590
    qemu_free(entry->qemu_put_mouse_event_name);
591
    qemu_free(entry);
592
}
593

    
594
void kbd_put_keycode(int keycode)
595
{
596
    if (qemu_put_kbd_event) {
597
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
598
    }
599
}
600

    
601
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
602
{
603
    QEMUPutMouseEvent *mouse_event;
604
    void *mouse_event_opaque;
605
    int width;
606

    
607
    if (!qemu_put_mouse_event_current) {
608
        return;
609
    }
610

    
611
    mouse_event =
612
        qemu_put_mouse_event_current->qemu_put_mouse_event;
613
    mouse_event_opaque =
614
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
615

    
616
    if (mouse_event) {
617
        if (graphic_rotate) {
618
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
619
                width = 0x7fff;
620
            else
621
                width = graphic_width - 1;
622
            mouse_event(mouse_event_opaque,
623
                                 width - dy, dx, dz, buttons_state);
624
        } else
625
            mouse_event(mouse_event_opaque,
626
                                 dx, dy, dz, buttons_state);
627
    }
628
}
629

    
630
int kbd_mouse_is_absolute(void)
631
{
632
    if (!qemu_put_mouse_event_current)
633
        return 0;
634

    
635
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
636
}
637

    
638
void do_info_mice(void)
639
{
640
    QEMUPutMouseEntry *cursor;
641
    int index = 0;
642

    
643
    if (!qemu_put_mouse_event_head) {
644
        term_printf("No mouse devices connected\n");
645
        return;
646
    }
647

    
648
    term_printf("Mouse devices available:\n");
649
    cursor = qemu_put_mouse_event_head;
650
    while (cursor != NULL) {
651
        term_printf("%c Mouse #%d: %s\n",
652
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
653
                    index, cursor->qemu_put_mouse_event_name);
654
        index++;
655
        cursor = cursor->next;
656
    }
657
}
658

    
659
void do_mouse_set(int index)
660
{
661
    QEMUPutMouseEntry *cursor;
662
    int i = 0;
663

    
664
    if (!qemu_put_mouse_event_head) {
665
        term_printf("No mouse devices connected\n");
666
        return;
667
    }
668

    
669
    cursor = qemu_put_mouse_event_head;
670
    while (cursor != NULL && index != i) {
671
        i++;
672
        cursor = cursor->next;
673
    }
674

    
675
    if (cursor != NULL)
676
        qemu_put_mouse_event_current = cursor;
677
    else
678
        term_printf("Mouse at given index not found\n");
679
}
680

    
681
/* compute with 96 bit intermediate result: (a*b)/c */
682
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
683
{
684
    union {
685
        uint64_t ll;
686
        struct {
687
#ifdef WORDS_BIGENDIAN
688
            uint32_t high, low;
689
#else
690
            uint32_t low, high;
691
#endif
692
        } l;
693
    } u, res;
694
    uint64_t rl, rh;
695

    
696
    u.ll = a;
697
    rl = (uint64_t)u.l.low * (uint64_t)b;
698
    rh = (uint64_t)u.l.high * (uint64_t)b;
699
    rh += (rl >> 32);
700
    res.l.high = rh / c;
701
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
702
    return res.ll;
703
}
704

    
705
/***********************************************************/
706
/* real time host monotonic timer */
707

    
708
#define QEMU_TIMER_BASE 1000000000LL
709

    
710
#ifdef WIN32
711

    
712
static int64_t clock_freq;
713

    
714
static void init_get_clock(void)
715
{
716
    LARGE_INTEGER freq;
717
    int ret;
718
    ret = QueryPerformanceFrequency(&freq);
719
    if (ret == 0) {
720
        fprintf(stderr, "Could not calibrate ticks\n");
721
        exit(1);
722
    }
723
    clock_freq = freq.QuadPart;
724
}
725

    
726
static int64_t get_clock(void)
727
{
728
    LARGE_INTEGER ti;
729
    QueryPerformanceCounter(&ti);
730
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
731
}
732

    
733
#else
734

    
735
static int use_rt_clock;
736

    
737
static void init_get_clock(void)
738
{
739
    use_rt_clock = 0;
740
#if defined(__linux__)
741
    {
742
        struct timespec ts;
743
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
744
            use_rt_clock = 1;
745
        }
746
    }
747
#endif
748
}
749

    
750
static int64_t get_clock(void)
751
{
752
#if defined(__linux__)
753
    if (use_rt_clock) {
754
        struct timespec ts;
755
        clock_gettime(CLOCK_MONOTONIC, &ts);
756
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
757
    } else
758
#endif
759
    {
760
        /* XXX: using gettimeofday leads to problems if the date
761
           changes, so it should be avoided. */
762
        struct timeval tv;
763
        gettimeofday(&tv, NULL);
764
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
765
    }
766
}
767
#endif
768

    
769
/* Return the virtual CPU time, based on the instruction counter.  */
770
static int64_t cpu_get_icount(void)
771
{
772
    int64_t icount;
773
    CPUState *env = cpu_single_env;;
774
    icount = qemu_icount;
775
    if (env) {
776
        if (!can_do_io(env))
777
            fprintf(stderr, "Bad clock read\n");
778
        icount -= (env->icount_decr.u16.low + env->icount_extra);
779
    }
780
    return qemu_icount_bias + (icount << icount_time_shift);
781
}
782

    
783
/***********************************************************/
784
/* guest cycle counter */
785

    
786
static int64_t cpu_ticks_prev;
787
static int64_t cpu_ticks_offset;
788
static int64_t cpu_clock_offset;
789
static int cpu_ticks_enabled;
790

    
791
/* return the host CPU cycle counter and handle stop/restart */
792
int64_t cpu_get_ticks(void)
793
{
794
    if (use_icount) {
795
        return cpu_get_icount();
796
    }
797
    if (!cpu_ticks_enabled) {
798
        return cpu_ticks_offset;
799
    } else {
800
        int64_t ticks;
801
        ticks = cpu_get_real_ticks();
802
        if (cpu_ticks_prev > ticks) {
803
            /* Note: non increasing ticks may happen if the host uses
804
               software suspend */
805
            cpu_ticks_offset += cpu_ticks_prev - ticks;
806
        }
807
        cpu_ticks_prev = ticks;
808
        return ticks + cpu_ticks_offset;
809
    }
810
}
811

    
812
/* return the host CPU monotonic timer and handle stop/restart */
813
static int64_t cpu_get_clock(void)
814
{
815
    int64_t ti;
816
    if (!cpu_ticks_enabled) {
817
        return cpu_clock_offset;
818
    } else {
819
        ti = get_clock();
820
        return ti + cpu_clock_offset;
821
    }
822
}
823

    
824
/* enable cpu_get_ticks() */
825
void cpu_enable_ticks(void)
826
{
827
    if (!cpu_ticks_enabled) {
828
        cpu_ticks_offset -= cpu_get_real_ticks();
829
        cpu_clock_offset -= get_clock();
830
        cpu_ticks_enabled = 1;
831
    }
832
}
833

    
834
/* disable cpu_get_ticks() : the clock is stopped. You must not call
835
   cpu_get_ticks() after that.  */
836
void cpu_disable_ticks(void)
837
{
838
    if (cpu_ticks_enabled) {
839
        cpu_ticks_offset = cpu_get_ticks();
840
        cpu_clock_offset = cpu_get_clock();
841
        cpu_ticks_enabled = 0;
842
    }
843
}
844

    
845
/***********************************************************/
846
/* timers */
847

    
848
#define QEMU_TIMER_REALTIME 0
849
#define QEMU_TIMER_VIRTUAL  1
850

    
851
struct QEMUClock {
852
    int type;
853
    /* XXX: add frequency */
854
};
855

    
856
struct QEMUTimer {
857
    QEMUClock *clock;
858
    int64_t expire_time;
859
    QEMUTimerCB *cb;
860
    void *opaque;
861
    struct QEMUTimer *next;
862
};
863

    
864
struct qemu_alarm_timer {
865
    char const *name;
866
    unsigned int flags;
867

    
868
    int (*start)(struct qemu_alarm_timer *t);
869
    void (*stop)(struct qemu_alarm_timer *t);
870
    void (*rearm)(struct qemu_alarm_timer *t);
871
    void *priv;
872
};
873

    
874
#define ALARM_FLAG_DYNTICKS  0x1
875
#define ALARM_FLAG_EXPIRED   0x2
876

    
877
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
878
{
879
    return t->flags & ALARM_FLAG_DYNTICKS;
880
}
881

    
882
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
883
{
884
    if (!alarm_has_dynticks(t))
885
        return;
886

    
887
    t->rearm(t);
888
}
889

    
890
/* TODO: MIN_TIMER_REARM_US should be optimized */
891
#define MIN_TIMER_REARM_US 250
892

    
893
static struct qemu_alarm_timer *alarm_timer;
894

    
895
#ifdef _WIN32
896

    
897
struct qemu_alarm_win32 {
898
    MMRESULT timerId;
899
    HANDLE host_alarm;
900
    unsigned int period;
901
} alarm_win32_data = {0, NULL, -1};
902

    
903
static int win32_start_timer(struct qemu_alarm_timer *t);
904
static void win32_stop_timer(struct qemu_alarm_timer *t);
905
static void win32_rearm_timer(struct qemu_alarm_timer *t);
906

    
907
#else
908

    
909
static int unix_start_timer(struct qemu_alarm_timer *t);
910
static void unix_stop_timer(struct qemu_alarm_timer *t);
911

    
912
#ifdef __linux__
913

    
914
static int dynticks_start_timer(struct qemu_alarm_timer *t);
915
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
916
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
917

    
918
static int hpet_start_timer(struct qemu_alarm_timer *t);
919
static void hpet_stop_timer(struct qemu_alarm_timer *t);
920

    
921
static int rtc_start_timer(struct qemu_alarm_timer *t);
922
static void rtc_stop_timer(struct qemu_alarm_timer *t);
923

    
924
#endif /* __linux__ */
925

    
926
#endif /* _WIN32 */
927

    
928
/* Correlation between real and virtual time is always going to be
929
   fairly approximate, so ignore small variation.
930
   When the guest is idle real and virtual time will be aligned in
931
   the IO wait loop.  */
932
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
933

    
934
static void icount_adjust(void)
935
{
936
    int64_t cur_time;
937
    int64_t cur_icount;
938
    int64_t delta;
939
    static int64_t last_delta;
940
    /* If the VM is not running, then do nothing.  */
941
    if (!vm_running)
942
        return;
943

    
944
    cur_time = cpu_get_clock();
945
    cur_icount = qemu_get_clock(vm_clock);
946
    delta = cur_icount - cur_time;
947
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
948
    if (delta > 0
949
        && last_delta + ICOUNT_WOBBLE < delta * 2
950
        && icount_time_shift > 0) {
951
        /* The guest is getting too far ahead.  Slow time down.  */
952
        icount_time_shift--;
953
    }
954
    if (delta < 0
955
        && last_delta - ICOUNT_WOBBLE > delta * 2
956
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
957
        /* The guest is getting too far behind.  Speed time up.  */
958
        icount_time_shift++;
959
    }
960
    last_delta = delta;
961
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
962
}
963

    
964
static void icount_adjust_rt(void * opaque)
965
{
966
    qemu_mod_timer(icount_rt_timer,
967
                   qemu_get_clock(rt_clock) + 1000);
968
    icount_adjust();
969
}
970

    
971
static void icount_adjust_vm(void * opaque)
972
{
973
    qemu_mod_timer(icount_vm_timer,
974
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
975
    icount_adjust();
976
}
977

    
978
static void init_icount_adjust(void)
979
{
980
    /* Have both realtime and virtual time triggers for speed adjustment.
981
       The realtime trigger catches emulated time passing too slowly,
982
       the virtual time trigger catches emulated time passing too fast.
983
       Realtime triggers occur even when idle, so use them less frequently
984
       than VM triggers.  */
985
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
986
    qemu_mod_timer(icount_rt_timer,
987
                   qemu_get_clock(rt_clock) + 1000);
988
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
989
    qemu_mod_timer(icount_vm_timer,
990
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
991
}
992

    
993
static struct qemu_alarm_timer alarm_timers[] = {
994
#ifndef _WIN32
995
#ifdef __linux__
996
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
997
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
998
    /* HPET - if available - is preferred */
999
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1000
    /* ...otherwise try RTC */
1001
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1002
#endif
1003
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1004
#else
1005
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1006
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1007
    {"win32", 0, win32_start_timer,
1008
     win32_stop_timer, NULL, &alarm_win32_data},
1009
#endif
1010
    {NULL, }
1011
};
1012

    
1013
static void show_available_alarms(void)
1014
{
1015
    int i;
1016

    
1017
    printf("Available alarm timers, in order of precedence:\n");
1018
    for (i = 0; alarm_timers[i].name; i++)
1019
        printf("%s\n", alarm_timers[i].name);
1020
}
1021

    
1022
static void configure_alarms(char const *opt)
1023
{
1024
    int i;
1025
    int cur = 0;
1026
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1027
    char *arg;
1028
    char *name;
1029
    struct qemu_alarm_timer tmp;
1030

    
1031
    if (!strcmp(opt, "?")) {
1032
        show_available_alarms();
1033
        exit(0);
1034
    }
1035

    
1036
    arg = strdup(opt);
1037

    
1038
    /* Reorder the array */
1039
    name = strtok(arg, ",");
1040
    while (name) {
1041
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1042
            if (!strcmp(alarm_timers[i].name, name))
1043
                break;
1044
        }
1045

    
1046
        if (i == count) {
1047
            fprintf(stderr, "Unknown clock %s\n", name);
1048
            goto next;
1049
        }
1050

    
1051
        if (i < cur)
1052
            /* Ignore */
1053
            goto next;
1054

    
1055
        /* Swap */
1056
        tmp = alarm_timers[i];
1057
        alarm_timers[i] = alarm_timers[cur];
1058
        alarm_timers[cur] = tmp;
1059

    
1060
        cur++;
1061
next:
1062
        name = strtok(NULL, ",");
1063
    }
1064

    
1065
    free(arg);
1066

    
1067
    if (cur) {
1068
        /* Disable remaining timers */
1069
        for (i = cur; i < count; i++)
1070
            alarm_timers[i].name = NULL;
1071
    } else {
1072
        show_available_alarms();
1073
        exit(1);
1074
    }
1075
}
1076

    
1077
QEMUClock *rt_clock;
1078
QEMUClock *vm_clock;
1079

    
1080
static QEMUTimer *active_timers[2];
1081

    
1082
static QEMUClock *qemu_new_clock(int type)
1083
{
1084
    QEMUClock *clock;
1085
    clock = qemu_mallocz(sizeof(QEMUClock));
1086
    if (!clock)
1087
        return NULL;
1088
    clock->type = type;
1089
    return clock;
1090
}
1091

    
1092
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1093
{
1094
    QEMUTimer *ts;
1095

    
1096
    ts = qemu_mallocz(sizeof(QEMUTimer));
1097
    ts->clock = clock;
1098
    ts->cb = cb;
1099
    ts->opaque = opaque;
1100
    return ts;
1101
}
1102

    
1103
void qemu_free_timer(QEMUTimer *ts)
1104
{
1105
    qemu_free(ts);
1106
}
1107

    
1108
/* stop a timer, but do not dealloc it */
1109
void qemu_del_timer(QEMUTimer *ts)
1110
{
1111
    QEMUTimer **pt, *t;
1112

    
1113
    /* NOTE: this code must be signal safe because
1114
       qemu_timer_expired() can be called from a signal. */
1115
    pt = &active_timers[ts->clock->type];
1116
    for(;;) {
1117
        t = *pt;
1118
        if (!t)
1119
            break;
1120
        if (t == ts) {
1121
            *pt = t->next;
1122
            break;
1123
        }
1124
        pt = &t->next;
1125
    }
1126
}
1127

    
1128
/* modify the current timer so that it will be fired when current_time
1129
   >= expire_time. The corresponding callback will be called. */
1130
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1131
{
1132
    QEMUTimer **pt, *t;
1133

    
1134
    qemu_del_timer(ts);
1135

    
1136
    /* add the timer in the sorted list */
1137
    /* NOTE: this code must be signal safe because
1138
       qemu_timer_expired() can be called from a signal. */
1139
    pt = &active_timers[ts->clock->type];
1140
    for(;;) {
1141
        t = *pt;
1142
        if (!t)
1143
            break;
1144
        if (t->expire_time > expire_time)
1145
            break;
1146
        pt = &t->next;
1147
    }
1148
    ts->expire_time = expire_time;
1149
    ts->next = *pt;
1150
    *pt = ts;
1151

    
1152
    /* Rearm if necessary  */
1153
    if (pt == &active_timers[ts->clock->type]) {
1154
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1155
            qemu_rearm_alarm_timer(alarm_timer);
1156
        }
1157
        /* Interrupt execution to force deadline recalculation.  */
1158
        if (use_icount && cpu_single_env) {
1159
            cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1160
        }
1161
    }
1162
}
1163

    
1164
int qemu_timer_pending(QEMUTimer *ts)
1165
{
1166
    QEMUTimer *t;
1167
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1168
        if (t == ts)
1169
            return 1;
1170
    }
1171
    return 0;
1172
}
1173

    
1174
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1175
{
1176
    if (!timer_head)
1177
        return 0;
1178
    return (timer_head->expire_time <= current_time);
1179
}
1180

    
1181
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1182
{
1183
    QEMUTimer *ts;
1184

    
1185
    for(;;) {
1186
        ts = *ptimer_head;
1187
        if (!ts || ts->expire_time > current_time)
1188
            break;
1189
        /* remove timer from the list before calling the callback */
1190
        *ptimer_head = ts->next;
1191
        ts->next = NULL;
1192

    
1193
        /* run the callback (the timer list can be modified) */
1194
        ts->cb(ts->opaque);
1195
    }
1196
}
1197

    
1198
int64_t qemu_get_clock(QEMUClock *clock)
1199
{
1200
    switch(clock->type) {
1201
    case QEMU_TIMER_REALTIME:
1202
        return get_clock() / 1000000;
1203
    default:
1204
    case QEMU_TIMER_VIRTUAL:
1205
        if (use_icount) {
1206
            return cpu_get_icount();
1207
        } else {
1208
            return cpu_get_clock();
1209
        }
1210
    }
1211
}
1212

    
1213
static void init_timers(void)
1214
{
1215
    init_get_clock();
1216
    ticks_per_sec = QEMU_TIMER_BASE;
1217
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1218
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1219
}
1220

    
1221
/* save a timer */
1222
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1223
{
1224
    uint64_t expire_time;
1225

    
1226
    if (qemu_timer_pending(ts)) {
1227
        expire_time = ts->expire_time;
1228
    } else {
1229
        expire_time = -1;
1230
    }
1231
    qemu_put_be64(f, expire_time);
1232
}
1233

    
1234
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1235
{
1236
    uint64_t expire_time;
1237

    
1238
    expire_time = qemu_get_be64(f);
1239
    if (expire_time != -1) {
1240
        qemu_mod_timer(ts, expire_time);
1241
    } else {
1242
        qemu_del_timer(ts);
1243
    }
1244
}
1245

    
1246
static void timer_save(QEMUFile *f, void *opaque)
1247
{
1248
    if (cpu_ticks_enabled) {
1249
        hw_error("cannot save state if virtual timers are running");
1250
    }
1251
    qemu_put_be64(f, cpu_ticks_offset);
1252
    qemu_put_be64(f, ticks_per_sec);
1253
    qemu_put_be64(f, cpu_clock_offset);
1254
}
1255

    
1256
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1257
{
1258
    if (version_id != 1 && version_id != 2)
1259
        return -EINVAL;
1260
    if (cpu_ticks_enabled) {
1261
        return -EINVAL;
1262
    }
1263
    cpu_ticks_offset=qemu_get_be64(f);
1264
    ticks_per_sec=qemu_get_be64(f);
1265
    if (version_id == 2) {
1266
        cpu_clock_offset=qemu_get_be64(f);
1267
    }
1268
    return 0;
1269
}
1270

    
1271
#ifdef _WIN32
1272
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1273
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1274
#else
1275
static void host_alarm_handler(int host_signum)
1276
#endif
1277
{
1278
#if 0
1279
#define DISP_FREQ 1000
1280
    {
1281
        static int64_t delta_min = INT64_MAX;
1282
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1283
        static int count;
1284
        ti = qemu_get_clock(vm_clock);
1285
        if (last_clock != 0) {
1286
            delta = ti - last_clock;
1287
            if (delta < delta_min)
1288
                delta_min = delta;
1289
            if (delta > delta_max)
1290
                delta_max = delta;
1291
            delta_cum += delta;
1292
            if (++count == DISP_FREQ) {
1293
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1294
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1295
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1296
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1297
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1298
                count = 0;
1299
                delta_min = INT64_MAX;
1300
                delta_max = 0;
1301
                delta_cum = 0;
1302
            }
1303
        }
1304
        last_clock = ti;
1305
    }
1306
#endif
1307
    if (alarm_has_dynticks(alarm_timer) ||
1308
        (!use_icount &&
1309
            qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1310
                               qemu_get_clock(vm_clock))) ||
1311
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1312
                           qemu_get_clock(rt_clock))) {
1313
#ifdef _WIN32
1314
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1315
        SetEvent(data->host_alarm);
1316
#endif
1317
        CPUState *env = next_cpu;
1318

    
1319
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1320

    
1321
        if (env) {
1322
            /* stop the currently executing cpu because a timer occured */
1323
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1324
#ifdef USE_KQEMU
1325
            if (env->kqemu_enabled) {
1326
                kqemu_cpu_interrupt(env);
1327
            }
1328
#endif
1329
        }
1330
        event_pending = 1;
1331
    }
1332
}
1333

    
1334
static int64_t qemu_next_deadline(void)
1335
{
1336
    int64_t delta;
1337

    
1338
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1339
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1340
                     qemu_get_clock(vm_clock);
1341
    } else {
1342
        /* To avoid problems with overflow limit this to 2^32.  */
1343
        delta = INT32_MAX;
1344
    }
1345

    
1346
    if (delta < 0)
1347
        delta = 0;
1348

    
1349
    return delta;
1350
}
1351

    
1352
#if defined(__linux__) || defined(_WIN32)
1353
static uint64_t qemu_next_deadline_dyntick(void)
1354
{
1355
    int64_t delta;
1356
    int64_t rtdelta;
1357

    
1358
    if (use_icount)
1359
        delta = INT32_MAX;
1360
    else
1361
        delta = (qemu_next_deadline() + 999) / 1000;
1362

    
1363
    if (active_timers[QEMU_TIMER_REALTIME]) {
1364
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1365
                 qemu_get_clock(rt_clock))*1000;
1366
        if (rtdelta < delta)
1367
            delta = rtdelta;
1368
    }
1369

    
1370
    if (delta < MIN_TIMER_REARM_US)
1371
        delta = MIN_TIMER_REARM_US;
1372

    
1373
    return delta;
1374
}
1375
#endif
1376

    
1377
#ifndef _WIN32
1378

    
1379
#if defined(__linux__)
1380

    
1381
#define RTC_FREQ 1024
1382

    
1383
static void enable_sigio_timer(int fd)
1384
{
1385
    struct sigaction act;
1386

    
1387
    /* timer signal */
1388
    sigfillset(&act.sa_mask);
1389
    act.sa_flags = 0;
1390
    act.sa_handler = host_alarm_handler;
1391

    
1392
    sigaction(SIGIO, &act, NULL);
1393
    fcntl(fd, F_SETFL, O_ASYNC);
1394
    fcntl(fd, F_SETOWN, getpid());
1395
}
1396

    
1397
static int hpet_start_timer(struct qemu_alarm_timer *t)
1398
{
1399
    struct hpet_info info;
1400
    int r, fd;
1401

    
1402
    fd = open("/dev/hpet", O_RDONLY);
1403
    if (fd < 0)
1404
        return -1;
1405

    
1406
    /* Set frequency */
1407
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1408
    if (r < 0) {
1409
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1410
                "error, but for better emulation accuracy type:\n"
1411
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1412
        goto fail;
1413
    }
1414

    
1415
    /* Check capabilities */
1416
    r = ioctl(fd, HPET_INFO, &info);
1417
    if (r < 0)
1418
        goto fail;
1419

    
1420
    /* Enable periodic mode */
1421
    r = ioctl(fd, HPET_EPI, 0);
1422
    if (info.hi_flags && (r < 0))
1423
        goto fail;
1424

    
1425
    /* Enable interrupt */
1426
    r = ioctl(fd, HPET_IE_ON, 0);
1427
    if (r < 0)
1428
        goto fail;
1429

    
1430
    enable_sigio_timer(fd);
1431
    t->priv = (void *)(long)fd;
1432

    
1433
    return 0;
1434
fail:
1435
    close(fd);
1436
    return -1;
1437
}
1438

    
1439
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1440
{
1441
    int fd = (long)t->priv;
1442

    
1443
    close(fd);
1444
}
1445

    
1446
static int rtc_start_timer(struct qemu_alarm_timer *t)
1447
{
1448
    int rtc_fd;
1449
    unsigned long current_rtc_freq = 0;
1450

    
1451
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1452
    if (rtc_fd < 0)
1453
        return -1;
1454
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1455
    if (current_rtc_freq != RTC_FREQ &&
1456
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1457
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1458
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1459
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1460
        goto fail;
1461
    }
1462
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1463
    fail:
1464
        close(rtc_fd);
1465
        return -1;
1466
    }
1467

    
1468
    enable_sigio_timer(rtc_fd);
1469

    
1470
    t->priv = (void *)(long)rtc_fd;
1471

    
1472
    return 0;
1473
}
1474

    
1475
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1476
{
1477
    int rtc_fd = (long)t->priv;
1478

    
1479
    close(rtc_fd);
1480
}
1481

    
1482
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1483
{
1484
    struct sigevent ev;
1485
    timer_t host_timer;
1486
    struct sigaction act;
1487

    
1488
    sigfillset(&act.sa_mask);
1489
    act.sa_flags = 0;
1490
    act.sa_handler = host_alarm_handler;
1491

    
1492
    sigaction(SIGALRM, &act, NULL);
1493

    
1494
    ev.sigev_value.sival_int = 0;
1495
    ev.sigev_notify = SIGEV_SIGNAL;
1496
    ev.sigev_signo = SIGALRM;
1497

    
1498
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1499
        perror("timer_create");
1500

    
1501
        /* disable dynticks */
1502
        fprintf(stderr, "Dynamic Ticks disabled\n");
1503

    
1504
        return -1;
1505
    }
1506

    
1507
    t->priv = (void *)host_timer;
1508

    
1509
    return 0;
1510
}
1511

    
1512
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1513
{
1514
    timer_t host_timer = (timer_t)t->priv;
1515

    
1516
    timer_delete(host_timer);
1517
}
1518

    
1519
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1520
{
1521
    timer_t host_timer = (timer_t)t->priv;
1522
    struct itimerspec timeout;
1523
    int64_t nearest_delta_us = INT64_MAX;
1524
    int64_t current_us;
1525

    
1526
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1527
                !active_timers[QEMU_TIMER_VIRTUAL])
1528
        return;
1529

    
1530
    nearest_delta_us = qemu_next_deadline_dyntick();
1531

    
1532
    /* check whether a timer is already running */
1533
    if (timer_gettime(host_timer, &timeout)) {
1534
        perror("gettime");
1535
        fprintf(stderr, "Internal timer error: aborting\n");
1536
        exit(1);
1537
    }
1538
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1539
    if (current_us && current_us <= nearest_delta_us)
1540
        return;
1541

    
1542
    timeout.it_interval.tv_sec = 0;
1543
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1544
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1545
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1546
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1547
        perror("settime");
1548
        fprintf(stderr, "Internal timer error: aborting\n");
1549
        exit(1);
1550
    }
1551
}
1552

    
1553
#endif /* defined(__linux__) */
1554

    
1555
static int unix_start_timer(struct qemu_alarm_timer *t)
1556
{
1557
    struct sigaction act;
1558
    struct itimerval itv;
1559
    int err;
1560

    
1561
    /* timer signal */
1562
    sigfillset(&act.sa_mask);
1563
    act.sa_flags = 0;
1564
    act.sa_handler = host_alarm_handler;
1565

    
1566
    sigaction(SIGALRM, &act, NULL);
1567

    
1568
    itv.it_interval.tv_sec = 0;
1569
    /* for i386 kernel 2.6 to get 1 ms */
1570
    itv.it_interval.tv_usec = 999;
1571
    itv.it_value.tv_sec = 0;
1572
    itv.it_value.tv_usec = 10 * 1000;
1573

    
1574
    err = setitimer(ITIMER_REAL, &itv, NULL);
1575
    if (err)
1576
        return -1;
1577

    
1578
    return 0;
1579
}
1580

    
1581
static void unix_stop_timer(struct qemu_alarm_timer *t)
1582
{
1583
    struct itimerval itv;
1584

    
1585
    memset(&itv, 0, sizeof(itv));
1586
    setitimer(ITIMER_REAL, &itv, NULL);
1587
}
1588

    
1589
#endif /* !defined(_WIN32) */
1590

    
1591
#ifdef _WIN32
1592

    
1593
static int win32_start_timer(struct qemu_alarm_timer *t)
1594
{
1595
    TIMECAPS tc;
1596
    struct qemu_alarm_win32 *data = t->priv;
1597
    UINT flags;
1598

    
1599
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1600
    if (!data->host_alarm) {
1601
        perror("Failed CreateEvent");
1602
        return -1;
1603
    }
1604

    
1605
    memset(&tc, 0, sizeof(tc));
1606
    timeGetDevCaps(&tc, sizeof(tc));
1607

    
1608
    if (data->period < tc.wPeriodMin)
1609
        data->period = tc.wPeriodMin;
1610

    
1611
    timeBeginPeriod(data->period);
1612

    
1613
    flags = TIME_CALLBACK_FUNCTION;
1614
    if (alarm_has_dynticks(t))
1615
        flags |= TIME_ONESHOT;
1616
    else
1617
        flags |= TIME_PERIODIC;
1618

    
1619
    data->timerId = timeSetEvent(1,         // interval (ms)
1620
                        data->period,       // resolution
1621
                        host_alarm_handler, // function
1622
                        (DWORD)t,           // parameter
1623
                        flags);
1624

    
1625
    if (!data->timerId) {
1626
        perror("Failed to initialize win32 alarm timer");
1627

    
1628
        timeEndPeriod(data->period);
1629
        CloseHandle(data->host_alarm);
1630
        return -1;
1631
    }
1632

    
1633
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1634

    
1635
    return 0;
1636
}
1637

    
1638
static void win32_stop_timer(struct qemu_alarm_timer *t)
1639
{
1640
    struct qemu_alarm_win32 *data = t->priv;
1641

    
1642
    timeKillEvent(data->timerId);
1643
    timeEndPeriod(data->period);
1644

    
1645
    CloseHandle(data->host_alarm);
1646
}
1647

    
1648
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1649
{
1650
    struct qemu_alarm_win32 *data = t->priv;
1651
    uint64_t nearest_delta_us;
1652

    
1653
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1654
                !active_timers[QEMU_TIMER_VIRTUAL])
1655
        return;
1656

    
1657
    nearest_delta_us = qemu_next_deadline_dyntick();
1658
    nearest_delta_us /= 1000;
1659

    
1660
    timeKillEvent(data->timerId);
1661

    
1662
    data->timerId = timeSetEvent(1,
1663
                        data->period,
1664
                        host_alarm_handler,
1665
                        (DWORD)t,
1666
                        TIME_ONESHOT | TIME_PERIODIC);
1667

    
1668
    if (!data->timerId) {
1669
        perror("Failed to re-arm win32 alarm timer");
1670

    
1671
        timeEndPeriod(data->period);
1672
        CloseHandle(data->host_alarm);
1673
        exit(1);
1674
    }
1675
}
1676

    
1677
#endif /* _WIN32 */
1678

    
1679
static void init_timer_alarm(void)
1680
{
1681
    struct qemu_alarm_timer *t;
1682
    int i, err = -1;
1683

    
1684
    for (i = 0; alarm_timers[i].name; i++) {
1685
        t = &alarm_timers[i];
1686

    
1687
        err = t->start(t);
1688
        if (!err)
1689
            break;
1690
    }
1691

    
1692
    if (err) {
1693
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1694
        fprintf(stderr, "Terminating\n");
1695
        exit(1);
1696
    }
1697

    
1698
    alarm_timer = t;
1699
}
1700

    
1701
static void quit_timers(void)
1702
{
1703
    alarm_timer->stop(alarm_timer);
1704
    alarm_timer = NULL;
1705
}
1706

    
1707
/***********************************************************/
1708
/* host time/date access */
1709
void qemu_get_timedate(struct tm *tm, int offset)
1710
{
1711
    time_t ti;
1712
    struct tm *ret;
1713

    
1714
    time(&ti);
1715
    ti += offset;
1716
    if (rtc_date_offset == -1) {
1717
        if (rtc_utc)
1718
            ret = gmtime(&ti);
1719
        else
1720
            ret = localtime(&ti);
1721
    } else {
1722
        ti -= rtc_date_offset;
1723
        ret = gmtime(&ti);
1724
    }
1725

    
1726
    memcpy(tm, ret, sizeof(struct tm));
1727
}
1728

    
1729
int qemu_timedate_diff(struct tm *tm)
1730
{
1731
    time_t seconds;
1732

    
1733
    if (rtc_date_offset == -1)
1734
        if (rtc_utc)
1735
            seconds = mktimegm(tm);
1736
        else
1737
            seconds = mktime(tm);
1738
    else
1739
        seconds = mktimegm(tm) + rtc_date_offset;
1740

    
1741
    return seconds - time(NULL);
1742
}
1743

    
1744
/***********************************************************/
1745
/* character device */
1746

    
1747
static void qemu_chr_event(CharDriverState *s, int event)
1748
{
1749
    if (!s->chr_event)
1750
        return;
1751
    s->chr_event(s->handler_opaque, event);
1752
}
1753

    
1754
static void qemu_chr_reset_bh(void *opaque)
1755
{
1756
    CharDriverState *s = opaque;
1757
    qemu_chr_event(s, CHR_EVENT_RESET);
1758
    qemu_bh_delete(s->bh);
1759
    s->bh = NULL;
1760
}
1761

    
1762
void qemu_chr_reset(CharDriverState *s)
1763
{
1764
    if (s->bh == NULL) {
1765
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1766
        qemu_bh_schedule(s->bh);
1767
    }
1768
}
1769

    
1770
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1771
{
1772
    return s->chr_write(s, buf, len);
1773
}
1774

    
1775
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1776
{
1777
    if (!s->chr_ioctl)
1778
        return -ENOTSUP;
1779
    return s->chr_ioctl(s, cmd, arg);
1780
}
1781

    
1782
int qemu_chr_can_read(CharDriverState *s)
1783
{
1784
    if (!s->chr_can_read)
1785
        return 0;
1786
    return s->chr_can_read(s->handler_opaque);
1787
}
1788

    
1789
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1790
{
1791
    s->chr_read(s->handler_opaque, buf, len);
1792
}
1793

    
1794
void qemu_chr_accept_input(CharDriverState *s)
1795
{
1796
    if (s->chr_accept_input)
1797
        s->chr_accept_input(s);
1798
}
1799

    
1800
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1801
{
1802
    char buf[4096];
1803
    va_list ap;
1804
    va_start(ap, fmt);
1805
    vsnprintf(buf, sizeof(buf), fmt, ap);
1806
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1807
    va_end(ap);
1808
}
1809

    
1810
void qemu_chr_send_event(CharDriverState *s, int event)
1811
{
1812
    if (s->chr_send_event)
1813
        s->chr_send_event(s, event);
1814
}
1815

    
1816
void qemu_chr_add_handlers(CharDriverState *s,
1817
                           IOCanRWHandler *fd_can_read,
1818
                           IOReadHandler *fd_read,
1819
                           IOEventHandler *fd_event,
1820
                           void *opaque)
1821
{
1822
    s->chr_can_read = fd_can_read;
1823
    s->chr_read = fd_read;
1824
    s->chr_event = fd_event;
1825
    s->handler_opaque = opaque;
1826
    if (s->chr_update_read_handler)
1827
        s->chr_update_read_handler(s);
1828
}
1829

    
1830
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1831
{
1832
    return len;
1833
}
1834

    
1835
static CharDriverState *qemu_chr_open_null(void)
1836
{
1837
    CharDriverState *chr;
1838

    
1839
    chr = qemu_mallocz(sizeof(CharDriverState));
1840
    if (!chr)
1841
        return NULL;
1842
    chr->chr_write = null_chr_write;
1843
    return chr;
1844
}
1845

    
1846
/* MUX driver for serial I/O splitting */
1847
static int term_timestamps;
1848
static int64_t term_timestamps_start;
1849
#define MAX_MUX 4
1850
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
1851
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1852
typedef struct {
1853
    IOCanRWHandler *chr_can_read[MAX_MUX];
1854
    IOReadHandler *chr_read[MAX_MUX];
1855
    IOEventHandler *chr_event[MAX_MUX];
1856
    void *ext_opaque[MAX_MUX];
1857
    CharDriverState *drv;
1858
    unsigned char buffer[MUX_BUFFER_SIZE];
1859
    int prod;
1860
    int cons;
1861
    int mux_cnt;
1862
    int term_got_escape;
1863
    int max_size;
1864
} MuxDriver;
1865

    
1866

    
1867
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1868
{
1869
    MuxDriver *d = chr->opaque;
1870
    int ret;
1871
    if (!term_timestamps) {
1872
        ret = d->drv->chr_write(d->drv, buf, len);
1873
    } else {
1874
        int i;
1875

    
1876
        ret = 0;
1877
        for(i = 0; i < len; i++) {
1878
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1879
            if (buf[i] == '\n') {
1880
                char buf1[64];
1881
                int64_t ti;
1882
                int secs;
1883

    
1884
                ti = get_clock();
1885
                if (term_timestamps_start == -1)
1886
                    term_timestamps_start = ti;
1887
                ti -= term_timestamps_start;
1888
                secs = ti / 1000000000;
1889
                snprintf(buf1, sizeof(buf1),
1890
                         "[%02d:%02d:%02d.%03d] ",
1891
                         secs / 3600,
1892
                         (secs / 60) % 60,
1893
                         secs % 60,
1894
                         (int)((ti / 1000000) % 1000));
1895
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1896
            }
1897
        }
1898
    }
1899
    return ret;
1900
}
1901

    
1902
static const char * const mux_help[] = {
1903
    "% h    print this help\n\r",
1904
    "% x    exit emulator\n\r",
1905
    "% s    save disk data back to file (if -snapshot)\n\r",
1906
    "% t    toggle console timestamps\n\r"
1907
    "% b    send break (magic sysrq)\n\r",
1908
    "% c    switch between console and monitor\n\r",
1909
    "% %  sends %\n\r",
1910
    NULL
1911
};
1912

    
1913
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1914
static void mux_print_help(CharDriverState *chr)
1915
{
1916
    int i, j;
1917
    char ebuf[15] = "Escape-Char";
1918
    char cbuf[50] = "\n\r";
1919

    
1920
    if (term_escape_char > 0 && term_escape_char < 26) {
1921
        snprintf(cbuf, sizeof(cbuf), "\n\r");
1922
        snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1923
    } else {
1924
        snprintf(cbuf, sizeof(cbuf),
1925
                 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1926
                 term_escape_char);
1927
    }
1928
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1929
    for (i = 0; mux_help[i] != NULL; i++) {
1930
        for (j=0; mux_help[i][j] != '\0'; j++) {
1931
            if (mux_help[i][j] == '%')
1932
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1933
            else
1934
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1935
        }
1936
    }
1937
}
1938

    
1939
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1940
{
1941
    if (d->term_got_escape) {
1942
        d->term_got_escape = 0;
1943
        if (ch == term_escape_char)
1944
            goto send_char;
1945
        switch(ch) {
1946
        case '?':
1947
        case 'h':
1948
            mux_print_help(chr);
1949
            break;
1950
        case 'x':
1951
            {
1952
                 const char *term =  "QEMU: Terminated\n\r";
1953
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1954
                 exit(0);
1955
                 break;
1956
            }
1957
        case 's':
1958
            {
1959
                int i;
1960
                for (i = 0; i < nb_drives; i++) {
1961
                        bdrv_commit(drives_table[i].bdrv);
1962
                }
1963
            }
1964
            break;
1965
        case 'b':
1966
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1967
            break;
1968
        case 'c':
1969
            /* Switch to the next registered device */
1970
            chr->focus++;
1971
            if (chr->focus >= d->mux_cnt)
1972
                chr->focus = 0;
1973
            break;
1974
       case 't':
1975
           term_timestamps = !term_timestamps;
1976
           term_timestamps_start = -1;
1977
           break;
1978
        }
1979
    } else if (ch == term_escape_char) {
1980
        d->term_got_escape = 1;
1981
    } else {
1982
    send_char:
1983
        return 1;
1984
    }
1985
    return 0;
1986
}
1987

    
1988
static void mux_chr_accept_input(CharDriverState *chr)
1989
{
1990
    int m = chr->focus;
1991
    MuxDriver *d = chr->opaque;
1992

    
1993
    while (d->prod != d->cons &&
1994
           d->chr_can_read[m] &&
1995
           d->chr_can_read[m](d->ext_opaque[m])) {
1996
        d->chr_read[m](d->ext_opaque[m],
1997
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1998
    }
1999
}
2000

    
2001
static int mux_chr_can_read(void *opaque)
2002
{
2003
    CharDriverState *chr = opaque;
2004
    MuxDriver *d = chr->opaque;
2005

    
2006
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2007
        return 1;
2008
    if (d->chr_can_read[chr->focus])
2009
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2010
    return 0;
2011
}
2012

    
2013
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2014
{
2015
    CharDriverState *chr = opaque;
2016
    MuxDriver *d = chr->opaque;
2017
    int m = chr->focus;
2018
    int i;
2019

    
2020
    mux_chr_accept_input (opaque);
2021

    
2022
    for(i = 0; i < size; i++)
2023
        if (mux_proc_byte(chr, d, buf[i])) {
2024
            if (d->prod == d->cons &&
2025
                d->chr_can_read[m] &&
2026
                d->chr_can_read[m](d->ext_opaque[m]))
2027
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2028
            else
2029
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2030
        }
2031
}
2032

    
2033
static void mux_chr_event(void *opaque, int event)
2034
{
2035
    CharDriverState *chr = opaque;
2036
    MuxDriver *d = chr->opaque;
2037
    int i;
2038

    
2039
    /* Send the event to all registered listeners */
2040
    for (i = 0; i < d->mux_cnt; i++)
2041
        if (d->chr_event[i])
2042
            d->chr_event[i](d->ext_opaque[i], event);
2043
}
2044

    
2045
static void mux_chr_update_read_handler(CharDriverState *chr)
2046
{
2047
    MuxDriver *d = chr->opaque;
2048

    
2049
    if (d->mux_cnt >= MAX_MUX) {
2050
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2051
        return;
2052
    }
2053
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2054
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2055
    d->chr_read[d->mux_cnt] = chr->chr_read;
2056
    d->chr_event[d->mux_cnt] = chr->chr_event;
2057
    /* Fix up the real driver with mux routines */
2058
    if (d->mux_cnt == 0) {
2059
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2060
                              mux_chr_event, chr);
2061
    }
2062
    chr->focus = d->mux_cnt;
2063
    d->mux_cnt++;
2064
}
2065

    
2066
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2067
{
2068
    CharDriverState *chr;
2069
    MuxDriver *d;
2070

    
2071
    chr = qemu_mallocz(sizeof(CharDriverState));
2072
    if (!chr)
2073
        return NULL;
2074
    d = qemu_mallocz(sizeof(MuxDriver));
2075
    if (!d) {
2076
        free(chr);
2077
        return NULL;
2078
    }
2079

    
2080
    chr->opaque = d;
2081
    d->drv = drv;
2082
    chr->focus = -1;
2083
    chr->chr_write = mux_chr_write;
2084
    chr->chr_update_read_handler = mux_chr_update_read_handler;
2085
    chr->chr_accept_input = mux_chr_accept_input;
2086
    return chr;
2087
}
2088

    
2089

    
2090
#ifdef _WIN32
2091

    
2092
static void socket_cleanup(void)
2093
{
2094
    WSACleanup();
2095
}
2096

    
2097
static int socket_init(void)
2098
{
2099
    WSADATA Data;
2100
    int ret, err;
2101

    
2102
    ret = WSAStartup(MAKEWORD(2,2), &Data);
2103
    if (ret != 0) {
2104
        err = WSAGetLastError();
2105
        fprintf(stderr, "WSAStartup: %d\n", err);
2106
        return -1;
2107
    }
2108
    atexit(socket_cleanup);
2109
    return 0;
2110
}
2111

    
2112
static int send_all(int fd, const uint8_t *buf, int len1)
2113
{
2114
    int ret, len;
2115

    
2116
    len = len1;
2117
    while (len > 0) {
2118
        ret = send(fd, buf, len, 0);
2119
        if (ret < 0) {
2120
            int errno;
2121
            errno = WSAGetLastError();
2122
            if (errno != WSAEWOULDBLOCK) {
2123
                return -1;
2124
            }
2125
        } else if (ret == 0) {
2126
            break;
2127
        } else {
2128
            buf += ret;
2129
            len -= ret;
2130
        }
2131
    }
2132
    return len1 - len;
2133
}
2134

    
2135
#else
2136

    
2137
static int unix_write(int fd, const uint8_t *buf, int len1)
2138
{
2139
    int ret, len;
2140

    
2141
    len = len1;
2142
    while (len > 0) {
2143
        ret = write(fd, buf, len);
2144
        if (ret < 0) {
2145
            if (errno != EINTR && errno != EAGAIN)
2146
                return -1;
2147
        } else if (ret == 0) {
2148
            break;
2149
        } else {
2150
            buf += ret;
2151
            len -= ret;
2152
        }
2153
    }
2154
    return len1 - len;
2155
}
2156

    
2157
static inline int send_all(int fd, const uint8_t *buf, int len1)
2158
{
2159
    return unix_write(fd, buf, len1);
2160
}
2161
#endif /* !_WIN32 */
2162

    
2163
#ifndef _WIN32
2164

    
2165
typedef struct {
2166
    int fd_in, fd_out;
2167
    int max_size;
2168
} FDCharDriver;
2169

    
2170
#define STDIO_MAX_CLIENTS 1
2171
static int stdio_nb_clients = 0;
2172

    
2173
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2174
{
2175
    FDCharDriver *s = chr->opaque;
2176
    return unix_write(s->fd_out, buf, len);
2177
}
2178

    
2179
static int fd_chr_read_poll(void *opaque)
2180
{
2181
    CharDriverState *chr = opaque;
2182
    FDCharDriver *s = chr->opaque;
2183

    
2184
    s->max_size = qemu_chr_can_read(chr);
2185
    return s->max_size;
2186
}
2187

    
2188
static void fd_chr_read(void *opaque)
2189
{
2190
    CharDriverState *chr = opaque;
2191
    FDCharDriver *s = chr->opaque;
2192
    int size, len;
2193
    uint8_t buf[1024];
2194

    
2195
    len = sizeof(buf);
2196
    if (len > s->max_size)
2197
        len = s->max_size;
2198
    if (len == 0)
2199
        return;
2200
    size = read(s->fd_in, buf, len);
2201
    if (size == 0) {
2202
        /* FD has been closed. Remove it from the active list.  */
2203
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2204
        return;
2205
    }
2206
    if (size > 0) {
2207
        qemu_chr_read(chr, buf, size);
2208
    }
2209
}
2210

    
2211
static void fd_chr_update_read_handler(CharDriverState *chr)
2212
{
2213
    FDCharDriver *s = chr->opaque;
2214

    
2215
    if (s->fd_in >= 0) {
2216
        if (nographic && s->fd_in == 0) {
2217
        } else {
2218
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2219
                                 fd_chr_read, NULL, chr);
2220
        }
2221
    }
2222
}
2223

    
2224
static void fd_chr_close(struct CharDriverState *chr)
2225
{
2226
    FDCharDriver *s = chr->opaque;
2227

    
2228
    if (s->fd_in >= 0) {
2229
        if (nographic && s->fd_in == 0) {
2230
        } else {
2231
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2232
        }
2233
    }
2234

    
2235
    qemu_free(s);
2236
}
2237

    
2238
/* open a character device to a unix fd */
2239
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2240
{
2241
    CharDriverState *chr;
2242
    FDCharDriver *s;
2243

    
2244
    chr = qemu_mallocz(sizeof(CharDriverState));
2245
    if (!chr)
2246
        return NULL;
2247
    s = qemu_mallocz(sizeof(FDCharDriver));
2248
    if (!s) {
2249
        free(chr);
2250
        return NULL;
2251
    }
2252
    s->fd_in = fd_in;
2253
    s->fd_out = fd_out;
2254
    chr->opaque = s;
2255
    chr->chr_write = fd_chr_write;
2256
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2257
    chr->chr_close = fd_chr_close;
2258

    
2259
    qemu_chr_reset(chr);
2260

    
2261
    return chr;
2262
}
2263

    
2264
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2265
{
2266
    int fd_out;
2267

    
2268
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2269
    if (fd_out < 0)
2270
        return NULL;
2271
    return qemu_chr_open_fd(-1, fd_out);
2272
}
2273

    
2274
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2275
{
2276
    int fd_in, fd_out;
2277
    char filename_in[256], filename_out[256];
2278

    
2279
    snprintf(filename_in, 256, "%s.in", filename);
2280
    snprintf(filename_out, 256, "%s.out", filename);
2281
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2282
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2283
    if (fd_in < 0 || fd_out < 0) {
2284
        if (fd_in >= 0)
2285
            close(fd_in);
2286
        if (fd_out >= 0)
2287
            close(fd_out);
2288
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2289
        if (fd_in < 0)
2290
            return NULL;
2291
    }
2292
    return qemu_chr_open_fd(fd_in, fd_out);
2293
}
2294

    
2295

    
2296
/* for STDIO, we handle the case where several clients use it
2297
   (nographic mode) */
2298

    
2299
#define TERM_FIFO_MAX_SIZE 1
2300

    
2301
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2302
static int term_fifo_size;
2303

    
2304
static int stdio_read_poll(void *opaque)
2305
{
2306
    CharDriverState *chr = opaque;
2307

    
2308
    /* try to flush the queue if needed */
2309
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2310
        qemu_chr_read(chr, term_fifo, 1);
2311
        term_fifo_size = 0;
2312
    }
2313
    /* see if we can absorb more chars */
2314
    if (term_fifo_size == 0)
2315
        return 1;
2316
    else
2317
        return 0;
2318
}
2319

    
2320
static void stdio_read(void *opaque)
2321
{
2322
    int size;
2323
    uint8_t buf[1];
2324
    CharDriverState *chr = opaque;
2325

    
2326
    size = read(0, buf, 1);
2327
    if (size == 0) {
2328
        /* stdin has been closed. Remove it from the active list.  */
2329
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2330
        return;
2331
    }
2332
    if (size > 0) {
2333
        if (qemu_chr_can_read(chr) > 0) {
2334
            qemu_chr_read(chr, buf, 1);
2335
        } else if (term_fifo_size == 0) {
2336
            term_fifo[term_fifo_size++] = buf[0];
2337
        }
2338
    }
2339
}
2340

    
2341
/* init terminal so that we can grab keys */
2342
static struct termios oldtty;
2343
static int old_fd0_flags;
2344
static int term_atexit_done;
2345

    
2346
static void term_exit(void)
2347
{
2348
    tcsetattr (0, TCSANOW, &oldtty);
2349
    fcntl(0, F_SETFL, old_fd0_flags);
2350
}
2351

    
2352
static void term_init(void)
2353
{
2354
    struct termios tty;
2355

    
2356
    tcgetattr (0, &tty);
2357
    oldtty = tty;
2358
    old_fd0_flags = fcntl(0, F_GETFL);
2359

    
2360
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2361
                          |INLCR|IGNCR|ICRNL|IXON);
2362
    tty.c_oflag |= OPOST;
2363
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2364
    /* if graphical mode, we allow Ctrl-C handling */
2365
    if (nographic)
2366
        tty.c_lflag &= ~ISIG;
2367
    tty.c_cflag &= ~(CSIZE|PARENB);
2368
    tty.c_cflag |= CS8;
2369
    tty.c_cc[VMIN] = 1;
2370
    tty.c_cc[VTIME] = 0;
2371

    
2372
    tcsetattr (0, TCSANOW, &tty);
2373

    
2374
    if (!term_atexit_done++)
2375
        atexit(term_exit);
2376

    
2377
    fcntl(0, F_SETFL, O_NONBLOCK);
2378
}
2379

    
2380
static void qemu_chr_close_stdio(struct CharDriverState *chr)
2381
{
2382
    term_exit();
2383
    stdio_nb_clients--;
2384
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2385
    fd_chr_close(chr);
2386
}
2387

    
2388
static CharDriverState *qemu_chr_open_stdio(void)
2389
{
2390
    CharDriverState *chr;
2391

    
2392
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2393
        return NULL;
2394
    chr = qemu_chr_open_fd(0, 1);
2395
    chr->chr_close = qemu_chr_close_stdio;
2396
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2397
    stdio_nb_clients++;
2398
    term_init();
2399

    
2400
    return chr;
2401
}
2402

    
2403
#ifdef __sun__
2404
/* Once Solaris has openpty(), this is going to be removed. */
2405
int openpty(int *amaster, int *aslave, char *name,
2406
            struct termios *termp, struct winsize *winp)
2407
{
2408
        const char *slave;
2409
        int mfd = -1, sfd = -1;
2410

    
2411
        *amaster = *aslave = -1;
2412

    
2413
        mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2414
        if (mfd < 0)
2415
                goto err;
2416

    
2417
        if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2418
                goto err;
2419

    
2420
        if ((slave = ptsname(mfd)) == NULL)
2421
                goto err;
2422

    
2423
        if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2424
                goto err;
2425

    
2426
        if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2427
            (termp != NULL && tcgetattr(sfd, termp) < 0))
2428
                goto err;
2429

    
2430
        if (amaster)
2431
                *amaster = mfd;
2432
        if (aslave)
2433
                *aslave = sfd;
2434
        if (winp)
2435
                ioctl(sfd, TIOCSWINSZ, winp);
2436

    
2437
        return 0;
2438

    
2439
err:
2440
        if (sfd != -1)
2441
                close(sfd);
2442
        close(mfd);
2443
        return -1;
2444
}
2445

    
2446
void cfmakeraw (struct termios *termios_p)
2447
{
2448
        termios_p->c_iflag &=
2449
                ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2450
        termios_p->c_oflag &= ~OPOST;
2451
        termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2452
        termios_p->c_cflag &= ~(CSIZE|PARENB);
2453
        termios_p->c_cflag |= CS8;
2454

    
2455
        termios_p->c_cc[VMIN] = 0;
2456
        termios_p->c_cc[VTIME] = 0;
2457
}
2458
#endif
2459

    
2460
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2461
    || defined(__NetBSD__) || defined(__OpenBSD__)
2462

    
2463
typedef struct {
2464
    int fd;
2465
    int connected;
2466
    int polling;
2467
    int read_bytes;
2468
    QEMUTimer *timer;
2469
} PtyCharDriver;
2470

    
2471
static void pty_chr_update_read_handler(CharDriverState *chr);
2472
static void pty_chr_state(CharDriverState *chr, int connected);
2473

    
2474
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2475
{
2476
    PtyCharDriver *s = chr->opaque;
2477

    
2478
    if (!s->connected) {
2479
        /* guest sends data, check for (re-)connect */
2480
        pty_chr_update_read_handler(chr);
2481
        return 0;
2482
    }
2483
    return unix_write(s->fd, buf, len);
2484
}
2485

    
2486
static int pty_chr_read_poll(void *opaque)
2487
{
2488
    CharDriverState *chr = opaque;
2489
    PtyCharDriver *s = chr->opaque;
2490

    
2491
    s->read_bytes = qemu_chr_can_read(chr);
2492
    return s->read_bytes;
2493
}
2494

    
2495
static void pty_chr_read(void *opaque)
2496
{
2497
    CharDriverState *chr = opaque;
2498
    PtyCharDriver *s = chr->opaque;
2499
    int size, len;
2500
    uint8_t buf[1024];
2501

    
2502
    len = sizeof(buf);
2503
    if (len > s->read_bytes)
2504
        len = s->read_bytes;
2505
    if (len == 0)
2506
        return;
2507
    size = read(s->fd, buf, len);
2508
    if ((size == -1 && errno == EIO) ||
2509
        (size == 0)) {
2510
        pty_chr_state(chr, 0);
2511
        return;
2512
    }
2513
    if (size > 0) {
2514
        pty_chr_state(chr, 1);
2515
        qemu_chr_read(chr, buf, size);
2516
    }
2517
}
2518

    
2519
static void pty_chr_update_read_handler(CharDriverState *chr)
2520
{
2521
    PtyCharDriver *s = chr->opaque;
2522

    
2523
    qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2524
                         pty_chr_read, NULL, chr);
2525
    s->polling = 1;
2526
    /*
2527
     * Short timeout here: just need wait long enougth that qemu makes
2528
     * it through the poll loop once.  When reconnected we want a
2529
     * short timeout so we notice it almost instantly.  Otherwise
2530
     * read() gives us -EIO instantly, making pty_chr_state() reset the
2531
     * timeout to the normal (much longer) poll interval before the
2532
     * timer triggers.
2533
     */
2534
    qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2535
}
2536

    
2537
static void pty_chr_state(CharDriverState *chr, int connected)
2538
{
2539
    PtyCharDriver *s = chr->opaque;
2540

    
2541
    if (!connected) {
2542
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2543
        s->connected = 0;
2544
        s->polling = 0;
2545
        /* (re-)connect poll interval for idle guests: once per second.
2546
         * We check more frequently in case the guests sends data to
2547
         * the virtual device linked to our pty. */
2548
        qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2549
    } else {
2550
        if (!s->connected)
2551
            qemu_chr_reset(chr);
2552
        s->connected = 1;
2553
    }
2554
}
2555

    
2556
static void pty_chr_timer(void *opaque)
2557
{
2558
    struct CharDriverState *chr = opaque;
2559
    PtyCharDriver *s = chr->opaque;
2560

    
2561
    if (s->connected)
2562
        return;
2563
    if (s->polling) {
2564
        /* If we arrive here without polling being cleared due
2565
         * read returning -EIO, then we are (re-)connected */
2566
        pty_chr_state(chr, 1);
2567
        return;
2568
    }
2569

    
2570
    /* Next poll ... */
2571
    pty_chr_update_read_handler(chr);
2572
}
2573

    
2574
static void pty_chr_close(struct CharDriverState *chr)
2575
{
2576
    PtyCharDriver *s = chr->opaque;
2577

    
2578
    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2579
    close(s->fd);
2580
    qemu_free(s);
2581
}
2582

    
2583
static CharDriverState *qemu_chr_open_pty(void)
2584
{
2585
    CharDriverState *chr;
2586
    PtyCharDriver *s;
2587
    struct termios tty;
2588
    int slave_fd;
2589
#if defined(__OpenBSD__)
2590
    char pty_name[PATH_MAX];
2591
#define q_ptsname(x) pty_name
2592
#else
2593
    char *pty_name = NULL;
2594
#define q_ptsname(x) ptsname(x)
2595
#endif
2596

    
2597
    chr = qemu_mallocz(sizeof(CharDriverState));
2598
    if (!chr)
2599
        return NULL;
2600
    s = qemu_mallocz(sizeof(PtyCharDriver));
2601
    if (!s) {
2602
        qemu_free(chr);
2603
        return NULL;
2604
    }
2605

    
2606
    if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2607
        return NULL;
2608
    }
2609

    
2610
    /* Set raw attributes on the pty. */
2611
    cfmakeraw(&tty);
2612
    tcsetattr(slave_fd, TCSAFLUSH, &tty);
2613
    close(slave_fd);
2614

    
2615
    fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2616

    
2617
    chr->opaque = s;
2618
    chr->chr_write = pty_chr_write;
2619
    chr->chr_update_read_handler = pty_chr_update_read_handler;
2620
    chr->chr_close = pty_chr_close;
2621

    
2622
    s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2623

    
2624
    return chr;
2625
}
2626

    
2627
static void tty_serial_init(int fd, int speed,
2628
                            int parity, int data_bits, int stop_bits)
2629
{
2630
    struct termios tty;
2631
    speed_t spd;
2632

    
2633
#if 0
2634
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2635
           speed, parity, data_bits, stop_bits);
2636
#endif
2637
    tcgetattr (fd, &tty);
2638

    
2639
#define MARGIN 1.1
2640
    if (speed <= 50 * MARGIN)
2641
        spd = B50;
2642
    else if (speed <= 75 * MARGIN)
2643
        spd = B75;
2644
    else if (speed <= 300 * MARGIN)
2645
        spd = B300;
2646
    else if (speed <= 600 * MARGIN)
2647
        spd = B600;
2648
    else if (speed <= 1200 * MARGIN)
2649
        spd = B1200;
2650
    else if (speed <= 2400 * MARGIN)
2651
        spd = B2400;
2652
    else if (speed <= 4800 * MARGIN)
2653
        spd = B4800;
2654
    else if (speed <= 9600 * MARGIN)
2655
        spd = B9600;
2656
    else if (speed <= 19200 * MARGIN)
2657
        spd = B19200;
2658
    else if (speed <= 38400 * MARGIN)
2659
        spd = B38400;
2660
    else if (speed <= 57600 * MARGIN)
2661
        spd = B57600;
2662
    else if (speed <= 115200 * MARGIN)
2663
        spd = B115200;
2664
    else
2665
        spd = B115200;
2666

    
2667
    cfsetispeed(&tty, spd);
2668
    cfsetospeed(&tty, spd);
2669

    
2670
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2671
                          |INLCR|IGNCR|ICRNL|IXON);
2672
    tty.c_oflag |= OPOST;
2673
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2674
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2675
    switch(data_bits) {
2676
    default:
2677
    case 8:
2678
        tty.c_cflag |= CS8;
2679
        break;
2680
    case 7:
2681
        tty.c_cflag |= CS7;
2682
        break;
2683
    case 6:
2684
        tty.c_cflag |= CS6;
2685
        break;
2686
    case 5:
2687
        tty.c_cflag |= CS5;
2688
        break;
2689
    }
2690
    switch(parity) {
2691
    default:
2692
    case 'N':
2693
        break;
2694
    case 'E':
2695
        tty.c_cflag |= PARENB;
2696
        break;
2697
    case 'O':
2698
        tty.c_cflag |= PARENB | PARODD;
2699
        break;
2700
    }
2701
    if (stop_bits == 2)
2702
        tty.c_cflag |= CSTOPB;
2703

    
2704
    tcsetattr (fd, TCSANOW, &tty);
2705
}
2706

    
2707
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2708
{
2709
    FDCharDriver *s = chr->opaque;
2710

    
2711
    switch(cmd) {
2712
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2713
        {
2714
            QEMUSerialSetParams *ssp = arg;
2715
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2716
                            ssp->data_bits, ssp->stop_bits);
2717
        }
2718
        break;
2719
    case CHR_IOCTL_SERIAL_SET_BREAK:
2720
        {
2721
            int enable = *(int *)arg;
2722
            if (enable)
2723
                tcsendbreak(s->fd_in, 1);
2724
        }
2725
        break;
2726
    case CHR_IOCTL_SERIAL_GET_TIOCM:
2727
        {
2728
            int sarg = 0;
2729
            int *targ = (int *)arg;
2730
            ioctl(s->fd_in, TIOCMGET, &sarg);
2731
            *targ = 0;
2732
            if (sarg | TIOCM_CTS)
2733
                *targ |= CHR_TIOCM_CTS;
2734
            if (sarg | TIOCM_CAR)
2735
                *targ |= CHR_TIOCM_CAR;
2736
            if (sarg | TIOCM_DSR)
2737
                *targ |= CHR_TIOCM_DSR;
2738
            if (sarg | TIOCM_RI)
2739
                *targ |= CHR_TIOCM_RI;
2740
            if (sarg | TIOCM_DTR)
2741
                *targ |= CHR_TIOCM_DTR;
2742
            if (sarg | TIOCM_RTS)
2743
                *targ |= CHR_TIOCM_RTS;
2744
        }
2745
        break;
2746
    case CHR_IOCTL_SERIAL_SET_TIOCM:
2747
        {
2748
            int sarg = *(int *)arg;
2749
            int targ = 0;
2750
            if (sarg | CHR_TIOCM_DTR)
2751
                targ |= TIOCM_DTR;
2752
            if (sarg | CHR_TIOCM_RTS)
2753
                targ |= TIOCM_RTS;
2754
            ioctl(s->fd_in, TIOCMSET, &targ);
2755
        }
2756
        break;
2757
    default:
2758
        return -ENOTSUP;
2759
    }
2760
    return 0;
2761
}
2762

    
2763
static CharDriverState *qemu_chr_open_tty(const char *filename)
2764
{
2765
    CharDriverState *chr;
2766
    int fd;
2767

    
2768
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2769
    tty_serial_init(fd, 115200, 'N', 8, 1);
2770
    chr = qemu_chr_open_fd(fd, fd);
2771
    if (!chr) {
2772
        close(fd);
2773
        return NULL;
2774
    }
2775
    chr->chr_ioctl = tty_serial_ioctl;
2776
    qemu_chr_reset(chr);
2777
    return chr;
2778
}
2779
#else  /* ! __linux__ && ! __sun__ */
2780
static CharDriverState *qemu_chr_open_pty(void)
2781
{
2782
    return NULL;
2783
}
2784
#endif /* __linux__ || __sun__ */
2785

    
2786
#if defined(__linux__)
2787
typedef struct {
2788
    int fd;
2789
    int mode;
2790
} ParallelCharDriver;
2791

    
2792
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2793
{
2794
    if (s->mode != mode) {
2795
        int m = mode;
2796
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2797
            return 0;
2798
        s->mode = mode;
2799
    }
2800
    return 1;
2801
}
2802

    
2803
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2804
{
2805
    ParallelCharDriver *drv = chr->opaque;
2806
    int fd = drv->fd;
2807
    uint8_t b;
2808

    
2809
    switch(cmd) {
2810
    case CHR_IOCTL_PP_READ_DATA:
2811
        if (ioctl(fd, PPRDATA, &b) < 0)
2812
            return -ENOTSUP;
2813
        *(uint8_t *)arg = b;
2814
        break;
2815
    case CHR_IOCTL_PP_WRITE_DATA:
2816
        b = *(uint8_t *)arg;
2817
        if (ioctl(fd, PPWDATA, &b) < 0)
2818
            return -ENOTSUP;
2819
        break;
2820
    case CHR_IOCTL_PP_READ_CONTROL:
2821
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2822
            return -ENOTSUP;
2823
        /* Linux gives only the lowest bits, and no way to know data
2824
           direction! For better compatibility set the fixed upper
2825
           bits. */
2826
        *(uint8_t *)arg = b | 0xc0;
2827
        break;
2828
    case CHR_IOCTL_PP_WRITE_CONTROL:
2829
        b = *(uint8_t *)arg;
2830
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2831
            return -ENOTSUP;
2832
        break;
2833
    case CHR_IOCTL_PP_READ_STATUS:
2834
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2835
            return -ENOTSUP;
2836
        *(uint8_t *)arg = b;
2837
        break;
2838
    case CHR_IOCTL_PP_DATA_DIR:
2839
        if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2840
            return -ENOTSUP;
2841
        break;
2842
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2843
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2844
            struct ParallelIOArg *parg = arg;
2845
            int n = read(fd, parg->buffer, parg->count);
2846
            if (n != parg->count) {
2847
                return -EIO;
2848
            }
2849
        }
2850
        break;
2851
    case CHR_IOCTL_PP_EPP_READ:
2852
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2853
            struct ParallelIOArg *parg = arg;
2854
            int n = read(fd, parg->buffer, parg->count);
2855
            if (n != parg->count) {
2856
                return -EIO;
2857
            }
2858
        }
2859
        break;
2860
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2861
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2862
            struct ParallelIOArg *parg = arg;
2863
            int n = write(fd, parg->buffer, parg->count);
2864
            if (n != parg->count) {
2865
                return -EIO;
2866
            }
2867
        }
2868
        break;
2869
    case CHR_IOCTL_PP_EPP_WRITE:
2870
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2871
            struct ParallelIOArg *parg = arg;
2872
            int n = write(fd, parg->buffer, parg->count);
2873
            if (n != parg->count) {
2874
                return -EIO;
2875
            }
2876
        }
2877
        break;
2878
    default:
2879
        return -ENOTSUP;
2880
    }
2881
    return 0;
2882
}
2883

    
2884
static void pp_close(CharDriverState *chr)
2885
{
2886
    ParallelCharDriver *drv = chr->opaque;
2887
    int fd = drv->fd;
2888

    
2889
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2890
    ioctl(fd, PPRELEASE);
2891
    close(fd);
2892
    qemu_free(drv);
2893
}
2894

    
2895
static CharDriverState *qemu_chr_open_pp(const char *filename)
2896
{
2897
    CharDriverState *chr;
2898
    ParallelCharDriver *drv;
2899
    int fd;
2900

    
2901
    TFR(fd = open(filename, O_RDWR));
2902
    if (fd < 0)
2903
        return NULL;
2904

    
2905
    if (ioctl(fd, PPCLAIM) < 0) {
2906
        close(fd);
2907
        return NULL;
2908
    }
2909

    
2910
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2911
    if (!drv) {
2912
        close(fd);
2913
        return NULL;
2914
    }
2915
    drv->fd = fd;
2916
    drv->mode = IEEE1284_MODE_COMPAT;
2917

    
2918
    chr = qemu_mallocz(sizeof(CharDriverState));
2919
    if (!chr) {
2920
        qemu_free(drv);
2921
        close(fd);
2922
        return NULL;
2923
    }
2924
    chr->chr_write = null_chr_write;
2925
    chr->chr_ioctl = pp_ioctl;
2926
    chr->chr_close = pp_close;
2927
    chr->opaque = drv;
2928

    
2929
    qemu_chr_reset(chr);
2930

    
2931
    return chr;
2932
}
2933
#endif /* __linux__ */
2934

    
2935
#else /* _WIN32 */
2936

    
2937
typedef struct {
2938
    int max_size;
2939
    HANDLE hcom, hrecv, hsend;
2940
    OVERLAPPED orecv, osend;
2941
    BOOL fpipe;
2942
    DWORD len;
2943
} WinCharState;
2944

    
2945
#define NSENDBUF 2048
2946
#define NRECVBUF 2048
2947
#define MAXCONNECT 1
2948
#define NTIMEOUT 5000
2949

    
2950
static int win_chr_poll(void *opaque);
2951
static int win_chr_pipe_poll(void *opaque);
2952

    
2953
static void win_chr_close(CharDriverState *chr)
2954
{
2955
    WinCharState *s = chr->opaque;
2956

    
2957
    if (s->hsend) {
2958
        CloseHandle(s->hsend);
2959
        s->hsend = NULL;
2960
    }
2961
    if (s->hrecv) {
2962
        CloseHandle(s->hrecv);
2963
        s->hrecv = NULL;
2964
    }
2965
    if (s->hcom) {
2966
        CloseHandle(s->hcom);
2967
        s->hcom = NULL;
2968
    }
2969
    if (s->fpipe)
2970
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2971
    else
2972
        qemu_del_polling_cb(win_chr_poll, chr);
2973
}
2974

    
2975
static int win_chr_init(CharDriverState *chr, const char *filename)
2976
{
2977
    WinCharState *s = chr->opaque;
2978
    COMMCONFIG comcfg;
2979
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2980
    COMSTAT comstat;
2981
    DWORD size;
2982
    DWORD err;
2983

    
2984
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2985
    if (!s->hsend) {
2986
        fprintf(stderr, "Failed CreateEvent\n");
2987
        goto fail;
2988
    }
2989
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2990
    if (!s->hrecv) {
2991
        fprintf(stderr, "Failed CreateEvent\n");
2992
        goto fail;
2993
    }
2994

    
2995
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2996
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2997
    if (s->hcom == INVALID_HANDLE_VALUE) {
2998
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2999
        s->hcom = NULL;
3000
        goto fail;
3001
    }
3002

    
3003
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3004
        fprintf(stderr, "Failed SetupComm\n");
3005
        goto fail;
3006
    }
3007

    
3008
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3009
    size = sizeof(COMMCONFIG);
3010
    GetDefaultCommConfig(filename, &comcfg, &size);
3011
    comcfg.dcb.DCBlength = sizeof(DCB);
3012
    CommConfigDialog(filename, NULL, &comcfg);
3013

    
3014
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
3015
        fprintf(stderr, "Failed SetCommState\n");
3016
        goto fail;
3017
    }
3018

    
3019
    if (!SetCommMask(s->hcom, EV_ERR)) {
3020
        fprintf(stderr, "Failed SetCommMask\n");
3021
        goto fail;
3022
    }
3023

    
3024
    cto.ReadIntervalTimeout = MAXDWORD;
3025
    if (!SetCommTimeouts(s->hcom, &cto)) {
3026
        fprintf(stderr, "Failed SetCommTimeouts\n");
3027
        goto fail;
3028
    }
3029

    
3030
    if (!ClearCommError(s->hcom, &err, &comstat)) {
3031
        fprintf(stderr, "Failed ClearCommError\n");
3032
        goto fail;
3033
    }
3034
    qemu_add_polling_cb(win_chr_poll, chr);
3035
    return 0;
3036

    
3037
 fail:
3038
    win_chr_close(chr);
3039
    return -1;
3040
}
3041

    
3042
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3043
{
3044
    WinCharState *s = chr->opaque;
3045
    DWORD len, ret, size, err;
3046

    
3047
    len = len1;
3048
    ZeroMemory(&s->osend, sizeof(s->osend));
3049
    s->osend.hEvent = s->hsend;
3050
    while (len > 0) {
3051
        if (s->hsend)
3052
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3053
        else
3054
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
3055
        if (!ret) {
3056
            err = GetLastError();
3057
            if (err == ERROR_IO_PENDING) {
3058
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3059
                if (ret) {
3060
                    buf += size;
3061
                    len -= size;
3062
                } else {
3063
                    break;
3064
                }
3065
            } else {
3066
                break;
3067
            }
3068
        } else {
3069
            buf += size;
3070
            len -= size;
3071
        }
3072
    }
3073
    return len1 - len;
3074
}
3075

    
3076
static int win_chr_read_poll(CharDriverState *chr)
3077
{
3078
    WinCharState *s = chr->opaque;
3079

    
3080
    s->max_size = qemu_chr_can_read(chr);
3081
    return s->max_size;
3082
}
3083

    
3084
static void win_chr_readfile(CharDriverState *chr)
3085
{
3086
    WinCharState *s = chr->opaque;
3087
    int ret, err;
3088
    uint8_t buf[1024];
3089
    DWORD size;
3090

    
3091
    ZeroMemory(&s->orecv, sizeof(s->orecv));
3092
    s->orecv.hEvent = s->hrecv;
3093
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3094
    if (!ret) {
3095
        err = GetLastError();
3096
        if (err == ERROR_IO_PENDING) {
3097
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3098
        }
3099
    }
3100

    
3101
    if (size > 0) {
3102
        qemu_chr_read(chr, buf, size);
3103
    }
3104
}
3105

    
3106
static void win_chr_read(CharDriverState *chr)
3107
{
3108
    WinCharState *s = chr->opaque;
3109

    
3110
    if (s->len > s->max_size)
3111
        s->len = s->max_size;
3112
    if (s->len == 0)
3113
        return;
3114

    
3115
    win_chr_readfile(chr);
3116
}
3117

    
3118
static int win_chr_poll(void *opaque)
3119
{
3120
    CharDriverState *chr = opaque;
3121
    WinCharState *s = chr->opaque;
3122
    COMSTAT status;
3123
    DWORD comerr;
3124

    
3125
    ClearCommError(s->hcom, &comerr, &status);
3126
    if (status.cbInQue > 0) {
3127
        s->len = status.cbInQue;
3128
        win_chr_read_poll(chr);
3129
        win_chr_read(chr);
3130
        return 1;
3131
    }
3132
    return 0;
3133
}
3134

    
3135
static CharDriverState *qemu_chr_open_win(const char *filename)
3136
{
3137
    CharDriverState *chr;
3138
    WinCharState *s;
3139

    
3140
    chr = qemu_mallocz(sizeof(CharDriverState));
3141
    if (!chr)
3142
        return NULL;
3143
    s = qemu_mallocz(sizeof(WinCharState));
3144
    if (!s) {
3145
        free(chr);
3146
        return NULL;
3147
    }
3148
    chr->opaque = s;
3149
    chr->chr_write = win_chr_write;
3150
    chr->chr_close = win_chr_close;
3151

    
3152
    if (win_chr_init(chr, filename) < 0) {
3153
        free(s);
3154
        free(chr);
3155
        return NULL;
3156
    }
3157
    qemu_chr_reset(chr);
3158
    return chr;
3159
}
3160

    
3161
static int win_chr_pipe_poll(void *opaque)
3162
{
3163
    CharDriverState *chr = opaque;
3164
    WinCharState *s = chr->opaque;
3165
    DWORD size;
3166

    
3167
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3168
    if (size > 0) {
3169
        s->len = size;
3170
        win_chr_read_poll(chr);
3171
        win_chr_read(chr);
3172
        return 1;
3173
    }
3174
    return 0;
3175
}
3176

    
3177
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3178
{
3179
    WinCharState *s = chr->opaque;
3180
    OVERLAPPED ov;
3181
    int ret;
3182
    DWORD size;
3183
    char openname[256];
3184

    
3185
    s->fpipe = TRUE;
3186

    
3187
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3188
    if (!s->hsend) {
3189
        fprintf(stderr, "Failed CreateEvent\n");
3190
        goto fail;
3191
    }
3192
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3193
    if (!s->hrecv) {
3194
        fprintf(stderr, "Failed CreateEvent\n");
3195
        goto fail;
3196
    }
3197

    
3198
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3199
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3200
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3201
                              PIPE_WAIT,
3202
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3203
    if (s->hcom == INVALID_HANDLE_VALUE) {
3204
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3205
        s->hcom = NULL;
3206
        goto fail;
3207
    }
3208

    
3209
    ZeroMemory(&ov, sizeof(ov));
3210
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3211
    ret = ConnectNamedPipe(s->hcom, &ov);
3212
    if (ret) {
3213
        fprintf(stderr, "Failed ConnectNamedPipe\n");
3214
        goto fail;
3215
    }
3216

    
3217
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3218
    if (!ret) {
3219
        fprintf(stderr, "Failed GetOverlappedResult\n");
3220
        if (ov.hEvent) {
3221
            CloseHandle(ov.hEvent);
3222
            ov.hEvent = NULL;
3223
        }
3224
        goto fail;
3225
    }
3226

    
3227
    if (ov.hEvent) {
3228
        CloseHandle(ov.hEvent);
3229
        ov.hEvent = NULL;
3230
    }
3231
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
3232
    return 0;
3233

    
3234
 fail:
3235
    win_chr_close(chr);
3236
    return -1;
3237
}
3238

    
3239

    
3240
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3241
{
3242
    CharDriverState *chr;
3243
    WinCharState *s;
3244

    
3245
    chr = qemu_mallocz(sizeof(CharDriverState));
3246
    if (!chr)
3247
        return NULL;
3248
    s = qemu_mallocz(sizeof(WinCharState));
3249
    if (!s) {
3250
        free(chr);
3251
        return NULL;
3252
    }
3253
    chr->opaque = s;
3254
    chr->chr_write = win_chr_write;
3255
    chr->chr_close = win_chr_close;
3256

    
3257
    if (win_chr_pipe_init(chr, filename) < 0) {
3258
        free(s);
3259
        free(chr);
3260
        return NULL;
3261
    }
3262
    qemu_chr_reset(chr);
3263
    return chr;
3264
}
3265

    
3266
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3267
{
3268
    CharDriverState *chr;
3269
    WinCharState *s;
3270

    
3271
    chr = qemu_mallocz(sizeof(CharDriverState));
3272
    if (!chr)
3273
        return NULL;
3274
    s = qemu_mallocz(sizeof(WinCharState));
3275
    if (!s) {
3276
        free(chr);
3277
        return NULL;
3278
    }
3279
    s->hcom = fd_out;
3280
    chr->opaque = s;
3281
    chr->chr_write = win_chr_write;
3282
    qemu_chr_reset(chr);
3283
    return chr;
3284
}
3285

    
3286
static CharDriverState *qemu_chr_open_win_con(const char *filename)
3287
{
3288
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3289
}
3290

    
3291
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3292
{
3293
    HANDLE fd_out;
3294

    
3295
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3296
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3297
    if (fd_out == INVALID_HANDLE_VALUE)
3298
        return NULL;
3299

    
3300
    return qemu_chr_open_win_file(fd_out);
3301
}
3302
#endif /* !_WIN32 */
3303

    
3304
/***********************************************************/
3305
/* UDP Net console */
3306

    
3307
typedef struct {
3308
    int fd;
3309
    struct sockaddr_in daddr;
3310
    uint8_t buf[1024];
3311
    int bufcnt;
3312
    int bufptr;
3313
    int max_size;
3314
} NetCharDriver;
3315

    
3316
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3317
{
3318
    NetCharDriver *s = chr->opaque;
3319

    
3320
    return sendto(s->fd, buf, len, 0,
3321
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3322
}
3323

    
3324
static int udp_chr_read_poll(void *opaque)
3325
{
3326
    CharDriverState *chr = opaque;
3327
    NetCharDriver *s = chr->opaque;
3328

    
3329
    s->max_size = qemu_chr_can_read(chr);
3330

    
3331
    /* If there were any stray characters in the queue process them
3332
     * first
3333
     */
3334
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3335
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3336
        s->bufptr++;
3337
        s->max_size = qemu_chr_can_read(chr);
3338
    }
3339
    return s->max_size;
3340
}
3341

    
3342
static void udp_chr_read(void *opaque)
3343
{
3344
    CharDriverState *chr = opaque;
3345
    NetCharDriver *s = chr->opaque;
3346

    
3347
    if (s->max_size == 0)
3348
        return;
3349
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3350
    s->bufptr = s->bufcnt;
3351
    if (s->bufcnt <= 0)
3352
        return;
3353

    
3354
    s->bufptr = 0;
3355
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3356
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3357
        s->bufptr++;
3358
        s->max_size = qemu_chr_can_read(chr);
3359
    }
3360
}
3361

    
3362
static void udp_chr_update_read_handler(CharDriverState *chr)
3363
{
3364
    NetCharDriver *s = chr->opaque;
3365

    
3366
    if (s->fd >= 0) {
3367
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3368
                             udp_chr_read, NULL, chr);
3369
    }
3370
}
3371

    
3372
int parse_host_port(struct sockaddr_in *saddr, const char *str);
3373
#ifndef _WIN32
3374
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3375
#endif
3376
int parse_host_src_port(struct sockaddr_in *haddr,
3377
                        struct sockaddr_in *saddr,
3378
                        const char *str);
3379

    
3380
static CharDriverState *qemu_chr_open_udp(const char *def)
3381
{
3382
    CharDriverState *chr = NULL;
3383
    NetCharDriver *s = NULL;
3384
    int fd = -1;
3385
    struct sockaddr_in saddr;
3386

    
3387
    chr = qemu_mallocz(sizeof(CharDriverState));
3388
    if (!chr)
3389
        goto return_err;
3390
    s = qemu_mallocz(sizeof(NetCharDriver));
3391
    if (!s)
3392
        goto return_err;
3393

    
3394
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3395
    if (fd < 0) {
3396
        perror("socket(PF_INET, SOCK_DGRAM)");
3397
        goto return_err;
3398
    }
3399

    
3400
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3401
        printf("Could not parse: %s\n", def);
3402
        goto return_err;
3403
    }
3404

    
3405
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3406
    {
3407
        perror("bind");
3408
        goto return_err;
3409
    }
3410

    
3411
    s->fd = fd;
3412
    s->bufcnt = 0;
3413
    s->bufptr = 0;
3414
    chr->opaque = s;
3415
    chr->chr_write = udp_chr_write;
3416
    chr->chr_update_read_handler = udp_chr_update_read_handler;
3417
    return chr;
3418

    
3419
return_err:
3420
    if (chr)
3421
        free(chr);
3422
    if (s)
3423
        free(s);
3424
    if (fd >= 0)
3425
        closesocket(fd);
3426
    return NULL;
3427
}
3428

    
3429
/***********************************************************/
3430
/* TCP Net console */
3431

    
3432
typedef struct {
3433
    int fd, listen_fd;
3434
    int connected;
3435
    int max_size;
3436
    int do_telnetopt;
3437
    int do_nodelay;
3438
    int is_unix;
3439
} TCPCharDriver;
3440

    
3441
static void tcp_chr_accept(void *opaque);
3442

    
3443
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3444
{
3445
    TCPCharDriver *s = chr->opaque;
3446
    if (s->connected) {
3447
        return send_all(s->fd, buf, len);
3448
    } else {
3449
        /* XXX: indicate an error ? */
3450
        return len;
3451
    }
3452
}
3453

    
3454
static int tcp_chr_read_poll(void *opaque)
3455
{
3456
    CharDriverState *chr = opaque;
3457
    TCPCharDriver *s = chr->opaque;
3458
    if (!s->connected)
3459
        return 0;
3460
    s->max_size = qemu_chr_can_read(chr);
3461
    return s->max_size;
3462
}
3463

    
3464
#define IAC 255
3465
#define IAC_BREAK 243
3466
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3467
                                      TCPCharDriver *s,
3468
                                      uint8_t *buf, int *size)
3469
{
3470
    /* Handle any telnet client's basic IAC options to satisfy char by
3471
     * char mode with no echo.  All IAC options will be removed from
3472
     * the buf and the do_telnetopt variable will be used to track the
3473
     * state of the width of the IAC information.
3474
     *
3475
     * IAC commands come in sets of 3 bytes with the exception of the
3476
     * "IAC BREAK" command and the double IAC.
3477
     */
3478

    
3479
    int i;
3480
    int j = 0;
3481

    
3482
    for (i = 0; i < *size; i++) {
3483
        if (s->do_telnetopt > 1) {
3484
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3485
                /* Double IAC means send an IAC */
3486
                if (j != i)
3487
                    buf[j] = buf[i];
3488
                j++;
3489
                s->do_telnetopt = 1;
3490
            } else {
3491
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3492
                    /* Handle IAC break commands by sending a serial break */
3493
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3494
                    s->do_telnetopt++;
3495
                }
3496
                s->do_telnetopt++;
3497
            }
3498
            if (s->do_telnetopt >= 4) {
3499
                s->do_telnetopt = 1;
3500
            }
3501
        } else {
3502
            if ((unsigned char)buf[i] == IAC) {
3503
                s->do_telnetopt = 2;
3504
            } else {
3505
                if (j != i)
3506
                    buf[j] = buf[i];
3507
                j++;
3508
            }
3509
        }
3510
    }
3511
    *size = j;
3512
}
3513

    
3514
static void tcp_chr_read(void *opaque)
3515
{
3516
    CharDriverState *chr = opaque;
3517
    TCPCharDriver *s = chr->opaque;
3518
    uint8_t buf[1024];
3519
    int len, size;
3520

    
3521
    if (!s->connected || s->max_size <= 0)
3522
        return;
3523
    len = sizeof(buf);
3524
    if (len > s->max_size)
3525
        len = s->max_size;
3526
    size = recv(s->fd, buf, len, 0);
3527
    if (size == 0) {
3528
        /* connection closed */
3529
        s->connected = 0;
3530
        if (s->listen_fd >= 0) {
3531
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3532
        }
3533
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3534
        closesocket(s->fd);
3535
        s->fd = -1;
3536
    } else if (size > 0) {
3537
        if (s->do_telnetopt)
3538
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3539
        if (size > 0)
3540
            qemu_chr_read(chr, buf, size);
3541
    }
3542
}
3543

    
3544
static void tcp_chr_connect(void *opaque)
3545
{
3546
    CharDriverState *chr = opaque;
3547
    TCPCharDriver *s = chr->opaque;
3548

    
3549
    s->connected = 1;
3550
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3551
                         tcp_chr_read, NULL, chr);
3552
    qemu_chr_reset(chr);
3553
}
3554

    
3555
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3556
static void tcp_chr_telnet_init(int fd)
3557
{
3558
    char buf[3];
3559
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3560
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3561
    send(fd, (char *)buf, 3, 0);
3562
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3563
    send(fd, (char *)buf, 3, 0);
3564
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3565
    send(fd, (char *)buf, 3, 0);
3566
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3567
    send(fd, (char *)buf, 3, 0);
3568
}
3569

    
3570
static void socket_set_nodelay(int fd)
3571
{
3572
    int val = 1;
3573
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3574
}
3575

    
3576
static void tcp_chr_accept(void *opaque)
3577
{
3578
    CharDriverState *chr = opaque;
3579
    TCPCharDriver *s = chr->opaque;
3580
    struct sockaddr_in saddr;
3581
#ifndef _WIN32
3582
    struct sockaddr_un uaddr;
3583
#endif
3584
    struct sockaddr *addr;
3585
    socklen_t len;
3586
    int fd;
3587

    
3588
    for(;;) {
3589
#ifndef _WIN32
3590
        if (s->is_unix) {
3591
            len = sizeof(uaddr);
3592
            addr = (struct sockaddr *)&uaddr;
3593
        } else
3594
#endif
3595
        {
3596
            len = sizeof(saddr);
3597
            addr = (struct sockaddr *)&saddr;
3598
        }
3599
        fd = accept(s->listen_fd, addr, &len);
3600
        if (fd < 0 && errno != EINTR) {
3601
            return;
3602
        } else if (fd >= 0) {
3603
            if (s->do_telnetopt)
3604
                tcp_chr_telnet_init(fd);
3605
            break;
3606
        }
3607
    }
3608
    socket_set_nonblock(fd);
3609
    if (s->do_nodelay)
3610
        socket_set_nodelay(fd);
3611
    s->fd = fd;
3612
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3613
    tcp_chr_connect(chr);
3614
}
3615

    
3616
static void tcp_chr_close(CharDriverState *chr)
3617
{
3618
    TCPCharDriver *s = chr->opaque;
3619
    if (s->fd >= 0)
3620
        closesocket(s->fd);
3621
    if (s->listen_fd >= 0)
3622
        closesocket(s->listen_fd);
3623
    qemu_free(s);
3624
}
3625

    
3626
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3627
                                          int is_telnet,
3628
                                          int is_unix)
3629
{
3630
    CharDriverState *chr = NULL;
3631
    TCPCharDriver *s = NULL;
3632
    int fd = -1, ret, err, val;
3633
    int is_listen = 0;
3634
    int is_waitconnect = 1;
3635
    int do_nodelay = 0;
3636
    const char *ptr;
3637
    struct sockaddr_in saddr;
3638
#ifndef _WIN32
3639
    struct sockaddr_un uaddr;
3640
#endif
3641
    struct sockaddr *addr;
3642
    socklen_t addrlen;
3643

    
3644
#ifndef _WIN32
3645
    if (is_unix) {
3646
        addr = (struct sockaddr *)&uaddr;
3647
        addrlen = sizeof(uaddr);
3648
        if (parse_unix_path(&uaddr, host_str) < 0)
3649
            goto fail;
3650
    } else
3651
#endif
3652
    {
3653
        addr = (struct sockaddr *)&saddr;
3654
        addrlen = sizeof(saddr);
3655
        if (parse_host_port(&saddr, host_str) < 0)
3656
            goto fail;
3657
    }
3658

    
3659
    ptr = host_str;
3660
    while((ptr = strchr(ptr,','))) {
3661
        ptr++;
3662
        if (!strncmp(ptr,"server",6)) {
3663
            is_listen = 1;
3664
        } else if (!strncmp(ptr,"nowait",6)) {
3665
            is_waitconnect = 0;
3666
        } else if (!strncmp(ptr,"nodelay",6)) {
3667
            do_nodelay = 1;
3668
        } else {
3669
            printf("Unknown option: %s\n", ptr);
3670
            goto fail;
3671
        }
3672
    }
3673
    if (!is_listen)
3674
        is_waitconnect = 0;
3675

    
3676
    chr = qemu_mallocz(sizeof(CharDriverState));
3677
    if (!chr)
3678
        goto fail;
3679
    s = qemu_mallocz(sizeof(TCPCharDriver));
3680
    if (!s)
3681
        goto fail;
3682

    
3683
#ifndef _WIN32
3684
    if (is_unix)
3685
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3686
    else
3687
#endif
3688
        fd = socket(PF_INET, SOCK_STREAM, 0);
3689

    
3690
    if (fd < 0)
3691
        goto fail;
3692

    
3693
    if (!is_waitconnect)
3694
        socket_set_nonblock(fd);
3695

    
3696
    s->connected = 0;
3697
    s->fd = -1;
3698
    s->listen_fd = -1;
3699
    s->is_unix = is_unix;
3700
    s->do_nodelay = do_nodelay && !is_unix;
3701

    
3702
    chr->opaque = s;
3703
    chr->chr_write = tcp_chr_write;
3704
    chr->chr_close = tcp_chr_close;
3705

    
3706
    if (is_listen) {
3707
        /* allow fast reuse */
3708
#ifndef _WIN32
3709
        if (is_unix) {
3710
            char path[109];
3711
            pstrcpy(path, sizeof(path), uaddr.sun_path);
3712
            unlink(path);
3713
        } else
3714
#endif
3715
        {
3716
            val = 1;
3717
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3718
        }
3719

    
3720
        ret = bind(fd, addr, addrlen);
3721
        if (ret < 0)
3722
            goto fail;
3723

    
3724
        ret = listen(fd, 0);
3725
        if (ret < 0)
3726
            goto fail;
3727

    
3728
        s->listen_fd = fd;
3729
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3730
        if (is_telnet)
3731
            s->do_telnetopt = 1;
3732
    } else {
3733
        for(;;) {
3734
            ret = connect(fd, addr, addrlen);
3735
            if (ret < 0) {
3736
                err = socket_error();
3737
                if (err == EINTR || err == EWOULDBLOCK) {
3738
                } else if (err == EINPROGRESS) {
3739
                    break;
3740
#ifdef _WIN32
3741
                } else if (err == WSAEALREADY) {
3742
                    break;
3743
#endif
3744
                } else {
3745
                    goto fail;
3746
                }
3747
            } else {
3748
                s->connected = 1;
3749
                break;
3750
            }
3751
        }
3752
        s->fd = fd;
3753
        socket_set_nodelay(fd);
3754
        if (s->connected)
3755
            tcp_chr_connect(chr);
3756
        else
3757
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3758
    }
3759

    
3760
    if (is_listen && is_waitconnect) {
3761
        printf("QEMU waiting for connection on: %s\n", host_str);
3762
        tcp_chr_accept(chr);
3763
        socket_set_nonblock(s->listen_fd);
3764
    }
3765

    
3766
    return chr;
3767
 fail:
3768
    if (fd >= 0)
3769
        closesocket(fd);
3770
    qemu_free(s);
3771
    qemu_free(chr);
3772
    return NULL;
3773
}
3774

    
3775
CharDriverState *qemu_chr_open(const char *filename)
3776
{
3777
    const char *p;
3778

    
3779
    if (!strcmp(filename, "vc")) {
3780
        return text_console_init(&display_state, 0);
3781
    } else if (strstart(filename, "vc:", &p)) {
3782
        return text_console_init(&display_state, p);
3783
    } else if (!strcmp(filename, "null")) {
3784
        return qemu_chr_open_null();
3785
    } else
3786
    if (strstart(filename, "tcp:", &p)) {
3787
        return qemu_chr_open_tcp(p, 0, 0);
3788
    } else
3789
    if (strstart(filename, "telnet:", &p)) {
3790
        return qemu_chr_open_tcp(p, 1, 0);
3791
    } else
3792
    if (strstart(filename, "udp:", &p)) {
3793
        return qemu_chr_open_udp(p);
3794
    } else
3795
    if (strstart(filename, "mon:", &p)) {
3796
        CharDriverState *drv = qemu_chr_open(p);
3797
        if (drv) {
3798
            drv = qemu_chr_open_mux(drv);
3799
            monitor_init(drv, !nographic);
3800
            return drv;
3801
        }
3802
        printf("Unable to open driver: %s\n", p);
3803
        return 0;
3804
    } else
3805
#ifndef _WIN32
3806
    if (strstart(filename, "unix:", &p)) {
3807
        return qemu_chr_open_tcp(p, 0, 1);
3808
    } else if (strstart(filename, "file:", &p)) {
3809
        return qemu_chr_open_file_out(p);
3810
    } else if (strstart(filename, "pipe:", &p)) {
3811
        return qemu_chr_open_pipe(p);
3812
    } else if (!strcmp(filename, "pty")) {
3813
        return qemu_chr_open_pty();
3814
    } else if (!strcmp(filename, "stdio")) {
3815
        return qemu_chr_open_stdio();
3816
    } else
3817
#if defined(__linux__)
3818
    if (strstart(filename, "/dev/parport", NULL)) {
3819
        return qemu_chr_open_pp(filename);
3820
    } else
3821
#endif
3822
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3823
    || defined(__NetBSD__) || defined(__OpenBSD__)
3824
    if (strstart(filename, "/dev/", NULL)) {
3825
        return qemu_chr_open_tty(filename);
3826
    } else
3827
#endif
3828
#else /* !_WIN32 */
3829
    if (strstart(filename, "COM", NULL)) {
3830
        return qemu_chr_open_win(filename);
3831
    } else
3832
    if (strstart(filename, "pipe:", &p)) {
3833
        return qemu_chr_open_win_pipe(p);
3834
    } else
3835
    if (strstart(filename, "con:", NULL)) {
3836
        return qemu_chr_open_win_con(filename);
3837
    } else
3838
    if (strstart(filename, "file:", &p)) {
3839
        return qemu_chr_open_win_file_out(p);
3840
    } else
3841
#endif
3842
#ifdef CONFIG_BRLAPI
3843
    if (!strcmp(filename, "braille")) {
3844
        return chr_baum_init();
3845
    } else
3846
#endif
3847
    {
3848
        return NULL;
3849
    }
3850
}
3851

    
3852
void qemu_chr_close(CharDriverState *chr)
3853
{
3854
    if (chr->chr_close)
3855
        chr->chr_close(chr);
3856
    qemu_free(chr);
3857
}
3858

    
3859
/***********************************************************/
3860
/* network device redirectors */
3861

    
3862
__attribute__ (( unused ))
3863
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3864
{
3865
    int len, i, j, c;
3866

    
3867
    for(i=0;i<size;i+=16) {
3868
        len = size - i;
3869
        if (len > 16)
3870
            len = 16;
3871
        fprintf(f, "%08x ", i);
3872
        for(j=0;j<16;j++) {
3873
            if (j < len)
3874
                fprintf(f, " %02x", buf[i+j]);
3875
            else
3876
                fprintf(f, "   ");
3877
        }
3878
        fprintf(f, " ");
3879
        for(j=0;j<len;j++) {
3880
            c = buf[i+j];
3881
            if (c < ' ' || c > '~')
3882
                c = '.';
3883
            fprintf(f, "%c", c);
3884
        }
3885
        fprintf(f, "\n");
3886
    }
3887
}
3888

    
3889
static int parse_macaddr(uint8_t *macaddr, const char *p)
3890
{
3891
    int i;
3892
    char *last_char;
3893
    long int offset;
3894

    
3895
    errno = 0;
3896
    offset = strtol(p, &last_char, 0);    
3897
    if (0 == errno && '\0' == *last_char &&
3898
            offset >= 0 && offset <= 0xFFFFFF) {
3899
        macaddr[3] = (offset & 0xFF0000) >> 16;
3900
        macaddr[4] = (offset & 0xFF00) >> 8;
3901
        macaddr[5] = offset & 0xFF;
3902
        return 0;
3903
    } else {
3904
        for(i = 0; i < 6; i++) {
3905
            macaddr[i] = strtol(p, (char **)&p, 16);
3906
            if (i == 5) {
3907
                if (*p != '\0')
3908
                    return -1;
3909
            } else {
3910
                if (*p != ':' && *p != '-')
3911
                    return -1;
3912
                p++;
3913
            }
3914
        }
3915
        return 0;    
3916
    }
3917

    
3918
    return -1;
3919
}
3920

    
3921
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3922
{
3923
    const char *p, *p1;
3924
    int len;
3925
    p = *pp;
3926
    p1 = strchr(p, sep);
3927
    if (!p1)
3928
        return -1;
3929
    len = p1 - p;
3930
    p1++;
3931
    if (buf_size > 0) {
3932
        if (len > buf_size - 1)
3933
            len = buf_size - 1;
3934
        memcpy(buf, p, len);
3935
        buf[len] = '\0';
3936
    }
3937
    *pp = p1;
3938
    return 0;
3939
}
3940

    
3941
int parse_host_src_port(struct sockaddr_in *haddr,
3942
                        struct sockaddr_in *saddr,
3943
                        const char *input_str)
3944
{
3945
    char *str = strdup(input_str);
3946
    char *host_str = str;
3947
    char *src_str;
3948
    const char *src_str2;
3949
    char *ptr;
3950

    
3951
    /*
3952
     * Chop off any extra arguments at the end of the string which
3953
     * would start with a comma, then fill in the src port information
3954
     * if it was provided else use the "any address" and "any port".
3955
     */
3956
    if ((ptr = strchr(str,',')))
3957
        *ptr = '\0';
3958

    
3959
    if ((src_str = strchr(input_str,'@'))) {
3960
        *src_str = '\0';
3961
        src_str++;
3962
    }
3963

    
3964
    if (parse_host_port(haddr, host_str) < 0)
3965
        goto fail;
3966

    
3967
    src_str2 = src_str;
3968
    if (!src_str || *src_str == '\0')
3969
        src_str2 = ":0";
3970

    
3971
    if (parse_host_port(saddr, src_str2) < 0)
3972
        goto fail;
3973

    
3974
    free(str);
3975
    return(0);
3976

    
3977
fail:
3978
    free(str);
3979
    return -1;
3980
}
3981

    
3982
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3983
{
3984
    char buf[512];
3985
    struct hostent *he;
3986
    const char *p, *r;
3987
    int port;
3988

    
3989
    p = str;
3990
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3991
        return -1;
3992
    saddr->sin_family = AF_INET;
3993
    if (buf[0] == '\0') {
3994
        saddr->sin_addr.s_addr = 0;
3995
    } else {
3996
        if (isdigit(buf[0])) {
3997
            if (!inet_aton(buf, &saddr->sin_addr))
3998
                return -1;
3999
        } else {
4000
            if ((he = gethostbyname(buf)) == NULL)
4001
                return - 1;
4002
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
4003
        }
4004
    }
4005
    port = strtol(p, (char **)&r, 0);
4006
    if (r == p)
4007
        return -1;
4008
    saddr->sin_port = htons(port);
4009
    return 0;
4010
}
4011

    
4012
#ifndef _WIN32
4013
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4014
{
4015
    const char *p;
4016
    int len;
4017

    
4018
    len = MIN(108, strlen(str));
4019
    p = strchr(str, ',');
4020
    if (p)
4021
        len = MIN(len, p - str);
4022

    
4023
    memset(uaddr, 0, sizeof(*uaddr));
4024

    
4025
    uaddr->sun_family = AF_UNIX;
4026
    memcpy(uaddr->sun_path, str, len);
4027

    
4028
    return 0;
4029
}
4030
#endif
4031

    
4032
/* find or alloc a new VLAN */
4033
VLANState *qemu_find_vlan(int id)
4034
{
4035
    VLANState **pvlan, *vlan;
4036
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4037
        if (vlan->id == id)
4038
            return vlan;
4039
    }
4040
    vlan = qemu_mallocz(sizeof(VLANState));
4041
    if (!vlan)
4042
        return NULL;
4043
    vlan->id = id;
4044
    vlan->next = NULL;
4045
    pvlan = &first_vlan;
4046
    while (*pvlan != NULL)
4047
        pvlan = &(*pvlan)->next;
4048
    *pvlan = vlan;
4049
    return vlan;
4050
}
4051

    
4052
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4053
                                      IOReadHandler *fd_read,
4054
                                      IOCanRWHandler *fd_can_read,
4055
                                      void *opaque)
4056
{
4057
    VLANClientState *vc, **pvc;
4058
    vc = qemu_mallocz(sizeof(VLANClientState));
4059
    if (!vc)
4060
        return NULL;
4061
    vc->fd_read = fd_read;
4062
    vc->fd_can_read = fd_can_read;
4063
    vc->opaque = opaque;
4064
    vc->vlan = vlan;
4065

    
4066
    vc->next = NULL;
4067
    pvc = &vlan->first_client;
4068
    while (*pvc != NULL)
4069
        pvc = &(*pvc)->next;
4070
    *pvc = vc;
4071
    return vc;
4072
}
4073

    
4074
void qemu_del_vlan_client(VLANClientState *vc)
4075
{
4076
    VLANClientState **pvc = &vc->vlan->first_client;
4077

    
4078
    while (*pvc != NULL)
4079
        if (*pvc == vc) {
4080
            *pvc = vc->next;
4081
            free(vc);
4082
            break;
4083
        } else
4084
            pvc = &(*pvc)->next;
4085
}
4086

    
4087
int qemu_can_send_packet(VLANClientState *vc1)
4088
{
4089
    VLANState *vlan = vc1->vlan;
4090
    VLANClientState *vc;
4091

    
4092
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4093
        if (vc != vc1) {
4094
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4095
                return 1;
4096
        }
4097
    }
4098
    return 0;
4099
}
4100

    
4101
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4102
{
4103
    VLANState *vlan = vc1->vlan;
4104
    VLANClientState *vc;
4105

    
4106
#if 0
4107
    printf("vlan %d send:\n", vlan->id);
4108
    hex_dump(stdout, buf, size);
4109
#endif
4110
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4111
        if (vc != vc1) {
4112
            vc->fd_read(vc->opaque, buf, size);
4113
        }
4114
    }
4115
}
4116

    
4117
#if defined(CONFIG_SLIRP)
4118

    
4119
/* slirp network adapter */
4120

    
4121
static int slirp_inited;
4122
static VLANClientState *slirp_vc;
4123

    
4124
int slirp_can_output(void)
4125
{
4126
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
4127
}
4128

    
4129
void slirp_output(const uint8_t *pkt, int pkt_len)
4130
{
4131
#if 0
4132
    printf("slirp output:\n");
4133
    hex_dump(stdout, pkt, pkt_len);
4134
#endif
4135
    if (!slirp_vc)
4136
        return;
4137
    qemu_send_packet(slirp_vc, pkt, pkt_len);
4138
}
4139

    
4140
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4141
{
4142
#if 0
4143
    printf("slirp input:\n");
4144
    hex_dump(stdout, buf, size);
4145
#endif
4146
    slirp_input(buf, size);
4147
}
4148

    
4149
static int net_slirp_init(VLANState *vlan)
4150
{
4151
    if (!slirp_inited) {
4152
        slirp_inited = 1;
4153
        slirp_init();
4154
    }
4155
    slirp_vc = qemu_new_vlan_client(vlan,
4156
                                    slirp_receive, NULL, NULL);
4157
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4158
    return 0;
4159
}
4160

    
4161
static void net_slirp_redir(const char *redir_str)
4162
{
4163
    int is_udp;
4164
    char buf[256], *r;
4165
    const char *p;
4166
    struct in_addr guest_addr;
4167
    int host_port, guest_port;
4168

    
4169
    if (!slirp_inited) {
4170
        slirp_inited = 1;
4171
        slirp_init();
4172
    }
4173

    
4174
    p = redir_str;
4175
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4176
        goto fail;
4177
    if (!strcmp(buf, "tcp")) {
4178
        is_udp = 0;
4179
    } else if (!strcmp(buf, "udp")) {
4180
        is_udp = 1;
4181
    } else {
4182
        goto fail;
4183
    }
4184

    
4185
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4186
        goto fail;
4187
    host_port = strtol(buf, &r, 0);
4188
    if (r == buf)
4189
        goto fail;
4190

    
4191
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4192
        goto fail;
4193
    if (buf[0] == '\0') {
4194
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
4195
    }
4196
    if (!inet_aton(buf, &guest_addr))
4197
        goto fail;
4198

    
4199
    guest_port = strtol(p, &r, 0);
4200
    if (r == p)
4201
        goto fail;
4202

    
4203
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4204
        fprintf(stderr, "qemu: could not set up redirection\n");
4205
        exit(1);
4206
    }
4207
    return;
4208
 fail:
4209
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4210
    exit(1);
4211
}
4212

    
4213
#ifndef _WIN32
4214

    
4215
char smb_dir[1024];
4216

    
4217
static void erase_dir(char *dir_name)
4218
{
4219
    DIR *d;
4220
    struct dirent *de;
4221
    char filename[1024];
4222

    
4223
    /* erase all the files in the directory */
4224
    if ((d = opendir(dir_name)) != 0) {
4225
        for(;;) {
4226
            de = readdir(d);
4227
            if (!de)
4228
                break;
4229
            if (strcmp(de->d_name, ".") != 0 &&
4230
                strcmp(de->d_name, "..") != 0) {
4231
                snprintf(filename, sizeof(filename), "%s/%s",
4232
                         smb_dir, de->d_name);
4233
                if (unlink(filename) != 0)  /* is it a directory? */
4234
                    erase_dir(filename);
4235
            }
4236
        }
4237
        closedir(d);
4238
        rmdir(dir_name);
4239
    }
4240
}
4241

    
4242
/* automatic user mode samba server configuration */
4243
static void smb_exit(void)
4244
{
4245
    erase_dir(smb_dir);
4246
}
4247

    
4248
/* automatic user mode samba server configuration */
4249
static void net_slirp_smb(const char *exported_dir)
4250
{
4251
    char smb_conf[1024];
4252
    char smb_cmdline[1024];
4253
    FILE *f;
4254

    
4255
    if (!slirp_inited) {
4256
        slirp_inited = 1;
4257
        slirp_init();
4258
    }
4259

    
4260
    /* XXX: better tmp dir construction */
4261
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4262
    if (mkdir(smb_dir, 0700) < 0) {
4263
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4264
        exit(1);
4265
    }
4266
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4267

    
4268
    f = fopen(smb_conf, "w");
4269
    if (!f) {
4270
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4271
        exit(1);
4272
    }
4273
    fprintf(f,
4274
            "[global]\n"
4275
            "private dir=%s\n"
4276
            "smb ports=0\n"
4277
            "socket address=127.0.0.1\n"
4278
            "pid directory=%s\n"
4279
            "lock directory=%s\n"
4280
            "log file=%s/log.smbd\n"
4281
            "smb passwd file=%s/smbpasswd\n"
4282
            "security = share\n"
4283
            "[qemu]\n"
4284
            "path=%s\n"
4285
            "read only=no\n"
4286
            "guest ok=yes\n",
4287
            smb_dir,
4288
            smb_dir,
4289
            smb_dir,
4290
            smb_dir,
4291
            smb_dir,
4292
            exported_dir
4293
            );
4294
    fclose(f);
4295
    atexit(smb_exit);
4296

    
4297
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4298
             SMBD_COMMAND, smb_conf);
4299

    
4300
    slirp_add_exec(0, smb_cmdline, 4, 139);
4301
}
4302

    
4303
#endif /* !defined(_WIN32) */
4304
void do_info_slirp(void)
4305
{
4306
    slirp_stats();
4307
}
4308

    
4309
#endif /* CONFIG_SLIRP */
4310

    
4311
#if !defined(_WIN32)
4312

    
4313
typedef struct TAPState {
4314
    VLANClientState *vc;
4315
    int fd;
4316
    char down_script[1024];
4317
} TAPState;
4318

    
4319
static void tap_receive(void *opaque, const uint8_t *buf, int size)
4320
{
4321
    TAPState *s = opaque;
4322
    int ret;
4323
    for(;;) {
4324
        ret = write(s->fd, buf, size);
4325
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4326
        } else {
4327
            break;
4328
        }
4329
    }
4330
}
4331

    
4332
static void tap_send(void *opaque)
4333
{
4334
    TAPState *s = opaque;
4335
    uint8_t buf[4096];
4336
    int size;
4337

    
4338
#ifdef __sun__
4339
    struct strbuf sbuf;
4340
    int f = 0;
4341
    sbuf.maxlen = sizeof(buf);
4342
    sbuf.buf = buf;
4343
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4344
#else
4345
    size = read(s->fd, buf, sizeof(buf));
4346
#endif
4347
    if (size > 0) {
4348
        qemu_send_packet(s->vc, buf, size);
4349
    }
4350
}
4351

    
4352
/* fd support */
4353

    
4354
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4355
{
4356
    TAPState *s;
4357

    
4358
    s = qemu_mallocz(sizeof(TAPState));
4359
    if (!s)
4360
        return NULL;
4361
    s->fd = fd;
4362
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4363
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4364
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4365
    return s;
4366
}
4367

    
4368
#if defined (_BSD) || defined (__FreeBSD_kernel__)
4369
static int tap_open(char *ifname, int ifname_size)
4370
{
4371
    int fd;
4372
    char *dev;
4373
    struct stat s;
4374

    
4375
    TFR(fd = open("/dev/tap", O_RDWR));
4376
    if (fd < 0) {
4377
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4378
        return -1;
4379
    }
4380

    
4381
    fstat(fd, &s);
4382
    dev = devname(s.st_rdev, S_IFCHR);
4383
    pstrcpy(ifname, ifname_size, dev);
4384

    
4385
    fcntl(fd, F_SETFL, O_NONBLOCK);
4386
    return fd;
4387
}
4388
#elif defined(__sun__)
4389
#define TUNNEWPPA       (('T'<<16) | 0x0001)
4390
/*
4391
 * Allocate TAP device, returns opened fd.
4392
 * Stores dev name in the first arg(must be large enough).
4393
 */
4394
int tap_alloc(char *dev, size_t dev_size)
4395
{
4396
    int tap_fd, if_fd, ppa = -1;
4397
    static int ip_fd = 0;
4398
    char *ptr;
4399

    
4400
    static int arp_fd = 0;
4401
    int ip_muxid, arp_muxid;
4402
    struct strioctl  strioc_if, strioc_ppa;
4403
    int link_type = I_PLINK;;
4404
    struct lifreq ifr;
4405
    char actual_name[32] = "";
4406

    
4407
    memset(&ifr, 0x0, sizeof(ifr));
4408

    
4409
    if( *dev ){
4410
       ptr = dev;
4411
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
4412
       ppa = atoi(ptr);
4413
    }
4414

    
4415
    /* Check if IP device was opened */
4416
    if( ip_fd )
4417
       close(ip_fd);
4418

    
4419
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4420
    if (ip_fd < 0) {
4421
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4422
       return -1;
4423
    }
4424

    
4425
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4426
    if (tap_fd < 0) {
4427
       syslog(LOG_ERR, "Can't open /dev/tap");
4428
       return -1;
4429
    }
4430

    
4431
    /* Assign a new PPA and get its unit number. */
4432
    strioc_ppa.ic_cmd = TUNNEWPPA;
4433
    strioc_ppa.ic_timout = 0;
4434
    strioc_ppa.ic_len = sizeof(ppa);
4435
    strioc_ppa.ic_dp = (char *)&ppa;
4436
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4437
       syslog (LOG_ERR, "Can't assign new interface");
4438

    
4439
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4440
    if (if_fd < 0) {
4441
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
4442
       return -1;
4443
    }
4444
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
4445
       syslog(LOG_ERR, "Can't push IP module");
4446
       return -1;
4447
    }
4448

    
4449
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4450
        syslog(LOG_ERR, "Can't get flags\n");
4451

    
4452
    snprintf (actual_name, 32, "tap%d", ppa);
4453
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4454

    
4455
    ifr.lifr_ppa = ppa;
4456
    /* Assign ppa according to the unit number returned by tun device */
4457

    
4458
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4459
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
4460
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4461
        syslog (LOG_ERR, "Can't get flags\n");
4462
    /* Push arp module to if_fd */
4463
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
4464
        syslog (LOG_ERR, "Can't push ARP module (2)");
4465

    
4466
    /* Push arp module to ip_fd */
4467
    if (ioctl (ip_fd, I_POP, NULL) < 0)
4468
        syslog (LOG_ERR, "I_POP failed\n");
4469
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4470
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
4471
    /* Open arp_fd */
4472
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4473
    if (arp_fd < 0)
4474
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4475

    
4476
    /* Set ifname to arp */
4477
    strioc_if.ic_cmd = SIOCSLIFNAME;
4478
    strioc_if.ic_timout = 0;
4479
    strioc_if.ic_len = sizeof(ifr);
4480
    strioc_if.ic_dp = (char *)&ifr;
4481
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4482
        syslog (LOG_ERR, "Can't set ifname to arp\n");
4483
    }
4484

    
4485
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4486
       syslog(LOG_ERR, "Can't link TAP device to IP");
4487
       return -1;
4488
    }
4489

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

    
4493
    close (if_fd);
4494

    
4495
    memset(&ifr, 0x0, sizeof(ifr));
4496
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4497
    ifr.lifr_ip_muxid  = ip_muxid;
4498
    ifr.lifr_arp_muxid = arp_muxid;
4499

    
4500
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4501
    {
4502
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4503
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4504
      syslog (LOG_ERR, "Can't set multiplexor id");
4505
    }
4506

    
4507
    snprintf(dev, dev_size, "tap%d", ppa);
4508
    return tap_fd;
4509
}
4510

    
4511
static int tap_open(char *ifname, int ifname_size)
4512
{
4513
    char  dev[10]="";
4514
    int fd;
4515
    if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4516
       fprintf(stderr, "Cannot allocate TAP device\n");
4517
       return -1;
4518
    }
4519
    pstrcpy(ifname, ifname_size, dev);
4520
    fcntl(fd, F_SETFL, O_NONBLOCK);
4521
    return fd;
4522
}
4523
#else
4524
static int tap_open(char *ifname, int ifname_size)
4525
{
4526
    struct ifreq ifr;
4527
    int fd, ret;
4528

    
4529
    TFR(fd = open("/dev/net/tun", O_RDWR));
4530
    if (fd < 0) {
4531
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4532
        return -1;
4533
    }
4534
    memset(&ifr, 0, sizeof(ifr));
4535
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4536
    if (ifname[0] != '\0')
4537
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4538
    else
4539
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4540
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4541
    if (ret != 0) {
4542
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4543
        close(fd);
4544
        return -1;
4545
    }
4546
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4547
    fcntl(fd, F_SETFL, O_NONBLOCK);
4548
    return fd;
4549
}
4550
#endif
4551

    
4552
static int launch_script(const char *setup_script, const char *ifname, int fd)
4553
{
4554
    int pid, status;
4555
    char *args[3];
4556
    char **parg;
4557

    
4558
        /* try to launch network script */
4559
        pid = fork();
4560
        if (pid >= 0) {
4561
            if (pid == 0) {
4562
                int open_max = sysconf (_SC_OPEN_MAX), i;
4563
                for (i = 0; i < open_max; i++)
4564
                    if (i != STDIN_FILENO &&
4565
                        i != STDOUT_FILENO &&
4566
                        i != STDERR_FILENO &&
4567
                        i != fd)
4568
                        close(i);
4569

    
4570
                parg = args;
4571
                *parg++ = (char *)setup_script;
4572
                *parg++ = (char *)ifname;
4573
                *parg++ = NULL;
4574
                execv(setup_script, args);
4575
                _exit(1);
4576
            }
4577
            while (waitpid(pid, &status, 0) != pid);
4578
            if (!WIFEXITED(status) ||
4579
                WEXITSTATUS(status) != 0) {
4580
                fprintf(stderr, "%s: could not launch network script\n",
4581
                        setup_script);
4582
                return -1;
4583
            }
4584
        }
4585
    return 0;
4586
}
4587

    
4588
static int net_tap_init(VLANState *vlan, const char *ifname1,
4589
                        const char *setup_script, const char *down_script)
4590
{
4591
    TAPState *s;
4592
    int fd;
4593
    char ifname[128];
4594

    
4595
    if (ifname1 != NULL)
4596
        pstrcpy(ifname, sizeof(ifname), ifname1);
4597
    else
4598
        ifname[0] = '\0';
4599
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4600
    if (fd < 0)
4601
        return -1;
4602

    
4603
    if (!setup_script || !strcmp(setup_script, "no"))
4604
        setup_script = "";
4605
    if (setup_script[0] != '\0') {
4606
        if (launch_script(setup_script, ifname, fd))
4607
            return -1;
4608
    }
4609
    s = net_tap_fd_init(vlan, fd);
4610
    if (!s)
4611
        return -1;
4612
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4613
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4614
    if (down_script && strcmp(down_script, "no"))
4615
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4616
    return 0;
4617
}
4618

    
4619
#endif /* !_WIN32 */
4620

    
4621
#if defined(CONFIG_VDE)
4622
typedef struct VDEState {
4623
    VLANClientState *vc;
4624
    VDECONN *vde;
4625
} VDEState;
4626

    
4627
static void vde_to_qemu(void *opaque)
4628
{
4629
    VDEState *s = opaque;
4630
    uint8_t buf[4096];
4631
    int size;
4632

    
4633
    size = vde_recv(s->vde, buf, sizeof(buf), 0);
4634
    if (size > 0) {
4635
        qemu_send_packet(s->vc, buf, size);
4636
    }
4637
}
4638

    
4639
static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4640
{
4641
    VDEState *s = opaque;
4642
    int ret;
4643
    for(;;) {
4644
        ret = vde_send(s->vde, buf, size, 0);
4645
        if (ret < 0 && errno == EINTR) {
4646
        } else {
4647
            break;
4648
        }
4649
    }
4650
}
4651

    
4652
static int net_vde_init(VLANState *vlan, const char *sock, int port,
4653
                        const char *group, int mode)
4654
{
4655
    VDEState *s;
4656
    char *init_group = strlen(group) ? (char *)group : NULL;
4657
    char *init_sock = strlen(sock) ? (char *)sock : NULL;
4658

    
4659
    struct vde_open_args args = {
4660
        .port = port,
4661
        .group = init_group,
4662
        .mode = mode,
4663
    };
4664

    
4665
    s = qemu_mallocz(sizeof(VDEState));
4666
    if (!s)
4667
        return -1;
4668
    s->vde = vde_open(init_sock, "QEMU", &args);
4669
    if (!s->vde){
4670
        free(s);
4671
        return -1;
4672
    }
4673
    s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4674
    qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4675
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4676
             sock, vde_datafd(s->vde));
4677
    return 0;
4678
}
4679
#endif
4680

    
4681
/* network connection */
4682
typedef struct NetSocketState {
4683
    VLANClientState *vc;
4684
    int fd;
4685
    int state; /* 0 = getting length, 1 = getting data */
4686
    int index;
4687
    int packet_len;
4688
    uint8_t buf[4096];
4689
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4690
} NetSocketState;
4691

    
4692
typedef struct NetSocketListenState {
4693
    VLANState *vlan;
4694
    int fd;
4695
} NetSocketListenState;
4696

    
4697
/* XXX: we consider we can send the whole packet without blocking */
4698
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4699
{
4700
    NetSocketState *s = opaque;
4701
    uint32_t len;
4702
    len = htonl(size);
4703

    
4704
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4705
    send_all(s->fd, buf, size);
4706
}
4707

    
4708
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4709
{
4710
    NetSocketState *s = opaque;
4711
    sendto(s->fd, buf, size, 0,
4712
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4713
}
4714

    
4715
static void net_socket_send(void *opaque)
4716
{
4717
    NetSocketState *s = opaque;
4718
    int l, size, err;
4719
    uint8_t buf1[4096];
4720
    const uint8_t *buf;
4721

    
4722
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4723
    if (size < 0) {
4724
        err = socket_error();
4725
        if (err != EWOULDBLOCK)
4726
            goto eoc;
4727
    } else if (size == 0) {
4728
        /* end of connection */
4729
    eoc:
4730
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4731
        closesocket(s->fd);
4732
        return;
4733
    }
4734
    buf = buf1;
4735
    while (size > 0) {
4736
        /* reassemble a packet from the network */
4737
        switch(s->state) {
4738
        case 0:
4739
            l = 4 - s->index;
4740
            if (l > size)
4741
                l = size;
4742
            memcpy(s->buf + s->index, buf, l);
4743
            buf += l;
4744
            size -= l;
4745
            s->index += l;
4746
            if (s->index == 4) {
4747
                /* got length */
4748
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4749
                s->index = 0;
4750
                s->state = 1;
4751
            }
4752
            break;
4753
        case 1:
4754
            l = s->packet_len - s->index;
4755
            if (l > size)
4756
                l = size;
4757
            memcpy(s->buf + s->index, buf, l);
4758
            s->index += l;
4759
            buf += l;
4760
            size -= l;
4761
            if (s->index >= s->packet_len) {
4762
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4763
                s->index = 0;
4764
                s->state = 0;
4765
            }
4766
            break;
4767
        }
4768
    }
4769
}
4770

    
4771
static void net_socket_send_dgram(void *opaque)
4772
{
4773
    NetSocketState *s = opaque;
4774
    int size;
4775

    
4776
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4777
    if (size < 0)
4778
        return;
4779
    if (size == 0) {
4780
        /* end of connection */
4781
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4782
        return;
4783
    }
4784
    qemu_send_packet(s->vc, s->buf, size);
4785
}
4786

    
4787
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4788
{
4789
    struct ip_mreq imr;
4790
    int fd;
4791
    int val, ret;
4792
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4793
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4794
                inet_ntoa(mcastaddr->sin_addr),
4795
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4796
        return -1;
4797

    
4798
    }
4799
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4800
    if (fd < 0) {
4801
        perror("socket(PF_INET, SOCK_DGRAM)");
4802
        return -1;
4803
    }
4804

    
4805
    val = 1;
4806
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4807
                   (const char *)&val, sizeof(val));
4808
    if (ret < 0) {
4809
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4810
        goto fail;
4811
    }
4812

    
4813
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4814
    if (ret < 0) {
4815
        perror("bind");
4816
        goto fail;
4817
    }
4818

    
4819
    /* Add host to multicast group */
4820
    imr.imr_multiaddr = mcastaddr->sin_addr;
4821
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4822

    
4823
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4824
                     (const char *)&imr, sizeof(struct ip_mreq));
4825
    if (ret < 0) {
4826
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4827
        goto fail;
4828
    }
4829

    
4830
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4831
    val = 1;
4832
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4833
                   (const char *)&val, sizeof(val));
4834
    if (ret < 0) {
4835
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4836
        goto fail;
4837
    }
4838

    
4839
    socket_set_nonblock(fd);
4840
    return fd;
4841
fail:
4842
    if (fd >= 0)
4843
        closesocket(fd);
4844
    return -1;
4845
}
4846

    
4847
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4848
                                          int is_connected)
4849
{
4850
    struct sockaddr_in saddr;
4851
    int newfd;
4852
    socklen_t saddr_len;
4853
    NetSocketState *s;
4854

    
4855
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4856
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4857
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4858
     */
4859

    
4860
    if (is_connected) {
4861
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4862
            /* must be bound */
4863
            if (saddr.sin_addr.s_addr==0) {
4864
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4865
                        fd);
4866
                return NULL;
4867
            }
4868
            /* clone dgram socket */
4869
            newfd = net_socket_mcast_create(&saddr);
4870
            if (newfd < 0) {
4871
                /* error already reported by net_socket_mcast_create() */
4872
                close(fd);
4873
                return NULL;
4874
            }
4875
            /* clone newfd to fd, close newfd */
4876
            dup2(newfd, fd);
4877
            close(newfd);
4878

    
4879
        } else {
4880
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4881
                    fd, strerror(errno));
4882
            return NULL;
4883
        }
4884
    }
4885

    
4886
    s = qemu_mallocz(sizeof(NetSocketState));
4887
    if (!s)
4888
        return NULL;
4889
    s->fd = fd;
4890

    
4891
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4892
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4893

    
4894
    /* mcast: save bound address as dst */
4895
    if (is_connected) s->dgram_dst=saddr;
4896

    
4897
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4898
            "socket: fd=%d (%s mcast=%s:%d)",
4899
            fd, is_connected? "cloned" : "",
4900
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4901
    return s;
4902
}
4903

    
4904
static void net_socket_connect(void *opaque)
4905
{
4906
    NetSocketState *s = opaque;
4907
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4908
}
4909

    
4910
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4911
                                          int is_connected)
4912
{
4913
    NetSocketState *s;
4914
    s = qemu_mallocz(sizeof(NetSocketState));
4915
    if (!s)
4916
        return NULL;
4917
    s->fd = fd;
4918
    s->vc = qemu_new_vlan_client(vlan,
4919
                                 net_socket_receive, NULL, s);
4920
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4921
             "socket: fd=%d", fd);
4922
    if (is_connected) {
4923
        net_socket_connect(s);
4924
    } else {
4925
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4926
    }
4927
    return s;
4928
}
4929

    
4930
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4931
                                          int is_connected)
4932
{
4933
    int so_type=-1, optlen=sizeof(so_type);
4934

    
4935
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4936
        (socklen_t *)&optlen)< 0) {
4937
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4938
        return NULL;
4939
    }
4940
    switch(so_type) {
4941
    case SOCK_DGRAM:
4942
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4943
    case SOCK_STREAM:
4944
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4945
    default:
4946
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4947
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4948
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4949
    }
4950
    return NULL;
4951
}
4952

    
4953
static void net_socket_accept(void *opaque)
4954
{
4955
    NetSocketListenState *s = opaque;
4956
    NetSocketState *s1;
4957
    struct sockaddr_in saddr;
4958
    socklen_t len;
4959
    int fd;
4960

    
4961
    for(;;) {
4962
        len = sizeof(saddr);
4963
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4964
        if (fd < 0 && errno != EINTR) {
4965
            return;
4966
        } else if (fd >= 0) {
4967
            break;
4968
        }
4969
    }
4970
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4971
    if (!s1) {
4972
        closesocket(fd);
4973
    } else {
4974
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4975
                 "socket: connection from %s:%d",
4976
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4977
    }
4978
}
4979

    
4980
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4981
{
4982
    NetSocketListenState *s;
4983
    int fd, val, ret;
4984
    struct sockaddr_in saddr;
4985

    
4986
    if (parse_host_port(&saddr, host_str) < 0)
4987
        r