Statistics
| Branch: | Revision:

root / vl.c @ 087f4ae0

History | View | Annotate | Download (183.6 kB)

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

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

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

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

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

    
74
#include "qemu_socket.h"
75

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

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

    
87
#include "disas.h"
88

    
89
#include "exec-all.h"
90

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

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

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

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

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

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

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

    
176
/***********************************************************/
177
/* x86 ISA bus support */
178

    
179
target_phys_addr_t isa_mem_base = 0;
180
PicState2 *isa_pic;
181

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

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

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

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

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

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

    
229
void init_ioports(void)
230
{
231
    int i;
232

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

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

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

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

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

    
293
void isa_unassign_ioport(int start, int length)
294
{
295
    int i;
296

    
297
    for(i = start; i < start + length; i++) {
298
        ioport_read_table[0][i] = default_ioport_readb;
299
        ioport_read_table[1][i] = default_ioport_readw;
300
        ioport_read_table[2][i] = default_ioport_readl;
301

    
302
        ioport_write_table[0][i] = default_ioport_writeb;
303
        ioport_write_table[1][i] = default_ioport_writew;
304
        ioport_write_table[2][i] = default_ioport_writel;
305
    }
306
}
307

    
308
/***********************************************************/
309

    
310
void cpu_outb(CPUState *env, int addr, int val)
311
{
312
#ifdef DEBUG_IOPORT
313
    if (loglevel & CPU_LOG_IOPORT)
314
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
315
#endif    
316
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
317
#ifdef USE_KQEMU
318
    if (env)
319
        env->last_io_time = cpu_get_time_fast();
320
#endif
321
}
322

    
323
void cpu_outw(CPUState *env, int addr, int val)
324
{
325
#ifdef DEBUG_IOPORT
326
    if (loglevel & CPU_LOG_IOPORT)
327
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
328
#endif    
329
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
330
#ifdef USE_KQEMU
331
    if (env)
332
        env->last_io_time = cpu_get_time_fast();
333
#endif
334
}
335

    
336
void cpu_outl(CPUState *env, int addr, int val)
337
{
338
#ifdef DEBUG_IOPORT
339
    if (loglevel & CPU_LOG_IOPORT)
340
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
341
#endif
342
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
343
#ifdef USE_KQEMU
344
    if (env)
345
        env->last_io_time = cpu_get_time_fast();
346
#endif
347
}
348

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

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

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

    
394
/***********************************************************/
395
void hw_error(const char *fmt, ...)
396
{
397
    va_list ap;
398
    CPUState *env;
399

    
400
    va_start(ap, fmt);
401
    fprintf(stderr, "qemu: hardware error: ");
402
    vfprintf(stderr, fmt, ap);
403
    fprintf(stderr, "\n");
404
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
405
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
406
#ifdef TARGET_I386
407
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
408
#else
409
        cpu_dump_state(env, stderr, fprintf, 0);
410
#endif
411
    }
412
    va_end(ap);
413
    abort();
414
}
415

    
416
/***********************************************************/
417
/* keyboard/mouse */
418

    
419
static QEMUPutKBDEvent *qemu_put_kbd_event;
420
static void *qemu_put_kbd_event_opaque;
421
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
422
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
423

    
424
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
425
{
426
    qemu_put_kbd_event_opaque = opaque;
427
    qemu_put_kbd_event = func;
428
}
429

    
430
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
431
                                                void *opaque, int absolute,
432
                                                const char *name)
433
{
434
    QEMUPutMouseEntry *s, *cursor;
435

    
436
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
437
    if (!s)
438
        return NULL;
439

    
440
    s->qemu_put_mouse_event = func;
441
    s->qemu_put_mouse_event_opaque = opaque;
442
    s->qemu_put_mouse_event_absolute = absolute;
443
    s->qemu_put_mouse_event_name = qemu_strdup(name);
444
    s->next = NULL;
445

    
446
    if (!qemu_put_mouse_event_head) {
447
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
448
        return s;
449
    }
450

    
451
    cursor = qemu_put_mouse_event_head;
452
    while (cursor->next != NULL)
453
        cursor = cursor->next;
454

    
455
    cursor->next = s;
456
    qemu_put_mouse_event_current = s;
457

    
458
    return s;
459
}
460

    
461
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
462
{
463
    QEMUPutMouseEntry *prev = NULL, *cursor;
464

    
465
    if (!qemu_put_mouse_event_head || entry == NULL)
466
        return;
467

    
468
    cursor = qemu_put_mouse_event_head;
469
    while (cursor != NULL && cursor != entry) {
470
        prev = cursor;
471
        cursor = cursor->next;
472
    }
473

    
474
    if (cursor == NULL) // does not exist or list empty
475
        return;
476
    else if (prev == NULL) { // entry is head
477
        qemu_put_mouse_event_head = cursor->next;
478
        if (qemu_put_mouse_event_current == entry)
479
            qemu_put_mouse_event_current = cursor->next;
480
        qemu_free(entry->qemu_put_mouse_event_name);
481
        qemu_free(entry);
482
        return;
483
    }
484

    
485
    prev->next = entry->next;
486

    
487
    if (qemu_put_mouse_event_current == entry)
488
        qemu_put_mouse_event_current = prev;
489

    
490
    qemu_free(entry->qemu_put_mouse_event_name);
491
    qemu_free(entry);
492
}
493

    
494
void kbd_put_keycode(int keycode)
495
{
496
    if (qemu_put_kbd_event) {
497
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
498
    }
499
}
500

    
501
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
502
{
503
    QEMUPutMouseEvent *mouse_event;
504
    void *mouse_event_opaque;
505

    
506
    if (!qemu_put_mouse_event_current) {
507
        return;
508
    }
509

    
510
    mouse_event =
511
        qemu_put_mouse_event_current->qemu_put_mouse_event;
512
    mouse_event_opaque =
513
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
514

    
515
    if (mouse_event) {
516
        mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
517
    }
518
}
519

    
520
int kbd_mouse_is_absolute(void)
521
{
522
    if (!qemu_put_mouse_event_current)
523
        return 0;
524

    
525
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
526
}
527

    
528
void do_info_mice(void)
529
{
530
    QEMUPutMouseEntry *cursor;
531
    int index = 0;
532

    
533
    if (!qemu_put_mouse_event_head) {
534
        term_printf("No mouse devices connected\n");
535
        return;
536
    }
537

    
538
    term_printf("Mouse devices available:\n");
539
    cursor = qemu_put_mouse_event_head;
540
    while (cursor != NULL) {
541
        term_printf("%c Mouse #%d: %s\n",
542
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
543
                    index, cursor->qemu_put_mouse_event_name);
544
        index++;
545
        cursor = cursor->next;
546
    }
547
}
548

    
549
void do_mouse_set(int index)
550
{
551
    QEMUPutMouseEntry *cursor;
552
    int i = 0;
553

    
554
    if (!qemu_put_mouse_event_head) {
555
        term_printf("No mouse devices connected\n");
556
        return;
557
    }
558

    
559
    cursor = qemu_put_mouse_event_head;
560
    while (cursor != NULL && index != i) {
561
        i++;
562
        cursor = cursor->next;
563
    }
564

    
565
    if (cursor != NULL)
566
        qemu_put_mouse_event_current = cursor;
567
    else
568
        term_printf("Mouse at given index not found\n");
569
}
570

    
571
/* compute with 96 bit intermediate result: (a*b)/c */
572
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
573
{
574
    union {
575
        uint64_t ll;
576
        struct {
577
#ifdef WORDS_BIGENDIAN
578
            uint32_t high, low;
579
#else
580
            uint32_t low, high;
581
#endif            
582
        } l;
583
    } u, res;
584
    uint64_t rl, rh;
585

    
586
    u.ll = a;
587
    rl = (uint64_t)u.l.low * (uint64_t)b;
588
    rh = (uint64_t)u.l.high * (uint64_t)b;
589
    rh += (rl >> 32);
590
    res.l.high = rh / c;
591
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
592
    return res.ll;
593
}
594

    
595
/***********************************************************/
596
/* real time host monotonic timer */
597

    
598
#define QEMU_TIMER_BASE 1000000000LL
599

    
600
#ifdef WIN32
601

    
602
static int64_t clock_freq;
603

    
604
static void init_get_clock(void)
605
{
606
    LARGE_INTEGER freq;
607
    int ret;
608
    ret = QueryPerformanceFrequency(&freq);
609
    if (ret == 0) {
610
        fprintf(stderr, "Could not calibrate ticks\n");
611
        exit(1);
612
    }
613
    clock_freq = freq.QuadPart;
614
}
615

    
616
static int64_t get_clock(void)
617
{
618
    LARGE_INTEGER ti;
619
    QueryPerformanceCounter(&ti);
620
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
621
}
622

    
623
#else
624

    
625
static int use_rt_clock;
626

    
627
static void init_get_clock(void)
628
{
629
    use_rt_clock = 0;
630
#if defined(__linux__)
631
    {
632
        struct timespec ts;
633
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
634
            use_rt_clock = 1;
635
        }
636
    }
637
#endif
638
}
639

    
640
static int64_t get_clock(void)
641
{
642
#if defined(__linux__)
643
    if (use_rt_clock) {
644
        struct timespec ts;
645
        clock_gettime(CLOCK_MONOTONIC, &ts);
646
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
647
    } else 
648
#endif
649
    {
650
        /* XXX: using gettimeofday leads to problems if the date
651
           changes, so it should be avoided. */
652
        struct timeval tv;
653
        gettimeofday(&tv, NULL);
654
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
655
    }
656
}
657

    
658
#endif
659

    
660
/***********************************************************/
661
/* guest cycle counter */
662

    
663
static int64_t cpu_ticks_prev;
664
static int64_t cpu_ticks_offset;
665
static int64_t cpu_clock_offset;
666
static int cpu_ticks_enabled;
667

    
668
/* return the host CPU cycle counter and handle stop/restart */
669
int64_t cpu_get_ticks(void)
670
{
671
    if (!cpu_ticks_enabled) {
672
        return cpu_ticks_offset;
673
    } else {
674
        int64_t ticks;
675
        ticks = cpu_get_real_ticks();
676
        if (cpu_ticks_prev > ticks) {
677
            /* Note: non increasing ticks may happen if the host uses
678
               software suspend */
679
            cpu_ticks_offset += cpu_ticks_prev - ticks;
680
        }
681
        cpu_ticks_prev = ticks;
682
        return ticks + cpu_ticks_offset;
683
    }
684
}
685

    
686
/* return the host CPU monotonic timer and handle stop/restart */
687
static int64_t cpu_get_clock(void)
688
{
689
    int64_t ti;
690
    if (!cpu_ticks_enabled) {
691
        return cpu_clock_offset;
692
    } else {
693
        ti = get_clock();
694
        return ti + cpu_clock_offset;
695
    }
696
}
697

    
698
/* enable cpu_get_ticks() */
699
void cpu_enable_ticks(void)
700
{
701
    if (!cpu_ticks_enabled) {
702
        cpu_ticks_offset -= cpu_get_real_ticks();
703
        cpu_clock_offset -= get_clock();
704
        cpu_ticks_enabled = 1;
705
    }
706
}
707

    
708
/* disable cpu_get_ticks() : the clock is stopped. You must not call
709
   cpu_get_ticks() after that.  */
710
void cpu_disable_ticks(void)
711
{
712
    if (cpu_ticks_enabled) {
713
        cpu_ticks_offset = cpu_get_ticks();
714
        cpu_clock_offset = cpu_get_clock();
715
        cpu_ticks_enabled = 0;
716
    }
717
}
718

    
719
/***********************************************************/
720
/* timers */
721
 
722
#define QEMU_TIMER_REALTIME 0
723
#define QEMU_TIMER_VIRTUAL  1
724

    
725
struct QEMUClock {
726
    int type;
727
    /* XXX: add frequency */
728
};
729

    
730
struct QEMUTimer {
731
    QEMUClock *clock;
732
    int64_t expire_time;
733
    QEMUTimerCB *cb;
734
    void *opaque;
735
    struct QEMUTimer *next;
736
};
737

    
738
QEMUClock *rt_clock;
739
QEMUClock *vm_clock;
740

    
741
static QEMUTimer *active_timers[2];
742
#ifdef _WIN32
743
static MMRESULT timerID;
744
static HANDLE host_alarm = NULL;
745
static unsigned int period = 1;
746
#else
747
/* frequency of the times() clock tick */
748
static int timer_freq;
749
#endif
750

    
751
QEMUClock *qemu_new_clock(int type)
752
{
753
    QEMUClock *clock;
754
    clock = qemu_mallocz(sizeof(QEMUClock));
755
    if (!clock)
756
        return NULL;
757
    clock->type = type;
758
    return clock;
759
}
760

    
761
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
762
{
763
    QEMUTimer *ts;
764

    
765
    ts = qemu_mallocz(sizeof(QEMUTimer));
766
    ts->clock = clock;
767
    ts->cb = cb;
768
    ts->opaque = opaque;
769
    return ts;
770
}
771

    
772
void qemu_free_timer(QEMUTimer *ts)
773
{
774
    qemu_free(ts);
775
}
776

    
777
/* stop a timer, but do not dealloc it */
778
void qemu_del_timer(QEMUTimer *ts)
779
{
780
    QEMUTimer **pt, *t;
781

    
782
    /* NOTE: this code must be signal safe because
783
       qemu_timer_expired() can be called from a signal. */
784
    pt = &active_timers[ts->clock->type];
785
    for(;;) {
786
        t = *pt;
787
        if (!t)
788
            break;
789
        if (t == ts) {
790
            *pt = t->next;
791
            break;
792
        }
793
        pt = &t->next;
794
    }
795
}
796

    
797
/* modify the current timer so that it will be fired when current_time
798
   >= expire_time. The corresponding callback will be called. */
799
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
800
{
801
    QEMUTimer **pt, *t;
802

    
803
    qemu_del_timer(ts);
804

    
805
    /* add the timer in the sorted list */
806
    /* NOTE: this code must be signal safe because
807
       qemu_timer_expired() can be called from a signal. */
808
    pt = &active_timers[ts->clock->type];
809
    for(;;) {
810
        t = *pt;
811
        if (!t)
812
            break;
813
        if (t->expire_time > expire_time) 
814
            break;
815
        pt = &t->next;
816
    }
817
    ts->expire_time = expire_time;
818
    ts->next = *pt;
819
    *pt = ts;
820
}
821

    
822
int qemu_timer_pending(QEMUTimer *ts)
823
{
824
    QEMUTimer *t;
825
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
826
        if (t == ts)
827
            return 1;
828
    }
829
    return 0;
830
}
831

    
832
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
833
{
834
    if (!timer_head)
835
        return 0;
836
    return (timer_head->expire_time <= current_time);
837
}
838

    
839
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
840
{
841
    QEMUTimer *ts;
842
    
843
    for(;;) {
844
        ts = *ptimer_head;
845
        if (!ts || ts->expire_time > current_time)
846
            break;
847
        /* remove timer from the list before calling the callback */
848
        *ptimer_head = ts->next;
849
        ts->next = NULL;
850
        
851
        /* run the callback (the timer list can be modified) */
852
        ts->cb(ts->opaque);
853
    }
854
}
855

    
856
int64_t qemu_get_clock(QEMUClock *clock)
857
{
858
    switch(clock->type) {
859
    case QEMU_TIMER_REALTIME:
860
        return get_clock() / 1000000;
861
    default:
862
    case QEMU_TIMER_VIRTUAL:
863
        return cpu_get_clock();
864
    }
865
}
866

    
867
static void init_timers(void)
868
{
869
    init_get_clock();
870
    ticks_per_sec = QEMU_TIMER_BASE;
871
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
872
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
873
}
874

    
875
/* save a timer */
876
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
877
{
878
    uint64_t expire_time;
879

    
880
    if (qemu_timer_pending(ts)) {
881
        expire_time = ts->expire_time;
882
    } else {
883
        expire_time = -1;
884
    }
885
    qemu_put_be64(f, expire_time);
886
}
887

    
888
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
889
{
890
    uint64_t expire_time;
891

    
892
    expire_time = qemu_get_be64(f);
893
    if (expire_time != -1) {
894
        qemu_mod_timer(ts, expire_time);
895
    } else {
896
        qemu_del_timer(ts);
897
    }
898
}
899

    
900
static void timer_save(QEMUFile *f, void *opaque)
901
{
902
    if (cpu_ticks_enabled) {
903
        hw_error("cannot save state if virtual timers are running");
904
    }
905
    qemu_put_be64s(f, &cpu_ticks_offset);
906
    qemu_put_be64s(f, &ticks_per_sec);
907
    qemu_put_be64s(f, &cpu_clock_offset);
908
}
909

    
910
static int timer_load(QEMUFile *f, void *opaque, int version_id)
911
{
912
    if (version_id != 1 && version_id != 2)
913
        return -EINVAL;
914
    if (cpu_ticks_enabled) {
915
        return -EINVAL;
916
    }
917
    qemu_get_be64s(f, &cpu_ticks_offset);
918
    qemu_get_be64s(f, &ticks_per_sec);
919
    if (version_id == 2) {
920
        qemu_get_be64s(f, &cpu_clock_offset);
921
    }
922
    return 0;
923
}
924

    
925
#ifdef _WIN32
926
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
927
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
928
#else
929
static void host_alarm_handler(int host_signum)
930
#endif
931
{
932
#if 0
933
#define DISP_FREQ 1000
934
    {
935
        static int64_t delta_min = INT64_MAX;
936
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
937
        static int count;
938
        ti = qemu_get_clock(vm_clock);
939
        if (last_clock != 0) {
940
            delta = ti - last_clock;
941
            if (delta < delta_min)
942
                delta_min = delta;
943
            if (delta > delta_max)
944
                delta_max = delta;
945
            delta_cum += delta;
946
            if (++count == DISP_FREQ) {
947
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
948
                       muldiv64(delta_min, 1000000, ticks_per_sec),
949
                       muldiv64(delta_max, 1000000, ticks_per_sec),
950
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
951
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
952
                count = 0;
953
                delta_min = INT64_MAX;
954
                delta_max = 0;
955
                delta_cum = 0;
956
            }
957
        }
958
        last_clock = ti;
959
    }
960
#endif
961
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
962
                           qemu_get_clock(vm_clock)) ||
963
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
964
                           qemu_get_clock(rt_clock))) {
965
#ifdef _WIN32
966
        SetEvent(host_alarm);
967
#endif
968
        CPUState *env = cpu_single_env;
969
        if (env) {
970
            /* stop the currently executing cpu because a timer occured */
971
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
972
#ifdef USE_KQEMU
973
            if (env->kqemu_enabled) {
974
                kqemu_cpu_interrupt(env);
975
            }
976
#endif
977
        }
978
    }
979
}
980

    
981
#ifndef _WIN32
982

    
983
#if defined(__linux__)
984

    
985
#define RTC_FREQ 1024
986

    
987
static int rtc_fd;
988

    
989
static int start_rtc_timer(void)
990
{
991
    rtc_fd = open("/dev/rtc", O_RDONLY);
992
    if (rtc_fd < 0)
993
        return -1;
994
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
995
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
996
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
997
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
998
        goto fail;
999
    }
1000
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1001
    fail:
1002
        close(rtc_fd);
1003
        return -1;
1004
    }
1005
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1006
    return 0;
1007
}
1008

    
1009
#else
1010

    
1011
static int start_rtc_timer(void)
1012
{
1013
    return -1;
1014
}
1015

    
1016
#endif /* !defined(__linux__) */
1017

    
1018
#endif /* !defined(_WIN32) */
1019

    
1020
static void init_timer_alarm(void)
1021
{
1022
#ifdef _WIN32
1023
    {
1024
        int count=0;
1025
        TIMECAPS tc;
1026

    
1027
        ZeroMemory(&tc, sizeof(TIMECAPS));
1028
        timeGetDevCaps(&tc, sizeof(TIMECAPS));
1029
        if (period < tc.wPeriodMin)
1030
            period = tc.wPeriodMin;
1031
        timeBeginPeriod(period);
1032
        timerID = timeSetEvent(1,     // interval (ms)
1033
                               period,     // resolution
1034
                               host_alarm_handler, // function
1035
                               (DWORD)&count,  // user parameter
1036
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1037
         if( !timerID ) {
1038
            perror("failed timer alarm");
1039
            exit(1);
1040
         }
1041
        host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1042
        if (!host_alarm) {
1043
            perror("failed CreateEvent");
1044
            exit(1);
1045
        }
1046
        qemu_add_wait_object(host_alarm, NULL, NULL);
1047
    }
1048
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1049
#else
1050
    {
1051
        struct sigaction act;
1052
        struct itimerval itv;
1053
        
1054
        /* get times() syscall frequency */
1055
        timer_freq = sysconf(_SC_CLK_TCK);
1056
        
1057
        /* timer signal */
1058
        sigfillset(&act.sa_mask);
1059
       act.sa_flags = 0;
1060
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1061
        act.sa_flags |= SA_ONSTACK;
1062
#endif
1063
        act.sa_handler = host_alarm_handler;
1064
        sigaction(SIGALRM, &act, NULL);
1065

    
1066
        itv.it_interval.tv_sec = 0;
1067
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1068
        itv.it_value.tv_sec = 0;
1069
        itv.it_value.tv_usec = 10 * 1000;
1070
        setitimer(ITIMER_REAL, &itv, NULL);
1071
        /* we probe the tick duration of the kernel to inform the user if
1072
           the emulated kernel requested a too high timer frequency */
1073
        getitimer(ITIMER_REAL, &itv);
1074

    
1075
#if defined(__linux__)
1076
        /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1077
           have timers with 1 ms resolution. The correct solution will
1078
           be to use the POSIX real time timers available in recent
1079
           2.6 kernels */
1080
        if (itv.it_interval.tv_usec > 1000 || 1) {
1081
            /* try to use /dev/rtc to have a faster timer */
1082
            if (start_rtc_timer() < 0)
1083
                goto use_itimer;
1084
            /* disable itimer */
1085
            itv.it_interval.tv_sec = 0;
1086
            itv.it_interval.tv_usec = 0;
1087
            itv.it_value.tv_sec = 0;
1088
            itv.it_value.tv_usec = 0;
1089
            setitimer(ITIMER_REAL, &itv, NULL);
1090

    
1091
            /* use the RTC */
1092
            sigaction(SIGIO, &act, NULL);
1093
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1094
            fcntl(rtc_fd, F_SETOWN, getpid());
1095
        } else 
1096
#endif /* defined(__linux__) */
1097
        {
1098
        use_itimer:
1099
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1100
                                   PIT_FREQ) / 1000000;
1101
        }
1102
    }
1103
#endif
1104
}
1105

    
1106
void quit_timers(void)
1107
{
1108
#ifdef _WIN32
1109
    timeKillEvent(timerID);
1110
    timeEndPeriod(period);
1111
    if (host_alarm) {
1112
        CloseHandle(host_alarm);
1113
        host_alarm = NULL;
1114
    }
1115
#endif
1116
}
1117

    
1118
/***********************************************************/
1119
/* character device */
1120

    
1121
static void qemu_chr_event(CharDriverState *s, int event)
1122
{
1123
    if (!s->chr_event)
1124
        return;
1125
    s->chr_event(s->handler_opaque, event);
1126
}
1127

    
1128
static void qemu_chr_reset_bh(void *opaque)
1129
{
1130
    CharDriverState *s = opaque;
1131
    qemu_chr_event(s, CHR_EVENT_RESET);
1132
    qemu_bh_delete(s->bh);
1133
    s->bh = NULL;
1134
}
1135

    
1136
void qemu_chr_reset(CharDriverState *s)
1137
{
1138
    if (s->bh == NULL) {
1139
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1140
        qemu_bh_schedule(s->bh);
1141
    }
1142
}
1143

    
1144
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1145
{
1146
    return s->chr_write(s, buf, len);
1147
}
1148

    
1149
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1150
{
1151
    if (!s->chr_ioctl)
1152
        return -ENOTSUP;
1153
    return s->chr_ioctl(s, cmd, arg);
1154
}
1155

    
1156
int qemu_chr_can_read(CharDriverState *s)
1157
{
1158
    if (!s->chr_can_read)
1159
        return 0;
1160
    return s->chr_can_read(s->handler_opaque);
1161
}
1162

    
1163
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1164
{
1165
    s->chr_read(s->handler_opaque, buf, len);
1166
}
1167

    
1168

    
1169
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1170
{
1171
    char buf[4096];
1172
    va_list ap;
1173
    va_start(ap, fmt);
1174
    vsnprintf(buf, sizeof(buf), fmt, ap);
1175
    qemu_chr_write(s, buf, strlen(buf));
1176
    va_end(ap);
1177
}
1178

    
1179
void qemu_chr_send_event(CharDriverState *s, int event)
1180
{
1181
    if (s->chr_send_event)
1182
        s->chr_send_event(s, event);
1183
}
1184

    
1185
void qemu_chr_add_handlers(CharDriverState *s, 
1186
                           IOCanRWHandler *fd_can_read, 
1187
                           IOReadHandler *fd_read,
1188
                           IOEventHandler *fd_event,
1189
                           void *opaque)
1190
{
1191
    s->chr_can_read = fd_can_read;
1192
    s->chr_read = fd_read;
1193
    s->chr_event = fd_event;
1194
    s->handler_opaque = opaque;
1195
    if (s->chr_update_read_handler)
1196
        s->chr_update_read_handler(s);
1197
}
1198
             
1199
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1200
{
1201
    return len;
1202
}
1203

    
1204
static CharDriverState *qemu_chr_open_null(void)
1205
{
1206
    CharDriverState *chr;
1207

    
1208
    chr = qemu_mallocz(sizeof(CharDriverState));
1209
    if (!chr)
1210
        return NULL;
1211
    chr->chr_write = null_chr_write;
1212
    return chr;
1213
}
1214

    
1215
#ifdef _WIN32
1216

    
1217
static void socket_cleanup(void)
1218
{
1219
    WSACleanup();
1220
}
1221

    
1222
static int socket_init(void)
1223
{
1224
    WSADATA Data;
1225
    int ret, err;
1226

    
1227
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1228
    if (ret != 0) {
1229
        err = WSAGetLastError();
1230
        fprintf(stderr, "WSAStartup: %d\n", err);
1231
        return -1;
1232
    }
1233
    atexit(socket_cleanup);
1234
    return 0;
1235
}
1236

    
1237
static int send_all(int fd, const uint8_t *buf, int len1)
1238
{
1239
    int ret, len;
1240
    
1241
    len = len1;
1242
    while (len > 0) {
1243
        ret = send(fd, buf, len, 0);
1244
        if (ret < 0) {
1245
            int errno;
1246
            errno = WSAGetLastError();
1247
            if (errno != WSAEWOULDBLOCK) {
1248
                return -1;
1249
            }
1250
        } else if (ret == 0) {
1251
            break;
1252
        } else {
1253
            buf += ret;
1254
            len -= ret;
1255
        }
1256
    }
1257
    return len1 - len;
1258
}
1259

    
1260
void socket_set_nonblock(int fd)
1261
{
1262
    unsigned long opt = 1;
1263
    ioctlsocket(fd, FIONBIO, &opt);
1264
}
1265

    
1266
#else
1267

    
1268
static int unix_write(int fd, const uint8_t *buf, int len1)
1269
{
1270
    int ret, len;
1271

    
1272
    len = len1;
1273
    while (len > 0) {
1274
        ret = write(fd, buf, len);
1275
        if (ret < 0) {
1276
            if (errno != EINTR && errno != EAGAIN)
1277
                return -1;
1278
        } else if (ret == 0) {
1279
            break;
1280
        } else {
1281
            buf += ret;
1282
            len -= ret;
1283
        }
1284
    }
1285
    return len1 - len;
1286
}
1287

    
1288
static inline int send_all(int fd, const uint8_t *buf, int len1)
1289
{
1290
    return unix_write(fd, buf, len1);
1291
}
1292

    
1293
void socket_set_nonblock(int fd)
1294
{
1295
    fcntl(fd, F_SETFL, O_NONBLOCK);
1296
}
1297
#endif /* !_WIN32 */
1298

    
1299
#ifndef _WIN32
1300

    
1301
typedef struct {
1302
    int fd_in, fd_out;
1303
    int max_size;
1304
} FDCharDriver;
1305

    
1306
#define STDIO_MAX_CLIENTS 2
1307

    
1308
static int stdio_nb_clients;
1309
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1310

    
1311
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1312
{
1313
    FDCharDriver *s = chr->opaque;
1314
    return unix_write(s->fd_out, buf, len);
1315
}
1316

    
1317
static int fd_chr_read_poll(void *opaque)
1318
{
1319
    CharDriverState *chr = opaque;
1320
    FDCharDriver *s = chr->opaque;
1321

    
1322
    s->max_size = qemu_chr_can_read(chr);
1323
    return s->max_size;
1324
}
1325

    
1326
static void fd_chr_read(void *opaque)
1327
{
1328
    CharDriverState *chr = opaque;
1329
    FDCharDriver *s = chr->opaque;
1330
    int size, len;
1331
    uint8_t buf[1024];
1332
    
1333
    len = sizeof(buf);
1334
    if (len > s->max_size)
1335
        len = s->max_size;
1336
    if (len == 0)
1337
        return;
1338
    size = read(s->fd_in, buf, len);
1339
    if (size == 0) {
1340
        /* FD has been closed. Remove it from the active list.  */
1341
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1342
        return;
1343
    }
1344
    if (size > 0) {
1345
        qemu_chr_read(chr, buf, size);
1346
    }
1347
}
1348

    
1349
static void fd_chr_update_read_handler(CharDriverState *chr)
1350
{
1351
    FDCharDriver *s = chr->opaque;
1352

    
1353
    if (s->fd_in >= 0) {
1354
        if (nographic && s->fd_in == 0) {
1355
        } else {
1356
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1357
                                 fd_chr_read, NULL, chr);
1358
        }
1359
    }
1360
}
1361

    
1362
/* open a character device to a unix fd */
1363
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1364
{
1365
    CharDriverState *chr;
1366
    FDCharDriver *s;
1367

    
1368
    chr = qemu_mallocz(sizeof(CharDriverState));
1369
    if (!chr)
1370
        return NULL;
1371
    s = qemu_mallocz(sizeof(FDCharDriver));
1372
    if (!s) {
1373
        free(chr);
1374
        return NULL;
1375
    }
1376
    s->fd_in = fd_in;
1377
    s->fd_out = fd_out;
1378
    chr->opaque = s;
1379
    chr->chr_write = fd_chr_write;
1380
    chr->chr_update_read_handler = fd_chr_update_read_handler;
1381

    
1382
    qemu_chr_reset(chr);
1383

    
1384
    return chr;
1385
}
1386

    
1387
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1388
{
1389
    int fd_out;
1390

    
1391
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1392
    if (fd_out < 0)
1393
        return NULL;
1394
    return qemu_chr_open_fd(-1, fd_out);
1395
}
1396

    
1397
static CharDriverState *qemu_chr_open_pipe(const char *filename)
1398
{
1399
    int fd_in, fd_out;
1400
    char filename_in[256], filename_out[256];
1401

    
1402
    snprintf(filename_in, 256, "%s.in", filename);
1403
    snprintf(filename_out, 256, "%s.out", filename);
1404
    fd_in = open(filename_in, O_RDWR | O_BINARY);
1405
    fd_out = open(filename_out, O_RDWR | O_BINARY);
1406
    if (fd_in < 0 || fd_out < 0) {
1407
        if (fd_in >= 0)
1408
            close(fd_in);
1409
        if (fd_out >= 0)
1410
            close(fd_out);
1411
        fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1412
        if (fd_in < 0)
1413
            return NULL;
1414
    }
1415
    return qemu_chr_open_fd(fd_in, fd_out);
1416
}
1417

    
1418

    
1419
/* for STDIO, we handle the case where several clients use it
1420
   (nographic mode) */
1421

    
1422
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1423

    
1424
#define TERM_FIFO_MAX_SIZE 1
1425

    
1426
static int term_got_escape, client_index;
1427
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1428
static int term_fifo_size;
1429
static int term_timestamps;
1430
static int64_t term_timestamps_start;
1431

    
1432
void term_print_help(void)
1433
{
1434
    printf("\n"
1435
           "C-a h    print this help\n"
1436
           "C-a x    exit emulator\n"
1437
           "C-a s    save disk data back to file (if -snapshot)\n"
1438
           "C-a b    send break (magic sysrq)\n"
1439
           "C-a t    toggle console timestamps\n"
1440
           "C-a c    switch between console and monitor\n"
1441
           "C-a C-a  send C-a\n"
1442
           );
1443
}
1444

    
1445
/* called when a char is received */
1446
static void stdio_received_byte(int ch)
1447
{
1448
    if (term_got_escape) {
1449
        term_got_escape = 0;
1450
        switch(ch) {
1451
        case 'h':
1452
            term_print_help();
1453
            break;
1454
        case 'x':
1455
            exit(0);
1456
            break;
1457
        case 's': 
1458
            {
1459
                int i;
1460
                for (i = 0; i < MAX_DISKS; i++) {
1461
                    if (bs_table[i])
1462
                        bdrv_commit(bs_table[i]);
1463
                }
1464
            }
1465
            break;
1466
        case 'b':
1467
            if (client_index < stdio_nb_clients) {
1468
                CharDriverState *chr;
1469
                FDCharDriver *s;
1470

    
1471
                chr = stdio_clients[client_index];
1472
                s = chr->opaque;
1473
                qemu_chr_event(chr, CHR_EVENT_BREAK);
1474
            }
1475
            break;
1476
        case 'c':
1477
            client_index++;
1478
            if (client_index >= stdio_nb_clients)
1479
                client_index = 0;
1480
            if (client_index == 0) {
1481
                /* send a new line in the monitor to get the prompt */
1482
                ch = '\r';
1483
                goto send_char;
1484
            }
1485
            break;
1486
        case 't':
1487
            term_timestamps = !term_timestamps;
1488
            term_timestamps_start = -1;
1489
            break;
1490
        case TERM_ESCAPE:
1491
            goto send_char;
1492
        }
1493
    } else if (ch == TERM_ESCAPE) {
1494
        term_got_escape = 1;
1495
    } else {
1496
    send_char:
1497
        if (client_index < stdio_nb_clients) {
1498
            uint8_t buf[1];
1499
            CharDriverState *chr;
1500
            
1501
            chr = stdio_clients[client_index];
1502
            if (qemu_chr_can_read(chr) > 0) {
1503
                buf[0] = ch;
1504
                qemu_chr_read(chr, buf, 1);
1505
            } else if (term_fifo_size == 0) {
1506
                term_fifo[term_fifo_size++] = ch;
1507
            }
1508
        }
1509
    }
1510
}
1511

    
1512
static int stdio_read_poll(void *opaque)
1513
{
1514
    CharDriverState *chr;
1515

    
1516
    if (client_index < stdio_nb_clients) {
1517
        chr = stdio_clients[client_index];
1518
        /* try to flush the queue if needed */
1519
        if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1520
            qemu_chr_read(chr, term_fifo, 1);
1521
            term_fifo_size = 0;
1522
        }
1523
        /* see if we can absorb more chars */
1524
        if (term_fifo_size == 0)
1525
            return 1;
1526
        else
1527
            return 0;
1528
    } else {
1529
        return 1;
1530
    }
1531
}
1532

    
1533
static void stdio_read(void *opaque)
1534
{
1535
    int size;
1536
    uint8_t buf[1];
1537
    
1538
    size = read(0, buf, 1);
1539
    if (size == 0) {
1540
        /* stdin has been closed. Remove it from the active list.  */
1541
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1542
        return;
1543
    }
1544
    if (size > 0)
1545
        stdio_received_byte(buf[0]);
1546
}
1547

    
1548
static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1549
{
1550
    FDCharDriver *s = chr->opaque;
1551
    if (!term_timestamps) {
1552
        return unix_write(s->fd_out, buf, len);
1553
    } else {
1554
        int i;
1555
        char buf1[64];
1556

    
1557
        for(i = 0; i < len; i++) {
1558
            unix_write(s->fd_out, buf + i, 1);
1559
            if (buf[i] == '\n') {
1560
                int64_t ti;
1561
                int secs;
1562

    
1563
                ti = get_clock();
1564
                if (term_timestamps_start == -1)
1565
                    term_timestamps_start = ti;
1566
                ti -= term_timestamps_start;
1567
                secs = ti / 1000000000;
1568
                snprintf(buf1, sizeof(buf1), 
1569
                         "[%02d:%02d:%02d.%03d] ",
1570
                         secs / 3600,
1571
                         (secs / 60) % 60,
1572
                         secs % 60,
1573
                         (int)((ti / 1000000) % 1000));
1574
                unix_write(s->fd_out, buf1, strlen(buf1));
1575
            }
1576
        }
1577
        return len;
1578
    }
1579
}
1580

    
1581
/* init terminal so that we can grab keys */
1582
static struct termios oldtty;
1583
static int old_fd0_flags;
1584

    
1585
static void term_exit(void)
1586
{
1587
    tcsetattr (0, TCSANOW, &oldtty);
1588
    fcntl(0, F_SETFL, old_fd0_flags);
1589
}
1590

    
1591
static void term_init(void)
1592
{
1593
    struct termios tty;
1594

    
1595
    tcgetattr (0, &tty);
1596
    oldtty = tty;
1597
    old_fd0_flags = fcntl(0, F_GETFL);
1598

    
1599
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1600
                          |INLCR|IGNCR|ICRNL|IXON);
1601
    tty.c_oflag |= OPOST;
1602
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1603
    /* if graphical mode, we allow Ctrl-C handling */
1604
    if (nographic)
1605
        tty.c_lflag &= ~ISIG;
1606
    tty.c_cflag &= ~(CSIZE|PARENB);
1607
    tty.c_cflag |= CS8;
1608
    tty.c_cc[VMIN] = 1;
1609
    tty.c_cc[VTIME] = 0;
1610
    
1611
    tcsetattr (0, TCSANOW, &tty);
1612

    
1613
    atexit(term_exit);
1614

    
1615
    fcntl(0, F_SETFL, O_NONBLOCK);
1616
}
1617

    
1618
static CharDriverState *qemu_chr_open_stdio(void)
1619
{
1620
    CharDriverState *chr;
1621

    
1622
    if (nographic) {
1623
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1624
            return NULL;
1625
        chr = qemu_chr_open_fd(0, 1);
1626
        chr->chr_write = stdio_write;
1627
        if (stdio_nb_clients == 0)
1628
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1629
        client_index = stdio_nb_clients;
1630
    } else {
1631
        if (stdio_nb_clients != 0)
1632
            return NULL;
1633
        chr = qemu_chr_open_fd(0, 1);
1634
    }
1635
    stdio_clients[stdio_nb_clients++] = chr;
1636
    if (stdio_nb_clients == 1) {
1637
        /* set the terminal in raw mode */
1638
        term_init();
1639
    }
1640
    return chr;
1641
}
1642

    
1643
#if defined(__linux__)
1644
static CharDriverState *qemu_chr_open_pty(void)
1645
{
1646
    struct termios tty;
1647
    char slave_name[1024];
1648
    int master_fd, slave_fd;
1649
    
1650
    /* Not satisfying */
1651
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1652
        return NULL;
1653
    }
1654
    
1655
    /* Disabling local echo and line-buffered output */
1656
    tcgetattr (master_fd, &tty);
1657
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1658
    tty.c_cc[VMIN] = 1;
1659
    tty.c_cc[VTIME] = 0;
1660
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1661

    
1662
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1663
    return qemu_chr_open_fd(master_fd, master_fd);
1664
}
1665

    
1666
static void tty_serial_init(int fd, int speed, 
1667
                            int parity, int data_bits, int stop_bits)
1668
{
1669
    struct termios tty;
1670
    speed_t spd;
1671

    
1672
#if 0
1673
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1674
           speed, parity, data_bits, stop_bits);
1675
#endif
1676
    tcgetattr (fd, &tty);
1677

    
1678
    switch(speed) {
1679
    case 50:
1680
        spd = B50;
1681
        break;
1682
    case 75:
1683
        spd = B75;
1684
        break;
1685
    case 300:
1686
        spd = B300;
1687
        break;
1688
    case 600:
1689
        spd = B600;
1690
        break;
1691
    case 1200:
1692
        spd = B1200;
1693
        break;
1694
    case 2400:
1695
        spd = B2400;
1696
        break;
1697
    case 4800:
1698
        spd = B4800;
1699
        break;
1700
    case 9600:
1701
        spd = B9600;
1702
        break;
1703
    case 19200:
1704
        spd = B19200;
1705
        break;
1706
    case 38400:
1707
        spd = B38400;
1708
        break;
1709
    case 57600:
1710
        spd = B57600;
1711
        break;
1712
    default:
1713
    case 115200:
1714
        spd = B115200;
1715
        break;
1716
    }
1717

    
1718
    cfsetispeed(&tty, spd);
1719
    cfsetospeed(&tty, spd);
1720

    
1721
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1722
                          |INLCR|IGNCR|ICRNL|IXON);
1723
    tty.c_oflag |= OPOST;
1724
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1725
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1726
    switch(data_bits) {
1727
    default:
1728
    case 8:
1729
        tty.c_cflag |= CS8;
1730
        break;
1731
    case 7:
1732
        tty.c_cflag |= CS7;
1733
        break;
1734
    case 6:
1735
        tty.c_cflag |= CS6;
1736
        break;
1737
    case 5:
1738
        tty.c_cflag |= CS5;
1739
        break;
1740
    }
1741
    switch(parity) {
1742
    default:
1743
    case 'N':
1744
        break;
1745
    case 'E':
1746
        tty.c_cflag |= PARENB;
1747
        break;
1748
    case 'O':
1749
        tty.c_cflag |= PARENB | PARODD;
1750
        break;
1751
    }
1752
    if (stop_bits == 2)
1753
        tty.c_cflag |= CSTOPB;
1754
    
1755
    tcsetattr (fd, TCSANOW, &tty);
1756
}
1757

    
1758
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1759
{
1760
    FDCharDriver *s = chr->opaque;
1761
    
1762
    switch(cmd) {
1763
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1764
        {
1765
            QEMUSerialSetParams *ssp = arg;
1766
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1767
                            ssp->data_bits, ssp->stop_bits);
1768
        }
1769
        break;
1770
    case CHR_IOCTL_SERIAL_SET_BREAK:
1771
        {
1772
            int enable = *(int *)arg;
1773
            if (enable)
1774
                tcsendbreak(s->fd_in, 1);
1775
        }
1776
        break;
1777
    default:
1778
        return -ENOTSUP;
1779
    }
1780
    return 0;
1781
}
1782

    
1783
static CharDriverState *qemu_chr_open_tty(const char *filename)
1784
{
1785
    CharDriverState *chr;
1786
    int fd;
1787

    
1788
    fd = open(filename, O_RDWR | O_NONBLOCK);
1789
    if (fd < 0)
1790
        return NULL;
1791
    fcntl(fd, F_SETFL, O_NONBLOCK);
1792
    tty_serial_init(fd, 115200, 'N', 8, 1);
1793
    chr = qemu_chr_open_fd(fd, fd);
1794
    if (!chr)
1795
        return NULL;
1796
    chr->chr_ioctl = tty_serial_ioctl;
1797
    qemu_chr_reset(chr);
1798
    return chr;
1799
}
1800

    
1801
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1802
{
1803
    int fd = (int)chr->opaque;
1804
    uint8_t b;
1805

    
1806
    switch(cmd) {
1807
    case CHR_IOCTL_PP_READ_DATA:
1808
        if (ioctl(fd, PPRDATA, &b) < 0)
1809
            return -ENOTSUP;
1810
        *(uint8_t *)arg = b;
1811
        break;
1812
    case CHR_IOCTL_PP_WRITE_DATA:
1813
        b = *(uint8_t *)arg;
1814
        if (ioctl(fd, PPWDATA, &b) < 0)
1815
            return -ENOTSUP;
1816
        break;
1817
    case CHR_IOCTL_PP_READ_CONTROL:
1818
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1819
            return -ENOTSUP;
1820
        *(uint8_t *)arg = b;
1821
        break;
1822
    case CHR_IOCTL_PP_WRITE_CONTROL:
1823
        b = *(uint8_t *)arg;
1824
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1825
            return -ENOTSUP;
1826
        break;
1827
    case CHR_IOCTL_PP_READ_STATUS:
1828
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1829
            return -ENOTSUP;
1830
        *(uint8_t *)arg = b;
1831
        break;
1832
    default:
1833
        return -ENOTSUP;
1834
    }
1835
    return 0;
1836
}
1837

    
1838
static CharDriverState *qemu_chr_open_pp(const char *filename)
1839
{
1840
    CharDriverState *chr;
1841
    int fd;
1842

    
1843
    fd = open(filename, O_RDWR);
1844
    if (fd < 0)
1845
        return NULL;
1846

    
1847
    if (ioctl(fd, PPCLAIM) < 0) {
1848
        close(fd);
1849
        return NULL;
1850
    }
1851

    
1852
    chr = qemu_mallocz(sizeof(CharDriverState));
1853
    if (!chr) {
1854
        close(fd);
1855
        return NULL;
1856
    }
1857
    chr->opaque = (void *)fd;
1858
    chr->chr_write = null_chr_write;
1859
    chr->chr_ioctl = pp_ioctl;
1860

    
1861
    qemu_chr_reset(chr);
1862

    
1863
    return chr;
1864
}
1865

    
1866
#else
1867
static CharDriverState *qemu_chr_open_pty(void)
1868
{
1869
    return NULL;
1870
}
1871
#endif
1872

    
1873
#endif /* !defined(_WIN32) */
1874

    
1875
#ifdef _WIN32
1876
typedef struct {
1877
    int max_size;
1878
    HANDLE hcom, hrecv, hsend;
1879
    OVERLAPPED orecv, osend;
1880
    BOOL fpipe;
1881
    DWORD len;
1882
} WinCharState;
1883

    
1884
#define NSENDBUF 2048
1885
#define NRECVBUF 2048
1886
#define MAXCONNECT 1
1887
#define NTIMEOUT 5000
1888

    
1889
static int win_chr_poll(void *opaque);
1890
static int win_chr_pipe_poll(void *opaque);
1891

    
1892
static void win_chr_close(CharDriverState *chr)
1893
{
1894
    WinCharState *s = chr->opaque;
1895

    
1896
    if (s->hsend) {
1897
        CloseHandle(s->hsend);
1898
        s->hsend = NULL;
1899
    }
1900
    if (s->hrecv) {
1901
        CloseHandle(s->hrecv);
1902
        s->hrecv = NULL;
1903
    }
1904
    if (s->hcom) {
1905
        CloseHandle(s->hcom);
1906
        s->hcom = NULL;
1907
    }
1908
    if (s->fpipe)
1909
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
1910
    else
1911
        qemu_del_polling_cb(win_chr_poll, chr);
1912
}
1913

    
1914
static int win_chr_init(CharDriverState *chr, const char *filename)
1915
{
1916
    WinCharState *s = chr->opaque;
1917
    COMMCONFIG comcfg;
1918
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1919
    COMSTAT comstat;
1920
    DWORD size;
1921
    DWORD err;
1922
    
1923
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1924
    if (!s->hsend) {
1925
        fprintf(stderr, "Failed CreateEvent\n");
1926
        goto fail;
1927
    }
1928
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1929
    if (!s->hrecv) {
1930
        fprintf(stderr, "Failed CreateEvent\n");
1931
        goto fail;
1932
    }
1933

    
1934
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1935
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1936
    if (s->hcom == INVALID_HANDLE_VALUE) {
1937
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1938
        s->hcom = NULL;
1939
        goto fail;
1940
    }
1941
    
1942
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1943
        fprintf(stderr, "Failed SetupComm\n");
1944
        goto fail;
1945
    }
1946
    
1947
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1948
    size = sizeof(COMMCONFIG);
1949
    GetDefaultCommConfig(filename, &comcfg, &size);
1950
    comcfg.dcb.DCBlength = sizeof(DCB);
1951
    CommConfigDialog(filename, NULL, &comcfg);
1952

    
1953
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1954
        fprintf(stderr, "Failed SetCommState\n");
1955
        goto fail;
1956
    }
1957

    
1958
    if (!SetCommMask(s->hcom, EV_ERR)) {
1959
        fprintf(stderr, "Failed SetCommMask\n");
1960
        goto fail;
1961
    }
1962

    
1963
    cto.ReadIntervalTimeout = MAXDWORD;
1964
    if (!SetCommTimeouts(s->hcom, &cto)) {
1965
        fprintf(stderr, "Failed SetCommTimeouts\n");
1966
        goto fail;
1967
    }
1968
    
1969
    if (!ClearCommError(s->hcom, &err, &comstat)) {
1970
        fprintf(stderr, "Failed ClearCommError\n");
1971
        goto fail;
1972
    }
1973
    qemu_add_polling_cb(win_chr_poll, chr);
1974
    return 0;
1975

    
1976
 fail:
1977
    win_chr_close(chr);
1978
    return -1;
1979
}
1980

    
1981
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1982
{
1983
    WinCharState *s = chr->opaque;
1984
    DWORD len, ret, size, err;
1985

    
1986
    len = len1;
1987
    ZeroMemory(&s->osend, sizeof(s->osend));
1988
    s->osend.hEvent = s->hsend;
1989
    while (len > 0) {
1990
        if (s->hsend)
1991
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1992
        else
1993
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
1994
        if (!ret) {
1995
            err = GetLastError();
1996
            if (err == ERROR_IO_PENDING) {
1997
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1998
                if (ret) {
1999
                    buf += size;
2000
                    len -= size;
2001
                } else {
2002
                    break;
2003
                }
2004
            } else {
2005
                break;
2006
            }
2007
        } else {
2008
            buf += size;
2009
            len -= size;
2010
        }
2011
    }
2012
    return len1 - len;
2013
}
2014

    
2015
static int win_chr_read_poll(CharDriverState *chr)
2016
{
2017
    WinCharState *s = chr->opaque;
2018

    
2019
    s->max_size = qemu_chr_can_read(chr);
2020
    return s->max_size;
2021
}
2022

    
2023
static void win_chr_readfile(CharDriverState *chr)
2024
{
2025
    WinCharState *s = chr->opaque;
2026
    int ret, err;
2027
    uint8_t buf[1024];
2028
    DWORD size;
2029
    
2030
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2031
    s->orecv.hEvent = s->hrecv;
2032
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2033
    if (!ret) {
2034
        err = GetLastError();
2035
        if (err == ERROR_IO_PENDING) {
2036
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2037
        }
2038
    }
2039

    
2040
    if (size > 0) {
2041
        qemu_chr_read(chr, buf, size);
2042
    }
2043
}
2044

    
2045
static void win_chr_read(CharDriverState *chr)
2046
{
2047
    WinCharState *s = chr->opaque;
2048

    
2049
    if (s->len > s->max_size)
2050
        s->len = s->max_size;
2051
    if (s->len == 0)
2052
        return;
2053
    
2054
    win_chr_readfile(chr);
2055
}
2056

    
2057
static int win_chr_poll(void *opaque)
2058
{
2059
    CharDriverState *chr = opaque;
2060
    WinCharState *s = chr->opaque;
2061
    COMSTAT status;
2062
    DWORD comerr;
2063
    
2064
    ClearCommError(s->hcom, &comerr, &status);
2065
    if (status.cbInQue > 0) {
2066
        s->len = status.cbInQue;
2067
        win_chr_read_poll(chr);
2068
        win_chr_read(chr);
2069
        return 1;
2070
    }
2071
    return 0;
2072
}
2073

    
2074
static CharDriverState *qemu_chr_open_win(const char *filename)
2075
{
2076
    CharDriverState *chr;
2077
    WinCharState *s;
2078
    
2079
    chr = qemu_mallocz(sizeof(CharDriverState));
2080
    if (!chr)
2081
        return NULL;
2082
    s = qemu_mallocz(sizeof(WinCharState));
2083
    if (!s) {
2084
        free(chr);
2085
        return NULL;
2086
    }
2087
    chr->opaque = s;
2088
    chr->chr_write = win_chr_write;
2089
    chr->chr_close = win_chr_close;
2090

    
2091
    if (win_chr_init(chr, filename) < 0) {
2092
        free(s);
2093
        free(chr);
2094
        return NULL;
2095
    }
2096
    qemu_chr_reset(chr);
2097
    return chr;
2098
}
2099

    
2100
static int win_chr_pipe_poll(void *opaque)
2101
{
2102
    CharDriverState *chr = opaque;
2103
    WinCharState *s = chr->opaque;
2104
    DWORD size;
2105

    
2106
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2107
    if (size > 0) {
2108
        s->len = size;
2109
        win_chr_read_poll(chr);
2110
        win_chr_read(chr);
2111
        return 1;
2112
    }
2113
    return 0;
2114
}
2115

    
2116
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2117
{
2118
    WinCharState *s = chr->opaque;
2119
    OVERLAPPED ov;
2120
    int ret;
2121
    DWORD size;
2122
    char openname[256];
2123
    
2124
    s->fpipe = TRUE;
2125

    
2126
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2127
    if (!s->hsend) {
2128
        fprintf(stderr, "Failed CreateEvent\n");
2129
        goto fail;
2130
    }
2131
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2132
    if (!s->hrecv) {
2133
        fprintf(stderr, "Failed CreateEvent\n");
2134
        goto fail;
2135
    }
2136
    
2137
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2138
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2139
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2140
                              PIPE_WAIT,
2141
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2142
    if (s->hcom == INVALID_HANDLE_VALUE) {
2143
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2144
        s->hcom = NULL;
2145
        goto fail;
2146
    }
2147

    
2148
    ZeroMemory(&ov, sizeof(ov));
2149
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2150
    ret = ConnectNamedPipe(s->hcom, &ov);
2151
    if (ret) {
2152
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2153
        goto fail;
2154
    }
2155

    
2156
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2157
    if (!ret) {
2158
        fprintf(stderr, "Failed GetOverlappedResult\n");
2159
        if (ov.hEvent) {
2160
            CloseHandle(ov.hEvent);
2161
            ov.hEvent = NULL;
2162
        }
2163
        goto fail;
2164
    }
2165

    
2166
    if (ov.hEvent) {
2167
        CloseHandle(ov.hEvent);
2168
        ov.hEvent = NULL;
2169
    }
2170
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2171
    return 0;
2172

    
2173
 fail:
2174
    win_chr_close(chr);
2175
    return -1;
2176
}
2177

    
2178

    
2179
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2180
{
2181
    CharDriverState *chr;
2182
    WinCharState *s;
2183

    
2184
    chr = qemu_mallocz(sizeof(CharDriverState));
2185
    if (!chr)
2186
        return NULL;
2187
    s = qemu_mallocz(sizeof(WinCharState));
2188
    if (!s) {
2189
        free(chr);
2190
        return NULL;
2191
    }
2192
    chr->opaque = s;
2193
    chr->chr_write = win_chr_write;
2194
    chr->chr_close = win_chr_close;
2195
    
2196
    if (win_chr_pipe_init(chr, filename) < 0) {
2197
        free(s);
2198
        free(chr);
2199
        return NULL;
2200
    }
2201
    qemu_chr_reset(chr);
2202
    return chr;
2203
}
2204

    
2205
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2206
{
2207
    CharDriverState *chr;
2208
    WinCharState *s;
2209

    
2210
    chr = qemu_mallocz(sizeof(CharDriverState));
2211
    if (!chr)
2212
        return NULL;
2213
    s = qemu_mallocz(sizeof(WinCharState));
2214
    if (!s) {
2215
        free(chr);
2216
        return NULL;
2217
    }
2218
    s->hcom = fd_out;
2219
    chr->opaque = s;
2220
    chr->chr_write = win_chr_write;
2221
    qemu_chr_reset(chr);
2222
    return chr;
2223
}
2224
    
2225
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2226
{
2227
    HANDLE fd_out;
2228
    
2229
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2230
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2231
    if (fd_out == INVALID_HANDLE_VALUE)
2232
        return NULL;
2233

    
2234
    return qemu_chr_open_win_file(fd_out);
2235
}
2236
#endif
2237

    
2238
/***********************************************************/
2239
/* UDP Net console */
2240

    
2241
typedef struct {
2242
    int fd;
2243
    struct sockaddr_in daddr;
2244
    char buf[1024];
2245
    int bufcnt;
2246
    int bufptr;
2247
    int max_size;
2248
} NetCharDriver;
2249

    
2250
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2251
{
2252
    NetCharDriver *s = chr->opaque;
2253

    
2254
    return sendto(s->fd, buf, len, 0,
2255
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2256
}
2257

    
2258
static int udp_chr_read_poll(void *opaque)
2259
{
2260
    CharDriverState *chr = opaque;
2261
    NetCharDriver *s = chr->opaque;
2262

    
2263
    s->max_size = qemu_chr_can_read(chr);
2264

    
2265
    /* If there were any stray characters in the queue process them
2266
     * first
2267
     */
2268
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2269
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2270
        s->bufptr++;
2271
        s->max_size = qemu_chr_can_read(chr);
2272
    }
2273
    return s->max_size;
2274
}
2275

    
2276
static void udp_chr_read(void *opaque)
2277
{
2278
    CharDriverState *chr = opaque;
2279
    NetCharDriver *s = chr->opaque;
2280

    
2281
    if (s->max_size == 0)
2282
        return;
2283
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2284
    s->bufptr = s->bufcnt;
2285
    if (s->bufcnt <= 0)
2286
        return;
2287

    
2288
    s->bufptr = 0;
2289
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2290
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2291
        s->bufptr++;
2292
        s->max_size = qemu_chr_can_read(chr);
2293
    }
2294
}
2295

    
2296
static void udp_chr_update_read_handler(CharDriverState *chr)
2297
{
2298
    NetCharDriver *s = chr->opaque;
2299

    
2300
    if (s->fd >= 0) {
2301
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2302
                             udp_chr_read, NULL, chr);
2303
    }
2304
}
2305

    
2306
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2307
#ifndef _WIN32
2308
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2309
#endif
2310
int parse_host_src_port(struct sockaddr_in *haddr,
2311
                        struct sockaddr_in *saddr,
2312
                        const char *str);
2313

    
2314
static CharDriverState *qemu_chr_open_udp(const char *def)
2315
{
2316
    CharDriverState *chr = NULL;
2317
    NetCharDriver *s = NULL;
2318
    int fd = -1;
2319
    struct sockaddr_in saddr;
2320

    
2321
    chr = qemu_mallocz(sizeof(CharDriverState));
2322
    if (!chr)
2323
        goto return_err;
2324
    s = qemu_mallocz(sizeof(NetCharDriver));
2325
    if (!s)
2326
        goto return_err;
2327

    
2328
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2329
    if (fd < 0) {
2330
        perror("socket(PF_INET, SOCK_DGRAM)");
2331
        goto return_err;
2332
    }
2333

    
2334
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2335
        printf("Could not parse: %s\n", def);
2336
        goto return_err;
2337
    }
2338

    
2339
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2340
    {
2341
        perror("bind");
2342
        goto return_err;
2343
    }
2344

    
2345
    s->fd = fd;
2346
    s->bufcnt = 0;
2347
    s->bufptr = 0;
2348
    chr->opaque = s;
2349
    chr->chr_write = udp_chr_write;
2350
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2351
    return chr;
2352

    
2353
return_err:
2354
    if (chr)
2355
        free(chr);
2356
    if (s)
2357
        free(s);
2358
    if (fd >= 0)
2359
        closesocket(fd);
2360
    return NULL;
2361
}
2362

    
2363
/***********************************************************/
2364
/* TCP Net console */
2365

    
2366
typedef struct {
2367
    int fd, listen_fd;
2368
    int connected;
2369
    int max_size;
2370
    int do_telnetopt;
2371
    int do_nodelay;
2372
    int is_unix;
2373
} TCPCharDriver;
2374

    
2375
static void tcp_chr_accept(void *opaque);
2376

    
2377
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2378
{
2379
    TCPCharDriver *s = chr->opaque;
2380
    if (s->connected) {
2381
        return send_all(s->fd, buf, len);
2382
    } else {
2383
        /* XXX: indicate an error ? */
2384
        return len;
2385
    }
2386
}
2387

    
2388
static int tcp_chr_read_poll(void *opaque)
2389
{
2390
    CharDriverState *chr = opaque;
2391
    TCPCharDriver *s = chr->opaque;
2392
    if (!s->connected)
2393
        return 0;
2394
    s->max_size = qemu_chr_can_read(chr);
2395
    return s->max_size;
2396
}
2397

    
2398
#define IAC 255
2399
#define IAC_BREAK 243
2400
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2401
                                      TCPCharDriver *s,
2402
                                      char *buf, int *size)
2403
{
2404
    /* Handle any telnet client's basic IAC options to satisfy char by
2405
     * char mode with no echo.  All IAC options will be removed from
2406
     * the buf and the do_telnetopt variable will be used to track the
2407
     * state of the width of the IAC information.
2408
     *
2409
     * IAC commands come in sets of 3 bytes with the exception of the
2410
     * "IAC BREAK" command and the double IAC.
2411
     */
2412

    
2413
    int i;
2414
    int j = 0;
2415

    
2416
    for (i = 0; i < *size; i++) {
2417
        if (s->do_telnetopt > 1) {
2418
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2419
                /* Double IAC means send an IAC */
2420
                if (j != i)
2421
                    buf[j] = buf[i];
2422
                j++;
2423
                s->do_telnetopt = 1;
2424
            } else {
2425
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2426
                    /* Handle IAC break commands by sending a serial break */
2427
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
2428
                    s->do_telnetopt++;
2429
                }
2430
                s->do_telnetopt++;
2431
            }
2432
            if (s->do_telnetopt >= 4) {
2433
                s->do_telnetopt = 1;
2434
            }
2435
        } else {
2436
            if ((unsigned char)buf[i] == IAC) {
2437
                s->do_telnetopt = 2;
2438
            } else {
2439
                if (j != i)
2440
                    buf[j] = buf[i];
2441
                j++;
2442
            }
2443
        }
2444
    }
2445
    *size = j;
2446
}
2447

    
2448
static void tcp_chr_read(void *opaque)
2449
{
2450
    CharDriverState *chr = opaque;
2451
    TCPCharDriver *s = chr->opaque;
2452
    uint8_t buf[1024];
2453
    int len, size;
2454

    
2455
    if (!s->connected || s->max_size <= 0)
2456
        return;
2457
    len = sizeof(buf);
2458
    if (len > s->max_size)
2459
        len = s->max_size;
2460
    size = recv(s->fd, buf, len, 0);
2461
    if (size == 0) {
2462
        /* connection closed */
2463
        s->connected = 0;
2464
        if (s->listen_fd >= 0) {
2465
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2466
        }
2467
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2468
        closesocket(s->fd);
2469
        s->fd = -1;
2470
    } else if (size > 0) {
2471
        if (s->do_telnetopt)
2472
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2473
        if (size > 0)
2474
            qemu_chr_read(chr, buf, size);
2475
    }
2476
}
2477

    
2478
static void tcp_chr_connect(void *opaque)
2479
{
2480
    CharDriverState *chr = opaque;
2481
    TCPCharDriver *s = chr->opaque;
2482

    
2483
    s->connected = 1;
2484
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2485
                         tcp_chr_read, NULL, chr);
2486
    qemu_chr_reset(chr);
2487
}
2488

    
2489
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2490
static void tcp_chr_telnet_init(int fd)
2491
{
2492
    char buf[3];
2493
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2494
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2495
    send(fd, (char *)buf, 3, 0);
2496
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2497
    send(fd, (char *)buf, 3, 0);
2498
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2499
    send(fd, (char *)buf, 3, 0);
2500
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2501
    send(fd, (char *)buf, 3, 0);
2502
}
2503

    
2504
static void socket_set_nodelay(int fd)
2505
{
2506
    int val = 1;
2507
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2508
}
2509

    
2510
static void tcp_chr_accept(void *opaque)
2511
{
2512
    CharDriverState *chr = opaque;
2513
    TCPCharDriver *s = chr->opaque;
2514
    struct sockaddr_in saddr;
2515
#ifndef _WIN32
2516
    struct sockaddr_un uaddr;
2517
#endif
2518
    struct sockaddr *addr;
2519
    socklen_t len;
2520
    int fd;
2521

    
2522
    for(;;) {
2523
#ifndef _WIN32
2524
        if (s->is_unix) {
2525
            len = sizeof(uaddr);
2526
            addr = (struct sockaddr *)&uaddr;
2527
        } else
2528
#endif
2529
        {
2530
            len = sizeof(saddr);
2531
            addr = (struct sockaddr *)&saddr;
2532
        }
2533
        fd = accept(s->listen_fd, addr, &len);
2534
        if (fd < 0 && errno != EINTR) {
2535
            return;
2536
        } else if (fd >= 0) {
2537
            if (s->do_telnetopt)
2538
                tcp_chr_telnet_init(fd);
2539
            break;
2540
        }
2541
    }
2542
    socket_set_nonblock(fd);
2543
    if (s->do_nodelay)
2544
        socket_set_nodelay(fd);
2545
    s->fd = fd;
2546
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2547
    tcp_chr_connect(chr);
2548
}
2549

    
2550
static void tcp_chr_close(CharDriverState *chr)
2551
{
2552
    TCPCharDriver *s = chr->opaque;
2553
    if (s->fd >= 0)
2554
        closesocket(s->fd);
2555
    if (s->listen_fd >= 0)
2556
        closesocket(s->listen_fd);
2557
    qemu_free(s);
2558
}
2559

    
2560
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2561
                                          int is_telnet,
2562
                                          int is_unix)
2563
{
2564
    CharDriverState *chr = NULL;
2565
    TCPCharDriver *s = NULL;
2566
    int fd = -1, ret, err, val;
2567
    int is_listen = 0;
2568
    int is_waitconnect = 1;
2569
    int do_nodelay = 0;
2570
    const char *ptr;
2571
    struct sockaddr_in saddr;
2572
#ifndef _WIN32
2573
    struct sockaddr_un uaddr;
2574
#endif
2575
    struct sockaddr *addr;
2576
    socklen_t addrlen;
2577

    
2578
#ifndef _WIN32
2579
    if (is_unix) {
2580
        addr = (struct sockaddr *)&uaddr;
2581
        addrlen = sizeof(uaddr);
2582
        if (parse_unix_path(&uaddr, host_str) < 0)
2583
            goto fail;
2584
    } else
2585
#endif
2586
    {
2587
        addr = (struct sockaddr *)&saddr;
2588
        addrlen = sizeof(saddr);
2589
        if (parse_host_port(&saddr, host_str) < 0)
2590
            goto fail;
2591
    }
2592

    
2593
    ptr = host_str;
2594
    while((ptr = strchr(ptr,','))) {
2595
        ptr++;
2596
        if (!strncmp(ptr,"server",6)) {
2597
            is_listen = 1;
2598
        } else if (!strncmp(ptr,"nowait",6)) {
2599
            is_waitconnect = 0;
2600
        } else if (!strncmp(ptr,"nodelay",6)) {
2601
            do_nodelay = 1;
2602
        } else {
2603
            printf("Unknown option: %s\n", ptr);
2604
            goto fail;
2605
        }
2606
    }
2607
    if (!is_listen)
2608
        is_waitconnect = 0;
2609

    
2610
    chr = qemu_mallocz(sizeof(CharDriverState));
2611
    if (!chr)
2612
        goto fail;
2613
    s = qemu_mallocz(sizeof(TCPCharDriver));
2614
    if (!s)
2615
        goto fail;
2616

    
2617
#ifndef _WIN32
2618
    if (is_unix)
2619
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2620
    else
2621
#endif
2622
        fd = socket(PF_INET, SOCK_STREAM, 0);
2623
        
2624
    if (fd < 0) 
2625
        goto fail;
2626

    
2627
    if (!is_waitconnect)
2628
        socket_set_nonblock(fd);
2629

    
2630
    s->connected = 0;
2631
    s->fd = -1;
2632
    s->listen_fd = -1;
2633
    s->is_unix = is_unix;
2634
    s->do_nodelay = do_nodelay && !is_unix;
2635

    
2636
    chr->opaque = s;
2637
    chr->chr_write = tcp_chr_write;
2638
    chr->chr_close = tcp_chr_close;
2639

    
2640
    if (is_listen) {
2641
        /* allow fast reuse */
2642
#ifndef _WIN32
2643
        if (is_unix) {
2644
            char path[109];
2645
            strncpy(path, uaddr.sun_path, 108);
2646
            path[108] = 0;
2647
            unlink(path);
2648
        } else
2649
#endif
2650
        {
2651
            val = 1;
2652
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2653
        }
2654
        
2655
        ret = bind(fd, addr, addrlen);
2656
        if (ret < 0)
2657
            goto fail;
2658

    
2659
        ret = listen(fd, 0);
2660
        if (ret < 0)
2661
            goto fail;
2662

    
2663
        s->listen_fd = fd;
2664
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2665
        if (is_telnet)
2666
            s->do_telnetopt = 1;
2667
    } else {
2668
        for(;;) {
2669
            ret = connect(fd, addr, addrlen);
2670
            if (ret < 0) {
2671
                err = socket_error();
2672
                if (err == EINTR || err == EWOULDBLOCK) {
2673
                } else if (err == EINPROGRESS) {
2674
                    break;
2675
                } else {
2676
                    goto fail;
2677
                }
2678
            } else {
2679
                s->connected = 1;
2680
                break;
2681
            }
2682
        }
2683
        s->fd = fd;
2684
        socket_set_nodelay(fd);
2685
        if (s->connected)
2686
            tcp_chr_connect(chr);
2687
        else
2688
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2689
    }
2690
    
2691
    if (is_listen && is_waitconnect) {
2692
        printf("QEMU waiting for connection on: %s\n", host_str);
2693
        tcp_chr_accept(chr);
2694
        socket_set_nonblock(s->listen_fd);
2695
    }
2696

    
2697
    return chr;
2698
 fail:
2699
    if (fd >= 0)
2700
        closesocket(fd);
2701
    qemu_free(s);
2702
    qemu_free(chr);
2703
    return NULL;
2704
}
2705

    
2706
CharDriverState *qemu_chr_open(const char *filename)
2707
{
2708
    const char *p;
2709

    
2710
    if (!strcmp(filename, "vc")) {
2711
        return text_console_init(&display_state);
2712
    } else if (!strcmp(filename, "null")) {
2713
        return qemu_chr_open_null();
2714
    } else 
2715
    if (strstart(filename, "tcp:", &p)) {
2716
        return qemu_chr_open_tcp(p, 0, 0);
2717
    } else
2718
    if (strstart(filename, "telnet:", &p)) {
2719
        return qemu_chr_open_tcp(p, 1, 0);
2720
    } else
2721
    if (strstart(filename, "udp:", &p)) {
2722
        return qemu_chr_open_udp(p);
2723
    } else
2724
#ifndef _WIN32
2725
    if (strstart(filename, "unix:", &p)) {
2726
        return qemu_chr_open_tcp(p, 0, 1);
2727
    } else if (strstart(filename, "file:", &p)) {
2728
        return qemu_chr_open_file_out(p);
2729
    } else if (strstart(filename, "pipe:", &p)) {
2730
        return qemu_chr_open_pipe(p);
2731
    } else if (!strcmp(filename, "pty")) {
2732
        return qemu_chr_open_pty();
2733
    } else if (!strcmp(filename, "stdio")) {
2734
        return qemu_chr_open_stdio();
2735
    } else 
2736
#endif
2737
#if defined(__linux__)
2738
    if (strstart(filename, "/dev/parport", NULL)) {
2739
        return qemu_chr_open_pp(filename);
2740
    } else 
2741
    if (strstart(filename, "/dev/", NULL)) {
2742
        return qemu_chr_open_tty(filename);
2743
    } else 
2744
#endif
2745
#ifdef _WIN32
2746
    if (strstart(filename, "COM", NULL)) {
2747
        return qemu_chr_open_win(filename);
2748
    } else
2749
    if (strstart(filename, "pipe:", &p)) {
2750
        return qemu_chr_open_win_pipe(p);
2751
    } else
2752
    if (strstart(filename, "file:", &p)) {
2753
        return qemu_chr_open_win_file_out(p);
2754
    }
2755
#endif
2756
    {
2757
        return NULL;
2758
    }
2759
}
2760

    
2761
void qemu_chr_close(CharDriverState *chr)
2762
{
2763
    if (chr->chr_close)
2764
        chr->chr_close(chr);
2765
}
2766

    
2767
/***********************************************************/
2768
/* network device redirectors */
2769

    
2770
void hex_dump(FILE *f, const uint8_t *buf, int size)
2771
{
2772
    int len, i, j, c;
2773

    
2774
    for(i=0;i<size;i+=16) {
2775
        len = size - i;
2776
        if (len > 16)
2777
            len = 16;
2778
        fprintf(f, "%08x ", i);
2779
        for(j=0;j<16;j++) {
2780
            if (j < len)
2781
                fprintf(f, " %02x", buf[i+j]);
2782
            else
2783
                fprintf(f, "   ");
2784
        }
2785
        fprintf(f, " ");
2786
        for(j=0;j<len;j++) {
2787
            c = buf[i+j];
2788
            if (c < ' ' || c > '~')
2789
                c = '.';
2790
            fprintf(f, "%c", c);
2791
        }
2792
        fprintf(f, "\n");
2793
    }
2794
}
2795

    
2796
static int parse_macaddr(uint8_t *macaddr, const char *p)
2797
{
2798
    int i;
2799
    for(i = 0; i < 6; i++) {
2800
        macaddr[i] = strtol(p, (char **)&p, 16);
2801
        if (i == 5) {
2802
            if (*p != '\0') 
2803
                return -1;
2804
        } else {
2805
            if (*p != ':') 
2806
                return -1;
2807
            p++;
2808
        }
2809
    }
2810
    return 0;
2811
}
2812

    
2813
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2814
{
2815
    const char *p, *p1;
2816
    int len;
2817
    p = *pp;
2818
    p1 = strchr(p, sep);
2819
    if (!p1)
2820
        return -1;
2821
    len = p1 - p;
2822
    p1++;
2823
    if (buf_size > 0) {
2824
        if (len > buf_size - 1)
2825
            len = buf_size - 1;
2826
        memcpy(buf, p, len);
2827
        buf[len] = '\0';
2828
    }
2829
    *pp = p1;
2830
    return 0;
2831
}
2832

    
2833
int parse_host_src_port(struct sockaddr_in *haddr,
2834
                        struct sockaddr_in *saddr,
2835
                        const char *input_str)
2836
{
2837
    char *str = strdup(input_str);
2838
    char *host_str = str;
2839
    char *src_str;
2840
    char *ptr;
2841

    
2842
    /*
2843
     * Chop off any extra arguments at the end of the string which
2844
     * would start with a comma, then fill in the src port information
2845
     * if it was provided else use the "any address" and "any port".
2846
     */
2847
    if ((ptr = strchr(str,',')))
2848
        *ptr = '\0';
2849

    
2850
    if ((src_str = strchr(input_str,'@'))) {
2851
        *src_str = '\0';
2852
        src_str++;
2853
    }
2854

    
2855
    if (parse_host_port(haddr, host_str) < 0)
2856
        goto fail;
2857

    
2858
    if (!src_str || *src_str == '\0')
2859
        src_str = ":0";
2860

    
2861
    if (parse_host_port(saddr, src_str) < 0)
2862
        goto fail;
2863

    
2864
    free(str);
2865
    return(0);
2866

    
2867
fail:
2868
    free(str);
2869
    return -1;
2870
}
2871

    
2872
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2873
{
2874
    char buf[512];
2875
    struct hostent *he;
2876
    const char *p, *r;
2877
    int port;
2878

    
2879
    p = str;
2880
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2881
        return -1;
2882
    saddr->sin_family = AF_INET;
2883
    if (buf[0] == '\0') {
2884
        saddr->sin_addr.s_addr = 0;
2885
    } else {
2886
        if (isdigit(buf[0])) {
2887
            if (!inet_aton(buf, &saddr->sin_addr))
2888
                return -1;
2889
        } else {
2890
            if ((he = gethostbyname(buf)) == NULL)
2891
                return - 1;
2892
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2893
        }
2894
    }
2895
    port = strtol(p, (char **)&r, 0);
2896
    if (r == p)
2897
        return -1;
2898
    saddr->sin_port = htons(port);
2899
    return 0;
2900
}
2901

    
2902
#ifndef _WIN32
2903
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2904
{
2905
    const char *p;
2906
    int len;
2907

    
2908
    len = MIN(108, strlen(str));
2909
    p = strchr(str, ',');
2910
    if (p)
2911
        len = MIN(len, p - str);
2912

    
2913
    memset(uaddr, 0, sizeof(*uaddr));
2914

    
2915
    uaddr->sun_family = AF_UNIX;
2916
    memcpy(uaddr->sun_path, str, len);
2917

    
2918
    return 0;
2919
}
2920
#endif
2921

    
2922
/* find or alloc a new VLAN */
2923
VLANState *qemu_find_vlan(int id)
2924
{
2925
    VLANState **pvlan, *vlan;
2926
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2927
        if (vlan->id == id)
2928
            return vlan;
2929
    }
2930
    vlan = qemu_mallocz(sizeof(VLANState));
2931
    if (!vlan)
2932
        return NULL;
2933
    vlan->id = id;
2934
    vlan->next = NULL;
2935
    pvlan = &first_vlan;
2936
    while (*pvlan != NULL)
2937
        pvlan = &(*pvlan)->next;
2938
    *pvlan = vlan;
2939
    return vlan;
2940
}
2941

    
2942
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2943
                                      IOReadHandler *fd_read,
2944
                                      IOCanRWHandler *fd_can_read,
2945
                                      void *opaque)
2946
{
2947
    VLANClientState *vc, **pvc;
2948
    vc = qemu_mallocz(sizeof(VLANClientState));
2949
    if (!vc)
2950
        return NULL;
2951
    vc->fd_read = fd_read;
2952
    vc->fd_can_read = fd_can_read;
2953
    vc->opaque = opaque;
2954
    vc->vlan = vlan;
2955

    
2956
    vc->next = NULL;
2957
    pvc = &vlan->first_client;
2958
    while (*pvc != NULL)
2959
        pvc = &(*pvc)->next;
2960
    *pvc = vc;
2961
    return vc;
2962
}
2963

    
2964
int qemu_can_send_packet(VLANClientState *vc1)
2965
{
2966
    VLANState *vlan = vc1->vlan;
2967
    VLANClientState *vc;
2968

    
2969
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2970
        if (vc != vc1) {
2971
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2972
                return 0;
2973
        }
2974
    }
2975
    return 1;
2976
}
2977

    
2978
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2979
{
2980
    VLANState *vlan = vc1->vlan;
2981
    VLANClientState *vc;
2982

    
2983
#if 0
2984
    printf("vlan %d send:\n", vlan->id);
2985
    hex_dump(stdout, buf, size);
2986
#endif
2987
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2988
        if (vc != vc1) {
2989
            vc->fd_read(vc->opaque, buf, size);
2990
        }
2991
    }
2992
}
2993

    
2994
#if defined(CONFIG_SLIRP)
2995

    
2996
/* slirp network adapter */
2997

    
2998
static int slirp_inited;
2999
static VLANClientState *slirp_vc;
3000

    
3001
int slirp_can_output(void)
3002
{
3003
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3004
}
3005

    
3006
void slirp_output(const uint8_t *pkt, int pkt_len)
3007
{
3008
#if 0
3009
    printf("slirp output:\n");
3010
    hex_dump(stdout, pkt, pkt_len);
3011
#endif
3012
    if (!slirp_vc)
3013
        return;
3014
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3015
}
3016

    
3017
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3018
{
3019
#if 0
3020
    printf("slirp input:\n");
3021
    hex_dump(stdout, buf, size);
3022
#endif
3023
    slirp_input(buf, size);
3024
}
3025

    
3026
static int net_slirp_init(VLANState *vlan)
3027
{
3028
    if (!slirp_inited) {
3029
        slirp_inited = 1;
3030
        slirp_init();
3031
    }
3032
    slirp_vc = qemu_new_vlan_client(vlan, 
3033
                                    slirp_receive, NULL, NULL);
3034
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3035
    return 0;
3036
}
3037

    
3038
static void net_slirp_redir(const char *redir_str)
3039
{
3040
    int is_udp;
3041
    char buf[256], *r;
3042
    const char *p;
3043
    struct in_addr guest_addr;
3044
    int host_port, guest_port;
3045
    
3046
    if (!slirp_inited) {
3047
        slirp_inited = 1;
3048
        slirp_init();
3049
    }
3050

    
3051
    p = redir_str;
3052
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3053
        goto fail;
3054
    if (!strcmp(buf, "tcp")) {
3055
        is_udp = 0;
3056
    } else if (!strcmp(buf, "udp")) {
3057
        is_udp = 1;
3058
    } else {
3059
        goto fail;
3060
    }
3061

    
3062
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3063
        goto fail;
3064
    host_port = strtol(buf, &r, 0);
3065
    if (r == buf)
3066
        goto fail;
3067

    
3068
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3069
        goto fail;
3070
    if (buf[0] == '\0') {
3071
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3072
    }
3073
    if (!inet_aton(buf, &guest_addr))
3074
        goto fail;
3075
    
3076
    guest_port = strtol(p, &r, 0);
3077
    if (r == p)
3078
        goto fail;
3079
    
3080
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3081
        fprintf(stderr, "qemu: could not set up redirection\n");
3082
        exit(1);
3083
    }
3084
    return;
3085
 fail:
3086
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3087
    exit(1);
3088
}
3089
    
3090
#ifndef _WIN32
3091

    
3092
char smb_dir[1024];
3093

    
3094
static void smb_exit(void)
3095
{
3096
    DIR *d;
3097
    struct dirent *de;
3098
    char filename[1024];
3099

    
3100
    /* erase all the files in the directory */
3101
    d = opendir(smb_dir);
3102
    for(;;) {
3103
        de = readdir(d);
3104
        if (!de)
3105
            break;
3106
        if (strcmp(de->d_name, ".") != 0 &&
3107
            strcmp(de->d_name, "..") != 0) {
3108
            snprintf(filename, sizeof(filename), "%s/%s", 
3109
                     smb_dir, de->d_name);
3110
            unlink(filename);
3111
        }
3112
    }
3113
    closedir(d);
3114
    rmdir(smb_dir);
3115
}
3116

    
3117
/* automatic user mode samba server configuration */
3118
void net_slirp_smb(const char *exported_dir)
3119
{
3120
    char smb_conf[1024];
3121
    char smb_cmdline[1024];
3122
    FILE *f;
3123

    
3124
    if (!slirp_inited) {
3125
        slirp_inited = 1;
3126
        slirp_init();
3127
    }
3128

    
3129
    /* XXX: better tmp dir construction */
3130
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3131
    if (mkdir(smb_dir, 0700) < 0) {
3132
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3133
        exit(1);
3134
    }
3135
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3136
    
3137
    f = fopen(smb_conf, "w");
3138
    if (!f) {
3139
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3140
        exit(1);
3141
    }
3142
    fprintf(f, 
3143
            "[global]\n"
3144
            "private dir=%s\n"
3145
            "smb ports=0\n"
3146
            "socket address=127.0.0.1\n"
3147
            "pid directory=%s\n"
3148
            "lock directory=%s\n"
3149
            "log file=%s/log.smbd\n"
3150
            "smb passwd file=%s/smbpasswd\n"
3151
            "security = share\n"
3152
            "[qemu]\n"
3153
            "path=%s\n"
3154
            "read only=no\n"
3155
            "guest ok=yes\n",
3156
            smb_dir,
3157
            smb_dir,
3158
            smb_dir,
3159
            smb_dir,
3160
            smb_dir,
3161
            exported_dir
3162
            );
3163
    fclose(f);
3164
    atexit(smb_exit);
3165

    
3166
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3167
             SMBD_COMMAND, smb_conf);
3168
    
3169
    slirp_add_exec(0, smb_cmdline, 4, 139);
3170
}
3171

    
3172
#endif /* !defined(_WIN32) */
3173

    
3174
#endif /* CONFIG_SLIRP */
3175

    
3176
#if !defined(_WIN32)
3177

    
3178
typedef struct TAPState {
3179
    VLANClientState *vc;
3180
    int fd;
3181
} TAPState;
3182

    
3183
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3184
{
3185
    TAPState *s = opaque;
3186
    int ret;
3187
    for(;;) {
3188
        ret = write(s->fd, buf, size);
3189
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3190
        } else {
3191
            break;
3192
        }
3193
    }
3194
}
3195

    
3196
static void tap_send(void *opaque)
3197
{
3198
    TAPState *s = opaque;
3199
    uint8_t buf[4096];
3200
    int size;
3201

    
3202
    size = read(s->fd, buf, sizeof(buf));
3203
    if (size > 0) {
3204
        qemu_send_packet(s->vc, buf, size);
3205
    }
3206
}
3207

    
3208
/* fd support */
3209

    
3210
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3211
{
3212
    TAPState *s;
3213

    
3214
    s = qemu_mallocz(sizeof(TAPState));
3215
    if (!s)
3216
        return NULL;
3217
    s->fd = fd;
3218
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3219
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3220
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3221
    return s;
3222
}
3223

    
3224
#ifdef _BSD
3225
static int tap_open(char *ifname, int ifname_size)
3226
{
3227
    int fd;
3228
    char *dev;
3229
    struct stat s;
3230

    
3231
    fd = open("/dev/tap", O_RDWR);
3232
    if (fd < 0) {
3233
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3234
        return -1;
3235
    }
3236

    
3237
    fstat(fd, &s);
3238
    dev = devname(s.st_rdev, S_IFCHR);
3239
    pstrcpy(ifname, ifname_size, dev);
3240

    
3241
    fcntl(fd, F_SETFL, O_NONBLOCK);
3242
    return fd;
3243
}
3244
#elif defined(__sun__)
3245
static int tap_open(char *ifname, int ifname_size)
3246
{
3247
    fprintf(stderr, "warning: tap_open not yet implemented\n");
3248
    return -1;
3249
}
3250
#else
3251
static int tap_open(char *ifname, int ifname_size)
3252
{
3253
    struct ifreq ifr;
3254
    int fd, ret;
3255
    
3256
    fd = open("/dev/net/tun", O_RDWR);
3257
    if (fd < 0) {
3258
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3259
        return -1;
3260
    }
3261
    memset(&ifr, 0, sizeof(ifr));
3262
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3263
    if (ifname[0] != '\0')
3264
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3265
    else
3266
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3267
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3268
    if (ret != 0) {
3269
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3270
        close(fd);
3271
        return -1;
3272
    }
3273
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3274
    fcntl(fd, F_SETFL, O_NONBLOCK);
3275
    return fd;
3276
}
3277
#endif
3278

    
3279
static int net_tap_init(VLANState *vlan, const char *ifname1,
3280
                        const char *setup_script)
3281
{
3282
    TAPState *s;
3283
    int pid, status, fd;
3284
    char *args[3];
3285
    char **parg;
3286
    char ifname[128];
3287

    
3288
    if (ifname1 != NULL)
3289
        pstrcpy(ifname, sizeof(ifname), ifname1);
3290
    else
3291
        ifname[0] = '\0';
3292
    fd = tap_open(ifname, sizeof(ifname));
3293
    if (fd < 0)
3294
        return -1;
3295

    
3296
    if (!setup_script || !strcmp(setup_script, "no"))
3297
        setup_script = "";
3298
    if (setup_script[0] != '\0') {
3299
        /* try to launch network init script */
3300
        pid = fork();
3301
        if (pid >= 0) {
3302
            if (pid == 0) {
3303
                parg = args;
3304
                *parg++ = (char *)setup_script;
3305
                *parg++ = ifname;
3306
                *parg++ = NULL;
3307
                execv(setup_script, args);
3308
                _exit(1);
3309
            }
3310
            while (waitpid(pid, &status, 0) != pid);
3311
            if (!WIFEXITED(status) ||
3312
                WEXITSTATUS(status) != 0) {
3313
                fprintf(stderr, "%s: could not launch network script\n",
3314
                        setup_script);
3315
                return -1;
3316
            }
3317
        }
3318
    }
3319
    s = net_tap_fd_init(vlan, fd);
3320
    if (!s)
3321
        return -1;
3322
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3323
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3324
    return 0;
3325
}
3326

    
3327
#endif /* !_WIN32 */
3328

    
3329
/* network connection */
3330
typedef struct NetSocketState {
3331
    VLANClientState *vc;
3332
    int fd;
3333
    int state; /* 0 = getting length, 1 = getting data */
3334
    int index;
3335
    int packet_len;
3336
    uint8_t buf[4096];
3337
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3338
} NetSocketState;
3339

    
3340
typedef struct NetSocketListenState {
3341
    VLANState *vlan;
3342
    int fd;
3343
} NetSocketListenState;
3344

    
3345
/* XXX: we consider we can send the whole packet without blocking */
3346
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3347
{
3348
    NetSocketState *s = opaque;
3349
    uint32_t len;
3350
    len = htonl(size);
3351

    
3352
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3353
    send_all(s->fd, buf, size);
3354
}
3355

    
3356
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3357
{
3358
    NetSocketState *s = opaque;
3359
    sendto(s->fd, buf, size, 0, 
3360
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3361
}
3362

    
3363
static void net_socket_send(void *opaque)
3364
{
3365
    NetSocketState *s = opaque;
3366
    int l, size, err;
3367
    uint8_t buf1[4096];
3368
    const uint8_t *buf;
3369

    
3370
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3371
    if (size < 0) {
3372
        err = socket_error();
3373
        if (err != EWOULDBLOCK) 
3374
            goto eoc;
3375
    } else if (size == 0) {
3376
        /* end of connection */
3377
    eoc:
3378
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3379
        closesocket(s->fd);
3380
        return;
3381
    }
3382
    buf = buf1;
3383
    while (size > 0) {
3384
        /* reassemble a packet from the network */
3385
        switch(s->state) {
3386
        case 0:
3387
            l = 4 - s->index;
3388
            if (l > size)
3389
                l = size;
3390
            memcpy(s->buf + s->index, buf, l);
3391
            buf += l;
3392
            size -= l;
3393
            s->index += l;
3394
            if (s->index == 4) {
3395
                /* got length */
3396
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3397
                s->index = 0;
3398
                s->state = 1;
3399
            }
3400
            break;
3401
        case 1:
3402
            l = s->packet_len - s->index;
3403
            if (l > size)
3404
                l = size;
3405
            memcpy(s->buf + s->index, buf, l);
3406
            s->index += l;
3407
            buf += l;
3408
            size -= l;
3409
            if (s->index >= s->packet_len) {
3410
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3411
                s->index = 0;
3412
                s->state = 0;
3413
            }
3414
            break;
3415
        }
3416
    }
3417
}
3418

    
3419
static void net_socket_send_dgram(void *opaque)
3420
{
3421
    NetSocketState *s = opaque;
3422
    int size;
3423

    
3424
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3425
    if (size < 0) 
3426
        return;
3427
    if (size == 0) {
3428
        /* end of connection */
3429
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3430
        return;
3431
    }
3432
    qemu_send_packet(s->vc, s->buf, size);
3433
}
3434

    
3435
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3436
{
3437
    struct ip_mreq imr;
3438
    int fd;
3439
    int val, ret;
3440
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3441
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3442
                inet_ntoa(mcastaddr->sin_addr), 
3443
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3444
        return -1;
3445

    
3446
    }
3447
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3448
    if (fd < 0) {
3449
        perror("socket(PF_INET, SOCK_DGRAM)");
3450
        return -1;
3451
    }
3452

    
3453
    val = 1;
3454
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3455
                   (const char *)&val, sizeof(val));
3456
    if (ret < 0) {
3457
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3458
        goto fail;
3459
    }
3460

    
3461
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3462
    if (ret < 0) {
3463
        perror("bind");
3464
        goto fail;
3465
    }
3466
    
3467
    /* Add host to multicast group */
3468
    imr.imr_multiaddr = mcastaddr->sin_addr;
3469
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3470

    
3471
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3472
                     (const char *)&imr, sizeof(struct ip_mreq));
3473
    if (ret < 0) {
3474
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3475
        goto fail;
3476
    }
3477

    
3478
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3479
    val = 1;
3480
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3481
                   (const char *)&val, sizeof(val));
3482
    if (ret < 0) {
3483
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3484
        goto fail;
3485
    }
3486

    
3487
    socket_set_nonblock(fd);
3488
    return fd;
3489
fail:
3490
    if (fd >= 0) 
3491
        closesocket(fd);
3492
    return -1;
3493
}
3494

    
3495
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3496
                                          int is_connected)
3497
{
3498
    struct sockaddr_in saddr;
3499
    int newfd;
3500
    socklen_t saddr_len;
3501
    NetSocketState *s;
3502

    
3503
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3504
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3505
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3506
     */
3507

    
3508
    if (is_connected) {
3509
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3510
            /* must be bound */
3511
            if (saddr.sin_addr.s_addr==0) {
3512
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3513
                        fd);
3514
                return NULL;
3515
            }
3516
            /* clone dgram socket */
3517
            newfd = net_socket_mcast_create(&saddr);
3518
            if (newfd < 0) {
3519
                /* error already reported by net_socket_mcast_create() */
3520
                close(fd);
3521
                return NULL;
3522
            }
3523
            /* clone newfd to fd, close newfd */
3524
            dup2(newfd, fd);
3525
            close(newfd);
3526
        
3527
        } else {
3528
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3529
                    fd, strerror(errno));
3530
            return NULL;
3531
        }
3532
    }
3533

    
3534
    s = qemu_mallocz(sizeof(NetSocketState));
3535
    if (!s)
3536
        return NULL;
3537
    s->fd = fd;
3538

    
3539
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3540
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3541

    
3542
    /* mcast: save bound address as dst */
3543
    if (is_connected) s->dgram_dst=saddr;
3544

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

    
3552
static void net_socket_connect(void *opaque)
3553
{
3554
    NetSocketState *s = opaque;
3555
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3556
}
3557

    
3558
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3559
                                          int is_connected)
3560
{
3561
    NetSocketState *s;
3562
    s = qemu_mallocz(sizeof(NetSocketState));
3563
    if (!s)
3564
        return NULL;
3565
    s->fd = fd;
3566
    s->vc = qemu_new_vlan_client(vlan, 
3567
                                 net_socket_receive, NULL, s);
3568
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3569
             "socket: fd=%d", fd);
3570
    if (is_connected) {
3571
        net_socket_connect(s);
3572
    } else {
3573
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3574
    }
3575
    return s;
3576
}
3577

    
3578
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3579
                                          int is_connected)
3580
{
3581
    int so_type=-1, optlen=sizeof(so_type);
3582

    
3583
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3584
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3585
        return NULL;
3586
    }
3587
    switch(so_type) {
3588
    case SOCK_DGRAM:
3589
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3590
    case SOCK_STREAM:
3591
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3592
    default:
3593
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3594
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3595
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3596
    }
3597
    return NULL;
3598
}
3599

    
3600
static void net_socket_accept(void *opaque)
3601
{
3602
    NetSocketListenState *s = opaque;    
3603
    NetSocketState *s1;
3604
    struct sockaddr_in saddr;
3605
    socklen_t len;
3606
    int fd;
3607

    
3608
    for(;;) {
3609
        len = sizeof(saddr);
3610
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3611
        if (fd < 0 && errno != EINTR) {
3612
            return;
3613
        } else if (fd >= 0) {
3614
            break;
3615
        }
3616
    }
3617
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3618
    if (!s1) {
3619
        closesocket(fd);
3620
    } else {
3621
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3622
                 "socket: connection from %s:%d", 
3623
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3624
    }
3625
}
3626

    
3627
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3628
{
3629
    NetSocketListenState *s;
3630
    int fd, val, ret;
3631
    struct sockaddr_in saddr;
3632

    
3633
    if (parse_host_port(&saddr, host_str) < 0)
3634
        return -1;
3635
    
3636
    s = qemu_mallocz(sizeof(NetSocketListenState));
3637
    if (!s)
3638
        return -1;
3639

    
3640
    fd = socket(PF_INET, SOCK_STREAM, 0);
3641
    if (fd < 0) {
3642
        perror("socket");
3643
        return -1;
3644
    }
3645
    socket_set_nonblock(fd);
3646

    
3647
    /* allow fast reuse */
3648
    val = 1;
3649
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3650
    
3651
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3652
    if (ret < 0) {
3653
        perror("bind");
3654
        return -1;
3655
    }
3656
    ret = listen(fd, 0);
3657
    if (ret < 0) {
3658
        perror("listen");
3659
        return -1;
3660
    }
3661
    s->vlan = vlan;
3662
    s->fd = fd;
3663
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3664
    return 0;
3665
}
3666

    
3667
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3668
{
3669
    NetSocketState *s;
3670
    int fd, connected, ret, err;
3671
    struct sockaddr_in saddr;
3672

    
3673
    if (parse_host_port(&saddr, host_str) < 0)
3674
        return -1;
3675

    
3676
    fd = socket(PF_INET, SOCK_STREAM, 0);
3677
    if (fd < 0) {
3678
        perror("socket");
3679
        return -1;
3680
    }
3681
    socket_set_nonblock(fd);
3682

    
3683
    connected = 0;
3684
    for(;;) {
3685
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3686
        if (ret < 0) {
3687
            err = socket_error();
3688
            if (err == EINTR || err == EWOULDBLOCK) {
3689
            } else if (err == EINPROGRESS) {
3690
                break;
3691
            } else {
3692
                perror("connect");
3693
                closesocket(fd);
3694
                return -1;
3695
            }
3696
        } else {
3697
            connected = 1;
3698
            break;
3699
        }
3700
    }
3701
    s = net_socket_fd_init(vlan, fd, connected);
3702
    if (!s)
3703
        return -1;
3704
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3705
             "socket: connect to %s:%d", 
3706
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3707
    return 0;
3708
}
3709

    
3710
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3711
{
3712
    NetSocketState *s;
3713
    int fd;
3714
    struct sockaddr_in saddr;
3715

    
3716
    if (parse_host_port(&saddr, host_str) < 0)
3717
        return -1;
3718

    
3719

    
3720
    fd = net_socket_mcast_create(&saddr);
3721
    if (fd < 0)
3722
        return -1;
3723

    
3724
    s = net_socket_fd_init(vlan, fd, 0);
3725
    if (!s)
3726
        return -1;
3727

    
3728
    s->dgram_dst = saddr;
3729
    
3730
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3731
             "socket: mcast=%s:%d", 
3732
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3733
    return 0;
3734

    
3735
}
3736

    
3737
static int get_param_value(char *buf, int buf_size,
3738
                           const char *tag, const char *str)
3739
{
3740
    const char *p;
3741
    char *q;
3742
    char option[128];
3743

    
3744
    p = str;
3745
    for(;;) {
3746
        q = option;
3747
        while (*p != '\0' && *p != '=') {
3748
            if ((q - option) < sizeof(option) - 1)
3749
                *q++ = *p;
3750
            p++;
3751
        }
3752
        *q = '\0';
3753
        if (*p != '=')
3754
            break;
3755
        p++;
3756
        if (!strcmp(tag, option)) {
3757
            q = buf;
3758
            while (*p != '\0' && *p != ',') {
3759
                if ((q - buf) < buf_size - 1)
3760
                    *q++ = *p;
3761
                p++;
3762
            }
3763
            *q = '\0';
3764
            return q - buf;
3765
        } else {
3766
            while (*p != '\0' && *p != ',') {
3767
                p++;
3768
            }
3769
        }
3770
        if (*p != ',')
3771
            break;
3772
        p++;
3773
    }
3774
    return 0;
3775
}
3776

    
3777
static int net_client_init(const char *str)
3778
{
3779
    const char *p;
3780
    char *q;
3781
    char device[64];
3782
    char buf[1024];
3783
    int vlan_id, ret;
3784
    VLANState *vlan;
3785

    
3786
    p = str;
3787
    q = device;
3788
    while (*p != '\0' && *p != ',') {
3789
        if ((q - device) < sizeof(device) - 1)
3790
            *q++ = *p;
3791
        p++;
3792
    }
3793
    *q = '\0';
3794
    if (*p == ',')
3795
        p++;
3796
    vlan_id = 0;
3797
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3798
        vlan_id = strtol(buf, NULL, 0);
3799
    }
3800
    vlan = qemu_find_vlan(vlan_id);
3801
    if (!vlan) {
3802
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3803
        return -1;
3804
    }
3805
    if (!strcmp(device, "nic")) {
3806
        NICInfo *nd;
3807
        uint8_t *macaddr;
3808

    
3809
        if (nb_nics >= MAX_NICS) {
3810
            fprintf(stderr, "Too Many NICs\n");
3811
            return -1;
3812
        }
3813
        nd = &nd_table[nb_nics];
3814
        macaddr = nd->macaddr;
3815
        macaddr[0] = 0x52;
3816
        macaddr[1] = 0x54;
3817
        macaddr[2] = 0x00;
3818
        macaddr[3] = 0x12;
3819
        macaddr[4] = 0x34;
3820
        macaddr[5] = 0x56 + nb_nics;
3821

    
3822
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3823
            if (parse_macaddr(macaddr, buf) < 0) {
3824
                fprintf(stderr, "invalid syntax for ethernet address\n");
3825
                return -1;
3826
            }
3827
        }
3828
        if (get_param_value(buf, sizeof(buf), "model", p)) {
3829
            nd->model = strdup(buf);
3830
        }
3831
        nd->vlan = vlan;
3832
        nb_nics++;
3833
        ret = 0;
3834
    } else
3835
    if (!strcmp(device, "none")) {
3836
        /* does nothing. It is needed to signal that no network cards
3837
           are wanted */
3838
        ret = 0;
3839
    } else
3840
#ifdef CONFIG_SLIRP
3841
    if (!strcmp(device, "user")) {
3842
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3843
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3844
        }
3845
        ret = net_slirp_init(vlan);
3846
    } else
3847
#endif
3848
#ifdef _WIN32
3849
    if (!strcmp(device, "tap")) {
3850
        char ifname[64];
3851
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3852
            fprintf(stderr, "tap: no interface name\n");
3853
            return -1;
3854
        }
3855
        ret = tap_win32_init(vlan, ifname);
3856
    } else
3857
#else
3858
    if (!strcmp(device, "tap")) {
3859
        char ifname[64];
3860
        char setup_script[1024];
3861
        int fd;
3862
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3863
            fd = strtol(buf, NULL, 0);
3864
            ret = -1;
3865
            if (net_tap_fd_init(vlan, fd))
3866
                ret = 0;
3867
        } else {
3868
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3869
                ifname[0] = '\0';
3870
            }
3871
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3872
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3873
            }
3874
            ret = net_tap_init(vlan, ifname, setup_script);
3875
        }
3876
    } else
3877
#endif
3878
    if (!strcmp(device, "socket")) {
3879
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3880
            int fd;
3881
            fd = strtol(buf, NULL, 0);
3882
            ret = -1;
3883
            if (net_socket_fd_init(vlan, fd, 1))
3884
                ret = 0;
3885
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3886
            ret = net_socket_listen_init(vlan, buf);
3887
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3888
            ret = net_socket_connect_init(vlan, buf);
3889
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3890
            ret = net_socket_mcast_init(vlan, buf);
3891
        } else {
3892
            fprintf(stderr, "Unknown socket options: %s\n", p);
3893
            return -1;
3894
        }
3895
    } else
3896
    {
3897
        fprintf(stderr, "Unknown network device: %s\n", device);
3898
        return -1;
3899
    }
3900
    if (ret < 0) {
3901
        fprintf(stderr, "Could not initialize device '%s'\n", device);
3902
    }
3903
    
3904
    return ret;
3905
}
3906

    
3907
void do_info_network(void)
3908
{
3909
    VLANState *vlan;
3910
    VLANClientState *vc;
3911

    
3912
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3913
        term_printf("VLAN %d devices:\n", vlan->id);
3914
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3915
            term_printf("  %s\n", vc->info_str);
3916
    }
3917
}
3918

    
3919
/***********************************************************/
3920
/* USB devices */
3921

    
3922
static USBPort *used_usb_ports;
3923
static USBPort *free_usb_ports;
3924

    
3925
/* ??? Maybe change this to register a hub to keep track of the topology.  */
3926
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3927
                            usb_attachfn attach)
3928
{
3929
    port->opaque = opaque;
3930
    port->index = index;
3931
    port->attach = attach;
3932
    port->next = free_usb_ports;
3933
    free_usb_ports = port;
3934
}
3935

    
3936
static int usb_device_add(const char *devname)
3937
{
3938
    const char *p;
3939
    USBDevice *dev;
3940
    USBPort *port;
3941

    
3942
    if (!free_usb_ports)
3943
        return -1;
3944

    
3945
    if (strstart(devname, "host:", &p)) {
3946
        dev = usb_host_device_open(p);
3947
    } else if (!strcmp(devname, "mouse")) {
3948
        dev = usb_mouse_init();
3949
    } else if (!strcmp(devname, "tablet")) {
3950
        dev = usb_tablet_init();
3951
    } else if (strstart(devname, "disk:", &p)) {
3952
        dev = usb_msd_init(p);
3953
    } else {
3954
        return -1;
3955
    }
3956
    if (!dev)
3957
        return -1;
3958

    
3959
    /* Find a USB port to add the device to.  */
3960
    port = free_usb_ports;
3961
    if (!port->next) {
3962
        USBDevice *hub;
3963

    
3964
        /* Create a new hub and chain it on.  */
3965
        free_usb_ports = NULL;
3966
        port->next = used_usb_ports;
3967
        used_usb_ports = port;
3968

    
3969
        hub = usb_hub_init(VM_USB_HUB_SIZE);
3970
        usb_attach(port, hub);
3971
        port = free_usb_ports;
3972
    }
3973

    
3974
    free_usb_ports = port->next;
3975
    port->next = used_usb_ports;
3976
    used_usb_ports = port;
3977
    usb_attach(port, dev);
3978
    return 0;
3979
}
3980

    
3981
static int usb_device_del(const char *devname)
3982
{
3983
    USBPort *port;
3984
    USBPort **lastp;
3985
    USBDevice *dev;
3986
    int bus_num, addr;
3987
    const char *p;
3988

    
3989
    if (!used_usb_ports)
3990
        return -1;
3991

    
3992
    p = strchr(devname, '.');
3993
    if (!p) 
3994
        return -1;
3995
    bus_num = strtoul(devname, NULL, 0);
3996
    addr = strtoul(p + 1, NULL, 0);
3997
    if (bus_num != 0)
3998
        return -1;
3999

    
4000
    lastp = &used_usb_ports;
4001
    port = used_usb_ports;
4002
    while (port && port->dev->addr != addr) {
4003
        lastp = &port->next;
4004
        port = port->next;
4005
    }
4006

    
4007
    if (!port)
4008
        return -1;
4009

    
4010
    dev = port->dev;
4011
    *lastp = port->next;
4012
    usb_attach(port, NULL);
4013
    dev->handle_destroy(dev);
4014
    port->next = free_usb_ports;
4015
    free_usb_ports = port;
4016
    return 0;
4017
}
4018

    
4019
void do_usb_add(const char *devname)
4020
{
4021
    int ret;
4022
    ret = usb_device_add(devname);
4023
    if (ret < 0) 
4024
        term_printf("Could not add USB device '%s'\n", devname);
4025
}
4026

    
4027
void do_usb_del(const char *devname)
4028
{
4029
    int ret;
4030
    ret = usb_device_del(devname);
4031
    if (ret < 0) 
4032
        term_printf("Could not remove USB device '%s'\n", devname);
4033
}
4034

    
4035
void usb_info(void)
4036
{
4037
    USBDevice *dev;
4038
    USBPort *port;
4039
    const char *speed_str;
4040

    
4041
    if (!usb_enabled) {
4042
        term_printf("USB support not enabled\n");
4043
        return;
4044
    }
4045

    
4046
    for (port = used_usb_ports; port; port = port->next) {
4047
        dev = port->dev;
4048
        if (!dev)
4049
            continue;
4050
        switch(dev->speed) {
4051
        case USB_SPEED_LOW: 
4052
            speed_str = "1.5"; 
4053
            break;
4054
        case USB_SPEED_FULL: 
4055
            speed_str = "12"; 
4056
            break;
4057
        case USB_SPEED_HIGH: 
4058
            speed_str = "480"; 
4059
            break;
4060
        default:
4061
            speed_str = "?"; 
4062
            break;
4063
        }
4064
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4065
                    0, dev->addr, speed_str, dev->devname);
4066
    }
4067
}
4068

    
4069
/***********************************************************/
4070
/* pid file */
4071

    
4072
static char *pid_filename;
4073

    
4074
/* Remove PID file. Called on normal exit */
4075

    
4076
static void remove_pidfile(void) 
4077
{
4078
    unlink (pid_filename);
4079
}
4080

    
4081
static void create_pidfile(const char *filename)
4082
{
4083
    struct stat pidstat;
4084
    FILE *f;
4085

    
4086
    /* Try to write our PID to the named file */
4087
    if (stat(filename, &pidstat) < 0) {
4088
        if (errno == ENOENT) {
4089
            if ((f = fopen (filename, "w")) == NULL) {
4090
                perror("Opening pidfile");
4091
                exit(1);
4092
            }
4093
            fprintf(f, "%d\n", getpid());
4094
            fclose(f);
4095
            pid_filename = qemu_strdup(filename);
4096
            if (!pid_filename) {
4097
                fprintf(stderr, "Could not save PID filename");
4098
                exit(1);
4099
            }
4100
            atexit(remove_pidfile);
4101
        }
4102
    } else {
4103
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
4104
                filename);
4105
        exit(1);
4106
    }
4107
}
4108

    
4109
/***********************************************************/
4110
/* dumb display */
4111

    
4112
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4113
{
4114
}
4115

    
4116
static void dumb_resize(DisplayState *ds, int w, int h)
4117
{
4118
}
4119

    
4120
static void dumb_refresh(DisplayState *ds)
4121
{
4122
    vga_hw_update();
4123
}
4124

    
4125
void dumb_display_init(DisplayState *ds)
4126
{
4127
    ds->data = NULL;
4128
    ds->linesize = 0;
4129
    ds->depth = 0;
4130
    ds->dpy_update = dumb_update;
4131
    ds->dpy_resize = dumb_resize;
4132
    ds->dpy_refresh = dumb_refresh;
4133
}
4134

    
4135
/***********************************************************/
4136
/* I/O handling */
4137

    
4138
#define MAX_IO_HANDLERS 64
4139

    
4140
typedef struct IOHandlerRecord {
4141
    int fd;
4142
    IOCanRWHandler *fd_read_poll;
4143
    IOHandler *fd_read;
4144
    IOHandler *fd_write;
4145
    void *opaque;
4146
    /* temporary data */
4147
    struct pollfd *ufd;
4148
    struct IOHandlerRecord *next;
4149
} IOHandlerRecord;
4150

    
4151
static IOHandlerRecord *first_io_handler;
4152

    
4153
/* XXX: fd_read_poll should be suppressed, but an API change is
4154
   necessary in the character devices to suppress fd_can_read(). */
4155
int qemu_set_fd_handler2(int fd, 
4156
                         IOCanRWHandler *fd_read_poll, 
4157
                         IOHandler *fd_read, 
4158
                         IOHandler *fd_write, 
4159
                         void *opaque)
4160
{
4161
    IOHandlerRecord **pioh, *ioh;
4162

    
4163
    if (!fd_read && !fd_write) {
4164
        pioh = &first_io_handler;
4165
        for(;;) {
4166
            ioh = *pioh;
4167
            if (ioh == NULL)
4168
                break;
4169
            if (ioh->fd == fd) {
4170
                *pioh = ioh->next;
4171
                qemu_free(ioh);
4172
                break;
4173
            }
4174
            pioh = &ioh->next;
4175
        }
4176
    } else {
4177
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4178
            if (ioh->fd == fd)
4179
                goto found;
4180
        }
4181
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4182
        if (!ioh)
4183
            return -1;
4184
        ioh->next = first_io_handler;
4185
        first_io_handler = ioh;
4186
    found:
4187
        ioh->fd = fd;
4188
        ioh->fd_read_poll = fd_read_poll;
4189
        ioh->fd_read = fd_read;
4190
        ioh->fd_write = fd_write;
4191
        ioh->opaque = opaque;
4192
    }
4193
    return 0;
4194
}
4195

    
4196
int qemu_set_fd_handler(int fd, 
4197
                        IOHandler *fd_read, 
4198
                        IOHandler *fd_write, 
4199
                        void *opaque)
4200
{
4201
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4202
}
4203

    
4204
/***********************************************************/
4205
/* Polling handling */
4206

    
4207
typedef struct PollingEntry {
4208
    PollingFunc *func;
4209
    void *opaque;
4210
    struct PollingEntry *next;
4211
} PollingEntry;
4212

    
4213
static PollingEntry *first_polling_entry;
4214

    
4215
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4216
{
4217
    PollingEntry **ppe, *pe;
4218
    pe = qemu_mallocz(sizeof(PollingEntry));
4219
    if (!pe)
4220
        return -1;
4221
    pe->func = func;
4222
    pe->opaque = opaque;
4223
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4224
    *ppe = pe;
4225
    return 0;
4226
}
4227

    
4228
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4229
{
4230
    PollingEntry **ppe, *pe;
4231
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4232
        pe = *ppe;
4233
        if (pe->func == func && pe->opaque == opaque) {
4234
            *ppe = pe->next;
4235
            qemu_free(pe);
4236
            break;
4237
        }
4238
    }
4239
}
4240

    
4241
#ifdef _WIN32
4242
/***********************************************************/
4243
/* Wait objects support */
4244
typedef struct WaitObjects {
4245
    int num;
4246
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4247
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4248
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4249
} WaitObjects;
4250

    
4251
static WaitObjects wait_objects = {0};
4252
    
4253
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4254
{
4255
    WaitObjects *w = &wait_objects;
4256

    
4257
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4258
        return -1;
4259
    w->events[w->num] = handle;
4260
    w->func[w->num] = func;
4261
    w->opaque[w->num] = opaque;
4262
    w->num++;
4263
    return 0;
4264
}
4265

    
4266
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4267
{
4268
    int i, found;
4269
    WaitObjects *w = &wait_objects;
4270

    
4271
    found = 0;
4272
    for (i = 0; i < w->num; i++) {
4273
        if (w->events[i] == handle)
4274
            found = 1;
4275
        if (found) {
4276
            w->events[i] = w->events[i + 1];
4277
            w->func[i] = w->func[i + 1];
4278
            w->opaque[i] = w->opaque[i + 1];
4279
        }            
4280
    }
4281
    if (found)
4282
        w->num--;
4283
}
4284
#endif
4285

    
4286
/***********************************************************/
4287
/* savevm/loadvm support */
4288

    
4289
#define IO_BUF_SIZE 32768
4290

    
4291
struct QEMUFile {
4292
    FILE *outfile;
4293
    BlockDriverState *bs;
4294
    int is_file;
4295
    int is_writable;
4296
    int64_t base_offset;
4297
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4298
                           when reading */
4299
    int buf_index;
4300
    int buf_size; /* 0 when writing */
4301
    uint8_t buf[IO_BUF_SIZE];
4302
};
4303

    
4304
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4305
{
4306
    QEMUFile *f;
4307

    
4308
    f = qemu_mallocz(sizeof(QEMUFile));
4309
    if (!f)
4310
        return NULL;
4311
    if (!strcmp(mode, "wb")) {
4312
        f->is_writable = 1;
4313
    } else if (!strcmp(mode, "rb")) {
4314
        f->is_writable = 0;
4315
    } else {
4316
        goto fail;
4317
    }
4318
    f->outfile = fopen(filename, mode);
4319
    if (!f->outfile)
4320
        goto fail;
4321
    f->is_file = 1;
4322
    return f;
4323
 fail:
4324
    if (f->outfile)
4325
        fclose(f->outfile);
4326
    qemu_free(f);
4327
    return NULL;
4328
}
4329

    
4330
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4331
{
4332
    QEMUFile *f;
4333

    
4334
    f = qemu_mallocz(sizeof(QEMUFile));
4335
    if (!f)
4336
        return NULL;
4337
    f->is_file = 0;
4338
    f->bs = bs;
4339
    f->is_writable = is_writable;
4340
    f->base_offset = offset;
4341
    return f;
4342
}
4343

    
4344
void qemu_fflush(QEMUFile *f)
4345
{
4346
    if (!f->is_writable)
4347
        return;
4348
    if (f->buf_index > 0) {
4349
        if (f->is_file) {
4350
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4351
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4352
        } else {
4353
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4354
                        f->buf, f->buf_index);
4355
        }
4356
        f->buf_offset += f->buf_index;
4357
        f->buf_index = 0;
4358
    }
4359
}
4360

    
4361
static void qemu_fill_buffer(QEMUFile *f)
4362
{
4363
    int len;
4364

    
4365
    if (f->is_writable)
4366
        return;
4367
    if (f->is_file) {
4368
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4369
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4370
        if (len < 0)
4371
            len = 0;
4372
    } else {
4373
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4374
                         f->buf, IO_BUF_SIZE);
4375
        if (len < 0)
4376
            len = 0;
4377
    }
4378
    f->buf_index = 0;
4379
    f->buf_size = len;
4380
    f->buf_offset += len;
4381
}
4382

    
4383
void qemu_fclose(QEMUFile *f)
4384
{
4385
    if (f->is_writable)
4386
        qemu_fflush(f);
4387
    if (f->is_file) {
4388
        fclose(f->outfile);
4389
    }
4390
    qemu_free(f);
4391
}
4392

    
4393
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4394
{
4395
    int l;
4396
    while (size > 0) {
4397
        l = IO_BUF_SIZE - f->buf_index;
4398
        if (l > size)
4399
            l = size;
4400
        memcpy(f->buf + f->buf_index, buf, l);
4401
        f->buf_index += l;
4402
        buf += l;
4403
        size -= l;
4404
        if (f->buf_index >= IO_BUF_SIZE)
4405
            qemu_fflush(f);
4406
    }
4407
}
4408

    
4409
void qemu_put_byte(QEMUFile *f, int v)
4410
{
4411
    f->buf[f->buf_index++] = v;
4412
    if (f->buf_index >= IO_BUF_SIZE)
4413
        qemu_fflush(f);
4414
}
4415

    
4416
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4417
{
4418
    int size, l;
4419

    
4420
    size = size1;
4421
    while (size > 0) {
4422
        l = f->buf_size - f->buf_index;
4423
        if (l == 0) {
4424
            qemu_fill_buffer(f);
4425
            l = f->buf_size - f->buf_index;
4426
            if (l == 0)
4427
                break;
4428
        }
4429
        if (l > size)
4430
            l = size;
4431
        memcpy(buf, f->buf + f->buf_index, l);
4432
        f->buf_index += l;
4433
        buf += l;
4434
        size -= l;
4435
    }
4436
    return size1 - size;
4437
}
4438

    
4439
int qemu_get_byte(QEMUFile *f)
4440
{
4441
    if (f->buf_index >= f->buf_size) {
4442
        qemu_fill_buffer(f);
4443
        if (f->buf_index >= f->buf_size)
4444
            return 0;
4445
    }
4446
    return f->buf[f->buf_index++];
4447
}
4448

    
4449
int64_t qemu_ftell(QEMUFile *f)
4450
{
4451
    return f->buf_offset - f->buf_size + f->buf_index;
4452
}
4453

    
4454
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4455
{
4456
    if (whence == SEEK_SET) {
4457
        /* nothing to do */
4458
    } else if (whence == SEEK_CUR) {
4459
        pos += qemu_ftell(f);
4460
    } else {
4461
        /* SEEK_END not supported */
4462
        return -1;
4463
    }
4464
    if (f->is_writable) {
4465
        qemu_fflush(f);
4466
        f->buf_offset = pos;
4467
    } else {
4468
        f->buf_offset = pos;
4469
        f->buf_index = 0;
4470
        f->buf_size = 0;
4471
    }
4472
    return pos;
4473
}
4474

    
4475
void qemu_put_be16(QEMUFile *f, unsigned int v)
4476
{
4477
    qemu_put_byte(f, v >> 8);
4478
    qemu_put_byte(f, v);
4479
}
4480

    
4481
void qemu_put_be32(QEMUFile *f, unsigned int v)
4482
{
4483
    qemu_put_byte(f, v >> 24);
4484
    qemu_put_byte(f, v >> 16);
4485
    qemu_put_byte(f, v >> 8);
4486
    qemu_put_byte(f, v);
4487
}
4488

    
4489
void qemu_put_be64(QEMUFile *f, uint64_t v)
4490
{
4491
    qemu_put_be32(f, v >> 32);
4492
    qemu_put_be32(f, v);
4493
}
4494

    
4495
unsigned int qemu_get_be16(QEMUFile *f)
4496
{
4497
    unsigned int v;
4498
    v = qemu_get_byte(f) << 8;
4499
    v |= qemu_get_byte(f);
4500
    return v;
4501
}
4502

    
4503
unsigned int qemu_get_be32(QEMUFile *f)
4504
{
4505
    unsigned int v;
4506
    v = qemu_get_byte(f) << 24;
4507
    v |= qemu_get_byte(f) << 16;
4508
    v |= qemu_get_byte(f) << 8;
4509
    v |= qemu_get_byte(f);
4510
    return v;
4511
}
4512

    
4513
uint64_t qemu_get_be64(QEMUFile *f)
4514
{
4515
    uint64_t v;
4516
    v = (uint64_t)qemu_get_be32(f) << 32;
4517
    v |= qemu_get_be32(f);
4518
    return v;
4519
}
4520

    
4521
typedef struct SaveStateEntry {
4522
    char idstr[256];
4523
    int instance_id;
4524
    int version_id;
4525
    SaveStateHandler *save_state;
4526
    LoadStateHandler *load_state;
4527
    void *opaque;
4528
    struct SaveStateEntry *next;
4529
} SaveStateEntry;
4530

    
4531
static SaveStateEntry *first_se;
4532

    
4533
int register_savevm(const char *idstr, 
4534
                    int instance_id, 
4535
                    int version_id,
4536
                    SaveStateHandler *save_state,
4537
                    LoadStateHandler *load_state,
4538
                    void *opaque)
4539
{
4540
    SaveStateEntry *se, **pse;
4541

    
4542
    se = qemu_malloc(sizeof(SaveStateEntry));
4543
    if (!se)
4544
        return -1;
4545
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4546
    se->instance_id = instance_id;
4547
    se->version_id = version_id;
4548
    se->save_state = save_state;
4549
    se->load_state = load_state;
4550
    se->opaque = opaque;
4551
    se->next = NULL;
4552

    
4553
    /* add at the end of list */
4554
    pse = &first_se;
4555
    while (*pse != NULL)
4556
        pse = &(*pse)->next;
4557
    *pse = se;
4558
    return 0;
4559
}
4560

    
4561
#define QEMU_VM_FILE_MAGIC   0x5145564d
4562
#define QEMU_VM_FILE_VERSION 0x00000002
4563

    
4564
int qemu_savevm_state(QEMUFile *f)
4565
{
4566
    SaveStateEntry *se;
4567
    int len, ret;
4568
    int64_t cur_pos, len_pos, total_len_pos;
4569

    
4570
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4571
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4572
    total_len_pos = qemu_ftell(f);
4573
    qemu_put_be64(f, 0); /* total size */
4574

    
4575
    for(se = first_se; se != NULL; se = se->next) {
4576
        /* ID string */
4577
        len = strlen(se->idstr);
4578
        qemu_put_byte(f, len);
4579
        qemu_put_buffer(f, se->idstr, len);
4580

    
4581
        qemu_put_be32(f, se->instance_id);
4582
        qemu_put_be32(f, se->version_id);
4583

    
4584
        /* record size: filled later */
4585
        len_pos = qemu_ftell(f);
4586
        qemu_put_be32(f, 0);
4587
        
4588
        se->save_state(f, se->opaque);
4589

    
4590
        /* fill record size */
4591
        cur_pos = qemu_ftell(f);
4592
        len = cur_pos - len_pos - 4;
4593
        qemu_fseek(f, len_pos, SEEK_SET);
4594
        qemu_put_be32(f, len);
4595
        qemu_fseek(f, cur_pos, SEEK_SET);
4596
    }
4597
    cur_pos = qemu_ftell(f);
4598
    qemu_fseek(f, total_len_pos, SEEK_SET);
4599
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4600
    qemu_fseek(f, cur_pos, SEEK_SET);
4601

    
4602
    ret = 0;
4603
    return ret;
4604
}
4605

    
4606
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4607
{
4608
    SaveStateEntry *se;
4609

    
4610
    for(se = first_se; se != NULL; se = se->next) {
4611
        if (!strcmp(se->idstr, idstr) && 
4612
            instance_id == se->instance_id)
4613
            return se;
4614
    }
4615
    return NULL;
4616
}
4617

    
4618
int qemu_loadvm_state(QEMUFile *f)
4619
{
4620
    SaveStateEntry *se;
4621
    int len, ret, instance_id, record_len, version_id;
4622
    int64_t total_len, end_pos, cur_pos;
4623
    unsigned int v;
4624
    char idstr[256];
4625
    
4626
    v = qemu_get_be32(f);
4627
    if (v != QEMU_VM_FILE_MAGIC)
4628
        goto fail;
4629
    v = qemu_get_be32(f);
4630
    if (v != QEMU_VM_FILE_VERSION) {
4631
    fail:
4632
        ret = -1;
4633
        goto the_end;
4634
    }
4635
    total_len = qemu_get_be64(f);
4636
    end_pos = total_len + qemu_ftell(f);
4637
    for(;;) {
4638
        if (qemu_ftell(f) >= end_pos)
4639
            break;
4640
        len = qemu_get_byte(f);
4641
        qemu_get_buffer(f, idstr, len);
4642
        idstr[len] = '\0';
4643
        instance_id = qemu_get_be32(f);
4644
        version_id = qemu_get_be32(f);
4645
        record_len = qemu_get_be32(f);
4646
#if 0
4647
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4648
               idstr, instance_id, version_id, record_len);
4649
#endif
4650
        cur_pos = qemu_ftell(f);
4651
        se = find_se(idstr, instance_id);
4652
        if (!se) {
4653
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4654
                    instance_id, idstr);
4655
        } else {
4656
            ret = se->load_state(f, se->opaque, version_id);
4657
            if (ret < 0) {
4658
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4659
                        instance_id, idstr);
4660
            }
4661
        }
4662
        /* always seek to exact end of record */
4663
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4664
    }
4665
    ret = 0;
4666
 the_end:
4667
    return ret;
4668
}
4669

    
4670
/* device can contain snapshots */
4671
static int bdrv_can_snapshot(BlockDriverState *bs)
4672
{
4673
    return (bs &&
4674
            !bdrv_is_removable(bs) &&
4675
            !bdrv_is_read_only(bs));
4676
}
4677

    
4678
/* device must be snapshots in order to have a reliable snapshot */
4679
static int bdrv_has_snapshot(BlockDriverState *bs)
4680
{
4681
    return (bs &&
4682
            !bdrv_is_removable(bs) &&
4683
            !bdrv_is_read_only(bs));
4684
}
4685

    
4686
static BlockDriverState *get_bs_snapshots(void)
4687
{
4688
    BlockDriverState *bs;
4689
    int i;
4690

    
4691
    if (bs_snapshots)
4692
        return bs_snapshots;
4693
    for(i = 0; i <= MAX_DISKS; i++) {
4694
        bs = bs_table[i];
4695
        if (bdrv_can_snapshot(bs))
4696
            goto ok;
4697
    }
4698
    return NULL;
4699
 ok:
4700
    bs_snapshots = bs;
4701
    return bs;
4702
}
4703

    
4704
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4705
                              const char *name)
4706
{
4707
    QEMUSnapshotInfo *sn_tab, *sn;
4708
    int nb_sns, i, ret;
4709
    
4710
    ret = -ENOENT;
4711
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4712
    if (nb_sns < 0)
4713
        return ret;
4714
    for(i = 0; i < nb_sns; i++) {
4715
        sn = &sn_tab[i];
4716
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4717
            *sn_info = *sn;
4718
            ret = 0;
4719
            break;
4720
        }
4721
    }
4722
    qemu_free(sn_tab);
4723
    return ret;
4724
}
4725

    
4726
void do_savevm(const char *name)
4727
{
4728
    BlockDriverState *bs, *bs1;
4729
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4730
    int must_delete, ret, i;
4731
    BlockDriverInfo bdi1, *bdi = &bdi1;
4732
    QEMUFile *f;
4733
    int saved_vm_running;
4734
#ifdef _WIN32
4735
    struct _timeb tb;
4736
#else
4737
    struct timeval tv;
4738
#endif
4739

    
4740
    bs = get_bs_snapshots();
4741
    if (!bs) {
4742
        term_printf("No block device can accept snapshots\n");
4743
        return;
4744
    }
4745

    
4746
    /* ??? Should this occur after vm_stop?  */
4747
    qemu_aio_flush();
4748

    
4749
    saved_vm_running = vm_running;
4750
    vm_stop(0);
4751
    
4752
    must_delete = 0;
4753
    if (name) {
4754
        ret = bdrv_snapshot_find(bs, old_sn, name);
4755
        if (ret >= 0) {
4756
            must_delete = 1;
4757
        }
4758
    }
4759
    memset(sn, 0, sizeof(*sn));
4760
    if (must_delete) {
4761
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4762
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4763
    } else {
4764
        if (name)
4765
            pstrcpy(sn->name, sizeof(sn->name), name);
4766
    }
4767

    
4768
    /* fill auxiliary fields */
4769
#ifdef _WIN32
4770
    _ftime(&tb);
4771
    sn->date_sec = tb.time;
4772
    sn->date_nsec = tb.millitm * 1000000;
4773
#else
4774
    gettimeofday(&tv, NULL);
4775
    sn->date_sec = tv.tv_sec;
4776
    sn->date_nsec = tv.tv_usec * 1000;
4777
#endif
4778
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4779
    
4780
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4781
        term_printf("Device %s does not support VM state snapshots\n",
4782
                    bdrv_get_device_name(bs));
4783
        goto the_end;
4784
    }
4785
    
4786
    /* save the VM state */
4787
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4788
    if (!f) {
4789
        term_printf("Could not open VM state file\n");
4790
        goto the_end;
4791
    }
4792
    ret = qemu_savevm_state(f);
4793
    sn->vm_state_size = qemu_ftell(f);
4794
    qemu_fclose(f);
4795
    if (ret < 0) {
4796
        term_printf("Error %d while writing VM\n", ret);
4797
        goto the_end;
4798
    }
4799
    
4800
    /* create the snapshots */
4801

    
4802
    for(i = 0; i < MAX_DISKS; i++) {
4803
        bs1 = bs_table[i];
4804
        if (bdrv_has_snapshot(bs1)) {
4805
            if (must_delete) {
4806
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4807
                if (ret < 0) {
4808
                    term_printf("Error while deleting snapshot on '%s'\n",
4809
                                bdrv_get_device_name(bs1));
4810
                }
4811
            }
4812
            ret = bdrv_snapshot_create(bs1, sn);
4813
            if (ret < 0) {
4814
                term_printf("Error while creating snapshot on '%s'\n",
4815
                            bdrv_get_device_name(bs1));
4816
            }
4817
        }
4818
    }
4819

    
4820
 the_end:
4821
    if (saved_vm_running)
4822
        vm_start();
4823
}
4824

    
4825
void do_loadvm(const char *name)
4826
{
4827
    BlockDriverState *bs, *bs1;
4828
    BlockDriverInfo bdi1, *bdi = &bdi1;
4829
    QEMUFile *f;
4830
    int i, ret;
4831
    int saved_vm_running;
4832

    
4833
    bs = get_bs_snapshots();
4834
    if (!bs) {
4835
        term_printf("No block device supports snapshots\n");
4836
        return;
4837
    }
4838
    
4839
    /* Flush all IO requests so they don't interfere with the new state.  */
4840
    qemu_aio_flush();
4841

    
4842
    saved_vm_running = vm_running;
4843
    vm_stop(0);
4844

    
4845
    for(i = 0; i <= MAX_DISKS; i++) {
4846
        bs1 = bs_table[i];
4847
        if (bdrv_has_snapshot(bs1)) {
4848
            ret = bdrv_snapshot_goto(bs1, name);
4849
            if (ret < 0) {
4850
                if (bs != bs1)
4851
                    term_printf("Warning: ");
4852
                switch(ret) {
4853
                case -ENOTSUP:
4854
                    term_printf("Snapshots not supported on device '%s'\n",
4855
                                bdrv_get_device_name(bs1));
4856
                    break;
4857
                case -ENOENT:
4858
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
4859
                                name, bdrv_get_device_name(bs1));
4860
                    break;
4861
                default:
4862
                    term_printf("Error %d while activating snapshot on '%s'\n",
4863
                                ret, bdrv_get_device_name(bs1));
4864
                    break;
4865
                }
4866
                /* fatal on snapshot block device */
4867
                if (bs == bs1)
4868
                    goto the_end;
4869
            }
4870
        }
4871
    }
4872

    
4873
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4874
        term_printf("Device %s does not support VM state snapshots\n",
4875
                    bdrv_get_device_name(bs));
4876
        return;
4877
    }
4878
    
4879
    /* restore the VM state */
4880
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4881
    if (!f) {
4882
        term_printf("Could not open VM state file\n");
4883
        goto the_end;
4884
    }
4885
    ret = qemu_loadvm_state(f);
4886
    qemu_fclose(f);
4887
    if (ret < 0) {
4888
        term_printf("Error %d while loading VM state\n", ret);
4889
    }
4890
 the_end:
4891
    if (saved_vm_running)
4892
        vm_start();
4893
}
4894

    
4895
void do_delvm(const char *name)
4896
{
4897
    BlockDriverState *bs, *bs1;
4898
    int i, ret;
4899

    
4900
    bs = get_bs_snapshots();
4901
    if (!bs) {
4902
        term_printf("No block device supports snapshots\n");
4903
        return;
4904
    }
4905
    
4906
    for(i = 0; i <= MAX_DISKS; i++) {
4907
        bs1 = bs_table[i];
4908
        if (bdrv_has_snapshot(bs1)) {
4909
            ret = bdrv_snapshot_delete(bs1, name);
4910
            if (ret < 0) {
4911
                if (ret == -ENOTSUP)
4912
                    term_printf("Snapshots not supported on device '%s'\n",
4913
                                bdrv_get_device_name(bs1));
4914
                else
4915
                    term_printf("Error %d while deleting snapshot on '%s'\n",
4916
                                ret, bdrv_get_device_name(bs1));
4917
            }
4918
        }
4919
    }
4920
}
4921

    
4922
void do_info_snapshots(void)
4923
{
4924
    BlockDriverState *bs, *bs1;
4925
    QEMUSnapshotInfo *sn_tab, *sn;
4926
    int nb_sns, i;
4927
    char buf[256];
4928

    
4929
    bs = get_bs_snapshots();
4930
    if (!bs) {
4931
        term_printf("No available block device supports snapshots\n");
4932
        return;
4933
    }
4934
    term_printf("Snapshot devices:");
4935
    for(i = 0; i <= MAX_DISKS; i++) {
4936
        bs1 = bs_table[i];
4937
        if (bdrv_has_snapshot(bs1)) {
4938
            if (bs == bs1)
4939
                term_printf(" %s", bdrv_get_device_name(bs1));
4940
        }
4941
    }
4942
    term_printf("\n");
4943

    
4944
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4945
    if (nb_sns < 0) {
4946
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4947
        return;
4948
    }
4949
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4950
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4951
    for(i = 0; i < nb_sns; i++) {
4952
        sn = &sn_tab[i];
4953
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4954
    }
4955
    qemu_free(sn_tab);
4956
}
4957

    
4958
/***********************************************************/
4959
/* cpu save/restore */
4960

    
4961
#if defined(TARGET_I386)
4962

    
4963
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4964
{
4965
    qemu_put_be32(f, dt->selector);
4966
    qemu_put_betl(f, dt->base);
4967
    qemu_put_be32(f, dt->limit);
4968
    qemu_put_be32(f, dt->flags);
4969
}
4970

    
4971
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4972
{
4973
    dt->selector = qemu_get_be32(f);
4974
    dt->base = qemu_get_betl(f);
4975
    dt->limit = qemu_get_be32(f);
4976
    dt->flags = qemu_get_be32(f);
4977
}
4978

    
4979
void cpu_save(QEMUFile *f, void *opaque)
4980
{
4981
    CPUState *env = opaque;
4982
    uint16_t fptag, fpus, fpuc, fpregs_format;
4983
    uint32_t hflags;
4984
    int i;
4985
    
4986
    for(i = 0; i < CPU_NB_REGS; i++)
4987
        qemu_put_betls(f, &env->regs[i]);
4988
    qemu_put_betls(f, &env->eip);
4989
    qemu_put_betls(f, &env->eflags);
4990
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4991
    qemu_put_be32s(f, &hflags);
4992
    
4993
    /* FPU */
4994
    fpuc = env->fpuc;
4995
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4996
    fptag = 0;
4997
    for(i = 0; i < 8; i++) {
4998
        fptag |= ((!env->fptags[i]) << i);
4999
    }
5000
    
5001
    qemu_put_be16s(f, &fpuc);
5002
    qemu_put_be16s(f, &fpus);
5003
    qemu_put_be16s(f, &fptag);
5004

    
5005
#ifdef USE_X86LDOUBLE
5006
    fpregs_format = 0;
5007
#else
5008
    fpregs_format = 1;
5009
#endif
5010
    qemu_put_be16s(f, &fpregs_format);
5011
    
5012
    for(i = 0; i < 8; i++) {
5013
#ifdef USE_X86LDOUBLE
5014
        {
5015
            uint64_t mant;
5016
            uint16_t exp;
5017
            /* we save the real CPU data (in case of MMX usage only 'mant'
5018
               contains the MMX register */
5019
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5020
            qemu_put_be64(f, mant);
5021
            qemu_put_be16(f, exp);
5022
        }
5023
#else
5024
        /* if we use doubles for float emulation, we save the doubles to
5025
           avoid losing information in case of MMX usage. It can give
5026
           problems if the image is restored on a CPU where long
5027
           doubles are used instead. */
5028
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5029
#endif
5030
    }
5031

    
5032
    for(i = 0; i < 6; i++)
5033
        cpu_put_seg(f, &env->segs[i]);
5034
    cpu_put_seg(f, &env->ldt);
5035
    cpu_put_seg(f, &env->tr);
5036
    cpu_put_seg(f, &env->gdt);
5037
    cpu_put_seg(f, &env->idt);
5038
    
5039
    qemu_put_be32s(f, &env->sysenter_cs);
5040
    qemu_put_be32s(f, &env->sysenter_esp);
5041
    qemu_put_be32s(f, &env->sysenter_eip);
5042
    
5043
    qemu_put_betls(f, &env->cr[0]);
5044
    qemu_put_betls(f, &env->cr[2]);
5045
    qemu_put_betls(f, &env->cr[3]);
5046
    qemu_put_betls(f, &env->cr[4]);
5047
    
5048
    for(i = 0; i < 8; i++)
5049
        qemu_put_betls(f, &env->dr[i]);
5050

    
5051
    /* MMU */
5052
    qemu_put_be32s(f, &env->a20_mask);
5053

    
5054
    /* XMM */
5055
    qemu_put_be32s(f, &env->mxcsr);
5056
    for(i = 0; i < CPU_NB_REGS; i++) {
5057
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5058
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5059
    }
5060

    
5061
#ifdef TARGET_X86_64
5062
    qemu_put_be64s(f, &env->efer);
5063
    qemu_put_be64s(f, &env->star);
5064
    qemu_put_be64s(f, &env->lstar);
5065
    qemu_put_be64s(f, &env->cstar);
5066
    qemu_put_be64s(f, &env->fmask);
5067
    qemu_put_be64s(f, &env->kernelgsbase);
5068
#endif
5069
    qemu_put_be32s(f, &env->smbase);
5070
}
5071

    
5072
#ifdef USE_X86LDOUBLE
5073
/* XXX: add that in a FPU generic layer */
5074
union x86_longdouble {
5075
    uint64_t mant;
5076
    uint16_t exp;
5077
};
5078

    
5079
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5080
#define EXPBIAS1 1023
5081
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5082
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5083

    
5084
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5085
{
5086
    int e;
5087
    /* mantissa */
5088
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5089
    /* exponent + sign */
5090
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5091
    e |= SIGND1(temp) >> 16;
5092
    p->exp = e;
5093
}
5094
#endif
5095

    
5096
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5097
{
5098
    CPUState *env = opaque;
5099
    int i, guess_mmx;
5100
    uint32_t hflags;
5101
    uint16_t fpus, fpuc, fptag, fpregs_format;
5102

    
5103
    if (version_id != 3 && version_id != 4)
5104
        return -EINVAL;
5105
    for(i = 0; i < CPU_NB_REGS; i++)
5106
        qemu_get_betls(f, &env->regs[i]);
5107
    qemu_get_betls(f, &env->eip);
5108
    qemu_get_betls(f, &env->eflags);
5109
    qemu_get_be32s(f, &hflags);
5110

    
5111
    qemu_get_be16s(f, &fpuc);
5112
    qemu_get_be16s(f, &fpus);
5113
    qemu_get_be16s(f, &fptag);
5114
    qemu_get_be16s(f, &fpregs_format);
5115
    
5116
    /* NOTE: we cannot always restore the FPU state if the image come
5117
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5118
       if we are in an MMX state to restore correctly in that case. */
5119
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5120
    for(i = 0; i < 8; i++) {
5121
        uint64_t mant;
5122
        uint16_t exp;
5123
        
5124
        switch(fpregs_format) {
5125
        case 0:
5126
            mant = qemu_get_be64(f);
5127
            exp = qemu_get_be16(f);
5128
#ifdef USE_X86LDOUBLE
5129
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5130
#else
5131
            /* difficult case */
5132
            if (guess_mmx)
5133
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5134
            else
5135
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5136
#endif
5137
            break;
5138
        case 1:
5139
            mant = qemu_get_be64(f);
5140
#ifdef USE_X86LDOUBLE
5141
            {
5142
                union x86_longdouble *p;
5143
                /* difficult case */
5144
                p = (void *)&env->fpregs[i];
5145
                if (guess_mmx) {
5146
                    p->mant = mant;
5147
                    p->exp = 0xffff;
5148
                } else {
5149
                    fp64_to_fp80(p, mant);
5150
                }
5151
            }
5152
#else
5153
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5154
#endif            
5155
            break;
5156
        default:
5157
            return -EINVAL;
5158
        }
5159
    }
5160

    
5161
    env->fpuc = fpuc;
5162
    /* XXX: restore FPU round state */
5163
    env->fpstt = (fpus >> 11) & 7;
5164
    env->fpus = fpus & ~0x3800;
5165
    fptag ^= 0xff;
5166
    for(i = 0; i < 8; i++) {
5167
        env->fptags[i] = (fptag >> i) & 1;
5168
    }
5169
    
5170
    for(i = 0; i < 6; i++)
5171
        cpu_get_seg(f, &env->segs[i]);
5172
    cpu_get_seg(f, &env->ldt);
5173
    cpu_get_seg(f, &env->tr);
5174
    cpu_get_seg(f, &env->gdt);
5175
    cpu_get_seg(f, &env->idt);
5176
    
5177
    qemu_get_be32s(f, &env->sysenter_cs);
5178
    qemu_get_be32s(f, &env->sysenter_esp);
5179
    qemu_get_be32s(f, &env->sysenter_eip);
5180
    
5181
    qemu_get_betls(f, &env->cr[0]);
5182
    qemu_get_betls(f, &env->cr[2]);
5183
    qemu_get_betls(f, &env->cr[3]);
5184
    qemu_get_betls(f, &env->cr[4]);
5185
    
5186
    for(i = 0; i < 8; i++)
5187
        qemu_get_betls(f, &env->dr[i]);
5188

    
5189
    /* MMU */
5190
    qemu_get_be32s(f, &env->a20_mask);
5191

    
5192
    qemu_get_be32s(f, &env->mxcsr);
5193
    for(i = 0; i < CPU_NB_REGS; i++) {
5194
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5195
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5196
    }
5197

    
5198
#ifdef TARGET_X86_64
5199
    qemu_get_be64s(f, &env->efer);
5200
    qemu_get_be64s(f, &env->star);
5201
    qemu_get_be64s(f, &env->lstar);
5202
    qemu_get_be64s(f, &env->cstar);
5203
    qemu_get_be64s(f, &env->fmask);
5204
    qemu_get_be64s(f, &env->kernelgsbase);
5205
#endif
5206
    if (version_id >= 4) 
5207
        qemu_get_be32s(f, &env->smbase);
5208

    
5209
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5210
    env->hflags = hflags;
5211
    tlb_flush(env, 1);
5212
    return 0;
5213
}
5214

    
5215
#elif defined(TARGET_PPC)
5216
void cpu_save(QEMUFile *f, void *opaque)
5217
{
5218
}
5219

    
5220
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5221
{
5222
    return 0;
5223
}
5224

    
5225
#elif defined(TARGET_MIPS)
5226
void cpu_save(QEMUFile *f, void *opaque)
5227
{
5228
}
5229

    
5230
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5231
{
5232
    return 0;
5233
}
5234

    
5235
#elif defined(TARGET_SPARC)
5236
void cpu_save(QEMUFile *f, void *opaque)
5237
{
5238
    CPUState *env = opaque;
5239
    int i;
5240
    uint32_t tmp;
5241

    
5242
    for(i = 0; i < 8; i++)
5243
        qemu_put_betls(f, &env->gregs[i]);
5244
    for(i = 0; i < NWINDOWS * 16; i++)
5245
        qemu_put_betls(f, &env->regbase[i]);
5246

    
5247
    /* FPU */
5248
    for(i = 0; i < TARGET_FPREGS; i++) {
5249
        union {
5250
            float32 f;
5251
            uint32_t i;
5252
        } u;
5253
        u.f = env->fpr[i];
5254
        qemu_put_be32(f, u.i);
5255
    }
5256

    
5257
    qemu_put_betls(f, &env->pc);
5258
    qemu_put_betls(f, &env->npc);
5259
    qemu_put_betls(f, &env->y);
5260
    tmp = GET_PSR(env);
5261
    qemu_put_be32(f, tmp);
5262
    qemu_put_betls(f, &env->fsr);
5263
    qemu_put_betls(f, &env->tbr);
5264
#ifndef TARGET_SPARC64
5265
    qemu_put_be32s(f, &env->wim);
5266
    /* MMU */
5267
    for(i = 0; i < 16; i++)
5268
        qemu_put_be32s(f, &env->mmuregs[i]);
5269
#endif
5270
}
5271

    
5272
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5273
{
5274
    CPUState *env = opaque;
5275
    int i;
5276
    uint32_t tmp;
5277

    
5278
    for(i = 0; i < 8; i++)
5279
        qemu_get_betls(f, &env->gregs[i]);
5280
    for(i = 0; i < NWINDOWS * 16; i++)
5281
        qemu_get_betls(f, &env->regbase[i]);
5282

    
5283
    /* FPU */
5284
    for(i = 0; i < TARGET_FPREGS; i++) {
5285
        union {
5286
            float32 f;
5287
            uint32_t i;
5288
        } u;
5289
        u.i = qemu_get_be32(f);
5290
        env->fpr[i] = u.f;
5291
    }
5292

    
5293
    qemu_get_betls(f, &env->pc);
5294
    qemu_get_betls(f, &env->npc);
5295
    qemu_get_betls(f, &env->y);
5296
    tmp = qemu_get_be32(f);
5297
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5298
                     correctly updated */
5299
    PUT_PSR(env, tmp);
5300
    qemu_get_betls(f, &env->fsr);
5301
    qemu_get_betls(f, &env->tbr);
5302
#ifndef TARGET_SPARC64
5303
    qemu_get_be32s(f, &env->wim);
5304
    /* MMU */
5305
    for(i = 0; i < 16; i++)
5306
        qemu_get_be32s(f, &env->mmuregs[i]);
5307
#endif
5308
    tlb_flush(env, 1);
5309
    return 0;
5310
}
5311

    
5312
#elif defined(TARGET_ARM)
5313

    
5314
/* ??? Need to implement these.  */
5315
void cpu_save(QEMUFile *f, void *opaque)
5316
{
5317
}
5318

    
5319
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5320
{
5321
    return 0;
5322
}
5323

    
5324
#else
5325

    
5326
#warning No CPU save/restore functions
5327

    
5328
#endif
5329

    
5330
/***********************************************************/
5331
/* ram save/restore */
5332

    
5333
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5334
{
5335
    int v;
5336

    
5337
    v = qemu_get_byte(f);
5338
    switch(v) {
5339
    case 0:
5340
        if (qemu_get_buffer(f, buf, len) != len)
5341
            return -EIO;
5342
        break;
5343
    case 1:
5344
        v = qemu_get_byte(f);
5345
        memset(buf, v, len);
5346
        break;
5347
    default:
5348
        return -EINVAL;
5349
    }
5350
    return 0;
5351
}
5352

    
5353
static int ram_load_v1(QEMUFile *f, void *opaque)
5354
{
5355
    int i, ret;
5356

    
5357
    if (qemu_get_be32(f) != phys_ram_size)
5358
        return -EINVAL;
5359
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5360
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5361
        if (ret)
5362
            return ret;
5363
    }
5364
    return 0;
5365
}
5366

    
5367
#define BDRV_HASH_BLOCK_SIZE 1024
5368
#define IOBUF_SIZE 4096
5369
#define RAM_CBLOCK_MAGIC 0xfabe
5370

    
5371
typedef struct RamCompressState {
5372
    z_stream zstream;
5373
    QEMUFile *f;
5374
    uint8_t buf[IOBUF_SIZE];
5375
} RamCompressState;
5376

    
5377
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5378
{
5379
    int ret;
5380
    memset(s, 0, sizeof(*s));
5381
    s->f = f;
5382
    ret = deflateInit2(&s->zstream, 1,
5383
                       Z_DEFLATED, 15, 
5384
                       9, Z_DEFAULT_STRATEGY);
5385
    if (ret != Z_OK)
5386
        return -1;
5387
    s->zstream.avail_out = IOBUF_SIZE;
5388
    s->zstream.next_out = s->buf;
5389
    return 0;
5390
}
5391

    
5392
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5393
{
5394
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5395
    qemu_put_be16(s->f, len);
5396
    qemu_put_buffer(s->f, buf, len);
5397
}
5398

    
5399
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5400
{
5401
    int ret;
5402

    
5403
    s->zstream.avail_in = len;
5404
    s->zstream.next_in = (uint8_t *)buf;
5405
    while (s->zstream.avail_in > 0) {
5406
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5407
        if (ret != Z_OK)
5408
            return -1;
5409
        if (s->zstream.avail_out == 0) {
5410
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5411
            s->zstream.avail_out = IOBUF_SIZE;
5412
            s->zstream.next_out = s->buf;
5413
        }
5414
    }
5415
    return 0;
5416
}
5417

    
5418
static void ram_compress_close(RamCompressState *s)
5419
{
5420
    int len, ret;
5421

    
5422
    /* compress last bytes */
5423
    for(;;) {
5424
        ret = deflate(&s->zstream, Z_FINISH);
5425
        if (ret == Z_OK || ret == Z_STREAM_END) {
5426
            len = IOBUF_SIZE - s->zstream.avail_out;
5427
            if (len > 0) {
5428
                ram_put_cblock(s, s->buf, len);
5429
            }
5430
            s->zstream.avail_out = IOBUF_SIZE;
5431
            s->zstream.next_out = s->buf;
5432
            if (ret == Z_STREAM_END)
5433
                break;
5434
        } else {
5435
            goto fail;
5436
        }
5437
    }
5438
fail:
5439
    deflateEnd(&s->zstream);
5440
}
5441

    
5442
typedef struct RamDecompressState {
5443
    z_stream zstream;
5444
    QEMUFile *f;
5445
    uint8_t buf[IOBUF_SIZE];
5446
} RamDecompressState;
5447

    
5448
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5449
{
5450
    int ret;
5451
    memset(s, 0, sizeof(*s));
5452
    s->f = f;
5453
    ret = inflateInit(&s->zstream);
5454
    if (ret != Z_OK)
5455
        return -1;
5456
    return 0;
5457
}
5458

    
5459
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5460
{
5461
    int ret, clen;
5462

    
5463
    s->zstream.avail_out = len;
5464
    s->zstream.next_out = buf;
5465
    while (s->zstream.avail_out > 0) {
5466
        if (s->zstream.avail_in == 0) {
5467
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5468
                return -1;
5469
            clen = qemu_get_be16(s->f);
5470
            if (clen > IOBUF_SIZE)
5471
                return -1;
5472
            qemu_get_buffer(s->f, s->buf, clen);
5473
            s->zstream.avail_in = clen;
5474
            s->zstream.next_in = s->buf;
5475
        }
5476
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5477
        if (ret != Z_OK && ret != Z_STREAM_END) {
5478
            return -1;
5479
        }
5480
    }
5481
    return 0;
5482
}
5483

    
5484
static void ram_decompress_close(RamDecompressState *s)
5485
{
5486
    inflateEnd(&s->zstream);
5487
}
5488

    
5489
static void ram_save(QEMUFile *f, void *opaque)
5490
{
5491
    int i;
5492
    RamCompressState s1, *s = &s1;
5493
    uint8_t buf[10];
5494
    
5495
    qemu_put_be32(f, phys_ram_size);
5496
    if (ram_compress_open(s, f) < 0)
5497
        return;
5498
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5499
#if 0
5500
        if (tight_savevm_enabled) {
5501
            int64_t sector_num;
5502
            int j;
5503

5504
            /* find if the memory block is available on a virtual
5505
               block device */
5506
            sector_num = -1;
5507
            for(j = 0; j < MAX_DISKS; j++) {
5508
                if (bs_table[j]) {
5509
                    sector_num = bdrv_hash_find(bs_table[j], 
5510
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5511
                    if (sector_num >= 0)
5512
                        break;
5513
                }
5514
            }
5515
            if (j == MAX_DISKS)
5516
                goto normal_compress;
5517
            buf[0] = 1;
5518
            buf[1] = j;
5519
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5520
            ram_compress_buf(s, buf, 10);
5521
        } else 
5522
#endif
5523
        {
5524
            //        normal_compress:
5525
            buf[0] = 0;
5526
            ram_compress_buf(s, buf, 1);
5527
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5528
        }
5529
    }
5530
    ram_compress_close(s);
5531
}
5532

    
5533
static int ram_load(QEMUFile *f, void *opaque, int version_id)
5534
{
5535
    RamDecompressState s1, *s = &s1;
5536
    uint8_t buf[10];
5537
    int i;
5538

    
5539
    if (version_id == 1)
5540
        return ram_load_v1(f, opaque);
5541
    if (version_id != 2)
5542
        return -EINVAL;
5543
    if (qemu_get_be32(f) != phys_ram_size)
5544
        return -EINVAL;
5545
    if (ram_decompress_open(s, f) < 0)
5546
        return -EINVAL;
5547
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5548
        if (ram_decompress_buf(s, buf, 1) < 0) {
5549
            fprintf(stderr, "Error while reading ram block header\n");
5550
            goto error;
5551
        }
5552
        if (buf[0] == 0) {
5553
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5554
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5555
                goto error;
5556
            }
5557
        } else 
5558
#if 0
5559
        if (buf[0] == 1) {
5560
            int bs_index;
5561
            int64_t sector_num;
5562

5563
            ram_decompress_buf(s, buf + 1, 9);
5564
            bs_index = buf[1];
5565
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5566
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5567
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
5568
                goto error;
5569
            }
5570
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5571
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5572
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5573
                        bs_index, sector_num);
5574
                goto error;
5575
            }
5576
        } else 
5577
#endif
5578
        {
5579
        error:
5580
            printf("Error block header\n");
5581
            return -EINVAL;
5582
        }
5583
    }
5584
    ram_decompress_close(s);
5585
    return 0;
5586
}
5587

    
5588
/***********************************************************/
5589
/* bottom halves (can be seen as timers which expire ASAP) */
5590

    
5591
struct QEMUBH {
5592
    QEMUBHFunc *cb;
5593
    void *opaque;
5594
    int scheduled;
5595
    QEMUBH *next;
5596
};
5597

    
5598
static QEMUBH *first_bh = NULL;
5599

    
5600
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5601
{
5602
    QEMUBH *bh;
5603
    bh = qemu_mallocz(sizeof(QEMUBH));
5604
    if (!bh)
5605
        return NULL;
5606
    bh->cb = cb;
5607
    bh->opaque = opaque;
5608
    return bh;
5609
}
5610

    
5611
int qemu_bh_poll(void)
5612
{
5613
    QEMUBH *bh, **pbh;
5614
    int ret;
5615

    
5616
    ret = 0;
5617
    for(;;) {
5618
        pbh = &first_bh;
5619
        bh = *pbh;
5620
        if (!bh)
5621
            break;
5622
        ret = 1;
5623
        *pbh = bh->next;
5624
        bh->scheduled = 0;
5625
        bh->cb(bh->opaque);
5626
    }
5627
    return ret;
5628
}
5629

    
5630
void qemu_bh_schedule(QEMUBH *bh)
5631
{
5632
    CPUState *env = cpu_single_env;
5633
    if (bh->scheduled)
5634
        return;
5635
    bh->scheduled = 1;
5636
    bh->next = first_bh;
5637
    first_bh = bh;
5638

    
5639
    /* stop the currently executing CPU to execute the BH ASAP */
5640
    if (env) {
5641
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5642
    }
5643
}
5644

    
5645
void qemu_bh_cancel(QEMUBH *bh)
5646
{
5647
    QEMUBH **pbh;
5648
    if (bh->scheduled) {
5649
        pbh = &first_bh;
5650
        while (*pbh != bh)
5651
            pbh = &(*pbh)->next;
5652
        *pbh = bh->next;
5653
        bh->scheduled = 0;
5654
    }
5655
}
5656

    
5657
void qemu_bh_delete(QEMUBH *bh)
5658
{
5659
    qemu_bh_cancel(bh);
5660
    qemu_free(bh);
5661
}
5662

    
5663
/***********************************************************/
5664
/* machine registration */
5665

    
5666
QEMUMachine *first_machine = NULL;
5667

    
5668
int qemu_register_machine(QEMUMachine *m)
5669
{
5670
    QEMUMachine **pm;
5671
    pm = &first_machine;
5672
    while (*pm != NULL)
5673
        pm = &(*pm)->next;
5674
    m->next = NULL;
5675
    *pm = m;
5676
    return 0;
5677
}
5678

    
5679
QEMUMachine *find_machine(const char *name)
5680
{
5681
    QEMUMachine *m;
5682

    
5683
    for(m = first_machine; m != NULL; m = m->next) {
5684
        if (!strcmp(m->name, name))
5685
            return m;
5686
    }
5687
    return NULL;
5688
}
5689

    
5690
/***********************************************************/
5691
/* main execution loop */
5692

    
5693
void gui_update(void *opaque)
5694
{
5695
    display_state.dpy_refresh(&display_state);
5696
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5697
}
5698

    
5699
struct vm_change_state_entry {
5700
    VMChangeStateHandler *cb;
5701
    void *opaque;
5702
    LIST_ENTRY (vm_change_state_entry) entries;
5703
};
5704

    
5705
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5706

    
5707
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5708
                                                     void *opaque)
5709
{
5710
    VMChangeStateEntry *e;
5711

    
5712
    e = qemu_mallocz(sizeof (*e));
5713
    if (!e)
5714
        return NULL;
5715

    
5716
    e->cb = cb;
5717
    e->opaque = opaque;
5718
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5719
    return e;
5720
}
5721

    
5722
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5723
{
5724
    LIST_REMOVE (e, entries);
5725
    qemu_free (e);
5726
}
5727

    
5728
static void vm_state_notify(int running)
5729
{
5730
    VMChangeStateEntry *e;
5731

    
5732
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5733
        e->cb(e->opaque, running);
5734
    }
5735
}
5736

    
5737
/* XXX: support several handlers */
5738
static VMStopHandler *vm_stop_cb;
5739
static void *vm_stop_opaque;
5740

    
5741
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5742
{
5743
    vm_stop_cb = cb;
5744
    vm_stop_opaque = opaque;
5745
    return 0;
5746
}
5747

    
5748
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5749
{
5750
    vm_stop_cb = NULL;
5751
}
5752

    
5753
void vm_start(void)
5754
{
5755
    if (!vm_running) {
5756
        cpu_enable_ticks();
5757
        vm_running = 1;
5758
        vm_state_notify(1);
5759
    }
5760
}
5761

    
5762
void vm_stop(int reason) 
5763
{
5764
    if (vm_running) {
5765
        cpu_disable_ticks();
5766
        vm_running = 0;
5767
        if (reason != 0) {
5768
            if (vm_stop_cb) {
5769
                vm_stop_cb(vm_stop_opaque, reason);
5770
            }
5771
        }
5772
        vm_state_notify(0);
5773
    }
5774
}
5775

    
5776
/* reset/shutdown handler */
5777

    
5778
typedef struct QEMUResetEntry {
5779
    QEMUResetHandler *func;
5780
    void *opaque;
5781
    struct QEMUResetEntry *next;
5782
} QEMUResetEntry;
5783

    
5784
static QEMUResetEntry *first_reset_entry;
5785
static int reset_requested;
5786
static int shutdown_requested;
5787
static int powerdown_requested;
5788

    
5789
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5790
{
5791
    QEMUResetEntry **pre, *re;
5792

    
5793
    pre = &first_reset_entry;
5794
    while (*pre != NULL)
5795
        pre = &(*pre)->next;
5796
    re = qemu_mallocz(sizeof(QEMUResetEntry));
5797
    re->func = func;
5798
    re->opaque = opaque;
5799
    re->next = NULL;
5800
    *pre = re;
5801
}
5802

    
5803
static void qemu_system_reset(void)
5804
{
5805
    QEMUResetEntry *re;
5806

    
5807
    /* reset all devices */
5808
    for(re = first_reset_entry; re != NULL; re = re->next) {
5809
        re->func(re->opaque);
5810
    }
5811
}
5812

    
5813
void qemu_system_reset_request(void)
5814
{
5815
    if (no_reboot) {
5816
        shutdown_requested = 1;
5817
    } else {
5818
        reset_requested = 1;
5819
    }
5820
    if (cpu_single_env)
5821
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5822
}
5823

    
5824
void qemu_system_shutdown_request(void)
5825
{
5826
    shutdown_requested = 1;
5827
    if (cpu_single_env)
5828
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5829
}
5830

    
5831
void qemu_system_powerdown_request(void)
5832
{
5833
    powerdown_requested = 1;
5834
    if (cpu_single_env)
5835
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5836
}
5837

    
5838
void main_loop_wait(int timeout)
5839
{
5840
    IOHandlerRecord *ioh, *ioh_next;
5841
    fd_set rfds, wfds, xfds;
5842
    int ret, nfds;
5843
    struct timeval tv;
5844
    PollingEntry *pe;
5845

    
5846

    
5847
    /* XXX: need to suppress polling by better using win32 events */
5848
    ret = 0;
5849
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5850
        ret |= pe->func(pe->opaque);
5851
    }
5852
#ifdef _WIN32
5853
    if (ret == 0 && timeout > 0) {
5854
        int err;
5855
        WaitObjects *w = &wait_objects;
5856
        
5857
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5858
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5859
            if (w->func[ret - WAIT_OBJECT_0])
5860
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5861
        } else if (ret == WAIT_TIMEOUT) {
5862
        } else {
5863
            err = GetLastError();
5864
            fprintf(stderr, "Wait error %d %d\n", ret, err);
5865
        }
5866
    }
5867
#endif
5868
    /* poll any events */
5869
    /* XXX: separate device handlers from system ones */
5870
    nfds = -1;
5871
    FD_ZERO(&rfds);
5872
    FD_ZERO(&wfds);
5873
    FD_ZERO(&xfds);
5874
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5875
        if (ioh->fd_read &&
5876
            (!ioh->fd_read_poll ||
5877
             ioh->fd_read_poll(ioh->opaque) != 0)) {
5878
            FD_SET(ioh->fd, &rfds);
5879
            if (ioh->fd > nfds)
5880
                nfds = ioh->fd;
5881
        }
5882
        if (ioh->fd_write) {
5883
            FD_SET(ioh->fd, &wfds);
5884
            if (ioh->fd > nfds)
5885
                nfds = ioh->fd;
5886
        }
5887
    }
5888
    
5889
    tv.tv_sec = 0;
5890
#ifdef _WIN32
5891
    tv.tv_usec = 0;
5892
#else
5893
    tv.tv_usec = timeout * 1000;
5894
#endif
5895
#if defined(CONFIG_SLIRP)
5896
    if (slirp_inited) {
5897
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5898
    }
5899
#endif
5900
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5901
    if (ret > 0) {
5902
        /* XXX: better handling of removal */
5903
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5904
            ioh_next = ioh->next;
5905
            if (FD_ISSET(ioh->fd, &rfds)) {
5906
                ioh->fd_read(ioh->opaque);
5907
            }
5908
            if (FD_ISSET(ioh->fd, &wfds)) {
5909
                ioh->fd_write(ioh->opaque);
5910
            }
5911
        }
5912
    }
5913
#if defined(CONFIG_SLIRP)
5914
    if (slirp_inited) {
5915
        if (ret < 0) {
5916
            FD_ZERO(&rfds);
5917
            FD_ZERO(&wfds);
5918
            FD_ZERO(&xfds);
5919
        }
5920
        slirp_select_poll(&rfds, &wfds, &xfds);
5921
    }
5922
#endif
5923
    qemu_aio_poll();
5924
    qemu_bh_poll();
5925

    
5926
    if (vm_running) {
5927
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
5928
                        qemu_get_clock(vm_clock));
5929
        /* run dma transfers, if any */
5930
        DMA_run();
5931
    }
5932
    
5933
    /* real time timers */
5934
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
5935
                    qemu_get_clock(rt_clock));
5936
}
5937

    
5938
static CPUState *cur_cpu;
5939

    
5940
int main_loop(void)
5941
{
5942
    int ret, timeout;
5943
#ifdef CONFIG_PROFILER
5944
    int64_t ti;
5945
#endif
5946
    CPUState *env;
5947

    
5948
    cur_cpu = first_cpu;
5949
    for(;;) {
5950
        if (vm_running) {
5951

    
5952
            env = cur_cpu;
5953
            for(;;) {
5954
                /* get next cpu */
5955
                env = env->next_cpu;
5956
                if (!env)
5957
                    env = first_cpu;
5958
#ifdef CONFIG_PROFILER
5959
                ti = profile_getclock();
5960
#endif
5961
                ret = cpu_exec(env);
5962
#ifdef CONFIG_PROFILER
5963
                qemu_time += profile_getclock() - ti;
5964
#endif
5965
                if (ret != EXCP_HALTED)
5966
                    break;
5967
                /* all CPUs are halted ? */
5968
                if (env == cur_cpu) {
5969
                    ret = EXCP_HLT;
5970
                    break;
5971
                }
5972
            }
5973
            cur_cpu = env;
5974

    
5975
            if (shutdown_requested) {
5976
                ret = EXCP_INTERRUPT;
5977
                break;
5978
            }
5979
            if (reset_requested) {
5980
                reset_requested = 0;
5981
                qemu_system_reset();
5982
                ret = EXCP_INTERRUPT;
5983
            }
5984
            if (powerdown_requested) {
5985
                powerdown_requested = 0;
5986
                qemu_system_powerdown();
5987
                ret = EXCP_INTERRUPT;
5988
            }
5989
            if (ret == EXCP_DEBUG) {
5990
                vm_stop(EXCP_DEBUG);
5991
            }
5992
            /* if hlt instruction, we wait until the next IRQ */
5993
            /* XXX: use timeout computed from timers */
5994
            if (ret == EXCP_HLT)
5995
                timeout = 10;
5996
            else
5997
                timeout = 0;
5998
        } else {
5999
            timeout = 10;
6000
        }
6001
#ifdef CONFIG_PROFILER
6002
        ti = profile_getclock();
6003
#endif
6004
        main_loop_wait(timeout);
6005
#ifdef CONFIG_PROFILER
6006
        dev_time += profile_getclock() - ti;
6007
#endif
6008
    }
6009
    cpu_disable_ticks();
6010
    return ret;
6011
}
6012

    
6013
void help(void)
6014
{
6015
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6016
           "usage: %s [options] [disk_image]\n"
6017
           "\n"
6018
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6019
           "\n"
6020
           "Standard options:\n"
6021
           "-M machine      select emulated machine (-M ? for list)\n"
6022
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6023
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6024
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6025
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6026
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6027
           "-snapshot       write to temporary files instead of disk image files\n"
6028
#ifdef CONFIG_SDL
6029
           "-no-quit        disable SDL window close capability\n"
6030
#endif
6031
#ifdef TARGET_I386
6032
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6033
#endif
6034
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6035
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
6036
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
6037
#ifndef _WIN32
6038
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
6039
#endif
6040
#ifdef HAS_AUDIO
6041
           "-audio-help     print list of audio drivers and their options\n"
6042
           "-soundhw c1,... enable audio support\n"
6043
           "                and only specified sound cards (comma separated list)\n"
6044
           "                use -soundhw ? to get the list of supported cards\n"
6045
           "                use -soundhw all to enable all of them\n"
6046
#endif
6047
           "-localtime      set the real time clock to local time [default=utc]\n"
6048
           "-full-screen    start in full screen\n"
6049
#ifdef TARGET_I386
6050
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6051
#endif
6052
           "-usb            enable the USB driver (will be the default soon)\n"
6053
           "-usbdevice name add the host or guest USB device 'name'\n"
6054
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6055
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6056
#endif
6057
           "\n"
6058
           "Network options:\n"
6059
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6060
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6061
#ifdef CONFIG_SLIRP
6062
           "-net user[,vlan=n][,hostname=host]\n"
6063
           "                connect the user mode network stack to VLAN 'n' and send\n"
6064
           "                hostname 'host' to DHCP clients\n"
6065
#endif
6066
#ifdef _WIN32
6067
           "-net tap[,vlan=n],ifname=name\n"
6068
           "                connect the host TAP network interface to VLAN 'n'\n"
6069
#else
6070
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6071
           "                connect the host TAP network interface to VLAN 'n' and use\n"
6072
           "                the network script 'file' (default=%s);\n"
6073
           "                use 'script=no' to disable script execution;\n"
6074
           "                use 'fd=h' to connect to an already opened TAP interface\n"
6075
#endif
6076
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6077
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
6078
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6079
           "                connect the vlan 'n' to multicast maddr and port\n"
6080
           "-net none       use it alone to have zero network devices; if no -net option\n"
6081
           "                is provided, the default is '-net nic -net user'\n"
6082
           "\n"
6083
#ifdef CONFIG_SLIRP
6084
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
6085
#ifndef _WIN32
6086
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6087
#endif
6088
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6089
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
6090
#endif
6091
           "\n"
6092
           "Linux boot specific:\n"
6093
           "-kernel bzImage use 'bzImage' as kernel image\n"
6094
           "-append cmdline use 'cmdline' as kernel command line\n"
6095
           "-initrd file    use 'file' as initial ram disk\n"
6096
           "\n"
6097
           "Debug/Expert options:\n"
6098
           "-monitor dev    redirect the monitor to char device 'dev'\n"
6099
           "-serial dev     redirect the serial port to char device 'dev'\n"
6100
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
6101
           "-pidfile file   Write PID to 'file'\n"
6102
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
6103
           "-s              wait gdb connection to port %d\n"
6104
           "-p port         change gdb connection port\n"
6105
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6106
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6107
           "                translation (t=none or lba) (usually qemu can guess them)\n"
6108
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6109
#ifdef USE_KQEMU
6110
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6111
           "-no-kqemu       disable KQEMU kernel module usage\n"
6112
#endif
6113
#ifdef USE_CODE_COPY
6114
           "-no-code-copy   disable code copy acceleration\n"
6115
#endif
6116
#ifdef TARGET_I386
6117
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6118
           "                (default is CL-GD5446 PCI VGA)\n"
6119
           "-no-acpi        disable ACPI\n"
6120
#endif
6121
           "-no-reboot      exit instead of rebooting\n"
6122
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6123
           "-vnc display    start a VNC server on display\n"
6124
#ifndef _WIN32
6125
           "-daemonize      daemonize QEMU after initializing\n"
6126
#endif
6127
           "-option-rom rom load a file, rom, into the option ROM space\n"
6128
           "\n"
6129
           "During emulation, the following keys are useful:\n"
6130
           "ctrl-alt-f      toggle full screen\n"
6131
           "ctrl-alt-n      switch to virtual console 'n'\n"
6132
           "ctrl-alt        toggle mouse and keyboard grab\n"
6133
           "\n"
6134
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
6135
           ,
6136
           "qemu",
6137
           DEFAULT_RAM_SIZE,
6138
#ifndef _WIN32
6139
           DEFAULT_NETWORK_SCRIPT,
6140
#endif
6141
           DEFAULT_GDBSTUB_PORT,
6142
           "/tmp/qemu.log");
6143
    exit(1);
6144
}
6145

    
6146
#define HAS_ARG 0x0001
6147

    
6148
enum {
6149
    QEMU_OPTION_h,
6150

    
6151
    QEMU_OPTION_M,
6152
    QEMU_OPTION_fda,
6153
    QEMU_OPTION_fdb,
6154
    QEMU_OPTION_hda,
6155
    QEMU_OPTION_hdb,
6156
    QEMU_OPTION_hdc,
6157
    QEMU_OPTION_hdd,
6158
    QEMU_OPTION_cdrom,
6159
    QEMU_OPTION_boot,
6160
    QEMU_OPTION_snapshot,
6161
#ifdef TARGET_I386
6162
    QEMU_OPTION_no_fd_bootchk,
6163
#endif
6164
    QEMU_OPTION_m,
6165
    QEMU_OPTION_nographic,
6166
#ifdef HAS_AUDIO
6167
    QEMU_OPTION_audio_help,
6168
    QEMU_OPTION_soundhw,
6169
#endif
6170

    
6171
    QEMU_OPTION_net,
6172
    QEMU_OPTION_tftp,
6173
    QEMU_OPTION_smb,
6174
    QEMU_OPTION_redir,
6175

    
6176
    QEMU_OPTION_kernel,
6177
    QEMU_OPTION_append,
6178
    QEMU_OPTION_initrd,
6179

    
6180
    QEMU_OPTION_S,
6181
    QEMU_OPTION_s,
6182
    QEMU_OPTION_p,
6183
    QEMU_OPTION_d,
6184
    QEMU_OPTION_hdachs,
6185
    QEMU_OPTION_L,
6186
    QEMU_OPTION_no_code_copy,
6187
    QEMU_OPTION_k,
6188
    QEMU_OPTION_localtime,
6189
    QEMU_OPTION_cirrusvga,
6190
    QEMU_OPTION_g,
6191
    QEMU_OPTION_std_vga,
6192
    QEMU_OPTION_monitor,
6193
    QEMU_OPTION_serial,
6194
    QEMU_OPTION_parallel,
6195
    QEMU_OPTION_loadvm,
6196
    QEMU_OPTION_full_screen,
6197
    QEMU_OPTION_no_quit,
6198
    QEMU_OPTION_pidfile,
6199
    QEMU_OPTION_no_kqemu,
6200
    QEMU_OPTION_kernel_kqemu,
6201
    QEMU_OPTION_win2k_hack,
6202
    QEMU_OPTION_usb,
6203
    QEMU_OPTION_usbdevice,
6204
    QEMU_OPTION_smp,
6205
    QEMU_OPTION_vnc,
6206
    QEMU_OPTION_no_acpi,
6207
    QEMU_OPTION_no_reboot,
6208
    QEMU_OPTION_daemonize,
6209
    QEMU_OPTION_option_rom,
6210
    QEMU_OPTION_semihosting
6211
};
6212

    
6213
typedef struct QEMUOption {
6214
    const char *name;
6215
    int flags;
6216
    int index;
6217
} QEMUOption;
6218

    
6219
const QEMUOption qemu_options[] = {
6220
    { "h", 0, QEMU_OPTION_h },
6221
    { "help", 0, QEMU_OPTION_h },
6222

    
6223
    { "M", HAS_ARG, QEMU_OPTION_M },
6224
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6225
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6226
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6227
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6228
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6229
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6230
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6231
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6232
    { "snapshot", 0, QEMU_OPTION_snapshot },
6233
#ifdef TARGET_I386
6234
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6235
#endif
6236
    { "m", HAS_ARG, QEMU_OPTION_m },
6237
    { "nographic", 0, QEMU_OPTION_nographic },
6238
    { "k", HAS_ARG, QEMU_OPTION_k },
6239
#ifdef HAS_AUDIO
6240
    { "audio-help", 0, QEMU_OPTION_audio_help },
6241
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6242
#endif
6243

    
6244
    { "net", HAS_ARG, QEMU_OPTION_net},
6245
#ifdef CONFIG_SLIRP
6246
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6247
#ifndef _WIN32
6248
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6249
#endif
6250
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6251
#endif
6252

    
6253
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6254
    { "append", HAS_ARG, QEMU_OPTION_append },
6255
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6256

    
6257
    { "S", 0, QEMU_OPTION_S },
6258
    { "s", 0, QEMU_OPTION_s },
6259
    { "p", HAS_ARG, QEMU_OPTION_p },
6260
    { "d", HAS_ARG, QEMU_OPTION_d },
6261
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6262
    { "L", HAS_ARG, QEMU_OPTION_L },
6263
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6264
#ifdef USE_KQEMU
6265
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6266
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6267
#endif
6268
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6269
    { "g", 1, QEMU_OPTION_g },
6270
#endif
6271
    { "localtime", 0, QEMU_OPTION_localtime },
6272
    { "std-vga", 0, QEMU_OPTION_std_vga },
6273
    { "monitor", 1, QEMU_OPTION_monitor },
6274
    { "serial", 1, QEMU_OPTION_serial },
6275
    { "parallel", 1, QEMU_OPTION_parallel },
6276
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6277
    { "full-screen", 0, QEMU_OPTION_full_screen },
6278
#ifdef CONFIG_SDL
6279
    { "no-quit", 0, QEMU_OPTION_no_quit },
6280
#endif
6281
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6282
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6283
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6284
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6285
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6286

    
6287
    /* temporary options */
6288
    { "usb", 0, QEMU_OPTION_usb },
6289
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6290
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6291
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
6292
    { "daemonize", 0, QEMU_OPTION_daemonize },
6293
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6294
#if defined(TARGET_ARM)
6295
    { "semihosting", 0, QEMU_OPTION_semihosting },
6296
#endif
6297
    { NULL },
6298
};
6299

    
6300
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6301

    
6302
/* this stack is only used during signal handling */
6303
#define SIGNAL_STACK_SIZE 32768
6304

    
6305
static uint8_t *signal_stack;
6306

    
6307
#endif
6308

    
6309
/* password input */
6310

    
6311
static BlockDriverState *get_bdrv(int index)
6312
{
6313
    BlockDriverState *bs;
6314

    
6315
    if (index < 4) {
6316
        bs = bs_table[index];
6317
    } else if (index < 6) {
6318
        bs = fd_table[index - 4];
6319
    } else {
6320
        bs = NULL;
6321
    }
6322
    return bs;
6323
}
6324

    
6325
static void read_passwords(void)
6326
{
6327
    BlockDriverState *bs;
6328
    int i, j;
6329
    char password[256];
6330

    
6331
    for(i = 0; i < 6; i++) {
6332
        bs = get_bdrv(i);
6333
        if (bs && bdrv_is_encrypted(bs)) {
6334
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6335
            for(j = 0; j < 3; j++) {
6336
                monitor_readline("Password: ", 
6337
                                 1, password, sizeof(password));
6338
                if (bdrv_set_key(bs, password) == 0)
6339
                    break;
6340
                term_printf("invalid password\n");
6341
            }
6342
        }
6343
    }
6344
}
6345

    
6346
/* XXX: currently we cannot use simultaneously different CPUs */
6347
void register_machines(void)
6348
{
6349
#if defined(TARGET_I386)
6350
    qemu_register_machine(&pc_machine);
6351
    qemu_register_machine(&isapc_machine);
6352
#elif defined(TARGET_PPC)
6353
    qemu_register_machine(&heathrow_machine);
6354
    qemu_register_machine(&core99_machine);
6355
    qemu_register_machine(&prep_machine);
6356
#elif defined(TARGET_MIPS)
6357
    qemu_register_machine(&mips_machine);
6358
    qemu_register_machine(&mips_malta_machine);
6359
#elif defined(TARGET_SPARC)
6360
#ifdef TARGET_SPARC64
6361
    qemu_register_machine(&sun4u_machine);
6362
#else
6363
    qemu_register_machine(&sun4m_machine);
6364
#endif
6365
#elif defined(TARGET_ARM)
6366
    qemu_register_machine(&integratorcp926_machine);
6367
    qemu_register_machine(&integratorcp1026_machine);
6368
    qemu_register_machine(&versatilepb_machine);
6369
    qemu_register_machine(&versatileab_machine);
6370
    qemu_register_machine(&realview_machine);
6371
#elif defined(TARGET_SH4)
6372
    qemu_register_machine(&shix_machine);
6373
#else
6374
#error unsupported CPU
6375
#endif
6376
}
6377

    
6378
#ifdef HAS_AUDIO
6379
struct soundhw soundhw[] = {
6380
#ifdef TARGET_I386
6381
    {
6382
        "pcspk",
6383
        "PC speaker",
6384
        0,
6385
        1,
6386
        { .init_isa = pcspk_audio_init }
6387
    },
6388
#endif
6389
    {
6390
        "sb16",
6391
        "Creative Sound Blaster 16",
6392
        0,
6393
        1,
6394
        { .init_isa = SB16_init }
6395
    },
6396

    
6397
#ifdef CONFIG_ADLIB
6398
    {
6399
        "adlib",
6400
#ifdef HAS_YMF262
6401
        "Yamaha YMF262 (OPL3)",
6402
#else
6403
        "Yamaha YM3812 (OPL2)",
6404
#endif
6405
        0,
6406
        1,
6407
        { .init_isa = Adlib_init }
6408
    },
6409
#endif
6410

    
6411
#ifdef CONFIG_GUS
6412
    {
6413
        "gus",
6414
        "Gravis Ultrasound GF1",
6415
        0,
6416
        1,
6417
        { .init_isa = GUS_init }
6418
    },
6419
#endif
6420

    
6421
    {
6422
        "es1370",
6423
        "ENSONIQ AudioPCI ES1370",
6424
        0,
6425
        0,
6426
        { .init_pci = es1370_init }
6427
    },
6428

    
6429
    { NULL, NULL, 0, 0, { NULL } }
6430
};
6431

    
6432
static void select_soundhw (const char *optarg)
6433
{
6434
    struct soundhw *c;
6435

    
6436
    if (*optarg == '?') {
6437
    show_valid_cards:
6438

    
6439
        printf ("Valid sound card names (comma separated):\n");
6440
        for (c = soundhw; c->name; ++c) {
6441
            printf ("%-11s %s\n", c->name, c->descr);
6442
        }
6443
        printf ("\n-soundhw all will enable all of the above\n");
6444
        exit (*optarg != '?');
6445
    }
6446
    else {
6447
        size_t l;
6448
        const char *p;
6449
        char *e;
6450
        int bad_card = 0;
6451

    
6452
        if (!strcmp (optarg, "all")) {
6453
            for (c = soundhw; c->name; ++c) {
6454
                c->enabled = 1;
6455
            }
6456
            return;
6457
        }
6458

    
6459
        p = optarg;
6460
        while (*p) {
6461
            e = strchr (p, ',');
6462
            l = !e ? strlen (p) : (size_t) (e - p);
6463

    
6464
            for (c = soundhw; c->name; ++c) {
6465
                if (!strncmp (c->name, p, l)) {
6466
                    c->enabled = 1;
6467
                    break;
6468
                }
6469
            }
6470

    
6471
            if (!c->name) {
6472
                if (l > 80) {
6473
                    fprintf (stderr,
6474
                             "Unknown sound card name (too big to show)\n");
6475
                }
6476
                else {
6477
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
6478
                             (int) l, p);
6479
                }
6480
                bad_card = 1;
6481
            }
6482
            p += l + (e != NULL);
6483
        }
6484

    
6485
        if (bad_card)
6486
            goto show_valid_cards;
6487
    }
6488
}
6489
#endif
6490

    
6491
#ifdef _WIN32
6492
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6493
{
6494
    exit(STATUS_CONTROL_C_EXIT);
6495
    return TRUE;
6496
}
6497
#endif
6498

    
6499
#define MAX_NET_CLIENTS 32
6500

    
6501
int main(int argc, char **argv)
6502
{
6503
#ifdef CONFIG_GDBSTUB
6504
    int use_gdbstub, gdbstub_port;
6505
#endif
6506
    int i, cdrom_index;
6507
    int snapshot, linux_boot;
6508
    const char *initrd_filename;
6509
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6510
    const char *kernel_filename, *kernel_cmdline;
6511
    DisplayState *ds = &display_state;
6512
    int cyls, heads, secs, translation;
6513
    char net_clients[MAX_NET_CLIENTS][256];
6514
    int nb_net_clients;
6515
    int optind;
6516
    const char *r, *optarg;
6517
    CharDriverState *monitor_hd;
6518
    char monitor_device[128];
6519
    char serial_devices[MAX_SERIAL_PORTS][128];
6520
    int serial_device_index;
6521
    char parallel_devices[MAX_PARALLEL_PORTS][128];
6522
    int parallel_device_index;
6523
    const char *loadvm = NULL;
6524
    QEMUMachine *machine;
6525
    char usb_devices[MAX_USB_CMDLINE][128];
6526
    int usb_devices_index;
6527
    int fds[2];
6528

    
6529
    LIST_INIT (&vm_change_state_head);
6530
#ifndef _WIN32
6531
    {
6532
        struct sigaction act;
6533
        sigfillset(&act.sa_mask);
6534
        act.sa_flags = 0;
6535
        act.sa_handler = SIG_IGN;
6536
        sigaction(SIGPIPE, &act, NULL);
6537
    }
6538
#else
6539
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6540
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
6541
       QEMU to run on a single CPU */
6542
    {
6543
        HANDLE h;
6544
        DWORD mask, smask;
6545
        int i;
6546
        h = GetCurrentProcess();
6547
        if (GetProcessAffinityMask(h, &mask, &smask)) {
6548
            for(i = 0; i < 32; i++) {
6549
                if (mask & (1 << i))
6550
                    break;
6551
            }
6552
            if (i != 32) {
6553
                mask = 1 << i;
6554
                SetProcessAffinityMask(h, mask);
6555
            }
6556
        }
6557
    }
6558
#endif
6559

    
6560
    register_machines();
6561
    machine = first_machine;
6562
    initrd_filename = NULL;
6563
    for(i = 0; i < MAX_FD; i++)
6564
        fd_filename[i] = NULL;
6565
    for(i = 0; i < MAX_DISKS; i++)
6566
        hd_filename[i] = NULL;
6567
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6568
    vga_ram_size = VGA_RAM_SIZE;
6569
#ifdef CONFIG_GDBSTUB
6570
    use_gdbstub = 0;
6571
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
6572
#endif
6573
    snapshot = 0;
6574
    nographic = 0;
6575
    kernel_filename = NULL;
6576
    kernel_cmdline = "";
6577
#ifdef TARGET_PPC
6578
    cdrom_index = 1;
6579
#else
6580
    cdrom_index = 2;
6581
#endif
6582
    cyls = heads = secs = 0;
6583
    translation = BIOS_ATA_TRANSLATION_AUTO;
6584
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6585

    
6586
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6587
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
6588
        serial_devices[i][0] = '\0';
6589
    serial_device_index = 0;
6590
    
6591
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6592
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6593
        parallel_devices[i][0] = '\0';
6594
    parallel_device_index = 0;
6595
    
6596
    usb_devices_index = 0;
6597
    
6598
    nb_net_clients = 0;
6599

    
6600
    nb_nics = 0;
6601
    /* default mac address of the first network interface */
6602
    
6603
    optind = 1;
6604
    for(;;) {
6605
        if (optind >= argc)
6606
            break;
6607
        r = argv[optind];
6608
        if (r[0] != '-') {
6609
            hd_filename[0] = argv[optind++];
6610
        } else {
6611
            const QEMUOption *popt;
6612

    
6613
            optind++;
6614
            /* Treat --foo the same as -foo.  */
6615
            if (r[1] == '-')
6616
                r++;
6617
            popt = qemu_options;
6618
            for(;;) {
6619
                if (!popt->name) {
6620
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
6621
                            argv[0], r);
6622
                    exit(1);
6623
                }
6624
                if (!strcmp(popt->name, r + 1))
6625
                    break;
6626
                popt++;
6627
            }
6628
            if (popt->flags & HAS_ARG) {
6629
                if (optind >= argc) {
6630
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
6631
                            argv[0], r);
6632
                    exit(1);
6633
                }
6634
                optarg = argv[optind++];
6635
            } else {
6636
                optarg = NULL;
6637
            }
6638

    
6639
            switch(popt->index) {
6640
            case QEMU_OPTION_M:
6641
                machine = find_machine(optarg);
6642
                if (!machine) {
6643
                    QEMUMachine *m;
6644
                    printf("Supported machines are:\n");
6645
                    for(m = first_machine; m != NULL; m = m->next) {
6646
                        printf("%-10s %s%s\n",
6647
                               m->name, m->desc, 
6648
                               m == first_machine ? " (default)" : "");
6649
                    }
6650
                    exit(1);
6651
                }
6652
                break;
6653
            case QEMU_OPTION_initrd:
6654
                initrd_filename = optarg;
6655
                break;
6656
            case QEMU_OPTION_hda:
6657
            case QEMU_OPTION_hdb:
6658
            case QEMU_OPTION_hdc:
6659
            case QEMU_OPTION_hdd:
6660
                {
6661
                    int hd_index;
6662
                    hd_index = popt->index - QEMU_OPTION_hda;
6663
                    hd_filename[hd_index] = optarg;
6664
                    if (hd_index == cdrom_index)
6665
                        cdrom_index = -1;
6666
                }
6667
                break;
6668
            case QEMU_OPTION_snapshot:
6669
                snapshot = 1;
6670
                break;
6671
            case QEMU_OPTION_hdachs:
6672
                {
6673
                    const char *p;
6674
                    p = optarg;
6675
                    cyls = strtol(p, (char **)&p, 0);
6676
                    if (cyls < 1 || cyls > 16383)
6677
                        goto chs_fail;
6678
                    if (*p != ',')
6679
                        goto chs_fail;
6680
                    p++;
6681
                    heads = strtol(p, (char **)&p, 0);
6682
                    if (heads < 1 || heads > 16)
6683
                        goto chs_fail;
6684
                    if (*p != ',')
6685
                        goto chs_fail;
6686
                    p++;
6687
                    secs = strtol(p, (char **)&p, 0);
6688
                    if (secs < 1 || secs > 63)
6689
                        goto chs_fail;
6690
                    if (*p == ',') {
6691
                        p++;
6692
                        if (!strcmp(p, "none"))
6693
                            translation = BIOS_ATA_TRANSLATION_NONE;
6694
                        else if (!strcmp(p, "lba"))
6695
                            translation = BIOS_ATA_TRANSLATION_LBA;
6696
                        else if (!strcmp(p, "auto"))
6697
                            translation = BIOS_ATA_TRANSLATION_AUTO;
6698
                        else
6699
                            goto chs_fail;
6700
                    } else if (*p != '\0') {
6701
                    chs_fail:
6702
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
6703
                        exit(1);
6704
                    }
6705
                }
6706
                break;
6707
            case QEMU_OPTION_nographic:
6708
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6709
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6710
                nographic = 1;
6711
                break;
6712
            case QEMU_OPTION_kernel:
6713
                kernel_filename = optarg;
6714
                break;
6715
            case QEMU_OPTION_append:
6716
                kernel_cmdline = optarg;
6717
                break;
6718
            case QEMU_OPTION_cdrom:
6719
                if (cdrom_index >= 0) {
6720
                    hd_filename[cdrom_index] = optarg;
6721
                }
6722
                break;
6723
            case QEMU_OPTION_boot:
6724
                boot_device = optarg[0];
6725
                if (boot_device != 'a' && 
6726
#if defined(TARGET_SPARC) || defined(TARGET_I386)
6727
                    // Network boot
6728
                    boot_device != 'n' &&
6729
#endif
6730
                    boot_device != 'c' && boot_device != 'd') {
6731
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6732
                    exit(1);
6733
                }
6734
                break;
6735
            case QEMU_OPTION_fda:
6736
                fd_filename[0] = optarg;
6737
                break;
6738
            case QEMU_OPTION_fdb:
6739
                fd_filename[1] = optarg;
6740
                break;
6741
#ifdef TARGET_I386
6742
            case QEMU_OPTION_no_fd_bootchk:
6743
                fd_bootchk = 0;
6744
                break;
6745
#endif
6746
            case QEMU_OPTION_no_code_copy:
6747
                code_copy_enabled = 0;
6748
                break;
6749
            case QEMU_OPTION_net:
6750
                if (nb_net_clients >= MAX_NET_CLIENTS) {
6751
                    fprintf(stderr, "qemu: too many network clients\n");
6752
                    exit(1);
6753
                }
6754
                pstrcpy(net_clients[nb_net_clients],
6755
                        sizeof(net_clients[0]),
6756
                        optarg);
6757
                nb_net_clients++;
6758
                break;
6759
#ifdef CONFIG_SLIRP
6760
            case QEMU_OPTION_tftp:
6761
                tftp_prefix = optarg;
6762
                break;
6763
#ifndef _WIN32
6764
            case QEMU_OPTION_smb:
6765
                net_slirp_smb(optarg);
6766
                break;
6767
#endif
6768
            case QEMU_OPTION_redir:
6769
                net_slirp_redir(optarg);                
6770
                break;
6771
#endif
6772
#ifdef HAS_AUDIO
6773
            case QEMU_OPTION_audio_help:
6774
                AUD_help ();
6775
                exit (0);
6776
                break;
6777
            case QEMU_OPTION_soundhw:
6778
                select_soundhw (optarg);
6779
                break;
6780
#endif
6781
            case QEMU_OPTION_h:
6782
                help();
6783
                break;
6784
            case QEMU_OPTION_m:
6785
                ram_size = atoi(optarg) * 1024 * 1024;
6786
                if (ram_size <= 0)
6787
                    help();
6788
                if (ram_size > PHYS_RAM_MAX_SIZE) {
6789
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6790
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
6791
                    exit(1);
6792
                }
6793
                break;
6794
            case QEMU_OPTION_d:
6795
                {
6796
                    int mask;
6797
                    CPULogItem *item;
6798
                    
6799
                    mask = cpu_str_to_log_mask(optarg);
6800
                    if (!mask) {
6801
                        printf("Log items (comma separated):\n");
6802
                    for(item = cpu_log_items; item->mask != 0; item++) {
6803
                        printf("%-10s %s\n", item->name, item->help);
6804
                    }
6805
                    exit(1);
6806
                    }
6807
                    cpu_set_log(mask);
6808
                }
6809
                break;
6810
#ifdef CONFIG_GDBSTUB
6811
            case QEMU_OPTION_s:
6812
                use_gdbstub = 1;
6813
                break;
6814
            case QEMU_OPTION_p:
6815
                gdbstub_port = atoi(optarg);
6816
                break;
6817
#endif
6818
            case QEMU_OPTION_L:
6819
                bios_dir = optarg;
6820
                break;
6821
            case QEMU_OPTION_S:
6822
                autostart = 0;
6823
                break;
6824
            case QEMU_OPTION_k:
6825
                keyboard_layout = optarg;
6826
                break;
6827
            case QEMU_OPTION_localtime:
6828
                rtc_utc = 0;
6829
                break;
6830
            case QEMU_OPTION_cirrusvga:
6831
                cirrus_vga_enabled = 1;
6832
                break;
6833
            case QEMU_OPTION_std_vga:
6834
                cirrus_vga_enabled = 0;
6835
                break;
6836
            case QEMU_OPTION_g:
6837
                {
6838
                    const char *p;
6839
                    int w, h, depth;
6840
                    p = optarg;
6841
                    w = strtol(p, (char **)&p, 10);
6842
                    if (w <= 0) {
6843
                    graphic_error:
6844
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
6845
                        exit(1);
6846
                    }
6847
                    if (*p != 'x')
6848
                        goto graphic_error;
6849
                    p++;
6850
                    h = strtol(p, (char **)&p, 10);
6851
                    if (h <= 0)
6852
                        goto graphic_error;
6853
                    if (*p == 'x') {
6854
                        p++;
6855
                        depth = strtol(p, (char **)&p, 10);
6856
                        if (depth != 8 && depth != 15 && depth != 16 && 
6857
                            depth != 24 && depth != 32)
6858
                            goto graphic_error;
6859
                    } else if (*p == '\0') {
6860
                        depth = graphic_depth;
6861
                    } else {
6862
                        goto graphic_error;
6863
                    }
6864
                    
6865
                    graphic_width = w;
6866
                    graphic_height = h;
6867
                    graphic_depth = depth;
6868
                }
6869
                break;
6870
            case QEMU_OPTION_monitor:
6871
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6872
                break;
6873
            case QEMU_OPTION_serial:
6874
                if (serial_device_index >= MAX_SERIAL_PORTS) {
6875
                    fprintf(stderr, "qemu: too many serial ports\n");
6876
                    exit(1);
6877
                }
6878
                pstrcpy(serial_devices[serial_device_index], 
6879
                        sizeof(serial_devices[0]), optarg);
6880
                serial_device_index++;
6881
                break;
6882
            case QEMU_OPTION_parallel:
6883
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6884
                    fprintf(stderr, "qemu: too many parallel ports\n");
6885
                    exit(1);
6886
                }
6887
                pstrcpy(parallel_devices[parallel_device_index], 
6888
                        sizeof(parallel_devices[0]), optarg);
6889
                parallel_device_index++;
6890
                break;
6891
            case QEMU_OPTION_loadvm:
6892
                loadvm = optarg;
6893
                break;
6894
            case QEMU_OPTION_full_screen:
6895
                full_screen = 1;
6896
                break;
6897
#ifdef CONFIG_SDL
6898
            case QEMU_OPTION_no_quit:
6899
                no_quit = 1;
6900
                break;
6901
#endif
6902
            case QEMU_OPTION_pidfile:
6903
                create_pidfile(optarg);
6904
                break;
6905
#ifdef TARGET_I386
6906
            case QEMU_OPTION_win2k_hack:
6907
                win2k_install_hack = 1;
6908
                break;
6909
#endif
6910
#ifdef USE_KQEMU
6911
            case QEMU_OPTION_no_kqemu:
6912
                kqemu_allowed = 0;
6913
                break;
6914
            case QEMU_OPTION_kernel_kqemu:
6915
                kqemu_allowed = 2;
6916
                break;
6917
#endif
6918
            case QEMU_OPTION_usb:
6919
                usb_enabled = 1;
6920
                break;
6921
            case QEMU_OPTION_usbdevice:
6922
                usb_enabled = 1;
6923
                if (usb_devices_index >= MAX_USB_CMDLINE) {
6924
                    fprintf(stderr, "Too many USB devices\n");
6925
                    exit(1);
6926
                }
6927
                pstrcpy(usb_devices[usb_devices_index],
6928
                        sizeof(usb_devices[usb_devices_index]),
6929
                        optarg);
6930
                usb_devices_index++;
6931
                break;
6932
            case QEMU_OPTION_smp:
6933
                smp_cpus = atoi(optarg);
6934
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6935
                    fprintf(stderr, "Invalid number of CPUs\n");
6936
                    exit(1);
6937
                }
6938
                break;
6939
            case QEMU_OPTION_vnc:
6940
                vnc_display = optarg;
6941
                break;
6942
            case QEMU_OPTION_no_acpi:
6943
                acpi_enabled = 0;
6944
                break;
6945
            case QEMU_OPTION_no_reboot:
6946
                no_reboot = 1;
6947
                break;
6948
            case QEMU_OPTION_daemonize:
6949
                daemonize = 1;
6950
                break;
6951
            case QEMU_OPTION_option_rom:
6952
                if (nb_option_roms >= MAX_OPTION_ROMS) {
6953
                    fprintf(stderr, "Too many option ROMs\n");
6954
                    exit(1);
6955
                }
6956
                option_rom[nb_option_roms] = optarg;
6957
                nb_option_roms++;
6958
                break;
6959
            case QEMU_OPTION_semihosting:
6960
                semihosting_enabled = 1;
6961
                break;
6962
            }
6963
        }
6964
    }
6965

    
6966
#ifndef _WIN32
6967
    if (daemonize && !nographic && vnc_display == NULL) {
6968
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
6969
        daemonize = 0;
6970
    }
6971

    
6972
    if (daemonize) {
6973
        pid_t pid;
6974

    
6975
        if (pipe(fds) == -1)
6976
            exit(1);
6977

    
6978
        pid = fork();
6979
        if (pid > 0) {
6980
            uint8_t status;
6981
            ssize_t len;
6982

    
6983
            close(fds[1]);
6984

    
6985
        again:
6986
            len = read(fds[0], &status, 1);
6987
            if (len == -1 && (errno == EINTR))
6988
                goto again;
6989
            
6990
            if (len != 1 || status != 0)
6991
                exit(1);
6992
            else
6993
                exit(0);
6994
        } else if (pid < 0)
6995
            exit(1);
6996

    
6997
        setsid();
6998

    
6999
        pid = fork();
7000
        if (pid > 0)
7001
            exit(0);
7002
        else if (pid < 0)
7003
            exit(1);
7004

    
7005
        umask(027);
7006
        chdir("/");
7007

    
7008
        signal(SIGTSTP, SIG_IGN);
7009
        signal(SIGTTOU, SIG_IGN);
7010
        signal(SIGTTIN, SIG_IGN);
7011
    }
7012
#endif
7013

    
7014
#ifdef USE_KQEMU
7015
    if (smp_cpus > 1)
7016
        kqemu_allowed = 0;
7017
#endif
7018
    linux_boot = (kernel_filename != NULL);
7019

    
7020
    if (!linux_boot &&
7021
        hd_filename[0] == '\0' && 
7022
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7023
        fd_filename[0] == '\0')
7024
        help();
7025

    
7026
    /* boot to floppy or the default cd if no hard disk defined yet */
7027
    if (hd_filename[0] == '\0' && boot_device == 'c') {
7028
        if (fd_filename[0] != '\0')
7029
            boot_device = 'a';
7030
        else
7031
            boot_device = 'd';
7032
    }
7033

    
7034
    setvbuf(stdout, NULL, _IOLBF, 0);
7035
    
7036
    init_timers();
7037
    init_timer_alarm();
7038
    qemu_aio_init();
7039

    
7040
#ifdef _WIN32
7041
    socket_init();
7042
#endif
7043

    
7044
    /* init network clients */
7045
    if (nb_net_clients == 0) {
7046
        /* if no clients, we use a default config */
7047
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
7048
                "nic");
7049
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
7050
                "user");
7051
        nb_net_clients = 2;
7052
    }
7053

    
7054
    for(i = 0;i < nb_net_clients; i++) {
7055
        if (net_client_init(net_clients[i]) < 0)
7056
            exit(1);
7057
    }
7058

    
7059
#ifdef TARGET_I386
7060
    if (boot_device == 'n') {
7061
        for (i = 0; i < nb_nics; i++) {
7062
            const char *model = nd_table[i].model;
7063
            char buf[1024];
7064
            if (model == NULL)
7065
                model = "ne2k_pci";
7066
            snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7067
            if (get_image_size(buf) > 0) {
7068
                option_rom[nb_option_roms] = strdup(buf);
7069
                nb_option_roms++;
7070
                break;
7071
            }
7072
        }
7073
        if (i == nb_nics) {
7074
            fprintf(stderr, "No valid PXE rom found for network device\n");
7075
            exit(1);
7076
        }
7077
        boot_device = 'c'; /* to prevent confusion by the BIOS */
7078
    }
7079
#endif
7080

    
7081
    /* init the memory */
7082
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7083

    
7084
    phys_ram_base = qemu_vmalloc(phys_ram_size);
7085
    if (!phys_ram_base) {
7086
        fprintf(stderr, "Could not allocate physical memory\n");
7087
        exit(1);
7088
    }
7089

    
7090
    /* we always create the cdrom drive, even if no disk is there */
7091
    bdrv_init();
7092
    if (cdrom_index >= 0) {
7093
        bs_table[cdrom_index] = bdrv_new("cdrom");
7094
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7095
    }
7096

    
7097
    /* open the virtual block devices */
7098
    for(i = 0; i < MAX_DISKS; i++) {
7099
        if (hd_filename[i]) {
7100
            if (!bs_table[i]) {
7101
                char buf[64];
7102
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7103
                bs_table[i] = bdrv_new(buf);
7104
            }
7105
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7106
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7107
                        hd_filename[i]);
7108
                exit(1);
7109
            }
7110
            if (i == 0 && cyls != 0) {
7111
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7112
                bdrv_set_translation_hint(bs_table[i], translation);
7113
            }
7114
        }
7115
    }
7116

    
7117
    /* we always create at least one floppy disk */
7118
    fd_table[0] = bdrv_new("fda");
7119
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7120

    
7121
    for(i = 0; i < MAX_FD; i++) {
7122
        if (fd_filename[i]) {
7123
            if (!fd_table[i]) {
7124
                char buf[64];
7125
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7126
                fd_table[i] = bdrv_new(buf);
7127
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7128
            }
7129
            if (fd_filename[i] != '\0') {
7130
                if (bdrv_open(fd_table[i], fd_filename[i],
7131
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7132
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7133
                            fd_filename[i]);
7134
                    exit(1);
7135
                }
7136
            }
7137
        }
7138
    }
7139

    
7140
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7141
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7142

    
7143
    init_ioports();
7144

    
7145
    /* terminal init */
7146
    if (nographic) {
7147
        dumb_display_init(ds);
7148
    } else if (vnc_display != NULL) {
7149
        vnc_display_init(ds, vnc_display);
7150
    } else {
7151
#if defined(CONFIG_SDL)
7152
        sdl_display_init(ds, full_screen);
7153
#elif defined(CONFIG_COCOA)
7154
        cocoa_display_init(ds, full_screen);
7155
#else
7156
        dumb_display_init(ds);
7157
#endif
7158
    }
7159

    
7160
    monitor_hd = qemu_chr_open(monitor_device);
7161
    if (!monitor_hd) {
7162
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7163
        exit(1);
7164
    }
7165
    monitor_init(monitor_hd, !nographic);
7166

    
7167
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7168
        const char *devname = serial_devices[i];
7169
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7170
            serial_hds[i] = qemu_chr_open(devname);
7171
            if (!serial_hds[i]) {
7172
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7173
                        devname);
7174
                exit(1);
7175
            }
7176
            if (!strcmp(devname, "vc"))
7177
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7178
        }
7179
    }
7180

    
7181
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7182
        const char *devname = parallel_devices[i];
7183
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7184
            parallel_hds[i] = qemu_chr_open(devname);
7185
            if (!parallel_hds[i]) {
7186
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7187
                        devname);
7188
                exit(1);
7189
            }
7190
            if (!strcmp(devname, "vc"))
7191
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7192
        }
7193
    }
7194

    
7195
    machine->init(ram_size, vga_ram_size, boot_device,
7196
                  ds, fd_filename, snapshot,
7197
                  kernel_filename, kernel_cmdline, initrd_filename);
7198

    
7199
    /* init USB devices */
7200
    if (usb_enabled) {
7201
        for(i = 0; i < usb_devices_index; i++) {
7202
            if (usb_device_add(usb_devices[i]) < 0) {
7203
                fprintf(stderr, "Warning: could not add USB device %s\n",
7204
                        usb_devices[i]);
7205
            }
7206
        }
7207
    }
7208

    
7209
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7210
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7211

    
7212
#ifdef CONFIG_GDBSTUB
7213
    if (use_gdbstub) {
7214
        /* XXX: use standard host:port notation and modify options
7215
           accordingly. */
7216
        if (gdbserver_start_port(gdbstub_port) < 0) {
7217
            fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7218
                    gdbstub_port);
7219
            exit(1);
7220
        }
7221
    } else 
7222
#endif
7223
    if (loadvm)
7224
        do_loadvm(loadvm);
7225

    
7226
    {
7227
        /* XXX: simplify init */
7228
        read_passwords();
7229
        if (autostart) {
7230
            vm_start();
7231
        }
7232
    }
7233

    
7234
    if (daemonize) {
7235
        uint8_t status = 0;
7236
        ssize_t len;
7237
        int fd;
7238

    
7239
    again1:
7240
        len = write(fds[1], &status, 1);
7241
        if (len == -1 && (errno == EINTR))
7242
            goto again1;
7243

    
7244
        if (len != 1)
7245
            exit(1);
7246

    
7247
        fd = open("/dev/null", O_RDWR);
7248
        if (fd == -1)
7249
            exit(1);
7250

    
7251
        dup2(fd, 0);
7252
        dup2(fd, 1);
7253
        dup2(fd, 2);
7254

    
7255
        close(fd);
7256
    }
7257

    
7258
    main_loop();
7259
    quit_timers();
7260
    return 0;
7261
}