Statistics
| Branch: | Revision:

root / vl.c @ 3b21e03e

History | View | Annotate | Download (176.6 kB)

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

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

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

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

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

    
74
#include "qemu_socket.h"
75

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

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

    
87
#include "disas.h"
88

    
89
#include "exec-all.h"
90

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

    
93
//#define DEBUG_UNUSED_IOPORT
94
//#define DEBUG_IOPORT
95

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

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

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

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

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

    
165
/***********************************************************/
166
/* x86 ISA bus support */
167

    
168
target_phys_addr_t isa_mem_base = 0;
169
PicState2 *isa_pic;
170

    
171
uint32_t default_ioport_readb(void *opaque, uint32_t address)
172
{
173
#ifdef DEBUG_UNUSED_IOPORT
174
    fprintf(stderr, "inb: port=0x%04x\n", address);
175
#endif
176
    return 0xff;
177
}
178

    
179
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
180
{
181
#ifdef DEBUG_UNUSED_IOPORT
182
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
183
#endif
184
}
185

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

    
196
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
197
{
198
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
199
    address = (address + 1) & (MAX_IOPORTS - 1);
200
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
201
}
202

    
203
uint32_t default_ioport_readl(void *opaque, uint32_t address)
204
{
205
#ifdef DEBUG_UNUSED_IOPORT
206
    fprintf(stderr, "inl: port=0x%04x\n", address);
207
#endif
208
    return 0xffffffff;
209
}
210

    
211
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
212
{
213
#ifdef DEBUG_UNUSED_IOPORT
214
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
215
#endif
216
}
217

    
218
void init_ioports(void)
219
{
220
    int i;
221

    
222
    for(i = 0; i < MAX_IOPORTS; i++) {
223
        ioport_read_table[0][i] = default_ioport_readb;
224
        ioport_write_table[0][i] = default_ioport_writeb;
225
        ioport_read_table[1][i] = default_ioport_readw;
226
        ioport_write_table[1][i] = default_ioport_writew;
227
        ioport_read_table[2][i] = default_ioport_readl;
228
        ioport_write_table[2][i] = default_ioport_writel;
229
    }
230
}
231

    
232
/* size is the word size in byte */
233
int register_ioport_read(int start, int length, int size, 
234
                         IOPortReadFunc *func, void *opaque)
235
{
236
    int i, bsize;
237

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

    
257
/* size is the word size in byte */
258
int register_ioport_write(int start, int length, int size, 
259
                          IOPortWriteFunc *func, void *opaque)
260
{
261
    int i, bsize;
262

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

    
282
void isa_unassign_ioport(int start, int length)
283
{
284
    int i;
285

    
286
    for(i = start; i < start + length; i++) {
287
        ioport_read_table[0][i] = default_ioport_readb;
288
        ioport_read_table[1][i] = default_ioport_readw;
289
        ioport_read_table[2][i] = default_ioport_readl;
290

    
291
        ioport_write_table[0][i] = default_ioport_writeb;
292
        ioport_write_table[1][i] = default_ioport_writew;
293
        ioport_write_table[2][i] = default_ioport_writel;
294
    }
295
}
296

    
297
/***********************************************************/
298

    
299
void pstrcpy(char *buf, int buf_size, const char *str)
300
{
301
    int c;
302
    char *q = buf;
303

    
304
    if (buf_size <= 0)
305
        return;
306

    
307
    for(;;) {
308
        c = *str++;
309
        if (c == 0 || q >= buf + buf_size - 1)
310
            break;
311
        *q++ = c;
312
    }
313
    *q = '\0';
314
}
315

    
316
/* strcat and truncate. */
317
char *pstrcat(char *buf, int buf_size, const char *s)
318
{
319
    int len;
320
    len = strlen(buf);
321
    if (len < buf_size) 
322
        pstrcpy(buf + len, buf_size - len, s);
323
    return buf;
324
}
325

    
326
int strstart(const char *str, const char *val, const char **ptr)
327
{
328
    const char *p, *q;
329
    p = str;
330
    q = val;
331
    while (*q != '\0') {
332
        if (*p != *q)
333
            return 0;
334
        p++;
335
        q++;
336
    }
337
    if (ptr)
338
        *ptr = p;
339
    return 1;
340
}
341

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

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

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

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

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

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

    
426
/***********************************************************/
427
void hw_error(const char *fmt, ...)
428
{
429
    va_list ap;
430
    CPUState *env;
431

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

    
448
/***********************************************************/
449
/* keyboard/mouse */
450

    
451
static QEMUPutKBDEvent *qemu_put_kbd_event;
452
static void *qemu_put_kbd_event_opaque;
453
static QEMUPutMouseEvent *qemu_put_mouse_event;
454
static void *qemu_put_mouse_event_opaque;
455
static int qemu_put_mouse_event_absolute;
456

    
457
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
458
{
459
    qemu_put_kbd_event_opaque = opaque;
460
    qemu_put_kbd_event = func;
461
}
462

    
463
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
464
{
465
    qemu_put_mouse_event_opaque = opaque;
466
    qemu_put_mouse_event = func;
467
    qemu_put_mouse_event_absolute = absolute;
468
}
469

    
470
void kbd_put_keycode(int keycode)
471
{
472
    if (qemu_put_kbd_event) {
473
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
474
    }
475
}
476

    
477
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
478
{
479
    if (qemu_put_mouse_event) {
480
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
481
                             dx, dy, dz, buttons_state);
482
    }
483
}
484

    
485
int kbd_mouse_is_absolute(void)
486
{
487
    return qemu_put_mouse_event_absolute;
488
}
489

    
490
/* compute with 96 bit intermediate result: (a*b)/c */
491
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
492
{
493
    union {
494
        uint64_t ll;
495
        struct {
496
#ifdef WORDS_BIGENDIAN
497
            uint32_t high, low;
498
#else
499
            uint32_t low, high;
500
#endif            
501
        } l;
502
    } u, res;
503
    uint64_t rl, rh;
504

    
505
    u.ll = a;
506
    rl = (uint64_t)u.l.low * (uint64_t)b;
507
    rh = (uint64_t)u.l.high * (uint64_t)b;
508
    rh += (rl >> 32);
509
    res.l.high = rh / c;
510
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
511
    return res.ll;
512
}
513

    
514
/***********************************************************/
515
/* real time host monotonic timer */
516

    
517
#define QEMU_TIMER_BASE 1000000000LL
518

    
519
#ifdef WIN32
520

    
521
static int64_t clock_freq;
522

    
523
static void init_get_clock(void)
524
{
525
    LARGE_INTEGER freq;
526
    int ret;
527
    ret = QueryPerformanceFrequency(&freq);
528
    if (ret == 0) {
529
        fprintf(stderr, "Could not calibrate ticks\n");
530
        exit(1);
531
    }
532
    clock_freq = freq.QuadPart;
533
}
534

    
535
static int64_t get_clock(void)
536
{
537
    LARGE_INTEGER ti;
538
    QueryPerformanceCounter(&ti);
539
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
540
}
541

    
542
#else
543

    
544
static int use_rt_clock;
545

    
546
static void init_get_clock(void)
547
{
548
    use_rt_clock = 0;
549
#if defined(__linux__)
550
    {
551
        struct timespec ts;
552
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
553
            use_rt_clock = 1;
554
        }
555
    }
556
#endif
557
}
558

    
559
static int64_t get_clock(void)
560
{
561
#if defined(__linux__)
562
    if (use_rt_clock) {
563
        struct timespec ts;
564
        clock_gettime(CLOCK_MONOTONIC, &ts);
565
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
566
    } else 
567
#endif
568
    {
569
        /* XXX: using gettimeofday leads to problems if the date
570
           changes, so it should be avoided. */
571
        struct timeval tv;
572
        gettimeofday(&tv, NULL);
573
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
574
    }
575
}
576

    
577
#endif
578

    
579
/***********************************************************/
580
/* guest cycle counter */
581

    
582
static int64_t cpu_ticks_prev;
583
static int64_t cpu_ticks_offset;
584
static int64_t cpu_clock_offset;
585
static int cpu_ticks_enabled;
586

    
587
/* return the host CPU cycle counter and handle stop/restart */
588
int64_t cpu_get_ticks(void)
589
{
590
    if (!cpu_ticks_enabled) {
591
        return cpu_ticks_offset;
592
    } else {
593
        int64_t ticks;
594
        ticks = cpu_get_real_ticks();
595
        if (cpu_ticks_prev > ticks) {
596
            /* Note: non increasing ticks may happen if the host uses
597
               software suspend */
598
            cpu_ticks_offset += cpu_ticks_prev - ticks;
599
        }
600
        cpu_ticks_prev = ticks;
601
        return ticks + cpu_ticks_offset;
602
    }
603
}
604

    
605
/* return the host CPU monotonic timer and handle stop/restart */
606
static int64_t cpu_get_clock(void)
607
{
608
    int64_t ti;
609
    if (!cpu_ticks_enabled) {
610
        return cpu_clock_offset;
611
    } else {
612
        ti = get_clock();
613
        return ti + cpu_clock_offset;
614
    }
615
}
616

    
617
/* enable cpu_get_ticks() */
618
void cpu_enable_ticks(void)
619
{
620
    if (!cpu_ticks_enabled) {
621
        cpu_ticks_offset -= cpu_get_real_ticks();
622
        cpu_clock_offset -= get_clock();
623
        cpu_ticks_enabled = 1;
624
    }
625
}
626

    
627
/* disable cpu_get_ticks() : the clock is stopped. You must not call
628
   cpu_get_ticks() after that.  */
629
void cpu_disable_ticks(void)
630
{
631
    if (cpu_ticks_enabled) {
632
        cpu_ticks_offset = cpu_get_ticks();
633
        cpu_clock_offset = cpu_get_clock();
634
        cpu_ticks_enabled = 0;
635
    }
636
}
637

    
638
/***********************************************************/
639
/* timers */
640
 
641
#define QEMU_TIMER_REALTIME 0
642
#define QEMU_TIMER_VIRTUAL  1
643

    
644
struct QEMUClock {
645
    int type;
646
    /* XXX: add frequency */
647
};
648

    
649
struct QEMUTimer {
650
    QEMUClock *clock;
651
    int64_t expire_time;
652
    QEMUTimerCB *cb;
653
    void *opaque;
654
    struct QEMUTimer *next;
655
};
656

    
657
QEMUClock *rt_clock;
658
QEMUClock *vm_clock;
659

    
660
static QEMUTimer *active_timers[2];
661
#ifdef _WIN32
662
static MMRESULT timerID;
663
static HANDLE host_alarm = NULL;
664
static unsigned int period = 1;
665
#else
666
/* frequency of the times() clock tick */
667
static int timer_freq;
668
#endif
669

    
670
QEMUClock *qemu_new_clock(int type)
671
{
672
    QEMUClock *clock;
673
    clock = qemu_mallocz(sizeof(QEMUClock));
674
    if (!clock)
675
        return NULL;
676
    clock->type = type;
677
    return clock;
678
}
679

    
680
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
681
{
682
    QEMUTimer *ts;
683

    
684
    ts = qemu_mallocz(sizeof(QEMUTimer));
685
    ts->clock = clock;
686
    ts->cb = cb;
687
    ts->opaque = opaque;
688
    return ts;
689
}
690

    
691
void qemu_free_timer(QEMUTimer *ts)
692
{
693
    qemu_free(ts);
694
}
695

    
696
/* stop a timer, but do not dealloc it */
697
void qemu_del_timer(QEMUTimer *ts)
698
{
699
    QEMUTimer **pt, *t;
700

    
701
    /* NOTE: this code must be signal safe because
702
       qemu_timer_expired() can be called from a signal. */
703
    pt = &active_timers[ts->clock->type];
704
    for(;;) {
705
        t = *pt;
706
        if (!t)
707
            break;
708
        if (t == ts) {
709
            *pt = t->next;
710
            break;
711
        }
712
        pt = &t->next;
713
    }
714
}
715

    
716
/* modify the current timer so that it will be fired when current_time
717
   >= expire_time. The corresponding callback will be called. */
718
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
719
{
720
    QEMUTimer **pt, *t;
721

    
722
    qemu_del_timer(ts);
723

    
724
    /* add the timer in the sorted list */
725
    /* NOTE: this code must be signal safe because
726
       qemu_timer_expired() can be called from a signal. */
727
    pt = &active_timers[ts->clock->type];
728
    for(;;) {
729
        t = *pt;
730
        if (!t)
731
            break;
732
        if (t->expire_time > expire_time) 
733
            break;
734
        pt = &t->next;
735
    }
736
    ts->expire_time = expire_time;
737
    ts->next = *pt;
738
    *pt = ts;
739
}
740

    
741
int qemu_timer_pending(QEMUTimer *ts)
742
{
743
    QEMUTimer *t;
744
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
745
        if (t == ts)
746
            return 1;
747
    }
748
    return 0;
749
}
750

    
751
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
752
{
753
    if (!timer_head)
754
        return 0;
755
    return (timer_head->expire_time <= current_time);
756
}
757

    
758
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
759
{
760
    QEMUTimer *ts;
761
    
762
    for(;;) {
763
        ts = *ptimer_head;
764
        if (!ts || ts->expire_time > current_time)
765
            break;
766
        /* remove timer from the list before calling the callback */
767
        *ptimer_head = ts->next;
768
        ts->next = NULL;
769
        
770
        /* run the callback (the timer list can be modified) */
771
        ts->cb(ts->opaque);
772
    }
773
}
774

    
775
int64_t qemu_get_clock(QEMUClock *clock)
776
{
777
    switch(clock->type) {
778
    case QEMU_TIMER_REALTIME:
779
        return get_clock() / 1000000;
780
    default:
781
    case QEMU_TIMER_VIRTUAL:
782
        return cpu_get_clock();
783
    }
784
}
785

    
786
static void init_timers(void)
787
{
788
    init_get_clock();
789
    ticks_per_sec = QEMU_TIMER_BASE;
790
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
791
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
792
}
793

    
794
/* save a timer */
795
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
796
{
797
    uint64_t expire_time;
798

    
799
    if (qemu_timer_pending(ts)) {
800
        expire_time = ts->expire_time;
801
    } else {
802
        expire_time = -1;
803
    }
804
    qemu_put_be64(f, expire_time);
805
}
806

    
807
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
808
{
809
    uint64_t expire_time;
810

    
811
    expire_time = qemu_get_be64(f);
812
    if (expire_time != -1) {
813
        qemu_mod_timer(ts, expire_time);
814
    } else {
815
        qemu_del_timer(ts);
816
    }
817
}
818

    
819
static void timer_save(QEMUFile *f, void *opaque)
820
{
821
    if (cpu_ticks_enabled) {
822
        hw_error("cannot save state if virtual timers are running");
823
    }
824
    qemu_put_be64s(f, &cpu_ticks_offset);
825
    qemu_put_be64s(f, &ticks_per_sec);
826
    qemu_put_be64s(f, &cpu_clock_offset);
827
}
828

    
829
static int timer_load(QEMUFile *f, void *opaque, int version_id)
830
{
831
    if (version_id != 1 && version_id != 2)
832
        return -EINVAL;
833
    if (cpu_ticks_enabled) {
834
        return -EINVAL;
835
    }
836
    qemu_get_be64s(f, &cpu_ticks_offset);
837
    qemu_get_be64s(f, &ticks_per_sec);
838
    if (version_id == 2) {
839
        qemu_get_be64s(f, &cpu_clock_offset);
840
    }
841
    return 0;
842
}
843

    
844
#ifdef _WIN32
845
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
846
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
847
#else
848
static void host_alarm_handler(int host_signum)
849
#endif
850
{
851
#if 0
852
#define DISP_FREQ 1000
853
    {
854
        static int64_t delta_min = INT64_MAX;
855
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
856
        static int count;
857
        ti = qemu_get_clock(vm_clock);
858
        if (last_clock != 0) {
859
            delta = ti - last_clock;
860
            if (delta < delta_min)
861
                delta_min = delta;
862
            if (delta > delta_max)
863
                delta_max = delta;
864
            delta_cum += delta;
865
            if (++count == DISP_FREQ) {
866
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
867
                       muldiv64(delta_min, 1000000, ticks_per_sec),
868
                       muldiv64(delta_max, 1000000, ticks_per_sec),
869
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
870
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
871
                count = 0;
872
                delta_min = INT64_MAX;
873
                delta_max = 0;
874
                delta_cum = 0;
875
            }
876
        }
877
        last_clock = ti;
878
    }
879
#endif
880
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
881
                           qemu_get_clock(vm_clock)) ||
882
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
883
                           qemu_get_clock(rt_clock))) {
884
#ifdef _WIN32
885
        SetEvent(host_alarm);
886
#endif
887
        CPUState *env = cpu_single_env;
888
        if (env) {
889
            /* stop the currently executing cpu because a timer occured */
890
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
891
#ifdef USE_KQEMU
892
            if (env->kqemu_enabled) {
893
                kqemu_cpu_interrupt(env);
894
            }
895
#endif
896
        }
897
    }
898
}
899

    
900
#ifndef _WIN32
901

    
902
#if defined(__linux__)
903

    
904
#define RTC_FREQ 1024
905

    
906
static int rtc_fd;
907

    
908
static int start_rtc_timer(void)
909
{
910
    rtc_fd = open("/dev/rtc", O_RDONLY);
911
    if (rtc_fd < 0)
912
        return -1;
913
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
914
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
915
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
916
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
917
        goto fail;
918
    }
919
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
920
    fail:
921
        close(rtc_fd);
922
        return -1;
923
    }
924
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
925
    return 0;
926
}
927

    
928
#else
929

    
930
static int start_rtc_timer(void)
931
{
932
    return -1;
933
}
934

    
935
#endif /* !defined(__linux__) */
936

    
937
#endif /* !defined(_WIN32) */
938

    
939
static void init_timer_alarm(void)
940
{
941
#ifdef _WIN32
942
    {
943
        int count=0;
944
        TIMECAPS tc;
945

    
946
        ZeroMemory(&tc, sizeof(TIMECAPS));
947
        timeGetDevCaps(&tc, sizeof(TIMECAPS));
948
        if (period < tc.wPeriodMin)
949
            period = tc.wPeriodMin;
950
        timeBeginPeriod(period);
951
        timerID = timeSetEvent(1,     // interval (ms)
952
                               period,     // resolution
953
                               host_alarm_handler, // function
954
                               (DWORD)&count,  // user parameter
955
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
956
         if( !timerID ) {
957
            perror("failed timer alarm");
958
            exit(1);
959
         }
960
        host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
961
        if (!host_alarm) {
962
            perror("failed CreateEvent");
963
            exit(1);
964
        }
965
        qemu_add_wait_object(host_alarm, NULL, NULL);
966
    }
967
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
968
#else
969
    {
970
        struct sigaction act;
971
        struct itimerval itv;
972
        
973
        /* get times() syscall frequency */
974
        timer_freq = sysconf(_SC_CLK_TCK);
975
        
976
        /* timer signal */
977
        sigfillset(&act.sa_mask);
978
       act.sa_flags = 0;
979
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
980
        act.sa_flags |= SA_ONSTACK;
981
#endif
982
        act.sa_handler = host_alarm_handler;
983
        sigaction(SIGALRM, &act, NULL);
984

    
985
        itv.it_interval.tv_sec = 0;
986
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
987
        itv.it_value.tv_sec = 0;
988
        itv.it_value.tv_usec = 10 * 1000;
989
        setitimer(ITIMER_REAL, &itv, NULL);
990
        /* we probe the tick duration of the kernel to inform the user if
991
           the emulated kernel requested a too high timer frequency */
992
        getitimer(ITIMER_REAL, &itv);
993

    
994
#if defined(__linux__)
995
        /* XXX: force /dev/rtc usage because even 2.6 kernels may not
996
           have timers with 1 ms resolution. The correct solution will
997
           be to use the POSIX real time timers available in recent
998
           2.6 kernels */
999
        if (itv.it_interval.tv_usec > 1000 || 1) {
1000
            /* try to use /dev/rtc to have a faster timer */
1001
            if (start_rtc_timer() < 0)
1002
                goto use_itimer;
1003
            /* disable itimer */
1004
            itv.it_interval.tv_sec = 0;
1005
            itv.it_interval.tv_usec = 0;
1006
            itv.it_value.tv_sec = 0;
1007
            itv.it_value.tv_usec = 0;
1008
            setitimer(ITIMER_REAL, &itv, NULL);
1009

    
1010
            /* use the RTC */
1011
            sigaction(SIGIO, &act, NULL);
1012
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1013
            fcntl(rtc_fd, F_SETOWN, getpid());
1014
        } else 
1015
#endif /* defined(__linux__) */
1016
        {
1017
        use_itimer:
1018
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1019
                                   PIT_FREQ) / 1000000;
1020
        }
1021
    }
1022
#endif
1023
}
1024

    
1025
void quit_timers(void)
1026
{
1027
#ifdef _WIN32
1028
    timeKillEvent(timerID);
1029
    timeEndPeriod(period);
1030
    if (host_alarm) {
1031
        CloseHandle(host_alarm);
1032
        host_alarm = NULL;
1033
    }
1034
#endif
1035
}
1036

    
1037
/***********************************************************/
1038
/* character device */
1039

    
1040
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1041
{
1042
    return s->chr_write(s, buf, len);
1043
}
1044

    
1045
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1046
{
1047
    if (!s->chr_ioctl)
1048
        return -ENOTSUP;
1049
    return s->chr_ioctl(s, cmd, arg);
1050
}
1051

    
1052
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1053
{
1054
    char buf[4096];
1055
    va_list ap;
1056
    va_start(ap, fmt);
1057
    vsnprintf(buf, sizeof(buf), fmt, ap);
1058
    qemu_chr_write(s, buf, strlen(buf));
1059
    va_end(ap);
1060
}
1061

    
1062
void qemu_chr_send_event(CharDriverState *s, int event)
1063
{
1064
    if (s->chr_send_event)
1065
        s->chr_send_event(s, event);
1066
}
1067

    
1068
void qemu_chr_add_read_handler(CharDriverState *s, 
1069
                               IOCanRWHandler *fd_can_read, 
1070
                               IOReadHandler *fd_read, void *opaque)
1071
{
1072
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1073
}
1074
             
1075
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1076
{
1077
    s->chr_event = chr_event;
1078
}
1079

    
1080
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1081
{
1082
    return len;
1083
}
1084

    
1085
static void null_chr_add_read_handler(CharDriverState *chr, 
1086
                                    IOCanRWHandler *fd_can_read, 
1087
                                    IOReadHandler *fd_read, void *opaque)
1088
{
1089
}
1090

    
1091
CharDriverState *qemu_chr_open_null(void)
1092
{
1093
    CharDriverState *chr;
1094

    
1095
    chr = qemu_mallocz(sizeof(CharDriverState));
1096
    if (!chr)
1097
        return NULL;
1098
    chr->chr_write = null_chr_write;
1099
    chr->chr_add_read_handler = null_chr_add_read_handler;
1100
    return chr;
1101
}
1102

    
1103
#ifdef _WIN32
1104

    
1105
static void socket_cleanup(void)
1106
{
1107
    WSACleanup();
1108
}
1109

    
1110
static int socket_init(void)
1111
{
1112
    WSADATA Data;
1113
    int ret, err;
1114

    
1115
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1116
    if (ret != 0) {
1117
        err = WSAGetLastError();
1118
        fprintf(stderr, "WSAStartup: %d\n", err);
1119
        return -1;
1120
    }
1121
    atexit(socket_cleanup);
1122
    return 0;
1123
}
1124

    
1125
static int send_all(int fd, const uint8_t *buf, int len1)
1126
{
1127
    int ret, len;
1128
    
1129
    len = len1;
1130
    while (len > 0) {
1131
        ret = send(fd, buf, len, 0);
1132
        if (ret < 0) {
1133
            int errno;
1134
            errno = WSAGetLastError();
1135
            if (errno != WSAEWOULDBLOCK) {
1136
                return -1;
1137
            }
1138
        } else if (ret == 0) {
1139
            break;
1140
        } else {
1141
            buf += ret;
1142
            len -= ret;
1143
        }
1144
    }
1145
    return len1 - len;
1146
}
1147

    
1148
void socket_set_nonblock(int fd)
1149
{
1150
    unsigned long opt = 1;
1151
    ioctlsocket(fd, FIONBIO, &opt);
1152
}
1153

    
1154
#else
1155

    
1156
static int unix_write(int fd, const uint8_t *buf, int len1)
1157
{
1158
    int ret, len;
1159

    
1160
    len = len1;
1161
    while (len > 0) {
1162
        ret = write(fd, buf, len);
1163
        if (ret < 0) {
1164
            if (errno != EINTR && errno != EAGAIN)
1165
                return -1;
1166
        } else if (ret == 0) {
1167
            break;
1168
        } else {
1169
            buf += ret;
1170
            len -= ret;
1171
        }
1172
    }
1173
    return len1 - len;
1174
}
1175

    
1176
static inline int send_all(int fd, const uint8_t *buf, int len1)
1177
{
1178
    return unix_write(fd, buf, len1);
1179
}
1180

    
1181
void socket_set_nonblock(int fd)
1182
{
1183
    fcntl(fd, F_SETFL, O_NONBLOCK);
1184
}
1185
#endif /* !_WIN32 */
1186

    
1187
#ifndef _WIN32
1188

    
1189
typedef struct {
1190
    int fd_in, fd_out;
1191
    IOCanRWHandler *fd_can_read; 
1192
    IOReadHandler *fd_read;
1193
    void *fd_opaque;
1194
    int max_size;
1195
} FDCharDriver;
1196

    
1197
#define STDIO_MAX_CLIENTS 2
1198

    
1199
static int stdio_nb_clients;
1200
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1201

    
1202
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1203
{
1204
    FDCharDriver *s = chr->opaque;
1205
    return unix_write(s->fd_out, buf, len);
1206
}
1207

    
1208
static int fd_chr_read_poll(void *opaque)
1209
{
1210
    CharDriverState *chr = opaque;
1211
    FDCharDriver *s = chr->opaque;
1212

    
1213
    s->max_size = s->fd_can_read(s->fd_opaque);
1214
    return s->max_size;
1215
}
1216

    
1217
static void fd_chr_read(void *opaque)
1218
{
1219
    CharDriverState *chr = opaque;
1220
    FDCharDriver *s = chr->opaque;
1221
    int size, len;
1222
    uint8_t buf[1024];
1223
    
1224
    len = sizeof(buf);
1225
    if (len > s->max_size)
1226
        len = s->max_size;
1227
    if (len == 0)
1228
        return;
1229
    size = read(s->fd_in, buf, len);
1230
    if (size > 0) {
1231
        s->fd_read(s->fd_opaque, buf, size);
1232
    }
1233
}
1234

    
1235
static void fd_chr_add_read_handler(CharDriverState *chr, 
1236
                                    IOCanRWHandler *fd_can_read, 
1237
                                    IOReadHandler *fd_read, void *opaque)
1238
{
1239
    FDCharDriver *s = chr->opaque;
1240

    
1241
    if (s->fd_in >= 0) {
1242
        s->fd_can_read = fd_can_read;
1243
        s->fd_read = fd_read;
1244
        s->fd_opaque = opaque;
1245
        if (nographic && s->fd_in == 0) {
1246
        } else {
1247
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1248
                                 fd_chr_read, NULL, chr);
1249
        }
1250
    }
1251
}
1252

    
1253
/* open a character device to a unix fd */
1254
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1255
{
1256
    CharDriverState *chr;
1257
    FDCharDriver *s;
1258

    
1259
    chr = qemu_mallocz(sizeof(CharDriverState));
1260
    if (!chr)
1261
        return NULL;
1262
    s = qemu_mallocz(sizeof(FDCharDriver));
1263
    if (!s) {
1264
        free(chr);
1265
        return NULL;
1266
    }
1267
    s->fd_in = fd_in;
1268
    s->fd_out = fd_out;
1269
    chr->opaque = s;
1270
    chr->chr_write = fd_chr_write;
1271
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1272
    return chr;
1273
}
1274

    
1275
CharDriverState *qemu_chr_open_file_out(const char *file_out)
1276
{
1277
    int fd_out;
1278

    
1279
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1280
    if (fd_out < 0)
1281
        return NULL;
1282
    return qemu_chr_open_fd(-1, fd_out);
1283
}
1284

    
1285
CharDriverState *qemu_chr_open_pipe(const char *filename)
1286
{
1287
    int fd;
1288

    
1289
    fd = open(filename, O_RDWR | O_BINARY);
1290
    if (fd < 0)
1291
        return NULL;
1292
    return qemu_chr_open_fd(fd, fd);
1293
}
1294

    
1295

    
1296
/* for STDIO, we handle the case where several clients use it
1297
   (nographic mode) */
1298

    
1299
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1300

    
1301
#define TERM_FIFO_MAX_SIZE 1
1302

    
1303
static int term_got_escape, client_index;
1304
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1305
static int term_fifo_size;
1306
static int term_timestamps;
1307
static int64_t term_timestamps_start;
1308

    
1309
void term_print_help(void)
1310
{
1311
    printf("\n"
1312
           "C-a h    print this help\n"
1313
           "C-a x    exit emulator\n"
1314
           "C-a s    save disk data back to file (if -snapshot)\n"
1315
           "C-a b    send break (magic sysrq)\n"
1316
           "C-a t    toggle console timestamps\n"
1317
           "C-a c    switch between console and monitor\n"
1318
           "C-a C-a  send C-a\n"
1319
           );
1320
}
1321

    
1322
/* called when a char is received */
1323
static void stdio_received_byte(int ch)
1324
{
1325
    if (term_got_escape) {
1326
        term_got_escape = 0;
1327
        switch(ch) {
1328
        case 'h':
1329
            term_print_help();
1330
            break;
1331
        case 'x':
1332
            exit(0);
1333
            break;
1334
        case 's': 
1335
            {
1336
                int i;
1337
                for (i = 0; i < MAX_DISKS; i++) {
1338
                    if (bs_table[i])
1339
                        bdrv_commit(bs_table[i]);
1340
                }
1341
            }
1342
            break;
1343
        case 'b':
1344
            if (client_index < stdio_nb_clients) {
1345
                CharDriverState *chr;
1346
                FDCharDriver *s;
1347

    
1348
                chr = stdio_clients[client_index];
1349
                s = chr->opaque;
1350
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1351
            }
1352
            break;
1353
        case 'c':
1354
            client_index++;
1355
            if (client_index >= stdio_nb_clients)
1356
                client_index = 0;
1357
            if (client_index == 0) {
1358
                /* send a new line in the monitor to get the prompt */
1359
                ch = '\r';
1360
                goto send_char;
1361
            }
1362
            break;
1363
        case 't':
1364
            term_timestamps = !term_timestamps;
1365
            term_timestamps_start = -1;
1366
            break;
1367
        case TERM_ESCAPE:
1368
            goto send_char;
1369
        }
1370
    } else if (ch == TERM_ESCAPE) {
1371
        term_got_escape = 1;
1372
    } else {
1373
    send_char:
1374
        if (client_index < stdio_nb_clients) {
1375
            uint8_t buf[1];
1376
            CharDriverState *chr;
1377
            FDCharDriver *s;
1378
            
1379
            chr = stdio_clients[client_index];
1380
            s = chr->opaque;
1381
            if (s->fd_can_read(s->fd_opaque) > 0) {
1382
                buf[0] = ch;
1383
                s->fd_read(s->fd_opaque, buf, 1);
1384
            } else if (term_fifo_size == 0) {
1385
                term_fifo[term_fifo_size++] = ch;
1386
            }
1387
        }
1388
    }
1389
}
1390

    
1391
static int stdio_read_poll(void *opaque)
1392
{
1393
    CharDriverState *chr;
1394
    FDCharDriver *s;
1395

    
1396
    if (client_index < stdio_nb_clients) {
1397
        chr = stdio_clients[client_index];
1398
        s = chr->opaque;
1399
        /* try to flush the queue if needed */
1400
        if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1401
            s->fd_read(s->fd_opaque, term_fifo, 1);
1402
            term_fifo_size = 0;
1403
        }
1404
        /* see if we can absorb more chars */
1405
        if (term_fifo_size == 0)
1406
            return 1;
1407
        else
1408
            return 0;
1409
    } else {
1410
        return 1;
1411
    }
1412
}
1413

    
1414
static void stdio_read(void *opaque)
1415
{
1416
    int size;
1417
    uint8_t buf[1];
1418
    
1419
    size = read(0, buf, 1);
1420
    if (size == 0) {
1421
        /* stdin has been closed. Remove it from the active list.  */
1422
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1423
        return;
1424
    }
1425
    if (size > 0)
1426
        stdio_received_byte(buf[0]);
1427
}
1428

    
1429
static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1430
{
1431
    FDCharDriver *s = chr->opaque;
1432
    if (!term_timestamps) {
1433
        return unix_write(s->fd_out, buf, len);
1434
    } else {
1435
        int i;
1436
        char buf1[64];
1437

    
1438
        for(i = 0; i < len; i++) {
1439
            unix_write(s->fd_out, buf + i, 1);
1440
            if (buf[i] == '\n') {
1441
                int64_t ti;
1442
                int secs;
1443

    
1444
                ti = get_clock();
1445
                if (term_timestamps_start == -1)
1446
                    term_timestamps_start = ti;
1447
                ti -= term_timestamps_start;
1448
                secs = ti / 1000000000;
1449
                snprintf(buf1, sizeof(buf1), 
1450
                         "[%02d:%02d:%02d.%03d] ",
1451
                         secs / 3600,
1452
                         (secs / 60) % 60,
1453
                         secs % 60,
1454
                         (int)((ti / 1000000) % 1000));
1455
                unix_write(s->fd_out, buf1, strlen(buf1));
1456
            }
1457
        }
1458
        return len;
1459
    }
1460
}
1461

    
1462
/* init terminal so that we can grab keys */
1463
static struct termios oldtty;
1464
static int old_fd0_flags;
1465

    
1466
static void term_exit(void)
1467
{
1468
    tcsetattr (0, TCSANOW, &oldtty);
1469
    fcntl(0, F_SETFL, old_fd0_flags);
1470
}
1471

    
1472
static void term_init(void)
1473
{
1474
    struct termios tty;
1475

    
1476
    tcgetattr (0, &tty);
1477
    oldtty = tty;
1478
    old_fd0_flags = fcntl(0, F_GETFL);
1479

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

    
1494
    atexit(term_exit);
1495

    
1496
    fcntl(0, F_SETFL, O_NONBLOCK);
1497
}
1498

    
1499
CharDriverState *qemu_chr_open_stdio(void)
1500
{
1501
    CharDriverState *chr;
1502

    
1503
    if (nographic) {
1504
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1505
            return NULL;
1506
        chr = qemu_chr_open_fd(0, 1);
1507
        chr->chr_write = stdio_write;
1508
        if (stdio_nb_clients == 0)
1509
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1510
        client_index = stdio_nb_clients;
1511
    } else {
1512
        if (stdio_nb_clients != 0)
1513
            return NULL;
1514
        chr = qemu_chr_open_fd(0, 1);
1515
    }
1516
    stdio_clients[stdio_nb_clients++] = chr;
1517
    if (stdio_nb_clients == 1) {
1518
        /* set the terminal in raw mode */
1519
        term_init();
1520
    }
1521
    return chr;
1522
}
1523

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

    
1543
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1544
    return qemu_chr_open_fd(master_fd, master_fd);
1545
}
1546

    
1547
static void tty_serial_init(int fd, int speed, 
1548
                            int parity, int data_bits, int stop_bits)
1549
{
1550
    struct termios tty;
1551
    speed_t spd;
1552

    
1553
#if 0
1554
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1555
           speed, parity, data_bits, stop_bits);
1556
#endif
1557
    tcgetattr (fd, &tty);
1558

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

    
1599
    cfsetispeed(&tty, spd);
1600
    cfsetospeed(&tty, spd);
1601

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

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

    
1664
CharDriverState *qemu_chr_open_tty(const char *filename)
1665
{
1666
    CharDriverState *chr;
1667
    int fd;
1668

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

    
1681
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1682
{
1683
    int fd = (int)chr->opaque;
1684
    uint8_t b;
1685

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

    
1718
CharDriverState *qemu_chr_open_pp(const char *filename)
1719
{
1720
    CharDriverState *chr;
1721
    int fd;
1722

    
1723
    fd = open(filename, O_RDWR);
1724
    if (fd < 0)
1725
        return NULL;
1726

    
1727
    if (ioctl(fd, PPCLAIM) < 0) {
1728
        close(fd);
1729
        return NULL;
1730
    }
1731

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

    
1744
#else
1745
CharDriverState *qemu_chr_open_pty(void)
1746
{
1747
    return NULL;
1748
}
1749
#endif
1750

    
1751
#endif /* !defined(_WIN32) */
1752

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

    
1765
#define NSENDBUF 2048
1766
#define NRECVBUF 2048
1767
#define MAXCONNECT 1
1768
#define NTIMEOUT 5000
1769

    
1770
static int win_chr_poll(void *opaque);
1771
static int win_chr_pipe_poll(void *opaque);
1772

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

    
1793
static void win_chr_close(CharDriverState *chr)
1794
{
1795
    WinCharState *s = chr->opaque;
1796
    win_chr_close2(s);
1797
}
1798

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

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

    
1837
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1838
        fprintf(stderr, "Failed SetCommState\n");
1839
        goto fail;
1840
    }
1841

    
1842
    if (!SetCommMask(s->hcom, EV_ERR)) {
1843
        fprintf(stderr, "Failed SetCommMask\n");
1844
        goto fail;
1845
    }
1846

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

    
1860
 fail:
1861
    win_chr_close2(s);
1862
    return -1;
1863
}
1864

    
1865
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1866
{
1867
    WinCharState *s = chr->opaque;
1868
    DWORD len, ret, size, err;
1869

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

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

    
1921
    if (size > 0) {
1922
        s->fd_read(s->win_opaque, buf, size);
1923
    }
1924
}
1925

    
1926
static void win_chr_read(WinCharState *s)
1927
{
1928
    if (s->len > s->max_size)
1929
        s->len = s->max_size;
1930
    if (s->len == 0)
1931
        return;
1932
    
1933
    win_chr_readfile(s);
1934
}
1935

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

    
1952
static void win_chr_add_read_handler(CharDriverState *chr, 
1953
                                    IOCanRWHandler *fd_can_read, 
1954
                                    IOReadHandler *fd_read, void *opaque)
1955
{
1956
    WinCharState *s = chr->opaque;
1957

    
1958
    s->fd_can_read = fd_can_read;
1959
    s->fd_read = fd_read;
1960
    s->win_opaque = opaque;
1961
}
1962

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

    
1981
    if (win_chr_init(s, filename) < 0) {
1982
        free(s);
1983
        free(chr);
1984
        return NULL;
1985
    }
1986
    return chr;
1987
}
1988

    
1989
static int win_chr_pipe_poll(void *opaque)
1990
{
1991
    WinCharState *s = opaque;
1992
    DWORD size;
1993

    
1994
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1995
    if (size > 0) {
1996
        s->len = size;
1997
        win_chr_read_poll(s);
1998
        win_chr_read(s);
1999
        return 1;
2000
    }
2001
    return 0;
2002
}
2003

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

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

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

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

    
2053
    if (ov.hEvent) {
2054
        CloseHandle(ov.hEvent);
2055
        ov.hEvent = NULL;
2056
    }
2057
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2058
    return 0;
2059

    
2060
 fail:
2061
    win_chr_close2(s);
2062
    return -1;
2063
}
2064

    
2065

    
2066
CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2067
{
2068
    CharDriverState *chr;
2069
    WinCharState *s;
2070

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

    
2092
CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2093
{
2094
    CharDriverState *chr;
2095
    WinCharState *s;
2096

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

    
2121
    return qemu_chr_open_win_file(fd_out);
2122
}
2123
#endif
2124

    
2125
/***********************************************************/
2126
/* UDP Net console */
2127

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

    
2140
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2141
{
2142
    NetCharDriver *s = chr->opaque;
2143

    
2144
    return sendto(s->fd, buf, len, 0,
2145
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2146
}
2147

    
2148
static int udp_chr_read_poll(void *opaque)
2149
{
2150
    CharDriverState *chr = opaque;
2151
    NetCharDriver *s = chr->opaque;
2152

    
2153
    s->max_size = s->fd_can_read(s->fd_opaque);
2154

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

    
2166
static void udp_chr_read(void *opaque)
2167
{
2168
    CharDriverState *chr = opaque;
2169
    NetCharDriver *s = chr->opaque;
2170

    
2171
    if (s->max_size == 0)
2172
        return;
2173
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2174
    s->bufptr = s->bufcnt;
2175
    if (s->bufcnt <= 0)
2176
        return;
2177

    
2178
    s->bufptr = 0;
2179
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2180
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2181
        s->bufptr++;
2182
        s->max_size = s->fd_can_read(s->fd_opaque);
2183
    }
2184
}
2185

    
2186
static void udp_chr_add_read_handler(CharDriverState *chr,
2187
                                    IOCanRWHandler *fd_can_read,
2188
                                    IOReadHandler *fd_read, void *opaque)
2189
{
2190
    NetCharDriver *s = chr->opaque;
2191

    
2192
    if (s->fd >= 0) {
2193
        s->fd_can_read = fd_can_read;
2194
        s->fd_read = fd_read;
2195
        s->fd_opaque = opaque;
2196
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2197
                             udp_chr_read, NULL, chr);
2198
    }
2199
}
2200

    
2201
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2202
int parse_host_src_port(struct sockaddr_in *haddr,
2203
                        struct sockaddr_in *saddr,
2204
                        const char *str);
2205

    
2206
CharDriverState *qemu_chr_open_udp(const char *def)
2207
{
2208
    CharDriverState *chr = NULL;
2209
    NetCharDriver *s = NULL;
2210
    int fd = -1;
2211
    struct sockaddr_in saddr;
2212

    
2213
    chr = qemu_mallocz(sizeof(CharDriverState));
2214
    if (!chr)
2215
        goto return_err;
2216
    s = qemu_mallocz(sizeof(NetCharDriver));
2217
    if (!s)
2218
        goto return_err;
2219

    
2220
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2221
    if (fd < 0) {
2222
        perror("socket(PF_INET, SOCK_DGRAM)");
2223
        goto return_err;
2224
    }
2225

    
2226
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2227
        printf("Could not parse: %s\n", def);
2228
        goto return_err;
2229
    }
2230

    
2231
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2232
    {
2233
        perror("bind");
2234
        goto return_err;
2235
    }
2236

    
2237
    s->fd = fd;
2238
    s->bufcnt = 0;
2239
    s->bufptr = 0;
2240
    chr->opaque = s;
2241
    chr->chr_write = udp_chr_write;
2242
    chr->chr_add_read_handler = udp_chr_add_read_handler;
2243
    return chr;
2244

    
2245
return_err:
2246
    if (chr)
2247
        free(chr);
2248
    if (s)
2249
        free(s);
2250
    if (fd >= 0)
2251
        closesocket(fd);
2252
    return NULL;
2253
}
2254

    
2255
/***********************************************************/
2256
/* TCP Net console */
2257

    
2258
typedef struct {
2259
    IOCanRWHandler *fd_can_read;
2260
    IOReadHandler *fd_read;
2261
    void *fd_opaque;
2262
    int fd, listen_fd;
2263
    int connected;
2264
    int max_size;
2265
    int do_telnetopt;
2266
} TCPCharDriver;
2267

    
2268
static void tcp_chr_accept(void *opaque);
2269

    
2270
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2271
{
2272
    TCPCharDriver *s = chr->opaque;
2273
    if (s->connected) {
2274
        return send_all(s->fd, buf, len);
2275
    } else {
2276
        /* XXX: indicate an error ? */
2277
        return len;
2278
    }
2279
}
2280

    
2281
static int tcp_chr_read_poll(void *opaque)
2282
{
2283
    CharDriverState *chr = opaque;
2284
    TCPCharDriver *s = chr->opaque;
2285
    if (!s->connected)
2286
        return 0;
2287
    s->max_size = s->fd_can_read(s->fd_opaque);
2288
    return s->max_size;
2289
}
2290

    
2291
#define IAC 255
2292
#define IAC_BREAK 243
2293
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2294
                                      TCPCharDriver *s,
2295
                                      char *buf, int *size)
2296
{
2297
    /* Handle any telnet client's basic IAC options to satisfy char by
2298
     * char mode with no echo.  All IAC options will be removed from
2299
     * the buf and the do_telnetopt variable will be used to track the
2300
     * state of the width of the IAC information.
2301
     *
2302
     * IAC commands come in sets of 3 bytes with the exception of the
2303
     * "IAC BREAK" command and the double IAC.
2304
     */
2305

    
2306
    int i;
2307
    int j = 0;
2308

    
2309
    for (i = 0; i < *size; i++) {
2310
        if (s->do_telnetopt > 1) {
2311
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2312
                /* Double IAC means send an IAC */
2313
                if (j != i)
2314
                    buf[j] = buf[i];
2315
                j++;
2316
                s->do_telnetopt = 1;
2317
            } else {
2318
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2319
                    /* Handle IAC break commands by sending a serial break */
2320
                    chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2321
                    s->do_telnetopt++;
2322
                }
2323
                s->do_telnetopt++;
2324
            }
2325
            if (s->do_telnetopt >= 4) {
2326
                s->do_telnetopt = 1;
2327
            }
2328
        } else {
2329
            if ((unsigned char)buf[i] == IAC) {
2330
                s->do_telnetopt = 2;
2331
            } else {
2332
                if (j != i)
2333
                    buf[j] = buf[i];
2334
                j++;
2335
            }
2336
        }
2337
    }
2338
    *size = j;
2339
}
2340

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

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

    
2371
static void tcp_chr_add_read_handler(CharDriverState *chr,
2372
                                     IOCanRWHandler *fd_can_read,
2373
                                    IOReadHandler *fd_read, void *opaque)
2374
{
2375
    TCPCharDriver *s = chr->opaque;
2376

    
2377
    s->fd_can_read = fd_can_read;
2378
    s->fd_read = fd_read;
2379
    s->fd_opaque = opaque;
2380
}
2381

    
2382
static void tcp_chr_connect(void *opaque)
2383
{
2384
    CharDriverState *chr = opaque;
2385
    TCPCharDriver *s = chr->opaque;
2386

    
2387
    s->connected = 1;
2388
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2389
                         tcp_chr_read, NULL, chr);
2390
}
2391

    
2392
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2393
static void tcp_chr_telnet_init(int fd)
2394
{
2395
    char buf[3];
2396
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2397
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2398
    send(fd, (char *)buf, 3, 0);
2399
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2400
    send(fd, (char *)buf, 3, 0);
2401
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2402
    send(fd, (char *)buf, 3, 0);
2403
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2404
    send(fd, (char *)buf, 3, 0);
2405
}
2406

    
2407
static void tcp_chr_accept(void *opaque)
2408
{
2409
    CharDriverState *chr = opaque;
2410
    TCPCharDriver *s = chr->opaque;
2411
    struct sockaddr_in saddr;
2412
    socklen_t len;
2413
    int fd;
2414

    
2415
    for(;;) {
2416
        len = sizeof(saddr);
2417
        fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2418
        if (fd < 0 && errno != EINTR) {
2419
            return;
2420
        } else if (fd >= 0) {
2421
            if (s->do_telnetopt)
2422
                tcp_chr_telnet_init(fd);
2423
            break;
2424
        }
2425
    }
2426
    socket_set_nonblock(fd);
2427
    s->fd = fd;
2428
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2429
    tcp_chr_connect(chr);
2430
}
2431

    
2432
static void tcp_chr_close(CharDriverState *chr)
2433
{
2434
    TCPCharDriver *s = chr->opaque;
2435
    if (s->fd >= 0)
2436
        closesocket(s->fd);
2437
    if (s->listen_fd >= 0)
2438
        closesocket(s->listen_fd);
2439
    qemu_free(s);
2440
}
2441

    
2442
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2443
                                          int is_telnet)
2444
{
2445
    CharDriverState *chr = NULL;
2446
    TCPCharDriver *s = NULL;
2447
    int fd = -1, ret, err, val;
2448
    int is_listen = 0;
2449
    int is_waitconnect = 1;
2450
    const char *ptr;
2451
    struct sockaddr_in saddr;
2452

    
2453
    if (parse_host_port(&saddr, host_str) < 0)
2454
        goto fail;
2455

    
2456
    ptr = host_str;
2457
    while((ptr = strchr(ptr,','))) {
2458
        ptr++;
2459
        if (!strncmp(ptr,"server",6)) {
2460
            is_listen = 1;
2461
        } else if (!strncmp(ptr,"nowait",6)) {
2462
            is_waitconnect = 0;
2463
        } else {
2464
            printf("Unknown option: %s\n", ptr);
2465
            goto fail;
2466
        }
2467
    }
2468
    if (!is_listen)
2469
        is_waitconnect = 0;
2470

    
2471
    chr = qemu_mallocz(sizeof(CharDriverState));
2472
    if (!chr)
2473
        goto fail;
2474
    s = qemu_mallocz(sizeof(TCPCharDriver));
2475
    if (!s)
2476
        goto fail;
2477
    
2478
    fd = socket(PF_INET, SOCK_STREAM, 0);
2479
    if (fd < 0) 
2480
        goto fail;
2481

    
2482
    if (!is_waitconnect)
2483
        socket_set_nonblock(fd);
2484

    
2485
    s->connected = 0;
2486
    s->fd = -1;
2487
    s->listen_fd = -1;
2488
    if (is_listen) {
2489
        /* allow fast reuse */
2490
        val = 1;
2491
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2492
        
2493
        ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2494
        if (ret < 0) 
2495
            goto fail;
2496
        ret = listen(fd, 0);
2497
        if (ret < 0)
2498
            goto fail;
2499
        s->listen_fd = fd;
2500
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2501
        if (is_telnet)
2502
            s->do_telnetopt = 1;
2503
    } else {
2504
        for(;;) {
2505
            ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2506
            if (ret < 0) {
2507
                err = socket_error();
2508
                if (err == EINTR || err == EWOULDBLOCK) {
2509
                } else if (err == EINPROGRESS) {
2510
                    break;
2511
                } else {
2512
                    goto fail;
2513
                }
2514
            } else {
2515
                s->connected = 1;
2516
                break;
2517
            }
2518
        }
2519
        s->fd = fd;
2520
        if (s->connected)
2521
            tcp_chr_connect(chr);
2522
        else
2523
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2524
    }
2525
    
2526
    chr->opaque = s;
2527
    chr->chr_write = tcp_chr_write;
2528
    chr->chr_add_read_handler = tcp_chr_add_read_handler;
2529
    chr->chr_close = tcp_chr_close;
2530
    if (is_listen && is_waitconnect) {
2531
        printf("QEMU waiting for connection on: %s\n", host_str);
2532
        tcp_chr_accept(chr);
2533
        socket_set_nonblock(s->listen_fd);
2534
    }
2535

    
2536
    return chr;
2537
 fail:
2538
    if (fd >= 0)
2539
        closesocket(fd);
2540
    qemu_free(s);
2541
    qemu_free(chr);
2542
    return NULL;
2543
}
2544

    
2545
CharDriverState *qemu_chr_open(const char *filename)
2546
{
2547
    const char *p;
2548

    
2549
    if (!strcmp(filename, "vc")) {
2550
        return text_console_init(&display_state);
2551
    } else if (!strcmp(filename, "null")) {
2552
        return qemu_chr_open_null();
2553
    } else 
2554
    if (strstart(filename, "tcp:", &p)) {
2555
        return qemu_chr_open_tcp(p, 0);
2556
    } else
2557
    if (strstart(filename, "telnet:", &p)) {
2558
        return qemu_chr_open_tcp(p, 1);
2559
    } else
2560
    if (strstart(filename, "udp:", &p)) {
2561
        return qemu_chr_open_udp(p);
2562
    } else
2563
#ifndef _WIN32
2564
    if (strstart(filename, "file:", &p)) {
2565
        return qemu_chr_open_file_out(p);
2566
    } else if (strstart(filename, "pipe:", &p)) {
2567
        return qemu_chr_open_pipe(p);
2568
    } else if (!strcmp(filename, "pty")) {
2569
        return qemu_chr_open_pty();
2570
    } else if (!strcmp(filename, "stdio")) {
2571
        return qemu_chr_open_stdio();
2572
    } else 
2573
#endif
2574
#if defined(__linux__)
2575
    if (strstart(filename, "/dev/parport", NULL)) {
2576
        return qemu_chr_open_pp(filename);
2577
    } else 
2578
    if (strstart(filename, "/dev/", NULL)) {
2579
        return qemu_chr_open_tty(filename);
2580
    } else 
2581
#endif
2582
#ifdef _WIN32
2583
    if (strstart(filename, "COM", NULL)) {
2584
        return qemu_chr_open_win(filename);
2585
    } else
2586
    if (strstart(filename, "pipe:", &p)) {
2587
        return qemu_chr_open_win_pipe(p);
2588
    } else
2589
    if (strstart(filename, "file:", &p)) {
2590
        return qemu_chr_open_win_file_out(p);
2591
    }
2592
#endif
2593
    {
2594
        return NULL;
2595
    }
2596
}
2597

    
2598
void qemu_chr_close(CharDriverState *chr)
2599
{
2600
    if (chr->chr_close)
2601
        chr->chr_close(chr);
2602
}
2603

    
2604
/***********************************************************/
2605
/* network device redirectors */
2606

    
2607
void hex_dump(FILE *f, const uint8_t *buf, int size)
2608
{
2609
    int len, i, j, c;
2610

    
2611
    for(i=0;i<size;i+=16) {
2612
        len = size - i;
2613
        if (len > 16)
2614
            len = 16;
2615
        fprintf(f, "%08x ", i);
2616
        for(j=0;j<16;j++) {
2617
            if (j < len)
2618
                fprintf(f, " %02x", buf[i+j]);
2619
            else
2620
                fprintf(f, "   ");
2621
        }
2622
        fprintf(f, " ");
2623
        for(j=0;j<len;j++) {
2624
            c = buf[i+j];
2625
            if (c < ' ' || c > '~')
2626
                c = '.';
2627
            fprintf(f, "%c", c);
2628
        }
2629
        fprintf(f, "\n");
2630
    }
2631
}
2632

    
2633
static int parse_macaddr(uint8_t *macaddr, const char *p)
2634
{
2635
    int i;
2636
    for(i = 0; i < 6; i++) {
2637
        macaddr[i] = strtol(p, (char **)&p, 16);
2638
        if (i == 5) {
2639
            if (*p != '\0') 
2640
                return -1;
2641
        } else {
2642
            if (*p != ':') 
2643
                return -1;
2644
            p++;
2645
        }
2646
    }
2647
    return 0;
2648
}
2649

    
2650
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2651
{
2652
    const char *p, *p1;
2653
    int len;
2654
    p = *pp;
2655
    p1 = strchr(p, sep);
2656
    if (!p1)
2657
        return -1;
2658
    len = p1 - p;
2659
    p1++;
2660
    if (buf_size > 0) {
2661
        if (len > buf_size - 1)
2662
            len = buf_size - 1;
2663
        memcpy(buf, p, len);
2664
        buf[len] = '\0';
2665
    }
2666
    *pp = p1;
2667
    return 0;
2668
}
2669

    
2670
int parse_host_src_port(struct sockaddr_in *haddr,
2671
                        struct sockaddr_in *saddr,
2672
                        const char *input_str)
2673
{
2674
    char *str = strdup(input_str);
2675
    char *host_str = str;
2676
    char *src_str;
2677
    char *ptr;
2678

    
2679
    /*
2680
     * Chop off any extra arguments at the end of the string which
2681
     * would start with a comma, then fill in the src port information
2682
     * if it was provided else use the "any address" and "any port".
2683
     */
2684
    if ((ptr = strchr(str,',')))
2685
        *ptr = '\0';
2686

    
2687
    if ((src_str = strchr(input_str,'@'))) {
2688
        *src_str = '\0';
2689
        src_str++;
2690
    }
2691

    
2692
    if (parse_host_port(haddr, host_str) < 0)
2693
        goto fail;
2694

    
2695
    if (!src_str || *src_str == '\0')
2696
        src_str = ":0";
2697

    
2698
    if (parse_host_port(saddr, src_str) < 0)
2699
        goto fail;
2700

    
2701
    free(str);
2702
    return(0);
2703

    
2704
fail:
2705
    free(str);
2706
    return -1;
2707
}
2708

    
2709
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2710
{
2711
    char buf[512];
2712
    struct hostent *he;
2713
    const char *p, *r;
2714
    int port;
2715

    
2716
    p = str;
2717
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2718
        return -1;
2719
    saddr->sin_family = AF_INET;
2720
    if (buf[0] == '\0') {
2721
        saddr->sin_addr.s_addr = 0;
2722
    } else {
2723
        if (isdigit(buf[0])) {
2724
            if (!inet_aton(buf, &saddr->sin_addr))
2725
                return -1;
2726
        } else {
2727
            if ((he = gethostbyname(buf)) == NULL)
2728
                return - 1;
2729
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2730
        }
2731
    }
2732
    port = strtol(p, (char **)&r, 0);
2733
    if (r == p)
2734
        return -1;
2735
    saddr->sin_port = htons(port);
2736
    return 0;
2737
}
2738

    
2739
/* find or alloc a new VLAN */
2740
VLANState *qemu_find_vlan(int id)
2741
{
2742
    VLANState **pvlan, *vlan;
2743
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2744
        if (vlan->id == id)
2745
            return vlan;
2746
    }
2747
    vlan = qemu_mallocz(sizeof(VLANState));
2748
    if (!vlan)
2749
        return NULL;
2750
    vlan->id = id;
2751
    vlan->next = NULL;
2752
    pvlan = &first_vlan;
2753
    while (*pvlan != NULL)
2754
        pvlan = &(*pvlan)->next;
2755
    *pvlan = vlan;
2756
    return vlan;
2757
}
2758

    
2759
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2760
                                      IOReadHandler *fd_read,
2761
                                      IOCanRWHandler *fd_can_read,
2762
                                      void *opaque)
2763
{
2764
    VLANClientState *vc, **pvc;
2765
    vc = qemu_mallocz(sizeof(VLANClientState));
2766
    if (!vc)
2767
        return NULL;
2768
    vc->fd_read = fd_read;
2769
    vc->fd_can_read = fd_can_read;
2770
    vc->opaque = opaque;
2771
    vc->vlan = vlan;
2772

    
2773
    vc->next = NULL;
2774
    pvc = &vlan->first_client;
2775
    while (*pvc != NULL)
2776
        pvc = &(*pvc)->next;
2777
    *pvc = vc;
2778
    return vc;
2779
}
2780

    
2781
int qemu_can_send_packet(VLANClientState *vc1)
2782
{
2783
    VLANState *vlan = vc1->vlan;
2784
    VLANClientState *vc;
2785

    
2786
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2787
        if (vc != vc1) {
2788
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2789
                return 0;
2790
        }
2791
    }
2792
    return 1;
2793
}
2794

    
2795
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2796
{
2797
    VLANState *vlan = vc1->vlan;
2798
    VLANClientState *vc;
2799

    
2800
#if 0
2801
    printf("vlan %d send:\n", vlan->id);
2802
    hex_dump(stdout, buf, size);
2803
#endif
2804
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2805
        if (vc != vc1) {
2806
            vc->fd_read(vc->opaque, buf, size);
2807
        }
2808
    }
2809
}
2810

    
2811
#if defined(CONFIG_SLIRP)
2812

    
2813
/* slirp network adapter */
2814

    
2815
static int slirp_inited;
2816
static VLANClientState *slirp_vc;
2817

    
2818
int slirp_can_output(void)
2819
{
2820
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
2821
}
2822

    
2823
void slirp_output(const uint8_t *pkt, int pkt_len)
2824
{
2825
#if 0
2826
    printf("slirp output:\n");
2827
    hex_dump(stdout, pkt, pkt_len);
2828
#endif
2829
    if (!slirp_vc)
2830
        return;
2831
    qemu_send_packet(slirp_vc, pkt, pkt_len);
2832
}
2833

    
2834
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2835
{
2836
#if 0
2837
    printf("slirp input:\n");
2838
    hex_dump(stdout, buf, size);
2839
#endif
2840
    slirp_input(buf, size);
2841
}
2842

    
2843
static int net_slirp_init(VLANState *vlan)
2844
{
2845
    if (!slirp_inited) {
2846
        slirp_inited = 1;
2847
        slirp_init();
2848
    }
2849
    slirp_vc = qemu_new_vlan_client(vlan, 
2850
                                    slirp_receive, NULL, NULL);
2851
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2852
    return 0;
2853
}
2854

    
2855
static void net_slirp_redir(const char *redir_str)
2856
{
2857
    int is_udp;
2858
    char buf[256], *r;
2859
    const char *p;
2860
    struct in_addr guest_addr;
2861
    int host_port, guest_port;
2862
    
2863
    if (!slirp_inited) {
2864
        slirp_inited = 1;
2865
        slirp_init();
2866
    }
2867

    
2868
    p = redir_str;
2869
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2870
        goto fail;
2871
    if (!strcmp(buf, "tcp")) {
2872
        is_udp = 0;
2873
    } else if (!strcmp(buf, "udp")) {
2874
        is_udp = 1;
2875
    } else {
2876
        goto fail;
2877
    }
2878

    
2879
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2880
        goto fail;
2881
    host_port = strtol(buf, &r, 0);
2882
    if (r == buf)
2883
        goto fail;
2884

    
2885
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2886
        goto fail;
2887
    if (buf[0] == '\0') {
2888
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
2889
    }
2890
    if (!inet_aton(buf, &guest_addr))
2891
        goto fail;
2892
    
2893
    guest_port = strtol(p, &r, 0);
2894
    if (r == p)
2895
        goto fail;
2896
    
2897
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2898
        fprintf(stderr, "qemu: could not set up redirection\n");
2899
        exit(1);
2900
    }
2901
    return;
2902
 fail:
2903
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2904
    exit(1);
2905
}
2906
    
2907
#ifndef _WIN32
2908

    
2909
char smb_dir[1024];
2910

    
2911
static void smb_exit(void)
2912
{
2913
    DIR *d;
2914
    struct dirent *de;
2915
    char filename[1024];
2916

    
2917
    /* erase all the files in the directory */
2918
    d = opendir(smb_dir);
2919
    for(;;) {
2920
        de = readdir(d);
2921
        if (!de)
2922
            break;
2923
        if (strcmp(de->d_name, ".") != 0 &&
2924
            strcmp(de->d_name, "..") != 0) {
2925
            snprintf(filename, sizeof(filename), "%s/%s", 
2926
                     smb_dir, de->d_name);
2927
            unlink(filename);
2928
        }
2929
    }
2930
    closedir(d);
2931
    rmdir(smb_dir);
2932
}
2933

    
2934
/* automatic user mode samba server configuration */
2935
void net_slirp_smb(const char *exported_dir)
2936
{
2937
    char smb_conf[1024];
2938
    char smb_cmdline[1024];
2939
    FILE *f;
2940

    
2941
    if (!slirp_inited) {
2942
        slirp_inited = 1;
2943
        slirp_init();
2944
    }
2945

    
2946
    /* XXX: better tmp dir construction */
2947
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2948
    if (mkdir(smb_dir, 0700) < 0) {
2949
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2950
        exit(1);
2951
    }
2952
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2953
    
2954
    f = fopen(smb_conf, "w");
2955
    if (!f) {
2956
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2957
        exit(1);
2958
    }
2959
    fprintf(f, 
2960
            "[global]\n"
2961
            "private dir=%s\n"
2962
            "smb ports=0\n"
2963
            "socket address=127.0.0.1\n"
2964
            "pid directory=%s\n"
2965
            "lock directory=%s\n"
2966
            "log file=%s/log.smbd\n"
2967
            "smb passwd file=%s/smbpasswd\n"
2968
            "security = share\n"
2969
            "[qemu]\n"
2970
            "path=%s\n"
2971
            "read only=no\n"
2972
            "guest ok=yes\n",
2973
            smb_dir,
2974
            smb_dir,
2975
            smb_dir,
2976
            smb_dir,
2977
            smb_dir,
2978
            exported_dir
2979
            );
2980
    fclose(f);
2981
    atexit(smb_exit);
2982

    
2983
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2984
             smb_conf);
2985
    
2986
    slirp_add_exec(0, smb_cmdline, 4, 139);
2987
}
2988

    
2989
#endif /* !defined(_WIN32) */
2990

    
2991
#endif /* CONFIG_SLIRP */
2992

    
2993
#if !defined(_WIN32)
2994

    
2995
typedef struct TAPState {
2996
    VLANClientState *vc;
2997
    int fd;
2998
} TAPState;
2999

    
3000
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3001
{
3002
    TAPState *s = opaque;
3003
    int ret;
3004
    for(;;) {
3005
        ret = write(s->fd, buf, size);
3006
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3007
        } else {
3008
            break;
3009
        }
3010
    }
3011
}
3012

    
3013
static void tap_send(void *opaque)
3014
{
3015
    TAPState *s = opaque;
3016
    uint8_t buf[4096];
3017
    int size;
3018

    
3019
    size = read(s->fd, buf, sizeof(buf));
3020
    if (size > 0) {
3021
        qemu_send_packet(s->vc, buf, size);
3022
    }
3023
}
3024

    
3025
/* fd support */
3026

    
3027
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3028
{
3029
    TAPState *s;
3030

    
3031
    s = qemu_mallocz(sizeof(TAPState));
3032
    if (!s)
3033
        return NULL;
3034
    s->fd = fd;
3035
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3036
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3037
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3038
    return s;
3039
}
3040

    
3041
#ifdef _BSD
3042
static int tap_open(char *ifname, int ifname_size)
3043
{
3044
    int fd;
3045
    char *dev;
3046
    struct stat s;
3047

    
3048
    fd = open("/dev/tap", O_RDWR);
3049
    if (fd < 0) {
3050
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3051
        return -1;
3052
    }
3053

    
3054
    fstat(fd, &s);
3055
    dev = devname(s.st_rdev, S_IFCHR);
3056
    pstrcpy(ifname, ifname_size, dev);
3057

    
3058
    fcntl(fd, F_SETFL, O_NONBLOCK);
3059
    return fd;
3060
}
3061
#elif defined(__sun__)
3062
static int tap_open(char *ifname, int ifname_size)
3063
{
3064
    fprintf(stderr, "warning: tap_open not yet implemented\n");
3065
    return -1;
3066
}
3067
#else
3068
static int tap_open(char *ifname, int ifname_size)
3069
{
3070
    struct ifreq ifr;
3071
    int fd, ret;
3072
    
3073
    fd = open("/dev/net/tun", O_RDWR);
3074
    if (fd < 0) {
3075
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3076
        return -1;
3077
    }
3078
    memset(&ifr, 0, sizeof(ifr));
3079
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3080
    if (ifname[0] != '\0')
3081
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3082
    else
3083
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3084
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3085
    if (ret != 0) {
3086
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3087
        close(fd);
3088
        return -1;
3089
    }
3090
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3091
    fcntl(fd, F_SETFL, O_NONBLOCK);
3092
    return fd;
3093
}
3094
#endif
3095

    
3096
static int net_tap_init(VLANState *vlan, const char *ifname1,
3097
                        const char *setup_script)
3098
{
3099
    TAPState *s;
3100
    int pid, status, fd;
3101
    char *args[3];
3102
    char **parg;
3103
    char ifname[128];
3104

    
3105
    if (ifname1 != NULL)
3106
        pstrcpy(ifname, sizeof(ifname), ifname1);
3107
    else
3108
        ifname[0] = '\0';
3109
    fd = tap_open(ifname, sizeof(ifname));
3110
    if (fd < 0)
3111
        return -1;
3112

    
3113
    if (!setup_script)
3114
        setup_script = "";
3115
    if (setup_script[0] != '\0') {
3116
        /* try to launch network init script */
3117
        pid = fork();
3118
        if (pid >= 0) {
3119
            if (pid == 0) {
3120
                parg = args;
3121
                *parg++ = (char *)setup_script;
3122
                *parg++ = ifname;
3123
                *parg++ = NULL;
3124
                execv(setup_script, args);
3125
                _exit(1);
3126
            }
3127
            while (waitpid(pid, &status, 0) != pid);
3128
            if (!WIFEXITED(status) ||
3129
                WEXITSTATUS(status) != 0) {
3130
                fprintf(stderr, "%s: could not launch network script\n",
3131
                        setup_script);
3132
                return -1;
3133
            }
3134
        }
3135
    }
3136
    s = net_tap_fd_init(vlan, fd);
3137
    if (!s)
3138
        return -1;
3139
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3140
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3141
    return 0;
3142
}
3143

    
3144
#endif /* !_WIN32 */
3145

    
3146
/* network connection */
3147
typedef struct NetSocketState {
3148
    VLANClientState *vc;
3149
    int fd;
3150
    int state; /* 0 = getting length, 1 = getting data */
3151
    int index;
3152
    int packet_len;
3153
    uint8_t buf[4096];
3154
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3155
} NetSocketState;
3156

    
3157
typedef struct NetSocketListenState {
3158
    VLANState *vlan;
3159
    int fd;
3160
} NetSocketListenState;
3161

    
3162
/* XXX: we consider we can send the whole packet without blocking */
3163
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3164
{
3165
    NetSocketState *s = opaque;
3166
    uint32_t len;
3167
    len = htonl(size);
3168

    
3169
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3170
    send_all(s->fd, buf, size);
3171
}
3172

    
3173
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3174
{
3175
    NetSocketState *s = opaque;
3176
    sendto(s->fd, buf, size, 0, 
3177
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3178
}
3179

    
3180
static void net_socket_send(void *opaque)
3181
{
3182
    NetSocketState *s = opaque;
3183
    int l, size, err;
3184
    uint8_t buf1[4096];
3185
    const uint8_t *buf;
3186

    
3187
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3188
    if (size < 0) {
3189
        err = socket_error();
3190
        if (err != EWOULDBLOCK) 
3191
            goto eoc;
3192
    } else if (size == 0) {
3193
        /* end of connection */
3194
    eoc:
3195
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3196
        closesocket(s->fd);
3197
        return;
3198
    }
3199
    buf = buf1;
3200
    while (size > 0) {
3201
        /* reassemble a packet from the network */
3202
        switch(s->state) {
3203
        case 0:
3204
            l = 4 - s->index;
3205
            if (l > size)
3206
                l = size;
3207
            memcpy(s->buf + s->index, buf, l);
3208
            buf += l;
3209
            size -= l;
3210
            s->index += l;
3211
            if (s->index == 4) {
3212
                /* got length */
3213
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3214
                s->index = 0;
3215
                s->state = 1;
3216
            }
3217
            break;
3218
        case 1:
3219
            l = s->packet_len - s->index;
3220
            if (l > size)
3221
                l = size;
3222
            memcpy(s->buf + s->index, buf, l);
3223
            s->index += l;
3224
            buf += l;
3225
            size -= l;
3226
            if (s->index >= s->packet_len) {
3227
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3228
                s->index = 0;
3229
                s->state = 0;
3230
            }
3231
            break;
3232
        }
3233
    }
3234
}
3235

    
3236
static void net_socket_send_dgram(void *opaque)
3237
{
3238
    NetSocketState *s = opaque;
3239
    int size;
3240

    
3241
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3242
    if (size < 0) 
3243
        return;
3244
    if (size == 0) {
3245
        /* end of connection */
3246
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3247
        return;
3248
    }
3249
    qemu_send_packet(s->vc, s->buf, size);
3250
}
3251

    
3252
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3253
{
3254
    struct ip_mreq imr;
3255
    int fd;
3256
    int val, ret;
3257
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3258
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3259
                inet_ntoa(mcastaddr->sin_addr), 
3260
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3261
        return -1;
3262

    
3263
    }
3264
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3265
    if (fd < 0) {
3266
        perror("socket(PF_INET, SOCK_DGRAM)");
3267
        return -1;
3268
    }
3269

    
3270
    val = 1;
3271
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3272
                   (const char *)&val, sizeof(val));
3273
    if (ret < 0) {
3274
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3275
        goto fail;
3276
    }
3277

    
3278
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3279
    if (ret < 0) {
3280
        perror("bind");
3281
        goto fail;
3282
    }
3283
    
3284
    /* Add host to multicast group */
3285
    imr.imr_multiaddr = mcastaddr->sin_addr;
3286
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3287

    
3288
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3289
                     (const char *)&imr, sizeof(struct ip_mreq));
3290
    if (ret < 0) {
3291
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3292
        goto fail;
3293
    }
3294

    
3295
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3296
    val = 1;
3297
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3298
                   (const char *)&val, sizeof(val));
3299
    if (ret < 0) {
3300
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3301
        goto fail;
3302
    }
3303

    
3304
    socket_set_nonblock(fd);
3305
    return fd;
3306
fail:
3307
    if (fd >= 0) 
3308
        closesocket(fd);
3309
    return -1;
3310
}
3311

    
3312
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3313
                                          int is_connected)
3314
{
3315
    struct sockaddr_in saddr;
3316
    int newfd;
3317
    socklen_t saddr_len;
3318
    NetSocketState *s;
3319

    
3320
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3321
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3322
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3323
     */
3324

    
3325
    if (is_connected) {
3326
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3327
            /* must be bound */
3328
            if (saddr.sin_addr.s_addr==0) {
3329
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3330
                        fd);
3331
                return NULL;
3332
            }
3333
            /* clone dgram socket */
3334
            newfd = net_socket_mcast_create(&saddr);
3335
            if (newfd < 0) {
3336
                /* error already reported by net_socket_mcast_create() */
3337
                close(fd);
3338
                return NULL;
3339
            }
3340
            /* clone newfd to fd, close newfd */
3341
            dup2(newfd, fd);
3342
            close(newfd);
3343
        
3344
        } else {
3345
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3346
                    fd, strerror(errno));
3347
            return NULL;
3348
        }
3349
    }
3350

    
3351
    s = qemu_mallocz(sizeof(NetSocketState));
3352
    if (!s)
3353
        return NULL;
3354
    s->fd = fd;
3355

    
3356
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3357
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3358

    
3359
    /* mcast: save bound address as dst */
3360
    if (is_connected) s->dgram_dst=saddr;
3361

    
3362
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3363
            "socket: fd=%d (%s mcast=%s:%d)", 
3364
            fd, is_connected? "cloned" : "",
3365
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3366
    return s;
3367
}
3368

    
3369
static void net_socket_connect(void *opaque)
3370
{
3371
    NetSocketState *s = opaque;
3372
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3373
}
3374

    
3375
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3376
                                          int is_connected)
3377
{
3378
    NetSocketState *s;
3379
    s = qemu_mallocz(sizeof(NetSocketState));
3380
    if (!s)
3381
        return NULL;
3382
    s->fd = fd;
3383
    s->vc = qemu_new_vlan_client(vlan, 
3384
                                 net_socket_receive, NULL, s);
3385
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3386
             "socket: fd=%d", fd);
3387
    if (is_connected) {
3388
        net_socket_connect(s);
3389
    } else {
3390
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3391
    }
3392
    return s;
3393
}
3394

    
3395
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3396
                                          int is_connected)
3397
{
3398
    int so_type=-1, optlen=sizeof(so_type);
3399

    
3400
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3401
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3402
        return NULL;
3403
    }
3404
    switch(so_type) {
3405
    case SOCK_DGRAM:
3406
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3407
    case SOCK_STREAM:
3408
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3409
    default:
3410
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3411
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3412
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3413
    }
3414
    return NULL;
3415
}
3416

    
3417
static void net_socket_accept(void *opaque)
3418
{
3419
    NetSocketListenState *s = opaque;    
3420
    NetSocketState *s1;
3421
    struct sockaddr_in saddr;
3422
    socklen_t len;
3423
    int fd;
3424

    
3425
    for(;;) {
3426
        len = sizeof(saddr);
3427
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3428
        if (fd < 0 && errno != EINTR) {
3429
            return;
3430
        } else if (fd >= 0) {
3431
            break;
3432
        }
3433
    }
3434
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3435
    if (!s1) {
3436
        closesocket(fd);
3437
    } else {
3438
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3439
                 "socket: connection from %s:%d", 
3440
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3441
    }
3442
}
3443

    
3444
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3445
{
3446
    NetSocketListenState *s;
3447
    int fd, val, ret;
3448
    struct sockaddr_in saddr;
3449

    
3450
    if (parse_host_port(&saddr, host_str) < 0)
3451
        return -1;
3452
    
3453
    s = qemu_mallocz(sizeof(NetSocketListenState));
3454
    if (!s)
3455
        return -1;
3456

    
3457
    fd = socket(PF_INET, SOCK_STREAM, 0);
3458
    if (fd < 0) {
3459
        perror("socket");
3460
        return -1;
3461
    }
3462
    socket_set_nonblock(fd);
3463

    
3464
    /* allow fast reuse */
3465
    val = 1;
3466
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3467
    
3468
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3469
    if (ret < 0) {
3470
        perror("bind");
3471
        return -1;
3472
    }
3473
    ret = listen(fd, 0);
3474
    if (ret < 0) {
3475
        perror("listen");
3476
        return -1;
3477
    }
3478
    s->vlan = vlan;
3479
    s->fd = fd;
3480
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3481
    return 0;
3482
}
3483

    
3484
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3485
{
3486
    NetSocketState *s;
3487
    int fd, connected, ret, err;
3488
    struct sockaddr_in saddr;
3489

    
3490
    if (parse_host_port(&saddr, host_str) < 0)
3491
        return -1;
3492

    
3493
    fd = socket(PF_INET, SOCK_STREAM, 0);
3494
    if (fd < 0) {
3495
        perror("socket");
3496
        return -1;
3497
    }
3498
    socket_set_nonblock(fd);
3499

    
3500
    connected = 0;
3501
    for(;;) {
3502
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3503
        if (ret < 0) {
3504
            err = socket_error();
3505
            if (err == EINTR || err == EWOULDBLOCK) {
3506
            } else if (err == EINPROGRESS) {
3507
                break;
3508
            } else {
3509
                perror("connect");
3510
                closesocket(fd);
3511
                return -1;
3512
            }
3513
        } else {
3514
            connected = 1;
3515
            break;
3516
        }
3517
    }
3518
    s = net_socket_fd_init(vlan, fd, connected);
3519
    if (!s)
3520
        return -1;
3521
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3522
             "socket: connect to %s:%d", 
3523
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3524
    return 0;
3525
}
3526

    
3527
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3528
{
3529
    NetSocketState *s;
3530
    int fd;
3531
    struct sockaddr_in saddr;
3532

    
3533
    if (parse_host_port(&saddr, host_str) < 0)
3534
        return -1;
3535

    
3536

    
3537
    fd = net_socket_mcast_create(&saddr);
3538
    if (fd < 0)
3539
        return -1;
3540

    
3541
    s = net_socket_fd_init(vlan, fd, 0);
3542
    if (!s)
3543
        return -1;
3544

    
3545
    s->dgram_dst = saddr;
3546
    
3547
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3548
             "socket: mcast=%s:%d", 
3549
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3550
    return 0;
3551

    
3552
}
3553

    
3554
static int get_param_value(char *buf, int buf_size,
3555
                           const char *tag, const char *str)
3556
{
3557
    const char *p;
3558
    char *q;
3559
    char option[128];
3560

    
3561
    p = str;
3562
    for(;;) {
3563
        q = option;
3564
        while (*p != '\0' && *p != '=') {
3565
            if ((q - option) < sizeof(option) - 1)
3566
                *q++ = *p;
3567
            p++;
3568
        }
3569
        *q = '\0';
3570
        if (*p != '=')
3571
            break;
3572
        p++;
3573
        if (!strcmp(tag, option)) {
3574
            q = buf;
3575
            while (*p != '\0' && *p != ',') {
3576
                if ((q - buf) < buf_size - 1)
3577
                    *q++ = *p;
3578
                p++;
3579
            }
3580
            *q = '\0';
3581
            return q - buf;
3582
        } else {
3583
            while (*p != '\0' && *p != ',') {
3584
                p++;
3585
            }
3586
        }
3587
        if (*p != ',')
3588
            break;
3589
        p++;
3590
    }
3591
    return 0;
3592
}
3593

    
3594
int net_client_init(const char *str)
3595
{
3596
    const char *p;
3597
    char *q;
3598
    char device[64];
3599
    char buf[1024];
3600
    int vlan_id, ret;
3601
    VLANState *vlan;
3602

    
3603
    p = str;
3604
    q = device;
3605
    while (*p != '\0' && *p != ',') {
3606
        if ((q - device) < sizeof(device) - 1)
3607
            *q++ = *p;
3608
        p++;
3609
    }
3610
    *q = '\0';
3611
    if (*p == ',')
3612
        p++;
3613
    vlan_id = 0;
3614
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3615
        vlan_id = strtol(buf, NULL, 0);
3616
    }
3617
    vlan = qemu_find_vlan(vlan_id);
3618
    if (!vlan) {
3619
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3620
        return -1;
3621
    }
3622
    if (!strcmp(device, "nic")) {
3623
        NICInfo *nd;
3624
        uint8_t *macaddr;
3625

    
3626
        if (nb_nics >= MAX_NICS) {
3627
            fprintf(stderr, "Too Many NICs\n");
3628
            return -1;
3629
        }
3630
        nd = &nd_table[nb_nics];
3631
        macaddr = nd->macaddr;
3632
        macaddr[0] = 0x52;
3633
        macaddr[1] = 0x54;
3634
        macaddr[2] = 0x00;
3635
        macaddr[3] = 0x12;
3636
        macaddr[4] = 0x34;
3637
        macaddr[5] = 0x56 + nb_nics;
3638

    
3639
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3640
            if (parse_macaddr(macaddr, buf) < 0) {
3641
                fprintf(stderr, "invalid syntax for ethernet address\n");
3642
                return -1;
3643
            }
3644
        }
3645
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3646
            nd->model = strdup(buf);
3647
        }
3648
        nd->vlan = vlan;
3649
        nb_nics++;
3650
        ret = 0;
3651
    } else
3652
    if (!strcmp(device, "none")) {
3653
        /* does nothing. It is needed to signal that no network cards
3654
           are wanted */
3655
        ret = 0;
3656
    } else
3657
#ifdef CONFIG_SLIRP
3658
    if (!strcmp(device, "user")) {
3659
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3660
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3661
        }
3662
        ret = net_slirp_init(vlan);
3663
    } else
3664
#endif
3665
#ifdef _WIN32
3666
    if (!strcmp(device, "tap")) {
3667
        char ifname[64];
3668
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3669
            fprintf(stderr, "tap: no interface name\n");
3670
            return -1;
3671
        }
3672
        ret = tap_win32_init(vlan, ifname);
3673
    } else
3674
#else
3675
    if (!strcmp(device, "tap")) {
3676
        char ifname[64];
3677
        char setup_script[1024];
3678
        int fd;
3679
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3680
            fd = strtol(buf, NULL, 0);
3681
            ret = -1;
3682
            if (net_tap_fd_init(vlan, fd))
3683
                ret = 0;
3684
        } else {
3685
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3686
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3687
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3688
            }
3689
            ret = net_tap_init(vlan, ifname, setup_script);
3690
        }
3691
    } else
3692
#endif
3693
    if (!strcmp(device, "socket")) {
3694
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3695
            int fd;
3696
            fd = strtol(buf, NULL, 0);
3697
            ret = -1;
3698
            if (net_socket_fd_init(vlan, fd, 1))
3699
                ret = 0;
3700
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3701
            ret = net_socket_listen_init(vlan, buf);
3702
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3703
            ret = net_socket_connect_init(vlan, buf);
3704
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3705
            ret = net_socket_mcast_init(vlan, buf);
3706
        } else {
3707
            fprintf(stderr, "Unknown socket options: %s\n", p);
3708
            return -1;
3709
        }
3710
    } else
3711
    {
3712
        fprintf(stderr, "Unknown network device: %s\n", device);
3713
        return -1;
3714
    }
3715
    if (ret < 0) {
3716
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3717
    }
3718
    
3719
    return ret;
3720
}
3721

    
3722
void do_info_network(void)
3723
{
3724
    VLANState *vlan;
3725
    VLANClientState *vc;
3726

    
3727
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3728
        term_printf("VLAN %d devices:\n", vlan->id);
3729
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3730
            term_printf("  %s\n", vc->info_str);
3731
    }
3732
}
3733
 
3734
/***********************************************************/
3735
/* USB devices */
3736

    
3737
static USBPort *used_usb_ports;
3738
static USBPort *free_usb_ports;
3739

    
3740
/* ??? Maybe change this to register a hub to keep track of the topology.  */
3741
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3742
                            usb_attachfn attach)
3743
{
3744
    port->opaque = opaque;
3745
    port->index = index;
3746
    port->attach = attach;
3747
    port->next = free_usb_ports;
3748
    free_usb_ports = port;
3749
}
3750

    
3751
static int usb_device_add(const char *devname)
3752
{
3753
    const char *p;
3754
    USBDevice *dev;
3755
    USBPort *port;
3756

    
3757
    if (!free_usb_ports)
3758
        return -1;
3759

    
3760
    if (strstart(devname, "host:", &p)) {
3761
        dev = usb_host_device_open(p);
3762
    } else if (!strcmp(devname, "mouse")) {
3763
        dev = usb_mouse_init();
3764
    } else if (!strcmp(devname, "tablet")) {
3765
        dev = usb_tablet_init();
3766
    } else if (strstart(devname, "disk:", &p)) {
3767
        dev = usb_msd_init(p);
3768
    } else {
3769
        return -1;
3770
    }
3771
    if (!dev)
3772
        return -1;
3773

    
3774
    /* Find a USB port to add the device to.  */
3775
    port = free_usb_ports;
3776
    if (!port->next) {
3777
        USBDevice *hub;
3778

    
3779
        /* Create a new hub and chain it on.  */
3780
        free_usb_ports = NULL;
3781
        port->next = used_usb_ports;
3782
        used_usb_ports = port;
3783

    
3784
        hub = usb_hub_init(VM_USB_HUB_SIZE);
3785
        usb_attach(port, hub);
3786
        port = free_usb_ports;
3787
    }
3788

    
3789
    free_usb_ports = port->next;
3790
    port->next = used_usb_ports;
3791
    used_usb_ports = port;
3792
    usb_attach(port, dev);
3793
    return 0;
3794
}
3795

    
3796
static int usb_device_del(const char *devname)
3797
{
3798
    USBPort *port;
3799
    USBPort **lastp;
3800
    USBDevice *dev;
3801
    int bus_num, addr;
3802
    const char *p;
3803

    
3804
    if (!used_usb_ports)
3805
        return -1;
3806

    
3807
    p = strchr(devname, '.');
3808
    if (!p) 
3809
        return -1;
3810
    bus_num = strtoul(devname, NULL, 0);
3811
    addr = strtoul(p + 1, NULL, 0);
3812
    if (bus_num != 0)
3813
        return -1;
3814

    
3815
    lastp = &used_usb_ports;
3816
    port = used_usb_ports;
3817
    while (port && port->dev->addr != addr) {
3818
        lastp = &port->next;
3819
        port = port->next;
3820
    }
3821

    
3822
    if (!port)
3823
        return -1;
3824

    
3825
    dev = port->dev;
3826
    *lastp = port->next;
3827
    usb_attach(port, NULL);
3828
    dev->handle_destroy(dev);
3829
    port->next = free_usb_ports;
3830
    free_usb_ports = port;
3831
    return 0;
3832
}
3833

    
3834
void do_usb_add(const char *devname)
3835
{
3836
    int ret;
3837
    ret = usb_device_add(devname);
3838
    if (ret < 0) 
3839
        term_printf("Could not add USB device '%s'\n", devname);
3840
}
3841

    
3842
void do_usb_del(const char *devname)
3843
{
3844
    int ret;
3845
    ret = usb_device_del(devname);
3846
    if (ret < 0) 
3847
        term_printf("Could not remove USB device '%s'\n", devname);
3848
}
3849

    
3850
void usb_info(void)
3851
{
3852
    USBDevice *dev;
3853
    USBPort *port;
3854
    const char *speed_str;
3855

    
3856
    if (!usb_enabled) {
3857
        term_printf("USB support not enabled\n");
3858
        return;
3859
    }
3860

    
3861
    for (port = used_usb_ports; port; port = port->next) {
3862
        dev = port->dev;
3863
        if (!dev)
3864
            continue;
3865
        switch(dev->speed) {
3866
        case USB_SPEED_LOW: 
3867
            speed_str = "1.5"; 
3868
            break;
3869
        case USB_SPEED_FULL: 
3870
            speed_str = "12"; 
3871
            break;
3872
        case USB_SPEED_HIGH: 
3873
            speed_str = "480"; 
3874
            break;
3875
        default:
3876
            speed_str = "?"; 
3877
            break;
3878
        }
3879
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
3880
                    0, dev->addr, speed_str, dev->devname);
3881
    }
3882
}
3883

    
3884
/***********************************************************/
3885
/* pid file */
3886

    
3887
static char *pid_filename;
3888

    
3889
/* Remove PID file. Called on normal exit */
3890

    
3891
static void remove_pidfile(void) 
3892
{
3893
    unlink (pid_filename);
3894
}
3895

    
3896
static void create_pidfile(const char *filename)
3897
{
3898
    struct stat pidstat;
3899
    FILE *f;
3900

    
3901
    /* Try to write our PID to the named file */
3902
    if (stat(filename, &pidstat) < 0) {
3903
        if (errno == ENOENT) {
3904
            if ((f = fopen (filename, "w")) == NULL) {
3905
                perror("Opening pidfile");
3906
                exit(1);
3907
            }
3908
            fprintf(f, "%d\n", getpid());
3909
            fclose(f);
3910
            pid_filename = qemu_strdup(filename);
3911
            if (!pid_filename) {
3912
                fprintf(stderr, "Could not save PID filename");
3913
                exit(1);
3914
            }
3915
            atexit(remove_pidfile);
3916
        }
3917
    } else {
3918
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
3919
                filename);
3920
        exit(1);
3921
    }
3922
}
3923

    
3924
/***********************************************************/
3925
/* dumb display */
3926

    
3927
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3928
{
3929
}
3930

    
3931
static void dumb_resize(DisplayState *ds, int w, int h)
3932
{
3933
}
3934

    
3935
static void dumb_refresh(DisplayState *ds)
3936
{
3937
    vga_hw_update();
3938
}
3939

    
3940
void dumb_display_init(DisplayState *ds)
3941
{
3942
    ds->data = NULL;
3943
    ds->linesize = 0;
3944
    ds->depth = 0;
3945
    ds->dpy_update = dumb_update;
3946
    ds->dpy_resize = dumb_resize;
3947
    ds->dpy_refresh = dumb_refresh;
3948
}
3949

    
3950
/***********************************************************/
3951
/* I/O handling */
3952

    
3953
#define MAX_IO_HANDLERS 64
3954

    
3955
typedef struct IOHandlerRecord {
3956
    int fd;
3957
    IOCanRWHandler *fd_read_poll;
3958
    IOHandler *fd_read;
3959
    IOHandler *fd_write;
3960
    void *opaque;
3961
    /* temporary data */
3962
    struct pollfd *ufd;
3963
    struct IOHandlerRecord *next;
3964
} IOHandlerRecord;
3965

    
3966
static IOHandlerRecord *first_io_handler;
3967

    
3968
/* XXX: fd_read_poll should be suppressed, but an API change is
3969
   necessary in the character devices to suppress fd_can_read(). */
3970
int qemu_set_fd_handler2(int fd, 
3971
                         IOCanRWHandler *fd_read_poll, 
3972
                         IOHandler *fd_read, 
3973
                         IOHandler *fd_write, 
3974
                         void *opaque)
3975
{
3976
    IOHandlerRecord **pioh, *ioh;
3977

    
3978
    if (!fd_read && !fd_write) {
3979
        pioh = &first_io_handler;
3980
        for(;;) {
3981
            ioh = *pioh;
3982
            if (ioh == NULL)
3983
                break;
3984
            if (ioh->fd == fd) {
3985
                *pioh = ioh->next;
3986
                qemu_free(ioh);
3987
                break;
3988
            }
3989
            pioh = &ioh->next;
3990
        }
3991
    } else {
3992
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3993
            if (ioh->fd == fd)
3994
                goto found;
3995
        }
3996
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3997
        if (!ioh)
3998
            return -1;
3999
        ioh->next = first_io_handler;
4000
        first_io_handler = ioh;
4001
    found:
4002
        ioh->fd = fd;
4003
        ioh->fd_read_poll = fd_read_poll;
4004
        ioh->fd_read = fd_read;
4005
        ioh->fd_write = fd_write;
4006
        ioh->opaque = opaque;
4007
    }
4008
    return 0;
4009
}
4010

    
4011
int qemu_set_fd_handler(int fd, 
4012
                        IOHandler *fd_read, 
4013
                        IOHandler *fd_write, 
4014
                        void *opaque)
4015
{
4016
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4017
}
4018

    
4019
/***********************************************************/
4020
/* Polling handling */
4021

    
4022
typedef struct PollingEntry {
4023
    PollingFunc *func;
4024
    void *opaque;
4025
    struct PollingEntry *next;
4026
} PollingEntry;
4027

    
4028
static PollingEntry *first_polling_entry;
4029

    
4030
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4031
{
4032
    PollingEntry **ppe, *pe;
4033
    pe = qemu_mallocz(sizeof(PollingEntry));
4034
    if (!pe)
4035
        return -1;
4036
    pe->func = func;
4037
    pe->opaque = opaque;
4038
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4039
    *ppe = pe;
4040
    return 0;
4041
}
4042

    
4043
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4044
{
4045
    PollingEntry **ppe, *pe;
4046
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4047
        pe = *ppe;
4048
        if (pe->func == func && pe->opaque == opaque) {
4049
            *ppe = pe->next;
4050
            qemu_free(pe);
4051
            break;
4052
        }
4053
    }
4054
}
4055

    
4056
#ifdef _WIN32
4057
/***********************************************************/
4058
/* Wait objects support */
4059
typedef struct WaitObjects {
4060
    int num;
4061
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4062
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4063
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4064
} WaitObjects;
4065

    
4066
static WaitObjects wait_objects = {0};
4067
    
4068
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4069
{
4070
    WaitObjects *w = &wait_objects;
4071

    
4072
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4073
        return -1;
4074
    w->events[w->num] = handle;
4075
    w->func[w->num] = func;
4076
    w->opaque[w->num] = opaque;
4077
    w->num++;
4078
    return 0;
4079
}
4080

    
4081
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4082
{
4083
    int i, found;
4084
    WaitObjects *w = &wait_objects;
4085

    
4086
    found = 0;
4087
    for (i = 0; i < w->num; i++) {
4088
        if (w->events[i] == handle)
4089
            found = 1;
4090
        if (found) {
4091
            w->events[i] = w->events[i + 1];
4092
            w->func[i] = w->func[i + 1];
4093
            w->opaque[i] = w->opaque[i + 1];
4094
        }            
4095
    }
4096
    if (found)
4097
        w->num--;
4098
}
4099
#endif
4100

    
4101
/***********************************************************/
4102
/* savevm/loadvm support */
4103

    
4104
#define IO_BUF_SIZE 32768
4105

    
4106
struct QEMUFile {
4107
    FILE *outfile;
4108
    BlockDriverState *bs;
4109
    int is_file;
4110
    int is_writable;
4111
    int64_t base_offset;
4112
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4113
                           when reading */
4114
    int buf_index;
4115
    int buf_size; /* 0 when writing */
4116
    uint8_t buf[IO_BUF_SIZE];
4117
};
4118

    
4119
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4120
{
4121
    QEMUFile *f;
4122

    
4123
    f = qemu_mallocz(sizeof(QEMUFile));
4124
    if (!f)
4125
        return NULL;
4126
    if (!strcmp(mode, "wb")) {
4127
        f->is_writable = 1;
4128
    } else if (!strcmp(mode, "rb")) {
4129
        f->is_writable = 0;
4130
    } else {
4131
        goto fail;
4132
    }
4133
    f->outfile = fopen(filename, mode);
4134
    if (!f->outfile)
4135
        goto fail;
4136
    f->is_file = 1;
4137
    return f;
4138
 fail:
4139
    if (f->outfile)
4140
        fclose(f->outfile);
4141
    qemu_free(f);
4142
    return NULL;
4143
}
4144

    
4145
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4146
{
4147
    QEMUFile *f;
4148

    
4149
    f = qemu_mallocz(sizeof(QEMUFile));
4150
    if (!f)
4151
        return NULL;
4152
    f->is_file = 0;
4153
    f->bs = bs;
4154
    f->is_writable = is_writable;
4155
    f->base_offset = offset;
4156
    return f;
4157
}
4158

    
4159
void qemu_fflush(QEMUFile *f)
4160
{
4161
    if (!f->is_writable)
4162
        return;
4163
    if (f->buf_index > 0) {
4164
        if (f->is_file) {
4165
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4166
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4167
        } else {
4168
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4169
                        f->buf, f->buf_index);
4170
        }
4171
        f->buf_offset += f->buf_index;
4172
        f->buf_index = 0;
4173
    }
4174
}
4175

    
4176
static void qemu_fill_buffer(QEMUFile *f)
4177
{
4178
    int len;
4179

    
4180
    if (f->is_writable)
4181
        return;
4182
    if (f->is_file) {
4183
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4184
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4185
        if (len < 0)
4186
            len = 0;
4187
    } else {
4188
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4189
                         f->buf, IO_BUF_SIZE);
4190
        if (len < 0)
4191
            len = 0;
4192
    }
4193
    f->buf_index = 0;
4194
    f->buf_size = len;
4195
    f->buf_offset += len;
4196
}
4197

    
4198
void qemu_fclose(QEMUFile *f)
4199
{
4200
    if (f->is_writable)
4201
        qemu_fflush(f);
4202
    if (f->is_file) {
4203
        fclose(f->outfile);
4204
    }
4205
    qemu_free(f);
4206
}
4207

    
4208
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4209
{
4210
    int l;
4211
    while (size > 0) {
4212
        l = IO_BUF_SIZE - f->buf_index;
4213
        if (l > size)
4214
            l = size;
4215
        memcpy(f->buf + f->buf_index, buf, l);
4216
        f->buf_index += l;
4217
        buf += l;
4218
        size -= l;
4219
        if (f->buf_index >= IO_BUF_SIZE)
4220
            qemu_fflush(f);
4221
    }
4222
}
4223

    
4224
void qemu_put_byte(QEMUFile *f, int v)
4225
{
4226
    f->buf[f->buf_index++] = v;
4227
    if (f->buf_index >= IO_BUF_SIZE)
4228
        qemu_fflush(f);
4229
}
4230

    
4231
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4232
{
4233
    int size, l;
4234

    
4235
    size = size1;
4236
    while (size > 0) {
4237
        l = f->buf_size - f->buf_index;
4238
        if (l == 0) {
4239
            qemu_fill_buffer(f);
4240
            l = f->buf_size - f->buf_index;
4241
            if (l == 0)
4242
                break;
4243
        }
4244
        if (l > size)
4245
            l = size;
4246
        memcpy(buf, f->buf + f->buf_index, l);
4247
        f->buf_index += l;
4248
        buf += l;
4249
        size -= l;
4250
    }
4251
    return size1 - size;
4252
}
4253

    
4254
int qemu_get_byte(QEMUFile *f)
4255
{
4256
    if (f->buf_index >= f->buf_size) {
4257
        qemu_fill_buffer(f);
4258
        if (f->buf_index >= f->buf_size)
4259
            return 0;
4260
    }
4261
    return f->buf[f->buf_index++];
4262
}
4263

    
4264
int64_t qemu_ftell(QEMUFile *f)
4265
{
4266
    return f->buf_offset - f->buf_size + f->buf_index;
4267
}
4268

    
4269
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4270
{
4271
    if (whence == SEEK_SET) {
4272
        /* nothing to do */
4273
    } else if (whence == SEEK_CUR) {
4274
        pos += qemu_ftell(f);
4275
    } else {
4276
        /* SEEK_END not supported */
4277
        return -1;
4278
    }
4279
    if (f->is_writable) {
4280
        qemu_fflush(f);
4281
        f->buf_offset = pos;
4282
    } else {
4283
        f->buf_offset = pos;
4284
        f->buf_index = 0;
4285
        f->buf_size = 0;
4286
    }
4287
    return pos;
4288
}
4289

    
4290
void qemu_put_be16(QEMUFile *f, unsigned int v)
4291
{
4292
    qemu_put_byte(f, v >> 8);
4293
    qemu_put_byte(f, v);
4294
}
4295

    
4296
void qemu_put_be32(QEMUFile *f, unsigned int v)
4297
{
4298
    qemu_put_byte(f, v >> 24);
4299
    qemu_put_byte(f, v >> 16);
4300
    qemu_put_byte(f, v >> 8);
4301
    qemu_put_byte(f, v);
4302
}
4303

    
4304
void qemu_put_be64(QEMUFile *f, uint64_t v)
4305
{
4306
    qemu_put_be32(f, v >> 32);
4307
    qemu_put_be32(f, v);
4308
}
4309

    
4310
unsigned int qemu_get_be16(QEMUFile *f)
4311
{
4312
    unsigned int v;
4313
    v = qemu_get_byte(f) << 8;
4314
    v |= qemu_get_byte(f);
4315
    return v;
4316
}
4317

    
4318
unsigned int qemu_get_be32(QEMUFile *f)
4319
{
4320
    unsigned int v;
4321
    v = qemu_get_byte(f) << 24;
4322
    v |= qemu_get_byte(f) << 16;
4323
    v |= qemu_get_byte(f) << 8;
4324
    v |= qemu_get_byte(f);
4325
    return v;
4326
}
4327

    
4328
uint64_t qemu_get_be64(QEMUFile *f)
4329
{
4330
    uint64_t v;
4331
    v = (uint64_t)qemu_get_be32(f) << 32;
4332
    v |= qemu_get_be32(f);
4333
    return v;
4334
}
4335

    
4336
typedef struct SaveStateEntry {
4337
    char idstr[256];
4338
    int instance_id;
4339
    int version_id;
4340
    SaveStateHandler *save_state;
4341
    LoadStateHandler *load_state;
4342
    void *opaque;
4343
    struct SaveStateEntry *next;
4344
} SaveStateEntry;
4345

    
4346
static SaveStateEntry *first_se;
4347

    
4348
int register_savevm(const char *idstr, 
4349
                    int instance_id, 
4350
                    int version_id,
4351
                    SaveStateHandler *save_state,
4352
                    LoadStateHandler *load_state,
4353
                    void *opaque)
4354
{
4355
    SaveStateEntry *se, **pse;
4356

    
4357
    se = qemu_malloc(sizeof(SaveStateEntry));
4358
    if (!se)
4359
        return -1;
4360
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4361
    se->instance_id = instance_id;
4362
    se->version_id = version_id;
4363
    se->save_state = save_state;
4364
    se->load_state = load_state;
4365
    se->opaque = opaque;
4366
    se->next = NULL;
4367

    
4368
    /* add at the end of list */
4369
    pse = &first_se;
4370
    while (*pse != NULL)
4371
        pse = &(*pse)->next;
4372
    *pse = se;
4373
    return 0;
4374
}
4375

    
4376
#define QEMU_VM_FILE_MAGIC   0x5145564d
4377
#define QEMU_VM_FILE_VERSION 0x00000002
4378

    
4379
int qemu_savevm_state(QEMUFile *f)
4380
{
4381
    SaveStateEntry *se;
4382
    int len, ret;
4383
    int64_t cur_pos, len_pos, total_len_pos;
4384

    
4385
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4386
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4387
    total_len_pos = qemu_ftell(f);
4388
    qemu_put_be64(f, 0); /* total size */
4389

    
4390
    for(se = first_se; se != NULL; se = se->next) {
4391
        /* ID string */
4392
        len = strlen(se->idstr);
4393
        qemu_put_byte(f, len);
4394
        qemu_put_buffer(f, se->idstr, len);
4395

    
4396
        qemu_put_be32(f, se->instance_id);
4397
        qemu_put_be32(f, se->version_id);
4398

    
4399
        /* record size: filled later */
4400
        len_pos = qemu_ftell(f);
4401
        qemu_put_be32(f, 0);
4402
        
4403
        se->save_state(f, se->opaque);
4404

    
4405
        /* fill record size */
4406
        cur_pos = qemu_ftell(f);
4407
        len = cur_pos - len_pos - 4;
4408
        qemu_fseek(f, len_pos, SEEK_SET);
4409
        qemu_put_be32(f, len);
4410
        qemu_fseek(f, cur_pos, SEEK_SET);
4411
    }
4412
    cur_pos = qemu_ftell(f);
4413
    qemu_fseek(f, total_len_pos, SEEK_SET);
4414
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4415
    qemu_fseek(f, cur_pos, SEEK_SET);
4416

    
4417
    ret = 0;
4418
    return ret;
4419
}
4420

    
4421
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4422
{
4423
    SaveStateEntry *se;
4424

    
4425
    for(se = first_se; se != NULL; se = se->next) {
4426
        if (!strcmp(se->idstr, idstr) && 
4427
            instance_id == se->instance_id)
4428
            return se;
4429
    }
4430
    return NULL;
4431
}
4432

    
4433
int qemu_loadvm_state(QEMUFile *f)
4434
{
4435
    SaveStateEntry *se;
4436
    int len, ret, instance_id, record_len, version_id;
4437
    int64_t total_len, end_pos, cur_pos;
4438
    unsigned int v;
4439
    char idstr[256];
4440
    
4441
    v = qemu_get_be32(f);
4442
    if (v != QEMU_VM_FILE_MAGIC)
4443
        goto fail;
4444
    v = qemu_get_be32(f);
4445
    if (v != QEMU_VM_FILE_VERSION) {
4446
    fail:
4447
        ret = -1;
4448
        goto the_end;
4449
    }
4450
    total_len = qemu_get_be64(f);
4451
    end_pos = total_len + qemu_ftell(f);
4452
    for(;;) {
4453
        if (qemu_ftell(f) >= end_pos)
4454
            break;
4455
        len = qemu_get_byte(f);
4456
        qemu_get_buffer(f, idstr, len);
4457
        idstr[len] = '\0';
4458
        instance_id = qemu_get_be32(f);
4459
        version_id = qemu_get_be32(f);
4460
        record_len = qemu_get_be32(f);
4461
#if 0
4462
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4463
               idstr, instance_id, version_id, record_len);
4464
#endif
4465
        cur_pos = qemu_ftell(f);
4466
        se = find_se(idstr, instance_id);
4467
        if (!se) {
4468
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4469
                    instance_id, idstr);
4470
        } else {
4471
            ret = se->load_state(f, se->opaque, version_id);
4472
            if (ret < 0) {
4473
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4474
                        instance_id, idstr);
4475
            }
4476
        }
4477
        /* always seek to exact end of record */
4478
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4479
    }
4480
    ret = 0;
4481
 the_end:
4482
    return ret;
4483
}
4484

    
4485
/* device can contain snapshots */
4486
static int bdrv_can_snapshot(BlockDriverState *bs)
4487
{
4488
    return (bs &&
4489
            !bdrv_is_removable(bs) &&
4490
            !bdrv_is_read_only(bs));
4491
}
4492

    
4493
/* device must be snapshots in order to have a reliable snapshot */
4494
static int bdrv_has_snapshot(BlockDriverState *bs)
4495
{
4496
    return (bs &&
4497
            !bdrv_is_removable(bs) &&
4498
            !bdrv_is_read_only(bs));
4499
}
4500

    
4501
static BlockDriverState *get_bs_snapshots(void)
4502
{
4503
    BlockDriverState *bs;
4504
    int i;
4505

    
4506
    if (bs_snapshots)
4507
        return bs_snapshots;
4508
    for(i = 0; i <= MAX_DISKS; i++) {
4509
        bs = bs_table[i];
4510
        if (bdrv_can_snapshot(bs))
4511
            goto ok;
4512
    }
4513
    return NULL;
4514
 ok:
4515
    bs_snapshots = bs;
4516
    return bs;
4517
}
4518

    
4519
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4520
                              const char *name)
4521
{
4522
    QEMUSnapshotInfo *sn_tab, *sn;
4523
    int nb_sns, i, ret;
4524
    
4525
    ret = -ENOENT;
4526
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4527
    if (nb_sns < 0)
4528
        return ret;
4529
    for(i = 0; i < nb_sns; i++) {
4530
        sn = &sn_tab[i];
4531
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4532
            *sn_info = *sn;
4533
            ret = 0;
4534
            break;
4535
        }
4536
    }
4537
    qemu_free(sn_tab);
4538
    return ret;
4539
}
4540

    
4541
void do_savevm(const char *name)
4542
{
4543
    BlockDriverState *bs, *bs1;
4544
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4545
    int must_delete, ret, i;
4546
    BlockDriverInfo bdi1, *bdi = &bdi1;
4547
    QEMUFile *f;
4548
    int saved_vm_running;
4549
#ifdef _WIN32
4550
    struct _timeb tb;
4551
#else
4552
    struct timeval tv;
4553
#endif
4554

    
4555
    bs = get_bs_snapshots();
4556
    if (!bs) {
4557
        term_printf("No block device can accept snapshots\n");
4558
        return;
4559
    }
4560

    
4561
    /* ??? Should this occur after vm_stop?  */
4562
    qemu_aio_flush();
4563

    
4564
    saved_vm_running = vm_running;
4565
    vm_stop(0);
4566
    
4567
    must_delete = 0;
4568
    if (name) {
4569
        ret = bdrv_snapshot_find(bs, old_sn, name);
4570
        if (ret >= 0) {
4571
            must_delete = 1;
4572
        }
4573
    }
4574
    memset(sn, 0, sizeof(*sn));
4575
    if (must_delete) {
4576
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4577
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4578
    } else {
4579
        if (name)
4580
            pstrcpy(sn->name, sizeof(sn->name), name);
4581
    }
4582

    
4583
    /* fill auxiliary fields */
4584
#ifdef _WIN32
4585
    _ftime(&tb);
4586
    sn->date_sec = tb.time;
4587
    sn->date_nsec = tb.millitm * 1000000;
4588
#else
4589
    gettimeofday(&tv, NULL);
4590
    sn->date_sec = tv.tv_sec;
4591
    sn->date_nsec = tv.tv_usec * 1000;
4592
#endif
4593
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4594
    
4595
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4596
        term_printf("Device %s does not support VM state snapshots\n",
4597
                    bdrv_get_device_name(bs));
4598
        goto the_end;
4599
    }
4600
    
4601
    /* save the VM state */
4602
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4603
    if (!f) {
4604
        term_printf("Could not open VM state file\n");
4605
        goto the_end;
4606
    }
4607
    ret = qemu_savevm_state(f);
4608
    sn->vm_state_size = qemu_ftell(f);
4609
    qemu_fclose(f);
4610
    if (ret < 0) {
4611
        term_printf("Error %d while writing VM\n", ret);
4612
        goto the_end;
4613
    }
4614
    
4615
    /* create the snapshots */
4616

    
4617
    for(i = 0; i < MAX_DISKS; i++) {
4618
        bs1 = bs_table[i];
4619
        if (bdrv_has_snapshot(bs1)) {
4620
            if (must_delete) {
4621
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4622
                if (ret < 0) {
4623
                    term_printf("Error while deleting snapshot on '%s'\n",
4624
                                bdrv_get_device_name(bs1));
4625
                }
4626
            }
4627
            ret = bdrv_snapshot_create(bs1, sn);
4628
            if (ret < 0) {
4629
                term_printf("Error while creating snapshot on '%s'\n",
4630
                            bdrv_get_device_name(bs1));
4631
            }
4632
        }
4633
    }
4634

    
4635
 the_end:
4636
    if (saved_vm_running)
4637
        vm_start();
4638
}
4639

    
4640
void do_loadvm(const char *name)
4641
{
4642
    BlockDriverState *bs, *bs1;
4643
    BlockDriverInfo bdi1, *bdi = &bdi1;
4644
    QEMUFile *f;
4645
    int i, ret;
4646
    int saved_vm_running;
4647

    
4648
    bs = get_bs_snapshots();
4649
    if (!bs) {
4650
        term_printf("No block device supports snapshots\n");
4651
        return;
4652
    }
4653
    
4654
    /* Flush all IO requests so they don't interfere with the new state.  */
4655
    qemu_aio_flush();
4656

    
4657
    saved_vm_running = vm_running;
4658
    vm_stop(0);
4659

    
4660
    for(i = 0; i <= MAX_DISKS; i++) {
4661
        bs1 = bs_table[i];
4662
        if (bdrv_has_snapshot(bs1)) {
4663
            ret = bdrv_snapshot_goto(bs1, name);
4664
            if (ret < 0) {
4665
                if (bs != bs1)
4666
                    term_printf("Warning: ");
4667
                switch(ret) {
4668
                case -ENOTSUP:
4669
                    term_printf("Snapshots not supported on device '%s'\n",
4670
                                bdrv_get_device_name(bs1));
4671
                    break;
4672
                case -ENOENT:
4673
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
4674
                                name, bdrv_get_device_name(bs1));
4675
                    break;
4676
                default:
4677
                    term_printf("Error %d while activating snapshot on '%s'\n",
4678
                                ret, bdrv_get_device_name(bs1));
4679
                    break;
4680
                }
4681
                /* fatal on snapshot block device */
4682
                if (bs == bs1)
4683
                    goto the_end;
4684
            }
4685
        }
4686
    }
4687

    
4688
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4689
        term_printf("Device %s does not support VM state snapshots\n",
4690
                    bdrv_get_device_name(bs));
4691
        return;
4692
    }
4693
    
4694
    /* restore the VM state */
4695
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4696
    if (!f) {
4697
        term_printf("Could not open VM state file\n");
4698
        goto the_end;
4699
    }
4700
    ret = qemu_loadvm_state(f);
4701
    qemu_fclose(f);
4702
    if (ret < 0) {
4703
        term_printf("Error %d while loading VM state\n", ret);
4704
    }
4705
 the_end:
4706
    if (saved_vm_running)
4707
        vm_start();
4708
}
4709

    
4710
void do_delvm(const char *name)
4711
{
4712
    BlockDriverState *bs, *bs1;
4713
    int i, ret;
4714

    
4715
    bs = get_bs_snapshots();
4716
    if (!bs) {
4717
        term_printf("No block device supports snapshots\n");
4718
        return;
4719
    }
4720
    
4721
    for(i = 0; i <= MAX_DISKS; i++) {
4722
        bs1 = bs_table[i];
4723
        if (bdrv_has_snapshot(bs1)) {
4724
            ret = bdrv_snapshot_delete(bs1, name);
4725
            if (ret < 0) {
4726
                if (ret == -ENOTSUP)
4727
                    term_printf("Snapshots not supported on device '%s'\n",
4728
                                bdrv_get_device_name(bs1));
4729
                else
4730
                    term_printf("Error %d while deleting snapshot on '%s'\n",
4731
                                ret, bdrv_get_device_name(bs1));
4732
            }
4733
        }
4734
    }
4735
}
4736

    
4737
void do_info_snapshots(void)
4738
{
4739
    BlockDriverState *bs, *bs1;
4740
    QEMUSnapshotInfo *sn_tab, *sn;
4741
    int nb_sns, i;
4742
    char buf[256];
4743

    
4744
    bs = get_bs_snapshots();
4745
    if (!bs) {
4746
        term_printf("No available block device supports snapshots\n");
4747
        return;
4748
    }
4749
    term_printf("Snapshot devices:");
4750
    for(i = 0; i <= MAX_DISKS; i++) {
4751
        bs1 = bs_table[i];
4752
        if (bdrv_has_snapshot(bs1)) {
4753
            if (bs == bs1)
4754
                term_printf(" %s", bdrv_get_device_name(bs1));
4755
        }
4756
    }
4757
    term_printf("\n");
4758

    
4759
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4760
    if (nb_sns < 0) {
4761
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4762
        return;
4763
    }
4764
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4765
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4766
    for(i = 0; i < nb_sns; i++) {
4767
        sn = &sn_tab[i];
4768
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4769
    }
4770
    qemu_free(sn_tab);
4771
}
4772

    
4773
/***********************************************************/
4774
/* cpu save/restore */
4775

    
4776
#if defined(TARGET_I386)
4777

    
4778
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4779
{
4780
    qemu_put_be32(f, dt->selector);
4781
    qemu_put_betl(f, dt->base);
4782
    qemu_put_be32(f, dt->limit);
4783
    qemu_put_be32(f, dt->flags);
4784
}
4785

    
4786
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4787
{
4788
    dt->selector = qemu_get_be32(f);
4789
    dt->base = qemu_get_betl(f);
4790
    dt->limit = qemu_get_be32(f);
4791
    dt->flags = qemu_get_be32(f);
4792
}
4793

    
4794
void cpu_save(QEMUFile *f, void *opaque)
4795
{
4796
    CPUState *env = opaque;
4797
    uint16_t fptag, fpus, fpuc, fpregs_format;
4798
    uint32_t hflags;
4799
    int i;
4800
    
4801
    for(i = 0; i < CPU_NB_REGS; i++)
4802
        qemu_put_betls(f, &env->regs[i]);
4803
    qemu_put_betls(f, &env->eip);
4804
    qemu_put_betls(f, &env->eflags);
4805
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4806
    qemu_put_be32s(f, &hflags);
4807
    
4808
    /* FPU */
4809
    fpuc = env->fpuc;
4810
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4811
    fptag = 0;
4812
    for(i = 0; i < 8; i++) {
4813
        fptag |= ((!env->fptags[i]) << i);
4814
    }
4815
    
4816
    qemu_put_be16s(f, &fpuc);
4817
    qemu_put_be16s(f, &fpus);
4818
    qemu_put_be16s(f, &fptag);
4819

    
4820
#ifdef USE_X86LDOUBLE
4821
    fpregs_format = 0;
4822
#else
4823
    fpregs_format = 1;
4824
#endif
4825
    qemu_put_be16s(f, &fpregs_format);
4826
    
4827
    for(i = 0; i < 8; i++) {
4828
#ifdef USE_X86LDOUBLE
4829
        {
4830
            uint64_t mant;
4831
            uint16_t exp;
4832
            /* we save the real CPU data (in case of MMX usage only 'mant'
4833
               contains the MMX register */
4834
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4835
            qemu_put_be64(f, mant);
4836
            qemu_put_be16(f, exp);
4837
        }
4838
#else
4839
        /* if we use doubles for float emulation, we save the doubles to
4840
           avoid losing information in case of MMX usage. It can give
4841
           problems if the image is restored on a CPU where long
4842
           doubles are used instead. */
4843
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4844
#endif
4845
    }
4846

    
4847
    for(i = 0; i < 6; i++)
4848
        cpu_put_seg(f, &env->segs[i]);
4849
    cpu_put_seg(f, &env->ldt);
4850
    cpu_put_seg(f, &env->tr);
4851
    cpu_put_seg(f, &env->gdt);
4852
    cpu_put_seg(f, &env->idt);
4853
    
4854
    qemu_put_be32s(f, &env->sysenter_cs);
4855
    qemu_put_be32s(f, &env->sysenter_esp);
4856
    qemu_put_be32s(f, &env->sysenter_eip);
4857
    
4858
    qemu_put_betls(f, &env->cr[0]);
4859
    qemu_put_betls(f, &env->cr[2]);
4860
    qemu_put_betls(f, &env->cr[3]);
4861
    qemu_put_betls(f, &env->cr[4]);
4862
    
4863
    for(i = 0; i < 8; i++)
4864
        qemu_put_betls(f, &env->dr[i]);
4865

    
4866
    /* MMU */
4867
    qemu_put_be32s(f, &env->a20_mask);
4868

    
4869
    /* XMM */
4870
    qemu_put_be32s(f, &env->mxcsr);
4871
    for(i = 0; i < CPU_NB_REGS; i++) {
4872
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4873
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4874
    }
4875

    
4876
#ifdef TARGET_X86_64
4877
    qemu_put_be64s(f, &env->efer);
4878
    qemu_put_be64s(f, &env->star);
4879
    qemu_put_be64s(f, &env->lstar);
4880
    qemu_put_be64s(f, &env->cstar);
4881
    qemu_put_be64s(f, &env->fmask);
4882
    qemu_put_be64s(f, &env->kernelgsbase);
4883
#endif
4884
    qemu_put_be32s(f, &env->smbase);
4885
}
4886

    
4887
#ifdef USE_X86LDOUBLE
4888
/* XXX: add that in a FPU generic layer */
4889
union x86_longdouble {
4890
    uint64_t mant;
4891
    uint16_t exp;
4892
};
4893

    
4894
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
4895
#define EXPBIAS1 1023
4896
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
4897
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
4898

    
4899
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4900
{
4901
    int e;
4902
    /* mantissa */
4903
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4904
    /* exponent + sign */
4905
    e = EXPD1(temp) - EXPBIAS1 + 16383;
4906
    e |= SIGND1(temp) >> 16;
4907
    p->exp = e;
4908
}
4909
#endif
4910

    
4911
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4912
{
4913
    CPUState *env = opaque;
4914
    int i, guess_mmx;
4915
    uint32_t hflags;
4916
    uint16_t fpus, fpuc, fptag, fpregs_format;
4917

    
4918
    if (version_id != 3 && version_id != 4)
4919
        return -EINVAL;
4920
    for(i = 0; i < CPU_NB_REGS; i++)
4921
        qemu_get_betls(f, &env->regs[i]);
4922
    qemu_get_betls(f, &env->eip);
4923
    qemu_get_betls(f, &env->eflags);
4924
    qemu_get_be32s(f, &hflags);
4925

    
4926
    qemu_get_be16s(f, &fpuc);
4927
    qemu_get_be16s(f, &fpus);
4928
    qemu_get_be16s(f, &fptag);
4929
    qemu_get_be16s(f, &fpregs_format);
4930
    
4931
    /* NOTE: we cannot always restore the FPU state if the image come
4932
       from a host with a different 'USE_X86LDOUBLE' define. We guess
4933
       if we are in an MMX state to restore correctly in that case. */
4934
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4935
    for(i = 0; i < 8; i++) {
4936
        uint64_t mant;
4937
        uint16_t exp;
4938
        
4939
        switch(fpregs_format) {
4940
        case 0:
4941
            mant = qemu_get_be64(f);
4942
            exp = qemu_get_be16(f);
4943
#ifdef USE_X86LDOUBLE
4944
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
4945
#else
4946
            /* difficult case */
4947
            if (guess_mmx)
4948
                env->fpregs[i].mmx.MMX_Q(0) = mant;
4949
            else
4950
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
4951
#endif
4952
            break;
4953
        case 1:
4954
            mant = qemu_get_be64(f);
4955
#ifdef USE_X86LDOUBLE
4956
            {
4957
                union x86_longdouble *p;
4958
                /* difficult case */
4959
                p = (void *)&env->fpregs[i];
4960
                if (guess_mmx) {
4961
                    p->mant = mant;
4962
                    p->exp = 0xffff;
4963
                } else {
4964
                    fp64_to_fp80(p, mant);
4965
                }
4966
            }
4967
#else
4968
            env->fpregs[i].mmx.MMX_Q(0) = mant;
4969
#endif            
4970
            break;
4971
        default:
4972
            return -EINVAL;
4973
        }
4974
    }
4975

    
4976
    env->fpuc = fpuc;
4977
    /* XXX: restore FPU round state */
4978
    env->fpstt = (fpus >> 11) & 7;
4979
    env->fpus = fpus & ~0x3800;
4980
    fptag ^= 0xff;
4981
    for(i = 0; i < 8; i++) {
4982
        env->fptags[i] = (fptag >> i) & 1;
4983
    }
4984
    
4985
    for(i = 0; i < 6; i++)
4986
        cpu_get_seg(f, &env->segs[i]);
4987
    cpu_get_seg(f, &env->ldt);
4988
    cpu_get_seg(f, &env->tr);
4989
    cpu_get_seg(f, &env->gdt);
4990
    cpu_get_seg(f, &env->idt);
4991
    
4992
    qemu_get_be32s(f, &env->sysenter_cs);
4993
    qemu_get_be32s(f, &env->sysenter_esp);
4994
    qemu_get_be32s(f, &env->sysenter_eip);
4995
    
4996
    qemu_get_betls(f, &env->cr[0]);
4997
    qemu_get_betls(f, &env->cr[2]);
4998
    qemu_get_betls(f, &env->cr[3]);
4999
    qemu_get_betls(f, &env->cr[4]);
5000
    
5001
    for(i = 0; i < 8; i++)
5002
        qemu_get_betls(f, &env->dr[i]);
5003

    
5004
    /* MMU */
5005
    qemu_get_be32s(f, &env->a20_mask);
5006

    
5007
    qemu_get_be32s(f, &env->mxcsr);
5008
    for(i = 0; i < CPU_NB_REGS; i++) {
5009
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5010
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5011
    }
5012

    
5013
#ifdef TARGET_X86_64
5014
    qemu_get_be64s(f, &env->efer);
5015
    qemu_get_be64s(f, &env->star);
5016
    qemu_get_be64s(f, &env->lstar);
5017
    qemu_get_be64s(f, &env->cstar);
5018
    qemu_get_be64s(f, &env->fmask);
5019
    qemu_get_be64s(f, &env->kernelgsbase);
5020
#endif
5021
    if (version_id >= 4) 
5022
        qemu_get_be32s(f, &env->smbase);
5023

    
5024
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5025
    env->hflags = hflags;
5026
    tlb_flush(env, 1);
5027
    return 0;
5028
}
5029

    
5030
#elif defined(TARGET_PPC)
5031
void cpu_save(QEMUFile *f, void *opaque)
5032
{
5033
}
5034

    
5035
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5036
{
5037
    return 0;
5038
}
5039

    
5040
#elif defined(TARGET_MIPS)
5041
void cpu_save(QEMUFile *f, void *opaque)
5042
{
5043
}
5044

    
5045
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5046
{
5047
    return 0;
5048
}
5049

    
5050
#elif defined(TARGET_SPARC)
5051
void cpu_save(QEMUFile *f, void *opaque)
5052
{
5053
    CPUState *env = opaque;
5054
    int i;
5055
    uint32_t tmp;
5056

    
5057
    for(i = 0; i < 8; i++)
5058
        qemu_put_betls(f, &env->gregs[i]);
5059
    for(i = 0; i < NWINDOWS * 16; i++)
5060
        qemu_put_betls(f, &env->regbase[i]);
5061

    
5062
    /* FPU */
5063
    for(i = 0; i < TARGET_FPREGS; i++) {
5064
        union {
5065
            float32 f;
5066
            uint32_t i;
5067
        } u;
5068
        u.f = env->fpr[i];
5069
        qemu_put_be32(f, u.i);
5070
    }
5071

    
5072
    qemu_put_betls(f, &env->pc);
5073
    qemu_put_betls(f, &env->npc);
5074
    qemu_put_betls(f, &env->y);
5075
    tmp = GET_PSR(env);
5076
    qemu_put_be32(f, tmp);
5077
    qemu_put_betls(f, &env->fsr);
5078
    qemu_put_betls(f, &env->tbr);
5079
#ifndef TARGET_SPARC64
5080
    qemu_put_be32s(f, &env->wim);
5081
    /* MMU */
5082
    for(i = 0; i < 16; i++)
5083
        qemu_put_be32s(f, &env->mmuregs[i]);
5084
#endif
5085
}
5086

    
5087
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5088
{
5089
    CPUState *env = opaque;
5090
    int i;
5091
    uint32_t tmp;
5092

    
5093
    for(i = 0; i < 8; i++)
5094
        qemu_get_betls(f, &env->gregs[i]);
5095
    for(i = 0; i < NWINDOWS * 16; i++)
5096
        qemu_get_betls(f, &env->regbase[i]);
5097

    
5098
    /* FPU */
5099
    for(i = 0; i < TARGET_FPREGS; i++) {
5100
        union {
5101
            float32 f;
5102
            uint32_t i;
5103
        } u;
5104
        u.i = qemu_get_be32(f);
5105
        env->fpr[i] = u.f;
5106
    }
5107

    
5108
    qemu_get_betls(f, &env->pc);
5109
    qemu_get_betls(f, &env->npc);
5110
    qemu_get_betls(f, &env->y);
5111
    tmp = qemu_get_be32(f);
5112
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5113
                     correctly updated */
5114
    PUT_PSR(env, tmp);
5115
    qemu_get_betls(f, &env->fsr);
5116
    qemu_get_betls(f, &env->tbr);
5117
#ifndef TARGET_SPARC64
5118
    qemu_get_be32s(f, &env->wim);
5119
    /* MMU */
5120
    for(i = 0; i < 16; i++)
5121
        qemu_get_be32s(f, &env->mmuregs[i]);
5122
#endif
5123
    tlb_flush(env, 1);
5124
    return 0;
5125
}
5126

    
5127
#elif defined(TARGET_ARM)
5128

    
5129
/* ??? Need to implement these.  */
5130
void cpu_save(QEMUFile *f, void *opaque)
5131
{
5132
}
5133

    
5134
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5135
{
5136
    return 0;
5137
}
5138

    
5139
#else
5140

    
5141
#warning No CPU save/restore functions
5142

    
5143
#endif
5144

    
5145
/***********************************************************/
5146
/* ram save/restore */
5147

    
5148
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5149
{
5150
    int v;
5151

    
5152
    v = qemu_get_byte(f);
5153
    switch(v) {
5154
    case 0:
5155
        if (qemu_get_buffer(f, buf, len) != len)
5156
            return -EIO;
5157
        break;
5158
    case 1:
5159
        v = qemu_get_byte(f);
5160
        memset(buf, v, len);
5161
        break;
5162
    default:
5163
        return -EINVAL;
5164
    }
5165
    return 0;
5166
}
5167

    
5168
static int ram_load_v1(QEMUFile *f, void *opaque)
5169
{
5170
    int i, ret;
5171

    
5172
    if (qemu_get_be32(f) != phys_ram_size)
5173
        return -EINVAL;
5174
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5175
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5176
        if (ret)
5177
            return ret;
5178
    }
5179
    return 0;
5180
}
5181

    
5182
#define BDRV_HASH_BLOCK_SIZE 1024
5183
#define IOBUF_SIZE 4096
5184
#define RAM_CBLOCK_MAGIC 0xfabe
5185

    
5186
typedef struct RamCompressState {
5187
    z_stream zstream;
5188
    QEMUFile *f;
5189
    uint8_t buf[IOBUF_SIZE];
5190
} RamCompressState;
5191

    
5192
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5193
{
5194
    int ret;
5195
    memset(s, 0, sizeof(*s));
5196
    s->f = f;
5197
    ret = deflateInit2(&s->zstream, 1,
5198
                       Z_DEFLATED, 15, 
5199
                       9, Z_DEFAULT_STRATEGY);
5200
    if (ret != Z_OK)
5201
        return -1;
5202
    s->zstream.avail_out = IOBUF_SIZE;
5203
    s->zstream.next_out = s->buf;
5204
    return 0;
5205
}
5206

    
5207
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5208
{
5209
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5210
    qemu_put_be16(s->f, len);
5211
    qemu_put_buffer(s->f, buf, len);
5212
}
5213

    
5214
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5215
{
5216
    int ret;
5217

    
5218
    s->zstream.avail_in = len;
5219
    s->zstream.next_in = (uint8_t *)buf;
5220
    while (s->zstream.avail_in > 0) {
5221
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5222
        if (ret != Z_OK)
5223
            return -1;
5224
        if (s->zstream.avail_out == 0) {
5225
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5226
            s->zstream.avail_out = IOBUF_SIZE;
5227
            s->zstream.next_out = s->buf;
5228
        }
5229
    }
5230
    return 0;
5231
}
5232

    
5233
static void ram_compress_close(RamCompressState *s)
5234
{
5235
    int len, ret;
5236

    
5237
    /* compress last bytes */
5238
    for(;;) {
5239
        ret = deflate(&s->zstream, Z_FINISH);
5240
        if (ret == Z_OK || ret == Z_STREAM_END) {
5241
            len = IOBUF_SIZE - s->zstream.avail_out;
5242
            if (len > 0) {
5243
                ram_put_cblock(s, s->buf, len);
5244
            }
5245
            s->zstream.avail_out = IOBUF_SIZE;
5246
            s->zstream.next_out = s->buf;
5247
            if (ret == Z_STREAM_END)
5248
                break;
5249
        } else {
5250
            goto fail;
5251
        }
5252
    }
5253
fail:
5254
    deflateEnd(&s->zstream);
5255
}
5256

    
5257
typedef struct RamDecompressState {
5258
    z_stream zstream;
5259
    QEMUFile *f;
5260
    uint8_t buf[IOBUF_SIZE];
5261
} RamDecompressState;
5262

    
5263
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5264
{
5265
    int ret;
5266
    memset(s, 0, sizeof(*s));
5267
    s->f = f;
5268
    ret = inflateInit(&s->zstream);
5269
    if (ret != Z_OK)
5270
        return -1;
5271
    return 0;
5272
}
5273

    
5274
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5275
{
5276
    int ret, clen;
5277

    
5278
    s->zstream.avail_out = len;
5279
    s->zstream.next_out = buf;
5280
    while (s->zstream.avail_out > 0) {
5281
        if (s->zstream.avail_in == 0) {
5282
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5283
                return -1;
5284
            clen = qemu_get_be16(s->f);
5285
            if (clen > IOBUF_SIZE)
5286
                return -1;
5287
            qemu_get_buffer(s->f, s->buf, clen);
5288
            s->zstream.avail_in = clen;
5289
            s->zstream.next_in = s->buf;
5290
        }
5291
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5292
        if (ret != Z_OK && ret != Z_STREAM_END) {
5293
            return -1;
5294
        }
5295
    }
5296
    return 0;
5297
}
5298

    
5299
static void ram_decompress_close(RamDecompressState *s)
5300
{
5301
    inflateEnd(&s->zstream);
5302
}
5303

    
5304
static void ram_save(QEMUFile *f, void *opaque)
5305
{
5306
    int i;
5307
    RamCompressState s1, *s = &s1;
5308
    uint8_t buf[10];
5309
    
5310
    qemu_put_be32(f, phys_ram_size);
5311
    if (ram_compress_open(s, f) < 0)
5312
        return;
5313
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5314
#if 0
5315
        if (tight_savevm_enabled) {
5316
            int64_t sector_num;
5317
            int j;
5318

5319
            /* find if the memory block is available on a virtual
5320
               block device */
5321
            sector_num = -1;
5322
            for(j = 0; j < MAX_DISKS; j++) {
5323
                if (bs_table[j]) {
5324
                    sector_num = bdrv_hash_find(bs_table[j], 
5325
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5326
                    if (sector_num >= 0)
5327
                        break;
5328
                }
5329
            }
5330
            if (j == MAX_DISKS)
5331
                goto normal_compress;
5332
            buf[0] = 1;
5333
            buf[1] = j;
5334
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5335
            ram_compress_buf(s, buf, 10);
5336
        } else 
5337
#endif
5338
        {
5339
            //        normal_compress:
5340
            buf[0] = 0;
5341
            ram_compress_buf(s, buf, 1);
5342
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5343
        }
5344
    }
5345
    ram_compress_close(s);
5346
}
5347

    
5348
static int ram_load(QEMUFile *f, void *opaque, int version_id)
5349
{
5350
    RamDecompressState s1, *s = &s1;
5351
    uint8_t buf[10];
5352
    int i;
5353

    
5354
    if (version_id == 1)
5355
        return ram_load_v1(f, opaque);
5356
    if (version_id != 2)
5357
        return -EINVAL;
5358
    if (qemu_get_be32(f) != phys_ram_size)
5359
        return -EINVAL;
5360
    if (ram_decompress_open(s, f) < 0)
5361
        return -EINVAL;
5362
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5363
        if (ram_decompress_buf(s, buf, 1) < 0) {
5364
            fprintf(stderr, "Error while reading ram block header\n");
5365
            goto error;
5366
        }
5367
        if (buf[0] == 0) {
5368
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5369
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5370
                goto error;
5371
            }
5372
        } else 
5373
#if 0
5374
        if (buf[0] == 1) {
5375
            int bs_index;
5376
            int64_t sector_num;
5377

5378
            ram_decompress_buf(s, buf + 1, 9);
5379
            bs_index = buf[1];
5380
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5381
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5382
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
5383
                goto error;
5384
            }
5385
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5386
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5387
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5388
                        bs_index, sector_num);
5389
                goto error;
5390
            }
5391
        } else 
5392
#endif
5393
        {
5394
        error:
5395
            printf("Error block header\n");
5396
            return -EINVAL;
5397
        }
5398
    }
5399
    ram_decompress_close(s);
5400
    return 0;
5401
}
5402

    
5403
/***********************************************************/
5404
/* bottom halves (can be seen as timers which expire ASAP) */
5405

    
5406
struct QEMUBH {
5407
    QEMUBHFunc *cb;
5408
    void *opaque;
5409
    int scheduled;
5410
    QEMUBH *next;
5411
};
5412

    
5413
static QEMUBH *first_bh = NULL;
5414

    
5415
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5416
{
5417
    QEMUBH *bh;
5418
    bh = qemu_mallocz(sizeof(QEMUBH));
5419
    if (!bh)
5420
        return NULL;
5421
    bh->cb = cb;
5422
    bh->opaque = opaque;
5423
    return bh;
5424
}
5425

    
5426
int qemu_bh_poll(void)
5427
{
5428
    QEMUBH *bh, **pbh;
5429
    int ret;
5430

    
5431
    ret = 0;
5432
    for(;;) {
5433
        pbh = &first_bh;
5434
        bh = *pbh;
5435
        if (!bh)
5436
            break;
5437
        ret = 1;
5438
        *pbh = bh->next;
5439
        bh->scheduled = 0;
5440
        bh->cb(bh->opaque);
5441
    }
5442
    return ret;
5443
}
5444

    
5445
void qemu_bh_schedule(QEMUBH *bh)
5446
{
5447
    CPUState *env = cpu_single_env;
5448
    if (bh->scheduled)
5449
        return;
5450
    bh->scheduled = 1;
5451
    bh->next = first_bh;
5452
    first_bh = bh;
5453

    
5454
    /* stop the currently executing CPU to execute the BH ASAP */
5455
    if (env) {
5456
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5457
    }
5458
}
5459

    
5460
void qemu_bh_cancel(QEMUBH *bh)
5461
{
5462
    QEMUBH **pbh;
5463
    if (bh->scheduled) {
5464
        pbh = &first_bh;
5465
        while (*pbh != bh)
5466
            pbh = &(*pbh)->next;
5467
        *pbh = bh->next;
5468
        bh->scheduled = 0;
5469
    }
5470
}
5471

    
5472
void qemu_bh_delete(QEMUBH *bh)
5473
{
5474
    qemu_bh_cancel(bh);
5475
    qemu_free(bh);
5476
}
5477

    
5478
/***********************************************************/
5479
/* machine registration */
5480

    
5481
QEMUMachine *first_machine = NULL;
5482

    
5483
int qemu_register_machine(QEMUMachine *m)
5484
{
5485
    QEMUMachine **pm;
5486
    pm = &first_machine;
5487
    while (*pm != NULL)
5488
        pm = &(*pm)->next;
5489
    m->next = NULL;
5490
    *pm = m;
5491
    return 0;
5492
}
5493

    
5494
QEMUMachine *find_machine(const char *name)
5495
{
5496
    QEMUMachine *m;
5497

    
5498
    for(m = first_machine; m != NULL; m = m->next) {
5499
        if (!strcmp(m->name, name))
5500
            return m;
5501
    }
5502
    return NULL;
5503
}
5504

    
5505
/***********************************************************/
5506
/* main execution loop */
5507

    
5508
void gui_update(void *opaque)
5509
{
5510
    display_state.dpy_refresh(&display_state);
5511
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5512
}
5513

    
5514
struct vm_change_state_entry {
5515
    VMChangeStateHandler *cb;
5516
    void *opaque;
5517
    LIST_ENTRY (vm_change_state_entry) entries;
5518
};
5519

    
5520
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5521

    
5522
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5523
                                                     void *opaque)
5524
{
5525
    VMChangeStateEntry *e;
5526

    
5527
    e = qemu_mallocz(sizeof (*e));
5528
    if (!e)
5529
        return NULL;
5530

    
5531
    e->cb = cb;
5532
    e->opaque = opaque;
5533
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5534
    return e;
5535
}
5536

    
5537
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5538
{
5539
    LIST_REMOVE (e, entries);
5540
    qemu_free (e);
5541
}
5542

    
5543
static void vm_state_notify(int running)
5544
{
5545
    VMChangeStateEntry *e;
5546

    
5547
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5548
        e->cb(e->opaque, running);
5549
    }
5550
}
5551

    
5552
/* XXX: support several handlers */
5553
static VMStopHandler *vm_stop_cb;
5554
static void *vm_stop_opaque;
5555

    
5556
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5557
{
5558
    vm_stop_cb = cb;
5559
    vm_stop_opaque = opaque;
5560
    return 0;
5561
}
5562

    
5563
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5564
{
5565
    vm_stop_cb = NULL;
5566
}
5567

    
5568
void vm_start(void)
5569
{
5570
    if (!vm_running) {
5571
        cpu_enable_ticks();
5572
        vm_running = 1;
5573
        vm_state_notify(1);
5574
    }
5575
}
5576

    
5577
void vm_stop(int reason) 
5578
{
5579
    if (vm_running) {
5580
        cpu_disable_ticks();
5581
        vm_running = 0;
5582
        if (reason != 0) {
5583
            if (vm_stop_cb) {
5584
                vm_stop_cb(vm_stop_opaque, reason);
5585
            }
5586
        }
5587
        vm_state_notify(0);
5588
    }
5589
}
5590

    
5591
/* reset/shutdown handler */
5592

    
5593
typedef struct QEMUResetEntry {
5594
    QEMUResetHandler *func;
5595
    void *opaque;
5596
    struct QEMUResetEntry *next;
5597
} QEMUResetEntry;
5598

    
5599
static QEMUResetEntry *first_reset_entry;
5600
static int reset_requested;
5601
static int shutdown_requested;
5602
static int powerdown_requested;
5603

    
5604
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5605
{
5606
    QEMUResetEntry **pre, *re;
5607

    
5608
    pre = &first_reset_entry;
5609
    while (*pre != NULL)
5610
        pre = &(*pre)->next;
5611
    re = qemu_mallocz(sizeof(QEMUResetEntry));
5612
    re->func = func;
5613
    re->opaque = opaque;
5614
    re->next = NULL;
5615
    *pre = re;
5616
}
5617

    
5618
void qemu_system_reset(void)
5619
{
5620
    QEMUResetEntry *re;
5621

    
5622
    /* reset all devices */
5623
    for(re = first_reset_entry; re != NULL; re = re->next) {
5624
        re->func(re->opaque);
5625
    }
5626
}
5627

    
5628
void qemu_system_reset_request(void)
5629
{
5630
    reset_requested = 1;
5631
    if (cpu_single_env)
5632
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5633
}
5634

    
5635
void qemu_system_shutdown_request(void)
5636
{
5637
    shutdown_requested = 1;
5638
    if (cpu_single_env)
5639
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5640
}
5641

    
5642
void qemu_system_powerdown_request(void)
5643
{
5644
    powerdown_requested = 1;
5645
    if (cpu_single_env)
5646
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5647
}
5648

    
5649
void main_loop_wait(int timeout)
5650
{
5651
    IOHandlerRecord *ioh, *ioh_next;
5652
    fd_set rfds, wfds, xfds;
5653
    int ret, nfds;
5654
    struct timeval tv;
5655
    PollingEntry *pe;
5656

    
5657

    
5658
    /* XXX: need to suppress polling by better using win32 events */
5659
    ret = 0;
5660
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5661
        ret |= pe->func(pe->opaque);
5662
    }
5663
#ifdef _WIN32
5664
    if (ret == 0 && timeout > 0) {
5665
        int err;
5666
        WaitObjects *w = &wait_objects;
5667
        
5668
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5669
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5670
            if (w->func[ret - WAIT_OBJECT_0])
5671
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5672
        } else if (ret == WAIT_TIMEOUT) {
5673
        } else {
5674
            err = GetLastError();
5675
            fprintf(stderr, "Wait error %d %d\n", ret, err);
5676
        }
5677
    }
5678
#endif
5679
    /* poll any events */
5680
    /* XXX: separate device handlers from system ones */
5681
    nfds = -1;
5682
    FD_ZERO(&rfds);
5683
    FD_ZERO(&wfds);
5684
    FD_ZERO(&xfds);
5685
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5686
        if (ioh->fd_read &&
5687
            (!ioh->fd_read_poll ||
5688
             ioh->fd_read_poll(ioh->opaque) != 0)) {
5689
            FD_SET(ioh->fd, &rfds);
5690
            if (ioh->fd > nfds)
5691
                nfds = ioh->fd;
5692
        }
5693
        if (ioh->fd_write) {
5694
            FD_SET(ioh->fd, &wfds);
5695
            if (ioh->fd > nfds)
5696
                nfds = ioh->fd;
5697
        }
5698
    }
5699
    
5700
    tv.tv_sec = 0;
5701
#ifdef _WIN32
5702
    tv.tv_usec = 0;
5703
#else
5704
    tv.tv_usec = timeout * 1000;
5705
#endif
5706
#if defined(CONFIG_SLIRP)
5707
    if (slirp_inited) {
5708
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5709
    }
5710
#endif
5711
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5712
    if (ret > 0) {
5713
        /* XXX: better handling of removal */
5714
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5715
            ioh_next = ioh->next;
5716
            if (FD_ISSET(ioh->fd, &rfds)) {
5717
                ioh->fd_read(ioh->opaque);
5718
            }
5719
            if (FD_ISSET(ioh->fd, &wfds)) {
5720
                ioh->fd_write(ioh->opaque);
5721
            }
5722
        }
5723
    }
5724
#if defined(CONFIG_SLIRP)
5725
    if (slirp_inited) {
5726
        if (ret < 0) {
5727
            FD_ZERO(&rfds);
5728
            FD_ZERO(&wfds);
5729
            FD_ZERO(&xfds);
5730
        }
5731
        slirp_select_poll(&rfds, &wfds, &xfds);
5732
    }
5733
#endif
5734
    qemu_aio_poll();
5735
    qemu_bh_poll();
5736

    
5737
    if (vm_running) {
5738
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
5739
                        qemu_get_clock(vm_clock));
5740
        /* run dma transfers, if any */
5741
        DMA_run();
5742
    }
5743
    
5744
    /* real time timers */
5745
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
5746
                    qemu_get_clock(rt_clock));
5747
}
5748

    
5749
static CPUState *cur_cpu;
5750

    
5751
int main_loop(void)
5752
{
5753
    int ret, timeout;
5754
#ifdef CONFIG_PROFILER
5755
    int64_t ti;
5756
#endif
5757
    CPUState *env;
5758

    
5759
    cur_cpu = first_cpu;
5760
    for(;;) {
5761
        if (vm_running) {
5762

    
5763
            env = cur_cpu;
5764
            for(;;) {
5765
                /* get next cpu */
5766
                env = env->next_cpu;
5767
                if (!env)
5768
                    env = first_cpu;
5769
#ifdef CONFIG_PROFILER
5770
                ti = profile_getclock();
5771
#endif
5772
                ret = cpu_exec(env);
5773
#ifdef CONFIG_PROFILER
5774
                qemu_time += profile_getclock() - ti;
5775
#endif
5776
                if (ret != EXCP_HALTED)
5777
                    break;
5778
                /* all CPUs are halted ? */
5779
                if (env == cur_cpu) {
5780
                    ret = EXCP_HLT;
5781
                    break;
5782
                }
5783
            }
5784
            cur_cpu = env;
5785

    
5786
            if (shutdown_requested) {
5787
                ret = EXCP_INTERRUPT;
5788
                break;
5789
            }
5790
            if (reset_requested) {
5791
                reset_requested = 0;
5792
                qemu_system_reset();
5793
                ret = EXCP_INTERRUPT;
5794
            }
5795
            if (powerdown_requested) {
5796
                powerdown_requested = 0;
5797
                qemu_system_powerdown();
5798
                ret = EXCP_INTERRUPT;
5799
            }
5800
            if (ret == EXCP_DEBUG) {
5801
                vm_stop(EXCP_DEBUG);
5802
            }
5803
            /* if hlt instruction, we wait until the next IRQ */
5804
            /* XXX: use timeout computed from timers */
5805
            if (ret == EXCP_HLT)
5806
                timeout = 10;
5807
            else
5808
                timeout = 0;
5809
        } else {
5810
            timeout = 10;
5811
        }
5812
#ifdef CONFIG_PROFILER
5813
        ti = profile_getclock();
5814
#endif
5815
        main_loop_wait(timeout);
5816
#ifdef CONFIG_PROFILER
5817
        dev_time += profile_getclock() - ti;
5818
#endif
5819
    }
5820
    cpu_disable_ticks();
5821
    return ret;
5822
}
5823

    
5824
void help(void)
5825
{
5826
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
5827
           "usage: %s [options] [disk_image]\n"
5828
           "\n"
5829
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5830
           "\n"
5831
           "Standard options:\n"
5832
           "-M machine      select emulated machine (-M ? for list)\n"
5833
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
5834
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
5835
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
5836
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5837
           "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5838
           "-snapshot       write to temporary files instead of disk image files\n"
5839
#ifdef TARGET_I386
5840
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
5841
#endif
5842
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
5843
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
5844
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
5845
#ifndef _WIN32
5846
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
5847
#endif
5848
#ifdef HAS_AUDIO
5849
           "-audio-help     print list of audio drivers and their options\n"
5850
           "-soundhw c1,... enable audio support\n"
5851
           "                and only specified sound cards (comma separated list)\n"
5852
           "                use -soundhw ? to get the list of supported cards\n"
5853
           "                use -soundhw all to enable all of them\n"
5854
#endif
5855
           "-localtime      set the real time clock to local time [default=utc]\n"
5856
           "-full-screen    start in full screen\n"
5857
#ifdef TARGET_I386
5858
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
5859
#endif
5860
           "-usb            enable the USB driver (will be the default soon)\n"
5861
           "-usbdevice name add the host or guest USB device 'name'\n"
5862
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
5863
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
5864
#endif
5865
           "\n"
5866
           "Network options:\n"
5867
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5868
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
5869
#ifdef CONFIG_SLIRP
5870
           "-net user[,vlan=n][,hostname=host]\n"
5871
           "                connect the user mode network stack to VLAN 'n' and send\n"
5872
           "                hostname 'host' to DHCP clients\n"
5873
#endif
5874
#ifdef _WIN32
5875
           "-net tap[,vlan=n],ifname=name\n"
5876
           "                connect the host TAP network interface to VLAN 'n'\n"
5877
#else
5878
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5879
           "                connect the host TAP network interface to VLAN 'n' and use\n"
5880
           "                the network script 'file' (default=%s);\n"
5881
           "                use 'fd=h' to connect to an already opened TAP interface\n"
5882
#endif
5883
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5884
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
5885
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5886
           "                connect the vlan 'n' to multicast maddr and port\n"
5887
           "-net none       use it alone to have zero network devices; if no -net option\n"
5888
           "                is provided, the default is '-net nic -net user'\n"
5889
           "\n"
5890
#ifdef CONFIG_SLIRP
5891
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
5892
#ifndef _WIN32
5893
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
5894
#endif
5895
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5896
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
5897
#endif
5898
           "\n"
5899
           "Linux boot specific:\n"
5900
           "-kernel bzImage use 'bzImage' as kernel image\n"
5901
           "-append cmdline use 'cmdline' as kernel command line\n"
5902
           "-initrd file    use 'file' as initial ram disk\n"
5903
           "\n"
5904
           "Debug/Expert options:\n"
5905
           "-monitor dev    redirect the monitor to char device 'dev'\n"
5906
           "-serial dev     redirect the serial port to char device 'dev'\n"
5907
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
5908
           "-pidfile file   Write PID to 'file'\n"
5909
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
5910
           "-s              wait gdb connection to port %d\n"
5911
           "-p port         change gdb connection port\n"
5912
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
5913
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
5914
           "                translation (t=none or lba) (usually qemu can guess them)\n"
5915
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
5916
#ifdef USE_KQEMU
5917
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
5918
           "-no-kqemu       disable KQEMU kernel module usage\n"
5919
#endif
5920
#ifdef USE_CODE_COPY
5921
           "-no-code-copy   disable code copy acceleration\n"
5922
#endif
5923
#ifdef TARGET_I386
5924
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
5925
           "                (default is CL-GD5446 PCI VGA)\n"
5926
           "-no-acpi        disable ACPI\n"
5927
#endif
5928
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
5929
           "-vnc display    start a VNC server on display\n"
5930
           "\n"
5931
           "During emulation, the following keys are useful:\n"
5932
           "ctrl-alt-f      toggle full screen\n"
5933
           "ctrl-alt-n      switch to virtual console 'n'\n"
5934
           "ctrl-alt        toggle mouse and keyboard grab\n"
5935
           "\n"
5936
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
5937
           ,
5938
           "qemu",
5939
           DEFAULT_RAM_SIZE,
5940
#ifndef _WIN32
5941
           DEFAULT_NETWORK_SCRIPT,
5942
#endif
5943
           DEFAULT_GDBSTUB_PORT,
5944
           "/tmp/qemu.log");
5945
    exit(1);
5946
}
5947

    
5948
#define HAS_ARG 0x0001
5949

    
5950
enum {
5951
    QEMU_OPTION_h,
5952

    
5953
    QEMU_OPTION_M,
5954
    QEMU_OPTION_fda,
5955
    QEMU_OPTION_fdb,
5956
    QEMU_OPTION_hda,
5957
    QEMU_OPTION_hdb,
5958
    QEMU_OPTION_hdc,
5959
    QEMU_OPTION_hdd,
5960
    QEMU_OPTION_cdrom,
5961
    QEMU_OPTION_boot,
5962
    QEMU_OPTION_snapshot,
5963
#ifdef TARGET_I386
5964
    QEMU_OPTION_no_fd_bootchk,
5965
#endif
5966
    QEMU_OPTION_m,
5967
    QEMU_OPTION_nographic,
5968
#ifdef HAS_AUDIO
5969
    QEMU_OPTION_audio_help,
5970
    QEMU_OPTION_soundhw,
5971
#endif
5972

    
5973
    QEMU_OPTION_net,
5974
    QEMU_OPTION_tftp,
5975
    QEMU_OPTION_smb,
5976
    QEMU_OPTION_redir,
5977

    
5978
    QEMU_OPTION_kernel,
5979
    QEMU_OPTION_append,
5980
    QEMU_OPTION_initrd,
5981

    
5982
    QEMU_OPTION_S,
5983
    QEMU_OPTION_s,
5984
    QEMU_OPTION_p,
5985
    QEMU_OPTION_d,
5986
    QEMU_OPTION_hdachs,
5987
    QEMU_OPTION_L,
5988
    QEMU_OPTION_no_code_copy,
5989
    QEMU_OPTION_k,
5990
    QEMU_OPTION_localtime,
5991
    QEMU_OPTION_cirrusvga,
5992
    QEMU_OPTION_g,
5993
    QEMU_OPTION_std_vga,
5994
    QEMU_OPTION_monitor,
5995
    QEMU_OPTION_serial,
5996
    QEMU_OPTION_parallel,
5997
    QEMU_OPTION_loadvm,
5998
    QEMU_OPTION_full_screen,
5999
    QEMU_OPTION_pidfile,
6000
    QEMU_OPTION_no_kqemu,
6001
    QEMU_OPTION_kernel_kqemu,
6002
    QEMU_OPTION_win2k_hack,
6003
    QEMU_OPTION_usb,
6004
    QEMU_OPTION_usbdevice,
6005
    QEMU_OPTION_smp,
6006
    QEMU_OPTION_vnc,
6007
    QEMU_OPTION_no_acpi,
6008
};
6009

    
6010
typedef struct QEMUOption {
6011
    const char *name;
6012
    int flags;
6013
    int index;
6014
} QEMUOption;
6015

    
6016
const QEMUOption qemu_options[] = {
6017
    { "h", 0, QEMU_OPTION_h },
6018

    
6019
    { "M", HAS_ARG, QEMU_OPTION_M },
6020
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6021
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6022
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6023
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6024
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6025
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6026
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6027
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6028
    { "snapshot", 0, QEMU_OPTION_snapshot },
6029
#ifdef TARGET_I386
6030
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6031
#endif
6032
    { "m", HAS_ARG, QEMU_OPTION_m },
6033
    { "nographic", 0, QEMU_OPTION_nographic },
6034
    { "k", HAS_ARG, QEMU_OPTION_k },
6035
#ifdef HAS_AUDIO
6036
    { "audio-help", 0, QEMU_OPTION_audio_help },
6037
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6038
#endif
6039

    
6040
    { "net", HAS_ARG, QEMU_OPTION_net},
6041
#ifdef CONFIG_SLIRP
6042
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6043
#ifndef _WIN32
6044
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6045
#endif
6046
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6047
#endif
6048

    
6049
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6050
    { "append", HAS_ARG, QEMU_OPTION_append },
6051
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6052

    
6053
    { "S", 0, QEMU_OPTION_S },
6054
    { "s", 0, QEMU_OPTION_s },
6055
    { "p", HAS_ARG, QEMU_OPTION_p },
6056
    { "d", HAS_ARG, QEMU_OPTION_d },
6057
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6058
    { "L", HAS_ARG, QEMU_OPTION_L },
6059
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6060
#ifdef USE_KQEMU
6061
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6062
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6063
#endif
6064
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6065
    { "g", 1, QEMU_OPTION_g },
6066
#endif
6067
    { "localtime", 0, QEMU_OPTION_localtime },
6068
    { "std-vga", 0, QEMU_OPTION_std_vga },
6069
    { "monitor", 1, QEMU_OPTION_monitor },
6070
    { "serial", 1, QEMU_OPTION_serial },
6071
    { "parallel", 1, QEMU_OPTION_parallel },
6072
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6073
    { "full-screen", 0, QEMU_OPTION_full_screen },
6074
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6075
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6076
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6077
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6078
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6079
    
6080
    /* temporary options */
6081
    { "usb", 0, QEMU_OPTION_usb },
6082
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6083
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6084
    { NULL },
6085
};
6086

    
6087
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6088

    
6089
/* this stack is only used during signal handling */
6090
#define SIGNAL_STACK_SIZE 32768
6091

    
6092
static uint8_t *signal_stack;
6093

    
6094
#endif
6095

    
6096
/* password input */
6097

    
6098
static BlockDriverState *get_bdrv(int index)
6099
{
6100
    BlockDriverState *bs;
6101

    
6102
    if (index < 4) {
6103
        bs = bs_table[index];
6104
    } else if (index < 6) {
6105
        bs = fd_table[index - 4];
6106
    } else {
6107
        bs = NULL;
6108
    }
6109
    return bs;
6110
}
6111

    
6112
static void read_passwords(void)
6113
{
6114
    BlockDriverState *bs;
6115
    int i, j;
6116
    char password[256];
6117

    
6118
    for(i = 0; i < 6; i++) {
6119
        bs = get_bdrv(i);
6120
        if (bs && bdrv_is_encrypted(bs)) {
6121
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6122
            for(j = 0; j < 3; j++) {
6123
                monitor_readline("Password: ", 
6124
                                 1, password, sizeof(password));
6125
                if (bdrv_set_key(bs, password) == 0)
6126
                    break;
6127
                term_printf("invalid password\n");
6128
            }
6129
        }
6130
    }
6131
}
6132

    
6133
/* XXX: currently we cannot use simultaneously different CPUs */
6134
void register_machines(void)
6135
{
6136
#if defined(TARGET_I386)
6137
    qemu_register_machine(&pc_machine);
6138
    qemu_register_machine(&isapc_machine);
6139
#elif defined(TARGET_PPC)
6140
    qemu_register_machine(&heathrow_machine);
6141
    qemu_register_machine(&core99_machine);
6142
    qemu_register_machine(&prep_machine);
6143
#elif defined(TARGET_MIPS)
6144
    qemu_register_machine(&mips_machine);
6145
#elif defined(TARGET_SPARC)
6146
#ifdef TARGET_SPARC64
6147
    qemu_register_machine(&sun4u_machine);
6148
#else
6149
    qemu_register_machine(&sun4m_machine);
6150
#endif
6151
#elif defined(TARGET_ARM)
6152
    qemu_register_machine(&integratorcp926_machine);
6153
    qemu_register_machine(&integratorcp1026_machine);
6154
    qemu_register_machine(&versatilepb_machine);
6155
    qemu_register_machine(&versatileab_machine);
6156
    qemu_register_machine(&realview_machine);
6157
#elif defined(TARGET_SH4)
6158
    qemu_register_machine(&shix_machine);
6159
#else
6160
#error unsupported CPU
6161
#endif
6162
}
6163

    
6164
#ifdef HAS_AUDIO
6165
struct soundhw soundhw[] = {
6166
#ifdef TARGET_I386
6167
    {
6168
        "pcspk",
6169
        "PC speaker",
6170
        0,
6171
        1,
6172
        { .init_isa = pcspk_audio_init }
6173
    },
6174
#endif
6175
    {
6176
        "sb16",
6177
        "Creative Sound Blaster 16",
6178
        0,
6179
        1,
6180
        { .init_isa = SB16_init }
6181
    },
6182

    
6183
#ifdef CONFIG_ADLIB
6184
    {
6185
        "adlib",
6186
#ifdef HAS_YMF262
6187
        "Yamaha YMF262 (OPL3)",
6188
#else
6189
        "Yamaha YM3812 (OPL2)",
6190
#endif
6191
        0,
6192
        1,
6193
        { .init_isa = Adlib_init }
6194
    },
6195
#endif
6196

    
6197
#ifdef CONFIG_GUS
6198
    {
6199
        "gus",
6200
        "Gravis Ultrasound GF1",
6201
        0,
6202
        1,
6203
        { .init_isa = GUS_init }
6204
    },
6205
#endif
6206

    
6207
    {
6208
        "es1370",
6209
        "ENSONIQ AudioPCI ES1370",
6210
        0,
6211
        0,
6212
        { .init_pci = es1370_init }
6213
    },
6214

    
6215
    { NULL, NULL, 0, 0, { NULL } }
6216
};
6217

    
6218
static void select_soundhw (const char *optarg)
6219
{
6220
    struct soundhw *c;
6221

    
6222
    if (*optarg == '?') {
6223
    show_valid_cards:
6224

    
6225
        printf ("Valid sound card names (comma separated):\n");
6226
        for (c = soundhw; c->name; ++c) {
6227
            printf ("%-11s %s\n", c->name, c->descr);
6228
        }
6229
        printf ("\n-soundhw all will enable all of the above\n");
6230
        exit (*optarg != '?');
6231
    }
6232
    else {
6233
        size_t l;
6234
        const char *p;
6235
        char *e;
6236
        int bad_card = 0;
6237

    
6238
        if (!strcmp (optarg, "all")) {
6239
            for (c = soundhw; c->name; ++c) {
6240
                c->enabled = 1;
6241
            }
6242
            return;
6243
        }
6244

    
6245
        p = optarg;
6246
        while (*p) {
6247
            e = strchr (p, ',');
6248
            l = !e ? strlen (p) : (size_t) (e - p);
6249

    
6250
            for (c = soundhw; c->name; ++c) {
6251
                if (!strncmp (c->name, p, l)) {
6252
                    c->enabled = 1;
6253
                    break;
6254
                }
6255
            }
6256

    
6257
            if (!c->name) {
6258
                if (l > 80) {
6259
                    fprintf (stderr,
6260
                             "Unknown sound card name (too big to show)\n");
6261
                }
6262
                else {
6263
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
6264
                             (int) l, p);
6265
                }
6266
                bad_card = 1;
6267
            }
6268
            p += l + (e != NULL);
6269
        }
6270

    
6271
        if (bad_card)
6272
            goto show_valid_cards;
6273
    }
6274
}
6275
#endif
6276

    
6277
#ifdef _WIN32
6278
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6279
{
6280
    exit(STATUS_CONTROL_C_EXIT);
6281
    return TRUE;
6282
}
6283
#endif
6284

    
6285
#define MAX_NET_CLIENTS 32
6286

    
6287
int main(int argc, char **argv)
6288
{
6289
#ifdef CONFIG_GDBSTUB
6290
    int use_gdbstub, gdbstub_port;
6291
#endif
6292
    int i, cdrom_index;
6293
    int snapshot, linux_boot;
6294
    const char *initrd_filename;
6295
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6296
    const char *kernel_filename, *kernel_cmdline;
6297
    DisplayState *ds = &display_state;
6298
    int cyls, heads, secs, translation;
6299
    int start_emulation = 1;
6300
    char net_clients[MAX_NET_CLIENTS][256];
6301
    int nb_net_clients;
6302
    int optind;
6303
    const char *r, *optarg;
6304
    CharDriverState *monitor_hd;
6305
    char monitor_device[128];
6306
    char serial_devices[MAX_SERIAL_PORTS][128];
6307
    int serial_device_index;
6308
    char parallel_devices[MAX_PARALLEL_PORTS][128];
6309
    int parallel_device_index;
6310
    const char *loadvm = NULL;
6311
    QEMUMachine *machine;
6312
    char usb_devices[MAX_USB_CMDLINE][128];
6313
    int usb_devices_index;
6314

    
6315
    LIST_INIT (&vm_change_state_head);
6316
#ifndef _WIN32
6317
    {
6318
        struct sigaction act;
6319
        sigfillset(&act.sa_mask);
6320
        act.sa_flags = 0;
6321
        act.sa_handler = SIG_IGN;
6322
        sigaction(SIGPIPE, &act, NULL);
6323
    }
6324
#else
6325
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6326
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
6327
       QEMU to run on a single CPU */
6328
    {
6329
        HANDLE h;
6330
        DWORD mask, smask;
6331
        int i;
6332
        h = GetCurrentProcess();
6333
        if (GetProcessAffinityMask(h, &mask, &smask)) {
6334
            for(i = 0; i < 32; i++) {
6335
                if (mask & (1 << i))
6336
                    break;
6337
            }
6338
            if (i != 32) {
6339
                mask = 1 << i;
6340
                SetProcessAffinityMask(h, mask);
6341
            }
6342
        }
6343
    }
6344
#endif
6345

    
6346
    register_machines();
6347
    machine = first_machine;
6348
    initrd_filename = NULL;
6349
    for(i = 0; i < MAX_FD; i++)
6350
        fd_filename[i] = NULL;
6351
    for(i = 0; i < MAX_DISKS; i++)
6352
        hd_filename[i] = NULL;
6353
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6354
    vga_ram_size = VGA_RAM_SIZE;
6355
    bios_size = BIOS_SIZE;
6356
#ifdef CONFIG_GDBSTUB
6357
    use_gdbstub = 0;
6358
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
6359
#endif
6360
    snapshot = 0;
6361
    nographic = 0;
6362
    kernel_filename = NULL;
6363
    kernel_cmdline = "";
6364
#ifdef TARGET_PPC
6365
    cdrom_index = 1;
6366
#else
6367
    cdrom_index = 2;
6368
#endif
6369
    cyls = heads = secs = 0;
6370
    translation = BIOS_ATA_TRANSLATION_AUTO;
6371
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6372

    
6373
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6374
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
6375
        serial_devices[i][0] = '\0';
6376
    serial_device_index = 0;
6377
    
6378
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6379
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6380
        parallel_devices[i][0] = '\0';
6381
    parallel_device_index = 0;
6382
    
6383
    usb_devices_index = 0;
6384
    
6385
    nb_net_clients = 0;
6386

    
6387
    nb_nics = 0;
6388
    /* default mac address of the first network interface */
6389
    
6390
    optind = 1;
6391
    for(;;) {
6392
        if (optind >= argc)
6393
            break;
6394
        r = argv[optind];
6395
        if (r[0] != '-') {
6396
            hd_filename[0] = argv[optind++];
6397
        } else {
6398
            const QEMUOption *popt;
6399

    
6400
            optind++;
6401
            popt = qemu_options;
6402
            for(;;) {
6403
                if (!popt->name) {
6404
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
6405
                            argv[0], r);
6406
                    exit(1);
6407
                }
6408
                if (!strcmp(popt->name, r + 1))
6409
                    break;
6410
                popt++;
6411
            }
6412
            if (popt->flags & HAS_ARG) {
6413
                if (optind >= argc) {
6414
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
6415
                            argv[0], r);
6416
                    exit(1);
6417
                }
6418
                optarg = argv[optind++];
6419
            } else {
6420
                optarg = NULL;
6421
            }
6422

    
6423
            switch(popt->index) {
6424
            case QEMU_OPTION_M:
6425
                machine = find_machine(optarg);
6426
                if (!machine) {
6427
                    QEMUMachine *m;
6428
                    printf("Supported machines are:\n");
6429
                    for(m = first_machine; m != NULL; m = m->next) {
6430
                        printf("%-10s %s%s\n",
6431
                               m->name, m->desc, 
6432
                               m == first_machine ? " (default)" : "");
6433
                    }
6434
                    exit(1);
6435
                }
6436
                break;
6437
            case QEMU_OPTION_initrd:
6438
                initrd_filename = optarg;
6439
                break;
6440
            case QEMU_OPTION_hda:
6441
            case QEMU_OPTION_hdb:
6442
            case QEMU_OPTION_hdc:
6443
            case QEMU_OPTION_hdd:
6444
                {
6445
                    int hd_index;
6446
                    hd_index = popt->index - QEMU_OPTION_hda;
6447
                    hd_filename[hd_index] = optarg;
6448
                    if (hd_index == cdrom_index)
6449
                        cdrom_index = -1;
6450
                }
6451
                break;
6452
            case QEMU_OPTION_snapshot:
6453
                snapshot = 1;
6454
                break;
6455
            case QEMU_OPTION_hdachs:
6456
                {
6457
                    const char *p;
6458
                    p = optarg;
6459
                    cyls = strtol(p, (char **)&p, 0);
6460
                    if (cyls < 1 || cyls > 16383)
6461
                        goto chs_fail;
6462
                    if (*p != ',')
6463
                        goto chs_fail;
6464
                    p++;
6465
                    heads = strtol(p, (char **)&p, 0);
6466
                    if (heads < 1 || heads > 16)
6467
                        goto chs_fail;
6468
                    if (*p != ',')
6469
                        goto chs_fail;
6470
                    p++;
6471
                    secs = strtol(p, (char **)&p, 0);
6472
                    if (secs < 1 || secs > 63)
6473
                        goto chs_fail;
6474
                    if (*p == ',') {
6475
                        p++;
6476
                        if (!strcmp(p, "none"))
6477
                            translation = BIOS_ATA_TRANSLATION_NONE;
6478
                        else if (!strcmp(p, "lba"))
6479
                            translation = BIOS_ATA_TRANSLATION_LBA;
6480
                        else if (!strcmp(p, "auto"))
6481
                            translation = BIOS_ATA_TRANSLATION_AUTO;
6482
                        else
6483
                            goto chs_fail;
6484
                    } else if (*p != '\0') {
6485
                    chs_fail:
6486
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
6487
                        exit(1);
6488
                    }
6489
                }
6490
                break;
6491
            case QEMU_OPTION_nographic:
6492
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6493
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6494
                nographic = 1;
6495
                break;
6496
            case QEMU_OPTION_kernel:
6497
                kernel_filename = optarg;
6498
                break;
6499
            case QEMU_OPTION_append:
6500
                kernel_cmdline = optarg;
6501
                break;
6502
            case QEMU_OPTION_cdrom:
6503
                if (cdrom_index >= 0) {
6504
                    hd_filename[cdrom_index] = optarg;
6505
                }
6506
                break;
6507
            case QEMU_OPTION_boot:
6508
                boot_device = optarg[0];
6509
                if (boot_device != 'a' && 
6510
#ifdef TARGET_SPARC
6511
                    // Network boot
6512
                    boot_device != 'n' &&
6513
#endif
6514
                    boot_device != 'c' && boot_device != 'd') {
6515
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6516
                    exit(1);
6517
                }
6518
                break;
6519
            case QEMU_OPTION_fda:
6520
                fd_filename[0] = optarg;
6521
                break;
6522
            case QEMU_OPTION_fdb:
6523
                fd_filename[1] = optarg;
6524
                break;
6525
#ifdef TARGET_I386
6526
            case QEMU_OPTION_no_fd_bootchk:
6527
                fd_bootchk = 0;
6528
                break;
6529
#endif
6530
            case QEMU_OPTION_no_code_copy:
6531
                code_copy_enabled = 0;
6532
                break;
6533
            case QEMU_OPTION_net:
6534
                if (nb_net_clients >= MAX_NET_CLIENTS) {
6535
                    fprintf(stderr, "qemu: too many network clients\n");
6536
                    exit(1);
6537
                }
6538
                pstrcpy(net_clients[nb_net_clients],
6539
                        sizeof(net_clients[0]),
6540
                        optarg);
6541
                nb_net_clients++;
6542
                break;
6543
#ifdef CONFIG_SLIRP
6544
            case QEMU_OPTION_tftp:
6545
                tftp_prefix = optarg;
6546
                break;
6547
#ifndef _WIN32
6548
            case QEMU_OPTION_smb:
6549
                net_slirp_smb(optarg);
6550
                break;
6551
#endif
6552
            case QEMU_OPTION_redir:
6553
                net_slirp_redir(optarg);                
6554
                break;
6555
#endif
6556
#ifdef HAS_AUDIO
6557
            case QEMU_OPTION_audio_help:
6558
                AUD_help ();
6559
                exit (0);
6560
                break;
6561
            case QEMU_OPTION_soundhw:
6562
                select_soundhw (optarg);
6563
                break;
6564
#endif
6565
            case QEMU_OPTION_h:
6566
                help();
6567
                break;
6568
            case QEMU_OPTION_m:
6569
                ram_size = atoi(optarg) * 1024 * 1024;
6570
                if (ram_size <= 0)
6571
                    help();
6572
                if (ram_size > PHYS_RAM_MAX_SIZE) {
6573
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6574
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
6575
                    exit(1);
6576
                }
6577
                break;
6578
            case QEMU_OPTION_d:
6579
                {
6580
                    int mask;
6581
                    CPULogItem *item;
6582
                    
6583
                    mask = cpu_str_to_log_mask(optarg);
6584
                    if (!mask) {
6585
                        printf("Log items (comma separated):\n");
6586
                    for(item = cpu_log_items; item->mask != 0; item++) {
6587
                        printf("%-10s %s\n", item->name, item->help);
6588
                    }
6589
                    exit(1);
6590
                    }
6591
                    cpu_set_log(mask);
6592
                }
6593
                break;
6594
#ifdef CONFIG_GDBSTUB
6595
            case QEMU_OPTION_s:
6596
                use_gdbstub = 1;
6597
                break;
6598
            case QEMU_OPTION_p:
6599
                gdbstub_port = atoi(optarg);
6600
                break;
6601
#endif
6602
            case QEMU_OPTION_L:
6603
                bios_dir = optarg;
6604
                break;
6605
            case QEMU_OPTION_S:
6606
                start_emulation = 0;
6607
                break;
6608
            case QEMU_OPTION_k:
6609
                keyboard_layout = optarg;
6610
                break;
6611
            case QEMU_OPTION_localtime:
6612
                rtc_utc = 0;
6613
                break;
6614
            case QEMU_OPTION_cirrusvga:
6615
                cirrus_vga_enabled = 1;
6616
                break;
6617
            case QEMU_OPTION_std_vga:
6618
                cirrus_vga_enabled = 0;
6619
                break;
6620
            case QEMU_OPTION_g:
6621
                {
6622
                    const char *p;
6623
                    int w, h, depth;
6624
                    p = optarg;
6625
                    w = strtol(p, (char **)&p, 10);
6626
                    if (w <= 0) {
6627
                    graphic_error:
6628
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
6629
                        exit(1);
6630
                    }
6631
                    if (*p != 'x')
6632
                        goto graphic_error;
6633
                    p++;
6634
                    h = strtol(p, (char **)&p, 10);
6635
                    if (h <= 0)
6636
                        goto graphic_error;
6637
                    if (*p == 'x') {
6638
                        p++;
6639
                        depth = strtol(p, (char **)&p, 10);
6640
                        if (depth != 8 && depth != 15 && depth != 16 && 
6641
                            depth != 24 && depth != 32)
6642
                            goto graphic_error;
6643
                    } else if (*p == '\0') {
6644
                        depth = graphic_depth;
6645
                    } else {
6646
                        goto graphic_error;
6647
                    }
6648
                    
6649
                    graphic_width = w;
6650
                    graphic_height = h;
6651
                    graphic_depth = depth;
6652
                }
6653
                break;
6654
            case QEMU_OPTION_monitor:
6655
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6656
                break;
6657
            case QEMU_OPTION_serial:
6658
                if (serial_device_index >= MAX_SERIAL_PORTS) {
6659
                    fprintf(stderr, "qemu: too many serial ports\n");
6660
                    exit(1);
6661
                }
6662
                pstrcpy(serial_devices[serial_device_index], 
6663
                        sizeof(serial_devices[0]), optarg);
6664
                serial_device_index++;
6665
                break;
6666
            case QEMU_OPTION_parallel:
6667
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6668
                    fprintf(stderr, "qemu: too many parallel ports\n");
6669
                    exit(1);
6670
                }
6671
                pstrcpy(parallel_devices[parallel_device_index], 
6672
                        sizeof(parallel_devices[0]), optarg);
6673
                parallel_device_index++;
6674
                break;
6675
            case QEMU_OPTION_loadvm:
6676
                loadvm = optarg;
6677
                break;
6678
            case QEMU_OPTION_full_screen:
6679
                full_screen = 1;
6680
                break;
6681
            case QEMU_OPTION_pidfile:
6682
                create_pidfile(optarg);
6683
                break;
6684
#ifdef TARGET_I386
6685
            case QEMU_OPTION_win2k_hack:
6686
                win2k_install_hack = 1;
6687
                break;
6688
#endif
6689
#ifdef USE_KQEMU
6690
            case QEMU_OPTION_no_kqemu:
6691
                kqemu_allowed = 0;
6692
                break;
6693
            case QEMU_OPTION_kernel_kqemu:
6694
                kqemu_allowed = 2;
6695
                break;
6696
#endif
6697
            case QEMU_OPTION_usb:
6698
                usb_enabled = 1;
6699
                break;
6700
            case QEMU_OPTION_usbdevice:
6701
                usb_enabled = 1;
6702
                if (usb_devices_index >= MAX_USB_CMDLINE) {
6703
                    fprintf(stderr, "Too many USB devices\n");
6704
                    exit(1);
6705
                }
6706
                pstrcpy(usb_devices[usb_devices_index],
6707
                        sizeof(usb_devices[usb_devices_index]),
6708
                        optarg);
6709
                usb_devices_index++;
6710
                break;
6711
            case QEMU_OPTION_smp:
6712
                smp_cpus = atoi(optarg);
6713
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6714
                    fprintf(stderr, "Invalid number of CPUs\n");
6715
                    exit(1);
6716
                }
6717
                break;
6718
            case QEMU_OPTION_vnc:
6719
                vnc_display = atoi(optarg);
6720
                if (vnc_display < 0) {
6721
                    fprintf(stderr, "Invalid VNC display\n");
6722
                    exit(1);
6723
                }
6724
                break;
6725
            case QEMU_OPTION_no_acpi:
6726
                acpi_enabled = 0;
6727
                break;
6728
            }
6729
        }
6730
    }
6731

    
6732
#ifdef USE_KQEMU
6733
    if (smp_cpus > 1)
6734
        kqemu_allowed = 0;
6735
#endif
6736
    linux_boot = (kernel_filename != NULL);
6737
        
6738
    if (!linux_boot && 
6739
        hd_filename[0] == '\0' && 
6740
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6741
        fd_filename[0] == '\0')
6742
        help();
6743
    
6744
    /* boot to cd by default if no hard disk */
6745
    if (hd_filename[0] == '\0' && boot_device == 'c') {
6746
        if (fd_filename[0] != '\0')
6747
            boot_device = 'a';
6748
        else
6749
            boot_device = 'd';
6750
    }
6751

    
6752
    setvbuf(stdout, NULL, _IOLBF, 0);
6753
    
6754
    init_timers();
6755
    init_timer_alarm();
6756
    qemu_aio_init();
6757

    
6758
#ifdef _WIN32
6759
    socket_init();
6760
#endif
6761

    
6762
    /* init network clients */
6763
    if (nb_net_clients == 0) {
6764
        /* if no clients, we use a default config */
6765
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
6766
                "nic");
6767
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
6768
                "user");
6769
        nb_net_clients = 2;
6770
    }
6771

    
6772
    for(i = 0;i < nb_net_clients; i++) {
6773
        if (net_client_init(net_clients[i]) < 0)
6774
            exit(1);
6775
    }
6776

    
6777
    /* init the memory */
6778
    phys_ram_size = ram_size + vga_ram_size + bios_size;
6779

    
6780
    phys_ram_base = qemu_vmalloc(phys_ram_size);
6781
    if (!phys_ram_base) {
6782
        fprintf(stderr, "Could not allocate physical memory\n");
6783
        exit(1);
6784
    }
6785

    
6786
    /* we always create the cdrom drive, even if no disk is there */
6787
    bdrv_init();
6788
    if (cdrom_index >= 0) {
6789
        bs_table[cdrom_index] = bdrv_new("cdrom");
6790
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6791
    }
6792

    
6793
    /* open the virtual block devices */
6794
    for(i = 0; i < MAX_DISKS; i++) {
6795
        if (hd_filename[i]) {
6796
            if (!bs_table[i]) {
6797
                char buf[64];
6798
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6799
                bs_table[i] = bdrv_new(buf);
6800
            }
6801
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6802
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6803
                        hd_filename[i]);
6804
                exit(1);
6805
            }
6806
            if (i == 0 && cyls != 0) {
6807
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6808
                bdrv_set_translation_hint(bs_table[i], translation);
6809
            }
6810
        }
6811
    }
6812

    
6813
    /* we always create at least one floppy disk */
6814
    fd_table[0] = bdrv_new("fda");
6815
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6816

    
6817
    for(i = 0; i < MAX_FD; i++) {
6818
        if (fd_filename[i]) {
6819
            if (!fd_table[i]) {
6820
                char buf[64];
6821
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6822
                fd_table[i] = bdrv_new(buf);
6823
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6824
            }
6825
            if (fd_filename[i] != '\0') {
6826
                if (bdrv_open(fd_table[i], fd_filename[i],
6827
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6828
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6829
                            fd_filename[i]);
6830
                    exit(1);
6831
                }
6832
            }
6833
        }
6834
    }
6835

    
6836
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6837
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
6838

    
6839
    init_ioports();
6840

    
6841
    /* terminal init */
6842
    if (nographic) {
6843
        dumb_display_init(ds);
6844
    } else if (vnc_display != -1) {
6845
        vnc_display_init(ds, vnc_display);
6846
    } else {
6847
#if defined(CONFIG_SDL)
6848
        sdl_display_init(ds, full_screen);
6849
#elif defined(CONFIG_COCOA)
6850
        cocoa_display_init(ds, full_screen);
6851
#else
6852
        dumb_display_init(ds);
6853
#endif
6854
    }
6855

    
6856
    monitor_hd = qemu_chr_open(monitor_device);
6857
    if (!monitor_hd) {
6858
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6859
        exit(1);
6860
    }
6861
    monitor_init(monitor_hd, !nographic);
6862

    
6863
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6864
        const char *devname = serial_devices[i];
6865
        if (devname[0] != '\0' && strcmp(devname, "none")) {
6866
            serial_hds[i] = qemu_chr_open(devname);
6867
            if (!serial_hds[i]) {
6868
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
6869
                        devname);
6870
                exit(1);
6871
            }
6872
            if (!strcmp(devname, "vc"))
6873
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6874
        }
6875
    }
6876

    
6877
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6878
        const char *devname = parallel_devices[i];
6879
        if (devname[0] != '\0' && strcmp(devname, "none")) {
6880
            parallel_hds[i] = qemu_chr_open(devname);
6881
            if (!parallel_hds[i]) {
6882
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
6883
                        devname);
6884
                exit(1);
6885
            }
6886
            if (!strcmp(devname, "vc"))
6887
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6888
        }
6889
    }
6890

    
6891
    machine->init(ram_size, vga_ram_size, boot_device,
6892
                  ds, fd_filename, snapshot,
6893
                  kernel_filename, kernel_cmdline, initrd_filename);
6894

    
6895
    /* init USB devices */
6896
    if (usb_enabled) {
6897
        for(i = 0; i < usb_devices_index; i++) {
6898
            if (usb_device_add(usb_devices[i]) < 0) {
6899
                fprintf(stderr, "Warning: could not add USB device %s\n",
6900
                        usb_devices[i]);
6901
            }
6902
        }
6903
    }
6904

    
6905
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6906
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6907

    
6908
#ifdef CONFIG_GDBSTUB
6909
    if (use_gdbstub) {
6910
        if (gdbserver_start(gdbstub_port) < 0) {
6911
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
6912
                    gdbstub_port);
6913
            exit(1);
6914
        } else {
6915
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
6916
        }
6917
    } else 
6918
#endif
6919
    if (loadvm)
6920
        do_loadvm(loadvm);
6921

    
6922
    {
6923
        /* XXX: simplify init */
6924
        read_passwords();
6925
        if (start_emulation) {
6926
            vm_start();
6927
        }
6928
    }
6929
    main_loop();
6930
    quit_timers();
6931
    return 0;
6932
}