Statistics
| Branch: | Revision:

root / vl.c @ eec85c2a

History | View | Annotate | Download (195.6 kB)

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

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

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

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

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

    
74
#include "qemu_socket.h"
75

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

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

    
87
#include "disas.h"
88

    
89
#include "exec-all.h"
90

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

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

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

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

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

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

    
117
#define DISK_OPTIONS_SIZE 256
118

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

    
180
/***********************************************************/
181
/* x86 ISA bus support */
182

    
183
target_phys_addr_t isa_mem_base = 0;
184
PicState2 *isa_pic;
185

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

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

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

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

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

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

    
233
void init_ioports(void)
234
{
235
    int i;
236

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

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

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

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

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

    
297
void isa_unassign_ioport(int start, int length)
298
{
299
    int i;
300

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

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

    
312
/***********************************************************/
313

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

    
319
    if (buf_size <= 0)
320
        return;
321

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

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

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

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

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

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

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

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

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

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

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

    
463
/***********************************************************/
464
/* keyboard/mouse */
465

    
466
static QEMUPutKBDEvent *qemu_put_kbd_event;
467
static void *qemu_put_kbd_event_opaque;
468
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
469
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
470

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

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

    
483
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
484
    if (!s)
485
        return NULL;
486

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

    
493
    if (!qemu_put_mouse_event_head) {
494
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
495
        return s;
496
    }
497

    
498
    cursor = qemu_put_mouse_event_head;
499
    while (cursor->next != NULL)
500
        cursor = cursor->next;
501

    
502
    cursor->next = s;
503
    qemu_put_mouse_event_current = s;
504

    
505
    return s;
506
}
507

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

    
512
    if (!qemu_put_mouse_event_head || entry == NULL)
513
        return;
514

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

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

    
532
    prev->next = entry->next;
533

    
534
    if (qemu_put_mouse_event_current == entry)
535
        qemu_put_mouse_event_current = prev;
536

    
537
    qemu_free(entry->qemu_put_mouse_event_name);
538
    qemu_free(entry);
539
}
540

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

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

    
553
    if (!qemu_put_mouse_event_current) {
554
        return;
555
    }
556

    
557
    mouse_event =
558
        qemu_put_mouse_event_current->qemu_put_mouse_event;
559
    mouse_event_opaque =
560
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
561

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

    
567
int kbd_mouse_is_absolute(void)
568
{
569
    if (!qemu_put_mouse_event_current)
570
        return 0;
571

    
572
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
573
}
574

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

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

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

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

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

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

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

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

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

    
642
/***********************************************************/
643
/* real time host monotonic timer */
644

    
645
#define QEMU_TIMER_BASE 1000000000LL
646

    
647
#ifdef WIN32
648

    
649
static int64_t clock_freq;
650

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

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

    
670
#else
671

    
672
static int use_rt_clock;
673

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

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

    
705
#endif
706

    
707
/***********************************************************/
708
/* guest cycle counter */
709

    
710
static int64_t cpu_ticks_prev;
711
static int64_t cpu_ticks_offset;
712
static int64_t cpu_clock_offset;
713
static int cpu_ticks_enabled;
714

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

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

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

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

    
766
/***********************************************************/
767
/* timers */
768
 
769
#define QEMU_TIMER_REALTIME 0
770
#define QEMU_TIMER_VIRTUAL  1
771

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

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

    
785
QEMUClock *rt_clock;
786
QEMUClock *vm_clock;
787

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

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

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

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

    
819
void qemu_free_timer(QEMUTimer *ts)
820
{
821
    qemu_free(ts);
822
}
823

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

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

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

    
850
    qemu_del_timer(ts);
851

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1028
#ifndef _WIN32
1029

    
1030
#if defined(__linux__)
1031

    
1032
#define RTC_FREQ 1024
1033

    
1034
static int rtc_fd;
1035

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

    
1056
#else
1057

    
1058
static int start_rtc_timer(void)
1059
{
1060
    return -1;
1061
}
1062

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

    
1065
#endif /* !defined(_WIN32) */
1066

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

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

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

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

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

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

    
1165
/***********************************************************/
1166
/* character device */
1167

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

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

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

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

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

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

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

    
1219
static CharDriverState *qemu_chr_open_null(void)
1220
{
1221
    CharDriverState *chr;
1222

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

    
1231
#ifdef _WIN32
1232

    
1233
static void socket_cleanup(void)
1234
{
1235
    WSACleanup();
1236
}
1237

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

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

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

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

    
1282
#else
1283

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

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

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

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

    
1315
#ifndef _WIN32
1316

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

    
1325
#define STDIO_MAX_CLIENTS 2
1326

    
1327
static int stdio_nb_clients;
1328
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1329

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

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

    
1341
    s->max_size = s->fd_can_read(s->fd_opaque);
1342
    return s->max_size;
1343
}
1344

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

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

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

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

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

    
1408
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1409
{
1410
    int fd_out;
1411

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

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

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

    
1439

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

    
1443
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1444

    
1445
#define TERM_FIFO_MAX_SIZE 1
1446

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

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

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

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

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

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

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

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

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

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

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

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

    
1616
static void term_init(void)
1617
{
1618
    struct termios tty;
1619

    
1620
    tcgetattr (0, &tty);
1621
    oldtty = tty;
1622
    old_fd0_flags = fcntl(0, F_GETFL);
1623

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

    
1638
    atexit(term_exit);
1639

    
1640
    fcntl(0, F_SETFL, O_NONBLOCK);
1641
}
1642

    
1643
static CharDriverState *qemu_chr_open_stdio(void)
1644
{
1645
    CharDriverState *chr;
1646

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

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

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

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

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

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

    
1743
    cfsetispeed(&tty, spd);
1744
    cfsetospeed(&tty, spd);
1745

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

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

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

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

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

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

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

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

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

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

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

    
1895
#endif /* !defined(_WIN32) */
1896

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

    
1909
#define NSENDBUF 2048
1910
#define NRECVBUF 2048
1911
#define MAXCONNECT 1
1912
#define NTIMEOUT 5000
1913

    
1914
static int win_chr_poll(void *opaque);
1915
static int win_chr_pipe_poll(void *opaque);
1916

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

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

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

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

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

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

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

    
2004
 fail:
2005
    win_chr_close2(s);
2006
    return -1;
2007
}
2008

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

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

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

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

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

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

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

    
2102
    s->fd_can_read = fd_can_read;
2103
    s->fd_read = fd_read;
2104
    s->win_opaque = opaque;
2105
}
2106

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

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

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

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

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

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

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

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

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

    
2204
 fail:
2205
    win_chr_close2(s);
2206
    return -1;
2207
}
2208

    
2209

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

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

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

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

    
2265
    return qemu_chr_open_win_file(fd_out);
2266
}
2267
#endif
2268

    
2269
/***********************************************************/
2270
/* UDP Net console */
2271

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

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

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

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

    
2297
    s->max_size = s->fd_can_read(s->fd_opaque);
2298

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2402
/***********************************************************/
2403
/* TCP Net console */
2404

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

    
2416
static void tcp_chr_accept(void *opaque);
2417

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

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

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

    
2456
    int i;
2457
    int j = 0;
2458

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

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

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

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

    
2527
    s->fd_can_read = fd_can_read;
2528
    s->fd_read = fd_read;
2529
    s->fd_opaque = opaque;
2530
}
2531

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

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

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

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

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

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

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

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

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

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

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

    
2669
    if (!is_waitconnect)
2670
        socket_set_nonblock(fd);
2671

    
2672
    s->connected = 0;
2673
    s->fd = -1;
2674
    s->listen_fd = -1;
2675
    s->is_unix = is_unix;
2676

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

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

    
2701
        ret = listen(fd, 0);
2702
        if (ret < 0)
2703
            goto fail;
2704

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

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

    
2747
CharDriverState *qemu_chr_open(const char *filename)
2748
{
2749
    const char *p;
2750

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

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

    
2808
/***********************************************************/
2809
/* network device redirectors */
2810

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

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

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

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

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

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

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

    
2896
    if (parse_host_port(haddr, host_str) < 0)
2897
        goto fail;
2898

    
2899
    if (!src_str || *src_str == '\0')
2900
        src_str = ":0";
2901

    
2902
    if (parse_host_port(saddr, src_str) < 0)
2903
        goto fail;
2904

    
2905
    free(str);
2906
    return(0);
2907

    
2908
fail:
2909
    free(str);
2910
    return -1;
2911
}
2912

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

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

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

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

    
2954
    memset(uaddr, 0, sizeof(*uaddr));
2955

    
2956
    uaddr->sun_family = AF_UNIX;
2957
    memcpy(uaddr->sun_path, str, len);
2958

    
2959
    return 0;
2960
}
2961
#endif
2962

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

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

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

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

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

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

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

    
3035
#if defined(CONFIG_SLIRP)
3036

    
3037
/* slirp network adapter */
3038

    
3039
static int slirp_inited;
3040
static VLANClientState *slirp_vc;
3041

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

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

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

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

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

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

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

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

    
3133
char smb_dir[1024];
3134

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

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

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

    
3165
    if (!slirp_inited) {
3166
        slirp_inited = 1;
3167
        slirp_init();
3168
    }
3169

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

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

    
3213
#endif /* !defined(_WIN32) */
3214

    
3215
#endif /* CONFIG_SLIRP */
3216

    
3217
#if !defined(_WIN32)
3218

    
3219
typedef struct TAPState {
3220
    VLANClientState *vc;
3221
    int fd;
3222
} TAPState;
3223

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

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

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

    
3249
/* fd support */
3250

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

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

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

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

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

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

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

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

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

    
3368
#endif /* !_WIN32 */
3369

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

    
3381
typedef struct NetSocketListenState {
3382
    VLANState *vlan;
3383
    int fd;
3384
} NetSocketListenState;
3385

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3714
    if (parse_host_port(&saddr, host_str) < 0)
3715
        return -1;
3716

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

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

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

    
3757
    if (parse_host_port(&saddr, host_str) < 0)
3758
        return -1;
3759

    
3760

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

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

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

    
3776
}
3777

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

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

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

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

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

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

    
3946
void do_info_network(void)
3947
{
3948
    VLANState *vlan;
3949
    VLANClientState *vc;
3950

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

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

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

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

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

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

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

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

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

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

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

    
4041
    for(i = 0; i < num_scsi_disks; i++) {
4042

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

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

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

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

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

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

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

    
4126
    return 0;
4127
}
4128

    
4129

    
4130
/***********************************************************/
4131
/* USB devices */
4132

    
4133
static USBPort *used_usb_ports;
4134
static USBPort *free_usb_ports;
4135

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

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

    
4153
    if (!free_usb_ports)
4154
        return -1;
4155

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

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

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

    
4180
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4181
        usb_attach(port, hub);
4182
        port = free_usb_ports;
4183
    }
4184

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

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

    
4200
    if (!used_usb_ports)
4201
        return -1;
4202

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

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

    
4218
    if (!port)
4219
        return -1;
4220

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

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

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

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

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

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

    
4280
/***********************************************************/
4281
/* pid file */
4282

    
4283
static char *pid_filename;
4284

    
4285
/* Remove PID file. Called on normal exit */
4286

    
4287
static void remove_pidfile(void) 
4288
{
4289
    unlink (pid_filename);
4290
}
4291

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

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

    
4320
/***********************************************************/
4321
/* dumb display */
4322

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

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

    
4331
static void dumb_refresh(DisplayState *ds)
4332
{
4333
    vga_hw_update();
4334
}
4335

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

    
4346
/***********************************************************/
4347
/* I/O handling */
4348

    
4349
#define MAX_IO_HANDLERS 64
4350

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

    
4362
static IOHandlerRecord *first_io_handler;
4363

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

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

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

    
4415
/***********************************************************/
4416
/* Polling handling */
4417

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

    
4424
static PollingEntry *first_polling_entry;
4425

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

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

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

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

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

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

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

    
4497
/***********************************************************/
4498
/* savevm/loadvm support */
4499

    
4500
#define IO_BUF_SIZE 32768
4501

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

    
4515
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4516
{
4517
    QEMUFile *f;
4518

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

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

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

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

    
4572
static void qemu_fill_buffer(QEMUFile *f)
4573
{
4574
    int len;
4575

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4742
static SaveStateEntry *first_se;
4743

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

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

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

    
4772
#define QEMU_VM_FILE_MAGIC   0x5145564d
4773
#define QEMU_VM_FILE_VERSION 0x00000002
4774

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

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

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

    
4792
        qemu_put_be32(f, se->instance_id);
4793
        qemu_put_be32(f, se->version_id);
4794

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

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

    
4813
    ret = 0;
4814
    return ret;
4815
}
4816

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

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

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

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

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

    
4897
static BlockDriverState *get_bs_snapshots(void)
4898
{
4899
    BlockDriverState *bs;
4900
    int i;
4901

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

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

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

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

    
4957
    /* ??? Should this occur after vm_stop?  */
4958
    qemu_aio_flush();
4959

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

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

    
5013
    for(i = 0; i < MAX_DISKS; i++) {
5014
        bs1 = bs_table[i];
5015
        if (bdrv_has_snapshot(bs1)) {
5016
            if (must_delete) {
5017
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5018
                if (ret < 0) {
5019
                    term_printf("Error while deleting snapshot on '%s'\n",
5020
                                bdrv_get_device_name(bs1));
5021
                }
5022
            }
5023
            ret = bdrv_snapshot_create(bs1, sn);
5024
            if (ret < 0) {
5025
                term_printf("Error while creating snapshot on '%s'\n",
5026
                            bdrv_get_device_name(bs1));
5027
            }
5028
        }
5029
    }
5030

    
5031
 the_end:
5032
    if (saved_vm_running)
5033
        vm_start();
5034
}
5035

    
5036
void do_loadvm(const char *name)
5037
{
5038
    BlockDriverState *bs, *bs1;
5039
    BlockDriverInfo bdi1, *bdi = &bdi1;
5040
    QEMUFile *f;
5041
    int i, ret;
5042
    int saved_vm_running;
5043

    
5044
    bs = get_bs_snapshots();
5045
    if (!bs) {
5046
        term_printf("No block device supports snapshots\n");
5047
        return;
5048
    }
5049
    
5050
    /* Flush all IO requests so they don't interfere with the new state.  */
5051
    qemu_aio_flush();
5052

    
5053
    saved_vm_running = vm_running;
5054
    vm_stop(0);
5055

    
5056
    for(i = 0; i <= MAX_DISKS; i++) {
5057
        bs1 = bs_table[i];
5058
        if (bdrv_has_snapshot(bs1)) {
5059
            ret = bdrv_snapshot_goto(bs1, name);
5060
            if (ret < 0) {
5061
                if (bs != bs1)
5062
                    term_printf("Warning: ");
5063
                switch(ret) {
5064
                case -ENOTSUP:
5065
                    term_printf("Snapshots not supported on device '%s'\n",
5066
                                bdrv_get_device_name(bs1));
5067
                    break;
5068
                case -ENOENT:
5069
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
5070
                                name, bdrv_get_device_name(bs1));
5071
                    break;
5072
                default:
5073
                    term_printf("Error %d while activating snapshot on '%s'\n",
5074
                                ret, bdrv_get_device_name(bs1));
5075
                    break;
5076
                }
5077
                /* fatal on snapshot block device */
5078
                if (bs == bs1)
5079
                    goto the_end;
5080
            }
5081
        }
5082
    }
5083

    
5084
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5085
        term_printf("Device %s does not support VM state snapshots\n",
5086
                    bdrv_get_device_name(bs));
5087
        return;
5088
    }
5089
    
5090
    /* restore the VM state */
5091
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5092
    if (!f) {
5093
        term_printf("Could not open VM state file\n");
5094
        goto the_end;
5095
    }
5096
    ret = qemu_loadvm_state(f);
5097
    qemu_fclose(f);
5098
    if (ret < 0) {
5099
        term_printf("Error %d while loading VM state\n", ret);
5100
    }
5101
 the_end:
5102
    if (saved_vm_running)
5103
        vm_start();
5104
}
5105

    
5106
void do_delvm(const char *name)
5107
{
5108
    BlockDriverState *bs, *bs1;
5109
    int i, ret;
5110

    
5111
    bs = get_bs_snapshots();
5112
    if (!bs) {
5113
        term_printf("No block device supports snapshots\n");
5114
        return;
5115
    }
5116
    
5117
    for(i = 0; i <= MAX_DISKS; i++) {
5118
        bs1 = bs_table[i];
5119
        if (bdrv_has_snapshot(bs1)) {
5120
            ret = bdrv_snapshot_delete(bs1, name);
5121
            if (ret < 0) {
5122
                if (ret == -ENOTSUP)
5123
                    term_printf("Snapshots not supported on device '%s'\n",
5124
                                bdrv_get_device_name(bs1));
5125
                else
5126
                    term_printf("Error %d while deleting snapshot on '%s'\n",
5127
                                ret, bdrv_get_device_name(bs1));
5128
            }
5129
        }
5130
    }
5131
}
5132

    
5133
void do_info_snapshots(void)
5134
{
5135
    BlockDriverState *bs, *bs1;
5136
    QEMUSnapshotInfo *sn_tab, *sn;
5137
    int nb_sns, i;
5138
    char buf[256];
5139

    
5140
    bs = get_bs_snapshots();
5141
    if (!bs) {
5142
        term_printf("No available block device supports snapshots\n");
5143
        return;
5144
    }
5145
    term_printf("Snapshot devices:");
5146
    for(i = 0; i <= MAX_DISKS; i++) {
5147
        bs1 = bs_table[i];
5148
        if (bdrv_has_snapshot(bs1)) {
5149
            if (bs == bs1)
5150
                term_printf(" %s", bdrv_get_device_name(bs1));
5151
        }
5152
    }
5153
    term_printf("\n");
5154

    
5155
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5156
    if (nb_sns < 0) {
5157
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5158
        return;
5159
    }
5160
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5161
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5162
    for(i = 0; i < nb_sns; i++) {
5163
        sn = &sn_tab[i];
5164
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5165
    }
5166
    qemu_free(sn_tab);
5167
}
5168

    
5169
/***********************************************************/
5170
/* cpu save/restore */
5171

    
5172
#if defined(TARGET_I386)
5173

    
5174
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5175
{
5176
    qemu_put_be32(f, dt->selector);
5177
    qemu_put_betl(f, dt->base);
5178
    qemu_put_be32(f, dt->limit);
5179
    qemu_put_be32(f, dt->flags);
5180
}
5181

    
5182
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5183
{
5184
    dt->selector = qemu_get_be32(f);
5185
    dt->base = qemu_get_betl(f);
5186
    dt->limit = qemu_get_be32(f);
5187
    dt->flags = qemu_get_be32(f);
5188
}
5189

    
5190
void cpu_save(QEMUFile *f, void *opaque)
5191
{
5192
    CPUState *env = opaque;
5193
    uint16_t fptag, fpus, fpuc, fpregs_format;
5194
    uint32_t hflags;
5195
    int i;
5196
    
5197
    for(i = 0; i < CPU_NB_REGS; i++)
5198
        qemu_put_betls(f, &env->regs[i]);
5199
    qemu_put_betls(f, &env->eip);
5200
    qemu_put_betls(f, &env->eflags);
5201
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5202
    qemu_put_be32s(f, &hflags);
5203
    
5204
    /* FPU */
5205
    fpuc = env->fpuc;
5206
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5207
    fptag = 0;
5208
    for(i = 0; i < 8; i++) {
5209
        fptag |= ((!env->fptags[i]) << i);
5210
    }
5211
    
5212
    qemu_put_be16s(f, &fpuc);
5213
    qemu_put_be16s(f, &fpus);
5214
    qemu_put_be16s(f, &fptag);
5215

    
5216
#ifdef USE_X86LDOUBLE
5217
    fpregs_format = 0;
5218
#else
5219
    fpregs_format = 1;
5220
#endif
5221
    qemu_put_be16s(f, &fpregs_format);
5222
    
5223
    for(i = 0; i < 8; i++) {
5224
#ifdef USE_X86LDOUBLE
5225
        {
5226
            uint64_t mant;
5227
            uint16_t exp;
5228
            /* we save the real CPU data (in case of MMX usage only 'mant'
5229
               contains the MMX register */
5230
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5231
            qemu_put_be64(f, mant);
5232
            qemu_put_be16(f, exp);
5233
        }
5234
#else
5235
        /* if we use doubles for float emulation, we save the doubles to
5236
           avoid losing information in case of MMX usage. It can give
5237
           problems if the image is restored on a CPU where long
5238
           doubles are used instead. */
5239
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5240
#endif
5241
    }
5242

    
5243
    for(i = 0; i < 6; i++)
5244
        cpu_put_seg(f, &env->segs[i]);
5245
    cpu_put_seg(f, &env->ldt);
5246
    cpu_put_seg(f, &env->tr);
5247
    cpu_put_seg(f, &env->gdt);
5248
    cpu_put_seg(f, &env->idt);
5249
    
5250
    qemu_put_be32s(f, &env->sysenter_cs);
5251
    qemu_put_be32s(f, &env->sysenter_esp);
5252
    qemu_put_be32s(f, &env->sysenter_eip);
5253
    
5254
    qemu_put_betls(f, &env->cr[0]);
5255
    qemu_put_betls(f, &env->cr[2]);
5256
    qemu_put_betls(f, &env->cr[3]);
5257
    qemu_put_betls(f, &env->cr[4]);
5258
    
5259
    for(i = 0; i < 8; i++)
5260
        qemu_put_betls(f, &env->dr[i]);
5261

    
5262
    /* MMU */
5263
    qemu_put_be32s(f, &env->a20_mask);
5264

    
5265
    /* XMM */
5266
    qemu_put_be32s(f, &env->mxcsr);
5267
    for(i = 0; i < CPU_NB_REGS; i++) {
5268
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5269
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5270
    }
5271

    
5272
#ifdef TARGET_X86_64
5273
    qemu_put_be64s(f, &env->efer);
5274
    qemu_put_be64s(f, &env->star);
5275
    qemu_put_be64s(f, &env->lstar);
5276
    qemu_put_be64s(f, &env->cstar);
5277
    qemu_put_be64s(f, &env->fmask);
5278
    qemu_put_be64s(f, &env->kernelgsbase);
5279
#endif
5280
    qemu_put_be32s(f, &env->smbase);
5281
}
5282

    
5283
#ifdef USE_X86LDOUBLE
5284
/* XXX: add that in a FPU generic layer */
5285
union x86_longdouble {
5286
    uint64_t mant;
5287
    uint16_t exp;
5288
};
5289

    
5290
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5291
#define EXPBIAS1 1023
5292
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5293
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5294

    
5295
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5296
{
5297
    int e;
5298
    /* mantissa */
5299
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5300
    /* exponent + sign */
5301
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5302
    e |= SIGND1(temp) >> 16;
5303
    p->exp = e;
5304
}
5305
#endif
5306

    
5307
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5308
{
5309
    CPUState *env = opaque;
5310
    int i, guess_mmx;
5311
    uint32_t hflags;
5312
    uint16_t fpus, fpuc, fptag, fpregs_format;
5313

    
5314
    if (version_id != 3 && version_id != 4)
5315
        return -EINVAL;
5316
    for(i = 0; i < CPU_NB_REGS; i++)
5317
        qemu_get_betls(f, &env->regs[i]);
5318
    qemu_get_betls(f, &env->eip);
5319
    qemu_get_betls(f, &env->eflags);
5320
    qemu_get_be32s(f, &hflags);
5321

    
5322
    qemu_get_be16s(f, &fpuc);
5323
    qemu_get_be16s(f, &fpus);
5324
    qemu_get_be16s(f, &fptag);
5325
    qemu_get_be16s(f, &fpregs_format);
5326
    
5327
    /* NOTE: we cannot always restore the FPU state if the image come
5328
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5329
       if we are in an MMX state to restore correctly in that case. */
5330
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5331
    for(i = 0; i < 8; i++) {
5332
        uint64_t mant;
5333
        uint16_t exp;
5334
        
5335
        switch(fpregs_format) {
5336
        case 0:
5337
            mant = qemu_get_be64(f);
5338
            exp = qemu_get_be16(f);
5339
#ifdef USE_X86LDOUBLE
5340
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5341
#else
5342
            /* difficult case */
5343
            if (guess_mmx)
5344
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5345
            else
5346
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5347
#endif
5348
            break;
5349
        case 1:
5350
            mant = qemu_get_be64(f);
5351
#ifdef USE_X86LDOUBLE
5352
            {
5353
                union x86_longdouble *p;
5354
                /* difficult case */
5355
                p = (void *)&env->fpregs[i];
5356
                if (guess_mmx) {
5357
                    p->mant = mant;
5358
                    p->exp = 0xffff;
5359
                } else {
5360
                    fp64_to_fp80(p, mant);
5361
                }
5362
            }
5363
#else
5364
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5365
#endif            
5366
            break;
5367
        default:
5368
            return -EINVAL;
5369
        }
5370
    }
5371

    
5372
    env->fpuc = fpuc;
5373
    /* XXX: restore FPU round state */
5374
    env->fpstt = (fpus >> 11) & 7;
5375
    env->fpus = fpus & ~0x3800;
5376
    fptag ^= 0xff;
5377
    for(i = 0; i < 8; i++) {
5378
        env->fptags[i] = (fptag >> i) & 1;
5379
    }
5380
    
5381
    for(i = 0; i < 6; i++)
5382
        cpu_get_seg(f, &env->segs[i]);
5383
    cpu_get_seg(f, &env->ldt);
5384
    cpu_get_seg(f, &env->tr);
5385
    cpu_get_seg(f, &env->gdt);
5386
    cpu_get_seg(f, &env->idt);
5387
    
5388
    qemu_get_be32s(f, &env->sysenter_cs);
5389
    qemu_get_be32s(f, &env->sysenter_esp);
5390
    qemu_get_be32s(f, &env->sysenter_eip);
5391
    
5392
    qemu_get_betls(f, &env->cr[0]);
5393
    qemu_get_betls(f, &env->cr[2]);
5394
    qemu_get_betls(f, &env->cr[3]);
5395
    qemu_get_betls(f, &env->cr[4]);
5396
    
5397
    for(i = 0; i < 8; i++)
5398
        qemu_get_betls(f, &env->dr[i]);
5399

    
5400
    /* MMU */
5401
    qemu_get_be32s(f, &env->a20_mask);
5402

    
5403
    qemu_get_be32s(f, &env->mxcsr);
5404
    for(i = 0; i < CPU_NB_REGS; i++) {
5405
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5406
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5407
    }
5408

    
5409
#ifdef TARGET_X86_64
5410
    qemu_get_be64s(f, &env->efer);
5411
    qemu_get_be64s(f, &env->star);
5412
    qemu_get_be64s(f, &env->lstar);
5413
    qemu_get_be64s(f, &env->cstar);
5414
    qemu_get_be64s(f, &env->fmask);
5415
    qemu_get_be64s(f, &env->kernelgsbase);
5416
#endif
5417
    if (version_id >= 4) 
5418
        qemu_get_be32s(f, &env->smbase);
5419

    
5420
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5421
    env->hflags = hflags;
5422
    tlb_flush(env, 1);
5423
    return 0;
5424
}
5425

    
5426
#elif defined(TARGET_PPC)
5427
void cpu_save(QEMUFile *f, void *opaque)
5428
{
5429
}
5430

    
5431
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5432
{
5433
    return 0;
5434
}
5435

    
5436
#elif defined(TARGET_MIPS)
5437
void cpu_save(QEMUFile *f, void *opaque)
5438
{
5439
}
5440

    
5441
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5442
{
5443
    return 0;
5444
}
5445

    
5446
#elif defined(TARGET_SPARC)
5447
void cpu_save(QEMUFile *f, void *opaque)
5448
{
5449
    CPUState *env = opaque;
5450
    int i;
5451
    uint32_t tmp;
5452

    
5453
    for(i = 0; i < 8; i++)
5454
        qemu_put_betls(f, &env->gregs[i]);
5455
    for(i = 0; i < NWINDOWS * 16; i++)
5456
        qemu_put_betls(f, &env->regbase[i]);
5457

    
5458
    /* FPU */
5459
    for(i = 0; i < TARGET_FPREGS; i++) {
5460
        union {
5461
            float32 f;
5462
            uint32_t i;
5463
        } u;
5464
        u.f = env->fpr[i];
5465
        qemu_put_be32(f, u.i);
5466
    }
5467

    
5468
    qemu_put_betls(f, &env->pc);
5469
    qemu_put_betls(f, &env->npc);
5470
    qemu_put_betls(f, &env->y);
5471
    tmp = GET_PSR(env);
5472
    qemu_put_be32(f, tmp);
5473
    qemu_put_betls(f, &env->fsr);
5474
    qemu_put_betls(f, &env->tbr);
5475
#ifndef TARGET_SPARC64
5476
    qemu_put_be32s(f, &env->wim);
5477
    /* MMU */
5478
    for(i = 0; i < 16; i++)
5479
        qemu_put_be32s(f, &env->mmuregs[i]);
5480
#endif
5481
}
5482

    
5483
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5484
{
5485
    CPUState *env = opaque;
5486
    int i;
5487
    uint32_t tmp;
5488

    
5489
    for(i = 0; i < 8; i++)
5490
        qemu_get_betls(f, &env->gregs[i]);
5491
    for(i = 0; i < NWINDOWS * 16; i++)
5492
        qemu_get_betls(f, &env->regbase[i]);
5493

    
5494
    /* FPU */
5495
    for(i = 0; i < TARGET_FPREGS; i++) {
5496
        union {
5497
            float32 f;
5498
            uint32_t i;
5499
        } u;
5500
        u.i = qemu_get_be32(f);
5501
        env->fpr[i] = u.f;
5502
    }
5503

    
5504
    qemu_get_betls(f, &env->pc);
5505
    qemu_get_betls(f, &env->npc);
5506
    qemu_get_betls(f, &env->y);
5507
    tmp = qemu_get_be32(f);
5508
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5509
                     correctly updated */
5510
    PUT_PSR(env, tmp);
5511
    qemu_get_betls(f, &env->fsr);
5512
    qemu_get_betls(f, &env->tbr);
5513
#ifndef TARGET_SPARC64
5514
    qemu_get_be32s(f, &env->wim);
5515
    /* MMU */
5516
    for(i = 0; i < 16; i++)
5517
        qemu_get_be32s(f, &env->mmuregs[i]);
5518
#endif
5519
    tlb_flush(env, 1);
5520
    return 0;
5521
}
5522

    
5523
#elif defined(TARGET_ARM)
5524

    
5525
/* ??? Need to implement these.  */
5526
void cpu_save(QEMUFile *f, void *opaque)
5527
{
5528
}
5529

    
5530
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5531
{
5532
    return 0;
5533
}
5534

    
5535
#else
5536

    
5537
#warning No CPU save/restore functions
5538

    
5539
#endif
5540

    
5541
/***********************************************************/
5542
/* ram save/restore */
5543

    
5544
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5545
{
5546
    int v;
5547

    
5548
    v = qemu_get_byte(f);
5549
    switch(v) {
5550
    case 0:
5551
        if (qemu_get_buffer(f, buf, len) != len)
5552
            return -EIO;
5553
        break;
5554
    case 1:
5555
        v = qemu_get_byte(f);
5556
        memset(buf, v, len);
5557
        break;
5558
    default:
5559
        return -EINVAL;
5560
    }
5561
    return 0;
5562
}
5563

    
5564
static int ram_load_v1(QEMUFile *f, void *opaque)
5565
{
5566
    int i, ret;
5567

    
5568
    if (qemu_get_be32(f) != phys_ram_size)
5569
        return -EINVAL;
5570
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5571
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5572
        if (ret)
5573
            return ret;
5574
    }
5575
    return 0;
5576
}
5577

    
5578
#define BDRV_HASH_BLOCK_SIZE 1024
5579
#define IOBUF_SIZE 4096
5580
#define RAM_CBLOCK_MAGIC 0xfabe
5581

    
5582
typedef struct RamCompressState {
5583
    z_stream zstream;
5584
    QEMUFile *f;
5585
    uint8_t buf[IOBUF_SIZE];
5586
} RamCompressState;
5587

    
5588
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5589
{
5590
    int ret;
5591
    memset(s, 0, sizeof(*s));
5592
    s->f = f;
5593
    ret = deflateInit2(&s->zstream, 1,
5594
                       Z_DEFLATED, 15, 
5595
                       9, Z_DEFAULT_STRATEGY);
5596
    if (ret != Z_OK)
5597
        return -1;
5598
    s->zstream.avail_out = IOBUF_SIZE;
5599
    s->zstream.next_out = s->buf;
5600
    return 0;
5601
}
5602

    
5603
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5604
{
5605
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5606
    qemu_put_be16(s->f, len);
5607
    qemu_put_buffer(s->f, buf, len);
5608
}
5609

    
5610
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5611
{
5612
    int ret;
5613

    
5614
    s->zstream.avail_in = len;
5615
    s->zstream.next_in = (uint8_t *)buf;
5616
    while (s->zstream.avail_in > 0) {
5617
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5618
        if (ret != Z_OK)
5619
            return -1;
5620
        if (s->zstream.avail_out == 0) {
5621
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5622
            s->zstream.avail_out = IOBUF_SIZE;
5623
            s->zstream.next_out = s->buf;
5624
        }
5625
    }
5626
    return 0;
5627
}
5628

    
5629
static void ram_compress_close(RamCompressState *s)
5630
{
5631
    int len, ret;
5632

    
5633
    /* compress last bytes */
5634
    for(;;) {
5635
        ret = deflate(&s->zstream, Z_FINISH);
5636
        if (ret == Z_OK || ret == Z_STREAM_END) {
5637
            len = IOBUF_SIZE - s->zstream.avail_out;
5638
            if (len > 0) {
5639
                ram_put_cblock(s, s->buf, len);
5640
            }
5641
            s->zstream.avail_out = IOBUF_SIZE;
5642
            s->zstream.next_out = s->buf;
5643
            if (ret == Z_STREAM_END)
5644
                break;
5645
        } else {
5646
            goto fail;
5647
        }
5648
    }
5649
fail:
5650
    deflateEnd(&s->zstream);
5651
}
5652

    
5653
typedef struct RamDecompressState {
5654
    z_stream zstream;
5655
    QEMUFile *f;
5656
    uint8_t buf[IOBUF_SIZE];
5657
} RamDecompressState;
5658

    
5659
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5660
{
5661
    int ret;
5662
    memset(s, 0, sizeof(*s));
5663
    s->f = f;
5664
    ret = inflateInit(&s->zstream);
5665
    if (ret != Z_OK)
5666
        return -1;
5667
    return 0;
5668
}
5669

    
5670
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5671
{
5672
    int ret, clen;
5673

    
5674
    s->zstream.avail_out = len;
5675
    s->zstream.next_out = buf;
5676
    while (s->zstream.avail_out > 0) {
5677
        if (s->zstream.avail_in == 0) {
5678
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5679
                return -1;
5680
            clen = qemu_get_be16(s->f);
5681
            if (clen > IOBUF_SIZE)
5682
                return -1;
5683
            qemu_get_buffer(s->f, s->buf, clen);
5684
            s->zstream.avail_in = clen;
5685
            s->zstream.next_in = s->buf;
5686
        }
5687
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5688
        if (ret != Z_OK && ret != Z_STREAM_END) {
5689
            return -1;
5690
        }
5691
    }
5692
    return 0;
5693
}
5694

    
5695
static void ram_decompress_close(RamDecompressState *s)
5696
{
5697
    inflateEnd(&s->zstream);
5698
}
5699

    
5700
static void ram_save(QEMUFile *f, void *opaque)
5701
{
5702
    int i;
5703
    RamCompressState s1, *s = &s1;
5704
    uint8_t buf[10];
5705
    
5706
    qemu_put_be32(f, phys_ram_size);
5707
    if (ram_compress_open(s, f) < 0)
5708
        return;
5709
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5710
#if 0
5711
        if (tight_savevm_enabled) {
5712
            int64_t sector_num;
5713
            int j;
5714

5715
            /* find if the memory block is available on a virtual
5716
               block device */
5717
            sector_num = -1;
5718
            for(j = 0; j < MAX_DISKS; j++) {
5719
                if (bs_table[j]) {
5720
                    sector_num = bdrv_hash_find(bs_table[j], 
5721
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5722
                    if (sector_num >= 0)
5723
                        break;
5724
                }
5725
            }
5726
            if (j == MAX_DISKS)
5727
                goto normal_compress;
5728
            buf[0] = 1;
5729
            buf[1] = j;
5730
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5731
            ram_compress_buf(s, buf, 10);
5732
        } else 
5733
#endif
5734
        {
5735
            //        normal_compress:
5736
            buf[0] = 0;
5737
            ram_compress_buf(s, buf, 1);
5738
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5739
        }
5740
    }
5741
    ram_compress_close(s);
5742
}
5743

    
5744
static int ram_load(QEMUFile *f, void *opaque, int version_id)
5745
{
5746
    RamDecompressState s1, *s = &s1;
5747
    uint8_t buf[10];
5748
    int i;
5749

    
5750
    if (version_id == 1)
5751
        return ram_load_v1(f, opaque);
5752
    if (version_id != 2)
5753
        return -EINVAL;
5754
    if (qemu_get_be32(f) != phys_ram_size)
5755
        return -EINVAL;
5756
    if (ram_decompress_open(s, f) < 0)
5757
        return -EINVAL;
5758
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5759
        if (ram_decompress_buf(s, buf, 1) < 0) {
5760
            fprintf(stderr, "Error while reading ram block header\n");
5761
            goto error;
5762
        }
5763
        if (buf[0] == 0) {
5764
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5765
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5766
                goto error;
5767
            }
5768
        } else 
5769
#if 0
5770
        if (buf[0] == 1) {
5771
            int bs_index;
5772
            int64_t sector_num;
5773

5774
            ram_decompress_buf(s, buf + 1, 9);
5775
            bs_index = buf[1];
5776
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5777
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5778
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
5779
                goto error;
5780
            }
5781
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5782
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5783
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5784
                        bs_index, sector_num);
5785
                goto error;
5786
            }
5787
        } else 
5788
#endif
5789
        {
5790
        error:
5791
            printf("Error block header\n");
5792
            return -EINVAL;
5793
        }
5794
    }
5795
    ram_decompress_close(s);
5796
    return 0;
5797
}
5798

    
5799
/***********************************************************/
5800
/* bottom halves (can be seen as timers which expire ASAP) */
5801

    
5802
struct QEMUBH {
5803
    QEMUBHFunc *cb;
5804
    void *opaque;
5805
    int scheduled;
5806
    QEMUBH *next;
5807
};
5808

    
5809
static QEMUBH *first_bh = NULL;
5810

    
5811
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5812
{
5813
    QEMUBH *bh;
5814
    bh = qemu_mallocz(sizeof(QEMUBH));
5815
    if (!bh)
5816
        return NULL;
5817
    bh->cb = cb;
5818
    bh->opaque = opaque;
5819
    return bh;
5820
}
5821

    
5822
int qemu_bh_poll(void)
5823
{
5824
    QEMUBH *bh, **pbh;
5825
    int ret;
5826

    
5827
    ret = 0;
5828
    for(;;) {
5829
        pbh = &first_bh;
5830
        bh = *pbh;
5831
        if (!bh)
5832
            break;
5833
        ret = 1;
5834
        *pbh = bh->next;
5835
        bh->scheduled = 0;
5836
        bh->cb(bh->opaque);
5837
    }
5838
    return ret;
5839
}
5840

    
5841
void qemu_bh_schedule(QEMUBH *bh)
5842
{
5843
    CPUState *env = cpu_single_env;
5844
    if (bh->scheduled)
5845
        return;
5846
    bh->scheduled = 1;
5847
    bh->next = first_bh;
5848
    first_bh = bh;
5849

    
5850
    /* stop the currently executing CPU to execute the BH ASAP */
5851
    if (env) {
5852
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5853
    }
5854
}
5855

    
5856
void qemu_bh_cancel(QEMUBH *bh)
5857
{
5858
    QEMUBH **pbh;
5859
    if (bh->scheduled) {
5860
        pbh = &first_bh;
5861
        while (*pbh != bh)
5862
            pbh = &(*pbh)->next;
5863
        *pbh = bh->next;
5864
        bh->scheduled = 0;
5865
    }
5866
}
5867

    
5868
void qemu_bh_delete(QEMUBH *bh)
5869
{
5870
    qemu_bh_cancel(bh);
5871
    qemu_free(bh);
5872
}
5873

    
5874
/***********************************************************/
5875
/* machine registration */
5876

    
5877
QEMUMachine *first_machine = NULL;
5878

    
5879
int qemu_register_machine(QEMUMachine *m)
5880
{
5881
    QEMUMachine **pm;
5882
    pm = &first_machine;
5883
    while (*pm != NULL)
5884
        pm = &(*pm)->next;
5885
    m->next = NULL;
5886
    *pm = m;
5887
    return 0;
5888
}
5889

    
5890
QEMUMachine *find_machine(const char *name)
5891
{
5892
    QEMUMachine *m;
5893

    
5894
    for(m = first_machine; m != NULL; m = m->next) {
5895
        if (!strcmp(m->name, name))
5896
            return m;
5897
    }
5898
    return NULL;
5899
}
5900

    
5901
/***********************************************************/
5902
/* main execution loop */
5903

    
5904
void gui_update(void *opaque)
5905
{
5906
    display_state.dpy_refresh(&display_state);
5907
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5908
}
5909

    
5910
struct vm_change_state_entry {
5911
    VMChangeStateHandler *cb;
5912
    void *opaque;
5913
    LIST_ENTRY (vm_change_state_entry) entries;
5914
};
5915

    
5916
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5917

    
5918
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5919
                                                     void *opaque)
5920
{
5921
    VMChangeStateEntry *e;
5922

    
5923
    e = qemu_mallocz(sizeof (*e));
5924
    if (!e)
5925
        return NULL;
5926

    
5927
    e->cb = cb;
5928
    e->opaque = opaque;
5929
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5930
    return e;
5931
}
5932

    
5933
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5934
{
5935
    LIST_REMOVE (e, entries);
5936
    qemu_free (e);
5937
}
5938

    
5939
static void vm_state_notify(int running)
5940
{
5941
    VMChangeStateEntry *e;
5942

    
5943
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5944
        e->cb(e->opaque, running);
5945
    }
5946
}
5947

    
5948
/* XXX: support several handlers */
5949
static VMStopHandler *vm_stop_cb;
5950
static void *vm_stop_opaque;
5951

    
5952
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5953
{
5954
    vm_stop_cb = cb;
5955
    vm_stop_opaque = opaque;
5956
    return 0;
5957
}
5958

    
5959
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5960
{
5961
    vm_stop_cb = NULL;
5962
}
5963

    
5964
void vm_start(void)
5965
{
5966
    if (!vm_running) {
5967
        cpu_enable_ticks();
5968
        vm_running = 1;
5969
        vm_state_notify(1);
5970
    }
5971
}
5972

    
5973
void vm_stop(int reason) 
5974
{
5975
    if (vm_running) {
5976
        cpu_disable_ticks();
5977
        vm_running = 0;
5978
        if (reason != 0) {
5979
            if (vm_stop_cb) {
5980
                vm_stop_cb(vm_stop_opaque, reason);
5981
            }
5982
        }
5983
        vm_state_notify(0);
5984
    }
5985
}
5986

    
5987
/* reset/shutdown handler */
5988

    
5989
typedef struct QEMUResetEntry {
5990
    QEMUResetHandler *func;
5991
    void *opaque;
5992
    struct QEMUResetEntry *next;
5993
} QEMUResetEntry;
5994

    
5995
static QEMUResetEntry *first_reset_entry;
5996
static int reset_requested;
5997
static int shutdown_requested;
5998
static int powerdown_requested;
5999

    
6000
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6001
{
6002
    QEMUResetEntry **pre, *re;
6003

    
6004
    pre = &first_reset_entry;
6005
    while (*pre != NULL)
6006
        pre = &(*pre)->next;
6007
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6008
    re->func = func;
6009
    re->opaque = opaque;
6010
    re->next = NULL;
6011
    *pre = re;
6012
}
6013

    
6014
static void qemu_system_reset(void)
6015
{
6016
    QEMUResetEntry *re;
6017

    
6018
    /* reset all devices */
6019
    for(re = first_reset_entry; re != NULL; re = re->next) {
6020
        re->func(re->opaque);
6021
    }
6022
}
6023

    
6024
void qemu_system_reset_request(void)
6025
{
6026
    if (no_reboot) {
6027
        shutdown_requested = 1;
6028
    } else {
6029
        reset_requested = 1;
6030
    }
6031
    if (cpu_single_env)
6032
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6033
}
6034

    
6035
void qemu_system_shutdown_request(void)
6036
{
6037
    shutdown_requested = 1;
6038
    if (cpu_single_env)
6039
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6040
}
6041

    
6042
void qemu_system_powerdown_request(void)
6043
{
6044
    powerdown_requested = 1;
6045
    if (cpu_single_env)
6046
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6047
}
6048

    
6049
void main_loop_wait(int timeout)
6050
{
6051
    IOHandlerRecord *ioh, *ioh_next;
6052
    fd_set rfds, wfds, xfds;
6053
    int ret, nfds;
6054
    struct timeval tv;
6055
    PollingEntry *pe;
6056

    
6057

    
6058
    /* XXX: need to suppress polling by better using win32 events */
6059
    ret = 0;
6060
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6061
        ret |= pe->func(pe->opaque);
6062
    }
6063
#ifdef _WIN32
6064
    if (ret == 0 && timeout > 0) {
6065
        int err;
6066
        WaitObjects *w = &wait_objects;
6067
        
6068
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6069
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6070
            if (w->func[ret - WAIT_OBJECT_0])
6071
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6072
        } else if (ret == WAIT_TIMEOUT) {
6073
        } else {
6074
            err = GetLastError();
6075
            fprintf(stderr, "Wait error %d %d\n", ret, err);
6076
        }
6077
    }
6078
#endif
6079
    /* poll any events */
6080
    /* XXX: separate device handlers from system ones */
6081
    nfds = -1;
6082
    FD_ZERO(&rfds);
6083
    FD_ZERO(&wfds);
6084
    FD_ZERO(&xfds);
6085
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6086
        if (ioh->fd_read &&
6087
            (!ioh->fd_read_poll ||
6088
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6089
            FD_SET(ioh->fd, &rfds);
6090
            if (ioh->fd > nfds)
6091
                nfds = ioh->fd;
6092
        }
6093
        if (ioh->fd_write) {
6094
            FD_SET(ioh->fd, &wfds);
6095
            if (ioh->fd > nfds)
6096
                nfds = ioh->fd;
6097
        }
6098
    }
6099
    
6100
    tv.tv_sec = 0;
6101
#ifdef _WIN32
6102
    tv.tv_usec = 0;
6103
#else
6104
    tv.tv_usec = timeout * 1000;
6105
#endif
6106
#if defined(CONFIG_SLIRP)
6107
    if (slirp_inited) {
6108
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6109
    }
6110
#endif
6111
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6112
    if (ret > 0) {
6113
        /* XXX: better handling of removal */
6114
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
6115
            ioh_next = ioh->next;
6116
            if (FD_ISSET(ioh->fd, &rfds)) {
6117
                ioh->fd_read(ioh->opaque);
6118
            }
6119
            if (FD_ISSET(ioh->fd, &wfds)) {
6120
                ioh->fd_write(ioh->opaque);
6121
            }
6122
        }
6123
    }
6124
#if defined(CONFIG_SLIRP)
6125
    if (slirp_inited) {
6126
        if (ret < 0) {
6127
            FD_ZERO(&rfds);
6128
            FD_ZERO(&wfds);
6129
            FD_ZERO(&xfds);
6130
        }
6131
        slirp_select_poll(&rfds, &wfds, &xfds);
6132
    }
6133
#endif
6134
    qemu_aio_poll();
6135
    qemu_bh_poll();
6136

    
6137
    if (vm_running) {
6138
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
6139
                        qemu_get_clock(vm_clock));
6140
        /* run dma transfers, if any */
6141
        DMA_run();
6142
    }
6143
    
6144
    /* real time timers */
6145
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
6146
                    qemu_get_clock(rt_clock));
6147
}
6148

    
6149
static CPUState *cur_cpu;
6150

    
6151
int main_loop(void)
6152
{
6153
    int ret, timeout;
6154
#ifdef CONFIG_PROFILER
6155
    int64_t ti;
6156
#endif
6157
    CPUState *env;
6158

    
6159
    cur_cpu = first_cpu;
6160
    for(;;) {
6161
        if (vm_running) {
6162

    
6163
            env = cur_cpu;
6164
            for(;;) {
6165
                /* get next cpu */
6166
                env = env->next_cpu;
6167
                if (!env)
6168
                    env = first_cpu;
6169
#ifdef CONFIG_PROFILER
6170
                ti = profile_getclock();
6171
#endif
6172
                ret = cpu_exec(env);
6173
#ifdef CONFIG_PROFILER
6174
                qemu_time += profile_getclock() - ti;
6175
#endif
6176
                if (ret != EXCP_HALTED)
6177
                    break;
6178
                /* all CPUs are halted ? */
6179
                if (env == cur_cpu) {
6180
                    ret = EXCP_HLT;
6181
                    break;
6182
                }
6183
            }
6184
            cur_cpu = env;
6185

    
6186
            if (shutdown_requested) {
6187
                ret = EXCP_INTERRUPT;
6188
                break;
6189
            }
6190
            if (reset_requested) {
6191
                reset_requested = 0;
6192
                qemu_system_reset();
6193
                ret = EXCP_INTERRUPT;
6194
            }
6195
            if (powerdown_requested) {
6196
                powerdown_requested = 0;
6197
                qemu_system_powerdown();
6198
                ret = EXCP_INTERRUPT;
6199
            }
6200
            if (ret == EXCP_DEBUG) {
6201
                vm_stop(EXCP_DEBUG);
6202
            }
6203
            /* if hlt instruction, we wait until the next IRQ */
6204
            /* XXX: use timeout computed from timers */
6205
            if (ret == EXCP_HLT)
6206
                timeout = 10;
6207
            else
6208
                timeout = 0;
6209
        } else {
6210
            timeout = 10;
6211
        }
6212
#ifdef CONFIG_PROFILER
6213
        ti = profile_getclock();
6214
#endif
6215
        main_loop_wait(timeout);
6216
#ifdef CONFIG_PROFILER
6217
        dev_time += profile_getclock() - ti;
6218
#endif
6219
    }
6220
    cpu_disable_ticks();
6221
    return ret;
6222
}
6223

    
6224
void help(void)
6225
{
6226
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
6227
           "usage: %s [options] [disk_image]\n"
6228
           "\n"
6229
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6230
           "\n"
6231
           "Standard options:\n"
6232
           "-M machine      select emulated machine (-M ? for list)\n"
6233
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6234
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6235
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6236
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6237
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6238
           "-disk ide,img=file[,hdx=a..dd][,type=disk|cdrom] \n"
6239
           "                defaults are: hdx=a,type=disk \n"
6240
           "-disk scsi,img=file[,sdx=a..g][,type=disk|cdrom][,id=n]  \n"
6241
           "                defaults are: sdx=a,type=disk,id='auto assign' \n"
6242
           "-snapshot       write to temporary files instead of disk image files\n"
6243
#ifdef CONFIG_SDL
6244
           "-no-quit        disable SDL window close capability\n"
6245
#endif
6246
#ifdef TARGET_I386
6247
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6248
#endif
6249
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6250
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
6251
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
6252
#ifndef _WIN32
6253
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
6254
#endif
6255
#ifdef HAS_AUDIO
6256
           "-audio-help     print list of audio drivers and their options\n"
6257
           "-soundhw c1,... enable audio support\n"
6258
           "                and only specified sound cards (comma separated list)\n"
6259
           "                use -soundhw ? to get the list of supported cards\n"
6260
           "                use -soundhw all to enable all of them\n"
6261
#endif
6262
           "-localtime      set the real time clock to local time [default=utc]\n"
6263
           "-full-screen    start in full screen\n"
6264
#ifdef TARGET_I386
6265
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6266
#endif
6267
           "-usb            enable the USB driver (will be the default soon)\n"
6268
           "-usbdevice name add the host or guest USB device 'name'\n"
6269
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6270
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6271
#endif
6272
           "\n"
6273
           "Network options:\n"
6274
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6275
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6276
#ifdef CONFIG_SLIRP
6277
           "-net user[,vlan=n][,hostname=host]\n"
6278
           "                connect the user mode network stack to VLAN 'n' and send\n"
6279
           "                hostname 'host' to DHCP clients\n"
6280
#endif
6281
#ifdef _WIN32
6282
           "-net tap[,vlan=n],ifname=name\n"
6283
           "                connect the host TAP network interface to VLAN 'n'\n"
6284
#else
6285
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6286
           "                connect the host TAP network interface to VLAN 'n' and use\n"
6287
           "                the network script 'file' (default=%s);\n"
6288
           "                use 'fd=h' to connect to an already opened TAP interface\n"
6289
#endif
6290
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6291
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
6292
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6293
           "                connect the vlan 'n' to multicast maddr and port\n"
6294
           "-net none       use it alone to have zero network devices; if no -net option\n"
6295
           "                is provided, the default is '-net nic -net user'\n"
6296
           "\n"
6297
#ifdef CONFIG_SLIRP
6298
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
6299
#ifndef _WIN32
6300
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6301
#endif
6302
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6303
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
6304
#endif
6305
           "\n"
6306
           "Linux boot specific:\n"
6307
           "-kernel bzImage use 'bzImage' as kernel image\n"
6308
           "-append cmdline use 'cmdline' as kernel command line\n"
6309
           "-initrd file    use 'file' as initial ram disk\n"
6310
           "\n"
6311
           "Debug/Expert options:\n"
6312
           "-monitor dev    redirect the monitor to char device 'dev'\n"
6313
           "-serial dev     redirect the serial port to char device 'dev'\n"
6314
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
6315
           "-pidfile file   Write PID to 'file'\n"
6316
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
6317
           "-s              wait gdb connection to port %d\n"
6318
           "-p port         change gdb connection port\n"
6319
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6320
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6321
           "                translation (t=none or lba) (usually qemu can guess them)\n"
6322
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6323
#ifdef USE_KQEMU
6324
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6325
           "-no-kqemu       disable KQEMU kernel module usage\n"
6326
#endif
6327
#ifdef USE_CODE_COPY
6328
           "-no-code-copy   disable code copy acceleration\n"
6329
#endif
6330
#ifdef TARGET_I386
6331
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6332
           "                (default is CL-GD5446 PCI VGA)\n"
6333
           "-no-acpi        disable ACPI\n"
6334
#endif
6335
           "-no-reboot      exit instead of rebooting\n"
6336
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6337
           "-vnc display    start a VNC server on display\n"
6338
#ifndef _WIN32
6339
           "-daemonize      daemonize QEMU after initializing\n"
6340
#endif
6341
           "-option-rom rom load a file, rom, into the option ROM space\n"
6342
           "\n"
6343
           "During emulation, the following keys are useful:\n"
6344
           "ctrl-alt-f      toggle full screen\n"
6345
           "ctrl-alt-n      switch to virtual console 'n'\n"
6346
           "ctrl-alt        toggle mouse and keyboard grab\n"
6347
           "\n"
6348
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
6349
           ,
6350
           "qemu",
6351
           DEFAULT_RAM_SIZE,
6352
#ifndef _WIN32
6353
           DEFAULT_NETWORK_SCRIPT,
6354
#endif
6355
           DEFAULT_GDBSTUB_PORT,
6356
           "/tmp/qemu.log");
6357
    exit(1);
6358
}
6359

    
6360
#define HAS_ARG 0x0001
6361

    
6362
enum {
6363
    QEMU_OPTION_h,
6364

    
6365
    QEMU_OPTION_M,
6366
    QEMU_OPTION_fda,
6367
    QEMU_OPTION_fdb,
6368
    QEMU_OPTION_hda,
6369
    QEMU_OPTION_hdb,
6370
    QEMU_OPTION_hdc,
6371
    QEMU_OPTION_hdd,
6372
    QEMU_OPTION_cdrom,
6373
    QEMU_OPTION_boot,
6374
    QEMU_OPTION_snapshot,
6375
#ifdef TARGET_I386
6376
    QEMU_OPTION_no_fd_bootchk,
6377
#endif
6378
    QEMU_OPTION_m,
6379
    QEMU_OPTION_nographic,
6380
#ifdef HAS_AUDIO
6381
    QEMU_OPTION_audio_help,
6382
    QEMU_OPTION_soundhw,
6383
#endif
6384

    
6385
    QEMU_OPTION_net,
6386
    QEMU_OPTION_tftp,
6387
    QEMU_OPTION_smb,
6388
    QEMU_OPTION_redir,
6389

    
6390
    QEMU_OPTION_kernel,
6391
    QEMU_OPTION_append,
6392
    QEMU_OPTION_initrd,
6393

    
6394
    QEMU_OPTION_S,
6395
    QEMU_OPTION_s,
6396
    QEMU_OPTION_p,
6397
    QEMU_OPTION_d,
6398
    QEMU_OPTION_hdachs,
6399
    QEMU_OPTION_L,
6400
    QEMU_OPTION_no_code_copy,
6401
    QEMU_OPTION_k,
6402
    QEMU_OPTION_localtime,
6403
    QEMU_OPTION_cirrusvga,
6404
    QEMU_OPTION_g,
6405
    QEMU_OPTION_std_vga,
6406
    QEMU_OPTION_monitor,
6407
    QEMU_OPTION_serial,
6408
    QEMU_OPTION_parallel,
6409
    QEMU_OPTION_loadvm,
6410
    QEMU_OPTION_full_screen,
6411
    QEMU_OPTION_no_quit,
6412
    QEMU_OPTION_pidfile,
6413
    QEMU_OPTION_no_kqemu,
6414
    QEMU_OPTION_kernel_kqemu,
6415
    QEMU_OPTION_win2k_hack,
6416
    QEMU_OPTION_usb,
6417
    QEMU_OPTION_usbdevice,
6418
    QEMU_OPTION_smp,
6419
    QEMU_OPTION_vnc,
6420
    QEMU_OPTION_no_acpi,
6421
    QEMU_OPTION_no_reboot,
6422
    QEMU_OPTION_daemonize,
6423
    QEMU_OPTION_disk,
6424
    QEMU_OPTION_option_rom,
6425
};
6426

    
6427
typedef struct QEMUOption {
6428
    const char *name;
6429
    int flags;
6430
    int index;
6431
} QEMUOption;
6432

    
6433
const QEMUOption qemu_options[] = {
6434
    { "h", 0, QEMU_OPTION_h },
6435

    
6436
    { "M", HAS_ARG, QEMU_OPTION_M },
6437
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6438
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6439
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6440
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6441
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6442
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6443
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6444
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6445
    { "snapshot", 0, QEMU_OPTION_snapshot },
6446
#ifdef TARGET_I386
6447
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6448
#endif
6449
    { "m", HAS_ARG, QEMU_OPTION_m },
6450
    { "nographic", 0, QEMU_OPTION_nographic },
6451
    { "k", HAS_ARG, QEMU_OPTION_k },
6452
#ifdef HAS_AUDIO
6453
    { "audio-help", 0, QEMU_OPTION_audio_help },
6454
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6455
#endif
6456

    
6457
    { "net", HAS_ARG, QEMU_OPTION_net},
6458
#ifdef CONFIG_SLIRP
6459
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6460
#ifndef _WIN32
6461
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6462
#endif
6463
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6464
#endif
6465

    
6466
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6467
    { "append", HAS_ARG, QEMU_OPTION_append },
6468
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6469

    
6470
    { "S", 0, QEMU_OPTION_S },
6471
    { "s", 0, QEMU_OPTION_s },
6472
    { "p", HAS_ARG, QEMU_OPTION_p },
6473
    { "d", HAS_ARG, QEMU_OPTION_d },
6474
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6475
    { "L", HAS_ARG, QEMU_OPTION_L },
6476
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6477
#ifdef USE_KQEMU
6478
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6479
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6480
#endif
6481
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6482
    { "g", 1, QEMU_OPTION_g },
6483
#endif
6484
    { "localtime", 0, QEMU_OPTION_localtime },
6485
    { "std-vga", 0, QEMU_OPTION_std_vga },
6486
    { "monitor", 1, QEMU_OPTION_monitor },
6487
    { "serial", 1, QEMU_OPTION_serial },
6488
    { "parallel", 1, QEMU_OPTION_parallel },
6489
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6490
    { "full-screen", 0, QEMU_OPTION_full_screen },
6491
#ifdef CONFIG_SDL
6492
    { "no-quit", 0, QEMU_OPTION_no_quit },
6493
#endif
6494
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6495
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6496
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6497
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6498
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6499
    { "disk", HAS_ARG, QEMU_OPTION_disk },
6500
    
6501
    /* temporary options */
6502
    { "usb", 0, QEMU_OPTION_usb },
6503
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6504
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6505
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
6506
    { "daemonize", 0, QEMU_OPTION_daemonize },
6507
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6508
    { NULL },
6509
};
6510

    
6511
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6512

    
6513
/* this stack is only used during signal handling */
6514
#define SIGNAL_STACK_SIZE 32768
6515

    
6516
static uint8_t *signal_stack;
6517

    
6518
#endif
6519

    
6520
/* password input */
6521

    
6522
static BlockDriverState *get_bdrv(int index)
6523
{
6524
    BlockDriverState *bs;
6525

    
6526
    if (index < 4) {
6527
        bs = bs_table[index];
6528
    } else if (index < 6) {
6529
        bs = fd_table[index - 4];
6530
    } else {
6531
        bs = NULL;
6532
    }
6533
    return bs;
6534
}
6535

    
6536
static void read_passwords(void)
6537
{
6538
    BlockDriverState *bs;
6539
    int i, j;
6540
    char password[256];
6541

    
6542
    for(i = 0; i < 6; i++) {
6543
        bs = get_bdrv(i);
6544
        if (bs && bdrv_is_encrypted(bs)) {
6545
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6546
            for(j = 0; j < 3; j++) {
6547
                monitor_readline("Password: ", 
6548
                                 1, password, sizeof(password));
6549
                if (bdrv_set_key(bs, password) == 0)
6550
                    break;
6551
                term_printf("invalid password\n");
6552
            }
6553
        }
6554
    }
6555
}
6556

    
6557
/* XXX: currently we cannot use simultaneously different CPUs */
6558
void register_machines(void)
6559
{
6560
#if defined(TARGET_I386)
6561
    qemu_register_machine(&pc_machine);
6562
    qemu_register_machine(&isapc_machine);
6563
#elif defined(TARGET_PPC)
6564
    qemu_register_machine(&heathrow_machine);
6565
    qemu_register_machine(&core99_machine);
6566
    qemu_register_machine(&prep_machine);
6567
#elif defined(TARGET_MIPS)
6568
    qemu_register_machine(&mips_machine);
6569
#elif defined(TARGET_SPARC)
6570
#ifdef TARGET_SPARC64
6571
    qemu_register_machine(&sun4u_machine);
6572
#else
6573
    qemu_register_machine(&sun4m_machine);
6574
#endif
6575
#elif defined(TARGET_ARM)
6576
    qemu_register_machine(&integratorcp926_machine);
6577
    qemu_register_machine(&integratorcp1026_machine);
6578
    qemu_register_machine(&versatilepb_machine);
6579
    qemu_register_machine(&versatileab_machine);
6580
    qemu_register_machine(&realview_machine);
6581
#elif defined(TARGET_SH4)
6582
    qemu_register_machine(&shix_machine);
6583
#else
6584
#error unsupported CPU
6585
#endif
6586
}
6587

    
6588
#ifdef HAS_AUDIO
6589
struct soundhw soundhw[] = {
6590
#ifdef TARGET_I386
6591
    {
6592
        "pcspk",
6593
        "PC speaker",
6594
        0,
6595
        1,
6596
        { .init_isa = pcspk_audio_init }
6597
    },
6598
#endif
6599
    {
6600
        "sb16",
6601
        "Creative Sound Blaster 16",
6602
        0,
6603
        1,
6604
        { .init_isa = SB16_init }
6605
    },
6606

    
6607
#ifdef CONFIG_ADLIB
6608
    {
6609
        "adlib",
6610
#ifdef HAS_YMF262
6611
        "Yamaha YMF262 (OPL3)",
6612
#else
6613
        "Yamaha YM3812 (OPL2)",
6614
#endif
6615
        0,
6616
        1,
6617
        { .init_isa = Adlib_init }
6618
    },
6619
#endif
6620

    
6621
#ifdef CONFIG_GUS
6622
    {
6623
        "gus",
6624
        "Gravis Ultrasound GF1",
6625
        0,
6626
        1,
6627
        { .init_isa = GUS_init }
6628
    },
6629
#endif
6630

    
6631
    {
6632
        "es1370",
6633
        "ENSONIQ AudioPCI ES1370",
6634
        0,
6635
        0,
6636
        { .init_pci = es1370_init }
6637
    },
6638

    
6639
    { NULL, NULL, 0, 0, { NULL } }
6640
};
6641

    
6642
static void select_soundhw (const char *optarg)
6643
{
6644
    struct soundhw *c;
6645

    
6646
    if (*optarg == '?') {
6647
    show_valid_cards:
6648

    
6649
        printf ("Valid sound card names (comma separated):\n");
6650
        for (c = soundhw; c->name; ++c) {
6651
            printf ("%-11s %s\n", c->name, c->descr);
6652
        }
6653
        printf ("\n-soundhw all will enable all of the above\n");
6654
        exit (*optarg != '?');
6655
    }
6656
    else {
6657
        size_t l;
6658
        const char *p;
6659
        char *e;
6660
        int bad_card = 0;
6661

    
6662
        if (!strcmp (optarg, "all")) {
6663
            for (c = soundhw; c->name; ++c) {
6664
                c->enabled = 1;
6665
            }
6666
            return;
6667
        }
6668

    
6669
        p = optarg;
6670
        while (*p) {
6671
            e = strchr (p, ',');
6672
            l = !e ? strlen (p) : (size_t) (e - p);
6673

    
6674
            for (c = soundhw; c->name; ++c) {
6675
                if (!strncmp (c->name, p, l)) {
6676
                    c->enabled = 1;
6677
                    break;
6678
                }
6679
            }
6680

    
6681
            if (!c->name) {
6682
                if (l > 80) {
6683
                    fprintf (stderr,
6684
                             "Unknown sound card name (too big to show)\n");
6685
                }
6686
                else {
6687
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
6688
                             (int) l, p);
6689
                }
6690
                bad_card = 1;
6691
            }
6692
            p += l + (e != NULL);
6693
        }
6694

    
6695
        if (bad_card)
6696
            goto show_valid_cards;
6697
    }
6698
}
6699
#endif
6700

    
6701
#ifdef _WIN32
6702
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6703
{
6704
    exit(STATUS_CONTROL_C_EXIT);
6705
    return TRUE;
6706
}
6707
#endif
6708

    
6709
#define MAX_NET_CLIENTS 32
6710

    
6711
int main(int argc, char **argv)
6712
{
6713
#ifdef CONFIG_GDBSTUB
6714
    int use_gdbstub, gdbstub_port;
6715
#endif
6716
    int i, cdrom_index;
6717
    int snapshot, linux_boot;
6718
    const char *initrd_filename;
6719
    const char *fd_filename[MAX_FD];
6720
    char scsi_options[MAX_SCSI_DISKS] [DISK_OPTIONS_SIZE];
6721
    char ide_options[MAX_DISKS] [DISK_OPTIONS_SIZE];
6722
    int num_ide_disks;
6723
    int num_scsi_disks;
6724
    const char *kernel_filename, *kernel_cmdline;
6725
    DisplayState *ds = &display_state;
6726
    int cyls, heads, secs, translation;
6727
    int start_emulation = 1;
6728
    char net_clients[MAX_NET_CLIENTS][256];
6729
    int nb_net_clients;
6730
    int optind;
6731
    const char *r, *optarg;
6732
    CharDriverState *monitor_hd;
6733
    char monitor_device[128];
6734
    char serial_devices[MAX_SERIAL_PORTS][128];
6735
    int serial_device_index;
6736
    char parallel_devices[MAX_PARALLEL_PORTS][128];
6737
    int parallel_device_index;
6738
    const char *loadvm = NULL;
6739
    QEMUMachine *machine;
6740
    char usb_devices[MAX_USB_CMDLINE][128];
6741
    int usb_devices_index;
6742
    int fds[2];
6743

    
6744
    LIST_INIT (&vm_change_state_head);
6745
#ifndef _WIN32
6746
    {
6747
        struct sigaction act;
6748
        sigfillset(&act.sa_mask);
6749
        act.sa_flags = 0;
6750
        act.sa_handler = SIG_IGN;
6751
        sigaction(SIGPIPE, &act, NULL);
6752
    }
6753
#else
6754
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6755
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
6756
       QEMU to run on a single CPU */
6757
    {
6758
        HANDLE h;
6759
        DWORD mask, smask;
6760
        int i;
6761
        h = GetCurrentProcess();
6762
        if (GetProcessAffinityMask(h, &mask, &smask)) {
6763
            for(i = 0; i < 32; i++) {
6764
                if (mask & (1 << i))
6765
                    break;
6766
            }
6767
            if (i != 32) {
6768
                mask = 1 << i;
6769
                SetProcessAffinityMask(h, mask);
6770
            }
6771
        }
6772
    }
6773
#endif
6774

    
6775
    register_machines();
6776
    machine = first_machine;
6777
    initrd_filename = NULL;
6778
    for(i = 0; i < MAX_SCSI_DISKS; i++) {
6779
        scsi_disks_info[i].device_type = SCSI_NONE;
6780
        bs_scsi_table[i] = NULL;
6781
    }
6782

    
6783
    num_ide_disks = 0;
6784
    num_scsi_disks = 0;
6785

    
6786
    for(i = 0; i < MAX_FD; i++)
6787
        fd_filename[i] = NULL;
6788
    for(i = 0; i < MAX_DISKS; i++) {
6789
        ide_options[i][0] =  '\0';
6790
    }
6791
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6792
    vga_ram_size = VGA_RAM_SIZE;
6793
    bios_size = BIOS_SIZE;
6794
#ifdef CONFIG_GDBSTUB
6795
    use_gdbstub = 0;
6796
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
6797
#endif
6798
    snapshot = 0;
6799
    nographic = 0;
6800
    kernel_filename = NULL;
6801
    kernel_cmdline = "";
6802
#ifdef TARGET_PPC
6803
    cdrom_index = 1;
6804
#else
6805
    cdrom_index = 2;
6806
#endif
6807
    cyls = heads = secs = 0;
6808
    translation = BIOS_ATA_TRANSLATION_AUTO;
6809
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6810

    
6811
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6812
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
6813
        serial_devices[i][0] = '\0';
6814
    serial_device_index = 0;
6815
    
6816
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6817
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6818
        parallel_devices[i][0] = '\0';
6819
    parallel_device_index = 0;
6820
    
6821
    usb_devices_index = 0;
6822
    
6823
    nb_net_clients = 0;
6824

    
6825
    nb_nics = 0;
6826
    /* default mac address of the first network interface */
6827
    
6828
    optind = 1;
6829
    for(;;) {
6830
        if (optind >= argc)
6831
            break;
6832
        r = argv[optind];
6833
        if (r[0] != '-') {
6834

    
6835
        /* Build new disk IDE syntax string */
6836
        pstrcpy(ide_options[0],
6837
                14,
6838
                "hdx=a,img=");
6839
        /*Add on image filename */
6840
        pstrcpy(&(ide_options[0][13]),
6841
                sizeof(ide_options[0])-13,
6842
                argv[optind++]);
6843
        num_ide_disks++;
6844
        } else {
6845
            const QEMUOption *popt;
6846

    
6847
            optind++;
6848
            popt = qemu_options;
6849
            for(;;) {
6850
                if (!popt->name) {
6851
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
6852
                            argv[0], r);
6853
                    exit(1);
6854
                }
6855
                if (!strcmp(popt->name, r + 1))
6856
                    break;
6857
                popt++;
6858
            }
6859
            if (popt->flags & HAS_ARG) {
6860
                if (optind >= argc) {
6861
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
6862
                            argv[0], r);
6863
                    exit(1);
6864
                }
6865
                optarg = argv[optind++];
6866
            } else {
6867
                optarg = NULL;
6868
            }
6869

    
6870
            switch(popt->index) {
6871
            case QEMU_OPTION_M:
6872
                machine = find_machine(optarg);
6873
                if (!machine) {
6874
                    QEMUMachine *m;
6875
                    printf("Supported machines are:\n");
6876
                    for(m = first_machine; m != NULL; m = m->next) {
6877
                        printf("%-10s %s%s\n",
6878
                               m->name, m->desc, 
6879
                               m == first_machine ? " (default)" : "");
6880
                    }
6881
                    exit(1);
6882
                }
6883
                break;
6884
            case QEMU_OPTION_initrd:
6885
                initrd_filename = optarg;
6886
                break;
6887
            case QEMU_OPTION_hda:
6888
            case QEMU_OPTION_hdb:
6889
            case QEMU_OPTION_hdc:
6890
            case QEMU_OPTION_hdd:
6891
                {
6892
                    int hd_index;
6893
                    const char newIDE_DiskSyntax [][10] = {
6894
                       "hdx=a,img=", "hdx=b,img=", "hdx=c,img=", "hdx=d,img=" };
6895

    
6896
                    hd_index = popt->index - QEMU_OPTION_hda;
6897
                    if (num_ide_disks >= MAX_DISKS) {
6898
                        fprintf(stderr, "qemu: too many IDE disks defined.\n");
6899
                        exit(1);
6900
                    }
6901
                    /* Build new disk IDE syntax string */
6902
                    pstrcpy(ide_options[hd_index],
6903
                            11,
6904
                            newIDE_DiskSyntax[hd_index]);
6905
                    /* Add on image filename */
6906
                    pstrcpy(&(ide_options[hd_index][10]),
6907
                            sizeof(ide_options[0])-10,
6908
                            optarg);
6909
                    num_ide_disks++;
6910
                }
6911
                break;
6912
            case QEMU_OPTION_disk: /*Combined IDE and SCSI, for disk and CDROM */
6913
                {
6914
                    const char *p_input_char;
6915
                    char *p_output_string;
6916
                    char device[64];
6917
                    int disk_index;
6918

    
6919
                    p_input_char = optarg;
6920
                    p_output_string = device;
6921
                    while (*p_input_char != '\0' && *p_input_char != ',') {
6922
                        if ((p_output_string - device) < sizeof(device) - 1)
6923
                            *p_output_string++ = *p_input_char;
6924
                        p_input_char++;
6925
                    }
6926
                    *p_output_string = '\0';
6927
                    if (*p_input_char == ',')
6928
                        p_input_char++;
6929

    
6930
                    if (!strcmp(device, "scsi")) {
6931
                        if (num_scsi_disks >= MAX_SCSI_DISKS) {
6932
                            fprintf(stderr, "qemu: too many SCSI disks defined.\n");
6933
                            exit(1);
6934
                        }
6935
                        pstrcpy(scsi_options[num_scsi_disks],
6936
                                sizeof(scsi_options[0]),
6937
                                p_input_char);
6938
                        num_scsi_disks++;
6939
                    } else if (!strcmp(device,"ide")) {
6940
                        if (num_ide_disks >= MAX_DISKS) {
6941
                            fprintf(stderr, "qemu: too many IDE disks/cdroms defined.\n");
6942
                            exit(1);
6943
                        }
6944
                        disk_index = 0; /* default is hda */
6945
                        if (get_param_value(device, sizeof(device),"hdx",p_input_char)) {
6946
                            if (device[0] >= 'a' && device[0] <= 'd') {
6947
                                disk_index = device[0] - 'a';
6948
                            } else {
6949
                                fprintf(stderr, "qemu: invalid IDE disk hdx= value: %s\n", device);
6950
                                return -1;
6951
                            }
6952
                        }
6953
                        else disk_index=0;
6954
                        pstrcpy(ide_options[disk_index],
6955
                                sizeof(ide_options[0]),
6956
                                p_input_char);
6957
                        num_ide_disks++;
6958
                    } else {
6959
                        fprintf(stderr, "qemu: -disk option must specify IDE or SCSI: %s \n",device);
6960
                        exit(1);
6961
                    }
6962
                }
6963
                break;
6964
            case QEMU_OPTION_snapshot:
6965
                snapshot = 1;
6966
                break;
6967
            case QEMU_OPTION_hdachs:
6968
                {
6969
                    const char *p;
6970
                    p = optarg;
6971
                    cyls = strtol(p, (char **)&p, 0);
6972
                    if (cyls < 1 || cyls > 16383)
6973
                        goto chs_fail;
6974
                    if (*p != ',')
6975
                        goto chs_fail;
6976
                    p++;
6977
                    heads = strtol(p, (char **)&p, 0);
6978
                    if (heads < 1 || heads > 16)
6979
                        goto chs_fail;
6980
                    if (*p != ',')
6981
                        goto chs_fail;
6982
                    p++;
6983
                    secs = strtol(p, (char **)&p, 0);
6984
                    if (secs < 1 || secs > 63)
6985
                        goto chs_fail;
6986
                    if (*p == ',') {
6987
                        p++;
6988
                        if (!strcmp(p, "none"))
6989
                            translation = BIOS_ATA_TRANSLATION_NONE;
6990
                        else if (!strcmp(p, "lba"))
6991
                            translation = BIOS_ATA_TRANSLATION_LBA;
6992
                        else if (!strcmp(p, "auto"))
6993
                            translation = BIOS_ATA_TRANSLATION_AUTO;
6994
                        else
6995
                            goto chs_fail;
6996
                    } else if (*p != '\0') {
6997
                    chs_fail:
6998
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
6999
                        exit(1);
7000
                    }
7001
                }
7002
                break;
7003
            case QEMU_OPTION_nographic:
7004
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7005
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7006
                nographic = 1;
7007
                break;
7008
            case QEMU_OPTION_kernel:
7009
                kernel_filename = optarg;
7010
                break;
7011
            case QEMU_OPTION_append:
7012
                kernel_cmdline = optarg;
7013
                break;
7014
            case QEMU_OPTION_cdrom:
7015
#if !defined(TARGET_SPARC) || defined(TARGET_SPARC64)
7016
                /* Assume boot cdrom is IDE */
7017
                {
7018
                    char buf[22];
7019
                    if (num_ide_disks >= MAX_DISKS) {
7020
                        fprintf(stderr, "qemu: too many IDE disks/cdroms defined.\n");
7021
                        exit(1);
7022
                    }
7023
                    snprintf(buf, sizeof(buf), "type=cdrom,hdx=%c,img=", cdrom_index + 'a');
7024
                    /* Build new disk IDE syntax string */
7025
                    pstrcpy(ide_options[cdrom_index],
7026
                            22,
7027
                            buf);
7028
                    /* Add on image filename */
7029
                    pstrcpy(&(ide_options[cdrom_index][21]),
7030
                            sizeof(ide_options[0])-21,
7031
                            optarg);
7032
                    num_ide_disks++;
7033
                }
7034
#else
7035
                /* Assume boot cdrom is SCSI */
7036
                {
7037
                    char buf[27];
7038
                    if (num_scsi_disks >= MAX_SCSI_DISKS) {
7039
                        fprintf(stderr, "qemu: too many SCSI disks/cdroms defined.\n");
7040
                        exit(1);
7041
                    }
7042
                    snprintf(buf, sizeof(buf), "type=cdrom,sdx=%c,id=%d,img=",
7043
                             num_scsi_disks + 'a', num_scsi_disks + 2);
7044
                    /* Build new disk SCSI syntax string */
7045
                    pstrcpy(scsi_options[num_scsi_disks],
7046
                            27,
7047
                            buf);
7048
                    /* Add on image filename */
7049
                    pstrcpy(&(scsi_options[num_scsi_disks][26]),
7050
                            sizeof(scsi_options[0])-26,
7051
                            optarg);
7052
                    num_scsi_disks++;
7053
                }
7054
#endif
7055
                break;
7056
            case QEMU_OPTION_boot:
7057
                boot_device = optarg[0];
7058
                if (boot_device != 'a' && 
7059
#if defined(TARGET_SPARC) || defined(TARGET_I386)
7060
                    // Network boot
7061
                    boot_device != 'n' &&
7062
#endif
7063
                    boot_device != 'c' && boot_device != 'd') {
7064
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7065
                    exit(1);
7066
                }
7067
                break;
7068
            case QEMU_OPTION_fda:
7069
                fd_filename[0] = optarg;
7070
                break;
7071
            case QEMU_OPTION_fdb:
7072
                fd_filename[1] = optarg;
7073
                break;
7074
#ifdef TARGET_I386
7075
            case QEMU_OPTION_no_fd_bootchk:
7076
                fd_bootchk = 0;
7077
                break;
7078
#endif
7079
            case QEMU_OPTION_no_code_copy:
7080
                code_copy_enabled = 0;
7081
                break;
7082
            case QEMU_OPTION_net:
7083
                if (nb_net_clients >= MAX_NET_CLIENTS) {
7084
                    fprintf(stderr, "qemu: too many network clients\n");
7085
                    exit(1);
7086
                }
7087
                pstrcpy(net_clients[nb_net_clients],
7088
                        sizeof(net_clients[0]),
7089
                        optarg);
7090
                nb_net_clients++;
7091
                break;
7092
#ifdef CONFIG_SLIRP
7093
            case QEMU_OPTION_tftp:
7094
                tftp_prefix = optarg;
7095
                break;
7096
#ifndef _WIN32
7097
            case QEMU_OPTION_smb:
7098
                net_slirp_smb(optarg);
7099
                break;
7100
#endif
7101
            case QEMU_OPTION_redir:
7102
                net_slirp_redir(optarg);                
7103
                break;
7104
#endif
7105
#ifdef HAS_AUDIO
7106
            case QEMU_OPTION_audio_help:
7107
                AUD_help ();
7108
                exit (0);
7109
                break;
7110
            case QEMU_OPTION_soundhw:
7111
                select_soundhw (optarg);
7112
                break;
7113
#endif
7114
            case QEMU_OPTION_h:
7115
                help();
7116
                break;
7117
            case QEMU_OPTION_m:
7118
                ram_size = atoi(optarg) * 1024 * 1024;
7119
                if (ram_size <= 0)
7120
                    help();
7121
                if (ram_size > PHYS_RAM_MAX_SIZE) {
7122
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7123
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
7124
                    exit(1);
7125
                }
7126
                break;
7127
            case QEMU_OPTION_d:
7128
                {
7129
                    int mask;
7130
                    CPULogItem *item;
7131
                    
7132
                    mask = cpu_str_to_log_mask(optarg);
7133
                    if (!mask) {
7134
                        printf("Log items (comma separated):\n");
7135
                    for(item = cpu_log_items; item->mask != 0; item++) {
7136
                        printf("%-10s %s\n", item->name, item->help);
7137
                    }
7138
                    exit(1);
7139
                    }
7140
                    cpu_set_log(mask);
7141
                }
7142
                break;
7143
#ifdef CONFIG_GDBSTUB
7144
            case QEMU_OPTION_s:
7145
                use_gdbstub = 1;
7146
                break;
7147
            case QEMU_OPTION_p:
7148
                gdbstub_port = atoi(optarg);
7149
                break;
7150
#endif
7151
            case QEMU_OPTION_L:
7152
                bios_dir = optarg;
7153
                break;
7154
            case QEMU_OPTION_S:
7155
                start_emulation = 0;
7156
                break;
7157
            case QEMU_OPTION_k:
7158
                keyboard_layout = optarg;
7159
                break;
7160
            case QEMU_OPTION_localtime:
7161
                rtc_utc = 0;
7162
                break;
7163
            case QEMU_OPTION_cirrusvga:
7164
                cirrus_vga_enabled = 1;
7165
                break;
7166
            case QEMU_OPTION_std_vga:
7167
                cirrus_vga_enabled = 0;
7168
                break;
7169
            case QEMU_OPTION_g:
7170
                {
7171
                    const char *p;
7172
                    int w, h, depth;
7173
                    p = optarg;
7174
                    w = strtol(p, (char **)&p, 10);
7175
                    if (w <= 0) {
7176
                    graphic_error:
7177
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
7178
                        exit(1);
7179
                    }
7180
                    if (*p != 'x')
7181
                        goto graphic_error;
7182
                    p++;
7183
                    h = strtol(p, (char **)&p, 10);
7184
                    if (h <= 0)
7185
                        goto graphic_error;
7186
                    if (*p == 'x') {
7187
                        p++;
7188
                        depth = strtol(p, (char **)&p, 10);
7189
                        if (depth != 8 && depth != 15 && depth != 16 && 
7190
                            depth != 24 && depth != 32)
7191
                            goto graphic_error;
7192
                    } else if (*p == '\0') {
7193
                        depth = graphic_depth;
7194
                    } else {
7195
                        goto graphic_error;
7196
                    }
7197
                    
7198
                    graphic_width = w;
7199
                    graphic_height = h;
7200
                    graphic_depth = depth;
7201
                }
7202
                break;
7203
            case QEMU_OPTION_monitor:
7204
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7205
                break;
7206
            case QEMU_OPTION_serial:
7207
                if (serial_device_index >= MAX_SERIAL_PORTS) {
7208
                    fprintf(stderr, "qemu: too many serial ports\n");
7209
                    exit(1);
7210
                }
7211
                pstrcpy(serial_devices[serial_device_index], 
7212
                        sizeof(serial_devices[0]), optarg);
7213
                serial_device_index++;
7214
                break;
7215
            case QEMU_OPTION_parallel:
7216
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7217
                    fprintf(stderr, "qemu: too many parallel ports\n");
7218
                    exit(1);
7219
                }
7220
                pstrcpy(parallel_devices[parallel_device_index], 
7221
                        sizeof(parallel_devices[0]), optarg);
7222
                parallel_device_index++;
7223
                break;
7224
            case QEMU_OPTION_loadvm:
7225
                loadvm = optarg;
7226
                break;
7227
            case QEMU_OPTION_full_screen:
7228
                full_screen = 1;
7229
                break;
7230
#ifdef CONFIG_SDL
7231
            case QEMU_OPTION_no_quit:
7232
                no_quit = 1;
7233
                break;
7234
#endif
7235
            case QEMU_OPTION_pidfile:
7236
                create_pidfile(optarg);
7237
                break;
7238
#ifdef TARGET_I386
7239
            case QEMU_OPTION_win2k_hack:
7240
                win2k_install_hack = 1;
7241
                break;
7242
#endif
7243
#ifdef USE_KQEMU
7244
            case QEMU_OPTION_no_kqemu:
7245
                kqemu_allowed = 0;
7246
                break;
7247
            case QEMU_OPTION_kernel_kqemu:
7248
                kqemu_allowed = 2;
7249
                break;
7250
#endif
7251
            case QEMU_OPTION_usb:
7252
                usb_enabled = 1;
7253
                break;
7254
            case QEMU_OPTION_usbdevice:
7255
                usb_enabled = 1;
7256
                if (usb_devices_index >= MAX_USB_CMDLINE) {
7257
                    fprintf(stderr, "Too many USB devices\n");
7258
                    exit(1);
7259
                }
7260
                pstrcpy(usb_devices[usb_devices_index],
7261
                        sizeof(usb_devices[usb_devices_index]),
7262
                        optarg);
7263
                usb_devices_index++;
7264
                break;
7265
            case QEMU_OPTION_smp:
7266
                smp_cpus = atoi(optarg);
7267
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7268
                    fprintf(stderr, "Invalid number of CPUs\n");
7269
                    exit(1);
7270
                }
7271
                break;
7272
            case QEMU_OPTION_vnc:
7273
                vnc_display = optarg;
7274
                break;
7275
            case QEMU_OPTION_no_acpi:
7276
                acpi_enabled = 0;
7277
                break;
7278
            case QEMU_OPTION_no_reboot:
7279
                no_reboot = 1;
7280
                break;
7281
            case QEMU_OPTION_daemonize:
7282
                daemonize = 1;
7283
                break;
7284
            case QEMU_OPTION_option_rom:
7285
                if (nb_option_roms >= MAX_OPTION_ROMS) {
7286
                    fprintf(stderr, "Too many option ROMs\n");
7287
                    exit(1);
7288
                }
7289
                option_rom[nb_option_roms] = optarg;
7290
                nb_option_roms++;
7291
                break;
7292
            }
7293
        }
7294
    }
7295

    
7296
#ifndef _WIN32
7297
    if (daemonize && !nographic && vnc_display == NULL) {
7298
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7299
        daemonize = 0;
7300
    }
7301

    
7302
    if (daemonize) {
7303
        pid_t pid;
7304

    
7305
        if (pipe(fds) == -1)
7306
            exit(1);
7307

    
7308
        pid = fork();
7309
        if (pid > 0) {
7310
            uint8_t status;
7311
            ssize_t len;
7312

    
7313
            close(fds[1]);
7314

    
7315
        again:
7316
            len = read(fds[0], &status, 1);
7317
            if (len == -1 && (errno == EINTR))
7318
                goto again;
7319
            
7320
            if (len != 1 || status != 0)
7321
                exit(1);
7322
            else
7323
                exit(0);
7324
        } else if (pid < 0)
7325
            exit(1);
7326

    
7327
        setsid();
7328

    
7329
        pid = fork();
7330
        if (pid > 0)
7331
            exit(0);
7332
        else if (pid < 0)
7333
            exit(1);
7334

    
7335
        umask(027);
7336
        chdir("/");
7337

    
7338
        signal(SIGTSTP, SIG_IGN);
7339
        signal(SIGTTOU, SIG_IGN);
7340
        signal(SIGTTIN, SIG_IGN);
7341
    }
7342
#endif
7343

    
7344
#ifdef USE_KQEMU
7345
    if (smp_cpus > 1)
7346
        kqemu_allowed = 0;
7347
#endif
7348
    linux_boot = (kernel_filename != NULL);
7349

    
7350
    if (!linux_boot &&
7351
        num_ide_disks == 0 &&
7352
        num_scsi_disks == 0 &&
7353
        fd_filename[0] == '\0')
7354
        help();
7355

    
7356
    setvbuf(stdout, NULL, _IOLBF, 0);
7357
    
7358
    init_timers();
7359
    init_timer_alarm();
7360
    qemu_aio_init();
7361

    
7362
#ifdef _WIN32
7363
    socket_init();
7364
#endif
7365

    
7366
    /* init network clients */
7367
    if (nb_net_clients == 0) {
7368
        /* if no clients, we use a default config */
7369
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
7370
                "nic");
7371
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
7372
                "user");
7373
        nb_net_clients = 2;
7374
    }
7375

    
7376
    for(i = 0;i < nb_net_clients; i++) {
7377
        if (net_client_init(net_clients[i]) < 0)
7378
            exit(1);
7379
    }
7380

    
7381
#ifdef TARGET_I386
7382
    if (boot_device == 'n') {
7383
        for (i = 0; i < nb_nics; i++) {
7384
            const char *model = nd_table[i].model;
7385
            char buf[1024];
7386
            if (model == NULL)
7387
                model = "ne2k_pci";
7388
            snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7389
            if (get_image_size(buf) > 0) {
7390
                option_rom[nb_option_roms] = strdup(buf);
7391
                nb_option_roms++;
7392
                break;
7393
            }
7394
        }
7395
        if (i == nb_nics) {
7396
            fprintf(stderr, "No valid PXE rom found for network device\n");
7397
            exit(1);
7398
        }
7399
        boot_device = 'c'; /* to prevent confusion by the BIOS */
7400
    }
7401
#endif
7402

    
7403
    /* init the memory */
7404
    phys_ram_size = ram_size + vga_ram_size + bios_size;
7405

    
7406
    for (i = 0; i < nb_option_roms; i++) {
7407
        int ret = get_image_size(option_rom[i]);
7408
        if (ret == -1) {
7409
            fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7410
            exit(1);
7411
        }
7412
        phys_ram_size += ret;
7413
    }
7414

    
7415
    phys_ram_base = qemu_vmalloc(phys_ram_size);
7416
    if (!phys_ram_base) {
7417
        fprintf(stderr, "Could not allocate physical memory\n");
7418
        exit(1);
7419
    }
7420

    
7421
    bdrv_init();
7422

    
7423
    /* open the virtual block devices, disks or CDRoms */
7424
    if (disk_options_init(num_ide_disks,ide_options,snapshot,
7425
                          num_scsi_disks,scsi_options,
7426
                          cdrom_index,
7427
                          cyls, heads, secs, translation)){
7428
        exit(1);
7429
    }
7430

    
7431
    /* boot to floppy or default cd if no hard disk */
7432
    if (num_ide_disks == 0 && boot_device == 'c') {
7433
        if (fd_filename[0] != '\0')
7434
            boot_device = 'a';
7435
        else
7436
            boot_device = 'd';
7437
    }
7438

    
7439
    /* we always create at least one floppy disk */
7440
    fd_table[0] = bdrv_new("fda");
7441
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7442

    
7443
    for(i = 0; i < MAX_FD; i++) {
7444
        if (fd_filename[i]) {
7445
            if (!fd_table[i]) {
7446
                char buf[64];
7447
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7448
                fd_table[i] = bdrv_new(buf);
7449
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7450
            }
7451
            if (fd_filename[i] != '\0') {
7452
                if (bdrv_open(fd_table[i], fd_filename[i],
7453
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7454
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7455
                            fd_filename[i]);
7456
                    exit(1);
7457
                }
7458
            }
7459
        }
7460
    }
7461

    
7462
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7463
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7464

    
7465
    init_ioports();
7466

    
7467
    /* terminal init */
7468
    if (nographic) {
7469
        dumb_display_init(ds);
7470
    } else if (vnc_display != NULL) {
7471
        vnc_display_init(ds, vnc_display);
7472
    } else {
7473
#if defined(CONFIG_SDL)
7474
        sdl_display_init(ds, full_screen);
7475
#elif defined(CONFIG_COCOA)
7476
        cocoa_display_init(ds, full_screen);
7477
#else
7478
        dumb_display_init(ds);
7479
#endif
7480
    }
7481

    
7482
    monitor_hd = qemu_chr_open(monitor_device);
7483
    if (!monitor_hd) {
7484
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7485
        exit(1);
7486
    }
7487
    monitor_init(monitor_hd, !nographic);
7488

    
7489
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7490
        const char *devname = serial_devices[i];
7491
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7492
            serial_hds[i] = qemu_chr_open(devname);
7493
            if (!serial_hds[i]) {
7494
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7495
                        devname);
7496
                exit(1);
7497
            }
7498
            if (!strcmp(devname, "vc"))
7499
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7500
        }
7501
    }
7502

    
7503
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7504
        const char *devname = parallel_devices[i];
7505
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7506
            parallel_hds[i] = qemu_chr_open(devname);
7507
            if (!parallel_hds[i]) {
7508
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7509
                        devname);
7510
                exit(1);
7511
            }
7512
            if (!strcmp(devname, "vc"))
7513
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7514
        }
7515
    }
7516

    
7517
    machine->init(ram_size, vga_ram_size, boot_device,
7518
                  ds, fd_filename, snapshot,
7519
                  kernel_filename, kernel_cmdline, initrd_filename);
7520

    
7521
    /* init USB devices */
7522
    if (usb_enabled) {
7523
        for(i = 0; i < usb_devices_index; i++) {
7524
            if (usb_device_add(usb_devices[i]) < 0) {
7525
                fprintf(stderr, "Warning: could not add USB device %s\n",
7526
                        usb_devices[i]);
7527
            }
7528
        }
7529
    }
7530

    
7531
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7532
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7533

    
7534
#ifdef CONFIG_GDBSTUB
7535
    if (use_gdbstub) {
7536
        if (gdbserver_start(gdbstub_port) < 0) {
7537
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
7538
                    gdbstub_port);
7539
            exit(1);
7540
        } else {
7541
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
7542
        }
7543
    } else 
7544
#endif
7545
    if (loadvm)
7546
        do_loadvm(loadvm);
7547

    
7548
    {
7549
        /* XXX: simplify init */
7550
        read_passwords();
7551
        if (start_emulation) {
7552
            vm_start();
7553
        }
7554
    }
7555

    
7556
    if (daemonize) {
7557
        uint8_t status = 0;
7558
        ssize_t len;
7559
        int fd;
7560

    
7561
    again1:
7562
        len = write(fds[1], &status, 1);
7563
        if (len == -1 && (errno == EINTR))
7564
            goto again1;
7565

    
7566
        if (len != 1)
7567
            exit(1);
7568

    
7569
        fd = open("/dev/null", O_RDWR);
7570
        if (fd == -1)
7571
            exit(1);
7572

    
7573
        dup2(fd, 0);
7574
        dup2(fd, 1);
7575
        dup2(fd, 2);
7576

    
7577
        close(fd);
7578
    }
7579

    
7580
    main_loop();
7581
    quit_timers();
7582
    return 0;
7583
}