Statistics
| Branch: | Revision:

root / vl.c @ c3d2689d

History | View | Annotate | Download (208.3 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2007 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
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
51
#include <freebsd/stdlib.h>
52
#else
53
#ifndef __sun__
54
#include <linux/if.h>
55
#include <linux/if_tun.h>
56
#include <pty.h>
57
#include <malloc.h>
58
#include <linux/rtc.h>
59
#include <linux/ppdev.h>
60
#include <linux/parport.h>
61
#else
62
#include <sys/stat.h>
63
#include <sys/ethernet.h>
64
#include <sys/sockio.h>
65
#include <arpa/inet.h>
66
#include <netinet/arp.h>
67
#include <netinet/in.h>
68
#include <netinet/in_systm.h>
69
#include <netinet/ip.h>
70
#include <netinet/ip_icmp.h> // must come after ip.h
71
#include <netinet/udp.h>
72
#include <netinet/tcp.h>
73
#include <net/if.h>
74
#include <syslog.h>
75
#include <stropts.h>
76
#endif
77
#endif
78
#endif
79

    
80
#if defined(CONFIG_SLIRP)
81
#include "libslirp.h"
82
#endif
83

    
84
#ifdef _WIN32
85
#include <malloc.h>
86
#include <sys/timeb.h>
87
#include <windows.h>
88
#define getopt_long_only getopt_long
89
#define memalign(align, size) malloc(size)
90
#endif
91

    
92
#include "qemu_socket.h"
93

    
94
#ifdef CONFIG_SDL
95
#ifdef __APPLE__
96
#include <SDL/SDL.h>
97
#endif
98
#endif /* CONFIG_SDL */
99

    
100
#ifdef CONFIG_COCOA
101
#undef main
102
#define main qemu_main
103
#endif /* CONFIG_COCOA */
104

    
105
#include "disas.h"
106

    
107
#include "exec-all.h"
108

    
109
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
110
#ifdef __sun__
111
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
112
#else
113
#define SMBD_COMMAND "/usr/sbin/smbd"
114
#endif
115

    
116
//#define DEBUG_UNUSED_IOPORT
117
//#define DEBUG_IOPORT
118

    
119
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
120

    
121
#ifdef TARGET_PPC
122
#define DEFAULT_RAM_SIZE 144
123
#else
124
#define DEFAULT_RAM_SIZE 128
125
#endif
126
/* in ms */
127
#define GUI_REFRESH_INTERVAL 30
128

    
129
/* Max number of USB devices that can be specified on the commandline.  */
130
#define MAX_USB_CMDLINE 8
131

    
132
/* XXX: use a two level table to limit memory usage */
133
#define MAX_IOPORTS 65536
134

    
135
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
136
char phys_ram_file[1024];
137
void *ioport_opaque[MAX_IOPORTS];
138
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
139
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
140
/* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
141
   to store the VM snapshots */
142
BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
143
BlockDriverState *pflash_table[MAX_PFLASH];
144
BlockDriverState *sd_bdrv;
145
BlockDriverState *mtd_bdrv;
146
/* point to the block driver where the snapshots are managed */
147
BlockDriverState *bs_snapshots;
148
int vga_ram_size;
149
static DisplayState display_state;
150
int nographic;
151
const char* keyboard_layout = NULL;
152
int64_t ticks_per_sec;
153
int boot_device = 'c';
154
int ram_size;
155
int pit_min_timer_count = 0;
156
int nb_nics;
157
NICInfo nd_table[MAX_NICS];
158
int vm_running;
159
int rtc_utc = 1;
160
int cirrus_vga_enabled = 1;
161
int vmsvga_enabled = 0;
162
#ifdef TARGET_SPARC
163
int graphic_width = 1024;
164
int graphic_height = 768;
165
int graphic_depth = 8;
166
#else
167
int graphic_width = 800;
168
int graphic_height = 600;
169
int graphic_depth = 15;
170
#endif
171
int full_screen = 0;
172
int no_frame = 0;
173
int no_quit = 0;
174
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
175
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
176
#ifdef TARGET_I386
177
int win2k_install_hack = 0;
178
#endif
179
int usb_enabled = 0;
180
static VLANState *first_vlan;
181
int smp_cpus = 1;
182
const char *vnc_display;
183
#if defined(TARGET_SPARC)
184
#define MAX_CPUS 16
185
#elif defined(TARGET_I386)
186
#define MAX_CPUS 255
187
#else
188
#define MAX_CPUS 1
189
#endif
190
int acpi_enabled = 1;
191
int fd_bootchk = 1;
192
int no_reboot = 0;
193
int cursor_hide = 1;
194
int graphic_rotate = 0;
195
int daemonize = 0;
196
const char *option_rom[MAX_OPTION_ROMS];
197
int nb_option_roms;
198
int semihosting_enabled = 0;
199
int autostart = 1;
200
#ifdef TARGET_ARM
201
int old_param = 0;
202
#endif
203
const char *qemu_name;
204
int alt_grab = 0;
205
#ifdef TARGET_SPARC
206
unsigned int nb_prom_envs = 0;
207
const char *prom_envs[MAX_PROM_ENVS];
208
#endif
209

    
210
#define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
211

    
212
/***********************************************************/
213
/* x86 ISA bus support */
214

    
215
target_phys_addr_t isa_mem_base = 0;
216
PicState2 *isa_pic;
217

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

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

    
233
/* default is to make two byte accesses */
234
uint32_t default_ioport_readw(void *opaque, uint32_t address)
235
{
236
    uint32_t data;
237
    data = ioport_read_table[0][address](ioport_opaque[address], address);
238
    address = (address + 1) & (MAX_IOPORTS - 1);
239
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
240
    return data;
241
}
242

    
243
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
244
{
245
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
246
    address = (address + 1) & (MAX_IOPORTS - 1);
247
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
248
}
249

    
250
uint32_t default_ioport_readl(void *opaque, uint32_t address)
251
{
252
#ifdef DEBUG_UNUSED_IOPORT
253
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
254
#endif
255
    return 0xffffffff;
256
}
257

    
258
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
259
{
260
#ifdef DEBUG_UNUSED_IOPORT
261
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
262
#endif
263
}
264

    
265
void init_ioports(void)
266
{
267
    int i;
268

    
269
    for(i = 0; i < MAX_IOPORTS; i++) {
270
        ioport_read_table[0][i] = default_ioport_readb;
271
        ioport_write_table[0][i] = default_ioport_writeb;
272
        ioport_read_table[1][i] = default_ioport_readw;
273
        ioport_write_table[1][i] = default_ioport_writew;
274
        ioport_read_table[2][i] = default_ioport_readl;
275
        ioport_write_table[2][i] = default_ioport_writel;
276
    }
277
}
278

    
279
/* size is the word size in byte */
280
int register_ioport_read(int start, int length, int size, 
281
                         IOPortReadFunc *func, void *opaque)
282
{
283
    int i, bsize;
284

    
285
    if (size == 1) {
286
        bsize = 0;
287
    } else if (size == 2) {
288
        bsize = 1;
289
    } else if (size == 4) {
290
        bsize = 2;
291
    } else {
292
        hw_error("register_ioport_read: invalid size");
293
        return -1;
294
    }
295
    for(i = start; i < start + length; i += size) {
296
        ioport_read_table[bsize][i] = func;
297
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
298
            hw_error("register_ioport_read: invalid opaque");
299
        ioport_opaque[i] = opaque;
300
    }
301
    return 0;
302
}
303

    
304
/* size is the word size in byte */
305
int register_ioport_write(int start, int length, int size, 
306
                          IOPortWriteFunc *func, void *opaque)
307
{
308
    int i, bsize;
309

    
310
    if (size == 1) {
311
        bsize = 0;
312
    } else if (size == 2) {
313
        bsize = 1;
314
    } else if (size == 4) {
315
        bsize = 2;
316
    } else {
317
        hw_error("register_ioport_write: invalid size");
318
        return -1;
319
    }
320
    for(i = start; i < start + length; i += size) {
321
        ioport_write_table[bsize][i] = func;
322
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
323
            hw_error("register_ioport_write: invalid opaque");
324
        ioport_opaque[i] = opaque;
325
    }
326
    return 0;
327
}
328

    
329
void isa_unassign_ioport(int start, int length)
330
{
331
    int i;
332

    
333
    for(i = start; i < start + length; i++) {
334
        ioport_read_table[0][i] = default_ioport_readb;
335
        ioport_read_table[1][i] = default_ioport_readw;
336
        ioport_read_table[2][i] = default_ioport_readl;
337

    
338
        ioport_write_table[0][i] = default_ioport_writeb;
339
        ioport_write_table[1][i] = default_ioport_writew;
340
        ioport_write_table[2][i] = default_ioport_writel;
341
    }
342
}
343

    
344
/***********************************************************/
345

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

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

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

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

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

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

    
430
/***********************************************************/
431
void hw_error(const char *fmt, ...)
432
{
433
    va_list ap;
434
    CPUState *env;
435

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

    
452
/***********************************************************/
453
/* keyboard/mouse */
454

    
455
static QEMUPutKBDEvent *qemu_put_kbd_event;
456
static void *qemu_put_kbd_event_opaque;
457
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
458
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
459

    
460
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
461
{
462
    qemu_put_kbd_event_opaque = opaque;
463
    qemu_put_kbd_event = func;
464
}
465

    
466
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
467
                                                void *opaque, int absolute,
468
                                                const char *name)
469
{
470
    QEMUPutMouseEntry *s, *cursor;
471

    
472
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
473
    if (!s)
474
        return NULL;
475

    
476
    s->qemu_put_mouse_event = func;
477
    s->qemu_put_mouse_event_opaque = opaque;
478
    s->qemu_put_mouse_event_absolute = absolute;
479
    s->qemu_put_mouse_event_name = qemu_strdup(name);
480
    s->next = NULL;
481

    
482
    if (!qemu_put_mouse_event_head) {
483
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
484
        return s;
485
    }
486

    
487
    cursor = qemu_put_mouse_event_head;
488
    while (cursor->next != NULL)
489
        cursor = cursor->next;
490

    
491
    cursor->next = s;
492
    qemu_put_mouse_event_current = s;
493

    
494
    return s;
495
}
496

    
497
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
498
{
499
    QEMUPutMouseEntry *prev = NULL, *cursor;
500

    
501
    if (!qemu_put_mouse_event_head || entry == NULL)
502
        return;
503

    
504
    cursor = qemu_put_mouse_event_head;
505
    while (cursor != NULL && cursor != entry) {
506
        prev = cursor;
507
        cursor = cursor->next;
508
    }
509

    
510
    if (cursor == NULL) // does not exist or list empty
511
        return;
512
    else if (prev == NULL) { // entry is head
513
        qemu_put_mouse_event_head = cursor->next;
514
        if (qemu_put_mouse_event_current == entry)
515
            qemu_put_mouse_event_current = cursor->next;
516
        qemu_free(entry->qemu_put_mouse_event_name);
517
        qemu_free(entry);
518
        return;
519
    }
520

    
521
    prev->next = entry->next;
522

    
523
    if (qemu_put_mouse_event_current == entry)
524
        qemu_put_mouse_event_current = prev;
525

    
526
    qemu_free(entry->qemu_put_mouse_event_name);
527
    qemu_free(entry);
528
}
529

    
530
void kbd_put_keycode(int keycode)
531
{
532
    if (qemu_put_kbd_event) {
533
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
534
    }
535
}
536

    
537
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
538
{
539
    QEMUPutMouseEvent *mouse_event;
540
    void *mouse_event_opaque;
541
    int width;
542

    
543
    if (!qemu_put_mouse_event_current) {
544
        return;
545
    }
546

    
547
    mouse_event =
548
        qemu_put_mouse_event_current->qemu_put_mouse_event;
549
    mouse_event_opaque =
550
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
551

    
552
    if (mouse_event) {
553
        if (graphic_rotate) {
554
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
555
                width = 0x7fff;
556
            else
557
                width = graphic_width;
558
            mouse_event(mouse_event_opaque,
559
                                 width - dy, dx, dz, buttons_state);
560
        } else
561
            mouse_event(mouse_event_opaque,
562
                                 dx, dy, dz, buttons_state);
563
    }
564
}
565

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

    
571
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
572
}
573

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

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

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

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

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

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

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

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

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

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

    
644
#define QEMU_TIMER_BASE 1000000000LL
645

    
646
#ifdef WIN32
647

    
648
static int64_t clock_freq;
649

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

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

    
669
#else
670

    
671
static int use_rt_clock;
672

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

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

    
704
#endif
705

    
706
/***********************************************************/
707
/* guest cycle counter */
708

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

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

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

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

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

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

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

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

    
784
QEMUClock *rt_clock;
785
QEMUClock *vm_clock;
786

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

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

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

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

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

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

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

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

    
849
    qemu_del_timer(ts);
850

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1027
#ifndef _WIN32
1028

    
1029
#if defined(__linux__)
1030

    
1031
#define RTC_FREQ 1024
1032

    
1033
static int rtc_fd;
1034

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

    
1055
#else
1056

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

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

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

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

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

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

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

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

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

    
1164
/***********************************************************/
1165
/* character device */
1166

    
1167
static void qemu_chr_event(CharDriverState *s, int event)
1168
{
1169
    if (!s->chr_event)
1170
        return;
1171
    s->chr_event(s->handler_opaque, event);
1172
}
1173

    
1174
static void qemu_chr_reset_bh(void *opaque)
1175
{
1176
    CharDriverState *s = opaque;
1177
    qemu_chr_event(s, CHR_EVENT_RESET);
1178
    qemu_bh_delete(s->bh);
1179
    s->bh = NULL;
1180
}
1181

    
1182
void qemu_chr_reset(CharDriverState *s)
1183
{
1184
    if (s->bh == NULL) {
1185
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1186
        qemu_bh_schedule(s->bh);
1187
    }
1188
}
1189

    
1190
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1191
{
1192
    return s->chr_write(s, buf, len);
1193
}
1194

    
1195
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1196
{
1197
    if (!s->chr_ioctl)
1198
        return -ENOTSUP;
1199
    return s->chr_ioctl(s, cmd, arg);
1200
}
1201

    
1202
int qemu_chr_can_read(CharDriverState *s)
1203
{
1204
    if (!s->chr_can_read)
1205
        return 0;
1206
    return s->chr_can_read(s->handler_opaque);
1207
}
1208

    
1209
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1210
{
1211
    s->chr_read(s->handler_opaque, buf, len);
1212
}
1213

    
1214

    
1215
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1216
{
1217
    char buf[4096];
1218
    va_list ap;
1219
    va_start(ap, fmt);
1220
    vsnprintf(buf, sizeof(buf), fmt, ap);
1221
    qemu_chr_write(s, buf, strlen(buf));
1222
    va_end(ap);
1223
}
1224

    
1225
void qemu_chr_send_event(CharDriverState *s, int event)
1226
{
1227
    if (s->chr_send_event)
1228
        s->chr_send_event(s, event);
1229
}
1230

    
1231
void qemu_chr_add_handlers(CharDriverState *s, 
1232
                           IOCanRWHandler *fd_can_read, 
1233
                           IOReadHandler *fd_read,
1234
                           IOEventHandler *fd_event,
1235
                           void *opaque)
1236
{
1237
    s->chr_can_read = fd_can_read;
1238
    s->chr_read = fd_read;
1239
    s->chr_event = fd_event;
1240
    s->handler_opaque = opaque;
1241
    if (s->chr_update_read_handler)
1242
        s->chr_update_read_handler(s);
1243
}
1244
             
1245
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1246
{
1247
    return len;
1248
}
1249

    
1250
static CharDriverState *qemu_chr_open_null(void)
1251
{
1252
    CharDriverState *chr;
1253

    
1254
    chr = qemu_mallocz(sizeof(CharDriverState));
1255
    if (!chr)
1256
        return NULL;
1257
    chr->chr_write = null_chr_write;
1258
    return chr;
1259
}
1260

    
1261
/* MUX driver for serial I/O splitting */
1262
static int term_timestamps;
1263
static int64_t term_timestamps_start;
1264
#define MAX_MUX 4
1265
typedef struct {
1266
    IOCanRWHandler *chr_can_read[MAX_MUX];
1267
    IOReadHandler *chr_read[MAX_MUX];
1268
    IOEventHandler *chr_event[MAX_MUX];
1269
    void *ext_opaque[MAX_MUX];
1270
    CharDriverState *drv;
1271
    int mux_cnt;
1272
    int term_got_escape;
1273
    int max_size;
1274
} MuxDriver;
1275

    
1276

    
1277
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1278
{
1279
    MuxDriver *d = chr->opaque;
1280
    int ret;
1281
    if (!term_timestamps) {
1282
        ret = d->drv->chr_write(d->drv, buf, len);
1283
    } else {
1284
        int i;
1285

    
1286
        ret = 0;
1287
        for(i = 0; i < len; i++) {
1288
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1289
            if (buf[i] == '\n') {
1290
                char buf1[64];
1291
                int64_t ti;
1292
                int secs;
1293

    
1294
                ti = get_clock();
1295
                if (term_timestamps_start == -1)
1296
                    term_timestamps_start = ti;
1297
                ti -= term_timestamps_start;
1298
                secs = ti / 1000000000;
1299
                snprintf(buf1, sizeof(buf1),
1300
                         "[%02d:%02d:%02d.%03d] ",
1301
                         secs / 3600,
1302
                         (secs / 60) % 60,
1303
                         secs % 60,
1304
                         (int)((ti / 1000000) % 1000));
1305
                d->drv->chr_write(d->drv, buf1, strlen(buf1));
1306
            }
1307
        }
1308
    }
1309
    return ret;
1310
}
1311

    
1312
static char *mux_help[] = {
1313
    "% h    print this help\n\r",
1314
    "% x    exit emulator\n\r",
1315
    "% s    save disk data back to file (if -snapshot)\n\r",
1316
    "% t    toggle console timestamps\n\r"
1317
    "% b    send break (magic sysrq)\n\r",
1318
    "% c    switch between console and monitor\n\r",
1319
    "% %  sends %\n\r",
1320
    NULL
1321
};
1322

    
1323
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1324
static void mux_print_help(CharDriverState *chr)
1325
{
1326
    int i, j;
1327
    char ebuf[15] = "Escape-Char";
1328
    char cbuf[50] = "\n\r";
1329

    
1330
    if (term_escape_char > 0 && term_escape_char < 26) {
1331
        sprintf(cbuf,"\n\r");
1332
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1333
    } else {
1334
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1335
    }
1336
    chr->chr_write(chr, cbuf, strlen(cbuf));
1337
    for (i = 0; mux_help[i] != NULL; i++) {
1338
        for (j=0; mux_help[i][j] != '\0'; j++) {
1339
            if (mux_help[i][j] == '%')
1340
                chr->chr_write(chr, ebuf, strlen(ebuf));
1341
            else
1342
                chr->chr_write(chr, &mux_help[i][j], 1);
1343
        }
1344
    }
1345
}
1346

    
1347
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1348
{
1349
    if (d->term_got_escape) {
1350
        d->term_got_escape = 0;
1351
        if (ch == term_escape_char)
1352
            goto send_char;
1353
        switch(ch) {
1354
        case '?':
1355
        case 'h':
1356
            mux_print_help(chr);
1357
            break;
1358
        case 'x':
1359
            {
1360
                 char *term =  "QEMU: Terminated\n\r";
1361
                 chr->chr_write(chr,term,strlen(term));
1362
                 exit(0);
1363
                 break;
1364
            }
1365
        case 's':
1366
            {
1367
                int i;
1368
                for (i = 0; i < MAX_DISKS; i++) {
1369
                    if (bs_table[i])
1370
                        bdrv_commit(bs_table[i]);
1371
                }
1372
                if (mtd_bdrv)
1373
                    bdrv_commit(mtd_bdrv);
1374
            }
1375
            break;
1376
        case 'b':
1377
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1378
            break;
1379
        case 'c':
1380
            /* Switch to the next registered device */
1381
            chr->focus++;
1382
            if (chr->focus >= d->mux_cnt)
1383
                chr->focus = 0;
1384
            break;
1385
       case 't':
1386
           term_timestamps = !term_timestamps;
1387
           term_timestamps_start = -1;
1388
           break;
1389
        }
1390
    } else if (ch == term_escape_char) {
1391
        d->term_got_escape = 1;
1392
    } else {
1393
    send_char:
1394
        return 1;
1395
    }
1396
    return 0;
1397
}
1398

    
1399
static int mux_chr_can_read(void *opaque)
1400
{
1401
    CharDriverState *chr = opaque;
1402
    MuxDriver *d = chr->opaque;
1403
    if (d->chr_can_read[chr->focus])
1404
       return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1405
    return 0;
1406
}
1407

    
1408
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1409
{
1410
    CharDriverState *chr = opaque;
1411
    MuxDriver *d = chr->opaque;
1412
    int i;
1413
    for(i = 0; i < size; i++)
1414
        if (mux_proc_byte(chr, d, buf[i]))
1415
            d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1416
}
1417

    
1418
static void mux_chr_event(void *opaque, int event)
1419
{
1420
    CharDriverState *chr = opaque;
1421
    MuxDriver *d = chr->opaque;
1422
    int i;
1423

    
1424
    /* Send the event to all registered listeners */
1425
    for (i = 0; i < d->mux_cnt; i++)
1426
        if (d->chr_event[i])
1427
            d->chr_event[i](d->ext_opaque[i], event);
1428
}
1429

    
1430
static void mux_chr_update_read_handler(CharDriverState *chr)
1431
{
1432
    MuxDriver *d = chr->opaque;
1433

    
1434
    if (d->mux_cnt >= MAX_MUX) {
1435
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1436
        return;
1437
    }
1438
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1439
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1440
    d->chr_read[d->mux_cnt] = chr->chr_read;
1441
    d->chr_event[d->mux_cnt] = chr->chr_event;
1442
    /* Fix up the real driver with mux routines */
1443
    if (d->mux_cnt == 0) {
1444
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1445
                              mux_chr_event, chr);
1446
    }
1447
    chr->focus = d->mux_cnt;
1448
    d->mux_cnt++;
1449
}
1450

    
1451
CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1452
{
1453
    CharDriverState *chr;
1454
    MuxDriver *d;
1455

    
1456
    chr = qemu_mallocz(sizeof(CharDriverState));
1457
    if (!chr)
1458
        return NULL;
1459
    d = qemu_mallocz(sizeof(MuxDriver));
1460
    if (!d) {
1461
        free(chr);
1462
        return NULL;
1463
    }
1464

    
1465
    chr->opaque = d;
1466
    d->drv = drv;
1467
    chr->focus = -1;
1468
    chr->chr_write = mux_chr_write;
1469
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1470
    return chr;
1471
}
1472

    
1473

    
1474
#ifdef _WIN32
1475

    
1476
static void socket_cleanup(void)
1477
{
1478
    WSACleanup();
1479
}
1480

    
1481
static int socket_init(void)
1482
{
1483
    WSADATA Data;
1484
    int ret, err;
1485

    
1486
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1487
    if (ret != 0) {
1488
        err = WSAGetLastError();
1489
        fprintf(stderr, "WSAStartup: %d\n", err);
1490
        return -1;
1491
    }
1492
    atexit(socket_cleanup);
1493
    return 0;
1494
}
1495

    
1496
static int send_all(int fd, const uint8_t *buf, int len1)
1497
{
1498
    int ret, len;
1499
    
1500
    len = len1;
1501
    while (len > 0) {
1502
        ret = send(fd, buf, len, 0);
1503
        if (ret < 0) {
1504
            int errno;
1505
            errno = WSAGetLastError();
1506
            if (errno != WSAEWOULDBLOCK) {
1507
                return -1;
1508
            }
1509
        } else if (ret == 0) {
1510
            break;
1511
        } else {
1512
            buf += ret;
1513
            len -= ret;
1514
        }
1515
    }
1516
    return len1 - len;
1517
}
1518

    
1519
void socket_set_nonblock(int fd)
1520
{
1521
    unsigned long opt = 1;
1522
    ioctlsocket(fd, FIONBIO, &opt);
1523
}
1524

    
1525
#else
1526

    
1527
static int unix_write(int fd, const uint8_t *buf, int len1)
1528
{
1529
    int ret, len;
1530

    
1531
    len = len1;
1532
    while (len > 0) {
1533
        ret = write(fd, buf, len);
1534
        if (ret < 0) {
1535
            if (errno != EINTR && errno != EAGAIN)
1536
                return -1;
1537
        } else if (ret == 0) {
1538
            break;
1539
        } else {
1540
            buf += ret;
1541
            len -= ret;
1542
        }
1543
    }
1544
    return len1 - len;
1545
}
1546

    
1547
static inline int send_all(int fd, const uint8_t *buf, int len1)
1548
{
1549
    return unix_write(fd, buf, len1);
1550
}
1551

    
1552
void socket_set_nonblock(int fd)
1553
{
1554
    fcntl(fd, F_SETFL, O_NONBLOCK);
1555
}
1556
#endif /* !_WIN32 */
1557

    
1558
#ifndef _WIN32
1559

    
1560
typedef struct {
1561
    int fd_in, fd_out;
1562
    int max_size;
1563
} FDCharDriver;
1564

    
1565
#define STDIO_MAX_CLIENTS 1
1566
static int stdio_nb_clients = 0;
1567

    
1568
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1569
{
1570
    FDCharDriver *s = chr->opaque;
1571
    return unix_write(s->fd_out, buf, len);
1572
}
1573

    
1574
static int fd_chr_read_poll(void *opaque)
1575
{
1576
    CharDriverState *chr = opaque;
1577
    FDCharDriver *s = chr->opaque;
1578

    
1579
    s->max_size = qemu_chr_can_read(chr);
1580
    return s->max_size;
1581
}
1582

    
1583
static void fd_chr_read(void *opaque)
1584
{
1585
    CharDriverState *chr = opaque;
1586
    FDCharDriver *s = chr->opaque;
1587
    int size, len;
1588
    uint8_t buf[1024];
1589
    
1590
    len = sizeof(buf);
1591
    if (len > s->max_size)
1592
        len = s->max_size;
1593
    if (len == 0)
1594
        return;
1595
    size = read(s->fd_in, buf, len);
1596
    if (size == 0) {
1597
        /* FD has been closed. Remove it from the active list.  */
1598
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1599
        return;
1600
    }
1601
    if (size > 0) {
1602
        qemu_chr_read(chr, buf, size);
1603
    }
1604
}
1605

    
1606
static void fd_chr_update_read_handler(CharDriverState *chr)
1607
{
1608
    FDCharDriver *s = chr->opaque;
1609

    
1610
    if (s->fd_in >= 0) {
1611
        if (nographic && s->fd_in == 0) {
1612
        } else {
1613
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1614
                                 fd_chr_read, NULL, chr);
1615
        }
1616
    }
1617
}
1618

    
1619
/* open a character device to a unix fd */
1620
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1621
{
1622
    CharDriverState *chr;
1623
    FDCharDriver *s;
1624

    
1625
    chr = qemu_mallocz(sizeof(CharDriverState));
1626
    if (!chr)
1627
        return NULL;
1628
    s = qemu_mallocz(sizeof(FDCharDriver));
1629
    if (!s) {
1630
        free(chr);
1631
        return NULL;
1632
    }
1633
    s->fd_in = fd_in;
1634
    s->fd_out = fd_out;
1635
    chr->opaque = s;
1636
    chr->chr_write = fd_chr_write;
1637
    chr->chr_update_read_handler = fd_chr_update_read_handler;
1638

    
1639
    qemu_chr_reset(chr);
1640

    
1641
    return chr;
1642
}
1643

    
1644
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1645
{
1646
    int fd_out;
1647

    
1648
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
1649
    if (fd_out < 0)
1650
        return NULL;
1651
    return qemu_chr_open_fd(-1, fd_out);
1652
}
1653

    
1654
static CharDriverState *qemu_chr_open_pipe(const char *filename)
1655
{
1656
    int fd_in, fd_out;
1657
    char filename_in[256], filename_out[256];
1658

    
1659
    snprintf(filename_in, 256, "%s.in", filename);
1660
    snprintf(filename_out, 256, "%s.out", filename);
1661
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
1662
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
1663
    if (fd_in < 0 || fd_out < 0) {
1664
        if (fd_in >= 0)
1665
            close(fd_in);
1666
        if (fd_out >= 0)
1667
            close(fd_out);
1668
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
1669
        if (fd_in < 0)
1670
            return NULL;
1671
    }
1672
    return qemu_chr_open_fd(fd_in, fd_out);
1673
}
1674

    
1675

    
1676
/* for STDIO, we handle the case where several clients use it
1677
   (nographic mode) */
1678

    
1679
#define TERM_FIFO_MAX_SIZE 1
1680

    
1681
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1682
static int term_fifo_size;
1683

    
1684
static int stdio_read_poll(void *opaque)
1685
{
1686
    CharDriverState *chr = opaque;
1687

    
1688
    /* try to flush the queue if needed */
1689
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1690
        qemu_chr_read(chr, term_fifo, 1);
1691
        term_fifo_size = 0;
1692
    }
1693
    /* see if we can absorb more chars */
1694
    if (term_fifo_size == 0)
1695
        return 1;
1696
    else
1697
        return 0;
1698
}
1699

    
1700
static void stdio_read(void *opaque)
1701
{
1702
    int size;
1703
    uint8_t buf[1];
1704
    CharDriverState *chr = opaque;
1705

    
1706
    size = read(0, buf, 1);
1707
    if (size == 0) {
1708
        /* stdin has been closed. Remove it from the active list.  */
1709
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1710
        return;
1711
    }
1712
    if (size > 0) {
1713
        if (qemu_chr_can_read(chr) > 0) {
1714
            qemu_chr_read(chr, buf, 1);
1715
        } else if (term_fifo_size == 0) {
1716
            term_fifo[term_fifo_size++] = buf[0];
1717
        }
1718
    }
1719
}
1720

    
1721
/* init terminal so that we can grab keys */
1722
static struct termios oldtty;
1723
static int old_fd0_flags;
1724

    
1725
static void term_exit(void)
1726
{
1727
    tcsetattr (0, TCSANOW, &oldtty);
1728
    fcntl(0, F_SETFL, old_fd0_flags);
1729
}
1730

    
1731
static void term_init(void)
1732
{
1733
    struct termios tty;
1734

    
1735
    tcgetattr (0, &tty);
1736
    oldtty = tty;
1737
    old_fd0_flags = fcntl(0, F_GETFL);
1738

    
1739
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1740
                          |INLCR|IGNCR|ICRNL|IXON);
1741
    tty.c_oflag |= OPOST;
1742
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1743
    /* if graphical mode, we allow Ctrl-C handling */
1744
    if (nographic)
1745
        tty.c_lflag &= ~ISIG;
1746
    tty.c_cflag &= ~(CSIZE|PARENB);
1747
    tty.c_cflag |= CS8;
1748
    tty.c_cc[VMIN] = 1;
1749
    tty.c_cc[VTIME] = 0;
1750
    
1751
    tcsetattr (0, TCSANOW, &tty);
1752

    
1753
    atexit(term_exit);
1754

    
1755
    fcntl(0, F_SETFL, O_NONBLOCK);
1756
}
1757

    
1758
static CharDriverState *qemu_chr_open_stdio(void)
1759
{
1760
    CharDriverState *chr;
1761

    
1762
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1763
        return NULL;
1764
    chr = qemu_chr_open_fd(0, 1);
1765
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1766
    stdio_nb_clients++;
1767
    term_init();
1768

    
1769
    return chr;
1770
}
1771

    
1772
#if defined(__linux__) || defined(__sun__)
1773
static CharDriverState *qemu_chr_open_pty(void)
1774
{
1775
    struct termios tty;
1776
    char slave_name[1024];
1777
    int master_fd, slave_fd;
1778
    
1779
#if defined(__linux__)
1780
    /* Not satisfying */
1781
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1782
        return NULL;
1783
    }
1784
#endif
1785
    
1786
    /* Disabling local echo and line-buffered output */
1787
    tcgetattr (master_fd, &tty);
1788
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1789
    tty.c_cc[VMIN] = 1;
1790
    tty.c_cc[VTIME] = 0;
1791
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1792

    
1793
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1794
    return qemu_chr_open_fd(master_fd, master_fd);
1795
}
1796

    
1797
static void tty_serial_init(int fd, int speed, 
1798
                            int parity, int data_bits, int stop_bits)
1799
{
1800
    struct termios tty;
1801
    speed_t spd;
1802

    
1803
#if 0
1804
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1805
           speed, parity, data_bits, stop_bits);
1806
#endif
1807
    tcgetattr (fd, &tty);
1808

    
1809
    switch(speed) {
1810
    case 50:
1811
        spd = B50;
1812
        break;
1813
    case 75:
1814
        spd = B75;
1815
        break;
1816
    case 300:
1817
        spd = B300;
1818
        break;
1819
    case 600:
1820
        spd = B600;
1821
        break;
1822
    case 1200:
1823
        spd = B1200;
1824
        break;
1825
    case 2400:
1826
        spd = B2400;
1827
        break;
1828
    case 4800:
1829
        spd = B4800;
1830
        break;
1831
    case 9600:
1832
        spd = B9600;
1833
        break;
1834
    case 19200:
1835
        spd = B19200;
1836
        break;
1837
    case 38400:
1838
        spd = B38400;
1839
        break;
1840
    case 57600:
1841
        spd = B57600;
1842
        break;
1843
    default:
1844
    case 115200:
1845
        spd = B115200;
1846
        break;
1847
    }
1848

    
1849
    cfsetispeed(&tty, spd);
1850
    cfsetospeed(&tty, spd);
1851

    
1852
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1853
                          |INLCR|IGNCR|ICRNL|IXON);
1854
    tty.c_oflag |= OPOST;
1855
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1856
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1857
    switch(data_bits) {
1858
    default:
1859
    case 8:
1860
        tty.c_cflag |= CS8;
1861
        break;
1862
    case 7:
1863
        tty.c_cflag |= CS7;
1864
        break;
1865
    case 6:
1866
        tty.c_cflag |= CS6;
1867
        break;
1868
    case 5:
1869
        tty.c_cflag |= CS5;
1870
        break;
1871
    }
1872
    switch(parity) {
1873
    default:
1874
    case 'N':
1875
        break;
1876
    case 'E':
1877
        tty.c_cflag |= PARENB;
1878
        break;
1879
    case 'O':
1880
        tty.c_cflag |= PARENB | PARODD;
1881
        break;
1882
    }
1883
    if (stop_bits == 2)
1884
        tty.c_cflag |= CSTOPB;
1885
    
1886
    tcsetattr (fd, TCSANOW, &tty);
1887
}
1888

    
1889
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1890
{
1891
    FDCharDriver *s = chr->opaque;
1892
    
1893
    switch(cmd) {
1894
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1895
        {
1896
            QEMUSerialSetParams *ssp = arg;
1897
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1898
                            ssp->data_bits, ssp->stop_bits);
1899
        }
1900
        break;
1901
    case CHR_IOCTL_SERIAL_SET_BREAK:
1902
        {
1903
            int enable = *(int *)arg;
1904
            if (enable)
1905
                tcsendbreak(s->fd_in, 1);
1906
        }
1907
        break;
1908
    default:
1909
        return -ENOTSUP;
1910
    }
1911
    return 0;
1912
}
1913

    
1914
static CharDriverState *qemu_chr_open_tty(const char *filename)
1915
{
1916
    CharDriverState *chr;
1917
    int fd;
1918

    
1919
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1920
    fcntl(fd, F_SETFL, O_NONBLOCK);
1921
    tty_serial_init(fd, 115200, 'N', 8, 1);
1922
    chr = qemu_chr_open_fd(fd, fd);
1923
    if (!chr) {
1924
        close(fd);
1925
        return NULL;
1926
    }
1927
    chr->chr_ioctl = tty_serial_ioctl;
1928
    qemu_chr_reset(chr);
1929
    return chr;
1930
}
1931
#else  /* ! __linux__ && ! __sun__ */
1932
static CharDriverState *qemu_chr_open_pty(void)
1933
{
1934
    return NULL;
1935
}
1936
#endif /* __linux__ || __sun__ */
1937

    
1938
#if defined(__linux__)
1939
typedef struct {
1940
    int fd;
1941
    int mode;
1942
} ParallelCharDriver;
1943

    
1944
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1945
{
1946
    if (s->mode != mode) {
1947
        int m = mode;
1948
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1949
            return 0;
1950
        s->mode = mode;
1951
    }
1952
    return 1;
1953
}
1954

    
1955
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1956
{
1957
    ParallelCharDriver *drv = chr->opaque;
1958
    int fd = drv->fd;
1959
    uint8_t b;
1960

    
1961
    switch(cmd) {
1962
    case CHR_IOCTL_PP_READ_DATA:
1963
        if (ioctl(fd, PPRDATA, &b) < 0)
1964
            return -ENOTSUP;
1965
        *(uint8_t *)arg = b;
1966
        break;
1967
    case CHR_IOCTL_PP_WRITE_DATA:
1968
        b = *(uint8_t *)arg;
1969
        if (ioctl(fd, PPWDATA, &b) < 0)
1970
            return -ENOTSUP;
1971
        break;
1972
    case CHR_IOCTL_PP_READ_CONTROL:
1973
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1974
            return -ENOTSUP;
1975
        /* Linux gives only the lowest bits, and no way to know data
1976
           direction! For better compatibility set the fixed upper
1977
           bits. */
1978
        *(uint8_t *)arg = b | 0xc0;
1979
        break;
1980
    case CHR_IOCTL_PP_WRITE_CONTROL:
1981
        b = *(uint8_t *)arg;
1982
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1983
            return -ENOTSUP;
1984
        break;
1985
    case CHR_IOCTL_PP_READ_STATUS:
1986
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1987
            return -ENOTSUP;
1988
        *(uint8_t *)arg = b;
1989
        break;
1990
    case CHR_IOCTL_PP_EPP_READ_ADDR:
1991
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1992
            struct ParallelIOArg *parg = arg;
1993
            int n = read(fd, parg->buffer, parg->count);
1994
            if (n != parg->count) {
1995
                return -EIO;
1996
            }
1997
        }
1998
        break;
1999
    case CHR_IOCTL_PP_EPP_READ:
2000
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2001
            struct ParallelIOArg *parg = arg;
2002
            int n = read(fd, parg->buffer, parg->count);
2003
            if (n != parg->count) {
2004
                return -EIO;
2005
            }
2006
        }
2007
        break;
2008
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2009
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2010
            struct ParallelIOArg *parg = arg;
2011
            int n = write(fd, parg->buffer, parg->count);
2012
            if (n != parg->count) {
2013
                return -EIO;
2014
            }
2015
        }
2016
        break;
2017
    case CHR_IOCTL_PP_EPP_WRITE:
2018
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2019
            struct ParallelIOArg *parg = arg;
2020
            int n = write(fd, parg->buffer, parg->count);
2021
            if (n != parg->count) {
2022
                return -EIO;
2023
            }
2024
        }
2025
        break;
2026
    default:
2027
        return -ENOTSUP;
2028
    }
2029
    return 0;
2030
}
2031

    
2032
static void pp_close(CharDriverState *chr)
2033
{
2034
    ParallelCharDriver *drv = chr->opaque;
2035
    int fd = drv->fd;
2036

    
2037
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2038
    ioctl(fd, PPRELEASE);
2039
    close(fd);
2040
    qemu_free(drv);
2041
}
2042

    
2043
static CharDriverState *qemu_chr_open_pp(const char *filename)
2044
{
2045
    CharDriverState *chr;
2046
    ParallelCharDriver *drv;
2047
    int fd;
2048

    
2049
    TFR(fd = open(filename, O_RDWR));
2050
    if (fd < 0)
2051
        return NULL;
2052

    
2053
    if (ioctl(fd, PPCLAIM) < 0) {
2054
        close(fd);
2055
        return NULL;
2056
    }
2057

    
2058
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2059
    if (!drv) {
2060
        close(fd);
2061
        return NULL;
2062
    }
2063
    drv->fd = fd;
2064
    drv->mode = IEEE1284_MODE_COMPAT;
2065

    
2066
    chr = qemu_mallocz(sizeof(CharDriverState));
2067
    if (!chr) {
2068
        qemu_free(drv);
2069
        close(fd);
2070
        return NULL;
2071
    }
2072
    chr->chr_write = null_chr_write;
2073
    chr->chr_ioctl = pp_ioctl;
2074
    chr->chr_close = pp_close;
2075
    chr->opaque = drv;
2076

    
2077
    qemu_chr_reset(chr);
2078

    
2079
    return chr;
2080
}
2081
#endif /* __linux__ */
2082

    
2083
#else /* _WIN32 */
2084

    
2085
typedef struct {
2086
    int max_size;
2087
    HANDLE hcom, hrecv, hsend;
2088
    OVERLAPPED orecv, osend;
2089
    BOOL fpipe;
2090
    DWORD len;
2091
} WinCharState;
2092

    
2093
#define NSENDBUF 2048
2094
#define NRECVBUF 2048
2095
#define MAXCONNECT 1
2096
#define NTIMEOUT 5000
2097

    
2098
static int win_chr_poll(void *opaque);
2099
static int win_chr_pipe_poll(void *opaque);
2100

    
2101
static void win_chr_close(CharDriverState *chr)
2102
{
2103
    WinCharState *s = chr->opaque;
2104

    
2105
    if (s->hsend) {
2106
        CloseHandle(s->hsend);
2107
        s->hsend = NULL;
2108
    }
2109
    if (s->hrecv) {
2110
        CloseHandle(s->hrecv);
2111
        s->hrecv = NULL;
2112
    }
2113
    if (s->hcom) {
2114
        CloseHandle(s->hcom);
2115
        s->hcom = NULL;
2116
    }
2117
    if (s->fpipe)
2118
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2119
    else
2120
        qemu_del_polling_cb(win_chr_poll, chr);
2121
}
2122

    
2123
static int win_chr_init(CharDriverState *chr, const char *filename)
2124
{
2125
    WinCharState *s = chr->opaque;
2126
    COMMCONFIG comcfg;
2127
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2128
    COMSTAT comstat;
2129
    DWORD size;
2130
    DWORD err;
2131
    
2132
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2133
    if (!s->hsend) {
2134
        fprintf(stderr, "Failed CreateEvent\n");
2135
        goto fail;
2136
    }
2137
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2138
    if (!s->hrecv) {
2139
        fprintf(stderr, "Failed CreateEvent\n");
2140
        goto fail;
2141
    }
2142

    
2143
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2144
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2145
    if (s->hcom == INVALID_HANDLE_VALUE) {
2146
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2147
        s->hcom = NULL;
2148
        goto fail;
2149
    }
2150
    
2151
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2152
        fprintf(stderr, "Failed SetupComm\n");
2153
        goto fail;
2154
    }
2155
    
2156
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2157
    size = sizeof(COMMCONFIG);
2158
    GetDefaultCommConfig(filename, &comcfg, &size);
2159
    comcfg.dcb.DCBlength = sizeof(DCB);
2160
    CommConfigDialog(filename, NULL, &comcfg);
2161

    
2162
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2163
        fprintf(stderr, "Failed SetCommState\n");
2164
        goto fail;
2165
    }
2166

    
2167
    if (!SetCommMask(s->hcom, EV_ERR)) {
2168
        fprintf(stderr, "Failed SetCommMask\n");
2169
        goto fail;
2170
    }
2171

    
2172
    cto.ReadIntervalTimeout = MAXDWORD;
2173
    if (!SetCommTimeouts(s->hcom, &cto)) {
2174
        fprintf(stderr, "Failed SetCommTimeouts\n");
2175
        goto fail;
2176
    }
2177
    
2178
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2179
        fprintf(stderr, "Failed ClearCommError\n");
2180
        goto fail;
2181
    }
2182
    qemu_add_polling_cb(win_chr_poll, chr);
2183
    return 0;
2184

    
2185
 fail:
2186
    win_chr_close(chr);
2187
    return -1;
2188
}
2189

    
2190
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2191
{
2192
    WinCharState *s = chr->opaque;
2193
    DWORD len, ret, size, err;
2194

    
2195
    len = len1;
2196
    ZeroMemory(&s->osend, sizeof(s->osend));
2197
    s->osend.hEvent = s->hsend;
2198
    while (len > 0) {
2199
        if (s->hsend)
2200
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2201
        else
2202
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2203
        if (!ret) {
2204
            err = GetLastError();
2205
            if (err == ERROR_IO_PENDING) {
2206
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2207
                if (ret) {
2208
                    buf += size;
2209
                    len -= size;
2210
                } else {
2211
                    break;
2212
                }
2213
            } else {
2214
                break;
2215
            }
2216
        } else {
2217
            buf += size;
2218
            len -= size;
2219
        }
2220
    }
2221
    return len1 - len;
2222
}
2223

    
2224
static int win_chr_read_poll(CharDriverState *chr)
2225
{
2226
    WinCharState *s = chr->opaque;
2227

    
2228
    s->max_size = qemu_chr_can_read(chr);
2229
    return s->max_size;
2230
}
2231

    
2232
static void win_chr_readfile(CharDriverState *chr)
2233
{
2234
    WinCharState *s = chr->opaque;
2235
    int ret, err;
2236
    uint8_t buf[1024];
2237
    DWORD size;
2238
    
2239
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2240
    s->orecv.hEvent = s->hrecv;
2241
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2242
    if (!ret) {
2243
        err = GetLastError();
2244
        if (err == ERROR_IO_PENDING) {
2245
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2246
        }
2247
    }
2248

    
2249
    if (size > 0) {
2250
        qemu_chr_read(chr, buf, size);
2251
    }
2252
}
2253

    
2254
static void win_chr_read(CharDriverState *chr)
2255
{
2256
    WinCharState *s = chr->opaque;
2257

    
2258
    if (s->len > s->max_size)
2259
        s->len = s->max_size;
2260
    if (s->len == 0)
2261
        return;
2262
    
2263
    win_chr_readfile(chr);
2264
}
2265

    
2266
static int win_chr_poll(void *opaque)
2267
{
2268
    CharDriverState *chr = opaque;
2269
    WinCharState *s = chr->opaque;
2270
    COMSTAT status;
2271
    DWORD comerr;
2272
    
2273
    ClearCommError(s->hcom, &comerr, &status);
2274
    if (status.cbInQue > 0) {
2275
        s->len = status.cbInQue;
2276
        win_chr_read_poll(chr);
2277
        win_chr_read(chr);
2278
        return 1;
2279
    }
2280
    return 0;
2281
}
2282

    
2283
static CharDriverState *qemu_chr_open_win(const char *filename)
2284
{
2285
    CharDriverState *chr;
2286
    WinCharState *s;
2287
    
2288
    chr = qemu_mallocz(sizeof(CharDriverState));
2289
    if (!chr)
2290
        return NULL;
2291
    s = qemu_mallocz(sizeof(WinCharState));
2292
    if (!s) {
2293
        free(chr);
2294
        return NULL;
2295
    }
2296
    chr->opaque = s;
2297
    chr->chr_write = win_chr_write;
2298
    chr->chr_close = win_chr_close;
2299

    
2300
    if (win_chr_init(chr, filename) < 0) {
2301
        free(s);
2302
        free(chr);
2303
        return NULL;
2304
    }
2305
    qemu_chr_reset(chr);
2306
    return chr;
2307
}
2308

    
2309
static int win_chr_pipe_poll(void *opaque)
2310
{
2311
    CharDriverState *chr = opaque;
2312
    WinCharState *s = chr->opaque;
2313
    DWORD size;
2314

    
2315
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2316
    if (size > 0) {
2317
        s->len = size;
2318
        win_chr_read_poll(chr);
2319
        win_chr_read(chr);
2320
        return 1;
2321
    }
2322
    return 0;
2323
}
2324

    
2325
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2326
{
2327
    WinCharState *s = chr->opaque;
2328
    OVERLAPPED ov;
2329
    int ret;
2330
    DWORD size;
2331
    char openname[256];
2332
    
2333
    s->fpipe = TRUE;
2334

    
2335
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2336
    if (!s->hsend) {
2337
        fprintf(stderr, "Failed CreateEvent\n");
2338
        goto fail;
2339
    }
2340
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2341
    if (!s->hrecv) {
2342
        fprintf(stderr, "Failed CreateEvent\n");
2343
        goto fail;
2344
    }
2345
    
2346
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2347
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2348
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2349
                              PIPE_WAIT,
2350
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2351
    if (s->hcom == INVALID_HANDLE_VALUE) {
2352
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2353
        s->hcom = NULL;
2354
        goto fail;
2355
    }
2356

    
2357
    ZeroMemory(&ov, sizeof(ov));
2358
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2359
    ret = ConnectNamedPipe(s->hcom, &ov);
2360
    if (ret) {
2361
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2362
        goto fail;
2363
    }
2364

    
2365
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2366
    if (!ret) {
2367
        fprintf(stderr, "Failed GetOverlappedResult\n");
2368
        if (ov.hEvent) {
2369
            CloseHandle(ov.hEvent);
2370
            ov.hEvent = NULL;
2371
        }
2372
        goto fail;
2373
    }
2374

    
2375
    if (ov.hEvent) {
2376
        CloseHandle(ov.hEvent);
2377
        ov.hEvent = NULL;
2378
    }
2379
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2380
    return 0;
2381

    
2382
 fail:
2383
    win_chr_close(chr);
2384
    return -1;
2385
}
2386

    
2387

    
2388
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2389
{
2390
    CharDriverState *chr;
2391
    WinCharState *s;
2392

    
2393
    chr = qemu_mallocz(sizeof(CharDriverState));
2394
    if (!chr)
2395
        return NULL;
2396
    s = qemu_mallocz(sizeof(WinCharState));
2397
    if (!s) {
2398
        free(chr);
2399
        return NULL;
2400
    }
2401
    chr->opaque = s;
2402
    chr->chr_write = win_chr_write;
2403
    chr->chr_close = win_chr_close;
2404
    
2405
    if (win_chr_pipe_init(chr, filename) < 0) {
2406
        free(s);
2407
        free(chr);
2408
        return NULL;
2409
    }
2410
    qemu_chr_reset(chr);
2411
    return chr;
2412
}
2413

    
2414
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2415
{
2416
    CharDriverState *chr;
2417
    WinCharState *s;
2418

    
2419
    chr = qemu_mallocz(sizeof(CharDriverState));
2420
    if (!chr)
2421
        return NULL;
2422
    s = qemu_mallocz(sizeof(WinCharState));
2423
    if (!s) {
2424
        free(chr);
2425
        return NULL;
2426
    }
2427
    s->hcom = fd_out;
2428
    chr->opaque = s;
2429
    chr->chr_write = win_chr_write;
2430
    qemu_chr_reset(chr);
2431
    return chr;
2432
}
2433

    
2434
static CharDriverState *qemu_chr_open_win_con(const char *filename)
2435
{
2436
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2437
}
2438

    
2439
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2440
{
2441
    HANDLE fd_out;
2442
    
2443
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2444
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2445
    if (fd_out == INVALID_HANDLE_VALUE)
2446
        return NULL;
2447

    
2448
    return qemu_chr_open_win_file(fd_out);
2449
}
2450
#endif /* !_WIN32 */
2451

    
2452
/***********************************************************/
2453
/* UDP Net console */
2454

    
2455
typedef struct {
2456
    int fd;
2457
    struct sockaddr_in daddr;
2458
    char buf[1024];
2459
    int bufcnt;
2460
    int bufptr;
2461
    int max_size;
2462
} NetCharDriver;
2463

    
2464
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2465
{
2466
    NetCharDriver *s = chr->opaque;
2467

    
2468
    return sendto(s->fd, buf, len, 0,
2469
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2470
}
2471

    
2472
static int udp_chr_read_poll(void *opaque)
2473
{
2474
    CharDriverState *chr = opaque;
2475
    NetCharDriver *s = chr->opaque;
2476

    
2477
    s->max_size = qemu_chr_can_read(chr);
2478

    
2479
    /* If there were any stray characters in the queue process them
2480
     * first
2481
     */
2482
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2483
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2484
        s->bufptr++;
2485
        s->max_size = qemu_chr_can_read(chr);
2486
    }
2487
    return s->max_size;
2488
}
2489

    
2490
static void udp_chr_read(void *opaque)
2491
{
2492
    CharDriverState *chr = opaque;
2493
    NetCharDriver *s = chr->opaque;
2494

    
2495
    if (s->max_size == 0)
2496
        return;
2497
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2498
    s->bufptr = s->bufcnt;
2499
    if (s->bufcnt <= 0)
2500
        return;
2501

    
2502
    s->bufptr = 0;
2503
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2504
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2505
        s->bufptr++;
2506
        s->max_size = qemu_chr_can_read(chr);
2507
    }
2508
}
2509

    
2510
static void udp_chr_update_read_handler(CharDriverState *chr)
2511
{
2512
    NetCharDriver *s = chr->opaque;
2513

    
2514
    if (s->fd >= 0) {
2515
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2516
                             udp_chr_read, NULL, chr);
2517
    }
2518
}
2519

    
2520
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2521
#ifndef _WIN32
2522
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2523
#endif
2524
int parse_host_src_port(struct sockaddr_in *haddr,
2525
                        struct sockaddr_in *saddr,
2526
                        const char *str);
2527

    
2528
static CharDriverState *qemu_chr_open_udp(const char *def)
2529
{
2530
    CharDriverState *chr = NULL;
2531
    NetCharDriver *s = NULL;
2532
    int fd = -1;
2533
    struct sockaddr_in saddr;
2534

    
2535
    chr = qemu_mallocz(sizeof(CharDriverState));
2536
    if (!chr)
2537
        goto return_err;
2538
    s = qemu_mallocz(sizeof(NetCharDriver));
2539
    if (!s)
2540
        goto return_err;
2541

    
2542
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2543
    if (fd < 0) {
2544
        perror("socket(PF_INET, SOCK_DGRAM)");
2545
        goto return_err;
2546
    }
2547

    
2548
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2549
        printf("Could not parse: %s\n", def);
2550
        goto return_err;
2551
    }
2552

    
2553
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2554
    {
2555
        perror("bind");
2556
        goto return_err;
2557
    }
2558

    
2559
    s->fd = fd;
2560
    s->bufcnt = 0;
2561
    s->bufptr = 0;
2562
    chr->opaque = s;
2563
    chr->chr_write = udp_chr_write;
2564
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2565
    return chr;
2566

    
2567
return_err:
2568
    if (chr)
2569
        free(chr);
2570
    if (s)
2571
        free(s);
2572
    if (fd >= 0)
2573
        closesocket(fd);
2574
    return NULL;
2575
}
2576

    
2577
/***********************************************************/
2578
/* TCP Net console */
2579

    
2580
typedef struct {
2581
    int fd, listen_fd;
2582
    int connected;
2583
    int max_size;
2584
    int do_telnetopt;
2585
    int do_nodelay;
2586
    int is_unix;
2587
} TCPCharDriver;
2588

    
2589
static void tcp_chr_accept(void *opaque);
2590

    
2591
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2592
{
2593
    TCPCharDriver *s = chr->opaque;
2594
    if (s->connected) {
2595
        return send_all(s->fd, buf, len);
2596
    } else {
2597
        /* XXX: indicate an error ? */
2598
        return len;
2599
    }
2600
}
2601

    
2602
static int tcp_chr_read_poll(void *opaque)
2603
{
2604
    CharDriverState *chr = opaque;
2605
    TCPCharDriver *s = chr->opaque;
2606
    if (!s->connected)
2607
        return 0;
2608
    s->max_size = qemu_chr_can_read(chr);
2609
    return s->max_size;
2610
}
2611

    
2612
#define IAC 255
2613
#define IAC_BREAK 243
2614
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2615
                                      TCPCharDriver *s,
2616
                                      char *buf, int *size)
2617
{
2618
    /* Handle any telnet client's basic IAC options to satisfy char by
2619
     * char mode with no echo.  All IAC options will be removed from
2620
     * the buf and the do_telnetopt variable will be used to track the
2621
     * state of the width of the IAC information.
2622
     *
2623
     * IAC commands come in sets of 3 bytes with the exception of the
2624
     * "IAC BREAK" command and the double IAC.
2625
     */
2626

    
2627
    int i;
2628
    int j = 0;
2629

    
2630
    for (i = 0; i < *size; i++) {
2631
        if (s->do_telnetopt > 1) {
2632
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2633
                /* Double IAC means send an IAC */
2634
                if (j != i)
2635
                    buf[j] = buf[i];
2636
                j++;
2637
                s->do_telnetopt = 1;
2638
            } else {
2639
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2640
                    /* Handle IAC break commands by sending a serial break */
2641
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
2642
                    s->do_telnetopt++;
2643
                }
2644
                s->do_telnetopt++;
2645
            }
2646
            if (s->do_telnetopt >= 4) {
2647
                s->do_telnetopt = 1;
2648
            }
2649
        } else {
2650
            if ((unsigned char)buf[i] == IAC) {
2651
                s->do_telnetopt = 2;
2652
            } else {
2653
                if (j != i)
2654
                    buf[j] = buf[i];
2655
                j++;
2656
            }
2657
        }
2658
    }
2659
    *size = j;
2660
}
2661

    
2662
static void tcp_chr_read(void *opaque)
2663
{
2664
    CharDriverState *chr = opaque;
2665
    TCPCharDriver *s = chr->opaque;
2666
    uint8_t buf[1024];
2667
    int len, size;
2668

    
2669
    if (!s->connected || s->max_size <= 0)
2670
        return;
2671
    len = sizeof(buf);
2672
    if (len > s->max_size)
2673
        len = s->max_size;
2674
    size = recv(s->fd, buf, len, 0);
2675
    if (size == 0) {
2676
        /* connection closed */
2677
        s->connected = 0;
2678
        if (s->listen_fd >= 0) {
2679
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2680
        }
2681
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2682
        closesocket(s->fd);
2683
        s->fd = -1;
2684
    } else if (size > 0) {
2685
        if (s->do_telnetopt)
2686
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2687
        if (size > 0)
2688
            qemu_chr_read(chr, buf, size);
2689
    }
2690
}
2691

    
2692
static void tcp_chr_connect(void *opaque)
2693
{
2694
    CharDriverState *chr = opaque;
2695
    TCPCharDriver *s = chr->opaque;
2696

    
2697
    s->connected = 1;
2698
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2699
                         tcp_chr_read, NULL, chr);
2700
    qemu_chr_reset(chr);
2701
}
2702

    
2703
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2704
static void tcp_chr_telnet_init(int fd)
2705
{
2706
    char buf[3];
2707
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2708
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2709
    send(fd, (char *)buf, 3, 0);
2710
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2711
    send(fd, (char *)buf, 3, 0);
2712
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2713
    send(fd, (char *)buf, 3, 0);
2714
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2715
    send(fd, (char *)buf, 3, 0);
2716
}
2717

    
2718
static void socket_set_nodelay(int fd)
2719
{
2720
    int val = 1;
2721
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2722
}
2723

    
2724
static void tcp_chr_accept(void *opaque)
2725
{
2726
    CharDriverState *chr = opaque;
2727
    TCPCharDriver *s = chr->opaque;
2728
    struct sockaddr_in saddr;
2729
#ifndef _WIN32
2730
    struct sockaddr_un uaddr;
2731
#endif
2732
    struct sockaddr *addr;
2733
    socklen_t len;
2734
    int fd;
2735

    
2736
    for(;;) {
2737
#ifndef _WIN32
2738
        if (s->is_unix) {
2739
            len = sizeof(uaddr);
2740
            addr = (struct sockaddr *)&uaddr;
2741
        } else
2742
#endif
2743
        {
2744
            len = sizeof(saddr);
2745
            addr = (struct sockaddr *)&saddr;
2746
        }
2747
        fd = accept(s->listen_fd, addr, &len);
2748
        if (fd < 0 && errno != EINTR) {
2749
            return;
2750
        } else if (fd >= 0) {
2751
            if (s->do_telnetopt)
2752
                tcp_chr_telnet_init(fd);
2753
            break;
2754
        }
2755
    }
2756
    socket_set_nonblock(fd);
2757
    if (s->do_nodelay)
2758
        socket_set_nodelay(fd);
2759
    s->fd = fd;
2760
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2761
    tcp_chr_connect(chr);
2762
}
2763

    
2764
static void tcp_chr_close(CharDriverState *chr)
2765
{
2766
    TCPCharDriver *s = chr->opaque;
2767
    if (s->fd >= 0)
2768
        closesocket(s->fd);
2769
    if (s->listen_fd >= 0)
2770
        closesocket(s->listen_fd);
2771
    qemu_free(s);
2772
}
2773

    
2774
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2775
                                          int is_telnet,
2776
                                          int is_unix)
2777
{
2778
    CharDriverState *chr = NULL;
2779
    TCPCharDriver *s = NULL;
2780
    int fd = -1, ret, err, val;
2781
    int is_listen = 0;
2782
    int is_waitconnect = 1;
2783
    int do_nodelay = 0;
2784
    const char *ptr;
2785
    struct sockaddr_in saddr;
2786
#ifndef _WIN32
2787
    struct sockaddr_un uaddr;
2788
#endif
2789
    struct sockaddr *addr;
2790
    socklen_t addrlen;
2791

    
2792
#ifndef _WIN32
2793
    if (is_unix) {
2794
        addr = (struct sockaddr *)&uaddr;
2795
        addrlen = sizeof(uaddr);
2796
        if (parse_unix_path(&uaddr, host_str) < 0)
2797
            goto fail;
2798
    } else
2799
#endif
2800
    {
2801
        addr = (struct sockaddr *)&saddr;
2802
        addrlen = sizeof(saddr);
2803
        if (parse_host_port(&saddr, host_str) < 0)
2804
            goto fail;
2805
    }
2806

    
2807
    ptr = host_str;
2808
    while((ptr = strchr(ptr,','))) {
2809
        ptr++;
2810
        if (!strncmp(ptr,"server",6)) {
2811
            is_listen = 1;
2812
        } else if (!strncmp(ptr,"nowait",6)) {
2813
            is_waitconnect = 0;
2814
        } else if (!strncmp(ptr,"nodelay",6)) {
2815
            do_nodelay = 1;
2816
        } else {
2817
            printf("Unknown option: %s\n", ptr);
2818
            goto fail;
2819
        }
2820
    }
2821
    if (!is_listen)
2822
        is_waitconnect = 0;
2823

    
2824
    chr = qemu_mallocz(sizeof(CharDriverState));
2825
    if (!chr)
2826
        goto fail;
2827
    s = qemu_mallocz(sizeof(TCPCharDriver));
2828
    if (!s)
2829
        goto fail;
2830

    
2831
#ifndef _WIN32
2832
    if (is_unix)
2833
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2834
    else
2835
#endif
2836
        fd = socket(PF_INET, SOCK_STREAM, 0);
2837
        
2838
    if (fd < 0) 
2839
        goto fail;
2840

    
2841
    if (!is_waitconnect)
2842
        socket_set_nonblock(fd);
2843

    
2844
    s->connected = 0;
2845
    s->fd = -1;
2846
    s->listen_fd = -1;
2847
    s->is_unix = is_unix;
2848
    s->do_nodelay = do_nodelay && !is_unix;
2849

    
2850
    chr->opaque = s;
2851
    chr->chr_write = tcp_chr_write;
2852
    chr->chr_close = tcp_chr_close;
2853

    
2854
    if (is_listen) {
2855
        /* allow fast reuse */
2856
#ifndef _WIN32
2857
        if (is_unix) {
2858
            char path[109];
2859
            strncpy(path, uaddr.sun_path, 108);
2860
            path[108] = 0;
2861
            unlink(path);
2862
        } else
2863
#endif
2864
        {
2865
            val = 1;
2866
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2867
        }
2868
        
2869
        ret = bind(fd, addr, addrlen);
2870
        if (ret < 0)
2871
            goto fail;
2872

    
2873
        ret = listen(fd, 0);
2874
        if (ret < 0)
2875
            goto fail;
2876

    
2877
        s->listen_fd = fd;
2878
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2879
        if (is_telnet)
2880
            s->do_telnetopt = 1;
2881
    } else {
2882
        for(;;) {
2883
            ret = connect(fd, addr, addrlen);
2884
            if (ret < 0) {
2885
                err = socket_error();
2886
                if (err == EINTR || err == EWOULDBLOCK) {
2887
                } else if (err == EINPROGRESS) {
2888
                    break;
2889
#ifdef _WIN32
2890
                } else if (err == WSAEALREADY) {
2891
                    break;
2892
#endif
2893
                } else {
2894
                    goto fail;
2895
                }
2896
            } else {
2897
                s->connected = 1;
2898
                break;
2899
            }
2900
        }
2901
        s->fd = fd;
2902
        socket_set_nodelay(fd);
2903
        if (s->connected)
2904
            tcp_chr_connect(chr);
2905
        else
2906
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2907
    }
2908
    
2909
    if (is_listen && is_waitconnect) {
2910
        printf("QEMU waiting for connection on: %s\n", host_str);
2911
        tcp_chr_accept(chr);
2912
        socket_set_nonblock(s->listen_fd);
2913
    }
2914

    
2915
    return chr;
2916
 fail:
2917
    if (fd >= 0)
2918
        closesocket(fd);
2919
    qemu_free(s);
2920
    qemu_free(chr);
2921
    return NULL;
2922
}
2923

    
2924
CharDriverState *qemu_chr_open(const char *filename)
2925
{
2926
    const char *p;
2927

    
2928
    if (!strcmp(filename, "vc")) {
2929
        return text_console_init(&display_state, 0);
2930
    } else if (strstart(filename, "vc:", &p)) {
2931
        return text_console_init(&display_state, p);
2932
    } else if (!strcmp(filename, "null")) {
2933
        return qemu_chr_open_null();
2934
    } else 
2935
    if (strstart(filename, "tcp:", &p)) {
2936
        return qemu_chr_open_tcp(p, 0, 0);
2937
    } else
2938
    if (strstart(filename, "telnet:", &p)) {
2939
        return qemu_chr_open_tcp(p, 1, 0);
2940
    } else
2941
    if (strstart(filename, "udp:", &p)) {
2942
        return qemu_chr_open_udp(p);
2943
    } else
2944
    if (strstart(filename, "mon:", &p)) {
2945
        CharDriverState *drv = qemu_chr_open(p);
2946
        if (drv) {
2947
            drv = qemu_chr_open_mux(drv);
2948
            monitor_init(drv, !nographic);
2949
            return drv;
2950
        }
2951
        printf("Unable to open driver: %s\n", p);
2952
        return 0;
2953
    } else
2954
#ifndef _WIN32
2955
    if (strstart(filename, "unix:", &p)) {
2956
        return qemu_chr_open_tcp(p, 0, 1);
2957
    } else if (strstart(filename, "file:", &p)) {
2958
        return qemu_chr_open_file_out(p);
2959
    } else if (strstart(filename, "pipe:", &p)) {
2960
        return qemu_chr_open_pipe(p);
2961
    } else if (!strcmp(filename, "pty")) {
2962
        return qemu_chr_open_pty();
2963
    } else if (!strcmp(filename, "stdio")) {
2964
        return qemu_chr_open_stdio();
2965
    } else 
2966
#if defined(__linux__)
2967
    if (strstart(filename, "/dev/parport", NULL)) {
2968
        return qemu_chr_open_pp(filename);
2969
    } else 
2970
#endif
2971
#if defined(__linux__) || defined(__sun__)
2972
    if (strstart(filename, "/dev/", NULL)) {
2973
        return qemu_chr_open_tty(filename);
2974
    } else
2975
#endif
2976
#else /* !_WIN32 */
2977
    if (strstart(filename, "COM", NULL)) {
2978
        return qemu_chr_open_win(filename);
2979
    } else
2980
    if (strstart(filename, "pipe:", &p)) {
2981
        return qemu_chr_open_win_pipe(p);
2982
    } else
2983
    if (strstart(filename, "con:", NULL)) {
2984
        return qemu_chr_open_win_con(filename);
2985
    } else
2986
    if (strstart(filename, "file:", &p)) {
2987
        return qemu_chr_open_win_file_out(p);
2988
    }
2989
#endif
2990
    {
2991
        return NULL;
2992
    }
2993
}
2994

    
2995
void qemu_chr_close(CharDriverState *chr)
2996
{
2997
    if (chr->chr_close)
2998
        chr->chr_close(chr);
2999
}
3000

    
3001
/***********************************************************/
3002
/* network device redirectors */
3003

    
3004
void hex_dump(FILE *f, const uint8_t *buf, int size)
3005
{
3006
    int len, i, j, c;
3007

    
3008
    for(i=0;i<size;i+=16) {
3009
        len = size - i;
3010
        if (len > 16)
3011
            len = 16;
3012
        fprintf(f, "%08x ", i);
3013
        for(j=0;j<16;j++) {
3014
            if (j < len)
3015
                fprintf(f, " %02x", buf[i+j]);
3016
            else
3017
                fprintf(f, "   ");
3018
        }
3019
        fprintf(f, " ");
3020
        for(j=0;j<len;j++) {
3021
            c = buf[i+j];
3022
            if (c < ' ' || c > '~')
3023
                c = '.';
3024
            fprintf(f, "%c", c);
3025
        }
3026
        fprintf(f, "\n");
3027
    }
3028
}
3029

    
3030
static int parse_macaddr(uint8_t *macaddr, const char *p)
3031
{
3032
    int i;
3033
    for(i = 0; i < 6; i++) {
3034
        macaddr[i] = strtol(p, (char **)&p, 16);
3035
        if (i == 5) {
3036
            if (*p != '\0') 
3037
                return -1;
3038
        } else {
3039
            if (*p != ':') 
3040
                return -1;
3041
            p++;
3042
        }
3043
    }
3044
    return 0;
3045
}
3046

    
3047
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3048
{
3049
    const char *p, *p1;
3050
    int len;
3051
    p = *pp;
3052
    p1 = strchr(p, sep);
3053
    if (!p1)
3054
        return -1;
3055
    len = p1 - p;
3056
    p1++;
3057
    if (buf_size > 0) {
3058
        if (len > buf_size - 1)
3059
            len = buf_size - 1;
3060
        memcpy(buf, p, len);
3061
        buf[len] = '\0';
3062
    }
3063
    *pp = p1;
3064
    return 0;
3065
}
3066

    
3067
int parse_host_src_port(struct sockaddr_in *haddr,
3068
                        struct sockaddr_in *saddr,
3069
                        const char *input_str)
3070
{
3071
    char *str = strdup(input_str);
3072
    char *host_str = str;
3073
    char *src_str;
3074
    char *ptr;
3075

    
3076
    /*
3077
     * Chop off any extra arguments at the end of the string which
3078
     * would start with a comma, then fill in the src port information
3079
     * if it was provided else use the "any address" and "any port".
3080
     */
3081
    if ((ptr = strchr(str,',')))
3082
        *ptr = '\0';
3083

    
3084
    if ((src_str = strchr(input_str,'@'))) {
3085
        *src_str = '\0';
3086
        src_str++;
3087
    }
3088

    
3089
    if (parse_host_port(haddr, host_str) < 0)
3090
        goto fail;
3091

    
3092
    if (!src_str || *src_str == '\0')
3093
        src_str = ":0";
3094

    
3095
    if (parse_host_port(saddr, src_str) < 0)
3096
        goto fail;
3097

    
3098
    free(str);
3099
    return(0);
3100

    
3101
fail:
3102
    free(str);
3103
    return -1;
3104
}
3105

    
3106
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3107
{
3108
    char buf[512];
3109
    struct hostent *he;
3110
    const char *p, *r;
3111
    int port;
3112

    
3113
    p = str;
3114
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3115
        return -1;
3116
    saddr->sin_family = AF_INET;
3117
    if (buf[0] == '\0') {
3118
        saddr->sin_addr.s_addr = 0;
3119
    } else {
3120
        if (isdigit(buf[0])) {
3121
            if (!inet_aton(buf, &saddr->sin_addr))
3122
                return -1;
3123
        } else {
3124
            if ((he = gethostbyname(buf)) == NULL)
3125
                return - 1;
3126
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3127
        }
3128
    }
3129
    port = strtol(p, (char **)&r, 0);
3130
    if (r == p)
3131
        return -1;
3132
    saddr->sin_port = htons(port);
3133
    return 0;
3134
}
3135

    
3136
#ifndef _WIN32
3137
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3138
{
3139
    const char *p;
3140
    int len;
3141

    
3142
    len = MIN(108, strlen(str));
3143
    p = strchr(str, ',');
3144
    if (p)
3145
        len = MIN(len, p - str);
3146

    
3147
    memset(uaddr, 0, sizeof(*uaddr));
3148

    
3149
    uaddr->sun_family = AF_UNIX;
3150
    memcpy(uaddr->sun_path, str, len);
3151

    
3152
    return 0;
3153
}
3154
#endif
3155

    
3156
/* find or alloc a new VLAN */
3157
VLANState *qemu_find_vlan(int id)
3158
{
3159
    VLANState **pvlan, *vlan;
3160
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3161
        if (vlan->id == id)
3162
            return vlan;
3163
    }
3164
    vlan = qemu_mallocz(sizeof(VLANState));
3165
    if (!vlan)
3166
        return NULL;
3167
    vlan->id = id;
3168
    vlan->next = NULL;
3169
    pvlan = &first_vlan;
3170
    while (*pvlan != NULL)
3171
        pvlan = &(*pvlan)->next;
3172
    *pvlan = vlan;
3173
    return vlan;
3174
}
3175

    
3176
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3177
                                      IOReadHandler *fd_read,
3178
                                      IOCanRWHandler *fd_can_read,
3179
                                      void *opaque)
3180
{
3181
    VLANClientState *vc, **pvc;
3182
    vc = qemu_mallocz(sizeof(VLANClientState));
3183
    if (!vc)
3184
        return NULL;
3185
    vc->fd_read = fd_read;
3186
    vc->fd_can_read = fd_can_read;
3187
    vc->opaque = opaque;
3188
    vc->vlan = vlan;
3189

    
3190
    vc->next = NULL;
3191
    pvc = &vlan->first_client;
3192
    while (*pvc != NULL)
3193
        pvc = &(*pvc)->next;
3194
    *pvc = vc;
3195
    return vc;
3196
}
3197

    
3198
int qemu_can_send_packet(VLANClientState *vc1)
3199
{
3200
    VLANState *vlan = vc1->vlan;
3201
    VLANClientState *vc;
3202

    
3203
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3204
        if (vc != vc1) {
3205
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3206
                return 1;
3207
        }
3208
    }
3209
    return 0;
3210
}
3211

    
3212
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3213
{
3214
    VLANState *vlan = vc1->vlan;
3215
    VLANClientState *vc;
3216

    
3217
#if 0
3218
    printf("vlan %d send:\n", vlan->id);
3219
    hex_dump(stdout, buf, size);
3220
#endif
3221
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3222
        if (vc != vc1) {
3223
            vc->fd_read(vc->opaque, buf, size);
3224
        }
3225
    }
3226
}
3227

    
3228
#if defined(CONFIG_SLIRP)
3229

    
3230
/* slirp network adapter */
3231

    
3232
static int slirp_inited;
3233
static VLANClientState *slirp_vc;
3234

    
3235
int slirp_can_output(void)
3236
{
3237
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3238
}
3239

    
3240
void slirp_output(const uint8_t *pkt, int pkt_len)
3241
{
3242
#if 0
3243
    printf("slirp output:\n");
3244
    hex_dump(stdout, pkt, pkt_len);
3245
#endif
3246
    if (!slirp_vc)
3247
        return;
3248
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3249
}
3250

    
3251
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3252
{
3253
#if 0
3254
    printf("slirp input:\n");
3255
    hex_dump(stdout, buf, size);
3256
#endif
3257
    slirp_input(buf, size);
3258
}
3259

    
3260
static int net_slirp_init(VLANState *vlan)
3261
{
3262
    if (!slirp_inited) {
3263
        slirp_inited = 1;
3264
        slirp_init();
3265
    }
3266
    slirp_vc = qemu_new_vlan_client(vlan, 
3267
                                    slirp_receive, NULL, NULL);
3268
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3269
    return 0;
3270
}
3271

    
3272
static void net_slirp_redir(const char *redir_str)
3273
{
3274
    int is_udp;
3275
    char buf[256], *r;
3276
    const char *p;
3277
    struct in_addr guest_addr;
3278
    int host_port, guest_port;
3279
    
3280
    if (!slirp_inited) {
3281
        slirp_inited = 1;
3282
        slirp_init();
3283
    }
3284

    
3285
    p = redir_str;
3286
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3287
        goto fail;
3288
    if (!strcmp(buf, "tcp")) {
3289
        is_udp = 0;
3290
    } else if (!strcmp(buf, "udp")) {
3291
        is_udp = 1;
3292
    } else {
3293
        goto fail;
3294
    }
3295

    
3296
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3297
        goto fail;
3298
    host_port = strtol(buf, &r, 0);
3299
    if (r == buf)
3300
        goto fail;
3301

    
3302
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3303
        goto fail;
3304
    if (buf[0] == '\0') {
3305
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3306
    }
3307
    if (!inet_aton(buf, &guest_addr))
3308
        goto fail;
3309
    
3310
    guest_port = strtol(p, &r, 0);
3311
    if (r == p)
3312
        goto fail;
3313
    
3314
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3315
        fprintf(stderr, "qemu: could not set up redirection\n");
3316
        exit(1);
3317
    }
3318
    return;
3319
 fail:
3320
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3321
    exit(1);
3322
}
3323
    
3324
#ifndef _WIN32
3325

    
3326
char smb_dir[1024];
3327

    
3328
static void smb_exit(void)
3329
{
3330
    DIR *d;
3331
    struct dirent *de;
3332
    char filename[1024];
3333

    
3334
    /* erase all the files in the directory */
3335
    d = opendir(smb_dir);
3336
    for(;;) {
3337
        de = readdir(d);
3338
        if (!de)
3339
            break;
3340
        if (strcmp(de->d_name, ".") != 0 &&
3341
            strcmp(de->d_name, "..") != 0) {
3342
            snprintf(filename, sizeof(filename), "%s/%s", 
3343
                     smb_dir, de->d_name);
3344
            unlink(filename);
3345
        }
3346
    }
3347
    closedir(d);
3348
    rmdir(smb_dir);
3349
}
3350

    
3351
/* automatic user mode samba server configuration */
3352
void net_slirp_smb(const char *exported_dir)
3353
{
3354
    char smb_conf[1024];
3355
    char smb_cmdline[1024];
3356
    FILE *f;
3357

    
3358
    if (!slirp_inited) {
3359
        slirp_inited = 1;
3360
        slirp_init();
3361
    }
3362

    
3363
    /* XXX: better tmp dir construction */
3364
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3365
    if (mkdir(smb_dir, 0700) < 0) {
3366
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3367
        exit(1);
3368
    }
3369
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3370
    
3371
    f = fopen(smb_conf, "w");
3372
    if (!f) {
3373
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3374
        exit(1);
3375
    }
3376
    fprintf(f, 
3377
            "[global]\n"
3378
            "private dir=%s\n"
3379
            "smb ports=0\n"
3380
            "socket address=127.0.0.1\n"
3381
            "pid directory=%s\n"
3382
            "lock directory=%s\n"
3383
            "log file=%s/log.smbd\n"
3384
            "smb passwd file=%s/smbpasswd\n"
3385
            "security = share\n"
3386
            "[qemu]\n"
3387
            "path=%s\n"
3388
            "read only=no\n"
3389
            "guest ok=yes\n",
3390
            smb_dir,
3391
            smb_dir,
3392
            smb_dir,
3393
            smb_dir,
3394
            smb_dir,
3395
            exported_dir
3396
            );
3397
    fclose(f);
3398
    atexit(smb_exit);
3399

    
3400
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3401
             SMBD_COMMAND, smb_conf);
3402
    
3403
    slirp_add_exec(0, smb_cmdline, 4, 139);
3404
}
3405

    
3406
#endif /* !defined(_WIN32) */
3407

    
3408
#endif /* CONFIG_SLIRP */
3409

    
3410
#if !defined(_WIN32)
3411

    
3412
typedef struct TAPState {
3413
    VLANClientState *vc;
3414
    int fd;
3415
} TAPState;
3416

    
3417
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3418
{
3419
    TAPState *s = opaque;
3420
    int ret;
3421
    for(;;) {
3422
        ret = write(s->fd, buf, size);
3423
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3424
        } else {
3425
            break;
3426
        }
3427
    }
3428
}
3429

    
3430
static void tap_send(void *opaque)
3431
{
3432
    TAPState *s = opaque;
3433
    uint8_t buf[4096];
3434
    int size;
3435

    
3436
#ifdef __sun__
3437
    struct strbuf sbuf;
3438
    int f = 0;
3439
    sbuf.maxlen = sizeof(buf);
3440
    sbuf.buf = buf;
3441
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3442
#else
3443
    size = read(s->fd, buf, sizeof(buf));
3444
#endif
3445
    if (size > 0) {
3446
        qemu_send_packet(s->vc, buf, size);
3447
    }
3448
}
3449

    
3450
/* fd support */
3451

    
3452
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3453
{
3454
    TAPState *s;
3455

    
3456
    s = qemu_mallocz(sizeof(TAPState));
3457
    if (!s)
3458
        return NULL;
3459
    s->fd = fd;
3460
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3461
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3462
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3463
    return s;
3464
}
3465

    
3466
#if defined (_BSD) || defined (__FreeBSD_kernel__)
3467
static int tap_open(char *ifname, int ifname_size)
3468
{
3469
    int fd;
3470
    char *dev;
3471
    struct stat s;
3472

    
3473
    TFR(fd = open("/dev/tap", O_RDWR));
3474
    if (fd < 0) {
3475
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3476
        return -1;
3477
    }
3478

    
3479
    fstat(fd, &s);
3480
    dev = devname(s.st_rdev, S_IFCHR);
3481
    pstrcpy(ifname, ifname_size, dev);
3482

    
3483
    fcntl(fd, F_SETFL, O_NONBLOCK);
3484
    return fd;
3485
}
3486
#elif defined(__sun__)
3487
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3488
/* 
3489
 * Allocate TAP device, returns opened fd. 
3490
 * Stores dev name in the first arg(must be large enough).
3491
 */  
3492
int tap_alloc(char *dev)
3493
{
3494
    int tap_fd, if_fd, ppa = -1;
3495
    static int ip_fd = 0;
3496
    char *ptr;
3497

    
3498
    static int arp_fd = 0;
3499
    int ip_muxid, arp_muxid;
3500
    struct strioctl  strioc_if, strioc_ppa;
3501
    int link_type = I_PLINK;;
3502
    struct lifreq ifr;
3503
    char actual_name[32] = "";
3504

    
3505
    memset(&ifr, 0x0, sizeof(ifr));
3506

    
3507
    if( *dev ){
3508
       ptr = dev;        
3509
       while( *ptr && !isdigit((int)*ptr) ) ptr++; 
3510
       ppa = atoi(ptr);
3511
    }
3512

    
3513
    /* Check if IP device was opened */
3514
    if( ip_fd )
3515
       close(ip_fd);
3516

    
3517
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3518
    if (ip_fd < 0) {
3519
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3520
       return -1;
3521
    }
3522

    
3523
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3524
    if (tap_fd < 0) {
3525
       syslog(LOG_ERR, "Can't open /dev/tap");
3526
       return -1;
3527
    }
3528

    
3529
    /* Assign a new PPA and get its unit number. */
3530
    strioc_ppa.ic_cmd = TUNNEWPPA;
3531
    strioc_ppa.ic_timout = 0;
3532
    strioc_ppa.ic_len = sizeof(ppa);
3533
    strioc_ppa.ic_dp = (char *)&ppa;
3534
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3535
       syslog (LOG_ERR, "Can't assign new interface");
3536

    
3537
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3538
    if (if_fd < 0) {
3539
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3540
       return -1;
3541
    }
3542
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3543
       syslog(LOG_ERR, "Can't push IP module");
3544
       return -1;
3545
    }
3546

    
3547
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3548
        syslog(LOG_ERR, "Can't get flags\n");
3549

    
3550
    snprintf (actual_name, 32, "tap%d", ppa);
3551
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3552

    
3553
    ifr.lifr_ppa = ppa;
3554
    /* Assign ppa according to the unit number returned by tun device */
3555

    
3556
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3557
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
3558
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3559
        syslog (LOG_ERR, "Can't get flags\n");
3560
    /* Push arp module to if_fd */
3561
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
3562
        syslog (LOG_ERR, "Can't push ARP module (2)");
3563

    
3564
    /* Push arp module to ip_fd */
3565
    if (ioctl (ip_fd, I_POP, NULL) < 0)
3566
        syslog (LOG_ERR, "I_POP failed\n");
3567
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3568
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
3569
    /* Open arp_fd */
3570
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3571
    if (arp_fd < 0)
3572
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3573

    
3574
    /* Set ifname to arp */
3575
    strioc_if.ic_cmd = SIOCSLIFNAME;
3576
    strioc_if.ic_timout = 0;
3577
    strioc_if.ic_len = sizeof(ifr);
3578
    strioc_if.ic_dp = (char *)&ifr;
3579
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3580
        syslog (LOG_ERR, "Can't set ifname to arp\n");
3581
    }
3582

    
3583
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3584
       syslog(LOG_ERR, "Can't link TAP device to IP");
3585
       return -1;
3586
    }
3587

    
3588
    if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3589
        syslog (LOG_ERR, "Can't link TAP device to ARP");
3590

    
3591
    close (if_fd);
3592

    
3593
    memset(&ifr, 0x0, sizeof(ifr));
3594
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3595
    ifr.lifr_ip_muxid  = ip_muxid;
3596
    ifr.lifr_arp_muxid = arp_muxid;
3597

    
3598
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3599
    {
3600
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
3601
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
3602
      syslog (LOG_ERR, "Can't set multiplexor id");
3603
    }
3604

    
3605
    sprintf(dev, "tap%d", ppa);
3606
    return tap_fd;
3607
}
3608

    
3609
static int tap_open(char *ifname, int ifname_size)
3610
{
3611
    char  dev[10]="";
3612
    int fd;
3613
    if( (fd = tap_alloc(dev)) < 0 ){
3614
       fprintf(stderr, "Cannot allocate TAP device\n");
3615
       return -1;
3616
    }
3617
    pstrcpy(ifname, ifname_size, dev);
3618
    fcntl(fd, F_SETFL, O_NONBLOCK);
3619
    return fd;
3620
}
3621
#else
3622
static int tap_open(char *ifname, int ifname_size)
3623
{
3624
    struct ifreq ifr;
3625
    int fd, ret;
3626
    
3627
    TFR(fd = open("/dev/net/tun", O_RDWR));
3628
    if (fd < 0) {
3629
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3630
        return -1;
3631
    }
3632
    memset(&ifr, 0, sizeof(ifr));
3633
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3634
    if (ifname[0] != '\0')
3635
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3636
    else
3637
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3638
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3639
    if (ret != 0) {
3640
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3641
        close(fd);
3642
        return -1;
3643
    }
3644
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3645
    fcntl(fd, F_SETFL, O_NONBLOCK);
3646
    return fd;
3647
}
3648
#endif
3649

    
3650
static int net_tap_init(VLANState *vlan, const char *ifname1,
3651
                        const char *setup_script)
3652
{
3653
    TAPState *s;
3654
    int pid, status, fd;
3655
    char *args[3];
3656
    char **parg;
3657
    char ifname[128];
3658

    
3659
    if (ifname1 != NULL)
3660
        pstrcpy(ifname, sizeof(ifname), ifname1);
3661
    else
3662
        ifname[0] = '\0';
3663
    TFR(fd = tap_open(ifname, sizeof(ifname)));
3664
    if (fd < 0)
3665
        return -1;
3666

    
3667
    if (!setup_script || !strcmp(setup_script, "no"))
3668
        setup_script = "";
3669
    if (setup_script[0] != '\0') {
3670
        /* try to launch network init script */
3671
        pid = fork();
3672
        if (pid >= 0) {
3673
            if (pid == 0) {
3674
                int open_max = sysconf (_SC_OPEN_MAX), i;
3675
                for (i = 0; i < open_max; i++)
3676
                    if (i != STDIN_FILENO &&
3677
                        i != STDOUT_FILENO &&
3678
                        i != STDERR_FILENO &&
3679
                        i != fd)
3680
                        close(i);
3681

    
3682
                parg = args;
3683
                *parg++ = (char *)setup_script;
3684
                *parg++ = ifname;
3685
                *parg++ = NULL;
3686
                execv(setup_script, args);
3687
                _exit(1);
3688
            }
3689
            while (waitpid(pid, &status, 0) != pid);
3690
            if (!WIFEXITED(status) ||
3691
                WEXITSTATUS(status) != 0) {
3692
                fprintf(stderr, "%s: could not launch network script\n",
3693
                        setup_script);
3694
                return -1;
3695
            }
3696
        }
3697
    }
3698
    s = net_tap_fd_init(vlan, fd);
3699
    if (!s)
3700
        return -1;
3701
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3702
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3703
    return 0;
3704
}
3705

    
3706
#endif /* !_WIN32 */
3707

    
3708
/* network connection */
3709
typedef struct NetSocketState {
3710
    VLANClientState *vc;
3711
    int fd;
3712
    int state; /* 0 = getting length, 1 = getting data */
3713
    int index;
3714
    int packet_len;
3715
    uint8_t buf[4096];
3716
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3717
} NetSocketState;
3718

    
3719
typedef struct NetSocketListenState {
3720
    VLANState *vlan;
3721
    int fd;
3722
} NetSocketListenState;
3723

    
3724
/* XXX: we consider we can send the whole packet without blocking */
3725
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3726
{
3727
    NetSocketState *s = opaque;
3728
    uint32_t len;
3729
    len = htonl(size);
3730

    
3731
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3732
    send_all(s->fd, buf, size);
3733
}
3734

    
3735
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3736
{
3737
    NetSocketState *s = opaque;
3738
    sendto(s->fd, buf, size, 0, 
3739
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3740
}
3741

    
3742
static void net_socket_send(void *opaque)
3743
{
3744
    NetSocketState *s = opaque;
3745
    int l, size, err;
3746
    uint8_t buf1[4096];
3747
    const uint8_t *buf;
3748

    
3749
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3750
    if (size < 0) {
3751
        err = socket_error();
3752
        if (err != EWOULDBLOCK) 
3753
            goto eoc;
3754
    } else if (size == 0) {
3755
        /* end of connection */
3756
    eoc:
3757
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3758
        closesocket(s->fd);
3759
        return;
3760
    }
3761
    buf = buf1;
3762
    while (size > 0) {
3763
        /* reassemble a packet from the network */
3764
        switch(s->state) {
3765
        case 0:
3766
            l = 4 - s->index;
3767
            if (l > size)
3768
                l = size;
3769
            memcpy(s->buf + s->index, buf, l);
3770
            buf += l;
3771
            size -= l;
3772
            s->index += l;
3773
            if (s->index == 4) {
3774
                /* got length */
3775
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3776
                s->index = 0;
3777
                s->state = 1;
3778
            }
3779
            break;
3780
        case 1:
3781
            l = s->packet_len - s->index;
3782
            if (l > size)
3783
                l = size;
3784
            memcpy(s->buf + s->index, buf, l);
3785
            s->index += l;
3786
            buf += l;
3787
            size -= l;
3788
            if (s->index >= s->packet_len) {
3789
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3790
                s->index = 0;
3791
                s->state = 0;
3792
            }
3793
            break;
3794
        }
3795
    }
3796
}
3797

    
3798
static void net_socket_send_dgram(void *opaque)
3799
{
3800
    NetSocketState *s = opaque;
3801
    int size;
3802

    
3803
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3804
    if (size < 0) 
3805
        return;
3806
    if (size == 0) {
3807
        /* end of connection */
3808
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3809
        return;
3810
    }
3811
    qemu_send_packet(s->vc, s->buf, size);
3812
}
3813

    
3814
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3815
{
3816
    struct ip_mreq imr;
3817
    int fd;
3818
    int val, ret;
3819
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3820
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3821
                inet_ntoa(mcastaddr->sin_addr), 
3822
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3823
        return -1;
3824

    
3825
    }
3826
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3827
    if (fd < 0) {
3828
        perror("socket(PF_INET, SOCK_DGRAM)");
3829
        return -1;
3830
    }
3831

    
3832
    val = 1;
3833
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3834
                   (const char *)&val, sizeof(val));
3835
    if (ret < 0) {
3836
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3837
        goto fail;
3838
    }
3839

    
3840
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3841
    if (ret < 0) {
3842
        perror("bind");
3843
        goto fail;
3844
    }
3845
    
3846
    /* Add host to multicast group */
3847
    imr.imr_multiaddr = mcastaddr->sin_addr;
3848
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3849

    
3850
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3851
                     (const char *)&imr, sizeof(struct ip_mreq));
3852
    if (ret < 0) {
3853
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3854
        goto fail;
3855
    }
3856

    
3857
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3858
    val = 1;
3859
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3860
                   (const char *)&val, sizeof(val));
3861
    if (ret < 0) {
3862
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3863
        goto fail;
3864
    }
3865

    
3866
    socket_set_nonblock(fd);
3867
    return fd;
3868
fail:
3869
    if (fd >= 0) 
3870
        closesocket(fd);
3871
    return -1;
3872
}
3873

    
3874
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3875
                                          int is_connected)
3876
{
3877
    struct sockaddr_in saddr;
3878
    int newfd;
3879
    socklen_t saddr_len;
3880
    NetSocketState *s;
3881

    
3882
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3883
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3884
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3885
     */
3886

    
3887
    if (is_connected) {
3888
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3889
            /* must be bound */
3890
            if (saddr.sin_addr.s_addr==0) {
3891
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3892
                        fd);
3893
                return NULL;
3894
            }
3895
            /* clone dgram socket */
3896
            newfd = net_socket_mcast_create(&saddr);
3897
            if (newfd < 0) {
3898
                /* error already reported by net_socket_mcast_create() */
3899
                close(fd);
3900
                return NULL;
3901
            }
3902
            /* clone newfd to fd, close newfd */
3903
            dup2(newfd, fd);
3904
            close(newfd);
3905
        
3906
        } else {
3907
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3908
                    fd, strerror(errno));
3909
            return NULL;
3910
        }
3911
    }
3912

    
3913
    s = qemu_mallocz(sizeof(NetSocketState));
3914
    if (!s)
3915
        return NULL;
3916
    s->fd = fd;
3917

    
3918
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3919
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3920

    
3921
    /* mcast: save bound address as dst */
3922
    if (is_connected) s->dgram_dst=saddr;
3923

    
3924
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3925
            "socket: fd=%d (%s mcast=%s:%d)", 
3926
            fd, is_connected? "cloned" : "",
3927
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3928
    return s;
3929
}
3930

    
3931
static void net_socket_connect(void *opaque)
3932
{
3933
    NetSocketState *s = opaque;
3934
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3935
}
3936

    
3937
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3938
                                          int is_connected)
3939
{
3940
    NetSocketState *s;
3941
    s = qemu_mallocz(sizeof(NetSocketState));
3942
    if (!s)
3943
        return NULL;
3944
    s->fd = fd;
3945
    s->vc = qemu_new_vlan_client(vlan, 
3946
                                 net_socket_receive, NULL, s);
3947
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3948
             "socket: fd=%d", fd);
3949
    if (is_connected) {
3950
        net_socket_connect(s);
3951
    } else {
3952
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3953
    }
3954
    return s;
3955
}
3956

    
3957
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3958
                                          int is_connected)
3959
{
3960
    int so_type=-1, optlen=sizeof(so_type);
3961

    
3962
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3963
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3964
        return NULL;
3965
    }
3966
    switch(so_type) {
3967
    case SOCK_DGRAM:
3968
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3969
    case SOCK_STREAM:
3970
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3971
    default:
3972
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3973
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3974
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3975
    }
3976
    return NULL;
3977
}
3978

    
3979
static void net_socket_accept(void *opaque)
3980
{
3981
    NetSocketListenState *s = opaque;    
3982
    NetSocketState *s1;
3983
    struct sockaddr_in saddr;
3984
    socklen_t len;
3985
    int fd;
3986

    
3987
    for(;;) {
3988
        len = sizeof(saddr);
3989
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3990
        if (fd < 0 && errno != EINTR) {
3991
            return;
3992
        } else if (fd >= 0) {
3993
            break;
3994
        }
3995
    }
3996
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3997
    if (!s1) {
3998
        closesocket(fd);
3999
    } else {
4000
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4001
                 "socket: connection from %s:%d", 
4002
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4003
    }
4004
}
4005

    
4006
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4007
{
4008
    NetSocketListenState *s;
4009
    int fd, val, ret;
4010
    struct sockaddr_in saddr;
4011

    
4012
    if (parse_host_port(&saddr, host_str) < 0)
4013
        return -1;
4014
    
4015
    s = qemu_mallocz(sizeof(NetSocketListenState));
4016
    if (!s)
4017
        return -1;
4018

    
4019
    fd = socket(PF_INET, SOCK_STREAM, 0);
4020
    if (fd < 0) {
4021
        perror("socket");
4022
        return -1;
4023
    }
4024
    socket_set_nonblock(fd);
4025

    
4026
    /* allow fast reuse */
4027
    val = 1;
4028
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4029
    
4030
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4031
    if (ret < 0) {
4032
        perror("bind");
4033
        return -1;
4034
    }
4035
    ret = listen(fd, 0);
4036
    if (ret < 0) {
4037
        perror("listen");
4038
        return -1;
4039
    }
4040
    s->vlan = vlan;
4041
    s->fd = fd;
4042
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4043
    return 0;
4044
}
4045

    
4046
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4047
{
4048
    NetSocketState *s;
4049
    int fd, connected, ret, err;
4050
    struct sockaddr_in saddr;
4051

    
4052
    if (parse_host_port(&saddr, host_str) < 0)
4053
        return -1;
4054

    
4055
    fd = socket(PF_INET, SOCK_STREAM, 0);
4056
    if (fd < 0) {
4057
        perror("socket");
4058
        return -1;
4059
    }
4060
    socket_set_nonblock(fd);
4061

    
4062
    connected = 0;
4063
    for(;;) {
4064
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4065
        if (ret < 0) {
4066
            err = socket_error();
4067
            if (err == EINTR || err == EWOULDBLOCK) {
4068
            } else if (err == EINPROGRESS) {
4069
                break;
4070
#ifdef _WIN32
4071
            } else if (err == WSAEALREADY) {
4072
                break;
4073
#endif
4074
            } else {
4075
                perror("connect");
4076
                closesocket(fd);
4077
                return -1;
4078
            }
4079
        } else {
4080
            connected = 1;
4081
            break;
4082
        }
4083
    }
4084
    s = net_socket_fd_init(vlan, fd, connected);
4085
    if (!s)
4086
        return -1;
4087
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4088
             "socket: connect to %s:%d", 
4089
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4090
    return 0;
4091
}
4092

    
4093
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4094
{
4095
    NetSocketState *s;
4096
    int fd;
4097
    struct sockaddr_in saddr;
4098

    
4099
    if (parse_host_port(&saddr, host_str) < 0)
4100
        return -1;
4101

    
4102

    
4103
    fd = net_socket_mcast_create(&saddr);
4104
    if (fd < 0)
4105
        return -1;
4106

    
4107
    s = net_socket_fd_init(vlan, fd, 0);
4108
    if (!s)
4109
        return -1;
4110

    
4111
    s->dgram_dst = saddr;
4112
    
4113
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4114
             "socket: mcast=%s:%d", 
4115
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4116
    return 0;
4117

    
4118
}
4119

    
4120
static int get_param_value(char *buf, int buf_size,
4121
                           const char *tag, const char *str)
4122
{
4123
    const char *p;
4124
    char *q;
4125
    char option[128];
4126

    
4127
    p = str;
4128
    for(;;) {
4129
        q = option;
4130
        while (*p != '\0' && *p != '=') {
4131
            if ((q - option) < sizeof(option) - 1)
4132
                *q++ = *p;
4133
            p++;
4134
        }
4135
        *q = '\0';
4136
        if (*p != '=')
4137
            break;
4138
        p++;
4139
        if (!strcmp(tag, option)) {
4140
            q = buf;
4141
            while (*p != '\0' && *p != ',') {
4142
                if ((q - buf) < buf_size - 1)
4143
                    *q++ = *p;
4144
                p++;
4145
            }
4146
            *q = '\0';
4147
            return q - buf;
4148
        } else {
4149
            while (*p != '\0' && *p != ',') {
4150
                p++;
4151
            }
4152
        }
4153
        if (*p != ',')
4154
            break;
4155
        p++;
4156
    }
4157
    return 0;
4158
}
4159

    
4160
static int net_client_init(const char *str)
4161
{
4162
    const char *p;
4163
    char *q;
4164
    char device[64];
4165
    char buf[1024];
4166
    int vlan_id, ret;
4167
    VLANState *vlan;
4168

    
4169
    p = str;
4170
    q = device;
4171
    while (*p != '\0' && *p != ',') {
4172
        if ((q - device) < sizeof(device) - 1)
4173
            *q++ = *p;
4174
        p++;
4175
    }
4176
    *q = '\0';
4177
    if (*p == ',')
4178
        p++;
4179
    vlan_id = 0;
4180
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4181
        vlan_id = strtol(buf, NULL, 0);
4182
    }
4183
    vlan = qemu_find_vlan(vlan_id);
4184
    if (!vlan) {
4185
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4186
        return -1;
4187
    }
4188
    if (!strcmp(device, "nic")) {
4189
        NICInfo *nd;
4190
        uint8_t *macaddr;
4191

    
4192
        if (nb_nics >= MAX_NICS) {
4193
            fprintf(stderr, "Too Many NICs\n");
4194
            return -1;
4195
        }
4196
        nd = &nd_table[nb_nics];
4197
        macaddr = nd->macaddr;
4198
        macaddr[0] = 0x52;
4199
        macaddr[1] = 0x54;
4200
        macaddr[2] = 0x00;
4201
        macaddr[3] = 0x12;
4202
        macaddr[4] = 0x34;
4203
        macaddr[5] = 0x56 + nb_nics;
4204

    
4205
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4206
            if (parse_macaddr(macaddr, buf) < 0) {
4207
                fprintf(stderr, "invalid syntax for ethernet address\n");
4208
                return -1;
4209
            }
4210
        }
4211
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4212
            nd->model = strdup(buf);
4213
        }
4214
        nd->vlan = vlan;
4215
        nb_nics++;
4216
        vlan->nb_guest_devs++;
4217
        ret = 0;
4218
    } else
4219
    if (!strcmp(device, "none")) {
4220
        /* does nothing. It is needed to signal that no network cards
4221
           are wanted */
4222
        ret = 0;
4223
    } else
4224
#ifdef CONFIG_SLIRP
4225
    if (!strcmp(device, "user")) {
4226
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4227
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4228
        }
4229
        vlan->nb_host_devs++;
4230
        ret = net_slirp_init(vlan);
4231
    } else
4232
#endif
4233
#ifdef _WIN32
4234
    if (!strcmp(device, "tap")) {
4235
        char ifname[64];
4236
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4237
            fprintf(stderr, "tap: no interface name\n");
4238
            return -1;
4239
        }
4240
        vlan->nb_host_devs++;
4241
        ret = tap_win32_init(vlan, ifname);
4242
    } else
4243
#else
4244
    if (!strcmp(device, "tap")) {
4245
        char ifname[64];
4246
        char setup_script[1024];
4247
        int fd;
4248
        vlan->nb_host_devs++;
4249
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4250
            fd = strtol(buf, NULL, 0);
4251
            ret = -1;
4252
            if (net_tap_fd_init(vlan, fd))
4253
                ret = 0;
4254
        } else {
4255
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4256
                ifname[0] = '\0';
4257
            }
4258
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4259
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4260
            }
4261
            ret = net_tap_init(vlan, ifname, setup_script);
4262
        }
4263
    } else
4264
#endif
4265
    if (!strcmp(device, "socket")) {
4266
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4267
            int fd;
4268
            fd = strtol(buf, NULL, 0);
4269
            ret = -1;
4270
            if (net_socket_fd_init(vlan, fd, 1))
4271
                ret = 0;
4272
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4273
            ret = net_socket_listen_init(vlan, buf);
4274
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4275
            ret = net_socket_connect_init(vlan, buf);
4276
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4277
            ret = net_socket_mcast_init(vlan, buf);
4278
        } else {
4279
            fprintf(stderr, "Unknown socket options: %s\n", p);
4280
            return -1;
4281
        }
4282
        vlan->nb_host_devs++;
4283
    } else
4284
    {
4285
        fprintf(stderr, "Unknown network device: %s\n", device);
4286
        return -1;
4287
    }
4288
    if (ret < 0) {
4289
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4290
    }
4291
    
4292
    return ret;
4293
}
4294

    
4295
void do_info_network(void)
4296
{
4297
    VLANState *vlan;
4298
    VLANClientState *vc;
4299

    
4300
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4301
        term_printf("VLAN %d devices:\n", vlan->id);
4302
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4303
            term_printf("  %s\n", vc->info_str);
4304
    }
4305
}
4306

    
4307
/***********************************************************/
4308
/* USB devices */
4309

    
4310
static USBPort *used_usb_ports;
4311
static USBPort *free_usb_ports;
4312

    
4313
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4314
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4315
                            usb_attachfn attach)
4316
{
4317
    port->opaque = opaque;
4318
    port->index = index;
4319
    port->attach = attach;
4320
    port->next = free_usb_ports;
4321
    free_usb_ports = port;
4322
}
4323

    
4324
static int usb_device_add(const char *devname)
4325
{
4326
    const char *p;
4327
    USBDevice *dev;
4328
    USBPort *port;
4329

    
4330
    if (!free_usb_ports)
4331
        return -1;
4332

    
4333
    if (strstart(devname, "host:", &p)) {
4334
        dev = usb_host_device_open(p);
4335
    } else if (!strcmp(devname, "mouse")) {
4336
        dev = usb_mouse_init();
4337
    } else if (!strcmp(devname, "tablet")) {
4338
        dev = usb_tablet_init();
4339
    } else if (!strcmp(devname, "keyboard")) {
4340
        dev = usb_keyboard_init();
4341
    } else if (strstart(devname, "disk:", &p)) {
4342
        dev = usb_msd_init(p);
4343
    } else if (!strcmp(devname, "wacom-tablet")) {
4344
        dev = usb_wacom_init();
4345
    } else {
4346
        return -1;
4347
    }
4348
    if (!dev)
4349
        return -1;
4350

    
4351
    /* Find a USB port to add the device to.  */
4352
    port = free_usb_ports;
4353
    if (!port->next) {
4354
        USBDevice *hub;
4355

    
4356
        /* Create a new hub and chain it on.  */
4357
        free_usb_ports = NULL;
4358
        port->next = used_usb_ports;
4359
        used_usb_ports = port;
4360

    
4361
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4362
        usb_attach(port, hub);
4363
        port = free_usb_ports;
4364
    }
4365

    
4366
    free_usb_ports = port->next;
4367
    port->next = used_usb_ports;
4368
    used_usb_ports = port;
4369
    usb_attach(port, dev);
4370
    return 0;
4371
}
4372

    
4373
static int usb_device_del(const char *devname)
4374
{
4375
    USBPort *port;
4376
    USBPort **lastp;
4377
    USBDevice *dev;
4378
    int bus_num, addr;
4379
    const char *p;
4380

    
4381
    if (!used_usb_ports)
4382
        return -1;
4383

    
4384
    p = strchr(devname, '.');
4385
    if (!p) 
4386
        return -1;
4387
    bus_num = strtoul(devname, NULL, 0);
4388
    addr = strtoul(p + 1, NULL, 0);
4389
    if (bus_num != 0)
4390
        return -1;
4391

    
4392
    lastp = &used_usb_ports;
4393
    port = used_usb_ports;
4394
    while (port && port->dev->addr != addr) {
4395
        lastp = &port->next;
4396
        port = port->next;
4397
    }
4398

    
4399
    if (!port)
4400
        return -1;
4401

    
4402
    dev = port->dev;
4403
    *lastp = port->next;
4404
    usb_attach(port, NULL);
4405
    dev->handle_destroy(dev);
4406
    port->next = free_usb_ports;
4407
    free_usb_ports = port;
4408
    return 0;
4409
}
4410

    
4411
void do_usb_add(const char *devname)
4412
{
4413
    int ret;
4414
    ret = usb_device_add(devname);
4415
    if (ret < 0) 
4416
        term_printf("Could not add USB device '%s'\n", devname);
4417
}
4418

    
4419
void do_usb_del(const char *devname)
4420
{
4421
    int ret;
4422
    ret = usb_device_del(devname);
4423
    if (ret < 0) 
4424
        term_printf("Could not remove USB device '%s'\n", devname);
4425
}
4426

    
4427
void usb_info(void)
4428
{
4429
    USBDevice *dev;
4430
    USBPort *port;
4431
    const char *speed_str;
4432

    
4433
    if (!usb_enabled) {
4434
        term_printf("USB support not enabled\n");
4435
        return;
4436
    }
4437

    
4438
    for (port = used_usb_ports; port; port = port->next) {
4439
        dev = port->dev;
4440
        if (!dev)
4441
            continue;
4442
        switch(dev->speed) {
4443
        case USB_SPEED_LOW: 
4444
            speed_str = "1.5"; 
4445
            break;
4446
        case USB_SPEED_FULL: 
4447
            speed_str = "12"; 
4448
            break;
4449
        case USB_SPEED_HIGH: 
4450
            speed_str = "480"; 
4451
            break;
4452
        default:
4453
            speed_str = "?"; 
4454
            break;
4455
        }
4456
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4457
                    0, dev->addr, speed_str, dev->devname);
4458
    }
4459
}
4460

    
4461
/***********************************************************/
4462
/* PCMCIA/Cardbus */
4463

    
4464
static struct pcmcia_socket_entry_s {
4465
    struct pcmcia_socket_s *socket;
4466
    struct pcmcia_socket_entry_s *next;
4467
} *pcmcia_sockets = 0;
4468

    
4469
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4470
{
4471
    struct pcmcia_socket_entry_s *entry;
4472

    
4473
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4474
    entry->socket = socket;
4475
    entry->next = pcmcia_sockets;
4476
    pcmcia_sockets = entry;
4477
}
4478

    
4479
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4480
{
4481
    struct pcmcia_socket_entry_s *entry, **ptr;
4482

    
4483
    ptr = &pcmcia_sockets;
4484
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4485
        if (entry->socket == socket) {
4486
            *ptr = entry->next;
4487
            qemu_free(entry);
4488
        }
4489
}
4490

    
4491
void pcmcia_info(void)
4492
{
4493
    struct pcmcia_socket_entry_s *iter;
4494
    if (!pcmcia_sockets)
4495
        term_printf("No PCMCIA sockets\n");
4496

    
4497
    for (iter = pcmcia_sockets; iter; iter = iter->next)
4498
        term_printf("%s: %s\n", iter->socket->slot_string,
4499
                    iter->socket->attached ? iter->socket->card_string :
4500
                    "Empty");
4501
}
4502

    
4503
/***********************************************************/
4504
/* dumb display */
4505

    
4506
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4507
{
4508
}
4509

    
4510
static void dumb_resize(DisplayState *ds, int w, int h)
4511
{
4512
}
4513

    
4514
static void dumb_refresh(DisplayState *ds)
4515
{
4516
#if defined(CONFIG_SDL)
4517
    vga_hw_update();
4518
#endif
4519
}
4520

    
4521
static void dumb_display_init(DisplayState *ds)
4522
{
4523
    ds->data = NULL;
4524
    ds->linesize = 0;
4525
    ds->depth = 0;
4526
    ds->dpy_update = dumb_update;
4527
    ds->dpy_resize = dumb_resize;
4528
    ds->dpy_refresh = dumb_refresh;
4529
}
4530

    
4531
/***********************************************************/
4532
/* I/O handling */
4533

    
4534
#define MAX_IO_HANDLERS 64
4535

    
4536
typedef struct IOHandlerRecord {
4537
    int fd;
4538
    IOCanRWHandler *fd_read_poll;
4539
    IOHandler *fd_read;
4540
    IOHandler *fd_write;
4541
    int deleted;
4542
    void *opaque;
4543
    /* temporary data */
4544
    struct pollfd *ufd;
4545
    struct IOHandlerRecord *next;
4546
} IOHandlerRecord;
4547

    
4548
static IOHandlerRecord *first_io_handler;
4549

    
4550
/* XXX: fd_read_poll should be suppressed, but an API change is
4551
   necessary in the character devices to suppress fd_can_read(). */
4552
int qemu_set_fd_handler2(int fd, 
4553
                         IOCanRWHandler *fd_read_poll, 
4554
                         IOHandler *fd_read, 
4555
                         IOHandler *fd_write, 
4556
                         void *opaque)
4557
{
4558
    IOHandlerRecord **pioh, *ioh;
4559

    
4560
    if (!fd_read && !fd_write) {
4561
        pioh = &first_io_handler;
4562
        for(;;) {
4563
            ioh = *pioh;
4564
            if (ioh == NULL)
4565
                break;
4566
            if (ioh->fd == fd) {
4567
                ioh->deleted = 1;
4568
                break;
4569
            }
4570
            pioh = &ioh->next;
4571
        }
4572
    } else {
4573
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4574
            if (ioh->fd == fd)
4575
                goto found;
4576
        }
4577
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4578
        if (!ioh)
4579
            return -1;
4580
        ioh->next = first_io_handler;
4581
        first_io_handler = ioh;
4582
    found:
4583
        ioh->fd = fd;
4584
        ioh->fd_read_poll = fd_read_poll;
4585
        ioh->fd_read = fd_read;
4586
        ioh->fd_write = fd_write;
4587
        ioh->opaque = opaque;
4588
        ioh->deleted = 0;
4589
    }
4590
    return 0;
4591
}
4592

    
4593
int qemu_set_fd_handler(int fd, 
4594
                        IOHandler *fd_read, 
4595
                        IOHandler *fd_write, 
4596
                        void *opaque)
4597
{
4598
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4599
}
4600

    
4601
/***********************************************************/
4602
/* Polling handling */
4603

    
4604
typedef struct PollingEntry {
4605
    PollingFunc *func;
4606
    void *opaque;
4607
    struct PollingEntry *next;
4608
} PollingEntry;
4609

    
4610
static PollingEntry *first_polling_entry;
4611

    
4612
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4613
{
4614
    PollingEntry **ppe, *pe;
4615
    pe = qemu_mallocz(sizeof(PollingEntry));
4616
    if (!pe)
4617
        return -1;
4618
    pe->func = func;
4619
    pe->opaque = opaque;
4620
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4621
    *ppe = pe;
4622
    return 0;
4623
}
4624

    
4625
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4626
{
4627
    PollingEntry **ppe, *pe;
4628
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4629
        pe = *ppe;
4630
        if (pe->func == func && pe->opaque == opaque) {
4631
            *ppe = pe->next;
4632
            qemu_free(pe);
4633
            break;
4634
        }
4635
    }
4636
}
4637

    
4638
#ifdef _WIN32
4639
/***********************************************************/
4640
/* Wait objects support */
4641
typedef struct WaitObjects {
4642
    int num;
4643
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4644
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4645
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4646
} WaitObjects;
4647

    
4648
static WaitObjects wait_objects = {0};
4649
    
4650
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4651
{
4652
    WaitObjects *w = &wait_objects;
4653

    
4654
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4655
        return -1;
4656
    w->events[w->num] = handle;
4657
    w->func[w->num] = func;
4658
    w->opaque[w->num] = opaque;
4659
    w->num++;
4660
    return 0;
4661
}
4662

    
4663
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4664
{
4665
    int i, found;
4666
    WaitObjects *w = &wait_objects;
4667

    
4668
    found = 0;
4669
    for (i = 0; i < w->num; i++) {
4670
        if (w->events[i] == handle)
4671
            found = 1;
4672
        if (found) {
4673
            w->events[i] = w->events[i + 1];
4674
            w->func[i] = w->func[i + 1];
4675
            w->opaque[i] = w->opaque[i + 1];
4676
        }            
4677
    }
4678
    if (found)
4679
        w->num--;
4680
}
4681
#endif
4682

    
4683
/***********************************************************/
4684
/* savevm/loadvm support */
4685

    
4686
#define IO_BUF_SIZE 32768
4687

    
4688
struct QEMUFile {
4689
    FILE *outfile;
4690
    BlockDriverState *bs;
4691
    int is_file;
4692
    int is_writable;
4693
    int64_t base_offset;
4694
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4695
                           when reading */
4696
    int buf_index;
4697
    int buf_size; /* 0 when writing */
4698
    uint8_t buf[IO_BUF_SIZE];
4699
};
4700

    
4701
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4702
{
4703
    QEMUFile *f;
4704

    
4705
    f = qemu_mallocz(sizeof(QEMUFile));
4706
    if (!f)
4707
        return NULL;
4708
    if (!strcmp(mode, "wb")) {
4709
        f->is_writable = 1;
4710
    } else if (!strcmp(mode, "rb")) {
4711
        f->is_writable = 0;
4712
    } else {
4713
        goto fail;
4714
    }
4715
    f->outfile = fopen(filename, mode);
4716
    if (!f->outfile)
4717
        goto fail;
4718
    f->is_file = 1;
4719
    return f;
4720
 fail:
4721
    if (f->outfile)
4722
        fclose(f->outfile);
4723
    qemu_free(f);
4724
    return NULL;
4725
}
4726

    
4727
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4728
{
4729
    QEMUFile *f;
4730

    
4731
    f = qemu_mallocz(sizeof(QEMUFile));
4732
    if (!f)
4733
        return NULL;
4734
    f->is_file = 0;
4735
    f->bs = bs;
4736
    f->is_writable = is_writable;
4737
    f->base_offset = offset;
4738
    return f;
4739
}
4740

    
4741
void qemu_fflush(QEMUFile *f)
4742
{
4743
    if (!f->is_writable)
4744
        return;
4745
    if (f->buf_index > 0) {
4746
        if (f->is_file) {
4747
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4748
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4749
        } else {
4750
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4751
                        f->buf, f->buf_index);
4752
        }
4753
        f->buf_offset += f->buf_index;
4754
        f->buf_index = 0;
4755
    }
4756
}
4757

    
4758
static void qemu_fill_buffer(QEMUFile *f)
4759
{
4760
    int len;
4761

    
4762
    if (f->is_writable)
4763
        return;
4764
    if (f->is_file) {
4765
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4766
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4767
        if (len < 0)
4768
            len = 0;
4769
    } else {
4770
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4771
                         f->buf, IO_BUF_SIZE);
4772
        if (len < 0)
4773
            len = 0;
4774
    }
4775
    f->buf_index = 0;
4776
    f->buf_size = len;
4777
    f->buf_offset += len;
4778
}
4779

    
4780
void qemu_fclose(QEMUFile *f)
4781
{
4782
    if (f->is_writable)
4783
        qemu_fflush(f);
4784
    if (f->is_file) {
4785
        fclose(f->outfile);
4786
    }
4787
    qemu_free(f);
4788
}
4789

    
4790
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4791
{
4792
    int l;
4793
    while (size > 0) {
4794
        l = IO_BUF_SIZE - f->buf_index;
4795
        if (l > size)
4796
            l = size;
4797
        memcpy(f->buf + f->buf_index, buf, l);
4798
        f->buf_index += l;
4799
        buf += l;
4800
        size -= l;
4801
        if (f->buf_index >= IO_BUF_SIZE)
4802
            qemu_fflush(f);
4803
    }
4804
}
4805

    
4806
void qemu_put_byte(QEMUFile *f, int v)
4807
{
4808
    f->buf[f->buf_index++] = v;
4809
    if (f->buf_index >= IO_BUF_SIZE)
4810
        qemu_fflush(f);
4811
}
4812

    
4813
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4814
{
4815
    int size, l;
4816

    
4817
    size = size1;
4818
    while (size > 0) {
4819
        l = f->buf_size - f->buf_index;
4820
        if (l == 0) {
4821
            qemu_fill_buffer(f);
4822
            l = f->buf_size - f->buf_index;
4823
            if (l == 0)
4824
                break;
4825
        }
4826
        if (l > size)
4827
            l = size;
4828
        memcpy(buf, f->buf + f->buf_index, l);
4829
        f->buf_index += l;
4830
        buf += l;
4831
        size -= l;
4832
    }
4833
    return size1 - size;
4834
}
4835

    
4836
int qemu_get_byte(QEMUFile *f)
4837
{
4838
    if (f->buf_index >= f->buf_size) {
4839
        qemu_fill_buffer(f);
4840
        if (f->buf_index >= f->buf_size)
4841
            return 0;
4842
    }
4843
    return f->buf[f->buf_index++];
4844
}
4845

    
4846
int64_t qemu_ftell(QEMUFile *f)
4847
{
4848
    return f->buf_offset - f->buf_size + f->buf_index;
4849
}
4850

    
4851
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4852
{
4853
    if (whence == SEEK_SET) {
4854
        /* nothing to do */
4855
    } else if (whence == SEEK_CUR) {
4856
        pos += qemu_ftell(f);
4857
    } else {
4858
        /* SEEK_END not supported */
4859
        return -1;
4860
    }
4861
    if (f->is_writable) {
4862
        qemu_fflush(f);
4863
        f->buf_offset = pos;
4864
    } else {
4865
        f->buf_offset = pos;
4866
        f->buf_index = 0;
4867
        f->buf_size = 0;
4868
    }
4869
    return pos;
4870
}
4871

    
4872
void qemu_put_be16(QEMUFile *f, unsigned int v)
4873
{
4874
    qemu_put_byte(f, v >> 8);
4875
    qemu_put_byte(f, v);
4876
}
4877

    
4878
void qemu_put_be32(QEMUFile *f, unsigned int v)
4879
{
4880
    qemu_put_byte(f, v >> 24);
4881
    qemu_put_byte(f, v >> 16);
4882
    qemu_put_byte(f, v >> 8);
4883
    qemu_put_byte(f, v);
4884
}
4885

    
4886
void qemu_put_be64(QEMUFile *f, uint64_t v)
4887
{
4888
    qemu_put_be32(f, v >> 32);
4889
    qemu_put_be32(f, v);
4890
}
4891

    
4892
unsigned int qemu_get_be16(QEMUFile *f)
4893
{
4894
    unsigned int v;
4895
    v = qemu_get_byte(f) << 8;
4896
    v |= qemu_get_byte(f);
4897
    return v;
4898
}
4899

    
4900
unsigned int qemu_get_be32(QEMUFile *f)
4901
{
4902
    unsigned int v;
4903
    v = qemu_get_byte(f) << 24;
4904
    v |= qemu_get_byte(f) << 16;
4905
    v |= qemu_get_byte(f) << 8;
4906
    v |= qemu_get_byte(f);
4907
    return v;
4908
}
4909

    
4910
uint64_t qemu_get_be64(QEMUFile *f)
4911
{
4912
    uint64_t v;
4913
    v = (uint64_t)qemu_get_be32(f) << 32;
4914
    v |= qemu_get_be32(f);
4915
    return v;
4916
}
4917

    
4918
typedef struct SaveStateEntry {
4919
    char idstr[256];
4920
    int instance_id;
4921
    int version_id;
4922
    SaveStateHandler *save_state;
4923
    LoadStateHandler *load_state;
4924
    void *opaque;
4925
    struct SaveStateEntry *next;
4926
} SaveStateEntry;
4927

    
4928
static SaveStateEntry *first_se;
4929

    
4930
int register_savevm(const char *idstr, 
4931
                    int instance_id, 
4932
                    int version_id,
4933
                    SaveStateHandler *save_state,
4934
                    LoadStateHandler *load_state,
4935
                    void *opaque)
4936
{
4937
    SaveStateEntry *se, **pse;
4938

    
4939
    se = qemu_malloc(sizeof(SaveStateEntry));
4940
    if (!se)
4941
        return -1;
4942
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4943
    se->instance_id = instance_id;
4944
    se->version_id = version_id;
4945
    se->save_state = save_state;
4946
    se->load_state = load_state;
4947
    se->opaque = opaque;
4948
    se->next = NULL;
4949

    
4950
    /* add at the end of list */
4951
    pse = &first_se;
4952
    while (*pse != NULL)
4953
        pse = &(*pse)->next;
4954
    *pse = se;
4955
    return 0;
4956
}
4957

    
4958
#define QEMU_VM_FILE_MAGIC   0x5145564d
4959
#define QEMU_VM_FILE_VERSION 0x00000002
4960

    
4961
int qemu_savevm_state(QEMUFile *f)
4962
{
4963
    SaveStateEntry *se;
4964
    int len, ret;
4965
    int64_t cur_pos, len_pos, total_len_pos;
4966

    
4967
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4968
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4969
    total_len_pos = qemu_ftell(f);
4970
    qemu_put_be64(f, 0); /* total size */
4971

    
4972
    for(se = first_se; se != NULL; se = se->next) {
4973
        /* ID string */
4974
        len = strlen(se->idstr);
4975
        qemu_put_byte(f, len);
4976
        qemu_put_buffer(f, se->idstr, len);
4977

    
4978
        qemu_put_be32(f, se->instance_id);
4979
        qemu_put_be32(f, se->version_id);
4980

    
4981
        /* record size: filled later */
4982
        len_pos = qemu_ftell(f);
4983
        qemu_put_be32(f, 0);
4984
        
4985
        se->save_state(f, se->opaque);
4986

    
4987
        /* fill record size */
4988
        cur_pos = qemu_ftell(f);
4989
        len = cur_pos - len_pos - 4;
4990
        qemu_fseek(f, len_pos, SEEK_SET);
4991
        qemu_put_be32(f, len);
4992
        qemu_fseek(f, cur_pos, SEEK_SET);
4993
    }
4994
    cur_pos = qemu_ftell(f);
4995
    qemu_fseek(f, total_len_pos, SEEK_SET);
4996
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4997
    qemu_fseek(f, cur_pos, SEEK_SET);
4998

    
4999
    ret = 0;
5000
    return ret;
5001
}
5002

    
5003
static SaveStateEntry *find_se(const char *idstr, int instance_id)
5004
{
5005
    SaveStateEntry *se;
5006

    
5007
    for(se = first_se; se != NULL; se = se->next) {
5008
        if (!strcmp(se->idstr, idstr) && 
5009
            instance_id == se->instance_id)
5010
            return se;
5011
    }
5012
    return NULL;
5013
}
5014

    
5015
int qemu_loadvm_state(QEMUFile *f)
5016
{
5017
    SaveStateEntry *se;
5018
    int len, ret, instance_id, record_len, version_id;
5019
    int64_t total_len, end_pos, cur_pos;
5020
    unsigned int v;
5021
    char idstr[256];
5022
    
5023
    v = qemu_get_be32(f);
5024
    if (v != QEMU_VM_FILE_MAGIC)
5025
        goto fail;
5026
    v = qemu_get_be32(f);
5027
    if (v != QEMU_VM_FILE_VERSION) {
5028
    fail:
5029
        ret = -1;
5030
        goto the_end;
5031
    }
5032
    total_len = qemu_get_be64(f);
5033
    end_pos = total_len + qemu_ftell(f);
5034
    for(;;) {
5035
        if (qemu_ftell(f) >= end_pos)
5036
            break;
5037
        len = qemu_get_byte(f);
5038
        qemu_get_buffer(f, idstr, len);
5039
        idstr[len] = '\0';
5040
        instance_id = qemu_get_be32(f);
5041
        version_id = qemu_get_be32(f);
5042
        record_len = qemu_get_be32(f);
5043
#if 0
5044
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
5045
               idstr, instance_id, version_id, record_len);
5046
#endif
5047
        cur_pos = qemu_ftell(f);
5048
        se = find_se(idstr, instance_id);
5049
        if (!se) {
5050
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
5051
                    instance_id, idstr);
5052
        } else {
5053
            ret = se->load_state(f, se->opaque, version_id);
5054
            if (ret < 0) {
5055
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
5056
                        instance_id, idstr);
5057
            }
5058
        }
5059
        /* always seek to exact end of record */
5060
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5061
    }
5062
    ret = 0;
5063
 the_end:
5064
    return ret;
5065
}
5066

    
5067
/* device can contain snapshots */
5068
static int bdrv_can_snapshot(BlockDriverState *bs)
5069
{
5070
    return (bs &&
5071
            !bdrv_is_removable(bs) &&
5072
            !bdrv_is_read_only(bs));
5073
}
5074

    
5075
/* device must be snapshots in order to have a reliable snapshot */
5076
static int bdrv_has_snapshot(BlockDriverState *bs)
5077
{
5078
    return (bs &&
5079
            !bdrv_is_removable(bs) &&
5080
            !bdrv_is_read_only(bs));
5081
}
5082

    
5083
static BlockDriverState *get_bs_snapshots(void)
5084
{
5085
    BlockDriverState *bs;
5086
    int i;
5087

    
5088
    if (bs_snapshots)
5089
        return bs_snapshots;
5090
    for(i = 0; i <= MAX_DISKS; i++) {
5091
        bs = bs_table[i];
5092
        if (bdrv_can_snapshot(bs))
5093
            goto ok;
5094
    }
5095
    return NULL;
5096
 ok:
5097
    bs_snapshots = bs;
5098
    return bs;
5099
}
5100

    
5101
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5102
                              const char *name)
5103
{
5104
    QEMUSnapshotInfo *sn_tab, *sn;
5105
    int nb_sns, i, ret;
5106
    
5107
    ret = -ENOENT;
5108
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5109
    if (nb_sns < 0)
5110
        return ret;
5111
    for(i = 0; i < nb_sns; i++) {
5112
        sn = &sn_tab[i];
5113
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5114
            *sn_info = *sn;
5115
            ret = 0;
5116
            break;
5117
        }
5118
    }
5119
    qemu_free(sn_tab);
5120
    return ret;
5121
}
5122

    
5123
void do_savevm(const char *name)
5124
{
5125
    BlockDriverState *bs, *bs1;
5126
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5127
    int must_delete, ret, i;
5128
    BlockDriverInfo bdi1, *bdi = &bdi1;
5129
    QEMUFile *f;
5130
    int saved_vm_running;
5131
#ifdef _WIN32
5132
    struct _timeb tb;
5133
#else
5134
    struct timeval tv;
5135
#endif
5136

    
5137
    bs = get_bs_snapshots();
5138
    if (!bs) {
5139
        term_printf("No block device can accept snapshots\n");
5140
        return;
5141
    }
5142

    
5143
    /* ??? Should this occur after vm_stop?  */
5144
    qemu_aio_flush();
5145

    
5146
    saved_vm_running = vm_running;
5147
    vm_stop(0);
5148
    
5149
    must_delete = 0;
5150
    if (name) {
5151
        ret = bdrv_snapshot_find(bs, old_sn, name);
5152
        if (ret >= 0) {
5153
            must_delete = 1;
5154
        }
5155
    }
5156
    memset(sn, 0, sizeof(*sn));
5157
    if (must_delete) {
5158
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5159
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5160
    } else {
5161
        if (name)
5162
            pstrcpy(sn->name, sizeof(sn->name), name);
5163
    }
5164

    
5165
    /* fill auxiliary fields */
5166
#ifdef _WIN32
5167
    _ftime(&tb);
5168
    sn->date_sec = tb.time;
5169
    sn->date_nsec = tb.millitm * 1000000;
5170
#else
5171
    gettimeofday(&tv, NULL);
5172
    sn->date_sec = tv.tv_sec;
5173
    sn->date_nsec = tv.tv_usec * 1000;
5174
#endif
5175
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5176
    
5177
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5178
        term_printf("Device %s does not support VM state snapshots\n",
5179
                    bdrv_get_device_name(bs));
5180
        goto the_end;
5181
    }
5182
    
5183
    /* save the VM state */
5184
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5185
    if (!f) {
5186
        term_printf("Could not open VM state file\n");
5187
        goto the_end;
5188
    }
5189
    ret = qemu_savevm_state(f);
5190
    sn->vm_state_size = qemu_ftell(f);
5191
    qemu_fclose(f);
5192
    if (ret < 0) {
5193
        term_printf("Error %d while writing VM\n", ret);
5194
        goto the_end;
5195
    }
5196
    
5197
    /* create the snapshots */
5198

    
5199
    for(i = 0; i < MAX_DISKS; i++) {
5200
        bs1 = bs_table[i];
5201
        if (bdrv_has_snapshot(bs1)) {
5202
            if (must_delete) {
5203
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5204
                if (ret < 0) {
5205
                    term_printf("Error while deleting snapshot on '%s'\n",
5206
                                bdrv_get_device_name(bs1));
5207
                }
5208
            }
5209
            ret = bdrv_snapshot_create(bs1, sn);
5210
            if (ret < 0) {
5211
                term_printf("Error while creating snapshot on '%s'\n",
5212
                            bdrv_get_device_name(bs1));
5213
            }
5214
        }
5215
    }
5216

    
5217
 the_end:
5218
    if (saved_vm_running)
5219
        vm_start();
5220
}
5221

    
5222
void do_loadvm(const char *name)
5223
{
5224
    BlockDriverState *bs, *bs1;
5225
    BlockDriverInfo bdi1, *bdi = &bdi1;
5226
    QEMUFile *f;
5227
    int i, ret;
5228
    int saved_vm_running;
5229

    
5230
    bs = get_bs_snapshots();
5231
    if (!bs) {
5232
        term_printf("No block device supports snapshots\n");
5233
        return;
5234
    }
5235
    
5236
    /* Flush all IO requests so they don't interfere with the new state.  */
5237
    qemu_aio_flush();
5238

    
5239
    saved_vm_running = vm_running;
5240
    vm_stop(0);
5241

    
5242
    for(i = 0; i <= MAX_DISKS; i++) {
5243
        bs1 = bs_table[i];
5244
        if (bdrv_has_snapshot(bs1)) {
5245
            ret = bdrv_snapshot_goto(bs1, name);
5246
            if (ret < 0) {
5247
                if (bs != bs1)
5248
                    term_printf("Warning: ");
5249
                switch(ret) {
5250
                case -ENOTSUP:
5251
                    term_printf("Snapshots not supported on device '%s'\n",
5252
                                bdrv_get_device_name(bs1));
5253
                    break;
5254
                case -ENOENT:
5255
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
5256
                                name, bdrv_get_device_name(bs1));
5257
                    break;
5258
                default:
5259
                    term_printf("Error %d while activating snapshot on '%s'\n",
5260
                                ret, bdrv_get_device_name(bs1));
5261
                    break;
5262
                }
5263
                /* fatal on snapshot block device */
5264
                if (bs == bs1)
5265
                    goto the_end;
5266
            }
5267
        }
5268
    }
5269

    
5270
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5271
        term_printf("Device %s does not support VM state snapshots\n",
5272
                    bdrv_get_device_name(bs));
5273
        return;
5274
    }
5275
    
5276
    /* restore the VM state */
5277
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5278
    if (!f) {
5279
        term_printf("Could not open VM state file\n");
5280
        goto the_end;
5281
    }
5282
    ret = qemu_loadvm_state(f);
5283
    qemu_fclose(f);
5284
    if (ret < 0) {
5285
        term_printf("Error %d while loading VM state\n", ret);
5286
    }
5287
 the_end:
5288
    if (saved_vm_running)
5289
        vm_start();
5290
}
5291

    
5292
void do_delvm(const char *name)
5293
{
5294
    BlockDriverState *bs, *bs1;
5295
    int i, ret;
5296

    
5297
    bs = get_bs_snapshots();
5298
    if (!bs) {
5299
        term_printf("No block device supports snapshots\n");
5300
        return;
5301
    }
5302
    
5303
    for(i = 0; i <= MAX_DISKS; i++) {
5304
        bs1 = bs_table[i];
5305
        if (bdrv_has_snapshot(bs1)) {
5306
            ret = bdrv_snapshot_delete(bs1, name);
5307
            if (ret < 0) {
5308
                if (ret == -ENOTSUP)
5309
                    term_printf("Snapshots not supported on device '%s'\n",
5310
                                bdrv_get_device_name(bs1));
5311
                else
5312
                    term_printf("Error %d while deleting snapshot on '%s'\n",
5313
                                ret, bdrv_get_device_name(bs1));
5314
            }
5315
        }
5316
    }
5317
}
5318

    
5319
void do_info_snapshots(void)
5320
{
5321
    BlockDriverState *bs, *bs1;
5322
    QEMUSnapshotInfo *sn_tab, *sn;
5323
    int nb_sns, i;
5324
    char buf[256];
5325

    
5326
    bs = get_bs_snapshots();
5327
    if (!bs) {
5328
        term_printf("No available block device supports snapshots\n");
5329
        return;
5330
    }
5331
    term_printf("Snapshot devices:");
5332
    for(i = 0; i <= MAX_DISKS; i++) {
5333
        bs1 = bs_table[i];
5334
        if (bdrv_has_snapshot(bs1)) {
5335
            if (bs == bs1)
5336
                term_printf(" %s", bdrv_get_device_name(bs1));
5337
        }
5338
    }
5339
    term_printf("\n");
5340

    
5341
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5342
    if (nb_sns < 0) {
5343
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5344
        return;
5345
    }
5346
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5347
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5348
    for(i = 0; i < nb_sns; i++) {
5349
        sn = &sn_tab[i];
5350
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5351
    }
5352
    qemu_free(sn_tab);
5353
}
5354

    
5355
/***********************************************************/
5356
/* cpu save/restore */
5357

    
5358
#if defined(TARGET_I386)
5359

    
5360
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5361
{
5362
    qemu_put_be32(f, dt->selector);
5363
    qemu_put_betl(f, dt->base);
5364
    qemu_put_be32(f, dt->limit);
5365
    qemu_put_be32(f, dt->flags);
5366
}
5367

    
5368
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5369
{
5370
    dt->selector = qemu_get_be32(f);
5371
    dt->base = qemu_get_betl(f);
5372
    dt->limit = qemu_get_be32(f);
5373
    dt->flags = qemu_get_be32(f);
5374
}
5375

    
5376
void cpu_save(QEMUFile *f, void *opaque)
5377
{
5378
    CPUState *env = opaque;
5379
    uint16_t fptag, fpus, fpuc, fpregs_format;
5380
    uint32_t hflags;
5381
    int i;
5382
    
5383
    for(i = 0; i < CPU_NB_REGS; i++)
5384
        qemu_put_betls(f, &env->regs[i]);
5385
    qemu_put_betls(f, &env->eip);
5386
    qemu_put_betls(f, &env->eflags);
5387
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5388
    qemu_put_be32s(f, &hflags);
5389
    
5390
    /* FPU */
5391
    fpuc = env->fpuc;
5392
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5393
    fptag = 0;
5394
    for(i = 0; i < 8; i++) {
5395
        fptag |= ((!env->fptags[i]) << i);
5396
    }
5397
    
5398
    qemu_put_be16s(f, &fpuc);
5399
    qemu_put_be16s(f, &fpus);
5400
    qemu_put_be16s(f, &fptag);
5401

    
5402
#ifdef USE_X86LDOUBLE
5403
    fpregs_format = 0;
5404
#else
5405
    fpregs_format = 1;
5406
#endif
5407
    qemu_put_be16s(f, &fpregs_format);
5408
    
5409
    for(i = 0; i < 8; i++) {
5410
#ifdef USE_X86LDOUBLE
5411
        {
5412
            uint64_t mant;
5413
            uint16_t exp;
5414
            /* we save the real CPU data (in case of MMX usage only 'mant'
5415
               contains the MMX register */
5416
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5417
            qemu_put_be64(f, mant);
5418
            qemu_put_be16(f, exp);
5419
        }
5420
#else
5421
        /* if we use doubles for float emulation, we save the doubles to
5422
           avoid losing information in case of MMX usage. It can give
5423
           problems if the image is restored on a CPU where long
5424
           doubles are used instead. */
5425
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5426
#endif
5427
    }
5428

    
5429
    for(i = 0; i < 6; i++)
5430
        cpu_put_seg(f, &env->segs[i]);
5431
    cpu_put_seg(f, &env->ldt);
5432
    cpu_put_seg(f, &env->tr);
5433
    cpu_put_seg(f, &env->gdt);
5434
    cpu_put_seg(f, &env->idt);
5435
    
5436
    qemu_put_be32s(f, &env->sysenter_cs);
5437
    qemu_put_be32s(f, &env->sysenter_esp);
5438
    qemu_put_be32s(f, &env->sysenter_eip);
5439
    
5440
    qemu_put_betls(f, &env->cr[0]);
5441
    qemu_put_betls(f, &env->cr[2]);
5442
    qemu_put_betls(f, &env->cr[3]);
5443
    qemu_put_betls(f, &env->cr[4]);
5444
    
5445
    for(i = 0; i < 8; i++)
5446
        qemu_put_betls(f, &env->dr[i]);
5447

    
5448
    /* MMU */
5449
    qemu_put_be32s(f, &env->a20_mask);
5450

    
5451
    /* XMM */
5452
    qemu_put_be32s(f, &env->mxcsr);
5453
    for(i = 0; i < CPU_NB_REGS; i++) {
5454
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5455
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5456
    }
5457

    
5458
#ifdef TARGET_X86_64
5459
    qemu_put_be64s(f, &env->efer);
5460
    qemu_put_be64s(f, &env->star);
5461
    qemu_put_be64s(f, &env->lstar);
5462
    qemu_put_be64s(f, &env->cstar);
5463
    qemu_put_be64s(f, &env->fmask);
5464
    qemu_put_be64s(f, &env->kernelgsbase);
5465
#endif
5466
    qemu_put_be32s(f, &env->smbase);
5467
}
5468

    
5469
#ifdef USE_X86LDOUBLE
5470
/* XXX: add that in a FPU generic layer */
5471
union x86_longdouble {
5472
    uint64_t mant;
5473
    uint16_t exp;
5474
};
5475

    
5476
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5477
#define EXPBIAS1 1023
5478
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5479
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5480

    
5481
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5482
{
5483
    int e;
5484
    /* mantissa */
5485
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5486
    /* exponent + sign */
5487
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5488
    e |= SIGND1(temp) >> 16;
5489
    p->exp = e;
5490
}
5491
#endif
5492

    
5493
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5494
{
5495
    CPUState *env = opaque;
5496
    int i, guess_mmx;
5497
    uint32_t hflags;
5498
    uint16_t fpus, fpuc, fptag, fpregs_format;
5499

    
5500
    if (version_id != 3 && version_id != 4)
5501
        return -EINVAL;
5502
    for(i = 0; i < CPU_NB_REGS; i++)
5503
        qemu_get_betls(f, &env->regs[i]);
5504
    qemu_get_betls(f, &env->eip);
5505
    qemu_get_betls(f, &env->eflags);
5506
    qemu_get_be32s(f, &hflags);
5507

    
5508
    qemu_get_be16s(f, &fpuc);
5509
    qemu_get_be16s(f, &fpus);
5510
    qemu_get_be16s(f, &fptag);
5511
    qemu_get_be16s(f, &fpregs_format);
5512
    
5513
    /* NOTE: we cannot always restore the FPU state if the image come
5514
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5515
       if we are in an MMX state to restore correctly in that case. */
5516
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5517
    for(i = 0; i < 8; i++) {
5518
        uint64_t mant;
5519
        uint16_t exp;
5520
        
5521
        switch(fpregs_format) {
5522
        case 0:
5523
            mant = qemu_get_be64(f);
5524
            exp = qemu_get_be16(f);
5525
#ifdef USE_X86LDOUBLE
5526
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5527
#else
5528
            /* difficult case */
5529
            if (guess_mmx)
5530
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5531
            else
5532
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5533
#endif
5534
            break;
5535
        case 1:
5536
            mant = qemu_get_be64(f);
5537
#ifdef USE_X86LDOUBLE
5538
            {
5539
                union x86_longdouble *p;
5540
                /* difficult case */
5541
                p = (void *)&env->fpregs[i];
5542
                if (guess_mmx) {
5543
                    p->mant = mant;
5544
                    p->exp = 0xffff;
5545
                } else {
5546
                    fp64_to_fp80(p, mant);
5547
                }
5548
            }
5549
#else
5550
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5551
#endif            
5552
            break;
5553
        default:
5554
            return -EINVAL;
5555
        }
5556
    }
5557

    
5558
    env->fpuc = fpuc;
5559
    /* XXX: restore FPU round state */
5560
    env->fpstt = (fpus >> 11) & 7;
5561
    env->fpus = fpus & ~0x3800;
5562
    fptag ^= 0xff;
5563
    for(i = 0; i < 8; i++) {
5564
        env->fptags[i] = (fptag >> i) & 1;
5565
    }
5566
    
5567
    for(i = 0; i < 6; i++)
5568
        cpu_get_seg(f, &env->segs[i]);
5569
    cpu_get_seg(f, &env->ldt);
5570
    cpu_get_seg(f, &env->tr);
5571
    cpu_get_seg(f, &env->gdt);
5572
    cpu_get_seg(f, &env->idt);
5573
    
5574
    qemu_get_be32s(f, &env->sysenter_cs);
5575
    qemu_get_be32s(f, &env->sysenter_esp);
5576
    qemu_get_be32s(f, &env->sysenter_eip);
5577
    
5578
    qemu_get_betls(f, &env->cr[0]);
5579
    qemu_get_betls(f, &env->cr[2]);
5580
    qemu_get_betls(f, &env->cr[3]);
5581
    qemu_get_betls(f, &env->cr[4]);
5582
    
5583
    for(i = 0; i < 8; i++)
5584
        qemu_get_betls(f, &env->dr[i]);
5585

    
5586
    /* MMU */
5587
    qemu_get_be32s(f, &env->a20_mask);
5588

    
5589
    qemu_get_be32s(f, &env->mxcsr);
5590
    for(i = 0; i < CPU_NB_REGS; i++) {
5591
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5592
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5593
    }
5594

    
5595
#ifdef TARGET_X86_64
5596
    qemu_get_be64s(f, &env->efer);
5597
    qemu_get_be64s(f, &env->star);
5598
    qemu_get_be64s(f, &env->lstar);
5599
    qemu_get_be64s(f, &env->cstar);
5600
    qemu_get_be64s(f, &env->fmask);
5601
    qemu_get_be64s(f, &env->kernelgsbase);
5602
#endif
5603
    if (version_id >= 4) 
5604
        qemu_get_be32s(f, &env->smbase);
5605

    
5606
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5607
    env->hflags = hflags;
5608
    tlb_flush(env, 1);
5609
    return 0;
5610
}
5611

    
5612
#elif defined(TARGET_PPC)
5613
void cpu_save(QEMUFile *f, void *opaque)
5614
{
5615
}
5616

    
5617
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5618
{
5619
    return 0;
5620
}
5621

    
5622
#elif defined(TARGET_MIPS)
5623
void cpu_save(QEMUFile *f, void *opaque)
5624
{
5625
}
5626

    
5627
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5628
{
5629
    return 0;
5630
}
5631

    
5632
#elif defined(TARGET_SPARC)
5633
void cpu_save(QEMUFile *f, void *opaque)
5634
{
5635
    CPUState *env = opaque;
5636
    int i;
5637
    uint32_t tmp;
5638

    
5639
    for(i = 0; i < 8; i++)
5640
        qemu_put_betls(f, &env->gregs[i]);
5641
    for(i = 0; i < NWINDOWS * 16; i++)
5642
        qemu_put_betls(f, &env->regbase[i]);
5643

    
5644
    /* FPU */
5645
    for(i = 0; i < TARGET_FPREGS; i++) {
5646
        union {
5647
            float32 f;
5648
            uint32_t i;
5649
        } u;
5650
        u.f = env->fpr[i];
5651
        qemu_put_be32(f, u.i);
5652
    }
5653

    
5654
    qemu_put_betls(f, &env->pc);
5655
    qemu_put_betls(f, &env->npc);
5656
    qemu_put_betls(f, &env->y);
5657
    tmp = GET_PSR(env);
5658
    qemu_put_be32(f, tmp);
5659
    qemu_put_betls(f, &env->fsr);
5660
    qemu_put_betls(f, &env->tbr);
5661
#ifndef TARGET_SPARC64
5662
    qemu_put_be32s(f, &env->wim);
5663
    /* MMU */
5664
    for(i = 0; i < 16; i++)
5665
        qemu_put_be32s(f, &env->mmuregs[i]);
5666
#endif
5667
}
5668

    
5669
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5670
{
5671
    CPUState *env = opaque;
5672
    int i;
5673
    uint32_t tmp;
5674

    
5675
    for(i = 0; i < 8; i++)
5676
        qemu_get_betls(f, &env->gregs[i]);
5677
    for(i = 0; i < NWINDOWS * 16; i++)
5678
        qemu_get_betls(f, &env->regbase[i]);
5679

    
5680
    /* FPU */
5681
    for(i = 0; i < TARGET_FPREGS; i++) {
5682
        union {
5683
            float32 f;
5684
            uint32_t i;
5685
        } u;
5686
        u.i = qemu_get_be32(f);
5687
        env->fpr[i] = u.f;
5688
    }
5689

    
5690
    qemu_get_betls(f, &env->pc);
5691
    qemu_get_betls(f, &env->npc);
5692
    qemu_get_betls(f, &env->y);
5693
    tmp = qemu_get_be32(f);
5694
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5695
                     correctly updated */
5696
    PUT_PSR(env, tmp);
5697
    qemu_get_betls(f, &env->fsr);
5698
    qemu_get_betls(f, &env->tbr);
5699
#ifndef TARGET_SPARC64
5700
    qemu_get_be32s(f, &env->wim);
5701
    /* MMU */
5702
    for(i = 0; i < 16; i++)
5703
        qemu_get_be32s(f, &env->mmuregs[i]);
5704
#endif
5705
    tlb_flush(env, 1);
5706
    return 0;
5707
}
5708

    
5709
#elif defined(TARGET_ARM)
5710

    
5711
void cpu_save(QEMUFile *f, void *opaque)
5712
{
5713
    int i;
5714
    CPUARMState *env = (CPUARMState *)opaque;
5715

    
5716
    for (i = 0; i < 16; i++) {
5717
        qemu_put_be32(f, env->regs[i]);
5718
    }
5719
    qemu_put_be32(f, cpsr_read(env));
5720
    qemu_put_be32(f, env->spsr);
5721
    for (i = 0; i < 6; i++) {
5722
        qemu_put_be32(f, env->banked_spsr[i]);
5723
        qemu_put_be32(f, env->banked_r13[i]);
5724
        qemu_put_be32(f, env->banked_r14[i]);
5725
    }
5726
    for (i = 0; i < 5; i++) {
5727
        qemu_put_be32(f, env->usr_regs[i]);
5728
        qemu_put_be32(f, env->fiq_regs[i]);
5729
    }
5730
    qemu_put_be32(f, env->cp15.c0_cpuid);
5731
    qemu_put_be32(f, env->cp15.c0_cachetype);
5732
    qemu_put_be32(f, env->cp15.c1_sys);
5733
    qemu_put_be32(f, env->cp15.c1_coproc);
5734
    qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5735
    qemu_put_be32(f, env->cp15.c2_base);
5736
    qemu_put_be32(f, env->cp15.c2_data);
5737
    qemu_put_be32(f, env->cp15.c2_insn);
5738
    qemu_put_be32(f, env->cp15.c3);
5739
    qemu_put_be32(f, env->cp15.c5_insn);
5740
    qemu_put_be32(f, env->cp15.c5_data);
5741
    for (i = 0; i < 8; i++) {
5742
        qemu_put_be32(f, env->cp15.c6_region[i]);
5743
    }
5744
    qemu_put_be32(f, env->cp15.c6_insn);
5745
    qemu_put_be32(f, env->cp15.c6_data);
5746
    qemu_put_be32(f, env->cp15.c9_insn);
5747
    qemu_put_be32(f, env->cp15.c9_data);
5748
    qemu_put_be32(f, env->cp15.c13_fcse);
5749
    qemu_put_be32(f, env->cp15.c13_context);
5750
    qemu_put_be32(f, env->cp15.c15_cpar);
5751

    
5752
    qemu_put_be32(f, env->features);
5753

    
5754
    if (arm_feature(env, ARM_FEATURE_VFP)) {
5755
        for (i = 0;  i < 16; i++) {
5756
            CPU_DoubleU u;
5757
            u.d = env->vfp.regs[i];
5758
            qemu_put_be32(f, u.l.upper);
5759
            qemu_put_be32(f, u.l.lower);
5760
        }
5761
        for (i = 0; i < 16; i++) {
5762
            qemu_put_be32(f, env->vfp.xregs[i]);
5763
        }
5764

    
5765
        /* TODO: Should use proper FPSCR access functions.  */
5766
        qemu_put_be32(f, env->vfp.vec_len);
5767
        qemu_put_be32(f, env->vfp.vec_stride);
5768
    }
5769

    
5770
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5771
        for (i = 0; i < 16; i++) {
5772
            qemu_put_be64(f, env->iwmmxt.regs[i]);
5773
        }
5774
        for (i = 0; i < 16; i++) {
5775
            qemu_put_be32(f, env->iwmmxt.cregs[i]);
5776
        }
5777
    }
5778
}
5779

    
5780
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5781
{
5782
    CPUARMState *env = (CPUARMState *)opaque;
5783
    int i;
5784

    
5785
    if (version_id != 0)
5786
        return -EINVAL;
5787

    
5788
    for (i = 0; i < 16; i++) {
5789
        env->regs[i] = qemu_get_be32(f);
5790
    }
5791
    cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5792
    env->spsr = qemu_get_be32(f);
5793
    for (i = 0; i < 6; i++) {
5794
        env->banked_spsr[i] = qemu_get_be32(f);
5795
        env->banked_r13[i] = qemu_get_be32(f);
5796
        env->banked_r14[i] = qemu_get_be32(f);
5797
    }
5798
    for (i = 0; i < 5; i++) {
5799
        env->usr_regs[i] = qemu_get_be32(f);
5800
        env->fiq_regs[i] = qemu_get_be32(f);
5801
    }
5802
    env->cp15.c0_cpuid = qemu_get_be32(f);
5803
    env->cp15.c0_cachetype = qemu_get_be32(f);
5804
    env->cp15.c1_sys = qemu_get_be32(f);
5805
    env->cp15.c1_coproc = qemu_get_be32(f);
5806
    env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5807
    env->cp15.c2_base = qemu_get_be32(f);
5808
    env->cp15.c2_data = qemu_get_be32(f);
5809
    env->cp15.c2_insn = qemu_get_be32(f);
5810
    env->cp15.c3 = qemu_get_be32(f);
5811
    env->cp15.c5_insn = qemu_get_be32(f);
5812
    env->cp15.c5_data = qemu_get_be32(f);
5813
    for (i = 0; i < 8; i++) {
5814
        env->cp15.c6_region[i] = qemu_get_be32(f);
5815
    }
5816
    env->cp15.c6_insn = qemu_get_be32(f);
5817
    env->cp15.c6_data = qemu_get_be32(f);
5818
    env->cp15.c9_insn = qemu_get_be32(f);
5819
    env->cp15.c9_data = qemu_get_be32(f);
5820
    env->cp15.c13_fcse = qemu_get_be32(f);
5821
    env->cp15.c13_context = qemu_get_be32(f);
5822
    env->cp15.c15_cpar = qemu_get_be32(f);
5823

    
5824
    env->features = qemu_get_be32(f);
5825

    
5826
    if (arm_feature(env, ARM_FEATURE_VFP)) {
5827
        for (i = 0;  i < 16; i++) {
5828
            CPU_DoubleU u;
5829
            u.l.upper = qemu_get_be32(f);
5830
            u.l.lower = qemu_get_be32(f);
5831
            env->vfp.regs[i] = u.d;
5832
        }
5833
        for (i = 0; i < 16; i++) {
5834
            env->vfp.xregs[i] = qemu_get_be32(f);
5835
        }
5836

    
5837
        /* TODO: Should use proper FPSCR access functions.  */
5838
        env->vfp.vec_len = qemu_get_be32(f);
5839
        env->vfp.vec_stride = qemu_get_be32(f);
5840
    }
5841

    
5842
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5843
        for (i = 0; i < 16; i++) {
5844
            env->iwmmxt.regs[i] = qemu_get_be64(f);
5845
        }
5846
        for (i = 0; i < 16; i++) {
5847
            env->iwmmxt.cregs[i] = qemu_get_be32(f);
5848
        }
5849
    }
5850

    
5851
    return 0;
5852
}
5853

    
5854
#else
5855

    
5856
#warning No CPU save/restore functions
5857

    
5858
#endif
5859

    
5860
/***********************************************************/
5861
/* ram save/restore */
5862

    
5863
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5864
{
5865
    int v;
5866

    
5867
    v = qemu_get_byte(f);
5868
    switch(v) {
5869
    case 0:
5870
        if (qemu_get_buffer(f, buf, len) != len)
5871
            return -EIO;
5872
        break;
5873
    case 1:
5874
        v = qemu_get_byte(f);
5875
        memset(buf, v, len);
5876
        break;
5877
    default:
5878
        return -EINVAL;
5879
    }
5880
    return 0;
5881
}
5882

    
5883
static int ram_load_v1(QEMUFile *f, void *opaque)
5884
{
5885
    int i, ret;
5886

    
5887
    if (qemu_get_be32(f) != phys_ram_size)
5888
        return -EINVAL;
5889
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5890
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5891
        if (ret)
5892
            return ret;
5893
    }
5894
    return 0;
5895
}
5896

    
5897
#define BDRV_HASH_BLOCK_SIZE 1024
5898
#define IOBUF_SIZE 4096
5899
#define RAM_CBLOCK_MAGIC 0xfabe
5900

    
5901
typedef struct RamCompressState {
5902
    z_stream zstream;
5903
    QEMUFile *f;
5904
    uint8_t buf[IOBUF_SIZE];
5905
} RamCompressState;
5906

    
5907
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5908
{
5909
    int ret;
5910
    memset(s, 0, sizeof(*s));
5911
    s->f = f;
5912
    ret = deflateInit2(&s->zstream, 1,
5913
                       Z_DEFLATED, 15, 
5914
                       9, Z_DEFAULT_STRATEGY);
5915
    if (ret != Z_OK)
5916
        return -1;
5917
    s->zstream.avail_out = IOBUF_SIZE;
5918
    s->zstream.next_out = s->buf;
5919
    return 0;
5920
}
5921

    
5922
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5923
{
5924
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5925
    qemu_put_be16(s->f, len);
5926
    qemu_put_buffer(s->f, buf, len);
5927
}
5928

    
5929
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5930
{
5931
    int ret;
5932

    
5933
    s->zstream.avail_in = len;
5934
    s->zstream.next_in = (uint8_t *)buf;
5935
    while (s->zstream.avail_in > 0) {
5936
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5937
        if (ret != Z_OK)
5938
            return -1;
5939
        if (s->zstream.avail_out == 0) {
5940
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5941
            s->zstream.avail_out = IOBUF_SIZE;
5942
            s->zstream.next_out = s->buf;
5943
        }
5944
    }
5945
    return 0;
5946
}
5947

    
5948
static void ram_compress_close(RamCompressState *s)
5949
{
5950
    int len, ret;
5951

    
5952
    /* compress last bytes */
5953
    for(;;) {
5954
        ret = deflate(&s->zstream, Z_FINISH);
5955
        if (ret == Z_OK || ret == Z_STREAM_END) {
5956
            len = IOBUF_SIZE - s->zstream.avail_out;
5957
            if (len > 0) {
5958
                ram_put_cblock(s, s->buf, len);
5959
            }
5960
            s->zstream.avail_out = IOBUF_SIZE;
5961
            s->zstream.next_out = s->buf;
5962
            if (ret == Z_STREAM_END)
5963
                break;
5964
        } else {
5965
            goto fail;
5966
        }
5967
    }
5968
fail:
5969
    deflateEnd(&s->zstream);
5970
}
5971

    
5972
typedef struct RamDecompressState {
5973
    z_stream zstream;
5974
    QEMUFile *f;
5975
    uint8_t buf[IOBUF_SIZE];
5976
} RamDecompressState;
5977

    
5978
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5979
{
5980
    int ret;
5981
    memset(s, 0, sizeof(*s));
5982
    s->f = f;
5983
    ret = inflateInit(&s->zstream);
5984
    if (ret != Z_OK)
5985
        return -1;
5986
    return 0;
5987
}
5988

    
5989
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5990
{
5991
    int ret, clen;
5992

    
5993
    s->zstream.avail_out = len;
5994
    s->zstream.next_out = buf;
5995
    while (s->zstream.avail_out > 0) {
5996
        if (s->zstream.avail_in == 0) {
5997
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5998
                return -1;
5999
            clen = qemu_get_be16(s->f);
6000
            if (clen > IOBUF_SIZE)
6001
                return -1;
6002
            qemu_get_buffer(s->f, s->buf, clen);
6003
            s->zstream.avail_in = clen;
6004
            s->zstream.next_in = s->buf;
6005
        }
6006
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6007
        if (ret != Z_OK && ret != Z_STREAM_END) {
6008
            return -1;
6009
        }
6010
    }
6011
    return 0;
6012
}
6013

    
6014
static void ram_decompress_close(RamDecompressState *s)
6015
{
6016
    inflateEnd(&s->zstream);
6017
}
6018

    
6019
static void ram_save(QEMUFile *f, void *opaque)
6020
{
6021
    int i;
6022
    RamCompressState s1, *s = &s1;
6023
    uint8_t buf[10];
6024
    
6025
    qemu_put_be32(f, phys_ram_size);
6026
    if (ram_compress_open(s, f) < 0)
6027
        return;
6028
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6029
#if 0
6030
        if (tight_savevm_enabled) {
6031
            int64_t sector_num;
6032
            int j;
6033

6034
            /* find if the memory block is available on a virtual
6035
               block device */
6036
            sector_num = -1;
6037
            for(j = 0; j < MAX_DISKS; j++) {
6038
                if (bs_table[j]) {
6039
                    sector_num = bdrv_hash_find(bs_table[j], 
6040
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6041
                    if (sector_num >= 0)
6042
                        break;
6043
                }
6044
            }
6045
            if (j == MAX_DISKS)
6046
                goto normal_compress;
6047
            buf[0] = 1;
6048
            buf[1] = j;
6049
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6050
            ram_compress_buf(s, buf, 10);
6051
        } else 
6052
#endif
6053
        {
6054
            //        normal_compress:
6055
            buf[0] = 0;
6056
            ram_compress_buf(s, buf, 1);
6057
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6058
        }
6059
    }
6060
    ram_compress_close(s);
6061
}
6062

    
6063
static int ram_load(QEMUFile *f, void *opaque, int version_id)
6064
{
6065
    RamDecompressState s1, *s = &s1;
6066
    uint8_t buf[10];
6067
    int i;
6068

    
6069
    if (version_id == 1)
6070
        return ram_load_v1(f, opaque);
6071
    if (version_id != 2)
6072
        return -EINVAL;
6073
    if (qemu_get_be32(f) != phys_ram_size)
6074
        return -EINVAL;
6075
    if (ram_decompress_open(s, f) < 0)
6076
        return -EINVAL;
6077
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6078
        if (ram_decompress_buf(s, buf, 1) < 0) {
6079
            fprintf(stderr, "Error while reading ram block header\n");
6080
            goto error;
6081
        }
6082
        if (buf[0] == 0) {
6083
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6084
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6085
                goto error;
6086
            }
6087
        } else 
6088
#if 0
6089
        if (buf[0] == 1) {
6090
            int bs_index;
6091
            int64_t sector_num;
6092

6093
            ram_decompress_buf(s, buf + 1, 9);
6094
            bs_index = buf[1];
6095
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6096
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6097
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
6098
                goto error;
6099
            }
6100
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
6101
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6102
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
6103
                        bs_index, sector_num);
6104
                goto error;
6105
            }
6106
        } else 
6107
#endif
6108
        {
6109
        error:
6110
            printf("Error block header\n");
6111
            return -EINVAL;
6112
        }
6113
    }
6114
    ram_decompress_close(s);
6115
    return 0;
6116
}
6117

    
6118
/***********************************************************/
6119
/* bottom halves (can be seen as timers which expire ASAP) */
6120

    
6121
struct QEMUBH {
6122
    QEMUBHFunc *cb;
6123
    void *opaque;
6124
    int scheduled;
6125
    QEMUBH *next;
6126
};
6127

    
6128
static QEMUBH *first_bh = NULL;
6129

    
6130
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6131
{
6132
    QEMUBH *bh;
6133
    bh = qemu_mallocz(sizeof(QEMUBH));
6134
    if (!bh)
6135
        return NULL;
6136
    bh->cb = cb;
6137
    bh->opaque = opaque;
6138
    return bh;
6139
}
6140

    
6141
int qemu_bh_poll(void)
6142
{
6143
    QEMUBH *bh, **pbh;
6144
    int ret;
6145

    
6146
    ret = 0;
6147
    for(;;) {
6148
        pbh = &first_bh;
6149
        bh = *pbh;
6150
        if (!bh)
6151
            break;
6152
        ret = 1;
6153
        *pbh = bh->next;
6154
        bh->scheduled = 0;
6155
        bh->cb(bh->opaque);
6156
    }
6157
    return ret;
6158
}
6159

    
6160
void qemu_bh_schedule(QEMUBH *bh)
6161
{
6162
    CPUState *env = cpu_single_env;
6163
    if (bh->scheduled)
6164
        return;
6165
    bh->scheduled = 1;
6166
    bh->next = first_bh;
6167
    first_bh = bh;
6168

    
6169
    /* stop the currently executing CPU to execute the BH ASAP */
6170
    if (env) {
6171
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6172
    }
6173
}
6174

    
6175
void qemu_bh_cancel(QEMUBH *bh)
6176
{
6177
    QEMUBH **pbh;
6178
    if (bh->scheduled) {
6179
        pbh = &first_bh;
6180
        while (*pbh != bh)
6181
            pbh = &(*pbh)->next;
6182
        *pbh = bh->next;
6183
        bh->scheduled = 0;
6184
    }
6185
}
6186

    
6187
void qemu_bh_delete(QEMUBH *bh)
6188
{
6189
    qemu_bh_cancel(bh);
6190
    qemu_free(bh);
6191
}
6192

    
6193
/***********************************************************/
6194
/* machine registration */
6195

    
6196
QEMUMachine *first_machine = NULL;
6197

    
6198
int qemu_register_machine(QEMUMachine *m)
6199
{
6200
    QEMUMachine **pm;
6201
    pm = &first_machine;
6202
    while (*pm != NULL)
6203
        pm = &(*pm)->next;
6204
    m->next = NULL;
6205
    *pm = m;
6206
    return 0;
6207
}
6208

    
6209
QEMUMachine *find_machine(const char *name)
6210
{
6211
    QEMUMachine *m;
6212

    
6213
    for(m = first_machine; m != NULL; m = m->next) {
6214
        if (!strcmp(m->name, name))
6215
            return m;
6216
    }
6217
    return NULL;
6218
}
6219

    
6220
/***********************************************************/
6221
/* main execution loop */
6222

    
6223
void gui_update(void *opaque)
6224
{
6225
    DisplayState *ds = opaque;
6226
    ds->dpy_refresh(ds);
6227
    qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6228
}
6229

    
6230
struct vm_change_state_entry {
6231
    VMChangeStateHandler *cb;
6232
    void *opaque;
6233
    LIST_ENTRY (vm_change_state_entry) entries;
6234
};
6235

    
6236
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6237

    
6238
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6239
                                                     void *opaque)
6240
{
6241
    VMChangeStateEntry *e;
6242

    
6243
    e = qemu_mallocz(sizeof (*e));
6244
    if (!e)
6245
        return NULL;
6246

    
6247
    e->cb = cb;
6248
    e->opaque = opaque;
6249
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6250
    return e;
6251
}
6252

    
6253
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6254
{
6255
    LIST_REMOVE (e, entries);
6256
    qemu_free (e);
6257
}
6258

    
6259
static void vm_state_notify(int running)
6260
{
6261
    VMChangeStateEntry *e;
6262

    
6263
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6264
        e->cb(e->opaque, running);
6265
    }
6266
}
6267

    
6268
/* XXX: support several handlers */
6269
static VMStopHandler *vm_stop_cb;
6270
static void *vm_stop_opaque;
6271

    
6272
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6273
{
6274
    vm_stop_cb = cb;
6275
    vm_stop_opaque = opaque;
6276
    return 0;
6277
}
6278

    
6279
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6280
{
6281
    vm_stop_cb = NULL;
6282
}
6283

    
6284
void vm_start(void)
6285
{
6286
    if (!vm_running) {
6287
        cpu_enable_ticks();
6288
        vm_running = 1;
6289
        vm_state_notify(1);
6290
    }
6291
}
6292

    
6293
void vm_stop(int reason) 
6294
{
6295
    if (vm_running) {
6296
        cpu_disable_ticks();
6297
        vm_running = 0;
6298
        if (reason != 0) {
6299
            if (vm_stop_cb) {
6300
                vm_stop_cb(vm_stop_opaque, reason);
6301
            }
6302
        }
6303
        vm_state_notify(0);
6304
    }
6305
}
6306

    
6307
/* reset/shutdown handler */
6308

    
6309
typedef struct QEMUResetEntry {
6310
    QEMUResetHandler *func;
6311
    void *opaque;
6312
    struct QEMUResetEntry *next;
6313
} QEMUResetEntry;
6314

    
6315
static QEMUResetEntry *first_reset_entry;
6316
static int reset_requested;
6317
static int shutdown_requested;
6318
static int powerdown_requested;
6319

    
6320
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6321
{
6322
    QEMUResetEntry **pre, *re;
6323

    
6324
    pre = &first_reset_entry;
6325
    while (*pre != NULL)
6326
        pre = &(*pre)->next;
6327
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6328
    re->func = func;
6329
    re->opaque = opaque;
6330
    re->next = NULL;
6331
    *pre = re;
6332
}
6333

    
6334
static void qemu_system_reset(void)
6335
{
6336
    QEMUResetEntry *re;
6337

    
6338
    /* reset all devices */
6339
    for(re = first_reset_entry; re != NULL; re = re->next) {
6340
        re->func(re->opaque);
6341
    }
6342
}
6343

    
6344
void qemu_system_reset_request(void)
6345
{
6346
    if (no_reboot) {
6347
        shutdown_requested = 1;
6348
    } else {
6349
        reset_requested = 1;
6350
    }
6351
    if (cpu_single_env)
6352
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6353
}
6354

    
6355
void qemu_system_shutdown_request(void)
6356
{
6357
    shutdown_requested = 1;
6358
    if (cpu_single_env)
6359
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6360
}
6361

    
6362
void qemu_system_powerdown_request(void)
6363
{
6364
    powerdown_requested = 1;
6365
    if (cpu_single_env)
6366
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6367
}
6368

    
6369
void main_loop_wait(int timeout)
6370
{
6371
    IOHandlerRecord *ioh;
6372
    fd_set rfds, wfds, xfds;
6373
    int ret, nfds;
6374
#ifdef _WIN32
6375
    int ret2, i;
6376
#endif
6377
    struct timeval tv;
6378
    PollingEntry *pe;
6379

    
6380

    
6381
    /* XXX: need to suppress polling by better using win32 events */
6382
    ret = 0;
6383
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6384
        ret |= pe->func(pe->opaque);
6385
    }
6386
#ifdef _WIN32
6387
    if (ret == 0) {
6388
        int err;
6389
        WaitObjects *w = &wait_objects;
6390
        
6391
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6392
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6393
            if (w->func[ret - WAIT_OBJECT_0])
6394
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6395
                
6396
            /* Check for additional signaled events */ 
6397
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6398
                                
6399
                /* Check if event is signaled */
6400
                ret2 = WaitForSingleObject(w->events[i], 0);
6401
                if(ret2 == WAIT_OBJECT_0) {
6402
                    if (w->func[i])
6403
                        w->func[i](w->opaque[i]);
6404
                } else if (ret2 == WAIT_TIMEOUT) {
6405
                } else {
6406
                    err = GetLastError();
6407
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6408
                }                
6409
            }                 
6410
        } else if (ret == WAIT_TIMEOUT) {
6411
        } else {
6412
            err = GetLastError();
6413
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6414
        }
6415
    }
6416
#endif
6417
    /* poll any events */
6418
    /* XXX: separate device handlers from system ones */
6419
    nfds = -1;
6420
    FD_ZERO(&rfds);
6421
    FD_ZERO(&wfds);
6422
    FD_ZERO(&xfds);
6423
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6424
        if (ioh->deleted)
6425
            continue;
6426
        if (ioh->fd_read &&
6427
            (!ioh->fd_read_poll ||
6428
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6429
            FD_SET(ioh->fd, &rfds);
6430
            if (ioh->fd > nfds)
6431
                nfds = ioh->fd;
6432
        }
6433
        if (ioh->fd_write) {
6434
            FD_SET(ioh->fd, &wfds);
6435
            if (ioh->fd > nfds)
6436
                nfds = ioh->fd;
6437
        }
6438
    }
6439
    
6440
    tv.tv_sec = 0;
6441
#ifdef _WIN32
6442
    tv.tv_usec = 0;
6443
#else
6444
    tv.tv_usec = timeout * 1000;
6445
#endif
6446
#if defined(CONFIG_SLIRP)
6447
    if (slirp_inited) {
6448
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6449
    }
6450
#endif
6451
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6452
    if (ret > 0) {
6453
        IOHandlerRecord **pioh;
6454

    
6455
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6456
            if (ioh->deleted)
6457
                continue;
6458
            if (FD_ISSET(ioh->fd, &rfds)) {
6459
                ioh->fd_read(ioh->opaque);
6460
            }
6461
            if (FD_ISSET(ioh->fd, &wfds)) {
6462
                ioh->fd_write(ioh->opaque);
6463
            }
6464
        }
6465

    
6466
        /* remove deleted IO handlers */
6467
        pioh = &first_io_handler;
6468
        while (*pioh) {
6469
            ioh = *pioh;
6470
            if (ioh->deleted) {
6471
                *pioh = ioh->next;
6472
                qemu_free(ioh);
6473
            } else 
6474
                pioh = &ioh->next;
6475
        }
6476
    }
6477
#if defined(CONFIG_SLIRP)
6478
    if (slirp_inited) {
6479
        if (ret < 0) {
6480
            FD_ZERO(&rfds);
6481
            FD_ZERO(&wfds);
6482
            FD_ZERO(&xfds);
6483
        }
6484
        slirp_select_poll(&rfds, &wfds, &xfds);
6485
    }
6486
#endif
6487
    qemu_aio_poll();
6488

    
6489
    if (vm_running) {
6490
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
6491
                        qemu_get_clock(vm_clock));
6492
        /* run dma transfers, if any */
6493
        DMA_run();
6494
    }
6495

    
6496
    /* real time timers */
6497
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
6498
                    qemu_get_clock(rt_clock));
6499

    
6500
    /* Check bottom-halves last in case any of the earlier events triggered
6501
       them.  */
6502
    qemu_bh_poll();
6503
    
6504
}
6505

    
6506
static CPUState *cur_cpu;
6507

    
6508
int main_loop(void)
6509
{
6510
    int ret, timeout;
6511
#ifdef CONFIG_PROFILER
6512
    int64_t ti;
6513
#endif
6514
    CPUState *env;
6515

    
6516
    cur_cpu = first_cpu;
6517
    for(;;) {
6518
        if (vm_running) {
6519

    
6520
            env = cur_cpu;
6521
            for(;;) {
6522
                /* get next cpu */
6523
                env = env->next_cpu;
6524
                if (!env)
6525
                    env = first_cpu;
6526
#ifdef CONFIG_PROFILER
6527
                ti = profile_getclock();
6528
#endif
6529
                ret = cpu_exec(env);
6530
#ifdef CONFIG_PROFILER
6531
                qemu_time += profile_getclock() - ti;
6532
#endif
6533
                if (ret == EXCP_HLT) {
6534
                    /* Give the next CPU a chance to run.  */
6535
                    cur_cpu = env;
6536
                    continue;
6537
                }
6538
                if (ret != EXCP_HALTED)
6539
                    break;
6540
                /* all CPUs are halted ? */
6541
                if (env == cur_cpu)
6542
                    break;
6543
            }
6544
            cur_cpu = env;
6545

    
6546
            if (shutdown_requested) {
6547
                ret = EXCP_INTERRUPT;
6548
                break;
6549
            }
6550
            if (reset_requested) {
6551
                reset_requested = 0;
6552
                qemu_system_reset();
6553
                ret = EXCP_INTERRUPT;
6554
            }
6555
            if (powerdown_requested) {
6556
                powerdown_requested = 0;
6557
                qemu_system_powerdown();
6558
                ret = EXCP_INTERRUPT;
6559
            }
6560
            if (ret == EXCP_DEBUG) {
6561
                vm_stop(EXCP_DEBUG);
6562
            }
6563
            /* If all cpus are halted then wait until the next IRQ */
6564
            /* XXX: use timeout computed from timers */
6565
            if (ret == EXCP_HALTED)
6566
                timeout = 10;
6567
            else
6568
                timeout = 0;
6569
        } else {
6570
            timeout = 10;
6571
        }
6572
#ifdef CONFIG_PROFILER
6573
        ti = profile_getclock();
6574
#endif
6575
        main_loop_wait(timeout);
6576
#ifdef CONFIG_PROFILER
6577
        dev_time += profile_getclock() - ti;
6578
#endif
6579
    }
6580
    cpu_disable_ticks();
6581
    return ret;
6582
}
6583

    
6584
static void help(int exitcode)
6585
{
6586
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6587
           "usage: %s [options] [disk_image]\n"
6588
           "\n"
6589
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6590
           "\n"
6591
           "Standard options:\n"
6592
           "-M machine      select emulated machine (-M ? for list)\n"
6593
           "-cpu cpu        select CPU (-cpu ? for list)\n"
6594
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6595
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6596
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6597
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6598
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
6599
           "-sd file        use 'file' as SecureDigital card image\n"
6600
           "-pflash file    use 'file' as a parallel flash image\n"
6601
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6602
           "-snapshot       write to temporary files instead of disk image files\n"
6603
#ifdef CONFIG_SDL
6604
           "-no-frame       open SDL window without a frame and window decorations\n"
6605
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6606
           "-no-quit        disable SDL window close capability\n"
6607
#endif
6608
#ifdef TARGET_I386
6609
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6610
#endif
6611
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6612
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
6613
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
6614
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
6615
#ifndef _WIN32
6616
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
6617
#endif
6618
#ifdef HAS_AUDIO
6619
           "-audio-help     print list of audio drivers and their options\n"
6620
           "-soundhw c1,... enable audio support\n"
6621
           "                and only specified sound cards (comma separated list)\n"
6622
           "                use -soundhw ? to get the list of supported cards\n"
6623
           "                use -soundhw all to enable all of them\n"
6624
#endif
6625
           "-localtime      set the real time clock to local time [default=utc]\n"
6626
           "-full-screen    start in full screen\n"
6627
#ifdef TARGET_I386
6628
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6629
#endif
6630
           "-usb            enable the USB driver (will be the default soon)\n"
6631
           "-usbdevice name add the host or guest USB device 'name'\n"
6632
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6633
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6634
#endif
6635
           "-name string    set the name of the guest\n"
6636
           "\n"
6637
           "Network options:\n"
6638
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6639
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6640
#ifdef CONFIG_SLIRP
6641
           "-net user[,vlan=n][,hostname=host]\n"
6642
           "                connect the user mode network stack to VLAN 'n' and send\n"
6643
           "                hostname 'host' to DHCP clients\n"
6644
#endif
6645
#ifdef _WIN32
6646
           "-net tap[,vlan=n],ifname=name\n"
6647
           "                connect the host TAP network interface to VLAN 'n'\n"
6648
#else
6649
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6650
           "                connect the host TAP network interface to VLAN 'n' and use\n"
6651
           "                the network script 'file' (default=%s);\n"
6652
           "                use 'script=no' to disable script execution;\n"
6653
           "                use 'fd=h' to connect to an already opened TAP interface\n"
6654
#endif
6655
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6656
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
6657
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6658
           "                connect the vlan 'n' to multicast maddr and port\n"
6659
           "-net none       use it alone to have zero network devices; if no -net option\n"
6660
           "                is provided, the default is '-net nic -net user'\n"
6661
           "\n"
6662
#ifdef CONFIG_SLIRP
6663
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
6664
           "-bootp file     advertise file in BOOTP replies\n"
6665
#ifndef _WIN32
6666
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6667
#endif
6668
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6669
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
6670
#endif
6671
           "\n"
6672
           "Linux boot specific:\n"
6673
           "-kernel bzImage use 'bzImage' as kernel image\n"
6674
           "-append cmdline use 'cmdline' as kernel command line\n"
6675
           "-initrd file    use 'file' as initial ram disk\n"
6676
           "\n"
6677
           "Debug/Expert options:\n"
6678
           "-monitor dev    redirect the monitor to char device 'dev'\n"
6679
           "-serial dev     redirect the serial port to char device 'dev'\n"
6680
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
6681
           "-pidfile file   Write PID to 'file'\n"
6682
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
6683
           "-s              wait gdb connection to port\n"
6684
           "-p port         set gdb connection port [default=%s]\n"
6685
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6686
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6687
           "                translation (t=none or lba) (usually qemu can guess them)\n"
6688
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6689
#ifdef USE_KQEMU
6690
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6691
           "-no-kqemu       disable KQEMU kernel module usage\n"
6692
#endif
6693
#ifdef USE_CODE_COPY
6694
           "-no-code-copy   disable code copy acceleration\n"
6695
#endif
6696
#ifdef TARGET_I386
6697
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6698
           "                (default is CL-GD5446 PCI VGA)\n"
6699
           "-no-acpi        disable ACPI\n"
6700
#endif
6701
           "-no-reboot      exit instead of rebooting\n"
6702
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6703
           "-vnc display    start a VNC server on display\n"
6704
#ifndef _WIN32
6705
           "-daemonize      daemonize QEMU after initializing\n"
6706
#endif
6707
           "-option-rom rom load a file, rom, into the option ROM space\n"
6708
#ifdef TARGET_SPARC
6709
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
6710
#endif
6711
           "\n"
6712
           "During emulation, the following keys are useful:\n"
6713
           "ctrl-alt-f      toggle full screen\n"
6714
           "ctrl-alt-n      switch to virtual console 'n'\n"
6715
           "ctrl-alt        toggle mouse and keyboard grab\n"
6716
           "\n"
6717
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
6718
           ,
6719
           "qemu",
6720
           DEFAULT_RAM_SIZE,
6721
#ifndef _WIN32
6722
           DEFAULT_NETWORK_SCRIPT,
6723
#endif
6724
           DEFAULT_GDBSTUB_PORT,
6725
           "/tmp/qemu.log");
6726
    exit(exitcode);
6727
}
6728

    
6729
#define HAS_ARG 0x0001
6730

    
6731
enum {
6732
    QEMU_OPTION_h,
6733

    
6734
    QEMU_OPTION_M,
6735
    QEMU_OPTION_cpu,
6736
    QEMU_OPTION_fda,
6737
    QEMU_OPTION_fdb,
6738
    QEMU_OPTION_hda,
6739
    QEMU_OPTION_hdb,
6740
    QEMU_OPTION_hdc,
6741
    QEMU_OPTION_hdd,
6742
    QEMU_OPTION_cdrom,
6743
    QEMU_OPTION_mtdblock,
6744
    QEMU_OPTION_sd,
6745
    QEMU_OPTION_pflash,
6746
    QEMU_OPTION_boot,
6747
    QEMU_OPTION_snapshot,
6748
#ifdef TARGET_I386
6749
    QEMU_OPTION_no_fd_bootchk,
6750
#endif
6751
    QEMU_OPTION_m,
6752
    QEMU_OPTION_nographic,
6753
    QEMU_OPTION_portrait,
6754
#ifdef HAS_AUDIO
6755
    QEMU_OPTION_audio_help,
6756
    QEMU_OPTION_soundhw,
6757
#endif
6758

    
6759
    QEMU_OPTION_net,
6760
    QEMU_OPTION_tftp,
6761
    QEMU_OPTION_bootp,
6762
    QEMU_OPTION_smb,
6763
    QEMU_OPTION_redir,
6764

    
6765
    QEMU_OPTION_kernel,
6766
    QEMU_OPTION_append,
6767
    QEMU_OPTION_initrd,
6768

    
6769
    QEMU_OPTION_S,
6770
    QEMU_OPTION_s,
6771
    QEMU_OPTION_p,
6772
    QEMU_OPTION_d,
6773
    QEMU_OPTION_hdachs,
6774
    QEMU_OPTION_L,
6775
    QEMU_OPTION_no_code_copy,
6776
    QEMU_OPTION_k,
6777
    QEMU_OPTION_localtime,
6778
    QEMU_OPTION_cirrusvga,
6779
    QEMU_OPTION_vmsvga,
6780
    QEMU_OPTION_g,
6781
    QEMU_OPTION_std_vga,
6782
    QEMU_OPTION_echr,
6783
    QEMU_OPTION_monitor,
6784
    QEMU_OPTION_serial,
6785
    QEMU_OPTION_parallel,
6786
    QEMU_OPTION_loadvm,
6787
    QEMU_OPTION_full_screen,
6788
    QEMU_OPTION_no_frame,
6789
    QEMU_OPTION_alt_grab,
6790
    QEMU_OPTION_no_quit,
6791
    QEMU_OPTION_pidfile,
6792
    QEMU_OPTION_no_kqemu,
6793
    QEMU_OPTION_kernel_kqemu,
6794
    QEMU_OPTION_win2k_hack,
6795
    QEMU_OPTION_usb,
6796
    QEMU_OPTION_usbdevice,
6797
    QEMU_OPTION_smp,
6798
    QEMU_OPTION_vnc,
6799
    QEMU_OPTION_no_acpi,
6800
    QEMU_OPTION_no_reboot,
6801
    QEMU_OPTION_show_cursor,
6802
    QEMU_OPTION_daemonize,
6803
    QEMU_OPTION_option_rom,
6804
    QEMU_OPTION_semihosting,
6805
    QEMU_OPTION_name,
6806
    QEMU_OPTION_prom_env,
6807
    QEMU_OPTION_old_param,
6808
};
6809

    
6810
typedef struct QEMUOption {
6811
    const char *name;
6812
    int flags;
6813
    int index;
6814
} QEMUOption;
6815

    
6816
const QEMUOption qemu_options[] = {
6817
    { "h", 0, QEMU_OPTION_h },
6818
    { "help", 0, QEMU_OPTION_h },
6819

    
6820
    { "M", HAS_ARG, QEMU_OPTION_M },
6821
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6822
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6823
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6824
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6825
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6826
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6827
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6828
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6829
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6830
    { "sd", HAS_ARG, QEMU_OPTION_sd },
6831
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6832
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6833
    { "snapshot", 0, QEMU_OPTION_snapshot },
6834
#ifdef TARGET_I386
6835
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6836
#endif
6837
    { "m", HAS_ARG, QEMU_OPTION_m },
6838
    { "nographic", 0, QEMU_OPTION_nographic },
6839
    { "portrait", 0, QEMU_OPTION_portrait },
6840
    { "k", HAS_ARG, QEMU_OPTION_k },
6841
#ifdef HAS_AUDIO
6842
    { "audio-help", 0, QEMU_OPTION_audio_help },
6843
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6844
#endif
6845

    
6846
    { "net", HAS_ARG, QEMU_OPTION_net},
6847
#ifdef CONFIG_SLIRP
6848
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6849
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6850
#ifndef _WIN32
6851
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6852
#endif
6853
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6854
#endif
6855

    
6856
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6857
    { "append", HAS_ARG, QEMU_OPTION_append },
6858
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6859

    
6860
    { "S", 0, QEMU_OPTION_S },
6861
    { "s", 0, QEMU_OPTION_s },
6862
    { "p", HAS_ARG, QEMU_OPTION_p },
6863
    { "d", HAS_ARG, QEMU_OPTION_d },
6864
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6865
    { "L", HAS_ARG, QEMU_OPTION_L },
6866
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6867
#ifdef USE_KQEMU
6868
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6869
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6870
#endif
6871
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6872
    { "g", 1, QEMU_OPTION_g },
6873
#endif
6874
    { "localtime", 0, QEMU_OPTION_localtime },
6875
    { "std-vga", 0, QEMU_OPTION_std_vga },
6876
    { "echr", HAS_ARG, QEMU_OPTION_echr },
6877
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6878
    { "serial", HAS_ARG, QEMU_OPTION_serial },
6879
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
6880
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6881
    { "full-screen", 0, QEMU_OPTION_full_screen },
6882
#ifdef CONFIG_SDL
6883
    { "no-frame", 0, QEMU_OPTION_no_frame },
6884
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
6885
    { "no-quit", 0, QEMU_OPTION_no_quit },
6886
#endif
6887
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6888
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6889
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6890
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6891
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6892

    
6893
    /* temporary options */
6894
    { "usb", 0, QEMU_OPTION_usb },
6895
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6896
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6897
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6898
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
6899
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
6900
    { "daemonize", 0, QEMU_OPTION_daemonize },
6901
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6902
#if defined(TARGET_ARM) || defined(TARGET_M68K)
6903
    { "semihosting", 0, QEMU_OPTION_semihosting },
6904
#endif
6905
    { "name", HAS_ARG, QEMU_OPTION_name },
6906
#if defined(TARGET_SPARC)
6907
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6908
#endif
6909
#if defined(TARGET_ARM)
6910
    { "old-param", 0, QEMU_OPTION_old_param },
6911
#endif
6912
    { NULL },
6913
};
6914

    
6915
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6916

    
6917
/* this stack is only used during signal handling */
6918
#define SIGNAL_STACK_SIZE 32768
6919

    
6920
static uint8_t *signal_stack;
6921

    
6922
#endif
6923

    
6924
/* password input */
6925

    
6926
int qemu_key_check(BlockDriverState *bs, const char *name)
6927
{
6928
    char password[256];
6929
    int i;
6930

    
6931
    if (!bdrv_is_encrypted(bs))
6932
        return 0;
6933

    
6934
    term_printf("%s is encrypted.\n", name);
6935
    for(i = 0; i < 3; i++) {
6936
        monitor_readline("Password: ", 1, password, sizeof(password));
6937
        if (bdrv_set_key(bs, password) == 0)
6938
            return 0;
6939
        term_printf("invalid password\n");
6940
    }
6941
    return -EPERM;
6942
}
6943

    
6944
static BlockDriverState *get_bdrv(int index)
6945
{
6946
    BlockDriverState *bs;
6947

    
6948
    if (index < 4) {
6949
        bs = bs_table[index];
6950
    } else if (index < 6) {
6951
        bs = fd_table[index - 4];
6952
    } else {
6953
        bs = NULL;
6954
    }
6955
    return bs;
6956
}
6957

    
6958
static void read_passwords(void)
6959
{
6960
    BlockDriverState *bs;
6961
    int i;
6962

    
6963
    for(i = 0; i < 6; i++) {
6964
        bs = get_bdrv(i);
6965
        if (bs)
6966
            qemu_key_check(bs, bdrv_get_device_name(bs));
6967
    }
6968
}
6969

    
6970
/* XXX: currently we cannot use simultaneously different CPUs */
6971
void register_machines(void)
6972
{
6973
#if defined(TARGET_I386)
6974
    qemu_register_machine(&pc_machine);
6975
    qemu_register_machine(&isapc_machine);
6976
#elif defined(TARGET_PPC)
6977
    qemu_register_machine(&heathrow_machine);
6978
    qemu_register_machine(&core99_machine);
6979
    qemu_register_machine(&prep_machine);
6980
    qemu_register_machine(&ref405ep_machine);
6981
    qemu_register_machine(&taihu_machine);
6982
#elif defined(TARGET_MIPS)
6983
    qemu_register_machine(&mips_machine);
6984
    qemu_register_machine(&mips_malta_machine);
6985
    qemu_register_machine(&mips_pica61_machine);
6986
#elif defined(TARGET_SPARC)
6987
#ifdef TARGET_SPARC64
6988
    qemu_register_machine(&sun4u_machine);
6989
#else
6990
    qemu_register_machine(&ss5_machine);
6991
    qemu_register_machine(&ss10_machine);
6992
#endif
6993
#elif defined(TARGET_ARM)
6994
    qemu_register_machine(&integratorcp_machine);
6995
    qemu_register_machine(&versatilepb_machine);
6996
    qemu_register_machine(&versatileab_machine);
6997
    qemu_register_machine(&realview_machine);
6998
    qemu_register_machine(&akitapda_machine);
6999
    qemu_register_machine(&spitzpda_machine);
7000
    qemu_register_machine(&borzoipda_machine);
7001
    qemu_register_machine(&terrierpda_machine);
7002
    qemu_register_machine(&palmte_machine);
7003
#elif defined(TARGET_SH4)
7004
    qemu_register_machine(&shix_machine);
7005
#elif defined(TARGET_ALPHA)
7006
    /* XXX: TODO */
7007
#elif defined(TARGET_M68K)
7008
    qemu_register_machine(&mcf5208evb_machine);
7009
    qemu_register_machine(&an5206_machine);
7010
#else
7011
#error unsupported CPU
7012
#endif
7013
}
7014

    
7015
#ifdef HAS_AUDIO
7016
struct soundhw soundhw[] = {
7017
#ifdef HAS_AUDIO_CHOICE
7018
#ifdef TARGET_I386
7019
    {
7020
        "pcspk",
7021
        "PC speaker",
7022
        0,
7023
        1,
7024
        { .init_isa = pcspk_audio_init }
7025
    },
7026
#endif
7027
    {
7028
        "sb16",
7029
        "Creative Sound Blaster 16",
7030
        0,
7031
        1,
7032
        { .init_isa = SB16_init }
7033
    },
7034

    
7035
#ifdef CONFIG_ADLIB
7036
    {
7037
        "adlib",
7038
#ifdef HAS_YMF262
7039
        "Yamaha YMF262 (OPL3)",
7040
#else
7041
        "Yamaha YM3812 (OPL2)",
7042
#endif
7043
        0,
7044
        1,
7045
        { .init_isa = Adlib_init }
7046
    },
7047
#endif
7048

    
7049
#ifdef CONFIG_GUS
7050
    {
7051
        "gus",
7052
        "Gravis Ultrasound GF1",
7053
        0,
7054
        1,
7055
        { .init_isa = GUS_init }
7056
    },
7057
#endif
7058

    
7059
    {
7060
        "es1370",
7061
        "ENSONIQ AudioPCI ES1370",
7062
        0,
7063
        0,
7064
        { .init_pci = es1370_init }
7065
    },
7066
#endif
7067

    
7068
    { NULL, NULL, 0, 0, { NULL } }
7069
};
7070

    
7071
static void select_soundhw (const char *optarg)
7072
{
7073
    struct soundhw *c;
7074

    
7075
    if (*optarg == '?') {
7076
    show_valid_cards:
7077

    
7078
        printf ("Valid sound card names (comma separated):\n");
7079
        for (c = soundhw; c->name; ++c) {
7080
            printf ("%-11s %s\n", c->name, c->descr);
7081
        }
7082
        printf ("\n-soundhw all will enable all of the above\n");
7083
        exit (*optarg != '?');
7084
    }
7085
    else {
7086
        size_t l;
7087
        const char *p;
7088
        char *e;
7089
        int bad_card = 0;
7090

    
7091
        if (!strcmp (optarg, "all")) {
7092
            for (c = soundhw; c->name; ++c) {
7093
                c->enabled = 1;
7094
            }
7095
            return;
7096
        }
7097

    
7098
        p = optarg;
7099
        while (*p) {
7100
            e = strchr (p, ',');
7101
            l = !e ? strlen (p) : (size_t) (e - p);
7102

    
7103
            for (c = soundhw; c->name; ++c) {
7104
                if (!strncmp (c->name, p, l)) {
7105
                    c->enabled = 1;
7106
                    break;
7107
                }
7108
            }
7109

    
7110
            if (!c->name) {
7111
                if (l > 80) {
7112
                    fprintf (stderr,
7113
                             "Unknown sound card name (too big to show)\n");
7114
                }
7115
                else {
7116
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
7117
                             (int) l, p);
7118
                }
7119
                bad_card = 1;
7120
            }
7121
            p += l + (e != NULL);
7122
        }
7123

    
7124
        if (bad_card)
7125
            goto show_valid_cards;
7126
    }
7127
}
7128
#endif
7129

    
7130
#ifdef _WIN32
7131
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7132
{
7133
    exit(STATUS_CONTROL_C_EXIT);
7134
    return TRUE;
7135
}
7136
#endif
7137

    
7138
#define MAX_NET_CLIENTS 32
7139

    
7140
int main(int argc, char **argv)
7141
{
7142
#ifdef CONFIG_GDBSTUB
7143
    int use_gdbstub;
7144
    const char *gdbstub_port;
7145
#endif
7146
    int i, cdrom_index, pflash_index;
7147
    int snapshot, linux_boot;
7148
    const char *initrd_filename;
7149
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7150
    const char *pflash_filename[MAX_PFLASH];
7151
    const char *sd_filename;
7152
    const char *mtd_filename;
7153
    const char *kernel_filename, *kernel_cmdline;
7154
    DisplayState *ds = &display_state;
7155
    int cyls, heads, secs, translation;
7156
    char net_clients[MAX_NET_CLIENTS][256];
7157
    int nb_net_clients;
7158
    int optind;
7159
    const char *r, *optarg;
7160
    CharDriverState *monitor_hd;
7161
    char monitor_device[128];
7162
    char serial_devices[MAX_SERIAL_PORTS][128];
7163
    int serial_device_index;
7164
    char parallel_devices[MAX_PARALLEL_PORTS][128];
7165
    int parallel_device_index;
7166
    const char *loadvm = NULL;
7167
    QEMUMachine *machine;
7168
    const char *cpu_model;
7169
    char usb_devices[MAX_USB_CMDLINE][128];
7170
    int usb_devices_index;
7171
    int fds[2];
7172
    const char *pid_file = NULL;
7173
    VLANState *vlan;
7174

    
7175
    LIST_INIT (&vm_change_state_head);
7176
#ifndef _WIN32
7177
    {
7178
        struct sigaction act;
7179
        sigfillset(&act.sa_mask);
7180
        act.sa_flags = 0;
7181
        act.sa_handler = SIG_IGN;
7182
        sigaction(SIGPIPE, &act, NULL);
7183
    }
7184
#else
7185
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7186
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
7187
       QEMU to run on a single CPU */
7188
    {
7189
        HANDLE h;
7190
        DWORD mask, smask;
7191
        int i;
7192
        h = GetCurrentProcess();
7193
        if (GetProcessAffinityMask(h, &mask, &smask)) {
7194
            for(i = 0; i < 32; i++) {
7195
                if (mask & (1 << i))
7196
                    break;
7197
            }
7198
            if (i != 32) {
7199
                mask = 1 << i;
7200
                SetProcessAffinityMask(h, mask);
7201
            }
7202
        }
7203
    }
7204
#endif
7205

    
7206
    register_machines();
7207
    machine = first_machine;
7208
    cpu_model = NULL;
7209
    initrd_filename = NULL;
7210
    for(i = 0; i < MAX_FD; i++)
7211
        fd_filename[i] = NULL;
7212
    for(i = 0; i < MAX_DISKS; i++)
7213
        hd_filename[i] = NULL;
7214
    for(i = 0; i < MAX_PFLASH; i++)
7215
        pflash_filename[i] = NULL;
7216
    pflash_index = 0;
7217
    sd_filename = NULL;
7218
    mtd_filename = NULL;
7219
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7220
    vga_ram_size = VGA_RAM_SIZE;
7221
#ifdef CONFIG_GDBSTUB
7222
    use_gdbstub = 0;
7223
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
7224
#endif
7225
    snapshot = 0;
7226
    nographic = 0;
7227
    kernel_filename = NULL;
7228
    kernel_cmdline = "";
7229
#ifdef TARGET_PPC
7230
    cdrom_index = 1;
7231
#else
7232
    cdrom_index = 2;
7233
#endif
7234
    cyls = heads = secs = 0;
7235
    translation = BIOS_ATA_TRANSLATION_AUTO;
7236
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7237

    
7238
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7239
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
7240
        serial_devices[i][0] = '\0';
7241
    serial_device_index = 0;
7242
    
7243
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7244
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7245
        parallel_devices[i][0] = '\0';
7246
    parallel_device_index = 0;
7247
    
7248
    usb_devices_index = 0;
7249
    
7250
    nb_net_clients = 0;
7251

    
7252
    nb_nics = 0;
7253
    /* default mac address of the first network interface */
7254
    
7255
    optind = 1;
7256
    for(;;) {
7257
        if (optind >= argc)
7258
            break;
7259
        r = argv[optind];
7260
        if (r[0] != '-') {
7261
            hd_filename[0] = argv[optind++];
7262
        } else {
7263
            const QEMUOption *popt;
7264

    
7265
            optind++;
7266
            /* Treat --foo the same as -foo.  */
7267
            if (r[1] == '-')
7268
                r++;
7269
            popt = qemu_options;
7270
            for(;;) {
7271
                if (!popt->name) {
7272
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
7273
                            argv[0], r);
7274
                    exit(1);
7275
                }
7276
                if (!strcmp(popt->name, r + 1))
7277
                    break;
7278
                popt++;
7279
            }
7280
            if (popt->flags & HAS_ARG) {
7281
                if (optind >= argc) {
7282
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
7283
                            argv[0], r);
7284
                    exit(1);
7285
                }
7286
                optarg = argv[optind++];
7287
            } else {
7288
                optarg = NULL;
7289
            }
7290

    
7291
            switch(popt->index) {
7292
            case QEMU_OPTION_M:
7293
                machine = find_machine(optarg);
7294
                if (!machine) {
7295
                    QEMUMachine *m;
7296
                    printf("Supported machines are:\n");
7297
                    for(m = first_machine; m != NULL; m = m->next) {
7298
                        printf("%-10s %s%s\n",
7299
                               m->name, m->desc, 
7300
                               m == first_machine ? " (default)" : "");
7301
                    }
7302
                    exit(*optarg != '?');
7303
                }
7304
                break;
7305
            case QEMU_OPTION_cpu:
7306
                /* hw initialization will check this */
7307
                if (*optarg == '?') {
7308
#if defined(TARGET_PPC)
7309
                    ppc_cpu_list(stdout, &fprintf);
7310
#elif defined(TARGET_ARM)
7311
                    arm_cpu_list();
7312
#elif defined(TARGET_MIPS)
7313
                    mips_cpu_list(stdout, &fprintf);
7314
#elif defined(TARGET_SPARC)
7315
                    sparc_cpu_list(stdout, &fprintf);
7316
#endif
7317
                    exit(0);
7318
                } else {
7319
                    cpu_model = optarg;
7320
                }
7321
                break;
7322
            case QEMU_OPTION_initrd:
7323
                initrd_filename = optarg;
7324
                break;
7325
            case QEMU_OPTION_hda:
7326
            case QEMU_OPTION_hdb:
7327
            case QEMU_OPTION_hdc:
7328
            case QEMU_OPTION_hdd:
7329
                {
7330
                    int hd_index;
7331
                    hd_index = popt->index - QEMU_OPTION_hda;
7332
                    hd_filename[hd_index] = optarg;
7333
                    if (hd_index == cdrom_index)
7334
                        cdrom_index = -1;
7335
                }
7336
                break;
7337
            case QEMU_OPTION_mtdblock:
7338
                mtd_filename = optarg;
7339
                break;
7340
            case QEMU_OPTION_sd:
7341
                sd_filename = optarg;
7342
                break;
7343
            case QEMU_OPTION_pflash:
7344
                if (pflash_index >= MAX_PFLASH) {
7345
                    fprintf(stderr, "qemu: too many parallel flash images\n");
7346
                    exit(1);
7347
                }
7348
                pflash_filename[pflash_index++] = optarg;
7349
                break;
7350
            case QEMU_OPTION_snapshot:
7351
                snapshot = 1;
7352
                break;
7353
            case QEMU_OPTION_hdachs:
7354
                {
7355
                    const char *p;
7356
                    p = optarg;
7357
                    cyls = strtol(p, (char **)&p, 0);
7358
                    if (cyls < 1 || cyls > 16383)
7359
                        goto chs_fail;
7360
                    if (*p != ',')
7361
                        goto chs_fail;
7362
                    p++;
7363
                    heads = strtol(p, (char **)&p, 0);
7364
                    if (heads < 1 || heads > 16)
7365
                        goto chs_fail;
7366
                    if (*p != ',')
7367
                        goto chs_fail;
7368
                    p++;
7369
                    secs = strtol(p, (char **)&p, 0);
7370
                    if (secs < 1 || secs > 63)
7371
                        goto chs_fail;
7372
                    if (*p == ',') {
7373
                        p++;
7374
                        if (!strcmp(p, "none"))
7375
                            translation = BIOS_ATA_TRANSLATION_NONE;
7376
                        else if (!strcmp(p, "lba"))
7377
                            translation = BIOS_ATA_TRANSLATION_LBA;
7378
                        else if (!strcmp(p, "auto"))
7379
                            translation = BIOS_ATA_TRANSLATION_AUTO;
7380
                        else
7381
                            goto chs_fail;
7382
                    } else if (*p != '\0') {
7383
                    chs_fail:
7384
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
7385
                        exit(1);
7386
                    }
7387
                }
7388
                break;
7389
            case QEMU_OPTION_nographic:
7390
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7391
                pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7392
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7393
                nographic = 1;
7394
                break;
7395
            case QEMU_OPTION_portrait:
7396
                graphic_rotate = 1;
7397
                break;
7398
            case QEMU_OPTION_kernel:
7399
                kernel_filename = optarg;
7400
                break;
7401
            case QEMU_OPTION_append:
7402
                kernel_cmdline = optarg;
7403
                break;
7404
            case QEMU_OPTION_cdrom:
7405
                if (cdrom_index >= 0) {
7406
                    hd_filename[cdrom_index] = optarg;
7407
                }
7408
                break;
7409
            case QEMU_OPTION_boot:
7410
                boot_device = optarg[0];
7411
                if (boot_device != 'a' && 
7412
#if defined(TARGET_SPARC) || defined(TARGET_I386)
7413
                    // Network boot
7414
                    boot_device != 'n' &&
7415
#endif
7416
                    boot_device != 'c' && boot_device != 'd') {
7417
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7418
                    exit(1);
7419
                }
7420
                break;
7421
            case QEMU_OPTION_fda:
7422
                fd_filename[0] = optarg;
7423
                break;
7424
            case QEMU_OPTION_fdb:
7425
                fd_filename[1] = optarg;
7426
                break;
7427
#ifdef TARGET_I386
7428
            case QEMU_OPTION_no_fd_bootchk:
7429
                fd_bootchk = 0;
7430
                break;
7431
#endif
7432
            case QEMU_OPTION_no_code_copy:
7433
                code_copy_enabled = 0;
7434
                break;
7435
            case QEMU_OPTION_net:
7436
                if (nb_net_clients >= MAX_NET_CLIENTS) {
7437
                    fprintf(stderr, "qemu: too many network clients\n");
7438
                    exit(1);
7439
                }
7440
                pstrcpy(net_clients[nb_net_clients],
7441
                        sizeof(net_clients[0]),
7442
                        optarg);
7443
                nb_net_clients++;
7444
                break;
7445
#ifdef CONFIG_SLIRP
7446
            case QEMU_OPTION_tftp:
7447
                tftp_prefix = optarg;
7448
                break;
7449
            case QEMU_OPTION_bootp:
7450
                bootp_filename = optarg;
7451
                break;
7452
#ifndef _WIN32
7453
            case QEMU_OPTION_smb:
7454
                net_slirp_smb(optarg);
7455
                break;
7456
#endif
7457
            case QEMU_OPTION_redir:
7458
                net_slirp_redir(optarg);                
7459
                break;
7460
#endif
7461
#ifdef HAS_AUDIO
7462
            case QEMU_OPTION_audio_help:
7463
                AUD_help ();
7464
                exit (0);
7465
                break;
7466
            case QEMU_OPTION_soundhw:
7467
                select_soundhw (optarg);
7468
                break;
7469
#endif
7470
            case QEMU_OPTION_h:
7471
                help(0);
7472
                break;
7473
            case QEMU_OPTION_m:
7474
                ram_size = atoi(optarg) * 1024 * 1024;
7475
                if (ram_size <= 0)
7476
                    help(1);
7477
                if (ram_size > PHYS_RAM_MAX_SIZE) {
7478
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7479
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
7480
                    exit(1);
7481
                }
7482
                break;
7483
            case QEMU_OPTION_d:
7484
                {
7485
                    int mask;
7486
                    CPULogItem *item;
7487
                    
7488
                    mask = cpu_str_to_log_mask(optarg);
7489
                    if (!mask) {
7490
                        printf("Log items (comma separated):\n");
7491
                    for(item = cpu_log_items; item->mask != 0; item++) {
7492
                        printf("%-10s %s\n", item->name, item->help);
7493
                    }
7494
                    exit(1);
7495
                    }
7496
                    cpu_set_log(mask);
7497
                }
7498
                break;
7499
#ifdef CONFIG_GDBSTUB
7500
            case QEMU_OPTION_s:
7501
                use_gdbstub = 1;
7502
                break;
7503
            case QEMU_OPTION_p:
7504
                gdbstub_port = optarg;
7505
                break;
7506
#endif
7507
            case QEMU_OPTION_L:
7508
                bios_dir = optarg;
7509
                break;
7510
            case QEMU_OPTION_S:
7511
                autostart = 0;
7512
                break;
7513
            case QEMU_OPTION_k:
7514
                keyboard_layout = optarg;
7515
                break;
7516
            case QEMU_OPTION_localtime:
7517
                rtc_utc = 0;
7518
                break;
7519
            case QEMU_OPTION_cirrusvga:
7520
                cirrus_vga_enabled = 1;
7521
                vmsvga_enabled = 0;
7522
                break;
7523
            case QEMU_OPTION_vmsvga:
7524
                cirrus_vga_enabled = 0;
7525
                vmsvga_enabled = 1;
7526
                break;
7527
            case QEMU_OPTION_std_vga:
7528
                cirrus_vga_enabled = 0;
7529
                vmsvga_enabled = 0;
7530
                break;
7531
            case QEMU_OPTION_g:
7532
                {
7533
                    const char *p;
7534
                    int w, h, depth;
7535
                    p = optarg;
7536
                    w = strtol(p, (char **)&p, 10);
7537
                    if (w <= 0) {
7538
                    graphic_error:
7539
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
7540
                        exit(1);
7541
                    }
7542
                    if (*p != 'x')
7543
                        goto graphic_error;
7544
                    p++;
7545
                    h = strtol(p, (char **)&p, 10);
7546
                    if (h <= 0)
7547
                        goto graphic_error;
7548
                    if (*p == 'x') {
7549
                        p++;
7550
                        depth = strtol(p, (char **)&p, 10);
7551
                        if (depth != 8 && depth != 15 && depth != 16 && 
7552
                            depth != 24 && depth != 32)
7553
                            goto graphic_error;
7554
                    } else if (*p == '\0') {
7555
                        depth = graphic_depth;
7556
                    } else {
7557
                        goto graphic_error;
7558
                    }
7559
                    
7560
                    graphic_width = w;
7561
                    graphic_height = h;
7562
                    graphic_depth = depth;
7563
                }
7564
                break;
7565
            case QEMU_OPTION_echr:
7566
                {
7567
                    char *r;
7568
                    term_escape_char = strtol(optarg, &r, 0);
7569
                    if (r == optarg)
7570
                        printf("Bad argument to echr\n");
7571
                    break;
7572
                }
7573
            case QEMU_OPTION_monitor:
7574
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7575
                break;
7576
            case QEMU_OPTION_serial:
7577
                if (serial_device_index >= MAX_SERIAL_PORTS) {
7578
                    fprintf(stderr, "qemu: too many serial ports\n");
7579
                    exit(1);
7580
                }
7581
                pstrcpy(serial_devices[serial_device_index], 
7582
                        sizeof(serial_devices[0]), optarg);
7583
                serial_device_index++;
7584
                break;
7585
            case QEMU_OPTION_parallel:
7586
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7587
                    fprintf(stderr, "qemu: too many parallel ports\n");
7588
                    exit(1);
7589
                }
7590
                pstrcpy(parallel_devices[parallel_device_index], 
7591
                        sizeof(parallel_devices[0]), optarg);
7592
                parallel_device_index++;
7593
                break;
7594
            case QEMU_OPTION_loadvm:
7595
                loadvm = optarg;
7596
                break;
7597
            case QEMU_OPTION_full_screen:
7598
                full_screen = 1;
7599
                break;
7600
#ifdef CONFIG_SDL
7601
            case QEMU_OPTION_no_frame:
7602
                no_frame = 1;
7603
                break;
7604
            case QEMU_OPTION_alt_grab:
7605
                alt_grab = 1;
7606
                break;
7607
            case QEMU_OPTION_no_quit:
7608
                no_quit = 1;
7609
                break;
7610
#endif
7611
            case QEMU_OPTION_pidfile:
7612
                pid_file = optarg;
7613
                break;
7614
#ifdef TARGET_I386
7615
            case QEMU_OPTION_win2k_hack:
7616
                win2k_install_hack = 1;
7617
                break;
7618
#endif
7619
#ifdef USE_KQEMU
7620
            case QEMU_OPTION_no_kqemu:
7621
                kqemu_allowed = 0;
7622
                break;
7623
            case QEMU_OPTION_kernel_kqemu:
7624
                kqemu_allowed = 2;
7625
                break;
7626
#endif
7627
            case QEMU_OPTION_usb:
7628
                usb_enabled = 1;
7629
                break;
7630
            case QEMU_OPTION_usbdevice:
7631
                usb_enabled = 1;
7632
                if (usb_devices_index >= MAX_USB_CMDLINE) {
7633
                    fprintf(stderr, "Too many USB devices\n");
7634
                    exit(1);
7635
                }
7636
                pstrcpy(usb_devices[usb_devices_index],
7637
                        sizeof(usb_devices[usb_devices_index]),
7638
                        optarg);
7639
                usb_devices_index++;
7640
                break;
7641
            case QEMU_OPTION_smp:
7642
                smp_cpus = atoi(optarg);
7643
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7644
                    fprintf(stderr, "Invalid number of CPUs\n");
7645
                    exit(1);
7646
                }
7647
                break;
7648
            case QEMU_OPTION_vnc:
7649
                vnc_display = optarg;
7650
                break;
7651
            case QEMU_OPTION_no_acpi:
7652
                acpi_enabled = 0;
7653
                break;
7654
            case QEMU_OPTION_no_reboot:
7655
                no_reboot = 1;
7656
                break;
7657
            case QEMU_OPTION_show_cursor:
7658
                cursor_hide = 0;
7659
                break;
7660
            case QEMU_OPTION_daemonize:
7661
                daemonize = 1;
7662
                break;
7663
            case QEMU_OPTION_option_rom:
7664
                if (nb_option_roms >= MAX_OPTION_ROMS) {
7665
                    fprintf(stderr, "Too many option ROMs\n");
7666
                    exit(1);
7667
                }
7668
                option_rom[nb_option_roms] = optarg;
7669
                nb_option_roms++;
7670
                break;
7671
            case QEMU_OPTION_semihosting:
7672
                semihosting_enabled = 1;
7673
                break;
7674
            case QEMU_OPTION_name:
7675
                qemu_name = optarg;
7676
                break;
7677
#ifdef TARGET_SPARC
7678
            case QEMU_OPTION_prom_env:
7679
                if (nb_prom_envs >= MAX_PROM_ENVS) {
7680
                    fprintf(stderr, "Too many prom variables\n");
7681
                    exit(1);
7682
                }
7683
                prom_envs[nb_prom_envs] = optarg;
7684
                nb_prom_envs++;
7685
                break;
7686
#endif
7687
#ifdef TARGET_ARM
7688
            case QEMU_OPTION_old_param:
7689
                old_param = 1;
7690
#endif
7691
            }
7692
        }
7693
    }
7694

    
7695
#ifndef _WIN32
7696
    if (daemonize && !nographic && vnc_display == NULL) {
7697
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7698
        daemonize = 0;
7699
    }
7700

    
7701
    if (daemonize) {
7702
        pid_t pid;
7703

    
7704
        if (pipe(fds) == -1)
7705
            exit(1);
7706

    
7707
        pid = fork();
7708
        if (pid > 0) {
7709
            uint8_t status;
7710
            ssize_t len;
7711

    
7712
            close(fds[1]);
7713

    
7714
        again:
7715
            len = read(fds[0], &status, 1);
7716
            if (len == -1 && (errno == EINTR))
7717
                goto again;
7718

    
7719
            if (len != 1)
7720
                exit(1);
7721
            else if (status == 1) {
7722
                fprintf(stderr, "Could not acquire pidfile\n");
7723
                exit(1);
7724
            } else
7725
                exit(0);
7726
        } else if (pid < 0)
7727
            exit(1);
7728

    
7729
        setsid();
7730

    
7731
        pid = fork();
7732
        if (pid > 0)
7733
            exit(0);
7734
        else if (pid < 0)
7735
            exit(1);
7736

    
7737
        umask(027);
7738
        chdir("/");
7739

    
7740
        signal(SIGTSTP, SIG_IGN);
7741
        signal(SIGTTOU, SIG_IGN);
7742
        signal(SIGTTIN, SIG_IGN);
7743
    }
7744
#endif
7745

    
7746
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7747
        if (daemonize) {
7748
            uint8_t status = 1;
7749
            write(fds[1], &status, 1);
7750
        } else
7751
            fprintf(stderr, "Could not acquire pid file\n");
7752
        exit(1);
7753
    }
7754

    
7755
#ifdef USE_KQEMU
7756
    if (smp_cpus > 1)
7757
        kqemu_allowed = 0;
7758
#endif
7759
    linux_boot = (kernel_filename != NULL);
7760

    
7761
    if (!linux_boot &&
7762
        boot_device != 'n' &&
7763
        hd_filename[0] == '\0' && 
7764
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7765
        fd_filename[0] == '\0')
7766
        help(1);
7767

    
7768
    /* boot to floppy or the default cd if no hard disk defined yet */
7769
    if (hd_filename[0] == '\0' && boot_device == 'c') {
7770
        if (fd_filename[0] != '\0')
7771
            boot_device = 'a';
7772
        else
7773
            boot_device = 'd';
7774
    }
7775

    
7776
    setvbuf(stdout, NULL, _IOLBF, 0);
7777
    
7778
    init_timers();
7779
    init_timer_alarm();
7780
    qemu_aio_init();
7781

    
7782
#ifdef _WIN32
7783
    socket_init();
7784
#endif
7785

    
7786
    /* init network clients */
7787
    if (nb_net_clients == 0) {
7788
        /* if no clients, we use a default config */
7789
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
7790
                "nic");
7791
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
7792
                "user");
7793
        nb_net_clients = 2;
7794
    }
7795

    
7796
    for(i = 0;i < nb_net_clients; i++) {
7797
        if (net_client_init(net_clients[i]) < 0)
7798
            exit(1);
7799
    }
7800
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7801
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7802
            continue;
7803
        if (vlan->nb_guest_devs == 0) {
7804
            fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7805
            exit(1);
7806
        }
7807
        if (vlan->nb_host_devs == 0)
7808
            fprintf(stderr,
7809
                    "Warning: vlan %d is not connected to host network\n",
7810
                    vlan->id);
7811
    }
7812

    
7813
#ifdef TARGET_I386
7814
    if (boot_device == 'n') {
7815
        for (i = 0; i < nb_nics; i++) {
7816
            const char *model = nd_table[i].model;
7817
            char buf[1024];
7818
            if (model == NULL)
7819
                model = "ne2k_pci";
7820
            snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7821
            if (get_image_size(buf) > 0) {
7822
                option_rom[nb_option_roms] = strdup(buf);
7823
                nb_option_roms++;
7824
                break;
7825
            }
7826
        }
7827
        if (i == nb_nics) {
7828
            fprintf(stderr, "No valid PXE rom found for network device\n");
7829
            exit(1);
7830
        }
7831
        boot_device = 'c'; /* to prevent confusion by the BIOS */
7832
    }
7833
#endif
7834

    
7835
    /* init the memory */
7836
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7837

    
7838
    phys_ram_base = qemu_vmalloc(phys_ram_size);
7839
    if (!phys_ram_base) {
7840
        fprintf(stderr, "Could not allocate physical memory\n");
7841
        exit(1);
7842
    }
7843

    
7844
    /* we always create the cdrom drive, even if no disk is there */
7845
    bdrv_init();
7846
    if (cdrom_index >= 0) {
7847
        bs_table[cdrom_index] = bdrv_new("cdrom");
7848
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7849
    }
7850

    
7851
    /* open the virtual block devices */
7852
    for(i = 0; i < MAX_DISKS; i++) {
7853
        if (hd_filename[i]) {
7854
            if (!bs_table[i]) {
7855
                char buf[64];
7856
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7857
                bs_table[i] = bdrv_new(buf);
7858
            }
7859
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7860
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7861
                        hd_filename[i]);
7862
                exit(1);
7863
            }
7864
            if (i == 0 && cyls != 0) {
7865
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7866
                bdrv_set_translation_hint(bs_table[i], translation);
7867
            }
7868
        }
7869
    }
7870

    
7871
    /* we always create at least one floppy disk */
7872
    fd_table[0] = bdrv_new("fda");
7873
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7874

    
7875
    for(i = 0; i < MAX_FD; i++) {
7876
        if (fd_filename[i]) {
7877
            if (!fd_table[i]) {
7878
                char buf[64];
7879
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7880
                fd_table[i] = bdrv_new(buf);
7881
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7882
            }
7883
            if (fd_filename[i][0] != '\0') {
7884
                if (bdrv_open(fd_table[i], fd_filename[i],
7885
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7886
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7887
                            fd_filename[i]);
7888
                    exit(1);
7889
                }
7890
            }
7891
        }
7892
    }
7893

    
7894
    /* Open the virtual parallel flash block devices */
7895
    for(i = 0; i < MAX_PFLASH; i++) {
7896
        if (pflash_filename[i]) {
7897
            if (!pflash_table[i]) {
7898
                char buf[64];
7899
                snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7900
                pflash_table[i] = bdrv_new(buf);
7901
            }
7902
            if (bdrv_open(pflash_table[i], pflash_filename[i],
7903
                          snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7904
                fprintf(stderr, "qemu: could not open flash image '%s'\n",
7905
                        pflash_filename[i]);
7906
                exit(1);
7907
            }
7908
        }
7909
    }
7910

    
7911
    sd_bdrv = bdrv_new ("sd");
7912
    /* FIXME: This isn't really a floppy, but it's a reasonable
7913
       approximation.  */
7914
    bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7915
    if (sd_filename) {
7916
        if (bdrv_open(sd_bdrv, sd_filename,
7917
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7918
            fprintf(stderr, "qemu: could not open SD card image %s\n",
7919
                    sd_filename);
7920
        } else
7921
            qemu_key_check(sd_bdrv, sd_filename);
7922
    }
7923

    
7924
    if (mtd_filename) {
7925
        mtd_bdrv = bdrv_new ("mtd");
7926
        if (bdrv_open(mtd_bdrv, mtd_filename,
7927
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7928
            qemu_key_check(mtd_bdrv, mtd_filename)) {
7929
            fprintf(stderr, "qemu: could not open Flash image %s\n",
7930
                    mtd_filename);
7931
            bdrv_delete(mtd_bdrv);
7932
            mtd_bdrv = 0;
7933
        }
7934
    }
7935

    
7936
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7937
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7938

    
7939
    init_ioports();
7940

    
7941
    /* terminal init */
7942
    memset(&display_state, 0, sizeof(display_state));
7943
    if (nographic) {
7944
        /* nearly nothing to do */
7945
        dumb_display_init(ds);
7946
    } else if (vnc_display != NULL) {
7947
        vnc_display_init(ds, vnc_display);
7948
    } else {
7949
#if defined(CONFIG_SDL)
7950
        sdl_display_init(ds, full_screen, no_frame);
7951
#elif defined(CONFIG_COCOA)
7952
        cocoa_display_init(ds, full_screen);
7953
#endif
7954
    }
7955

    
7956
    /* Maintain compatibility with multiple stdio monitors */
7957
    if (!strcmp(monitor_device,"stdio")) {
7958
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7959
            if (!strcmp(serial_devices[i],"mon:stdio")) {
7960
                monitor_device[0] = '\0';
7961
                break;
7962
            } else if (!strcmp(serial_devices[i],"stdio")) {
7963
                monitor_device[0] = '\0';
7964
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7965
                break;
7966
            }
7967
        }
7968
    }
7969
    if (monitor_device[0] != '\0') {
7970
        monitor_hd = qemu_chr_open(monitor_device);
7971
        if (!monitor_hd) {
7972
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7973
            exit(1);
7974
        }
7975
        monitor_init(monitor_hd, !nographic);
7976
    }
7977

    
7978
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7979
        const char *devname = serial_devices[i];
7980
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7981
            serial_hds[i] = qemu_chr_open(devname);
7982
            if (!serial_hds[i]) {
7983
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7984
                        devname);
7985
                exit(1);
7986
            }
7987
            if (strstart(devname, "vc", 0))
7988
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7989
        }
7990
    }
7991

    
7992
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7993
        const char *devname = parallel_devices[i];
7994
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7995
            parallel_hds[i] = qemu_chr_open(devname);
7996
            if (!parallel_hds[i]) {
7997
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7998
                        devname);
7999
                exit(1);
8000
            }
8001
            if (strstart(devname, "vc", 0))
8002
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8003
        }
8004
    }
8005

    
8006
    machine->init(ram_size, vga_ram_size, boot_device,
8007
                  ds, fd_filename, snapshot,
8008
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8009

    
8010
    /* init USB devices */
8011
    if (usb_enabled) {
8012
        for(i = 0; i < usb_devices_index; i++) {
8013
            if (usb_device_add(usb_devices[i]) < 0) {
8014
                fprintf(stderr, "Warning: could not add USB device %s\n",
8015
                        usb_devices[i]);
8016
            }
8017
        }
8018
    }
8019

    
8020
    if (display_state.dpy_refresh) {
8021
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8022
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8023
    }
8024

    
8025
#ifdef CONFIG_GDBSTUB
8026
    if (use_gdbstub) {
8027
        /* XXX: use standard host:port notation and modify options
8028
           accordingly. */
8029
        if (gdbserver_start(gdbstub_port) < 0) {
8030
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8031
                    gdbstub_port);
8032
            exit(1);
8033
        }
8034
    }
8035
#endif
8036

    
8037
    if (loadvm)
8038
        do_loadvm(loadvm);
8039

    
8040
    {
8041
        /* XXX: simplify init */
8042
        read_passwords();
8043
        if (autostart) {
8044
            vm_start();
8045
        }
8046
    }
8047

    
8048
    if (daemonize) {
8049
        uint8_t status = 0;
8050
        ssize_t len;
8051
        int fd;
8052

    
8053
    again1:
8054
        len = write(fds[1], &status, 1);
8055
        if (len == -1 && (errno == EINTR))
8056
            goto again1;
8057

    
8058
        if (len != 1)
8059
            exit(1);
8060

    
8061
        TFR(fd = open("/dev/null", O_RDWR));
8062
        if (fd == -1)
8063
            exit(1);
8064

    
8065
        dup2(fd, 0);
8066
        dup2(fd, 1);
8067
        dup2(fd, 2);
8068

    
8069
        close(fd);
8070
    }
8071

    
8072
    main_loop();
8073
    quit_timers();
8074
    return 0;
8075
}