Statistics
| Branch: | Revision:

root / vl.c @ 455204eb

History | View | Annotate | Download (194.4 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2006 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
#endif
59
#endif
60
#endif
61

    
62
#if defined(CONFIG_SLIRP)
63
#include "libslirp.h"
64
#endif
65

    
66
#ifdef _WIN32
67
#include <malloc.h>
68
#include <sys/timeb.h>
69
#include <windows.h>
70
#define getopt_long_only getopt_long
71
#define memalign(align, size) malloc(size)
72
#endif
73

    
74
#include "qemu_socket.h"
75

    
76
#ifdef CONFIG_SDL
77
#ifdef __APPLE__
78
#include <SDL/SDL.h>
79
#endif
80
#endif /* CONFIG_SDL */
81

    
82
#ifdef CONFIG_COCOA
83
#undef main
84
#define main qemu_main
85
#endif /* CONFIG_COCOA */
86

    
87
#include "disas.h"
88

    
89
#include "exec-all.h"
90

    
91
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92
#ifdef __sun__
93
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
94
#else
95
#define SMBD_COMMAND "/usr/sbin/smbd"
96
#endif
97

    
98
//#define DEBUG_UNUSED_IOPORT
99
//#define DEBUG_IOPORT
100

    
101
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
102

    
103
#ifdef TARGET_PPC
104
#define DEFAULT_RAM_SIZE 144
105
#else
106
#define DEFAULT_RAM_SIZE 128
107
#endif
108
/* in ms */
109
#define GUI_REFRESH_INTERVAL 30
110

    
111
/* Max number of USB devices that can be specified on the commandline.  */
112
#define MAX_USB_CMDLINE 8
113

    
114
/* XXX: use a two level table to limit memory usage */
115
#define MAX_IOPORTS 65536
116

    
117
#define DISK_OPTIONS_SIZE 256
118

    
119
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
120
char phys_ram_file[1024];
121
void *ioport_opaque[MAX_IOPORTS];
122
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
123
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
124
/* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
125
   to store the VM snapshots */
126
BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
127
/* point to the block driver where the snapshots are managed */
128
BlockDriverState *bs_snapshots;
129
BlockDriverState *bs_scsi_table[MAX_SCSI_DISKS];
130
SCSIDiskInfo scsi_disks_info[MAX_SCSI_DISKS];
131
int scsi_hba_lsi; /* Count of scsi disks/cdrom using this lsi adapter */
132
int vga_ram_size;
133
int bios_size;
134
static DisplayState display_state;
135
int nographic;
136
const char* keyboard_layout = NULL;
137
int64_t ticks_per_sec;
138
int boot_device = 'c';
139
int ram_size;
140
int pit_min_timer_count = 0;
141
int nb_nics;
142
NICInfo nd_table[MAX_NICS];
143
QEMUTimer *gui_timer;
144
int vm_running;
145
int rtc_utc = 1;
146
int cirrus_vga_enabled = 1;
147
#ifdef TARGET_SPARC
148
int graphic_width = 1024;
149
int graphic_height = 768;
150
#else
151
int graphic_width = 800;
152
int graphic_height = 600;
153
#endif
154
int graphic_depth = 15;
155
int full_screen = 0;
156
int no_quit = 0;
157
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
158
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
159
#ifdef TARGET_I386
160
int win2k_install_hack = 0;
161
#endif
162
int usb_enabled = 0;
163
static VLANState *first_vlan;
164
int smp_cpus = 1;
165
const char *vnc_display;
166
#if defined(TARGET_SPARC)
167
#define MAX_CPUS 16
168
#elif defined(TARGET_I386)
169
#define MAX_CPUS 255
170
#else
171
#define MAX_CPUS 1
172
#endif
173
int acpi_enabled = 1;
174
int fd_bootchk = 1;
175
int no_reboot = 0;
176
int daemonize = 0;
177

    
178
/***********************************************************/
179
/* x86 ISA bus support */
180

    
181
target_phys_addr_t isa_mem_base = 0;
182
PicState2 *isa_pic;
183

    
184
uint32_t default_ioport_readb(void *opaque, uint32_t address)
185
{
186
#ifdef DEBUG_UNUSED_IOPORT
187
    fprintf(stderr, "inb: port=0x%04x\n", address);
188
#endif
189
    return 0xff;
190
}
191

    
192
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
193
{
194
#ifdef DEBUG_UNUSED_IOPORT
195
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
196
#endif
197
}
198

    
199
/* default is to make two byte accesses */
200
uint32_t default_ioport_readw(void *opaque, uint32_t address)
201
{
202
    uint32_t data;
203
    data = ioport_read_table[0][address](ioport_opaque[address], address);
204
    address = (address + 1) & (MAX_IOPORTS - 1);
205
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
206
    return data;
207
}
208

    
209
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
210
{
211
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
212
    address = (address + 1) & (MAX_IOPORTS - 1);
213
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
214
}
215

    
216
uint32_t default_ioport_readl(void *opaque, uint32_t address)
217
{
218
#ifdef DEBUG_UNUSED_IOPORT
219
    fprintf(stderr, "inl: port=0x%04x\n", address);
220
#endif
221
    return 0xffffffff;
222
}
223

    
224
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
225
{
226
#ifdef DEBUG_UNUSED_IOPORT
227
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
228
#endif
229
}
230

    
231
void init_ioports(void)
232
{
233
    int i;
234

    
235
    for(i = 0; i < MAX_IOPORTS; i++) {
236
        ioport_read_table[0][i] = default_ioport_readb;
237
        ioport_write_table[0][i] = default_ioport_writeb;
238
        ioport_read_table[1][i] = default_ioport_readw;
239
        ioport_write_table[1][i] = default_ioport_writew;
240
        ioport_read_table[2][i] = default_ioport_readl;
241
        ioport_write_table[2][i] = default_ioport_writel;
242
    }
243
}
244

    
245
/* size is the word size in byte */
246
int register_ioport_read(int start, int length, int size, 
247
                         IOPortReadFunc *func, void *opaque)
248
{
249
    int i, bsize;
250

    
251
    if (size == 1) {
252
        bsize = 0;
253
    } else if (size == 2) {
254
        bsize = 1;
255
    } else if (size == 4) {
256
        bsize = 2;
257
    } else {
258
        hw_error("register_ioport_read: invalid size");
259
        return -1;
260
    }
261
    for(i = start; i < start + length; i += size) {
262
        ioport_read_table[bsize][i] = func;
263
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
264
            hw_error("register_ioport_read: invalid opaque");
265
        ioport_opaque[i] = opaque;
266
    }
267
    return 0;
268
}
269

    
270
/* size is the word size in byte */
271
int register_ioport_write(int start, int length, int size, 
272
                          IOPortWriteFunc *func, void *opaque)
273
{
274
    int i, bsize;
275

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

    
295
void isa_unassign_ioport(int start, int length)
296
{
297
    int i;
298

    
299
    for(i = start; i < start + length; i++) {
300
        ioport_read_table[0][i] = default_ioport_readb;
301
        ioport_read_table[1][i] = default_ioport_readw;
302
        ioport_read_table[2][i] = default_ioport_readl;
303

    
304
        ioport_write_table[0][i] = default_ioport_writeb;
305
        ioport_write_table[1][i] = default_ioport_writew;
306
        ioport_write_table[2][i] = default_ioport_writel;
307
    }
308
}
309

    
310
/***********************************************************/
311

    
312
void pstrcpy(char *buf, int buf_size, const char *str)
313
{
314
    int c;
315
    char *q = buf;
316

    
317
    if (buf_size <= 0)
318
        return;
319

    
320
    for(;;) {
321
        c = *str++;
322
        if (c == 0 || q >= buf + buf_size - 1)
323
            break;
324
        *q++ = c;
325
    }
326
    *q = '\0';
327
}
328

    
329
/* strcat and truncate. */
330
char *pstrcat(char *buf, int buf_size, const char *s)
331
{
332
    int len;
333
    len = strlen(buf);
334
    if (len < buf_size) 
335
        pstrcpy(buf + len, buf_size - len, s);
336
    return buf;
337
}
338

    
339
int strstart(const char *str, const char *val, const char **ptr)
340
{
341
    const char *p, *q;
342
    p = str;
343
    q = val;
344
    while (*q != '\0') {
345
        if (*p != *q)
346
            return 0;
347
        p++;
348
        q++;
349
    }
350
    if (ptr)
351
        *ptr = p;
352
    return 1;
353
}
354

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

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

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

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

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

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

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

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

    
461
/***********************************************************/
462
/* keyboard/mouse */
463

    
464
static QEMUPutKBDEvent *qemu_put_kbd_event;
465
static void *qemu_put_kbd_event_opaque;
466
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
467
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
468

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

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

    
481
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
482
    if (!s)
483
        return NULL;
484

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

    
491
    if (!qemu_put_mouse_event_head) {
492
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
493
        return s;
494
    }
495

    
496
    cursor = qemu_put_mouse_event_head;
497
    while (cursor->next != NULL)
498
        cursor = cursor->next;
499

    
500
    cursor->next = s;
501
    qemu_put_mouse_event_current = s;
502

    
503
    return s;
504
}
505

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

    
510
    if (!qemu_put_mouse_event_head || entry == NULL)
511
        return;
512

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

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

    
530
    prev->next = entry->next;
531

    
532
    if (qemu_put_mouse_event_current == entry)
533
        qemu_put_mouse_event_current = prev;
534

    
535
    qemu_free(entry->qemu_put_mouse_event_name);
536
    qemu_free(entry);
537
}
538

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

    
546
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
547
{
548
    QEMUPutMouseEvent *mouse_event;
549
    void *mouse_event_opaque;
550

    
551
    if (!qemu_put_mouse_event_current) {
552
        return;
553
    }
554

    
555
    mouse_event =
556
        qemu_put_mouse_event_current->qemu_put_mouse_event;
557
    mouse_event_opaque =
558
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
559

    
560
    if (mouse_event) {
561
        mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
562
    }
563
}
564

    
565
int kbd_mouse_is_absolute(void)
566
{
567
    if (!qemu_put_mouse_event_current)
568
        return 0;
569

    
570
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
571
}
572

    
573
void do_info_mice(void)
574
{
575
    QEMUPutMouseEntry *cursor;
576
    int index = 0;
577

    
578
    if (!qemu_put_mouse_event_head) {
579
        term_printf("No mouse devices connected\n");
580
        return;
581
    }
582

    
583
    term_printf("Mouse devices available:\n");
584
    cursor = qemu_put_mouse_event_head;
585
    while (cursor != NULL) {
586
        term_printf("%c Mouse #%d: %s\n",
587
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
588
                    index, cursor->qemu_put_mouse_event_name);
589
        index++;
590
        cursor = cursor->next;
591
    }
592
}
593

    
594
void do_mouse_set(int index)
595
{
596
    QEMUPutMouseEntry *cursor;
597
    int i = 0;
598

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

    
604
    cursor = qemu_put_mouse_event_head;
605
    while (cursor != NULL && index != i) {
606
        i++;
607
        cursor = cursor->next;
608
    }
609

    
610
    if (cursor != NULL)
611
        qemu_put_mouse_event_current = cursor;
612
    else
613
        term_printf("Mouse at given index not found\n");
614
}
615

    
616
/* compute with 96 bit intermediate result: (a*b)/c */
617
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
618
{
619
    union {
620
        uint64_t ll;
621
        struct {
622
#ifdef WORDS_BIGENDIAN
623
            uint32_t high, low;
624
#else
625
            uint32_t low, high;
626
#endif            
627
        } l;
628
    } u, res;
629
    uint64_t rl, rh;
630

    
631
    u.ll = a;
632
    rl = (uint64_t)u.l.low * (uint64_t)b;
633
    rh = (uint64_t)u.l.high * (uint64_t)b;
634
    rh += (rl >> 32);
635
    res.l.high = rh / c;
636
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
637
    return res.ll;
638
}
639

    
640
/***********************************************************/
641
/* real time host monotonic timer */
642

    
643
#define QEMU_TIMER_BASE 1000000000LL
644

    
645
#ifdef WIN32
646

    
647
static int64_t clock_freq;
648

    
649
static void init_get_clock(void)
650
{
651
    LARGE_INTEGER freq;
652
    int ret;
653
    ret = QueryPerformanceFrequency(&freq);
654
    if (ret == 0) {
655
        fprintf(stderr, "Could not calibrate ticks\n");
656
        exit(1);
657
    }
658
    clock_freq = freq.QuadPart;
659
}
660

    
661
static int64_t get_clock(void)
662
{
663
    LARGE_INTEGER ti;
664
    QueryPerformanceCounter(&ti);
665
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
666
}
667

    
668
#else
669

    
670
static int use_rt_clock;
671

    
672
static void init_get_clock(void)
673
{
674
    use_rt_clock = 0;
675
#if defined(__linux__)
676
    {
677
        struct timespec ts;
678
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
679
            use_rt_clock = 1;
680
        }
681
    }
682
#endif
683
}
684

    
685
static int64_t get_clock(void)
686
{
687
#if defined(__linux__)
688
    if (use_rt_clock) {
689
        struct timespec ts;
690
        clock_gettime(CLOCK_MONOTONIC, &ts);
691
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
692
    } else 
693
#endif
694
    {
695
        /* XXX: using gettimeofday leads to problems if the date
696
           changes, so it should be avoided. */
697
        struct timeval tv;
698
        gettimeofday(&tv, NULL);
699
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
700
    }
701
}
702

    
703
#endif
704

    
705
/***********************************************************/
706
/* guest cycle counter */
707

    
708
static int64_t cpu_ticks_prev;
709
static int64_t cpu_ticks_offset;
710
static int64_t cpu_clock_offset;
711
static int cpu_ticks_enabled;
712

    
713
/* return the host CPU cycle counter and handle stop/restart */
714
int64_t cpu_get_ticks(void)
715
{
716
    if (!cpu_ticks_enabled) {
717
        return cpu_ticks_offset;
718
    } else {
719
        int64_t ticks;
720
        ticks = cpu_get_real_ticks();
721
        if (cpu_ticks_prev > ticks) {
722
            /* Note: non increasing ticks may happen if the host uses
723
               software suspend */
724
            cpu_ticks_offset += cpu_ticks_prev - ticks;
725
        }
726
        cpu_ticks_prev = ticks;
727
        return ticks + cpu_ticks_offset;
728
    }
729
}
730

    
731
/* return the host CPU monotonic timer and handle stop/restart */
732
static int64_t cpu_get_clock(void)
733
{
734
    int64_t ti;
735
    if (!cpu_ticks_enabled) {
736
        return cpu_clock_offset;
737
    } else {
738
        ti = get_clock();
739
        return ti + cpu_clock_offset;
740
    }
741
}
742

    
743
/* enable cpu_get_ticks() */
744
void cpu_enable_ticks(void)
745
{
746
    if (!cpu_ticks_enabled) {
747
        cpu_ticks_offset -= cpu_get_real_ticks();
748
        cpu_clock_offset -= get_clock();
749
        cpu_ticks_enabled = 1;
750
    }
751
}
752

    
753
/* disable cpu_get_ticks() : the clock is stopped. You must not call
754
   cpu_get_ticks() after that.  */
755
void cpu_disable_ticks(void)
756
{
757
    if (cpu_ticks_enabled) {
758
        cpu_ticks_offset = cpu_get_ticks();
759
        cpu_clock_offset = cpu_get_clock();
760
        cpu_ticks_enabled = 0;
761
    }
762
}
763

    
764
/***********************************************************/
765
/* timers */
766
 
767
#define QEMU_TIMER_REALTIME 0
768
#define QEMU_TIMER_VIRTUAL  1
769

    
770
struct QEMUClock {
771
    int type;
772
    /* XXX: add frequency */
773
};
774

    
775
struct QEMUTimer {
776
    QEMUClock *clock;
777
    int64_t expire_time;
778
    QEMUTimerCB *cb;
779
    void *opaque;
780
    struct QEMUTimer *next;
781
};
782

    
783
QEMUClock *rt_clock;
784
QEMUClock *vm_clock;
785

    
786
static QEMUTimer *active_timers[2];
787
#ifdef _WIN32
788
static MMRESULT timerID;
789
static HANDLE host_alarm = NULL;
790
static unsigned int period = 1;
791
#else
792
/* frequency of the times() clock tick */
793
static int timer_freq;
794
#endif
795

    
796
QEMUClock *qemu_new_clock(int type)
797
{
798
    QEMUClock *clock;
799
    clock = qemu_mallocz(sizeof(QEMUClock));
800
    if (!clock)
801
        return NULL;
802
    clock->type = type;
803
    return clock;
804
}
805

    
806
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
807
{
808
    QEMUTimer *ts;
809

    
810
    ts = qemu_mallocz(sizeof(QEMUTimer));
811
    ts->clock = clock;
812
    ts->cb = cb;
813
    ts->opaque = opaque;
814
    return ts;
815
}
816

    
817
void qemu_free_timer(QEMUTimer *ts)
818
{
819
    qemu_free(ts);
820
}
821

    
822
/* stop a timer, but do not dealloc it */
823
void qemu_del_timer(QEMUTimer *ts)
824
{
825
    QEMUTimer **pt, *t;
826

    
827
    /* NOTE: this code must be signal safe because
828
       qemu_timer_expired() can be called from a signal. */
829
    pt = &active_timers[ts->clock->type];
830
    for(;;) {
831
        t = *pt;
832
        if (!t)
833
            break;
834
        if (t == ts) {
835
            *pt = t->next;
836
            break;
837
        }
838
        pt = &t->next;
839
    }
840
}
841

    
842
/* modify the current timer so that it will be fired when current_time
843
   >= expire_time. The corresponding callback will be called. */
844
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
845
{
846
    QEMUTimer **pt, *t;
847

    
848
    qemu_del_timer(ts);
849

    
850
    /* add the timer in the sorted list */
851
    /* NOTE: this code must be signal safe because
852
       qemu_timer_expired() can be called from a signal. */
853
    pt = &active_timers[ts->clock->type];
854
    for(;;) {
855
        t = *pt;
856
        if (!t)
857
            break;
858
        if (t->expire_time > expire_time) 
859
            break;
860
        pt = &t->next;
861
    }
862
    ts->expire_time = expire_time;
863
    ts->next = *pt;
864
    *pt = ts;
865
}
866

    
867
int qemu_timer_pending(QEMUTimer *ts)
868
{
869
    QEMUTimer *t;
870
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
871
        if (t == ts)
872
            return 1;
873
    }
874
    return 0;
875
}
876

    
877
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
878
{
879
    if (!timer_head)
880
        return 0;
881
    return (timer_head->expire_time <= current_time);
882
}
883

    
884
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
885
{
886
    QEMUTimer *ts;
887
    
888
    for(;;) {
889
        ts = *ptimer_head;
890
        if (!ts || ts->expire_time > current_time)
891
            break;
892
        /* remove timer from the list before calling the callback */
893
        *ptimer_head = ts->next;
894
        ts->next = NULL;
895
        
896
        /* run the callback (the timer list can be modified) */
897
        ts->cb(ts->opaque);
898
    }
899
}
900

    
901
int64_t qemu_get_clock(QEMUClock *clock)
902
{
903
    switch(clock->type) {
904
    case QEMU_TIMER_REALTIME:
905
        return get_clock() / 1000000;
906
    default:
907
    case QEMU_TIMER_VIRTUAL:
908
        return cpu_get_clock();
909
    }
910
}
911

    
912
static void init_timers(void)
913
{
914
    init_get_clock();
915
    ticks_per_sec = QEMU_TIMER_BASE;
916
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
917
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
918
}
919

    
920
/* save a timer */
921
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
922
{
923
    uint64_t expire_time;
924

    
925
    if (qemu_timer_pending(ts)) {
926
        expire_time = ts->expire_time;
927
    } else {
928
        expire_time = -1;
929
    }
930
    qemu_put_be64(f, expire_time);
931
}
932

    
933
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
934
{
935
    uint64_t expire_time;
936

    
937
    expire_time = qemu_get_be64(f);
938
    if (expire_time != -1) {
939
        qemu_mod_timer(ts, expire_time);
940
    } else {
941
        qemu_del_timer(ts);
942
    }
943
}
944

    
945
static void timer_save(QEMUFile *f, void *opaque)
946
{
947
    if (cpu_ticks_enabled) {
948
        hw_error("cannot save state if virtual timers are running");
949
    }
950
    qemu_put_be64s(f, &cpu_ticks_offset);
951
    qemu_put_be64s(f, &ticks_per_sec);
952
    qemu_put_be64s(f, &cpu_clock_offset);
953
}
954

    
955
static int timer_load(QEMUFile *f, void *opaque, int version_id)
956
{
957
    if (version_id != 1 && version_id != 2)
958
        return -EINVAL;
959
    if (cpu_ticks_enabled) {
960
        return -EINVAL;
961
    }
962
    qemu_get_be64s(f, &cpu_ticks_offset);
963
    qemu_get_be64s(f, &ticks_per_sec);
964
    if (version_id == 2) {
965
        qemu_get_be64s(f, &cpu_clock_offset);
966
    }
967
    return 0;
968
}
969

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

    
1026
#ifndef _WIN32
1027

    
1028
#if defined(__linux__)
1029

    
1030
#define RTC_FREQ 1024
1031

    
1032
static int rtc_fd;
1033

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

    
1054
#else
1055

    
1056
static int start_rtc_timer(void)
1057
{
1058
    return -1;
1059
}
1060

    
1061
#endif /* !defined(__linux__) */
1062

    
1063
#endif /* !defined(_WIN32) */
1064

    
1065
static void init_timer_alarm(void)
1066
{
1067
#ifdef _WIN32
1068
    {
1069
        int count=0;
1070
        TIMECAPS tc;
1071

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

    
1111
        itv.it_interval.tv_sec = 0;
1112
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1113
        itv.it_value.tv_sec = 0;
1114
        itv.it_value.tv_usec = 10 * 1000;
1115
        setitimer(ITIMER_REAL, &itv, NULL);
1116
        /* we probe the tick duration of the kernel to inform the user if
1117
           the emulated kernel requested a too high timer frequency */
1118
        getitimer(ITIMER_REAL, &itv);
1119

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

    
1136
            /* use the RTC */
1137
            sigaction(SIGIO, &act, NULL);
1138
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1139
            fcntl(rtc_fd, F_SETOWN, getpid());
1140
        } else 
1141
#endif /* defined(__linux__) */
1142
        {
1143
        use_itimer:
1144
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1145
                                   PIT_FREQ) / 1000000;
1146
        }
1147
    }
1148
#endif
1149
}
1150

    
1151
void quit_timers(void)
1152
{
1153
#ifdef _WIN32
1154
    timeKillEvent(timerID);
1155
    timeEndPeriod(period);
1156
    if (host_alarm) {
1157
        CloseHandle(host_alarm);
1158
        host_alarm = NULL;
1159
    }
1160
#endif
1161
}
1162

    
1163
/***********************************************************/
1164
/* character device */
1165

    
1166
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1167
{
1168
    return s->chr_write(s, buf, len);
1169
}
1170

    
1171
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1172
{
1173
    if (!s->chr_ioctl)
1174
        return -ENOTSUP;
1175
    return s->chr_ioctl(s, cmd, arg);
1176
}
1177

    
1178
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1179
{
1180
    char buf[4096];
1181
    va_list ap;
1182
    va_start(ap, fmt);
1183
    vsnprintf(buf, sizeof(buf), fmt, ap);
1184
    qemu_chr_write(s, buf, strlen(buf));
1185
    va_end(ap);
1186
}
1187

    
1188
void qemu_chr_send_event(CharDriverState *s, int event)
1189
{
1190
    if (s->chr_send_event)
1191
        s->chr_send_event(s, event);
1192
}
1193

    
1194
void qemu_chr_add_read_handler(CharDriverState *s, 
1195
                               IOCanRWHandler *fd_can_read, 
1196
                               IOReadHandler *fd_read, void *opaque)
1197
{
1198
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1199
}
1200
             
1201
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1202
{
1203
    s->chr_event = chr_event;
1204
}
1205

    
1206
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1207
{
1208
    return len;
1209
}
1210

    
1211
static void null_chr_add_read_handler(CharDriverState *chr, 
1212
                                    IOCanRWHandler *fd_can_read, 
1213
                                    IOReadHandler *fd_read, void *opaque)
1214
{
1215
}
1216

    
1217
static CharDriverState *qemu_chr_open_null(void)
1218
{
1219
    CharDriverState *chr;
1220

    
1221
    chr = qemu_mallocz(sizeof(CharDriverState));
1222
    if (!chr)
1223
        return NULL;
1224
    chr->chr_write = null_chr_write;
1225
    chr->chr_add_read_handler = null_chr_add_read_handler;
1226
    return chr;
1227
}
1228

    
1229
#ifdef _WIN32
1230

    
1231
static void socket_cleanup(void)
1232
{
1233
    WSACleanup();
1234
}
1235

    
1236
static int socket_init(void)
1237
{
1238
    WSADATA Data;
1239
    int ret, err;
1240

    
1241
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1242
    if (ret != 0) {
1243
        err = WSAGetLastError();
1244
        fprintf(stderr, "WSAStartup: %d\n", err);
1245
        return -1;
1246
    }
1247
    atexit(socket_cleanup);
1248
    return 0;
1249
}
1250

    
1251
static int send_all(int fd, const uint8_t *buf, int len1)
1252
{
1253
    int ret, len;
1254
    
1255
    len = len1;
1256
    while (len > 0) {
1257
        ret = send(fd, buf, len, 0);
1258
        if (ret < 0) {
1259
            int errno;
1260
            errno = WSAGetLastError();
1261
            if (errno != WSAEWOULDBLOCK) {
1262
                return -1;
1263
            }
1264
        } else if (ret == 0) {
1265
            break;
1266
        } else {
1267
            buf += ret;
1268
            len -= ret;
1269
        }
1270
    }
1271
    return len1 - len;
1272
}
1273

    
1274
void socket_set_nonblock(int fd)
1275
{
1276
    unsigned long opt = 1;
1277
    ioctlsocket(fd, FIONBIO, &opt);
1278
}
1279

    
1280
#else
1281

    
1282
static int unix_write(int fd, const uint8_t *buf, int len1)
1283
{
1284
    int ret, len;
1285

    
1286
    len = len1;
1287
    while (len > 0) {
1288
        ret = write(fd, buf, len);
1289
        if (ret < 0) {
1290
            if (errno != EINTR && errno != EAGAIN)
1291
                return -1;
1292
        } else if (ret == 0) {
1293
            break;
1294
        } else {
1295
            buf += ret;
1296
            len -= ret;
1297
        }
1298
    }
1299
    return len1 - len;
1300
}
1301

    
1302
static inline int send_all(int fd, const uint8_t *buf, int len1)
1303
{
1304
    return unix_write(fd, buf, len1);
1305
}
1306

    
1307
void socket_set_nonblock(int fd)
1308
{
1309
    fcntl(fd, F_SETFL, O_NONBLOCK);
1310
}
1311
#endif /* !_WIN32 */
1312

    
1313
#ifndef _WIN32
1314

    
1315
typedef struct {
1316
    int fd_in, fd_out;
1317
    IOCanRWHandler *fd_can_read; 
1318
    IOReadHandler *fd_read;
1319
    void *fd_opaque;
1320
    int max_size;
1321
} FDCharDriver;
1322

    
1323
#define STDIO_MAX_CLIENTS 2
1324

    
1325
static int stdio_nb_clients;
1326
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1327

    
1328
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1329
{
1330
    FDCharDriver *s = chr->opaque;
1331
    return unix_write(s->fd_out, buf, len);
1332
}
1333

    
1334
static int fd_chr_read_poll(void *opaque)
1335
{
1336
    CharDriverState *chr = opaque;
1337
    FDCharDriver *s = chr->opaque;
1338

    
1339
    s->max_size = s->fd_can_read(s->fd_opaque);
1340
    return s->max_size;
1341
}
1342

    
1343
static void fd_chr_read(void *opaque)
1344
{
1345
    CharDriverState *chr = opaque;
1346
    FDCharDriver *s = chr->opaque;
1347
    int size, len;
1348
    uint8_t buf[1024];
1349
    
1350
    len = sizeof(buf);
1351
    if (len > s->max_size)
1352
        len = s->max_size;
1353
    if (len == 0)
1354
        return;
1355
    size = read(s->fd_in, buf, len);
1356
    if (size == 0) {
1357
        /* FD has been closed. Remove it from the active list.  */
1358
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1359
        return;
1360
    }
1361
    if (size > 0) {
1362
        s->fd_read(s->fd_opaque, buf, size);
1363
    }
1364
}
1365

    
1366
static void fd_chr_add_read_handler(CharDriverState *chr, 
1367
                                    IOCanRWHandler *fd_can_read, 
1368
                                    IOReadHandler *fd_read, void *opaque)
1369
{
1370
    FDCharDriver *s = chr->opaque;
1371

    
1372
    if (s->fd_in >= 0) {
1373
        s->fd_can_read = fd_can_read;
1374
        s->fd_read = fd_read;
1375
        s->fd_opaque = opaque;
1376
        if (nographic && s->fd_in == 0) {
1377
        } else {
1378
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1379
                                 fd_chr_read, NULL, chr);
1380
        }
1381
    }
1382
}
1383

    
1384
/* open a character device to a unix fd */
1385
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1386
{
1387
    CharDriverState *chr;
1388
    FDCharDriver *s;
1389

    
1390
    chr = qemu_mallocz(sizeof(CharDriverState));
1391
    if (!chr)
1392
        return NULL;
1393
    s = qemu_mallocz(sizeof(FDCharDriver));
1394
    if (!s) {
1395
        free(chr);
1396
        return NULL;
1397
    }
1398
    s->fd_in = fd_in;
1399
    s->fd_out = fd_out;
1400
    chr->opaque = s;
1401
    chr->chr_write = fd_chr_write;
1402
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1403
    return chr;
1404
}
1405

    
1406
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1407
{
1408
    int fd_out;
1409

    
1410
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1411
    if (fd_out < 0)
1412
        return NULL;
1413
    return qemu_chr_open_fd(-1, fd_out);
1414
}
1415

    
1416
static CharDriverState *qemu_chr_open_pipe(const char *filename)
1417
{
1418
    int fd_in, fd_out;
1419
    char filename_in[256], filename_out[256];
1420

    
1421
    snprintf(filename_in, 256, "%s.in", filename);
1422
    snprintf(filename_out, 256, "%s.out", filename);
1423
    fd_in = open(filename_in, O_RDWR | O_BINARY);
1424
    fd_out = open(filename_out, O_RDWR | O_BINARY);
1425
    if (fd_in < 0 || fd_out < 0) {
1426
        if (fd_in >= 0)
1427
            close(fd_in);
1428
        if (fd_out >= 0)
1429
            close(fd_out);
1430
        fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1431
        if (fd_in < 0)
1432
            return NULL;
1433
    }
1434
    return qemu_chr_open_fd(fd_in, fd_out);
1435
}
1436

    
1437

    
1438
/* for STDIO, we handle the case where several clients use it
1439
   (nographic mode) */
1440

    
1441
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1442

    
1443
#define TERM_FIFO_MAX_SIZE 1
1444

    
1445
static int term_got_escape, client_index;
1446
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1447
static int term_fifo_size;
1448
static int term_timestamps;
1449
static int64_t term_timestamps_start;
1450

    
1451
void term_print_help(void)
1452
{
1453
    printf("\n"
1454
           "C-a h    print this help\n"
1455
           "C-a x    exit emulator\n"
1456
           "C-a s    save disk data back to file (if -snapshot)\n"
1457
           "C-a b    send break (magic sysrq)\n"
1458
           "C-a t    toggle console timestamps\n"
1459
           "C-a c    switch between console and monitor\n"
1460
           "C-a C-a  send C-a\n"
1461
           );
1462
}
1463

    
1464
/* called when a char is received */
1465
static void stdio_received_byte(int ch)
1466
{
1467
    if (term_got_escape) {
1468
        term_got_escape = 0;
1469
        switch(ch) {
1470
        case 'h':
1471
            term_print_help();
1472
            break;
1473
        case 'x':
1474
            exit(0);
1475
            break;
1476
        case 's': 
1477
            {
1478
                int i;
1479
                for (i = 0; i < MAX_DISKS; i++) {
1480
                    if (bs_table[i])
1481
                        bdrv_commit(bs_table[i]);
1482
                }
1483
            }
1484
            break;
1485
        case 'b':
1486
            if (client_index < stdio_nb_clients) {
1487
                CharDriverState *chr;
1488
                FDCharDriver *s;
1489

    
1490
                chr = stdio_clients[client_index];
1491
                s = chr->opaque;
1492
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1493
            }
1494
            break;
1495
        case 'c':
1496
            client_index++;
1497
            if (client_index >= stdio_nb_clients)
1498
                client_index = 0;
1499
            if (client_index == 0) {
1500
                /* send a new line in the monitor to get the prompt */
1501
                ch = '\r';
1502
                goto send_char;
1503
            }
1504
            break;
1505
        case 't':
1506
            term_timestamps = !term_timestamps;
1507
            term_timestamps_start = -1;
1508
            break;
1509
        case TERM_ESCAPE:
1510
            goto send_char;
1511
        }
1512
    } else if (ch == TERM_ESCAPE) {
1513
        term_got_escape = 1;
1514
    } else {
1515
    send_char:
1516
        if (client_index < stdio_nb_clients) {
1517
            uint8_t buf[1];
1518
            CharDriverState *chr;
1519
            FDCharDriver *s;
1520
            
1521
            chr = stdio_clients[client_index];
1522
            s = chr->opaque;
1523
            if (s->fd_can_read(s->fd_opaque) > 0) {
1524
                buf[0] = ch;
1525
                s->fd_read(s->fd_opaque, buf, 1);
1526
            } else if (term_fifo_size == 0) {
1527
                term_fifo[term_fifo_size++] = ch;
1528
            }
1529
        }
1530
    }
1531
}
1532

    
1533
static int stdio_read_poll(void *opaque)
1534
{
1535
    CharDriverState *chr;
1536
    FDCharDriver *s;
1537

    
1538
    if (client_index < stdio_nb_clients) {
1539
        chr = stdio_clients[client_index];
1540
        s = chr->opaque;
1541
        /* try to flush the queue if needed */
1542
        if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1543
            s->fd_read(s->fd_opaque, term_fifo, 1);
1544
            term_fifo_size = 0;
1545
        }
1546
        /* see if we can absorb more chars */
1547
        if (term_fifo_size == 0)
1548
            return 1;
1549
        else
1550
            return 0;
1551
    } else {
1552
        return 1;
1553
    }
1554
}
1555

    
1556
static void stdio_read(void *opaque)
1557
{
1558
    int size;
1559
    uint8_t buf[1];
1560
    
1561
    size = read(0, buf, 1);
1562
    if (size == 0) {
1563
        /* stdin has been closed. Remove it from the active list.  */
1564
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1565
        return;
1566
    }
1567
    if (size > 0)
1568
        stdio_received_byte(buf[0]);
1569
}
1570

    
1571
static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1572
{
1573
    FDCharDriver *s = chr->opaque;
1574
    if (!term_timestamps) {
1575
        return unix_write(s->fd_out, buf, len);
1576
    } else {
1577
        int i;
1578
        char buf1[64];
1579

    
1580
        for(i = 0; i < len; i++) {
1581
            unix_write(s->fd_out, buf + i, 1);
1582
            if (buf[i] == '\n') {
1583
                int64_t ti;
1584
                int secs;
1585

    
1586
                ti = get_clock();
1587
                if (term_timestamps_start == -1)
1588
                    term_timestamps_start = ti;
1589
                ti -= term_timestamps_start;
1590
                secs = ti / 1000000000;
1591
                snprintf(buf1, sizeof(buf1), 
1592
                         "[%02d:%02d:%02d.%03d] ",
1593
                         secs / 3600,
1594
                         (secs / 60) % 60,
1595
                         secs % 60,
1596
                         (int)((ti / 1000000) % 1000));
1597
                unix_write(s->fd_out, buf1, strlen(buf1));
1598
            }
1599
        }
1600
        return len;
1601
    }
1602
}
1603

    
1604
/* init terminal so that we can grab keys */
1605
static struct termios oldtty;
1606
static int old_fd0_flags;
1607

    
1608
static void term_exit(void)
1609
{
1610
    tcsetattr (0, TCSANOW, &oldtty);
1611
    fcntl(0, F_SETFL, old_fd0_flags);
1612
}
1613

    
1614
static void term_init(void)
1615
{
1616
    struct termios tty;
1617

    
1618
    tcgetattr (0, &tty);
1619
    oldtty = tty;
1620
    old_fd0_flags = fcntl(0, F_GETFL);
1621

    
1622
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1623
                          |INLCR|IGNCR|ICRNL|IXON);
1624
    tty.c_oflag |= OPOST;
1625
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1626
    /* if graphical mode, we allow Ctrl-C handling */
1627
    if (nographic)
1628
        tty.c_lflag &= ~ISIG;
1629
    tty.c_cflag &= ~(CSIZE|PARENB);
1630
    tty.c_cflag |= CS8;
1631
    tty.c_cc[VMIN] = 1;
1632
    tty.c_cc[VTIME] = 0;
1633
    
1634
    tcsetattr (0, TCSANOW, &tty);
1635

    
1636
    atexit(term_exit);
1637

    
1638
    fcntl(0, F_SETFL, O_NONBLOCK);
1639
}
1640

    
1641
static CharDriverState *qemu_chr_open_stdio(void)
1642
{
1643
    CharDriverState *chr;
1644

    
1645
    if (nographic) {
1646
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1647
            return NULL;
1648
        chr = qemu_chr_open_fd(0, 1);
1649
        chr->chr_write = stdio_write;
1650
        if (stdio_nb_clients == 0)
1651
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1652
        client_index = stdio_nb_clients;
1653
    } else {
1654
        if (stdio_nb_clients != 0)
1655
            return NULL;
1656
        chr = qemu_chr_open_fd(0, 1);
1657
    }
1658
    stdio_clients[stdio_nb_clients++] = chr;
1659
    if (stdio_nb_clients == 1) {
1660
        /* set the terminal in raw mode */
1661
        term_init();
1662
    }
1663
    return chr;
1664
}
1665

    
1666
#if defined(__linux__)
1667
static CharDriverState *qemu_chr_open_pty(void)
1668
{
1669
    struct termios tty;
1670
    char slave_name[1024];
1671
    int master_fd, slave_fd;
1672
    
1673
    /* Not satisfying */
1674
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1675
        return NULL;
1676
    }
1677
    
1678
    /* Disabling local echo and line-buffered output */
1679
    tcgetattr (master_fd, &tty);
1680
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1681
    tty.c_cc[VMIN] = 1;
1682
    tty.c_cc[VTIME] = 0;
1683
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1684

    
1685
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1686
    return qemu_chr_open_fd(master_fd, master_fd);
1687
}
1688

    
1689
static void tty_serial_init(int fd, int speed, 
1690
                            int parity, int data_bits, int stop_bits)
1691
{
1692
    struct termios tty;
1693
    speed_t spd;
1694

    
1695
#if 0
1696
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1697
           speed, parity, data_bits, stop_bits);
1698
#endif
1699
    tcgetattr (fd, &tty);
1700

    
1701
    switch(speed) {
1702
    case 50:
1703
        spd = B50;
1704
        break;
1705
    case 75:
1706
        spd = B75;
1707
        break;
1708
    case 300:
1709
        spd = B300;
1710
        break;
1711
    case 600:
1712
        spd = B600;
1713
        break;
1714
    case 1200:
1715
        spd = B1200;
1716
        break;
1717
    case 2400:
1718
        spd = B2400;
1719
        break;
1720
    case 4800:
1721
        spd = B4800;
1722
        break;
1723
    case 9600:
1724
        spd = B9600;
1725
        break;
1726
    case 19200:
1727
        spd = B19200;
1728
        break;
1729
    case 38400:
1730
        spd = B38400;
1731
        break;
1732
    case 57600:
1733
        spd = B57600;
1734
        break;
1735
    default:
1736
    case 115200:
1737
        spd = B115200;
1738
        break;
1739
    }
1740

    
1741
    cfsetispeed(&tty, spd);
1742
    cfsetospeed(&tty, spd);
1743

    
1744
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1745
                          |INLCR|IGNCR|ICRNL|IXON);
1746
    tty.c_oflag |= OPOST;
1747
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1748
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1749
    switch(data_bits) {
1750
    default:
1751
    case 8:
1752
        tty.c_cflag |= CS8;
1753
        break;
1754
    case 7:
1755
        tty.c_cflag |= CS7;
1756
        break;
1757
    case 6:
1758
        tty.c_cflag |= CS6;
1759
        break;
1760
    case 5:
1761
        tty.c_cflag |= CS5;
1762
        break;
1763
    }
1764
    switch(parity) {
1765
    default:
1766
    case 'N':
1767
        break;
1768
    case 'E':
1769
        tty.c_cflag |= PARENB;
1770
        break;
1771
    case 'O':
1772
        tty.c_cflag |= PARENB | PARODD;
1773
        break;
1774
    }
1775
    if (stop_bits == 2)
1776
        tty.c_cflag |= CSTOPB;
1777
    
1778
    tcsetattr (fd, TCSANOW, &tty);
1779
}
1780

    
1781
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1782
{
1783
    FDCharDriver *s = chr->opaque;
1784
    
1785
    switch(cmd) {
1786
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1787
        {
1788
            QEMUSerialSetParams *ssp = arg;
1789
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1790
                            ssp->data_bits, ssp->stop_bits);
1791
        }
1792
        break;
1793
    case CHR_IOCTL_SERIAL_SET_BREAK:
1794
        {
1795
            int enable = *(int *)arg;
1796
            if (enable)
1797
                tcsendbreak(s->fd_in, 1);
1798
        }
1799
        break;
1800
    default:
1801
        return -ENOTSUP;
1802
    }
1803
    return 0;
1804
}
1805

    
1806
static CharDriverState *qemu_chr_open_tty(const char *filename)
1807
{
1808
    CharDriverState *chr;
1809
    int fd;
1810

    
1811
    fd = open(filename, O_RDWR | O_NONBLOCK);
1812
    if (fd < 0)
1813
        return NULL;
1814
    fcntl(fd, F_SETFL, O_NONBLOCK);
1815
    tty_serial_init(fd, 115200, 'N', 8, 1);
1816
    chr = qemu_chr_open_fd(fd, fd);
1817
    if (!chr)
1818
        return NULL;
1819
    chr->chr_ioctl = tty_serial_ioctl;
1820
    return chr;
1821
}
1822

    
1823
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1824
{
1825
    int fd = (int)chr->opaque;
1826
    uint8_t b;
1827

    
1828
    switch(cmd) {
1829
    case CHR_IOCTL_PP_READ_DATA:
1830
        if (ioctl(fd, PPRDATA, &b) < 0)
1831
            return -ENOTSUP;
1832
        *(uint8_t *)arg = b;
1833
        break;
1834
    case CHR_IOCTL_PP_WRITE_DATA:
1835
        b = *(uint8_t *)arg;
1836
        if (ioctl(fd, PPWDATA, &b) < 0)
1837
            return -ENOTSUP;
1838
        break;
1839
    case CHR_IOCTL_PP_READ_CONTROL:
1840
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1841
            return -ENOTSUP;
1842
        *(uint8_t *)arg = b;
1843
        break;
1844
    case CHR_IOCTL_PP_WRITE_CONTROL:
1845
        b = *(uint8_t *)arg;
1846
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1847
            return -ENOTSUP;
1848
        break;
1849
    case CHR_IOCTL_PP_READ_STATUS:
1850
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1851
            return -ENOTSUP;
1852
        *(uint8_t *)arg = b;
1853
        break;
1854
    default:
1855
        return -ENOTSUP;
1856
    }
1857
    return 0;
1858
}
1859

    
1860
static CharDriverState *qemu_chr_open_pp(const char *filename)
1861
{
1862
    CharDriverState *chr;
1863
    int fd;
1864

    
1865
    fd = open(filename, O_RDWR);
1866
    if (fd < 0)
1867
        return NULL;
1868

    
1869
    if (ioctl(fd, PPCLAIM) < 0) {
1870
        close(fd);
1871
        return NULL;
1872
    }
1873

    
1874
    chr = qemu_mallocz(sizeof(CharDriverState));
1875
    if (!chr) {
1876
        close(fd);
1877
        return NULL;
1878
    }
1879
    chr->opaque = (void *)fd;
1880
    chr->chr_write = null_chr_write;
1881
    chr->chr_add_read_handler = null_chr_add_read_handler;
1882
    chr->chr_ioctl = pp_ioctl;
1883
    return chr;
1884
}
1885

    
1886
#else
1887
static CharDriverState *qemu_chr_open_pty(void)
1888
{
1889
    return NULL;
1890
}
1891
#endif
1892

    
1893
#endif /* !defined(_WIN32) */
1894

    
1895
#ifdef _WIN32
1896
typedef struct {
1897
    IOCanRWHandler *fd_can_read; 
1898
    IOReadHandler *fd_read;
1899
    void *win_opaque;
1900
    int max_size;
1901
    HANDLE hcom, hrecv, hsend;
1902
    OVERLAPPED orecv, osend;
1903
    BOOL fpipe;
1904
    DWORD len;
1905
} WinCharState;
1906

    
1907
#define NSENDBUF 2048
1908
#define NRECVBUF 2048
1909
#define MAXCONNECT 1
1910
#define NTIMEOUT 5000
1911

    
1912
static int win_chr_poll(void *opaque);
1913
static int win_chr_pipe_poll(void *opaque);
1914

    
1915
static void win_chr_close2(WinCharState *s)
1916
{
1917
    if (s->hsend) {
1918
        CloseHandle(s->hsend);
1919
        s->hsend = NULL;
1920
    }
1921
    if (s->hrecv) {
1922
        CloseHandle(s->hrecv);
1923
        s->hrecv = NULL;
1924
    }
1925
    if (s->hcom) {
1926
        CloseHandle(s->hcom);
1927
        s->hcom = NULL;
1928
    }
1929
    if (s->fpipe)
1930
        qemu_del_polling_cb(win_chr_pipe_poll, s);
1931
    else
1932
        qemu_del_polling_cb(win_chr_poll, s);
1933
}
1934

    
1935
static void win_chr_close(CharDriverState *chr)
1936
{
1937
    WinCharState *s = chr->opaque;
1938
    win_chr_close2(s);
1939
}
1940

    
1941
static int win_chr_init(WinCharState *s, const char *filename)
1942
{
1943
    COMMCONFIG comcfg;
1944
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1945
    COMSTAT comstat;
1946
    DWORD size;
1947
    DWORD err;
1948
    
1949
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1950
    if (!s->hsend) {
1951
        fprintf(stderr, "Failed CreateEvent\n");
1952
        goto fail;
1953
    }
1954
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1955
    if (!s->hrecv) {
1956
        fprintf(stderr, "Failed CreateEvent\n");
1957
        goto fail;
1958
    }
1959

    
1960
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1961
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1962
    if (s->hcom == INVALID_HANDLE_VALUE) {
1963
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1964
        s->hcom = NULL;
1965
        goto fail;
1966
    }
1967
    
1968
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1969
        fprintf(stderr, "Failed SetupComm\n");
1970
        goto fail;
1971
    }
1972
    
1973
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1974
    size = sizeof(COMMCONFIG);
1975
    GetDefaultCommConfig(filename, &comcfg, &size);
1976
    comcfg.dcb.DCBlength = sizeof(DCB);
1977
    CommConfigDialog(filename, NULL, &comcfg);
1978

    
1979
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1980
        fprintf(stderr, "Failed SetCommState\n");
1981
        goto fail;
1982
    }
1983

    
1984
    if (!SetCommMask(s->hcom, EV_ERR)) {
1985
        fprintf(stderr, "Failed SetCommMask\n");
1986
        goto fail;
1987
    }
1988

    
1989
    cto.ReadIntervalTimeout = MAXDWORD;
1990
    if (!SetCommTimeouts(s->hcom, &cto)) {
1991
        fprintf(stderr, "Failed SetCommTimeouts\n");
1992
        goto fail;
1993
    }
1994
    
1995
    if (!ClearCommError(s->hcom, &err, &comstat)) {
1996
        fprintf(stderr, "Failed ClearCommError\n");
1997
        goto fail;
1998
    }
1999
    qemu_add_polling_cb(win_chr_poll, s);
2000
    return 0;
2001

    
2002
 fail:
2003
    win_chr_close2(s);
2004
    return -1;
2005
}
2006

    
2007
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2008
{
2009
    WinCharState *s = chr->opaque;
2010
    DWORD len, ret, size, err;
2011

    
2012
    len = len1;
2013
    ZeroMemory(&s->osend, sizeof(s->osend));
2014
    s->osend.hEvent = s->hsend;
2015
    while (len > 0) {
2016
        if (s->hsend)
2017
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2018
        else
2019
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2020
        if (!ret) {
2021
            err = GetLastError();
2022
            if (err == ERROR_IO_PENDING) {
2023
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2024
                if (ret) {
2025
                    buf += size;
2026
                    len -= size;
2027
                } else {
2028
                    break;
2029
                }
2030
            } else {
2031
                break;
2032
            }
2033
        } else {
2034
            buf += size;
2035
            len -= size;
2036
        }
2037
    }
2038
    return len1 - len;
2039
}
2040

    
2041
static int win_chr_read_poll(WinCharState *s)
2042
{
2043
    s->max_size = s->fd_can_read(s->win_opaque);
2044
    return s->max_size;
2045
}
2046
            
2047
static void win_chr_readfile(WinCharState *s)
2048
{
2049
    int ret, err;
2050
    uint8_t buf[1024];
2051
    DWORD size;
2052
    
2053
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2054
    s->orecv.hEvent = s->hrecv;
2055
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2056
    if (!ret) {
2057
        err = GetLastError();
2058
        if (err == ERROR_IO_PENDING) {
2059
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2060
        }
2061
    }
2062

    
2063
    if (size > 0) {
2064
        s->fd_read(s->win_opaque, buf, size);
2065
    }
2066
}
2067

    
2068
static void win_chr_read(WinCharState *s)
2069
{
2070
    if (s->len > s->max_size)
2071
        s->len = s->max_size;
2072
    if (s->len == 0)
2073
        return;
2074
    
2075
    win_chr_readfile(s);
2076
}
2077

    
2078
static int win_chr_poll(void *opaque)
2079
{
2080
    WinCharState *s = opaque;
2081
    COMSTAT status;
2082
    DWORD comerr;
2083
    
2084
    ClearCommError(s->hcom, &comerr, &status);
2085
    if (status.cbInQue > 0) {
2086
        s->len = status.cbInQue;
2087
        win_chr_read_poll(s);
2088
        win_chr_read(s);
2089
        return 1;
2090
    }
2091
    return 0;
2092
}
2093

    
2094
static void win_chr_add_read_handler(CharDriverState *chr, 
2095
                                    IOCanRWHandler *fd_can_read, 
2096
                                    IOReadHandler *fd_read, void *opaque)
2097
{
2098
    WinCharState *s = chr->opaque;
2099

    
2100
    s->fd_can_read = fd_can_read;
2101
    s->fd_read = fd_read;
2102
    s->win_opaque = opaque;
2103
}
2104

    
2105
static CharDriverState *qemu_chr_open_win(const char *filename)
2106
{
2107
    CharDriverState *chr;
2108
    WinCharState *s;
2109
    
2110
    chr = qemu_mallocz(sizeof(CharDriverState));
2111
    if (!chr)
2112
        return NULL;
2113
    s = qemu_mallocz(sizeof(WinCharState));
2114
    if (!s) {
2115
        free(chr);
2116
        return NULL;
2117
    }
2118
    chr->opaque = s;
2119
    chr->chr_write = win_chr_write;
2120
    chr->chr_add_read_handler = win_chr_add_read_handler;
2121
    chr->chr_close = win_chr_close;
2122

    
2123
    if (win_chr_init(s, filename) < 0) {
2124
        free(s);
2125
        free(chr);
2126
        return NULL;
2127
    }
2128
    return chr;
2129
}
2130

    
2131
static int win_chr_pipe_poll(void *opaque)
2132
{
2133
    WinCharState *s = opaque;
2134
    DWORD size;
2135

    
2136
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2137
    if (size > 0) {
2138
        s->len = size;
2139
        win_chr_read_poll(s);
2140
        win_chr_read(s);
2141
        return 1;
2142
    }
2143
    return 0;
2144
}
2145

    
2146
static int win_chr_pipe_init(WinCharState *s, const char *filename)
2147
{
2148
    OVERLAPPED ov;
2149
    int ret;
2150
    DWORD size;
2151
    char openname[256];
2152
    
2153
    s->fpipe = TRUE;
2154

    
2155
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2156
    if (!s->hsend) {
2157
        fprintf(stderr, "Failed CreateEvent\n");
2158
        goto fail;
2159
    }
2160
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2161
    if (!s->hrecv) {
2162
        fprintf(stderr, "Failed CreateEvent\n");
2163
        goto fail;
2164
    }
2165
    
2166
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2167
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2168
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2169
                              PIPE_WAIT,
2170
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2171
    if (s->hcom == INVALID_HANDLE_VALUE) {
2172
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2173
        s->hcom = NULL;
2174
        goto fail;
2175
    }
2176

    
2177
    ZeroMemory(&ov, sizeof(ov));
2178
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2179
    ret = ConnectNamedPipe(s->hcom, &ov);
2180
    if (ret) {
2181
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2182
        goto fail;
2183
    }
2184

    
2185
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2186
    if (!ret) {
2187
        fprintf(stderr, "Failed GetOverlappedResult\n");
2188
        if (ov.hEvent) {
2189
            CloseHandle(ov.hEvent);
2190
            ov.hEvent = NULL;
2191
        }
2192
        goto fail;
2193
    }
2194

    
2195
    if (ov.hEvent) {
2196
        CloseHandle(ov.hEvent);
2197
        ov.hEvent = NULL;
2198
    }
2199
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2200
    return 0;
2201

    
2202
 fail:
2203
    win_chr_close2(s);
2204
    return -1;
2205
}
2206

    
2207

    
2208
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2209
{
2210
    CharDriverState *chr;
2211
    WinCharState *s;
2212

    
2213
    chr = qemu_mallocz(sizeof(CharDriverState));
2214
    if (!chr)
2215
        return NULL;
2216
    s = qemu_mallocz(sizeof(WinCharState));
2217
    if (!s) {
2218
        free(chr);
2219
        return NULL;
2220
    }
2221
    chr->opaque = s;
2222
    chr->chr_write = win_chr_write;
2223
    chr->chr_add_read_handler = win_chr_add_read_handler;
2224
    chr->chr_close = win_chr_close;
2225
    
2226
    if (win_chr_pipe_init(s, filename) < 0) {
2227
        free(s);
2228
        free(chr);
2229
        return NULL;
2230
    }
2231
    return chr;
2232
}
2233

    
2234
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2235
{
2236
    CharDriverState *chr;
2237
    WinCharState *s;
2238

    
2239
    chr = qemu_mallocz(sizeof(CharDriverState));
2240
    if (!chr)
2241
        return NULL;
2242
    s = qemu_mallocz(sizeof(WinCharState));
2243
    if (!s) {
2244
        free(chr);
2245
        return NULL;
2246
    }
2247
    s->hcom = fd_out;
2248
    chr->opaque = s;
2249
    chr->chr_write = win_chr_write;
2250
    chr->chr_add_read_handler = win_chr_add_read_handler;
2251
    return chr;
2252
}
2253
    
2254
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2255
{
2256
    HANDLE fd_out;
2257
    
2258
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2259
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2260
    if (fd_out == INVALID_HANDLE_VALUE)
2261
        return NULL;
2262

    
2263
    return qemu_chr_open_win_file(fd_out);
2264
}
2265
#endif
2266

    
2267
/***********************************************************/
2268
/* UDP Net console */
2269

    
2270
typedef struct {
2271
    IOCanRWHandler *fd_can_read;
2272
    IOReadHandler *fd_read;
2273
    void *fd_opaque;
2274
    int fd;
2275
    struct sockaddr_in daddr;
2276
    char buf[1024];
2277
    int bufcnt;
2278
    int bufptr;
2279
    int max_size;
2280
} NetCharDriver;
2281

    
2282
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2283
{
2284
    NetCharDriver *s = chr->opaque;
2285

    
2286
    return sendto(s->fd, buf, len, 0,
2287
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2288
}
2289

    
2290
static int udp_chr_read_poll(void *opaque)
2291
{
2292
    CharDriverState *chr = opaque;
2293
    NetCharDriver *s = chr->opaque;
2294

    
2295
    s->max_size = s->fd_can_read(s->fd_opaque);
2296

    
2297
    /* If there were any stray characters in the queue process them
2298
     * first
2299
     */
2300
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2301
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2302
        s->bufptr++;
2303
        s->max_size = s->fd_can_read(s->fd_opaque);
2304
    }
2305
    return s->max_size;
2306
}
2307

    
2308
static void udp_chr_read(void *opaque)
2309
{
2310
    CharDriverState *chr = opaque;
2311
    NetCharDriver *s = chr->opaque;
2312

    
2313
    if (s->max_size == 0)
2314
        return;
2315
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2316
    s->bufptr = s->bufcnt;
2317
    if (s->bufcnt <= 0)
2318
        return;
2319

    
2320
    s->bufptr = 0;
2321
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2322
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2323
        s->bufptr++;
2324
        s->max_size = s->fd_can_read(s->fd_opaque);
2325
    }
2326
}
2327

    
2328
static void udp_chr_add_read_handler(CharDriverState *chr,
2329
                                    IOCanRWHandler *fd_can_read,
2330
                                    IOReadHandler *fd_read, void *opaque)
2331
{
2332
    NetCharDriver *s = chr->opaque;
2333

    
2334
    if (s->fd >= 0) {
2335
        s->fd_can_read = fd_can_read;
2336
        s->fd_read = fd_read;
2337
        s->fd_opaque = opaque;
2338
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2339
                             udp_chr_read, NULL, chr);
2340
    }
2341
}
2342

    
2343
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2344
#ifndef _WIN32
2345
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2346
#endif
2347
int parse_host_src_port(struct sockaddr_in *haddr,
2348
                        struct sockaddr_in *saddr,
2349
                        const char *str);
2350

    
2351
static CharDriverState *qemu_chr_open_udp(const char *def)
2352
{
2353
    CharDriverState *chr = NULL;
2354
    NetCharDriver *s = NULL;
2355
    int fd = -1;
2356
    struct sockaddr_in saddr;
2357

    
2358
    chr = qemu_mallocz(sizeof(CharDriverState));
2359
    if (!chr)
2360
        goto return_err;
2361
    s = qemu_mallocz(sizeof(NetCharDriver));
2362
    if (!s)
2363
        goto return_err;
2364

    
2365
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2366
    if (fd < 0) {
2367
        perror("socket(PF_INET, SOCK_DGRAM)");
2368
        goto return_err;
2369
    }
2370

    
2371
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2372
        printf("Could not parse: %s\n", def);
2373
        goto return_err;
2374
    }
2375

    
2376
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2377
    {
2378
        perror("bind");
2379
        goto return_err;
2380
    }
2381

    
2382
    s->fd = fd;
2383
    s->bufcnt = 0;
2384
    s->bufptr = 0;
2385
    chr->opaque = s;
2386
    chr->chr_write = udp_chr_write;
2387
    chr->chr_add_read_handler = udp_chr_add_read_handler;
2388
    return chr;
2389

    
2390
return_err:
2391
    if (chr)
2392
        free(chr);
2393
    if (s)
2394
        free(s);
2395
    if (fd >= 0)
2396
        closesocket(fd);
2397
    return NULL;
2398
}
2399

    
2400
/***********************************************************/
2401
/* TCP Net console */
2402

    
2403
typedef struct {
2404
    IOCanRWHandler *fd_can_read;
2405
    IOReadHandler *fd_read;
2406
    void *fd_opaque;
2407
    int fd, listen_fd;
2408
    int connected;
2409
    int max_size;
2410
    int do_telnetopt;
2411
    int is_unix;
2412
} TCPCharDriver;
2413

    
2414
static void tcp_chr_accept(void *opaque);
2415

    
2416
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2417
{
2418
    TCPCharDriver *s = chr->opaque;
2419
    if (s->connected) {
2420
        return send_all(s->fd, buf, len);
2421
    } else {
2422
        /* XXX: indicate an error ? */
2423
        return len;
2424
    }
2425
}
2426

    
2427
static int tcp_chr_read_poll(void *opaque)
2428
{
2429
    CharDriverState *chr = opaque;
2430
    TCPCharDriver *s = chr->opaque;
2431
    if (!s->connected)
2432
        return 0;
2433
    if (!s->fd_can_read)
2434
        return 0;
2435
    s->max_size = s->fd_can_read(s->fd_opaque);
2436
    return s->max_size;
2437
}
2438

    
2439
#define IAC 255
2440
#define IAC_BREAK 243
2441
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2442
                                      TCPCharDriver *s,
2443
                                      char *buf, int *size)
2444
{
2445
    /* Handle any telnet client's basic IAC options to satisfy char by
2446
     * char mode with no echo.  All IAC options will be removed from
2447
     * the buf and the do_telnetopt variable will be used to track the
2448
     * state of the width of the IAC information.
2449
     *
2450
     * IAC commands come in sets of 3 bytes with the exception of the
2451
     * "IAC BREAK" command and the double IAC.
2452
     */
2453

    
2454
    int i;
2455
    int j = 0;
2456

    
2457
    for (i = 0; i < *size; i++) {
2458
        if (s->do_telnetopt > 1) {
2459
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2460
                /* Double IAC means send an IAC */
2461
                if (j != i)
2462
                    buf[j] = buf[i];
2463
                j++;
2464
                s->do_telnetopt = 1;
2465
            } else {
2466
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2467
                    /* Handle IAC break commands by sending a serial break */
2468
                    chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2469
                    s->do_telnetopt++;
2470
                }
2471
                s->do_telnetopt++;
2472
            }
2473
            if (s->do_telnetopt >= 4) {
2474
                s->do_telnetopt = 1;
2475
            }
2476
        } else {
2477
            if ((unsigned char)buf[i] == IAC) {
2478
                s->do_telnetopt = 2;
2479
            } else {
2480
                if (j != i)
2481
                    buf[j] = buf[i];
2482
                j++;
2483
            }
2484
        }
2485
    }
2486
    *size = j;
2487
}
2488

    
2489
static void tcp_chr_read(void *opaque)
2490
{
2491
    CharDriverState *chr = opaque;
2492
    TCPCharDriver *s = chr->opaque;
2493
    uint8_t buf[1024];
2494
    int len, size;
2495

    
2496
    if (!s->connected || s->max_size <= 0)
2497
        return;
2498
    len = sizeof(buf);
2499
    if (len > s->max_size)
2500
        len = s->max_size;
2501
    size = recv(s->fd, buf, len, 0);
2502
    if (size == 0) {
2503
        /* connection closed */
2504
        s->connected = 0;
2505
        if (s->listen_fd >= 0) {
2506
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2507
        }
2508
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2509
        closesocket(s->fd);
2510
        s->fd = -1;
2511
    } else if (size > 0) {
2512
        if (s->do_telnetopt)
2513
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2514
        if (size > 0)
2515
            s->fd_read(s->fd_opaque, buf, size);
2516
    }
2517
}
2518

    
2519
static void tcp_chr_add_read_handler(CharDriverState *chr,
2520
                                     IOCanRWHandler *fd_can_read,
2521
                                    IOReadHandler *fd_read, void *opaque)
2522
{
2523
    TCPCharDriver *s = chr->opaque;
2524

    
2525
    s->fd_can_read = fd_can_read;
2526
    s->fd_read = fd_read;
2527
    s->fd_opaque = opaque;
2528
}
2529

    
2530
static void tcp_chr_connect(void *opaque)
2531
{
2532
    CharDriverState *chr = opaque;
2533
    TCPCharDriver *s = chr->opaque;
2534

    
2535
    s->connected = 1;
2536
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2537
                         tcp_chr_read, NULL, chr);
2538
}
2539

    
2540
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2541
static void tcp_chr_telnet_init(int fd)
2542
{
2543
    char buf[3];
2544
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2545
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2546
    send(fd, (char *)buf, 3, 0);
2547
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2548
    send(fd, (char *)buf, 3, 0);
2549
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2550
    send(fd, (char *)buf, 3, 0);
2551
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2552
    send(fd, (char *)buf, 3, 0);
2553
}
2554

    
2555
static void tcp_chr_accept(void *opaque)
2556
{
2557
    CharDriverState *chr = opaque;
2558
    TCPCharDriver *s = chr->opaque;
2559
    struct sockaddr_in saddr;
2560
#ifndef _WIN32
2561
    struct sockaddr_un uaddr;
2562
#endif
2563
    struct sockaddr *addr;
2564
    socklen_t len;
2565
    int fd;
2566

    
2567
    for(;;) {
2568
#ifndef _WIN32
2569
        if (s->is_unix) {
2570
            len = sizeof(uaddr);
2571
            addr = (struct sockaddr *)&uaddr;
2572
        } else
2573
#endif
2574
        {
2575
            len = sizeof(saddr);
2576
            addr = (struct sockaddr *)&saddr;
2577
        }
2578
        fd = accept(s->listen_fd, addr, &len);
2579
        if (fd < 0 && errno != EINTR) {
2580
            return;
2581
        } else if (fd >= 0) {
2582
            if (s->do_telnetopt)
2583
                tcp_chr_telnet_init(fd);
2584
            break;
2585
        }
2586
    }
2587
    socket_set_nonblock(fd);
2588
    s->fd = fd;
2589
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2590
    tcp_chr_connect(chr);
2591
}
2592

    
2593
static void tcp_chr_close(CharDriverState *chr)
2594
{
2595
    TCPCharDriver *s = chr->opaque;
2596
    if (s->fd >= 0)
2597
        closesocket(s->fd);
2598
    if (s->listen_fd >= 0)
2599
        closesocket(s->listen_fd);
2600
    qemu_free(s);
2601
}
2602

    
2603
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2604
                                          int is_telnet,
2605
                                          int is_unix)
2606
{
2607
    CharDriverState *chr = NULL;
2608
    TCPCharDriver *s = NULL;
2609
    int fd = -1, ret, err, val;
2610
    int is_listen = 0;
2611
    int is_waitconnect = 1;
2612
    const char *ptr;
2613
    struct sockaddr_in saddr;
2614
#ifndef _WIN32
2615
    struct sockaddr_un uaddr;
2616
#endif
2617
    struct sockaddr *addr;
2618
    socklen_t addrlen;
2619

    
2620
#ifndef _WIN32
2621
    if (is_unix) {
2622
        addr = (struct sockaddr *)&uaddr;
2623
        addrlen = sizeof(uaddr);
2624
        if (parse_unix_path(&uaddr, host_str) < 0)
2625
            goto fail;
2626
    } else
2627
#endif
2628
    {
2629
        addr = (struct sockaddr *)&saddr;
2630
        addrlen = sizeof(saddr);
2631
        if (parse_host_port(&saddr, host_str) < 0)
2632
            goto fail;
2633
    }
2634

    
2635
    ptr = host_str;
2636
    while((ptr = strchr(ptr,','))) {
2637
        ptr++;
2638
        if (!strncmp(ptr,"server",6)) {
2639
            is_listen = 1;
2640
        } else if (!strncmp(ptr,"nowait",6)) {
2641
            is_waitconnect = 0;
2642
        } else {
2643
            printf("Unknown option: %s\n", ptr);
2644
            goto fail;
2645
        }
2646
    }
2647
    if (!is_listen)
2648
        is_waitconnect = 0;
2649

    
2650
    chr = qemu_mallocz(sizeof(CharDriverState));
2651
    if (!chr)
2652
        goto fail;
2653
    s = qemu_mallocz(sizeof(TCPCharDriver));
2654
    if (!s)
2655
        goto fail;
2656

    
2657
#ifndef _WIN32
2658
    if (is_unix)
2659
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2660
    else
2661
#endif
2662
        fd = socket(PF_INET, SOCK_STREAM, 0);
2663
        
2664
    if (fd < 0) 
2665
        goto fail;
2666

    
2667
    if (!is_waitconnect)
2668
        socket_set_nonblock(fd);
2669

    
2670
    s->connected = 0;
2671
    s->fd = -1;
2672
    s->listen_fd = -1;
2673
    s->is_unix = is_unix;
2674

    
2675
    chr->opaque = s;
2676
    chr->chr_write = tcp_chr_write;
2677
    chr->chr_add_read_handler = tcp_chr_add_read_handler;
2678
    chr->chr_close = tcp_chr_close;
2679

    
2680
    if (is_listen) {
2681
        /* allow fast reuse */
2682
#ifndef _WIN32
2683
        if (is_unix) {
2684
            char path[109];
2685
            strncpy(path, uaddr.sun_path, 108);
2686
            path[108] = 0;
2687
            unlink(path);
2688
        } else
2689
#endif
2690
        {
2691
            val = 1;
2692
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2693
        }
2694
        
2695
        ret = bind(fd, addr, addrlen);
2696
        if (ret < 0)
2697
            goto fail;
2698

    
2699
        ret = listen(fd, 0);
2700
        if (ret < 0)
2701
            goto fail;
2702

    
2703
        s->listen_fd = fd;
2704
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2705
        if (is_telnet)
2706
            s->do_telnetopt = 1;
2707
    } else {
2708
        for(;;) {
2709
            ret = connect(fd, addr, addrlen);
2710
            if (ret < 0) {
2711
                err = socket_error();
2712
                if (err == EINTR || err == EWOULDBLOCK) {
2713
                } else if (err == EINPROGRESS) {
2714
                    break;
2715
                } else {
2716
                    goto fail;
2717
                }
2718
            } else {
2719
                s->connected = 1;
2720
                break;
2721
            }
2722
        }
2723
        s->fd = fd;
2724
        if (s->connected)
2725
            tcp_chr_connect(chr);
2726
        else
2727
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2728
    }
2729
    
2730
    if (is_listen && is_waitconnect) {
2731
        printf("QEMU waiting for connection on: %s\n", host_str);
2732
        tcp_chr_accept(chr);
2733
        socket_set_nonblock(s->listen_fd);
2734
    }
2735

    
2736
    return chr;
2737
 fail:
2738
    if (fd >= 0)
2739
        closesocket(fd);
2740
    qemu_free(s);
2741
    qemu_free(chr);
2742
    return NULL;
2743
}
2744

    
2745
CharDriverState *qemu_chr_open(const char *filename)
2746
{
2747
    const char *p;
2748

    
2749
    if (!strcmp(filename, "vc")) {
2750
        return text_console_init(&display_state);
2751
    } else if (!strcmp(filename, "null")) {
2752
        return qemu_chr_open_null();
2753
    } else 
2754
    if (strstart(filename, "tcp:", &p)) {
2755
        return qemu_chr_open_tcp(p, 0, 0);
2756
    } else
2757
    if (strstart(filename, "telnet:", &p)) {
2758
        return qemu_chr_open_tcp(p, 1, 0);
2759
    } else
2760
    if (strstart(filename, "udp:", &p)) {
2761
        return qemu_chr_open_udp(p);
2762
    } else
2763
#ifndef _WIN32
2764
    if (strstart(filename, "unix:", &p)) {
2765
        return qemu_chr_open_tcp(p, 0, 1);
2766
    } else if (strstart(filename, "file:", &p)) {
2767
        return qemu_chr_open_file_out(p);
2768
    } else if (strstart(filename, "pipe:", &p)) {
2769
        return qemu_chr_open_pipe(p);
2770
    } else if (!strcmp(filename, "pty")) {
2771
        return qemu_chr_open_pty();
2772
    } else if (!strcmp(filename, "stdio")) {
2773
        return qemu_chr_open_stdio();
2774
    } else 
2775
#endif
2776
#if defined(__linux__)
2777
    if (strstart(filename, "/dev/parport", NULL)) {
2778
        return qemu_chr_open_pp(filename);
2779
    } else 
2780
    if (strstart(filename, "/dev/", NULL)) {
2781
        return qemu_chr_open_tty(filename);
2782
    } else 
2783
#endif
2784
#ifdef _WIN32
2785
    if (strstart(filename, "COM", NULL)) {
2786
        return qemu_chr_open_win(filename);
2787
    } else
2788
    if (strstart(filename, "pipe:", &p)) {
2789
        return qemu_chr_open_win_pipe(p);
2790
    } else
2791
    if (strstart(filename, "file:", &p)) {
2792
        return qemu_chr_open_win_file_out(p);
2793
    }
2794
#endif
2795
    {
2796
        return NULL;
2797
    }
2798
}
2799

    
2800
void qemu_chr_close(CharDriverState *chr)
2801
{
2802
    if (chr->chr_close)
2803
        chr->chr_close(chr);
2804
}
2805

    
2806
/***********************************************************/
2807
/* network device redirectors */
2808

    
2809
void hex_dump(FILE *f, const uint8_t *buf, int size)
2810
{
2811
    int len, i, j, c;
2812

    
2813
    for(i=0;i<size;i+=16) {
2814
        len = size - i;
2815
        if (len > 16)
2816
            len = 16;
2817
        fprintf(f, "%08x ", i);
2818
        for(j=0;j<16;j++) {
2819
            if (j < len)
2820
                fprintf(f, " %02x", buf[i+j]);
2821
            else
2822
                fprintf(f, "   ");
2823
        }
2824
        fprintf(f, " ");
2825
        for(j=0;j<len;j++) {
2826
            c = buf[i+j];
2827
            if (c < ' ' || c > '~')
2828
                c = '.';
2829
            fprintf(f, "%c", c);
2830
        }
2831
        fprintf(f, "\n");
2832
    }
2833
}
2834

    
2835
static int parse_macaddr(uint8_t *macaddr, const char *p)
2836
{
2837
    int i;
2838
    for(i = 0; i < 6; i++) {
2839
        macaddr[i] = strtol(p, (char **)&p, 16);
2840
        if (i == 5) {
2841
            if (*p != '\0') 
2842
                return -1;
2843
        } else {
2844
            if (*p != ':') 
2845
                return -1;
2846
            p++;
2847
        }
2848
    }
2849
    return 0;
2850
}
2851

    
2852
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2853
{
2854
    const char *p, *p1;
2855
    int len;
2856
    p = *pp;
2857
    p1 = strchr(p, sep);
2858
    if (!p1)
2859
        return -1;
2860
    len = p1 - p;
2861
    p1++;
2862
    if (buf_size > 0) {
2863
        if (len > buf_size - 1)
2864
            len = buf_size - 1;
2865
        memcpy(buf, p, len);
2866
        buf[len] = '\0';
2867
    }
2868
    *pp = p1;
2869
    return 0;
2870
}
2871

    
2872
int parse_host_src_port(struct sockaddr_in *haddr,
2873
                        struct sockaddr_in *saddr,
2874
                        const char *input_str)
2875
{
2876
    char *str = strdup(input_str);
2877
    char *host_str = str;
2878
    char *src_str;
2879
    char *ptr;
2880

    
2881
    /*
2882
     * Chop off any extra arguments at the end of the string which
2883
     * would start with a comma, then fill in the src port information
2884
     * if it was provided else use the "any address" and "any port".
2885
     */
2886
    if ((ptr = strchr(str,',')))
2887
        *ptr = '\0';
2888

    
2889
    if ((src_str = strchr(input_str,'@'))) {
2890
        *src_str = '\0';
2891
        src_str++;
2892
    }
2893

    
2894
    if (parse_host_port(haddr, host_str) < 0)
2895
        goto fail;
2896

    
2897
    if (!src_str || *src_str == '\0')
2898
        src_str = ":0";
2899

    
2900
    if (parse_host_port(saddr, src_str) < 0)
2901
        goto fail;
2902

    
2903
    free(str);
2904
    return(0);
2905

    
2906
fail:
2907
    free(str);
2908
    return -1;
2909
}
2910

    
2911
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2912
{
2913
    char buf[512];
2914
    struct hostent *he;
2915
    const char *p, *r;
2916
    int port;
2917

    
2918
    p = str;
2919
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2920
        return -1;
2921
    saddr->sin_family = AF_INET;
2922
    if (buf[0] == '\0') {
2923
        saddr->sin_addr.s_addr = 0;
2924
    } else {
2925
        if (isdigit(buf[0])) {
2926
            if (!inet_aton(buf, &saddr->sin_addr))
2927
                return -1;
2928
        } else {
2929
            if ((he = gethostbyname(buf)) == NULL)
2930
                return - 1;
2931
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2932
        }
2933
    }
2934
    port = strtol(p, (char **)&r, 0);
2935
    if (r == p)
2936
        return -1;
2937
    saddr->sin_port = htons(port);
2938
    return 0;
2939
}
2940

    
2941
#ifndef _WIN32
2942
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2943
{
2944
    const char *p;
2945
    int len;
2946

    
2947
    len = MIN(108, strlen(str));
2948
    p = strchr(str, ',');
2949
    if (p)
2950
        len = MIN(len, p - str);
2951

    
2952
    memset(uaddr, 0, sizeof(*uaddr));
2953

    
2954
    uaddr->sun_family = AF_UNIX;
2955
    memcpy(uaddr->sun_path, str, len);
2956

    
2957
    return 0;
2958
}
2959
#endif
2960

    
2961
/* find or alloc a new VLAN */
2962
VLANState *qemu_find_vlan(int id)
2963
{
2964
    VLANState **pvlan, *vlan;
2965
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2966
        if (vlan->id == id)
2967
            return vlan;
2968
    }
2969
    vlan = qemu_mallocz(sizeof(VLANState));
2970
    if (!vlan)
2971
        return NULL;
2972
    vlan->id = id;
2973
    vlan->next = NULL;
2974
    pvlan = &first_vlan;
2975
    while (*pvlan != NULL)
2976
        pvlan = &(*pvlan)->next;
2977
    *pvlan = vlan;
2978
    return vlan;
2979
}
2980

    
2981
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2982
                                      IOReadHandler *fd_read,
2983
                                      IOCanRWHandler *fd_can_read,
2984
                                      void *opaque)
2985
{
2986
    VLANClientState *vc, **pvc;
2987
    vc = qemu_mallocz(sizeof(VLANClientState));
2988
    if (!vc)
2989
        return NULL;
2990
    vc->fd_read = fd_read;
2991
    vc->fd_can_read = fd_can_read;
2992
    vc->opaque = opaque;
2993
    vc->vlan = vlan;
2994

    
2995
    vc->next = NULL;
2996
    pvc = &vlan->first_client;
2997
    while (*pvc != NULL)
2998
        pvc = &(*pvc)->next;
2999
    *pvc = vc;
3000
    return vc;
3001
}
3002

    
3003
int qemu_can_send_packet(VLANClientState *vc1)
3004
{
3005
    VLANState *vlan = vc1->vlan;
3006
    VLANClientState *vc;
3007

    
3008
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3009
        if (vc != vc1) {
3010
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3011
                return 0;
3012
        }
3013
    }
3014
    return 1;
3015
}
3016

    
3017
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3018
{
3019
    VLANState *vlan = vc1->vlan;
3020
    VLANClientState *vc;
3021

    
3022
#if 0
3023
    printf("vlan %d send:\n", vlan->id);
3024
    hex_dump(stdout, buf, size);
3025
#endif
3026
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3027
        if (vc != vc1) {
3028
            vc->fd_read(vc->opaque, buf, size);
3029
        }
3030
    }
3031
}
3032

    
3033
#if defined(CONFIG_SLIRP)
3034

    
3035
/* slirp network adapter */
3036

    
3037
static int slirp_inited;
3038
static VLANClientState *slirp_vc;
3039

    
3040
int slirp_can_output(void)
3041
{
3042
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3043
}
3044

    
3045
void slirp_output(const uint8_t *pkt, int pkt_len)
3046
{
3047
#if 0
3048
    printf("slirp output:\n");
3049
    hex_dump(stdout, pkt, pkt_len);
3050
#endif
3051
    if (!slirp_vc)
3052
        return;
3053
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3054
}
3055

    
3056
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3057
{
3058
#if 0
3059
    printf("slirp input:\n");
3060
    hex_dump(stdout, buf, size);
3061
#endif
3062
    slirp_input(buf, size);
3063
}
3064

    
3065
static int net_slirp_init(VLANState *vlan)
3066
{
3067
    if (!slirp_inited) {
3068
        slirp_inited = 1;
3069
        slirp_init();
3070
    }
3071
    slirp_vc = qemu_new_vlan_client(vlan, 
3072
                                    slirp_receive, NULL, NULL);
3073
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3074
    return 0;
3075
}
3076

    
3077
static void net_slirp_redir(const char *redir_str)
3078
{
3079
    int is_udp;
3080
    char buf[256], *r;
3081
    const char *p;
3082
    struct in_addr guest_addr;
3083
    int host_port, guest_port;
3084
    
3085
    if (!slirp_inited) {
3086
        slirp_inited = 1;
3087
        slirp_init();
3088
    }
3089

    
3090
    p = redir_str;
3091
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3092
        goto fail;
3093
    if (!strcmp(buf, "tcp")) {
3094
        is_udp = 0;
3095
    } else if (!strcmp(buf, "udp")) {
3096
        is_udp = 1;
3097
    } else {
3098
        goto fail;
3099
    }
3100

    
3101
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3102
        goto fail;
3103
    host_port = strtol(buf, &r, 0);
3104
    if (r == buf)
3105
        goto fail;
3106

    
3107
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3108
        goto fail;
3109
    if (buf[0] == '\0') {
3110
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3111
    }
3112
    if (!inet_aton(buf, &guest_addr))
3113
        goto fail;
3114
    
3115
    guest_port = strtol(p, &r, 0);
3116
    if (r == p)
3117
        goto fail;
3118
    
3119
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3120
        fprintf(stderr, "qemu: could not set up redirection\n");
3121
        exit(1);
3122
    }
3123
    return;
3124
 fail:
3125
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3126
    exit(1);
3127
}
3128
    
3129
#ifndef _WIN32
3130

    
3131
char smb_dir[1024];
3132

    
3133
static void smb_exit(void)
3134
{
3135
    DIR *d;
3136
    struct dirent *de;
3137
    char filename[1024];
3138

    
3139
    /* erase all the files in the directory */
3140
    d = opendir(smb_dir);
3141
    for(;;) {
3142
        de = readdir(d);
3143
        if (!de)
3144
            break;
3145
        if (strcmp(de->d_name, ".") != 0 &&
3146
            strcmp(de->d_name, "..") != 0) {
3147
            snprintf(filename, sizeof(filename), "%s/%s", 
3148
                     smb_dir, de->d_name);
3149
            unlink(filename);
3150
        }
3151
    }
3152
    closedir(d);
3153
    rmdir(smb_dir);
3154
}
3155

    
3156
/* automatic user mode samba server configuration */
3157
void net_slirp_smb(const char *exported_dir)
3158
{
3159
    char smb_conf[1024];
3160
    char smb_cmdline[1024];
3161
    FILE *f;
3162

    
3163
    if (!slirp_inited) {
3164
        slirp_inited = 1;
3165
        slirp_init();
3166
    }
3167

    
3168
    /* XXX: better tmp dir construction */
3169
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3170
    if (mkdir(smb_dir, 0700) < 0) {
3171
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3172
        exit(1);
3173
    }
3174
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3175
    
3176
    f = fopen(smb_conf, "w");
3177
    if (!f) {
3178
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3179
        exit(1);
3180
    }
3181
    fprintf(f, 
3182
            "[global]\n"
3183
            "private dir=%s\n"
3184
            "smb ports=0\n"
3185
            "socket address=127.0.0.1\n"
3186
            "pid directory=%s\n"
3187
            "lock directory=%s\n"
3188
            "log file=%s/log.smbd\n"
3189
            "smb passwd file=%s/smbpasswd\n"
3190
            "security = share\n"
3191
            "[qemu]\n"
3192
            "path=%s\n"
3193
            "read only=no\n"
3194
            "guest ok=yes\n",
3195
            smb_dir,
3196
            smb_dir,
3197
            smb_dir,
3198
            smb_dir,
3199
            smb_dir,
3200
            exported_dir
3201
            );
3202
    fclose(f);
3203
    atexit(smb_exit);
3204

    
3205
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3206
             SMBD_COMMAND, smb_conf);
3207
    
3208
    slirp_add_exec(0, smb_cmdline, 4, 139);
3209
}
3210

    
3211
#endif /* !defined(_WIN32) */
3212

    
3213
#endif /* CONFIG_SLIRP */
3214

    
3215
#if !defined(_WIN32)
3216

    
3217
typedef struct TAPState {
3218
    VLANClientState *vc;
3219
    int fd;
3220
} TAPState;
3221

    
3222
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3223
{
3224
    TAPState *s = opaque;
3225
    int ret;
3226
    for(;;) {
3227
        ret = write(s->fd, buf, size);
3228
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3229
        } else {
3230
            break;
3231
        }
3232
    }
3233
}
3234

    
3235
static void tap_send(void *opaque)
3236
{
3237
    TAPState *s = opaque;
3238
    uint8_t buf[4096];
3239
    int size;
3240

    
3241
    size = read(s->fd, buf, sizeof(buf));
3242
    if (size > 0) {
3243
        qemu_send_packet(s->vc, buf, size);
3244
    }
3245
}
3246

    
3247
/* fd support */
3248

    
3249
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3250
{
3251
    TAPState *s;
3252

    
3253
    s = qemu_mallocz(sizeof(TAPState));
3254
    if (!s)
3255
        return NULL;
3256
    s->fd = fd;
3257
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3258
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3259
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3260
    return s;
3261
}
3262

    
3263
#ifdef _BSD
3264
static int tap_open(char *ifname, int ifname_size)
3265
{
3266
    int fd;
3267
    char *dev;
3268
    struct stat s;
3269

    
3270
    fd = open("/dev/tap", O_RDWR);
3271
    if (fd < 0) {
3272
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3273
        return -1;
3274
    }
3275

    
3276
    fstat(fd, &s);
3277
    dev = devname(s.st_rdev, S_IFCHR);
3278
    pstrcpy(ifname, ifname_size, dev);
3279

    
3280
    fcntl(fd, F_SETFL, O_NONBLOCK);
3281
    return fd;
3282
}
3283
#elif defined(__sun__)
3284
static int tap_open(char *ifname, int ifname_size)
3285
{
3286
    fprintf(stderr, "warning: tap_open not yet implemented\n");
3287
    return -1;
3288
}
3289
#else
3290
static int tap_open(char *ifname, int ifname_size)
3291
{
3292
    struct ifreq ifr;
3293
    int fd, ret;
3294
    
3295
    fd = open("/dev/net/tun", O_RDWR);
3296
    if (fd < 0) {
3297
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3298
        return -1;
3299
    }
3300
    memset(&ifr, 0, sizeof(ifr));
3301
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3302
    if (ifname[0] != '\0')
3303
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3304
    else
3305
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3306
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3307
    if (ret != 0) {
3308
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3309
        close(fd);
3310
        return -1;
3311
    }
3312
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3313
    fcntl(fd, F_SETFL, O_NONBLOCK);
3314
    return fd;
3315
}
3316
#endif
3317

    
3318
static int net_tap_init(VLANState *vlan, const char *ifname1,
3319
                        const char *setup_script)
3320
{
3321
    TAPState *s;
3322
    int pid, status, fd;
3323
    char *args[3];
3324
    char **parg;
3325
    char ifname[128];
3326

    
3327
    if (ifname1 != NULL)
3328
        pstrcpy(ifname, sizeof(ifname), ifname1);
3329
    else
3330
        ifname[0] = '\0';
3331
    fd = tap_open(ifname, sizeof(ifname));
3332
    if (fd < 0)
3333
        return -1;
3334

    
3335
    if (!setup_script)
3336
        setup_script = "";
3337
    if (setup_script[0] != '\0') {
3338
        /* try to launch network init script */
3339
        pid = fork();
3340
        if (pid >= 0) {
3341
            if (pid == 0) {
3342
                parg = args;
3343
                *parg++ = (char *)setup_script;
3344
                *parg++ = ifname;
3345
                *parg++ = NULL;
3346
                execv(setup_script, args);
3347
                _exit(1);
3348
            }
3349
            while (waitpid(pid, &status, 0) != pid);
3350
            if (!WIFEXITED(status) ||
3351
                WEXITSTATUS(status) != 0) {
3352
                fprintf(stderr, "%s: could not launch network script\n",
3353
                        setup_script);
3354
                return -1;
3355
            }
3356
        }
3357
    }
3358
    s = net_tap_fd_init(vlan, fd);
3359
    if (!s)
3360
        return -1;
3361
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3362
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3363
    return 0;
3364
}
3365

    
3366
#endif /* !_WIN32 */
3367

    
3368
/* network connection */
3369
typedef struct NetSocketState {
3370
    VLANClientState *vc;
3371
    int fd;
3372
    int state; /* 0 = getting length, 1 = getting data */
3373
    int index;
3374
    int packet_len;
3375
    uint8_t buf[4096];
3376
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3377
} NetSocketState;
3378

    
3379
typedef struct NetSocketListenState {
3380
    VLANState *vlan;
3381
    int fd;
3382
} NetSocketListenState;
3383

    
3384
/* XXX: we consider we can send the whole packet without blocking */
3385
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3386
{
3387
    NetSocketState *s = opaque;
3388
    uint32_t len;
3389
    len = htonl(size);
3390

    
3391
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3392
    send_all(s->fd, buf, size);
3393
}
3394

    
3395
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3396
{
3397
    NetSocketState *s = opaque;
3398
    sendto(s->fd, buf, size, 0, 
3399
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3400
}
3401

    
3402
static void net_socket_send(void *opaque)
3403
{
3404
    NetSocketState *s = opaque;
3405
    int l, size, err;
3406
    uint8_t buf1[4096];
3407
    const uint8_t *buf;
3408

    
3409
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3410
    if (size < 0) {
3411
        err = socket_error();
3412
        if (err != EWOULDBLOCK) 
3413
            goto eoc;
3414
    } else if (size == 0) {
3415
        /* end of connection */
3416
    eoc:
3417
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3418
        closesocket(s->fd);
3419
        return;
3420
    }
3421
    buf = buf1;
3422
    while (size > 0) {
3423
        /* reassemble a packet from the network */
3424
        switch(s->state) {
3425
        case 0:
3426
            l = 4 - s->index;
3427
            if (l > size)
3428
                l = size;
3429
            memcpy(s->buf + s->index, buf, l);
3430
            buf += l;
3431
            size -= l;
3432
            s->index += l;
3433
            if (s->index == 4) {
3434
                /* got length */
3435
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3436
                s->index = 0;
3437
                s->state = 1;
3438
            }
3439
            break;
3440
        case 1:
3441
            l = s->packet_len - s->index;
3442
            if (l > size)
3443
                l = size;
3444
            memcpy(s->buf + s->index, buf, l);
3445
            s->index += l;
3446
            buf += l;
3447
            size -= l;
3448
            if (s->index >= s->packet_len) {
3449
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3450
                s->index = 0;
3451
                s->state = 0;
3452
            }
3453
            break;
3454
        }
3455
    }
3456
}
3457

    
3458
static void net_socket_send_dgram(void *opaque)
3459
{
3460
    NetSocketState *s = opaque;
3461
    int size;
3462

    
3463
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3464
    if (size < 0) 
3465
        return;
3466
    if (size == 0) {
3467
        /* end of connection */
3468
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3469
        return;
3470
    }
3471
    qemu_send_packet(s->vc, s->buf, size);
3472
}
3473

    
3474
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3475
{
3476
    struct ip_mreq imr;
3477
    int fd;
3478
    int val, ret;
3479
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3480
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3481
                inet_ntoa(mcastaddr->sin_addr), 
3482
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3483
        return -1;
3484

    
3485
    }
3486
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3487
    if (fd < 0) {
3488
        perror("socket(PF_INET, SOCK_DGRAM)");
3489
        return -1;
3490
    }
3491

    
3492
    val = 1;
3493
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3494
                   (const char *)&val, sizeof(val));
3495
    if (ret < 0) {
3496
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3497
        goto fail;
3498
    }
3499

    
3500
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3501
    if (ret < 0) {
3502
        perror("bind");
3503
        goto fail;
3504
    }
3505
    
3506
    /* Add host to multicast group */
3507
    imr.imr_multiaddr = mcastaddr->sin_addr;
3508
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3509

    
3510
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3511
                     (const char *)&imr, sizeof(struct ip_mreq));
3512
    if (ret < 0) {
3513
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3514
        goto fail;
3515
    }
3516

    
3517
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3518
    val = 1;
3519
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3520
                   (const char *)&val, sizeof(val));
3521
    if (ret < 0) {
3522
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3523
        goto fail;
3524
    }
3525

    
3526
    socket_set_nonblock(fd);
3527
    return fd;
3528
fail:
3529
    if (fd >= 0) 
3530
        closesocket(fd);
3531
    return -1;
3532
}
3533

    
3534
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3535
                                          int is_connected)
3536
{
3537
    struct sockaddr_in saddr;
3538
    int newfd;
3539
    socklen_t saddr_len;
3540
    NetSocketState *s;
3541

    
3542
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3543
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3544
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3545
     */
3546

    
3547
    if (is_connected) {
3548
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3549
            /* must be bound */
3550
            if (saddr.sin_addr.s_addr==0) {
3551
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3552
                        fd);
3553
                return NULL;
3554
            }
3555
            /* clone dgram socket */
3556
            newfd = net_socket_mcast_create(&saddr);
3557
            if (newfd < 0) {
3558
                /* error already reported by net_socket_mcast_create() */
3559
                close(fd);
3560
                return NULL;
3561
            }
3562
            /* clone newfd to fd, close newfd */
3563
            dup2(newfd, fd);
3564
            close(newfd);
3565
        
3566
        } else {
3567
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3568
                    fd, strerror(errno));
3569
            return NULL;
3570
        }
3571
    }
3572

    
3573
    s = qemu_mallocz(sizeof(NetSocketState));
3574
    if (!s)
3575
        return NULL;
3576
    s->fd = fd;
3577

    
3578
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3579
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3580

    
3581
    /* mcast: save bound address as dst */
3582
    if (is_connected) s->dgram_dst=saddr;
3583

    
3584
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3585
            "socket: fd=%d (%s mcast=%s:%d)", 
3586
            fd, is_connected? "cloned" : "",
3587
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3588
    return s;
3589
}
3590

    
3591
static void net_socket_connect(void *opaque)
3592
{
3593
    NetSocketState *s = opaque;
3594
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3595
}
3596

    
3597
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3598
                                          int is_connected)
3599
{
3600
    NetSocketState *s;
3601
    s = qemu_mallocz(sizeof(NetSocketState));
3602
    if (!s)
3603
        return NULL;
3604
    s->fd = fd;
3605
    s->vc = qemu_new_vlan_client(vlan, 
3606
                                 net_socket_receive, NULL, s);
3607
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3608
             "socket: fd=%d", fd);
3609
    if (is_connected) {
3610
        net_socket_connect(s);
3611
    } else {
3612
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3613
    }
3614
    return s;
3615
}
3616

    
3617
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3618
                                          int is_connected)
3619
{
3620
    int so_type=-1, optlen=sizeof(so_type);
3621

    
3622
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3623
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3624
        return NULL;
3625
    }
3626
    switch(so_type) {
3627
    case SOCK_DGRAM:
3628
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3629
    case SOCK_STREAM:
3630
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3631
    default:
3632
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3633
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3634
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3635
    }
3636
    return NULL;
3637
}
3638

    
3639
static void net_socket_accept(void *opaque)
3640
{
3641
    NetSocketListenState *s = opaque;    
3642
    NetSocketState *s1;
3643
    struct sockaddr_in saddr;
3644
    socklen_t len;
3645
    int fd;
3646

    
3647
    for(;;) {
3648
        len = sizeof(saddr);
3649
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3650
        if (fd < 0 && errno != EINTR) {
3651
            return;
3652
        } else if (fd >= 0) {
3653
            break;
3654
        }
3655
    }
3656
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3657
    if (!s1) {
3658
        closesocket(fd);
3659
    } else {
3660
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3661
                 "socket: connection from %s:%d", 
3662
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3663
    }
3664
}
3665

    
3666
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3667
{
3668
    NetSocketListenState *s;
3669
    int fd, val, ret;
3670
    struct sockaddr_in saddr;
3671

    
3672
    if (parse_host_port(&saddr, host_str) < 0)
3673
        return -1;
3674
    
3675
    s = qemu_mallocz(sizeof(NetSocketListenState));
3676
    if (!s)
3677
        return -1;
3678

    
3679
    fd = socket(PF_INET, SOCK_STREAM, 0);
3680
    if (fd < 0) {
3681
        perror("socket");
3682
        return -1;
3683
    }
3684
    socket_set_nonblock(fd);
3685

    
3686
    /* allow fast reuse */
3687
    val = 1;
3688
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3689
    
3690
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3691
    if (ret < 0) {
3692
        perror("bind");
3693
        return -1;
3694
    }
3695
    ret = listen(fd, 0);
3696
    if (ret < 0) {
3697
        perror("listen");
3698
        return -1;
3699
    }
3700
    s->vlan = vlan;
3701
    s->fd = fd;
3702
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3703
    return 0;
3704
}
3705

    
3706
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3707
{
3708
    NetSocketState *s;
3709
    int fd, connected, ret, err;
3710
    struct sockaddr_in saddr;
3711

    
3712
    if (parse_host_port(&saddr, host_str) < 0)
3713
        return -1;
3714

    
3715
    fd = socket(PF_INET, SOCK_STREAM, 0);
3716
    if (fd < 0) {
3717
        perror("socket");
3718
        return -1;
3719
    }
3720
    socket_set_nonblock(fd);
3721

    
3722
    connected = 0;
3723
    for(;;) {
3724
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3725
        if (ret < 0) {
3726
            err = socket_error();
3727
            if (err == EINTR || err == EWOULDBLOCK) {
3728
            } else if (err == EINPROGRESS) {
3729
                break;
3730
            } else {
3731
                perror("connect");
3732
                closesocket(fd);
3733
                return -1;
3734
            }
3735
        } else {
3736
            connected = 1;
3737
            break;
3738
        }
3739
    }
3740
    s = net_socket_fd_init(vlan, fd, connected);
3741
    if (!s)
3742
        return -1;
3743
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3744
             "socket: connect to %s:%d", 
3745
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3746
    return 0;
3747
}
3748

    
3749
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3750
{
3751
    NetSocketState *s;
3752
    int fd;
3753
    struct sockaddr_in saddr;
3754

    
3755
    if (parse_host_port(&saddr, host_str) < 0)
3756
        return -1;
3757

    
3758

    
3759
    fd = net_socket_mcast_create(&saddr);
3760
    if (fd < 0)
3761
        return -1;
3762

    
3763
    s = net_socket_fd_init(vlan, fd, 0);
3764
    if (!s)
3765
        return -1;
3766

    
3767
    s->dgram_dst = saddr;
3768
    
3769
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3770
             "socket: mcast=%s:%d", 
3771
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3772
    return 0;
3773

    
3774
}
3775

    
3776
static int get_param_value(char *buf, int buf_size,
3777
                           const char *tag, const char *str)
3778
{
3779
    const char *p;
3780
    char *q;
3781
    char option[128];
3782

    
3783
    p = str;
3784
    for(;;) {
3785
        q = option;
3786
        while (*p != '\0' && *p != '=') {
3787
            if ((q - option) < sizeof(option) - 1)
3788
                *q++ = *p;
3789
            p++;
3790
        }
3791
        *q = '\0';
3792
        if (*p != '=')
3793
            break;
3794
        p++;
3795
        if (!strcmp(tag, option)) {
3796
            q = buf;
3797
            while (*p != '\0' && *p != ',') {
3798
                if ((q - buf) < buf_size - 1)
3799
                    *q++ = *p;
3800
                p++;
3801
            }
3802
            *q = '\0';
3803
            return q - buf;
3804
        } else {
3805
            while (*p != '\0' && *p != ',') {
3806
                p++;
3807
            }
3808
        }
3809
        if (*p != ',')
3810
            break;
3811
        p++;
3812
    }
3813
    return 0;
3814
}
3815

    
3816
static int net_client_init(const char *str)
3817
{
3818
    const char *p;
3819
    char *q;
3820
    char device[64];
3821
    char buf[1024];
3822
    int vlan_id, ret;
3823
    VLANState *vlan;
3824

    
3825
    p = str;
3826
    q = device;
3827
    while (*p != '\0' && *p != ',') {
3828
        if ((q - device) < sizeof(device) - 1)
3829
            *q++ = *p;
3830
        p++;
3831
    }
3832
    *q = '\0';
3833
    if (*p == ',')
3834
        p++;
3835
    vlan_id = 0;
3836
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3837
        vlan_id = strtol(buf, NULL, 0);
3838
    }
3839
    vlan = qemu_find_vlan(vlan_id);
3840
    if (!vlan) {
3841
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3842
        return -1;
3843
    }
3844
    if (!strcmp(device, "nic")) {
3845
        NICInfo *nd;
3846
        uint8_t *macaddr;
3847

    
3848
        if (nb_nics >= MAX_NICS) {
3849
            fprintf(stderr, "Too Many NICs\n");
3850
            return -1;
3851
        }
3852
        nd = &nd_table[nb_nics];
3853
        macaddr = nd->macaddr;
3854
        macaddr[0] = 0x52;
3855
        macaddr[1] = 0x54;
3856
        macaddr[2] = 0x00;
3857
        macaddr[3] = 0x12;
3858
        macaddr[4] = 0x34;
3859
        macaddr[5] = 0x56 + nb_nics;
3860

    
3861
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3862
            if (parse_macaddr(macaddr, buf) < 0) {
3863
                fprintf(stderr, "invalid syntax for ethernet address\n");
3864
                return -1;
3865
            }
3866
        }
3867
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3868
            nd->model = strdup(buf);
3869
        }
3870
        nd->vlan = vlan;
3871
        nb_nics++;
3872
        ret = 0;
3873
    } else
3874
    if (!strcmp(device, "none")) {
3875
        /* does nothing. It is needed to signal that no network cards
3876
           are wanted */
3877
        ret = 0;
3878
    } else
3879
#ifdef CONFIG_SLIRP
3880
    if (!strcmp(device, "user")) {
3881
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3882
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3883
        }
3884
        ret = net_slirp_init(vlan);
3885
    } else
3886
#endif
3887
#ifdef _WIN32
3888
    if (!strcmp(device, "tap")) {
3889
        char ifname[64];
3890
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3891
            fprintf(stderr, "tap: no interface name\n");
3892
            return -1;
3893
        }
3894
        ret = tap_win32_init(vlan, ifname);
3895
    } else
3896
#else
3897
    if (!strcmp(device, "tap")) {
3898
        char ifname[64];
3899
        char setup_script[1024];
3900
        int fd;
3901
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3902
            fd = strtol(buf, NULL, 0);
3903
            ret = -1;
3904
            if (net_tap_fd_init(vlan, fd))
3905
                ret = 0;
3906
        } else {
3907
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3908
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3909
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3910
            }
3911
            ret = net_tap_init(vlan, ifname, setup_script);
3912
        }
3913
    } else
3914
#endif
3915
    if (!strcmp(device, "socket")) {
3916
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3917
            int fd;
3918
            fd = strtol(buf, NULL, 0);
3919
            ret = -1;
3920
            if (net_socket_fd_init(vlan, fd, 1))
3921
                ret = 0;
3922
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3923
            ret = net_socket_listen_init(vlan, buf);
3924
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3925
            ret = net_socket_connect_init(vlan, buf);
3926
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3927
            ret = net_socket_mcast_init(vlan, buf);
3928
        } else {
3929
            fprintf(stderr, "Unknown socket options: %s\n", p);
3930
            return -1;
3931
        }
3932
    } else
3933
    {
3934
        fprintf(stderr, "Unknown network device: %s\n", device);
3935
        return -1;
3936
    }
3937
    if (ret < 0) {
3938
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3939
    }
3940
    
3941
    return ret;
3942
}
3943

    
3944
void do_info_network(void)
3945
{
3946
    VLANState *vlan;
3947
    VLANClientState *vc;
3948

    
3949
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3950
        term_printf("VLAN %d devices:\n", vlan->id);
3951
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3952
            term_printf("  %s\n", vc->info_str);
3953
    }
3954
}
3955

    
3956
/* Parse IDE and SCSI disk options */
3957
static int disk_options_init(int num_ide_disks,
3958
                             char ide_disk_options[][DISK_OPTIONS_SIZE],
3959
                             int snapshot,
3960
                             int num_scsi_disks,
3961
                             char scsi_disk_options[][DISK_OPTIONS_SIZE],
3962
                             int cdrom_index,
3963
                             int cyls,
3964
                             int heads,
3965
                             int secs,
3966
                             int translation)
3967
{
3968
    char buf[256];
3969
    char dev_name[64];
3970
    int id, i, j;
3971
    int cdrom_device;
3972
    int ide_cdrom_created = 0;
3973
    int scsi_index;
3974
    scsi_host_adapters temp_adapter;
3975

    
3976
    /* Process any IDE disks/cdroms */
3977
    for (i=0; i< num_ide_disks; i++) {
3978
        for (j=0; j<MAX_DISKS; j++) {
3979
            if (ide_disk_options[j][0] == '\0')
3980
                continue;
3981

    
3982
            if (get_param_value(buf, sizeof(buf),"type",ide_disk_options[j])) {
3983
                if (!strcmp(buf, "disk")) {
3984
                    cdrom_device = 0;
3985
                } else if (!strcmp(buf, "cdrom")) {
3986
                    cdrom_device = 1;
3987
                    ide_cdrom_created = 1;
3988
                } else {
3989
                    fprintf(stderr, "qemu: invalid IDE disk type= value: %s\n", buf);
3990
                    return -1;
3991
                }
3992
            } else {
3993
                cdrom_device = 0;
3994
            }
3995

    
3996
            if (cdrom_device) {
3997
                snprintf(dev_name, sizeof(dev_name), "cdrom%c", i + '0');
3998
            } else {
3999
                snprintf(dev_name, sizeof(dev_name), "hd%c", i + 'a');
4000
            }
4001

    
4002
            if (!(get_param_value(buf, sizeof(buf),"img",ide_disk_options[j]))) {
4003
                fprintf(stderr, "qemu: missing IDE disk img= value.\n");
4004
                return -1;
4005
            }
4006

    
4007
            if (!(bs_table[i] = bdrv_new(dev_name))) {
4008
                fprintf(stderr, "qemu: unable to create new block device for:%s\n",dev_name);
4009
                return -1;
4010
            }
4011

    
4012
            if (cdrom_device) {
4013
                bdrv_set_type_hint(bs_table[i], BDRV_TYPE_CDROM);
4014
            }
4015

    
4016
            if (bdrv_open(bs_table[i], buf, snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
4017
                fprintf(stderr, "qemu: could not open hard disk image: '%s'\n",
4018
                        buf);
4019
                return -1;
4020
            }
4021
            if (i == 0 && cyls != 0) {
4022
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4023
                bdrv_set_translation_hint(bs_table[i], translation);
4024
            }
4025
            ide_disk_options[j][0] = '\0';
4026

    
4027
            if (i == cdrom_index) {
4028
                cdrom_index = -1;
4029
            }
4030
            break; /* finished with this IDE device*/
4031
        }
4032
    }
4033

    
4034
    if (cdrom_index >= 0 && (!ide_cdrom_created)) {
4035
        bs_table[cdrom_index] = bdrv_new("cdrom");
4036
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4037
    }
4038

    
4039
    for(i = 0; i < num_scsi_disks; i++) {
4040

    
4041
#if !defined(TARGET_SPARC) || defined(TARGET_SPARC64)
4042
        temp_adapter = SCSI_LSI_53C895A;
4043
        scsi_hba_lsi++;
4044
#else
4045
        temp_adapter = SCSI_ESP;
4046
#endif
4047

    
4048
        /*Check for sdx= parameter */
4049
        if (get_param_value(buf, sizeof(buf), "sdx", scsi_disk_options[i])) {
4050
            if (buf[0] >= 'a' && buf[0] <= 'g') {
4051
                scsi_index = buf[0] - 'a';
4052
            } else{
4053
                fprintf(stderr, "qemu: sdx= option for SCSI must be one letter from a-g. %s \n",buf);
4054
                exit(1);
4055
            }
4056
        } else {
4057
             scsi_index = 0;
4058
        }
4059

    
4060
        /* Check for SCSI id specified. */
4061
        if (get_param_value(buf, sizeof(buf),"id",scsi_disk_options[i])) {
4062
            id = strtol(buf, NULL, 0);
4063
            if (id < 0 || id > 6) {
4064
                fprintf(stderr, "qemu: SCSI id must be from 0-6: %d\n", id);
4065
                return -1;
4066
            }
4067
            /* Check if id already used */
4068
            for(j = 0; j < MAX_SCSI_DISKS; j++) {
4069
                if (scsi_disks_info[j].device_type != SCSI_NONE &&
4070
                    j != i &&
4071
                    scsi_disks_info[j].adapter == temp_adapter &&
4072
                    scsi_disks_info[j].id == id  ) {
4073
                    fprintf(stderr, "qemu: SCSI id already used: %u\n", id);
4074
                    return -1;
4075
                }
4076
            }
4077
        } else {
4078
            id = -1;
4079
        }
4080
        scsi_disks_info[i].adapter = temp_adapter;
4081
        scsi_disks_info[i].id = id;
4082

    
4083
        if (get_param_value(buf, sizeof(buf),"type",scsi_disk_options[i])) {
4084
            if (!strcmp(buf, "disk")) {
4085
                cdrom_device = 0;
4086
            } else if (!strcmp(buf, "cdrom")) {
4087
                cdrom_device = 1;
4088
            } else {
4089
                fprintf(stderr, "qemu: invalid SCSI disk type= value: %s\n", buf);
4090
                return -1;
4091
            }
4092
        } else {
4093
            cdrom_device = 0;
4094
        }
4095

    
4096
        if (cdrom_device) {
4097
            snprintf(dev_name, sizeof(buf), "cdrom%c", scsi_index + '0');
4098
            scsi_disks_info[scsi_index].device_type = SCSI_CDROM;
4099
        } else {
4100
            snprintf(dev_name, sizeof(buf), "sd%c", scsi_index + 'a');
4101
            scsi_disks_info[scsi_index].device_type = SCSI_DISK;
4102
        }
4103

    
4104
        if (!(bs_scsi_table[scsi_index] = bdrv_new(dev_name))) {
4105
            fprintf(stderr, "qemu: unable to create new block device for:%s\n",dev_name);
4106
            return -1;
4107
        }
4108

    
4109
        /* Get image filename from options and then try to open it */
4110
        if (get_param_value(buf, sizeof(buf),"img",scsi_disk_options[i])) {
4111
            if (bdrv_open(bs_scsi_table[scsi_index], buf, 0) < 0) {
4112
                fprintf(stderr, "qemu: could not open SCSI disk image img='%s'\n",buf);
4113
                return -1;
4114
            }
4115
        } else {
4116
            fprintf(stderr, "qemu: SCSI disk image not specified for sd%c \n", i + 'a');
4117
            return -1;
4118
        }
4119
        if (cdrom_device) {
4120
            bdrv_set_type_hint(bs_scsi_table[scsi_index], BDRV_TYPE_CDROM);
4121
        }
4122
    }
4123

    
4124
    return 0;
4125
}
4126

    
4127

    
4128
/***********************************************************/
4129
/* USB devices */
4130

    
4131
static USBPort *used_usb_ports;
4132
static USBPort *free_usb_ports;
4133

    
4134
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4135
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4136
                            usb_attachfn attach)
4137
{
4138
    port->opaque = opaque;
4139
    port->index = index;
4140
    port->attach = attach;
4141
    port->next = free_usb_ports;
4142
    free_usb_ports = port;
4143
}
4144

    
4145
static int usb_device_add(const char *devname)
4146
{
4147
    const char *p;
4148
    USBDevice *dev;
4149
    USBPort *port;
4150

    
4151
    if (!free_usb_ports)
4152
        return -1;
4153

    
4154
    if (strstart(devname, "host:", &p)) {
4155
        dev = usb_host_device_open(p);
4156
    } else if (!strcmp(devname, "mouse")) {
4157
        dev = usb_mouse_init();
4158
    } else if (!strcmp(devname, "tablet")) {
4159
        dev = usb_tablet_init();
4160
    } else if (strstart(devname, "disk:", &p)) {
4161
        dev = usb_msd_init(p);
4162
    } else {
4163
        return -1;
4164
    }
4165
    if (!dev)
4166
        return -1;
4167

    
4168
    /* Find a USB port to add the device to.  */
4169
    port = free_usb_ports;
4170
    if (!port->next) {
4171
        USBDevice *hub;
4172

    
4173
        /* Create a new hub and chain it on.  */
4174
        free_usb_ports = NULL;
4175
        port->next = used_usb_ports;
4176
        used_usb_ports = port;
4177

    
4178
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4179
        usb_attach(port, hub);
4180
        port = free_usb_ports;
4181
    }
4182

    
4183
    free_usb_ports = port->next;
4184
    port->next = used_usb_ports;
4185
    used_usb_ports = port;
4186
    usb_attach(port, dev);
4187
    return 0;
4188
}
4189

    
4190
static int usb_device_del(const char *devname)
4191
{
4192
    USBPort *port;
4193
    USBPort **lastp;
4194
    USBDevice *dev;
4195
    int bus_num, addr;
4196
    const char *p;
4197

    
4198
    if (!used_usb_ports)
4199
        return -1;
4200

    
4201
    p = strchr(devname, '.');
4202
    if (!p) 
4203
        return -1;
4204
    bus_num = strtoul(devname, NULL, 0);
4205
    addr = strtoul(p + 1, NULL, 0);
4206
    if (bus_num != 0)
4207
        return -1;
4208

    
4209
    lastp = &used_usb_ports;
4210
    port = used_usb_ports;
4211
    while (port && port->dev->addr != addr) {
4212
        lastp = &port->next;
4213
        port = port->next;
4214
    }
4215

    
4216
    if (!port)
4217
        return -1;
4218

    
4219
    dev = port->dev;
4220
    *lastp = port->next;
4221
    usb_attach(port, NULL);
4222
    dev->handle_destroy(dev);
4223
    port->next = free_usb_ports;
4224
    free_usb_ports = port;
4225
    return 0;
4226
}
4227

    
4228
void do_usb_add(const char *devname)
4229
{
4230
    int ret;
4231
    ret = usb_device_add(devname);
4232
    if (ret < 0) 
4233
        term_printf("Could not add USB device '%s'\n", devname);
4234
}
4235

    
4236
void do_usb_del(const char *devname)
4237
{
4238
    int ret;
4239
    ret = usb_device_del(devname);
4240
    if (ret < 0) 
4241
        term_printf("Could not remove USB device '%s'\n", devname);
4242
}
4243

    
4244
void usb_info(void)
4245
{
4246
    USBDevice *dev;
4247
    USBPort *port;
4248
    const char *speed_str;
4249

    
4250
    if (!usb_enabled) {
4251
        term_printf("USB support not enabled\n");
4252
        return;
4253
    }
4254

    
4255
    for (port = used_usb_ports; port; port = port->next) {
4256
        dev = port->dev;
4257
        if (!dev)
4258
            continue;
4259
        switch(dev->speed) {
4260
        case USB_SPEED_LOW: 
4261
            speed_str = "1.5"; 
4262
            break;
4263
        case USB_SPEED_FULL: 
4264
            speed_str = "12"; 
4265
            break;
4266
        case USB_SPEED_HIGH: 
4267
            speed_str = "480"; 
4268
            break;
4269
        default:
4270
            speed_str = "?"; 
4271
            break;
4272
        }
4273
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4274
                    0, dev->addr, speed_str, dev->devname);
4275
    }
4276
}
4277

    
4278
/***********************************************************/
4279
/* pid file */
4280

    
4281
static char *pid_filename;
4282

    
4283
/* Remove PID file. Called on normal exit */
4284

    
4285
static void remove_pidfile(void) 
4286
{
4287
    unlink (pid_filename);
4288
}
4289

    
4290
static void create_pidfile(const char *filename)
4291
{
4292
    struct stat pidstat;
4293
    FILE *f;
4294

    
4295
    /* Try to write our PID to the named file */
4296
    if (stat(filename, &pidstat) < 0) {
4297
        if (errno == ENOENT) {
4298
            if ((f = fopen (filename, "w")) == NULL) {
4299
                perror("Opening pidfile");
4300
                exit(1);
4301
            }
4302
            fprintf(f, "%d\n", getpid());
4303
            fclose(f);
4304
            pid_filename = qemu_strdup(filename);
4305
            if (!pid_filename) {
4306
                fprintf(stderr, "Could not save PID filename");
4307
                exit(1);
4308
            }
4309
            atexit(remove_pidfile);
4310
        }
4311
    } else {
4312
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
4313
                filename);
4314
        exit(1);
4315
    }
4316
}
4317

    
4318
/***********************************************************/
4319
/* dumb display */
4320

    
4321
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4322
{
4323
}
4324

    
4325
static void dumb_resize(DisplayState *ds, int w, int h)
4326
{
4327
}
4328

    
4329
static void dumb_refresh(DisplayState *ds)
4330
{
4331
    vga_hw_update();
4332
}
4333

    
4334
void dumb_display_init(DisplayState *ds)
4335
{
4336
    ds->data = NULL;
4337
    ds->linesize = 0;
4338
    ds->depth = 0;
4339
    ds->dpy_update = dumb_update;
4340
    ds->dpy_resize = dumb_resize;
4341
    ds->dpy_refresh = dumb_refresh;
4342
}
4343

    
4344
/***********************************************************/
4345
/* I/O handling */
4346

    
4347
#define MAX_IO_HANDLERS 64
4348

    
4349
typedef struct IOHandlerRecord {
4350
    int fd;
4351
    IOCanRWHandler *fd_read_poll;
4352
    IOHandler *fd_read;
4353
    IOHandler *fd_write;
4354
    void *opaque;
4355
    /* temporary data */
4356
    struct pollfd *ufd;
4357
    struct IOHandlerRecord *next;
4358
} IOHandlerRecord;
4359

    
4360
static IOHandlerRecord *first_io_handler;
4361

    
4362
/* XXX: fd_read_poll should be suppressed, but an API change is
4363
   necessary in the character devices to suppress fd_can_read(). */
4364
int qemu_set_fd_handler2(int fd, 
4365
                         IOCanRWHandler *fd_read_poll, 
4366
                         IOHandler *fd_read, 
4367
                         IOHandler *fd_write, 
4368
                         void *opaque)
4369
{
4370
    IOHandlerRecord **pioh, *ioh;
4371

    
4372
    if (!fd_read && !fd_write) {
4373
        pioh = &first_io_handler;
4374
        for(;;) {
4375
            ioh = *pioh;
4376
            if (ioh == NULL)
4377
                break;
4378
            if (ioh->fd == fd) {
4379
                *pioh = ioh->next;
4380
                qemu_free(ioh);
4381
                break;
4382
            }
4383
            pioh = &ioh->next;
4384
        }
4385
    } else {
4386
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4387
            if (ioh->fd == fd)
4388
                goto found;
4389
        }
4390
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4391
        if (!ioh)
4392
            return -1;
4393
        ioh->next = first_io_handler;
4394
        first_io_handler = ioh;
4395
    found:
4396
        ioh->fd = fd;
4397
        ioh->fd_read_poll = fd_read_poll;
4398
        ioh->fd_read = fd_read;
4399
        ioh->fd_write = fd_write;
4400
        ioh->opaque = opaque;
4401
    }
4402
    return 0;
4403
}
4404

    
4405
int qemu_set_fd_handler(int fd, 
4406
                        IOHandler *fd_read, 
4407
                        IOHandler *fd_write, 
4408
                        void *opaque)
4409
{
4410
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4411
}
4412

    
4413
/***********************************************************/
4414
/* Polling handling */
4415

    
4416
typedef struct PollingEntry {
4417
    PollingFunc *func;
4418
    void *opaque;
4419
    struct PollingEntry *next;
4420
} PollingEntry;
4421

    
4422
static PollingEntry *first_polling_entry;
4423

    
4424
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4425
{
4426
    PollingEntry **ppe, *pe;
4427
    pe = qemu_mallocz(sizeof(PollingEntry));
4428
    if (!pe)
4429
        return -1;
4430
    pe->func = func;
4431
    pe->opaque = opaque;
4432
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4433
    *ppe = pe;
4434
    return 0;
4435
}
4436

    
4437
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4438
{
4439
    PollingEntry **ppe, *pe;
4440
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4441
        pe = *ppe;
4442
        if (pe->func == func && pe->opaque == opaque) {
4443
            *ppe = pe->next;
4444
            qemu_free(pe);
4445
            break;
4446
        }
4447
    }
4448
}
4449

    
4450
#ifdef _WIN32
4451
/***********************************************************/
4452
/* Wait objects support */
4453
typedef struct WaitObjects {
4454
    int num;
4455
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4456
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4457
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4458
} WaitObjects;
4459

    
4460
static WaitObjects wait_objects = {0};
4461
    
4462
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4463
{
4464
    WaitObjects *w = &wait_objects;
4465

    
4466
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4467
        return -1;
4468
    w->events[w->num] = handle;
4469
    w->func[w->num] = func;
4470
    w->opaque[w->num] = opaque;
4471
    w->num++;
4472
    return 0;
4473
}
4474

    
4475
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4476
{
4477
    int i, found;
4478
    WaitObjects *w = &wait_objects;
4479

    
4480
    found = 0;
4481
    for (i = 0; i < w->num; i++) {
4482
        if (w->events[i] == handle)
4483
            found = 1;
4484
        if (found) {
4485
            w->events[i] = w->events[i + 1];
4486
            w->func[i] = w->func[i + 1];
4487
            w->opaque[i] = w->opaque[i + 1];
4488
        }            
4489
    }
4490
    if (found)
4491
        w->num--;
4492
}
4493
#endif
4494

    
4495
/***********************************************************/
4496
/* savevm/loadvm support */
4497

    
4498
#define IO_BUF_SIZE 32768
4499

    
4500
struct QEMUFile {
4501
    FILE *outfile;
4502
    BlockDriverState *bs;
4503
    int is_file;
4504
    int is_writable;
4505
    int64_t base_offset;
4506
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4507
                           when reading */
4508
    int buf_index;
4509
    int buf_size; /* 0 when writing */
4510
    uint8_t buf[IO_BUF_SIZE];
4511
};
4512

    
4513
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4514
{
4515
    QEMUFile *f;
4516

    
4517
    f = qemu_mallocz(sizeof(QEMUFile));
4518
    if (!f)
4519
        return NULL;
4520
    if (!strcmp(mode, "wb")) {
4521
        f->is_writable = 1;
4522
    } else if (!strcmp(mode, "rb")) {
4523
        f->is_writable = 0;
4524
    } else {
4525
        goto fail;
4526
    }
4527
    f->outfile = fopen(filename, mode);
4528
    if (!f->outfile)
4529
        goto fail;
4530
    f->is_file = 1;
4531
    return f;
4532
 fail:
4533
    if (f->outfile)
4534
        fclose(f->outfile);
4535
    qemu_free(f);
4536
    return NULL;
4537
}
4538

    
4539
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4540
{
4541
    QEMUFile *f;
4542

    
4543
    f = qemu_mallocz(sizeof(QEMUFile));
4544
    if (!f)
4545
        return NULL;
4546
    f->is_file = 0;
4547
    f->bs = bs;
4548
    f->is_writable = is_writable;
4549
    f->base_offset = offset;
4550
    return f;
4551
}
4552

    
4553
void qemu_fflush(QEMUFile *f)
4554
{
4555
    if (!f->is_writable)
4556
        return;
4557
    if (f->buf_index > 0) {
4558
        if (f->is_file) {
4559
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4560
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4561
        } else {
4562
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4563
                        f->buf, f->buf_index);
4564
        }
4565
        f->buf_offset += f->buf_index;
4566
        f->buf_index = 0;
4567
    }
4568
}
4569

    
4570
static void qemu_fill_buffer(QEMUFile *f)
4571
{
4572
    int len;
4573

    
4574
    if (f->is_writable)
4575
        return;
4576
    if (f->is_file) {
4577
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4578
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4579
        if (len < 0)
4580
            len = 0;
4581
    } else {
4582
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4583
                         f->buf, IO_BUF_SIZE);
4584
        if (len < 0)
4585
            len = 0;
4586
    }
4587
    f->buf_index = 0;
4588
    f->buf_size = len;
4589
    f->buf_offset += len;
4590
}
4591

    
4592
void qemu_fclose(QEMUFile *f)
4593
{
4594
    if (f->is_writable)
4595
        qemu_fflush(f);
4596
    if (f->is_file) {
4597
        fclose(f->outfile);
4598
    }
4599
    qemu_free(f);
4600
}
4601

    
4602
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4603
{
4604
    int l;
4605
    while (size > 0) {
4606
        l = IO_BUF_SIZE - f->buf_index;
4607
        if (l > size)
4608
            l = size;
4609
        memcpy(f->buf + f->buf_index, buf, l);
4610
        f->buf_index += l;
4611
        buf += l;
4612
        size -= l;
4613
        if (f->buf_index >= IO_BUF_SIZE)
4614
            qemu_fflush(f);
4615
    }
4616
}
4617

    
4618
void qemu_put_byte(QEMUFile *f, int v)
4619
{
4620
    f->buf[f->buf_index++] = v;
4621
    if (f->buf_index >= IO_BUF_SIZE)
4622
        qemu_fflush(f);
4623
}
4624

    
4625
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4626
{
4627
    int size, l;
4628

    
4629
    size = size1;
4630
    while (size > 0) {
4631
        l = f->buf_size - f->buf_index;
4632
        if (l == 0) {
4633
            qemu_fill_buffer(f);
4634
            l = f->buf_size - f->buf_index;
4635
            if (l == 0)
4636
                break;
4637
        }
4638
        if (l > size)
4639
            l = size;
4640
        memcpy(buf, f->buf + f->buf_index, l);
4641
        f->buf_index += l;
4642
        buf += l;
4643
        size -= l;
4644
    }
4645
    return size1 - size;
4646
}
4647

    
4648
int qemu_get_byte(QEMUFile *f)
4649
{
4650
    if (f->buf_index >= f->buf_size) {
4651
        qemu_fill_buffer(f);
4652
        if (f->buf_index >= f->buf_size)
4653
            return 0;
4654
    }
4655
    return f->buf[f->buf_index++];
4656
}
4657

    
4658
int64_t qemu_ftell(QEMUFile *f)
4659
{
4660
    return f->buf_offset - f->buf_size + f->buf_index;
4661
}
4662

    
4663
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4664
{
4665
    if (whence == SEEK_SET) {
4666
        /* nothing to do */
4667
    } else if (whence == SEEK_CUR) {
4668
        pos += qemu_ftell(f);
4669
    } else {
4670
        /* SEEK_END not supported */
4671
        return -1;
4672
    }
4673
    if (f->is_writable) {
4674
        qemu_fflush(f);
4675
        f->buf_offset = pos;
4676
    } else {
4677
        f->buf_offset = pos;
4678
        f->buf_index = 0;
4679
        f->buf_size = 0;
4680
    }
4681
    return pos;
4682
}
4683

    
4684
void qemu_put_be16(QEMUFile *f, unsigned int v)
4685
{
4686
    qemu_put_byte(f, v >> 8);
4687
    qemu_put_byte(f, v);
4688
}
4689

    
4690
void qemu_put_be32(QEMUFile *f, unsigned int v)
4691
{
4692
    qemu_put_byte(f, v >> 24);
4693
    qemu_put_byte(f, v >> 16);
4694
    qemu_put_byte(f, v >> 8);
4695
    qemu_put_byte(f, v);
4696
}
4697

    
4698
void qemu_put_be64(QEMUFile *f, uint64_t v)
4699
{
4700
    qemu_put_be32(f, v >> 32);
4701
    qemu_put_be32(f, v);
4702
}
4703

    
4704
unsigned int qemu_get_be16(QEMUFile *f)
4705
{
4706
    unsigned int v;
4707
    v = qemu_get_byte(f) << 8;
4708
    v |= qemu_get_byte(f);
4709
    return v;
4710
}
4711

    
4712
unsigned int qemu_get_be32(QEMUFile *f)
4713
{
4714
    unsigned int v;
4715
    v = qemu_get_byte(f) << 24;
4716
    v |= qemu_get_byte(f) << 16;
4717
    v |= qemu_get_byte(f) << 8;
4718
    v |= qemu_get_byte(f);
4719
    return v;
4720
}
4721

    
4722
uint64_t qemu_get_be64(QEMUFile *f)
4723
{
4724
    uint64_t v;
4725
    v = (uint64_t)qemu_get_be32(f) << 32;
4726
    v |= qemu_get_be32(f);
4727
    return v;
4728
}
4729

    
4730
typedef struct SaveStateEntry {
4731
    char idstr[256];
4732
    int instance_id;
4733
    int version_id;
4734
    SaveStateHandler *save_state;
4735
    LoadStateHandler *load_state;
4736
    void *opaque;
4737
    struct SaveStateEntry *next;
4738
} SaveStateEntry;
4739

    
4740
static SaveStateEntry *first_se;
4741

    
4742
int register_savevm(const char *idstr, 
4743
                    int instance_id, 
4744
                    int version_id,
4745
                    SaveStateHandler *save_state,
4746
                    LoadStateHandler *load_state,
4747
                    void *opaque)
4748
{
4749
    SaveStateEntry *se, **pse;
4750

    
4751
    se = qemu_malloc(sizeof(SaveStateEntry));
4752
    if (!se)
4753
        return -1;
4754
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4755
    se->instance_id = instance_id;
4756
    se->version_id = version_id;
4757
    se->save_state = save_state;
4758
    se->load_state = load_state;
4759
    se->opaque = opaque;
4760
    se->next = NULL;
4761

    
4762
    /* add at the end of list */
4763
    pse = &first_se;
4764
    while (*pse != NULL)
4765
        pse = &(*pse)->next;
4766
    *pse = se;
4767
    return 0;
4768
}
4769

    
4770
#define QEMU_VM_FILE_MAGIC   0x5145564d
4771
#define QEMU_VM_FILE_VERSION 0x00000002
4772

    
4773
int qemu_savevm_state(QEMUFile *f)
4774
{
4775
    SaveStateEntry *se;
4776
    int len, ret;
4777
    int64_t cur_pos, len_pos, total_len_pos;
4778

    
4779
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4780
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4781
    total_len_pos = qemu_ftell(f);
4782
    qemu_put_be64(f, 0); /* total size */
4783

    
4784
    for(se = first_se; se != NULL; se = se->next) {
4785
        /* ID string */
4786
        len = strlen(se->idstr);
4787
        qemu_put_byte(f, len);
4788
        qemu_put_buffer(f, se->idstr, len);
4789

    
4790
        qemu_put_be32(f, se->instance_id);
4791
        qemu_put_be32(f, se->version_id);
4792

    
4793
        /* record size: filled later */
4794
        len_pos = qemu_ftell(f);
4795
        qemu_put_be32(f, 0);
4796
        
4797
        se->save_state(f, se->opaque);
4798

    
4799
        /* fill record size */
4800
        cur_pos = qemu_ftell(f);
4801
        len = cur_pos - len_pos - 4;
4802
        qemu_fseek(f, len_pos, SEEK_SET);
4803
        qemu_put_be32(f, len);
4804
        qemu_fseek(f, cur_pos, SEEK_SET);
4805
    }
4806
    cur_pos = qemu_ftell(f);
4807
    qemu_fseek(f, total_len_pos, SEEK_SET);
4808
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4809
    qemu_fseek(f, cur_pos, SEEK_SET);
4810

    
4811
    ret = 0;
4812
    return ret;
4813
}
4814

    
4815
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4816
{
4817
    SaveStateEntry *se;
4818

    
4819
    for(se = first_se; se != NULL; se = se->next) {
4820
        if (!strcmp(se->idstr, idstr) && 
4821
            instance_id == se->instance_id)
4822
            return se;
4823
    }
4824
    return NULL;
4825
}
4826

    
4827
int qemu_loadvm_state(QEMUFile *f)
4828
{
4829
    SaveStateEntry *se;
4830
    int len, ret, instance_id, record_len, version_id;
4831
    int64_t total_len, end_pos, cur_pos;
4832
    unsigned int v;
4833
    char idstr[256];
4834
    
4835
    v = qemu_get_be32(f);
4836
    if (v != QEMU_VM_FILE_MAGIC)
4837
        goto fail;
4838
    v = qemu_get_be32(f);
4839
    if (v != QEMU_VM_FILE_VERSION) {
4840
    fail:
4841
        ret = -1;
4842
        goto the_end;
4843
    }
4844
    total_len = qemu_get_be64(f);
4845
    end_pos = total_len + qemu_ftell(f);
4846
    for(;;) {
4847
        if (qemu_ftell(f) >= end_pos)
4848
            break;
4849
        len = qemu_get_byte(f);
4850
        qemu_get_buffer(f, idstr, len);
4851
        idstr[len] = '\0';
4852
        instance_id = qemu_get_be32(f);
4853
        version_id = qemu_get_be32(f);
4854
        record_len = qemu_get_be32(f);
4855
#if 0
4856
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4857
               idstr, instance_id, version_id, record_len);
4858
#endif
4859
        cur_pos = qemu_ftell(f);
4860
        se = find_se(idstr, instance_id);
4861
        if (!se) {
4862
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4863
                    instance_id, idstr);
4864
        } else {
4865
            ret = se->load_state(f, se->opaque, version_id);
4866
            if (ret < 0) {
4867
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4868
                        instance_id, idstr);
4869
            }
4870
        }
4871
        /* always seek to exact end of record */
4872
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4873
    }
4874
    ret = 0;
4875
 the_end:
4876
    return ret;
4877
}
4878

    
4879
/* device can contain snapshots */
4880
static int bdrv_can_snapshot(BlockDriverState *bs)
4881
{
4882
    return (bs &&
4883
            !bdrv_is_removable(bs) &&
4884
            !bdrv_is_read_only(bs));
4885
}
4886

    
4887
/* device must be snapshots in order to have a reliable snapshot */
4888
static int bdrv_has_snapshot(BlockDriverState *bs)
4889
{
4890
    return (bs &&
4891
            !bdrv_is_removable(bs) &&
4892
            !bdrv_is_read_only(bs));
4893
}
4894

    
4895
static BlockDriverState *get_bs_snapshots(void)
4896
{
4897
    BlockDriverState *bs;
4898
    int i;
4899

    
4900
    if (bs_snapshots)
4901
        return bs_snapshots;
4902
    for(i = 0; i <= MAX_DISKS; i++) {
4903
        bs = bs_table[i];
4904
        if (bdrv_can_snapshot(bs))
4905
            goto ok;
4906
    }
4907
    return NULL;
4908
 ok:
4909
    bs_snapshots = bs;
4910
    return bs;
4911
}
4912

    
4913
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4914
                              const char *name)
4915
{
4916
    QEMUSnapshotInfo *sn_tab, *sn;
4917
    int nb_sns, i, ret;
4918
    
4919
    ret = -ENOENT;
4920
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4921
    if (nb_sns < 0)
4922
        return ret;
4923
    for(i = 0; i < nb_sns; i++) {
4924
        sn = &sn_tab[i];
4925
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4926
            *sn_info = *sn;
4927
            ret = 0;
4928
            break;
4929
        }
4930
    }
4931
    qemu_free(sn_tab);
4932
    return ret;
4933
}
4934

    
4935
void do_savevm(const char *name)
4936
{
4937
    BlockDriverState *bs, *bs1;
4938
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4939
    int must_delete, ret, i;
4940
    BlockDriverInfo bdi1, *bdi = &bdi1;
4941
    QEMUFile *f;
4942
    int saved_vm_running;
4943
#ifdef _WIN32
4944
    struct _timeb tb;
4945
#else
4946
    struct timeval tv;
4947
#endif
4948

    
4949
    bs = get_bs_snapshots();
4950
    if (!bs) {
4951
        term_printf("No block device can accept snapshots\n");
4952
        return;
4953
    }
4954

    
4955
    /* ??? Should this occur after vm_stop?  */
4956
    qemu_aio_flush();
4957

    
4958
    saved_vm_running = vm_running;
4959
    vm_stop(0);
4960
    
4961
    must_delete = 0;
4962
    if (name) {
4963
        ret = bdrv_snapshot_find(bs, old_sn, name);
4964
        if (ret >= 0) {
4965
            must_delete = 1;
4966
        }
4967
    }
4968
    memset(sn, 0, sizeof(*sn));
4969
    if (must_delete) {
4970
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4971
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4972
    } else {
4973
        if (name)
4974
            pstrcpy(sn->name, sizeof(sn->name), name);
4975
    }
4976

    
4977
    /* fill auxiliary fields */
4978
#ifdef _WIN32
4979
    _ftime(&tb);
4980
    sn->date_sec = tb.time;
4981
    sn->date_nsec = tb.millitm * 1000000;
4982
#else
4983
    gettimeofday(&tv, NULL);
4984
    sn->date_sec = tv.tv_sec;
4985
    sn->date_nsec = tv.tv_usec * 1000;
4986
#endif
4987
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4988
    
4989
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4990
        term_printf("Device %s does not support VM state snapshots\n",
4991
                    bdrv_get_device_name(bs));
4992
        goto the_end;
4993
    }
4994
    
4995
    /* save the VM state */
4996
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4997
    if (!f) {
4998
        term_printf("Could not open VM state file\n");
4999
        goto the_end;
5000
    }
5001
    ret = qemu_savevm_state(f);
5002
    sn->vm_state_size = qemu_ftell(f);
5003
    qemu_fclose(f);
5004