Statistics
| Branch: | Revision:

root / vl.c @ a171fe39

History | View | Annotate | Download (199.9 kB)

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

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

    
34
#ifndef _WIN32
35
#include <sys/times.h>
36
#include <sys/wait.h>
37
#include <termios.h>
38
#include <sys/poll.h>
39
#include <sys/mman.h>
40
#include <sys/ioctl.h>
41
#include <sys/socket.h>
42
#include <netinet/in.h>
43
#include <dirent.h>
44
#include <netdb.h>
45
#ifdef _BSD
46
#include <sys/stat.h>
47
#ifndef __APPLE__
48
#include <libutil.h>
49
#endif
50
#else
51
#ifndef __sun__
52
#include <linux/if.h>
53
#include <linux/if_tun.h>
54
#include <pty.h>
55
#include <malloc.h>
56
#include <linux/rtc.h>
57
#include <linux/ppdev.h>
58
#include <linux/parport.h>
59
#else
60
#include <sys/stat.h>
61
#include <sys/ethernet.h>
62
#include <sys/sockio.h>
63
#include <arpa/inet.h>
64
#include <netinet/arp.h>
65
#include <netinet/in.h>
66
#include <netinet/in_systm.h>
67
#include <netinet/ip.h>
68
#include <netinet/ip_icmp.h> // must come after ip.h
69
#include <netinet/udp.h>
70
#include <netinet/tcp.h>
71
#include <net/if.h>
72
#include <syslog.h>
73
#include <stropts.h>
74
#endif
75
#endif
76
#endif
77

    
78
#if defined(CONFIG_SLIRP)
79
#include "libslirp.h"
80
#endif
81

    
82
#ifdef _WIN32
83
#include <malloc.h>
84
#include <sys/timeb.h>
85
#include <windows.h>
86
#define getopt_long_only getopt_long
87
#define memalign(align, size) malloc(size)
88
#endif
89

    
90
#include "qemu_socket.h"
91

    
92
#ifdef CONFIG_SDL
93
#ifdef __APPLE__
94
#include <SDL/SDL.h>
95
#endif
96
#endif /* CONFIG_SDL */
97

    
98
#ifdef CONFIG_COCOA
99
#undef main
100
#define main qemu_main
101
#endif /* CONFIG_COCOA */
102

    
103
#include "disas.h"
104

    
105
#include "exec-all.h"
106

    
107
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
108
#ifdef __sun__
109
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110
#else
111
#define SMBD_COMMAND "/usr/sbin/smbd"
112
#endif
113

    
114
//#define DEBUG_UNUSED_IOPORT
115
//#define DEBUG_IOPORT
116

    
117
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
118

    
119
#ifdef TARGET_PPC
120
#define DEFAULT_RAM_SIZE 144
121
#else
122
#define DEFAULT_RAM_SIZE 128
123
#endif
124
/* in ms */
125
#define GUI_REFRESH_INTERVAL 30
126

    
127
/* Max number of USB devices that can be specified on the commandline.  */
128
#define MAX_USB_CMDLINE 8
129

    
130
/* XXX: use a two level table to limit memory usage */
131
#define MAX_IOPORTS 65536
132

    
133
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134
char phys_ram_file[1024];
135
void *ioport_opaque[MAX_IOPORTS];
136
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138
/* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139
   to store the VM snapshots */
140
BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
141
BlockDriverState *pflash_table[MAX_PFLASH];
142
BlockDriverState *sd_bdrv;
143
/* point to the block driver where the snapshots are managed */
144
BlockDriverState *bs_snapshots;
145
int vga_ram_size;
146
static DisplayState display_state;
147
int nographic;
148
const char* keyboard_layout = NULL;
149
int64_t ticks_per_sec;
150
int boot_device = 'c';
151
int ram_size;
152
int pit_min_timer_count = 0;
153
int nb_nics;
154
NICInfo nd_table[MAX_NICS];
155
QEMUTimer *gui_timer;
156
int vm_running;
157
int rtc_utc = 1;
158
int cirrus_vga_enabled = 1;
159
int vmsvga_enabled = 0;
160
#ifdef TARGET_SPARC
161
int graphic_width = 1024;
162
int graphic_height = 768;
163
int graphic_depth = 8;
164
#else
165
int graphic_width = 800;
166
int graphic_height = 600;
167
int graphic_depth = 15;
168
#endif
169
int full_screen = 0;
170
int no_frame = 0;
171
int no_quit = 0;
172
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
173
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
174
#ifdef TARGET_I386
175
int win2k_install_hack = 0;
176
#endif
177
int usb_enabled = 0;
178
static VLANState *first_vlan;
179
int smp_cpus = 1;
180
const char *vnc_display;
181
#if defined(TARGET_SPARC)
182
#define MAX_CPUS 16
183
#elif defined(TARGET_I386)
184
#define MAX_CPUS 255
185
#else
186
#define MAX_CPUS 1
187
#endif
188
int acpi_enabled = 1;
189
int fd_bootchk = 1;
190
int no_reboot = 0;
191
int graphic_rotate = 0;
192
int daemonize = 0;
193
const char *option_rom[MAX_OPTION_ROMS];
194
int nb_option_roms;
195
int semihosting_enabled = 0;
196
int autostart = 1;
197
const char *qemu_name;
198

    
199
/***********************************************************/
200
/* x86 ISA bus support */
201

    
202
target_phys_addr_t isa_mem_base = 0;
203
PicState2 *isa_pic;
204

    
205
uint32_t default_ioport_readb(void *opaque, uint32_t address)
206
{
207
#ifdef DEBUG_UNUSED_IOPORT
208
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
209
#endif
210
    return 0xff;
211
}
212

    
213
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
214
{
215
#ifdef DEBUG_UNUSED_IOPORT
216
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
217
#endif
218
}
219

    
220
/* default is to make two byte accesses */
221
uint32_t default_ioport_readw(void *opaque, uint32_t address)
222
{
223
    uint32_t data;
224
    data = ioport_read_table[0][address](ioport_opaque[address], address);
225
    address = (address + 1) & (MAX_IOPORTS - 1);
226
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
227
    return data;
228
}
229

    
230
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
231
{
232
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
233
    address = (address + 1) & (MAX_IOPORTS - 1);
234
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
235
}
236

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

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

    
252
void init_ioports(void)
253
{
254
    int i;
255

    
256
    for(i = 0; i < MAX_IOPORTS; i++) {
257
        ioport_read_table[0][i] = default_ioport_readb;
258
        ioport_write_table[0][i] = default_ioport_writeb;
259
        ioport_read_table[1][i] = default_ioport_readw;
260
        ioport_write_table[1][i] = default_ioport_writew;
261
        ioport_read_table[2][i] = default_ioport_readl;
262
        ioport_write_table[2][i] = default_ioport_writel;
263
    }
264
}
265

    
266
/* size is the word size in byte */
267
int register_ioport_read(int start, int length, int size, 
268
                         IOPortReadFunc *func, void *opaque)
269
{
270
    int i, bsize;
271

    
272
    if (size == 1) {
273
        bsize = 0;
274
    } else if (size == 2) {
275
        bsize = 1;
276
    } else if (size == 4) {
277
        bsize = 2;
278
    } else {
279
        hw_error("register_ioport_read: invalid size");
280
        return -1;
281
    }
282
    for(i = start; i < start + length; i += size) {
283
        ioport_read_table[bsize][i] = func;
284
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
285
            hw_error("register_ioport_read: invalid opaque");
286
        ioport_opaque[i] = opaque;
287
    }
288
    return 0;
289
}
290

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

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

    
316
void isa_unassign_ioport(int start, int length)
317
{
318
    int i;
319

    
320
    for(i = start; i < start + length; i++) {
321
        ioport_read_table[0][i] = default_ioport_readb;
322
        ioport_read_table[1][i] = default_ioport_readw;
323
        ioport_read_table[2][i] = default_ioport_readl;
324

    
325
        ioport_write_table[0][i] = default_ioport_writeb;
326
        ioport_write_table[1][i] = default_ioport_writew;
327
        ioport_write_table[2][i] = default_ioport_writel;
328
    }
329
}
330

    
331
/***********************************************************/
332

    
333
void cpu_outb(CPUState *env, int addr, int val)
334
{
335
#ifdef DEBUG_IOPORT
336
    if (loglevel & CPU_LOG_IOPORT)
337
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
338
#endif    
339
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
340
#ifdef USE_KQEMU
341
    if (env)
342
        env->last_io_time = cpu_get_time_fast();
343
#endif
344
}
345

    
346
void cpu_outw(CPUState *env, int addr, int val)
347
{
348
#ifdef DEBUG_IOPORT
349
    if (loglevel & CPU_LOG_IOPORT)
350
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
351
#endif    
352
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
353
#ifdef USE_KQEMU
354
    if (env)
355
        env->last_io_time = cpu_get_time_fast();
356
#endif
357
}
358

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

    
372
int cpu_inb(CPUState *env, int addr)
373
{
374
    int val;
375
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
376
#ifdef DEBUG_IOPORT
377
    if (loglevel & CPU_LOG_IOPORT)
378
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
379
#endif
380
#ifdef USE_KQEMU
381
    if (env)
382
        env->last_io_time = cpu_get_time_fast();
383
#endif
384
    return val;
385
}
386

    
387
int cpu_inw(CPUState *env, int addr)
388
{
389
    int val;
390
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
391
#ifdef DEBUG_IOPORT
392
    if (loglevel & CPU_LOG_IOPORT)
393
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
394
#endif
395
#ifdef USE_KQEMU
396
    if (env)
397
        env->last_io_time = cpu_get_time_fast();
398
#endif
399
    return val;
400
}
401

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

    
417
/***********************************************************/
418
void hw_error(const char *fmt, ...)
419
{
420
    va_list ap;
421
    CPUState *env;
422

    
423
    va_start(ap, fmt);
424
    fprintf(stderr, "qemu: hardware error: ");
425
    vfprintf(stderr, fmt, ap);
426
    fprintf(stderr, "\n");
427
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
428
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
429
#ifdef TARGET_I386
430
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
431
#else
432
        cpu_dump_state(env, stderr, fprintf, 0);
433
#endif
434
    }
435
    va_end(ap);
436
    abort();
437
}
438

    
439
/***********************************************************/
440
/* keyboard/mouse */
441

    
442
static QEMUPutKBDEvent *qemu_put_kbd_event;
443
static void *qemu_put_kbd_event_opaque;
444
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
445
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
446

    
447
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
448
{
449
    qemu_put_kbd_event_opaque = opaque;
450
    qemu_put_kbd_event = func;
451
}
452

    
453
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
454
                                                void *opaque, int absolute,
455
                                                const char *name)
456
{
457
    QEMUPutMouseEntry *s, *cursor;
458

    
459
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
460
    if (!s)
461
        return NULL;
462

    
463
    s->qemu_put_mouse_event = func;
464
    s->qemu_put_mouse_event_opaque = opaque;
465
    s->qemu_put_mouse_event_absolute = absolute;
466
    s->qemu_put_mouse_event_name = qemu_strdup(name);
467
    s->next = NULL;
468

    
469
    if (!qemu_put_mouse_event_head) {
470
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
471
        return s;
472
    }
473

    
474
    cursor = qemu_put_mouse_event_head;
475
    while (cursor->next != NULL)
476
        cursor = cursor->next;
477

    
478
    cursor->next = s;
479
    qemu_put_mouse_event_current = s;
480

    
481
    return s;
482
}
483

    
484
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
485
{
486
    QEMUPutMouseEntry *prev = NULL, *cursor;
487

    
488
    if (!qemu_put_mouse_event_head || entry == NULL)
489
        return;
490

    
491
    cursor = qemu_put_mouse_event_head;
492
    while (cursor != NULL && cursor != entry) {
493
        prev = cursor;
494
        cursor = cursor->next;
495
    }
496

    
497
    if (cursor == NULL) // does not exist or list empty
498
        return;
499
    else if (prev == NULL) { // entry is head
500
        qemu_put_mouse_event_head = cursor->next;
501
        if (qemu_put_mouse_event_current == entry)
502
            qemu_put_mouse_event_current = cursor->next;
503
        qemu_free(entry->qemu_put_mouse_event_name);
504
        qemu_free(entry);
505
        return;
506
    }
507

    
508
    prev->next = entry->next;
509

    
510
    if (qemu_put_mouse_event_current == entry)
511
        qemu_put_mouse_event_current = prev;
512

    
513
    qemu_free(entry->qemu_put_mouse_event_name);
514
    qemu_free(entry);
515
}
516

    
517
void kbd_put_keycode(int keycode)
518
{
519
    if (qemu_put_kbd_event) {
520
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
521
    }
522
}
523

    
524
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
525
{
526
    QEMUPutMouseEvent *mouse_event;
527
    void *mouse_event_opaque;
528
    int width;
529

    
530
    if (!qemu_put_mouse_event_current) {
531
        return;
532
    }
533

    
534
    mouse_event =
535
        qemu_put_mouse_event_current->qemu_put_mouse_event;
536
    mouse_event_opaque =
537
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
538

    
539
    if (mouse_event) {
540
        if (graphic_rotate) {
541
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
542
                width = 0x7fff;
543
            else
544
                width = graphic_width;
545
            mouse_event(mouse_event_opaque,
546
                                 width - dy, dx, dz, buttons_state);
547
        } else
548
            mouse_event(mouse_event_opaque,
549
                                 dx, dy, dz, buttons_state);
550
    }
551
}
552

    
553
int kbd_mouse_is_absolute(void)
554
{
555
    if (!qemu_put_mouse_event_current)
556
        return 0;
557

    
558
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
559
}
560

    
561
void (*kbd_mouse_set)(int x, int y, int on) = NULL;
562
void (*kbd_cursor_define)(int width, int height, int bpp, int hot_x, int hot_y,
563
                          uint8_t *image, uint8_t *mask) = NULL;
564

    
565
void do_info_mice(void)
566
{
567
    QEMUPutMouseEntry *cursor;
568
    int index = 0;
569

    
570
    if (!qemu_put_mouse_event_head) {
571
        term_printf("No mouse devices connected\n");
572
        return;
573
    }
574

    
575
    term_printf("Mouse devices available:\n");
576
    cursor = qemu_put_mouse_event_head;
577
    while (cursor != NULL) {
578
        term_printf("%c Mouse #%d: %s\n",
579
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
580
                    index, cursor->qemu_put_mouse_event_name);
581
        index++;
582
        cursor = cursor->next;
583
    }
584
}
585

    
586
void do_mouse_set(int index)
587
{
588
    QEMUPutMouseEntry *cursor;
589
    int i = 0;
590

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

    
596
    cursor = qemu_put_mouse_event_head;
597
    while (cursor != NULL && index != i) {
598
        i++;
599
        cursor = cursor->next;
600
    }
601

    
602
    if (cursor != NULL)
603
        qemu_put_mouse_event_current = cursor;
604
    else
605
        term_printf("Mouse at given index not found\n");
606
}
607

    
608
/* compute with 96 bit intermediate result: (a*b)/c */
609
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
610
{
611
    union {
612
        uint64_t ll;
613
        struct {
614
#ifdef WORDS_BIGENDIAN
615
            uint32_t high, low;
616
#else
617
            uint32_t low, high;
618
#endif            
619
        } l;
620
    } u, res;
621
    uint64_t rl, rh;
622

    
623
    u.ll = a;
624
    rl = (uint64_t)u.l.low * (uint64_t)b;
625
    rh = (uint64_t)u.l.high * (uint64_t)b;
626
    rh += (rl >> 32);
627
    res.l.high = rh / c;
628
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
629
    return res.ll;
630
}
631

    
632
/***********************************************************/
633
/* real time host monotonic timer */
634

    
635
#define QEMU_TIMER_BASE 1000000000LL
636

    
637
#ifdef WIN32
638

    
639
static int64_t clock_freq;
640

    
641
static void init_get_clock(void)
642
{
643
    LARGE_INTEGER freq;
644
    int ret;
645
    ret = QueryPerformanceFrequency(&freq);
646
    if (ret == 0) {
647
        fprintf(stderr, "Could not calibrate ticks\n");
648
        exit(1);
649
    }
650
    clock_freq = freq.QuadPart;
651
}
652

    
653
static int64_t get_clock(void)
654
{
655
    LARGE_INTEGER ti;
656
    QueryPerformanceCounter(&ti);
657
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
658
}
659

    
660
#else
661

    
662
static int use_rt_clock;
663

    
664
static void init_get_clock(void)
665
{
666
    use_rt_clock = 0;
667
#if defined(__linux__)
668
    {
669
        struct timespec ts;
670
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
671
            use_rt_clock = 1;
672
        }
673
    }
674
#endif
675
}
676

    
677
static int64_t get_clock(void)
678
{
679
#if defined(__linux__)
680
    if (use_rt_clock) {
681
        struct timespec ts;
682
        clock_gettime(CLOCK_MONOTONIC, &ts);
683
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
684
    } else 
685
#endif
686
    {
687
        /* XXX: using gettimeofday leads to problems if the date
688
           changes, so it should be avoided. */
689
        struct timeval tv;
690
        gettimeofday(&tv, NULL);
691
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
692
    }
693
}
694

    
695
#endif
696

    
697
/***********************************************************/
698
/* guest cycle counter */
699

    
700
static int64_t cpu_ticks_prev;
701
static int64_t cpu_ticks_offset;
702
static int64_t cpu_clock_offset;
703
static int cpu_ticks_enabled;
704

    
705
/* return the host CPU cycle counter and handle stop/restart */
706
int64_t cpu_get_ticks(void)
707
{
708
    if (!cpu_ticks_enabled) {
709
        return cpu_ticks_offset;
710
    } else {
711
        int64_t ticks;
712
        ticks = cpu_get_real_ticks();
713
        if (cpu_ticks_prev > ticks) {
714
            /* Note: non increasing ticks may happen if the host uses
715
               software suspend */
716
            cpu_ticks_offset += cpu_ticks_prev - ticks;
717
        }
718
        cpu_ticks_prev = ticks;
719
        return ticks + cpu_ticks_offset;
720
    }
721
}
722

    
723
/* return the host CPU monotonic timer and handle stop/restart */
724
static int64_t cpu_get_clock(void)
725
{
726
    int64_t ti;
727
    if (!cpu_ticks_enabled) {
728
        return cpu_clock_offset;
729
    } else {
730
        ti = get_clock();
731
        return ti + cpu_clock_offset;
732
    }
733
}
734

    
735
/* enable cpu_get_ticks() */
736
void cpu_enable_ticks(void)
737
{
738
    if (!cpu_ticks_enabled) {
739
        cpu_ticks_offset -= cpu_get_real_ticks();
740
        cpu_clock_offset -= get_clock();
741
        cpu_ticks_enabled = 1;
742
    }
743
}
744

    
745
/* disable cpu_get_ticks() : the clock is stopped. You must not call
746
   cpu_get_ticks() after that.  */
747
void cpu_disable_ticks(void)
748
{
749
    if (cpu_ticks_enabled) {
750
        cpu_ticks_offset = cpu_get_ticks();
751
        cpu_clock_offset = cpu_get_clock();
752
        cpu_ticks_enabled = 0;
753
    }
754
}
755

    
756
/***********************************************************/
757
/* timers */
758
 
759
#define QEMU_TIMER_REALTIME 0
760
#define QEMU_TIMER_VIRTUAL  1
761

    
762
struct QEMUClock {
763
    int type;
764
    /* XXX: add frequency */
765
};
766

    
767
struct QEMUTimer {
768
    QEMUClock *clock;
769
    int64_t expire_time;
770
    QEMUTimerCB *cb;
771
    void *opaque;
772
    struct QEMUTimer *next;
773
};
774

    
775
QEMUClock *rt_clock;
776
QEMUClock *vm_clock;
777

    
778
static QEMUTimer *active_timers[2];
779
#ifdef _WIN32
780
static MMRESULT timerID;
781
static HANDLE host_alarm = NULL;
782
static unsigned int period = 1;
783
#else
784
/* frequency of the times() clock tick */
785
static int timer_freq;
786
#endif
787

    
788
QEMUClock *qemu_new_clock(int type)
789
{
790
    QEMUClock *clock;
791
    clock = qemu_mallocz(sizeof(QEMUClock));
792
    if (!clock)
793
        return NULL;
794
    clock->type = type;
795
    return clock;
796
}
797

    
798
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
799
{
800
    QEMUTimer *ts;
801

    
802
    ts = qemu_mallocz(sizeof(QEMUTimer));
803
    ts->clock = clock;
804
    ts->cb = cb;
805
    ts->opaque = opaque;
806
    return ts;
807
}
808

    
809
void qemu_free_timer(QEMUTimer *ts)
810
{
811
    qemu_free(ts);
812
}
813

    
814
/* stop a timer, but do not dealloc it */
815
void qemu_del_timer(QEMUTimer *ts)
816
{
817
    QEMUTimer **pt, *t;
818

    
819
    /* NOTE: this code must be signal safe because
820
       qemu_timer_expired() can be called from a signal. */
821
    pt = &active_timers[ts->clock->type];
822
    for(;;) {
823
        t = *pt;
824
        if (!t)
825
            break;
826
        if (t == ts) {
827
            *pt = t->next;
828
            break;
829
        }
830
        pt = &t->next;
831
    }
832
}
833

    
834
/* modify the current timer so that it will be fired when current_time
835
   >= expire_time. The corresponding callback will be called. */
836
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
837
{
838
    QEMUTimer **pt, *t;
839

    
840
    qemu_del_timer(ts);
841

    
842
    /* add the timer in the sorted list */
843
    /* NOTE: this code must be signal safe because
844
       qemu_timer_expired() can be called from a signal. */
845
    pt = &active_timers[ts->clock->type];
846
    for(;;) {
847
        t = *pt;
848
        if (!t)
849
            break;
850
        if (t->expire_time > expire_time) 
851
            break;
852
        pt = &t->next;
853
    }
854
    ts->expire_time = expire_time;
855
    ts->next = *pt;
856
    *pt = ts;
857
}
858

    
859
int qemu_timer_pending(QEMUTimer *ts)
860
{
861
    QEMUTimer *t;
862
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
863
        if (t == ts)
864
            return 1;
865
    }
866
    return 0;
867
}
868

    
869
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
870
{
871
    if (!timer_head)
872
        return 0;
873
    return (timer_head->expire_time <= current_time);
874
}
875

    
876
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
877
{
878
    QEMUTimer *ts;
879
    
880
    for(;;) {
881
        ts = *ptimer_head;
882
        if (!ts || ts->expire_time > current_time)
883
            break;
884
        /* remove timer from the list before calling the callback */
885
        *ptimer_head = ts->next;
886
        ts->next = NULL;
887
        
888
        /* run the callback (the timer list can be modified) */
889
        ts->cb(ts->opaque);
890
    }
891
}
892

    
893
int64_t qemu_get_clock(QEMUClock *clock)
894
{
895
    switch(clock->type) {
896
    case QEMU_TIMER_REALTIME:
897
        return get_clock() / 1000000;
898
    default:
899
    case QEMU_TIMER_VIRTUAL:
900
        return cpu_get_clock();
901
    }
902
}
903

    
904
static void init_timers(void)
905
{
906
    init_get_clock();
907
    ticks_per_sec = QEMU_TIMER_BASE;
908
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
909
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
910
}
911

    
912
/* save a timer */
913
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
914
{
915
    uint64_t expire_time;
916

    
917
    if (qemu_timer_pending(ts)) {
918
        expire_time = ts->expire_time;
919
    } else {
920
        expire_time = -1;
921
    }
922
    qemu_put_be64(f, expire_time);
923
}
924

    
925
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
926
{
927
    uint64_t expire_time;
928

    
929
    expire_time = qemu_get_be64(f);
930
    if (expire_time != -1) {
931
        qemu_mod_timer(ts, expire_time);
932
    } else {
933
        qemu_del_timer(ts);
934
    }
935
}
936

    
937
static void timer_save(QEMUFile *f, void *opaque)
938
{
939
    if (cpu_ticks_enabled) {
940
        hw_error("cannot save state if virtual timers are running");
941
    }
942
    qemu_put_be64s(f, &cpu_ticks_offset);
943
    qemu_put_be64s(f, &ticks_per_sec);
944
    qemu_put_be64s(f, &cpu_clock_offset);
945
}
946

    
947
static int timer_load(QEMUFile *f, void *opaque, int version_id)
948
{
949
    if (version_id != 1 && version_id != 2)
950
        return -EINVAL;
951
    if (cpu_ticks_enabled) {
952
        return -EINVAL;
953
    }
954
    qemu_get_be64s(f, &cpu_ticks_offset);
955
    qemu_get_be64s(f, &ticks_per_sec);
956
    if (version_id == 2) {
957
        qemu_get_be64s(f, &cpu_clock_offset);
958
    }
959
    return 0;
960
}
961

    
962
#ifdef _WIN32
963
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
964
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
965
#else
966
static void host_alarm_handler(int host_signum)
967
#endif
968
{
969
#if 0
970
#define DISP_FREQ 1000
971
    {
972
        static int64_t delta_min = INT64_MAX;
973
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
974
        static int count;
975
        ti = qemu_get_clock(vm_clock);
976
        if (last_clock != 0) {
977
            delta = ti - last_clock;
978
            if (delta < delta_min)
979
                delta_min = delta;
980
            if (delta > delta_max)
981
                delta_max = delta;
982
            delta_cum += delta;
983
            if (++count == DISP_FREQ) {
984
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
985
                       muldiv64(delta_min, 1000000, ticks_per_sec),
986
                       muldiv64(delta_max, 1000000, ticks_per_sec),
987
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
988
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
989
                count = 0;
990
                delta_min = INT64_MAX;
991
                delta_max = 0;
992
                delta_cum = 0;
993
            }
994
        }
995
        last_clock = ti;
996
    }
997
#endif
998
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
999
                           qemu_get_clock(vm_clock)) ||
1000
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1001
                           qemu_get_clock(rt_clock))) {
1002
#ifdef _WIN32
1003
        SetEvent(host_alarm);
1004
#endif
1005
        CPUState *env = cpu_single_env;
1006
        if (env) {
1007
            /* stop the currently executing cpu because a timer occured */
1008
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1009
#ifdef USE_KQEMU
1010
            if (env->kqemu_enabled) {
1011
                kqemu_cpu_interrupt(env);
1012
            }
1013
#endif
1014
        }
1015
    }
1016
}
1017

    
1018
#ifndef _WIN32
1019

    
1020
#if defined(__linux__)
1021

    
1022
#define RTC_FREQ 1024
1023

    
1024
static int rtc_fd;
1025

    
1026
static int start_rtc_timer(void)
1027
{
1028
    rtc_fd = open("/dev/rtc", O_RDONLY);
1029
    if (rtc_fd < 0)
1030
        return -1;
1031
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1032
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1033
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1034
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1035
        goto fail;
1036
    }
1037
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1038
    fail:
1039
        close(rtc_fd);
1040
        return -1;
1041
    }
1042
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1043
    return 0;
1044
}
1045

    
1046
#else
1047

    
1048
static int start_rtc_timer(void)
1049
{
1050
    return -1;
1051
}
1052

    
1053
#endif /* !defined(__linux__) */
1054

    
1055
#endif /* !defined(_WIN32) */
1056

    
1057
static void init_timer_alarm(void)
1058
{
1059
#ifdef _WIN32
1060
    {
1061
        int count=0;
1062
        TIMECAPS tc;
1063

    
1064
        ZeroMemory(&tc, sizeof(TIMECAPS));
1065
        timeGetDevCaps(&tc, sizeof(TIMECAPS));
1066
        if (period < tc.wPeriodMin)
1067
            period = tc.wPeriodMin;
1068
        timeBeginPeriod(period);
1069
        timerID = timeSetEvent(1,     // interval (ms)
1070
                               period,     // resolution
1071
                               host_alarm_handler, // function
1072
                               (DWORD)&count,  // user parameter
1073
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1074
         if( !timerID ) {
1075
            perror("failed timer alarm");
1076
            exit(1);
1077
         }
1078
        host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1079
        if (!host_alarm) {
1080
            perror("failed CreateEvent");
1081
            exit(1);
1082
        }
1083
        qemu_add_wait_object(host_alarm, NULL, NULL);
1084
    }
1085
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1086
#else
1087
    {
1088
        struct sigaction act;
1089
        struct itimerval itv;
1090
        
1091
        /* get times() syscall frequency */
1092
        timer_freq = sysconf(_SC_CLK_TCK);
1093
        
1094
        /* timer signal */
1095
        sigfillset(&act.sa_mask);
1096
       act.sa_flags = 0;
1097
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1098
        act.sa_flags |= SA_ONSTACK;
1099
#endif
1100
        act.sa_handler = host_alarm_handler;
1101
        sigaction(SIGALRM, &act, NULL);
1102

    
1103
        itv.it_interval.tv_sec = 0;
1104
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1105
        itv.it_value.tv_sec = 0;
1106
        itv.it_value.tv_usec = 10 * 1000;
1107
        setitimer(ITIMER_REAL, &itv, NULL);
1108
        /* we probe the tick duration of the kernel to inform the user if
1109
           the emulated kernel requested a too high timer frequency */
1110
        getitimer(ITIMER_REAL, &itv);
1111

    
1112
#if defined(__linux__)
1113
        /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1114
           have timers with 1 ms resolution. The correct solution will
1115
           be to use the POSIX real time timers available in recent
1116
           2.6 kernels */
1117
        if (itv.it_interval.tv_usec > 1000 || 1) {
1118
            /* try to use /dev/rtc to have a faster timer */
1119
            if (start_rtc_timer() < 0)
1120
                goto use_itimer;
1121
            /* disable itimer */
1122
            itv.it_interval.tv_sec = 0;
1123
            itv.it_interval.tv_usec = 0;
1124
            itv.it_value.tv_sec = 0;
1125
            itv.it_value.tv_usec = 0;
1126
            setitimer(ITIMER_REAL, &itv, NULL);
1127

    
1128
            /* use the RTC */
1129
            sigaction(SIGIO, &act, NULL);
1130
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1131
            fcntl(rtc_fd, F_SETOWN, getpid());
1132
        } else 
1133
#endif /* defined(__linux__) */
1134
        {
1135
        use_itimer:
1136
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1137
                                   PIT_FREQ) / 1000000;
1138
        }
1139
    }
1140
#endif
1141
}
1142

    
1143
void quit_timers(void)
1144
{
1145
#ifdef _WIN32
1146
    timeKillEvent(timerID);
1147
    timeEndPeriod(period);
1148
    if (host_alarm) {
1149
        CloseHandle(host_alarm);
1150
        host_alarm = NULL;
1151
    }
1152
#endif
1153
}
1154

    
1155
/***********************************************************/
1156
/* character device */
1157

    
1158
static void qemu_chr_event(CharDriverState *s, int event)
1159
{
1160
    if (!s->chr_event)
1161
        return;
1162
    s->chr_event(s->handler_opaque, event);
1163
}
1164

    
1165
static void qemu_chr_reset_bh(void *opaque)
1166
{
1167
    CharDriverState *s = opaque;
1168
    qemu_chr_event(s, CHR_EVENT_RESET);
1169
    qemu_bh_delete(s->bh);
1170
    s->bh = NULL;
1171
}
1172

    
1173
void qemu_chr_reset(CharDriverState *s)
1174
{
1175
    if (s->bh == NULL) {
1176
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1177
        qemu_bh_schedule(s->bh);
1178
    }
1179
}
1180

    
1181
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1182
{
1183
    return s->chr_write(s, buf, len);
1184
}
1185

    
1186
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1187
{
1188
    if (!s->chr_ioctl)
1189
        return -ENOTSUP;
1190
    return s->chr_ioctl(s, cmd, arg);
1191
}
1192

    
1193
int qemu_chr_can_read(CharDriverState *s)
1194
{
1195
    if (!s->chr_can_read)
1196
        return 0;
1197
    return s->chr_can_read(s->handler_opaque);
1198
}
1199

    
1200
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1201
{
1202
    s->chr_read(s->handler_opaque, buf, len);
1203
}
1204

    
1205

    
1206
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1207
{
1208
    char buf[4096];
1209
    va_list ap;
1210
    va_start(ap, fmt);
1211
    vsnprintf(buf, sizeof(buf), fmt, ap);
1212
    qemu_chr_write(s, buf, strlen(buf));
1213
    va_end(ap);
1214
}
1215

    
1216
void qemu_chr_send_event(CharDriverState *s, int event)
1217
{
1218
    if (s->chr_send_event)
1219
        s->chr_send_event(s, event);
1220
}
1221

    
1222
void qemu_chr_add_handlers(CharDriverState *s, 
1223
                           IOCanRWHandler *fd_can_read, 
1224
                           IOReadHandler *fd_read,
1225
                           IOEventHandler *fd_event,
1226
                           void *opaque)
1227
{
1228
    s->chr_can_read = fd_can_read;
1229
    s->chr_read = fd_read;
1230
    s->chr_event = fd_event;
1231
    s->handler_opaque = opaque;
1232
    if (s->chr_update_read_handler)
1233
        s->chr_update_read_handler(s);
1234
}
1235
             
1236
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1237
{
1238
    return len;
1239
}
1240

    
1241
static CharDriverState *qemu_chr_open_null(void)
1242
{
1243
    CharDriverState *chr;
1244

    
1245
    chr = qemu_mallocz(sizeof(CharDriverState));
1246
    if (!chr)
1247
        return NULL;
1248
    chr->chr_write = null_chr_write;
1249
    return chr;
1250
}
1251

    
1252
/* MUX driver for serial I/O splitting */
1253
static int term_timestamps;
1254
static int64_t term_timestamps_start;
1255
#define MAX_MUX 4
1256
typedef struct {
1257
    IOCanRWHandler *chr_can_read[MAX_MUX];
1258
    IOReadHandler *chr_read[MAX_MUX];
1259
    IOEventHandler *chr_event[MAX_MUX];
1260
    void *ext_opaque[MAX_MUX];
1261
    CharDriverState *drv;
1262
    int mux_cnt;
1263
    int term_got_escape;
1264
    int max_size;
1265
} MuxDriver;
1266

    
1267

    
1268
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1269
{
1270
    MuxDriver *d = chr->opaque;
1271
    int ret;
1272
    if (!term_timestamps) {
1273
        ret = d->drv->chr_write(d->drv, buf, len);
1274
    } else {
1275
        int i;
1276

    
1277
        ret = 0;
1278
        for(i = 0; i < len; i++) {
1279
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1280
            if (buf[i] == '\n') {
1281
                char buf1[64];
1282
                int64_t ti;
1283
                int secs;
1284

    
1285
                ti = get_clock();
1286
                if (term_timestamps_start == -1)
1287
                    term_timestamps_start = ti;
1288
                ti -= term_timestamps_start;
1289
                secs = ti / 1000000000;
1290
                snprintf(buf1, sizeof(buf1),
1291
                         "[%02d:%02d:%02d.%03d] ",
1292
                         secs / 3600,
1293
                         (secs / 60) % 60,
1294
                         secs % 60,
1295
                         (int)((ti / 1000000) % 1000));
1296
                d->drv->chr_write(d->drv, buf1, strlen(buf1));
1297
            }
1298
        }
1299
    }
1300
    return ret;
1301
}
1302

    
1303
static char *mux_help[] = {
1304
    "% h    print this help\n\r",
1305
    "% x    exit emulator\n\r",
1306
    "% s    save disk data back to file (if -snapshot)\n\r",
1307
    "% t    toggle console timestamps\n\r"
1308
    "% b    send break (magic sysrq)\n\r",
1309
    "% c    switch between console and monitor\n\r",
1310
    "% %  sends %\n\r",
1311
    NULL
1312
};
1313

    
1314
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1315
static void mux_print_help(CharDriverState *chr)
1316
{
1317
    int i, j;
1318
    char ebuf[15] = "Escape-Char";
1319
    char cbuf[50] = "\n\r";
1320

    
1321
    if (term_escape_char > 0 && term_escape_char < 26) {
1322
        sprintf(cbuf,"\n\r");
1323
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1324
    } else {
1325
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1326
    }
1327
    chr->chr_write(chr, cbuf, strlen(cbuf));
1328
    for (i = 0; mux_help[i] != NULL; i++) {
1329
        for (j=0; mux_help[i][j] != '\0'; j++) {
1330
            if (mux_help[i][j] == '%')
1331
                chr->chr_write(chr, ebuf, strlen(ebuf));
1332
            else
1333
                chr->chr_write(chr, &mux_help[i][j], 1);
1334
        }
1335
    }
1336
}
1337

    
1338
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1339
{
1340
    if (d->term_got_escape) {
1341
        d->term_got_escape = 0;
1342
        if (ch == term_escape_char)
1343
            goto send_char;
1344
        switch(ch) {
1345
        case '?':
1346
        case 'h':
1347
            mux_print_help(chr);
1348
            break;
1349
        case 'x':
1350
            {
1351
                 char *term =  "QEMU: Terminated\n\r";
1352
                 chr->chr_write(chr,term,strlen(term));
1353
                 exit(0);
1354
                 break;
1355
            }
1356
        case 's':
1357
            {
1358
                int i;
1359
                for (i = 0; i < MAX_DISKS; i++) {
1360
                    if (bs_table[i])
1361
                        bdrv_commit(bs_table[i]);
1362
                }
1363
            }
1364
            break;
1365
        case 'b':
1366
            if (chr->chr_event)
1367
                chr->chr_event(chr->opaque, CHR_EVENT_BREAK);
1368
            break;
1369
        case 'c':
1370
            /* Switch to the next registered device */
1371
            chr->focus++;
1372
            if (chr->focus >= d->mux_cnt)
1373
                chr->focus = 0;
1374
            break;
1375
       case 't':
1376
           term_timestamps = !term_timestamps;
1377
           term_timestamps_start = -1;
1378
           break;
1379
        }
1380
    } else if (ch == term_escape_char) {
1381
        d->term_got_escape = 1;
1382
    } else {
1383
    send_char:
1384
        return 1;
1385
    }
1386
    return 0;
1387
}
1388

    
1389
static int mux_chr_can_read(void *opaque)
1390
{
1391
    CharDriverState *chr = opaque;
1392
    MuxDriver *d = chr->opaque;
1393
    if (d->chr_can_read[chr->focus])
1394
       return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1395
    return 0;
1396
}
1397

    
1398
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1399
{
1400
    CharDriverState *chr = opaque;
1401
    MuxDriver *d = chr->opaque;
1402
    int i;
1403
    for(i = 0; i < size; i++)
1404
        if (mux_proc_byte(chr, d, buf[i]))
1405
            d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1406
}
1407

    
1408
static void mux_chr_event(void *opaque, int event)
1409
{
1410
    CharDriverState *chr = opaque;
1411
    MuxDriver *d = chr->opaque;
1412
    int i;
1413

    
1414
    /* Send the event to all registered listeners */
1415
    for (i = 0; i < d->mux_cnt; i++)
1416
        if (d->chr_event[i])
1417
            d->chr_event[i](d->ext_opaque[i], event);
1418
}
1419

    
1420
static void mux_chr_update_read_handler(CharDriverState *chr)
1421
{
1422
    MuxDriver *d = chr->opaque;
1423

    
1424
    if (d->mux_cnt >= MAX_MUX) {
1425
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1426
        return;
1427
    }
1428
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1429
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1430
    d->chr_read[d->mux_cnt] = chr->chr_read;
1431
    d->chr_event[d->mux_cnt] = chr->chr_event;
1432
    /* Fix up the real driver with mux routines */
1433
    if (d->mux_cnt == 0) {
1434
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1435
                              mux_chr_event, chr);
1436
    }
1437
    chr->focus = d->mux_cnt;
1438
    d->mux_cnt++;
1439
}
1440

    
1441
CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1442
{
1443
    CharDriverState *chr;
1444
    MuxDriver *d;
1445

    
1446
    chr = qemu_mallocz(sizeof(CharDriverState));
1447
    if (!chr)
1448
        return NULL;
1449
    d = qemu_mallocz(sizeof(MuxDriver));
1450
    if (!d) {
1451
        free(chr);
1452
        return NULL;
1453
    }
1454

    
1455
    chr->opaque = d;
1456
    d->drv = drv;
1457
    chr->focus = -1;
1458
    chr->chr_write = mux_chr_write;
1459
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1460
    return chr;
1461
}
1462

    
1463

    
1464
#ifdef _WIN32
1465

    
1466
static void socket_cleanup(void)
1467
{
1468
    WSACleanup();
1469
}
1470

    
1471
static int socket_init(void)
1472
{
1473
    WSADATA Data;
1474
    int ret, err;
1475

    
1476
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1477
    if (ret != 0) {
1478
        err = WSAGetLastError();
1479
        fprintf(stderr, "WSAStartup: %d\n", err);
1480
        return -1;
1481
    }
1482
    atexit(socket_cleanup);
1483
    return 0;
1484
}
1485

    
1486
static int send_all(int fd, const uint8_t *buf, int len1)
1487
{
1488
    int ret, len;
1489
    
1490
    len = len1;
1491
    while (len > 0) {
1492
        ret = send(fd, buf, len, 0);
1493
        if (ret < 0) {
1494
            int errno;
1495
            errno = WSAGetLastError();
1496
            if (errno != WSAEWOULDBLOCK) {
1497
                return -1;
1498
            }
1499
        } else if (ret == 0) {
1500
            break;
1501
        } else {
1502
            buf += ret;
1503
            len -= ret;
1504
        }
1505
    }
1506
    return len1 - len;
1507
}
1508

    
1509
void socket_set_nonblock(int fd)
1510
{
1511
    unsigned long opt = 1;
1512
    ioctlsocket(fd, FIONBIO, &opt);
1513
}
1514

    
1515
#else
1516

    
1517
static int unix_write(int fd, const uint8_t *buf, int len1)
1518
{
1519
    int ret, len;
1520

    
1521
    len = len1;
1522
    while (len > 0) {
1523
        ret = write(fd, buf, len);
1524
        if (ret < 0) {
1525
            if (errno != EINTR && errno != EAGAIN)
1526
                return -1;
1527
        } else if (ret == 0) {
1528
            break;
1529
        } else {
1530
            buf += ret;
1531
            len -= ret;
1532
        }
1533
    }
1534
    return len1 - len;
1535
}
1536

    
1537
static inline int send_all(int fd, const uint8_t *buf, int len1)
1538
{
1539
    return unix_write(fd, buf, len1);
1540
}
1541

    
1542
void socket_set_nonblock(int fd)
1543
{
1544
    fcntl(fd, F_SETFL, O_NONBLOCK);
1545
}
1546
#endif /* !_WIN32 */
1547

    
1548
#ifndef _WIN32
1549

    
1550
typedef struct {
1551
    int fd_in, fd_out;
1552
    int max_size;
1553
} FDCharDriver;
1554

    
1555
#define STDIO_MAX_CLIENTS 1
1556
static int stdio_nb_clients = 0;
1557

    
1558
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1559
{
1560
    FDCharDriver *s = chr->opaque;
1561
    return unix_write(s->fd_out, buf, len);
1562
}
1563

    
1564
static int fd_chr_read_poll(void *opaque)
1565
{
1566
    CharDriverState *chr = opaque;
1567
    FDCharDriver *s = chr->opaque;
1568

    
1569
    s->max_size = qemu_chr_can_read(chr);
1570
    return s->max_size;
1571
}
1572

    
1573
static void fd_chr_read(void *opaque)
1574
{
1575
    CharDriverState *chr = opaque;
1576
    FDCharDriver *s = chr->opaque;
1577
    int size, len;
1578
    uint8_t buf[1024];
1579
    
1580
    len = sizeof(buf);
1581
    if (len > s->max_size)
1582
        len = s->max_size;
1583
    if (len == 0)
1584
        return;
1585
    size = read(s->fd_in, buf, len);
1586
    if (size == 0) {
1587
        /* FD has been closed. Remove it from the active list.  */
1588
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1589
        return;
1590
    }
1591
    if (size > 0) {
1592
        qemu_chr_read(chr, buf, size);
1593
    }
1594
}
1595

    
1596
static void fd_chr_update_read_handler(CharDriverState *chr)
1597
{
1598
    FDCharDriver *s = chr->opaque;
1599

    
1600
    if (s->fd_in >= 0) {
1601
        if (nographic && s->fd_in == 0) {
1602
        } else {
1603
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1604
                                 fd_chr_read, NULL, chr);
1605
        }
1606
    }
1607
}
1608

    
1609
/* open a character device to a unix fd */
1610
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1611
{
1612
    CharDriverState *chr;
1613
    FDCharDriver *s;
1614

    
1615
    chr = qemu_mallocz(sizeof(CharDriverState));
1616
    if (!chr)
1617
        return NULL;
1618
    s = qemu_mallocz(sizeof(FDCharDriver));
1619
    if (!s) {
1620
        free(chr);
1621
        return NULL;
1622
    }
1623
    s->fd_in = fd_in;
1624
    s->fd_out = fd_out;
1625
    chr->opaque = s;
1626
    chr->chr_write = fd_chr_write;
1627
    chr->chr_update_read_handler = fd_chr_update_read_handler;
1628

    
1629
    qemu_chr_reset(chr);
1630

    
1631
    return chr;
1632
}
1633

    
1634
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1635
{
1636
    int fd_out;
1637

    
1638
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1639
    if (fd_out < 0)
1640
        return NULL;
1641
    return qemu_chr_open_fd(-1, fd_out);
1642
}
1643

    
1644
static CharDriverState *qemu_chr_open_pipe(const char *filename)
1645
{
1646
    int fd_in, fd_out;
1647
    char filename_in[256], filename_out[256];
1648

    
1649
    snprintf(filename_in, 256, "%s.in", filename);
1650
    snprintf(filename_out, 256, "%s.out", filename);
1651
    fd_in = open(filename_in, O_RDWR | O_BINARY);
1652
    fd_out = open(filename_out, O_RDWR | O_BINARY);
1653
    if (fd_in < 0 || fd_out < 0) {
1654
        if (fd_in >= 0)
1655
            close(fd_in);
1656
        if (fd_out >= 0)
1657
            close(fd_out);
1658
        fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1659
        if (fd_in < 0)
1660
            return NULL;
1661
    }
1662
    return qemu_chr_open_fd(fd_in, fd_out);
1663
}
1664

    
1665

    
1666
/* for STDIO, we handle the case where several clients use it
1667
   (nographic mode) */
1668

    
1669
#define TERM_FIFO_MAX_SIZE 1
1670

    
1671
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1672
static int term_fifo_size;
1673

    
1674
static int stdio_read_poll(void *opaque)
1675
{
1676
    CharDriverState *chr = opaque;
1677

    
1678
    /* try to flush the queue if needed */
1679
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1680
        qemu_chr_read(chr, term_fifo, 1);
1681
        term_fifo_size = 0;
1682
    }
1683
    /* see if we can absorb more chars */
1684
    if (term_fifo_size == 0)
1685
        return 1;
1686
    else
1687
        return 0;
1688
}
1689

    
1690
static void stdio_read(void *opaque)
1691
{
1692
    int size;
1693
    uint8_t buf[1];
1694
    CharDriverState *chr = opaque;
1695

    
1696
    size = read(0, buf, 1);
1697
    if (size == 0) {
1698
        /* stdin has been closed. Remove it from the active list.  */
1699
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1700
        return;
1701
    }
1702
    if (size > 0) {
1703
        if (qemu_chr_can_read(chr) > 0) {
1704
            qemu_chr_read(chr, buf, 1);
1705
        } else if (term_fifo_size == 0) {
1706
            term_fifo[term_fifo_size++] = buf[0];
1707
        }
1708
    }
1709
}
1710

    
1711
/* init terminal so that we can grab keys */
1712
static struct termios oldtty;
1713
static int old_fd0_flags;
1714

    
1715
static void term_exit(void)
1716
{
1717
    tcsetattr (0, TCSANOW, &oldtty);
1718
    fcntl(0, F_SETFL, old_fd0_flags);
1719
}
1720

    
1721
static void term_init(void)
1722
{
1723
    struct termios tty;
1724

    
1725
    tcgetattr (0, &tty);
1726
    oldtty = tty;
1727
    old_fd0_flags = fcntl(0, F_GETFL);
1728

    
1729
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1730
                          |INLCR|IGNCR|ICRNL|IXON);
1731
    tty.c_oflag |= OPOST;
1732
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1733
    /* if graphical mode, we allow Ctrl-C handling */
1734
    if (nographic)
1735
        tty.c_lflag &= ~ISIG;
1736
    tty.c_cflag &= ~(CSIZE|PARENB);
1737
    tty.c_cflag |= CS8;
1738
    tty.c_cc[VMIN] = 1;
1739
    tty.c_cc[VTIME] = 0;
1740
    
1741
    tcsetattr (0, TCSANOW, &tty);
1742

    
1743
    atexit(term_exit);
1744

    
1745
    fcntl(0, F_SETFL, O_NONBLOCK);
1746
}
1747

    
1748
static CharDriverState *qemu_chr_open_stdio(void)
1749
{
1750
    CharDriverState *chr;
1751

    
1752
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1753
        return NULL;
1754
    chr = qemu_chr_open_fd(0, 1);
1755
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1756
    stdio_nb_clients++;
1757
    term_init();
1758

    
1759
    return chr;
1760
}
1761

    
1762
#if defined(__linux__)
1763
static CharDriverState *qemu_chr_open_pty(void)
1764
{
1765
    struct termios tty;
1766
    char slave_name[1024];
1767
    int master_fd, slave_fd;
1768
    
1769
    /* Not satisfying */
1770
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1771
        return NULL;
1772
    }
1773
    
1774
    /* Disabling local echo and line-buffered output */
1775
    tcgetattr (master_fd, &tty);
1776
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1777
    tty.c_cc[VMIN] = 1;
1778
    tty.c_cc[VTIME] = 0;
1779
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1780

    
1781
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1782
    return qemu_chr_open_fd(master_fd, master_fd);
1783
}
1784

    
1785
static void tty_serial_init(int fd, int speed, 
1786
                            int parity, int data_bits, int stop_bits)
1787
{
1788
    struct termios tty;
1789
    speed_t spd;
1790

    
1791
#if 0
1792
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1793
           speed, parity, data_bits, stop_bits);
1794
#endif
1795
    tcgetattr (fd, &tty);
1796

    
1797
    switch(speed) {
1798
    case 50:
1799
        spd = B50;
1800
        break;
1801
    case 75:
1802
        spd = B75;
1803
        break;
1804
    case 300:
1805
        spd = B300;
1806
        break;
1807
    case 600:
1808
        spd = B600;
1809
        break;
1810
    case 1200:
1811
        spd = B1200;
1812
        break;
1813
    case 2400:
1814
        spd = B2400;
1815
        break;
1816
    case 4800:
1817
        spd = B4800;
1818
        break;
1819
    case 9600:
1820
        spd = B9600;
1821
        break;
1822
    case 19200:
1823
        spd = B19200;
1824
        break;
1825
    case 38400:
1826
        spd = B38400;
1827
        break;
1828
    case 57600:
1829
        spd = B57600;
1830
        break;
1831
    default:
1832
    case 115200:
1833
        spd = B115200;
1834
        break;
1835
    }
1836

    
1837
    cfsetispeed(&tty, spd);
1838
    cfsetospeed(&tty, spd);
1839

    
1840
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1841
                          |INLCR|IGNCR|ICRNL|IXON);
1842
    tty.c_oflag |= OPOST;
1843
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1844
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1845
    switch(data_bits) {
1846
    default:
1847
    case 8:
1848
        tty.c_cflag |= CS8;
1849
        break;
1850
    case 7:
1851
        tty.c_cflag |= CS7;
1852
        break;
1853
    case 6:
1854
        tty.c_cflag |= CS6;
1855
        break;
1856
    case 5:
1857
        tty.c_cflag |= CS5;
1858
        break;
1859
    }
1860
    switch(parity) {
1861
    default:
1862
    case 'N':
1863
        break;
1864
    case 'E':
1865
        tty.c_cflag |= PARENB;
1866
        break;
1867
    case 'O':
1868
        tty.c_cflag |= PARENB | PARODD;
1869
        break;
1870
    }
1871
    if (stop_bits == 2)
1872
        tty.c_cflag |= CSTOPB;
1873
    
1874
    tcsetattr (fd, TCSANOW, &tty);
1875
}
1876

    
1877
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1878
{
1879
    FDCharDriver *s = chr->opaque;
1880
    
1881
    switch(cmd) {
1882
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1883
        {
1884
            QEMUSerialSetParams *ssp = arg;
1885
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1886
                            ssp->data_bits, ssp->stop_bits);
1887
        }
1888
        break;
1889
    case CHR_IOCTL_SERIAL_SET_BREAK:
1890
        {
1891
            int enable = *(int *)arg;
1892
            if (enable)
1893
                tcsendbreak(s->fd_in, 1);
1894
        }
1895
        break;
1896
    default:
1897
        return -ENOTSUP;
1898
    }
1899
    return 0;
1900
}
1901

    
1902
static CharDriverState *qemu_chr_open_tty(const char *filename)
1903
{
1904
    CharDriverState *chr;
1905
    int fd;
1906

    
1907
    fd = open(filename, O_RDWR | O_NONBLOCK);
1908
    if (fd < 0)
1909
        return NULL;
1910
    fcntl(fd, F_SETFL, O_NONBLOCK);
1911
    tty_serial_init(fd, 115200, 'N', 8, 1);
1912
    chr = qemu_chr_open_fd(fd, fd);
1913
    if (!chr)
1914
        return NULL;
1915
    chr->chr_ioctl = tty_serial_ioctl;
1916
    qemu_chr_reset(chr);
1917
    return chr;
1918
}
1919

    
1920
typedef struct {
1921
    int fd;
1922
    int mode;
1923
} ParallelCharDriver;
1924

    
1925
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1926
{
1927
    if (s->mode != mode) {
1928
        int m = mode;
1929
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1930
            return 0;
1931
        s->mode = mode;
1932
    }
1933
    return 1;
1934
}
1935

    
1936
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1937
{
1938
    ParallelCharDriver *drv = chr->opaque;
1939
    int fd = drv->fd;
1940
    uint8_t b;
1941

    
1942
    switch(cmd) {
1943
    case CHR_IOCTL_PP_READ_DATA:
1944
        if (ioctl(fd, PPRDATA, &b) < 0)
1945
            return -ENOTSUP;
1946
        *(uint8_t *)arg = b;
1947
        break;
1948
    case CHR_IOCTL_PP_WRITE_DATA:
1949
        b = *(uint8_t *)arg;
1950
        if (ioctl(fd, PPWDATA, &b) < 0)
1951
            return -ENOTSUP;
1952
        break;
1953
    case CHR_IOCTL_PP_READ_CONTROL:
1954
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1955
            return -ENOTSUP;
1956
        /* Linux gives only the lowest bits, and no way to know data
1957
           direction! For better compatibility set the fixed upper
1958
           bits. */
1959
        *(uint8_t *)arg = b | 0xc0;
1960
        break;
1961
    case CHR_IOCTL_PP_WRITE_CONTROL:
1962
        b = *(uint8_t *)arg;
1963
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1964
            return -ENOTSUP;
1965
        break;
1966
    case CHR_IOCTL_PP_READ_STATUS:
1967
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1968
            return -ENOTSUP;
1969
        *(uint8_t *)arg = b;
1970
        break;
1971
    case CHR_IOCTL_PP_EPP_READ_ADDR:
1972
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1973
            struct ParallelIOArg *parg = arg;
1974
            int n = read(fd, parg->buffer, parg->count);
1975
            if (n != parg->count) {
1976
                return -EIO;
1977
            }
1978
        }
1979
        break;
1980
    case CHR_IOCTL_PP_EPP_READ:
1981
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1982
            struct ParallelIOArg *parg = arg;
1983
            int n = read(fd, parg->buffer, parg->count);
1984
            if (n != parg->count) {
1985
                return -EIO;
1986
            }
1987
        }
1988
        break;
1989
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1990
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1991
            struct ParallelIOArg *parg = arg;
1992
            int n = write(fd, parg->buffer, parg->count);
1993
            if (n != parg->count) {
1994
                return -EIO;
1995
            }
1996
        }
1997
        break;
1998
    case CHR_IOCTL_PP_EPP_WRITE:
1999
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2000
            struct ParallelIOArg *parg = arg;
2001
            int n = write(fd, parg->buffer, parg->count);
2002
            if (n != parg->count) {
2003
                return -EIO;
2004
            }
2005
        }
2006
        break;
2007
    default:
2008
        return -ENOTSUP;
2009
    }
2010
    return 0;
2011
}
2012

    
2013
static void pp_close(CharDriverState *chr)
2014
{
2015
    ParallelCharDriver *drv = chr->opaque;
2016
    int fd = drv->fd;
2017

    
2018
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2019
    ioctl(fd, PPRELEASE);
2020
    close(fd);
2021
    qemu_free(drv);
2022
}
2023

    
2024
static CharDriverState *qemu_chr_open_pp(const char *filename)
2025
{
2026
    CharDriverState *chr;
2027
    ParallelCharDriver *drv;
2028
    int fd;
2029

    
2030
    fd = open(filename, O_RDWR);
2031
    if (fd < 0)
2032
        return NULL;
2033

    
2034
    if (ioctl(fd, PPCLAIM) < 0) {
2035
        close(fd);
2036
        return NULL;
2037
    }
2038

    
2039
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2040
    if (!drv) {
2041
        close(fd);
2042
        return NULL;
2043
    }
2044
    drv->fd = fd;
2045
    drv->mode = IEEE1284_MODE_COMPAT;
2046

    
2047
    chr = qemu_mallocz(sizeof(CharDriverState));
2048
    if (!chr) {
2049
        qemu_free(drv);
2050
        close(fd);
2051
        return NULL;
2052
    }
2053
    chr->chr_write = null_chr_write;
2054
    chr->chr_ioctl = pp_ioctl;
2055
    chr->chr_close = pp_close;
2056
    chr->opaque = drv;
2057

    
2058
    qemu_chr_reset(chr);
2059

    
2060
    return chr;
2061
}
2062

    
2063
#else
2064
static CharDriverState *qemu_chr_open_pty(void)
2065
{
2066
    return NULL;
2067
}
2068
#endif
2069

    
2070
#endif /* !defined(_WIN32) */
2071

    
2072
#ifdef _WIN32
2073
typedef struct {
2074
    int max_size;
2075
    HANDLE hcom, hrecv, hsend;
2076
    OVERLAPPED orecv, osend;
2077
    BOOL fpipe;
2078
    DWORD len;
2079
} WinCharState;
2080

    
2081
#define NSENDBUF 2048
2082
#define NRECVBUF 2048
2083
#define MAXCONNECT 1
2084
#define NTIMEOUT 5000
2085

    
2086
static int win_chr_poll(void *opaque);
2087
static int win_chr_pipe_poll(void *opaque);
2088

    
2089
static void win_chr_close(CharDriverState *chr)
2090
{
2091
    WinCharState *s = chr->opaque;
2092

    
2093
    if (s->hsend) {
2094
        CloseHandle(s->hsend);
2095
        s->hsend = NULL;
2096
    }
2097
    if (s->hrecv) {
2098
        CloseHandle(s->hrecv);
2099
        s->hrecv = NULL;
2100
    }
2101
    if (s->hcom) {
2102
        CloseHandle(s->hcom);
2103
        s->hcom = NULL;
2104
    }
2105
    if (s->fpipe)
2106
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2107
    else
2108
        qemu_del_polling_cb(win_chr_poll, chr);
2109
}
2110

    
2111
static int win_chr_init(CharDriverState *chr, const char *filename)
2112
{
2113
    WinCharState *s = chr->opaque;
2114
    COMMCONFIG comcfg;
2115
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2116
    COMSTAT comstat;
2117
    DWORD size;
2118
    DWORD err;
2119
    
2120
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2121
    if (!s->hsend) {
2122
        fprintf(stderr, "Failed CreateEvent\n");
2123
        goto fail;
2124
    }
2125
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2126
    if (!s->hrecv) {
2127
        fprintf(stderr, "Failed CreateEvent\n");
2128
        goto fail;
2129
    }
2130

    
2131
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2132
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2133
    if (s->hcom == INVALID_HANDLE_VALUE) {
2134
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2135
        s->hcom = NULL;
2136
        goto fail;
2137
    }
2138
    
2139
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2140
        fprintf(stderr, "Failed SetupComm\n");
2141
        goto fail;
2142
    }
2143
    
2144
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2145
    size = sizeof(COMMCONFIG);
2146
    GetDefaultCommConfig(filename, &comcfg, &size);
2147
    comcfg.dcb.DCBlength = sizeof(DCB);
2148
    CommConfigDialog(filename, NULL, &comcfg);
2149

    
2150
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2151
        fprintf(stderr, "Failed SetCommState\n");
2152
        goto fail;
2153
    }
2154

    
2155
    if (!SetCommMask(s->hcom, EV_ERR)) {
2156
        fprintf(stderr, "Failed SetCommMask\n");
2157
        goto fail;
2158
    }
2159

    
2160
    cto.ReadIntervalTimeout = MAXDWORD;
2161
    if (!SetCommTimeouts(s->hcom, &cto)) {
2162
        fprintf(stderr, "Failed SetCommTimeouts\n");
2163
        goto fail;
2164
    }
2165
    
2166
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2167
        fprintf(stderr, "Failed ClearCommError\n");
2168
        goto fail;
2169
    }
2170
    qemu_add_polling_cb(win_chr_poll, chr);
2171
    return 0;
2172

    
2173
 fail:
2174
    win_chr_close(chr);
2175
    return -1;
2176
}
2177

    
2178
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2179
{
2180
    WinCharState *s = chr->opaque;
2181
    DWORD len, ret, size, err;
2182

    
2183
    len = len1;
2184
    ZeroMemory(&s->osend, sizeof(s->osend));
2185
    s->osend.hEvent = s->hsend;
2186
    while (len > 0) {
2187
        if (s->hsend)
2188
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2189
        else
2190
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2191
        if (!ret) {
2192
            err = GetLastError();
2193
            if (err == ERROR_IO_PENDING) {
2194
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2195
                if (ret) {
2196
                    buf += size;
2197
                    len -= size;
2198
                } else {
2199
                    break;
2200
                }
2201
            } else {
2202
                break;
2203
            }
2204
        } else {
2205
            buf += size;
2206
            len -= size;
2207
        }
2208
    }
2209
    return len1 - len;
2210
}
2211

    
2212
static int win_chr_read_poll(CharDriverState *chr)
2213
{
2214
    WinCharState *s = chr->opaque;
2215

    
2216
    s->max_size = qemu_chr_can_read(chr);
2217
    return s->max_size;
2218
}
2219

    
2220
static void win_chr_readfile(CharDriverState *chr)
2221
{
2222
    WinCharState *s = chr->opaque;
2223
    int ret, err;
2224
    uint8_t buf[1024];
2225
    DWORD size;
2226
    
2227
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2228
    s->orecv.hEvent = s->hrecv;
2229
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2230
    if (!ret) {
2231
        err = GetLastError();
2232
        if (err == ERROR_IO_PENDING) {
2233
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2234
        }
2235
    }
2236

    
2237
    if (size > 0) {
2238
        qemu_chr_read(chr, buf, size);
2239
    }
2240
}
2241

    
2242
static void win_chr_read(CharDriverState *chr)
2243
{
2244
    WinCharState *s = chr->opaque;
2245

    
2246
    if (s->len > s->max_size)
2247
        s->len = s->max_size;
2248
    if (s->len == 0)
2249
        return;
2250
    
2251
    win_chr_readfile(chr);
2252
}
2253

    
2254
static int win_chr_poll(void *opaque)
2255
{
2256
    CharDriverState *chr = opaque;
2257
    WinCharState *s = chr->opaque;
2258
    COMSTAT status;
2259
    DWORD comerr;
2260
    
2261
    ClearCommError(s->hcom, &comerr, &status);
2262
    if (status.cbInQue > 0) {
2263
        s->len = status.cbInQue;
2264
        win_chr_read_poll(chr);
2265
        win_chr_read(chr);
2266
        return 1;
2267
    }
2268
    return 0;
2269
}
2270

    
2271
static CharDriverState *qemu_chr_open_win(const char *filename)
2272
{
2273
    CharDriverState *chr;
2274
    WinCharState *s;
2275
    
2276
    chr = qemu_mallocz(sizeof(CharDriverState));
2277
    if (!chr)
2278
        return NULL;
2279
    s = qemu_mallocz(sizeof(WinCharState));
2280
    if (!s) {
2281
        free(chr);
2282
        return NULL;
2283
    }
2284
    chr->opaque = s;
2285
    chr->chr_write = win_chr_write;
2286
    chr->chr_close = win_chr_close;
2287

    
2288
    if (win_chr_init(chr, filename) < 0) {
2289
        free(s);
2290
        free(chr);
2291
        return NULL;
2292
    }
2293
    qemu_chr_reset(chr);
2294
    return chr;
2295
}
2296

    
2297
static int win_chr_pipe_poll(void *opaque)
2298
{
2299
    CharDriverState *chr = opaque;
2300
    WinCharState *s = chr->opaque;
2301
    DWORD size;
2302

    
2303
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2304
    if (size > 0) {
2305
        s->len = size;
2306
        win_chr_read_poll(chr);
2307
        win_chr_read(chr);
2308
        return 1;
2309
    }
2310
    return 0;
2311
}
2312

    
2313
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2314
{
2315
    WinCharState *s = chr->opaque;
2316
    OVERLAPPED ov;
2317
    int ret;
2318
    DWORD size;
2319
    char openname[256];
2320
    
2321
    s->fpipe = TRUE;
2322

    
2323
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2324
    if (!s->hsend) {
2325
        fprintf(stderr, "Failed CreateEvent\n");
2326
        goto fail;
2327
    }
2328
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2329
    if (!s->hrecv) {
2330
        fprintf(stderr, "Failed CreateEvent\n");
2331
        goto fail;
2332
    }
2333
    
2334
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2335
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2336
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2337
                              PIPE_WAIT,
2338
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2339
    if (s->hcom == INVALID_HANDLE_VALUE) {
2340
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2341
        s->hcom = NULL;
2342
        goto fail;
2343
    }
2344

    
2345
    ZeroMemory(&ov, sizeof(ov));
2346
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2347
    ret = ConnectNamedPipe(s->hcom, &ov);
2348
    if (ret) {
2349
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2350
        goto fail;
2351
    }
2352

    
2353
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2354
    if (!ret) {
2355
        fprintf(stderr, "Failed GetOverlappedResult\n");
2356
        if (ov.hEvent) {
2357
            CloseHandle(ov.hEvent);
2358
            ov.hEvent = NULL;
2359
        }
2360
        goto fail;
2361
    }
2362

    
2363
    if (ov.hEvent) {
2364
        CloseHandle(ov.hEvent);
2365
        ov.hEvent = NULL;
2366
    }
2367
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2368
    return 0;
2369

    
2370
 fail:
2371
    win_chr_close(chr);
2372
    return -1;
2373
}
2374

    
2375

    
2376
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2377
{
2378
    CharDriverState *chr;
2379
    WinCharState *s;
2380

    
2381
    chr = qemu_mallocz(sizeof(CharDriverState));
2382
    if (!chr)
2383
        return NULL;
2384
    s = qemu_mallocz(sizeof(WinCharState));
2385
    if (!s) {
2386
        free(chr);
2387
        return NULL;
2388
    }
2389
    chr->opaque = s;
2390
    chr->chr_write = win_chr_write;
2391
    chr->chr_close = win_chr_close;
2392
    
2393
    if (win_chr_pipe_init(chr, filename) < 0) {
2394
        free(s);
2395
        free(chr);
2396
        return NULL;
2397
    }
2398
    qemu_chr_reset(chr);
2399
    return chr;
2400
}
2401

    
2402
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2403
{
2404
    CharDriverState *chr;
2405
    WinCharState *s;
2406

    
2407
    chr = qemu_mallocz(sizeof(CharDriverState));
2408
    if (!chr)
2409
        return NULL;
2410
    s = qemu_mallocz(sizeof(WinCharState));
2411
    if (!s) {
2412
        free(chr);
2413
        return NULL;
2414
    }
2415
    s->hcom = fd_out;
2416
    chr->opaque = s;
2417
    chr->chr_write = win_chr_write;
2418
    qemu_chr_reset(chr);
2419
    return chr;
2420
}
2421
    
2422
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2423
{
2424
    HANDLE fd_out;
2425
    
2426
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2427
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2428
    if (fd_out == INVALID_HANDLE_VALUE)
2429
        return NULL;
2430

    
2431
    return qemu_chr_open_win_file(fd_out);
2432
}
2433
#endif
2434

    
2435
/***********************************************************/
2436
/* UDP Net console */
2437

    
2438
typedef struct {
2439
    int fd;
2440
    struct sockaddr_in daddr;
2441
    char buf[1024];
2442
    int bufcnt;
2443
    int bufptr;
2444
    int max_size;
2445
} NetCharDriver;
2446

    
2447
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2448
{
2449
    NetCharDriver *s = chr->opaque;
2450

    
2451
    return sendto(s->fd, buf, len, 0,
2452
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2453
}
2454

    
2455
static int udp_chr_read_poll(void *opaque)
2456
{
2457
    CharDriverState *chr = opaque;
2458
    NetCharDriver *s = chr->opaque;
2459

    
2460
    s->max_size = qemu_chr_can_read(chr);
2461

    
2462
    /* If there were any stray characters in the queue process them
2463
     * first
2464
     */
2465
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2466
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2467
        s->bufptr++;
2468
        s->max_size = qemu_chr_can_read(chr);
2469
    }
2470
    return s->max_size;
2471
}
2472

    
2473
static void udp_chr_read(void *opaque)
2474
{
2475
    CharDriverState *chr = opaque;
2476
    NetCharDriver *s = chr->opaque;
2477

    
2478
    if (s->max_size == 0)
2479
        return;
2480
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2481
    s->bufptr = s->bufcnt;
2482
    if (s->bufcnt <= 0)
2483
        return;
2484

    
2485
    s->bufptr = 0;
2486
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2487
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2488
        s->bufptr++;
2489
        s->max_size = qemu_chr_can_read(chr);
2490
    }
2491
}
2492

    
2493
static void udp_chr_update_read_handler(CharDriverState *chr)
2494
{
2495
    NetCharDriver *s = chr->opaque;
2496

    
2497
    if (s->fd >= 0) {
2498
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2499
                             udp_chr_read, NULL, chr);
2500
    }
2501
}
2502

    
2503
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2504
#ifndef _WIN32
2505
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2506
#endif
2507
int parse_host_src_port(struct sockaddr_in *haddr,
2508
                        struct sockaddr_in *saddr,
2509
                        const char *str);
2510

    
2511
static CharDriverState *qemu_chr_open_udp(const char *def)
2512
{
2513
    CharDriverState *chr = NULL;
2514
    NetCharDriver *s = NULL;
2515
    int fd = -1;
2516
    struct sockaddr_in saddr;
2517

    
2518
    chr = qemu_mallocz(sizeof(CharDriverState));
2519
    if (!chr)
2520
        goto return_err;
2521
    s = qemu_mallocz(sizeof(NetCharDriver));
2522
    if (!s)
2523
        goto return_err;
2524

    
2525
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2526
    if (fd < 0) {
2527
        perror("socket(PF_INET, SOCK_DGRAM)");
2528
        goto return_err;
2529
    }
2530

    
2531
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2532
        printf("Could not parse: %s\n", def);
2533
        goto return_err;
2534
    }
2535

    
2536
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2537
    {
2538
        perror("bind");
2539
        goto return_err;
2540
    }
2541

    
2542
    s->fd = fd;
2543
    s->bufcnt = 0;
2544
    s->bufptr = 0;
2545
    chr->opaque = s;
2546
    chr->chr_write = udp_chr_write;
2547
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2548
    return chr;
2549

    
2550
return_err:
2551
    if (chr)
2552
        free(chr);
2553
    if (s)
2554
        free(s);
2555
    if (fd >= 0)
2556
        closesocket(fd);
2557
    return NULL;
2558
}
2559

    
2560
/***********************************************************/
2561
/* TCP Net console */
2562

    
2563
typedef struct {
2564
    int fd, listen_fd;
2565
    int connected;
2566
    int max_size;
2567
    int do_telnetopt;
2568
    int do_nodelay;
2569
    int is_unix;
2570
} TCPCharDriver;
2571

    
2572
static void tcp_chr_accept(void *opaque);
2573

    
2574
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2575
{
2576
    TCPCharDriver *s = chr->opaque;
2577
    if (s->connected) {
2578
        return send_all(s->fd, buf, len);
2579
    } else {
2580
        /* XXX: indicate an error ? */
2581
        return len;
2582
    }
2583
}
2584

    
2585
static int tcp_chr_read_poll(void *opaque)
2586
{
2587
    CharDriverState *chr = opaque;
2588
    TCPCharDriver *s = chr->opaque;
2589
    if (!s->connected)
2590
        return 0;
2591
    s->max_size = qemu_chr_can_read(chr);
2592
    return s->max_size;
2593
}
2594

    
2595
#define IAC 255
2596
#define IAC_BREAK 243
2597
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2598
                                      TCPCharDriver *s,
2599
                                      char *buf, int *size)
2600
{
2601
    /* Handle any telnet client's basic IAC options to satisfy char by
2602
     * char mode with no echo.  All IAC options will be removed from
2603
     * the buf and the do_telnetopt variable will be used to track the
2604
     * state of the width of the IAC information.
2605
     *
2606
     * IAC commands come in sets of 3 bytes with the exception of the
2607
     * "IAC BREAK" command and the double IAC.
2608
     */
2609

    
2610
    int i;
2611
    int j = 0;
2612

    
2613
    for (i = 0; i < *size; i++) {
2614
        if (s->do_telnetopt > 1) {
2615
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2616
                /* Double IAC means send an IAC */
2617
                if (j != i)
2618
                    buf[j] = buf[i];
2619
                j++;
2620
                s->do_telnetopt = 1;
2621
            } else {
2622
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2623
                    /* Handle IAC break commands by sending a serial break */
2624
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
2625
                    s->do_telnetopt++;
2626
                }
2627
                s->do_telnetopt++;
2628
            }
2629
            if (s->do_telnetopt >= 4) {
2630
                s->do_telnetopt = 1;
2631
            }
2632
        } else {
2633
            if ((unsigned char)buf[i] == IAC) {
2634
                s->do_telnetopt = 2;
2635
            } else {
2636
                if (j != i)
2637
                    buf[j] = buf[i];
2638
                j++;
2639
            }
2640
        }
2641
    }
2642
    *size = j;
2643
}
2644

    
2645
static void tcp_chr_read(void *opaque)
2646
{
2647
    CharDriverState *chr = opaque;
2648
    TCPCharDriver *s = chr->opaque;
2649
    uint8_t buf[1024];
2650
    int len, size;
2651

    
2652
    if (!s->connected || s->max_size <= 0)
2653
        return;
2654
    len = sizeof(buf);
2655
    if (len > s->max_size)
2656
        len = s->max_size;
2657
    size = recv(s->fd, buf, len, 0);
2658
    if (size == 0) {
2659
        /* connection closed */
2660
        s->connected = 0;
2661
        if (s->listen_fd >= 0) {
2662
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2663
        }
2664
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2665
        closesocket(s->fd);
2666
        s->fd = -1;
2667
    } else if (size > 0) {
2668
        if (s->do_telnetopt)
2669
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2670
        if (size > 0)
2671
            qemu_chr_read(chr, buf, size);
2672
    }
2673
}
2674

    
2675
static void tcp_chr_connect(void *opaque)
2676
{
2677
    CharDriverState *chr = opaque;
2678
    TCPCharDriver *s = chr->opaque;
2679

    
2680
    s->connected = 1;
2681
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2682
                         tcp_chr_read, NULL, chr);
2683
    qemu_chr_reset(chr);
2684
}
2685

    
2686
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2687
static void tcp_chr_telnet_init(int fd)
2688
{
2689
    char buf[3];
2690
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2691
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2692
    send(fd, (char *)buf, 3, 0);
2693
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2694
    send(fd, (char *)buf, 3, 0);
2695
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2696
    send(fd, (char *)buf, 3, 0);
2697
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2698
    send(fd, (char *)buf, 3, 0);
2699
}
2700

    
2701
static void socket_set_nodelay(int fd)
2702
{
2703
    int val = 1;
2704
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2705
}
2706

    
2707
static void tcp_chr_accept(void *opaque)
2708
{
2709
    CharDriverState *chr = opaque;
2710
    TCPCharDriver *s = chr->opaque;
2711
    struct sockaddr_in saddr;
2712
#ifndef _WIN32
2713
    struct sockaddr_un uaddr;
2714
#endif
2715
    struct sockaddr *addr;
2716
    socklen_t len;
2717
    int fd;
2718

    
2719
    for(;;) {
2720
#ifndef _WIN32
2721
        if (s->is_unix) {
2722
            len = sizeof(uaddr);
2723
            addr = (struct sockaddr *)&uaddr;
2724
        } else
2725
#endif
2726
        {
2727
            len = sizeof(saddr);
2728
            addr = (struct sockaddr *)&saddr;
2729
        }
2730
        fd = accept(s->listen_fd, addr, &len);
2731
        if (fd < 0 && errno != EINTR) {
2732
            return;
2733
        } else if (fd >= 0) {
2734
            if (s->do_telnetopt)
2735
                tcp_chr_telnet_init(fd);
2736
            break;
2737
        }
2738
    }
2739
    socket_set_nonblock(fd);
2740
    if (s->do_nodelay)
2741
        socket_set_nodelay(fd);
2742
    s->fd = fd;
2743
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2744
    tcp_chr_connect(chr);
2745
}
2746

    
2747
static void tcp_chr_close(CharDriverState *chr)
2748
{
2749
    TCPCharDriver *s = chr->opaque;
2750
    if (s->fd >= 0)
2751
        closesocket(s->fd);
2752
    if (s->listen_fd >= 0)
2753
        closesocket(s->listen_fd);
2754
    qemu_free(s);
2755
}
2756

    
2757
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2758
                                          int is_telnet,
2759
                                          int is_unix)
2760
{
2761
    CharDriverState *chr = NULL;
2762
    TCPCharDriver *s = NULL;
2763
    int fd = -1, ret, err, val;
2764
    int is_listen = 0;
2765
    int is_waitconnect = 1;
2766
    int do_nodelay = 0;
2767
    const char *ptr;
2768
    struct sockaddr_in saddr;
2769
#ifndef _WIN32
2770
    struct sockaddr_un uaddr;
2771
#endif
2772
    struct sockaddr *addr;
2773
    socklen_t addrlen;
2774

    
2775
#ifndef _WIN32
2776
    if (is_unix) {
2777
        addr = (struct sockaddr *)&uaddr;
2778
        addrlen = sizeof(uaddr);
2779
        if (parse_unix_path(&uaddr, host_str) < 0)
2780
            goto fail;
2781
    } else
2782
#endif
2783
    {
2784
        addr = (struct sockaddr *)&saddr;
2785
        addrlen = sizeof(saddr);
2786
        if (parse_host_port(&saddr, host_str) < 0)
2787
            goto fail;
2788
    }
2789

    
2790
    ptr = host_str;
2791
    while((ptr = strchr(ptr,','))) {
2792
        ptr++;
2793
        if (!strncmp(ptr,"server",6)) {
2794
            is_listen = 1;
2795
        } else if (!strncmp(ptr,"nowait",6)) {
2796
            is_waitconnect = 0;
2797
        } else if (!strncmp(ptr,"nodelay",6)) {
2798
            do_nodelay = 1;
2799
        } else {
2800
            printf("Unknown option: %s\n", ptr);
2801
            goto fail;
2802
        }
2803
    }
2804
    if (!is_listen)
2805
        is_waitconnect = 0;
2806

    
2807
    chr = qemu_mallocz(sizeof(CharDriverState));
2808
    if (!chr)
2809
        goto fail;
2810
    s = qemu_mallocz(sizeof(TCPCharDriver));
2811
    if (!s)
2812
        goto fail;
2813

    
2814
#ifndef _WIN32
2815
    if (is_unix)
2816
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2817
    else
2818
#endif
2819
        fd = socket(PF_INET, SOCK_STREAM, 0);
2820
        
2821
    if (fd < 0) 
2822
        goto fail;
2823

    
2824
    if (!is_waitconnect)
2825
        socket_set_nonblock(fd);
2826

    
2827
    s->connected = 0;
2828
    s->fd = -1;
2829
    s->listen_fd = -1;
2830
    s->is_unix = is_unix;
2831
    s->do_nodelay = do_nodelay && !is_unix;
2832

    
2833
    chr->opaque = s;
2834
    chr->chr_write = tcp_chr_write;
2835
    chr->chr_close = tcp_chr_close;
2836

    
2837
    if (is_listen) {
2838
        /* allow fast reuse */
2839
#ifndef _WIN32
2840
        if (is_unix) {
2841
            char path[109];
2842
            strncpy(path, uaddr.sun_path, 108);
2843
            path[108] = 0;
2844
            unlink(path);
2845
        } else
2846
#endif
2847
        {
2848
            val = 1;
2849
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2850
        }
2851
        
2852
        ret = bind(fd, addr, addrlen);
2853
        if (ret < 0)
2854
            goto fail;
2855

    
2856
        ret = listen(fd, 0);
2857
        if (ret < 0)
2858
            goto fail;
2859

    
2860
        s->listen_fd = fd;
2861
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2862
        if (is_telnet)
2863
            s->do_telnetopt = 1;
2864
    } else {
2865
        for(;;) {
2866
            ret = connect(fd, addr, addrlen);
2867
            if (ret < 0) {
2868
                err = socket_error();
2869
                if (err == EINTR || err == EWOULDBLOCK) {
2870
                } else if (err == EINPROGRESS) {
2871
                    break;
2872
#ifdef _WIN32
2873
                } else if (err == WSAEALREADY) {
2874
                    break;
2875
#endif
2876
                } else {
2877
                    goto fail;
2878
                }
2879
            } else {
2880
                s->connected = 1;
2881
                break;
2882
            }
2883
        }
2884
        s->fd = fd;
2885
        socket_set_nodelay(fd);
2886
        if (s->connected)
2887
            tcp_chr_connect(chr);
2888
        else
2889
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2890
    }
2891
    
2892
    if (is_listen && is_waitconnect) {
2893
        printf("QEMU waiting for connection on: %s\n", host_str);
2894
        tcp_chr_accept(chr);
2895
        socket_set_nonblock(s->listen_fd);
2896
    }
2897

    
2898
    return chr;
2899
 fail:
2900
    if (fd >= 0)
2901
        closesocket(fd);
2902
    qemu_free(s);
2903
    qemu_free(chr);
2904
    return NULL;
2905
}
2906

    
2907
CharDriverState *qemu_chr_open(const char *filename)
2908
{
2909
    const char *p;
2910

    
2911
    if (!strcmp(filename, "vc")) {
2912
        return text_console_init(&display_state);
2913
    } else if (!strcmp(filename, "null")) {
2914
        return qemu_chr_open_null();
2915
    } else 
2916
    if (strstart(filename, "tcp:", &p)) {
2917
        return qemu_chr_open_tcp(p, 0, 0);
2918
    } else
2919
    if (strstart(filename, "telnet:", &p)) {
2920
        return qemu_chr_open_tcp(p, 1, 0);
2921
    } else
2922
    if (strstart(filename, "udp:", &p)) {
2923
        return qemu_chr_open_udp(p);
2924
    } else
2925
    if (strstart(filename, "mon:", &p)) {
2926
        CharDriverState *drv = qemu_chr_open(p);
2927
        if (drv) {
2928
            drv = qemu_chr_open_mux(drv);
2929
            monitor_init(drv, !nographic);
2930
            return drv;
2931
        }
2932
        printf("Unable to open driver: %s\n", p);
2933
        return 0;
2934
    } else
2935
#ifndef _WIN32
2936
    if (strstart(filename, "unix:", &p)) {
2937
        return qemu_chr_open_tcp(p, 0, 1);
2938
    } else if (strstart(filename, "file:", &p)) {
2939
        return qemu_chr_open_file_out(p);
2940
    } else if (strstart(filename, "pipe:", &p)) {
2941
        return qemu_chr_open_pipe(p);
2942
    } else if (!strcmp(filename, "pty")) {
2943
        return qemu_chr_open_pty();
2944
    } else if (!strcmp(filename, "stdio")) {
2945
        return qemu_chr_open_stdio();
2946
    } else 
2947
#endif
2948
#if defined(__linux__)
2949
    if (strstart(filename, "/dev/parport", NULL)) {
2950
        return qemu_chr_open_pp(filename);
2951
    } else 
2952
    if (strstart(filename, "/dev/", NULL)) {
2953
        return qemu_chr_open_tty(filename);
2954
    } else 
2955
#endif
2956
#ifdef _WIN32
2957
    if (strstart(filename, "COM", NULL)) {
2958
        return qemu_chr_open_win(filename);
2959
    } else
2960
    if (strstart(filename, "pipe:", &p)) {
2961
        return qemu_chr_open_win_pipe(p);
2962
    } else
2963
    if (strstart(filename, "file:", &p)) {
2964
        return qemu_chr_open_win_file_out(p);
2965
    }
2966
#endif
2967
    {
2968
        return NULL;
2969
    }
2970
}
2971

    
2972
void qemu_chr_close(CharDriverState *chr)
2973
{
2974
    if (chr->chr_close)
2975
        chr->chr_close(chr);
2976
}
2977

    
2978
/***********************************************************/
2979
/* network device redirectors */
2980

    
2981
void hex_dump(FILE *f, const uint8_t *buf, int size)
2982
{
2983
    int len, i, j, c;
2984

    
2985
    for(i=0;i<size;i+=16) {
2986
        len = size - i;
2987
        if (len > 16)
2988
            len = 16;
2989
        fprintf(f, "%08x ", i);
2990
        for(j=0;j<16;j++) {
2991
            if (j < len)
2992
                fprintf(f, " %02x", buf[i+j]);
2993
            else
2994
                fprintf(f, "   ");
2995
        }
2996
        fprintf(f, " ");
2997
        for(j=0;j<len;j++) {
2998
            c = buf[i+j];
2999
            if (c < ' ' || c > '~')
3000
                c = '.';
3001
            fprintf(f, "%c", c);
3002
        }
3003
        fprintf(f, "\n");
3004
    }
3005
}
3006

    
3007
static int parse_macaddr(uint8_t *macaddr, const char *p)
3008
{
3009
    int i;
3010
    for(i = 0; i < 6; i++) {
3011
        macaddr[i] = strtol(p, (char **)&p, 16);
3012
        if (i == 5) {
3013
            if (*p != '\0') 
3014
                return -1;
3015
        } else {
3016
            if (*p != ':') 
3017
                return -1;
3018
            p++;
3019
        }
3020
    }
3021
    return 0;
3022
}
3023

    
3024
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3025
{
3026
    const char *p, *p1;
3027
    int len;
3028
    p = *pp;
3029
    p1 = strchr(p, sep);
3030
    if (!p1)
3031
        return -1;
3032
    len = p1 - p;
3033
    p1++;
3034
    if (buf_size > 0) {
3035
        if (len > buf_size - 1)
3036
            len = buf_size - 1;
3037
        memcpy(buf, p, len);
3038
        buf[len] = '\0';
3039
    }
3040
    *pp = p1;
3041
    return 0;
3042
}
3043

    
3044
int parse_host_src_port(struct sockaddr_in *haddr,
3045
                        struct sockaddr_in *saddr,
3046
                        const char *input_str)
3047
{
3048
    char *str = strdup(input_str);
3049
    char *host_str = str;
3050
    char *src_str;
3051
    char *ptr;
3052

    
3053
    /*
3054
     * Chop off any extra arguments at the end of the string which
3055
     * would start with a comma, then fill in the src port information
3056
     * if it was provided else use the "any address" and "any port".
3057
     */
3058
    if ((ptr = strchr(str,',')))
3059
        *ptr = '\0';
3060

    
3061
    if ((src_str = strchr(input_str,'@'))) {
3062
        *src_str = '\0';
3063
        src_str++;
3064
    }
3065

    
3066
    if (parse_host_port(haddr, host_str) < 0)
3067
        goto fail;
3068

    
3069
    if (!src_str || *src_str == '\0')
3070
        src_str = ":0";
3071

    
3072
    if (parse_host_port(saddr, src_str) < 0)
3073
        goto fail;
3074

    
3075
    free(str);
3076
    return(0);
3077

    
3078
fail:
3079
    free(str);
3080
    return -1;
3081
}
3082

    
3083
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3084
{
3085
    char buf[512];
3086
    struct hostent *he;
3087
    const char *p, *r;
3088
    int port;
3089

    
3090
    p = str;
3091
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3092
        return -1;
3093
    saddr->sin_family = AF_INET;
3094
    if (buf[0] == '\0') {
3095
        saddr->sin_addr.s_addr = 0;
3096
    } else {
3097
        if (isdigit(buf[0])) {
3098
            if (!inet_aton(buf, &saddr->sin_addr))
3099
                return -1;
3100
        } else {
3101
            if ((he = gethostbyname(buf)) == NULL)
3102
                return - 1;
3103
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3104
        }
3105
    }
3106
    port = strtol(p, (char **)&r, 0);
3107
    if (r == p)
3108
        return -1;
3109
    saddr->sin_port = htons(port);
3110
    return 0;
3111
}
3112

    
3113
#ifndef _WIN32
3114
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3115
{
3116
    const char *p;
3117
    int len;
3118

    
3119
    len = MIN(108, strlen(str));
3120
    p = strchr(str, ',');
3121
    if (p)
3122
        len = MIN(len, p - str);
3123

    
3124
    memset(uaddr, 0, sizeof(*uaddr));
3125

    
3126
    uaddr->sun_family = AF_UNIX;
3127
    memcpy(uaddr->sun_path, str, len);
3128

    
3129
    return 0;
3130
}
3131
#endif
3132

    
3133
/* find or alloc a new VLAN */
3134
VLANState *qemu_find_vlan(int id)
3135
{
3136
    VLANState **pvlan, *vlan;
3137
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3138
        if (vlan->id == id)
3139
            return vlan;
3140
    }
3141
    vlan = qemu_mallocz(sizeof(VLANState));
3142
    if (!vlan)
3143
        return NULL;
3144
    vlan->id = id;
3145
    vlan->next = NULL;
3146
    pvlan = &first_vlan;
3147
    while (*pvlan != NULL)
3148
        pvlan = &(*pvlan)->next;
3149
    *pvlan = vlan;
3150
    return vlan;
3151
}
3152

    
3153
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3154
                                      IOReadHandler *fd_read,
3155
                                      IOCanRWHandler *fd_can_read,
3156
                                      void *opaque)
3157
{
3158
    VLANClientState *vc, **pvc;
3159
    vc = qemu_mallocz(sizeof(VLANClientState));
3160
    if (!vc)
3161
        return NULL;
3162
    vc->fd_read = fd_read;
3163
    vc->fd_can_read = fd_can_read;
3164
    vc->opaque = opaque;
3165
    vc->vlan = vlan;
3166

    
3167
    vc->next = NULL;
3168
    pvc = &vlan->first_client;
3169
    while (*pvc != NULL)
3170
        pvc = &(*pvc)->next;
3171
    *pvc = vc;
3172
    return vc;
3173
}
3174

    
3175
int qemu_can_send_packet(VLANClientState *vc1)
3176
{
3177
    VLANState *vlan = vc1->vlan;
3178
    VLANClientState *vc;
3179

    
3180
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3181
        if (vc != vc1) {
3182
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3183
                return 0;
3184
        }
3185
    }
3186
    return 1;
3187
}
3188

    
3189
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3190
{
3191
    VLANState *vlan = vc1->vlan;
3192
    VLANClientState *vc;
3193

    
3194
#if 0
3195
    printf("vlan %d send:\n", vlan->id);
3196
    hex_dump(stdout, buf, size);
3197
#endif
3198
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3199
        if (vc != vc1) {
3200
            vc->fd_read(vc->opaque, buf, size);
3201
        }
3202
    }
3203
}
3204

    
3205
#if defined(CONFIG_SLIRP)
3206

    
3207
/* slirp network adapter */
3208

    
3209
static int slirp_inited;
3210
static VLANClientState *slirp_vc;
3211

    
3212
int slirp_can_output(void)
3213
{
3214
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3215
}
3216

    
3217
void slirp_output(const uint8_t *pkt, int pkt_len)
3218
{
3219
#if 0
3220
    printf("slirp output:\n");
3221
    hex_dump(stdout, pkt, pkt_len);
3222
#endif
3223
    if (!slirp_vc)
3224
        return;
3225
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3226
}
3227

    
3228
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3229
{
3230
#if 0
3231
    printf("slirp input:\n");
3232
    hex_dump(stdout, buf, size);
3233
#endif
3234
    slirp_input(buf, size);
3235
}
3236

    
3237
static int net_slirp_init(VLANState *vlan)
3238
{
3239
    if (!slirp_inited) {
3240
        slirp_inited = 1;
3241
        slirp_init();
3242
    }
3243
    slirp_vc = qemu_new_vlan_client(vlan, 
3244
                                    slirp_receive, NULL, NULL);
3245
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3246
    return 0;
3247
}
3248

    
3249
static void net_slirp_redir(const char *redir_str)
3250
{
3251
    int is_udp;
3252
    char buf[256], *r;
3253
    const char *p;
3254
    struct in_addr guest_addr;
3255
    int host_port, guest_port;
3256
    
3257
    if (!slirp_inited) {
3258
        slirp_inited = 1;
3259
        slirp_init();
3260
    }
3261

    
3262
    p = redir_str;
3263
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3264
        goto fail;
3265
    if (!strcmp(buf, "tcp")) {
3266
        is_udp = 0;
3267
    } else if (!strcmp(buf, "udp")) {
3268
        is_udp = 1;
3269
    } else {
3270
        goto fail;
3271
    }
3272

    
3273
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3274
        goto fail;
3275
    host_port = strtol(buf, &r, 0);
3276
    if (r == buf)
3277
        goto fail;
3278

    
3279
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3280
        goto fail;
3281
    if (buf[0] == '\0') {
3282
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3283
    }
3284
    if (!inet_aton(buf, &guest_addr))
3285
        goto fail;
3286
    
3287
    guest_port = strtol(p, &r, 0);
3288
    if (r == p)
3289
        goto fail;
3290
    
3291
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3292
        fprintf(stderr, "qemu: could not set up redirection\n");
3293
        exit(1);
3294
    }
3295
    return;
3296
 fail:
3297
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3298
    exit(1);
3299
}
3300
    
3301
#ifndef _WIN32
3302

    
3303
char smb_dir[1024];
3304

    
3305
static void smb_exit(void)
3306
{
3307
    DIR *d;
3308
    struct dirent *de;
3309
    char filename[1024];
3310

    
3311
    /* erase all the files in the directory */
3312
    d = opendir(smb_dir);
3313
    for(;;) {
3314
        de = readdir(d);
3315
        if (!de)
3316
            break;
3317
        if (strcmp(de->d_name, ".") != 0 &&
3318
            strcmp(de->d_name, "..") != 0) {
3319
            snprintf(filename, sizeof(filename), "%s/%s", 
3320
                     smb_dir, de->d_name);
3321
            unlink(filename);
3322
        }
3323
    }
3324
    closedir(d);
3325
    rmdir(smb_dir);
3326
}
3327

    
3328
/* automatic user mode samba server configuration */
3329
void net_slirp_smb(const char *exported_dir)
3330
{
3331
    char smb_conf[1024];
3332
    char smb_cmdline[1024];
3333
    FILE *f;
3334

    
3335
    if (!slirp_inited) {
3336
        slirp_inited = 1;
3337
        slirp_init();
3338
    }
3339

    
3340
    /* XXX: better tmp dir construction */
3341
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3342
    if (mkdir(smb_dir, 0700) < 0) {
3343
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3344
        exit(1);
3345
    }
3346
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3347
    
3348
    f = fopen(smb_conf, "w");
3349
    if (!f) {
3350
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3351
        exit(1);
3352
    }
3353
    fprintf(f, 
3354
            "[global]\n"
3355
            "private dir=%s\n"
3356
            "smb ports=0\n"
3357
            "socket address=127.0.0.1\n"
3358
            "pid directory=%s\n"
3359
            "lock directory=%s\n"
3360
            "log file=%s/log.smbd\n"
3361
            "smb passwd file=%s/smbpasswd\n"
3362
            "security = share\n"
3363
            "[qemu]\n"
3364
            "path=%s\n"
3365
            "read only=no\n"
3366
            "guest ok=yes\n",
3367
            smb_dir,
3368
            smb_dir,
3369
            smb_dir,
3370
            smb_dir,
3371
            smb_dir,
3372
            exported_dir
3373
            );
3374
    fclose(f);
3375
    atexit(smb_exit);
3376

    
3377
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3378
             SMBD_COMMAND, smb_conf);
3379
    
3380
    slirp_add_exec(0, smb_cmdline, 4, 139);
3381
}
3382

    
3383
#endif /* !defined(_WIN32) */
3384

    
3385
#endif /* CONFIG_SLIRP */
3386

    
3387
#if !defined(_WIN32)
3388

    
3389
typedef struct TAPState {
3390
    VLANClientState *vc;
3391
    int fd;
3392
} TAPState;
3393

    
3394
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3395
{
3396
    TAPState *s = opaque;
3397
    int ret;
3398
    for(;;) {
3399
        ret = write(s->fd, buf, size);
3400
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3401
        } else {
3402
            break;
3403
        }
3404
    }
3405
}
3406

    
3407
static void tap_send(void *opaque)
3408
{
3409
    TAPState *s = opaque;
3410
    uint8_t buf[4096];
3411
    int size;
3412

    
3413
#ifdef __sun__
3414
    struct strbuf sbuf;
3415
    int f = 0;
3416
    sbuf.maxlen = sizeof(buf);
3417
    sbuf.buf = buf;
3418
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3419
#else
3420
    size = read(s->fd, buf, sizeof(buf));
3421
#endif
3422
    if (size > 0) {
3423
        qemu_send_packet(s->vc, buf, size);
3424
    }
3425
}
3426

    
3427
/* fd support */
3428

    
3429
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3430
{
3431
    TAPState *s;
3432

    
3433
    s = qemu_mallocz(sizeof(TAPState));
3434
    if (!s)
3435
        return NULL;
3436
    s->fd = fd;
3437
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3438
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3439
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3440
    return s;
3441
}
3442

    
3443
#ifdef _BSD
3444
static int tap_open(char *ifname, int ifname_size)
3445
{
3446
    int fd;
3447
    char *dev;
3448
    struct stat s;
3449

    
3450
    fd = open("/dev/tap", O_RDWR);
3451
    if (fd < 0) {
3452
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3453
        return -1;
3454
    }
3455

    
3456
    fstat(fd, &s);
3457
    dev = devname(s.st_rdev, S_IFCHR);
3458
    pstrcpy(ifname, ifname_size, dev);
3459

    
3460
    fcntl(fd, F_SETFL, O_NONBLOCK);
3461
    return fd;
3462
}
3463
#elif defined(__sun__)
3464
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3465
/* 
3466
 * Allocate TAP device, returns opened fd. 
3467
 * Stores dev name in the first arg(must be large enough).
3468
 */  
3469
int tap_alloc(char *dev)
3470
{
3471
    int tap_fd, if_fd, ppa = -1;
3472
    static int ip_fd = 0;
3473
    char *ptr;
3474

    
3475
    static int arp_fd = 0;
3476
    int ip_muxid, arp_muxid;
3477
    struct strioctl  strioc_if, strioc_ppa;
3478
    int link_type = I_PLINK;;
3479
    struct lifreq ifr;
3480
    char actual_name[32] = "";
3481

    
3482
    memset(&ifr, 0x0, sizeof(ifr));
3483

    
3484
    if( *dev ){
3485
       ptr = dev;        
3486
       while( *ptr && !isdigit((int)*ptr) ) ptr++; 
3487
       ppa = atoi(ptr);
3488
    }
3489

    
3490
    /* Check if IP device was opened */
3491
    if( ip_fd )
3492
       close(ip_fd);
3493

    
3494
    if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3495
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3496
       return -1;
3497
    }
3498

    
3499
    if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3500
       syslog(LOG_ERR, "Can't open /dev/tap");
3501
       return -1;
3502
    }
3503

    
3504
    /* Assign a new PPA and get its unit number. */
3505
    strioc_ppa.ic_cmd = TUNNEWPPA;
3506
    strioc_ppa.ic_timout = 0;
3507
    strioc_ppa.ic_len = sizeof(ppa);
3508
    strioc_ppa.ic_dp = (char *)&ppa;
3509
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3510
       syslog (LOG_ERR, "Can't assign new interface");
3511

    
3512
    if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3513
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3514
       return -1;
3515
    }
3516
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3517
       syslog(LOG_ERR, "Can't push IP module");
3518
       return -1;
3519
    }
3520

    
3521
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3522
        syslog(LOG_ERR, "Can't get flags\n");
3523

    
3524
    snprintf (actual_name, 32, "tap%d", ppa);
3525
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3526

    
3527
    ifr.lifr_ppa = ppa;
3528
    /* Assign ppa according to the unit number returned by tun device */
3529

    
3530
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3531
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
3532
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3533
        syslog (LOG_ERR, "Can't get flags\n");
3534
    /* Push arp module to if_fd */
3535
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
3536
        syslog (LOG_ERR, "Can't push ARP module (2)");
3537

    
3538
    /* Push arp module to ip_fd */
3539
    if (ioctl (ip_fd, I_POP, NULL) < 0)
3540
        syslog (LOG_ERR, "I_POP failed\n");
3541
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3542
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
3543
    /* Open arp_fd */
3544
    if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3545
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3546

    
3547
    /* Set ifname to arp */
3548
    strioc_if.ic_cmd = SIOCSLIFNAME;
3549
    strioc_if.ic_timout = 0;
3550
    strioc_if.ic_len = sizeof(ifr);
3551
    strioc_if.ic_dp = (char *)&ifr;
3552
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3553
        syslog (LOG_ERR, "Can't set ifname to arp\n");
3554
    }
3555

    
3556
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3557
       syslog(LOG_ERR, "Can't link TAP device to IP");
3558
       return -1;
3559
    }
3560

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

    
3564
    close (if_fd);
3565

    
3566
    memset(&ifr, 0x0, sizeof(ifr));
3567
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3568
    ifr.lifr_ip_muxid  = ip_muxid;
3569
    ifr.lifr_arp_muxid = arp_muxid;
3570

    
3571
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3572
    {
3573
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
3574
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
3575
      syslog (LOG_ERR, "Can't set multiplexor id");
3576
    }
3577

    
3578
    sprintf(dev, "tap%d", ppa);
3579
    return tap_fd;
3580
}
3581

    
3582
static int tap_open(char *ifname, int ifname_size)
3583
{
3584
    char  dev[10]="";
3585
    int fd;
3586
    if( (fd = tap_alloc(dev)) < 0 ){
3587
       fprintf(stderr, "Cannot allocate TAP device\n");
3588
       return -1;
3589
    }
3590
    pstrcpy(ifname, ifname_size, dev);
3591
    fcntl(fd, F_SETFL, O_NONBLOCK);
3592
    return fd;
3593
}
3594
#else
3595
static int tap_open(char *ifname, int ifname_size)
3596
{
3597
    struct ifreq ifr;
3598
    int fd, ret;
3599
    
3600
    fd = open("/dev/net/tun", O_RDWR);
3601
    if (fd < 0) {
3602
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3603
        return -1;
3604
    }
3605
    memset(&ifr, 0, sizeof(ifr));
3606
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3607
    if (ifname[0] != '\0')
3608
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3609
    else
3610
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3611
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3612
    if (ret != 0) {
3613
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3614
        close(fd);
3615
        return -1;
3616
    }
3617
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3618
    fcntl(fd, F_SETFL, O_NONBLOCK);
3619
    return fd;
3620
}
3621
#endif
3622

    
3623
static int net_tap_init(VLANState *vlan, const char *ifname1,
3624
                        const char *setup_script)
3625
{
3626
    TAPState *s;
3627
    int pid, status, fd;
3628
    char *args[3];
3629
    char **parg;
3630
    char ifname[128];
3631

    
3632
    if (ifname1 != NULL)
3633
        pstrcpy(ifname, sizeof(ifname), ifname1);
3634
    else
3635
        ifname[0] = '\0';
3636
    fd = tap_open(ifname, sizeof(ifname));
3637
    if (fd < 0)
3638
        return -1;
3639

    
3640
    if (!setup_script || !strcmp(setup_script, "no"))
3641
        setup_script = "";
3642
    if (setup_script[0] != '\0') {
3643
        /* try to launch network init script */
3644
        pid = fork();
3645
        if (pid >= 0) {
3646
            if (pid == 0) {
3647
                int open_max = sysconf (_SC_OPEN_MAX), i;
3648
                for (i = 0; i < open_max; i++)
3649
                    if (i != STDIN_FILENO &&
3650
                        i != STDOUT_FILENO &&
3651
                        i != STDERR_FILENO &&
3652
                        i != fd)
3653
                        close(i);
3654

    
3655
                parg = args;
3656
                *parg++ = (char *)setup_script;
3657
                *parg++ = ifname;
3658
                *parg++ = NULL;
3659
                execv(setup_script, args);
3660
                _exit(1);
3661
            }
3662
            while (waitpid(pid, &status, 0) != pid);
3663
            if (!WIFEXITED(status) ||
3664
                WEXITSTATUS(status) != 0) {
3665
                fprintf(stderr, "%s: could not launch network script\n",
3666
                        setup_script);
3667
                return -1;
3668
            }
3669
        }
3670
    }
3671
    s = net_tap_fd_init(vlan, fd);
3672
    if (!s)
3673
        return -1;
3674
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3675
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3676
    return 0;
3677
}
3678

    
3679
#endif /* !_WIN32 */
3680

    
3681
/* network connection */
3682
typedef struct NetSocketState {
3683
    VLANClientState *vc;
3684
    int fd;
3685
    int state; /* 0 = getting length, 1 = getting data */
3686
    int index;
3687
    int packet_len;
3688
    uint8_t buf[4096];
3689
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3690
} NetSocketState;
3691

    
3692
typedef struct NetSocketListenState {
3693
    VLANState *vlan;
3694
    int fd;
3695
} NetSocketListenState;
3696

    
3697
/* XXX: we consider we can send the whole packet without blocking */
3698
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3699
{
3700
    NetSocketState *s = opaque;
3701
    uint32_t len;
3702
    len = htonl(size);
3703

    
3704
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3705
    send_all(s->fd, buf, size);
3706
}
3707

    
3708
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3709
{
3710
    NetSocketState *s = opaque;
3711
    sendto(s->fd, buf, size, 0, 
3712
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3713
}
3714

    
3715
static void net_socket_send(void *opaque)
3716
{
3717
    NetSocketState *s = opaque;
3718
    int l, size, err;
3719
    uint8_t buf1[4096];
3720
    const uint8_t *buf;
3721

    
3722
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3723
    if (size < 0) {
3724
        err = socket_error();
3725
        if (err != EWOULDBLOCK) 
3726
            goto eoc;
3727
    } else if (size == 0) {
3728
        /* end of connection */
3729
    eoc:
3730
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3731
        closesocket(s->fd);
3732
        return;
3733
    }
3734
    buf = buf1;
3735
    while (size > 0) {
3736
        /* reassemble a packet from the network */
3737
        switch(s->state) {
3738
        case 0:
3739
            l = 4 - s->index;
3740
            if (l > size)
3741
                l = size;
3742
            memcpy(s->buf + s->index, buf, l);
3743
            buf += l;
3744
            size -= l;
3745
            s->index += l;
3746
            if (s->index == 4) {
3747
                /* got length */
3748
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3749
                s->index = 0;
3750
                s->state = 1;
3751
            }
3752
            break;
3753
        case 1:
3754
            l = s->packet_len - s->index;
3755
            if (l > size)
3756
                l = size;
3757
            memcpy(s->buf + s->index, buf, l);
3758
            s->index += l;
3759
            buf += l;
3760
            size -= l;
3761
            if (s->index >= s->packet_len) {
3762
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3763
                s->index = 0;
3764
                s->state = 0;
3765
            }
3766
            break;
3767
        }
3768
    }
3769
}
3770

    
3771
static void net_socket_send_dgram(void *opaque)
3772
{
3773
    NetSocketState *s = opaque;
3774
    int size;
3775

    
3776
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3777
    if (size < 0) 
3778
        return;
3779
    if (size == 0) {
3780
        /* end of connection */
3781
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3782
        return;
3783
    }
3784
    qemu_send_packet(s->vc, s->buf, size);
3785
}
3786

    
3787
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3788
{
3789
    struct ip_mreq imr;
3790
    int fd;
3791
    int val, ret;
3792
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3793
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3794
                inet_ntoa(mcastaddr->sin_addr), 
3795
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3796
        return -1;
3797

    
3798
    }
3799
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3800
    if (fd < 0) {
3801
        perror("socket(PF_INET, SOCK_DGRAM)");
3802
        return -1;
3803
    }
3804

    
3805
    val = 1;
3806
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3807
                   (const char *)&val, sizeof(val));
3808
    if (ret < 0) {
3809
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3810
        goto fail;
3811
    }
3812

    
3813
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3814
    if (ret < 0) {
3815
        perror("bind");
3816
        goto fail;
3817
    }
3818
    
3819
    /* Add host to multicast group */
3820
    imr.imr_multiaddr = mcastaddr->sin_addr;
3821
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3822

    
3823
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3824
                     (const char *)&imr, sizeof(struct ip_mreq));
3825
    if (ret < 0) {
3826
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3827
        goto fail;
3828
    }
3829

    
3830
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3831
    val = 1;
3832
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3833
                   (const char *)&val, sizeof(val));
3834
    if (ret < 0) {
3835
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3836
        goto fail;
3837
    }
3838

    
3839
    socket_set_nonblock(fd);
3840
    return fd;
3841
fail:
3842
    if (fd >= 0) 
3843
        closesocket(fd);
3844
    return -1;
3845
}
3846

    
3847
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3848
                                          int is_connected)
3849
{
3850
    struct sockaddr_in saddr;
3851
    int newfd;
3852
    socklen_t saddr_len;
3853
    NetSocketState *s;
3854

    
3855
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3856
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3857
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3858
     */
3859

    
3860
    if (is_connected) {
3861
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3862
            /* must be bound */
3863
            if (saddr.sin_addr.s_addr==0) {
3864
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3865
                        fd);
3866
                return NULL;
3867
            }
3868
            /* clone dgram socket */
3869
            newfd = net_socket_mcast_create(&saddr);
3870
            if (newfd < 0) {
3871
                /* error already reported by net_socket_mcast_create() */
3872
                close(fd);
3873
                return NULL;
3874
            }
3875
            /* clone newfd to fd, close newfd */
3876
            dup2(newfd, fd);
3877
            close(newfd);
3878
        
3879
        } else {
3880
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3881
                    fd, strerror(errno));
3882
            return NULL;
3883
        }
3884
    }
3885

    
3886
    s = qemu_mallocz(sizeof(NetSocketState));
3887
    if (!s)
3888
        return NULL;
3889
    s->fd = fd;
3890

    
3891
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3892
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3893

    
3894
    /* mcast: save bound address as dst */
3895
    if (is_connected) s->dgram_dst=saddr;
3896

    
3897
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3898
            "socket: fd=%d (%s mcast=%s:%d)", 
3899
            fd, is_connected? "cloned" : "",
3900
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3901
    return s;
3902
}
3903

    
3904
static void net_socket_connect(void *opaque)
3905
{
3906
    NetSocketState *s = opaque;
3907
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3908
}
3909

    
3910
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3911
                                          int is_connected)
3912
{
3913
    NetSocketState *s;
3914
    s = qemu_mallocz(sizeof(NetSocketState));
3915
    if (!s)
3916
        return NULL;
3917
    s->fd = fd;
3918
    s->vc = qemu_new_vlan_client(vlan, 
3919
                                 net_socket_receive, NULL, s);
3920
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3921
             "socket: fd=%d", fd);
3922
    if (is_connected) {
3923
        net_socket_connect(s);
3924
    } else {
3925
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3926
    }
3927
    return s;
3928
}
3929

    
3930
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3931
                                          int is_connected)
3932
{
3933
    int so_type=-1, optlen=sizeof(so_type);
3934

    
3935
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3936
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3937
        return NULL;
3938
    }
3939
    switch(so_type) {
3940
    case SOCK_DGRAM:
3941
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3942
    case SOCK_STREAM:
3943
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3944
    default:
3945
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3946
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3947
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3948
    }
3949
    return NULL;
3950
}
3951

    
3952
static void net_socket_accept(void *opaque)
3953
{
3954
    NetSocketListenState *s = opaque;    
3955
    NetSocketState *s1;
3956
    struct sockaddr_in saddr;
3957
    socklen_t len;
3958
    int fd;
3959

    
3960
    for(;;) {
3961
        len = sizeof(saddr);
3962
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3963
        if (fd < 0 && errno != EINTR) {
3964
            return;
3965
        } else if (fd >= 0) {
3966
            break;
3967
        }
3968
    }
3969
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3970
    if (!s1) {
3971
        closesocket(fd);
3972
    } else {
3973
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3974
                 "socket: connection from %s:%d", 
3975
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3976
    }
3977
}
3978

    
3979
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3980
{
3981
    NetSocketListenState *s;
3982
    int fd, val, ret;
3983
    struct sockaddr_in saddr;
3984

    
3985
    if (parse_host_port(&saddr, host_str) < 0)
3986
        return -1;
3987
    
3988
    s = qemu_mallocz(sizeof(NetSocketListenState));
3989
    if (!s)
3990
        return -1;
3991

    
3992
    fd = socket(PF_INET, SOCK_STREAM, 0);
3993
    if (fd < 0) {
3994
        perror("socket");
3995
        return -1;
3996
    }
3997
    socket_set_nonblock(fd);
3998

    
3999
    /* allow fast reuse */
4000
    val = 1;
4001
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4002
    
4003
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4004
    if (ret < 0) {
4005
        perror("bind");
4006
        return -1;
4007
    }
4008
    ret = listen(fd, 0);
4009
    if (ret < 0) {
4010
        perror("listen");
4011
        return -1;
4012
    }
4013
    s->vlan = vlan;
4014
    s->fd = fd;
4015
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4016
    return 0;
4017
}
4018

    
4019
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4020
{
4021
    NetSocketState *s;
4022
    int fd, connected, ret, err;
4023
    struct sockaddr_in saddr;
4024

    
4025
    if (parse_host_port(&saddr, host_str) < 0)
4026
        return -1;
4027

    
4028
    fd = socket(PF_INET, SOCK_STREAM, 0);
4029
    if (fd < 0) {
4030
        perror("socket");
4031
        return -1;
4032
    }
4033
    socket_set_nonblock(fd);
4034

    
4035
    connected = 0;
4036
    for(;;) {
4037
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4038
        if (ret < 0) {
4039
            err = socket_error();
4040
            if (err == EINTR || err == EWOULDBLOCK) {
4041
            } else if (err == EINPROGRESS) {
4042
                break;
4043
#ifdef _WIN32
4044
            } else if (err == WSAEALREADY) {
4045
                break;
4046
#endif
4047
            } else {
4048
                perror("connect");
4049
                closesocket(fd);
4050
                return -1;
4051
            }
4052
        } else {
4053
            connected = 1;
4054
            break;
4055
        }
4056
    }
4057
    s = net_socket_fd_init(vlan, fd, connected);
4058
    if (!s)
4059
        return -1;
4060
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4061
             "socket: connect to %s:%d", 
4062
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4063
    return 0;
4064
}
4065

    
4066
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4067
{
4068
    NetSocketState *s;
4069
    int fd;
4070
    struct sockaddr_in saddr;
4071

    
4072
    if (parse_host_port(&saddr, host_str) < 0)
4073
        return -1;
4074

    
4075

    
4076
    fd = net_socket_mcast_create(&saddr);
4077
    if (fd < 0)
4078
        return -1;
4079

    
4080
    s = net_socket_fd_init(vlan, fd, 0);
4081
    if (!s)
4082
        return -1;
4083

    
4084
    s->dgram_dst = saddr;
4085
    
4086
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4087
             "socket: mcast=%s:%d", 
4088
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4089
    return 0;
4090

    
4091
}
4092

    
4093
static int get_param_value(char *buf, int buf_size,
4094
                           const char *tag, const char *str)
4095
{
4096
    const char *p;
4097
    char *q;
4098
    char option[128];
4099

    
4100
    p = str;
4101
    for(;;) {
4102
        q = option;
4103
        while (*p != '\0' && *p != '=') {
4104
            if ((q - option) < sizeof(option) - 1)
4105
                *q++ = *p;
4106
            p++;
4107
        }
4108
        *q = '\0';
4109
        if (*p != '=')
4110
            break;
4111
        p++;
4112
        if (!strcmp(tag, option)) {
4113
            q = buf;
4114
            while (*p != '\0' && *p != ',') {
4115
                if ((q - buf) < buf_size - 1)
4116
                    *q++ = *p;
4117
                p++;
4118
            }
4119
            *q = '\0';
4120
            return q - buf;
4121
        } else {
4122
            while (*p != '\0' && *p != ',') {
4123
                p++;
4124
            }
4125
        }
4126
        if (*p != ',')
4127
            break;
4128
        p++;
4129
    }
4130
    return 0;
4131
}
4132

    
4133
static int net_client_init(const char *str)
4134
{
4135
    const char *p;
4136
    char *q;
4137
    char device[64];
4138
    char buf[1024];
4139
    int vlan_id, ret;
4140
    VLANState *vlan;
4141

    
4142
    p = str;
4143
    q = device;
4144
    while (*p != '\0' && *p != ',') {
4145
        if ((q - device) < sizeof(device) - 1)
4146
            *q++ = *p;
4147
        p++;
4148
    }
4149
    *q = '\0';
4150
    if (*p == ',')
4151
        p++;
4152
    vlan_id = 0;
4153
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4154
        vlan_id = strtol(buf, NULL, 0);
4155
    }
4156
    vlan = qemu_find_vlan(vlan_id);
4157
    if (!vlan) {
4158
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4159
        return -1;
4160
    }
4161
    if (!strcmp(device, "nic")) {
4162
        NICInfo *nd;
4163
        uint8_t *macaddr;
4164

    
4165
        if (nb_nics >= MAX_NICS) {
4166
            fprintf(stderr, "Too Many NICs\n");
4167
            return -1;
4168
        }
4169
        nd = &nd_table[nb_nics];
4170
        macaddr = nd->macaddr;
4171
        macaddr[0] = 0x52;
4172
        macaddr[1] = 0x54;
4173
        macaddr[2] = 0x00;
4174
        macaddr[3] = 0x12;
4175
        macaddr[4] = 0x34;
4176
        macaddr[5] = 0x56 + nb_nics;
4177

    
4178
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4179
            if (parse_macaddr(macaddr, buf) < 0) {
4180
                fprintf(stderr, "invalid syntax for ethernet address\n");
4181
                return -1;
4182
            }
4183
        }
4184
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4185
            nd->model = strdup(buf);
4186
        }
4187
        nd->vlan = vlan;
4188
        nb_nics++;
4189
        ret = 0;
4190
    } else
4191
    if (!strcmp(device, "none")) {
4192
        /* does nothing. It is needed to signal that no network cards
4193
           are wanted */
4194
        ret = 0;
4195
    } else
4196
#ifdef CONFIG_SLIRP
4197
    if (!strcmp(device, "user")) {
4198
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4199
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4200
        }
4201
        ret = net_slirp_init(vlan);
4202
    } else
4203
#endif
4204
#ifdef _WIN32
4205
    if (!strcmp(device, "tap")) {
4206
        char ifname[64];
4207
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4208
            fprintf(stderr, "tap: no interface name\n");
4209
            return -1;
4210
        }
4211
        ret = tap_win32_init(vlan, ifname);
4212
    } else
4213
#else
4214
    if (!strcmp(device, "tap")) {
4215
        char ifname[64];
4216
        char setup_script[1024];
4217
        int fd;
4218
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4219
            fd = strtol(buf, NULL, 0);
4220
            ret = -1;
4221
            if (net_tap_fd_init(vlan, fd))
4222
                ret = 0;
4223
        } else {
4224
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4225
                ifname[0] = '\0';
4226
            }
4227
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4228
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4229
            }
4230
            ret = net_tap_init(vlan, ifname, setup_script);
4231
        }
4232
    } else
4233
#endif
4234
    if (!strcmp(device, "socket")) {
4235
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4236
            int fd;
4237
            fd = strtol(buf, NULL, 0);
4238
            ret = -1;
4239
            if (net_socket_fd_init(vlan, fd, 1))
4240
                ret = 0;
4241
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4242
            ret = net_socket_listen_init(vlan, buf);
4243
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4244
            ret = net_socket_connect_init(vlan, buf);
4245
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4246
            ret = net_socket_mcast_init(vlan, buf);
4247
        } else {
4248
            fprintf(stderr, "Unknown socket options: %s\n", p);
4249
            return -1;
4250
        }
4251
    } else
4252
    {
4253
        fprintf(stderr, "Unknown network device: %s\n", device);
4254
        return -1;
4255
    }
4256
    if (ret < 0) {
4257
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4258
    }
4259
    
4260
    return ret;
4261
}
4262

    
4263
void do_info_network(void)
4264
{
4265
    VLANState *vlan;
4266
    VLANClientState *vc;
4267

    
4268
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4269
        term_printf("VLAN %d devices:\n", vlan->id);
4270
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4271
            term_printf("  %s\n", vc->info_str);
4272
    }
4273
}
4274

    
4275
/***********************************************************/
4276
/* USB devices */
4277

    
4278
static USBPort *used_usb_ports;
4279
static USBPort *free_usb_ports;
4280

    
4281
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4282
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4283
                            usb_attachfn attach)
4284
{
4285
    port->opaque = opaque;
4286
    port->index = index;
4287
    port->attach = attach;
4288
    port->next = free_usb_ports;
4289
    free_usb_ports = port;
4290
}
4291

    
4292
static int usb_device_add(const char *devname)
4293
{
4294
    const char *p;
4295
    USBDevice *dev;
4296
    USBPort *port;
4297

    
4298
    if (!free_usb_ports)
4299
        return -1;
4300

    
4301
    if (strstart(devname, "host:", &p)) {
4302
        dev = usb_host_device_open(p);
4303
    } else if (!strcmp(devname, "mouse")) {
4304
        dev = usb_mouse_init();
4305
    } else if (!strcmp(devname, "tablet")) {
4306
        dev = usb_tablet_init();
4307
    } else if (strstart(devname, "disk:", &p)) {
4308
        dev = usb_msd_init(p);
4309
    } else {
4310
        return -1;
4311
    }
4312
    if (!dev)
4313
        return -1;
4314

    
4315
    /* Find a USB port to add the device to.  */
4316
    port = free_usb_ports;
4317
    if (!port->next) {
4318
        USBDevice *hub;
4319

    
4320
        /* Create a new hub and chain it on.  */
4321
        free_usb_ports = NULL;
4322
        port->next = used_usb_ports;
4323
        used_usb_ports = port;
4324

    
4325
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4326
        usb_attach(port, hub);
4327
        port = free_usb_ports;
4328
    }
4329

    
4330
    free_usb_ports = port->next;
4331
    port->next = used_usb_ports;
4332
    used_usb_ports = port;
4333
    usb_attach(port, dev);
4334
    return 0;
4335
}
4336

    
4337
static int usb_device_del(const char *devname)
4338
{
4339
    USBPort *port;
4340
    USBPort **lastp;
4341
    USBDevice *dev;
4342
    int bus_num, addr;
4343
    const char *p;
4344

    
4345
    if (!used_usb_ports)
4346
        return -1;
4347

    
4348
    p = strchr(devname, '.');
4349
    if (!p) 
4350
        return -1;
4351
    bus_num = strtoul(devname, NULL, 0);
4352
    addr = strtoul(p + 1, NULL, 0);
4353
    if (bus_num != 0)
4354
        return -1;
4355

    
4356
    lastp = &used_usb_ports;
4357
    port = used_usb_ports;
4358
    while (port && port->dev->addr != addr) {
4359
        lastp = &port->next;
4360
        port = port->next;
4361
    }
4362

    
4363
    if (!port)
4364
        return -1;
4365

    
4366
    dev = port->dev;
4367
    *lastp = port->next;
4368
    usb_attach(port, NULL);
4369
    dev->handle_destroy(dev);
4370
    port->next = free_usb_ports;
4371
    free_usb_ports = port;
4372
    return 0;
4373
}
4374

    
4375
void do_usb_add(const char *devname)
4376
{
4377
    int ret;
4378
    ret = usb_device_add(devname);
4379
    if (ret < 0) 
4380
        term_printf("Could not add USB device '%s'\n", devname);
4381
}
4382

    
4383
void do_usb_del(const char *devname)
4384
{
4385
    int ret;
4386
    ret = usb_device_del(devname);
4387
    if (ret < 0) 
4388
        term_printf("Could not remove USB device '%s'\n", devname);
4389
}
4390

    
4391
void usb_info(void)
4392
{
4393
    USBDevice *dev;
4394
    USBPort *port;
4395
    const char *speed_str;
4396

    
4397
    if (!usb_enabled) {
4398
        term_printf("USB support not enabled\n");
4399
        return;
4400
    }
4401

    
4402
    for (port = used_usb_ports; port; port = port->next) {
4403
        dev = port->dev;
4404
        if (!dev)
4405
            continue;
4406
        switch(dev->speed) {
4407
        case USB_SPEED_LOW: 
4408
            speed_str = "1.5"; 
4409
            break;
4410
        case USB_SPEED_FULL: 
4411
            speed_str = "12"; 
4412
            break;
4413
        case USB_SPEED_HIGH: 
4414
            speed_str = "480"; 
4415
            break;
4416
        default:
4417
            speed_str = "?"; 
4418
            break;
4419
        }
4420
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4421
                    0, dev->addr, speed_str, dev->devname);
4422
    }
4423
}
4424

    
4425
/***********************************************************/
4426
/* PCMCIA/Cardbus */
4427

    
4428
static struct pcmcia_socket_entry_s {
4429
    struct pcmcia_socket_s *socket;
4430
    struct pcmcia_socket_entry_s *next;
4431
} *pcmcia_sockets = 0;
4432

    
4433
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4434
{
4435
    struct pcmcia_socket_entry_s *entry;
4436

    
4437
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4438
    entry->socket = socket;
4439
    entry->next = pcmcia_sockets;
4440
    pcmcia_sockets = entry;
4441
}
4442

    
4443
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4444
{
4445
    struct pcmcia_socket_entry_s *entry, **ptr;
4446

    
4447
    ptr = &pcmcia_sockets;
4448
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4449
        if (entry->socket == socket) {
4450
            *ptr = entry->next;
4451
            qemu_free(entry);
4452
        }
4453
}
4454

    
4455
void pcmcia_info(void)
4456
{
4457
    struct pcmcia_socket_entry_s *iter;
4458
    if (!pcmcia_sockets)
4459
        term_printf("No PCMCIA sockets\n");
4460

    
4461
    for (iter = pcmcia_sockets; iter; iter = iter->next)
4462
        term_printf("%s: %s\n", iter->socket->slot_string,
4463
                    iter->socket->attached ? iter->socket->card_string :
4464
                    "Empty");
4465
}
4466

    
4467
/***********************************************************/
4468
/* dumb display */
4469

    
4470
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4471
{
4472
}
4473

    
4474
static void dumb_resize(DisplayState *ds, int w, int h)
4475
{
4476
}
4477

    
4478
static void dumb_refresh(DisplayState *ds)
4479
{
4480
    vga_hw_update();
4481
}
4482

    
4483
void dumb_display_init(DisplayState *ds)
4484
{
4485
    ds->data = NULL;
4486
    ds->linesize = 0;
4487
    ds->depth = 0;
4488
    ds->dpy_update = dumb_update;
4489
    ds->dpy_resize = dumb_resize;
4490
    ds->dpy_refresh = dumb_refresh;
4491
}
4492

    
4493
/***********************************************************/
4494
/* I/O handling */
4495

    
4496
#define MAX_IO_HANDLERS 64
4497

    
4498
typedef struct IOHandlerRecord {
4499
    int fd;
4500
    IOCanRWHandler *fd_read_poll;
4501
    IOHandler *fd_read;
4502
    IOHandler *fd_write;
4503
    int deleted;
4504
    void *opaque;
4505
    /* temporary data */
4506
    struct pollfd *ufd;
4507
    struct IOHandlerRecord *next;
4508
} IOHandlerRecord;
4509

    
4510
static IOHandlerRecord *first_io_handler;
4511

    
4512
/* XXX: fd_read_poll should be suppressed, but an API change is
4513
   necessary in the character devices to suppress fd_can_read(). */
4514
int qemu_set_fd_handler2(int fd, 
4515
                         IOCanRWHandler *fd_read_poll, 
4516
                         IOHandler *fd_read, 
4517
                         IOHandler *fd_write, 
4518
                         void *opaque)
4519
{
4520
    IOHandlerRecord **pioh, *ioh;
4521

    
4522
    if (!fd_read && !fd_write) {
4523
        pioh = &first_io_handler;
4524
        for(;;) {
4525
            ioh = *pioh;
4526
            if (ioh == NULL)
4527
                break;
4528
            if (ioh->fd == fd) {
4529
                ioh->deleted = 1;
4530
                break;
4531
            }
4532
            pioh = &ioh->next;
4533
        }
4534
    } else {
4535
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4536
            if (ioh->fd == fd)
4537
                goto found;
4538
        }
4539
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4540
        if (!ioh)
4541
            return -1;
4542
        ioh->next = first_io_handler;
4543
        first_io_handler = ioh;
4544
    found:
4545
        ioh->fd = fd;
4546
        ioh->fd_read_poll = fd_read_poll;
4547
        ioh->fd_read = fd_read;
4548
        ioh->fd_write = fd_write;
4549
        ioh->opaque = opaque;
4550
        ioh->deleted = 0;
4551
    }
4552
    return 0;
4553
}
4554

    
4555
int qemu_set_fd_handler(int fd, 
4556
                        IOHandler *fd_read, 
4557
                        IOHandler *fd_write, 
4558
                        void *opaque)
4559
{
4560
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4561
}
4562

    
4563
/***********************************************************/
4564
/* Polling handling */
4565

    
4566
typedef struct PollingEntry {
4567
    PollingFunc *func;
4568
    void *opaque;
4569
    struct PollingEntry *next;
4570
} PollingEntry;
4571

    
4572
static PollingEntry *first_polling_entry;
4573

    
4574
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4575
{
4576
    PollingEntry **ppe, *pe;
4577
    pe = qemu_mallocz(sizeof(PollingEntry));
4578
    if (!pe)
4579
        return -1;
4580
    pe->func = func;
4581
    pe->opaque = opaque;
4582
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4583
    *ppe = pe;
4584
    return 0;
4585
}
4586

    
4587
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4588
{
4589
    PollingEntry **ppe, *pe;
4590
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4591
        pe = *ppe;
4592
        if (pe->func == func && pe->opaque == opaque) {
4593
            *ppe = pe->next;
4594
            qemu_free(pe);
4595
            break;
4596
        }
4597
    }
4598
}
4599

    
4600
#ifdef _WIN32
4601
/***********************************************************/
4602
/* Wait objects support */
4603
typedef struct WaitObjects {
4604
    int num;
4605
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4606
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4607
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4608
} WaitObjects;
4609

    
4610
static WaitObjects wait_objects = {0};
4611
    
4612
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4613
{
4614
    WaitObjects *w = &wait_objects;
4615

    
4616
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4617
        return -1;
4618
    w->events[w->num] = handle;
4619
    w->func[w->num] = func;
4620
    w->opaque[w->num] = opaque;
4621
    w->num++;
4622
    return 0;
4623
}
4624

    
4625
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4626
{
4627
    int i, found;
4628
    WaitObjects *w = &wait_objects;
4629

    
4630
    found = 0;
4631
    for (i = 0; i < w->num; i++) {
4632
        if (w->events[i] == handle)
4633
            found = 1;
4634
        if (found) {
4635
            w->events[i] = w->events[i + 1];
4636
            w->func[i] = w->func[i + 1];
4637
            w->opaque[i] = w->opaque[i + 1];
4638
        }            
4639
    }
4640
    if (found)
4641
        w->num--;
4642
}
4643
#endif
4644

    
4645
/***********************************************************/
4646
/* savevm/loadvm support */
4647

    
4648
#define IO_BUF_SIZE 32768
4649

    
4650
struct QEMUFile {
4651
    FILE *outfile;
4652
    BlockDriverState *bs;
4653
    int is_file;
4654
    int is_writable;
4655
    int64_t base_offset;
4656
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4657
                           when reading */
4658
    int buf_index;
4659
    int buf_size; /* 0 when writing */
4660
    uint8_t buf[IO_BUF_SIZE];
4661
};
4662

    
4663
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4664
{
4665
    QEMUFile *f;
4666

    
4667
    f = qemu_mallocz(sizeof(QEMUFile));
4668
    if (!f)
4669
        return NULL;
4670
    if (!strcmp(mode, "wb")) {
4671
        f->is_writable = 1;
4672
    } else if (!strcmp(mode, "rb")) {
4673
        f->is_writable = 0;
4674
    } else {
4675
        goto fail;
4676
    }
4677
    f->outfile = fopen(filename, mode);
4678
    if (!f->outfile)
4679
        goto fail;
4680
    f->is_file = 1;
4681
    return f;
4682
 fail:
4683
    if (f->outfile)
4684
        fclose(f->outfile);
4685
    qemu_free(f);
4686
    return NULL;
4687
}
4688

    
4689
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4690
{
4691
    QEMUFile *f;
4692

    
4693
    f = qemu_mallocz(sizeof(QEMUFile));
4694
    if (!f)
4695
        return NULL;
4696
    f->is_file = 0;
4697
    f->bs = bs;
4698
    f->is_writable = is_writable;
4699
    f->base_offset = offset;
4700
    return f;
4701
}
4702

    
4703
void qemu_fflush(QEMUFile *f)
4704
{
4705
    if (!f->is_writable)
4706
        return;
4707
    if (f->buf_index > 0) {
4708
        if (f->is_file) {
4709
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4710
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4711
        } else {
4712
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4713
                        f->buf, f->buf_index);
4714
        }
4715
        f->buf_offset += f->buf_index;
4716
        f->buf_index = 0;
4717
    }
4718
}
4719

    
4720
static void qemu_fill_buffer(QEMUFile *f)
4721
{
4722
    int len;
4723

    
4724
    if (f->is_writable)
4725
        return;
4726
    if (f->is_file) {
4727
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4728
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4729
        if (len < 0)
4730
            len = 0;
4731
    } else {
4732
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4733
                         f->buf, IO_BUF_SIZE);
4734
        if (len < 0)
4735
            len = 0;
4736
    }
4737
    f->buf_index = 0;
4738
    f->buf_size = len;
4739
    f->buf_offset += len;
4740
}
4741

    
4742
void qemu_fclose(QEMUFile *f)
4743
{
4744
    if (f->is_writable)
4745
        qemu_fflush(f);
4746
    if (f->is_file) {
4747
        fclose(f->outfile);
4748
    }
4749
    qemu_free(f);
4750
}
4751

    
4752
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4753
{
4754
    int l;
4755
    while (size > 0) {
4756
        l = IO_BUF_SIZE - f->buf_index;
4757
        if (l > size)
4758
            l = size;
4759
        memcpy(f->buf + f->buf_index, buf, l);
4760
        f->buf_index += l;
4761
        buf += l;
4762
        size -= l;
4763
        if (f->buf_index >= IO_BUF_SIZE)
4764
            qemu_fflush(f);
4765
    }
4766
}
4767

    
4768
void qemu_put_byte(QEMUFile *f, int v)
4769
{
4770
    f->buf[f->buf_index++] = v;
4771
    if (f->buf_index >= IO_BUF_SIZE)
4772
        qemu_fflush(f);
4773
}
4774

    
4775
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4776
{
4777
    int size, l;
4778

    
4779
    size = size1;
4780
    while (size > 0) {
4781
        l = f->buf_size - f->buf_index;
4782
        if (l == 0) {
4783
            qemu_fill_buffer(f);
4784
            l = f->buf_size - f->buf_index;
4785
            if (l == 0)
4786
                break;
4787
        }
4788
        if (l > size)
4789
            l = size;
4790
        memcpy(buf, f->buf + f->buf_index, l);
4791
        f->buf_index += l;
4792
        buf += l;
4793
        size -= l;
4794
    }
4795
    return size1 - size;
4796
}
4797

    
4798
int qemu_get_byte(QEMUFile *f)
4799
{
4800
    if (f->buf_index >= f->buf_size) {
4801
        qemu_fill_buffer(f);
4802
        if (f->buf_index >= f->buf_size)
4803
            return 0;
4804
    }
4805
    return f->buf[f->buf_index++];
4806
}
4807

    
4808
int64_t qemu_ftell(QEMUFile *f)
4809
{
4810
    return f->buf_offset - f->buf_size + f->buf_index;
4811
}
4812

    
4813
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4814
{
4815
    if (whence == SEEK_SET) {
4816
        /* nothing to do */
4817
    } else if (whence == SEEK_CUR) {
4818
        pos += qemu_ftell(f);
4819
    } else {
4820
        /* SEEK_END not supported */
4821
        return -1;
4822
    }
4823
    if (f->is_writable) {
4824
        qemu_fflush(f);
4825
        f->buf_offset = pos;
4826
    } else {
4827
        f->buf_offset = pos;
4828
        f->buf_index = 0;
4829
        f->buf_size = 0;
4830
    }
4831
    return pos;
4832
}
4833

    
4834
void qemu_put_be16(QEMUFile *f, unsigned int v)
4835
{
4836
    qemu_put_byte(f, v >> 8);
4837
    qemu_put_byte(f, v);
4838
}
4839

    
4840
void qemu_put_be32(QEMUFile *f, unsigned int v)
4841
{
4842
    qemu_put_byte(f, v >> 24);
4843
    qemu_put_byte(f, v >> 16);
4844
    qemu_put_byte(f, v >> 8);
4845
    qemu_put_byte(f, v);
4846
}
4847

    
4848
void qemu_put_be64(QEMUFile *f, uint64_t v)
4849
{
4850
    qemu_put_be32(f, v >> 32);
4851
    qemu_put_be32(f, v);
4852
}
4853

    
4854
unsigned int qemu_get_be16(QEMUFile *f)
4855
{
4856
    unsigned int v;
4857
    v = qemu_get_byte(f) << 8;
4858
    v |= qemu_get_byte(f);
4859
    return v;
4860
}
4861

    
4862
unsigned int qemu_get_be32(QEMUFile *f)
4863
{
4864
    unsigned int v;
4865
    v = qemu_get_byte(f) << 24;
4866
    v |= qemu_get_byte(f) << 16;
4867
    v |= qemu_get_byte(f) << 8;
4868
    v |= qemu_get_byte(f);
4869
    return v;
4870
}
4871

    
4872
uint64_t qemu_get_be64(QEMUFile *f)
4873
{
4874
    uint64_t v;
4875
    v = (uint64_t)qemu_get_be32(f) << 32;
4876
    v |= qemu_get_be32(f);
4877
    return v;
4878
}
4879

    
4880
typedef struct SaveStateEntry {
4881
    char idstr[256];
4882
    int instance_id;
4883
    int version_id;
4884
    SaveStateHandler *save_state;
4885
    LoadStateHandler *load_state;
4886
    void *opaque;
4887
    struct SaveStateEntry *next;
4888
} SaveStateEntry;
4889

    
4890
static SaveStateEntry *first_se;
4891

    
4892
int register_savevm(const char *idstr, 
4893
                    int instance_id, 
4894
                    int version_id,
4895
                    SaveStateHandler *save_state,
4896
                    LoadStateHandler *load_state,
4897
                    void *opaque)
4898
{
4899
    SaveStateEntry *se, **pse;
4900

    
4901
    se = qemu_malloc(sizeof(SaveStateEntry));
4902
    if (!se)
4903
        return -1;
4904
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4905
    se->instance_id = instance_id;
4906
    se->version_id = version_id;
4907
    se->save_state = save_state;
4908
    se->load_state = load_state;
4909
    se->opaque = opaque;
4910
    se->next = NULL;
4911

    
4912
    /* add at the end of list */
4913
    pse = &first_se;
4914
    while (*pse != NULL)
4915
        pse = &(*pse)->next;
4916
    *pse = se;
4917
    return 0;
4918
}
4919

    
4920
#define QEMU_VM_FILE_MAGIC   0x5145564d
4921
#define QEMU_VM_FILE_VERSION 0x00000002
4922

    
4923
int qemu_savevm_state(QEMUFile *f)
4924
{
4925
    SaveStateEntry *se;
4926
    int len, ret;
4927
    int64_t cur_pos, len_pos, total_len_pos;
4928

    
4929
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4930
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4931
    total_len_pos = qemu_ftell(f);
4932
    qemu_put_be64(f, 0); /* total size */
4933

    
4934
    for(se = first_se; se != NULL; se = se->next) {
4935
        /* ID string */
4936
        len = strlen(se->idstr);
4937
        qemu_put_byte(f, len);
4938
        qemu_put_buffer(f, se->idstr, len);
4939

    
4940
        qemu_put_be32(f, se->instance_id);
4941
        qemu_put_be32(f, se->version_id);
4942

    
4943
        /* record size: filled later */
4944
        len_pos = qemu_ftell(f);
4945
        qemu_put_be32(f, 0);
4946
        
4947
        se->save_state(f, se->opaque);
4948

    
4949
        /* fill record size */
4950
        cur_pos = qemu_ftell(f);
4951
        len = cur_pos - len_pos - 4;
4952
        qemu_fseek(f, len_pos, SEEK_SET);
4953
        qemu_put_be32(f, len);
4954
        qemu_fseek(f, cur_pos, SEEK_SET);
4955
    }
4956
    cur_pos = qemu_ftell(f);
4957
    qemu_fseek(f, total_len_pos, SEEK_SET);
4958
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4959
    qemu_fseek(f, cur_pos, SEEK_SET);
4960

    
4961
    ret = 0;
4962
    return ret;
4963
}
4964

    
4965
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4966
{
4967
    SaveStateEntry *se;
4968

    
4969
    for(se = first_se; se != NULL; se = se->next) {
4970
        if (!strcmp(se->idstr, idstr) && 
4971
            instance_id == se->instance_id)
4972
            return se;
4973
    }
4974
    return NULL;
4975
}
4976

    
4977
int qemu_loadvm_state(QEMUFile *f)
4978
{
4979
    SaveStateEntry *se;
4980
    int len, ret, instance_id, record_len, version_id;
4981
    int64_t total_len, end_pos, cur_pos;
4982
    unsigned int v;
4983
    char idstr[256];
4984
    
4985
    v = qemu_get_be32(f);
4986
    if (v != QEMU_VM_FILE_MAGIC)
4987
        goto fail;
4988
    v = qemu_get_be32(f);
4989
    if (v != QEMU_VM_FILE_VERSION) {
4990
    fail:
4991
        ret = -1;
4992
        goto the_end;
4993
    }
4994
    total_len = qemu_get_be64(f);
4995
    end_pos = total_len + qemu_ftell(f);
4996
    for(;;) {
4997