Statistics
| Branch: | Revision:

root / vl.c @ 1bdb68ea

History | View | Annotate | Download (147 kB)

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

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

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

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

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

    
73
#include "qemu_socket.h"
74

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

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

    
86
#include "disas.h"
87

    
88
#include "exec-all.h"
89

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

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

    
95
#if !defined(CONFIG_SOFTMMU)
96
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
97
#else
98
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
99
#endif
100

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
296
/***********************************************************/
297

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

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

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

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

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

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

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

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

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

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

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

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

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

    
447
/***********************************************************/
448
/* keyboard/mouse */
449

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

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

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

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

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

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

    
489
/***********************************************************/
490
/* timers */
491

    
492
#if defined(__powerpc__)
493

    
494
static inline uint32_t get_tbl(void) 
495
{
496
    uint32_t tbl;
497
    asm volatile("mftb %0" : "=r" (tbl));
498
    return tbl;
499
}
500

    
501
static inline uint32_t get_tbu(void) 
502
{
503
        uint32_t tbl;
504
        asm volatile("mftbu %0" : "=r" (tbl));
505
        return tbl;
506
}
507

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

    
520
#elif defined(__i386__)
521

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

    
535
#elif defined(__x86_64__)
536

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

    
548
#elif defined(__ia64)
549

    
550
int64_t cpu_get_real_ticks(void)
551
{
552
        int64_t val;
553
        asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
554
        return val;
555
}
556

    
557
#elif defined(__s390__)
558

    
559
int64_t cpu_get_real_ticks(void)
560
{
561
    int64_t val;
562
    asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
563
    return val;
564
}
565

    
566
#elif defined(__sparc__) && defined(HOST_SOLARIS)
567

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

    
588
#else
589
#error unsupported CPU
590
#endif
591

    
592
static int64_t cpu_ticks_prev;
593
static int64_t cpu_ticks_offset;
594
static int cpu_ticks_enabled;
595

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

    
613
/* enable cpu_get_ticks() */
614
void cpu_enable_ticks(void)
615
{
616
    if (!cpu_ticks_enabled) {
617
        cpu_ticks_offset -= cpu_get_real_ticks();
618
        cpu_ticks_enabled = 1;
619
    }
620
}
621

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

    
632
#ifdef _WIN32
633
void cpu_calibrate_ticks(void)
634
{
635
    LARGE_INTEGER freq;
636
    int ret;
637

    
638
    ret = QueryPerformanceFrequency(&freq);
639
    if (ret == 0) {
640
        fprintf(stderr, "Could not calibrate ticks\n");
641
        exit(1);
642
    }
643
    ticks_per_sec = freq.QuadPart;
644
}
645

    
646
#else
647
static int64_t get_clock(void)
648
{
649
    struct timeval tv;
650
    gettimeofday(&tv, NULL);
651
    return tv.tv_sec * 1000000LL + tv.tv_usec;
652
}
653

    
654
void cpu_calibrate_ticks(void)
655
{
656
    int64_t usec, ticks;
657

    
658
    usec = get_clock();
659
    ticks = cpu_get_real_ticks();
660
    usleep(50 * 1000);
661
    usec = get_clock() - usec;
662
    ticks = cpu_get_real_ticks() - ticks;
663
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
664
}
665
#endif /* !_WIN32 */
666

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

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

    
691
#define QEMU_TIMER_REALTIME 0
692
#define QEMU_TIMER_VIRTUAL  1
693

    
694
struct QEMUClock {
695
    int type;
696
    /* XXX: add frequency */
697
};
698

    
699
struct QEMUTimer {
700
    QEMUClock *clock;
701
    int64_t expire_time;
702
    QEMUTimerCB *cb;
703
    void *opaque;
704
    struct QEMUTimer *next;
705
};
706

    
707
QEMUClock *rt_clock;
708
QEMUClock *vm_clock;
709

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

    
720
QEMUClock *qemu_new_clock(int type)
721
{
722
    QEMUClock *clock;
723
    clock = qemu_mallocz(sizeof(QEMUClock));
724
    if (!clock)
725
        return NULL;
726
    clock->type = type;
727
    return clock;
728
}
729

    
730
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
731
{
732
    QEMUTimer *ts;
733

    
734
    ts = qemu_mallocz(sizeof(QEMUTimer));
735
    ts->clock = clock;
736
    ts->cb = cb;
737
    ts->opaque = opaque;
738
    return ts;
739
}
740

    
741
void qemu_free_timer(QEMUTimer *ts)
742
{
743
    qemu_free(ts);
744
}
745

    
746
/* stop a timer, but do not dealloc it */
747
void qemu_del_timer(QEMUTimer *ts)
748
{
749
    QEMUTimer **pt, *t;
750

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

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

    
772
    qemu_del_timer(ts);
773

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

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

    
801
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
802
{
803
    if (!timer_head)
804
        return 0;
805
    return (timer_head->expire_time <= current_time);
806
}
807

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

    
825
int64_t qemu_get_clock(QEMUClock *clock)
826
{
827
    switch(clock->type) {
828
    case QEMU_TIMER_REALTIME:
829
#ifdef _WIN32
830
        return GetTickCount();
831
#else
832
        {
833
            struct tms tp;
834

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

    
851
/* save a timer */
852
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
853
{
854
    uint64_t expire_time;
855

    
856
    if (qemu_timer_pending(ts)) {
857
        expire_time = ts->expire_time;
858
    } else {
859
        expire_time = -1;
860
    }
861
    qemu_put_be64(f, expire_time);
862
}
863

    
864
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
865
{
866
    uint64_t expire_time;
867

    
868
    expire_time = qemu_get_be64(f);
869
    if (expire_time != -1) {
870
        qemu_mod_timer(ts, expire_time);
871
    } else {
872
        qemu_del_timer(ts);
873
    }
874
}
875

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

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

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

    
953
#ifndef _WIN32
954

    
955
#if defined(__linux__)
956

    
957
#define RTC_FREQ 1024
958

    
959
static int rtc_fd;
960

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

    
981
#else
982

    
983
static int start_rtc_timer(void)
984
{
985
    return -1;
986
}
987

    
988
#endif /* !defined(__linux__) */
989

    
990
#endif /* !defined(_WIN32) */
991

    
992
static void init_timers(void)
993
{
994
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
995
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
996

    
997
#ifdef _WIN32
998
    {
999
        int count=0;
1000
        TIMECAPS tc;
1001

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

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

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

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

    
1081
void quit_timers(void)
1082
{
1083
#ifdef _WIN32
1084
    timeKillEvent(timerID);
1085
    timeEndPeriod(period);
1086
    if (host_alarm) {
1087
        CloseHandle(host_alarm);
1088
        host_alarm = NULL;
1089
    }
1090
#endif
1091
}
1092

    
1093
/***********************************************************/
1094
/* character device */
1095

    
1096
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1097
{
1098
    return s->chr_write(s, buf, len);
1099
}
1100

    
1101
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1102
{
1103
    if (!s->chr_ioctl)
1104
        return -ENOTSUP;
1105
    return s->chr_ioctl(s, cmd, arg);
1106
}
1107

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

    
1118
void qemu_chr_send_event(CharDriverState *s, int event)
1119
{
1120
    if (s->chr_send_event)
1121
        s->chr_send_event(s, event);
1122
}
1123

    
1124
void qemu_chr_add_read_handler(CharDriverState *s, 
1125
                               IOCanRWHandler *fd_can_read, 
1126
                               IOReadHandler *fd_read, void *opaque)
1127
{
1128
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1129
}
1130
             
1131
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1132
{
1133
    s->chr_event = chr_event;
1134
}
1135

    
1136
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1137
{
1138
    return len;
1139
}
1140

    
1141
static void null_chr_add_read_handler(CharDriverState *chr, 
1142
                                    IOCanRWHandler *fd_can_read, 
1143
                                    IOReadHandler *fd_read, void *opaque)
1144
{
1145
}
1146

    
1147
CharDriverState *qemu_chr_open_null(void)
1148
{
1149
    CharDriverState *chr;
1150

    
1151
    chr = qemu_mallocz(sizeof(CharDriverState));
1152
    if (!chr)
1153
        return NULL;
1154
    chr->chr_write = null_chr_write;
1155
    chr->chr_add_read_handler = null_chr_add_read_handler;
1156
    return chr;
1157
}
1158

    
1159
#ifdef _WIN32
1160

    
1161
static void socket_cleanup(void)
1162
{
1163
    WSACleanup();
1164
}
1165

    
1166
static int socket_init(void)
1167
{
1168
    WSADATA Data;
1169
    int ret, err;
1170

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

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

    
1204
void socket_set_nonblock(int fd)
1205
{
1206
    unsigned long opt = 1;
1207
    ioctlsocket(fd, FIONBIO, &opt);
1208
}
1209

    
1210
#else
1211

    
1212
static int unix_write(int fd, const uint8_t *buf, int len1)
1213
{
1214
    int ret, len;
1215

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

    
1232
static inline int send_all(int fd, const uint8_t *buf, int len1)
1233
{
1234
    return unix_write(fd, buf, len1);
1235
}
1236

    
1237
void socket_set_nonblock(int fd)
1238
{
1239
    fcntl(fd, F_SETFL, O_NONBLOCK);
1240
}
1241
#endif /* !_WIN32 */
1242

    
1243
#ifndef _WIN32
1244

    
1245
typedef struct {
1246
    int fd_in, fd_out;
1247
    IOCanRWHandler *fd_can_read; 
1248
    IOReadHandler *fd_read;
1249
    void *fd_opaque;
1250
    int max_size;
1251
} FDCharDriver;
1252

    
1253
#define STDIO_MAX_CLIENTS 2
1254

    
1255
static int stdio_nb_clients;
1256
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1257

    
1258
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1259
{
1260
    FDCharDriver *s = chr->opaque;
1261
    return unix_write(s->fd_out, buf, len);
1262
}
1263

    
1264
static int fd_chr_read_poll(void *opaque)
1265
{
1266
    CharDriverState *chr = opaque;
1267
    FDCharDriver *s = chr->opaque;
1268

    
1269
    s->max_size = s->fd_can_read(s->fd_opaque);
1270
    return s->max_size;
1271
}
1272

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

    
1291
static void fd_chr_add_read_handler(CharDriverState *chr, 
1292
                                    IOCanRWHandler *fd_can_read, 
1293
                                    IOReadHandler *fd_read, void *opaque)
1294
{
1295
    FDCharDriver *s = chr->opaque;
1296

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

    
1309
/* open a character device to a unix fd */
1310
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1311
{
1312
    CharDriverState *chr;
1313
    FDCharDriver *s;
1314

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

    
1331
CharDriverState *qemu_chr_open_file_out(const char *file_out)
1332
{
1333
    int fd_out;
1334

    
1335
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1336
    if (fd_out < 0)
1337
        return NULL;
1338
    return qemu_chr_open_fd(-1, fd_out);
1339
}
1340

    
1341
CharDriverState *qemu_chr_open_pipe(const char *filename)
1342
{
1343
    int fd;
1344

    
1345
    fd = open(filename, O_RDWR | O_BINARY);
1346
    if (fd < 0)
1347
        return NULL;
1348
    return qemu_chr_open_fd(fd, fd);
1349
}
1350

    
1351

    
1352
/* for STDIO, we handle the case where several clients use it
1353
   (nographic mode) */
1354

    
1355
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1356

    
1357
#define TERM_FIFO_MAX_SIZE 1
1358

    
1359
static int term_got_escape, client_index;
1360
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1361
int term_fifo_size;
1362

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

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

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

    
1440
static int stdio_read_poll(void *opaque)
1441
{
1442
    CharDriverState *chr;
1443
    FDCharDriver *s;
1444

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

    
1463
static void stdio_read(void *opaque)
1464
{
1465
    int size;
1466
    uint8_t buf[1];
1467
    
1468
    size = read(0, buf, 1);
1469
    if (size > 0)
1470
        stdio_received_byte(buf[0]);
1471
}
1472

    
1473
/* init terminal so that we can grab keys */
1474
static struct termios oldtty;
1475
static int old_fd0_flags;
1476

    
1477
static void term_exit(void)
1478
{
1479
    tcsetattr (0, TCSANOW, &oldtty);
1480
    fcntl(0, F_SETFL, old_fd0_flags);
1481
}
1482

    
1483
static void term_init(void)
1484
{
1485
    struct termios tty;
1486

    
1487
    tcgetattr (0, &tty);
1488
    oldtty = tty;
1489
    old_fd0_flags = fcntl(0, F_GETFL);
1490

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

    
1505
    atexit(term_exit);
1506

    
1507
    fcntl(0, F_SETFL, O_NONBLOCK);
1508
}
1509

    
1510
CharDriverState *qemu_chr_open_stdio(void)
1511
{
1512
    CharDriverState *chr;
1513

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

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

    
1553
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1554
    return qemu_chr_open_fd(master_fd, master_fd);
1555
}
1556

    
1557
static void tty_serial_init(int fd, int speed, 
1558
                            int parity, int data_bits, int stop_bits)
1559
{
1560
    struct termios tty;
1561
    speed_t spd;
1562

    
1563
#if 0
1564
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1565
           speed, parity, data_bits, stop_bits);
1566
#endif
1567
    tcgetattr (fd, &tty);
1568

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

    
1609
    cfsetispeed(&tty, spd);
1610
    cfsetospeed(&tty, spd);
1611

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

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

    
1672
CharDriverState *qemu_chr_open_tty(const char *filename)
1673
{
1674
    CharDriverState *chr;
1675
    int fd;
1676

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

    
1689
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1690
{
1691
    int fd = (int)chr->opaque;
1692
    uint8_t b;
1693

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

    
1726
CharDriverState *qemu_chr_open_pp(const char *filename)
1727
{
1728
    CharDriverState *chr;
1729
    int fd;
1730

    
1731
    fd = open(filename, O_RDWR);
1732
    if (fd < 0)
1733
        return NULL;
1734

    
1735
    if (ioctl(fd, PPCLAIM) < 0) {
1736
        close(fd);
1737
        return NULL;
1738
    }
1739

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

    
1752
#else
1753
CharDriverState *qemu_chr_open_pty(void)
1754
{
1755
    return NULL;
1756
}
1757
#endif
1758

    
1759
#endif /* !defined(_WIN32) */
1760

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

    
1773
#define NSENDBUF 2048
1774
#define NRECVBUF 2048
1775
#define MAXCONNECT 1
1776
#define NTIMEOUT 5000
1777

    
1778
static int win_chr_poll(void *opaque);
1779
static int win_chr_pipe_poll(void *opaque);
1780

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

    
1801
static void win_chr_close(CharDriverState *chr)
1802
{
1803
    WinCharState *s = chr->opaque;
1804
    win_chr_close2(s);
1805
}
1806

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

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

    
1845
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1846
        fprintf(stderr, "Failed SetCommState\n");
1847
        goto fail;
1848
    }
1849

    
1850
    if (!SetCommMask(s->hcom, EV_ERR)) {
1851
        fprintf(stderr, "Failed SetCommMask\n");
1852
        goto fail;
1853
    }
1854

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

    
1868
 fail:
1869
    win_chr_close2(s);
1870
    return -1;
1871
}
1872

    
1873
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1874
{
1875
    WinCharState *s = chr->opaque;
1876
    DWORD len, ret, size, err;
1877

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

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

    
1929
    if (size > 0) {
1930
        s->fd_read(s->win_opaque, buf, size);
1931
    }
1932
}
1933

    
1934
static void win_chr_read(WinCharState *s)
1935
{
1936
    if (s->len > s->max_size)
1937
        s->len = s->max_size;
1938
    if (s->len == 0)
1939
        return;
1940
    
1941
    win_chr_readfile(s);
1942
}
1943

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

    
1960
static void win_chr_add_read_handler(CharDriverState *chr, 
1961
                                    IOCanRWHandler *fd_can_read, 
1962
                                    IOReadHandler *fd_read, void *opaque)
1963
{
1964
    WinCharState *s = chr->opaque;
1965

    
1966
    s->fd_can_read = fd_can_read;
1967
    s->fd_read = fd_read;
1968
    s->win_opaque = opaque;
1969
}
1970

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

    
1989
    if (win_chr_init(s, filename) < 0) {
1990
        free(s);
1991
        free(chr);
1992
        return NULL;
1993
    }
1994
    return chr;
1995
}
1996

    
1997
static int win_chr_pipe_poll(void *opaque)
1998
{
1999
    WinCharState *s = opaque;
2000
    DWORD size;
2001

    
2002
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2003
    if (size > 0) {
2004
        s->len = size;
2005
        win_chr_read_poll(s);
2006
        win_chr_read(s);
2007
        return 1;
2008
    }
2009
    return 0;
2010
}
2011

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

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

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

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

    
2061
    if (ov.hEvent) {
2062
        CloseHandle(ov.hEvent);
2063
        ov.hEvent = NULL;
2064
    }
2065
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2066
    return 0;
2067

    
2068
 fail:
2069
    win_chr_close2(s);
2070
    return -1;
2071
}
2072

    
2073

    
2074
CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2075
{
2076
    CharDriverState *chr;
2077
    WinCharState *s;
2078

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

    
2100
CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2101
{
2102
    CharDriverState *chr;
2103
    WinCharState *s;
2104

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

    
2129
    return qemu_chr_open_win_file(fd_out);
2130
}
2131
#endif
2132

    
2133
CharDriverState *qemu_chr_open(const char *filename)
2134
{
2135
    const char *p;
2136

    
2137
    if (!strcmp(filename, "vc")) {
2138
        return text_console_init(&display_state);
2139
    } else if (!strcmp(filename, "null")) {
2140
        return qemu_chr_open_null();
2141
    } else 
2142
#ifndef _WIN32
2143
    if (strstart(filename, "file:", &p)) {
2144
        return qemu_chr_open_file_out(p);
2145
    } else if (strstart(filename, "pipe:", &p)) {
2146
        return qemu_chr_open_pipe(p);
2147
    } else if (!strcmp(filename, "pty")) {
2148
        return qemu_chr_open_pty();
2149
    } else if (!strcmp(filename, "stdio")) {
2150
        return qemu_chr_open_stdio();
2151
    } else 
2152
#endif
2153
#if defined(__linux__)
2154
    if (strstart(filename, "/dev/parport", NULL)) {
2155
        return qemu_chr_open_pp(filename);
2156
    } else 
2157
    if (strstart(filename, "/dev/", NULL)) {
2158
        return qemu_chr_open_tty(filename);
2159
    } else 
2160
#endif
2161
#ifdef _WIN32
2162
    if (strstart(filename, "COM", NULL)) {
2163
        return qemu_chr_open_win(filename);
2164
    } else
2165
    if (strstart(filename, "pipe:", &p)) {
2166
        return qemu_chr_open_win_pipe(p);
2167
    } else
2168
    if (strstart(filename, "file:", &p)) {
2169
        return qemu_chr_open_win_file_out(p);
2170
    }
2171
#endif
2172
    {
2173
        return NULL;
2174
    }
2175
}
2176

    
2177
void qemu_chr_close(CharDriverState *chr)
2178
{
2179
    if (chr->chr_close)
2180
        chr->chr_close(chr);
2181
}
2182

    
2183
/***********************************************************/
2184
/* network device redirectors */
2185

    
2186
void hex_dump(FILE *f, const uint8_t *buf, int size)
2187
{
2188
    int len, i, j, c;
2189

    
2190
    for(i=0;i<size;i+=16) {
2191
        len = size - i;
2192
        if (len > 16)
2193
            len = 16;
2194
        fprintf(f, "%08x ", i);
2195
        for(j=0;j<16;j++) {
2196
            if (j < len)
2197
                fprintf(f, " %02x", buf[i+j]);
2198
            else
2199
                fprintf(f, "   ");
2200
        }
2201
        fprintf(f, " ");
2202
        for(j=0;j<len;j++) {
2203
            c = buf[i+j];
2204
            if (c < ' ' || c > '~')
2205
                c = '.';
2206
            fprintf(f, "%c", c);
2207
        }
2208
        fprintf(f, "\n");
2209
    }
2210
}
2211

    
2212
static int parse_macaddr(uint8_t *macaddr, const char *p)
2213
{
2214
    int i;
2215
    for(i = 0; i < 6; i++) {
2216
        macaddr[i] = strtol(p, (char **)&p, 16);
2217
        if (i == 5) {
2218
            if (*p != '\0') 
2219
                return -1;
2220
        } else {
2221
            if (*p != ':') 
2222
                return -1;
2223
            p++;
2224
        }
2225
    }
2226
    return 0;
2227
}
2228

    
2229
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2230
{
2231
    const char *p, *p1;
2232
    int len;
2233
    p = *pp;
2234
    p1 = strchr(p, sep);
2235
    if (!p1)
2236
        return -1;
2237
    len = p1 - p;
2238
    p1++;
2239
    if (buf_size > 0) {
2240
        if (len > buf_size - 1)
2241
            len = buf_size - 1;
2242
        memcpy(buf, p, len);
2243
        buf[len] = '\0';
2244
    }
2245
    *pp = p1;
2246
    return 0;
2247
}
2248

    
2249
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2250
{
2251
    char buf[512];
2252
    struct hostent *he;
2253
    const char *p, *r;
2254
    int port;
2255

    
2256
    p = str;
2257
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2258
        return -1;
2259
    saddr->sin_family = AF_INET;
2260
    if (buf[0] == '\0') {
2261
        saddr->sin_addr.s_addr = 0;
2262
    } else {
2263
        if (isdigit(buf[0])) {
2264
            if (!inet_aton(buf, &saddr->sin_addr))
2265
                return -1;
2266
        } else {
2267
            if ((he = gethostbyname(buf)) == NULL)
2268
                return - 1;
2269
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2270
        }
2271
    }
2272
    port = strtol(p, (char **)&r, 0);
2273
    if (r == p)
2274
        return -1;
2275
    saddr->sin_port = htons(port);
2276
    return 0;
2277
}
2278

    
2279
/* find or alloc a new VLAN */
2280
VLANState *qemu_find_vlan(int id)
2281
{
2282
    VLANState **pvlan, *vlan;
2283
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2284
        if (vlan->id == id)
2285
            return vlan;
2286
    }
2287
    vlan = qemu_mallocz(sizeof(VLANState));
2288
    if (!vlan)
2289
        return NULL;
2290
    vlan->id = id;
2291
    vlan->next = NULL;
2292
    pvlan = &first_vlan;
2293
    while (*pvlan != NULL)
2294
        pvlan = &(*pvlan)->next;
2295
    *pvlan = vlan;
2296
    return vlan;
2297
}
2298

    
2299
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2300
                                      IOReadHandler *fd_read,
2301
                                      IOCanRWHandler *fd_can_read,
2302
                                      void *opaque)
2303
{
2304
    VLANClientState *vc, **pvc;
2305
    vc = qemu_mallocz(sizeof(VLANClientState));
2306
    if (!vc)
2307
        return NULL;
2308
    vc->fd_read = fd_read;
2309
    vc->fd_can_read = fd_can_read;
2310
    vc->opaque = opaque;
2311
    vc->vlan = vlan;
2312

    
2313
    vc->next = NULL;
2314
    pvc = &vlan->first_client;
2315
    while (*pvc != NULL)
2316
        pvc = &(*pvc)->next;
2317
    *pvc = vc;
2318
    return vc;
2319
}
2320

    
2321
int qemu_can_send_packet(VLANClientState *vc1)
2322
{
2323
    VLANState *vlan = vc1->vlan;
2324
    VLANClientState *vc;
2325

    
2326
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2327
        if (vc != vc1) {
2328
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2329
                return 0;
2330
        }
2331
    }
2332
    return 1;
2333
}
2334

    
2335
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2336
{
2337
    VLANState *vlan = vc1->vlan;
2338
    VLANClientState *vc;
2339

    
2340
#if 0
2341
    printf("vlan %d send:\n", vlan->id);
2342
    hex_dump(stdout, buf, size);
2343
#endif
2344
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2345
        if (vc != vc1) {
2346
            vc->fd_read(vc->opaque, buf, size);
2347
        }
2348
    }
2349
}
2350

    
2351
#if defined(CONFIG_SLIRP)
2352

    
2353
/* slirp network adapter */
2354

    
2355
static int slirp_inited;
2356
static VLANClientState *slirp_vc;
2357

    
2358
int slirp_can_output(void)
2359
{
2360
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
2361
}
2362

    
2363
void slirp_output(const uint8_t *pkt, int pkt_len)
2364
{
2365
#if 0
2366
    printf("slirp output:\n");
2367
    hex_dump(stdout, pkt, pkt_len);
2368
#endif
2369
    if (!slirp_vc)
2370
        return;
2371
    qemu_send_packet(slirp_vc, pkt, pkt_len);
2372
}
2373

    
2374
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2375
{
2376
#if 0
2377
    printf("slirp input:\n");
2378
    hex_dump(stdout, buf, size);
2379
#endif
2380
    slirp_input(buf, size);
2381
}
2382

    
2383
static int net_slirp_init(VLANState *vlan)
2384
{
2385
    if (!slirp_inited) {
2386
        slirp_inited = 1;
2387
        slirp_init();
2388
    }
2389
    slirp_vc = qemu_new_vlan_client(vlan, 
2390
                                    slirp_receive, NULL, NULL);
2391
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2392
    return 0;
2393
}
2394

    
2395
static void net_slirp_redir(const char *redir_str)
2396
{
2397
    int is_udp;
2398
    char buf[256], *r;
2399
    const char *p;
2400
    struct in_addr guest_addr;
2401
    int host_port, guest_port;
2402
    
2403
    if (!slirp_inited) {
2404
        slirp_inited = 1;
2405
        slirp_init();
2406
    }
2407

    
2408
    p = redir_str;
2409
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2410
        goto fail;
2411
    if (!strcmp(buf, "tcp")) {
2412
        is_udp = 0;
2413
    } else if (!strcmp(buf, "udp")) {
2414
        is_udp = 1;
2415
    } else {
2416
        goto fail;
2417
    }
2418

    
2419
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2420
        goto fail;
2421
    host_port = strtol(buf, &r, 0);
2422
    if (r == buf)
2423
        goto fail;
2424

    
2425
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2426
        goto fail;
2427
    if (buf[0] == '\0') {
2428
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
2429
    }
2430
    if (!inet_aton(buf, &guest_addr))
2431
        goto fail;
2432
    
2433
    guest_port = strtol(p, &r, 0);
2434
    if (r == p)
2435
        goto fail;
2436
    
2437
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2438
        fprintf(stderr, "qemu: could not set up redirection\n");
2439
        exit(1);
2440
    }
2441
    return;
2442
 fail:
2443
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2444
    exit(1);
2445
}
2446
    
2447
#ifndef _WIN32
2448

    
2449
char smb_dir[1024];
2450

    
2451
static void smb_exit(void)
2452
{
2453
    DIR *d;
2454
    struct dirent *de;
2455
    char filename[1024];
2456

    
2457
    /* erase all the files in the directory */
2458
    d = opendir(smb_dir);
2459
    for(;;) {
2460
        de = readdir(d);
2461
        if (!de)
2462
            break;
2463
        if (strcmp(de->d_name, ".") != 0 &&
2464
            strcmp(de->d_name, "..") != 0) {
2465
            snprintf(filename, sizeof(filename), "%s/%s", 
2466
                     smb_dir, de->d_name);
2467
            unlink(filename);
2468
        }
2469
    }
2470
    closedir(d);
2471
    rmdir(smb_dir);
2472
}
2473

    
2474
/* automatic user mode samba server configuration */
2475
void net_slirp_smb(const char *exported_dir)
2476
{
2477
    char smb_conf[1024];
2478
    char smb_cmdline[1024];
2479
    FILE *f;
2480

    
2481
    if (!slirp_inited) {
2482
        slirp_inited = 1;
2483
        slirp_init();
2484
    }
2485

    
2486
    /* XXX: better tmp dir construction */
2487
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2488
    if (mkdir(smb_dir, 0700) < 0) {
2489
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2490
        exit(1);
2491
    }
2492
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2493
    
2494
    f = fopen(smb_conf, "w");
2495
    if (!f) {
2496
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2497
        exit(1);
2498
    }
2499
    fprintf(f, 
2500
            "[global]\n"
2501
            "private dir=%s\n"
2502
            "smb ports=0\n"
2503
            "socket address=127.0.0.1\n"
2504
            "pid directory=%s\n"
2505
            "lock directory=%s\n"
2506
            "log file=%s/log.smbd\n"
2507
            "smb passwd file=%s/smbpasswd\n"
2508
            "security = share\n"
2509
            "[qemu]\n"
2510
            "path=%s\n"
2511
            "read only=no\n"
2512
            "guest ok=yes\n",
2513
            smb_dir,
2514
            smb_dir,
2515
            smb_dir,
2516
            smb_dir,
2517
            smb_dir,
2518
            exported_dir
2519
            );
2520
    fclose(f);
2521
    atexit(smb_exit);
2522

    
2523
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2524
             smb_conf);
2525
    
2526
    slirp_add_exec(0, smb_cmdline, 4, 139);
2527
}
2528

    
2529
#endif /* !defined(_WIN32) */
2530

    
2531
#endif /* CONFIG_SLIRP */
2532

    
2533
#if !defined(_WIN32)
2534

    
2535
typedef struct TAPState {
2536
    VLANClientState *vc;
2537
    int fd;
2538
} TAPState;
2539

    
2540
static void tap_receive(void *opaque, const uint8_t *buf, int size)
2541
{
2542
    TAPState *s = opaque;
2543
    int ret;
2544
    for(;;) {
2545
        ret = write(s->fd, buf, size);
2546
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2547
        } else {
2548
            break;
2549
        }
2550
    }
2551
}
2552

    
2553
static void tap_send(void *opaque)
2554
{
2555
    TAPState *s = opaque;
2556
    uint8_t buf[4096];
2557
    int size;
2558

    
2559
    size = read(s->fd, buf, sizeof(buf));
2560
    if (size > 0) {
2561
        qemu_send_packet(s->vc, buf, size);
2562
    }
2563
}
2564

    
2565
/* fd support */
2566

    
2567
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2568
{
2569
    TAPState *s;
2570

    
2571
    s = qemu_mallocz(sizeof(TAPState));
2572
    if (!s)
2573
        return NULL;
2574
    s->fd = fd;
2575
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2576
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2577
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2578
    return s;
2579
}
2580

    
2581
#ifdef _BSD
2582
static int tap_open(char *ifname, int ifname_size)
2583
{
2584
    int fd;
2585
    char *dev;
2586
    struct stat s;
2587

    
2588
    fd = open("/dev/tap", O_RDWR);
2589
    if (fd < 0) {
2590
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2591
        return -1;
2592
    }
2593

    
2594
    fstat(fd, &s);
2595
    dev = devname(s.st_rdev, S_IFCHR);
2596
    pstrcpy(ifname, ifname_size, dev);
2597

    
2598
    fcntl(fd, F_SETFL, O_NONBLOCK);
2599
    return fd;
2600
}
2601
#elif defined(__sun__)
2602
static int tap_open(char *ifname, int ifname_size)
2603
{
2604
    fprintf(stderr, "warning: tap_open not yet implemented\n");
2605
    return -1;
2606
}
2607
#else
2608
static int tap_open(char *ifname, int ifname_size)
2609
{
2610
    struct ifreq ifr;
2611
    int fd, ret;
2612
    
2613
    fd = open("/dev/net/tun", O_RDWR);
2614
    if (fd < 0) {
2615
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2616
        return -1;
2617
    }
2618
    memset(&ifr, 0, sizeof(ifr));
2619
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2620
    if (ifname[0] != '\0')
2621
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2622
    else
2623
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2624
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2625
    if (ret != 0) {
2626
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2627
        close(fd);
2628
        return -1;
2629
    }
2630
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
2631
    fcntl(fd, F_SETFL, O_NONBLOCK);
2632
    return fd;
2633
}
2634
#endif
2635

    
2636
static int net_tap_init(VLANState *vlan, const char *ifname1,
2637
                        const char *setup_script)
2638
{
2639
    TAPState *s;
2640
    int pid, status, fd;
2641
    char *args[3];
2642
    char **parg;
2643
    char ifname[128];
2644

    
2645
    if (ifname1 != NULL)
2646
        pstrcpy(ifname, sizeof(ifname), ifname1);
2647
    else
2648
        ifname[0] = '\0';
2649
    fd = tap_open(ifname, sizeof(ifname));
2650
    if (fd < 0)
2651
        return -1;
2652

    
2653
    if (!setup_script)
2654
        setup_script = "";
2655
    if (setup_script[0] != '\0') {
2656
        /* try to launch network init script */
2657
        pid = fork();
2658
        if (pid >= 0) {
2659
            if (pid == 0) {
2660
                parg = args;
2661
                *parg++ = (char *)setup_script;
2662
                *parg++ = ifname;
2663
                *parg++ = NULL;
2664
                execv(setup_script, args);
2665
                _exit(1);
2666
            }
2667
            while (waitpid(pid, &status, 0) != pid);
2668
            if (!WIFEXITED(status) ||
2669
                WEXITSTATUS(status) != 0) {
2670
                fprintf(stderr, "%s: could not launch network script\n",
2671
                        setup_script);
2672
                return -1;
2673
            }
2674
        }
2675
    }
2676
    s = net_tap_fd_init(vlan, fd);
2677
    if (!s)
2678
        return -1;
2679
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
2680
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
2681
    return 0;
2682
}
2683

    
2684
#endif /* !_WIN32 */
2685

    
2686
/* network connection */
2687
typedef struct NetSocketState {
2688
    VLANClientState *vc;
2689
    int fd;
2690
    int state; /* 0 = getting length, 1 = getting data */
2691
    int index;
2692
    int packet_len;
2693
    uint8_t buf[4096];
2694
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2695
} NetSocketState;
2696

    
2697
typedef struct NetSocketListenState {
2698
    VLANState *vlan;
2699
    int fd;
2700
} NetSocketListenState;
2701

    
2702
/* XXX: we consider we can send the whole packet without blocking */
2703
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2704
{
2705
    NetSocketState *s = opaque;
2706
    uint32_t len;
2707
    len = htonl(size);
2708

    
2709
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2710
    send_all(s->fd, buf, size);
2711
}
2712

    
2713
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2714
{
2715
    NetSocketState *s = opaque;
2716
    sendto(s->fd, buf, size, 0, 
2717
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2718
}
2719

    
2720
static void net_socket_send(void *opaque)
2721
{
2722
    NetSocketState *s = opaque;
2723
    int l, size, err;
2724
    uint8_t buf1[4096];
2725
    const uint8_t *buf;
2726

    
2727
    size = recv(s->fd, buf1, sizeof(buf1), 0);
2728
    if (size < 0) {
2729
        err = socket_error();
2730
        if (err != EWOULDBLOCK) 
2731
            goto eoc;
2732
    } else if (size == 0) {
2733
        /* end of connection */
2734
    eoc:
2735
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2736
        closesocket(s->fd);
2737
        return;
2738
    }
2739
    buf = buf1;
2740
    while (size > 0) {
2741
        /* reassemble a packet from the network */
2742
        switch(s->state) {
2743
        case 0:
2744
            l = 4 - s->index;
2745
            if (l > size)
2746
                l = size;
2747
            memcpy(s->buf + s->index, buf, l);
2748
            buf += l;
2749
            size -= l;
2750
            s->index += l;
2751
            if (s->index == 4) {
2752
                /* got length */
2753
                s->packet_len = ntohl(*(uint32_t *)s->buf);
2754
                s->index = 0;
2755
                s->state = 1;
2756
            }
2757
            break;
2758
        case 1:
2759
            l = s->packet_len - s->index;
2760
            if (l > size)
2761
                l = size;
2762
            memcpy(s->buf + s->index, buf, l);
2763
            s->index += l;
2764
            buf += l;
2765
            size -= l;
2766
            if (s->index >= s->packet_len) {
2767
                qemu_send_packet(s->vc, s->buf, s->packet_len);
2768
                s->index = 0;
2769
                s->state = 0;
2770
            }
2771
            break;
2772
        }
2773
    }
2774
}
2775

    
2776
static void net_socket_send_dgram(void *opaque)
2777
{
2778
    NetSocketState *s = opaque;
2779
    int size;
2780

    
2781
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2782
    if (size < 0) 
2783
        return;
2784
    if (size == 0) {
2785
        /* end of connection */
2786
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2787
        return;
2788
    }
2789
    qemu_send_packet(s->vc, s->buf, size);
2790
}
2791

    
2792
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2793
{
2794
    struct ip_mreq imr;
2795
    int fd;
2796
    int val, ret;
2797
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2798
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2799
                inet_ntoa(mcastaddr->sin_addr), 
2800
                (int)ntohl(mcastaddr->sin_addr.s_addr));
2801
        return -1;
2802

    
2803
    }
2804
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2805
    if (fd < 0) {
2806
        perror("socket(PF_INET, SOCK_DGRAM)");
2807
        return -1;
2808
    }
2809

    
2810
    val = 1;
2811
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
2812
                   (const char *)&val, sizeof(val));
2813
    if (ret < 0) {
2814
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2815
        goto fail;
2816
    }
2817

    
2818
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2819
    if (ret < 0) {
2820
        perror("bind");
2821
        goto fail;
2822
    }
2823
    
2824
    /* Add host to multicast group */
2825
    imr.imr_multiaddr = mcastaddr->sin_addr;
2826
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
2827

    
2828
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
2829
                     (const char *)&imr, sizeof(struct ip_mreq));
2830
    if (ret < 0) {
2831
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
2832
        goto fail;
2833
    }
2834

    
2835
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2836
    val = 1;
2837
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
2838
                   (const char *)&val, sizeof(val));
2839
    if (ret < 0) {
2840
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2841
        goto fail;
2842
    }
2843

    
2844
    socket_set_nonblock(fd);
2845
    return fd;
2846
fail:
2847
    if (fd>=0) close(fd);
2848
    return -1;
2849
}
2850

    
2851
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
2852
                                          int is_connected)
2853
{
2854
    struct sockaddr_in saddr;
2855
    int newfd;
2856
    socklen_t saddr_len;
2857
    NetSocketState *s;
2858

    
2859
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2860
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
2861
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
2862
     */
2863

    
2864
    if (is_connected) {
2865
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2866
            /* must be bound */
2867
            if (saddr.sin_addr.s_addr==0) {
2868
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2869
                        fd);
2870
                return NULL;
2871
            }
2872
            /* clone dgram socket */
2873
            newfd = net_socket_mcast_create(&saddr);
2874
            if (newfd < 0) {
2875
                /* error already reported by net_socket_mcast_create() */
2876
                close(fd);
2877
                return NULL;
2878
            }
2879
            /* clone newfd to fd, close newfd */
2880
            dup2(newfd, fd);
2881
            close(newfd);
2882
        
2883
        } else {
2884
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2885
                    fd, strerror(errno));
2886
            return NULL;
2887
        }
2888
    }
2889

    
2890
    s = qemu_mallocz(sizeof(NetSocketState));
2891
    if (!s)
2892
        return NULL;
2893
    s->fd = fd;
2894

    
2895
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2896
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2897

    
2898
    /* mcast: save bound address as dst */
2899
    if (is_connected) s->dgram_dst=saddr;
2900

    
2901
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2902
            "socket: fd=%d (%s mcast=%s:%d)", 
2903
            fd, is_connected? "cloned" : "",
2904
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2905
    return s;
2906
}
2907

    
2908
static void net_socket_connect(void *opaque)
2909
{
2910
    NetSocketState *s = opaque;
2911
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2912
}
2913

    
2914
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
2915
                                          int is_connected)
2916
{
2917
    NetSocketState *s;
2918
    s = qemu_mallocz(sizeof(NetSocketState));
2919
    if (!s)
2920
        return NULL;
2921
    s->fd = fd;
2922
    s->vc = qemu_new_vlan_client(vlan, 
2923
                                 net_socket_receive, NULL, s);
2924
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2925
             "socket: fd=%d", fd);
2926
    if (is_connected) {
2927
        net_socket_connect(s);
2928
    } else {
2929
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2930
    }
2931
    return s;
2932
}
2933

    
2934
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
2935
                                          int is_connected)
2936
{
2937
    int so_type=-1, optlen=sizeof(so_type);
2938

    
2939
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2940
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2941
        return NULL;
2942
    }
2943
    switch(so_type) {
2944
    case SOCK_DGRAM:
2945
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
2946
    case SOCK_STREAM:
2947
        return net_socket_fd_init_stream(vlan, fd, is_connected);
2948
    default:
2949
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2950
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2951
        return net_socket_fd_init_stream(vlan, fd, is_connected);
2952
    }
2953
    return NULL;
2954
}
2955

    
2956
static void net_socket_accept(void *opaque)
2957
{
2958
    NetSocketListenState *s = opaque;    
2959
    NetSocketState *s1;
2960
    struct sockaddr_in saddr;
2961
    socklen_t len;
2962
    int fd;
2963

    
2964
    for(;;) {
2965
        len = sizeof(saddr);
2966
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2967
        if (fd < 0 && errno != EINTR) {
2968
            return;
2969
        } else if (fd >= 0) {
2970
            break;
2971
        }
2972
    }
2973
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
2974
    if (!s1) {
2975
        close(fd);
2976
    } else {
2977
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2978
                 "socket: connection from %s:%d", 
2979
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2980
    }
2981
}
2982

    
2983
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2984
{
2985
    NetSocketListenState *s;
2986
    int fd, val, ret;
2987
    struct sockaddr_in saddr;
2988

    
2989
    if (parse_host_port(&saddr, host_str) < 0)
2990
        return -1;
2991
    
2992
    s = qemu_mallocz(sizeof(NetSocketListenState));
2993
    if (!s)
2994
        return -1;
2995

    
2996
    fd = socket(PF_INET, SOCK_STREAM, 0);
2997
    if (fd < 0) {
2998
        perror("socket");
2999
        return -1;
3000
    }
3001
    socket_set_nonblock(fd);
3002

    
3003
    /* allow fast reuse */
3004
    val = 1;
3005
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3006
    
3007
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3008
    if (ret < 0) {
3009
        perror("bind");
3010
        return -1;
3011
    }
3012
    ret = listen(fd, 0);
3013
    if (ret < 0) {
3014
        perror("listen");
3015
        return -1;
3016
    }
3017
    s->vlan = vlan;
3018
    s->fd = fd;
3019
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3020
    return 0;
3021
}
3022

    
3023
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3024
{
3025
    NetSocketState *s;
3026
    int fd, connected, ret, err;
3027
    struct sockaddr_in saddr;
3028

    
3029
    if (parse_host_port(&saddr, host_str) < 0)
3030
        return -1;
3031

    
3032
    fd = socket(PF_INET, SOCK_STREAM, 0);
3033
    if (fd < 0) {
3034
        perror("socket");
3035
        return -1;
3036
    }
3037
    socket_set_nonblock(fd);
3038

    
3039
    connected = 0;
3040
    for(;;) {
3041
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3042
        if (ret < 0) {
3043
            err = socket_error();
3044
            if (err == EINTR || err == EWOULDBLOCK) {
3045
            } else if (err == EINPROGRESS) {
3046
                break;
3047
            } else {
3048
                perror("connect");
3049
                closesocket(fd);
3050
                return -1;
3051
            }
3052
        } else {
3053
            connected = 1;
3054
            break;
3055
        }
3056
    }
3057
    s = net_socket_fd_init(vlan, fd, connected);
3058
    if (!s)
3059
        return -1;
3060
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3061
             "socket: connect to %s:%d", 
3062
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3063
    return 0;
3064
}
3065

    
3066
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3067
{
3068
    NetSocketState *s;
3069
    int fd;
3070
    struct sockaddr_in saddr;
3071

    
3072
    if (parse_host_port(&saddr, host_str) < 0)
3073
        return -1;
3074

    
3075

    
3076
    fd = net_socket_mcast_create(&saddr);
3077
    if (fd < 0)
3078
        return -1;
3079

    
3080
    s = net_socket_fd_init(vlan, fd, 0);
3081
    if (!s)
3082
        return -1;
3083

    
3084
    s->dgram_dst = saddr;
3085
    
3086
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3087
             "socket: mcast=%s:%d", 
3088
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3089
    return 0;
3090

    
3091
}
3092

    
3093
static int get_param_value(char *buf, int buf_size,
3094
                           const char *tag, const char *str)
3095
{
3096
    const char *p;
3097
    char *q;
3098
    char option[128];
3099

    
3100
    p = str;
3101
    for(;;) {
3102
        q = option;
3103
        while (*p != '\0' && *p != '=') {
3104
            if ((q - option) < sizeof(option) - 1)
3105
                *q++ = *p;
3106
            p++;
3107
        }
3108
        *q = '\0';
3109
        if (*p != '=')
3110
            break;
3111
        p++;
3112
        if (!strcmp(tag, option)) {
3113
            q = buf;
3114
            while (*p != '\0' && *p != ',') {
3115
                if ((q - buf) < buf_size - 1)
3116
                    *q++ = *p;
3117
                p++;
3118
            }
3119
            *q = '\0';
3120
            return q - buf;
3121
        } else {
3122
            while (*p != '\0' && *p != ',') {
3123
                p++;
3124
            }
3125
        }
3126
        if (*p != ',')
3127
            break;
3128
        p++;
3129
    }
3130
    return 0;
3131
}
3132

    
3133
int net_client_init(const char *str)
3134
{
3135
    const char *p;
3136
    char *q;
3137
    char device[64];
3138
    char buf[1024];
3139
    int vlan_id, ret;
3140
    VLANState *vlan;
3141

    
3142
    p = str;
3143
    q = device;
3144
    while (*p != '\0' && *p != ',') {
3145
        if ((q - device) < sizeof(device) - 1)
3146
            *q++ = *p;
3147
        p++;
3148
    }
3149
    *q = '\0';
3150
    if (*p == ',')
3151
        p++;
3152
    vlan_id = 0;
3153
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3154
        vlan_id = strtol(buf, NULL, 0);
3155
    }
3156
    vlan = qemu_find_vlan(vlan_id);
3157
    if (!vlan) {
3158
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3159
        return -1;
3160
    }
3161
    if (!strcmp(device, "nic")) {
3162
        NICInfo *nd;
3163
        uint8_t *macaddr;
3164

    
3165
        if (nb_nics >= MAX_NICS) {
3166
            fprintf(stderr, "Too Many NICs\n");
3167
            return -1;
3168
        }
3169
        nd = &nd_table[nb_nics];
3170
        macaddr = nd->macaddr;
3171
        macaddr[0] = 0x52;
3172
        macaddr[1] = 0x54;
3173
        macaddr[2] = 0x00;
3174
        macaddr[3] = 0x12;
3175
        macaddr[4] = 0x34;
3176
        macaddr[5] = 0x56 + nb_nics;
3177

    
3178
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3179
            if (parse_macaddr(macaddr, buf) < 0) {
3180
                fprintf(stderr, "invalid syntax for ethernet address\n");
3181
                return -1;
3182
            }
3183
        }
3184
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3185
            nd->model = strdup(buf);
3186
        }
3187
        nd->vlan = vlan;
3188
        nb_nics++;
3189
        ret = 0;
3190
    } else
3191
    if (!strcmp(device, "none")) {
3192
        /* does nothing. It is needed to signal that no network cards
3193
           are wanted */
3194
        ret = 0;
3195
    } else
3196
#ifdef CONFIG_SLIRP
3197
    if (!strcmp(device, "user")) {
3198
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3199
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3200
        }
3201
        ret = net_slirp_init(vlan);
3202
    } else
3203
#endif
3204
#ifdef _WIN32
3205
    if (!strcmp(device, "tap")) {
3206
        char ifname[64];
3207
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3208
            fprintf(stderr, "tap: no interface name\n");
3209
            return -1;
3210
        }
3211
        ret = tap_win32_init(vlan, ifname);
3212
    } else
3213
#else
3214
    if (!strcmp(device, "tap")) {
3215
        char ifname[64];
3216
        char setup_script[1024];
3217
        int fd;
3218
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3219
            fd = strtol(buf, NULL, 0);
3220
            ret = -1;
3221
            if (net_tap_fd_init(vlan, fd))
3222
                ret = 0;
3223
        } else {
3224
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3225
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3226
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3227
            }
3228
            ret = net_tap_init(vlan, ifname, setup_script);
3229
        }
3230
    } else
3231
#endif
3232
    if (!strcmp(device, "socket")) {
3233
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3234
            int fd;
3235
            fd = strtol(buf, NULL, 0);
3236
            ret = -1;
3237
            if (net_socket_fd_init(vlan, fd, 1))
3238
                ret = 0;
3239
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3240
            ret = net_socket_listen_init(vlan, buf);
3241
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3242
            ret = net_socket_connect_init(vlan, buf);
3243
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3244
            ret = net_socket_mcast_init(vlan, buf);
3245
        } else {
3246
            fprintf(stderr, "Unknown socket options: %s\n", p);
3247
            return -1;
3248
        }
3249
    } else
3250
    {
3251
        fprintf(stderr, "Unknown network device: %s\n", device);
3252
        return -1;
3253
    }
3254
    if (ret < 0) {
3255
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3256
    }
3257
    
3258
    return ret;
3259
}
3260

    
3261
void do_info_network(void)
3262
{
3263
    VLANState *vlan;
3264
    VLANClientState *vc;
3265

    
3266
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3267
        term_printf("VLAN %d devices:\n", vlan->id);
3268
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3269
            term_printf("  %s\n", vc->info_str);
3270
    }
3271
}
3272
 
3273
/***********************************************************/
3274
/* USB devices */
3275

    
3276
static USBPort *used_usb_ports;
3277
static USBPort *free_usb_ports;
3278

    
3279
/* ??? Maybe change this to register a hub to keep track of the topology.  */
3280
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3281
                            usb_attachfn attach)
3282
{
3283
    port->opaque = opaque;
3284
    port->index = index;
3285
    port->attach = attach;
3286
    port->next = free_usb_ports;
3287
    free_usb_ports = port;
3288
}
3289

    
3290
static int usb_device_add(const char *devname)
3291
{
3292
    const char *p;
3293
    USBDevice *dev;
3294
    USBPort *port;
3295

    
3296
    if (!free_usb_ports)
3297
        return -1;
3298

    
3299
    if (strstart(devname, "host:", &p)) {
3300
        dev = usb_host_device_open(p);
3301
    } else if (!strcmp(devname, "mouse")) {
3302
        dev = usb_mouse_init();
3303
    } else if (!strcmp(devname, "tablet")) {
3304
        dev = usb_tablet_init();
3305
    } else if (strstart(devname, "disk:", &p)) {
3306
        dev = usb_msd_init(p);
3307
    } else {
3308
        return -1;
3309
    }
3310
    if (!dev)
3311
        return -1;
3312

    
3313
    /* Find a USB port to add the device to.  */
3314
    port = free_usb_ports;
3315
    if (!port->next) {
3316
        USBDevice *hub;
3317

    
3318
        /* Create a new hub and chain it on.  */
3319
        free_usb_ports = NULL;
3320
        port->next = used_usb_ports;
3321
        used_usb_ports = port;
3322

    
3323
        hub = usb_hub_init(VM_USB_HUB_SIZE);
3324
        usb_attach(port, hub);
3325
        port = free_usb_ports;
3326
    }
3327

    
3328
    free_usb_ports = port->next;
3329
    port->next = used_usb_ports;
3330
    used_usb_ports = port;
3331
    usb_attach(port, dev);
3332
    return 0;
3333
}
3334

    
3335
static int usb_device_del(const char *devname)
3336
{
3337
    USBPort *port;
3338
    USBPort **lastp;
3339
    int bus_num, addr;
3340
    const char *p;
3341

    
3342
    if (!used_usb_ports)
3343
        return -1;
3344

    
3345
    p = strchr(devname, '.');
3346
    if (!p) 
3347
        return -1;
3348
    bus_num = strtoul(devname, NULL, 0);
3349
    addr = strtoul(p + 1, NULL, 0);
3350
    if (bus_num != 0)
3351
        return -1;
3352

    
3353
    lastp = &used_usb_ports;
3354
    port = used_usb_ports;
3355
    while (port && port->dev->addr != addr) {
3356
        lastp = &port->next;
3357
        port = port->next;
3358
    }
3359

    
3360
    if (!port)
3361
        return -1;
3362

    
3363
    *lastp = port->next;
3364
    usb_attach(port, NULL);
3365
    port->next = free_usb_ports;
3366
    free_usb_ports = port;
3367
    return 0;
3368
}
3369

    
3370
void do_usb_add(const char *devname)
3371
{
3372
    int ret;
3373
    ret = usb_device_add(devname);
3374
    if (ret < 0) 
3375
        term_printf("Could not add USB device '%s'\n", devname);
3376
}
3377

    
3378
void do_usb_del(const char *devname)
3379
{
3380
    int ret;
3381
    ret = usb_device_del(devname);
3382
    if (ret < 0) 
3383
        term_printf("Could not remove USB device '%s'\n", devname);
3384
}
3385

    
3386
void usb_info(void)
3387
{
3388
    USBDevice *dev;
3389
    USBPort *port;
3390
    const char *speed_str;
3391

    
3392
    if (!usb_enabled) {
3393
        term_printf("USB support not enabled\n");
3394
        return;
3395
    }
3396

    
3397
    for (port = used_usb_ports; port; port = port->next) {
3398
        dev = port->dev;
3399
        if (!dev)
3400
            continue;
3401
        switch(dev->speed) {
3402
        case USB_SPEED_LOW: 
3403
            speed_str = "1.5"; 
3404
            break;
3405
        case USB_SPEED_FULL: 
3406
            speed_str = "12"; 
3407
            break;
3408
        case USB_SPEED_HIGH: 
3409
            speed_str = "480"; 
3410
            break;
3411
        default:
3412
            speed_str = "?"; 
3413
            break;
3414
        }
3415
        term_printf("  Device %d.%d, speed %s Mb/s\n", 
3416
                    0, dev->addr, speed_str);
3417
    }
3418
}
3419

    
3420
/***********************************************************/
3421
/* pid file */
3422

    
3423
static char *pid_filename;
3424

    
3425
/* Remove PID file. Called on normal exit */
3426

    
3427
static void remove_pidfile(void) 
3428
{
3429
    unlink (pid_filename);
3430
}
3431

    
3432
static void create_pidfile(const char *filename)
3433
{
3434
    struct stat pidstat;
3435
    FILE *f;
3436

    
3437
    /* Try to write our PID to the named file */
3438
    if (stat(filename, &pidstat) < 0) {
3439
        if (errno == ENOENT) {
3440
            if ((f = fopen (filename, "w")) == NULL) {
3441
                perror("Opening pidfile");
3442
                exit(1);
3443
            }
3444
            fprintf(f, "%d\n", getpid());
3445
            fclose(f);
3446
            pid_filename = qemu_strdup(filename);
3447
            if (!pid_filename) {
3448
                fprintf(stderr, "Could not save PID filename");
3449
                exit(1);
3450
            }
3451
            atexit(remove_pidfile);
3452
        }
3453
    } else {
3454
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
3455
                filename);
3456
        exit(1);
3457
    }
3458
}
3459

    
3460
/***********************************************************/
3461
/* dumb display */
3462

    
3463
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3464
{
3465
}
3466

    
3467
static void dumb_resize(DisplayState *ds, int w, int h)
3468
{
3469
}
3470

    
3471
static void dumb_refresh(DisplayState *ds)
3472
{
3473
    vga_hw_update();
3474
}
3475

    
3476
void dumb_display_init(DisplayState *ds)
3477
{
3478
    ds->data = NULL;
3479
    ds->linesize = 0;
3480
    ds->depth = 0;
3481
    ds->dpy_update = dumb_update;
3482
    ds->dpy_resize = dumb_resize;
3483
    ds->dpy_refresh = dumb_refresh;
3484
}
3485

    
3486
#if !defined(CONFIG_SOFTMMU)
3487
/***********************************************************/
3488
/* cpu signal handler */
3489
static void host_segv_handler(int host_signum, siginfo_t *info, 
3490
                              void *puc)
3491
{
3492
    if (cpu_signal_handler(host_signum, info, puc))
3493
        return;
3494
    if (stdio_nb_clients > 0)
3495
        term_exit();
3496
    abort();
3497
}
3498
#endif
3499

    
3500
/***********************************************************/
3501
/* I/O handling */
3502

    
3503
#define MAX_IO_HANDLERS 64
3504

    
3505
typedef struct IOHandlerRecord {
3506
    int fd;
3507
    IOCanRWHandler *fd_read_poll;
3508
    IOHandler *fd_read;
3509
    IOHandler *fd_write;
3510
    void *opaque;
3511
    /* temporary data */
3512
    struct pollfd *ufd;
3513
    struct IOHandlerRecord *next;
3514
} IOHandlerRecord;
3515

    
3516
static IOHandlerRecord *first_io_handler;
3517

    
3518
/* XXX: fd_read_poll should be suppressed, but an API change is
3519
   necessary in the character devices to suppress fd_can_read(). */
3520
int qemu_set_fd_handler2(int fd, 
3521
                         IOCanRWHandler *fd_read_poll, 
3522
                         IOHandler *fd_read, 
3523
                         IOHandler *fd_write, 
3524
                         void *opaque)
3525
{
3526
    IOHandlerRecord **pioh, *ioh;
3527

    
3528
    if (!fd_read && !fd_write) {
3529
        pioh = &first_io_handler;
3530
        for(;;) {
3531
            ioh = *pioh;
3532
            if (ioh == NULL)
3533
                break;
3534
            if (ioh->fd == fd) {
3535
                *pioh = ioh->next;
3536
                qemu_free(ioh);
3537
                break;
3538
            }
3539
            pioh = &ioh->next;
3540
        }
3541
    } else {
3542
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3543
            if (ioh->fd == fd)
3544
                goto found;
3545
        }
3546
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3547
        if (!ioh)
3548
            return -1;
3549
        ioh->next = first_io_handler;
3550
        first_io_handler = ioh;
3551
    found:
3552
        ioh->fd = fd;
3553
        ioh->fd_read_poll = fd_read_poll;
3554
        ioh->fd_read = fd_read;
3555
        ioh->fd_write = fd_write;
3556
        ioh->opaque = opaque;
3557
    }
3558
    return 0;
3559
}
3560

    
3561
int qemu_set_fd_handler(int fd, 
3562
                        IOHandler *fd_read, 
3563
                        IOHandler *fd_write, 
3564
                        void *opaque)
3565
{
3566
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3567
}
3568

    
3569
/***********************************************************/
3570
/* Polling handling */
3571

    
3572
typedef struct PollingEntry {
3573
    PollingFunc *func;
3574
    void *opaque;
3575
    struct PollingEntry *next;
3576
} PollingEntry;
3577

    
3578
static PollingEntry *first_polling_entry;
3579

    
3580
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3581
{
3582
    PollingEntry **ppe, *pe;
3583
    pe = qemu_mallocz(sizeof(PollingEntry));
3584
    if (!pe)
3585
        return -1;
3586
    pe->func = func;
3587
    pe->opaque = opaque;
3588
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3589
    *ppe = pe;
3590
    return 0;
3591
}
3592

    
3593
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3594
{
3595
    PollingEntry **ppe, *pe;
3596
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3597
        pe = *ppe;
3598
        if (pe->func == func && pe->opaque == opaque) {
3599
            *ppe = pe->next;
3600
            qemu_free(pe);
3601
            break;
3602
        }
3603
    }
3604
}
3605

    
3606
/***********************************************************/
3607
/* savevm/loadvm support */
3608

    
3609
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3610
{
3611
    fwrite(buf, 1, size, f);
3612
}
3613

    
3614
void qemu_put_byte(QEMUFile *f, int v)
3615
{
3616
    fputc(v, f);
3617
}
3618

    
3619
void qemu_put_be16(QEMUFile *f, unsigned int v)
3620
{
3621
    qemu_put_byte(f, v >> 8);
3622
    qemu_put_byte(f, v);
3623
}
3624

    
3625
void qemu_put_be32(QEMUFile *f, unsigned int v)
3626
{
3627
    qemu_put_byte(f, v >> 24);
3628
    qemu_put_byte(f, v >> 16);
3629
    qemu_put_byte(f, v >> 8);
3630
    qemu_put_byte(f, v);
3631
}
3632

    
3633
void qemu_put_be64(QEMUFile *f, uint64_t v)
3634
{
3635
    qemu_put_be32(f, v >> 32);
3636
    qemu_put_be32(f, v);
3637
}
3638

    
3639
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3640
{
3641
    return fread(buf, 1, size, f);
3642
}
3643

    
3644
int qemu_get_byte(QEMUFile *f)
3645
{
3646
    int v;
3647
    v = fgetc(f);
3648
    if (v == EOF)
3649
        return 0;
3650
    else
3651
        return v;
3652
}
3653

    
3654
unsigned int qemu_get_be16(QEMUFile *f)
3655
{
3656
    unsigned int v;
3657
    v = qemu_get_byte(f) << 8;
3658
    v |= qemu_get_byte(f);
3659
    return v;
3660
}
3661

    
3662
unsigned int qemu_get_be32(QEMUFile *f)
3663
{
3664
    unsigned int v;
3665
    v = qemu_get_byte(f) << 24;
3666
    v |= qemu_get_byte(f) << 16;
3667
    v |= qemu_get_byte(f) << 8;
3668
    v |= qemu_get_byte(f);
3669
    return v;
3670
}
3671

    
3672
uint64_t qemu_get_be64(QEMUFile *f)
3673
{
3674
    uint64_t v;
3675
    v = (uint64_t)qemu_get_be32(f) << 32;
3676
    v |= qemu_get_be32(f);
3677
    return v;
3678
}
3679

    
3680
int64_t qemu_ftell(QEMUFile *f)
3681
{
3682
    return ftell(f);
3683
}
3684

    
3685
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3686
{
3687
    if (fseek(f, pos, whence) < 0)
3688
        return -1;
3689
    return ftell(f);
3690
}
3691

    
3692
typedef struct SaveStateEntry {
3693
    char idstr[256];
3694
    int instance_id;
3695
    int version_id;
3696
    SaveStateHandler *save_state;
3697
    LoadStateHandler *load_state;
3698
    void *opaque;
3699
    struct SaveStateEntry *next;
3700
} SaveStateEntry;
3701

    
3702
static SaveStateEntry *first_se;
3703

    
3704
int register_savevm(const char *idstr, 
3705
                    int instance_id, 
3706
                    int version_id,
3707
                    SaveStateHandler *save_state,
3708
                    LoadStateHandler *load_state,
3709
                    void *opaque)
3710
{
3711
    SaveStateEntry *se, **pse;
3712

    
3713
    se = qemu_malloc(sizeof(SaveStateEntry));
3714
    if (!se)
3715
        return -1;
3716
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3717
    se->instance_id = instance_id;
3718
    se->version_id = version_id;
3719
    se->save_state = save_state;
3720
    se->load_state = load_state;
3721
    se->opaque = opaque;
3722
    se->next = NULL;
3723

    
3724
    /* add at the end of list */
3725
    pse = &first_se;
3726
    while (*pse != NULL)
3727
        pse = &(*pse)->next;
3728
    *pse = se;
3729
    return 0;
3730
}
3731

    
3732
#define QEMU_VM_FILE_MAGIC   0x5145564d
3733
#define QEMU_VM_FILE_VERSION 0x00000001
3734

    
3735
int qemu_savevm(const char *filename)
3736
{
3737
    SaveStateEntry *se;
3738
    QEMUFile *f;
3739
    int len, len_pos, cur_pos, saved_vm_running, ret;
3740

    
3741
    saved_vm_running = vm_running;
3742
    vm_stop(0);
3743

    
3744
    f = fopen(filename, "wb");
3745
    if (!f) {
3746
        ret = -1;
3747
        goto the_end;
3748
    }
3749

    
3750
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3751
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3752

    
3753
    for(se = first_se; se != NULL; se = se->next) {
3754
        /* ID string */
3755
        len = strlen(se->idstr);
3756
        qemu_put_byte(f, len);
3757
        qemu_put_buffer(f, se->idstr, len);
3758

    
3759
        qemu_put_be32(f, se->instance_id);
3760
        qemu_put_be32(f, se->version_id);
3761

    
3762
        /* record size: filled later */
3763
        len_pos = ftell(f);
3764
        qemu_put_be32(f, 0);
3765
        
3766
        se->save_state(f, se->opaque);
3767

    
3768
        /* fill record size */
3769
        cur_pos = ftell(f);
3770
        len = ftell(f) - len_pos - 4;
3771
        fseek(f, len_pos, SEEK_SET);
3772
        qemu_put_be32(f, len);
3773
        fseek(f, cur_pos, SEEK_SET);
3774
    }
3775

    
3776
    fclose(f);
3777
    ret = 0;
3778
 the_end:
3779
    if (saved_vm_running)
3780
        vm_start();
3781
    return ret;
3782
}
3783

    
3784
static SaveStateEntry *find_se(const char *idstr, int instance_id)
3785
{
3786
    SaveStateEntry *se;
3787

    
3788
    for(se = first_se; se != NULL; se = se->next) {
3789
        if (!strcmp(se->idstr, idstr) && 
3790
            instance_id == se->instance_id)
3791
            return se;
3792
    }
3793
    return NULL;
3794
}
3795

    
3796
int qemu_loadvm(const char *filename)
3797
{
3798
    SaveStateEntry *se;
3799
    QEMUFile *f;
3800
    int len, cur_pos, ret, instance_id, record_len, version_id;
3801
    int saved_vm_running;
3802
    unsigned int v;
3803
    char idstr[256];
3804
    
3805
    saved_vm_running = vm_running;
3806
    vm_stop(0);
3807

    
3808
    f = fopen(filename, "rb");
3809
    if (!f) {
3810
        ret = -1;
3811
        goto the_end;
3812
    }
3813

    
3814
    v = qemu_get_be32(f);
3815
    if (v != QEMU_VM_FILE_MAGIC)
3816
        goto fail;
3817
    v = qemu_get_be32(f);
3818
    if (v != QEMU_VM_FILE_VERSION) {
3819
    fail:
3820
        fclose(f);
3821
        ret = -1;
3822
        goto the_end;
3823
    }
3824
    for(;;) {
3825
        len = qemu_get_byte(f);
3826
        if (feof(f))
3827
            break;
3828
        qemu_get_buffer(f, idstr, len);
3829
        idstr[len] = '\0';
3830
        instance_id = qemu_get_be32(f);
3831
        version_id = qemu_get_be32(f);
3832
        record_len = qemu_get_be32(f);
3833
#if 0
3834
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
3835
               idstr, instance_id, version_id, record_len);
3836
#endif
3837
        cur_pos = ftell(f);
3838
        se = find_se(idstr, instance_id);
3839
        if (!se) {
3840
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
3841
                    instance_id, idstr);
3842
        } else {
3843
            ret = se->load_state(f, se->opaque, version_id);
3844
            if (ret < 0) {
3845
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
3846
                        instance_id, idstr);
3847
            }
3848
        }
3849
        /* always seek to exact end of record */
3850
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3851
    }
3852
    fclose(f);
3853
    ret = 0;
3854
 the_end:
3855
    if (saved_vm_running)
3856
        vm_start();
3857
    return ret;
3858
}
3859

    
3860
/***********************************************************/
3861
/* cpu save/restore */
3862

    
3863
#if defined(TARGET_I386)
3864

    
3865
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3866
{
3867
    qemu_put_be32(f, dt->selector);
3868
    qemu_put_betl(f, dt->base);
3869
    qemu_put_be32(f, dt->limit);
3870
    qemu_put_be32(f, dt->flags);
3871
}
3872

    
3873
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3874
{
3875
    dt->selector = qemu_get_be32(f);
3876
    dt->base = qemu_get_betl(f);
3877
    dt->limit = qemu_get_be32(f);
3878
    dt->flags = qemu_get_be32(f);
3879
}
3880

    
3881
void cpu_save(QEMUFile *f, void *opaque)
3882
{
3883
    CPUState *env = opaque;
3884
    uint16_t fptag, fpus, fpuc, fpregs_format;
3885
    uint32_t hflags;
3886
    int i;
3887
    
3888
    for(i = 0; i < CPU_NB_REGS; i++)
3889
        qemu_put_betls(f, &env->regs[i]);
3890
    qemu_put_betls(f, &env->eip);
3891
    qemu_put_betls(f, &env->eflags);
3892
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3893
    qemu_put_be32s(f, &hflags);
3894
    
3895
    /* FPU */
3896
    fpuc = env->fpuc;
3897
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3898
    fptag = 0;
3899
    for(i = 0; i < 8; i++) {
3900
        fptag |= ((!env->fptags[i]) << i);
3901
    }
3902
    
3903
    qemu_put_be16s(f, &fpuc);
3904
    qemu_put_be16s(f, &fpus);
3905
    qemu_put_be16s(f, &fptag);
3906

    
3907
#ifdef USE_X86LDOUBLE
3908
    fpregs_format = 0;
3909
#else
3910
    fpregs_format = 1;
3911
#endif
3912
    qemu_put_be16s(f, &fpregs_format);
3913
    
3914
    for(i = 0; i < 8; i++) {
3915
#ifdef USE_X86LDOUBLE
3916
        {
3917
            uint64_t mant;
3918
            uint16_t exp;
3919
            /* we save the real CPU data (in case of MMX usage only 'mant'
3920
               contains the MMX register */
3921
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3922
            qemu_put_be64(f, mant);
3923
            qemu_put_be16(f, exp);
3924
        }
3925
#else
3926
        /* if we use doubles for float emulation, we save the doubles to
3927
           avoid losing information in case of MMX usage. It can give
3928
           problems if the image is restored on a CPU where long
3929
           doubles are used instead. */
3930
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3931
#endif
3932
    }
3933

    
3934
    for(i = 0; i < 6; i++)
3935
        cpu_put_seg(f, &env->segs[i]);
3936
    cpu_put_seg(f, &env->ldt);
3937
    cpu_put_seg(f, &env->tr);
3938
    cpu_put_seg(f, &env->gdt);
3939
    cpu_put_seg(f, &env->idt);
3940
    
3941
    qemu_put_be32s(f, &env->sysenter_cs);
3942
    qemu_put_be32s(f, &env->sysenter_esp);
3943
    qemu_put_be32s(f, &env->sysenter_eip);
3944
    
3945
    qemu_put_betls(f, &env->cr[0]);
3946
    qemu_put_betls(f, &env->cr[2]);
3947
    qemu_put_betls(f, &env->cr[3]);
3948
    qemu_put_betls(f, &env->cr[4]);
3949
    
3950
    for(i = 0; i < 8; i++)
3951
        qemu_put_betls(f, &env->dr[i]);
3952

    
3953
    /* MMU */
3954
    qemu_put_be32s(f, &env->a20_mask);
3955

    
3956
    /* XMM */
3957
    qemu_put_be32s(f, &env->mxcsr);
3958
    for(i = 0; i < CPU_NB_REGS; i++) {
3959
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3960
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3961
    }
3962

    
3963
#ifdef TARGET_X86_64
3964
    qemu_put_be64s(f, &env->efer);
3965
    qemu_put_be64s(f, &env->star);
3966
    qemu_put_be64s(f, &env->lstar);
3967
    qemu_put_be64s(f, &env->cstar);
3968
    qemu_put_be64s(f, &env->fmask);
3969
    qemu_put_be64s(f, &env->kernelgsbase);
3970
#endif
3971
}
3972

    
3973
#ifdef USE_X86LDOUBLE
3974
/* XXX: add that in a FPU generic layer */
3975
union x86_longdouble {
3976
    uint64_t mant;
3977
    uint16_t exp;
3978
};
3979

    
3980
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
3981
#define EXPBIAS1 1023
3982
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
3983
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
3984

    
3985
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3986
{
3987
    int e;
3988
    /* mantissa */
3989
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3990
    /* exponent + sign */
3991
    e = EXPD1(temp) - EXPBIAS1 + 16383;
3992
    e |= SIGND1(temp) >> 16;
3993
    p->exp = e;
3994
}
3995
#endif
3996

    
3997
int cpu_load(QEMUFile *f, void *opaque, int version_id)
3998
{
3999
    CPUState *env = opaque;
4000
    int i, guess_mmx;
4001
    uint32_t hflags;
4002
    uint16_t fpus, fpuc, fptag, fpregs_format;
4003

    
4004
    if (version_id != 3)
4005
        return -EINVAL;
4006
    for(i = 0; i < CPU_NB_REGS; i++)
4007
        qemu_get_betls(f, &env->regs[i]);
4008
    qemu_get_betls(f, &env->eip);
4009
    qemu_get_betls(f, &env->eflags);
4010
    qemu_get_be32s(f, &hflags);
4011

    
4012
    qemu_get_be16s(f, &fpuc);
4013
    qemu_get_be16s(f, &fpus);
4014
    qemu_get_be16s(f, &fptag);
4015
    qemu_get_be16s(f, &fpregs_format);
4016
    
4017
    /* NOTE: we cannot always restore the FPU state if the image come
4018
       from a host with a different 'USE_X86LDOUBLE' define. We guess
4019
       if we are in an MMX state to restore correctly in that case. */
4020
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4021
    for(i = 0; i < 8; i++) {
4022
        uint64_t mant;
4023
        uint16_t exp;
4024
        
4025
        switch(fpregs_format) {
4026
        case 0:
4027
            mant = qemu_get_be64(f);
4028
            exp = qemu_get_be16(f);
4029
#ifdef USE_X86LDOUBLE
4030
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
4031
#else
4032
            /* difficult case */
4033
            if (guess_mmx)
4034
                env->fpregs[i].mmx.MMX_Q(0) = mant;
4035
            else
4036
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
4037
#endif
4038
            break;
4039
        case 1:
4040
            mant = qemu_get_be64(f);
4041
#ifdef USE_X86LDOUBLE
4042
            {
4043
                union x86_longdouble *p;
4044
                /* difficult case */
4045
                p = (void *)&env->fpregs[i];
4046
                if (guess_mmx) {
4047
                    p->mant = mant;
4048
                    p->exp = 0xffff;
4049
                } else {
4050
                    fp64_to_fp80(p, mant);
4051
                }
4052
            }
4053
#else
4054
            env->fpregs[i].mmx.MMX_Q(0) = mant;
4055
#endif            
4056
            break;
4057
        default:
4058
            return -EINVAL;
4059
        }
4060
    }
4061

    
4062
    env->fpuc = fpuc;
4063
    /* XXX: restore FPU round state */
4064
    env->fpstt = (fpus >> 11) & 7;
4065
    env->fpus = fpus & ~0x3800;
4066
    fptag ^= 0xff;
4067
    for(i = 0; i < 8; i++) {
4068
        env->fptags[i] = (fptag >> i) & 1;
4069
    }
4070
    
4071
    for(i = 0; i < 6; i++)
4072
        cpu_get_seg(f, &env->segs[i]);
4073
    cpu_get_seg(f, &env->ldt);
4074
    cpu_get_seg(f, &env->tr);
4075
    cpu_get_seg(f, &env->gdt);
4076
    cpu_get_seg(f, &env->idt);
4077
    
4078
    qemu_get_be32s(f, &env->sysenter_cs);
4079
    qemu_get_be32s(f, &env->sysenter_esp);
4080
    qemu_get_be32s(f, &env->sysenter_eip);
4081
    
4082
    qemu_get_betls(f, &env->cr[0]);
4083
    qemu_get_betls(f, &env->cr[2]);
4084
    qemu_get_betls(f, &env->cr[3]);
4085
    qemu_get_betls(f, &env->cr[4]);
4086
    
4087
    for(i = 0; i < 8; i++)
4088
        qemu_get_betls(f, &env->dr[i]);
4089

    
4090
    /* MMU */
4091
    qemu_get_be32s(f, &env->a20_mask);
4092

    
4093
    qemu_get_be32s(f, &env->mxcsr);
4094
    for(i = 0; i < CPU_NB_REGS; i++) {
4095
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4096
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4097
    }
4098

    
4099
#ifdef TARGET_X86_64
4100
    qemu_get_be64s(f, &env->efer);
4101
    qemu_get_be64s(f, &env->star);
4102
    qemu_get_be64s(f, &env->lstar);
4103
    qemu_get_be64s(f, &env->cstar);
4104
    qemu_get_be64s(f, &env->fmask);
4105
    qemu_get_be64s(f, &env->kernelgsbase);
4106
#endif
4107

    
4108
    /* XXX: compute hflags from scratch, except for CPL and IIF */
4109
    env->hflags = hflags;
4110
    tlb_flush(env, 1);
4111
    return 0;
4112
}
4113

    
4114
#elif defined(TARGET_PPC)
4115
void cpu_save(QEMUFile *f, void *opaque)
4116
{
4117
}
4118

    
4119
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4120
{
4121
    return 0;
4122
}
4123

    
4124
#elif defined(TARGET_MIPS)
4125
void cpu_save(QEMUFile *f, void *opaque)
4126
{
4127
}
4128

    
4129
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4130
{
4131
    return 0;
4132
}
4133

    
4134
#elif defined(TARGET_SPARC)
4135
void cpu_save(QEMUFile *f, void *opaque)
4136
{
4137
    CPUState *env = opaque;
4138
    int i;
4139
    uint32_t tmp;
4140

    
4141
    for(i = 0; i < 8; i++)
4142
        qemu_put_betls(f, &env->gregs[i]);
4143
    for(i = 0; i < NWINDOWS * 16; i++)
4144
        qemu_put_betls(f, &env->regbase[i]);
4145

    
4146
    /* FPU */
4147
    for(i = 0; i < TARGET_FPREGS; i++) {
4148
        union {
4149
            float32 f;
4150
            uint32_t i;
4151
        } u;
4152
        u.f = env->fpr[i];
4153
        qemu_put_be32(f, u.i);
4154
    }
4155

    
4156
    qemu_put_betls(f, &env->pc);
4157
    qemu_put_betls(f, &env->npc);
4158
    qemu_put_betls(f, &env->y);
4159
    tmp = GET_PSR(env);
4160
    qemu_put_be32(f, tmp);
4161
    qemu_put_betls(f, &env->fsr);
4162
    qemu_put_betls(f, &env->tbr);
4163
#ifndef TARGET_SPARC64
4164
    qemu_put_be32s(f, &env->wim);
4165
    /* MMU */
4166
    for(i = 0; i < 16; i++)
4167
        qemu_put_be32s(f, &env->mmuregs[i]);
4168
#endif
4169
}
4170

    
4171
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4172
{
4173
    CPUState *env = opaque;
4174
    int i;
4175
    uint32_t tmp;
4176

    
4177
    for(i = 0; i < 8; i++)
4178
        qemu_get_betls(f, &env->gregs[i]);
4179
    for(i = 0; i < NWINDOWS * 16; i++)
4180
        qemu_get_betls(f, &env->regbase[i]);
4181

    
4182
    /* FPU */
4183
    for(i = 0; i < TARGET_FPREGS; i++) {
4184
        union {
4185
            float32 f;
4186
            uint32_t i;
4187
        } u;
4188
        u.i = qemu_get_be32(f);
4189
        env->fpr[i] = u.f;
4190
    }
4191

    
4192
    qemu_get_betls(f, &env->pc);
4193
    qemu_get_betls(f, &env->npc);
4194
    qemu_get_betls(f, &env->y);
4195
    tmp = qemu_get_be32(f);
4196
    env->cwp = 0; /* needed to ensure that the wrapping registers are
4197
                     correctly updated */
4198
    PUT_PSR(env, tmp);
4199
    qemu_get_betls(f, &env->fsr);
4200
    qemu_get_betls(f, &env->tbr);
4201
#ifndef TARGET_SPARC64
4202
    qemu_get_be32s(f, &env->wim);
4203
    /* MMU */
4204
    for(i = 0; i < 16; i++)
4205
        qemu_get_be32s(f, &env->mmuregs[i]);
4206
#endif
4207
    tlb_flush(env, 1);
4208
    return 0;
4209
}
4210

    
4211
#elif defined(TARGET_ARM)
4212

    
4213
/* ??? Need to implement these.  */
4214
void cpu_save(QEMUFile *f, void *opaque)
4215
{
4216
}
4217

    
4218
int cpu_load(QEMUFile *f, void *opaque, int version_id)
4219
{
4220
    return 0;
4221
}
4222

    
4223
#else
4224

    
4225
#warning No CPU save/restore functions
4226

    
4227
#endif
4228

    
4229
/***********************************************************/
4230
/* ram save/restore */
4231

    
4232
/* we just avoid storing empty pages */
4233
static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4234
{
4235
    int i, v;
4236

    
4237
    v = buf[0];
4238
    for(i = 1; i < len; i++) {
4239
        if (buf[i] != v)
4240
            goto normal_save;
4241
    }
4242
    qemu_put_byte(f, 1);
4243
    qemu_put_byte(f, v);
4244
    return;
4245
 normal_save:
4246
    qemu_put_byte(f, 0); 
4247
    qemu_put_buffer(f, buf, len);
4248
}
4249

    
4250
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4251
{
4252
    int v;
4253

    
4254
    v = qemu_get_byte(f);
4255
    switch(v) {
4256
    case 0:
4257
        if (qemu_get_buffer(f, buf, len) != len)
4258
            return -EIO;
4259
        break;
4260
    case 1:
4261
        v = qemu_get_byte(f);
4262
        memset(buf, v, len);
4263
        break;
4264
    default:
4265
        return -EINVAL;
4266
    }
4267
    return 0;
4268
}
4269

    
4270
static void ram_save(QEMUFile *f, void *opaque)
4271
{
4272
    int i;
4273
    qemu_put_be32(f, phys_ram_size);
4274
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4275
        ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4276
    }
4277
}
4278

    
4279
static int ram_load(QEMUFile *f, void *opaque, int version_id)
4280
{
4281
    int i, ret;
4282

    
4283
    if (version_id != 1)
4284
        return -EINVAL;
4285
    if (qemu_get_be32(f) != phys_ram_size)
4286
        return -EINVAL;
4287
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4288
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4289
        if (ret)
4290
            return ret;
4291
    }
4292
    return 0;
4293
}
4294

    
4295
/***********************************************************/
4296
/* machine registration */
4297

    
4298
QEMUMachine *first_machine = NULL;
4299

    
4300
int qemu_register_machine(QEMUMachine *m)
4301
{
4302
    QEMUMachine **pm;
4303
    pm = &first_machine;
4304
    while (*pm != NULL)
4305
        pm = &(*pm)->next;
4306
    m->next = NULL;
4307
    *pm = m;
4308
    return 0;
4309
}
4310

    
4311
QEMUMachine *find_machine(const char *name)
4312
{
4313
    QEMUMachine *m;
4314

    
4315
    for(m = first_machine; m != NULL; m = m->next) {
4316
        if (!strcmp(m->name, name))
4317
            return m;
4318
    }
4319
    return NULL;
4320
}
4321

    
4322
/***********************************************************/
4323
/* main execution loop */
4324

    
4325
void gui_update(void *opaque)
4326
{
4327
    display_state.dpy_refresh(&display_state);
4328
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4329
}
4330

    
4331
struct vm_change_state_entry {
4332
    VMChangeStateHandler *cb;
4333
    void *opaque;
4334
    LIST_ENTRY (vm_change_state_entry) entries;
4335
};
4336

    
4337
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4338

    
4339
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4340
                                                     void *opaque)
4341
{
4342
    VMChangeStateEntry *e;
4343

    
4344
    e = qemu_mallocz(sizeof (*e));
4345
    if (!e)
4346
        return NULL;
4347

    
4348
    e->cb = cb;
4349
    e->opaque = opaque;
4350
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4351
    return e;
4352
}
4353

    
4354
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4355
{
4356
    LIST_REMOVE (e, entries);
4357
    qemu_free (e);
4358
}
4359

    
4360
static void vm_state_notify(int running)
4361
{
4362
    VMChangeStateEntry *e;
4363

    
4364
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4365
        e->cb(e->opaque, running);
4366
    }
4367
}
4368

    
4369
/* XXX: support several handlers */
4370
static VMStopHandler *vm_stop_cb;
4371
static void *vm_stop_opaque;
4372

    
4373
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4374
{
4375
    vm_stop_cb = cb;
4376
    vm_stop_opaque = opaque;
4377
    return 0;
4378
}
4379

    
4380
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4381
{
4382
    vm_stop_cb = NULL;
4383
}
4384

    
4385
void vm_start(void)
4386
{
4387
    if (!vm_running) {
4388
        cpu_enable_ticks();
4389
        vm_running = 1;
4390
        vm_state_notify(1);
4391
    }
4392
}
4393

    
4394
void vm_stop(int reason) 
4395
{
4396
    if (vm_running) {
4397
        cpu_disable_ticks();
4398
        vm_running = 0;
4399
        if (reason != 0) {
4400
            if (vm_stop_cb) {
4401
                vm_stop_cb(vm_stop_opaque, reason);
4402
            }
4403
        }
4404
        vm_state_notify(0);
4405
    }
4406
}
4407

    
4408
/* reset/shutdown handler */
4409

    
4410
typedef struct QEMUResetEntry {
4411
    QEMUResetHandler *func;
4412
    void *opaque;
4413
    struct QEMUResetEntry *next;
4414
} QEMUResetEntry;
4415

    
4416
static QEMUResetEntry *first_reset_entry;
4417
static int reset_requested;
4418
static int shutdown_requested;
4419
static int powerdown_requested;
4420

    
4421
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4422
{
4423
    QEMUResetEntry **pre, *re;
4424

    
4425
    pre = &first_reset_entry;
4426
    while (*pre != NULL)
4427
        pre = &(*pre)->next;
4428
    re = qemu_mallocz(sizeof(QEMUResetEntry));
4429
    re->func = func;
4430
    re->opaque = opaque;
4431
    re->next = NULL;
4432
    *pre = re;
4433
}
4434

    
4435
void qemu_system_reset(void)
4436
{
4437
    QEMUResetEntry *re;
4438

    
4439
    /* reset all devices */
4440
    for(re = first_reset_entry; re != NULL; re = re->next) {
4441
        re->func(re->opaque);
4442
    }
4443
}
4444

    
4445
void qemu_system_reset_request(void)
4446
{
4447
    reset_requested = 1;
4448
    if (cpu_single_env)
4449
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4450
}
4451

    
4452
void qemu_system_shutdown_request(void)
4453
{
4454
    shutdown_requested = 1;
4455
    if (cpu_single_env)
4456
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4457
}
4458

    
4459
void qemu_system_powerdown_request(void)
4460
{
4461
    powerdown_requested = 1;
4462
    if (cpu_single_env)
4463
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4464
}
4465

    
4466
void main_loop_wait(int timeout)
4467
{
4468
    IOHandlerRecord *ioh, *ioh_next;
4469
    fd_set rfds, wfds, xfds;
4470
    int ret, nfds;
4471
    struct timeval tv;
4472
    PollingEntry *pe;
4473

    
4474

    
4475
    /* XXX: need to suppress polling by better using win32 events */
4476
    ret = 0;
4477
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4478
        ret |= pe->func(pe->opaque);
4479
    }
4480
#ifdef _WIN32
4481
    if (ret == 0 && timeout > 0) {
4482
            int err;
4483
            HANDLE hEvents[1];
4484

    
4485
            hEvents[0] = host_alarm;
4486
            ret = WaitForMultipleObjects(1, hEvents, FALSE, timeout);
4487
            switch(ret) {
4488
            case WAIT_OBJECT_0 + 0:
4489
                break;
4490
            case WAIT_TIMEOUT:
4491
                break;
4492
            default:
4493
                err = GetLastError();
4494
                fprintf(stderr, "Wait error %d %d\n", ret, err);
4495
                break;
4496
            }
4497
    }
4498
#endif
4499
    /* poll any events */
4500
    /* XXX: separate device handlers from system ones */
4501
    nfds = -1;
4502
    FD_ZERO(&rfds);
4503
    FD_ZERO(&wfds);
4504
    FD_ZERO(&xfds);
4505
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4506
        if (ioh->fd_read &&
4507
            (!ioh->fd_read_poll ||
4508
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4509
            FD_SET(ioh->fd, &rfds);
4510
            if (ioh->fd > nfds)
4511
                nfds = ioh->fd;
4512
        }
4513
        if (ioh->fd_write) {
4514
            FD_SET(ioh->fd, &wfds);
4515
            if (ioh->fd > nfds)
4516
                nfds = ioh->fd;
4517
        }
4518
    }
4519
    
4520
    tv.tv_sec = 0;
4521
#ifdef _WIN32
4522
    tv.tv_usec = 0;
4523
#else
4524
    tv.tv_usec = timeout * 1000;
4525
#endif
4526
#if defined(CONFIG_SLIRP)
4527
    if (slirp_inited) {
4528
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4529
    }
4530
#endif
4531
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4532
    if (ret > 0) {
4533
        /* XXX: better handling of removal */
4534
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4535
            ioh_next = ioh->next;
4536
            if (FD_ISSET(ioh->fd, &rfds)) {
4537
                ioh->fd_read(ioh->opaque);
4538
            }
4539
            if (FD_ISSET(ioh->fd, &wfds)) {
4540
                ioh->fd_write(ioh->opaque);
4541
            }
4542
        }
4543
    }
4544
#if defined(CONFIG_SLIRP)
4545
    if (slirp_inited) {
4546
        if (ret < 0) {
4547
            FD_ZERO(&rfds);
4548
            FD_ZERO(&wfds);
4549
            FD_ZERO(&xfds);
4550
        }
4551
        slirp_select_poll(&rfds, &wfds, &xfds);
4552
    }
4553
#endif
4554
#ifdef _WIN32
4555
    tap_win32_poll();
4556
#endif
4557

    
4558
    if (vm_running) {
4559
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
4560
                        qemu_get_clock(vm_clock));
4561
        /* run dma transfers, if any */
4562
        DMA_run();
4563
    }
4564
    
4565
    /* real time timers */
4566
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
4567
                    qemu_get_clock(rt_clock));
4568
}
4569

    
4570
static CPUState *cur_cpu;
4571

    
4572
int main_loop(void)
4573
{
4574
    int ret, timeout;
4575
#ifdef CONFIG_PROFILER
4576
    int64_t ti;
4577
#endif
4578
    CPUState *env;
4579

    
4580
    cur_cpu = first_cpu;
4581
    for(;;) {
4582
        if (vm_running) {
4583

    
4584
            env = cur_cpu;
4585
            for(;;) {
4586
                /* get next cpu */
4587
                env = env->next_cpu;
4588
                if (!env)
4589
                    env = first_cpu;
4590
#ifdef CONFIG_PROFILER
4591
                ti = profile_getclock();
4592
#endif
4593
                ret = cpu_exec(env);
4594
#ifdef CONFIG_PROFILER
4595
                qemu_time += profile_getclock() - ti;
4596
#endif
4597
                if (ret != EXCP_HALTED)
4598
                    break;
4599
                /* all CPUs are halted ? */
4600
                if (env == cur_cpu) {
4601
                    ret = EXCP_HLT;
4602
                    break;
4603
                }
4604
            }
4605
            cur_cpu = env;
4606

    
4607
            if (shutdown_requested) {
4608
                ret = EXCP_INTERRUPT;
4609
                break;
4610
            }
4611
            if (reset_requested) {
4612
                reset_requested = 0;
4613
                qemu_system_reset();
4614
                ret = EXCP_INTERRUPT;
4615
            }
4616
            if (powerdown_requested) {
4617
                powerdown_requested = 0;
4618
                qemu_system_powerdown();
4619
                ret = EXCP_INTERRUPT;
4620
            }
4621
            if (ret == EXCP_DEBUG) {
4622
                vm_stop(EXCP_DEBUG);
4623
            }
4624
            /* if hlt instruction, we wait until the next IRQ */
4625
            /* XXX: use timeout computed from timers */
4626
            if (ret == EXCP_HLT)
4627
                timeout = 10;
4628
            else
4629
                timeout = 0;
4630
        } else {
4631
            timeout = 10;
4632
        }
4633
#ifdef CONFIG_PROFILER
4634
        ti = profile_getclock();
4635
#endif
4636
        main_loop_wait(timeout);
4637
#ifdef CONFIG_PROFILER
4638
        dev_time += profile_getclock() - ti;
4639
#endif
4640
    }
4641
    cpu_disable_ticks();
4642
    return ret;
4643
}
4644

    
4645
void help(void)
4646
{
4647
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4648
           "usage: %s [options] [disk_image]\n"
4649
           "\n"
4650
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4651
           "\n"
4652
           "Standard options:\n"
4653
           "-M machine      select emulated machine (-M ? for list)\n"
4654
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
4655
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
4656
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
4657
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4658
           "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4659
           "-snapshot       write to temporary files instead of disk image files\n"
4660
#ifdef TARGET_I386
4661
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
4662
#endif
4663
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
4664
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
4665
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
4666
#ifndef _WIN32
4667
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
4668
#endif
4669
#ifdef HAS_AUDIO
4670
           "-audio-help     print list of audio drivers and their options\n"
4671
           "-soundhw c1,... enable audio support\n"
4672
           "                and only specified sound cards (comma separated list)\n"
4673
           "                use -soundhw ? to get the list of supported cards\n"
4674
           "                use -soundhw all to enable all of them\n"
4675
#endif
4676
           "-localtime      set the real time clock to local time [default=utc]\n"
4677
           "-full-screen    start in full screen\n"
4678
#ifdef TARGET_I386
4679
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
4680
#endif
4681
           "-usb            enable the USB driver (will be the default soon)\n"
4682
           "-usbdevice name add the host or guest USB device 'name'\n"
4683
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4684
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
4685
#endif
4686
           "\n"
4687
           "Network options:\n"
4688
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4689
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
4690
#ifdef CONFIG_SLIRP
4691
           "-net user[,vlan=n][,hostname=host]\n"
4692
           "                connect the user mode network stack to VLAN 'n' and send\n"
4693
           "                hostname 'host' to DHCP clients\n"
4694
#endif
4695
#ifdef _WIN32
4696
           "-net tap[,vlan=n],ifname=name\n"
4697
           "                connect the host TAP network interface to VLAN 'n'\n"
4698
#else
4699
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4700
           "                connect the host TAP network interface to VLAN 'n' and use\n"
4701
           "                the network script 'file' (default=%s);\n"
4702
           "                use 'fd=h' to connect to an already opened TAP interface\n"
4703
#endif
4704
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4705
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
4706
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4707
           "                connect the vlan 'n' to multicast maddr and port\n"
4708
           "-net none       use it alone to have zero network devices; if no -net option\n"
4709
           "                is provided, the default is '-net nic -net user'\n"
4710
           "\n"
4711
#ifdef CONFIG_SLIRP
4712
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
4713
#ifndef _WIN32
4714
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
4715
#endif
4716
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4717
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
4718
#endif
4719
           "\n"
4720
           "Linux boot specific:\n"
4721
           "-kernel bzImage use 'bzImage' as kernel image\n"
4722
           "-append cmdline use 'cmdline' as kernel command line\n"
4723
           "-initrd file    use 'file' as initial ram disk\n"
4724
           "\n"
4725
           "Debug/Expert options:\n"
4726
           "-monitor dev    redirect the monitor to char device 'dev'\n"
4727
           "-serial dev     redirect the serial port to char device 'dev'\n"
4728
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
4729
           "-pidfile file   Write PID to 'file'\n"
4730
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
4731
           "-s              wait gdb connection to port %d\n"
4732
           "-p port         change gdb connection port\n"
4733
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
4734
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
4735
           "                translation (t=none or lba) (usually qemu can guess them)\n"
4736
           "-L path         set the directory for the BIOS and VGA BIOS\n"
4737
#ifdef USE_KQEMU
4738
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
4739
           "-no-kqemu       disable KQEMU kernel module usage\n"
4740
#endif
4741
#ifdef USE_CODE_COPY
4742
           "-no-code-copy   disable code copy acceleration\n"
4743
#endif
4744
#ifdef TARGET_I386
4745
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
4746
           "                (default is CL-GD5446 PCI VGA)\n"
4747
           "-no-acpi        disable ACPI\n"
4748
#endif
4749
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
4750
           "-vnc display    start a VNC server on display\n"
4751
           "\n"
4752
           "During emulation, the following keys are useful:\n"
4753
           "ctrl-alt-f      toggle full screen\n"
4754
           "ctrl-alt-n      switch to virtual console 'n'\n"
4755
           "ctrl-alt        toggle mouse and keyboard grab\n"
4756
           "\n"
4757
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4758
           ,
4759
#ifdef CONFIG_SOFTMMU
4760
           "qemu",
4761
#else
4762
           "qemu-fast",
4763
#endif
4764
           DEFAULT_RAM_SIZE,
4765
#ifndef _WIN32
4766
           DEFAULT_NETWORK_SCRIPT,
4767
#endif
4768
           DEFAULT_GDBSTUB_PORT,
4769
           "/tmp/qemu.log");
4770
#ifndef CONFIG_SOFTMMU
4771
    printf("\n"
4772
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4773
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4774
           "PC emulation.\n");
4775
#endif
4776
    exit(1);
4777
}
4778

    
4779
#define HAS_ARG 0x0001
4780

    
4781
enum {
4782
    QEMU_OPTION_h,
4783

    
4784
    QEMU_OPTION_M,
4785
    QEMU_OPTION_fda,
4786
    QEMU_OPTION_fdb,
4787
    QEMU_OPTION_hda,
4788
    QEMU_OPTION_hdb,
4789
    QEMU_OPTION_hdc,
4790
    QEMU_OPTION_hdd,
4791
    QEMU_OPTION_cdrom,
4792
    QEMU_OPTION_boot,
4793
    QEMU_OPTION_snapshot,
4794
#ifdef TARGET_I386
4795
    QEMU_OPTION_no_fd_bootchk,
4796
#endif
4797
    QEMU_OPTION_m,
4798
    QEMU_OPTION_nographic,
4799
#ifdef HAS_AUDIO
4800
    QEMU_OPTION_audio_help,
4801
    QEMU_OPTION_soundhw,
4802
#endif
4803

    
4804
    QEMU_OPTION_net,
4805
    QEMU_OPTION_tftp,
4806
    QEMU_OPTION_smb,
4807
    QEMU_OPTION_redir,
4808

    
4809
    QEMU_OPTION_kernel,
4810
    QEMU_OPTION_append,
4811
    QEMU_OPTION_initrd,
4812

    
4813
    QEMU_OPTION_S,
4814
    QEMU_OPTION_s,
4815
    QEMU_OPTION_p,
4816
    QEMU_OPTION_d,
4817
    QEMU_OPTION_hdachs,
4818
    QEMU_OPTION_L,
4819
    QEMU_OPTION_no_code_copy,
4820
    QEMU_OPTION_k,
4821
    QEMU_OPTION_localtime,
4822
    QEMU_OPTION_cirrusvga,
4823
    QEMU_OPTION_g,
4824
    QEMU_OPTION_std_vga,
4825
    QEMU_OPTION_monitor,
4826
    QEMU_OPTION_serial,
4827
    QEMU_OPTION_parallel,
4828
    QEMU_OPTION_loadvm,
4829
    QEMU_OPTION_full_screen,
4830
    QEMU_OPTION_pidfile,
4831
    QEMU_OPTION_no_kqemu,
4832
    QEMU_OPTION_kernel_kqemu,
4833
    QEMU_OPTION_win2k_hack,
4834
    QEMU_OPTION_usb,
4835
    QEMU_OPTION_usbdevice,
4836
    QEMU_OPTION_smp,
4837
    QEMU_OPTION_vnc,
4838
    QEMU_OPTION_no_acpi,
4839
};
4840

    
4841
typedef struct QEMUOption {
4842
    const char *name;
4843
    int flags;
4844
    int index;
4845
} QEMUOption;
4846

    
4847
const QEMUOption qemu_options[] = {
4848
    { "h", 0, QEMU_OPTION_h },
4849

    
4850
    { "M", HAS_ARG, QEMU_OPTION_M },
4851
    { "fda", HAS_ARG, QEMU_OPTION_fda },
4852
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4853
    { "hda", HAS_ARG, QEMU_OPTION_hda },
4854
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4855
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4856
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4857
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4858
    { "boot", HAS_ARG, QEMU_OPTION_boot },
4859
    { "snapshot", 0, QEMU_OPTION_snapshot },
4860
#ifdef TARGET_I386
4861
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4862
#endif
4863
    { "m", HAS_ARG, QEMU_OPTION_m },
4864
    { "nographic", 0, QEMU_OPTION_nographic },
4865
    { "k", HAS_ARG, QEMU_OPTION_k },
4866
#ifdef HAS_AUDIO
4867
    { "audio-help", 0, QEMU_OPTION_audio_help },
4868
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4869
#endif
4870

    
4871
    { "net", HAS_ARG, QEMU_OPTION_net},
4872
#ifdef CONFIG_SLIRP
4873
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4874
#ifndef _WIN32
4875
    { "smb", HAS_ARG, QEMU_OPTION_smb },
4876
#endif
4877
    { "redir", HAS_ARG, QEMU_OPTION_redir },
4878
#endif
4879

    
4880
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4881
    { "append", HAS_ARG, QEMU_OPTION_append },
4882
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4883

    
4884
    { "S", 0, QEMU_OPTION_S },
4885
    { "s", 0, QEMU_OPTION_s },
4886
    { "p", HAS_ARG, QEMU_OPTION_p },
4887
    { "d", HAS_ARG, QEMU_OPTION_d },
4888
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4889
    { "L", HAS_ARG, QEMU_OPTION_L },
4890
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4891
#ifdef USE_KQEMU
4892
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4893
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4894
#endif
4895
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4896
    { "g", 1, QEMU_OPTION_g },
4897
#endif
4898
    { "localtime", 0, QEMU_OPTION_localtime },
4899
    { "std-vga", 0, QEMU_OPTION_std_vga },
4900
    { "monitor", 1, QEMU_OPTION_monitor },
4901
    { "serial", 1, QEMU_OPTION_serial },
4902
    { "parallel", 1, QEMU_OPTION_parallel },
4903
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4904
    { "full-screen", 0, QEMU_OPTION_full_screen },
4905
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4906
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4907
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4908
    { "smp", HAS_ARG, QEMU_OPTION_smp },
4909
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4910
    
4911
    /* temporary options */
4912
    { "usb", 0, QEMU_OPTION_usb },
4913
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4914
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
4915
    { NULL },
4916
};
4917

    
4918
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
4919

    
4920
/* this stack is only used during signal handling */
4921
#define SIGNAL_STACK_SIZE 32768
4922

    
4923
static uint8_t *signal_stack;
4924

    
4925
#endif
4926

    
4927
/* password input */
4928

    
4929
static BlockDriverState *get_bdrv(int index)
4930
{
4931
    BlockDriverState *bs;
4932

    
4933
    if (index < 4) {
4934
        bs = bs_table[index];
4935
    } else if (index < 6) {
4936
        bs = fd_table[index - 4];
4937
    } else {
4938
        bs = NULL;
4939
    }
4940
    return bs;
4941
}
4942

    
4943
static void read_passwords(void)
4944
{
4945
    BlockDriverState *bs;
4946
    int i, j;
4947
    char password[256];
4948

    
4949
    for(i = 0; i < 6; i++) {
4950
        bs = get_bdrv(i);
4951
        if (bs && bdrv_is_encrypted(bs)) {
4952
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4953
            for(j = 0; j < 3; j++) {
4954
                monitor_readline("Password: ", 
4955
                                 1, password, sizeof(password));
4956
                if (bdrv_set_key(bs, password) == 0)
4957
                    break;
4958
                term_printf("invalid password\n");
4959
            }
4960
        }
4961
    }
4962
}
4963

    
4964
/* XXX: currently we cannot use simultaneously different CPUs */
4965
void register_machines(void)
4966
{
4967
#if defined(TARGET_I386)
4968
    qemu_register_machine(&pc_machine);
4969
    qemu_register_machine(&isapc_machine);
4970
#elif defined(TARGET_PPC)
4971
    qemu_register_machine(&heathrow_machine);
4972
    qemu_register_machine(&core99_machine);
4973
    qemu_register_machine(&prep_machine);
4974
#elif defined(TARGET_MIPS)
4975
    qemu_register_machine(&mips_machine);
4976
#elif defined(TARGET_SPARC)
4977
#ifdef TARGET_SPARC64
4978
    qemu_register_machine(&sun4u_machine);
4979
#else
4980
    qemu_register_machine(&sun4m_machine);
4981
#endif
4982
#elif defined(TARGET_ARM)
4983
    qemu_register_machine(&integratorcp926_machine);
4984
    qemu_register_machine(&integratorcp1026_machine);
4985
    qemu_register_machine(&versatilepb_machine);
4986
    qemu_register_machine(&versatileab_machine);
4987
#elif defined(TARGET_SH4)
4988
    qemu_register_machine(&shix_machine);
4989
#else
4990
#error unsupported CPU
4991
#endif
4992
}
4993

    
4994
#ifdef HAS_AUDIO
4995
struct soundhw soundhw[] = {
4996
#ifdef TARGET_I386
4997
    {
4998
        "pcspk",
4999
        "PC speaker",
5000
        0,
5001
        1,
5002
        { .init_isa = pcspk_audio_init }
5003
    },
5004
#endif
5005
    {
5006
        "sb16",
5007
        "Creative Sound Blaster 16",
5008
        0,
5009
        1,
5010
        { .init_isa = SB16_init }
5011
    },
5012

    
5013
#ifdef CONFIG_ADLIB
5014
    {
5015
        "adlib",
5016
#ifdef HAS_YMF262
5017
        "Yamaha YMF262 (OPL3)",
5018
#else
5019
        "Yamaha YM3812 (OPL2)",
5020
#endif
5021
        0,
5022
        1,
5023
        { .init_isa = Adlib_init }
5024
    },
5025
#endif
5026

    
5027
#ifdef CONFIG_GUS
5028
    {
5029
        "gus",
5030
        "Gravis Ultrasound GF1",
5031
        0,
5032
        1,
5033
        { .init_isa = GUS_init }
5034
    },
5035
#endif
5036

    
5037
    {
5038
        "es1370",
5039
        "ENSONIQ AudioPCI ES1370",
5040
        0,
5041
        0,
5042
        { .init_pci = es1370_init }
5043
    },
5044

    
5045
    { NULL, NULL, 0, 0, { NULL } }
5046
};
5047

    
5048
static void select_soundhw (const char *optarg)
5049
{
5050
    struct soundhw *c;
5051

    
5052
    if (*optarg == '?') {
5053
    show_valid_cards:
5054

    
5055
        printf ("Valid sound card names (comma separated):\n");
5056
        for (c = soundhw; c->name; ++c) {
5057
            printf ("%-11s %s\n", c->name, c->descr);
5058
        }
5059
        printf ("\n-soundhw all will enable all of the above\n");
5060
        exit (*optarg != '?');
5061
    }
5062
    else {
5063
        size_t l;
5064
        const char *p;
5065
        char *e;
5066
        int bad_card = 0;
5067

    
5068
        if (!strcmp (optarg, "all")) {
5069
            for (c = soundhw; c->name; ++c) {
5070
                c->enabled = 1;
5071
            }
5072
            return;
5073
        }
5074

    
5075
        p = optarg;
5076
        while (*p) {
5077
            e = strchr (p, ',');
5078
            l = !e ? strlen (p) : (size_t) (e - p);
5079

    
5080
            for (c = soundhw; c->name; ++c) {
5081
                if (!strncmp (c->name, p, l)) {
5082
                    c->enabled = 1;
5083
                    break;
5084
                }
5085
            }
5086

    
5087
            if (!c->name) {
5088
                if (l > 80) {
5089
                    fprintf (stderr,
5090
                             "Unknown sound card name (too big to show)\n");
5091
                }
5092
                else {
5093
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
5094
                             (int) l, p);
5095
                }
5096
                bad_card = 1;
5097
            }
5098
            p += l + (e != NULL);
5099
        }
5100

    
5101
        if (bad_card)
5102
            goto show_valid_cards;
5103
    }
5104
}
5105
#endif
5106

    
5107
#define MAX_NET_CLIENTS 32
5108

    
5109
int main(int argc, char **argv)
5110
{
5111
#ifdef CONFIG_GDBSTUB
5112
    int use_gdbstub, gdbstub_port;
5113
#endif
5114
    int i, cdrom_index;
5115
    int snapshot, linux_boot;
5116
    const char *initrd_filename;
5117
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5118
    const char *kernel_filename, *kernel_cmdline;
5119
    DisplayState *ds = &display_state;
5120
    int cyls, heads, secs, translation;
5121
    int start_emulation = 1;
5122
    char net_clients[MAX_NET_CLIENTS][256];
5123
    int nb_net_clients;
5124
    int optind;
5125
    const char *r, *optarg;
5126
    CharDriverState *monitor_hd;
5127
    char monitor_device[128];
5128
    char serial_devices[MAX_SERIAL_PORTS][128];
5129
    int serial_device_index;
5130
    char parallel_devices[MAX_PARALLEL_PORTS][128];
5131
    int parallel_device_index;
5132
    const char *loadvm = NULL;
5133
    QEMUMachine *machine;
5134
    char usb_devices[MAX_USB_CMDLINE][128];
5135
    int usb_devices_index;
5136

    
5137
    LIST_INIT (&vm_change_state_head);
5138
#if !defined(CONFIG_SOFTMMU)
5139
    /* we never want that malloc() uses mmap() */
5140
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5141
#endif
5142
    register_machines();
5143
    machine = first_machine;
5144
    initrd_filename = NULL;
5145
    for(i = 0; i < MAX_FD; i++)
5146
        fd_filename[i] = NULL;
5147
    for(i = 0; i < MAX_DISKS; i++)
5148
        hd_filename[i] = NULL;
5149
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5150
    vga_ram_size = VGA_RAM_SIZE;
5151
    bios_size = BIOS_SIZE;
5152
#ifdef CONFIG_GDBSTUB
5153
    use_gdbstub = 0;
5154
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
5155
#endif
5156
    snapshot = 0;
5157
    nographic = 0;
5158
    kernel_filename = NULL;
5159
    kernel_cmdline = "";
5160
#ifdef TARGET_PPC
5161
    cdrom_index = 1;
5162
#else
5163
    cdrom_index = 2;
5164
#endif
5165
    cyls = heads = secs = 0;
5166
    translation = BIOS_ATA_TRANSLATION_AUTO;
5167
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5168

    
5169
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5170
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
5171
        serial_devices[i][0] = '\0';
5172
    serial_device_index = 0;
5173
    
5174
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5175
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5176
        parallel_devices[i][0] = '\0';
5177
    parallel_device_index = 0;
5178
    
5179
    usb_devices_index = 0;
5180
    
5181
    nb_net_clients = 0;
5182

    
5183
    nb_nics = 0;
5184
    /* default mac address of the first network interface */
5185
    
5186
    optind = 1;
5187
    for(;;) {
5188
        if (optind >= argc)
5189
            break;
5190
        r = argv[optind];
5191
        if (r[0] != '-') {
5192
            hd_filename[0] = argv[optind++];
5193
        } else {
5194
            const QEMUOption *popt;
5195

    
5196
            optind++;
5197
            popt = qemu_options;
5198
            for(;;) {
5199
                if (!popt->name) {
5200
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
5201
                            argv[0], r);
5202
                    exit(1);
5203
                }
5204
                if (!strcmp(popt->name, r + 1))
5205
                    break;
5206
                popt++;
5207
            }
5208
            if (popt->flags & HAS_ARG) {
5209
                if (optind >= argc) {
5210
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
5211
                            argv[0], r);
5212
                    exit(1);
5213
                }
5214
                optarg = argv[optind++];
5215
            } else {
5216
                optarg = NULL;
5217
            }
5218

    
5219
            switch(popt->index) {
5220
            case QEMU_OPTION_M:
5221
                machine = find_machine(optarg);
5222
                if (!machine) {
5223
                    QEMUMachine *m;
5224
                    printf("Supported machines are:\n");
5225
                    for(m = first_machine; m != NULL; m = m->next) {
5226
                        printf("%-10s %s%s\n",
5227
                               m->name, m->desc, 
5228
                               m == first_machine ? " (default)" : "");
5229
                    }
5230
                    exit(1);
5231
                }
5232
                break;
5233
            case QEMU_OPTION_initrd:
5234
                initrd_filename = optarg;
5235
                break;
5236
            case QEMU_OPTION_hda:
5237
            case QEMU_OPTION_hdb:
5238
            case QEMU_OPTION_hdc:
5239
            case QEMU_OPTION_hdd:
5240
                {
5241
                    int hd_index;
5242
                    hd_index = popt->index - QEMU_OPTION_hda;
5243
                    hd_filename[hd_index] = optarg;
5244
                    if (hd_index == cdrom_index)
5245
                        cdrom_index = -1;
5246
                }
5247
                break;
5248
            case QEMU_OPTION_snapshot:
5249
                snapshot = 1;
5250
                break;
5251
            case QEMU_OPTION_hdachs:
5252
                {
5253
                    const char *p;
5254
                    p = optarg;
5255
                    cyls = strtol(p, (char **)&p, 0);
5256
                    if (cyls < 1 || cyls > 16383)
5257
                        goto chs_fail;
5258
                    if (*p != ',')
5259
                        goto chs_fail;
5260
                    p++;
5261
                    heads = strtol(p, (char **)&p, 0);
5262
                    if (heads < 1 || heads > 16)
5263
                        goto chs_fail;
5264
                    if (*p != ',')
5265
                        goto chs_fail;
5266
                    p++;
5267
                    secs = strtol(p, (char **)&p, 0);
5268
                    if (secs < 1 || secs > 63)
5269
                        goto chs_fail;
5270
                    if (*p == ',') {
5271
                        p++;
5272
                        if (!strcmp(p, "none"))
5273
                            translation = BIOS_ATA_TRANSLATION_NONE;
5274
                        else if (!strcmp(p, "lba"))
5275
                            translation = BIOS_ATA_TRANSLATION_LBA;
5276
                        else if (!strcmp(p, "auto"))
5277
                            translation = BIOS_ATA_TRANSLATION_AUTO;
5278
                        else
5279
                            goto chs_fail;
5280
                    } else if (*p != '\0') {
5281
                    chs_fail:
5282
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
5283
                        exit(1);
5284
                    }
5285
                }
5286
                break;
5287
            case QEMU_OPTION_nographic:
5288
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5289
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5290
                nographic = 1;
5291
                break;
5292
            case QEMU_OPTION_kernel:
5293
                kernel_filename = optarg;
5294
                break;
5295
            case QEMU_OPTION_append:
5296
                kernel_cmdline = optarg;
5297
                break;
5298
            case QEMU_OPTION_cdrom:
5299
                if (cdrom_index >= 0) {
5300
                    hd_filename[cdrom_index] = optarg;
5301
                }
5302
                break;
5303
            case QEMU_OPTION_boot:
5304
                boot_device = optarg[0];
5305
                if (boot_device != 'a' && 
5306
#ifdef TARGET_SPARC
5307
                    // Network boot
5308
                    boot_device != 'n' &&
5309
#endif
5310
                    boot_device != 'c' && boot_device != 'd') {
5311
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5312
                    exit(1);
5313
                }
5314
                break;
5315
            case QEMU_OPTION_fda:
5316
                fd_filename[0] = optarg;
5317
                break;
5318
            case QEMU_OPTION_fdb:
5319
                fd_filename[1] = optarg;
5320
                break;
5321
#ifdef TARGET_I386
5322
            case QEMU_OPTION_no_fd_bootchk:
5323
                fd_bootchk = 0;
5324
                break;
5325
#endif
5326
            case QEMU_OPTION_no_code_copy:
5327
                code_copy_enabled = 0;
5328
                break;
5329
            case QEMU_OPTION_net:
5330
                if (nb_net_clients >= MAX_NET_CLIENTS) {
5331
                    fprintf(stderr, "qemu: too many network clients\n");
5332
                    exit(1);
5333
                }
5334
                pstrcpy(net_clients[nb_net_clients],
5335
                        sizeof(net_clients[0]),
5336
                        optarg);
5337
                nb_net_clients++;
5338
                break;
5339
#ifdef CONFIG_SLIRP
5340
            case QEMU_OPTION_tftp:
5341
                tftp_prefix = optarg;
5342
                break;
5343
#ifndef _WIN32
5344
            case QEMU_OPTION_smb:
5345
                net_slirp_smb(optarg);
5346
                break;
5347
#endif
5348
            case QEMU_OPTION_redir:
5349
                net_slirp_redir(optarg);                
5350
                break;
5351
#endif
5352
#ifdef HAS_AUDIO
5353
            case QEMU_OPTION_audio_help:
5354
                AUD_help ();
5355
                exit (0);
5356
                break;
5357
            case QEMU_OPTION_soundhw:
5358
                select_soundhw (optarg);
5359
                break;
5360
#endif
5361
            case QEMU_OPTION_h:
5362
                help();
5363
                break;
5364
            case QEMU_OPTION_m:
5365
                ram_size = atoi(optarg) * 1024 * 1024;
5366
                if (ram_size <= 0)
5367
                    help();
5368
                if (ram_size > PHYS_RAM_MAX_SIZE) {
5369
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5370
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
5371
                    exit(1);
5372
                }
5373
                break;
5374
            case QEMU_OPTION_d:
5375
                {
5376
                    int mask;
5377
                    CPULogItem *item;
5378
                    
5379
                    mask = cpu_str_to_log_mask(optarg);
5380
                    if (!mask) {
5381
                        printf("Log items (comma separated):\n");
5382
                    for(item = cpu_log_items; item->mask != 0; item++) {
5383
                        printf("%-10s %s\n", item->name, item->help);
5384
                    }
5385
                    exit(1);
5386
                    }
5387
                    cpu_set_log(mask);
5388
                }
5389
                break;
5390
#ifdef CONFIG_GDBSTUB
5391
            case QEMU_OPTION_s:
5392
                use_gdbstub = 1;
5393
                break;
5394
            case QEMU_OPTION_p:
5395
                gdbstub_port = atoi(optarg);
5396
                break;
5397
#endif
5398
            case QEMU_OPTION_L:
5399
                bios_dir = optarg;
5400
                break;
5401
            case QEMU_OPTION_S:
5402
                start_emulation = 0;
5403
                break;
5404
            case QEMU_OPTION_k:
5405
                keyboard_layout = optarg;
5406
                break;
5407
            case QEMU_OPTION_localtime:
5408
                rtc_utc = 0;
5409
                break;
5410
            case QEMU_OPTION_cirrusvga:
5411
                cirrus_vga_enabled = 1;
5412
                break;
5413
            case QEMU_OPTION_std_vga:
5414
                cirrus_vga_enabled = 0;
5415
                break;
5416
            case QEMU_OPTION_g:
5417
                {
5418
                    const char *p;
5419
                    int w, h, depth;
5420
                    p = optarg;
5421
                    w = strtol(p, (char **)&p, 10);
5422
                    if (w <= 0) {
5423
                    graphic_error:
5424
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5425
                        exit(1);
5426
                    }
5427
                    if (*p != 'x')
5428
                        goto graphic_error;
5429
                    p++;
5430
                    h = strtol(p, (char **)&p, 10);
5431
                    if (h <= 0)
5432
                        goto graphic_error;
5433
                    if (*p == 'x') {
5434
                        p++;
5435
                        depth = strtol(p, (char **)&p, 10);
5436
                        if (depth != 8 && depth != 15 && depth != 16 && 
5437
                            depth != 24 && depth != 32)
5438
                            goto graphic_error;
5439
                    } else if (*p == '\0') {
5440
                        depth = graphic_depth;
5441
                    } else {
5442
                        goto graphic_error;
5443
                    }
5444
                    
5445
                    graphic_width = w;
5446
                    graphic_height = h;
5447
                    graphic_depth = depth;
5448
                }
5449
                break;
5450
            case QEMU_OPTION_monitor:
5451
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5452
                break;
5453
            case QEMU_OPTION_serial:
5454
                if (serial_device_index >= MAX_SERIAL_PORTS) {
5455
                    fprintf(stderr, "qemu: too many serial ports\n");
5456
                    exit(1);
5457
                }
5458
                pstrcpy(serial_devices[serial_device_index], 
5459
                        sizeof(serial_devices[0]), optarg);
5460
                serial_device_index++;
5461
                break;
5462
            case QEMU_OPTION_parallel:
5463
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5464
                    fprintf(stderr, "qemu: too many parallel ports\n");
5465
                    exit(1);
5466
                }
5467
                pstrcpy(parallel_devices[parallel_device_index], 
5468
                        sizeof(parallel_devices[0]), optarg);
5469
                parallel_device_index++;
5470
                break;
5471
            case QEMU_OPTION_loadvm:
5472
                loadvm = optarg;
5473
                break;
5474
            case QEMU_OPTION_full_screen:
5475
                full_screen = 1;
5476
                break;
5477
            case QEMU_OPTION_pidfile:
5478
                create_pidfile(optarg);
5479
                break;
5480
#ifdef TARGET_I386
5481
            case QEMU_OPTION_win2k_hack:
5482
                win2k_install_hack = 1;
5483
                break;
5484
#endif
5485
#ifdef USE_KQEMU
5486
            case QEMU_OPTION_no_kqemu:
5487
                kqemu_allowed = 0;
5488
                break;
5489
            case QEMU_OPTION_kernel_kqemu:
5490
                kqemu_allowed = 2;
5491
                break;
5492
#endif
5493
            case QEMU_OPTION_usb:
5494
                usb_enabled = 1;
5495
                break;
5496
            case QEMU_OPTION_usbdevice:
5497
                usb_enabled = 1;
5498
                if (usb_devices_index >= MAX_USB_CMDLINE) {
5499
                    fprintf(stderr, "Too many USB devices\n");
5500
                    exit(1);
5501
                }
5502
                pstrcpy(usb_devices[usb_devices_index],
5503
                        sizeof(usb_devices[usb_devices_index]),
5504
                        optarg);
5505
                usb_devices_index++;
5506
                break;
5507
            case QEMU_OPTION_smp:
5508
                smp_cpus = atoi(optarg);
5509
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5510
                    fprintf(stderr, "Invalid number of CPUs\n");
5511
                    exit(1);
5512
                }
5513
                break;
5514
            case QEMU_OPTION_vnc:
5515
                vnc_display = atoi(optarg);
5516
                if (vnc_display < 0) {
5517
                    fprintf(stderr, "Invalid VNC display\n");
5518
                    exit(1);
5519
                }
5520
                break;
5521
            case QEMU_OPTION_no_acpi:
5522
                acpi_enabled = 0;
5523
                break;
5524
            }
5525
        }
5526
    }
5527

    
5528
#ifdef USE_KQEMU
5529
    if (smp_cpus > 1)
5530
        kqemu_allowed = 0;
5531
#endif
5532
    linux_boot = (kernel_filename != NULL);
5533
        
5534
    if (!linux_boot && 
5535
        hd_filename[0] == '\0' && 
5536
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5537
        fd_filename[0] == '\0')
5538
        help();
5539
    
5540
    /* boot to cd by default if no hard disk */
5541
    if (hd_filename[0] == '\0' && boot_device == 'c') {
5542
        if (fd_filename[0] != '\0')
5543
            boot_device = 'a';
5544
        else
5545
            boot_device = 'd';
5546
    }
5547

    
5548
#if !defined(CONFIG_SOFTMMU)
5549
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5550
    {
5551
        static uint8_t stdout_buf[4096];
5552
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5553
    }
5554
#else
5555
    setvbuf(stdout, NULL, _IOLBF, 0);
5556
#endif
5557
    
5558
#ifdef _WIN32
5559
    socket_init();
5560
#endif
5561

    
5562
    /* init network clients */
5563
    if (nb_net_clients == 0) {
5564
        /* if no clients, we use a default config */
5565
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
5566
                "nic");
5567
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
5568
                "user");
5569
        nb_net_clients = 2;
5570
    }
5571

    
5572
    for(i = 0;i < nb_net_clients; i++) {
5573
        if (net_client_init(net_clients[i]) < 0)
5574
            exit(1);
5575
    }
5576

    
5577
    /* init the memory */
5578
    phys_ram_size = ram_size + vga_ram_size + bios_size;
5579

    
5580
#ifdef CONFIG_SOFTMMU
5581
    phys_ram_base = qemu_vmalloc(phys_ram_size);
5582
    if (!phys_ram_base) {
5583
        fprintf(stderr, "Could not allocate physical memory\n");
5584
        exit(1);
5585
    }
5586
#else
5587
    /* as we must map the same page at several addresses, we must use
5588
       a fd */
5589
    {
5590
        const char *tmpdir;
5591

    
5592
        tmpdir = getenv("QEMU_TMPDIR");
5593
        if (!tmpdir)
5594
            tmpdir = "/tmp";
5595
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5596
        if (mkstemp(phys_ram_file) < 0) {
5597
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
5598
                    phys_ram_file);
5599
            exit(1);
5600
        }
5601
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5602
        if (phys_ram_fd < 0) {
5603
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
5604
                    phys_ram_file);
5605
            exit(1);
5606
        }
5607
        ftruncate(phys_ram_fd, phys_ram_size);
5608
        unlink(phys_ram_file);
5609
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
5610
                             phys_ram_size, 
5611
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
5612
                             phys_ram_fd, 0);
5613
        if (phys_ram_base == MAP_FAILED) {
5614
            fprintf(stderr, "Could not map physical memory\n");
5615
            exit(1);
5616
        }
5617
    }
5618
#endif
5619

    
5620
    /* we always create the cdrom drive, even if no disk is there */
5621
    bdrv_init();
5622
    if (cdrom_index >= 0) {
5623
        bs_table[cdrom_index] = bdrv_new("cdrom");
5624
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5625
    }
5626

    
5627
    /* open the virtual block devices */
5628
    for(i = 0; i < MAX_DISKS; i++) {
5629
        if (hd_filename[i]) {
5630
            if (!bs_table[i]) {
5631
                char buf[64];
5632
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5633
                bs_table[i] = bdrv_new(buf);
5634
            }
5635
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5636
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5637
                        hd_filename[i]);
5638
                exit(1);
5639
            }
5640
            if (i == 0 && cyls != 0) {
5641
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5642
                bdrv_set_translation_hint(bs_table[i], translation);
5643
            }
5644
        }
5645
    }
5646

    
5647
    /* we always create at least one floppy disk */
5648
    fd_table[0] = bdrv_new("fda");
5649
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5650

    
5651
    for(i = 0; i < MAX_FD; i++) {
5652
        if (fd_filename[i]) {
5653
            if (!fd_table[i]) {
5654
                char buf[64];
5655
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5656
                fd_table[i] = bdrv_new(buf);
5657
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5658
            }
5659
            if (fd_filename[i] != '\0') {
5660
                if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5661
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5662
                            fd_filename[i]);
5663
                    exit(1);
5664
                }
5665
            }
5666
        }
5667
    }
5668

    
5669
    register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5670
    register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5671

    
5672
    init_ioports();
5673
    cpu_calibrate_ticks();
5674

    
5675
    /* terminal init */
5676
    if (nographic) {
5677
        dumb_display_init(ds);
5678
    } else if (vnc_display != -1) {
5679
        vnc_display_init(ds, vnc_display);
5680
    } else {
5681
#if defined(CONFIG_SDL)
5682
        sdl_display_init(ds, full_screen);
5683
#elif defined(CONFIG_COCOA)
5684
        cocoa_display_init(ds, full_screen);
5685
#else
5686
        dumb_display_init(ds);
5687
#endif
5688
    }
5689

    
5690
    monitor_hd = qemu_chr_open(monitor_device);
5691
    if (!monitor_hd) {
5692
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5693
        exit(1);
5694
    }
5695
    monitor_init(monitor_hd, !nographic);
5696

    
5697
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5698
        if (serial_devices[i][0] != '\0') {
5699
            serial_hds[i] = qemu_chr_open(serial_devices[i]);
5700
            if (!serial_hds[i]) {
5701
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
5702
                        serial_devices[i]);
5703
                exit(1);
5704
            }
5705
            if (!strcmp(serial_devices[i], "vc"))
5706
                qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5707
        }
5708
    }
5709

    
5710
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5711
        if (parallel_devices[i][0] != '\0') {
5712
            parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5713
            if (!parallel_hds[i]) {
5714
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
5715
                        parallel_devices[i]);
5716
                exit(1);
5717
            }
5718
            if (!strcmp(parallel_devices[i], "vc"))
5719
                qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5720
        }
5721
    }
5722

    
5723
    /* setup cpu signal handlers for MMU / self modifying code handling */
5724
#if !defined(CONFIG_SOFTMMU)
5725
    
5726
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5727
    {
5728
        stack_t stk;
5729
        signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5730
        stk.ss_sp = signal_stack;
5731
        stk.ss_size = SIGNAL_STACK_SIZE;
5732
        stk.ss_flags = 0;
5733

    
5734
        if (sigaltstack(&stk, NULL) < 0) {
5735
            perror("sigaltstack");
5736
            exit(1);
5737
        }
5738
    }
5739
#endif
5740
    {
5741
        struct sigaction act;
5742
        
5743
        sigfillset(&act.sa_mask);
5744
        act.sa_flags = SA_SIGINFO;
5745
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5746
        act.sa_flags |= SA_ONSTACK;
5747
#endif
5748
        act.sa_sigaction = host_segv_handler;
5749
        sigaction(SIGSEGV, &act, NULL);
5750
        sigaction(SIGBUS, &act, NULL);
5751
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
5752
        sigaction(SIGFPE, &act, NULL);
5753
#endif
5754
    }
5755
#endif
5756

    
5757
#ifndef _WIN32
5758
    {
5759
        struct sigaction act;
5760
        sigfillset(&act.sa_mask);
5761
        act.sa_flags = 0;
5762
        act.sa_handler = SIG_IGN;
5763
        sigaction(SIGPIPE, &act, NULL);
5764
    }
5765
#endif
5766
    init_timers();
5767

    
5768
    machine->init(ram_size, vga_ram_size, boot_device,
5769
                  ds, fd_filename, snapshot,
5770
                  kernel_filename, kernel_cmdline, initrd_filename);
5771

    
5772
    /* init USB devices */
5773
    if (usb_enabled) {
5774
        for(i = 0; i < usb_devices_index; i++) {
5775
            if (usb_device_add(usb_devices[i]) < 0) {
5776
                fprintf(stderr, "Warning: could not add USB device %s\n",
5777
                        usb_devices[i]);
5778
            }
5779
        }
5780
    }
5781

    
5782
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5783
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5784

    
5785
#ifdef CONFIG_GDBSTUB
5786
    if (use_gdbstub) {
5787
        if (gdbserver_start(gdbstub_port) < 0) {
5788
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
5789
                    gdbstub_port);
5790
            exit(1);
5791
        } else {
5792
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
5793
        }
5794
    } else 
5795
#endif
5796
    if (loadvm)
5797
        qemu_loadvm(loadvm);
5798

    
5799
    {
5800
        /* XXX: simplify init */
5801
        read_passwords();
5802
        if (start_emulation) {
5803
            vm_start();
5804
        }
5805
    }
5806
    main_loop();
5807
    quit_timers();
5808
    return 0;
5809
}