Statistics
| Branch: | Revision:

root / vl.c @ 26a76461

History | View | Annotate | Download (154.5 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2005 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

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

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

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

    
73
#include "qemu_socket.h"
74

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

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

    
86
#include "disas.h"
87

    
88
#include "exec-all.h"
89

    
90
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
91

    
92
//#define DEBUG_UNUSED_IOPORT
93
//#define DEBUG_IOPORT
94

    
95
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
96

    
97
#ifdef TARGET_PPC
98
#define DEFAULT_RAM_SIZE 144
99
#else
100
#define DEFAULT_RAM_SIZE 128
101
#endif
102
/* in ms */
103
#define GUI_REFRESH_INTERVAL 30
104

    
105
/* Max number of USB devices that can be specified on the commandline.  */
106
#define MAX_USB_CMDLINE 8
107

    
108
/* XXX: use a two level table to limit memory usage */
109
#define MAX_IOPORTS 65536
110

    
111
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
112
char phys_ram_file[1024];
113
void *ioport_opaque[MAX_IOPORTS];
114
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
115
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
116
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
117
int vga_ram_size;
118
int bios_size;
119
static DisplayState display_state;
120
int nographic;
121
const char* keyboard_layout = NULL;
122
int64_t ticks_per_sec;
123
int boot_device = 'c';
124
int ram_size;
125
int pit_min_timer_count = 0;
126
int nb_nics;
127
NICInfo nd_table[MAX_NICS];
128
QEMUTimer *gui_timer;
129
int vm_running;
130
int rtc_utc = 1;
131
int cirrus_vga_enabled = 1;
132
#ifdef TARGET_SPARC
133
int graphic_width = 1024;
134
int graphic_height = 768;
135
#else
136
int graphic_width = 800;
137
int graphic_height = 600;
138
#endif
139
int graphic_depth = 15;
140
int full_screen = 0;
141
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
142
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
143
#ifdef TARGET_I386
144
int win2k_install_hack = 0;
145
#endif
146
int usb_enabled = 0;
147
static VLANState *first_vlan;
148
int smp_cpus = 1;
149
int vnc_display = -1;
150
#if defined(TARGET_SPARC)
151
#define MAX_CPUS 16
152
#elif defined(TARGET_I386)
153
#define MAX_CPUS 255
154
#else
155
#define MAX_CPUS 1
156
#endif
157
int acpi_enabled = 1;
158
int fd_bootchk = 1;
159

    
160
/***********************************************************/
161
/* x86 ISA bus support */
162

    
163
target_phys_addr_t isa_mem_base = 0;
164
PicState2 *isa_pic;
165

    
166
uint32_t default_ioport_readb(void *opaque, uint32_t address)
167
{
168
#ifdef DEBUG_UNUSED_IOPORT
169
    fprintf(stderr, "inb: port=0x%04x\n", address);
170
#endif
171
    return 0xff;
172
}
173

    
174
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
175
{
176
#ifdef DEBUG_UNUSED_IOPORT
177
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
178
#endif
179
}
180

    
181
/* default is to make two byte accesses */
182
uint32_t default_ioport_readw(void *opaque, uint32_t address)
183
{
184
    uint32_t data;
185
    data = ioport_read_table[0][address](ioport_opaque[address], address);
186
    address = (address + 1) & (MAX_IOPORTS - 1);
187
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
188
    return data;
189
}
190

    
191
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
192
{
193
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
194
    address = (address + 1) & (MAX_IOPORTS - 1);
195
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
196
}
197

    
198
uint32_t default_ioport_readl(void *opaque, uint32_t address)
199
{
200
#ifdef DEBUG_UNUSED_IOPORT
201
    fprintf(stderr, "inl: port=0x%04x\n", address);
202
#endif
203
    return 0xffffffff;
204
}
205

    
206
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
207
{
208
#ifdef DEBUG_UNUSED_IOPORT
209
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
210
#endif
211
}
212

    
213
void init_ioports(void)
214
{
215
    int i;
216

    
217
    for(i = 0; i < MAX_IOPORTS; i++) {
218
        ioport_read_table[0][i] = default_ioport_readb;
219
        ioport_write_table[0][i] = default_ioport_writeb;
220
        ioport_read_table[1][i] = default_ioport_readw;
221
        ioport_write_table[1][i] = default_ioport_writew;
222
        ioport_read_table[2][i] = default_ioport_readl;
223
        ioport_write_table[2][i] = default_ioport_writel;
224
    }
225
}
226

    
227
/* size is the word size in byte */
228
int register_ioport_read(int start, int length, int size, 
229
                         IOPortReadFunc *func, void *opaque)
230
{
231
    int i, bsize;
232

    
233
    if (size == 1) {
234
        bsize = 0;
235
    } else if (size == 2) {
236
        bsize = 1;
237
    } else if (size == 4) {
238
        bsize = 2;
239
    } else {
240
        hw_error("register_ioport_read: invalid size");
241
        return -1;
242
    }
243
    for(i = start; i < start + length; i += size) {
244
        ioport_read_table[bsize][i] = func;
245
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
246
            hw_error("register_ioport_read: invalid opaque");
247
        ioport_opaque[i] = opaque;
248
    }
249
    return 0;
250
}
251

    
252
/* size is the word size in byte */
253
int register_ioport_write(int start, int length, int size, 
254
                          IOPortWriteFunc *func, void *opaque)
255
{
256
    int i, bsize;
257

    
258
    if (size == 1) {
259
        bsize = 0;
260
    } else if (size == 2) {
261
        bsize = 1;
262
    } else if (size == 4) {
263
        bsize = 2;
264
    } else {
265
        hw_error("register_ioport_write: invalid size");
266
        return -1;
267
    }
268
    for(i = start; i < start + length; i += size) {
269
        ioport_write_table[bsize][i] = func;
270
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
271
            hw_error("register_ioport_read: invalid opaque");
272
        ioport_opaque[i] = opaque;
273
    }
274
    return 0;
275
}
276

    
277
void isa_unassign_ioport(int start, int length)
278
{
279
    int i;
280

    
281
    for(i = start; i < start + length; i++) {
282
        ioport_read_table[0][i] = default_ioport_readb;
283
        ioport_read_table[1][i] = default_ioport_readw;
284
        ioport_read_table[2][i] = default_ioport_readl;
285

    
286
        ioport_write_table[0][i] = default_ioport_writeb;
287
        ioport_write_table[1][i] = default_ioport_writew;
288
        ioport_write_table[2][i] = default_ioport_writel;
289
    }
290
}
291

    
292
/***********************************************************/
293

    
294
void pstrcpy(char *buf, int buf_size, const char *str)
295
{
296
    int c;
297
    char *q = buf;
298

    
299
    if (buf_size <= 0)
300
        return;
301

    
302
    for(;;) {
303
        c = *str++;
304
        if (c == 0 || q >= buf + buf_size - 1)
305
            break;
306
        *q++ = c;
307
    }
308
    *q = '\0';
309
}
310

    
311
/* strcat and truncate. */
312
char *pstrcat(char *buf, int buf_size, const char *s)
313
{
314
    int len;
315
    len = strlen(buf);
316
    if (len < buf_size) 
317
        pstrcpy(buf + len, buf_size - len, s);
318
    return buf;
319
}
320

    
321
int strstart(const char *str, const char *val, const char **ptr)
322
{
323
    const char *p, *q;
324
    p = str;
325
    q = val;
326
    while (*q != '\0') {
327
        if (*p != *q)
328
            return 0;
329
        p++;
330
        q++;
331
    }
332
    if (ptr)
333
        *ptr = p;
334
    return 1;
335
}
336

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

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

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

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

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

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

    
421
/***********************************************************/
422
void hw_error(const char *fmt, ...)
423
{
424
    va_list ap;
425
    CPUState *env;
426

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

    
443
/***********************************************************/
444
/* keyboard/mouse */
445

    
446
static QEMUPutKBDEvent *qemu_put_kbd_event;
447
static void *qemu_put_kbd_event_opaque;
448
static QEMUPutMouseEvent *qemu_put_mouse_event;
449
static void *qemu_put_mouse_event_opaque;
450
static int qemu_put_mouse_event_absolute;
451

    
452
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
453
{
454
    qemu_put_kbd_event_opaque = opaque;
455
    qemu_put_kbd_event = func;
456
}
457

    
458
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
459
{
460
    qemu_put_mouse_event_opaque = opaque;
461
    qemu_put_mouse_event = func;
462
    qemu_put_mouse_event_absolute = absolute;
463
}
464

    
465
void kbd_put_keycode(int keycode)
466
{
467
    if (qemu_put_kbd_event) {
468
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
469
    }
470
}
471

    
472
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
473
{
474
    if (qemu_put_mouse_event) {
475
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
476
                             dx, dy, dz, buttons_state);
477
    }
478
}
479

    
480
int kbd_mouse_is_absolute(void)
481
{
482
    return qemu_put_mouse_event_absolute;
483
}
484

    
485
/***********************************************************/
486
/* timers */
487

    
488
#if defined(__powerpc__)
489

    
490
static inline uint32_t get_tbl(void) 
491
{
492
    uint32_t tbl;
493
    asm volatile("mftb %0" : "=r" (tbl));
494
    return tbl;
495
}
496

    
497
static inline uint32_t get_tbu(void) 
498
{
499
        uint32_t tbl;
500
        asm volatile("mftbu %0" : "=r" (tbl));
501
        return tbl;
502
}
503

    
504
int64_t cpu_get_real_ticks(void)
505
{
506
    uint32_t l, h, h1;
507
    /* NOTE: we test if wrapping has occurred */
508
    do {
509
        h = get_tbu();
510
        l = get_tbl();
511
        h1 = get_tbu();
512
    } while (h != h1);
513
    return ((int64_t)h << 32) | l;
514
}
515

    
516
#elif defined(__i386__)
517

    
518
int64_t cpu_get_real_ticks(void)
519
{
520
#ifdef _WIN32
521
    LARGE_INTEGER ti;
522
    QueryPerformanceCounter(&ti);
523
    return ti.QuadPart;
524
#else
525
    int64_t val;
526
    asm volatile ("rdtsc" : "=A" (val));
527
    return val;
528
#endif
529
}
530

    
531
#elif defined(__x86_64__)
532

    
533
int64_t cpu_get_real_ticks(void)
534
{
535
    uint32_t low,high;
536
    int64_t val;
537
    asm volatile("rdtsc" : "=a" (low), "=d" (high));
538
    val = high;
539
    val <<= 32;
540
    val |= low;
541
    return val;
542
}
543

    
544
#elif defined(__ia64)
545

    
546
int64_t cpu_get_real_ticks(void)
547
{
548
        int64_t val;
549
        asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
550
        return val;
551
}
552

    
553
#elif defined(__s390__)
554

    
555
int64_t cpu_get_real_ticks(void)
556
{
557
    int64_t val;
558
    asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
559
    return val;
560
}
561

    
562
#elif defined(__sparc__) && defined(HOST_SOLARIS)
563

    
564
uint64_t cpu_get_real_ticks (void)
565
{
566
#if     defined(_LP64)
567
        uint64_t        rval;
568
        asm volatile("rd %%tick,%0" : "=r"(rval));
569
        return rval;
570
#else
571
        union {
572
                uint64_t i64;
573
                struct {
574
                        uint32_t high;
575
                        uint32_t low;
576
                }       i32;
577
        } rval;
578
        asm volatile("rd %%tick,%1; srlx %1,32,%0"
579
                : "=r"(rval.i32.high), "=r"(rval.i32.low));
580
        return rval.i64;
581
#endif
582
}
583

    
584
#else
585
#error unsupported CPU
586
#endif
587

    
588
static int64_t cpu_ticks_prev;
589
static int64_t cpu_ticks_offset;
590
static int cpu_ticks_enabled;
591

    
592
static inline int64_t cpu_get_ticks(void)
593
{
594
    if (!cpu_ticks_enabled) {
595
        return cpu_ticks_offset;
596
    } else {
597
        int64_t ticks;
598
        ticks = cpu_get_real_ticks();
599
        if (cpu_ticks_prev > ticks) {
600
            /* Note: non increasing ticks may happen if the host uses
601
               software suspend */
602
            cpu_ticks_offset += cpu_ticks_prev - ticks;
603
        }
604
        cpu_ticks_prev = ticks;
605
        return ticks + cpu_ticks_offset;
606
    }
607
}
608

    
609
/* enable cpu_get_ticks() */
610
void cpu_enable_ticks(void)
611
{
612
    if (!cpu_ticks_enabled) {
613
        cpu_ticks_offset -= cpu_get_real_ticks();
614
        cpu_ticks_enabled = 1;
615
    }
616
}
617

    
618
/* disable cpu_get_ticks() : the clock is stopped. You must not call
619
   cpu_get_ticks() after that.  */
620
void cpu_disable_ticks(void)
621
{
622
    if (cpu_ticks_enabled) {
623
        cpu_ticks_offset = cpu_get_ticks();
624
        cpu_ticks_enabled = 0;
625
    }
626
}
627

    
628
#ifdef _WIN32
629
void cpu_calibrate_ticks(void)
630
{
631
    LARGE_INTEGER freq;
632
    int ret;
633

    
634
    ret = QueryPerformanceFrequency(&freq);
635
    if (ret == 0) {
636
        fprintf(stderr, "Could not calibrate ticks\n");
637
        exit(1);
638
    }
639
    ticks_per_sec = freq.QuadPart;
640
}
641

    
642
#else
643
static int64_t get_clock(void)
644
{
645
    struct timeval tv;
646
    gettimeofday(&tv, NULL);
647
    return tv.tv_sec * 1000000LL + tv.tv_usec;
648
}
649

    
650
void cpu_calibrate_ticks(void)
651
{
652
    int64_t usec, ticks;
653

    
654
    usec = get_clock();
655
    ticks = cpu_get_real_ticks();
656
    usleep(50 * 1000);
657
    usec = get_clock() - usec;
658
    ticks = cpu_get_real_ticks() - ticks;
659
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
660
}
661
#endif /* !_WIN32 */
662

    
663
/* compute with 96 bit intermediate result: (a*b)/c */
664
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
665
{
666
    union {
667
        uint64_t ll;
668
        struct {
669
#ifdef WORDS_BIGENDIAN
670
            uint32_t high, low;
671
#else
672
            uint32_t low, high;
673
#endif            
674
        } l;
675
    } u, res;
676
    uint64_t rl, rh;
677

    
678
    u.ll = a;
679
    rl = (uint64_t)u.l.low * (uint64_t)b;
680
    rh = (uint64_t)u.l.high * (uint64_t)b;
681
    rh += (rl >> 32);
682
    res.l.high = rh / c;
683
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
684
    return res.ll;
685
}
686

    
687
#define QEMU_TIMER_REALTIME 0
688
#define QEMU_TIMER_VIRTUAL  1
689

    
690
struct QEMUClock {
691
    int type;
692
    /* XXX: add frequency */
693
};
694

    
695
struct QEMUTimer {
696
    QEMUClock *clock;
697
    int64_t expire_time;
698
    QEMUTimerCB *cb;
699
    void *opaque;
700
    struct QEMUTimer *next;
701
};
702

    
703
QEMUClock *rt_clock;
704
QEMUClock *vm_clock;
705

    
706
static QEMUTimer *active_timers[2];
707
#ifdef _WIN32
708
static MMRESULT timerID;
709
static HANDLE host_alarm = NULL;
710
static unsigned int period = 1;
711
#else
712
/* frequency of the times() clock tick */
713
static int timer_freq;
714
#endif
715

    
716
QEMUClock *qemu_new_clock(int type)
717
{
718
    QEMUClock *clock;
719
    clock = qemu_mallocz(sizeof(QEMUClock));
720
    if (!clock)
721
        return NULL;
722
    clock->type = type;
723
    return clock;
724
}
725

    
726
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
727
{
728
    QEMUTimer *ts;
729

    
730
    ts = qemu_mallocz(sizeof(QEMUTimer));
731
    ts->clock = clock;
732
    ts->cb = cb;
733
    ts->opaque = opaque;
734
    return ts;
735
}
736

    
737
void qemu_free_timer(QEMUTimer *ts)
738
{
739
    qemu_free(ts);
740
}
741

    
742
/* stop a timer, but do not dealloc it */
743
void qemu_del_timer(QEMUTimer *ts)
744
{
745
    QEMUTimer **pt, *t;
746

    
747
    /* NOTE: this code must be signal safe because
748
       qemu_timer_expired() can be called from a signal. */
749
    pt = &active_timers[ts->clock->type];
750
    for(;;) {
751
        t = *pt;
752
        if (!t)
753
            break;
754
        if (t == ts) {
755
            *pt = t->next;
756
            break;
757
        }
758
        pt = &t->next;
759
    }
760
}
761

    
762
/* modify the current timer so that it will be fired when current_time
763
   >= expire_time. The corresponding callback will be called. */
764
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
765
{
766
    QEMUTimer **pt, *t;
767

    
768
    qemu_del_timer(ts);
769

    
770
    /* add the timer in the sorted list */
771
    /* NOTE: this code must be signal safe because
772
       qemu_timer_expired() can be called from a signal. */
773
    pt = &active_timers[ts->clock->type];
774
    for(;;) {
775
        t = *pt;
776
        if (!t)
777
            break;
778
        if (t->expire_time > expire_time) 
779
            break;
780
        pt = &t->next;
781
    }
782
    ts->expire_time = expire_time;
783
    ts->next = *pt;
784
    *pt = ts;
785
}
786

    
787
int qemu_timer_pending(QEMUTimer *ts)
788
{
789
    QEMUTimer *t;
790
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
791
        if (t == ts)
792
            return 1;
793
    }
794
    return 0;
795
}
796

    
797
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
798
{
799
    if (!timer_head)
800
        return 0;
801
    return (timer_head->expire_time <= current_time);
802
}
803

    
804
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
805
{
806
    QEMUTimer *ts;
807
    
808
    for(;;) {
809
        ts = *ptimer_head;
810
        if (!ts || ts->expire_time > current_time)
811
            break;
812
        /* remove timer from the list before calling the callback */
813
        *ptimer_head = ts->next;
814
        ts->next = NULL;
815
        
816
        /* run the callback (the timer list can be modified) */
817
        ts->cb(ts->opaque);
818
    }
819
}
820

    
821
int64_t qemu_get_clock(QEMUClock *clock)
822
{
823
    switch(clock->type) {
824
    case QEMU_TIMER_REALTIME:
825
#ifdef _WIN32
826
        return GetTickCount();
827
#else
828
        {
829
            struct tms tp;
830

    
831
            /* Note that using gettimeofday() is not a good solution
832
               for timers because its value change when the date is
833
               modified. */
834
            if (timer_freq == 100) {
835
                return times(&tp) * 10;
836
            } else {
837
                return ((int64_t)times(&tp) * 1000) / timer_freq;
838
            }
839
        }
840
#endif
841
    default:
842
    case QEMU_TIMER_VIRTUAL:
843
        return cpu_get_ticks();
844
    }
845
}
846

    
847
/* save a timer */
848
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
849
{
850
    uint64_t expire_time;
851

    
852
    if (qemu_timer_pending(ts)) {
853
        expire_time = ts->expire_time;
854
    } else {
855
        expire_time = -1;
856
    }
857
    qemu_put_be64(f, expire_time);
858
}
859

    
860
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
861
{
862
    uint64_t expire_time;
863

    
864
    expire_time = qemu_get_be64(f);
865
    if (expire_time != -1) {
866
        qemu_mod_timer(ts, expire_time);
867
    } else {
868
        qemu_del_timer(ts);
869
    }
870
}
871

    
872
static void timer_save(QEMUFile *f, void *opaque)
873
{
874
    if (cpu_ticks_enabled) {
875
        hw_error("cannot save state if virtual timers are running");
876
    }
877
    qemu_put_be64s(f, &cpu_ticks_offset);
878
    qemu_put_be64s(f, &ticks_per_sec);
879
}
880

    
881
static int timer_load(QEMUFile *f, void *opaque, int version_id)
882
{
883
    if (version_id != 1)
884
        return -EINVAL;
885
    if (cpu_ticks_enabled) {
886
        return -EINVAL;
887
    }
888
    qemu_get_be64s(f, &cpu_ticks_offset);
889
    qemu_get_be64s(f, &ticks_per_sec);
890
    return 0;
891
}
892

    
893
#ifdef _WIN32
894
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
895
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
896
#else
897
static void host_alarm_handler(int host_signum)
898
#endif
899
{
900
#if 0
901
#define DISP_FREQ 1000
902
    {
903
        static int64_t delta_min = INT64_MAX;
904
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
905
        static int count;
906
        ti = qemu_get_clock(vm_clock);
907
        if (last_clock != 0) {
908
            delta = ti - last_clock;
909
            if (delta < delta_min)
910
                delta_min = delta;
911
            if (delta > delta_max)
912
                delta_max = delta;
913
            delta_cum += delta;
914
            if (++count == DISP_FREQ) {
915
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
916
                       muldiv64(delta_min, 1000000, ticks_per_sec),
917
                       muldiv64(delta_max, 1000000, ticks_per_sec),
918
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
919
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
920
                count = 0;
921
                delta_min = INT64_MAX;
922
                delta_max = 0;
923
                delta_cum = 0;
924
            }
925
        }
926
        last_clock = ti;
927
    }
928
#endif
929
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
930
                           qemu_get_clock(vm_clock)) ||
931
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
932
                           qemu_get_clock(rt_clock))) {
933
#ifdef _WIN32
934
        SetEvent(host_alarm);
935
#endif
936
        CPUState *env = cpu_single_env;
937
        if (env) {
938
            /* stop the currently executing cpu because a timer occured */
939
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
940
#ifdef USE_KQEMU
941
            if (env->kqemu_enabled) {
942
                kqemu_cpu_interrupt(env);
943
            }
944
#endif
945
        }
946
    }
947
}
948

    
949
#ifndef _WIN32
950

    
951
#if defined(__linux__)
952

    
953
#define RTC_FREQ 1024
954

    
955
static int rtc_fd;
956

    
957
static int start_rtc_timer(void)
958
{
959
    rtc_fd = open("/dev/rtc", O_RDONLY);
960
    if (rtc_fd < 0)
961
        return -1;
962
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
963
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
964
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
965
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
966
        goto fail;
967
    }
968
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
969
    fail:
970
        close(rtc_fd);
971
        return -1;
972
    }
973
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
974
    return 0;
975
}
976

    
977
#else
978

    
979
static int start_rtc_timer(void)
980
{
981
    return -1;
982
}
983

    
984
#endif /* !defined(__linux__) */
985

    
986
#endif /* !defined(_WIN32) */
987

    
988
static void init_timers(void)
989
{
990
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
991
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
992

    
993
#ifdef _WIN32
994
    {
995
        int count=0;
996
        TIMECAPS tc;
997

    
998
        ZeroMemory(&tc, sizeof(TIMECAPS));
999
        timeGetDevCaps(&tc, sizeof(TIMECAPS));
1000
        if (period < tc.wPeriodMin)
1001
            period = tc.wPeriodMin;
1002
        timeBeginPeriod(period);
1003
        timerID = timeSetEvent(1,     // interval (ms)
1004
                               period,     // resolution
1005
                               host_alarm_handler, // function
1006
                               (DWORD)&count,  // user parameter
1007
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1008
         if( !timerID ) {
1009
            perror("failed timer alarm");
1010
            exit(1);
1011
         }
1012
        host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1013
        if (!host_alarm) {
1014
            perror("failed CreateEvent");
1015
            exit(1);
1016
        }
1017
        qemu_add_wait_object(host_alarm, NULL, NULL);
1018
    }
1019
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1020
#else
1021
    {
1022
        struct sigaction act;
1023
        struct itimerval itv;
1024
        
1025
        /* get times() syscall frequency */
1026
        timer_freq = sysconf(_SC_CLK_TCK);
1027
        
1028
        /* timer signal */
1029
        sigfillset(&act.sa_mask);
1030
       act.sa_flags = 0;
1031
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1032
        act.sa_flags |= SA_ONSTACK;
1033
#endif
1034
        act.sa_handler = host_alarm_handler;
1035
        sigaction(SIGALRM, &act, NULL);
1036

    
1037
        itv.it_interval.tv_sec = 0;
1038
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1039
        itv.it_value.tv_sec = 0;
1040
        itv.it_value.tv_usec = 10 * 1000;
1041
        setitimer(ITIMER_REAL, &itv, NULL);
1042
        /* we probe the tick duration of the kernel to inform the user if
1043
           the emulated kernel requested a too high timer frequency */
1044
        getitimer(ITIMER_REAL, &itv);
1045

    
1046
#if defined(__linux__)
1047
        /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1048
           have timers with 1 ms resolution. The correct solution will
1049
           be to use the POSIX real time timers available in recent
1050
           2.6 kernels */
1051
        if (itv.it_interval.tv_usec > 1000 || 1) {
1052
            /* try to use /dev/rtc to have a faster timer */
1053
            if (start_rtc_timer() < 0)
1054
                goto use_itimer;
1055
            /* disable itimer */
1056
            itv.it_interval.tv_sec = 0;
1057
            itv.it_interval.tv_usec = 0;
1058
            itv.it_value.tv_sec = 0;
1059
            itv.it_value.tv_usec = 0;
1060
            setitimer(ITIMER_REAL, &itv, NULL);
1061

    
1062
            /* use the RTC */
1063
            sigaction(SIGIO, &act, NULL);
1064
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1065
            fcntl(rtc_fd, F_SETOWN, getpid());
1066
        } else 
1067
#endif /* defined(__linux__) */
1068
        {
1069
        use_itimer:
1070
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1071
                                   PIT_FREQ) / 1000000;
1072
        }
1073
    }
1074
#endif
1075
}
1076

    
1077
void quit_timers(void)
1078
{
1079
#ifdef _WIN32
1080
    timeKillEvent(timerID);
1081
    timeEndPeriod(period);
1082
    if (host_alarm) {
1083
        CloseHandle(host_alarm);
1084
        host_alarm = NULL;
1085
    }
1086
#endif
1087
}
1088

    
1089
/***********************************************************/
1090
/* character device */
1091

    
1092
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1093
{
1094
    return s->chr_write(s, buf, len);
1095
}
1096

    
1097
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1098
{
1099
    if (!s->chr_ioctl)
1100
        return -ENOTSUP;
1101
    return s->chr_ioctl(s, cmd, arg);
1102
}
1103

    
1104
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1105
{
1106
    char buf[4096];
1107
    va_list ap;
1108
    va_start(ap, fmt);
1109
    vsnprintf(buf, sizeof(buf), fmt, ap);
1110
    qemu_chr_write(s, buf, strlen(buf));
1111
    va_end(ap);
1112
}
1113

    
1114
void qemu_chr_send_event(CharDriverState *s, int event)
1115
{
1116
    if (s->chr_send_event)
1117
        s->chr_send_event(s, event);
1118
}
1119

    
1120
void qemu_chr_add_read_handler(CharDriverState *s, 
1121
                               IOCanRWHandler *fd_can_read, 
1122
                               IOReadHandler *fd_read, void *opaque)
1123
{
1124
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1125
}
1126
             
1127
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1128
{
1129
    s->chr_event = chr_event;
1130
}
1131

    
1132
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1133
{
1134
    return len;
1135
}
1136

    
1137
static void null_chr_add_read_handler(CharDriverState *chr, 
1138
                                    IOCanRWHandler *fd_can_read, 
1139
                                    IOReadHandler *fd_read, void *opaque)
1140
{
1141
}
1142

    
1143
CharDriverState *qemu_chr_open_null(void)
1144
{
1145
    CharDriverState *chr;
1146

    
1147
    chr = qemu_mallocz(sizeof(CharDriverState));
1148
    if (!chr)
1149
        return NULL;
1150
    chr->chr_write = null_chr_write;
1151
    chr->chr_add_read_handler = null_chr_add_read_handler;
1152
    return chr;
1153
}
1154

    
1155
#ifdef _WIN32
1156

    
1157
static void socket_cleanup(void)
1158
{
1159
    WSACleanup();
1160
}
1161

    
1162
static int socket_init(void)
1163
{
1164
    WSADATA Data;
1165
    int ret, err;
1166

    
1167
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1168
    if (ret != 0) {
1169
        err = WSAGetLastError();
1170
        fprintf(stderr, "WSAStartup: %d\n", err);
1171
        return -1;
1172
    }
1173
    atexit(socket_cleanup);
1174
    return 0;
1175
}
1176

    
1177
static int send_all(int fd, const uint8_t *buf, int len1)
1178
{
1179
    int ret, len;
1180
    
1181
    len = len1;
1182
    while (len > 0) {
1183
        ret = send(fd, buf, len, 0);
1184
        if (ret < 0) {
1185
            int errno;
1186
            errno = WSAGetLastError();
1187
            if (errno != WSAEWOULDBLOCK) {
1188
                return -1;
1189
            }
1190
        } else if (ret == 0) {
1191
            break;
1192
        } else {
1193
            buf += ret;
1194
            len -= ret;
1195
        }
1196
    }
1197
    return len1 - len;
1198
}
1199

    
1200
void socket_set_nonblock(int fd)
1201
{
1202
    unsigned long opt = 1;
1203
    ioctlsocket(fd, FIONBIO, &opt);
1204
}
1205

    
1206
#else
1207

    
1208
static int unix_write(int fd, const uint8_t *buf, int len1)
1209
{
1210
    int ret, len;
1211

    
1212
    len = len1;
1213
    while (len > 0) {
1214
        ret = write(fd, buf, len);
1215
        if (ret < 0) {
1216
            if (errno != EINTR && errno != EAGAIN)
1217
                return -1;
1218
        } else if (ret == 0) {
1219
            break;
1220
        } else {
1221
            buf += ret;
1222
            len -= ret;
1223
        }
1224
    }
1225
    return len1 - len;
1226
}
1227

    
1228
static inline int send_all(int fd, const uint8_t *buf, int len1)
1229
{
1230
    return unix_write(fd, buf, len1);
1231
}
1232

    
1233
void socket_set_nonblock(int fd)
1234
{
1235
    fcntl(fd, F_SETFL, O_NONBLOCK);
1236
}
1237
#endif /* !_WIN32 */
1238

    
1239
#ifndef _WIN32
1240

    
1241
typedef struct {
1242
    int fd_in, fd_out;
1243
    IOCanRWHandler *fd_can_read; 
1244
    IOReadHandler *fd_read;
1245
    void *fd_opaque;
1246
    int max_size;
1247
} FDCharDriver;
1248

    
1249
#define STDIO_MAX_CLIENTS 2
1250

    
1251
static int stdio_nb_clients;
1252
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1253

    
1254
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1255
{
1256
    FDCharDriver *s = chr->opaque;
1257
    return unix_write(s->fd_out, buf, len);
1258
}
1259

    
1260
static int fd_chr_read_poll(void *opaque)
1261
{
1262
    CharDriverState *chr = opaque;
1263
    FDCharDriver *s = chr->opaque;
1264

    
1265
    s->max_size = s->fd_can_read(s->fd_opaque);
1266
    return s->max_size;
1267
}
1268

    
1269
static void fd_chr_read(void *opaque)
1270
{
1271
    CharDriverState *chr = opaque;
1272
    FDCharDriver *s = chr->opaque;
1273
    int size, len;
1274
    uint8_t buf[1024];
1275
    
1276
    len = sizeof(buf);
1277
    if (len > s->max_size)
1278
        len = s->max_size;
1279
    if (len == 0)
1280
        return;
1281
    size = read(s->fd_in, buf, len);
1282
    if (size > 0) {
1283
        s->fd_read(s->fd_opaque, buf, size);
1284
    }
1285
}
1286

    
1287
static void fd_chr_add_read_handler(CharDriverState *chr, 
1288
                                    IOCanRWHandler *fd_can_read, 
1289
                                    IOReadHandler *fd_read, void *opaque)
1290
{
1291
    FDCharDriver *s = chr->opaque;
1292

    
1293
    if (s->fd_in >= 0) {
1294
        s->fd_can_read = fd_can_read;
1295
        s->fd_read = fd_read;
1296
        s->fd_opaque = opaque;
1297
        if (nographic && s->fd_in == 0) {
1298
        } else {
1299
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1300
                                 fd_chr_read, NULL, chr);
1301
        }
1302
    }
1303
}
1304

    
1305
/* open a character device to a unix fd */
1306
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1307
{
1308
    CharDriverState *chr;
1309
    FDCharDriver *s;
1310

    
1311
    chr = qemu_mallocz(sizeof(CharDriverState));
1312
    if (!chr)
1313
        return NULL;
1314
    s = qemu_mallocz(sizeof(FDCharDriver));
1315
    if (!s) {
1316
        free(chr);
1317
        return NULL;
1318
    }
1319
    s->fd_in = fd_in;
1320
    s->fd_out = fd_out;
1321
    chr->opaque = s;
1322
    chr->chr_write = fd_chr_write;
1323
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1324
    return chr;
1325
}
1326

    
1327
CharDriverState *qemu_chr_open_file_out(const char *file_out)
1328
{
1329
    int fd_out;
1330

    
1331
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1332
    if (fd_out < 0)
1333
        return NULL;
1334
    return qemu_chr_open_fd(-1, fd_out);
1335
}
1336

    
1337
CharDriverState *qemu_chr_open_pipe(const char *filename)
1338
{
1339
    int fd;
1340

    
1341
    fd = open(filename, O_RDWR | O_BINARY);
1342
    if (fd < 0)
1343
        return NULL;
1344
    return qemu_chr_open_fd(fd, fd);
1345
}
1346

    
1347

    
1348
/* for STDIO, we handle the case where several clients use it
1349
   (nographic mode) */
1350

    
1351
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1352

    
1353
#define TERM_FIFO_MAX_SIZE 1
1354

    
1355
static int term_got_escape, client_index;
1356
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1357
int term_fifo_size;
1358

    
1359
void term_print_help(void)
1360
{
1361
    printf("\n"
1362
           "C-a h    print this help\n"
1363
           "C-a x    exit emulator\n"
1364
           "C-a s    save disk data back to file (if -snapshot)\n"
1365
           "C-a b    send break (magic sysrq)\n"
1366
           "C-a c    switch between console and monitor\n"
1367
           "C-a C-a  send C-a\n"
1368
           );
1369
}
1370

    
1371
/* called when a char is received */
1372
static void stdio_received_byte(int ch)
1373
{
1374
    if (term_got_escape) {
1375
        term_got_escape = 0;
1376
        switch(ch) {
1377
        case 'h':
1378
            term_print_help();
1379
            break;
1380
        case 'x':
1381
            exit(0);
1382
            break;
1383
        case 's': 
1384
            {
1385
                int i;
1386
                for (i = 0; i < MAX_DISKS; i++) {
1387
                    if (bs_table[i])
1388
                        bdrv_commit(bs_table[i]);
1389
                }
1390
            }
1391
            break;
1392
        case 'b':
1393
            if (client_index < stdio_nb_clients) {
1394
                CharDriverState *chr;
1395
                FDCharDriver *s;
1396

    
1397
                chr = stdio_clients[client_index];
1398
                s = chr->opaque;
1399
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1400
            }
1401
            break;
1402
        case 'c':
1403
            client_index++;
1404
            if (client_index >= stdio_nb_clients)
1405
                client_index = 0;
1406
            if (client_index == 0) {
1407
                /* send a new line in the monitor to get the prompt */
1408
                ch = '\r';
1409
                goto send_char;
1410
            }
1411
            break;
1412
        case TERM_ESCAPE:
1413
            goto send_char;
1414
        }
1415
    } else if (ch == TERM_ESCAPE) {
1416
        term_got_escape = 1;
1417
    } else {
1418
    send_char:
1419
        if (client_index < stdio_nb_clients) {
1420
            uint8_t buf[1];
1421
            CharDriverState *chr;
1422
            FDCharDriver *s;
1423
            
1424
            chr = stdio_clients[client_index];
1425
            s = chr->opaque;
1426
            if (s->fd_can_read(s->fd_opaque) > 0) {
1427
                buf[0] = ch;
1428
                s->fd_read(s->fd_opaque, buf, 1);
1429
            } else if (term_fifo_size == 0) {
1430
                term_fifo[term_fifo_size++] = ch;
1431
            }
1432
        }
1433
    }
1434
}
1435

    
1436
static int stdio_read_poll(void *opaque)
1437
{
1438
    CharDriverState *chr;
1439
    FDCharDriver *s;
1440

    
1441
    if (client_index < stdio_nb_clients) {
1442
        chr = stdio_clients[client_index];
1443
        s = chr->opaque;
1444
        /* try to flush the queue if needed */
1445
        if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1446
            s->fd_read(s->fd_opaque, term_fifo, 1);
1447
            term_fifo_size = 0;
1448
        }
1449
        /* see if we can absorb more chars */
1450
        if (term_fifo_size == 0)
1451
            return 1;
1452
        else
1453
            return 0;
1454
    } else {
1455
        return 1;
1456
    }
1457
}
1458

    
1459
static void stdio_read(void *opaque)
1460
{
1461
    int size;
1462
    uint8_t buf[1];
1463
    
1464
    size = read(0, buf, 1);
1465
    if (size > 0)
1466
        stdio_received_byte(buf[0]);
1467
}
1468

    
1469
/* init terminal so that we can grab keys */
1470
static struct termios oldtty;
1471
static int old_fd0_flags;
1472

    
1473
static void term_exit(void)
1474
{
1475
    tcsetattr (0, TCSANOW, &oldtty);
1476
    fcntl(0, F_SETFL, old_fd0_flags);
1477
}
1478

    
1479
static void term_init(void)
1480
{
1481
    struct termios tty;
1482

    
1483
    tcgetattr (0, &tty);
1484
    oldtty = tty;
1485
    old_fd0_flags = fcntl(0, F_GETFL);
1486

    
1487
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1488
                          |INLCR|IGNCR|ICRNL|IXON);
1489
    tty.c_oflag |= OPOST;
1490
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1491
    /* if graphical mode, we allow Ctrl-C handling */
1492
    if (nographic)
1493
        tty.c_lflag &= ~ISIG;
1494
    tty.c_cflag &= ~(CSIZE|PARENB);
1495
    tty.c_cflag |= CS8;
1496
    tty.c_cc[VMIN] = 1;
1497
    tty.c_cc[VTIME] = 0;
1498
    
1499
    tcsetattr (0, TCSANOW, &tty);
1500

    
1501
    atexit(term_exit);
1502

    
1503
    fcntl(0, F_SETFL, O_NONBLOCK);
1504
}
1505

    
1506
CharDriverState *qemu_chr_open_stdio(void)
1507
{
1508
    CharDriverState *chr;
1509

    
1510
    if (nographic) {
1511
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1512
            return NULL;
1513
        chr = qemu_chr_open_fd(0, 1);
1514
        if (stdio_nb_clients == 0)
1515
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1516
        client_index = stdio_nb_clients;
1517
    } else {
1518
        if (stdio_nb_clients != 0)
1519
            return NULL;
1520
        chr = qemu_chr_open_fd(0, 1);
1521
    }
1522
    stdio_clients[stdio_nb_clients++] = chr;
1523
    if (stdio_nb_clients == 1) {
1524
        /* set the terminal in raw mode */
1525
        term_init();
1526
    }
1527
    return chr;
1528
}
1529

    
1530
#if defined(__linux__)
1531
CharDriverState *qemu_chr_open_pty(void)
1532
{
1533
    struct termios tty;
1534
    char slave_name[1024];
1535
    int master_fd, slave_fd;
1536
    
1537
    /* Not satisfying */
1538
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1539
        return NULL;
1540
    }
1541
    
1542
    /* Disabling local echo and line-buffered output */
1543
    tcgetattr (master_fd, &tty);
1544
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1545
    tty.c_cc[VMIN] = 1;
1546
    tty.c_cc[VTIME] = 0;
1547
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1548

    
1549
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1550
    return qemu_chr_open_fd(master_fd, master_fd);
1551
}
1552

    
1553
static void tty_serial_init(int fd, int speed, 
1554
                            int parity, int data_bits, int stop_bits)
1555
{
1556
    struct termios tty;
1557
    speed_t spd;
1558

    
1559
#if 0
1560
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1561
           speed, parity, data_bits, stop_bits);
1562
#endif
1563
    tcgetattr (fd, &tty);
1564

    
1565
    switch(speed) {
1566
    case 50:
1567
        spd = B50;
1568
        break;
1569
    case 75:
1570
        spd = B75;
1571
        break;
1572
    case 300:
1573
        spd = B300;
1574
        break;
1575
    case 600:
1576
        spd = B600;
1577
        break;
1578
    case 1200:
1579
        spd = B1200;
1580
        break;
1581
    case 2400:
1582
        spd = B2400;
1583
        break;
1584
    case 4800:
1585
        spd = B4800;
1586
        break;
1587
    case 9600:
1588
        spd = B9600;
1589
        break;
1590
    case 19200:
1591
        spd = B19200;
1592
        break;
1593
    case 38400:
1594
        spd = B38400;
1595
        break;
1596
    case 57600:
1597
        spd = B57600;
1598
        break;
1599
    default:
1600
    case 115200:
1601
        spd = B115200;
1602
        break;
1603
    }
1604

    
1605
    cfsetispeed(&tty, spd);
1606
    cfsetospeed(&tty, spd);
1607

    
1608
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1609
                          |INLCR|IGNCR|ICRNL|IXON);
1610
    tty.c_oflag |= OPOST;
1611
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1612
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1613
    switch(data_bits) {
1614
    default:
1615
    case 8:
1616
        tty.c_cflag |= CS8;
1617
        break;
1618
    case 7:
1619
        tty.c_cflag |= CS7;
1620
        break;
1621
    case 6:
1622
        tty.c_cflag |= CS6;
1623
        break;
1624
    case 5:
1625
        tty.c_cflag |= CS5;
1626
        break;
1627
    }
1628
    switch(parity) {
1629
    default:
1630
    case 'N':
1631
        break;
1632
    case 'E':
1633
        tty.c_cflag |= PARENB;
1634
        break;
1635
    case 'O':
1636
        tty.c_cflag |= PARENB | PARODD;
1637
        break;
1638
    }
1639
    
1640
    tcsetattr (fd, TCSANOW, &tty);
1641
}
1642

    
1643
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1644
{
1645
    FDCharDriver *s = chr->opaque;
1646
    
1647
    switch(cmd) {
1648
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1649
        {
1650
            QEMUSerialSetParams *ssp = arg;
1651
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1652
                            ssp->data_bits, ssp->stop_bits);
1653
        }
1654
        break;
1655
    case CHR_IOCTL_SERIAL_SET_BREAK:
1656
        {
1657
            int enable = *(int *)arg;
1658
            if (enable)
1659
                tcsendbreak(s->fd_in, 1);
1660
        }
1661
        break;
1662
    default:
1663
        return -ENOTSUP;
1664
    }
1665
    return 0;
1666
}
1667

    
1668
CharDriverState *qemu_chr_open_tty(const char *filename)
1669
{
1670
    CharDriverState *chr;
1671
    int fd;
1672

    
1673
    fd = open(filename, O_RDWR | O_NONBLOCK);
1674
    if (fd < 0)
1675
        return NULL;
1676
    fcntl(fd, F_SETFL, O_NONBLOCK);
1677
    tty_serial_init(fd, 115200, 'N', 8, 1);
1678
    chr = qemu_chr_open_fd(fd, fd);
1679
    if (!chr)
1680
        return NULL;
1681
    chr->chr_ioctl = tty_serial_ioctl;
1682
    return chr;
1683
}
1684

    
1685
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1686
{
1687
    int fd = (int)chr->opaque;
1688
    uint8_t b;
1689

    
1690
    switch(cmd) {
1691
    case CHR_IOCTL_PP_READ_DATA:
1692
        if (ioctl(fd, PPRDATA, &b) < 0)
1693
            return -ENOTSUP;
1694
        *(uint8_t *)arg = b;
1695
        break;
1696
    case CHR_IOCTL_PP_WRITE_DATA:
1697
        b = *(uint8_t *)arg;
1698
        if (ioctl(fd, PPWDATA, &b) < 0)
1699
            return -ENOTSUP;
1700
        break;
1701
    case CHR_IOCTL_PP_READ_CONTROL:
1702
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1703
            return -ENOTSUP;
1704
        *(uint8_t *)arg = b;
1705
        break;
1706
    case CHR_IOCTL_PP_WRITE_CONTROL:
1707
        b = *(uint8_t *)arg;
1708
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1709
            return -ENOTSUP;
1710
        break;
1711
    case CHR_IOCTL_PP_READ_STATUS:
1712
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1713
            return -ENOTSUP;
1714
        *(uint8_t *)arg = b;
1715
        break;
1716
    default:
1717
        return -ENOTSUP;
1718
    }
1719
    return 0;
1720
}
1721

    
1722
CharDriverState *qemu_chr_open_pp(const char *filename)
1723
{
1724
    CharDriverState *chr;
1725
    int fd;
1726

    
1727
    fd = open(filename, O_RDWR);
1728
    if (fd < 0)
1729
        return NULL;
1730

    
1731
    if (ioctl(fd, PPCLAIM) < 0) {
1732
        close(fd);
1733
        return NULL;
1734
    }
1735

    
1736
    chr = qemu_mallocz(sizeof(CharDriverState));
1737
    if (!chr) {
1738
        close(fd);
1739
        return NULL;
1740
    }
1741
    chr->opaque = (void *)fd;
1742
    chr->chr_write = null_chr_write;
1743
    chr->chr_add_read_handler = null_chr_add_read_handler;
1744
    chr->chr_ioctl = pp_ioctl;
1745
    return chr;
1746
}
1747

    
1748
#else
1749
CharDriverState *qemu_chr_open_pty(void)
1750
{
1751
    return NULL;
1752
}
1753
#endif
1754

    
1755
#endif /* !defined(_WIN32) */
1756

    
1757
#ifdef _WIN32
1758
typedef struct {
1759
    IOCanRWHandler *fd_can_read; 
1760
    IOReadHandler *fd_read;
1761
    void *win_opaque;
1762
    int max_size;
1763
    HANDLE hcom, hrecv, hsend;
1764
    OVERLAPPED orecv, osend;
1765
    BOOL fpipe;
1766
    DWORD len;
1767
} WinCharState;
1768

    
1769
#define NSENDBUF 2048
1770
#define NRECVBUF 2048
1771
#define MAXCONNECT 1
1772
#define NTIMEOUT 5000
1773

    
1774
static int win_chr_poll(void *opaque);
1775
static int win_chr_pipe_poll(void *opaque);
1776

    
1777
static void win_chr_close2(WinCharState *s)
1778
{
1779
    if (s->hsend) {
1780
        CloseHandle(s->hsend);
1781
        s->hsend = NULL;
1782
    }
1783
    if (s->hrecv) {
1784
        CloseHandle(s->hrecv);
1785
        s->hrecv = NULL;
1786
    }
1787
    if (s->hcom) {
1788
        CloseHandle(s->hcom);
1789
        s->hcom = NULL;
1790
    }
1791
    if (s->fpipe)
1792
        qemu_del_polling_cb(win_chr_pipe_poll, s);
1793
    else
1794
        qemu_del_polling_cb(win_chr_poll, s);
1795
}
1796

    
1797
static void win_chr_close(CharDriverState *chr)
1798
{
1799
    WinCharState *s = chr->opaque;
1800
    win_chr_close2(s);
1801
}
1802

    
1803
static int win_chr_init(WinCharState *s, const char *filename)
1804
{
1805
    COMMCONFIG comcfg;
1806
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1807
    COMSTAT comstat;
1808
    DWORD size;
1809
    DWORD err;
1810
    
1811
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1812
    if (!s->hsend) {
1813
        fprintf(stderr, "Failed CreateEvent\n");
1814
        goto fail;
1815
    }
1816
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1817
    if (!s->hrecv) {
1818
        fprintf(stderr, "Failed CreateEvent\n");
1819
        goto fail;
1820
    }
1821

    
1822
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1823
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1824
    if (s->hcom == INVALID_HANDLE_VALUE) {
1825
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1826
        s->hcom = NULL;
1827
        goto fail;
1828
    }
1829
    
1830
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1831
        fprintf(stderr, "Failed SetupComm\n");
1832
        goto fail;
1833
    }
1834
    
1835
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1836
    size = sizeof(COMMCONFIG);
1837
    GetDefaultCommConfig(filename, &comcfg, &size);
1838
    comcfg.dcb.DCBlength = sizeof(DCB);
1839
    CommConfigDialog(filename, NULL, &comcfg);
1840

    
1841
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1842
        fprintf(stderr, "Failed SetCommState\n");
1843
        goto fail;
1844
    }
1845

    
1846
    if (!SetCommMask(s->hcom, EV_ERR)) {
1847
        fprintf(stderr, "Failed SetCommMask\n");
1848
        goto fail;
1849
    }
1850

    
1851
    cto.ReadIntervalTimeout = MAXDWORD;
1852
    if (!SetCommTimeouts(s->hcom, &cto)) {
1853
        fprintf(stderr, "Failed SetCommTimeouts\n");
1854
        goto fail;
1855
    }
1856
    
1857
    if (!ClearCommError(s->hcom, &err, &comstat)) {
1858
        fprintf(stderr, "Failed ClearCommError\n");
1859
        goto fail;
1860
    }
1861
    qemu_add_polling_cb(win_chr_poll, s);
1862
    return 0;
1863

    
1864
 fail:
1865
    win_chr_close2(s);
1866
    return -1;
1867
}
1868

    
1869
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1870
{
1871
    WinCharState *s = chr->opaque;
1872
    DWORD len, ret, size, err;
1873

    
1874
    len = len1;
1875
    ZeroMemory(&s->osend, sizeof(s->osend));
1876
    s->osend.hEvent = s->hsend;
1877
    while (len > 0) {
1878
        if (s->hsend)
1879
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1880
        else
1881
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1882
        if (!ret) {
1883
            err = GetLastError();
1884
            if (err == ERROR_IO_PENDING) {
1885
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1886
                if (ret) {
1887
                    buf += size;
1888
                    len -= size;
1889
                } else {
1890
                    break;
1891
                }
1892
            } else {
1893
                break;
1894
            }
1895
        } else {
1896
            buf += size;
1897
            len -= size;
1898
        }
1899
    }
1900
    return len1 - len;
1901
}
1902

    
1903
static int win_chr_read_poll(WinCharState *s)
1904
{
1905
    s->max_size = s->fd_can_read(s->win_opaque);
1906
    return s->max_size;
1907
}
1908
            
1909
static void win_chr_readfile(WinCharState *s)
1910
{
1911
    int ret, err;
1912
    uint8_t buf[1024];
1913
    DWORD size;
1914
    
1915
    ZeroMemory(&s->orecv, sizeof(s->orecv));
1916
    s->orecv.hEvent = s->hrecv;
1917
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1918
    if (!ret) {
1919
        err = GetLastError();
1920
        if (err == ERROR_IO_PENDING) {
1921
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1922
        }
1923
    }
1924

    
1925
    if (size > 0) {
1926
        s->fd_read(s->win_opaque, buf, size);
1927
    }
1928
}
1929

    
1930
static void win_chr_read(WinCharState *s)
1931
{
1932
    if (s->len > s->max_size)
1933
        s->len = s->max_size;
1934
    if (s->len == 0)
1935
        return;
1936
    
1937
    win_chr_readfile(s);
1938
}
1939

    
1940
static int win_chr_poll(void *opaque)
1941
{
1942
    WinCharState *s = opaque;
1943
    COMSTAT status;
1944
    DWORD comerr;
1945
    
1946
    ClearCommError(s->hcom, &comerr, &status);
1947
    if (status.cbInQue > 0) {
1948
        s->len = status.cbInQue;
1949
        win_chr_read_poll(s);
1950
        win_chr_read(s);
1951
        return 1;
1952
    }
1953
    return 0;
1954
}
1955

    
1956
static void win_chr_add_read_handler(CharDriverState *chr, 
1957
                                    IOCanRWHandler *fd_can_read, 
1958
                                    IOReadHandler *fd_read, void *opaque)
1959
{
1960
    WinCharState *s = chr->opaque;
1961

    
1962
    s->fd_can_read = fd_can_read;
1963
    s->fd_read = fd_read;
1964
    s->win_opaque = opaque;
1965
}
1966

    
1967
CharDriverState *qemu_chr_open_win(const char *filename)
1968
{
1969
    CharDriverState *chr;
1970
    WinCharState *s;
1971
    
1972
    chr = qemu_mallocz(sizeof(CharDriverState));
1973
    if (!chr)
1974
        return NULL;
1975
    s = qemu_mallocz(sizeof(WinCharState));
1976
    if (!s) {
1977
        free(chr);
1978
        return NULL;
1979
    }
1980
    chr->opaque = s;
1981
    chr->chr_write = win_chr_write;
1982
    chr->chr_add_read_handler = win_chr_add_read_handler;
1983
    chr->chr_close = win_chr_close;
1984

    
1985
    if (win_chr_init(s, filename) < 0) {
1986
        free(s);
1987
        free(chr);
1988
        return NULL;
1989
    }
1990
    return chr;
1991
}
1992

    
1993
static int win_chr_pipe_poll(void *opaque)
1994
{
1995
    WinCharState *s = opaque;
1996
    DWORD size;
1997

    
1998
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1999
    if (size > 0) {
2000
        s->len = size;
2001
        win_chr_read_poll(s);
2002
        win_chr_read(s);
2003
        return 1;
2004
    }
2005
    return 0;
2006
}
2007

    
2008
static int win_chr_pipe_init(WinCharState *s, const char *filename)
2009
{
2010
    OVERLAPPED ov;
2011
    int ret;
2012
    DWORD size;
2013
    char openname[256];
2014
    
2015
    s->fpipe = TRUE;
2016

    
2017
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2018
    if (!s->hsend) {
2019
        fprintf(stderr, "Failed CreateEvent\n");
2020
        goto fail;
2021
    }
2022
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2023
    if (!s->hrecv) {
2024
        fprintf(stderr, "Failed CreateEvent\n");
2025
        goto fail;
2026
    }
2027
    
2028
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2029
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2030
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2031
                              PIPE_WAIT,
2032
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2033
    if (s->hcom == INVALID_HANDLE_VALUE) {
2034
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2035
        s->hcom = NULL;
2036
        goto fail;
2037
    }
2038

    
2039
    ZeroMemory(&ov, sizeof(ov));
2040
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2041
    ret = ConnectNamedPipe(s->hcom, &ov);
2042
    if (ret) {
2043
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2044
        goto fail;
2045
    }
2046

    
2047
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2048
    if (!ret) {
2049
        fprintf(stderr, "Failed GetOverlappedResult\n");
2050
        if (ov.hEvent) {
2051
            CloseHandle(ov.hEvent);
2052
            ov.hEvent = NULL;
2053
        }
2054
        goto fail;
2055
    }
2056

    
2057
    if (ov.hEvent) {
2058
        CloseHandle(ov.hEvent);
2059
        ov.hEvent = NULL;
2060
    }
2061
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2062
    return 0;
2063

    
2064
 fail:
2065
    win_chr_close2(s);
2066
    return -1;
2067
}
2068

    
2069

    
2070
CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2071
{
2072
    CharDriverState *chr;
2073
    WinCharState *s;
2074

    
2075
    chr = qemu_mallocz(sizeof(CharDriverState));
2076
    if (!chr)
2077
        return NULL;
2078
    s = qemu_mallocz(sizeof(WinCharState));
2079
    if (!s) {
2080
        free(chr);
2081
        return NULL;
2082
    }
2083
    chr->opaque = s;
2084
    chr->chr_write = win_chr_write;
2085
    chr->chr_add_read_handler = win_chr_add_read_handler;
2086
    chr->chr_close = win_chr_close;
2087
    
2088
    if (win_chr_pipe_init(s, filename) < 0) {
2089
        free(s);
2090
        free(chr);
2091
        return NULL;
2092
    }
2093
    return chr;
2094
}
2095

    
2096
CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2097
{
2098
    CharDriverState *chr;
2099
    WinCharState *s;
2100

    
2101
    chr = qemu_mallocz(sizeof(CharDriverState));
2102
    if (!chr)
2103
        return NULL;
2104
    s = qemu_mallocz(sizeof(WinCharState));
2105
    if (!s) {
2106
        free(chr);
2107
        return NULL;
2108
    }
2109
    s->hcom = fd_out;
2110
    chr->opaque = s;
2111
    chr->chr_write = win_chr_write;
2112
    chr->chr_add_read_handler = win_chr_add_read_handler;
2113
    return chr;
2114
}
2115
    
2116
CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2117
{
2118
    HANDLE fd_out;
2119
    
2120
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2121
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2122
    if (fd_out == INVALID_HANDLE_VALUE)
2123
        return NULL;
2124

    
2125
    return qemu_chr_open_win_file(fd_out);
2126
}
2127
#endif
2128

    
2129
/***********************************************************/
2130
/* UDP Net console */
2131

    
2132
typedef struct {
2133
    IOCanRWHandler *fd_can_read;
2134
    IOReadHandler *fd_read;
2135
    void *fd_opaque;
2136
    int fd;
2137
    struct sockaddr_in daddr;
2138
    char buf[1024];
2139
    int bufcnt;
2140
    int bufptr;
2141
    int max_size;
2142
} NetCharDriver;
2143

    
2144
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2145
{
2146
    NetCharDriver *s = chr->opaque;
2147

    
2148
    return sendto(s->fd, buf, len, 0,
2149
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2150
}
2151

    
2152
static int udp_chr_read_poll(void *opaque)
2153
{
2154
    CharDriverState *chr = opaque;
2155
    NetCharDriver *s = chr->opaque;
2156

    
2157
    s->max_size = s->fd_can_read(s->fd_opaque);
2158

    
2159
    /* If there were any stray characters in the queue process them
2160
     * first
2161
     */
2162
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2163
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2164
        s->bufptr++;
2165
        s->max_size = s->fd_can_read(s->fd_opaque);
2166
    }
2167
    return s->max_size;
2168
}
2169

    
2170
static void udp_chr_read(void *opaque)
2171
{
2172
    CharDriverState *chr = opaque;
2173
    NetCharDriver *s = chr->opaque;
2174

    
2175
    if (s->max_size == 0)
2176
        return;
2177
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2178
    s->bufptr = s->bufcnt;
2179
    if (s->bufcnt <= 0)
2180
        return;
2181

    
2182
    s->bufptr = 0;
2183
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2184
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2185
        s->bufptr++;
2186
        s->max_size = s->fd_can_read(s->fd_opaque);
2187
    }
2188
}
2189

    
2190
static void udp_chr_add_read_handler(CharDriverState *chr,
2191
                                    IOCanRWHandler *fd_can_read,
2192
                                    IOReadHandler *fd_read, void *opaque)
2193
{
2194
    NetCharDriver *s = chr->opaque;
2195

    
2196
    if (s->fd >= 0) {
2197
        s->fd_can_read = fd_can_read;
2198
        s->fd_read = fd_read;
2199
        s->fd_opaque = opaque;
2200
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2201
                             udp_chr_read, NULL, chr);
2202
    }
2203
}
2204

    
2205
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2206

    
2207
CharDriverState *qemu_chr_open_udp(const char *def)
2208
{
2209
    CharDriverState *chr = NULL;
2210
    NetCharDriver *s = NULL;
2211
    int fd = -1;
2212
    int con_type;
2213
    struct sockaddr_in addr;
2214
    const char *p, *r;
2215
    int port;
2216

    
2217
    chr = qemu_mallocz(sizeof(CharDriverState));
2218
    if (!chr)
2219
        goto return_err;
2220
    s = qemu_mallocz(sizeof(NetCharDriver));
2221
    if (!s)
2222
        goto return_err;
2223

    
2224
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2225
    if (fd < 0) {
2226
        perror("socket(PF_INET, SOCK_DGRAM)");
2227
        goto return_err;
2228
    }
2229

    
2230
    /* There are three types of port definitions
2231
     * 1) udp:remote_port
2232
     *    Juse use 0.0.0.0 for the IP and send to remote
2233
     * 2) udp:remote_host:port
2234
     *    Use a IP and send traffic to remote
2235
     * 3) udp:local_port:remote_host:remote_port
2236
     *    Use local_port as the originator + #2
2237
     */
2238
    con_type = 0;
2239
    p = def;
2240
    while ((p = strchr(p, ':'))) {
2241
        p++;
2242
        con_type++;
2243
    }
2244

    
2245
    p = def;
2246
    memset(&addr,0,sizeof(addr));
2247
    addr.sin_family = AF_INET;
2248
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
2249
    s->daddr.sin_family = AF_INET;
2250
    s->daddr.sin_addr.s_addr = htonl(INADDR_ANY);
2251

    
2252
    switch (con_type) {
2253
        case 0:
2254
            port = strtol(p, (char **)&r, 0);
2255
            if (r == p) {
2256
                fprintf(stderr, "Error parsing port number\n");
2257
                goto return_err;
2258
            }
2259
            s->daddr.sin_port = htons((short)port);
2260
            break;
2261
        case 2:
2262
            port = strtol(p, (char **)&r, 0);
2263
            if (r == p) {
2264
                fprintf(stderr, "Error parsing port number\n");
2265
                goto return_err;
2266
            }
2267
            addr.sin_port = htons((short)port);
2268
            p = r + 1;
2269
            /* Fall through to case 1 now that we have the local port */
2270
        case 1:
2271
            if (parse_host_port(&s->daddr, p) < 0) {
2272
                fprintf(stderr, "Error parsing host name and port\n");
2273
                goto return_err;
2274
            }
2275
            break;
2276
        default:
2277
            fprintf(stderr, "Too many ':' characters\n");
2278
            goto return_err;
2279
    }
2280

    
2281
    if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
2282
    {
2283
        perror("bind");
2284
        goto return_err;
2285
    }
2286

    
2287
    s->fd = fd;
2288
    s->bufcnt = 0;
2289
    s->bufptr = 0;
2290
    chr->opaque = s;
2291
    chr->chr_write = udp_chr_write;
2292
    chr->chr_add_read_handler = udp_chr_add_read_handler;
2293
    return chr;
2294

    
2295
return_err:
2296
    if (chr)
2297
        free(chr);
2298
    if (s)
2299
        free(s);
2300
    if (fd >= 0)
2301
        closesocket(fd);
2302
    return NULL;
2303
}
2304

    
2305
/***********************************************************/
2306
/* TCP Net console */
2307

    
2308
typedef struct {
2309
    IOCanRWHandler *fd_can_read;
2310
    IOReadHandler *fd_read;
2311
    void *fd_opaque;
2312
    int fd, listen_fd;
2313
    int connected;
2314
    int max_size;
2315
} TCPCharDriver;
2316

    
2317
static void tcp_chr_accept(void *opaque);
2318

    
2319
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2320
{
2321
    TCPCharDriver *s = chr->opaque;
2322
    if (s->connected) {
2323
        return send_all(s->fd, buf, len);
2324
    } else {
2325
        /* XXX: indicate an error ? */
2326
        return len;
2327
    }
2328
}
2329

    
2330
static int tcp_chr_read_poll(void *opaque)
2331
{
2332
    CharDriverState *chr = opaque;
2333
    TCPCharDriver *s = chr->opaque;
2334
    if (!s->connected)
2335
        return 0;
2336
    s->max_size = s->fd_can_read(s->fd_opaque);
2337
    return s->max_size;
2338
}
2339

    
2340
static void tcp_chr_read(void *opaque)
2341
{
2342
    CharDriverState *chr = opaque;
2343
    TCPCharDriver *s = chr->opaque;
2344
    uint8_t buf[1024];
2345
    int len, size;
2346

    
2347
    if (!s->connected || s->max_size <= 0)
2348
        return;
2349
    len = sizeof(buf);
2350
    if (len > s->max_size)
2351
        len = s->max_size;
2352
    size = recv(s->fd, buf, len, 0);
2353
    if (size == 0) {
2354
        /* connection closed */
2355
        s->connected = 0;
2356
        if (s->listen_fd >= 0) {
2357
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2358
        }
2359
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2360
        closesocket(s->fd);
2361
        s->fd = -1;
2362
    } else if (size > 0) {
2363
        s->fd_read(s->fd_opaque, buf, size);
2364
    }
2365
}
2366

    
2367
static void tcp_chr_add_read_handler(CharDriverState *chr,
2368
                                     IOCanRWHandler *fd_can_read,
2369
                                    IOReadHandler *fd_read, void *opaque)
2370
{
2371
    TCPCharDriver *s = chr->opaque;
2372

    
2373
    s->fd_can_read = fd_can_read;
2374
    s->fd_read = fd_read;
2375
    s->fd_opaque = opaque;
2376
}
2377

    
2378
static void tcp_chr_connect(void *opaque)
2379
{
2380
    CharDriverState *chr = opaque;
2381
    TCPCharDriver *s = chr->opaque;
2382

    
2383
    s->connected = 1;
2384
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2385
                         tcp_chr_read, NULL, chr);
2386
}
2387

    
2388
static void tcp_chr_accept(void *opaque)
2389
{
2390
    CharDriverState *chr = opaque;
2391
    TCPCharDriver *s = chr->opaque;
2392
    struct sockaddr_in saddr;
2393
    socklen_t len;
2394
    int fd;
2395

    
2396
    for(;;) {
2397
        len = sizeof(saddr);
2398
        fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2399
        if (fd < 0 && errno != EINTR) {
2400
            return;
2401
        } else if (fd >= 0) {
2402
            break;
2403
        }
2404
    }
2405
    socket_set_nonblock(fd);
2406
    s->fd = fd;
2407
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2408
    tcp_chr_connect(chr);
2409
}
2410

    
2411
static void tcp_chr_close(CharDriverState *chr)
2412
{
2413
    TCPCharDriver *s = chr->opaque;
2414
    if (s->fd >= 0)
2415
        closesocket(s->fd);
2416
    if (s->listen_fd >= 0)
2417
        closesocket(s->listen_fd);
2418
    qemu_free(s);
2419
}
2420

    
2421
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2422
                                          int is_listen)
2423
{
2424
    CharDriverState *chr = NULL;
2425
    TCPCharDriver *s = NULL;
2426
    int fd = -1, ret, err, val;
2427
    struct sockaddr_in saddr;
2428

    
2429
    if (parse_host_port(&saddr, host_str) < 0)
2430
        goto fail;
2431

    
2432
    chr = qemu_mallocz(sizeof(CharDriverState));
2433
    if (!chr)
2434
        goto fail;
2435
    s = qemu_mallocz(sizeof(TCPCharDriver));
2436
    if (!s)
2437
        goto fail;
2438
    
2439
    fd = socket(PF_INET, SOCK_STREAM, 0);
2440
    if (fd < 0) 
2441
        goto fail;
2442
    socket_set_nonblock(fd);
2443

    
2444
    s->connected = 0;
2445
    s->fd = -1;
2446
    s->listen_fd = -1;
2447
    if (is_listen) {
2448
        /* allow fast reuse */
2449
        val = 1;
2450
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2451
        
2452
        ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2453
        if (ret < 0) 
2454
            goto fail;
2455
        ret = listen(fd, 0);
2456
        if (ret < 0)
2457
            goto fail;
2458
        s->listen_fd = fd;
2459
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2460
    } else {
2461
        for(;;) {
2462
            ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2463
            if (ret < 0) {
2464
                err = socket_error();
2465
                if (err == EINTR || err == EWOULDBLOCK) {
2466
                } else if (err == EINPROGRESS) {
2467
                    break;
2468
                } else {
2469
                    goto fail;
2470
                }
2471
            } else {
2472
                s->connected = 1;
2473
                break;
2474
            }
2475
        }
2476
        s->fd = fd;
2477
        if (s->connected)
2478
            tcp_chr_connect(chr);
2479
        else
2480
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2481
    }
2482
    
2483
    chr->opaque = s;
2484
    chr->chr_write = tcp_chr_write;
2485
    chr->chr_add_read_handler = tcp_chr_add_read_handler;
2486
    chr->chr_close = tcp_chr_close;
2487
    return chr;
2488
 fail:
2489
    if (fd >= 0)
2490
        closesocket(fd);
2491
    qemu_free(s);
2492
    qemu_free(chr);
2493
    return NULL;
2494
}
2495

    
2496
CharDriverState *qemu_chr_open(const char *filename)
2497
{
2498
    const char *p;
2499

    
2500
    if (!strcmp(filename, "vc")) {
2501
        return text_console_init(&display_state);
2502
    } else if (!strcmp(filename, "null")) {
2503
        return qemu_chr_open_null();
2504
    } else 
2505
    if (strstart(filename, "tcp:", &p)) {
2506
        return qemu_chr_open_tcp(p, 0);
2507
    } else
2508
    if (strstart(filename, "tcpl:", &p)) {
2509
        return qemu_chr_open_tcp(p, 1);
2510
    } else
2511
    if (strstart(filename, "udp:", &p)) {
2512
        return qemu_chr_open_udp(p);
2513
    } else
2514
#ifndef _WIN32
2515
    if (strstart(filename, "file:", &p)) {
2516
        return qemu_chr_open_file_out(p);
2517
    } else if (strstart(filename, "pipe:", &p)) {
2518
        return qemu_chr_open_pipe(p);
2519
    } else if (!strcmp(filename, "pty")) {
2520
        return qemu_chr_open_pty();
2521
    } else if (!strcmp(filename, "stdio")) {
2522
        return qemu_chr_open_stdio();
2523
    } else 
2524
#endif
2525
#if defined(__linux__)
2526
    if (strstart(filename, "/dev/parport", NULL)) {
2527
        return qemu_chr_open_pp(filename);
2528
    } else 
2529
    if (strstart(filename, "/dev/", NULL)) {
2530
        return qemu_chr_open_tty(filename);
2531
    } else 
2532
#endif
2533
#ifdef _WIN32
2534
    if (strstart(filename, "COM", NULL)) {
2535
        return qemu_chr_open_win(filename);
2536
    } else
2537
    if (strstart(filename, "pipe:", &p)) {
2538
        return qemu_chr_open_win_pipe(p);
2539
    } else
2540
    if (strstart(filename, "file:", &p)) {
2541
        return qemu_chr_open_win_file_out(p);
2542
    }
2543
#endif
2544
    {
2545
        return NULL;
2546
    }
2547
}
2548

    
2549
void qemu_chr_close(CharDriverState *chr)
2550
{
2551
    if (chr->chr_close)
2552
        chr->chr_close(chr);
2553
}
2554

    
2555
/***********************************************************/
2556
/* network device redirectors */
2557

    
2558
void hex_dump(FILE *f, const uint8_t *buf, int size)
2559
{
2560
    int len, i, j, c;
2561

    
2562
    for(i=0;i<size;i+=16) {
2563
        len = size - i;
2564
        if (len > 16)
2565
            len = 16;
2566
        fprintf(f, "%08x ", i);
2567
        for(j=0;j<16;j++) {
2568
            if (j < len)
2569
                fprintf(f, " %02x", buf[i+j]);
2570
            else
2571
                fprintf(f, "   ");
2572
        }
2573
        fprintf(f, " ");
2574
        for(j=0;j<len;j++) {
2575
            c = buf[i+j];
2576
            if (c < ' ' || c > '~')
2577
                c = '.';
2578
            fprintf(f, "%c", c);
2579
        }
2580
        fprintf(f, "\n");
2581
    }
2582
}
2583

    
2584
static int parse_macaddr(uint8_t *macaddr, const char *p)
2585
{
2586
    int i;
2587
    for(i = 0; i < 6; i++) {
2588
        macaddr[i] = strtol(p, (char **)&p, 16);
2589
        if (i == 5) {
2590
            if (*p != '\0') 
2591
                return -1;
2592
        } else {
2593
            if (*p != ':') 
2594
                return -1;
2595
            p++;
2596
        }
2597
    }
2598
    return 0;
2599
}
2600

    
2601
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2602
{
2603
    const char *p, *p1;
2604
    int len;
2605
    p = *pp;
2606
    p1 = strchr(p, sep);
2607
    if (!p1)
2608
        return -1;
2609
    len = p1 - p;
2610
    p1++;
2611
    if (buf_size > 0) {
2612
        if (len > buf_size - 1)
2613
            len = buf_size - 1;
2614
        memcpy(buf, p, len);
2615
        buf[len] = '\0';
2616
    }
2617
    *pp = p1;
2618
    return 0;
2619
}
2620

    
2621
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2622
{
2623
    char buf[512];
2624
    struct hostent *he;
2625
    const char *p, *r;
2626
    int port;
2627

    
2628
    p = str;
2629
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2630
        return -1;
2631
    saddr->sin_family = AF_INET;
2632
    if (buf[0] == '\0') {
2633
        saddr->sin_addr.s_addr = 0;
2634
    } else {
2635
        if (isdigit(buf[0])) {
2636
            if (!inet_aton(buf, &saddr->sin_addr))
2637
                return -1;
2638
        } else {
2639
            if ((he = gethostbyname(buf)) == NULL)
2640
                return - 1;
2641
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2642
        }
2643
    }
2644
    port = strtol(p, (char **)&r, 0);
2645
    if (r == p)
2646
        return -1;
2647
    saddr->sin_port = htons(port);
2648
    return 0;
2649
}
2650

    
2651
/* find or alloc a new VLAN */
2652
VLANState *qemu_find_vlan(int id)
2653
{
2654
    VLANState **pvlan, *vlan;
2655
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2656
        if (vlan->id == id)
2657
            return vlan;
2658
    }
2659
    vlan = qemu_mallocz(sizeof(VLANState));
2660
    if (!vlan)
2661
        return NULL;
2662
    vlan->id = id;
2663
    vlan->next = NULL;
2664
    pvlan = &first_vlan;
2665
    while (*pvlan != NULL)
2666
        pvlan = &(*pvlan)->next;
2667
    *pvlan = vlan;
2668
    return vlan;
2669
}
2670

    
2671
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2672
                                      IOReadHandler *fd_read,
2673
                                      IOCanRWHandler *fd_can_read,
2674
                                      void *opaque)
2675
{
2676
    VLANClientState *vc, **pvc;
2677
    vc = qemu_mallocz(sizeof(VLANClientState));
2678
    if (!vc)
2679
        return NULL;
2680
    vc->fd_read = fd_read;
2681
    vc->fd_can_read = fd_can_read;
2682
    vc->opaque = opaque;
2683
    vc->vlan = vlan;
2684

    
2685
    vc->next = NULL;
2686
    pvc = &vlan->first_client;
2687
    while (*pvc != NULL)
2688
        pvc = &(*pvc)->next;
2689
    *pvc = vc;
2690
    return vc;
2691
}
2692

    
2693
int qemu_can_send_packet(VLANClientState *vc1)
2694
{
2695
    VLANState *vlan = vc1->vlan;
2696
    VLANClientState *vc;
2697

    
2698
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2699
        if (vc != vc1) {
2700
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2701
                return 0;
2702
        }
2703
    }
2704
    return 1;
2705
}
2706

    
2707
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2708
{
2709
    VLANState *vlan = vc1->vlan;
2710
    VLANClientState *vc;
2711

    
2712
#if 0
2713
    printf("vlan %d send:\n", vlan->id);
2714
    hex_dump(stdout, buf, size);
2715
#endif
2716
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2717
        if (vc != vc1) {
2718
            vc->fd_read(vc->opaque, buf, size);
2719
        }
2720
    }
2721
}
2722

    
2723
#if defined(CONFIG_SLIRP)
2724

    
2725
/* slirp network adapter */
2726

    
2727
static int slirp_inited;
2728
static VLANClientState *slirp_vc;
2729

    
2730
int slirp_can_output(void)
2731
{
2732
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
2733
}
2734

    
2735
void slirp_output(const uint8_t *pkt, int pkt_len)
2736
{
2737
#if 0
2738
    printf("slirp output:\n");
2739
    hex_dump(stdout, pkt, pkt_len);
2740
#endif
2741
    if (!slirp_vc)
2742
        return;
2743
    qemu_send_packet(slirp_vc, pkt, pkt_len);
2744
}
2745

    
2746
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2747
{
2748
#if 0
2749
    printf("slirp input:\n");
2750
    hex_dump(stdout, buf, size);
2751
#endif
2752
    slirp_input(buf, size);
2753
}
2754

    
2755
static int net_slirp_init(VLANState *vlan)
2756
{
2757
    if (!slirp_inited) {
2758
        slirp_inited = 1;
2759
        slirp_init();
2760
    }
2761
    slirp_vc = qemu_new_vlan_client(vlan, 
2762
                                    slirp_receive, NULL, NULL);
2763
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2764
    return 0;
2765
}
2766

    
2767
static void net_slirp_redir(const char *redir_str)
2768
{
2769
    int is_udp;
2770
    char buf[256], *r;
2771
    const char *p;
2772
    struct in_addr guest_addr;
2773
    int host_port, guest_port;
2774
    
2775
    if (!slirp_inited) {
2776
        slirp_inited = 1;
2777
        slirp_init();
2778
    }
2779

    
2780
    p = redir_str;
2781
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2782
        goto fail;
2783
    if (!strcmp(buf, "tcp")) {
2784
        is_udp = 0;
2785
    } else if (!strcmp(buf, "udp")) {
2786
        is_udp = 1;
2787
    } else {
2788
        goto fail;
2789
    }
2790

    
2791
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2792
        goto fail;
2793
    host_port = strtol(buf, &r, 0);
2794
    if (r == buf)
2795
        goto fail;
2796

    
2797
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2798
        goto fail;
2799
    if (buf[0] == '\0') {
2800
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
2801
    }
2802
    if (!inet_aton(buf, &guest_addr))
2803
        goto fail;
2804
    
2805
    guest_port = strtol(p, &r, 0);
2806
    if (r == p)
2807
        goto fail;
2808
    
2809
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2810
        fprintf(stderr, "qemu: could not set up redirection\n");
2811
        exit(1);
2812
    }
2813
    return;
2814
 fail:
2815
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2816
    exit(1);
2817
}
2818
    
2819
#ifndef _WIN32
2820

    
2821
char smb_dir[1024];
2822

    
2823
static void smb_exit(void)
2824
{
2825
    DIR *d;
2826
    struct dirent *de;
2827
    char filename[1024];
2828

    
2829
    /* erase all the files in the directory */
2830
    d = opendir(smb_dir);
2831
    for(;;) {
2832
        de = readdir(d);
2833
        if (!de)
2834
            break;
2835
        if (strcmp(de->d_name, ".") != 0 &&
2836
            strcmp(de->d_name, "..") != 0) {
2837
            snprintf(filename, sizeof(filename), "%s/%s", 
2838
                     smb_dir, de->d_name);
2839
            unlink(filename);
2840
        }
2841
    }
2842
    closedir(d);
2843
    rmdir(smb_dir);
2844
}
2845

    
2846
/* automatic user mode samba server configuration */
2847
void net_slirp_smb(const char *exported_dir)
2848
{
2849
    char smb_conf[1024];
2850
    char smb_cmdline[1024];
2851
    FILE *f;
2852

    
2853
    if (!slirp_inited) {
2854
        slirp_inited = 1;
2855
        slirp_init();
2856
    }
2857

    
2858
    /* XXX: better tmp dir construction */
2859
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2860
    if (mkdir(smb_dir, 0700) < 0) {
2861
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2862
        exit(1);
2863
    }
2864
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2865
    
2866
    f = fopen(smb_conf, "w");
2867
    if (!f) {
2868
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2869
        exit(1);
2870
    }
2871
    fprintf(f, 
2872
            "[global]\n"
2873
            "private dir=%s\n"
2874
            "smb ports=0\n"
2875
            "socket address=127.0.0.1\n"
2876
            "pid directory=%s\n"
2877
            "lock directory=%s\n"
2878
            "log file=%s/log.smbd\n"
2879
            "smb passwd file=%s/smbpasswd\n"
2880
            "security = share\n"
2881
            "[qemu]\n"
2882
            "path=%s\n"
2883
            "read only=no\n"
2884
            "guest ok=yes\n",
2885
            smb_dir,
2886
            smb_dir,
2887
            smb_dir,
2888
            smb_dir,
2889
            smb_dir,
2890
            exported_dir
2891
            );
2892
    fclose(f);
2893
    atexit(smb_exit);
2894

    
2895
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2896
             smb_conf);
2897
    
2898
    slirp_add_exec(0, smb_cmdline, 4, 139);
2899
}
2900

    
2901
#endif /* !defined(_WIN32) */
2902

    
2903
#endif /* CONFIG_SLIRP */
2904

    
2905
#if !defined(_WIN32)
2906

    
2907
typedef struct TAPState {
2908
    VLANClientState *vc;
2909
    int fd;
2910
} TAPState;
2911

    
2912
static void tap_receive(void *opaque, const uint8_t *buf, int size)
2913
{
2914
    TAPState *s = opaque;
2915
    int ret;
2916
    for(;;) {
2917
        ret = write(s->fd, buf, size);
2918
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2919
        } else {
2920
            break;
2921
        }
2922
    }
2923
}
2924

    
2925
static void tap_send(void *opaque)
2926
{
2927
    TAPState *s = opaque;
2928
    uint8_t buf[4096];
2929
    int size;
2930

    
2931
    size = read(s->fd, buf, sizeof(buf));
2932
    if (size > 0) {
2933
        qemu_send_packet(s->vc, buf, size);
2934
    }
2935
}
2936

    
2937
/* fd support */
2938

    
2939
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2940
{
2941
    TAPState *s;
2942

    
2943
    s = qemu_mallocz(sizeof(TAPState));
2944
    if (!s)
2945
        return NULL;
2946
    s->fd = fd;
2947
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2948
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2949
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2950
    return s;
2951
}
2952

    
2953
#ifdef _BSD
2954
static int tap_open(char *ifname, int ifname_size)
2955
{
2956
    int fd;
2957
    char *dev;
2958
    struct stat s;
2959

    
2960
    fd = open("/dev/tap", O_RDWR);
2961
    if (fd < 0) {
2962
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2963
        return -1;
2964
    }
2965

    
2966
    fstat(fd, &s);
2967
    dev = devname(s.st_rdev, S_IFCHR);
2968
    pstrcpy(ifname, ifname_size, dev);
2969

    
2970
    fcntl(fd, F_SETFL, O_NONBLOCK);
2971
    return fd;
2972
}
2973
#elif defined(__sun__)
2974
static int tap_open(char *ifname, int ifname_size)
2975
{
2976
    fprintf(stderr, "warning: tap_open not yet implemented\n");
2977
    return -1;
2978
}
2979
#else
2980
static int tap_open(char *ifname, int ifname_size)
2981
{
2982
    struct ifreq ifr;
2983
    int fd, ret;
2984
    
2985
    fd = open("/dev/net/tun", O_RDWR);
2986
    if (fd < 0) {
2987
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2988
        return -1;
2989
    }
2990
    memset(&ifr, 0, sizeof(ifr));
2991
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2992
    if (ifname[0] != '\0')
2993
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2994
    else
2995
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2996
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2997
    if (ret != 0) {
2998
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2999
        close(fd);
3000
        return -1;
3001
    }
3002
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3003
    fcntl(fd, F_SETFL, O_NONBLOCK);
3004
    return fd;
3005
}
3006
#endif
3007

    
3008
static int net_tap_init(VLANState *vlan, const char *ifname1,
3009
                        const char *setup_script)
3010
{
3011
    TAPState *s;
3012
    int pid, status, fd;
3013
    char *args[3];
3014
    char **parg;
3015
    char ifname[128];
3016

    
3017
    if (ifname1 != NULL)
3018
        pstrcpy(ifname, sizeof(ifname), ifname1);
3019
    else
3020
        ifname[0] = '\0';
3021
    fd = tap_open(ifname, sizeof(ifname));
3022
    if (fd < 0)
3023
        return -1;
3024

    
3025
    if (!setup_script)
3026
        setup_script = "";
3027
    if (setup_script[0] != '\0') {
3028
        /* try to launch network init script */
3029
        pid = fork();
3030
        if (pid >= 0) {
3031
            if (pid == 0) {
3032
                parg = args;
3033
                *parg++ = (char *)setup_script;
3034
                *parg++ = ifname;
3035
                *parg++ = NULL;
3036
                execv(setup_script, args);
3037
                _exit(1);
3038
            }
3039
            while (waitpid(pid, &status, 0) != pid);
3040
            if (!WIFEXITED(status) ||
3041
                WEXITSTATUS(status) != 0) {
3042
                fprintf(stderr, "%s: could not launch network script\n",
3043
                        setup_script);
3044
                return -1;
3045
            }
3046
        }
3047
    }
3048
    s = net_tap_fd_init(vlan, fd);
3049
    if (!s)
3050
        return -1;
3051
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3052
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3053
    return 0;
3054
}
3055

    
3056
#endif /* !_WIN32 */
3057

    
3058
/* network connection */
3059
typedef struct NetSocketState {
3060
    VLANClientState *vc;
3061
    int fd;
3062
    int state; /* 0 = getting length, 1 = getting data */
3063
    int index;
3064
    int packet_len;
3065
    uint8_t buf[4096];
3066
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3067
} NetSocketState;
3068

    
3069
typedef struct NetSocketListenState {
3070
    VLANState *vlan;
3071
    int fd;
3072
} NetSocketListenState;
3073

    
3074
/* XXX: we consider we can send the whole packet without blocking */
3075
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3076
{
3077
    NetSocketState *s = opaque;
3078
    uint32_t len;
3079
    len = htonl(size);
3080

    
3081
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3082
    send_all(s->fd, buf, size);
3083
}
3084

    
3085
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3086
{
3087
    NetSocketState *s = opaque;
3088
    sendto(s->fd, buf, size, 0, 
3089
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3090
}
3091

    
3092
static void net_socket_send(void *opaque)
3093
{
3094
    NetSocketState *s = opaque;
3095
    int l, size, err;
3096
    uint8_t buf1[4096];
3097
    const uint8_t *buf;
3098

    
3099
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3100
    if (size < 0) {
3101
        err = socket_error();
3102
        if (err != EWOULDBLOCK) 
3103
            goto eoc;
3104
    } else if (size == 0) {
3105
        /* end of connection */
3106
    eoc:
3107
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3108
        closesocket(s->fd);
3109
        return;
3110
    }
3111
    buf = buf1;
3112
    while (size > 0) {
3113
        /* reassemble a packet from the network */
3114
        switch(s->state) {
3115
        case 0:
3116
            l = 4 - s->index;
3117
            if (l > size)
3118
                l = size;
3119
            memcpy(s->buf + s->index, buf, l);
3120
            buf += l;
3121
            size -= l;
3122
            s->index += l;
3123
            if (s->index == 4) {
3124
                /* got length */
3125
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3126
                s->index = 0;
3127
                s->state = 1;
3128
            }
3129
            break;
3130
        case 1:
3131
            l = s->packet_len - s->index;
3132
            if (l > size)
3133
                l = size;
3134
            memcpy(s->buf + s->index, buf, l);
3135
            s->index += l;
3136
            buf += l;
3137
            size -= l;
3138
            if (s->index >= s->packet_len) {
3139
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3140
                s->index = 0;
3141
                s->state = 0;
3142
            }
3143
            break;
3144
        }
3145
    }
3146
}
3147

    
3148
static void net_socket_send_dgram(void *opaque)
3149
{
3150
    NetSocketState *s = opaque;
3151
    int size;
3152

    
3153
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3154
    if (size < 0) 
3155
        return;
3156
    if (size == 0) {
3157
        /* end of connection */
3158
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3159
        return;
3160
    }
3161
    qemu_send_packet(s->vc, s->buf, size);
3162
}
3163

    
3164
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3165
{
3166
    struct ip_mreq imr;
3167
    int fd;
3168
    int val, ret;
3169
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3170
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3171
                inet_ntoa(mcastaddr->sin_addr), 
3172
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3173
        return -1;
3174

    
3175
    }
3176
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3177
    if (fd < 0) {
3178
        perror("socket(PF_INET, SOCK_DGRAM)");
3179
        return -1;
3180
    }
3181

    
3182
    val = 1;
3183
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3184
                   (const char *)&val, sizeof(val));
3185
    if (ret < 0) {
3186
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3187
        goto fail;
3188
    }
3189

    
3190
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3191
    if (ret < 0) {
3192
        perror("bind");
3193
        goto fail;
3194
    }
3195
    
3196
    /* Add host to multicast group */
3197
    imr.imr_multiaddr = mcastaddr->sin_addr;
3198
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3199

    
3200
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3201
                     (const char *)&imr, sizeof(struct ip_mreq));
3202
    if (ret < 0) {
3203
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3204
        goto fail;
3205
    }
3206

    
3207
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3208
    val = 1;
3209
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3210
                   (const char *)&val, sizeof(val));
3211
    if (ret < 0) {
3212
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3213
        goto fail;
3214
    }
3215

    
3216
    socket_set_nonblock(fd);
3217
    return fd;
3218
fail:
3219
    if (fd >= 0) 
3220
        closesocket(fd);
3221
    return -1;
3222
}
3223

    
3224
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3225
                                          int is_connected)
3226
{
3227
    struct sockaddr_in saddr;
3228
    int newfd;
3229
    socklen_t saddr_len;
3230
    NetSocketState *s;
3231

    
3232
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3233
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3234
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3235
     */
3236

    
3237
    if (is_connected) {
3238
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3239
            /* must be bound */
3240
            if (saddr.sin_addr.s_addr==0) {
3241
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3242
                        fd);
3243
                return NULL;
3244
            }
3245
            /* clone dgram socket */
3246
            newfd = net_socket_mcast_create(&saddr);
3247
            if (newfd < 0) {
3248
                /* error already reported by net_socket_mcast_create() */
3249
                close(fd);
3250
                return NULL;
3251
            }
3252
            /* clone newfd to fd, close newfd */
3253
            dup2(newfd, fd);
3254
            close(newfd);
3255
        
3256
        } else {
3257
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3258
                    fd, strerror(errno));
3259
            return NULL;
3260
        }
3261
    }
3262

    
3263
    s = qemu_mallocz(sizeof(NetSocketState));
3264
    if (!s)
3265
        return NULL;
3266
    s->fd = fd;
3267

    
3268
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3269
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3270

    
3271
    /* mcast: save bound address as dst */
3272
    if (is_connected) s->dgram_dst=saddr;
3273

    
3274
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3275
            "socket: fd=%d (%s mcast=%s:%d)", 
3276
            fd, is_connected? "cloned" : "",
3277
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3278
    return s;
3279
}
3280

    
3281
static void net_socket_connect(void *opaque)
3282
{
3283
    NetSocketState *s = opaque;
3284
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3285
}
3286

    
3287
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3288
                                          int is_connected)
3289
{
3290
    NetSocketState *s;
3291
    s = qemu_mallocz(sizeof(NetSocketState));
3292
    if (!s)
3293
        return NULL;
3294
    s->fd = fd;
3295
    s->vc = qemu_new_vlan_client(vlan, 
3296
                                 net_socket_receive, NULL, s);
3297
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3298
             "socket: fd=%d", fd);
3299
    if (is_connected) {
3300
        net_socket_connect(s);
3301
    } else {
3302
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3303
    }
3304
    return s;
3305
}
3306

    
3307
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3308
                                          int is_connected)
3309
{
3310
    int so_type=-1, optlen=sizeof(so_type);
3311

    
3312
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3313
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3314
        return NULL;
3315
    }
3316
    switch(so_type) {
3317
    case SOCK_DGRAM:
3318
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3319
    case SOCK_STREAM:
3320
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3321
    default:
3322
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3323
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3324
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3325
    }
3326
    return NULL;
3327
}
3328

    
3329
static void net_socket_accept(void *opaque)
3330
{
3331
    NetSocketListenState *s = opaque;    
3332
    NetSocketState *s1;
3333
    struct sockaddr_in saddr;
3334
    socklen_t len;
3335
    int fd;
3336

    
3337
    for(;;) {
3338
        len = sizeof(saddr);
3339
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3340
        if (fd < 0 && errno != EINTR) {
3341
            return;
3342
        } else if (fd >= 0) {
3343
            break;
3344
        }
3345
    }
3346
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3347
    if (!s1) {
3348
        closesocket(fd);
3349
    } else {
3350
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3351
                 "socket: connection from %s:%d", 
3352
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3353
    }
3354
}
3355

    
3356
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3357
{
3358
    NetSocketListenState *s;
3359
    int fd, val, ret;
3360
    struct sockaddr_in saddr;
3361

    
3362
    if (parse_host_port(&saddr, host_str) < 0)
3363
        return -1;
3364
    
3365
    s = qemu_mallocz(sizeof(NetSocketListenState));
3366
    if (!s)
3367
        return -1;
3368

    
3369
    fd = socket(PF_INET, SOCK_STREAM, 0);
3370
    if (fd < 0) {
3371
        perror("socket");
3372
        return -1;
3373
    }
3374
    socket_set_nonblock(fd);
3375

    
3376
    /* allow fast reuse */
3377
    val = 1;
3378
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3379
    
3380
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3381
    if (ret < 0) {
3382
        perror("bind");
3383
        return -1;
3384
    }
3385
    ret = listen(fd, 0);
3386
    if (ret < 0) {
3387
        perror("listen");
3388
        return -1;
3389
    }
3390
    s->vlan = vlan;
3391
    s->fd = fd;
3392
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3393
    return 0;
3394
}
3395

    
3396
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3397
{
3398
    NetSocketState *s;
3399
    int fd, connected, ret, err;
3400
    struct sockaddr_in saddr;
3401

    
3402
    if (parse_host_port(&saddr, host_str) < 0)
3403
        return -1;
3404

    
3405
    fd = socket(PF_INET, SOCK_STREAM, 0);
3406
    if (fd < 0) {
3407
        perror("socket");
3408
        return -1;
3409
    }
3410
    socket_set_nonblock(fd);
3411

    
3412
    connected = 0;
3413
    for(;;) {
3414
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3415
        if (ret < 0) {
3416
            err = socket_error();
3417
            if (err == EINTR || err == EWOULDBLOCK) {
3418
            } else if (err == EINPROGRESS) {
3419
                break;
3420
            } else {
3421
                perror("connect");
3422
                closesocket(fd);
3423
                return -1;
3424
            }
3425
        } else {
3426
            connected = 1;
3427
            break;
3428
        }
3429
    }
3430
    s = net_socket_fd_init(vlan, fd, connected);
3431
    if (!s)
3432
        return -1;
3433
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3434
             "socket: connect to %s:%d", 
3435
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3436
    return 0;
3437
}
3438

    
3439
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3440
{
3441
    NetSocketState *s;
3442
    int fd;
3443
    struct sockaddr_in saddr;
3444

    
3445
    if (parse_host_port(&saddr, host_str) < 0)
3446
        return -1;
3447

    
3448

    
3449
    fd = net_socket_mcast_create(&saddr);
3450
    if (fd < 0)
3451
        return -1;
3452

    
3453
    s = net_socket_fd_init(vlan, fd, 0);
3454
    if (!s)
3455
        return -1;
3456

    
3457
    s->dgram_dst = saddr;
3458
    
3459
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3460
             "socket: mcast=%s:%d", 
3461
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3462
    return 0;
3463

    
3464
}
3465

    
3466
static int get_param_value(char *buf, int buf_size,
3467
                           const char *tag, const char *str)
3468
{
3469
    const char *p;
3470
    char *q;
3471
    char option[128];
3472

    
3473
    p = str;
3474
    for(;;) {
3475
        q = option;
3476
        while (*p != '\0' && *p != '=') {
3477
            if ((q - option) < sizeof(option) - 1)
3478
                *q++ = *p;
3479
            p++;
3480
        }
3481
        *q = '\0';
3482
        if (*p != '=')
3483
            break;
3484
        p++;
3485
        if (!strcmp(tag, option)) {
3486
            q = buf;
3487
            while (*p != '\0' && *p != ',') {
3488
                if ((q - buf) < buf_size - 1)
3489
                    *q++ = *p;
3490
                p++;
3491
            }
3492
            *q = '\0';
3493
            return q - buf;
3494
        } else {
3495
            while (*p != '\0' && *p != ',') {
3496
                p++;
3497
            }
3498
        }
3499
        if (*p != ',')
3500
            break;
3501
        p++;
3502
    }
3503
    return 0;
3504
}
3505

    
3506
int net_client_init(const char *str)
3507
{
3508
    const char *p;
3509
    char *q;
3510
    char device[64];
3511
    char buf[1024];
3512
    int vlan_id, ret;
3513
    VLANState *vlan;
3514

    
3515
    p = str;
3516
    q = device;
3517
    while (*p != '\0' && *p != ',') {
3518
        if ((q - device) < sizeof(device) - 1)
3519
            *q++ = *p;
3520
        p++;
3521
    }
3522
    *q = '\0';
3523
    if (*p == ',')
3524
        p++;
3525
    vlan_id = 0;
3526
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3527
        vlan_id = strtol(buf, NULL, 0);
3528
    }
3529
    vlan = qemu_find_vlan(vlan_id);
3530
    if (!vlan) {
3531
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3532
        return -1;
3533
    }
3534
    if (!strcmp(device, "nic")) {
3535
        NICInfo *nd;
3536
        uint8_t *macaddr;
3537

    
3538
        if (nb_nics >= MAX_NICS) {
3539
            fprintf(stderr, "Too Many NICs\n");
3540
            return -1;
3541
        }
3542
        nd = &nd_table[nb_nics];
3543
        macaddr = nd->macaddr;
3544
        macaddr[0] = 0x52;
3545
        macaddr[1] = 0x54;
3546
        macaddr[2] = 0x00;
3547
        macaddr[3] = 0x12;
3548
        macaddr[4] = 0x34;
3549
        macaddr[5] = 0x56 + nb_nics;
3550

    
3551
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3552
            if (parse_macaddr(macaddr, buf) < 0) {
3553
                fprintf(stderr, "invalid syntax for ethernet address\n");
3554
                return -1;
3555
            }
3556
        }
3557
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3558
            nd->model = strdup(buf);
3559
        }
3560
        nd->vlan = vlan;
3561
        nb_nics++;
3562
        ret = 0;
3563
    } else
3564
    if (!strcmp(device, "none")) {
3565
        /* does nothing. It is needed to signal that no network cards
3566
           are wanted */
3567
        ret = 0;
3568
    } else
3569
#ifdef CONFIG_SLIRP
3570
    if (!strcmp(device, "user")) {
3571
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3572
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3573
        }
3574
        ret = net_slirp_init(vlan);
3575
    } else
3576
#endif
3577
#ifdef _WIN32
3578
    if (!strcmp(device, "tap")) {
3579
        char ifname[64];
3580
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3581
            fprintf(stderr, "tap: no interface name\n");
3582
            return -1;
3583
        }
3584
        ret = tap_win32_init(vlan, ifname);
3585
    } else
3586
#else
3587
    if (!strcmp(device, "tap")) {
3588
        char ifname[64];
3589
        char setup_script[1024];
3590
        int fd;
3591
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3592
            fd = strtol(buf, NULL, 0);
3593
            ret = -1;
3594
            if (net_tap_fd_init(vlan, fd))
3595
                ret = 0;
3596
        } else {
3597
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3598
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3599
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3600
            }
3601
            ret = net_tap_init(vlan, ifname, setup_script);
3602
        }
3603
    } else
3604
#endif
3605
    if (!strcmp(device, "socket")) {
3606
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3607
            int fd;
3608
            fd = strtol(buf, NULL, 0);
3609
            ret = -1;
3610
            if (net_socket_fd_init(vlan, fd, 1))
3611
                ret = 0;
3612
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3613
            ret = net_socket_listen_init(vlan, buf);
3614
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3615
            ret = net_socket_connect_init(vlan, buf);
3616
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3617
            ret = net_socket_mcast_init(vlan, buf);
3618
        } else {
3619
            fprintf(stderr, "Unknown socket options: %s\n", p);
3620
            return -1;
3621
        }
3622
    } else
3623
    {
3624
        fprintf(stderr, "Unknown network device: %s\n", device);
3625
        return -1;
3626
    }
3627
    if (ret < 0) {
3628
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3629
    }
3630
    
3631
    return ret;
3632
}
3633

    
3634
void do_info_network(void)
3635
{
3636
    VLANState *vlan;
3637
    VLANClientState *vc;
3638

    
3639
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3640
        term_printf("VLAN %d devices:\n", vlan->id);
3641
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3642
            term_printf("  %s\n", vc->info_str);
3643
    }
3644
}
3645
 
3646
/***********************************************************/
3647
/* USB devices */
3648

    
3649
static USBPort *used_usb_ports;
3650
static USBPort *free_usb_ports;
3651

    
3652
/* ??? Maybe change this to register a hub to keep track of the topology.  */
3653
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3654
                            usb_attachfn attach)
3655
{
3656
    port->opaque = opaque;
3657
    port->index = index;
3658
    port->attach = attach;
3659
    port->next = free_usb_ports;
3660
    free_usb_ports = port;
3661
}
3662

    
3663
static int usb_device_add(const char *devname)
3664
{
3665
    const char *p;
3666
    USBDevice *dev;
3667
    USBPort *port;
3668

    
3669
    if (!free_usb_ports)
3670
        return -1;
3671

    
3672
    if (strstart(devname, "host:", &p)) {
3673
        dev = usb_host_device_open(p);
3674
    } else if (!strcmp(devname, "mouse")) {
3675
        dev = usb_mouse_init();
3676
    } else if (!strcmp(devname, "tablet")) {
3677
        dev = usb_tablet_init();
3678
    } else if (strstart(devname, "disk:", &p)) {
3679
        dev = usb_msd_init(p);
3680
    } else {
3681
        return -1;
3682
    }
3683
    if (!dev)
3684
        return -1;
3685

    
3686
    /* Find a USB port to add the device to.  */
3687
    port = free_usb_ports;
3688
    if (!port->next) {
3689
        USBDevice *hub;
3690

    
3691
        /* Create a new hub and chain it on.  */
3692
        free_usb_ports = NULL;
3693
        port->next = used_usb_ports;
3694
        used_usb_ports = port;
3695

    
3696
        hub = usb_hub_init(VM_USB_HUB_SIZE);
3697
        usb_attach(port, hub);
3698
        port = free_usb_ports;
3699
    }
3700

    
3701
    free_usb_ports = port->next;
3702
    port->next = used_usb_ports;
3703
    used_usb_ports = port;
3704
    usb_attach(port, dev);
3705
    return 0;
3706
}
3707

    
3708
static int usb_device_del(const char *devname)
3709
{
3710
    USBPort *port;
3711
    USBPort **lastp;
3712
    int bus_num, addr;
3713
    const char *p;
3714

    
3715
    if (!used_usb_ports)
3716
        return -1;
3717

    
3718
    p = strchr(devname, '.');
3719
    if (!p) 
3720
        return -1;
3721
    bus_num = strtoul(devname, NULL, 0);
3722
    addr = strtoul(p + 1, NULL, 0);
3723
    if (bus_num != 0)
3724
        return -1;
3725

    
3726
    lastp = &used_usb_ports;
3727
    port = used_usb_ports;
3728
    while (port && port->dev->addr != addr) {
3729
        lastp = &port->next;
3730
        port = port->next;
3731
    }
3732

    
3733
    if (!port)
3734
        return -1;
3735

    
3736
    *lastp = port->next;
3737
    usb_attach(port, NULL);
3738
    port->next = free_usb_ports;
3739
    free_usb_ports = port;
3740
    return 0;
3741
}
3742

    
3743
void do_usb_add(const char *devname)
3744
{
3745
    int ret;
3746
    ret = usb_device_add(devname);
3747
    if (ret < 0) 
3748
        term_printf("Could not add USB device '%s'\n", devname);
3749
}
3750

    
3751
void do_usb_del(const char *devname)
3752
{
3753
    int ret;
3754
    ret = usb_device_del(devname);
3755
    if (ret < 0) 
3756
        term_printf("Could not remove USB device '%s'\n", devname);
3757
}
3758

    
3759
void usb_info(void)
3760
{
3761
    USBDevice *dev;
3762
    USBPort *port;
3763
    const char *speed_str;
3764

    
3765
    if (!usb_enabled) {
3766
        term_printf("USB support not enabled\n");
3767
        return;
3768
    }
3769

    
3770
    for (port = used_usb_ports; port; port = port->next) {
3771
        dev = port->dev;
3772
        if (!dev)
3773
            continue;
3774
        switch(dev->speed) {
3775
        case USB_SPEED_LOW: 
3776
            speed_str = "1.5"; 
3777
            break;
3778
        case USB_SPEED_FULL: 
3779
            speed_str = "12"; 
3780
            break;
3781
        case USB_SPEED_HIGH: 
3782
            speed_str = "480"; 
3783
            break;
3784
        default:
3785
            speed_str = "?"; 
3786
            break;
3787
        }
3788
        term_printf("  Device %d.%d, speed %s Mb/s\n", 
3789
                    0, dev->addr, speed_str);
3790
    }
3791
}
3792

    
3793
/***********************************************************/
3794
/* pid file */
3795

    
3796
static char *pid_filename;
3797

    
3798
/* Remove PID file. Called on normal exit */
3799

    
3800
static void remove_pidfile(void) 
3801
{
3802
    unlink (pid_filename);
3803
}
3804

    
3805
static void create_pidfile(const char *filename)
3806
{
3807
    struct stat pidstat;
3808
    FILE *f;
3809

    
3810
    /* Try to write our PID to the named file */
3811
    if (stat(filename, &pidstat) < 0) {
3812
        if (errno == ENOENT) {
3813
            if ((f = fopen (filename, "w")) == NULL) {
3814
                perror("Opening pidfile");
3815
                exit(1);
3816
            }
3817
            fprintf(f, "%d\n", getpid());
3818
            fclose(f);
3819
            pid_filename = qemu_strdup(filename);
3820
            if (!pid_filename) {
3821
                fprintf(stderr, "Could not save PID filename");
3822
                exit(1);
3823
            }
3824
            atexit(remove_pidfile);
3825
        }
3826
    } else {
3827
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
3828
                filename);
3829
        exit(1);
3830
    }
3831
}
3832

    
3833
/***********************************************************/
3834
/* dumb display */
3835

    
3836
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3837
{
3838
}
3839

    
3840
static void dumb_resize(DisplayState *ds, int w, int h)
3841
{
3842
}
3843

    
3844
static void dumb_refresh(DisplayState *ds)
3845
{
3846
    vga_hw_update();
3847
}
3848

    
3849
void dumb_display_init(DisplayState *ds)
3850
{
3851
    ds->data = NULL;
3852
    ds->linesize = 0;
3853
    ds->depth = 0;
3854
    ds->dpy_update = dumb_update;
3855
    ds->dpy_resize = dumb_resize;
3856
    ds->dpy_refresh = dumb_refresh;
3857
}
3858

    
3859
/***********************************************************/
3860
/* I/O handling */
3861

    
3862
#define MAX_IO_HANDLERS 64
3863

    
3864
typedef struct IOHandlerRecord {
3865
    int fd;
3866
    IOCanRWHandler *fd_read_poll;
3867
    IOHandler *fd_read;
3868
    IOHandler *fd_write;
3869
    void *opaque;
3870
    /* temporary data */
3871
    struct pollfd *ufd;
3872
    struct IOHandlerRecord *next;
3873
} IOHandlerRecord;
3874

    
3875
static IOHandlerRecord *first_io_handler;
3876

    
3877
/* XXX: fd_read_poll should be suppressed, but an API change is
3878
   necessary in the character devices to suppress fd_can_read(). */
3879
int qemu_set_fd_handler2(int fd, 
3880
                         IOCanRWHandler *fd_read_poll, 
3881
                         IOHandler *fd_read, 
3882
                         IOHandler *fd_write, 
3883
                         void *opaque)
3884
{
3885
    IOHandlerRecord **pioh, *ioh;
3886

    
3887
    if (!fd_read && !fd_write) {
3888
        pioh = &first_io_handler;
3889
        for(;;) {
3890
            ioh = *pioh;
3891
            if (ioh == NULL)
3892
                break;
3893
            if (ioh->fd == fd) {
3894
                *pioh = ioh->next;
3895
                qemu_free(ioh);
3896
                break;
3897
            }
3898
            pioh = &ioh->next;
3899
        }
3900
    } else {
3901
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3902
            if (ioh->fd == fd)
3903
                goto found;
3904
        }
3905
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3906
        if (!ioh)
3907
            return -1;
3908
        ioh->next = first_io_handler;
3909
        first_io_handler = ioh;
3910
    found:
3911
        ioh->fd = fd;
3912
        ioh->fd_read_poll = fd_read_poll;
3913
        ioh->fd_read = fd_read;
3914
        ioh->fd_write = fd_write;
3915
        ioh->opaque = opaque;
3916
    }
3917
    return 0;
3918
}
3919

    
3920
int qemu_set_fd_handler(int fd, 
3921
                        IOHandler *fd_read, 
3922
                        IOHandler *fd_write, 
3923
                        void *opaque)
3924
{
3925
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3926
}
3927

    
3928
/***********************************************************/
3929
/* Polling handling */
3930

    
3931
typedef struct PollingEntry {
3932
    PollingFunc *func;
3933
    void *opaque;
3934
    struct PollingEntry *next;
3935
} PollingEntry;
3936

    
3937
static PollingEntry *first_polling_entry;
3938

    
3939
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3940
{
3941
    PollingEntry **ppe, *pe;
3942
    pe = qemu_mallocz(sizeof(PollingEntry));
3943
    if (!pe)
3944
        return -1;
3945
    pe->func = func;
3946
    pe->opaque = opaque;
3947
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3948
    *ppe = pe;
3949
    return 0;
3950
}
3951

    
3952
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3953
{
3954
    PollingEntry **ppe, *pe;
3955
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3956
        pe = *ppe;
3957
        if (pe->func == func && pe->opaque == opaque) {
3958
            *ppe = pe->next;
3959
            qemu_free(pe);
3960
            break;
3961
        }
3962
    }
3963
}
3964

    
3965
#ifdef _WIN32
3966
/***********************************************************/
3967
/* Wait objects support */
3968
typedef struct WaitObjects {
3969
    int num;
3970
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3971
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3972
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3973
} WaitObjects;
3974

    
3975
static WaitObjects wait_objects = {0};
3976
    
3977
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3978
{
3979
    WaitObjects *w = &wait_objects;
3980

    
3981
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
3982
        return -1;
3983
    w->events[w->num] = handle;
3984
    w->func[w->num] = func;
3985
    w->opaque[w->num] = opaque;
3986
    w->num++;
3987
    return 0;
3988
}
3989

    
3990
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3991
{
3992
    int i, found;
3993
    WaitObjects *w = &wait_objects;
3994

    
3995
    found = 0;
3996
    for (i = 0; i < w->num; i++) {
3997
        if (w->events[i] == handle)
3998
            found = 1;
3999
        if (found) {
4000
            w->events[i] = w->events[i + 1];
4001
            w->func[i] = w->func[i + 1];
4002
            w->opaque[i] = w->opaque[i + 1];
4003
        }            
4004
    }
4005
    if (found)
4006
        w->num--;
4007
}
4008
#endif
4009

    
4010
/***********************************************************/
4011
/* savevm/loadvm support */
4012

    
4013
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4014
{
4015
    fwrite(buf, 1, size, f);
4016
}
4017

    
4018
void qemu_put_byte(QEMUFile *f, int v)
4019
{
4020
    fputc(v, f);
4021
}
4022

    
4023
void qemu_put_be16(QEMUFile *f, unsigned int v)
4024
{
4025
    qemu_put_byte(f, v >> 8);
4026
    qemu_put_byte(f, v);
4027
}
4028

    
4029
void qemu_put_be32(QEMUFile *f, unsigned int v)
4030
{
4031
    qemu_put_byte(f, v >> 24);
4032
    qemu_put_byte(f, v >> 16);
4033
    qemu_put_byte(f, v >> 8);
4034
    qemu_put_byte(f, v);
4035
}
4036

    
4037
void qemu_put_be64(QEMUFile *f, uint64_t v)
4038
{
4039
    qemu_put_be32(f, v >> 32);
4040
    qemu_put_be32(f, v);
4041
}
4042

    
4043
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
4044
{
4045
    return fread(buf, 1, size, f);
4046
}
4047

    
4048
int qemu_get_byte(QEMUFile *f)
4049
{
4050
    int v;
4051
    v = fgetc(f);
4052
    if (v == EOF)
4053
        return 0;
4054
    else
4055
        return v;
4056
}
4057

    
4058
unsigned int qemu_get_be16(QEMUFile *f)
4059
{
4060
    unsigned int v;
4061
    v = qemu_get_byte(f) << 8;
4062
    v |= qemu_get_byte(f);
4063
    return v;
4064
}
4065

    
4066
unsigned int qemu_get_be32(QEMUFile *f)
4067
{
4068
    unsigned int v;
4069
    v = qemu_get_byte(f) << 24;
4070
    v |= qemu_get_byte(f) << 16;
4071
    v |= qemu_get_byte(f) << 8;
4072
    v |= qemu_get_byte(f);
4073
    return v;
4074
}
4075

    
4076
uint64_t qemu_get_be64(QEMUFile *f)
4077
{
4078
    uint64_t v;
4079
    v = (uint64_t)qemu_get_be32(f) << 32;
4080
    v |= qemu_get_be32(f);
4081
    return v;
4082
}
4083

    
4084
int64_t qemu_ftell(QEMUFile *f)
4085
{
4086
    return ftell(f);
4087
}
4088

    
4089
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4090
{
4091
    if (fseek(f, pos, whence) < 0)
4092
        return -1;
4093
    return ftell(f);
4094
}
4095

    
4096
typedef struct SaveStateEntry {
4097
    char idstr[256];
4098
    int instance_id;
4099
    int version_id;
4100
    SaveStateHandler *save_state;
4101
    LoadStateHandler *load_state;
4102
    void *opaque;
4103
    struct SaveStateEntry *next;
4104
} SaveStateEntry;
4105

    
4106
static SaveStateEntry *first_se;
4107

    
4108
int register_savevm(const char *idstr, 
4109
                    int instance_id, 
4110
                    int version_id,
4111
                    SaveStateHandler *save_state,
4112
                    LoadStateHandler *load_state,
4113
                    void *opaque)
4114
{
4115
    SaveStateEntry *se, **pse;
4116

    
4117
    se = qemu_malloc(sizeof(SaveStateEntry));
4118
    if (!se)
4119
        return -1;
4120
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4121
    se->instance_id = instance_id;
4122
    se->version_id = version_id;
4123
    se->save_state = save_state;
4124
    se->load_state = load_state;
4125
    se->opaque = opaque;
4126
    se->next = NULL;
4127

    
4128
    /* add at the end of list */
4129
    pse = &first_se;
4130
    while (*pse != NULL)
4131
        pse = &(*pse)->next;
4132
    *pse = se;
4133
    return 0;
4134
}
4135

    
4136
#define QEMU_VM_FILE_MAGIC   0x5145564d
4137
#define QEMU_VM_FILE_VERSION 0x00000001
4138

    
4139
int qemu_savevm(const char *filename)
4140
{
4141
    SaveStateEntry *se;
4142
    QEMUFile *f;
4143
    int len, len_pos, cur_pos, saved_vm_running, ret;
4144

    
4145
    saved_vm_running = vm_running;
4146
    vm_stop(0);
4147

    
4148
    f = fopen(filename, "wb");
4149
    if (!f) {
4150
        ret = -1;
4151
        goto the_end;
4152
    }
4153

    
4154
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4155
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4156

    
4157
    for(se = first_se; se != NULL; se = se->next) {
4158
        /* ID string */
4159
        len = strlen(se->idstr);
4160
        qemu_put_byte(f, len);
4161
        qemu_put_buffer(f, se->idstr, len);
4162

    
4163
        qemu_put_be32(f, se->instance_id);
4164
        qemu_put_be32(f, se->version_id);
4165

    
4166
        /* record size: filled later */
4167
        len_pos = ftell(f);
4168
        qemu_put_be32(f, 0);
4169
        
4170
        se->save_state(f, se->opaque);
4171

    
4172
        /* fill record size */
4173
        cur_pos = ftell(f);
4174
        len = ftell(f) - len_pos - 4;
4175
        fseek(f, len_pos, SEEK_SET);
4176
        qemu_put_be32(f, len);
4177
        fseek(f, cur_pos, SEEK_SET);
4178
    }
4179

    
4180
    fclose(f);
4181
    ret = 0;
4182
 the_end:
4183
    if (saved_vm_running)
4184
        vm_start();
4185
    return ret;
4186
}
4187

    
4188
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4189
{
4190
    SaveStateEntry *se;
4191

    
4192
    for(se = first_se; se != NULL; se = se->next) {
4193
        if (!strcmp(se->idstr, idstr) && 
4194
            instance_id == se->instance_id)
4195
            return se;
4196
    }
4197
    return NULL;
4198
}
4199

    
4200
int qemu_loadvm(const char *filename)
4201
{
4202
    SaveStateEntry *se;
4203
    QEMUFile *f;
4204
    int len, cur_pos, ret, instance_id, record_len, version_id;
4205
    int saved_vm_running;
4206
    unsigned int v;
4207
    char idstr[256];
4208
    
4209
    saved_vm_running = vm_running;
4210
    vm_stop(0);
4211

    
4212
    f = fopen(filename, "rb");
4213
    if (!f) {
4214
        ret = -1;
4215
        goto the_end;
4216
    }
4217

    
4218
    v = qemu_get_be32(f);
4219
    if (v != QEMU_VM_FILE_MAGIC)
4220
        goto fail;
4221
    v = qemu_get_be32(f);
4222
    if (v != QEMU_VM_FILE_VERSION) {
4223
    fail:
4224
        fclose(f);
4225
        ret = -1;
4226
        goto the_end;
4227
    }
4228
    for(;;) {
4229
        len = qemu_get_byte(f);
4230
        if (feof(f))
4231
            break;
4232
        qemu_get_buffer(f, idstr, len);
4233
        idstr[len] = '\0';
4234
        instance_id = qemu_get_be32(f);
4235
        version_id = qemu_get_be32(f);
4236
        record_len = qemu_get_be32(f);
4237
#if 0
4238
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4239
               idstr, instance_id, version_id, record_len);
4240
#endif
4241
        cur_pos = ftell(f);
4242
        se = find_se(idstr, instance_id);
4243
        if (!se) {
4244
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4245
                    instance_id, idstr);
4246
        } else {
4247
            ret = se->load_state(f, se->opaque, version_id);
4248
            if (ret < 0) {
4249
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4250
                        instance_id, idstr);
4251
            }
4252
        }
4253
        /* always seek to exact end of record */
4254
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4255
    }
4256
    fclose(f);
4257
    ret = 0;
4258
 the_end:
4259
    if (saved_vm_running)
4260
        vm_start();
4261
    return ret;
4262
}
4263

    
4264
/***********************************************************/
4265
/* cpu save/restore */
4266

    
4267
#if defined(TARGET_I386)
4268

    
4269
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4270
{
4271
    qemu_put_be32(f, dt->selector);
4272
    qemu_put_betl(f, dt->base);
4273
    qemu_put_be32(f, dt->limit);
4274
    qemu_put_be32(f, dt->flags);
4275
}
4276

    
4277
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4278
{
4279
    dt->selector = qemu_get_be32(f);
4280
    dt->base = qemu_get_betl(f);
4281
    dt->limit = qemu_get_be32(f);
4282
    dt->flags = qemu_get_be32(f);
4283
}
4284

    
4285
void cpu_save(QEMUFile *f, void *opaque)
4286
{
4287
    CPUState *env = opaque;
4288
    uint16_t fptag, fpus, fpuc, fpregs_format;
4289
    uint32_t hflags;
4290
    int i;
4291
    
4292
    for(i = 0; i < CPU_NB_REGS; i++)
4293
        qemu_put_betls(f, &env->regs[i]);
4294
    qemu_put_betls(f, &env->eip);
4295
    qemu_put_betls(f, &env->eflags);
4296
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4297
    qemu_put_be32s(f, &hflags);
4298
    
4299
    /* FPU */
4300
    fpuc = env->fpuc;
4301
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4302
    fptag = 0;
4303
    for(i = 0; i < 8; i++) {
4304
        fptag |= ((!env->fptags[i]) << i);
4305
    }
4306
    
4307
    qemu_put_be16s(f, &fpuc);
4308
    qemu_put_be16s(f, &fpus);
4309
    qemu_put_be16s(f, &fptag);
4310

    
4311
#ifdef USE_X86LDOUBLE
4312
    fpregs_format = 0;
4313
#else
4314
    fpregs_format = 1;
4315
#endif
4316
    qemu_put_be16s(f, &fpregs_format);
4317
    
4318
    for(i = 0; i < 8; i++) {
4319
#ifdef USE_X86LDOUBLE
4320
        {
4321
            uint64_t mant;
4322
            uint16_t exp;
4323
            /* we save the real CPU data (in case of MMX usage only 'mant'
4324
               contains the MMX register */
4325
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4326
            qemu_put_be64(f, mant);
4327
            qemu_put_be16(f, exp);
4328
        }
4329
#else
4330
        /* if we use doubles for float emulation, we save the doubles to
4331
           avoid losing information in case of MMX usage. It can give
4332
           problems if the image is restored on a CPU where long
4333
           doubles are used instead. */
4334
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4335
#endif
4336
    }
4337

    
4338
    for(i = 0; i < 6; i++)
4339
        cpu_put_seg(f, &env->segs[i]);
4340
    cpu_put_seg(f, &env->ldt);
4341
    cpu_put_seg(f, &env->tr);
4342
    cpu_put_seg(f, &env->gdt);
4343
    cpu_put_seg(f, &env->idt);
4344
    
4345
    qemu_put_be32s(f, &env->sysenter_cs);
4346
    qemu_put_be32s(f, &env->sysenter_esp);
4347
    qemu_put_be32s(f, &env->sysenter_eip);
4348
    
4349
    qemu_put_betls(f, &env->cr[0]);
4350
    qemu_put_betls(f, &env->cr[2]);
4351
    qemu_put_betls(f, &env->cr[3]);
4352
    qemu_put_betls(f, &env->cr[4]);
4353
    
4354
    for(i = 0; i < 8; i++)
4355
        qemu_put_betls(f, &env->dr[i]);
4356

    
4357
    /* MMU */
4358
    qemu_put_be32s(f, &env->a20_mask);
4359

    
4360
    /* XMM */
4361
    qemu_put_be32s(f, &env->mxcsr);
4362
    for(i = 0; i < CPU_NB_REGS; i++) {
4363
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4364
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4365
    }
4366

    
4367
#ifdef TARGET_X86_64
4368
    qemu_put_be64s(f, &env->efer);
4369
    qemu_put_be64s(f, &env->star);
4370
    qemu_put_be64s(f, &env->lstar);
4371
    qemu_put_be64s(f, &env->cstar);
4372
    qemu_put_be64s(f, &env->fmask);
4373
    qemu_put_be64s(f, &env->kernelgsbase);
4374
#endif
4375
}
4376

    
4377
#ifdef USE_X86LDOUBLE
4378
/* XXX: add that in a FPU generic layer */
4379
union x86_longdouble {
4380
    uint64_t mant;
4381
    uint16_t exp;
4382
};
4383

    
4384
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
4385
#define EXPBIAS1 1023
4386
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
4387
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
4388

    
4389
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4390
{
4391
    int e;
4392
    /* mantissa */
4393
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4394
    /* exponent + sign */
4395
    e = EXPD1(temp) - EXPBIAS1 + 16383;
4396
    e |= SIGND1(temp) >> 16;
4397
    p->exp = e;
4398
}
4399
#endif
4400

    
4401
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4402
{
4403
    CPUState *env = opaque;
4404
    int i, guess_mmx;
4405
    uint32_t hflags;
4406
    uint16_t fpus, fpuc, fptag, fpregs_format;
4407

    
4408
    if (version_id != 3)
4409
        return -EINVAL;
4410
    for(i = 0; i < CPU_NB_REGS; i++)
4411
        qemu_get_betls(f, &env->regs[i]);
4412
    qemu_get_betls(f, &env->eip);
4413
    qemu_get_betls(f, &env->eflags);
4414
    qemu_get_be32s(f, &hflags);
4415

    
4416
    qemu_get_be16s(f, &fpuc);
4417
    qemu_get_be16s(f, &fpus);
4418
    qemu_get_be16s(f, &fptag);
4419
    qemu_get_be16s(f, &fpregs_format);
4420
    
4421
    /* NOTE: we cannot always restore the FPU state if the image come
4422
       from a host with a different 'USE_X86LDOUBLE' define. We guess
4423
       if we are in an MMX state to restore correctly in that case. */
4424
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4425
    for(i = 0; i < 8; i++) {
4426
        uint64_t mant;
4427
        uint16_t exp;
4428
        
4429
        switch(fpregs_format) {
4430
        case 0:
4431
            mant = qemu_get_be64(f);
4432
            exp = qemu_get_be16(f);
4433
#ifdef USE_X86LDOUBLE
4434
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
4435
#else
4436
            /* difficult case */
4437
            if (guess_mmx)
4438
                env->fpregs[i].mmx.MMX_Q(0) = mant;
4439
            else
4440
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
4441
#endif
4442
            break;
4443
        case 1:
4444
            mant = qemu_get_be64(f);
4445
#ifdef USE_X86LDOUBLE
4446
            {
4447
                union x86_longdouble *p;
4448
                /* difficult case */
4449
                p = (void *)&env->fpregs[i];
4450
                if (guess_mmx) {
4451
                    p->mant = mant;
4452
                    p->exp = 0xffff;
4453
                } else {
4454
                    fp64_to_fp80(p, mant);
4455
                }
4456
            }
4457
#else
4458
            env->fpregs[i].mmx.MMX_Q(0) = mant;
4459
#endif            
4460
            break;
4461
        default:
4462
            return -EINVAL;
4463
        }
4464
    }
4465

    
4466
    env->fpuc = fpuc;
4467
    /* XXX: restore FPU round state */
4468
    env->fpstt = (fpus >> 11) & 7;
4469
    env->fpus = fpus & ~0x3800;
4470
    fptag ^= 0xff;
4471
    for(i = 0; i < 8; i++) {
4472
        env->fptags[i] = (fptag >> i) & 1;
4473
    }
4474
    
4475
    for(i = 0; i < 6; i++)
4476
        cpu_get_seg(f, &env->segs[i]);
4477
    cpu_get_seg(f, &env->ldt);
4478
    cpu_get_seg(f, &env->tr);
4479
    cpu_get_seg(f, &env->gdt);
4480
    cpu_get_seg(f, &env->idt);
4481
    
4482
    qemu_get_be32s(f, &env->sysenter_cs);
4483
    qemu_get_be32s(f, &env->sysenter_esp);
4484
    qemu_get_be32s(f, &env->sysenter_eip);
4485
    
4486
    qemu_get_betls(f, &env->cr[0]);
4487
    qemu_get_betls(f, &env->cr[2]);
4488
    qemu_get_betls(f, &env->cr[3]);
4489
    qemu_get_betls(f, &env->cr[4]);
4490
    
4491
    for(i = 0; i < 8; i++)
4492
        qemu_get_betls(f, &env->dr[i]);
4493

    
4494
    /* MMU */
4495
    qemu_get_be32s(f, &env->a20_mask);
4496

    
4497
    qemu_get_be32s(f, &env->mxcsr);
4498
    for(i = 0; i < CPU_NB_REGS; i++) {
4499
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4500
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4501
    }
4502

    
4503
#ifdef TARGET_X86_64
4504
    qemu_get_be64s(f, &env->efer);
4505
    qemu_get_be64s(f, &env->star);
4506
    qemu_get_be64s(f, &env->lstar);
4507
    qemu_get_be64s(f, &env->cstar);
4508
    qemu_get_be64s(f, &env->fmask);
4509
    qemu_get_be64s(f, &env->kernelgsbase);
4510
#endif
4511

    
4512
    /* XXX: compute hflags from scratch, except for CPL and IIF */
4513
    env->hflags = hflags;
4514
    tlb_flush(env, 1);
4515
    return 0;
4516
}
4517

    
4518
#elif defined(TARGET_PPC)
4519
void cpu_save(QEMUFile *f, void *opaque)
4520
{
4521
}
4522

    
4523
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4524
{
4525
    return 0;
4526
}
4527

    
4528
#elif defined(TARGET_MIPS)
4529
void cpu_save(QEMUFile *f, void *opaque)
4530
{
4531
}
4532

    
4533
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4534
{
4535
    return 0;
4536
}
4537

    
4538
#elif defined(TARGET_SPARC)
4539
void cpu_save(QEMUFile *f, void *opaque)
4540
{
4541
    CPUState *env = opaque;
4542
    int i;
4543
    uint32_t tmp;
4544

    
4545
    for(i = 0; i < 8; i++)
4546
        qemu_put_betls(f, &env->gregs[i]);
4547
    for(i = 0; i < NWINDOWS * 16; i++)
4548
        qemu_put_betls(f, &env->regbase[i]);
4549

    
4550
    /* FPU */
4551
    for(i = 0; i < TARGET_FPREGS; i++) {
4552
        union {
4553
            float32 f;
4554
            uint32_t i;
4555
        } u;
4556
        u.f = env->fpr[i];
4557
        qemu_put_be32(f, u.i);
4558
    }
4559

    
4560
    qemu_put_betls(f, &env->pc);
4561
    qemu_put_betls(f, &env->npc);
4562
    qemu_put_betls(f, &env->y);
4563
    tmp = GET_PSR(env);
4564
    qemu_put_be32(f, tmp);
4565
    qemu_put_betls(f, &env->fsr);
4566
    qemu_put_betls(f, &env->tbr);
4567
#ifndef TARGET_SPARC64
4568
    qemu_put_be32s(f, &env->wim);
4569
    /* MMU */
4570
    for(i = 0; i < 16; i++)
4571
        qemu_put_be32s(f, &env->mmuregs[i]);
4572
#endif
4573
}
4574

    
4575
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4576
{
4577
    CPUState *env = opaque;
4578
    int i;
4579
    uint32_t tmp;
4580

    
4581
    for(i = 0; i < 8; i++)
4582
        qemu_get_betls(f, &env->gregs[i]);
4583
    for(i = 0; i < NWINDOWS * 16; i++)
4584
        qemu_get_betls(f, &env->regbase[i]);
4585

    
4586
    /* FPU */
4587
    for(i = 0; i < TARGET_FPREGS; i++) {
4588
        union {
4589
            float32 f;
4590
            uint32_t i;
4591
        } u;
4592
        u.i = qemu_get_be32(f);
4593
        env->fpr[i] = u.f;
4594
    }
4595

    
4596
    qemu_get_betls(f, &env->pc);
4597
    qemu_get_betls(f, &env->npc);
4598
    qemu_get_betls(f, &env->y);
4599
    tmp = qemu_get_be32(f);
4600
    env->cwp = 0; /* needed to ensure that the wrapping registers are
4601
                     correctly updated */
4602
    PUT_PSR(env, tmp);
4603
    qemu_get_betls(f, &env->fsr);
4604
    qemu_get_betls(f, &env->tbr);
4605
#ifndef TARGET_SPARC64
4606
    qemu_get_be32s(f, &env->wim);
4607
    /* MMU */
4608
    for(i = 0; i < 16; i++)
4609
        qemu_get_be32s(f, &env->mmuregs[i]);
4610
#endif
4611
    tlb_flush(env, 1);
4612
    return 0;
4613
}
4614

    
4615
#elif defined(TARGET_ARM)
4616

    
4617
/* ??? Need to implement these.  */
4618
void cpu_save(QEMUFile *f, void *opaque)
4619
{
4620
}
4621

    
4622
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4623
{
4624
    return 0;
4625
}
4626

    
4627
#else
4628

    
4629
#warning No CPU save/restore functions
4630

    
4631
#endif
4632

    
4633
/***********************************************************/
4634
/* ram save/restore */
4635

    
4636
/* we just avoid storing empty pages */
4637
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4638
{
4639
    int i, v;
4640

    
4641
    v = buf[0];
4642
    for(i = 1; i < len; i++) {
4643
        if (buf[i] != v)
4644
            goto normal_save;
4645
    }
4646
    qemu_put_byte(f, 1);
4647
    qemu_put_byte(f, v);
4648
    return;
4649
 normal_save:
4650
    qemu_put_byte(f, 0); 
4651
    qemu_put_buffer(f, buf, len);
4652
}
4653

    
4654
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4655
{
4656
    int v;
4657

    
4658
    v = qemu_get_byte(f);
4659
    switch(v) {
4660
    case 0:
4661
        if (qemu_get_buffer(f, buf, len) != len)
4662
            return -EIO;
4663
        break;
4664
    case 1:
4665
        v = qemu_get_byte(f);
4666
        memset(buf, v, len);
4667
        break;
4668
    default:
4669
        return -EINVAL;
4670
    }
4671
    return 0;
4672
}
4673

    
4674
static void ram_save(QEMUFile *f, void *opaque)
4675
{
4676
    int i;
4677
    qemu_put_be32(f, phys_ram_size);
4678
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4679
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4680
    }
4681
}
4682

    
4683
static int ram_load(QEMUFile *f, void *opaque, int version_id)
4684
{
4685
    int i, ret;
4686

    
4687
    if (version_id != 1)
4688
        return -EINVAL;
4689
    if (qemu_get_be32(f) != phys_ram_size)
4690
        return -EINVAL;
4691
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4692
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4693
        if (ret)
4694
            return ret;
4695
    }
4696
    return 0;
4697
}
4698

    
4699
/***********************************************************/
4700
/* machine registration */
4701

    
4702
QEMUMachine *first_machine = NULL;
4703

    
4704
int qemu_register_machine(QEMUMachine *m)
4705
{
4706
    QEMUMachine **pm;
4707
    pm = &first_machine;
4708
    while (*pm != NULL)
4709
        pm = &(*pm)->next;
4710
    m->next = NULL;
4711
    *pm = m;
4712
    return 0;
4713
}
4714

    
4715
QEMUMachine *find_machine(const char *name)
4716
{
4717
    QEMUMachine *m;
4718

    
4719
    for(m = first_machine; m != NULL; m = m->next) {
4720
        if (!strcmp(m->name, name))
4721
            return m;
4722
    }
4723
    return NULL;
4724
}
4725

    
4726
/***********************************************************/
4727
/* main execution loop */
4728

    
4729
void gui_update(void *opaque)
4730
{
4731
    display_state.dpy_refresh(&display_state);
4732
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4733
}
4734

    
4735
struct vm_change_state_entry {
4736
    VMChangeStateHandler *cb;
4737
    void *opaque;
4738
    LIST_ENTRY (vm_change_state_entry) entries;
4739
};
4740

    
4741
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4742

    
4743
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4744
                                                     void *opaque)
4745
{
4746
    VMChangeStateEntry *e;
4747

    
4748
    e = qemu_mallocz(sizeof (*e));
4749
    if (!e)
4750
        return NULL;
4751

    
4752
    e->cb = cb;
4753
    e->opaque = opaque;
4754
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4755
    return e;
4756
}
4757

    
4758
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4759
{
4760
    LIST_REMOVE (e, entries);
4761
    qemu_free (e);
4762
}
4763

    
4764
static void vm_state_notify(int running)
4765
{
4766
    VMChangeStateEntry *e;
4767

    
4768
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4769
        e->cb(e->opaque, running);
4770
    }
4771
}
4772

    
4773
/* XXX: support several handlers */
4774
static VMStopHandler *vm_stop_cb;
4775
static void *vm_stop_opaque;
4776

    
4777
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4778
{
4779
    vm_stop_cb = cb;
4780
    vm_stop_opaque = opaque;
4781
    return 0;
4782
}
4783

    
4784
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4785
{
4786
    vm_stop_cb = NULL;
4787
}
4788

    
4789
void vm_start(void)
4790
{
4791
    if (!vm_running) {
4792
        cpu_enable_ticks();
4793
        vm_running = 1;
4794
        vm_state_notify(1);
4795
    }
4796
}
4797

    
4798
void vm_stop(int reason) 
4799
{
4800
    if (vm_running) {
4801
        cpu_disable_ticks();
4802
        vm_running = 0;
4803
        if (reason != 0) {
4804
            if (vm_stop_cb) {
4805
                vm_stop_cb(vm_stop_opaque, reason);
4806
            }
4807
        }
4808
        vm_state_notify(0);
4809
    }
4810
}
4811

    
4812
/* reset/shutdown handler */
4813

    
4814
typedef struct QEMUResetEntry {
4815
    QEMUResetHandler *func;
4816
    void *opaque;
4817
    struct QEMUResetEntry *next;
4818
} QEMUResetEntry;
4819

    
4820
static QEMUResetEntry *first_reset_entry;
4821
static int reset_requested;
4822
static int shutdown_requested;
4823
static int powerdown_requested;
4824

    
4825
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4826
{
4827
    QEMUResetEntry **pre, *re;
4828

    
4829
    pre = &first_reset_entry;
4830
    while (*pre != NULL)
4831
        pre = &(*pre)->next;
4832
    re = qemu_mallocz(sizeof(QEMUResetEntry));
4833
    re->func = func;
4834
    re->opaque = opaque;
4835
    re->next = NULL;
4836
    *pre = re;
4837
}
4838

    
4839
void qemu_system_reset(void)
4840
{
4841
    QEMUResetEntry *re;
4842

    
4843
    /* reset all devices */
4844
    for(re = first_reset_entry; re != NULL; re = re->next) {
4845
        re->func(re->opaque);
4846
    }
4847
}
4848

    
4849
void qemu_system_reset_request(void)
4850
{
4851
    reset_requested = 1;
4852
    if (cpu_single_env)
4853
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4854
}
4855

    
4856
void qemu_system_shutdown_request(void)
4857
{
4858
    shutdown_requested = 1;
4859
    if (cpu_single_env)
4860
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4861
}
4862

    
4863
void qemu_system_powerdown_request(void)
4864
{
4865
    powerdown_requested = 1;
4866
    if (cpu_single_env)
4867
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4868
}
4869

    
4870
void main_loop_wait(int timeout)
4871
{
4872
    IOHandlerRecord *ioh, *ioh_next;
4873
    fd_set rfds, wfds, xfds;
4874
    int ret, nfds;
4875
    struct timeval tv;
4876
    PollingEntry *pe;
4877

    
4878

    
4879
    /* XXX: need to suppress polling by better using win32 events */
4880
    ret = 0;
4881
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4882
        ret |= pe->func(pe->opaque);
4883
    }
4884
#ifdef _WIN32
4885
    if (ret == 0 && timeout > 0) {
4886
        int err;
4887
        WaitObjects *w = &wait_objects;
4888
        
4889
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
4890
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4891
            if (w->func[ret - WAIT_OBJECT_0])
4892
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4893
        } else if (ret == WAIT_TIMEOUT) {
4894
        } else {
4895
            err = GetLastError();
4896
            fprintf(stderr, "Wait error %d %d\n", ret, err);
4897
        }
4898
    }
4899
#endif
4900
    /* poll any events */
4901
    /* XXX: separate device handlers from system ones */
4902
    nfds = -1;
4903
    FD_ZERO(&rfds);
4904
    FD_ZERO(&wfds);
4905
    FD_ZERO(&xfds);
4906
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4907
        if (ioh->fd_read &&
4908
            (!ioh->fd_read_poll ||
4909
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4910
            FD_SET(ioh->fd, &rfds);
4911
            if (ioh->fd > nfds)
4912
                nfds = ioh->fd;
4913
        }
4914
        if (ioh->fd_write) {
4915
            FD_SET(ioh->fd, &wfds);
4916
            if (ioh->fd > nfds)
4917
                nfds = ioh->fd;
4918
        }
4919
    }
4920
    
4921
    tv.tv_sec = 0;
4922
#ifdef _WIN32
4923
    tv.tv_usec = 0;
4924
#else
4925
    tv.tv_usec = timeout * 1000;
4926
#endif
4927
#if defined(CONFIG_SLIRP)
4928
    if (slirp_inited) {
4929
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4930
    }
4931
#endif
4932
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4933
    if (ret > 0) {
4934
        /* XXX: better handling of removal */
4935
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4936
            ioh_next = ioh->next;
4937
            if (FD_ISSET(ioh->fd, &rfds)) {
4938
                ioh->fd_read(ioh->opaque);
4939
            }
4940
            if (FD_ISSET(ioh->fd, &wfds)) {
4941
                ioh->fd_write(ioh->opaque);
4942
            }
4943
        }
4944
    }
4945
#if defined(CONFIG_SLIRP)
4946
    if (slirp_inited) {
4947
        if (ret < 0) {
4948
            FD_ZERO(&rfds);
4949
            FD_ZERO(&wfds);
4950
            FD_ZERO(&xfds);
4951
        }
4952
        slirp_select_poll(&rfds, &wfds, &xfds);
4953
    }
4954
#endif
4955
#ifdef _WIN32
4956
    tap_win32_poll();
4957
#endif
4958

    
4959
    if (vm_running) {
4960
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
4961
                        qemu_get_clock(vm_clock));
4962
        /* run dma transfers, if any */
4963
        DMA_run();
4964
    }
4965
    
4966
    /* real time timers */
4967
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
4968
                    qemu_get_clock(rt_clock));
4969
}
4970

    
4971
static CPUState *cur_cpu;
4972

    
4973
int main_loop(void)
4974
{
4975
    int ret, timeout;
4976
#ifdef CONFIG_PROFILER
4977
    int64_t ti;
4978
#endif
4979
    CPUState *env;
4980

    
4981
    cur_cpu = first_cpu;
4982
    for(;;) {
4983
        if (vm_running) {
4984

    
4985
            env = cur_cpu;
4986
            for(;;) {
4987
                /* get next cpu */
4988
                env = env->next_cpu;
4989
                if (!env)
4990
                    env = first_cpu;
4991
#ifdef CONFIG_PROFILER
4992
                ti = profile_getclock();
4993
#endif
4994
                ret = cpu_exec(env);
4995
#ifdef CONFIG_PROFILER
4996
                qemu_time += profile_getclock() - ti;
4997
#endif
4998
                if (ret != EXCP_HALTED)
4999
                    break;
5000
                /* all CPUs are halted ? */
5001
                if (env == cur_cpu) {
5002
                    ret = EXCP_HLT;
5003
                    break;
5004
                }
5005
            }
5006
            cur_cpu = env;
5007

    
5008
            if (shutdown_requested) {
5009
                ret = EXCP_INTERRUPT;
5010
                break;
5011
            }
5012
            if (reset_requested) {
5013
                reset_requested = 0;
5014
                qemu_system_reset();
5015
                ret = EXCP_INTERRUPT;
5016
            }
5017
            if (powerdown_requested) {
5018
                powerdown_requested = 0;
5019
                qemu_system_powerdown();
5020
                ret = EXCP_INTERRUPT;
5021
            }
5022
            if (ret == EXCP_DEBUG) {
5023
                vm_stop(EXCP_DEBUG);
5024
            }
5025
            /* if hlt instruction, we wait until the next IRQ */
5026
            /* XXX: use timeout computed from timers */
5027
            if (ret == EXCP_HLT)
5028
                timeout = 10;
5029
            else
5030
                timeout = 0;
5031
        } else {
5032
            timeout = 10;
5033
        }
5034
#ifdef CONFIG_PROFILER
5035
        ti = profile_getclock();
5036
#endif
5037
        main_loop_wait(timeout);
5038
#ifdef CONFIG_PROFILER
5039
        dev_time += profile_getclock() - ti;
5040
#endif
5041
    }
5042
    cpu_disable_ticks();
5043
    return ret;
5044
}
5045

    
5046
void help(void)
5047
{
5048
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5049
           "usage: %s [options] [disk_image]\n"
5050
           "\n"
5051
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5052
           "\n"
5053
           "Standard options:\n"
5054