Statistics
| Branch: | Revision:

root / vl.c @ 42550fde

History | View | Annotate | Download (189.7 kB)

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

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

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

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

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

    
74
#include "qemu_socket.h"
75

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

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

    
87
#include "disas.h"
88

    
89
#include "exec-all.h"
90

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

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

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

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

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

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

    
112
#define DISK_OPTIONS_SIZE 256
113

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

    
173
/***********************************************************/
174
/* x86 ISA bus support */
175

    
176
target_phys_addr_t isa_mem_base = 0;
177
PicState2 *isa_pic;
178

    
179
uint32_t default_ioport_readb(void *opaque, uint32_t address)
180
{
181
#ifdef DEBUG_UNUSED_IOPORT
182
    fprintf(stderr, "inb: port=0x%04x\n", address);
183
#endif
184
    return 0xff;
185
}
186

    
187
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
188
{
189
#ifdef DEBUG_UNUSED_IOPORT
190
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
191
#endif
192
}
193

    
194
/* default is to make two byte accesses */
195
uint32_t default_ioport_readw(void *opaque, uint32_t address)
196
{
197
    uint32_t data;
198
    data = ioport_read_table[0][address](ioport_opaque[address], address);
199
    address = (address + 1) & (MAX_IOPORTS - 1);
200
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
201
    return data;
202
}
203

    
204
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
205
{
206
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
207
    address = (address + 1) & (MAX_IOPORTS - 1);
208
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
209
}
210

    
211
uint32_t default_ioport_readl(void *opaque, uint32_t address)
212
{
213
#ifdef DEBUG_UNUSED_IOPORT
214
    fprintf(stderr, "inl: port=0x%04x\n", address);
215
#endif
216
    return 0xffffffff;
217
}
218

    
219
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
220
{
221
#ifdef DEBUG_UNUSED_IOPORT
222
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
223
#endif
224
}
225

    
226
void init_ioports(void)
227
{
228
    int i;
229

    
230
    for(i = 0; i < MAX_IOPORTS; i++) {
231
        ioport_read_table[0][i] = default_ioport_readb;
232
        ioport_write_table[0][i] = default_ioport_writeb;
233
        ioport_read_table[1][i] = default_ioport_readw;
234
        ioport_write_table[1][i] = default_ioport_writew;
235
        ioport_read_table[2][i] = default_ioport_readl;
236
        ioport_write_table[2][i] = default_ioport_writel;
237
    }
238
}
239

    
240
/* size is the word size in byte */
241
int register_ioport_read(int start, int length, int size, 
242
                         IOPortReadFunc *func, void *opaque)
243
{
244
    int i, bsize;
245

    
246
    if (size == 1) {
247
        bsize = 0;
248
    } else if (size == 2) {
249
        bsize = 1;
250
    } else if (size == 4) {
251
        bsize = 2;
252
    } else {
253
        hw_error("register_ioport_read: invalid size");
254
        return -1;
255
    }
256
    for(i = start; i < start + length; i += size) {
257
        ioport_read_table[bsize][i] = func;
258
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
259
            hw_error("register_ioport_read: invalid opaque");
260
        ioport_opaque[i] = opaque;
261
    }
262
    return 0;
263
}
264

    
265
/* size is the word size in byte */
266
int register_ioport_write(int start, int length, int size, 
267
                          IOPortWriteFunc *func, void *opaque)
268
{
269
    int i, bsize;
270

    
271
    if (size == 1) {
272
        bsize = 0;
273
    } else if (size == 2) {
274
        bsize = 1;
275
    } else if (size == 4) {
276
        bsize = 2;
277
    } else {
278
        hw_error("register_ioport_write: invalid size");
279
        return -1;
280
    }
281
    for(i = start; i < start + length; i += size) {
282
        ioport_write_table[bsize][i] = func;
283
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
284
            hw_error("register_ioport_read: invalid opaque");
285
        ioport_opaque[i] = opaque;
286
    }
287
    return 0;
288
}
289

    
290
void isa_unassign_ioport(int start, int length)
291
{
292
    int i;
293

    
294
    for(i = start; i < start + length; i++) {
295
        ioport_read_table[0][i] = default_ioport_readb;
296
        ioport_read_table[1][i] = default_ioport_readw;
297
        ioport_read_table[2][i] = default_ioport_readl;
298

    
299
        ioport_write_table[0][i] = default_ioport_writeb;
300
        ioport_write_table[1][i] = default_ioport_writew;
301
        ioport_write_table[2][i] = default_ioport_writel;
302
    }
303
}
304

    
305
/***********************************************************/
306

    
307
void pstrcpy(char *buf, int buf_size, const char *str)
308
{
309
    int c;
310
    char *q = buf;
311

    
312
    if (buf_size <= 0)
313
        return;
314

    
315
    for(;;) {
316
        c = *str++;
317
        if (c == 0 || q >= buf + buf_size - 1)
318
            break;
319
        *q++ = c;
320
    }
321
    *q = '\0';
322
}
323

    
324
/* strcat and truncate. */
325
char *pstrcat(char *buf, int buf_size, const char *s)
326
{
327
    int len;
328
    len = strlen(buf);
329
    if (len < buf_size) 
330
        pstrcpy(buf + len, buf_size - len, s);
331
    return buf;
332
}
333

    
334
int strstart(const char *str, const char *val, const char **ptr)
335
{
336
    const char *p, *q;
337
    p = str;
338
    q = val;
339
    while (*q != '\0') {
340
        if (*p != *q)
341
            return 0;
342
        p++;
343
        q++;
344
    }
345
    if (ptr)
346
        *ptr = p;
347
    return 1;
348
}
349

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

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

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

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

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

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

    
434
/***********************************************************/
435
void hw_error(const char *fmt, ...)
436
{
437
    va_list ap;
438
    CPUState *env;
439

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

    
456
/***********************************************************/
457
/* keyboard/mouse */
458

    
459
static QEMUPutKBDEvent *qemu_put_kbd_event;
460
static void *qemu_put_kbd_event_opaque;
461
static QEMUPutMouseEvent *qemu_put_mouse_event;
462
static void *qemu_put_mouse_event_opaque;
463
static int qemu_put_mouse_event_absolute;
464

    
465
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
466
{
467
    qemu_put_kbd_event_opaque = opaque;
468
    qemu_put_kbd_event = func;
469
}
470

    
471
void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
472
{
473
    qemu_put_mouse_event_opaque = opaque;
474
    qemu_put_mouse_event = func;
475
    qemu_put_mouse_event_absolute = absolute;
476
}
477

    
478
void kbd_put_keycode(int keycode)
479
{
480
    if (qemu_put_kbd_event) {
481
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
482
    }
483
}
484

    
485
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
486
{
487
    if (qemu_put_mouse_event) {
488
        qemu_put_mouse_event(qemu_put_mouse_event_opaque, 
489
                             dx, dy, dz, buttons_state);
490
    }
491
}
492

    
493
int kbd_mouse_is_absolute(void)
494
{
495
    return qemu_put_mouse_event_absolute;
496
}
497

    
498
/* compute with 96 bit intermediate result: (a*b)/c */
499
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
500
{
501
    union {
502
        uint64_t ll;
503
        struct {
504
#ifdef WORDS_BIGENDIAN
505
            uint32_t high, low;
506
#else
507
            uint32_t low, high;
508
#endif            
509
        } l;
510
    } u, res;
511
    uint64_t rl, rh;
512

    
513
    u.ll = a;
514
    rl = (uint64_t)u.l.low * (uint64_t)b;
515
    rh = (uint64_t)u.l.high * (uint64_t)b;
516
    rh += (rl >> 32);
517
    res.l.high = rh / c;
518
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
519
    return res.ll;
520
}
521

    
522
/***********************************************************/
523
/* real time host monotonic timer */
524

    
525
#define QEMU_TIMER_BASE 1000000000LL
526

    
527
#ifdef WIN32
528

    
529
static int64_t clock_freq;
530

    
531
static void init_get_clock(void)
532
{
533
    LARGE_INTEGER freq;
534
    int ret;
535
    ret = QueryPerformanceFrequency(&freq);
536
    if (ret == 0) {
537
        fprintf(stderr, "Could not calibrate ticks\n");
538
        exit(1);
539
    }
540
    clock_freq = freq.QuadPart;
541
}
542

    
543
static int64_t get_clock(void)
544
{
545
    LARGE_INTEGER ti;
546
    QueryPerformanceCounter(&ti);
547
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
548
}
549

    
550
#else
551

    
552
static int use_rt_clock;
553

    
554
static void init_get_clock(void)
555
{
556
    use_rt_clock = 0;
557
#if defined(__linux__)
558
    {
559
        struct timespec ts;
560
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
561
            use_rt_clock = 1;
562
        }
563
    }
564
#endif
565
}
566

    
567
static int64_t get_clock(void)
568
{
569
#if defined(__linux__)
570
    if (use_rt_clock) {
571
        struct timespec ts;
572
        clock_gettime(CLOCK_MONOTONIC, &ts);
573
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
574
    } else 
575
#endif
576
    {
577
        /* XXX: using gettimeofday leads to problems if the date
578
           changes, so it should be avoided. */
579
        struct timeval tv;
580
        gettimeofday(&tv, NULL);
581
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
582
    }
583
}
584

    
585
#endif
586

    
587
/***********************************************************/
588
/* guest cycle counter */
589

    
590
static int64_t cpu_ticks_prev;
591
static int64_t cpu_ticks_offset;
592
static int64_t cpu_clock_offset;
593
static int cpu_ticks_enabled;
594

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

    
613
/* return the host CPU monotonic timer and handle stop/restart */
614
static int64_t cpu_get_clock(void)
615
{
616
    int64_t ti;
617
    if (!cpu_ticks_enabled) {
618
        return cpu_clock_offset;
619
    } else {
620
        ti = get_clock();
621
        return ti + cpu_clock_offset;
622
    }
623
}
624

    
625
/* enable cpu_get_ticks() */
626
void cpu_enable_ticks(void)
627
{
628
    if (!cpu_ticks_enabled) {
629
        cpu_ticks_offset -= cpu_get_real_ticks();
630
        cpu_clock_offset -= get_clock();
631
        cpu_ticks_enabled = 1;
632
    }
633
}
634

    
635
/* disable cpu_get_ticks() : the clock is stopped. You must not call
636
   cpu_get_ticks() after that.  */
637
void cpu_disable_ticks(void)
638
{
639
    if (cpu_ticks_enabled) {
640
        cpu_ticks_offset = cpu_get_ticks();
641
        cpu_clock_offset = cpu_get_clock();
642
        cpu_ticks_enabled = 0;
643
    }
644
}
645

    
646
/***********************************************************/
647
/* timers */
648
 
649
#define QEMU_TIMER_REALTIME 0
650
#define QEMU_TIMER_VIRTUAL  1
651

    
652
struct QEMUClock {
653
    int type;
654
    /* XXX: add frequency */
655
};
656

    
657
struct QEMUTimer {
658
    QEMUClock *clock;
659
    int64_t expire_time;
660
    QEMUTimerCB *cb;
661
    void *opaque;
662
    struct QEMUTimer *next;
663
};
664

    
665
QEMUClock *rt_clock;
666
QEMUClock *vm_clock;
667

    
668
static QEMUTimer *active_timers[2];
669
#ifdef _WIN32
670
static MMRESULT timerID;
671
static HANDLE host_alarm = NULL;
672
static unsigned int period = 1;
673
#else
674
/* frequency of the times() clock tick */
675
static int timer_freq;
676
#endif
677

    
678
QEMUClock *qemu_new_clock(int type)
679
{
680
    QEMUClock *clock;
681
    clock = qemu_mallocz(sizeof(QEMUClock));
682
    if (!clock)
683
        return NULL;
684
    clock->type = type;
685
    return clock;
686
}
687

    
688
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
689
{
690
    QEMUTimer *ts;
691

    
692
    ts = qemu_mallocz(sizeof(QEMUTimer));
693
    ts->clock = clock;
694
    ts->cb = cb;
695
    ts->opaque = opaque;
696
    return ts;
697
}
698

    
699
void qemu_free_timer(QEMUTimer *ts)
700
{
701
    qemu_free(ts);
702
}
703

    
704
/* stop a timer, but do not dealloc it */
705
void qemu_del_timer(QEMUTimer *ts)
706
{
707
    QEMUTimer **pt, *t;
708

    
709
    /* NOTE: this code must be signal safe because
710
       qemu_timer_expired() can be called from a signal. */
711
    pt = &active_timers[ts->clock->type];
712
    for(;;) {
713
        t = *pt;
714
        if (!t)
715
            break;
716
        if (t == ts) {
717
            *pt = t->next;
718
            break;
719
        }
720
        pt = &t->next;
721
    }
722
}
723

    
724
/* modify the current timer so that it will be fired when current_time
725
   >= expire_time. The corresponding callback will be called. */
726
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
727
{
728
    QEMUTimer **pt, *t;
729

    
730
    qemu_del_timer(ts);
731

    
732
    /* add the timer in the sorted list */
733
    /* NOTE: this code must be signal safe because
734
       qemu_timer_expired() can be called from a signal. */
735
    pt = &active_timers[ts->clock->type];
736
    for(;;) {
737
        t = *pt;
738
        if (!t)
739
            break;
740
        if (t->expire_time > expire_time) 
741
            break;
742
        pt = &t->next;
743
    }
744
    ts->expire_time = expire_time;
745
    ts->next = *pt;
746
    *pt = ts;
747
}
748

    
749
int qemu_timer_pending(QEMUTimer *ts)
750
{
751
    QEMUTimer *t;
752
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
753
        if (t == ts)
754
            return 1;
755
    }
756
    return 0;
757
}
758

    
759
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
760
{
761
    if (!timer_head)
762
        return 0;
763
    return (timer_head->expire_time <= current_time);
764
}
765

    
766
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
767
{
768
    QEMUTimer *ts;
769
    
770
    for(;;) {
771
        ts = *ptimer_head;
772
        if (!ts || ts->expire_time > current_time)
773
            break;
774
        /* remove timer from the list before calling the callback */
775
        *ptimer_head = ts->next;
776
        ts->next = NULL;
777
        
778
        /* run the callback (the timer list can be modified) */
779
        ts->cb(ts->opaque);
780
    }
781
}
782

    
783
int64_t qemu_get_clock(QEMUClock *clock)
784
{
785
    switch(clock->type) {
786
    case QEMU_TIMER_REALTIME:
787
        return get_clock() / 1000000;
788
    default:
789
    case QEMU_TIMER_VIRTUAL:
790
        return cpu_get_clock();
791
    }
792
}
793

    
794
static void init_timers(void)
795
{
796
    init_get_clock();
797
    ticks_per_sec = QEMU_TIMER_BASE;
798
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
799
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
800
}
801

    
802
/* save a timer */
803
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
804
{
805
    uint64_t expire_time;
806

    
807
    if (qemu_timer_pending(ts)) {
808
        expire_time = ts->expire_time;
809
    } else {
810
        expire_time = -1;
811
    }
812
    qemu_put_be64(f, expire_time);
813
}
814

    
815
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
816
{
817
    uint64_t expire_time;
818

    
819
    expire_time = qemu_get_be64(f);
820
    if (expire_time != -1) {
821
        qemu_mod_timer(ts, expire_time);
822
    } else {
823
        qemu_del_timer(ts);
824
    }
825
}
826

    
827
static void timer_save(QEMUFile *f, void *opaque)
828
{
829
    if (cpu_ticks_enabled) {
830
        hw_error("cannot save state if virtual timers are running");
831
    }
832
    qemu_put_be64s(f, &cpu_ticks_offset);
833
    qemu_put_be64s(f, &ticks_per_sec);
834
    qemu_put_be64s(f, &cpu_clock_offset);
835
}
836

    
837
static int timer_load(QEMUFile *f, void *opaque, int version_id)
838
{
839
    if (version_id != 1 && version_id != 2)
840
        return -EINVAL;
841
    if (cpu_ticks_enabled) {
842
        return -EINVAL;
843
    }
844
    qemu_get_be64s(f, &cpu_ticks_offset);
845
    qemu_get_be64s(f, &ticks_per_sec);
846
    if (version_id == 2) {
847
        qemu_get_be64s(f, &cpu_clock_offset);
848
    }
849
    return 0;
850
}
851

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

    
908
#ifndef _WIN32
909

    
910
#if defined(__linux__)
911

    
912
#define RTC_FREQ 1024
913

    
914
static int rtc_fd;
915

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

    
936
#else
937

    
938
static int start_rtc_timer(void)
939
{
940
    return -1;
941
}
942

    
943
#endif /* !defined(__linux__) */
944

    
945
#endif /* !defined(_WIN32) */
946

    
947
static void init_timer_alarm(void)
948
{
949
#ifdef _WIN32
950
    {
951
        int count=0;
952
        TIMECAPS tc;
953

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

    
993
        itv.it_interval.tv_sec = 0;
994
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
995
        itv.it_value.tv_sec = 0;
996
        itv.it_value.tv_usec = 10 * 1000;
997
        setitimer(ITIMER_REAL, &itv, NULL);
998
        /* we probe the tick duration of the kernel to inform the user if
999
           the emulated kernel requested a too high timer frequency */
1000
        getitimer(ITIMER_REAL, &itv);
1001

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

    
1018
            /* use the RTC */
1019
            sigaction(SIGIO, &act, NULL);
1020
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1021
            fcntl(rtc_fd, F_SETOWN, getpid());
1022
        } else 
1023
#endif /* defined(__linux__) */
1024
        {
1025
        use_itimer:
1026
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1027
                                   PIT_FREQ) / 1000000;
1028
        }
1029
    }
1030
#endif
1031
}
1032

    
1033
void quit_timers(void)
1034
{
1035
#ifdef _WIN32
1036
    timeKillEvent(timerID);
1037
    timeEndPeriod(period);
1038
    if (host_alarm) {
1039
        CloseHandle(host_alarm);
1040
        host_alarm = NULL;
1041
    }
1042
#endif
1043
}
1044

    
1045
/***********************************************************/
1046
/* character device */
1047

    
1048
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1049
{
1050
    return s->chr_write(s, buf, len);
1051
}
1052

    
1053
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1054
{
1055
    if (!s->chr_ioctl)
1056
        return -ENOTSUP;
1057
    return s->chr_ioctl(s, cmd, arg);
1058
}
1059

    
1060
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1061
{
1062
    char buf[4096];
1063
    va_list ap;
1064
    va_start(ap, fmt);
1065
    vsnprintf(buf, sizeof(buf), fmt, ap);
1066
    qemu_chr_write(s, buf, strlen(buf));
1067
    va_end(ap);
1068
}
1069

    
1070
void qemu_chr_send_event(CharDriverState *s, int event)
1071
{
1072
    if (s->chr_send_event)
1073
        s->chr_send_event(s, event);
1074
}
1075

    
1076
void qemu_chr_add_read_handler(CharDriverState *s, 
1077
                               IOCanRWHandler *fd_can_read, 
1078
                               IOReadHandler *fd_read, void *opaque)
1079
{
1080
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1081
}
1082
             
1083
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1084
{
1085
    s->chr_event = chr_event;
1086
}
1087

    
1088
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1089
{
1090
    return len;
1091
}
1092

    
1093
static void null_chr_add_read_handler(CharDriverState *chr, 
1094
                                    IOCanRWHandler *fd_can_read, 
1095
                                    IOReadHandler *fd_read, void *opaque)
1096
{
1097
}
1098

    
1099
CharDriverState *qemu_chr_open_null(void)
1100
{
1101
    CharDriverState *chr;
1102

    
1103
    chr = qemu_mallocz(sizeof(CharDriverState));
1104
    if (!chr)
1105
        return NULL;
1106
    chr->chr_write = null_chr_write;
1107
    chr->chr_add_read_handler = null_chr_add_read_handler;
1108
    return chr;
1109
}
1110

    
1111
#ifdef _WIN32
1112

    
1113
static void socket_cleanup(void)
1114
{
1115
    WSACleanup();
1116
}
1117

    
1118
static int socket_init(void)
1119
{
1120
    WSADATA Data;
1121
    int ret, err;
1122

    
1123
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1124
    if (ret != 0) {
1125
        err = WSAGetLastError();
1126
        fprintf(stderr, "WSAStartup: %d\n", err);
1127
        return -1;
1128
    }
1129
    atexit(socket_cleanup);
1130
    return 0;
1131
}
1132

    
1133
static int send_all(int fd, const uint8_t *buf, int len1)
1134
{
1135
    int ret, len;
1136
    
1137
    len = len1;
1138
    while (len > 0) {
1139
        ret = send(fd, buf, len, 0);
1140
        if (ret < 0) {
1141
            int errno;
1142
            errno = WSAGetLastError();
1143
            if (errno != WSAEWOULDBLOCK) {
1144
                return -1;
1145
            }
1146
        } else if (ret == 0) {
1147
            break;
1148
        } else {
1149
            buf += ret;
1150
            len -= ret;
1151
        }
1152
    }
1153
    return len1 - len;
1154
}
1155

    
1156
void socket_set_nonblock(int fd)
1157
{
1158
    unsigned long opt = 1;
1159
    ioctlsocket(fd, FIONBIO, &opt);
1160
}
1161

    
1162
#else
1163

    
1164
static int unix_write(int fd, const uint8_t *buf, int len1)
1165
{
1166
    int ret, len;
1167

    
1168
    len = len1;
1169
    while (len > 0) {
1170
        ret = write(fd, buf, len);
1171
        if (ret < 0) {
1172
            if (errno != EINTR && errno != EAGAIN)
1173
                return -1;
1174
        } else if (ret == 0) {
1175
            break;
1176
        } else {
1177
            buf += ret;
1178
            len -= ret;
1179
        }
1180
    }
1181
    return len1 - len;
1182
}
1183

    
1184
static inline int send_all(int fd, const uint8_t *buf, int len1)
1185
{
1186
    return unix_write(fd, buf, len1);
1187
}
1188

    
1189
void socket_set_nonblock(int fd)
1190
{
1191
    fcntl(fd, F_SETFL, O_NONBLOCK);
1192
}
1193
#endif /* !_WIN32 */
1194

    
1195
#ifndef _WIN32
1196

    
1197
typedef struct {
1198
    int fd_in, fd_out;
1199
    IOCanRWHandler *fd_can_read; 
1200
    IOReadHandler *fd_read;
1201
    void *fd_opaque;
1202
    int max_size;
1203
} FDCharDriver;
1204

    
1205
#define STDIO_MAX_CLIENTS 2
1206

    
1207
static int stdio_nb_clients;
1208
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1209

    
1210
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1211
{
1212
    FDCharDriver *s = chr->opaque;
1213
    return unix_write(s->fd_out, buf, len);
1214
}
1215

    
1216
static int fd_chr_read_poll(void *opaque)
1217
{
1218
    CharDriverState *chr = opaque;
1219
    FDCharDriver *s = chr->opaque;
1220

    
1221
    s->max_size = s->fd_can_read(s->fd_opaque);
1222
    return s->max_size;
1223
}
1224

    
1225
static void fd_chr_read(void *opaque)
1226
{
1227
    CharDriverState *chr = opaque;
1228
    FDCharDriver *s = chr->opaque;
1229
    int size, len;
1230
    uint8_t buf[1024];
1231
    
1232
    len = sizeof(buf);
1233
    if (len > s->max_size)
1234
        len = s->max_size;
1235
    if (len == 0)
1236
        return;
1237
    size = read(s->fd_in, buf, len);
1238
    if (size == 0) {
1239
        /* FD has been closed. Remove it from the active list.  */
1240
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1241
        return;
1242
    }
1243
    if (size > 0) {
1244
        s->fd_read(s->fd_opaque, buf, size);
1245
    }
1246
}
1247

    
1248
static void fd_chr_add_read_handler(CharDriverState *chr, 
1249
                                    IOCanRWHandler *fd_can_read, 
1250
                                    IOReadHandler *fd_read, void *opaque)
1251
{
1252
    FDCharDriver *s = chr->opaque;
1253

    
1254
    if (s->fd_in >= 0) {
1255
        s->fd_can_read = fd_can_read;
1256
        s->fd_read = fd_read;
1257
        s->fd_opaque = opaque;
1258
        if (nographic && s->fd_in == 0) {
1259
        } else {
1260
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1261
                                 fd_chr_read, NULL, chr);
1262
        }
1263
    }
1264
}
1265

    
1266
/* open a character device to a unix fd */
1267
CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1268
{
1269
    CharDriverState *chr;
1270
    FDCharDriver *s;
1271

    
1272
    chr = qemu_mallocz(sizeof(CharDriverState));
1273
    if (!chr)
1274
        return NULL;
1275
    s = qemu_mallocz(sizeof(FDCharDriver));
1276
    if (!s) {
1277
        free(chr);
1278
        return NULL;
1279
    }
1280
    s->fd_in = fd_in;
1281
    s->fd_out = fd_out;
1282
    chr->opaque = s;
1283
    chr->chr_write = fd_chr_write;
1284
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1285
    return chr;
1286
}
1287

    
1288
CharDriverState *qemu_chr_open_file_out(const char *file_out)
1289
{
1290
    int fd_out;
1291

    
1292
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1293
    if (fd_out < 0)
1294
        return NULL;
1295
    return qemu_chr_open_fd(-1, fd_out);
1296
}
1297

    
1298
CharDriverState *qemu_chr_open_pipe(const char *filename)
1299
{
1300
    int fd;
1301

    
1302
    fd = open(filename, O_RDWR | O_BINARY);
1303
    if (fd < 0)
1304
        return NULL;
1305
    return qemu_chr_open_fd(fd, fd);
1306
}
1307

    
1308

    
1309
/* for STDIO, we handle the case where several clients use it
1310
   (nographic mode) */
1311

    
1312
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1313

    
1314
#define TERM_FIFO_MAX_SIZE 1
1315

    
1316
static int term_got_escape, client_index;
1317
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1318
static int term_fifo_size;
1319
static int term_timestamps;
1320
static int64_t term_timestamps_start;
1321

    
1322
void term_print_help(void)
1323
{
1324
    printf("\n"
1325
           "C-a h    print this help\n"
1326
           "C-a x    exit emulator\n"
1327
           "C-a s    save disk data back to file (if -snapshot)\n"
1328
           "C-a b    send break (magic sysrq)\n"
1329
           "C-a t    toggle console timestamps\n"
1330
           "C-a c    switch between console and monitor\n"
1331
           "C-a C-a  send C-a\n"
1332
           );
1333
}
1334

    
1335
/* called when a char is received */
1336
static void stdio_received_byte(int ch)
1337
{
1338
    if (term_got_escape) {
1339
        term_got_escape = 0;
1340
        switch(ch) {
1341
        case 'h':
1342
            term_print_help();
1343
            break;
1344
        case 'x':
1345
            exit(0);
1346
            break;
1347
        case 's': 
1348
            {
1349
                int i;
1350
                for (i = 0; i < MAX_DISKS; i++) {
1351
                    if (bs_table[i])
1352
                        bdrv_commit(bs_table[i]);
1353
                }
1354
            }
1355
            break;
1356
        case 'b':
1357
            if (client_index < stdio_nb_clients) {
1358
                CharDriverState *chr;
1359
                FDCharDriver *s;
1360

    
1361
                chr = stdio_clients[client_index];
1362
                s = chr->opaque;
1363
                chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1364
            }
1365
            break;
1366
        case 'c':
1367
            client_index++;
1368
            if (client_index >= stdio_nb_clients)
1369
                client_index = 0;
1370
            if (client_index == 0) {
1371
                /* send a new line in the monitor to get the prompt */
1372
                ch = '\r';
1373
                goto send_char;
1374
            }
1375
            break;
1376
        case 't':
1377
            term_timestamps = !term_timestamps;
1378
            term_timestamps_start = -1;
1379
            break;
1380
        case TERM_ESCAPE:
1381
            goto send_char;
1382
        }
1383
    } else if (ch == TERM_ESCAPE) {
1384
        term_got_escape = 1;
1385
    } else {
1386
    send_char:
1387
        if (client_index < stdio_nb_clients) {
1388
            uint8_t buf[1];
1389
            CharDriverState *chr;
1390
            FDCharDriver *s;
1391
            
1392
            chr = stdio_clients[client_index];
1393
            s = chr->opaque;
1394
            if (s->fd_can_read(s->fd_opaque) > 0) {
1395
                buf[0] = ch;
1396
                s->fd_read(s->fd_opaque, buf, 1);
1397
            } else if (term_fifo_size == 0) {
1398
                term_fifo[term_fifo_size++] = ch;
1399
            }
1400
        }
1401
    }
1402
}
1403

    
1404
static int stdio_read_poll(void *opaque)
1405
{
1406
    CharDriverState *chr;
1407
    FDCharDriver *s;
1408

    
1409
    if (client_index < stdio_nb_clients) {
1410
        chr = stdio_clients[client_index];
1411
        s = chr->opaque;
1412
        /* try to flush the queue if needed */
1413
        if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1414
            s->fd_read(s->fd_opaque, term_fifo, 1);
1415
            term_fifo_size = 0;
1416
        }
1417
        /* see if we can absorb more chars */
1418
        if (term_fifo_size == 0)
1419
            return 1;
1420
        else
1421
            return 0;
1422
    } else {
1423
        return 1;
1424
    }
1425
}
1426

    
1427
static void stdio_read(void *opaque)
1428
{
1429
    int size;
1430
    uint8_t buf[1];
1431
    
1432
    size = read(0, buf, 1);
1433
    if (size == 0) {
1434
        /* stdin has been closed. Remove it from the active list.  */
1435
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1436
        return;
1437
    }
1438
    if (size > 0)
1439
        stdio_received_byte(buf[0]);
1440
}
1441

    
1442
static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1443
{
1444
    FDCharDriver *s = chr->opaque;
1445
    if (!term_timestamps) {
1446
        return unix_write(s->fd_out, buf, len);
1447
    } else {
1448
        int i;
1449
        char buf1[64];
1450

    
1451
        for(i = 0; i < len; i++) {
1452
            unix_write(s->fd_out, buf + i, 1);
1453
            if (buf[i] == '\n') {
1454
                int64_t ti;
1455
                int secs;
1456

    
1457
                ti = get_clock();
1458
                if (term_timestamps_start == -1)
1459
                    term_timestamps_start = ti;
1460
                ti -= term_timestamps_start;
1461
                secs = ti / 1000000000;
1462
                snprintf(buf1, sizeof(buf1), 
1463
                         "[%02d:%02d:%02d.%03d] ",
1464
                         secs / 3600,
1465
                         (secs / 60) % 60,
1466
                         secs % 60,
1467
                         (int)((ti / 1000000) % 1000));
1468
                unix_write(s->fd_out, buf1, strlen(buf1));
1469
            }
1470
        }
1471
        return len;
1472
    }
1473
}
1474

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

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

    
1485
static void term_init(void)
1486
{
1487
    struct termios tty;
1488

    
1489
    tcgetattr (0, &tty);
1490
    oldtty = tty;
1491
    old_fd0_flags = fcntl(0, F_GETFL);
1492

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

    
1507
    atexit(term_exit);
1508

    
1509
    fcntl(0, F_SETFL, O_NONBLOCK);
1510
}
1511

    
1512
CharDriverState *qemu_chr_open_stdio(void)
1513
{
1514
    CharDriverState *chr;
1515

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

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

    
1556
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1557
    return qemu_chr_open_fd(master_fd, master_fd);
1558
}
1559

    
1560
static void tty_serial_init(int fd, int speed, 
1561
                            int parity, int data_bits, int stop_bits)
1562
{
1563
    struct termios tty;
1564
    speed_t spd;
1565

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

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

    
1612
    cfsetispeed(&tty, spd);
1613
    cfsetospeed(&tty, spd);
1614

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

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

    
1677
CharDriverState *qemu_chr_open_tty(const char *filename)
1678
{
1679
    CharDriverState *chr;
1680
    int fd;
1681

    
1682
    fd = open(filename, O_RDWR | O_NONBLOCK);
1683
    if (fd < 0)
1684
        return NULL;
1685
    fcntl(fd, F_SETFL, O_NONBLOCK);
1686
    tty_serial_init(fd, 115200, 'N', 8, 1);
1687
    chr = qemu_chr_open_fd(fd, fd);
1688
    if (!chr)
1689
        return NULL;
1690
    chr->chr_ioctl = tty_serial_ioctl;
1691
    return chr;
1692
}
1693

    
1694
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1695
{
1696
    int fd = (int)chr->opaque;
1697
    uint8_t b;
1698

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

    
1731
CharDriverState *qemu_chr_open_pp(const char *filename)
1732
{
1733
    CharDriverState *chr;
1734
    int fd;
1735

    
1736
    fd = open(filename, O_RDWR);
1737
    if (fd < 0)
1738
        return NULL;
1739

    
1740
    if (ioctl(fd, PPCLAIM) < 0) {
1741
        close(fd);
1742
        return NULL;
1743
    }
1744

    
1745
    chr = qemu_mallocz(sizeof(CharDriverState));
1746
    if (!chr) {
1747
        close(fd);
1748
        return NULL;
1749
    }
1750
    chr->opaque = (void *)fd;
1751
    chr->chr_write = null_chr_write;
1752
    chr->chr_add_read_handler = null_chr_add_read_handler;
1753
    chr->chr_ioctl = pp_ioctl;
1754
    return chr;
1755
}
1756

    
1757
#else
1758
CharDriverState *qemu_chr_open_pty(void)
1759
{
1760
    return NULL;
1761
}
1762
#endif
1763

    
1764
#endif /* !defined(_WIN32) */
1765

    
1766
#ifdef _WIN32
1767
typedef struct {
1768
    IOCanRWHandler *fd_can_read; 
1769
    IOReadHandler *fd_read;
1770
    void *win_opaque;
1771
    int max_size;
1772
    HANDLE hcom, hrecv, hsend;
1773
    OVERLAPPED orecv, osend;
1774
    BOOL fpipe;
1775
    DWORD len;
1776
} WinCharState;
1777

    
1778
#define NSENDBUF 2048
1779
#define NRECVBUF 2048
1780
#define MAXCONNECT 1
1781
#define NTIMEOUT 5000
1782

    
1783
static int win_chr_poll(void *opaque);
1784
static int win_chr_pipe_poll(void *opaque);
1785

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

    
1806
static void win_chr_close(CharDriverState *chr)
1807
{
1808
    WinCharState *s = chr->opaque;
1809
    win_chr_close2(s);
1810
}
1811

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

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

    
1850
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1851
        fprintf(stderr, "Failed SetCommState\n");
1852
        goto fail;
1853
    }
1854

    
1855
    if (!SetCommMask(s->hcom, EV_ERR)) {
1856
        fprintf(stderr, "Failed SetCommMask\n");
1857
        goto fail;
1858
    }
1859

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

    
1873
 fail:
1874
    win_chr_close2(s);
1875
    return -1;
1876
}
1877

    
1878
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1879
{
1880
    WinCharState *s = chr->opaque;
1881
    DWORD len, ret, size, err;
1882

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

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

    
1934
    if (size > 0) {
1935
        s->fd_read(s->win_opaque, buf, size);
1936
    }
1937
}
1938

    
1939
static void win_chr_read(WinCharState *s)
1940
{
1941
    if (s->len > s->max_size)
1942
        s->len = s->max_size;
1943
    if (s->len == 0)
1944
        return;
1945
    
1946
    win_chr_readfile(s);
1947
}
1948

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

    
1965
static void win_chr_add_read_handler(CharDriverState *chr, 
1966
                                    IOCanRWHandler *fd_can_read, 
1967
                                    IOReadHandler *fd_read, void *opaque)
1968
{
1969
    WinCharState *s = chr->opaque;
1970

    
1971
    s->fd_can_read = fd_can_read;
1972
    s->fd_read = fd_read;
1973
    s->win_opaque = opaque;
1974
}
1975

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

    
1994
    if (win_chr_init(s, filename) < 0) {
1995
        free(s);
1996
        free(chr);
1997
        return NULL;
1998
    }
1999
    return chr;
2000
}
2001

    
2002
static int win_chr_pipe_poll(void *opaque)
2003
{
2004
    WinCharState *s = opaque;
2005
    DWORD size;
2006

    
2007
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2008
    if (size > 0) {
2009
        s->len = size;
2010
        win_chr_read_poll(s);
2011
        win_chr_read(s);
2012
        return 1;
2013
    }
2014
    return 0;
2015
}
2016

    
2017
static int win_chr_pipe_init(WinCharState *s, const char *filename)
2018
{
2019
    OVERLAPPED ov;
2020
    int ret;
2021
    DWORD size;
2022
    char openname[256];
2023
    
2024
    s->fpipe = TRUE;
2025

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

    
2048
    ZeroMemory(&ov, sizeof(ov));
2049
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2050
    ret = ConnectNamedPipe(s->hcom, &ov);
2051
    if (ret) {
2052
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2053
        goto fail;
2054
    }
2055

    
2056
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2057
    if (!ret) {
2058
        fprintf(stderr, "Failed GetOverlappedResult\n");
2059
        if (ov.hEvent) {
2060
            CloseHandle(ov.hEvent);
2061
            ov.hEvent = NULL;
2062
        }
2063
        goto fail;
2064
    }
2065

    
2066
    if (ov.hEvent) {
2067
        CloseHandle(ov.hEvent);
2068
        ov.hEvent = NULL;
2069
    }
2070
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2071
    return 0;
2072

    
2073
 fail:
2074
    win_chr_close2(s);
2075
    return -1;
2076
}
2077

    
2078

    
2079
CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2080
{
2081
    CharDriverState *chr;
2082
    WinCharState *s;
2083

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

    
2105
CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2106
{
2107
    CharDriverState *chr;
2108
    WinCharState *s;
2109

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

    
2134
    return qemu_chr_open_win_file(fd_out);
2135
}
2136
#endif
2137

    
2138
/***********************************************************/
2139
/* UDP Net console */
2140

    
2141
typedef struct {
2142
    IOCanRWHandler *fd_can_read;
2143
    IOReadHandler *fd_read;
2144
    void *fd_opaque;
2145
    int fd;
2146
    struct sockaddr_in daddr;
2147
    char buf[1024];
2148
    int bufcnt;
2149
    int bufptr;
2150
    int max_size;
2151
} NetCharDriver;
2152

    
2153
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2154
{
2155
    NetCharDriver *s = chr->opaque;
2156

    
2157
    return sendto(s->fd, buf, len, 0,
2158
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2159
}
2160

    
2161
static int udp_chr_read_poll(void *opaque)
2162
{
2163
    CharDriverState *chr = opaque;
2164
    NetCharDriver *s = chr->opaque;
2165

    
2166
    s->max_size = s->fd_can_read(s->fd_opaque);
2167

    
2168
    /* If there were any stray characters in the queue process them
2169
     * first
2170
     */
2171
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2172
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2173
        s->bufptr++;
2174
        s->max_size = s->fd_can_read(s->fd_opaque);
2175
    }
2176
    return s->max_size;
2177
}
2178

    
2179
static void udp_chr_read(void *opaque)
2180
{
2181
    CharDriverState *chr = opaque;
2182
    NetCharDriver *s = chr->opaque;
2183

    
2184
    if (s->max_size == 0)
2185
        return;
2186
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2187
    s->bufptr = s->bufcnt;
2188
    if (s->bufcnt <= 0)
2189
        return;
2190

    
2191
    s->bufptr = 0;
2192
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2193
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2194
        s->bufptr++;
2195
        s->max_size = s->fd_can_read(s->fd_opaque);
2196
    }
2197
}
2198

    
2199
static void udp_chr_add_read_handler(CharDriverState *chr,
2200
                                    IOCanRWHandler *fd_can_read,
2201
                                    IOReadHandler *fd_read, void *opaque)
2202
{
2203
    NetCharDriver *s = chr->opaque;
2204

    
2205
    if (s->fd >= 0) {
2206
        s->fd_can_read = fd_can_read;
2207
        s->fd_read = fd_read;
2208
        s->fd_opaque = opaque;
2209
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2210
                             udp_chr_read, NULL, chr);
2211
    }
2212
}
2213

    
2214
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2215
int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2216
int parse_host_src_port(struct sockaddr_in *haddr,
2217
                        struct sockaddr_in *saddr,
2218
                        const char *str);
2219

    
2220
CharDriverState *qemu_chr_open_udp(const char *def)
2221
{
2222
    CharDriverState *chr = NULL;
2223
    NetCharDriver *s = NULL;
2224
    int fd = -1;
2225
    struct sockaddr_in saddr;
2226

    
2227
    chr = qemu_mallocz(sizeof(CharDriverState));
2228
    if (!chr)
2229
        goto return_err;
2230
    s = qemu_mallocz(sizeof(NetCharDriver));
2231
    if (!s)
2232
        goto return_err;
2233

    
2234
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2235
    if (fd < 0) {
2236
        perror("socket(PF_INET, SOCK_DGRAM)");
2237
        goto return_err;
2238
    }
2239

    
2240
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2241
        printf("Could not parse: %s\n", def);
2242
        goto return_err;
2243
    }
2244

    
2245
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2246
    {
2247
        perror("bind");
2248
        goto return_err;
2249
    }
2250

    
2251
    s->fd = fd;
2252
    s->bufcnt = 0;
2253
    s->bufptr = 0;
2254
    chr->opaque = s;
2255
    chr->chr_write = udp_chr_write;
2256
    chr->chr_add_read_handler = udp_chr_add_read_handler;
2257
    return chr;
2258

    
2259
return_err:
2260
    if (chr)
2261
        free(chr);
2262
    if (s)
2263
        free(s);
2264
    if (fd >= 0)
2265
        closesocket(fd);
2266
    return NULL;
2267
}
2268

    
2269
/***********************************************************/
2270
/* TCP Net console */
2271

    
2272
typedef struct {
2273
    IOCanRWHandler *fd_can_read;
2274
    IOReadHandler *fd_read;
2275
    void *fd_opaque;
2276
    int fd, listen_fd;
2277
    int connected;
2278
    int max_size;
2279
    int do_telnetopt;
2280
    int is_unix;
2281
} TCPCharDriver;
2282

    
2283
static void tcp_chr_accept(void *opaque);
2284

    
2285
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2286
{
2287
    TCPCharDriver *s = chr->opaque;
2288
    if (s->connected) {
2289
        return send_all(s->fd, buf, len);
2290
    } else {
2291
        /* XXX: indicate an error ? */
2292
        return len;
2293
    }
2294
}
2295

    
2296
static int tcp_chr_read_poll(void *opaque)
2297
{
2298
    CharDriverState *chr = opaque;
2299
    TCPCharDriver *s = chr->opaque;
2300
    if (!s->connected)
2301
        return 0;
2302
    if (!s->fd_can_read)
2303
        return 0;
2304
    s->max_size = s->fd_can_read(s->fd_opaque);
2305
    return s->max_size;
2306
}
2307

    
2308
#define IAC 255
2309
#define IAC_BREAK 243
2310
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2311
                                      TCPCharDriver *s,
2312
                                      char *buf, int *size)
2313
{
2314
    /* Handle any telnet client's basic IAC options to satisfy char by
2315
     * char mode with no echo.  All IAC options will be removed from
2316
     * the buf and the do_telnetopt variable will be used to track the
2317
     * state of the width of the IAC information.
2318
     *
2319
     * IAC commands come in sets of 3 bytes with the exception of the
2320
     * "IAC BREAK" command and the double IAC.
2321
     */
2322

    
2323
    int i;
2324
    int j = 0;
2325

    
2326
    for (i = 0; i < *size; i++) {
2327
        if (s->do_telnetopt > 1) {
2328
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2329
                /* Double IAC means send an IAC */
2330
                if (j != i)
2331
                    buf[j] = buf[i];
2332
                j++;
2333
                s->do_telnetopt = 1;
2334
            } else {
2335
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2336
                    /* Handle IAC break commands by sending a serial break */
2337
                    chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2338
                    s->do_telnetopt++;
2339
                }
2340
                s->do_telnetopt++;
2341
            }
2342
            if (s->do_telnetopt >= 4) {
2343
                s->do_telnetopt = 1;
2344
            }
2345
        } else {
2346
            if ((unsigned char)buf[i] == IAC) {
2347
                s->do_telnetopt = 2;
2348
            } else {
2349
                if (j != i)
2350
                    buf[j] = buf[i];
2351
                j++;
2352
            }
2353
        }
2354
    }
2355
    *size = j;
2356
}
2357

    
2358
static void tcp_chr_read(void *opaque)
2359
{
2360
    CharDriverState *chr = opaque;
2361
    TCPCharDriver *s = chr->opaque;
2362
    uint8_t buf[1024];
2363
    int len, size;
2364

    
2365
    if (!s->connected || s->max_size <= 0)
2366
        return;
2367
    len = sizeof(buf);
2368
    if (len > s->max_size)
2369
        len = s->max_size;
2370
    size = recv(s->fd, buf, len, 0);
2371
    if (size == 0) {
2372
        /* connection closed */
2373
        s->connected = 0;
2374
        if (s->listen_fd >= 0) {
2375
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2376
        }
2377
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2378
        closesocket(s->fd);
2379
        s->fd = -1;
2380
    } else if (size > 0) {
2381
        if (s->do_telnetopt)
2382
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2383
        if (size > 0)
2384
            s->fd_read(s->fd_opaque, buf, size);
2385
    }
2386
}
2387

    
2388
static void tcp_chr_add_read_handler(CharDriverState *chr,
2389
                                     IOCanRWHandler *fd_can_read,
2390
                                    IOReadHandler *fd_read, void *opaque)
2391
{
2392
    TCPCharDriver *s = chr->opaque;
2393

    
2394
    s->fd_can_read = fd_can_read;
2395
    s->fd_read = fd_read;
2396
    s->fd_opaque = opaque;
2397
}
2398

    
2399
static void tcp_chr_connect(void *opaque)
2400
{
2401
    CharDriverState *chr = opaque;
2402
    TCPCharDriver *s = chr->opaque;
2403

    
2404
    s->connected = 1;
2405
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2406
                         tcp_chr_read, NULL, chr);
2407
}
2408

    
2409
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2410
static void tcp_chr_telnet_init(int fd)
2411
{
2412
    char buf[3];
2413
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2414
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2415
    send(fd, (char *)buf, 3, 0);
2416
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2417
    send(fd, (char *)buf, 3, 0);
2418
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2419
    send(fd, (char *)buf, 3, 0);
2420
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2421
    send(fd, (char *)buf, 3, 0);
2422
}
2423

    
2424
static void tcp_chr_accept(void *opaque)
2425
{
2426
    CharDriverState *chr = opaque;
2427
    TCPCharDriver *s = chr->opaque;
2428
    struct sockaddr_in saddr;
2429
#ifndef _WIN32
2430
    struct sockaddr_un uaddr;
2431
#endif
2432
    struct sockaddr *addr;
2433
    socklen_t len;
2434
    int fd;
2435

    
2436
    for(;;) {
2437
#ifndef _WIN32
2438
        if (s->is_unix) {
2439
            len = sizeof(uaddr);
2440
            addr = (struct sockaddr *)&uaddr;
2441
        } else
2442
#endif
2443
        {
2444
            len = sizeof(saddr);
2445
            addr = (struct sockaddr *)&saddr;
2446
        }
2447
        fd = accept(s->listen_fd, addr, &len);
2448
        if (fd < 0 && errno != EINTR) {
2449
            return;
2450
        } else if (fd >= 0) {
2451
            if (s->do_telnetopt)
2452
                tcp_chr_telnet_init(fd);
2453
            break;
2454
        }
2455
    }
2456
    socket_set_nonblock(fd);
2457
    s->fd = fd;
2458
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2459
    tcp_chr_connect(chr);
2460
}
2461

    
2462
static void tcp_chr_close(CharDriverState *chr)
2463
{
2464
    TCPCharDriver *s = chr->opaque;
2465
    if (s->fd >= 0)
2466
        closesocket(s->fd);
2467
    if (s->listen_fd >= 0)
2468
        closesocket(s->listen_fd);
2469
    qemu_free(s);
2470
}
2471

    
2472
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2473
                                          int is_telnet,
2474
                                          int is_unix)
2475
{
2476
    CharDriverState *chr = NULL;
2477
    TCPCharDriver *s = NULL;
2478
    int fd = -1, ret, err, val;
2479
    int is_listen = 0;
2480
    int is_waitconnect = 1;
2481
    const char *ptr;
2482
    struct sockaddr_in saddr;
2483
#ifndef _WIN32
2484
    struct sockaddr_un uaddr;
2485
#endif
2486
    struct sockaddr *addr;
2487
    socklen_t addrlen;
2488

    
2489
#ifndef _WIN32
2490
    if (is_unix) {
2491
        addr = (struct sockaddr *)&uaddr;
2492
        addrlen = sizeof(uaddr);
2493
        if (parse_unix_path(&uaddr, host_str) < 0)
2494
            goto fail;
2495
    } else
2496
#endif
2497
    {
2498
        addr = (struct sockaddr *)&saddr;
2499
        addrlen = sizeof(saddr);
2500
        if (parse_host_port(&saddr, host_str) < 0)
2501
            goto fail;
2502
    }
2503

    
2504
    ptr = host_str;
2505
    while((ptr = strchr(ptr,','))) {
2506
        ptr++;
2507
        if (!strncmp(ptr,"server",6)) {
2508
            is_listen = 1;
2509
        } else if (!strncmp(ptr,"nowait",6)) {
2510
            is_waitconnect = 0;
2511
        } else {
2512
            printf("Unknown option: %s\n", ptr);
2513
            goto fail;
2514
        }
2515
    }
2516
    if (!is_listen)
2517
        is_waitconnect = 0;
2518

    
2519
    chr = qemu_mallocz(sizeof(CharDriverState));
2520
    if (!chr)
2521
        goto fail;
2522
    s = qemu_mallocz(sizeof(TCPCharDriver));
2523
    if (!s)
2524
        goto fail;
2525

    
2526
#ifndef _WIN32
2527
    if (is_unix)
2528
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2529
    else
2530
#endif
2531
        fd = socket(PF_INET, SOCK_STREAM, 0);
2532
        
2533
    if (fd < 0) 
2534
        goto fail;
2535

    
2536
    if (!is_waitconnect)
2537
        socket_set_nonblock(fd);
2538

    
2539
    s->connected = 0;
2540
    s->fd = -1;
2541
    s->listen_fd = -1;
2542
    s->is_unix = is_unix;
2543

    
2544
    chr->opaque = s;
2545
    chr->chr_write = tcp_chr_write;
2546
    chr->chr_add_read_handler = tcp_chr_add_read_handler;
2547
    chr->chr_close = tcp_chr_close;
2548

    
2549
    if (is_listen) {
2550
        /* allow fast reuse */
2551
#ifndef _WIN32
2552
        if (is_unix) {
2553
            char path[109];
2554
            strncpy(path, uaddr.sun_path, 108);
2555
            path[108] = 0;
2556
            unlink(path);
2557
        } else
2558
#endif
2559
        {
2560
            val = 1;
2561
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2562
        }
2563
        
2564
        ret = bind(fd, addr, addrlen);
2565
        if (ret < 0)
2566
            goto fail;
2567

    
2568
        ret = listen(fd, 0);
2569
        if (ret < 0)
2570
            goto fail;
2571

    
2572
        s->listen_fd = fd;
2573
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2574
        if (is_telnet)
2575
            s->do_telnetopt = 1;
2576
    } else {
2577
        for(;;) {
2578
            ret = connect(fd, addr, addrlen);
2579
            if (ret < 0) {
2580
                err = socket_error();
2581
                if (err == EINTR || err == EWOULDBLOCK) {
2582
                } else if (err == EINPROGRESS) {
2583
                    break;
2584
                } else {
2585
                    goto fail;
2586
                }
2587
            } else {
2588
                s->connected = 1;
2589
                break;
2590
            }
2591
        }
2592
        s->fd = fd;
2593
        if (s->connected)
2594
            tcp_chr_connect(chr);
2595
        else
2596
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2597
    }
2598
    
2599
    if (is_listen && is_waitconnect) {
2600
        printf("QEMU waiting for connection on: %s\n", host_str);
2601
        tcp_chr_accept(chr);
2602
        socket_set_nonblock(s->listen_fd);
2603
    }
2604

    
2605
    return chr;
2606
 fail:
2607
    if (fd >= 0)
2608
        closesocket(fd);
2609
    qemu_free(s);
2610
    qemu_free(chr);
2611
    return NULL;
2612
}
2613

    
2614
CharDriverState *qemu_chr_open(const char *filename)
2615
{
2616
    const char *p;
2617

    
2618
    if (!strcmp(filename, "vc")) {
2619
        return text_console_init(&display_state);
2620
    } else if (!strcmp(filename, "null")) {
2621
        return qemu_chr_open_null();
2622
    } else 
2623
    if (strstart(filename, "tcp:", &p)) {
2624
        return qemu_chr_open_tcp(p, 0, 0);
2625
    } else
2626
    if (strstart(filename, "telnet:", &p)) {
2627
        return qemu_chr_open_tcp(p, 1, 0);
2628
    } else
2629
    if (strstart(filename, "udp:", &p)) {
2630
        return qemu_chr_open_udp(p);
2631
    } else
2632
#ifndef _WIN32
2633
    if (strstart(filename, "unix:", &p)) {
2634
        return qemu_chr_open_tcp(p, 0, 1);
2635
    } else if (strstart(filename, "file:", &p)) {
2636
        return qemu_chr_open_file_out(p);
2637
    } else if (strstart(filename, "pipe:", &p)) {
2638
        return qemu_chr_open_pipe(p);
2639
    } else if (!strcmp(filename, "pty")) {
2640
        return qemu_chr_open_pty();
2641
    } else if (!strcmp(filename, "stdio")) {
2642
        return qemu_chr_open_stdio();
2643
    } else 
2644
#endif
2645
#if defined(__linux__)
2646
    if (strstart(filename, "/dev/parport", NULL)) {
2647
        return qemu_chr_open_pp(filename);
2648
    } else 
2649
    if (strstart(filename, "/dev/", NULL)) {
2650
        return qemu_chr_open_tty(filename);
2651
    } else 
2652
#endif
2653
#ifdef _WIN32
2654
    if (strstart(filename, "COM", NULL)) {
2655
        return qemu_chr_open_win(filename);
2656
    } else
2657
    if (strstart(filename, "pipe:", &p)) {
2658
        return qemu_chr_open_win_pipe(p);
2659
    } else
2660
    if (strstart(filename, "file:", &p)) {
2661
        return qemu_chr_open_win_file_out(p);
2662
    }
2663
#endif
2664
    {
2665
        return NULL;
2666
    }
2667
}
2668

    
2669
void qemu_chr_close(CharDriverState *chr)
2670
{
2671
    if (chr->chr_close)
2672
        chr->chr_close(chr);
2673
}
2674

    
2675
/***********************************************************/
2676
/* network device redirectors */
2677

    
2678
void hex_dump(FILE *f, const uint8_t *buf, int size)
2679
{
2680
    int len, i, j, c;
2681

    
2682
    for(i=0;i<size;i+=16) {
2683
        len = size - i;
2684
        if (len > 16)
2685
            len = 16;
2686
        fprintf(f, "%08x ", i);
2687
        for(j=0;j<16;j++) {
2688
            if (j < len)
2689
                fprintf(f, " %02x", buf[i+j]);
2690
            else
2691
                fprintf(f, "   ");
2692
        }
2693
        fprintf(f, " ");
2694
        for(j=0;j<len;j++) {
2695
            c = buf[i+j];
2696
            if (c < ' ' || c > '~')
2697
                c = '.';
2698
            fprintf(f, "%c", c);
2699
        }
2700
        fprintf(f, "\n");
2701
    }
2702
}
2703

    
2704
static int parse_macaddr(uint8_t *macaddr, const char *p)
2705
{
2706
    int i;
2707
    for(i = 0; i < 6; i++) {
2708
        macaddr[i] = strtol(p, (char **)&p, 16);
2709
        if (i == 5) {
2710
            if (*p != '\0') 
2711
                return -1;
2712
        } else {
2713
            if (*p != ':') 
2714
                return -1;
2715
            p++;
2716
        }
2717
    }
2718
    return 0;
2719
}
2720

    
2721
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2722
{
2723
    const char *p, *p1;
2724
    int len;
2725
    p = *pp;
2726
    p1 = strchr(p, sep);
2727
    if (!p1)
2728
        return -1;
2729
    len = p1 - p;
2730
    p1++;
2731
    if (buf_size > 0) {
2732
        if (len > buf_size - 1)
2733
            len = buf_size - 1;
2734
        memcpy(buf, p, len);
2735
        buf[len] = '\0';
2736
    }
2737
    *pp = p1;
2738
    return 0;
2739
}
2740

    
2741
int parse_host_src_port(struct sockaddr_in *haddr,
2742
                        struct sockaddr_in *saddr,
2743
                        const char *input_str)
2744
{
2745
    char *str = strdup(input_str);
2746
    char *host_str = str;
2747
    char *src_str;
2748
    char *ptr;
2749

    
2750
    /*
2751
     * Chop off any extra arguments at the end of the string which
2752
     * would start with a comma, then fill in the src port information
2753
     * if it was provided else use the "any address" and "any port".
2754
     */
2755
    if ((ptr = strchr(str,',')))
2756
        *ptr = '\0';
2757

    
2758
    if ((src_str = strchr(input_str,'@'))) {
2759
        *src_str = '\0';
2760
        src_str++;
2761
    }
2762

    
2763
    if (parse_host_port(haddr, host_str) < 0)
2764
        goto fail;
2765

    
2766
    if (!src_str || *src_str == '\0')
2767
        src_str = ":0";
2768

    
2769
    if (parse_host_port(saddr, src_str) < 0)
2770
        goto fail;
2771

    
2772
    free(str);
2773
    return(0);
2774

    
2775
fail:
2776
    free(str);
2777
    return -1;
2778
}
2779

    
2780
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2781
{
2782
    char buf[512];
2783
    struct hostent *he;
2784
    const char *p, *r;
2785
    int port;
2786

    
2787
    p = str;
2788
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2789
        return -1;
2790
    saddr->sin_family = AF_INET;
2791
    if (buf[0] == '\0') {
2792
        saddr->sin_addr.s_addr = 0;
2793
    } else {
2794
        if (isdigit(buf[0])) {
2795
            if (!inet_aton(buf, &saddr->sin_addr))
2796
                return -1;
2797
        } else {
2798
            if ((he = gethostbyname(buf)) == NULL)
2799
                return - 1;
2800
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2801
        }
2802
    }
2803
    port = strtol(p, (char **)&r, 0);
2804
    if (r == p)
2805
        return -1;
2806
    saddr->sin_port = htons(port);
2807
    return 0;
2808
}
2809

    
2810
int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2811
{
2812
    const char *p;
2813
    int len;
2814

    
2815
    len = MIN(108, strlen(str));
2816
    p = strchr(str, ',');
2817
    if (p)
2818
        len = MIN(len, p - str);
2819

    
2820
    memset(uaddr, 0, sizeof(*uaddr));
2821

    
2822
    uaddr->sun_family = AF_UNIX;
2823
    memcpy(uaddr->sun_path, str, len);
2824

    
2825
    return 0;
2826
}
2827

    
2828
/* find or alloc a new VLAN */
2829
VLANState *qemu_find_vlan(int id)
2830
{
2831
    VLANState **pvlan, *vlan;
2832
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2833
        if (vlan->id == id)
2834
            return vlan;
2835
    }
2836
    vlan = qemu_mallocz(sizeof(VLANState));
2837
    if (!vlan)
2838
        return NULL;
2839
    vlan->id = id;
2840
    vlan->next = NULL;
2841
    pvlan = &first_vlan;
2842
    while (*pvlan != NULL)
2843
        pvlan = &(*pvlan)->next;
2844
    *pvlan = vlan;
2845
    return vlan;
2846
}
2847

    
2848
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2849
                                      IOReadHandler *fd_read,
2850
                                      IOCanRWHandler *fd_can_read,
2851
                                      void *opaque)
2852
{
2853
    VLANClientState *vc, **pvc;
2854
    vc = qemu_mallocz(sizeof(VLANClientState));
2855
    if (!vc)
2856
        return NULL;
2857
    vc->fd_read = fd_read;
2858
    vc->fd_can_read = fd_can_read;
2859
    vc->opaque = opaque;
2860
    vc->vlan = vlan;
2861

    
2862
    vc->next = NULL;
2863
    pvc = &vlan->first_client;
2864
    while (*pvc != NULL)
2865
        pvc = &(*pvc)->next;
2866
    *pvc = vc;
2867
    return vc;
2868
}
2869

    
2870
int qemu_can_send_packet(VLANClientState *vc1)
2871
{
2872
    VLANState *vlan = vc1->vlan;
2873
    VLANClientState *vc;
2874

    
2875
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2876
        if (vc != vc1) {
2877
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2878
                return 0;
2879
        }
2880
    }
2881
    return 1;
2882
}
2883

    
2884
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2885
{
2886
    VLANState *vlan = vc1->vlan;
2887
    VLANClientState *vc;
2888

    
2889
#if 0
2890
    printf("vlan %d send:\n", vlan->id);
2891
    hex_dump(stdout, buf, size);
2892
#endif
2893
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2894
        if (vc != vc1) {
2895
            vc->fd_read(vc->opaque, buf, size);
2896
        }
2897
    }
2898
}
2899

    
2900
#if defined(CONFIG_SLIRP)
2901

    
2902
/* slirp network adapter */
2903

    
2904
static int slirp_inited;
2905
static VLANClientState *slirp_vc;
2906

    
2907
int slirp_can_output(void)
2908
{
2909
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
2910
}
2911

    
2912
void slirp_output(const uint8_t *pkt, int pkt_len)
2913
{
2914
#if 0
2915
    printf("slirp output:\n");
2916
    hex_dump(stdout, pkt, pkt_len);
2917
#endif
2918
    if (!slirp_vc)
2919
        return;
2920
    qemu_send_packet(slirp_vc, pkt, pkt_len);
2921
}
2922

    
2923
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2924
{
2925
#if 0
2926
    printf("slirp input:\n");
2927
    hex_dump(stdout, buf, size);
2928
#endif
2929
    slirp_input(buf, size);
2930
}
2931

    
2932
static int net_slirp_init(VLANState *vlan)
2933
{
2934
    if (!slirp_inited) {
2935
        slirp_inited = 1;
2936
        slirp_init();
2937
    }
2938
    slirp_vc = qemu_new_vlan_client(vlan, 
2939
                                    slirp_receive, NULL, NULL);
2940
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2941
    return 0;
2942
}
2943

    
2944
static void net_slirp_redir(const char *redir_str)
2945
{
2946
    int is_udp;
2947
    char buf[256], *r;
2948
    const char *p;
2949
    struct in_addr guest_addr;
2950
    int host_port, guest_port;
2951
    
2952
    if (!slirp_inited) {
2953
        slirp_inited = 1;
2954
        slirp_init();
2955
    }
2956

    
2957
    p = redir_str;
2958
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2959
        goto fail;
2960
    if (!strcmp(buf, "tcp")) {
2961
        is_udp = 0;
2962
    } else if (!strcmp(buf, "udp")) {
2963
        is_udp = 1;
2964
    } else {
2965
        goto fail;
2966
    }
2967

    
2968
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2969
        goto fail;
2970
    host_port = strtol(buf, &r, 0);
2971
    if (r == buf)
2972
        goto fail;
2973

    
2974
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2975
        goto fail;
2976
    if (buf[0] == '\0') {
2977
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
2978
    }
2979
    if (!inet_aton(buf, &guest_addr))
2980
        goto fail;
2981
    
2982
    guest_port = strtol(p, &r, 0);
2983
    if (r == p)
2984
        goto fail;
2985
    
2986
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2987
        fprintf(stderr, "qemu: could not set up redirection\n");
2988
        exit(1);
2989
    }
2990
    return;
2991
 fail:
2992
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2993
    exit(1);
2994
}
2995
    
2996
#ifndef _WIN32
2997

    
2998
char smb_dir[1024];
2999

    
3000
static void smb_exit(void)
3001
{
3002
    DIR *d;
3003
    struct dirent *de;
3004
    char filename[1024];
3005

    
3006
    /* erase all the files in the directory */
3007
    d = opendir(smb_dir);
3008
    for(;;) {
3009
        de = readdir(d);
3010
        if (!de)
3011
            break;
3012
        if (strcmp(de->d_name, ".") != 0 &&
3013
            strcmp(de->d_name, "..") != 0) {
3014
            snprintf(filename, sizeof(filename), "%s/%s", 
3015
                     smb_dir, de->d_name);
3016
            unlink(filename);
3017
        }
3018
    }
3019
    closedir(d);
3020
    rmdir(smb_dir);
3021
}
3022

    
3023
/* automatic user mode samba server configuration */
3024
void net_slirp_smb(const char *exported_dir)
3025
{
3026
    char smb_conf[1024];
3027
    char smb_cmdline[1024];
3028
    FILE *f;
3029

    
3030
    if (!slirp_inited) {
3031
        slirp_inited = 1;
3032
        slirp_init();
3033
    }
3034

    
3035
    /* XXX: better tmp dir construction */
3036
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3037
    if (mkdir(smb_dir, 0700) < 0) {
3038
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3039
        exit(1);
3040
    }
3041
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3042
    
3043
    f = fopen(smb_conf, "w");
3044
    if (!f) {
3045
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3046
        exit(1);
3047
    }
3048
    fprintf(f, 
3049
            "[global]\n"
3050
            "private dir=%s\n"
3051
            "smb ports=0\n"
3052
            "socket address=127.0.0.1\n"
3053
            "pid directory=%s\n"
3054
            "lock directory=%s\n"
3055
            "log file=%s/log.smbd\n"
3056
            "smb passwd file=%s/smbpasswd\n"
3057
            "security = share\n"
3058
            "[qemu]\n"
3059
            "path=%s\n"
3060
            "read only=no\n"
3061
            "guest ok=yes\n",
3062
            smb_dir,
3063
            smb_dir,
3064
            smb_dir,
3065
            smb_dir,
3066
            smb_dir,
3067
            exported_dir
3068
            );
3069
    fclose(f);
3070
    atexit(smb_exit);
3071

    
3072
    snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
3073
             smb_conf);
3074
    
3075
    slirp_add_exec(0, smb_cmdline, 4, 139);
3076
}
3077

    
3078
#endif /* !defined(_WIN32) */
3079

    
3080
#endif /* CONFIG_SLIRP */
3081

    
3082
#if !defined(_WIN32)
3083

    
3084
typedef struct TAPState {
3085
    VLANClientState *vc;
3086
    int fd;
3087
} TAPState;
3088

    
3089
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3090
{
3091
    TAPState *s = opaque;
3092
    int ret;
3093
    for(;;) {
3094
        ret = write(s->fd, buf, size);
3095
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3096
        } else {
3097
            break;
3098
        }
3099
    }
3100
}
3101

    
3102
static void tap_send(void *opaque)
3103
{
3104
    TAPState *s = opaque;
3105
    uint8_t buf[4096];
3106
    int size;
3107

    
3108
    size = read(s->fd, buf, sizeof(buf));
3109
    if (size > 0) {
3110
        qemu_send_packet(s->vc, buf, size);
3111
    }
3112
}
3113

    
3114
/* fd support */
3115

    
3116
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3117
{
3118
    TAPState *s;
3119

    
3120
    s = qemu_mallocz(sizeof(TAPState));
3121
    if (!s)
3122
        return NULL;
3123
    s->fd = fd;
3124
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3125
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3126
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3127
    return s;
3128
}
3129

    
3130
#ifdef _BSD
3131
static int tap_open(char *ifname, int ifname_size)
3132
{
3133
    int fd;
3134
    char *dev;
3135
    struct stat s;
3136

    
3137
    fd = open("/dev/tap", O_RDWR);
3138
    if (fd < 0) {
3139
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3140
        return -1;
3141
    }
3142

    
3143
    fstat(fd, &s);
3144
    dev = devname(s.st_rdev, S_IFCHR);
3145
    pstrcpy(ifname, ifname_size, dev);
3146

    
3147
    fcntl(fd, F_SETFL, O_NONBLOCK);
3148
    return fd;
3149
}
3150
#elif defined(__sun__)
3151
static int tap_open(char *ifname, int ifname_size)
3152
{
3153
    fprintf(stderr, "warning: tap_open not yet implemented\n");
3154
    return -1;
3155
}
3156
#else
3157
static int tap_open(char *ifname, int ifname_size)
3158
{
3159
    struct ifreq ifr;
3160
    int fd, ret;
3161
    
3162
    fd = open("/dev/net/tun", O_RDWR);
3163
    if (fd < 0) {
3164
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3165
        return -1;
3166
    }
3167
    memset(&ifr, 0, sizeof(ifr));
3168
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3169
    if (ifname[0] != '\0')
3170
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3171
    else
3172
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3173
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3174
    if (ret != 0) {
3175
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3176
        close(fd);
3177
        return -1;
3178
    }
3179
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3180
    fcntl(fd, F_SETFL, O_NONBLOCK);
3181
    return fd;
3182
}
3183
#endif
3184

    
3185
static int net_tap_init(VLANState *vlan, const char *ifname1,
3186
                        const char *setup_script)
3187
{
3188
    TAPState *s;
3189
    int pid, status, fd;
3190
    char *args[3];
3191
    char **parg;
3192
    char ifname[128];
3193

    
3194
    if (ifname1 != NULL)
3195
        pstrcpy(ifname, sizeof(ifname), ifname1);
3196
    else
3197
        ifname[0] = '\0';
3198
    fd = tap_open(ifname, sizeof(ifname));
3199
    if (fd < 0)
3200
        return -1;
3201

    
3202
    if (!setup_script)
3203
        setup_script = "";
3204
    if (setup_script[0] != '\0') {
3205
        /* try to launch network init script */
3206
        pid = fork();
3207
        if (pid >= 0) {
3208
            if (pid == 0) {
3209
                parg = args;
3210
                *parg++ = (char *)setup_script;
3211
                *parg++ = ifname;
3212
                *parg++ = NULL;
3213
                execv(setup_script, args);
3214
                _exit(1);
3215
            }
3216
            while (waitpid(pid, &status, 0) != pid);
3217
            if (!WIFEXITED(status) ||
3218
                WEXITSTATUS(status) != 0) {
3219
                fprintf(stderr, "%s: could not launch network script\n",
3220
                        setup_script);
3221
                return -1;
3222
            }
3223
        }
3224
    }
3225
    s = net_tap_fd_init(vlan, fd);
3226
    if (!s)
3227
        return -1;
3228
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3229
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3230
    return 0;
3231
}
3232

    
3233
#endif /* !_WIN32 */
3234

    
3235
/* network connection */
3236
typedef struct NetSocketState {
3237
    VLANClientState *vc;
3238
    int fd;
3239
    int state; /* 0 = getting length, 1 = getting data */
3240
    int index;
3241
    int packet_len;
3242
    uint8_t buf[4096];
3243
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3244
} NetSocketState;
3245

    
3246
typedef struct NetSocketListenState {
3247
    VLANState *vlan;
3248
    int fd;
3249
} NetSocketListenState;
3250

    
3251
/* XXX: we consider we can send the whole packet without blocking */
3252
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3253
{
3254
    NetSocketState *s = opaque;
3255
    uint32_t len;
3256
    len = htonl(size);
3257

    
3258
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3259
    send_all(s->fd, buf, size);
3260
}
3261

    
3262
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3263
{
3264
    NetSocketState *s = opaque;
3265
    sendto(s->fd, buf, size, 0, 
3266
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3267
}
3268

    
3269
static void net_socket_send(void *opaque)
3270
{
3271
    NetSocketState *s = opaque;
3272
    int l, size, err;
3273
    uint8_t buf1[4096];
3274
    const uint8_t *buf;
3275

    
3276
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3277
    if (size < 0) {
3278
        err = socket_error();
3279
        if (err != EWOULDBLOCK) 
3280
            goto eoc;
3281
    } else if (size == 0) {
3282
        /* end of connection */
3283
    eoc:
3284
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3285
        closesocket(s->fd);
3286
        return;
3287
    }
3288
    buf = buf1;
3289
    while (size > 0) {
3290
        /* reassemble a packet from the network */
3291
        switch(s->state) {
3292
        case 0:
3293
            l = 4 - s->index;
3294
            if (l > size)
3295
                l = size;
3296
            memcpy(s->buf + s->index, buf, l);
3297
            buf += l;
3298
            size -= l;
3299
            s->index += l;
3300
            if (s->index == 4) {
3301
                /* got length */
3302
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3303
                s->index = 0;
3304
                s->state = 1;
3305
            }
3306
            break;
3307
        case 1:
3308
            l = s->packet_len - s->index;
3309
            if (l > size)
3310
                l = size;
3311
            memcpy(s->buf + s->index, buf, l);
3312
            s->index += l;
3313
            buf += l;
3314
            size -= l;
3315
            if (s->index >= s->packet_len) {
3316
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3317
                s->index = 0;
3318
                s->state = 0;
3319
            }
3320
            break;
3321
        }
3322
    }
3323
}
3324

    
3325
static void net_socket_send_dgram(void *opaque)
3326
{
3327
    NetSocketState *s = opaque;
3328
    int size;
3329

    
3330
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3331
    if (size < 0) 
3332
        return;
3333
    if (size == 0) {
3334
        /* end of connection */
3335
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3336
        return;
3337
    }
3338
    qemu_send_packet(s->vc, s->buf, size);
3339
}
3340

    
3341
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3342
{
3343
    struct ip_mreq imr;
3344
    int fd;
3345
    int val, ret;
3346
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3347
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3348
                inet_ntoa(mcastaddr->sin_addr), 
3349
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3350
        return -1;
3351

    
3352
    }
3353
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3354
    if (fd < 0) {
3355
        perror("socket(PF_INET, SOCK_DGRAM)");
3356
        return -1;
3357
    }
3358

    
3359
    val = 1;
3360
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3361
                   (const char *)&val, sizeof(val));
3362
    if (ret < 0) {
3363
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3364
        goto fail;
3365
    }
3366

    
3367
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3368
    if (ret < 0) {
3369
        perror("bind");
3370
        goto fail;
3371
    }
3372
    
3373
    /* Add host to multicast group */
3374
    imr.imr_multiaddr = mcastaddr->sin_addr;
3375
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3376

    
3377
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3378
                     (const char *)&imr, sizeof(struct ip_mreq));
3379
    if (ret < 0) {
3380
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3381
        goto fail;
3382
    }
3383

    
3384
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3385
    val = 1;
3386
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3387
                   (const char *)&val, sizeof(val));
3388
    if (ret < 0) {
3389
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3390
        goto fail;
3391
    }
3392

    
3393
    socket_set_nonblock(fd);
3394
    return fd;
3395
fail:
3396
    if (fd >= 0) 
3397
        closesocket(fd);
3398
    return -1;
3399
}
3400

    
3401
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3402
                                          int is_connected)
3403
{
3404
    struct sockaddr_in saddr;
3405
    int newfd;
3406
    socklen_t saddr_len;
3407
    NetSocketState *s;
3408

    
3409
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3410
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3411
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3412
     */
3413

    
3414
    if (is_connected) {
3415
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3416
            /* must be bound */
3417
            if (saddr.sin_addr.s_addr==0) {
3418
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3419
                        fd);
3420
                return NULL;
3421
            }
3422
            /* clone dgram socket */
3423
            newfd = net_socket_mcast_create(&saddr);
3424
            if (newfd < 0) {
3425
                /* error already reported by net_socket_mcast_create() */
3426
                close(fd);
3427
                return NULL;
3428
            }
3429
            /* clone newfd to fd, close newfd */
3430
            dup2(newfd, fd);
3431
            close(newfd);
3432
        
3433
        } else {
3434
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3435
                    fd, strerror(errno));
3436
            return NULL;
3437
        }
3438
    }
3439

    
3440
    s = qemu_mallocz(sizeof(NetSocketState));
3441
    if (!s)
3442
        return NULL;
3443
    s->fd = fd;
3444

    
3445
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3446
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3447

    
3448
    /* mcast: save bound address as dst */
3449
    if (is_connected) s->dgram_dst=saddr;
3450

    
3451
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3452
            "socket: fd=%d (%s mcast=%s:%d)", 
3453
            fd, is_connected? "cloned" : "",
3454
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3455
    return s;
3456
}
3457

    
3458
static void net_socket_connect(void *opaque)
3459
{
3460
    NetSocketState *s = opaque;
3461
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3462
}
3463

    
3464
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3465
                                          int is_connected)
3466
{
3467
    NetSocketState *s;
3468
    s = qemu_mallocz(sizeof(NetSocketState));
3469
    if (!s)
3470
        return NULL;
3471
    s->fd = fd;
3472
    s->vc = qemu_new_vlan_client(vlan, 
3473
                                 net_socket_receive, NULL, s);
3474
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3475
             "socket: fd=%d", fd);
3476
    if (is_connected) {
3477
        net_socket_connect(s);
3478
    } else {
3479
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3480
    }
3481
    return s;
3482
}
3483

    
3484
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3485
                                          int is_connected)
3486
{
3487
    int so_type=-1, optlen=sizeof(so_type);
3488

    
3489
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3490
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3491
        return NULL;
3492
    }
3493
    switch(so_type) {
3494
    case SOCK_DGRAM:
3495
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3496
    case SOCK_STREAM:
3497
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3498
    default:
3499
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3500
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3501
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3502
    }
3503
    return NULL;
3504
}
3505

    
3506
static void net_socket_accept(void *opaque)
3507
{
3508
    NetSocketListenState *s = opaque;    
3509
    NetSocketState *s1;
3510
    struct sockaddr_in saddr;
3511
    socklen_t len;
3512
    int fd;
3513

    
3514
    for(;;) {
3515
        len = sizeof(saddr);
3516
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3517
        if (fd < 0 && errno != EINTR) {
3518
            return;
3519
        } else if (fd >= 0) {
3520
            break;
3521
        }
3522
    }
3523
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3524
    if (!s1) {
3525
        closesocket(fd);
3526
    } else {
3527
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3528
                 "socket: connection from %s:%d", 
3529
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3530
    }
3531
}
3532

    
3533
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3534
{
3535
    NetSocketListenState *s;
3536
    int fd, val, ret;
3537
    struct sockaddr_in saddr;
3538

    
3539
    if (parse_host_port(&saddr, host_str) < 0)
3540
        return -1;
3541
    
3542
    s = qemu_mallocz(sizeof(NetSocketListenState));
3543
    if (!s)
3544
        return -1;
3545

    
3546
    fd = socket(PF_INET, SOCK_STREAM, 0);
3547
    if (fd < 0) {
3548
        perror("socket");
3549
        return -1;
3550
    }
3551
    socket_set_nonblock(fd);
3552

    
3553
    /* allow fast reuse */
3554
    val = 1;
3555
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3556
    
3557
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3558
    if (ret < 0) {
3559
        perror("bind");
3560
        return -1;
3561
    }
3562
    ret = listen(fd, 0);
3563
    if (ret < 0) {
3564
        perror("listen");
3565
        return -1;
3566
    }
3567
    s->vlan = vlan;
3568
    s->fd = fd;
3569
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3570
    return 0;
3571
}
3572

    
3573
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3574
{
3575
    NetSocketState *s;
3576
    int fd, connected, ret, err;
3577
    struct sockaddr_in saddr;
3578

    
3579
    if (parse_host_port(&saddr, host_str) < 0)
3580
        return -1;
3581

    
3582
    fd = socket(PF_INET, SOCK_STREAM, 0);
3583
    if (fd < 0) {
3584
        perror("socket");
3585
        return -1;
3586
    }
3587
    socket_set_nonblock(fd);
3588

    
3589
    connected = 0;
3590
    for(;;) {
3591
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3592
        if (ret < 0) {
3593
            err = socket_error();
3594
            if (err == EINTR || err == EWOULDBLOCK) {
3595
            } else if (err == EINPROGRESS) {
3596
                break;
3597
            } else {
3598
                perror("connect");
3599
                closesocket(fd);
3600
                return -1;
3601
            }
3602
        } else {
3603
            connected = 1;
3604
            break;
3605
        }
3606
    }
3607
    s = net_socket_fd_init(vlan, fd, connected);
3608
    if (!s)
3609
        return -1;
3610
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3611
             "socket: connect to %s:%d", 
3612
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3613
    return 0;
3614
}
3615

    
3616
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3617
{
3618
    NetSocketState *s;
3619
    int fd;
3620
    struct sockaddr_in saddr;
3621

    
3622
    if (parse_host_port(&saddr, host_str) < 0)
3623
        return -1;
3624

    
3625

    
3626
    fd = net_socket_mcast_create(&saddr);
3627
    if (fd < 0)
3628
        return -1;
3629

    
3630
    s = net_socket_fd_init(vlan, fd, 0);
3631
    if (!s)
3632
        return -1;
3633

    
3634
    s->dgram_dst = saddr;
3635
    
3636
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3637
             "socket: mcast=%s:%d", 
3638
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3639
    return 0;
3640

    
3641
}
3642

    
3643
static int get_param_value(char *buf, int buf_size,
3644
                           const char *tag, const char *str)
3645
{
3646
    const char *p;
3647
    char *q;
3648
    char option[128];
3649

    
3650
    p = str;
3651
    for(;;) {
3652
        q = option;
3653
        while (*p != '\0' && *p != '=') {
3654
            if ((q - option) < sizeof(option) - 1)
3655
                *q++ = *p;
3656
            p++;
3657
        }
3658
        *q = '\0';
3659
        if (*p != '=')
3660
            break;
3661
        p++;
3662
        if (!strcmp(tag, option)) {
3663
            q = buf;
3664
            while (*p != '\0' && *p != ',') {
3665
                if ((q - buf) < buf_size - 1)
3666
                    *q++ = *p;
3667
                p++;
3668
            }
3669
            *q = '\0';
3670
            return q - buf;
3671
        } else {
3672
            while (*p != '\0' && *p != ',') {
3673
                p++;
3674
            }
3675
        }
3676
        if (*p != ',')
3677
            break;
3678
        p++;
3679
    }
3680
    return 0;
3681
}
3682

    
3683
int net_client_init(const char *str)
3684
{
3685
    const char *p;
3686
    char *q;
3687
    char device[64];
3688
    char buf[1024];
3689
    int vlan_id, ret;
3690
    VLANState *vlan;
3691

    
3692
    p = str;
3693
    q = device;
3694
    while (*p != '\0' && *p != ',') {
3695
        if ((q - device) < sizeof(device) - 1)
3696
            *q++ = *p;
3697
        p++;
3698
    }
3699
    *q = '\0';
3700
    if (*p == ',')
3701
        p++;
3702
    vlan_id = 0;
3703
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3704
        vlan_id = strtol(buf, NULL, 0);
3705
    }
3706
    vlan = qemu_find_vlan(vlan_id);
3707
    if (!vlan) {
3708
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3709
        return -1;
3710
    }
3711
    if (!strcmp(device, "nic")) {
3712
        NICInfo *nd;
3713
        uint8_t *macaddr;
3714

    
3715
        if (nb_nics >= MAX_NICS) {
3716
            fprintf(stderr, "Too Many NICs\n");
3717
            return -1;
3718
        }
3719
        nd = &nd_table[nb_nics];
3720
        macaddr = nd->macaddr;
3721
        macaddr[0] = 0x52;
3722
        macaddr[1] = 0x54;
3723
        macaddr[2] = 0x00;
3724
        macaddr[3] = 0x12;
3725
        macaddr[4] = 0x34;
3726
        macaddr[5] = 0x56 + nb_nics;
3727

    
3728
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3729
            if (parse_macaddr(macaddr, buf) < 0) {
3730
                fprintf(stderr, "invalid syntax for ethernet address\n");
3731
                return -1;
3732
            }
3733
        }
3734
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3735
            nd->model = strdup(buf);
3736
        }
3737
        nd->vlan = vlan;
3738
        nb_nics++;
3739
        ret = 0;
3740
    } else
3741
    if (!strcmp(device, "none")) {
3742
        /* does nothing. It is needed to signal that no network cards
3743
           are wanted */
3744
        ret = 0;
3745
    } else
3746
#ifdef CONFIG_SLIRP
3747
    if (!strcmp(device, "user")) {
3748
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3749
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3750
        }
3751
        ret = net_slirp_init(vlan);
3752
    } else
3753
#endif
3754
#ifdef _WIN32
3755
    if (!strcmp(device, "tap")) {
3756
        char ifname[64];
3757
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3758
            fprintf(stderr, "tap: no interface name\n");
3759
            return -1;
3760
        }
3761
        ret = tap_win32_init(vlan, ifname);
3762
    } else
3763
#else
3764
    if (!strcmp(device, "tap")) {
3765
        char ifname[64];
3766
        char setup_script[1024];
3767
        int fd;
3768
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3769
            fd = strtol(buf, NULL, 0);
3770
            ret = -1;
3771
            if (net_tap_fd_init(vlan, fd))
3772
                ret = 0;
3773
        } else {
3774
            get_param_value(ifname, sizeof(ifname), "ifname", p);
3775
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3776
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3777
            }
3778
            ret = net_tap_init(vlan, ifname, setup_script);
3779
        }
3780
    } else
3781
#endif
3782
    if (!strcmp(device, "socket")) {
3783
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3784
            int fd;
3785
            fd = strtol(buf, NULL, 0);
3786
            ret = -1;
3787
            if (net_socket_fd_init(vlan, fd, 1))
3788
                ret = 0;
3789
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3790
            ret = net_socket_listen_init(vlan, buf);
3791
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3792
            ret = net_socket_connect_init(vlan, buf);
3793
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3794
            ret = net_socket_mcast_init(vlan, buf);
3795
        } else {
3796
            fprintf(stderr, "Unknown socket options: %s\n", p);
3797
            return -1;
3798
        }
3799
    } else
3800
    {
3801
        fprintf(stderr, "Unknown network device: %s\n", device);
3802
        return -1;
3803
    }
3804
    if (ret < 0) {
3805
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3806
    }
3807
    
3808
    return ret;
3809
}
3810

    
3811
void do_info_network(void)
3812
{
3813
    VLANState *vlan;
3814
    VLANClientState *vc;
3815

    
3816
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3817
        term_printf("VLAN %d devices:\n", vlan->id);
3818
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3819
            term_printf("  %s\n", vc->info_str);
3820
    }
3821
}
3822

    
3823
/* Parse IDE and SCSI disk options */
3824
static int disk_options_init(int num_ide_disks,
3825
                             char ide_disk_options[][DISK_OPTIONS_SIZE],
3826
                             int snapshot,
3827
                             int num_scsi_disks,
3828
                             char scsi_disk_options[][DISK_OPTIONS_SIZE],
3829
                             int cdrom_index,
3830
                             int cyls,
3831
                             int heads,
3832
                             int secs,
3833
                             int translation)
3834
{
3835
    char buf[256];
3836
    char dev_name[64];
3837
    int id, i, j;
3838
    int cdrom_device;
3839
    int ide_cdrom_created = 0;
3840
    int scsi_index;
3841
    scsi_host_adapters temp_adapter;
3842

    
3843
    /* Process any IDE disks/cdroms */
3844
    for (i=0; i< num_ide_disks; i++) {
3845
        for (j=0; j<MAX_DISKS; j++) {
3846
            if (ide_disk_options[j][0] == '\0')
3847
                continue;
3848

    
3849
            if (get_param_value(buf, sizeof(buf),"type",ide_disk_options[j])) {
3850
                if (!strcmp(buf, "disk")) {
3851
                    cdrom_device = 0;
3852
                } else if (!strcmp(buf, "cdrom")) {
3853
                    cdrom_device = 1;
3854
                    ide_cdrom_created = 1;
3855
                } else {
3856
                    fprintf(stderr, "qemu: invalid IDE disk type= value: %s\n", buf);
3857
                    return -1;
3858
                }
3859
            } else {
3860
                cdrom_device = 0;
3861
            }
3862

    
3863
            if (cdrom_device) {
3864
                snprintf(dev_name, sizeof(dev_name), "cdrom%c", i);
3865
            } else {
3866
                snprintf(dev_name, sizeof(dev_name), "hd%c", i + 'a');
3867
            }
3868

    
3869
            if (!(get_param_value(buf, sizeof(buf),"img",ide_disk_options[j]))) {
3870
                fprintf(stderr, "qemu: missing IDE disk img= value.\n");
3871
                return -1;
3872
            }
3873

    
3874
            if (!(bs_table[i] = bdrv_new(dev_name))) {
3875
                fprintf(stderr, "qemu: unable to create new block device for:%s\n",dev_name);
3876
                return -1;
3877
            }
3878

    
3879
            if (cdrom_device) {
3880
                bdrv_set_type_hint(bs_table[i], BDRV_TYPE_CDROM);
3881
            }
3882

    
3883
            if (bdrv_open(bs_table[i], buf, snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
3884
                fprintf(stderr, "qemu: could not open hard disk image: '%s'\n",
3885
                        buf);
3886
                return -1;
3887
            }
3888
            if (i == 0 && cyls != 0) {
3889
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
3890
                bdrv_set_translation_hint(bs_table[i], translation);
3891
            }
3892
            ide_disk_options[j][0] = '\0';
3893

    
3894
            if (i == cdrom_index) {
3895
                cdrom_index = -1;
3896
            }
3897
            break; /* finished with this IDE device*/
3898
        }
3899
    }
3900

    
3901
    if (cdrom_index >= 0 && (!ide_cdrom_created)) {
3902
        bs_table[cdrom_index] = bdrv_new("cdrom");
3903
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
3904
    }
3905

    
3906
    for(i = 0; i < num_scsi_disks; i++) {
3907

    
3908
        temp_adapter = SCSI_LSI_53C895A;
3909
        scsi_hba_lsi++;
3910

    
3911
        /*Check for sdx= parameter */
3912
        if (get_param_value(buf, sizeof(buf), "sdx", scsi_disk_options[i])) {
3913
            if (buf[0] >= 'a' && buf[0] <= 'g') {
3914
                scsi_index = buf[0] - 'a';
3915
            } else{
3916
                fprintf(stderr, "qemu: sdx= option for SCSI must be one letter from a-g. %s \n",buf);
3917
                exit(1);
3918
            }
3919
        } else {
3920
             scsi_index = 0;
3921
        }
3922

    
3923
        /* Check for SCSI id specified. */
3924
        if (get_param_value(buf, sizeof(buf),"id",scsi_disk_options[i])) {
3925
            id = strtol(buf, NULL, 0);
3926
            if (id < 0 || id > 6) {
3927
                fprintf(stderr, "qemu: SCSI id must be from 0-6: %d\n", id);
3928
                return -1;
3929
            }
3930
            /* Check if id already used */
3931
            for(j = 0; j < MAX_SCSI_DISKS; j++) {
3932
                if (scsi_disks_info[j].device_type != SCSI_NONE &&
3933
                    j != i &&
3934
                    scsi_disks_info[j].adapter == temp_adapter &&
3935
                    scsi_disks_info[j].id == id  ) {
3936
                    fprintf(stderr, "qemu: SCSI id already used: %u\n", id);
3937
                    return -1;
3938
                }
3939
            }
3940
        } else {
3941
            id = -1;
3942
        }
3943
        scsi_disks_info[i].adapter = temp_adapter;
3944
        scsi_disks_info[i].id = id;
3945

    
3946
        if (get_param_value(buf, sizeof(buf),"type",scsi_disk_options[i])) {
3947
            if (!strcmp(buf, "disk")) {
3948
                cdrom_device = 0;
3949
            } else if (!strcmp(buf, "cdrom")) {
3950
                cdrom_device = 1;
3951
            } else {
3952
                fprintf(stderr, "qemu: invalid SCSI disk type= value: %s\n", buf);
3953
                return -1;
3954
            }
3955
        } else {
3956
            cdrom_device = 0;
3957
        }
3958

    
3959
        if (cdrom_device) {
3960
            snprintf(dev_name, sizeof(buf), "cdrom%c", scsi_index);
3961
            scsi_disks_info[scsi_index].device_type = SCSI_CDROM;
3962
        } else {
3963
            snprintf(dev_name, sizeof(buf), "sd%c", scsi_index + 'a');
3964
            scsi_disks_info[scsi_index].device_type = SCSI_DISK;
3965
        }
3966

    
3967
        if (!(bs_scsi_table[scsi_index] = bdrv_new(dev_name))) {
3968
            fprintf(stderr, "qemu: unable to create new block device for:%s\n",dev_name);
3969
            return -1;
3970
        }
3971

    
3972
        /* Get image filename from options and then try to open it */
3973
        if (get_param_value(buf, sizeof(buf),"img",scsi_disk_options[i])) {
3974
            if (bdrv_open(bs_scsi_table[scsi_index], buf, 0) < 0) {
3975
                fprintf(stderr, "qemu: could not open SCSI disk image img='%s'\n",buf);
3976
                return -1;
3977
            }
3978
        } else {
3979
            fprintf(stderr, "qemu: SCSI disk image not specified for sd%c \n", i + 'a');
3980
            return -1;
3981
        }
3982
    }
3983

    
3984
    return 0;
3985
}
3986

    
3987

    
3988
/***********************************************************/
3989
/* USB devices */
3990

    
3991
static USBPort *used_usb_ports;
3992
static USBPort *free_usb_ports;
3993

    
3994
/* ??? Maybe change this to register a hub to keep track of the topology.  */
3995
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3996
                            usb_attachfn attach)
3997
{
3998
    port->opaque = opaque;
3999
    port->index = index;
4000
    port->attach = attach;
4001
    port->next = free_usb_ports;
4002
    free_usb_ports = port;
4003
}
4004

    
4005
static int usb_device_add(const char *devname)
4006
{
4007
    const char *p;
4008
    USBDevice *dev;
4009
    USBPort *port;
4010

    
4011
    if (!free_usb_ports)
4012
        return -1;
4013

    
4014
    if (strstart(devname, "host:", &p)) {
4015
        dev = usb_host_device_open(p);
4016
    } else if (!strcmp(devname, "mouse")) {
4017
        dev = usb_mouse_init();
4018
    } else if (!strcmp(devname, "tablet")) {
4019
        dev = usb_tablet_init();
4020
    } else if (strstart(devname, "disk:", &p)) {
4021
        dev = usb_msd_init(p);
4022
    } else {
4023
        return -1;
4024
    }
4025
    if (!dev)
4026
        return -1;
4027

    
4028
    /* Find a USB port to add the device to.  */
4029
    port = free_usb_ports;
4030
    if (!port->next) {
4031
        USBDevice *hub;
4032

    
4033
        /* Create a new hub and chain it on.  */
4034
        free_usb_ports = NULL;
4035
        port->next = used_usb_ports;
4036
        used_usb_ports = port;
4037

    
4038
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4039
        usb_attach(port, hub);
4040
        port = free_usb_ports;
4041
    }
4042

    
4043
    free_usb_ports = port->next;
4044
    port->next = used_usb_ports;
4045
    used_usb_ports = port;
4046
    usb_attach(port, dev);
4047
    return 0;
4048
}
4049

    
4050
static int usb_device_del(const char *devname)
4051
{
4052
    USBPort *port;
4053
    USBPort **lastp;
4054
    USBDevice *dev;
4055
    int bus_num, addr;
4056
    const char *p;
4057

    
4058
    if (!used_usb_ports)
4059
        return -1;
4060

    
4061
    p = strchr(devname, '.');
4062
    if (!p) 
4063
        return -1;
4064
    bus_num = strtoul(devname, NULL, 0);
4065
    addr = strtoul(p + 1, NULL, 0);
4066
    if (bus_num != 0)
4067
        return -1;
4068

    
4069
    lastp = &used_usb_ports;
4070
    port = used_usb_ports;
4071
    while (port && port->dev->addr != addr) {
4072
        lastp = &port->next;
4073
        port = port->next;
4074
    }
4075

    
4076
    if (!port)
4077
        return -1;
4078

    
4079
    dev = port->dev;
4080
    *lastp = port->next;
4081
    usb_attach(port, NULL);
4082
    dev->handle_destroy(dev);
4083
    port->next = free_usb_ports;
4084
    free_usb_ports = port;
4085
    return 0;
4086
}
4087

    
4088
void do_usb_add(const char *devname)
4089
{
4090
    int ret;
4091
    ret = usb_device_add(devname);
4092
    if (ret < 0) 
4093
        term_printf("Could not add USB device '%s'\n", devname);
4094
}
4095

    
4096
void do_usb_del(const char *devname)
4097
{
4098
    int ret;
4099
    ret = usb_device_del(devname);
4100
    if (ret < 0) 
4101
        term_printf("Could not remove USB device '%s'\n", devname);
4102
}
4103

    
4104
void usb_info(void)
4105
{
4106
    USBDevice *dev;
4107
    USBPort *port;
4108
    const char *speed_str;
4109

    
4110
    if (!usb_enabled) {
4111
        term_printf("USB support not enabled\n");
4112
        return;
4113
    }
4114

    
4115
    for (port = used_usb_ports; port; port = port->next) {
4116
        dev = port->dev;
4117
        if (!dev)
4118
            continue;
4119
        switch(dev->speed) {
4120
        case USB_SPEED_LOW: 
4121
            speed_str = "1.5"; 
4122
            break;
4123
        case USB_SPEED_FULL: 
4124
            speed_str = "12"; 
4125
            break;
4126
        case USB_SPEED_HIGH: 
4127
            speed_str = "480"; 
4128
            break;
4129
        default:
4130
            speed_str = "?"; 
4131
            break;
4132
        }
4133
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4134
                    0, dev->addr, speed_str, dev->devname);
4135
    }
4136
}
4137

    
4138
/***********************************************************/
4139
/* pid file */
4140

    
4141
static char *pid_filename;
4142

    
4143
/* Remove PID file. Called on normal exit */
4144

    
4145
static void remove_pidfile(void) 
4146
{
4147
    unlink (pid_filename);
4148
}
4149

    
4150
static void create_pidfile(const char *filename)
4151
{
4152
    struct stat pidstat;
4153
    FILE *f;
4154

    
4155
    /* Try to write our PID to the named file */
4156
    if (stat(filename, &pidstat) < 0) {
4157
        if (errno == ENOENT) {
4158
            if ((f = fopen (filename, "w")) == NULL) {
4159
                perror("Opening pidfile");
4160
                exit(1);
4161
            }
4162
            fprintf(f, "%d\n", getpid());
4163
            fclose(f);
4164
            pid_filename = qemu_strdup(filename);
4165
            if (!pid_filename) {
4166
                fprintf(stderr, "Could not save PID filename");
4167
                exit(1);
4168
            }
4169
            atexit(remove_pidfile);
4170
        }
4171
    } else {
4172
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
4173
                filename);
4174
        exit(1);
4175
    }
4176
}
4177

    
4178
/***********************************************************/
4179
/* dumb display */
4180

    
4181
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4182
{
4183
}
4184

    
4185
static void dumb_resize(DisplayState *ds, int w, int h)
4186
{
4187
}
4188

    
4189
static void dumb_refresh(DisplayState *ds)
4190
{
4191
    vga_hw_update();
4192
}
4193

    
4194
void dumb_display_init(DisplayState *ds)
4195
{
4196
    ds->data = NULL;
4197
    ds->linesize = 0;
4198
    ds->depth = 0;
4199
    ds->dpy_update = dumb_update;
4200
    ds->dpy_resize = dumb_resize;
4201
    ds->dpy_refresh = dumb_refresh;
4202
}
4203

    
4204
/***********************************************************/
4205
/* I/O handling */
4206

    
4207
#define MAX_IO_HANDLERS 64
4208

    
4209
typedef struct IOHandlerRecord {
4210
    int fd;
4211
    IOCanRWHandler *fd_read_poll;
4212
    IOHandler *fd_read;
4213
    IOHandler *fd_write;
4214
    void *opaque;
4215
    /* temporary data */
4216
    struct pollfd *ufd;
4217
    struct IOHandlerRecord *next;
4218
} IOHandlerRecord;
4219

    
4220
static IOHandlerRecord *first_io_handler;
4221

    
4222
/* XXX: fd_read_poll should be suppressed, but an API change is
4223
   necessary in the character devices to suppress fd_can_read(). */
4224
int qemu_set_fd_handler2(int fd, 
4225
                         IOCanRWHandler *fd_read_poll, 
4226
                         IOHandler *fd_read, 
4227
                         IOHandler *fd_write, 
4228
                         void *opaque)
4229
{
4230
    IOHandlerRecord **pioh, *ioh;
4231

    
4232
    if (!fd_read && !fd_write) {
4233
        pioh = &first_io_handler;
4234
        for(;;) {
4235
            ioh = *pioh;
4236
            if (ioh == NULL)
4237
                break;
4238
            if (ioh->fd == fd) {
4239
                *pioh = ioh->next;
4240
                qemu_free(ioh);
4241
                break;
4242
            }
4243
            pioh = &ioh->next;
4244
        }
4245
    } else {
4246
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4247
            if (ioh->fd == fd)
4248
                goto found;
4249
        }
4250
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4251
        if (!ioh)
4252
            return -1;
4253
        ioh->next = first_io_handler;
4254
        first_io_handler = ioh;
4255
    found:
4256
        ioh->fd = fd;
4257
        ioh->fd_read_poll = fd_read_poll;
4258
        ioh->fd_read = fd_read;
4259
        ioh->fd_write = fd_write;
4260
        ioh->opaque = opaque;
4261
    }
4262
    return 0;
4263
}
4264

    
4265
int qemu_set_fd_handler(int fd, 
4266
                        IOHandler *fd_read, 
4267
                        IOHandler *fd_write, 
4268
                        void *opaque)
4269
{
4270
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4271
}
4272

    
4273
/***********************************************************/
4274
/* Polling handling */
4275

    
4276
typedef struct PollingEntry {
4277
    PollingFunc *func;
4278
    void *opaque;
4279
    struct PollingEntry *next;
4280
} PollingEntry;
4281

    
4282
static PollingEntry *first_polling_entry;
4283

    
4284
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4285
{
4286
    PollingEntry **ppe, *pe;
4287
    pe = qemu_mallocz(sizeof(PollingEntry));
4288
    if (!pe)
4289
        return -1;
4290
    pe->func = func;
4291
    pe->opaque = opaque;
4292
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4293
    *ppe = pe;
4294
    return 0;
4295
}
4296

    
4297
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4298
{
4299
    PollingEntry **ppe, *pe;
4300
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4301
        pe = *ppe;
4302
        if (pe->func == func && pe->opaque == opaque) {
4303
            *ppe = pe->next;
4304
            qemu_free(pe);
4305
            break;
4306
        }
4307
    }
4308
}
4309

    
4310
#ifdef _WIN32
4311
/***********************************************************/
4312
/* Wait objects support */
4313
typedef struct WaitObjects {
4314
    int num;
4315
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4316
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4317
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4318
} WaitObjects;
4319

    
4320
static WaitObjects wait_objects = {0};
4321
    
4322
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4323
{
4324
    WaitObjects *w = &wait_objects;
4325

    
4326
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4327
        return -1;
4328
    w->events[w->num] = handle;
4329
    w->func[w->num] = func;
4330
    w->opaque[w->num] = opaque;
4331
    w->num++;
4332
    return 0;
4333
}
4334

    
4335
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4336
{
4337
    int i, found;
4338
    WaitObjects *w = &wait_objects;
4339

    
4340
    found = 0;
4341
    for (i = 0; i < w->num; i++) {
4342
        if (w->events[i] == handle)
4343
            found = 1;
4344
        if (found) {
4345
            w->events[i] = w->events[i + 1];
4346
            w->func[i] = w->func[i + 1];
4347
            w->opaque[i] = w->opaque[i + 1];
4348
        }            
4349
    }
4350
    if (found)
4351
        w->num--;
4352
}
4353
#endif
4354

    
4355
/***********************************************************/
4356
/* savevm/loadvm support */
4357

    
4358
#define IO_BUF_SIZE 32768
4359

    
4360
struct QEMUFile {
4361
    FILE *outfile;
4362
    BlockDriverState *bs;
4363
    int is_file;
4364
    int is_writable;
4365
    int64_t base_offset;
4366
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4367
                           when reading */
4368
    int buf_index;
4369
    int buf_size; /* 0 when writing */
4370
    uint8_t buf[IO_BUF_SIZE];
4371
};
4372

    
4373
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4374
{
4375
    QEMUFile *f;
4376

    
4377
    f = qemu_mallocz(sizeof(QEMUFile));
4378
    if (!f)
4379
        return NULL;
4380
    if (!strcmp(mode, "wb")) {
4381
        f->is_writable = 1;
4382
    } else if (!strcmp(mode, "rb")) {
4383
        f->is_writable = 0;
4384
    } else {
4385
        goto fail;
4386
    }
4387
    f->outfile = fopen(filename, mode);
4388
    if (!f->outfile)
4389
        goto fail;
4390
    f->is_file = 1;
4391
    return f;
4392
 fail:
4393
    if (f->outfile)
4394
        fclose(f->outfile);
4395
    qemu_free(f);
4396
    return NULL;
4397
}
4398

    
4399
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4400
{
4401
    QEMUFile *f;
4402

    
4403
    f = qemu_mallocz(sizeof(QEMUFile));
4404
    if (!f)
4405
        return NULL;
4406
    f->is_file = 0;
4407
    f->bs = bs;
4408
    f->is_writable = is_writable;
4409
    f->base_offset = offset;
4410
    return f;
4411
}
4412

    
4413
void qemu_fflush(QEMUFile *f)
4414
{
4415
    if (!f->is_writable)
4416
        return;
4417
    if (f->buf_index > 0) {
4418
        if (f->is_file) {
4419
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4420
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4421
        } else {
4422
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4423
                        f->buf, f->buf_index);
4424
        }
4425
        f->buf_offset += f->buf_index;
4426
        f->buf_index = 0;
4427
    }
4428
}
4429

    
4430
static void qemu_fill_buffer(QEMUFile *f)
4431
{
4432
    int len;
4433

    
4434
    if (f->is_writable)
4435
        return;
4436
    if (f->is_file) {
4437
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4438
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4439
        if (len < 0)
4440
            len = 0;
4441
    } else {
4442
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4443
                         f->buf, IO_BUF_SIZE);
4444
        if (len < 0)
4445
            len = 0;
4446
    }
4447
    f->buf_index = 0;
4448
    f->buf_size = len;
4449
    f->buf_offset += len;
4450
}
4451

    
4452
void qemu_fclose(QEMUFile *f)
4453
{
4454
    if (f->is_writable)
4455
        qemu_fflush(f);
4456
    if (f->is_file) {
4457
        fclose(f->outfile);
4458
    }
4459
    qemu_free(f);
4460
}
4461

    
4462
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4463
{
4464
    int l;
4465
    while (size > 0) {
4466
        l = IO_BUF_SIZE - f->buf_index;
4467
        if (l > size)
4468
            l = size;
4469
        memcpy(f->buf + f->buf_index, buf, l);
4470
        f->buf_index += l;
4471
        buf += l;
4472
        size -= l;
4473
        if (f->buf_index >= IO_BUF_SIZE)
4474
            qemu_fflush(f);
4475
    }
4476
}
4477

    
4478
void qemu_put_byte(QEMUFile *f, int v)
4479
{
4480
    f->buf[f->buf_index++] = v;
4481
    if (f->buf_index >= IO_BUF_SIZE)
4482
        qemu_fflush(f);
4483
}
4484

    
4485
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4486
{
4487
    int size, l;
4488

    
4489
    size = size1;
4490
    while (size > 0) {
4491
        l = f->buf_size - f->buf_index;
4492
        if (l == 0) {
4493
            qemu_fill_buffer(f);
4494
            l = f->buf_size - f->buf_index;
4495
            if (l == 0)
4496
                break;
4497
        }
4498
        if (l > size)
4499
            l = size;
4500
        memcpy(buf, f->buf + f->buf_index, l);
4501
        f->buf_index += l;
4502
        buf += l;
4503
        size -= l;
4504
    }
4505
    return size1 - size;
4506
}
4507

    
4508
int qemu_get_byte(QEMUFile *f)
4509
{
4510
    if (f->buf_index >= f->buf_size) {
4511
        qemu_fill_buffer(f);
4512
        if (f->buf_index >= f->buf_size)
4513
            return 0;
4514
    }
4515
    return f->buf[f->buf_index++];
4516
}
4517

    
4518
int64_t qemu_ftell(QEMUFile *f)
4519
{
4520
    return f->buf_offset - f->buf_size + f->buf_index;
4521
}
4522

    
4523
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4524
{
4525
    if (whence == SEEK_SET) {
4526
        /* nothing to do */
4527
    } else if (whence == SEEK_CUR) {
4528
        pos += qemu_ftell(f);
4529
    } else {
4530
        /* SEEK_END not supported */
4531
        return -1;
4532
    }
4533
    if (f->is_writable) {
4534
        qemu_fflush(f);
4535
        f->buf_offset = pos;
4536
    } else {
4537
        f->buf_offset = pos;
4538
        f->buf_index = 0;
4539
        f->buf_size = 0;
4540
    }
4541
    return pos;
4542
}
4543

    
4544
void qemu_put_be16(QEMUFile *f, unsigned int v)
4545
{
4546
    qemu_put_byte(f, v >> 8);
4547
    qemu_put_byte(f, v);
4548
}
4549

    
4550
void qemu_put_be32(QEMUFile *f, unsigned int v)
4551
{
4552
    qemu_put_byte(f, v >> 24);
4553
    qemu_put_byte(f, v >> 16);
4554
    qemu_put_byte(f, v >> 8);
4555
    qemu_put_byte(f, v);
4556
}
4557

    
4558
void qemu_put_be64(QEMUFile *f, uint64_t v)
4559
{
4560
    qemu_put_be32(f, v >> 32);
4561
    qemu_put_be32(f, v);
4562
}
4563

    
4564
unsigned int qemu_get_be16(QEMUFile *f)
4565
{
4566
    unsigned int v;
4567
    v = qemu_get_byte(f) << 8;
4568
    v |= qemu_get_byte(f);
4569
    return v;
4570
}
4571

    
4572
unsigned int qemu_get_be32(QEMUFile *f)
4573
{
4574
    unsigned int v;
4575
    v = qemu_get_byte(f) << 24;
4576
    v |= qemu_get_byte(f) << 16;
4577
    v |= qemu_get_byte(f) << 8;
4578
    v |= qemu_get_byte(f);
4579
    return v;
4580
}
4581

    
4582
uint64_t qemu_get_be64(QEMUFile *f)
4583
{
4584
    uint64_t v;
4585
    v = (uint64_t)qemu_get_be32(f) << 32;
4586
    v |= qemu_get_be32(f);
4587
    return v;
4588
}
4589

    
4590
typedef struct SaveStateEntry {
4591
    char idstr[256];
4592
    int instance_id;
4593
    int version_id;
4594
    SaveStateHandler *save_state;
4595
    LoadStateHandler *load_state;
4596
    void *opaque;
4597
    struct SaveStateEntry *next;
4598
} SaveStateEntry;
4599

    
4600
static SaveStateEntry *first_se;
4601

    
4602
int register_savevm(const char *idstr, 
4603
                    int instance_id, 
4604
                    int version_id,
4605
                    SaveStateHandler *save_state,
4606
                    LoadStateHandler *load_state,
4607
                    void *opaque)
4608
{
4609
    SaveStateEntry *se, **pse;
4610

    
4611
    se = qemu_malloc(sizeof(SaveStateEntry));
4612
    if (!se)
4613
        return -1;
4614
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4615
    se->instance_id = instance_id;
4616
    se->version_id = version_id;
4617
    se->save_state = save_state;
4618
    se->load_state = load_state;
4619
    se->opaque = opaque;
4620
    se->next = NULL;
4621

    
4622
    /* add at the end of list */
4623
    pse = &first_se;
4624
    while (*pse != NULL)
4625
        pse = &(*pse)->next;
4626
    *pse = se;
4627
    return 0;
4628
}
4629

    
4630
#define QEMU_VM_FILE_MAGIC   0x5145564d
4631
#define QEMU_VM_FILE_VERSION 0x00000002
4632

    
4633
int qemu_savevm_state(QEMUFile *f)
4634
{
4635
    SaveStateEntry *se;
4636
    int len, ret;
4637
    int64_t cur_pos, len_pos, total_len_pos;
4638

    
4639
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4640
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4641
    total_len_pos = qemu_ftell(f);
4642
    qemu_put_be64(f, 0); /* total size */
4643

    
4644
    for(se = first_se; se != NULL; se = se->next) {
4645
        /* ID string */
4646
        len = strlen(se->idstr);
4647
        qemu_put_byte(f, len);
4648
        qemu_put_buffer(f, se->idstr, len);
4649

    
4650
        qemu_put_be32(f, se->instance_id);
4651
        qemu_put_be32(f, se->version_id);
4652

    
4653
        /* record size: filled later */
4654
        len_pos = qemu_ftell(f);
4655
        qemu_put_be32(f, 0);
4656
        
4657
        se->save_state(f, se->opaque);
4658

    
4659
        /* fill record size */
4660
        cur_pos = qemu_ftell(f);
4661
        len = cur_pos - len_pos - 4;
4662
        qemu_fseek(f, len_pos, SEEK_SET);
4663
        qemu_put_be32(f, len);
4664
        qemu_fseek(f, cur_pos, SEEK_SET);
4665
    }
4666
    cur_pos = qemu_ftell(f);
4667
    qemu_fseek(f, total_len_pos, SEEK_SET);
4668
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4669
    qemu_fseek(f, cur_pos, SEEK_SET);
4670

    
4671
    ret = 0;
4672
    return ret;
4673
}
4674

    
4675
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4676
{
4677
    SaveStateEntry *se;
4678

    
4679
    for(se = first_se; se != NULL; se = se->next) {
4680
        if (!strcmp(se->idstr, idstr) && 
4681
            instance_id == se->instance_id)
4682
            return se;
4683
    }
4684
    return NULL;
4685
}
4686

    
4687
int qemu_loadvm_state(QEMUFile *f)
4688
{
4689
    SaveStateEntry *se;
4690
    int len, ret, instance_id, record_len, version_id;
4691
    int64_t total_len, end_pos, cur_pos;
4692
    unsigned int v;
4693
    char idstr[256];
4694
    
4695
    v = qemu_get_be32(f);
4696
    if (v != QEMU_VM_FILE_MAGIC)
4697
        goto fail;
4698
    v = qemu_get_be32(f);
4699
    if (v != QEMU_VM_FILE_VERSION) {
4700
    fail:
4701
        ret = -1;
4702
        goto the_end;
4703
    }
4704
    total_len = qemu_get_be64(f);
4705
    end_pos = total_len + qemu_ftell(f);
4706
    for(;;) {
4707
        if (qemu_ftell(f) >= end_pos)
4708
            break;
4709
        len = qemu_get_byte(f);
4710
        qemu_get_buffer(f, idstr, len);
4711
        idstr[len] = '\0';
4712
        instance_id = qemu_get_be32(f);
4713
        version_id = qemu_get_be32(f);
4714
        record_len = qemu_get_be32(f);
4715
#if 0
4716
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4717
               idstr, instance_id, version_id, record_len);
4718
#endif
4719
        cur_pos = qemu_ftell(f);
4720
        se = find_se(idstr, instance_id);
4721
        if (!se) {
4722
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4723
                    instance_id, idstr);
4724
        } else {
4725
            ret = se->load_state(f, se->opaque, version_id);
4726
            if (ret < 0) {
4727
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4728
                        instance_id, idstr);
4729
            }
4730
        }
4731
        /* always seek to exact end of record */
4732
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4733
    }
4734
    ret = 0;
4735
 the_end:
4736
    return ret;
4737
}
4738

    
4739
/* device can contain snapshots */
4740
static int bdrv_can_snapshot(BlockDriverState *bs)
4741
{
4742
    return (bs &&
4743
            !bdrv_is_removable(bs) &&
4744
            !bdrv_is_read_only(bs));
4745
}
4746

    
4747
/* device must be snapshots in order to have a reliable snapshot */
4748
static int bdrv_has_snapshot(BlockDriverState *bs)
4749
{
4750
    return (bs &&
4751
            !bdrv_is_removable(bs) &&
4752
            !bdrv_is_read_only(bs));
4753
}
4754

    
4755
static BlockDriverState *get_bs_snapshots(void)
4756
{
4757
    BlockDriverState *bs;
4758
    int i;
4759

    
4760
    if (bs_snapshots)
4761
        return bs_snapshots;
4762
    for(i = 0; i <= MAX_DISKS; i++) {
4763
        bs = bs_table[i];
4764
        if (bdrv_can_snapshot(bs))
4765
            goto ok;
4766
    }
4767
    return NULL;
4768
 ok:
4769
    bs_snapshots = bs;
4770
    return bs;
4771
}
4772

    
4773
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4774
                              const char *name)
4775
{
4776
    QEMUSnapshotInfo *sn_tab, *sn;
4777
    int nb_sns, i, ret;
4778
    
4779
    ret = -ENOENT;
4780
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4781
    if (nb_sns < 0)
4782
        return ret;
4783
    for(i = 0; i < nb_sns; i++) {
4784
        sn = &sn_tab[i];
4785
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4786
            *sn_info = *sn;
4787
            ret = 0;
4788
            break;
4789
        }
4790
    }
4791
    qemu_free(sn_tab);
4792
    return ret;
4793
}
4794

    
4795
void do_savevm(const char *name)
4796
{
4797
    BlockDriverState *bs, *bs1;
4798
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4799
    int must_delete, ret, i;
4800
    BlockDriverInfo bdi1, *bdi = &bdi1;
4801
    QEMUFile *f;
4802
    int saved_vm_running;
4803
#ifdef _WIN32
4804
    struct _timeb tb;
4805
#else
4806
    struct timeval tv;
4807
#endif
4808

    
4809
    bs = get_bs_snapshots();
4810
    if (!bs) {
4811
        term_printf("No block device can accept snapshots\n");
4812
        return;
4813
    }
4814

    
4815
    /* ??? Should this occur after vm_stop?  */
4816
    qemu_aio_flush();
4817

    
4818
    saved_vm_running = vm_running;
4819
    vm_stop(0);
4820
    
4821
    must_delete = 0;
4822
    if (name) {
4823
        ret = bdrv_snapshot_find(bs, old_sn, name);
4824
        if (ret >= 0) {
4825
            must_delete = 1;
4826
        }
4827
    }
4828
    memset(sn, 0, sizeof(*sn));
4829
    if (must_delete) {
4830
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4831
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4832
    } else {
4833
        if (name)
4834
            pstrcpy(sn->name, sizeof(sn->name), name);
4835
    }
4836

    
4837
    /* fill auxiliary fields */
4838
#ifdef _WIN32
4839
    _ftime(&tb);
4840
    sn->date_sec = tb.time;
4841
    sn->date_nsec = tb.millitm * 1000000;
4842
#else
4843
    gettimeofday(&tv, NULL);
4844
    sn->date_sec = tv.tv_sec;
4845
    sn->date_nsec = tv.tv_usec * 1000;
4846
#endif
4847
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4848
    
4849
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4850
        term_printf("Device %s does not support VM state snapshots\n",
4851
                    bdrv_get_device_name(bs));
4852
        goto the_end;
4853
    }
4854
    
4855
    /* save the VM state */
4856
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4857
    if (!f) {
4858
        term_printf("Could not open VM state file\n");
4859
        goto the_end;
4860
    }
4861
    ret = qemu_savevm_state(f);
4862
    sn->vm_state_size = qemu_ftell(f);
4863
    qemu_fclose(f);
4864
    if (ret < 0) {
4865
        term_printf("Error %d while writing VM\n", ret);
4866
        goto the_end;
4867
    }
4868
    
4869
    /* create the snapshots */
4870

    
4871
    for(i = 0; i < MAX_DISKS; i++) {
4872
        bs1 = bs_table[i];
4873
        if (bdrv_has_snapshot(bs1)) {
4874
            if (must_delete) {
4875
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4876
                if (ret < 0) {
4877
                    term_printf("Error while deleting snapshot on '%s'\n",
4878
                                bdrv_get_device_name(bs1));
4879
                }
4880
            }
4881
            ret = bdrv_snapshot_create(bs1, sn);
4882
            if (ret < 0) {
4883
                term_printf("Error while creating snapshot on '%s'\n",
4884
                            bdrv_get_device_name(bs1));
4885
            }
4886
        }
4887
    }
4888

    
4889
 the_end:
4890
    if (saved_vm_running)
4891
        vm_start();
4892
}
4893

    
4894
void do_loadvm(const char *name)
4895
{
4896
    BlockDriverState *bs, *bs1;
4897
    BlockDriverInfo bdi1, *bdi = &bdi1;
4898
    QEMUFile *f;
4899
    int i, ret;
4900
    int saved_vm_running;
4901

    
4902
    bs = get_bs_snapshots();
4903
    if (!bs) {
4904
        term_printf("No block device supports snapshots\n");
4905
        return;
4906
    }
4907
    
4908
    /* Flush all IO requests so they don't interfere with the new state.  */
4909
    qemu_aio_flush();
4910

    
4911
    saved_vm_running = vm_running;
4912
    vm_stop(0);
4913

    
4914
    for(i = 0; i <= MAX_DISKS; i++) {
4915
        bs1 = bs_table[i];
4916
        if (bdrv_has_snapshot(bs1)) {
4917
            ret = bdrv_snapshot_goto(bs1, name);
4918
            if (ret < 0) {
4919
                if (bs != bs1)
4920
                    term_printf("Warning: ");
4921
                switch(ret) {
4922
                case -ENOTSUP:
4923
                    term_printf("Snapshots not supported on device '%s'\n",
4924
                                bdrv_get_device_name(bs1));
4925
                    break;
4926
                case -ENOENT:
4927
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
4928
                                name, bdrv_get_device_name(bs1));
4929
                    break;
4930
                default:
4931
                    term_printf("Error %d while activating snapshot on '%s'\n",
4932
                                ret, bdrv_get_device_name(bs1));
4933
                    break;
4934
                }
4935
                /* fatal on snapshot block device */
4936
                if (bs == bs1)
4937
                    goto the_end;
4938
            }
4939
        }
4940
    }
4941

    
4942
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4943
        term_printf("Device %s does not support VM state snapshots\n",
4944
                    bdrv_get_device_name(bs));
4945
        return;
4946
    }
4947
    
4948
    /* restore the VM state */
4949
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4950
    if (!f) {
4951
        term_printf("Could not open VM state file\n");
4952
        goto the_end;
4953
    }
4954
    ret = qemu_loadvm_state(f);
4955
    qemu_fclose(f);
4956
    if (ret < 0) {
4957
        term_printf("Error %d while loading VM state\n", ret);
4958
    }
4959
 the_end:
4960
    if (saved_vm_running)
4961
        vm_start();
4962
}
4963

    
4964
void do_delvm(const char *name)
4965
{
4966
    BlockDriverState *bs, *bs1;
4967
    int i, ret;
4968

    
4969
    bs = get_bs_snapshots();
4970
    if (!bs) {
4971
        term_printf("No block device supports snapshots\n");
4972
        return;
4973
    }
4974
    
4975
    for(i = 0; i <= MAX_DISKS; i++) {
4976
        bs1 = bs_table[i];
4977
        if (bdrv_has_snapshot(bs1)) {
4978
            ret = bdrv_snapshot_delete(bs1, name);
4979
            if (ret < 0) {
4980
                if (ret == -ENOTSUP)
4981
                    term_printf("Snapshots not supported on device '%s'\n",
4982
                                bdrv_get_device_name(bs1));
4983
                else
4984
                    term_printf("Error %d while deleting snapshot on '%s'\n",
4985
                                ret, bdrv_get_device_name(bs1));
4986
            }
4987
        }
4988
    }
4989
}
4990

    
4991
void do_info_snapshots(void)
4992
{
4993
    BlockDriverState *bs, *bs1;
4994
    QEMUSnapshotInfo *sn_tab, *sn;
4995
    int nb_sns, i;
4996
    char buf[256];
4997

    
4998
    bs = get_bs_snapshots();
4999
    if (!bs) {
5000
        term_printf("No available block device supports snapshots\n");
5001
        return;
5002
    }
5003
    term_printf("Snapshot devices:");
5004
    for(i = 0; i <= MAX_DISKS; i++) {
5005
        bs1 = bs_table[i];
5006
        if (bdrv_has_snapshot(bs1)) {
5007
            if (bs == bs1)
5008
                term_printf(" %s", bdrv_get_device_name(bs1));
5009
        }
5010
    }
5011
    term_printf("\n");
5012

    
5013
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5014
    if (nb_sns < 0) {
5015
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5016
        return;
5017
    }
5018
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5019
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5020
    for(i = 0; i < nb_sns; i++) {
5021
        sn = &sn_tab[i];
5022
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5023
    }
5024
    qemu_free(sn_tab);
5025
}
5026

    
5027
/***********************************************************/
5028
/* cpu save/restore */
5029

    
5030
#if defined(TARGET_I386)
5031

    
5032
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5033
{
5034
    qemu_put_be32(f, dt->selector);
5035
    qemu_put_betl(f, dt->base);
5036
    qemu_put_be32(f, dt->limit);
5037
    qemu_put_be32(f, dt->flags);
5038
}
5039

    
5040
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5041
{
5042
    dt->selector = qemu_get_be32(f);
5043
    dt->base = qemu_get_betl(f);
5044
    dt->limit = qemu_get_be32(f);
5045
    dt->flags = qemu_get_be32(f);
5046
}
5047

    
5048
void cpu_save(QEMUFile *f, void *opaque)
5049
{
5050
    CPUState *env = opaque;
5051
    uint16_t fptag, fpus, fpuc, fpregs_format;
5052
    uint32_t hflags;
5053
    int i;
5054
    
5055
    for(i = 0; i < CPU_NB_REGS; i++)
5056
        qemu_put_betls(f, &env->regs[i]);
5057
    qemu_put_betls(f, &env->eip);
5058
    qemu_put_betls(f, &env->eflags);
5059
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5060
    qemu_put_be32s(f, &hflags);
5061
    
5062
    /* FPU */
5063
    fpuc = env->fpuc;
5064
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5065
    fptag = 0;
5066
    for(i = 0; i < 8; i++) {
5067
        fptag |= ((!env->fptags[i]) << i);
5068
    }
5069
    
5070
    qemu_put_be16s(f, &fpuc);
5071
    qemu_put_be16s(f, &fpus);
5072
    qemu_put_be16s(f, &fptag);
5073

    
5074
#ifdef USE_X86LDOUBLE
5075
    fpregs_format = 0;
5076
#else
5077
    fpregs_format = 1;
5078
#endif
5079
    qemu_put_be16s(f, &fpregs_format);
5080
    
5081
    for(i = 0; i < 8; i++) {
5082
#ifdef USE_X86LDOUBLE
5083
        {
5084
            uint64_t mant;
5085
            uint16_t exp;
5086
            /* we save the real CPU data (in case of MMX usage only 'mant'
5087
               contains the MMX register */
5088
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5089
            qemu_put_be64(f, mant);
5090
            qemu_put_be16(f, exp);
5091
        }
5092
#else
5093
        /* if we use doubles for float emulation, we save the doubles to
5094
           avoid losing information in case of MMX usage. It can give
5095
           problems if the image is restored on a CPU where long
5096
           doubles are used instead. */
5097
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5098
#endif
5099
    }
5100

    
5101
    for(i = 0; i < 6; i++)
5102
        cpu_put_seg(f, &env->segs[i]);
5103
    cpu_put_seg(f, &env->ldt);
5104
    cpu_put_seg(f, &env->tr);
5105
    cpu_put_seg(f, &env->gdt);
5106
    cpu_put_seg(f, &env->idt);
5107
    
5108
    qemu_put_be32s(f, &env->sysenter_cs);
5109
    qemu_put_be32s(f, &env->sysenter_esp);
5110
    qemu_put_be32s(f, &env->sysenter_eip);
5111
    
5112
    qemu_put_betls(f, &env->cr[0]);
5113
    qemu_put_betls(f, &env->cr[2]);
5114
    qemu_put_betls(f, &env->cr[3]);
5115
    qemu_put_betls(f, &env->cr[4]);
5116
    
5117
    for(i = 0; i < 8; i++)
5118
        qemu_put_betls(f, &env->dr[i]);
5119

    
5120
    /* MMU */
5121
    qemu_put_be32s(f, &env->a20_mask);
5122

    
5123
    /* XMM */
5124
    qemu_put_be32s(f, &env->mxcsr);
5125
    for(i = 0; i < CPU_NB_REGS; i++) {
5126
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5127
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5128
    }
5129

    
5130
#ifdef TARGET_X86_64
5131
    qemu_put_be64s(f, &env->efer);
5132
    qemu_put_be64s(f, &env->star);
5133
    qemu_put_be64s(f, &env->lstar);
5134
    qemu_put_be64s(f, &env->cstar);
5135
    qemu_put_be64s(f, &env->fmask);
5136
    qemu_put_be64s(f, &env->kernelgsbase);
5137
#endif
5138
    qemu_put_be32s(f, &env->smbase);
5139
}
5140

    
5141
#ifdef USE_X86LDOUBLE
5142
/* XXX: add that in a FPU generic layer */
5143
union x86_longdouble {
5144
    uint64_t mant;
5145
    uint16_t exp;
5146
};
5147

    
5148
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5149
#define EXPBIAS1 1023
5150
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5151
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5152

    
5153
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5154
{
5155
    int e;
5156
    /* mantissa */
5157
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5158
    /* exponent + sign */
5159
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5160
    e |= SIGND1(temp) >> 16;
5161
    p->exp = e;
5162
}
5163
#endif
5164

    
5165
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5166
{
5167
    CPUState *env = opaque;
5168
    int i, guess_mmx;
5169
    uint32_t hflags;
5170
    uint16_t fpus, fpuc, fptag, fpregs_format;
5171

    
5172
    if (version_id != 3 && version_id != 4)
5173
        return -EINVAL;
5174
    for(i = 0; i < CPU_NB_REGS; i++)
5175
        qemu_get_betls(f, &env->regs[i]);
5176
    qemu_get_betls(f, &env->eip);
5177
    qemu_get_betls(f, &env->eflags);
5178
    qemu_get_be32s(f, &hflags);
5179

    
5180
    qemu_get_be16s(f, &fpuc);
5181
    qemu_get_be16s(f, &fpus);
5182
    qemu_get_be16s(f, &fptag);
5183
    qemu_get_be16s(f, &fpregs_format);
5184
    
5185
    /* NOTE: we cannot always restore the FPU state if the image come
5186
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5187
       if we are in an MMX state to restore correctly in that case. */
5188
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5189
    for(i = 0; i < 8; i++) {
5190
        uint64_t mant;
5191
        uint16_t exp;
5192
        
5193
        switch(fpregs_format) {
5194
        case 0:
5195
            mant = qemu_get_be64(f);
5196
            exp = qemu_get_be16(f);
5197
#ifdef USE_X86LDOUBLE
5198
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5199
#else
5200
            /* difficult case */
5201
            if (guess_mmx)
5202
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5203
            else
5204
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5205
#endif
5206
            break;
5207
        case 1:
5208
            mant = qemu_get_be64(f);
5209
#ifdef USE_X86LDOUBLE
5210
            {
5211
                union x86_longdouble *p;
5212
                /* difficult case */
5213
                p = (void *)&env->fpregs[i];
5214
                if (guess_mmx) {
5215
                    p->mant = mant;
5216
                    p->exp = 0xffff;
5217
                } else {
5218
                    fp64_to_fp80(p, mant);
5219
                }
5220
            }
5221
#else
5222
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5223
#endif            
5224
            break;
5225
        default:
5226
            return -EINVAL;
5227
        }
5228
    }
5229

    
5230
    env->fpuc = fpuc;
5231
    /* XXX: restore FPU round state */
5232
    env->fpstt = (fpus >> 11) & 7;
5233
    env->fpus = fpus & ~0x3800;
5234
    fptag ^= 0xff;
5235
    for(i = 0; i < 8; i++) {
5236
        env->fptags[i] = (fptag >> i) & 1;
5237
    }
5238
    
5239
    for(i = 0; i < 6; i++)
5240
        cpu_get_seg(f, &env->segs[i]);
5241
    cpu_get_seg(f, &env->ldt);
5242
    cpu_get_seg(f, &env->tr);
5243
    cpu_get_seg(f, &env->gdt);
5244
    cpu_get_seg(f, &env->idt);
5245
    
5246
    qemu_get_be32s(f, &env->sysenter_cs);
5247
    qemu_get_be32s(f, &env->sysenter_esp);
5248
    qemu_get_be32s(f, &env->sysenter_eip);
5249
    
5250
    qemu_get_betls(f, &env->cr[0]);
5251
    qemu_get_betls(f, &env->cr[2]);
5252
    qemu_get_betls(f, &env->cr[3]);
5253
    qemu_get_betls(f, &env->cr[4]);
5254
    
5255
    for(i = 0; i < 8; i++)
5256
        qemu_get_betls(f, &env->dr[i]);
5257

    
5258
    /* MMU */
5259
    qemu_get_be32s(f, &env->a20_mask);
5260

    
5261
    qemu_get_be32s(f, &env->mxcsr);
5262
    for(i = 0; i < CPU_NB_REGS; i++) {
5263
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5264
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5265
    }
5266

    
5267
#ifdef TARGET_X86_64
5268
    qemu_get_be64s(f, &env->efer);
5269
    qemu_get_be64s(f, &env->star);
5270
    qemu_get_be64s(f, &env->lstar);
5271
    qemu_get_be64s(f, &env->cstar);
5272
    qemu_get_be64s(f, &env->fmask);
5273
    qemu_get_be64s(f, &env->kernelgsbase);
5274
#endif
5275
    if (version_id >= 4) 
5276
        qemu_get_be32s(f, &env->smbase);
5277

    
5278
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5279
    env->hflags = hflags;
5280
    tlb_flush(env, 1);
5281
    return 0;
5282
}
5283

    
5284
#elif defined(TARGET_PPC)
5285
void cpu_save(QEMUFile *f, void *opaque)
5286
{
5287
}
5288

    
5289
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5290
{
5291
    return 0;
5292
}
5293

    
5294
#elif defined(TARGET_MIPS)
5295
void cpu_save(QEMUFile *f, void *opaque)
5296
{
5297
}
5298

    
5299
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5300
{
5301
    return 0;
5302
}
5303

    
5304
#elif defined(TARGET_SPARC)
5305
void cpu_save(QEMUFile *f, void *opaque)
5306
{
5307
    CPUState *env = opaque;
5308
    int i;
5309
    uint32_t tmp;
5310

    
5311
    for(i = 0; i < 8; i++)
5312
        qemu_put_betls(f, &env->gregs[i]);
5313
    for(i = 0; i < NWINDOWS * 16; i++)
5314
        qemu_put_betls(f, &env->regbase[i]);
5315

    
5316
    /* FPU */
5317
    for(i = 0; i < TARGET_FPREGS; i++) {
5318
        union {
5319
            float32 f;
5320
            uint32_t i;
5321
        } u;
5322
        u.f = env->fpr[i];
5323
        qemu_put_be32(f, u.i);
5324
    }
5325

    
5326
    qemu_put_betls(f, &env->pc);
5327
    qemu_put_betls(f, &env->npc);
5328
    qemu_put_betls(f, &env->y);
5329
    tmp = GET_PSR(env);
5330
    qemu_put_be32(f, tmp);
5331
    qemu_put_betls(f, &env->fsr);
5332
    qemu_put_betls(f, &env->tbr);
5333
#ifndef TARGET_SPARC64
5334
    qemu_put_be32s(f, &env->wim);
5335
    /* MMU */
5336
    for(i = 0; i < 16; i++)
5337
        qemu_put_be32s(f, &env->mmuregs[i]);
5338
#endif
5339
}
5340

    
5341
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5342
{
5343
    CPUState *env = opaque;
5344
    int i;
5345
    uint32_t tmp;
5346

    
5347
    for(i = 0; i < 8; i++)
5348
        qemu_get_betls(f, &env->gregs[i]);
5349
    for(i = 0; i < NWINDOWS * 16; i++)
5350
        qemu_get_betls(f, &env->regbase[i]);
5351

    
5352
    /* FPU */
5353
    for(i = 0; i < TARGET_FPREGS; i++) {
5354
        union {
5355
            float32 f;
5356
            uint32_t i;
5357
        } u;
5358
        u.i = qemu_get_be32(f);
5359
        env->fpr[i] = u.f;
5360
    }
5361

    
5362
    qemu_get_betls(f, &env->pc);
5363
    qemu_get_betls(f, &env->npc);
5364
    qemu_get_betls(f, &env->y);
5365
    tmp = qemu_get_be32(f);
5366
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5367
                     correctly updated */
5368
    PUT_PSR(env, tmp);
5369
    qemu_get_betls(f, &env->fsr);
5370
    qemu_get_betls(f, &env->tbr);
5371
#ifndef TARGET_SPARC64
5372
    qemu_get_be32s(f, &env->wim);
5373
    /* MMU */
5374
    for(i = 0; i < 16; i++)
5375
        qemu_get_be32s(f, &env->mmuregs[i]);
5376
#endif
5377
    tlb_flush(env, 1);
5378
    return 0;
5379
}
5380

    
5381
#elif defined(TARGET_ARM)
5382

    
5383
/* ??? Need to implement these.  */
5384
void cpu_save(QEMUFile *f, void *opaque)
5385
{
5386
}
5387

    
5388
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5389
{
5390
    return 0;
5391
}
5392

    
5393
#else
5394

    
5395
#warning No CPU save/restore functions
5396

    
5397
#endif
5398

    
5399
/***********************************************************/
5400
/* ram save/restore */
5401

    
5402
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5403
{
5404
    int v;
5405

    
5406
    v = qemu_get_byte(f);
5407
    switch(v) {
5408
    case 0:
5409
        if (qemu_get_buffer(f, buf, len) != len)
5410
            return -EIO;
5411
        break;
5412
    case 1:
5413
        v = qemu_get_byte(f);
5414
        memset(buf, v, len);
5415
        break;
5416
    default:
5417
        return -EINVAL;
5418
    }
5419
    return 0;
5420
}
5421

    
5422
static int ram_load_v1(QEMUFile *f, void *opaque)
5423
{
5424
    int i, ret;
5425

    
5426
    if (qemu_get_be32(f) != phys_ram_size)
5427
        return -EINVAL;
5428
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5429
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5430
        if (ret)
5431
            return ret;
5432
    }
5433
    return 0;
5434
}
5435

    
5436
#define BDRV_HASH_BLOCK_SIZE 1024
5437
#define IOBUF_SIZE 4096
5438
#define RAM_CBLOCK_MAGIC 0xfabe
5439

    
5440
typedef struct RamCompressState {
5441
    z_stream zstream;
5442
    QEMUFile *f;
5443
    uint8_t buf[IOBUF_SIZE];
5444
} RamCompressState;
5445

    
5446
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5447
{
5448
    int ret;
5449
    memset(s, 0, sizeof(*s));
5450
    s->f = f;
5451
    ret = deflateInit2(&s->zstream, 1,
5452
                       Z_DEFLATED, 15, 
5453
                       9, Z_DEFAULT_STRATEGY);
5454
    if (ret != Z_OK)
5455
        return -1;
5456
    s->zstream.avail_out = IOBUF_SIZE;
5457
    s->zstream.next_out = s->buf;
5458
    return 0;
5459
}
5460

    
5461
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5462
{
5463
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5464
    qemu_put_be16(s->f, len);
5465
    qemu_put_buffer(s->f, buf, len);
5466
}
5467

    
5468
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5469
{
5470
    int ret;
5471

    
5472
    s->zstream.avail_in = len;
5473
    s->zstream.next_in = (uint8_t *)buf;
5474
    while (s->zstream.avail_in > 0) {
5475
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5476
        if (ret != Z_OK)
5477
            return -1;
5478
        if (s->zstream.avail_out == 0) {
5479
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5480
            s->zstream.avail_out = IOBUF_SIZE;
5481
            s->zstream.next_out = s->buf;
5482
        }
5483
    }
5484
    return 0;
5485
}
5486

    
5487
static void ram_compress_close(RamCompressState *s)
5488
{
5489
    int len, ret;
5490

    
5491
    /* compress last bytes */
5492
    for(;;) {
5493
        ret = deflate(&s->zstream, Z_FINISH);
5494
        if (ret == Z_OK || ret == Z_STREAM_END) {
5495
            len = IOBUF_SIZE - s->zstream.avail_out;
5496
            if (len > 0) {
5497
                ram_put_cblock(s, s->buf, len);
5498
            }
5499
            s->zstream.avail_out = IOBUF_SIZE;
5500
            s->zstream.next_out = s->buf;
5501
            if (ret == Z_STREAM_END)
5502
                break;
5503
        } else {
5504
            goto fail;
5505
        }
5506
    }
5507
fail:
5508
    deflateEnd(&s->zstream);
5509
}
5510

    
5511
typedef struct RamDecompressState {
5512
    z_stream zstream;
5513
    QEMUFile *f;
5514
    uint8_t buf[IOBUF_SIZE];
5515
} RamDecompressState;
5516

    
5517
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5518
{
5519
    int ret;
5520
    memset(s, 0, sizeof(*s));
5521
    s->f = f;
5522
    ret = inflateInit(&s->zstream);
5523
    if (ret != Z_OK)
5524
        return -1;
5525
    return 0;
5526
}
5527

    
5528
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5529
{
5530
    int ret, clen;
5531

    
5532
    s->zstream.avail_out = len;
5533
    s->zstream.next_out = buf;
5534
    while (s->zstream.avail_out > 0) {
5535
        if (s->zstream.avail_in == 0) {
5536
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5537
                return -1;
5538
            clen = qemu_get_be16(s->f);
5539
            if (clen > IOBUF_SIZE)
5540
                return -1;
5541
            qemu_get_buffer(s->f, s->buf, clen);
5542
            s->zstream.avail_in = clen;
5543
            s->zstream.next_in = s->buf;
5544
        }
5545
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5546
        if (ret != Z_OK && ret != Z_STREAM_END) {
5547
            return -1;
5548
        }
5549
    }
5550
    return 0;
5551
}
5552

    
5553
static void ram_decompress_close(RamDecompressState *s)
5554
{
5555
    inflateEnd(&s->zstream);
5556
}
5557

    
5558
static void ram_save(QEMUFile *f, void *opaque)
5559
{
5560
    int i;
5561
    RamCompressState s1, *s = &s1;
5562
    uint8_t buf[10];
5563
    
5564
    qemu_put_be32(f, phys_ram_size);
5565
    if (ram_compress_open(s, f) < 0)
5566
        return;
5567
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5568
#if 0
5569
        if (tight_savevm_enabled) {
5570
            int64_t sector_num;
5571
            int j;
5572

5573
            /* find if the memory block is available on a virtual
5574
               block device */
5575
            sector_num = -1;
5576
            for(j = 0; j < MAX_DISKS; j++) {
5577
                if (bs_table[j]) {
5578
                    sector_num = bdrv_hash_find(bs_table[j], 
5579
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5580
                    if (sector_num >= 0)
5581
                        break;
5582
                }
5583
            }
5584
            if (j == MAX_DISKS)
5585
                goto normal_compress;
5586
            buf[0] = 1;
5587
            buf[1] = j;
5588
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5589
            ram_compress_buf(s, buf, 10);
5590
        } else 
5591
#endif
5592
        {
5593
            //        normal_compress:
5594
            buf[0] = 0;
5595
            ram_compress_buf(s, buf, 1);
5596
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5597
        }
5598
    }
5599
    ram_compress_close(s);
5600
}
5601

    
5602
static int ram_load(QEMUFile *f, void *opaque, int version_id)
5603
{
5604
    RamDecompressState s1, *s = &s1;
5605
    uint8_t buf[10];
5606
    int i;
5607

    
5608
    if (version_id == 1)
5609
        return ram_load_v1(f, opaque);
5610
    if (version_id != 2)
5611
        return -EINVAL;
5612
    if (qemu_get_be32(f) != phys_ram_size)
5613
        return -EINVAL;
5614
    if (ram_decompress_open(s, f) < 0)
5615
        return -EINVAL;
5616
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5617
        if (ram_decompress_buf(s, buf, 1) < 0) {
5618
            fprintf(stderr, "Error while reading ram block header\n");
5619
            goto error;
5620
        }
5621
        if (buf[0] == 0) {
5622
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5623
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5624
                goto error;
5625
            }
5626
        } else 
5627
#if 0
5628
        if (buf[0] == 1) {
5629
            int bs_index;
5630
            int64_t sector_num;
5631

5632
            ram_decompress_buf(s, buf + 1, 9);
5633
            bs_index = buf[1];
5634
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5635
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5636
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
5637
                goto error;
5638
            }
5639
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5640
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5641
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5642
                        bs_index, sector_num);
5643
                goto error;
5644
            }
5645
        } else 
5646
#endif
5647
        {
5648
        error:
5649
            printf("Error block header\n");
5650
            return -EINVAL;
5651
        }
5652
    }
5653
    ram_decompress_close(s);
5654
    return 0;
5655
}
5656

    
5657
/***********************************************************/
5658
/* bottom halves (can be seen as timers which expire ASAP) */
5659

    
5660
struct QEMUBH {
5661
    QEMUBHFunc *cb;
5662
    void *opaque;
5663
    int scheduled;
5664
    QEMUBH *next;
5665
};
5666

    
5667
static QEMUBH *first_bh = NULL;
5668

    
5669
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5670
{
5671
    QEMUBH *bh;
5672
    bh = qemu_mallocz(sizeof(QEMUBH));
5673
    if (!bh)
5674
        return NULL;
5675
    bh->cb = cb;
5676
    bh->opaque = opaque;
5677
    return bh;
5678
}
5679

    
5680
int qemu_bh_poll(void)
5681
{
5682
    QEMUBH *bh, **pbh;
5683
    int ret;
5684

    
5685
    ret = 0;
5686
    for(;;) {
5687
        pbh = &first_bh;
5688
        bh = *pbh;
5689
        if (!bh)
5690
            break;
5691
        ret = 1;
5692
        *pbh = bh->next;
5693
        bh->scheduled = 0;
5694
        bh->cb(bh->opaque);
5695
    }
5696
    return ret;
5697
}
5698

    
5699
void qemu_bh_schedule(QEMUBH *bh)
5700
{
5701
    CPUState *env = cpu_single_env;
5702
    if (bh->scheduled)
5703
        return;
5704
    bh->scheduled = 1;
5705
    bh->next = first_bh;
5706
    first_bh = bh;
5707

    
5708
    /* stop the currently executing CPU to execute the BH ASAP */
5709
    if (env) {
5710
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5711
    }
5712
}
5713

    
5714
void qemu_bh_cancel(QEMUBH *bh)
5715
{
5716
    QEMUBH **pbh;
5717
    if (bh->scheduled) {
5718
        pbh = &first_bh;
5719
        while (*pbh != bh)
5720
            pbh = &(*pbh)->next;
5721
        *pbh = bh->next;
5722
        bh->scheduled = 0;
5723
    }
5724
}
5725

    
5726
void qemu_bh_delete(QEMUBH *bh)
5727
{
5728
    qemu_bh_cancel(bh);
5729
    qemu_free(bh);
5730
}
5731

    
5732
/***********************************************************/
5733
/* machine registration */
5734

    
5735
QEMUMachine *first_machine = NULL;
5736

    
5737
int qemu_register_machine(QEMUMachine *m)
5738
{
5739
    QEMUMachine **pm;
5740
    pm = &first_machine;
5741
    while (*pm != NULL)
5742
        pm = &(*pm)->next;
5743
    m->next = NULL;
5744
    *pm = m;
5745
    return 0;
5746
}
5747

    
5748
QEMUMachine *find_machine(const char *name)
5749
{
5750
    QEMUMachine *m;
5751

    
5752
    for(m = first_machine; m != NULL; m = m->next) {
5753
        if (!strcmp(m->name, name))
5754
            return m;
5755
    }
5756
    return NULL;
5757
}
5758

    
5759
/***********************************************************/
5760
/* main execution loop */
5761

    
5762
void gui_update(void *opaque)
5763
{
5764
    display_state.dpy_refresh(&display_state);
5765
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5766
}
5767

    
5768
struct vm_change_state_entry {
5769
    VMChangeStateHandler *cb;
5770
    void *opaque;
5771
    LIST_ENTRY (vm_change_state_entry) entries;
5772
};
5773

    
5774
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5775

    
5776
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5777
                                                     void *opaque)
5778
{
5779
    VMChangeStateEntry *e;
5780

    
5781
    e = qemu_mallocz(sizeof (*e));
5782
    if (!e)
5783
        return NULL;
5784

    
5785
    e->cb = cb;
5786
    e->opaque = opaque;
5787
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5788
    return e;
5789
}
5790

    
5791
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5792
{
5793
    LIST_REMOVE (e, entries);
5794
    qemu_free (e);
5795
}
5796

    
5797
static void vm_state_notify(int running)
5798
{
5799
    VMChangeStateEntry *e;
5800

    
5801
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5802
        e->cb(e->opaque, running);
5803
    }
5804
}
5805

    
5806
/* XXX: support several handlers */
5807
static VMStopHandler *vm_stop_cb;
5808
static void *vm_stop_opaque;
5809

    
5810
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5811
{
5812
    vm_stop_cb = cb;
5813
    vm_stop_opaque = opaque;
5814
    return 0;
5815
}
5816

    
5817
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5818
{
5819
    vm_stop_cb = NULL;
5820
}
5821

    
5822
void vm_start(void)
5823
{
5824
    if (!vm_running) {
5825
        cpu_enable_ticks();
5826
        vm_running = 1;
5827
        vm_state_notify(1);
5828
    }
5829
}
5830

    
5831
void vm_stop(int reason) 
5832
{
5833
    if (vm_running) {
5834
        cpu_disable_ticks();
5835
        vm_running = 0;
5836
        if (reason != 0) {
5837
            if (vm_stop_cb) {
5838
                vm_stop_cb(vm_stop_opaque, reason);
5839
            }
5840
        }
5841
        vm_state_notify(0);
5842
    }
5843
}
5844

    
5845
/* reset/shutdown handler */
5846

    
5847
typedef struct QEMUResetEntry {
5848
    QEMUResetHandler *func;
5849
    void *opaque;
5850
    struct QEMUResetEntry *next;
5851
} QEMUResetEntry;
5852

    
5853
static QEMUResetEntry *first_reset_entry;
5854
static int reset_requested;
5855
static int shutdown_requested;
5856
static int powerdown_requested;
5857

    
5858
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5859
{
5860
    QEMUResetEntry **pre, *re;
5861

    
5862
    pre = &first_reset_entry;
5863
    while (*pre != NULL)
5864
        pre = &(*pre)->next;
5865
    re = qemu_mallocz(sizeof(QEMUResetEntry));
5866
    re->func = func;
5867
    re->opaque = opaque;
5868
    re->next = NULL;
5869
    *pre = re;
5870
}
5871

    
5872
void qemu_system_reset(void)
5873
{
5874
    QEMUResetEntry *re;
5875

    
5876
    /* reset all devices */
5877
    for(re = first_reset_entry; re != NULL; re = re->next) {
5878
        re->func(re->opaque);
5879
    }
5880
}
5881

    
5882
void qemu_system_reset_request(void)
5883
{
5884
    if (no_reboot) {
5885
        shutdown_requested = 1;
5886
    } else {
5887
        reset_requested = 1;
5888
    }
5889
    if (cpu_single_env)
5890
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5891
}
5892

    
5893
void qemu_system_shutdown_request(void)
5894
{
5895
    shutdown_requested = 1;
5896
    if (cpu_single_env)
5897
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5898
}
5899

    
5900
void qemu_system_powerdown_request(void)
5901
{
5902
    powerdown_requested = 1;
5903
    if (cpu_single_env)
5904
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5905
}
5906

    
5907
void main_loop_wait(int timeout)
5908
{
5909
    IOHandlerRecord *ioh, *ioh_next;
5910
    fd_set rfds, wfds, xfds;
5911
    int ret, nfds;
5912
    struct timeval tv;
5913
    PollingEntry *pe;
5914

    
5915

    
5916
    /* XXX: need to suppress polling by better using win32 events */
5917
    ret = 0;
5918
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5919
        ret |= pe->func(pe->opaque);
5920
    }
5921
#ifdef _WIN32
5922
    if (ret == 0 && timeout > 0) {
5923
        int err;
5924
        WaitObjects *w = &wait_objects;
5925
        
5926
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5927
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5928
            if (w->func[ret - WAIT_OBJECT_0])
5929
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5930
        } else if (ret == WAIT_TIMEOUT) {
5931
        } else {
5932
            err = GetLastError();
5933
            fprintf(stderr, "Wait error %d %d\n", ret, err);
5934
        }
5935
    }
5936
#endif
5937
    /* poll any events */
5938
    /* XXX: separate device handlers from system ones */
5939
    nfds = -1;
5940
    FD_ZERO(&rfds);
5941
    FD_ZERO(&wfds);
5942
    FD_ZERO(&xfds);
5943
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5944
        if (ioh->fd_read &&
5945
            (!ioh->fd_read_poll ||
5946
             ioh->fd_read_poll(ioh->opaque) != 0)) {
5947
            FD_SET(ioh->fd, &rfds);
5948
            if (ioh->fd > nfds)
5949
                nfds = ioh->fd;
5950
        }
5951
        if (ioh->fd_write) {
5952
            FD_SET(ioh->fd, &wfds);
5953
            if (ioh->fd > nfds)
5954
                nfds = ioh->fd;
5955
        }
5956
    }
5957
    
5958
    tv.tv_sec = 0;
5959
#ifdef _WIN32
5960
    tv.tv_usec = 0;
5961
#else
5962
    tv.tv_usec = timeout * 1000;
5963
#endif
5964
#if defined(CONFIG_SLIRP)
5965
    if (slirp_inited) {
5966
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5967
    }
5968
#endif
5969
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5970
    if (ret > 0) {
5971
        /* XXX: better handling of removal */
5972
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5973
            ioh_next = ioh->next;
5974
            if (FD_ISSET(ioh->fd, &rfds)) {
5975
                ioh->fd_read(ioh->opaque);
5976
            }
5977
            if (FD_ISSET(ioh->fd, &wfds)) {
5978
                ioh->fd_write(ioh->opaque);
5979
            }
5980
        }
5981
    }
5982
#if defined(CONFIG_SLIRP)
5983
    if (slirp_inited) {
5984
        if (ret < 0) {
5985
            FD_ZERO(&rfds);
5986
            FD_ZERO(&wfds);
5987
            FD_ZERO(&xfds);
5988
        }
5989
        slirp_select_poll(&rfds, &wfds, &xfds);
5990
    }
5991
#endif
5992
    qemu_aio_poll();
5993
    qemu_bh_poll();
5994

    
5995
    if (vm_running) {
5996
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
5997
                        qemu_get_clock(vm_clock));
5998
        /* run dma transfers, if any */
5999
        DMA_run();
6000
    }
6001
    
6002
    /* real time timers */
6003
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
6004
                    qemu_get_clock(rt_clock));
6005
}
6006

    
6007
static CPUState *cur_cpu;
6008

    
6009
int main_loop(void)
6010
{
6011
    int ret, timeout;
6012
#ifdef CONFIG_PROFILER
6013
    int64_t ti;
6014
#endif
6015
    CPUState *env;
6016

    
6017
    cur_cpu = first_cpu;
6018
    for(;;) {
6019
        if (vm_running) {
6020

    
6021
            env = cur_cpu;
6022
            for(;;) {
6023
                /* get next cpu */
6024
                env = env->next_cpu;
6025
                if (!env)
6026
                    env = first_cpu;
6027
#ifdef CONFIG_PROFILER
6028
                ti = profile_getclock();
6029
#endif
6030
                ret = cpu_exec(env);
6031
#ifdef CONFIG_PROFILER
6032
                qemu_time += profile_getclock() - ti;
6033
#endif
6034
                if (ret != EXCP_HALTED)
6035
                    break;
6036
                /* all CPUs are halted ? */
6037
                if (env == cur_cpu) {
6038
                    ret = EXCP_HLT;
6039
                    break;
6040
                }
6041
            }
6042
            cur_cpu = env;
6043

    
6044
            if (shutdown_requested) {
6045
                ret = EXCP_INTERRUPT;
6046
                break;
6047
            }
6048
            if (reset_requested) {
6049
                reset_requested = 0;
6050
                qemu_system_reset();
6051
                ret = EXCP_INTERRUPT;
6052
            }
6053
            if (powerdown_requested) {
6054
                powerdown_requested = 0;
6055
                qemu_system_powerdown();
6056
                ret = EXCP_INTERRUPT;
6057
            }
6058
            if (ret == EXCP_DEBUG) {
6059
                vm_stop(EXCP_DEBUG);
6060
            }
6061
            /* if hlt instruction, we wait until the next IRQ */
6062
            /* XXX: use timeout computed from timers */
6063
            if (ret == EXCP_HLT)
6064
                timeout = 10;
6065
            else
6066
                timeout = 0;
6067
        } else {
6068
            timeout = 10;
6069
        }
6070
#ifdef CONFIG_PROFILER
6071
        ti = profile_getclock();
6072
#endif
6073
        main_loop_wait(timeout);
6074
#ifdef CONFIG_PROFILER
6075
        dev_time += profile_getclock() - ti;
6076
#endif
6077
    }
6078
    cpu_disable_ticks();
6079
    return ret;
6080
}
6081

    
6082
void help(void)
6083
{
6084
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
6085
           "usage: %s [options] [disk_image]\n"
6086
           "\n"
6087
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6088
           "\n"
6089
           "Standard options:\n"
6090
           "-M machine      select emulated machine (-M ? for list)\n"
6091
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6092
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6093
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6094
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6095
           "-boot [a|c|d]   boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
6096
           "-disk ide,img=file[,hdx=a..dd][,type=disk|cdrom] \n"
6097
           "                defaults are: hdx=a,type=disk \n"
6098
           "-disk scsi,img=file[,sdx=a..g][,type=disk|cdrom][,id=n]  \n"
6099
           "                defaults are: sdx=a,type=disk,id='auto assign' \n"
6100
           "-snapshot       write to temporary files instead of disk image files\n"
6101
#ifdef CONFIG_SDL
6102
           "-no-quit        disable SDL window close capability\n"
6103
#endif
6104
#ifdef TARGET_I386
6105
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6106
#endif
6107
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6108
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
6109
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
6110
#ifndef _WIN32
6111
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
6112
#endif
6113
#ifdef HAS_AUDIO
6114
           "-audio-help     print list of audio drivers and their options\n"
6115
           "-soundhw c1,... enable audio support\n"
6116
           "                and only specified sound cards (comma separated list)\n"
6117
           "                use -soundhw ? to get the list of supported cards\n"
6118
           "                use -soundhw all to enable all of them\n"
6119
#endif
6120
           "-localtime      set the real time clock to local time [default=utc]\n"
6121
           "-full-screen    start in full screen\n"
6122
#ifdef TARGET_I386
6123
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6124
#endif
6125
           "-usb            enable the USB driver (will be the default soon)\n"
6126
           "-usbdevice name add the host or guest USB device 'name'\n"
6127
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6128
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6129
#endif
6130
           "\n"
6131
           "Network options:\n"
6132
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6133
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6134
#ifdef CONFIG_SLIRP
6135
           "-net user[,vlan=n][,hostname=host]\n"
6136
           "                connect the user mode network stack to VLAN 'n' and send\n"
6137
           "                hostname 'host' to DHCP clients\n"
6138
#endif
6139
#ifdef _WIN32
6140
           "-net tap[,vlan=n],ifname=name\n"
6141
           "                connect the host TAP network interface to VLAN 'n'\n"
6142
#else
6143
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6144
           "                connect the host TAP network interface to VLAN 'n' and use\n"
6145
           "                the network script 'file' (default=%s);\n"
6146
           "                use 'fd=h' to connect to an already opened TAP interface\n"
6147
#endif
6148
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6149
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
6150
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6151
           "                connect the vlan 'n' to multicast maddr and port\n"
6152
           "-net none       use it alone to have zero network devices; if no -net option\n"
6153
           "                is provided, the default is '-net nic -net user'\n"
6154
           "\n"
6155
#ifdef CONFIG_SLIRP
6156
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
6157
#ifndef _WIN32
6158
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6159
#endif
6160
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6161
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
6162
#endif
6163
           "\n"
6164
           "Linux boot specific:\n"
6165
           "-kernel bzImage use 'bzImage' as kernel image\n"
6166
           "-append cmdline use 'cmdline' as kernel command line\n"
6167
           "-initrd file    use 'file' as initial ram disk\n"
6168
           "\n"
6169
           "Debug/Expert options:\n"
6170
           "-monitor dev    redirect the monitor to char device 'dev'\n"
6171
           "-serial dev     redirect the serial port to char device 'dev'\n"
6172
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
6173
           "-pidfile file   Write PID to 'file'\n"
6174
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
6175
           "-s              wait gdb connection to port %d\n"
6176
           "-p port         change gdb connection port\n"
6177
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6178
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6179
           "                translation (t=none or lba) (usually qemu can guess them)\n"
6180
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6181
#ifdef USE_KQEMU
6182
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6183
           "-no-kqemu       disable KQEMU kernel module usage\n"
6184
#endif
6185
#ifdef USE_CODE_COPY
6186
           "-no-code-copy   disable code copy acceleration\n"
6187
#endif
6188
#ifdef TARGET_I386
6189
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6190
           "                (default is CL-GD5446 PCI VGA)\n"
6191
           "-no-acpi        disable ACPI\n"
6192
#endif
6193
           "-no-reboot      exit instead of rebooting\n"
6194
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6195
           "-vnc display    start a VNC server on display\n"
6196
#ifndef _WIN32
6197
           "-daemonize      daemonize QEMU after initializing\n"
6198
#endif
6199
           "\n"
6200
           "During emulation, the following keys are useful:\n"
6201
           "ctrl-alt-f      toggle full screen\n"
6202
           "ctrl-alt-n      switch to virtual console 'n'\n"
6203
           "ctrl-alt        toggle mouse and keyboard grab\n"
6204
           "\n"
6205
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
6206
           ,
6207
           "qemu",
6208
           DEFAULT_RAM_SIZE,
6209
#ifndef _WIN32
6210
           DEFAULT_NETWORK_SCRIPT,
6211
#endif
6212
           DEFAULT_GDBSTUB_PORT,
6213
           "/tmp/qemu.log");
6214
    exit(1);
6215
}
6216

    
6217
#define HAS_ARG 0x0001
6218

    
6219
enum {
6220
    QEMU_OPTION_h,
6221

    
6222
    QEMU_OPTION_M,
6223
    QEMU_OPTION_fda,
6224
    QEMU_OPTION_fdb,
6225
    QEMU_OPTION_hda,
6226
    QEMU_OPTION_hdb,
6227
    QEMU_OPTION_hdc,
6228
    QEMU_OPTION_hdd,
6229
    QEMU_OPTION_cdrom,
6230
    QEMU_OPTION_boot,
6231
    QEMU_OPTION_snapshot,
6232
#ifdef TARGET_I386
6233
    QEMU_OPTION_no_fd_bootchk,
6234
#endif
6235
    QEMU_OPTION_m,
6236
    QEMU_OPTION_nographic,
6237
#ifdef HAS_AUDIO
6238
    QEMU_OPTION_audio_help,
6239
    QEMU_OPTION_soundhw,
6240
#endif
6241

    
6242
    QEMU_OPTION_net,
6243
    QEMU_OPTION_tftp,
6244
    QEMU_OPTION_smb,
6245
    QEMU_OPTION_redir,
6246

    
6247
    QEMU_OPTION_kernel,
6248
    QEMU_OPTION_append,
6249
    QEMU_OPTION_initrd,
6250

    
6251
    QEMU_OPTION_S,
6252
    QEMU_OPTION_s,
6253
    QEMU_OPTION_p,
6254
    QEMU_OPTION_d,
6255
    QEMU_OPTION_hdachs,
6256
    QEMU_OPTION_L,
6257
    QEMU_OPTION_no_code_copy,
6258
    QEMU_OPTION_k,
6259
    QEMU_OPTION_localtime,
6260
    QEMU_OPTION_cirrusvga,
6261
    QEMU_OPTION_g,
6262
    QEMU_OPTION_std_vga,
6263
    QEMU_OPTION_monitor,
6264
    QEMU_OPTION_serial,
6265
    QEMU_OPTION_parallel,
6266
    QEMU_OPTION_loadvm,
6267
    QEMU_OPTION_full_screen,
6268
    QEMU_OPTION_no_quit,
6269
    QEMU_OPTION_pidfile,
6270
    QEMU_OPTION_no_kqemu,
6271
    QEMU_OPTION_kernel_kqemu,
6272
    QEMU_OPTION_win2k_hack,
6273
    QEMU_OPTION_usb,
6274
    QEMU_OPTION_usbdevice,
6275
    QEMU_OPTION_smp,
6276
    QEMU_OPTION_vnc,
6277
    QEMU_OPTION_no_acpi,
6278
    QEMU_OPTION_no_reboot,
6279
    QEMU_OPTION_daemonize,
6280
    QEMU_OPTION_disk,
6281
};
6282

    
6283
typedef struct QEMUOption {
6284
    const char *name;
6285
    int flags;
6286
    int index;
6287
} QEMUOption;
6288

    
6289
const QEMUOption qemu_options[] = {
6290
    { "h", 0, QEMU_OPTION_h },
6291

    
6292
    { "M", HAS_ARG, QEMU_OPTION_M },
6293
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6294
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6295
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6296
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6297
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6298
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6299
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6300
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6301
    { "snapshot", 0, QEMU_OPTION_snapshot },
6302
#ifdef TARGET_I386
6303
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6304
#endif
6305
    { "m", HAS_ARG, QEMU_OPTION_m },
6306
    { "nographic", 0, QEMU_OPTION_nographic },
6307
    { "k", HAS_ARG, QEMU_OPTION_k },
6308
#ifdef HAS_AUDIO
6309
    { "audio-help", 0, QEMU_OPTION_audio_help },
6310
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6311
#endif
6312

    
6313
    { "net", HAS_ARG, QEMU_OPTION_net},
6314
#ifdef CONFIG_SLIRP
6315
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6316
#ifndef _WIN32
6317
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6318
#endif
6319
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6320
#endif
6321

    
6322
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6323
    { "append", HAS_ARG, QEMU_OPTION_append },
6324
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6325

    
6326
    { "S", 0, QEMU_OPTION_S },
6327
    { "s", 0, QEMU_OPTION_s },
6328
    { "p", HAS_ARG, QEMU_OPTION_p },
6329
    { "d", HAS_ARG, QEMU_OPTION_d },
6330
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6331
    { "L", HAS_ARG, QEMU_OPTION_L },
6332
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6333
#ifdef USE_KQEMU
6334
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6335
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6336
#endif
6337
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6338
    { "g", 1, QEMU_OPTION_g },
6339
#endif
6340
    { "localtime", 0, QEMU_OPTION_localtime },
6341
    { "std-vga", 0, QEMU_OPTION_std_vga },
6342
    { "monitor", 1, QEMU_OPTION_monitor },
6343
    { "serial", 1, QEMU_OPTION_serial },
6344
    { "parallel", 1, QEMU_OPTION_parallel },
6345
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6346
    { "full-screen", 0, QEMU_OPTION_full_screen },
6347
#ifdef CONFIG_SDL
6348
    { "no-quit", 0, QEMU_OPTION_no_quit },
6349
#endif
6350
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6351
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6352
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6353
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6354
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6355
    { "disk", HAS_ARG, QEMU_OPTION_disk },
6356
    
6357
    /* temporary options */
6358
    { "usb", 0, QEMU_OPTION_usb },
6359
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6360
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6361
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
6362
    { "daemonize", 0, QEMU_OPTION_daemonize },
6363
    { NULL },
6364
};
6365

    
6366
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6367

    
6368
/* this stack is only used during signal handling */
6369
#define SIGNAL_STACK_SIZE 32768
6370

    
6371
static uint8_t *signal_stack;
6372

    
6373
#endif
6374

    
6375
/* password input */
6376

    
6377
static BlockDriverState *get_bdrv(int index)
6378
{
6379
    BlockDriverState *bs;
6380

    
6381
    if (index < 4) {
6382
        bs = bs_table[index];
6383
    } else if (index < 6) {
6384
        bs = fd_table[index - 4];
6385
    } else {
6386
        bs = NULL;
6387
    }
6388
    return bs;
6389
}
6390

    
6391
static void read_passwords(void)
6392
{
6393
    BlockDriverState *bs;
6394
    int i, j;
6395
    char password[256];
6396

    
6397
    for(i = 0; i < 6; i++) {
6398
        bs = get_bdrv(i);
6399
        if (bs && bdrv_is_encrypted(bs)) {
6400
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6401
            for(j = 0; j < 3; j++) {
6402
                monitor_readline("Password: ", 
6403
                                 1, password, sizeof(password));
6404
                if (bdrv_set_key(bs, password) == 0)
6405
                    break;
6406
                term_printf("invalid password\n");
6407
            }
6408
        }
6409
    }
6410
}
6411

    
6412
/* XXX: currently we cannot use simultaneously different CPUs */
6413
void register_machines(void)
6414
{
6415
#if defined(TARGET_I386)
6416
    qemu_register_machine(&pc_machine);
6417
    qemu_register_machine(&isapc_machine);
6418
#elif defined(TARGET_PPC)
6419
    qemu_register_machine(&heathrow_machine);
6420
    qemu_register_machine(&core99_machine);
6421
    qemu_register_machine(&prep_machine);
6422
#elif defined(TARGET_MIPS)
6423
    qemu_register_machine(&mips_machine);
6424
#elif defined(TARGET_SPARC)
6425
#ifdef TARGET_SPARC64
6426
    qemu_register_machine(&sun4u_machine);
6427
#else
6428
    qemu_register_machine(&sun4m_machine);
6429
#endif
6430
#elif defined(TARGET_ARM)
6431
    qemu_register_machine(&integratorcp926_machine);
6432
    qemu_register_machine(&integratorcp1026_machine);
6433
    qemu_register_machine(&versatilepb_machine);
6434
    qemu_register_machine(&versatileab_machine);
6435
    qemu_register_machine(&realview_machine);
6436
#elif defined(TARGET_SH4)
6437
    qemu_register_machine(&shix_machine);
6438
#else
6439
#error unsupported CPU
6440
#endif
6441
}
6442

    
6443
#ifdef HAS_AUDIO
6444
struct soundhw soundhw[] = {
6445
#ifdef TARGET_I386
6446
    {
6447
        "pcspk",
6448
        "PC speaker",
6449
        0,
6450
        1,
6451
        { .init_isa = pcspk_audio_init }
6452
    },
6453
#endif
6454
    {
6455
        "sb16",
6456
        "Creative Sound Blaster 16",
6457
        0,
6458
        1,
6459
        { .init_isa = SB16_init }
6460
    },
6461

    
6462
#ifdef CONFIG_ADLIB
6463
    {
6464
        "adlib",
6465
#ifdef HAS_YMF262
6466
        "Yamaha YMF262 (OPL3)",
6467
#else
6468
        "Yamaha YM3812 (OPL2)",
6469
#endif
6470
        0,
6471
        1,
6472
        { .init_isa = Adlib_init }
6473
    },
6474
#endif
6475

    
6476
#ifdef CONFIG_GUS
6477
    {
6478
        "gus",
6479
        "Gravis Ultrasound GF1",
6480
        0,
6481
        1,
6482
        { .init_isa = GUS_init }
6483
    },
6484
#endif
6485

    
6486
    {
6487
        "es1370",
6488
        "ENSONIQ AudioPCI ES1370",
6489
        0,
6490
        0,
6491
        { .init_pci = es1370_init }
6492
    },
6493

    
6494
    { NULL, NULL, 0, 0, { NULL } }
6495
};
6496

    
6497
static void select_soundhw (const char *optarg)
6498
{
6499
    struct soundhw *c;
6500

    
6501
    if (*optarg == '?') {
6502
    show_valid_cards:
6503

    
6504
        printf ("Valid sound card names (comma separated):\n");
6505
        for (c = soundhw; c->name; ++c) {
6506
            printf ("%-11s %s\n", c->name, c->descr);
6507
        }
6508
        printf ("\n-soundhw all will enable all of the above\n");
6509
        exit (*optarg != '?');
6510
    }
6511
    else {
6512
        size_t l;
6513
        const char *p;
6514
        char *e;
6515
        int bad_card = 0;
6516

    
6517
        if (!strcmp (optarg, "all")) {
6518
            for (c = soundhw; c->name; ++c) {
6519
                c->enabled = 1;
6520
            }
6521
            return;
6522
        }
6523

    
6524
        p = optarg;
6525
        while (*p) {
6526
            e = strchr (p, ',');
6527
            l = !e ? strlen (p) : (size_t) (e - p);
6528

    
6529
            for (c = soundhw; c->name; ++c) {
6530
                if (!strncmp (c->name, p, l)) {
6531
                    c->enabled = 1;
6532
                    break;
6533
                }
6534
            }
6535

    
6536
            if (!c->name) {
6537
                if (l > 80) {
6538
                    fprintf (stderr,
6539
                             "Unknown sound card name (too big to show)\n");
6540
                }
6541
                else {
6542
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
6543
                             (int) l, p);
6544
                }
6545
                bad_card = 1;
6546
            }
6547
            p += l + (e != NULL);
6548
        }
6549

    
6550
        if (bad_card)
6551
            goto show_valid_cards;
6552
    }
6553
}
6554
#endif
6555

    
6556
#ifdef _WIN32
6557
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6558
{
6559
    exit(STATUS_CONTROL_C_EXIT);
6560
    return TRUE;
6561
}
6562
#endif
6563

    
6564
#define MAX_NET_CLIENTS 32
6565

    
6566
int main(int argc, char **argv)
6567
{
6568
#ifdef CONFIG_GDBSTUB
6569
    int use_gdbstub, gdbstub_port;
6570
#endif
6571
    int i, cdrom_index;
6572
    int snapshot, linux_boot;
6573
    const char *initrd_filename;
6574
    const char *fd_filename[MAX_FD];
6575
    char scsi_options[MAX_SCSI_DISKS] [DISK_OPTIONS_SIZE];
6576
    char ide_options[MAX_DISKS] [DISK_OPTIONS_SIZE];
6577
    int num_ide_disks;
6578
    int num_scsi_disks;
6579
    const char *kernel_filename, *kernel_cmdline;
6580
    DisplayState *ds = &display_state;
6581
    int cyls, heads, secs, translation;
6582
    int start_emulation = 1;
6583
    char net_clients[MAX_NET_CLIENTS][256];
6584
    int nb_net_clients;
6585
    int optind;
6586
    const char *r, *optarg;
6587
    CharDriverState *monitor_hd;
6588
    char monitor_device[128];
6589
    char serial_devices[MAX_SERIAL_PORTS][128];
6590
    int serial_device_index;
6591
    char parallel_devices[MAX_PARALLEL_PORTS][128];
6592
    int parallel_device_index;
6593
    const char *loadvm = NULL;
6594
    QEMUMachine *machine;
6595
    char usb_devices[MAX_USB_CMDLINE][128];
6596
    int usb_devices_index;
6597
    int fds[2];
6598

    
6599
    LIST_INIT (&vm_change_state_head);
6600
#ifndef _WIN32
6601
    {
6602
        struct sigaction act;
6603
        sigfillset(&act.sa_mask);
6604
        act.sa_flags = 0;
6605
        act.sa_handler = SIG_IGN;
6606
        sigaction(SIGPIPE, &act, NULL);
6607
    }
6608
#else
6609
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6610
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
6611
       QEMU to run on a single CPU */
6612
    {
6613
        HANDLE h;
6614
        DWORD mask, smask;
6615
        int i;
6616
        h = GetCurrentProcess();
6617
        if (GetProcessAffinityMask(h, &mask, &smask)) {
6618
            for(i = 0; i < 32; i++) {
6619
                if (mask & (1 << i))
6620
                    break;
6621
            }
6622
            if (i != 32) {
6623
                mask = 1 << i;
6624
                SetProcessAffinityMask(h, mask);
6625
            }
6626
        }
6627
    }
6628
#endif
6629

    
6630
    register_machines();
6631
    machine = first_machine;
6632
    initrd_filename = NULL;
6633
    for(i = 0; i < MAX_SCSI_DISKS; i++) {
6634
        scsi_disks_info[i].device_type = SCSI_NONE;
6635
        bs_scsi_table[i] = NULL;
6636
    }
6637

    
6638
    num_ide_disks = 0;
6639
    num_scsi_disks = 0;
6640

    
6641
    for(i = 0; i < MAX_FD; i++)
6642
        fd_filename[i] = NULL;
6643
    for(i = 0; i < MAX_DISKS; i++) {
6644
        ide_options[i][0] =  '\0';
6645
    }
6646
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6647
    vga_ram_size = VGA_RAM_SIZE;
6648
    bios_size = BIOS_SIZE;
6649
#ifdef CONFIG_GDBSTUB
6650
    use_gdbstub = 0;
6651
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
6652
#endif
6653
    snapshot = 0;
6654
    nographic = 0;
6655
    kernel_filename = NULL;
6656
    kernel_cmdline = "";
6657
#ifdef TARGET_PPC
6658
    cdrom_index = 1;
6659
#else
6660
    cdrom_index = 2;
6661
#endif
6662
    cyls = heads = secs = 0;
6663
    translation = BIOS_ATA_TRANSLATION_AUTO;
6664
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6665

    
6666
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6667
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
6668
        serial_devices[i][0] = '\0';
6669
    serial_device_index = 0;
6670
    
6671
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6672
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6673
        parallel_devices[i][0] = '\0';
6674
    parallel_device_index = 0;
6675
    
6676
    usb_devices_index = 0;
6677
    
6678
    nb_net_clients = 0;
6679

    
6680
    nb_nics = 0;
6681
    /* default mac address of the first network interface */
6682
    
6683
    optind = 1;
6684
    for(;;) {
6685
        if (optind >= argc)
6686
            break;
6687
        r = argv[optind];
6688
        if (r[0] != '-') {
6689

    
6690
        /* Build new disk IDE syntax string */
6691
        pstrcpy(ide_options[0],
6692
                14,
6693
                "hdx=a,img=");
6694
        /*Add on image filename */
6695
        pstrcpy(&(ide_options[0][13]),
6696
                sizeof(ide_options[0])-13,
6697
                argv[optind++]);
6698
        num_ide_disks++;
6699
        } else {
6700
            const QEMUOption *popt;
6701

    
6702
            optind++;
6703
            popt = qemu_options;
6704
            for(;;) {
6705
                if (!popt->name) {
6706
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
6707
                            argv[0], r);
6708
                    exit(1);
6709
                }
6710
                if (!strcmp(popt->name, r + 1))
6711
                    break;
6712
                popt++;
6713
            }
6714
            if (popt->flags & HAS_ARG) {
6715
                if (optind >= argc) {
6716
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
6717
                            argv[0], r);
6718
                    exit(1);
6719
                }
6720
                optarg = argv[optind++];
6721
            } else {
6722
                optarg = NULL;
6723
            }
6724

    
6725
            switch(popt->index) {
6726
            case QEMU_OPTION_M:
6727
                machine = find_machine(optarg);
6728
                if (!machine) {
6729
                    QEMUMachine *m;
6730
                    printf("Supported machines are:\n");
6731
                    for(m = first_machine; m != NULL; m = m->next) {
6732
                        printf("%-10s %s%s\n",
6733
                               m->name, m->desc, 
6734
                               m == first_machine ? " (default)" : "");
6735
                    }
6736
                    exit(1);
6737
                }
6738
                break;
6739
            case QEMU_OPTION_initrd:
6740
                initrd_filename = optarg;
6741
                break;
6742
            case QEMU_OPTION_hda:
6743
            case QEMU_OPTION_hdb:
6744
            case QEMU_OPTION_hdc:
6745
            case QEMU_OPTION_hdd:
6746
                {
6747
                    int hd_index;
6748
                    const char newIDE_DiskSyntax [][10] = {
6749
                       "hdx=a,img=", "hdx=b,img=", "hdx=c,img=", "hdx=d,img=" };
6750

    
6751
                    hd_index = popt->index - QEMU_OPTION_hda;
6752
                    if (num_ide_disks >= MAX_DISKS){
6753
                        fprintf(stderr, "qemu: too many IDE disks defined.\n");
6754
                        exit(1);
6755
                    }
6756
                    /* Build new disk IDE syntax string */
6757
                    pstrcpy(ide_options[hd_index],
6758
                            11,
6759
                            newIDE_DiskSyntax[hd_index]);
6760
                    /* Add on image filename */
6761
                    pstrcpy(&(ide_options[hd_index][10]),
6762
                            sizeof(ide_options[0])-10,
6763
                            optarg);
6764
                    num_ide_disks++;
6765
                }
6766
                break;
6767
            case QEMU_OPTION_disk: /*Combined IDE and SCSI, for disk and CDROM */
6768
                {
6769
                    const char *p_input_char;
6770
                    char *p_output_string;
6771
                    char device[64];
6772
                    int disk_index;
6773

    
6774
                    p_input_char = optarg;
6775
                    p_output_string = device;
6776
                    while (*p_input_char != '\0' && *p_input_char != ',') {
6777
                        if ((p_output_string - device) < sizeof(device) - 1)
6778
                            *p_output_string++ = *p_input_char;
6779
                        p_input_char++;
6780
                    }
6781
                    *p_output_string = '\0';
6782
                    if (*p_input_char == ',')
6783
                        p_input_char++;
6784

    
6785
                    if (!strcmp(device, "scsi")) {
6786
                        if (num_scsi_disks >= MAX_SCSI_DISKS) {
6787
                            fprintf(stderr, "qemu: too many SCSI disks defined.\n");
6788
                            exit(1);
6789
                        }
6790
                        pstrcpy(scsi_options[num_scsi_disks],
6791
                                sizeof(scsi_options[0]),
6792
                                p_input_char);
6793
                        num_scsi_disks++;
6794
                    } else if (!strcmp(device,"ide")) {
6795
                        if (num_ide_disks >= MAX_DISKS) {
6796
                            fprintf(stderr, "qemu: too many IDE disks/cdroms defined.\n");
6797
                            exit(1);
6798
                        }
6799
                        disk_index = 0; /* default is hda */
6800
                        if (get_param_value(device, sizeof(device),"hdx",p_input_char)) {
6801
                            if (device[0] >= 'a' && device[0] <= 'd') {
6802
                                disk_index = device[0] - 'a';
6803
                            } else {
6804
                                fprintf(stderr, "qemu: invalid IDE disk hdx= value: %s\n", device);
6805
                                return -1;
6806
                            }
6807
                        }
6808
                        else disk_index=0;
6809
                        pstrcpy(ide_options[disk_index],
6810
                                sizeof(ide_options[0]),
6811
                                p_input_char);
6812
                        num_ide_disks++;
6813
                    } else {
6814
                        fprintf(stderr, "qemu: -disk option must specify IDE or SCSI: %s \n",device);
6815
                        exit(1);
6816
                    }
6817
                }
6818
                break;
6819
            case QEMU_OPTION_snapshot:
6820
                snapshot = 1;
6821
                break;
6822
            case QEMU_OPTION_hdachs:
6823
                {
6824
                    const char *p;
6825
                    p = optarg;
6826
                    cyls = strtol(p, (char **)&p, 0);
6827
                    if (cyls < 1 || cyls > 16383)
6828
                        goto chs_fail;
6829
                    if (*p != ',')
6830
                        goto chs_fail;
6831
                    p++;
6832
                    heads = strtol(p, (char **)&p, 0);
6833
                    if (heads < 1 || heads > 16)
6834
                        goto chs_fail;
6835
                    if (*p != ',')
6836
                        goto chs_fail;
6837
                    p++;
6838
                    secs = strtol(p, (char **)&p, 0);
6839
                    if (secs < 1 || secs > 63)
6840
                        goto chs_fail;
6841
                    if (*p == ',') {
6842
                        p++;
6843
                        if (!strcmp(p, "none"))
6844
                            translation = BIOS_ATA_TRANSLATION_NONE;
6845
                        else if (!strcmp(p, "lba"))
6846
                            translation = BIOS_ATA_TRANSLATION_LBA;
6847
                        else if (!strcmp(p, "auto"))
6848
                            translation = BIOS_ATA_TRANSLATION_AUTO;
6849
                        else
6850
                            goto chs_fail;
6851
                    } else if (*p != '\0') {
6852
                    chs_fail:
6853
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
6854
                        exit(1);
6855
                    }
6856
                }
6857
                break;
6858
            case QEMU_OPTION_nographic:
6859
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6860
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6861
                nographic = 1;
6862
                break;
6863
            case QEMU_OPTION_kernel:
6864
                kernel_filename = optarg;
6865
                break;
6866
            case QEMU_OPTION_append:
6867
                kernel_cmdline = optarg;
6868
                break;
6869
            case QEMU_OPTION_cdrom:
6870
                {
6871
                    char buf[24];
6872
                    if (num_ide_disks >= MAX_DISKS) {
6873
                        fprintf(stderr, "qemu: too many IDE disks/cdroms defined.\n");
6874
                        exit(1);
6875
                    }
6876
                    snprintf(buf, sizeof(buf), "type=cdrom,hdx=%c,img=", cdrom_index + 'a');
6877
                    /* Build new disk IDE syntax string */
6878
                    pstrcpy(ide_options[cdrom_index],
6879
                            25,
6880
                            buf);
6881
                    /* Add on image filename */
6882
                    pstrcpy(&(ide_options[cdrom_index][24]),
6883
                            sizeof(ide_options[0])-24,
6884
                            optarg);
6885
                    num_ide_disks++;
6886
                }
6887
                break;
6888
            case QEMU_OPTION_boot:
6889
                boot_device = optarg[0];
6890
                if (boot_device != 'a' && 
6891
#ifdef TARGET_SPARC
6892
                    // Network boot
6893
                    boot_device != 'n' &&
6894
#endif
6895
                    boot_device != 'c' && boot_device != 'd') {
6896
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6897
                    exit(1);
6898
                }
6899
                break;
6900
            case QEMU_OPTION_fda:
6901
                fd_filename[0] = optarg;
6902
                break;
6903
            case QEMU_OPTION_fdb:
6904
                fd_filename[1] = optarg;
6905
                break;
6906
#ifdef TARGET_I386
6907
            case QEMU_OPTION_no_fd_bootchk:
6908
                fd_bootchk = 0;
6909
                break;
6910
#endif
6911
            case QEMU_OPTION_no_code_copy:
6912
                code_copy_enabled = 0;
6913
                break;
6914
            case QEMU_OPTION_net:
6915
                if (nb_net_clients >= MAX_NET_CLIENTS) {
6916
                    fprintf(stderr, "qemu: too many network clients\n");
6917
                    exit(1);
6918
                }
6919
                pstrcpy(net_clients[nb_net_clients],
6920
                        sizeof(net_clients[0]),
6921
                        optarg);
6922
                nb_net_clients++;
6923
                break;
6924
#ifdef CONFIG_SLIRP
6925
            case QEMU_OPTION_tftp:
6926
                tftp_prefix = optarg;
6927
                break;
6928
#ifndef _WIN32
6929
            case QEMU_OPTION_smb:
6930
                net_slirp_smb(optarg);
6931
                break;
6932
#endif
6933
            case QEMU_OPTION_redir:
6934
                net_slirp_redir(optarg);                
6935
                break;
6936
#endif
6937
#ifdef HAS_AUDIO
6938
            case QEMU_OPTION_audio_help:
6939
                AUD_help ();
6940
                exit (0);
6941
                break;
6942
            case QEMU_OPTION_soundhw:
6943
                select_soundhw (optarg);
6944
                break;
6945
#endif
6946
            case QEMU_OPTION_h:
6947
                help();
6948
                break;
6949
            case QEMU_OPTION_m:
6950
                ram_size = atoi(optarg) * 1024 * 1024;
6951
                if (ram_size <= 0)
6952
                    help();
6953
                if (ram_size > PHYS_RAM_MAX_SIZE) {
6954
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6955
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
6956
                    exit(1);
6957
                }
6958
                break;
6959
            case QEMU_OPTION_d:
6960
                {
6961
                    int mask;
6962
                    CPULogItem *item;
6963
                    
6964
                    mask = cpu_str_to_log_mask(optarg);
6965
                    if (!mask) {
6966
                        printf("Log items (comma separated):\n");
6967
                    for(item = cpu_log_items; item->mask != 0; item++) {
6968
                        printf("%-10s %s\n", item->name, item->help);
6969
                    }
6970
                    exit(1);
6971
                    }
6972
                    cpu_set_log(mask);
6973
                }
6974
                break;
6975
#ifdef CONFIG_GDBSTUB
6976
            case QEMU_OPTION_s:
6977
                use_gdbstub = 1;
6978
                break;
6979
            case QEMU_OPTION_p:
6980
                gdbstub_port = atoi(optarg);
6981
                break;
6982
#endif
6983
            case QEMU_OPTION_L:
6984
                bios_dir = optarg;
6985
                break;
6986
            case QEMU_OPTION_S:
6987
                start_emulation = 0;
6988
                break;
6989
            case QEMU_OPTION_k:
6990
                keyboard_layout = optarg;
6991
                break;
6992
            case QEMU_OPTION_localtime:
6993
                rtc_utc = 0;
6994
                break;
6995
            case QEMU_OPTION_cirrusvga:
6996
                cirrus_vga_enabled = 1;
6997
                break;
6998
            case QEMU_OPTION_std_vga:
6999
                cirrus_vga_enabled = 0;
7000
                break;
7001
            case QEMU_OPTION_g:
7002
                {
7003
                    const char *p;
7004
                    int w, h, depth;
7005
                    p = optarg;
7006
                    w = strtol(p, (char **)&p, 10);
7007
                    if (w <= 0) {
7008
                    graphic_error:
7009
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
7010
                        exit(1);
7011
                    }
7012
                    if (*p != 'x')
7013
                        goto graphic_error;
7014
                    p++;
7015
                    h = strtol(p, (char **)&p, 10);
7016
                    if (h <= 0)
7017
                        goto graphic_error;
7018
                    if (*p == 'x') {
7019
                        p++;
7020
                        depth = strtol(p, (char **)&p, 10);
7021
                        if (depth != 8 && depth != 15 && depth != 16 && 
7022
                            depth != 24 && depth != 32)
7023
                            goto graphic_error;
7024
                    } else if (*p == '\0') {
7025
                        depth = graphic_depth;
7026
                    } else {
7027
                        goto graphic_error;
7028
                    }
7029
                    
7030
                    graphic_width = w;
7031
                    graphic_height = h;
7032
                    graphic_depth = depth;
7033
                }
7034
                break;
7035
            case QEMU_OPTION_monitor:
7036
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7037
                break;
7038
            case QEMU_OPTION_serial:
7039
                if (serial_device_index >= MAX_SERIAL_PORTS) {
7040
                    fprintf(stderr, "qemu: too many serial ports\n");
7041
                    exit(1);
7042
                }
7043
                pstrcpy(serial_devices[serial_device_index], 
7044
                        sizeof(serial_devices[0]), optarg);
7045
                serial_device_index++;
7046
                break;
7047
            case QEMU_OPTION_parallel:
7048
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7049
                    fprintf(stderr, "qemu: too many parallel ports\n");
7050
                    exit(1);
7051
                }
7052
                pstrcpy(parallel_devices[parallel_device_index], 
7053
                        sizeof(parallel_devices[0]), optarg);
7054
                parallel_device_index++;
7055
                break;
7056
            case QEMU_OPTION_loadvm:
7057
                loadvm = optarg;
7058
                break;
7059
            case QEMU_OPTION_full_screen:
7060
                full_screen = 1;
7061
                break;
7062
#ifdef CONFIG_SDL
7063
            case QEMU_OPTION_no_quit:
7064
                no_quit = 1;
7065
                break;
7066
#endif
7067
            case QEMU_OPTION_pidfile:
7068
                create_pidfile(optarg);
7069
                break;
7070
#ifdef TARGET_I386
7071
            case QEMU_OPTION_win2k_hack:
7072
                win2k_install_hack = 1;
7073
                break;
7074
#endif
7075
#ifdef USE_KQEMU
7076
            case QEMU_OPTION_no_kqemu:
7077
                kqemu_allowed = 0;
7078
                break;
7079
            case QEMU_OPTION_kernel_kqemu:
7080
                kqemu_allowed = 2;
7081
                break;
7082
#endif
7083
            case QEMU_OPTION_usb:
7084
                usb_enabled = 1;
7085
                break;
7086
            case QEMU_OPTION_usbdevice:
7087
                usb_enabled = 1;
7088
                if (usb_devices_index >= MAX_USB_CMDLINE) {
7089
                    fprintf(stderr, "Too many USB devices\n");
7090
                    exit(1);
7091
                }
7092
                pstrcpy(usb_devices[usb_devices_index],
7093
                        sizeof(usb_devices[usb_devices_index]),
7094
                        optarg);
7095
                usb_devices_index++;
7096
                break;
7097
            case QEMU_OPTION_smp:
7098
                smp_cpus = atoi(optarg);
7099
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7100
                    fprintf(stderr, "Invalid number of CPUs\n");
7101
                    exit(1);
7102
                }
7103
                break;
7104
            case QEMU_OPTION_vnc:
7105
                vnc_display = optarg;
7106
                break;
7107
            case QEMU_OPTION_no_acpi:
7108
                acpi_enabled = 0;
7109
                break;
7110
            case QEMU_OPTION_no_reboot:
7111
                no_reboot = 1;
7112
                break;
7113
            case QEMU_OPTION_daemonize:
7114
                daemonize = 1;
7115
                break;
7116
            }
7117
        }
7118
    }
7119

    
7120
#ifndef _WIN32
7121
    if (daemonize && !nographic && vnc_display == NULL) {
7122
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7123
        daemonize = 0;
7124
    }
7125

    
7126
    if (daemonize) {
7127
        pid_t pid;
7128

    
7129
        if (pipe(fds) == -1)
7130
            exit(1);
7131

    
7132
        pid = fork();
7133
        if (pid > 0) {
7134
            uint8_t status;
7135
            ssize_t len;
7136

    
7137
            close(fds[1]);
7138

    
7139
        again:
7140
            len = read(fds[0], &status, 1);
7141
            if (len == -1 && (errno == EINTR))
7142
                goto again;
7143
            
7144
            if (len != 1 || status != 0)
7145
                exit(1);
7146
            else
7147
                exit(0);
7148
        } else if (pid < 0)
7149
            exit(1);
7150

    
7151
        setsid();
7152

    
7153
        pid = fork();
7154
        if (pid > 0)
7155
            exit(0);
7156
        else if (pid < 0)
7157
            exit(1);
7158

    
7159
        umask(027);
7160
        chdir("/");
7161

    
7162
        signal(SIGTSTP, SIG_IGN);
7163
        signal(SIGTTOU, SIG_IGN);
7164
        signal(SIGTTIN, SIG_IGN);
7165
    }
7166
#endif
7167

    
7168
#ifdef USE_KQEMU
7169
    if (smp_cpus > 1)
7170
        kqemu_allowed = 0;
7171
#endif
7172
    linux_boot = (kernel_filename != NULL);
7173

    
7174
    if (!linux_boot &&
7175
        num_ide_disks == 0 &&
7176
        fd_filename[0] == '\0')
7177
        help();
7178

    
7179
    setvbuf(stdout, NULL, _IOLBF, 0);
7180
    
7181
    init_timers();
7182
    init_timer_alarm();
7183
    qemu_aio_init();
7184

    
7185
#ifdef _WIN32
7186
    socket_init();
7187
#endif
7188

    
7189
    /* init network clients */
7190
    if (nb_net_clients == 0) {
7191
        /* if no clients, we use a default config */
7192
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
7193
                "nic");
7194
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
7195
                "user");
7196
        nb_net_clients = 2;
7197
    }
7198

    
7199
    for(i = 0;i < nb_net_clients; i++) {
7200
        if (net_client_init(net_clients[i]) < 0)
7201
            exit(1);
7202
    }
7203

    
7204
    /* init the memory */
7205
    phys_ram_size = ram_size + vga_ram_size + bios_size;
7206

    
7207
    phys_ram_base = qemu_vmalloc(phys_ram_size);
7208
    if (!phys_ram_base) {
7209
        fprintf(stderr, "Could not allocate physical memory\n");
7210
        exit(1);
7211
    }
7212

    
7213
    bdrv_init();
7214

    
7215
    /* open the virtual block devices, disks or CDRoms */
7216
    if (disk_options_init(num_ide_disks,ide_options,snapshot,
7217
                          num_scsi_disks,scsi_options,
7218
                          cdrom_index,
7219
                          cyls, heads, secs, translation)){
7220
        exit(1);
7221
    }
7222

    
7223
    /* boot to floppy or default cd if no hard disk */
7224
    if (num_ide_disks == 0 && boot_device == 'c') {
7225
        if (fd_filename[0] != '\0')
7226
            boot_device = 'a';
7227
        else
7228
            boot_device = 'd';
7229
    }
7230

    
7231
    /* we always create at least one floppy disk */
7232
    fd_table[0] = bdrv_new("fda");
7233
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7234

    
7235
    for(i = 0; i < MAX_FD; i++) {
7236
        if (fd_filename[i]) {
7237
            if (!fd_table[i]) {
7238
                char buf[64];
7239
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7240
                fd_table[i] = bdrv_new(buf);
7241
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7242
            }
7243
            if (fd_filename[i] != '\0') {
7244
                if (bdrv_open(fd_table[i], fd_filename[i],
7245
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7246
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7247
                            fd_filename[i]);
7248
                    exit(1);
7249
                }
7250
            }
7251
        }
7252
    }
7253

    
7254
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7255
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7256

    
7257
    init_ioports();
7258

    
7259
    /* terminal init */
7260
    if (nographic) {
7261
        dumb_display_init(ds);
7262
    } else if (vnc_display != NULL) {
7263
        vnc_display_init(ds, vnc_display);
7264
    } else {
7265
#if defined(CONFIG_SDL)
7266
        sdl_display_init(ds, full_screen);
7267
#elif defined(CONFIG_COCOA)
7268
        cocoa_display_init(ds, full_screen);
7269
#else
7270
        dumb_display_init(ds);
7271
#endif
7272
    }
7273

    
7274
    monitor_hd = qemu_chr_open(monitor_device);
7275
    if (!monitor_hd) {
7276
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7277
        exit(1);
7278
    }
7279
    monitor_init(monitor_hd, !nographic);
7280

    
7281
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7282
        const char *devname = serial_devices[i];
7283
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7284
            serial_hds[i] = qemu_chr_open(devname);
7285
            if (!serial_hds[i]) {
7286
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7287
                        devname);
7288
                exit(1);
7289
            }
7290
            if (!strcmp(devname, "vc"))
7291
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7292
        }
7293
    }
7294

    
7295
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7296
        const char *devname = parallel_devices[i];
7297
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7298
            parallel_hds[i] = qemu_chr_open(devname);
7299
            if (!parallel_hds[i]) {
7300
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7301
                        devname);
7302
                exit(1);
7303
            }
7304
            if (!strcmp(devname, "vc"))
7305
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7306
        }
7307
    }
7308

    
7309
    machine->init(ram_size, vga_ram_size, boot_device,
7310
                  ds, fd_filename, snapshot,
7311
                  kernel_filename, kernel_cmdline, initrd_filename);
7312

    
7313
    /* init USB devices */
7314
    if (usb_enabled) {
7315
        for(i = 0; i < usb_devices_index; i++) {
7316
            if (usb_device_add(usb_devices[i]) < 0) {
7317
                fprintf(stderr, "Warning: could not add USB device %s\n",
7318
                        usb_devices[i]);
7319
            }
7320
        }
7321
    }
7322

    
7323
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7324
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7325

    
7326
#ifdef CONFIG_GDBSTUB
7327
    if (use_gdbstub) {
7328
        if (gdbserver_start(gdbstub_port) < 0) {
7329
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
7330
                    gdbstub_port);
7331
            exit(1);
7332
        } else {
7333
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
7334
        }
7335
    } else 
7336
#endif
7337
    if (loadvm)
7338
        do_loadvm(loadvm);
7339

    
7340
    {
7341
        /* XXX: simplify init */
7342
        read_passwords();
7343
        if (start_emulation) {
7344
            vm_start();
7345
        }
7346
    }
7347

    
7348
    if (daemonize) {
7349
        uint8_t status = 0;
7350
        ssize_t len;
7351
        int fd;
7352

    
7353
    again1:
7354
        len = write(fds[1], &status, 1);
7355
        if (len == -1 && (errno == EINTR))
7356
            goto again1;
7357

    
7358
        if (len != 1)
7359
            exit(1);
7360

    
7361
        fd = open("/dev/null", O_RDWR);
7362
        if (fd == -1)
7363
            exit(1);
7364

    
7365
        dup2(fd, 0);
7366
        dup2(fd, 1);
7367
        dup2(fd, 2);
7368

    
7369
        close(fd);
7370
    }
7371

    
7372
    main_loop();
7373
    quit_timers();
7374
    return 0;
7375
}