Statistics
| Branch: | Revision:

root / vl.c @ 17c275d9

History | View | Annotate | Download (184.7 kB)

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

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

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

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

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

    
74
#include "qemu_socket.h"
75

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

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

    
87
#include "disas.h"
88

    
89
#include "exec-all.h"
90

    
91
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92
#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
int bios_size;
129
static DisplayState display_state;
130
int nographic;
131
const char* keyboard_layout = NULL;
132
int64_t ticks_per_sec;
133
int boot_device = 'c';
134
int ram_size;
135
int pit_min_timer_count = 0;
136
int nb_nics;
137
NICInfo nd_table[MAX_NICS];
138
QEMUTimer *gui_timer;
139
int vm_running;
140
int rtc_utc = 1;
141
int cirrus_vga_enabled = 1;
142
#ifdef TARGET_SPARC
143
int graphic_width = 1024;
144
int graphic_height = 768;
145
#else
146
int graphic_width = 800;
147
int graphic_height = 600;
148
#endif
149
int graphic_depth = 15;
150
int full_screen = 0;
151
int no_quit = 0;
152
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
153
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
154
#ifdef TARGET_I386
155
int win2k_install_hack = 0;
156
#endif
157
int usb_enabled = 0;
158
static VLANState *first_vlan;
159
int smp_cpus = 1;
160
const char *vnc_display;
161
#if defined(TARGET_SPARC)
162
#define MAX_CPUS 16
163
#elif defined(TARGET_I386)
164
#define MAX_CPUS 255
165
#else
166
#define MAX_CPUS 1
167
#endif
168
int acpi_enabled = 1;
169
int fd_bootchk = 1;
170
int no_reboot = 0;
171
int daemonize = 0;
172
const char *option_rom[MAX_OPTION_ROMS];
173
int nb_option_roms;
174
int semihosting_enabled = 0;
175
int autostart = 1;
176

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
309
/***********************************************************/
310

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

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

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

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

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

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

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

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

    
417
/***********************************************************/
418
/* keyboard/mouse */
419

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

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

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

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

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

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

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

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

    
459
    return s;
460
}
461

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

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

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

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

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

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

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

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

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

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

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

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

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

    
526
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
527
}
528

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

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

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

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

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

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

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

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

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

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

    
599
#define QEMU_TIMER_BASE 1000000000LL
600

    
601
#ifdef WIN32
602

    
603
static int64_t clock_freq;
604

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

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

    
624
#else
625

    
626
static int use_rt_clock;
627

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

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

    
659
#endif
660

    
661
/***********************************************************/
662
/* guest cycle counter */
663

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

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

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

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

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

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

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

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

    
739
QEMUClock *rt_clock;
740
QEMUClock *vm_clock;
741

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

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

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

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

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

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

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

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

    
804
    qemu_del_timer(ts);
805

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

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

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

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

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

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

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

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

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

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

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

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

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

    
982
#ifndef _WIN32
983

    
984
#if defined(__linux__)
985

    
986
#define RTC_FREQ 1024
987

    
988
static int rtc_fd;
989

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

    
1010
#else
1011

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

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

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

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

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

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

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

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

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

    
1119
/***********************************************************/
1120
/* character device */
1121

    
1122
static void qemu_chr_reset_bh(void *opaque)
1123
{
1124
    CharDriverState *s = opaque;
1125
    if (s->chr_event)
1126
        s->chr_event(s, CHR_EVENT_RESET);
1127
    qemu_bh_delete(s->bh);
1128
    s->bh = NULL;
1129
}
1130

    
1131
void qemu_chr_reset(CharDriverState *s)
1132
{
1133
    if (s->bh == NULL) {
1134
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1135
        qemu_bh_schedule(s->bh);
1136
    }
1137
}
1138

    
1139
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1140
{
1141
    return s->chr_write(s, buf, len);
1142
}
1143

    
1144
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1145
{
1146
    if (!s->chr_ioctl)
1147
        return -ENOTSUP;
1148
    return s->chr_ioctl(s, cmd, arg);
1149
}
1150

    
1151
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1152
{
1153
    char buf[4096];
1154
    va_list ap;
1155
    va_start(ap, fmt);
1156
    vsnprintf(buf, sizeof(buf), fmt, ap);
1157
    qemu_chr_write(s, buf, strlen(buf));
1158
    va_end(ap);
1159
}
1160

    
1161
void qemu_chr_send_event(CharDriverState *s, int event)
1162
{
1163
    if (s->chr_send_event)
1164
        s->chr_send_event(s, event);
1165
}
1166

    
1167
void qemu_chr_add_read_handler(CharDriverState *s, 
1168
                               IOCanRWHandler *fd_can_read, 
1169
                               IOReadHandler *fd_read, void *opaque)
1170
{
1171
    s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1172
}
1173
             
1174
void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1175
{
1176
    s->chr_event = chr_event;
1177
}
1178

    
1179
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1180
{
1181
    return len;
1182
}
1183

    
1184
static void null_chr_add_read_handler(CharDriverState *chr, 
1185
                                    IOCanRWHandler *fd_can_read, 
1186
                                    IOReadHandler *fd_read, void *opaque)
1187
{
1188
}
1189

    
1190
static CharDriverState *qemu_chr_open_null(void)
1191
{
1192
    CharDriverState *chr;
1193

    
1194
    chr = qemu_mallocz(sizeof(CharDriverState));
1195
    if (!chr)
1196
        return NULL;
1197
    chr->chr_write = null_chr_write;
1198
    chr->chr_add_read_handler = null_chr_add_read_handler;
1199
    return chr;
1200
}
1201

    
1202
#ifdef _WIN32
1203

    
1204
static void socket_cleanup(void)
1205
{
1206
    WSACleanup();
1207
}
1208

    
1209
static int socket_init(void)
1210
{
1211
    WSADATA Data;
1212
    int ret, err;
1213

    
1214
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1215
    if (ret != 0) {
1216
        err = WSAGetLastError();
1217
        fprintf(stderr, "WSAStartup: %d\n", err);
1218
        return -1;
1219
    }
1220
    atexit(socket_cleanup);
1221
    return 0;
1222
}
1223

    
1224
static int send_all(int fd, const uint8_t *buf, int len1)
1225
{
1226
    int ret, len;
1227
    
1228
    len = len1;
1229
    while (len > 0) {
1230
        ret = send(fd, buf, len, 0);
1231
        if (ret < 0) {
1232
            int errno;
1233
            errno = WSAGetLastError();
1234
            if (errno != WSAEWOULDBLOCK) {
1235
                return -1;
1236
            }
1237
        } else if (ret == 0) {
1238
            break;
1239
        } else {
1240
            buf += ret;
1241
            len -= ret;
1242
        }
1243
    }
1244
    return len1 - len;
1245
}
1246

    
1247
void socket_set_nonblock(int fd)
1248
{
1249
    unsigned long opt = 1;
1250
    ioctlsocket(fd, FIONBIO, &opt);
1251
}
1252

    
1253
#else
1254

    
1255
static int unix_write(int fd, const uint8_t *buf, int len1)
1256
{
1257
    int ret, len;
1258

    
1259
    len = len1;
1260
    while (len > 0) {
1261
        ret = write(fd, buf, len);
1262
        if (ret < 0) {
1263
            if (errno != EINTR && errno != EAGAIN)
1264
                return -1;
1265
        } else if (ret == 0) {
1266
            break;
1267
        } else {
1268
            buf += ret;
1269
            len -= ret;
1270
        }
1271
    }
1272
    return len1 - len;
1273
}
1274

    
1275
static inline int send_all(int fd, const uint8_t *buf, int len1)
1276
{
1277
    return unix_write(fd, buf, len1);
1278
}
1279

    
1280
void socket_set_nonblock(int fd)
1281
{
1282
    fcntl(fd, F_SETFL, O_NONBLOCK);
1283
}
1284
#endif /* !_WIN32 */
1285

    
1286
#ifndef _WIN32
1287

    
1288
typedef struct {
1289
    int fd_in, fd_out;
1290
    IOCanRWHandler *fd_can_read; 
1291
    IOReadHandler *fd_read;
1292
    void *fd_opaque;
1293
    int max_size;
1294
} FDCharDriver;
1295

    
1296
#define STDIO_MAX_CLIENTS 2
1297

    
1298
static int stdio_nb_clients;
1299
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1300

    
1301
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1302
{
1303
    FDCharDriver *s = chr->opaque;
1304
    return unix_write(s->fd_out, buf, len);
1305
}
1306

    
1307
static int fd_chr_read_poll(void *opaque)
1308
{
1309
    CharDriverState *chr = opaque;
1310
    FDCharDriver *s = chr->opaque;
1311

    
1312
    s->max_size = s->fd_can_read(s->fd_opaque);
1313
    return s->max_size;
1314
}
1315

    
1316
static void fd_chr_read(void *opaque)
1317
{
1318
    CharDriverState *chr = opaque;
1319
    FDCharDriver *s = chr->opaque;
1320
    int size, len;
1321
    uint8_t buf[1024];
1322
    
1323
    len = sizeof(buf);
1324
    if (len > s->max_size)
1325
        len = s->max_size;
1326
    if (len == 0)
1327
        return;
1328
    size = read(s->fd_in, buf, len);
1329
    if (size == 0) {
1330
        /* FD has been closed. Remove it from the active list.  */
1331
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1332
        return;
1333
    }
1334
    if (size > 0) {
1335
        s->fd_read(s->fd_opaque, buf, size);
1336
    }
1337
}
1338

    
1339
static void fd_chr_add_read_handler(CharDriverState *chr, 
1340
                                    IOCanRWHandler *fd_can_read, 
1341
                                    IOReadHandler *fd_read, void *opaque)
1342
{
1343
    FDCharDriver *s = chr->opaque;
1344

    
1345
    if (s->fd_in >= 0) {
1346
        s->fd_can_read = fd_can_read;
1347
        s->fd_read = fd_read;
1348
        s->fd_opaque = opaque;
1349
        if (nographic && s->fd_in == 0) {
1350
        } else {
1351
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1352
                                 fd_chr_read, NULL, chr);
1353
        }
1354
    }
1355
}
1356

    
1357
/* open a character device to a unix fd */
1358
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1359
{
1360
    CharDriverState *chr;
1361
    FDCharDriver *s;
1362

    
1363
    chr = qemu_mallocz(sizeof(CharDriverState));
1364
    if (!chr)
1365
        return NULL;
1366
    s = qemu_mallocz(sizeof(FDCharDriver));
1367
    if (!s) {
1368
        free(chr);
1369
        return NULL;
1370
    }
1371
    s->fd_in = fd_in;
1372
    s->fd_out = fd_out;
1373
    chr->opaque = s;
1374
    chr->chr_write = fd_chr_write;
1375
    chr->chr_add_read_handler = fd_chr_add_read_handler;
1376

    
1377
    qemu_chr_reset(chr);
1378

    
1379
    return chr;
1380
}
1381

    
1382
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1383
{
1384
    int fd_out;
1385

    
1386
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1387
    if (fd_out < 0)
1388
        return NULL;
1389
    return qemu_chr_open_fd(-1, fd_out);
1390
}
1391

    
1392
static CharDriverState *qemu_chr_open_pipe(const char *filename)
1393
{
1394
    int fd_in, fd_out;
1395
    char filename_in[256], filename_out[256];
1396

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

    
1413

    
1414
/* for STDIO, we handle the case where several clients use it
1415
   (nographic mode) */
1416

    
1417
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1418

    
1419
#define TERM_FIFO_MAX_SIZE 1
1420

    
1421
static int term_got_escape, client_index;
1422
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1423
static int term_fifo_size;
1424
static int term_timestamps;
1425
static int64_t term_timestamps_start;
1426

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

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

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

    
1509
static int stdio_read_poll(void *opaque)
1510
{
1511
    CharDriverState *chr;
1512
    FDCharDriver *s;
1513

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

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

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

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

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

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

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

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

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

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

    
1612
    atexit(term_exit);
1613

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1851
    chr = qemu_mallocz(sizeof(CharDriverState));
1852
    if (!chr) {
1853
        close(fd);
1854
        return NULL;
1855
    }
1856
    chr->opaque = (void *)fd;
1857
    chr->chr_write = null_chr_write;
1858
    chr->chr_add_read_handler = null_chr_add_read_handler;
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
    IOCanRWHandler *fd_can_read; 
1878
    IOReadHandler *fd_read;
1879
    void *win_opaque;
1880
    int max_size;
1881
    HANDLE hcom, hrecv, hsend;
1882
    OVERLAPPED orecv, osend;
1883
    BOOL fpipe;
1884
    DWORD len;
1885
} WinCharState;
1886

    
1887
#define NSENDBUF 2048
1888
#define NRECVBUF 2048
1889
#define MAXCONNECT 1
1890
#define NTIMEOUT 5000
1891

    
1892
static int win_chr_poll(void *opaque);
1893
static int win_chr_pipe_poll(void *opaque);
1894

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

    
1915
static void win_chr_close(CharDriverState *chr)
1916
{
1917
    WinCharState *s = chr->opaque;
1918
    win_chr_close2(s);
1919
}
1920

    
1921
static int win_chr_init(WinCharState *s, const char *filename)
1922
{
1923
    COMMCONFIG comcfg;
1924
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1925
    COMSTAT comstat;
1926
    DWORD size;
1927
    DWORD err;
1928
    
1929
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1930
    if (!s->hsend) {
1931
        fprintf(stderr, "Failed CreateEvent\n");
1932
        goto fail;
1933
    }
1934
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1935
    if (!s->hrecv) {
1936
        fprintf(stderr, "Failed CreateEvent\n");
1937
        goto fail;
1938
    }
1939

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

    
1959
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
1960
        fprintf(stderr, "Failed SetCommState\n");
1961
        goto fail;
1962
    }
1963

    
1964
    if (!SetCommMask(s->hcom, EV_ERR)) {
1965
        fprintf(stderr, "Failed SetCommMask\n");
1966
        goto fail;
1967
    }
1968

    
1969
    cto.ReadIntervalTimeout = MAXDWORD;
1970
    if (!SetCommTimeouts(s->hcom, &cto)) {
1971
        fprintf(stderr, "Failed SetCommTimeouts\n");
1972
        goto fail;
1973
    }
1974
    
1975
    if (!ClearCommError(s->hcom, &err, &comstat)) {
1976
        fprintf(stderr, "Failed ClearCommError\n");
1977
        goto fail;
1978
    }
1979
    qemu_add_polling_cb(win_chr_poll, s);
1980
    return 0;
1981

    
1982
 fail:
1983
    win_chr_close2(s);
1984
    return -1;
1985
}
1986

    
1987
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1988
{
1989
    WinCharState *s = chr->opaque;
1990
    DWORD len, ret, size, err;
1991

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

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

    
2043
    if (size > 0) {
2044
        s->fd_read(s->win_opaque, buf, size);
2045
    }
2046
}
2047

    
2048
static void win_chr_read(WinCharState *s)
2049
{
2050
    if (s->len > s->max_size)
2051
        s->len = s->max_size;
2052
    if (s->len == 0)
2053
        return;
2054
    
2055
    win_chr_readfile(s);
2056
}
2057

    
2058
static int win_chr_poll(void *opaque)
2059
{
2060
    WinCharState *s = 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(s);
2068
        win_chr_read(s);
2069
        return 1;
2070
    }
2071
    return 0;
2072
}
2073

    
2074
static void win_chr_add_read_handler(CharDriverState *chr, 
2075
                                    IOCanRWHandler *fd_can_read, 
2076
                                    IOReadHandler *fd_read, void *opaque)
2077
{
2078
    WinCharState *s = chr->opaque;
2079

    
2080
    s->fd_can_read = fd_can_read;
2081
    s->fd_read = fd_read;
2082
    s->win_opaque = opaque;
2083
}
2084

    
2085
static CharDriverState *qemu_chr_open_win(const char *filename)
2086
{
2087
    CharDriverState *chr;
2088
    WinCharState *s;
2089
    
2090
    chr = qemu_mallocz(sizeof(CharDriverState));
2091
    if (!chr)
2092
        return NULL;
2093
    s = qemu_mallocz(sizeof(WinCharState));
2094
    if (!s) {
2095
        free(chr);
2096
        return NULL;
2097
    }
2098
    chr->opaque = s;
2099
    chr->chr_write = win_chr_write;
2100
    chr->chr_add_read_handler = win_chr_add_read_handler;
2101
    chr->chr_close = win_chr_close;
2102

    
2103
    if (win_chr_init(s, filename) < 0) {
2104
        free(s);
2105
        free(chr);
2106
        return NULL;
2107
    }
2108
    qemu_chr_reset(chr);
2109
    return chr;
2110
}
2111

    
2112
static int win_chr_pipe_poll(void *opaque)
2113
{
2114
    WinCharState *s = opaque;
2115
    DWORD size;
2116

    
2117
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2118
    if (size > 0) {
2119
        s->len = size;
2120
        win_chr_read_poll(s);
2121
        win_chr_read(s);
2122
        return 1;
2123
    }
2124
    return 0;
2125
}
2126

    
2127
static int win_chr_pipe_init(WinCharState *s, const char *filename)
2128
{
2129
    OVERLAPPED ov;
2130
    int ret;
2131
    DWORD size;
2132
    char openname[256];
2133
    
2134
    s->fpipe = TRUE;
2135

    
2136
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2137
    if (!s->hsend) {
2138
        fprintf(stderr, "Failed CreateEvent\n");
2139
        goto fail;
2140
    }
2141
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2142
    if (!s->hrecv) {
2143
        fprintf(stderr, "Failed CreateEvent\n");
2144
        goto fail;
2145
    }
2146
    
2147
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2148
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2149
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2150
                              PIPE_WAIT,
2151
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2152
    if (s->hcom == INVALID_HANDLE_VALUE) {
2153
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2154
        s->hcom = NULL;
2155
        goto fail;
2156
    }
2157

    
2158
    ZeroMemory(&ov, sizeof(ov));
2159
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2160
    ret = ConnectNamedPipe(s->hcom, &ov);
2161
    if (ret) {
2162
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2163
        goto fail;
2164
    }
2165

    
2166
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2167
    if (!ret) {
2168
        fprintf(stderr, "Failed GetOverlappedResult\n");
2169
        if (ov.hEvent) {
2170
            CloseHandle(ov.hEvent);
2171
            ov.hEvent = NULL;
2172
        }
2173
        goto fail;
2174
    }
2175

    
2176
    if (ov.hEvent) {
2177
        CloseHandle(ov.hEvent);
2178
        ov.hEvent = NULL;
2179
    }
2180
    qemu_add_polling_cb(win_chr_pipe_poll, s);
2181
    return 0;
2182

    
2183
 fail:
2184
    win_chr_close2(s);
2185
    return -1;
2186
}
2187

    
2188

    
2189
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2190
{
2191
    CharDriverState *chr;
2192
    WinCharState *s;
2193

    
2194
    chr = qemu_mallocz(sizeof(CharDriverState));
2195
    if (!chr)
2196
        return NULL;
2197
    s = qemu_mallocz(sizeof(WinCharState));
2198
    if (!s) {
2199
        free(chr);
2200
        return NULL;
2201
    }
2202
    chr->opaque = s;
2203
    chr->chr_write = win_chr_write;
2204
    chr->chr_add_read_handler = win_chr_add_read_handler;
2205
    chr->chr_close = win_chr_close;
2206
    
2207
    if (win_chr_pipe_init(s, filename) < 0) {
2208
        free(s);
2209
        free(chr);
2210
        return NULL;
2211
    }
2212
    qemu_chr_reset(chr);
2213
    return chr;
2214
}
2215

    
2216
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2217
{
2218
    CharDriverState *chr;
2219
    WinCharState *s;
2220

    
2221
    chr = qemu_mallocz(sizeof(CharDriverState));
2222
    if (!chr)
2223
        return NULL;
2224
    s = qemu_mallocz(sizeof(WinCharState));
2225
    if (!s) {
2226
        free(chr);
2227
        return NULL;
2228
    }
2229
    s->hcom = fd_out;
2230
    chr->opaque = s;
2231
    chr->chr_write = win_chr_write;
2232
    chr->chr_add_read_handler = win_chr_add_read_handler;
2233
    qemu_chr_reset(chr);
2234
    return chr;
2235
}
2236
    
2237
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2238
{
2239
    HANDLE fd_out;
2240
    
2241
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2242
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2243
    if (fd_out == INVALID_HANDLE_VALUE)
2244
        return NULL;
2245

    
2246
    return qemu_chr_open_win_file(fd_out);
2247
}
2248
#endif
2249

    
2250
/***********************************************************/
2251
/* UDP Net console */
2252

    
2253
typedef struct {
2254
    IOCanRWHandler *fd_can_read;
2255
    IOReadHandler *fd_read;
2256
    void *fd_opaque;
2257
    int fd;
2258
    struct sockaddr_in daddr;
2259
    char buf[1024];
2260
    int bufcnt;
2261
    int bufptr;
2262
    int max_size;
2263
} NetCharDriver;
2264

    
2265
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2266
{
2267
    NetCharDriver *s = chr->opaque;
2268

    
2269
    return sendto(s->fd, buf, len, 0,
2270
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2271
}
2272

    
2273
static int udp_chr_read_poll(void *opaque)
2274
{
2275
    CharDriverState *chr = opaque;
2276
    NetCharDriver *s = chr->opaque;
2277

    
2278
    s->max_size = s->fd_can_read(s->fd_opaque);
2279

    
2280
    /* If there were any stray characters in the queue process them
2281
     * first
2282
     */
2283
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2284
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2285
        s->bufptr++;
2286
        s->max_size = s->fd_can_read(s->fd_opaque);
2287
    }
2288
    return s->max_size;
2289
}
2290

    
2291
static void udp_chr_read(void *opaque)
2292
{
2293
    CharDriverState *chr = opaque;
2294
    NetCharDriver *s = chr->opaque;
2295

    
2296
    if (s->max_size == 0)
2297
        return;
2298
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2299
    s->bufptr = s->bufcnt;
2300
    if (s->bufcnt <= 0)
2301
        return;
2302

    
2303
    s->bufptr = 0;
2304
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2305
        s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2306
        s->bufptr++;
2307
        s->max_size = s->fd_can_read(s->fd_opaque);
2308
    }
2309
}
2310

    
2311
static void udp_chr_add_read_handler(CharDriverState *chr,
2312
                                    IOCanRWHandler *fd_can_read,
2313
                                    IOReadHandler *fd_read, void *opaque)
2314
{
2315
    NetCharDriver *s = chr->opaque;
2316

    
2317
    if (s->fd >= 0) {
2318
        s->fd_can_read = fd_can_read;
2319
        s->fd_read = fd_read;
2320
        s->fd_opaque = opaque;
2321
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2322
                             udp_chr_read, NULL, chr);
2323
    }
2324
}
2325

    
2326
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2327
#ifndef _WIN32
2328
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2329
#endif
2330
int parse_host_src_port(struct sockaddr_in *haddr,
2331
                        struct sockaddr_in *saddr,
2332
                        const char *str);
2333

    
2334
static CharDriverState *qemu_chr_open_udp(const char *def)
2335
{
2336
    CharDriverState *chr = NULL;
2337
    NetCharDriver *s = NULL;
2338
    int fd = -1;
2339
    struct sockaddr_in saddr;
2340

    
2341
    chr = qemu_mallocz(sizeof(CharDriverState));
2342
    if (!chr)
2343
        goto return_err;
2344
    s = qemu_mallocz(sizeof(NetCharDriver));
2345
    if (!s)
2346
        goto return_err;
2347

    
2348
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2349
    if (fd < 0) {
2350
        perror("socket(PF_INET, SOCK_DGRAM)");
2351
        goto return_err;
2352
    }
2353

    
2354
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2355
        printf("Could not parse: %s\n", def);
2356
        goto return_err;
2357
    }
2358

    
2359
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2360
    {
2361
        perror("bind");
2362
        goto return_err;
2363
    }
2364

    
2365
    s->fd = fd;
2366
    s->bufcnt = 0;
2367
    s->bufptr = 0;
2368
    chr->opaque = s;
2369
    chr->chr_write = udp_chr_write;
2370
    chr->chr_add_read_handler = udp_chr_add_read_handler;
2371
    return chr;
2372

    
2373
return_err:
2374
    if (chr)
2375
        free(chr);
2376
    if (s)
2377
        free(s);
2378
    if (fd >= 0)
2379
        closesocket(fd);
2380
    return NULL;
2381
}
2382

    
2383
/***********************************************************/
2384
/* TCP Net console */
2385

    
2386
typedef struct {
2387
    IOCanRWHandler *fd_can_read;
2388
    IOReadHandler *fd_read;
2389
    void *fd_opaque;
2390
    int fd, listen_fd;
2391
    int connected;
2392
    int max_size;
2393
    int do_telnetopt;
2394
    int is_unix;
2395
} TCPCharDriver;
2396

    
2397
static void tcp_chr_accept(void *opaque);
2398

    
2399
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2400
{
2401
    TCPCharDriver *s = chr->opaque;
2402
    if (s->connected) {
2403
        return send_all(s->fd, buf, len);
2404
    } else {
2405
        /* XXX: indicate an error ? */
2406
        return len;
2407
    }
2408
}
2409

    
2410
static int tcp_chr_read_poll(void *opaque)
2411
{
2412
    CharDriverState *chr = opaque;
2413
    TCPCharDriver *s = chr->opaque;
2414
    if (!s->connected)
2415
        return 0;
2416
    if (!s->fd_can_read)
2417
        return 0;
2418
    s->max_size = s->fd_can_read(s->fd_opaque);
2419
    return s->max_size;
2420
}
2421

    
2422
#define IAC 255
2423
#define IAC_BREAK 243
2424
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2425
                                      TCPCharDriver *s,
2426
                                      char *buf, int *size)
2427
{
2428
    /* Handle any telnet client's basic IAC options to satisfy char by
2429
     * char mode with no echo.  All IAC options will be removed from
2430
     * the buf and the do_telnetopt variable will be used to track the
2431
     * state of the width of the IAC information.
2432
     *
2433
     * IAC commands come in sets of 3 bytes with the exception of the
2434
     * "IAC BREAK" command and the double IAC.
2435
     */
2436

    
2437
    int i;
2438
    int j = 0;
2439

    
2440
    for (i = 0; i < *size; i++) {
2441
        if (s->do_telnetopt > 1) {
2442
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2443
                /* Double IAC means send an IAC */
2444
                if (j != i)
2445
                    buf[j] = buf[i];
2446
                j++;
2447
                s->do_telnetopt = 1;
2448
            } else {
2449
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2450
                    /* Handle IAC break commands by sending a serial break */
2451
                    chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2452
                    s->do_telnetopt++;
2453
                }
2454
                s->do_telnetopt++;
2455
            }
2456
            if (s->do_telnetopt >= 4) {
2457
                s->do_telnetopt = 1;
2458
            }
2459
        } else {
2460
            if ((unsigned char)buf[i] == IAC) {
2461
                s->do_telnetopt = 2;
2462
            } else {
2463
                if (j != i)
2464
                    buf[j] = buf[i];
2465
                j++;
2466
            }
2467
        }
2468
    }
2469
    *size = j;
2470
}
2471

    
2472
static void tcp_chr_read(void *opaque)
2473
{
2474
    CharDriverState *chr = opaque;
2475
    TCPCharDriver *s = chr->opaque;
2476
    uint8_t buf[1024];
2477
    int len, size;
2478

    
2479
    if (!s->connected || s->max_size <= 0)
2480
        return;
2481
    len = sizeof(buf);
2482
    if (len > s->max_size)
2483
        len = s->max_size;
2484
    size = recv(s->fd, buf, len, 0);
2485
    if (size == 0) {
2486
        /* connection closed */
2487
        s->connected = 0;
2488
        if (s->listen_fd >= 0) {
2489
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2490
        }
2491
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2492
        closesocket(s->fd);
2493
        s->fd = -1;
2494
    } else if (size > 0) {
2495
        if (s->do_telnetopt)
2496
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2497
        if (size > 0)
2498
            s->fd_read(s->fd_opaque, buf, size);
2499
    }
2500
}
2501

    
2502
static void tcp_chr_add_read_handler(CharDriverState *chr,
2503
                                     IOCanRWHandler *fd_can_read,
2504
                                    IOReadHandler *fd_read, void *opaque)
2505
{
2506
    TCPCharDriver *s = chr->opaque;
2507

    
2508
    s->fd_can_read = fd_can_read;
2509
    s->fd_read = fd_read;
2510
    s->fd_opaque = opaque;
2511
}
2512

    
2513
static void tcp_chr_connect(void *opaque)
2514
{
2515
    CharDriverState *chr = opaque;
2516
    TCPCharDriver *s = chr->opaque;
2517

    
2518
    s->connected = 1;
2519
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2520
                         tcp_chr_read, NULL, chr);
2521
    qemu_chr_reset(chr);
2522
}
2523

    
2524
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2525
static void tcp_chr_telnet_init(int fd)
2526
{
2527
    char buf[3];
2528
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2529
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2530
    send(fd, (char *)buf, 3, 0);
2531
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2532
    send(fd, (char *)buf, 3, 0);
2533
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2534
    send(fd, (char *)buf, 3, 0);
2535
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2536
    send(fd, (char *)buf, 3, 0);
2537
}
2538

    
2539
static void tcp_chr_accept(void *opaque)
2540
{
2541
    CharDriverState *chr = opaque;
2542
    TCPCharDriver *s = chr->opaque;
2543
    struct sockaddr_in saddr;
2544
#ifndef _WIN32
2545
    struct sockaddr_un uaddr;
2546
#endif
2547
    struct sockaddr *addr;
2548
    socklen_t len;
2549
    int fd;
2550

    
2551
    for(;;) {
2552
#ifndef _WIN32
2553
        if (s->is_unix) {
2554
            len = sizeof(uaddr);
2555
            addr = (struct sockaddr *)&uaddr;
2556
        } else
2557
#endif
2558
        {
2559
            len = sizeof(saddr);
2560
            addr = (struct sockaddr *)&saddr;
2561
        }
2562
        fd = accept(s->listen_fd, addr, &len);
2563
        if (fd < 0 && errno != EINTR) {
2564
            return;
2565
        } else if (fd >= 0) {
2566
            if (s->do_telnetopt)
2567
                tcp_chr_telnet_init(fd);
2568
            break;
2569
        }
2570
    }
2571
    socket_set_nonblock(fd);
2572
    s->fd = fd;
2573
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2574
    tcp_chr_connect(chr);
2575
}
2576

    
2577
static void tcp_chr_close(CharDriverState *chr)
2578
{
2579
    TCPCharDriver *s = chr->opaque;
2580
    if (s->fd >= 0)
2581
        closesocket(s->fd);
2582
    if (s->listen_fd >= 0)
2583
        closesocket(s->listen_fd);
2584
    qemu_free(s);
2585
}
2586

    
2587
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2588
                                          int is_telnet,
2589
                                          int is_unix)
2590
{
2591
    CharDriverState *chr = NULL;
2592
    TCPCharDriver *s = NULL;
2593
    int fd = -1, ret, err, val;
2594
    int is_listen = 0;
2595
    int is_waitconnect = 1;
2596
    const char *ptr;
2597
    struct sockaddr_in saddr;
2598
#ifndef _WIN32
2599
    struct sockaddr_un uaddr;
2600
#endif
2601
    struct sockaddr *addr;
2602
    socklen_t addrlen;
2603

    
2604
#ifndef _WIN32
2605
    if (is_unix) {
2606
        addr = (struct sockaddr *)&uaddr;
2607
        addrlen = sizeof(uaddr);
2608
        if (parse_unix_path(&uaddr, host_str) < 0)
2609
            goto fail;
2610
    } else
2611
#endif
2612
    {
2613
        addr = (struct sockaddr *)&saddr;
2614
        addrlen = sizeof(saddr);
2615
        if (parse_host_port(&saddr, host_str) < 0)
2616
            goto fail;
2617
    }
2618

    
2619
    ptr = host_str;
2620
    while((ptr = strchr(ptr,','))) {
2621
        ptr++;
2622
        if (!strncmp(ptr,"server",6)) {
2623
            is_listen = 1;
2624
        } else if (!strncmp(ptr,"nowait",6)) {
2625
            is_waitconnect = 0;
2626
        } else {
2627
            printf("Unknown option: %s\n", ptr);
2628
            goto fail;
2629
        }
2630
    }
2631
    if (!is_listen)
2632
        is_waitconnect = 0;
2633

    
2634
    chr = qemu_mallocz(sizeof(CharDriverState));
2635
    if (!chr)
2636
        goto fail;
2637
    s = qemu_mallocz(sizeof(TCPCharDriver));
2638
    if (!s)
2639
        goto fail;
2640

    
2641
#ifndef _WIN32
2642
    if (is_unix)
2643
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2644
    else
2645
#endif
2646
        fd = socket(PF_INET, SOCK_STREAM, 0);
2647
        
2648
    if (fd < 0) 
2649
        goto fail;
2650

    
2651
    if (!is_waitconnect)
2652
        socket_set_nonblock(fd);
2653

    
2654
    s->connected = 0;
2655
    s->fd = -1;
2656
    s->listen_fd = -1;
2657
    s->is_unix = is_unix;
2658

    
2659
    chr->opaque = s;
2660
    chr->chr_write = tcp_chr_write;
2661
    chr->chr_add_read_handler = tcp_chr_add_read_handler;
2662
    chr->chr_close = tcp_chr_close;
2663

    
2664
    if (is_listen) {
2665
        /* allow fast reuse */
2666
#ifndef _WIN32
2667
        if (is_unix) {
2668
            char path[109];
2669
            strncpy(path, uaddr.sun_path, 108);
2670
            path[108] = 0;
2671
            unlink(path);
2672
        } else
2673
#endif
2674
        {
2675
            val = 1;
2676
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2677
        }
2678
        
2679
        ret = bind(fd, addr, addrlen);
2680
        if (ret < 0)
2681
            goto fail;
2682

    
2683
        ret = listen(fd, 0);
2684
        if (ret < 0)
2685
            goto fail;
2686

    
2687
        s->listen_fd = fd;
2688
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2689
        if (is_telnet)
2690
            s->do_telnetopt = 1;
2691
    } else {
2692
        for(;;) {
2693
            ret = connect(fd, addr, addrlen);
2694
            if (ret < 0) {
2695
                err = socket_error();
2696
                if (err == EINTR || err == EWOULDBLOCK) {
2697
                } else if (err == EINPROGRESS) {
2698
                    break;
2699
                } else {
2700
                    goto fail;
2701
                }
2702
            } else {
2703
                s->connected = 1;
2704
                break;
2705
            }
2706
        }
2707
        s->fd = fd;
2708
        if (s->connected)
2709
            tcp_chr_connect(chr);
2710
        else
2711
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2712
    }
2713
    
2714
    if (is_listen && is_waitconnect) {
2715
        printf("QEMU waiting for connection on: %s\n", host_str);
2716
        tcp_chr_accept(chr);
2717
        socket_set_nonblock(s->listen_fd);
2718
    }
2719

    
2720
    return chr;
2721
 fail:
2722
    if (fd >= 0)
2723
        closesocket(fd);
2724
    qemu_free(s);
2725
    qemu_free(chr);
2726
    return NULL;
2727
}
2728

    
2729
CharDriverState *qemu_chr_open(const char *filename)
2730
{
2731
    const char *p;
2732

    
2733
    if (!strcmp(filename, "vc")) {
2734
        return text_console_init(&display_state);
2735
    } else if (!strcmp(filename, "null")) {
2736
        return qemu_chr_open_null();
2737
    } else 
2738
    if (strstart(filename, "tcp:", &p)) {
2739
        return qemu_chr_open_tcp(p, 0, 0);
2740
    } else
2741
    if (strstart(filename, "telnet:", &p)) {
2742
        return qemu_chr_open_tcp(p, 1, 0);
2743
    } else
2744
    if (strstart(filename, "udp:", &p)) {
2745
        return qemu_chr_open_udp(p);
2746
    } else
2747
#ifndef _WIN32
2748
    if (strstart(filename, "unix:", &p)) {
2749
        return qemu_chr_open_tcp(p, 0, 1);
2750
    } else if (strstart(filename, "file:", &p)) {
2751
        return qemu_chr_open_file_out(p);
2752
    } else if (strstart(filename, "pipe:", &p)) {
2753
        return qemu_chr_open_pipe(p);
2754
    } else if (!strcmp(filename, "pty")) {
2755
        return qemu_chr_open_pty();
2756
    } else if (!strcmp(filename, "stdio")) {
2757
        return qemu_chr_open_stdio();
2758
    } else 
2759
#endif
2760
#if defined(__linux__)
2761
    if (strstart(filename, "/dev/parport", NULL)) {
2762
        return qemu_chr_open_pp(filename);
2763
    } else 
2764
    if (strstart(filename, "/dev/", NULL)) {
2765
        return qemu_chr_open_tty(filename);
2766
    } else 
2767
#endif
2768
#ifdef _WIN32
2769
    if (strstart(filename, "COM", NULL)) {
2770
        return qemu_chr_open_win(filename);
2771
    } else
2772
    if (strstart(filename, "pipe:", &p)) {
2773
        return qemu_chr_open_win_pipe(p);
2774
    } else
2775
    if (strstart(filename, "file:", &p)) {
2776
        return qemu_chr_open_win_file_out(p);
2777
    }
2778
#endif
2779
    {
2780
        return NULL;
2781
    }
2782
}
2783

    
2784
void qemu_chr_close(CharDriverState *chr)
2785
{
2786
    if (chr->chr_close)
2787
        chr->chr_close(chr);
2788
}
2789

    
2790
/***********************************************************/
2791
/* network device redirectors */
2792

    
2793
void hex_dump(FILE *f, const uint8_t *buf, int size)
2794
{
2795
    int len, i, j, c;
2796

    
2797
    for(i=0;i<size;i+=16) {
2798
        len = size - i;
2799
        if (len > 16)
2800
            len = 16;
2801
        fprintf(f, "%08x ", i);
2802
        for(j=0;j<16;j++) {
2803
            if (j < len)
2804
                fprintf(f, " %02x", buf[i+j]);
2805
            else
2806
                fprintf(f, "   ");
2807
        }
2808
        fprintf(f, " ");
2809
        for(j=0;j<len;j++) {
2810
            c = buf[i+j];
2811
            if (c < ' ' || c > '~')
2812
                c = '.';
2813
            fprintf(f, "%c", c);
2814
        }
2815
        fprintf(f, "\n");
2816
    }
2817
}
2818

    
2819
static int parse_macaddr(uint8_t *macaddr, const char *p)
2820
{
2821
    int i;
2822
    for(i = 0; i < 6; i++) {
2823
        macaddr[i] = strtol(p, (char **)&p, 16);
2824
        if (i == 5) {
2825
            if (*p != '\0') 
2826
                return -1;
2827
        } else {
2828
            if (*p != ':') 
2829
                return -1;
2830
            p++;
2831
        }
2832
    }
2833
    return 0;
2834
}
2835

    
2836
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2837
{
2838
    const char *p, *p1;
2839
    int len;
2840
    p = *pp;
2841
    p1 = strchr(p, sep);
2842
    if (!p1)
2843
        return -1;
2844
    len = p1 - p;
2845
    p1++;
2846
    if (buf_size > 0) {
2847
        if (len > buf_size - 1)
2848
            len = buf_size - 1;
2849
        memcpy(buf, p, len);
2850
        buf[len] = '\0';
2851
    }
2852
    *pp = p1;
2853
    return 0;
2854
}
2855

    
2856
int parse_host_src_port(struct sockaddr_in *haddr,
2857
                        struct sockaddr_in *saddr,
2858
                        const char *input_str)
2859
{
2860
    char *str = strdup(input_str);
2861
    char *host_str = str;
2862
    char *src_str;
2863
    char *ptr;
2864

    
2865
    /*
2866
     * Chop off any extra arguments at the end of the string which
2867
     * would start with a comma, then fill in the src port information
2868
     * if it was provided else use the "any address" and "any port".
2869
     */
2870
    if ((ptr = strchr(str,',')))
2871
        *ptr = '\0';
2872

    
2873
    if ((src_str = strchr(input_str,'@'))) {
2874
        *src_str = '\0';
2875
        src_str++;
2876
    }
2877

    
2878
    if (parse_host_port(haddr, host_str) < 0)
2879
        goto fail;
2880

    
2881
    if (!src_str || *src_str == '\0')
2882
        src_str = ":0";
2883

    
2884
    if (parse_host_port(saddr, src_str) < 0)
2885
        goto fail;
2886

    
2887
    free(str);
2888
    return(0);
2889

    
2890
fail:
2891
    free(str);
2892
    return -1;
2893
}
2894

    
2895
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2896
{
2897
    char buf[512];
2898
    struct hostent *he;
2899
    const char *p, *r;
2900
    int port;
2901

    
2902
    p = str;
2903
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2904
        return -1;
2905
    saddr->sin_family = AF_INET;
2906
    if (buf[0] == '\0') {
2907
        saddr->sin_addr.s_addr = 0;
2908
    } else {
2909
        if (isdigit(buf[0])) {
2910
            if (!inet_aton(buf, &saddr->sin_addr))
2911
                return -1;
2912
        } else {
2913
            if ((he = gethostbyname(buf)) == NULL)
2914
                return - 1;
2915
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2916
        }
2917
    }
2918
    port = strtol(p, (char **)&r, 0);
2919
    if (r == p)
2920
        return -1;
2921
    saddr->sin_port = htons(port);
2922
    return 0;
2923
}
2924

    
2925
#ifndef _WIN32
2926
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2927
{
2928
    const char *p;
2929
    int len;
2930

    
2931
    len = MIN(108, strlen(str));
2932
    p = strchr(str, ',');
2933
    if (p)
2934
        len = MIN(len, p - str);
2935

    
2936
    memset(uaddr, 0, sizeof(*uaddr));
2937

    
2938
    uaddr->sun_family = AF_UNIX;
2939
    memcpy(uaddr->sun_path, str, len);
2940

    
2941
    return 0;
2942
}
2943
#endif
2944

    
2945
/* find or alloc a new VLAN */
2946
VLANState *qemu_find_vlan(int id)
2947
{
2948
    VLANState **pvlan, *vlan;
2949
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2950
        if (vlan->id == id)
2951
            return vlan;
2952
    }
2953
    vlan = qemu_mallocz(sizeof(VLANState));
2954
    if (!vlan)
2955
        return NULL;
2956
    vlan->id = id;
2957
    vlan->next = NULL;
2958
    pvlan = &first_vlan;
2959
    while (*pvlan != NULL)
2960
        pvlan = &(*pvlan)->next;
2961
    *pvlan = vlan;
2962
    return vlan;
2963
}
2964

    
2965
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2966
                                      IOReadHandler *fd_read,
2967
                                      IOCanRWHandler *fd_can_read,
2968
                                      void *opaque)
2969
{
2970
    VLANClientState *vc, **pvc;
2971
    vc = qemu_mallocz(sizeof(VLANClientState));
2972
    if (!vc)
2973
        return NULL;
2974
    vc->fd_read = fd_read;
2975
    vc->fd_can_read = fd_can_read;
2976
    vc->opaque = opaque;
2977
    vc->vlan = vlan;
2978

    
2979
    vc->next = NULL;
2980
    pvc = &vlan->first_client;
2981
    while (*pvc != NULL)
2982
        pvc = &(*pvc)->next;
2983
    *pvc = vc;
2984
    return vc;
2985
}
2986

    
2987
int qemu_can_send_packet(VLANClientState *vc1)
2988
{
2989
    VLANState *vlan = vc1->vlan;
2990
    VLANClientState *vc;
2991

    
2992
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2993
        if (vc != vc1) {
2994
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2995
                return 0;
2996
        }
2997
    }
2998
    return 1;
2999
}
3000

    
3001
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3002
{
3003
    VLANState *vlan = vc1->vlan;
3004
    VLANClientState *vc;
3005

    
3006
#if 0
3007
    printf("vlan %d send:\n", vlan->id);
3008
    hex_dump(stdout, buf, size);
3009
#endif
3010
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3011
        if (vc != vc1) {
3012
            vc->fd_read(vc->opaque, buf, size);
3013
        }
3014
    }
3015
}
3016

    
3017
#if defined(CONFIG_SLIRP)
3018

    
3019
/* slirp network adapter */
3020

    
3021
static int slirp_inited;
3022
static VLANClientState *slirp_vc;
3023

    
3024
int slirp_can_output(void)
3025
{
3026
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3027
}
3028

    
3029
void slirp_output(const uint8_t *pkt, int pkt_len)
3030
{
3031
#if 0
3032
    printf("slirp output:\n");
3033
    hex_dump(stdout, pkt, pkt_len);
3034
#endif
3035
    if (!slirp_vc)
3036
        return;
3037
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3038
}
3039

    
3040
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3041
{
3042
#if 0
3043
    printf("slirp input:\n");
3044
    hex_dump(stdout, buf, size);
3045
#endif
3046
    slirp_input(buf, size);
3047
}
3048

    
3049
static int net_slirp_init(VLANState *vlan)
3050
{
3051
    if (!slirp_inited) {
3052
        slirp_inited = 1;
3053
        slirp_init();
3054
    }
3055
    slirp_vc = qemu_new_vlan_client(vlan, 
3056
                                    slirp_receive, NULL, NULL);
3057
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3058
    return 0;
3059
}
3060

    
3061
static void net_slirp_redir(const char *redir_str)
3062
{
3063
    int is_udp;
3064
    char buf[256], *r;
3065
    const char *p;
3066
    struct in_addr guest_addr;
3067
    int host_port, guest_port;
3068
    
3069
    if (!slirp_inited) {
3070
        slirp_inited = 1;
3071
        slirp_init();
3072
    }
3073

    
3074
    p = redir_str;
3075
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3076
        goto fail;
3077
    if (!strcmp(buf, "tcp")) {
3078
        is_udp = 0;
3079
    } else if (!strcmp(buf, "udp")) {
3080
        is_udp = 1;
3081
    } else {
3082
        goto fail;
3083
    }
3084

    
3085
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3086
        goto fail;
3087
    host_port = strtol(buf, &r, 0);
3088
    if (r == buf)
3089
        goto fail;
3090

    
3091
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3092
        goto fail;
3093
    if (buf[0] == '\0') {
3094
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3095
    }
3096
    if (!inet_aton(buf, &guest_addr))
3097
        goto fail;
3098
    
3099
    guest_port = strtol(p, &r, 0);
3100
    if (r == p)
3101
        goto fail;
3102
    
3103
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3104
        fprintf(stderr, "qemu: could not set up redirection\n");
3105
        exit(1);
3106
    }
3107
    return;
3108
 fail:
3109
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3110
    exit(1);
3111
}
3112
    
3113
#ifndef _WIN32
3114

    
3115
char smb_dir[1024];
3116

    
3117
static void smb_exit(void)
3118
{
3119
    DIR *d;
3120
    struct dirent *de;
3121
    char filename[1024];
3122

    
3123
    /* erase all the files in the directory */
3124
    d = opendir(smb_dir);
3125
    for(;;) {
3126
        de = readdir(d);
3127
        if (!de)
3128
            break;
3129
        if (strcmp(de->d_name, ".") != 0 &&
3130
            strcmp(de->d_name, "..") != 0) {
3131
            snprintf(filename, sizeof(filename), "%s/%s", 
3132
                     smb_dir, de->d_name);
3133
            unlink(filename);
3134
        }
3135
    }
3136
    closedir(d);
3137
    rmdir(smb_dir);
3138
}
3139

    
3140
/* automatic user mode samba server configuration */
3141
void net_slirp_smb(const char *exported_dir)
3142
{
3143
    char smb_conf[1024];
3144
    char smb_cmdline[1024];
3145
    FILE *f;
3146

    
3147
    if (!slirp_inited) {
3148
        slirp_inited = 1;
3149
        slirp_init();
3150
    }
3151

    
3152
    /* XXX: better tmp dir construction */
3153
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3154
    if (mkdir(smb_dir, 0700) < 0) {
3155
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3156
        exit(1);
3157
    }
3158
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3159
    
3160
    f = fopen(smb_conf, "w");
3161
    if (!f) {
3162
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3163
        exit(1);
3164
    }
3165
    fprintf(f, 
3166
            "[global]\n"
3167
            "private dir=%s\n"
3168
            "smb ports=0\n"
3169
            "socket address=127.0.0.1\n"
3170
            "pid directory=%s\n"
3171
            "lock directory=%s\n"
3172
            "log file=%s/log.smbd\n"
3173
            "smb passwd file=%s/smbpasswd\n"
3174
            "security = share\n"
3175
            "[qemu]\n"
3176
            "path=%s\n"
3177
            "read only=no\n"
3178
            "guest ok=yes\n",
3179
            smb_dir,
3180
            smb_dir,
3181
            smb_dir,
3182
            smb_dir,
3183
            smb_dir,
3184
            exported_dir
3185
            );
3186
    fclose(f);
3187
    atexit(smb_exit);
3188

    
3189
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3190
             SMBD_COMMAND, smb_conf);
3191
    
3192
    slirp_add_exec(0, smb_cmdline, 4, 139);
3193
}
3194

    
3195
#endif /* !defined(_WIN32) */
3196

    
3197
#endif /* CONFIG_SLIRP */
3198

    
3199
#if !defined(_WIN32)
3200

    
3201
typedef struct TAPState {
3202
    VLANClientState *vc;
3203
    int fd;
3204
} TAPState;
3205

    
3206
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3207
{
3208
    TAPState *s = opaque;
3209
    int ret;
3210
    for(;;) {
3211
        ret = write(s->fd, buf, size);
3212
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3213
        } else {
3214
            break;
3215
        }
3216
    }
3217
}
3218

    
3219
static void tap_send(void *opaque)
3220
{
3221
    TAPState *s = opaque;
3222
    uint8_t buf[4096];
3223
    int size;
3224

    
3225
    size = read(s->fd, buf, sizeof(buf));
3226
    if (size > 0) {
3227
        qemu_send_packet(s->vc, buf, size);
3228
    }
3229
}
3230

    
3231
/* fd support */
3232

    
3233
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3234
{
3235
    TAPState *s;
3236

    
3237
    s = qemu_mallocz(sizeof(TAPState));
3238
    if (!s)
3239
        return NULL;
3240
    s->fd = fd;
3241
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3242
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3243
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3244
    return s;
3245
}
3246

    
3247
#ifdef _BSD
3248
static int tap_open(char *ifname, int ifname_size)
3249
{
3250
    int fd;
3251
    char *dev;
3252
    struct stat s;
3253

    
3254
    fd = open("/dev/tap", O_RDWR);
3255
    if (fd < 0) {
3256
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3257
        return -1;
3258
    }
3259

    
3260
    fstat(fd, &s);
3261
    dev = devname(s.st_rdev, S_IFCHR);
3262
    pstrcpy(ifname, ifname_size, dev);
3263

    
3264
    fcntl(fd, F_SETFL, O_NONBLOCK);
3265
    return fd;
3266
}
3267
#elif defined(__sun__)
3268
static int tap_open(char *ifname, int ifname_size)
3269
{
3270
    fprintf(stderr, "warning: tap_open not yet implemented\n");
3271
    return -1;
3272
}
3273
#else
3274
static int tap_open(char *ifname, int ifname_size)
3275
{
3276
    struct ifreq ifr;
3277
    int fd, ret;
3278
    
3279
    fd = open("/dev/net/tun", O_RDWR);
3280
    if (fd < 0) {
3281
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3282
        return -1;
3283
    }
3284
    memset(&ifr, 0, sizeof(ifr));
3285
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3286
    if (ifname[0] != '\0')
3287
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3288
    else
3289
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3290
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3291
    if (ret != 0) {
3292
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3293
        close(fd);
3294
        return -1;
3295
    }
3296
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3297
    fcntl(fd, F_SETFL, O_NONBLOCK);
3298
    return fd;
3299
}
3300
#endif
3301

    
3302
static int net_tap_init(VLANState *vlan, const char *ifname1,
3303
                        const char *setup_script)
3304
{
3305
    TAPState *s;
3306
    int pid, status, fd;
3307
    char *args[3];
3308
    char **parg;
3309
    char ifname[128];
3310

    
3311
    if (ifname1 != NULL)
3312
        pstrcpy(ifname, sizeof(ifname), ifname1);
3313
    else
3314
        ifname[0] = '\0';
3315
    fd = tap_open(ifname, sizeof(ifname));
3316
    if (fd < 0)
3317
        return -1;
3318

    
3319
    if (!setup_script)
3320
        setup_script = "";
3321
    if (setup_script[0] != '\0') {
3322
        /* try to launch network init script */
3323
        pid = fork();
3324
        if (pid >= 0) {
3325
            if (pid == 0) {
3326
                parg = args;
3327
                *parg++ = (char *)setup_script;
3328
                *parg++ = ifname;
3329
                *parg++ = NULL;
3330
                execv(setup_script, args);
3331
                _exit(1);
3332
            }
3333
            while (waitpid(pid, &status, 0) != pid);
3334
            if (!WIFEXITED(status) ||
3335
                WEXITSTATUS(status) != 0) {
3336
                fprintf(stderr, "%s: could not launch network script\n",
3337
                        setup_script);
3338
                return -1;
3339
            }
3340
        }
3341
    }
3342
    s = net_tap_fd_init(vlan, fd);
3343
    if (!s)
3344
        return -1;
3345
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3346
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3347
    return 0;
3348
}
3349

    
3350
#endif /* !_WIN32 */
3351

    
3352
/* network connection */
3353
typedef struct NetSocketState {
3354
    VLANClientState *vc;
3355
    int fd;
3356
    int state; /* 0 = getting length, 1 = getting data */
3357
    int index;
3358
    int packet_len;
3359
    uint8_t buf[4096];
3360
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3361
} NetSocketState;
3362

    
3363
typedef struct NetSocketListenState {
3364
    VLANState *vlan;
3365
    int fd;
3366
} NetSocketListenState;
3367

    
3368
/* XXX: we consider we can send the whole packet without blocking */
3369
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3370
{
3371
    NetSocketState *s = opaque;
3372
    uint32_t len;
3373
    len = htonl(size);
3374

    
3375
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3376
    send_all(s->fd, buf, size);
3377
}
3378

    
3379
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3380
{
3381
    NetSocketState *s = opaque;
3382
    sendto(s->fd, buf, size, 0, 
3383
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3384
}
3385

    
3386
static void net_socket_send(void *opaque)
3387
{
3388
    NetSocketState *s = opaque;
3389
    int l, size, err;
3390
    uint8_t buf1[4096];
3391
    const uint8_t *buf;
3392

    
3393
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3394
    if (size < 0) {
3395
        err = socket_error();
3396
        if (err != EWOULDBLOCK) 
3397
            goto eoc;
3398
    } else if (size == 0) {
3399
        /* end of connection */
3400
    eoc:
3401
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3402
        closesocket(s->fd);
3403
        return;
3404
    }
3405
    buf = buf1;
3406
    while (size > 0) {
3407
        /* reassemble a packet from the network */
3408
        switch(s->state) {
3409
        case 0:
3410
            l = 4 - s->index;
3411
            if (l > size)
3412
                l = size;
3413
            memcpy(s->buf + s->index, buf, l);
3414
            buf += l;
3415
            size -= l;
3416
            s->index += l;
3417
            if (s->index == 4) {
3418
                /* got length */
3419
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3420
                s->index = 0;
3421
                s->state = 1;
3422
            }
3423
            break;
3424
        case 1:
3425
            l = s->packet_len - s->index;
3426
            if (l > size)
3427
                l = size;
3428
            memcpy(s->buf + s->index, buf, l);
3429
            s->index += l;
3430
            buf += l;
3431
            size -= l;
3432
            if (s->index >= s->packet_len) {
3433
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3434
                s->index = 0;
3435
                s->state = 0;
3436
            }
3437
            break;
3438
        }
3439
    }
3440
}
3441

    
3442
static void net_socket_send_dgram(void *opaque)
3443
{
3444
    NetSocketState *s = opaque;
3445
    int size;
3446

    
3447
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3448
    if (size < 0) 
3449
        return;
3450
    if (size == 0) {
3451
        /* end of connection */
3452
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3453
        return;
3454
    }
3455
    qemu_send_packet(s->vc, s->buf, size);
3456
}
3457

    
3458
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3459
{
3460
    struct ip_mreq imr;
3461
    int fd;
3462
    int val, ret;
3463
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3464
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3465
                inet_ntoa(mcastaddr->sin_addr), 
3466
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3467
        return -1;
3468

    
3469
    }
3470
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3471
    if (fd < 0) {
3472
        perror("socket(PF_INET, SOCK_DGRAM)");
3473
        return -1;
3474
    }
3475

    
3476
    val = 1;
3477
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3478
                   (const char *)&val, sizeof(val));
3479
    if (ret < 0) {
3480
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3481
        goto fail;
3482
    }
3483

    
3484
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3485
    if (ret < 0) {
3486
        perror("bind");
3487
        goto fail;
3488
    }
3489
    
3490
    /* Add host to multicast group */
3491
    imr.imr_multiaddr = mcastaddr->sin_addr;
3492
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3493

    
3494
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3495
                     (const char *)&imr, sizeof(struct ip_mreq));
3496
    if (ret < 0) {
3497
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3498
        goto fail;
3499
    }
3500

    
3501
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3502
    val = 1;
3503
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3504
                   (const char *)&val, sizeof(val));
3505
    if (ret < 0) {
3506
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3507
        goto fail;
3508
    }
3509

    
3510
    socket_set_nonblock(fd);
3511
    return fd;
3512
fail:
3513
    if (fd >= 0) 
3514
        closesocket(fd);
3515
    return -1;
3516
}
3517

    
3518
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3519
                                          int is_connected)
3520
{
3521
    struct sockaddr_in saddr;
3522
    int newfd;
3523
    socklen_t saddr_len;
3524
    NetSocketState *s;
3525

    
3526
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3527
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3528
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3529
     */
3530

    
3531
    if (is_connected) {
3532
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3533
            /* must be bound */
3534
            if (saddr.sin_addr.s_addr==0) {
3535
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3536
                        fd);
3537
                return NULL;
3538
            }
3539
            /* clone dgram socket */
3540
            newfd = net_socket_mcast_create(&saddr);
3541
            if (newfd < 0) {
3542
                /* error already reported by net_socket_mcast_create() */
3543
                close(fd);
3544
                return NULL;
3545
            }
3546
            /* clone newfd to fd, close newfd */
3547
            dup2(newfd, fd);
3548
            close(newfd);
3549
        
3550
        } else {
3551
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3552
                    fd, strerror(errno));
3553
            return NULL;
3554
        }
3555
    }
3556

    
3557
    s = qemu_mallocz(sizeof(NetSocketState));
3558
    if (!s)
3559
        return NULL;
3560
    s->fd = fd;
3561

    
3562
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3563
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3564

    
3565
    /* mcast: save bound address as dst */
3566
    if (is_connected) s->dgram_dst=saddr;
3567

    
3568
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3569
            "socket: fd=%d (%s mcast=%s:%d)", 
3570
            fd, is_connected? "cloned" : "",
3571
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3572
    return s;
3573
}
3574

    
3575
static void net_socket_connect(void *opaque)
3576
{
3577
    NetSocketState *s = opaque;
3578
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3579
}
3580

    
3581
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3582
                                          int is_connected)
3583
{
3584
    NetSocketState *s;
3585
    s = qemu_mallocz(sizeof(NetSocketState));
3586
    if (!s)
3587
        return NULL;
3588
    s->fd = fd;
3589
    s->vc = qemu_new_vlan_client(vlan, 
3590
                                 net_socket_receive, NULL, s);
3591
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3592
             "socket: fd=%d", fd);
3593
    if (is_connected) {
3594
        net_socket_connect(s);
3595
    } else {
3596
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3597
    }
3598
    return s;
3599
}
3600

    
3601
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3602
                                          int is_connected)
3603
{
3604
    int so_type=-1, optlen=sizeof(so_type);
3605

    
3606
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3607
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3608
        return NULL;
3609
    }
3610
    switch(so_type) {
3611
    case SOCK_DGRAM:
3612
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3613
    case SOCK_STREAM:
3614
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3615
    default:
3616
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3617
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3618
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3619
    }
3620
    return NULL;
3621
}
3622

    
3623
static void net_socket_accept(void *opaque)
3624
{
3625
    NetSocketListenState *s = opaque;    
3626
    NetSocketState *s1;
3627
    struct sockaddr_in saddr;
3628
    socklen_t len;
3629
    int fd;
3630

    
3631
    for(;;) {
3632
        len = sizeof(saddr);
3633
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3634
        if (fd < 0 && errno != EINTR) {
3635
            return;
3636
        } else if (fd >= 0) {
3637
            break;
3638
        }
3639
    }
3640
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3641
    if (!s1) {
3642
        closesocket(fd);
3643
    } else {
3644
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3645
                 "socket: connection from %s:%d", 
3646
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3647
    }
3648
}
3649

    
3650
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3651
{
3652
    NetSocketListenState *s;
3653
    int fd, val, ret;
3654
    struct sockaddr_in saddr;
3655

    
3656
    if (parse_host_port(&saddr, host_str) < 0)
3657
        return -1;
3658
    
3659
    s = qemu_mallocz(sizeof(NetSocketListenState));
3660
    if (!s)
3661
        return -1;
3662

    
3663
    fd = socket(PF_INET, SOCK_STREAM, 0);
3664
    if (fd < 0) {
3665
        perror("socket");
3666
        return -1;
3667
    }
3668
    socket_set_nonblock(fd);
3669

    
3670
    /* allow fast reuse */
3671
    val = 1;
3672
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3673
    
3674
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3675
    if (ret < 0) {
3676
        perror("bind");
3677
        return -1;
3678
    }
3679
    ret = listen(fd, 0);
3680
    if (ret < 0) {
3681
        perror("listen");
3682
        return -1;
3683
    }
3684
    s->vlan = vlan;
3685
    s->fd = fd;
3686
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3687
    return 0;
3688
}
3689

    
3690
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3691
{
3692
    NetSocketState *s;
3693
    int fd, connected, ret, err;
3694
    struct sockaddr_in saddr;
3695

    
3696
    if (parse_host_port(&saddr, host_str) < 0)
3697
        return -1;
3698

    
3699
    fd = socket(PF_INET, SOCK_STREAM, 0);
3700
    if (fd < 0) {
3701
        perror("socket");
3702
        return -1;
3703
    }
3704
    socket_set_nonblock(fd);
3705

    
3706
    connected = 0;
3707
    for(;;) {
3708
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3709
        if (ret < 0) {
3710
            err = socket_error();
3711
            if (err == EINTR || err == EWOULDBLOCK) {
3712
            } else if (err == EINPROGRESS) {
3713
                break;
3714
            } else {
3715
                perror("connect");
3716
                closesocket(fd);
3717
                return -1;
3718
            }
3719
        } else {
3720
            connected = 1;
3721
            break;
3722
        }
3723
    }
3724
    s = net_socket_fd_init(vlan, fd, connected);
3725
    if (!s)
3726
        return -1;
3727
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3728
             "socket: connect to %s:%d", 
3729
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3730
    return 0;
3731
}
3732

    
3733
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3734
{
3735
    NetSocketState *s;
3736
    int fd;
3737
    struct sockaddr_in saddr;
3738

    
3739
    if (parse_host_port(&saddr, host_str) < 0)
3740
        return -1;
3741

    
3742

    
3743
    fd = net_socket_mcast_create(&saddr);
3744
    if (fd < 0)
3745
        return -1;
3746

    
3747
    s = net_socket_fd_init(vlan, fd, 0);
3748
    if (!s)
3749
        return -1;
3750

    
3751
    s->dgram_dst = saddr;
3752
    
3753
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3754
             "socket: mcast=%s:%d", 
3755
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3756
    return 0;
3757

    
3758
}
3759

    
3760
static int get_param_value(char *buf, int buf_size,
3761
                           const char *tag, const char *str)
3762
{
3763
    const char *p;
3764
    char *q;
3765
    char option[128];
3766

    
3767
    p = str;
3768
    for(;;) {
3769
        q = option;
3770
        while (*p != '\0' && *p != '=') {
3771
            if ((q - option) < sizeof(option) - 1)
3772
                *q++ = *p;
3773
            p++;
3774
        }
3775
        *q = '\0';
3776
        if (*p != '=')
3777
            break;
3778
        p++;
3779
        if (!strcmp(tag, option)) {
3780
            q = buf;
3781
            while (*p != '\0' && *p != ',') {
3782
                if ((q - buf) < buf_size - 1)
3783
                    *q++ = *p;
3784
                p++;
3785
            }
3786
            *q = '\0';
3787
            return q - buf;
3788
        } else {
3789
            while (*p != '\0' && *p != ',') {
3790
                p++;
3791
            }
3792
        }
3793
        if (*p != ',')
3794
            break;
3795
        p++;
3796
    }
3797
    return 0;
3798
}
3799

    
3800
static int net_client_init(const char *str)
3801
{
3802
    const char *p;
3803
    char *q;
3804
    char device[64];
3805
    char buf[1024];
3806
    int vlan_id, ret;
3807
    VLANState *vlan;
3808

    
3809
    p = str;
3810
    q = device;
3811
    while (*p != '\0' && *p != ',') {
3812
        if ((q - device) < sizeof(device) - 1)
3813
            *q++ = *p;
3814
        p++;
3815
    }
3816
    *q = '\0';
3817
    if (*p == ',')
3818
        p++;
3819
    vlan_id = 0;
3820
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3821
        vlan_id = strtol(buf, NULL, 0);
3822
    }
3823
    vlan = qemu_find_vlan(vlan_id);
3824
    if (!vlan) {
3825
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3826
        return -1;
3827
    }
3828
    if (!strcmp(device, "nic")) {
3829
        NICInfo *nd;
3830
        uint8_t *macaddr;
3831

    
3832
        if (nb_nics >= MAX_NICS) {
3833
            fprintf(stderr, "Too Many NICs\n");
3834
            return -1;
3835
        }
3836
        nd = &nd_table[nb_nics];
3837
        macaddr = nd->macaddr;
3838
        macaddr[0] = 0x52;
3839
        macaddr[1] = 0x54;
3840
        macaddr[2] = 0x00;
3841
        macaddr[3] = 0x12;
3842
        macaddr[4] = 0x34;
3843
        macaddr[5] = 0x56 + nb_nics;
3844

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

    
3930
void do_info_network(void)
3931
{
3932
    VLANState *vlan;
3933
    VLANClientState *vc;
3934

    
3935
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3936
        term_printf("VLAN %d devices:\n", vlan->id);
3937
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3938
            term_printf("  %s\n", vc->info_str);
3939
    }
3940
}
3941

    
3942
/***********************************************************/
3943
/* USB devices */
3944

    
3945
static USBPort *used_usb_ports;
3946
static USBPort *free_usb_ports;
3947

    
3948
/* ??? Maybe change this to register a hub to keep track of the topology.  */
3949
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3950
                            usb_attachfn attach)
3951
{
3952
    port->opaque = opaque;
3953
    port->index = index;
3954
    port->attach = attach;
3955
    port->next = free_usb_ports;
3956
    free_usb_ports = port;
3957
}
3958

    
3959
static int usb_device_add(const char *devname)
3960
{
3961
    const char *p;
3962
    USBDevice *dev;
3963
    USBPort *port;
3964

    
3965
    if (!free_usb_ports)
3966
        return -1;
3967

    
3968
    if (strstart(devname, "host:", &p)) {
3969
        dev = usb_host_device_open(p);
3970
    } else if (!strcmp(devname, "mouse")) {
3971
        dev = usb_mouse_init();
3972
    } else if (!strcmp(devname, "tablet")) {
3973
        dev = usb_tablet_init();
3974
    } else if (strstart(devname, "disk:", &p)) {
3975
        dev = usb_msd_init(p);
3976
    } else {
3977
        return -1;
3978
    }
3979
    if (!dev)
3980
        return -1;
3981

    
3982
    /* Find a USB port to add the device to.  */
3983
    port = free_usb_ports;
3984
    if (!port->next) {
3985
        USBDevice *hub;
3986

    
3987
        /* Create a new hub and chain it on.  */
3988
        free_usb_ports = NULL;
3989
        port->next = used_usb_ports;
3990
        used_usb_ports = port;
3991

    
3992
        hub = usb_hub_init(VM_USB_HUB_SIZE);
3993
        usb_attach(port, hub);
3994
        port = free_usb_ports;
3995
    }
3996

    
3997
    free_usb_ports = port->next;
3998
    port->next = used_usb_ports;
3999
    used_usb_ports = port;
4000
    usb_attach(port, dev);
4001
    return 0;
4002
}
4003

    
4004
static int usb_device_del(const char *devname)
4005
{
4006
    USBPort *port;
4007
    USBPort **lastp;
4008
    USBDevice *dev;
4009
    int bus_num, addr;
4010
    const char *p;
4011

    
4012
    if (!used_usb_ports)
4013
        return -1;
4014

    
4015
    p = strchr(devname, '.');
4016
    if (!p) 
4017
        return -1;
4018
    bus_num = strtoul(devname, NULL, 0);
4019
    addr = strtoul(p + 1, NULL, 0);
4020
    if (bus_num != 0)
4021
        return -1;
4022

    
4023
    lastp = &used_usb_ports;
4024
    port = used_usb_ports;
4025
    while (port && port->dev->addr != addr) {
4026
        lastp = &port->next;
4027
        port = port->next;
4028
    }
4029

    
4030
    if (!port)
4031
        return -1;
4032

    
4033
    dev = port->dev;
4034
    *lastp = port->next;
4035
    usb_attach(port, NULL);
4036
    dev->handle_destroy(dev);
4037
    port->next = free_usb_ports;
4038
    free_usb_ports = port;
4039
    return 0;
4040
}
4041

    
4042
void do_usb_add(const char *devname)
4043
{
4044
    int ret;
4045
    ret = usb_device_add(devname);
4046
    if (ret < 0) 
4047
        term_printf("Could not add USB device '%s'\n", devname);
4048
}
4049

    
4050
void do_usb_del(const char *devname)
4051
{
4052
    int ret;
4053
    ret = usb_device_del(devname);
4054
    if (ret < 0) 
4055
        term_printf("Could not remove USB device '%s'\n", devname);
4056
}
4057

    
4058
void usb_info(void)
4059
{
4060
    USBDevice *dev;
4061
    USBPort *port;
4062
    const char *speed_str;
4063

    
4064
    if (!usb_enabled) {
4065
        term_printf("USB support not enabled\n");
4066
        return;
4067
    }
4068

    
4069
    for (port = used_usb_ports; port; port = port->next) {
4070
        dev = port->dev;
4071
        if (!dev)
4072
            continue;
4073
        switch(dev->speed) {
4074
        case USB_SPEED_LOW: 
4075
            speed_str = "1.5"; 
4076
            break;
4077
        case USB_SPEED_FULL: 
4078
            speed_str = "12"; 
4079
            break;
4080
        case USB_SPEED_HIGH: 
4081
            speed_str = "480"; 
4082
            break;
4083
        default:
4084
            speed_str = "?"; 
4085
            break;
4086
        }
4087
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4088
                    0, dev->addr, speed_str, dev->devname);
4089
    }
4090
}
4091

    
4092
/***********************************************************/
4093
/* pid file */
4094

    
4095
static char *pid_filename;
4096

    
4097
/* Remove PID file. Called on normal exit */
4098

    
4099
static void remove_pidfile(void) 
4100
{
4101
    unlink (pid_filename);
4102
}
4103

    
4104
static void create_pidfile(const char *filename)
4105
{
4106
    struct stat pidstat;
4107
    FILE *f;
4108

    
4109
    /* Try to write our PID to the named file */
4110
    if (stat(filename, &pidstat) < 0) {
4111
        if (errno == ENOENT) {
4112
            if ((f = fopen (filename, "w")) == NULL) {
4113
                perror("Opening pidfile");
4114
                exit(1);
4115
            }
4116
            fprintf(f, "%d\n", getpid());
4117
            fclose(f);
4118
            pid_filename = qemu_strdup(filename);
4119
            if (!pid_filename) {
4120
                fprintf(stderr, "Could not save PID filename");
4121
                exit(1);
4122
            }
4123
            atexit(remove_pidfile);
4124
        }
4125
    } else {
4126
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
4127
                filename);
4128
        exit(1);
4129
    }
4130
}
4131

    
4132
/***********************************************************/
4133
/* dumb display */
4134

    
4135
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4136
{
4137
}
4138

    
4139
static void dumb_resize(DisplayState *ds, int w, int h)
4140
{
4141
}
4142

    
4143
static void dumb_refresh(DisplayState *ds)
4144
{
4145
    vga_hw_update();
4146
}
4147

    
4148
void dumb_display_init(DisplayState *ds)
4149
{
4150
    ds->data = NULL;
4151
    ds->linesize = 0;
4152
    ds->depth = 0;
4153
    ds->dpy_update = dumb_update;
4154
    ds->dpy_resize = dumb_resize;
4155
    ds->dpy_refresh = dumb_refresh;
4156
}
4157

    
4158
/***********************************************************/
4159
/* I/O handling */
4160

    
4161
#define MAX_IO_HANDLERS 64
4162

    
4163
typedef struct IOHandlerRecord {
4164
    int fd;
4165
    IOCanRWHandler *fd_read_poll;
4166
    IOHandler *fd_read;
4167
    IOHandler *fd_write;
4168
    void *opaque;
4169
    /* temporary data */
4170
    struct pollfd *ufd;
4171
    struct IOHandlerRecord *next;
4172
} IOHandlerRecord;
4173

    
4174
static IOHandlerRecord *first_io_handler;
4175

    
4176
/* XXX: fd_read_poll should be suppressed, but an API change is
4177
   necessary in the character devices to suppress fd_can_read(). */
4178
int qemu_set_fd_handler2(int fd, 
4179
                         IOCanRWHandler *fd_read_poll, 
4180
                         IOHandler *fd_read, 
4181
                         IOHandler *fd_write, 
4182
                         void *opaque)
4183
{
4184
    IOHandlerRecord **pioh, *ioh;
4185

    
4186
    if (!fd_read && !fd_write) {
4187
        pioh = &first_io_handler;
4188
        for(;;) {
4189
            ioh = *pioh;
4190
            if (ioh == NULL)
4191
                break;
4192
            if (ioh->fd == fd) {
4193
                *pioh = ioh->next;
4194
                qemu_free(ioh);
4195
                break;
4196
            }
4197
            pioh = &ioh->next;
4198
        }
4199
    } else {
4200
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4201
            if (ioh->fd == fd)
4202
                goto found;
4203
        }
4204
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4205
        if (!ioh)
4206
            return -1;
4207
        ioh->next = first_io_handler;
4208
        first_io_handler = ioh;
4209
    found:
4210
        ioh->fd = fd;
4211
        ioh->fd_read_poll = fd_read_poll;
4212
        ioh->fd_read = fd_read;
4213
        ioh->fd_write = fd_write;
4214
        ioh->opaque = opaque;
4215
    }
4216
    return 0;
4217
}
4218

    
4219
int qemu_set_fd_handler(int fd, 
4220
                        IOHandler *fd_read, 
4221
                        IOHandler *fd_write, 
4222
                        void *opaque)
4223
{
4224
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4225
}
4226

    
4227
/***********************************************************/
4228
/* Polling handling */
4229

    
4230
typedef struct PollingEntry {
4231
    PollingFunc *func;
4232
    void *opaque;
4233
    struct PollingEntry *next;
4234
} PollingEntry;
4235

    
4236
static PollingEntry *first_polling_entry;
4237

    
4238
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4239
{
4240
    PollingEntry **ppe, *pe;
4241
    pe = qemu_mallocz(sizeof(PollingEntry));
4242
    if (!pe)
4243
        return -1;
4244
    pe->func = func;
4245
    pe->opaque = opaque;
4246
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4247
    *ppe = pe;
4248
    return 0;
4249
}
4250

    
4251
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4252
{
4253
    PollingEntry **ppe, *pe;
4254
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4255
        pe = *ppe;
4256
        if (pe->func == func && pe->opaque == opaque) {
4257
            *ppe = pe->next;
4258
            qemu_free(pe);
4259
            break;
4260
        }
4261
    }
4262
}
4263

    
4264
#ifdef _WIN32
4265
/***********************************************************/
4266
/* Wait objects support */
4267
typedef struct WaitObjects {
4268
    int num;
4269
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4270
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4271
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4272
} WaitObjects;
4273

    
4274
static WaitObjects wait_objects = {0};
4275
    
4276
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4277
{
4278
    WaitObjects *w = &wait_objects;
4279

    
4280
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4281
        return -1;
4282
    w->events[w->num] = handle;
4283
    w->func[w->num] = func;
4284
    w->opaque[w->num] = opaque;
4285
    w->num++;
4286
    return 0;
4287
}
4288

    
4289
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4290
{
4291
    int i, found;
4292
    WaitObjects *w = &wait_objects;
4293

    
4294
    found = 0;
4295
    for (i = 0; i < w->num; i++) {
4296
        if (w->events[i] == handle)
4297
            found = 1;
4298
        if (found) {
4299
            w->events[i] = w->events[i + 1];
4300
            w->func[i] = w->func[i + 1];
4301
            w->opaque[i] = w->opaque[i + 1];
4302
        }            
4303
    }
4304
    if (found)
4305
        w->num--;
4306
}
4307
#endif
4308

    
4309
/***********************************************************/
4310
/* savevm/loadvm support */
4311

    
4312
#define IO_BUF_SIZE 32768
4313

    
4314
struct QEMUFile {
4315
    FILE *outfile;
4316
    BlockDriverState *bs;
4317
    int is_file;
4318
    int is_writable;
4319
    int64_t base_offset;
4320
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4321
                           when reading */
4322
    int buf_index;
4323
    int buf_size; /* 0 when writing */
4324
    uint8_t buf[IO_BUF_SIZE];
4325
};
4326

    
4327
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4328
{
4329
    QEMUFile *f;
4330

    
4331
    f = qemu_mallocz(sizeof(QEMUFile));
4332
    if (!f)
4333
        return NULL;
4334
    if (!strcmp(mode, "wb")) {
4335
        f->is_writable = 1;
4336
    } else if (!strcmp(mode, "rb")) {
4337
        f->is_writable = 0;
4338
    } else {
4339
        goto fail;
4340
    }
4341
    f->outfile = fopen(filename, mode);
4342
    if (!f->outfile)
4343
        goto fail;
4344
    f->is_file = 1;
4345
    return f;
4346
 fail:
4347
    if (f->outfile)
4348
        fclose(f->outfile);
4349
    qemu_free(f);
4350
    return NULL;
4351
}
4352

    
4353
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4354
{
4355
    QEMUFile *f;
4356

    
4357
    f = qemu_mallocz(sizeof(QEMUFile));
4358
    if (!f)
4359
        return NULL;
4360
    f->is_file = 0;
4361
    f->bs = bs;
4362
    f->is_writable = is_writable;
4363
    f->base_offset = offset;
4364
    return f;
4365
}
4366

    
4367
void qemu_fflush(QEMUFile *f)
4368
{
4369
    if (!f->is_writable)
4370
        return;
4371
    if (f->buf_index > 0) {
4372
        if (f->is_file) {
4373
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4374
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4375
        } else {
4376
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4377
                        f->buf, f->buf_index);
4378
        }
4379
        f->buf_offset += f->buf_index;
4380
        f->buf_index = 0;
4381
    }
4382
}
4383

    
4384
static void qemu_fill_buffer(QEMUFile *f)
4385
{
4386
    int len;
4387

    
4388
    if (f->is_writable)
4389
        return;
4390
    if (f->is_file) {
4391
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4392
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4393
        if (len < 0)
4394
            len = 0;
4395
    } else {
4396
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4397
                         f->buf, IO_BUF_SIZE);
4398
        if (len < 0)
4399
            len = 0;
4400
    }
4401
    f->buf_index = 0;
4402
    f->buf_size = len;
4403
    f->buf_offset += len;
4404
}
4405

    
4406
void qemu_fclose(QEMUFile *f)
4407
{
4408
    if (f->is_writable)
4409
        qemu_fflush(f);
4410
    if (f->is_file) {
4411
        fclose(f->outfile);
4412
    }
4413
    qemu_free(f);
4414
}
4415

    
4416
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4417
{
4418
    int l;
4419
    while (size > 0) {
4420
        l = IO_BUF_SIZE - f->buf_index;
4421
        if (l > size)
4422
            l = size;
4423
        memcpy(f->buf + f->buf_index, buf, l);
4424
        f->buf_index += l;
4425
        buf += l;
4426
        size -= l;
4427
        if (f->buf_index >= IO_BUF_SIZE)
4428
            qemu_fflush(f);
4429
    }
4430
}
4431

    
4432
void qemu_put_byte(QEMUFile *f, int v)
4433
{
4434
    f->buf[f->buf_index++] = v;
4435
    if (f->buf_index >= IO_BUF_SIZE)
4436
        qemu_fflush(f);
4437
}
4438

    
4439
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4440
{
4441
    int size, l;
4442

    
4443
    size = size1;
4444
    while (size > 0) {
4445
        l = f->buf_size - f->buf_index;
4446
        if (l == 0) {
4447
            qemu_fill_buffer(f);
4448
            l = f->buf_size - f->buf_index;
4449
            if (l == 0)
4450
                break;
4451
        }
4452
        if (l > size)
4453
            l = size;
4454
        memcpy(buf, f->buf + f->buf_index, l);
4455
        f->buf_index += l;
4456
        buf += l;
4457
        size -= l;
4458
    }
4459
    return size1 - size;
4460
}
4461

    
4462
int qemu_get_byte(QEMUFile *f)
4463
{
4464
    if (f->buf_index >= f->buf_size) {
4465
        qemu_fill_buffer(f);
4466
        if (f->buf_index >= f->buf_size)
4467
            return 0;
4468
    }
4469
    return f->buf[f->buf_index++];
4470
}
4471

    
4472
int64_t qemu_ftell(QEMUFile *f)
4473
{
4474
    return f->buf_offset - f->buf_size + f->buf_index;
4475
}
4476

    
4477
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4478
{
4479
    if (whence == SEEK_SET) {
4480
        /* nothing to do */
4481
    } else if (whence == SEEK_CUR) {
4482
        pos += qemu_ftell(f);
4483
    } else {
4484
        /* SEEK_END not supported */
4485
        return -1;
4486
    }
4487
    if (f->is_writable) {
4488
        qemu_fflush(f);
4489
        f->buf_offset = pos;
4490
    } else {
4491
        f->buf_offset = pos;
4492
        f->buf_index = 0;
4493
        f->buf_size = 0;
4494
    }
4495
    return pos;
4496
}
4497

    
4498
void qemu_put_be16(QEMUFile *f, unsigned int v)
4499
{
4500
    qemu_put_byte(f, v >> 8);
4501
    qemu_put_byte(f, v);
4502
}
4503

    
4504
void qemu_put_be32(QEMUFile *f, unsigned int v)
4505
{
4506
    qemu_put_byte(f, v >> 24);
4507
    qemu_put_byte(f, v >> 16);
4508
    qemu_put_byte(f, v >> 8);
4509
    qemu_put_byte(f, v);
4510
}
4511

    
4512
void qemu_put_be64(QEMUFile *f, uint64_t v)
4513
{
4514
    qemu_put_be32(f, v >> 32);
4515
    qemu_put_be32(f, v);
4516
}
4517

    
4518
unsigned int qemu_get_be16(QEMUFile *f)
4519
{
4520
    unsigned int v;
4521
    v = qemu_get_byte(f) << 8;
4522
    v |= qemu_get_byte(f);
4523
    return v;
4524
}
4525

    
4526
unsigned int qemu_get_be32(QEMUFile *f)
4527
{
4528
    unsigned int v;
4529
    v = qemu_get_byte(f) << 24;
4530
    v |= qemu_get_byte(f) << 16;
4531
    v |= qemu_get_byte(f) << 8;
4532
    v |= qemu_get_byte(f);
4533
    return v;
4534
}
4535

    
4536
uint64_t qemu_get_be64(QEMUFile *f)
4537
{
4538
    uint64_t v;
4539
    v = (uint64_t)qemu_get_be32(f) << 32;
4540
    v |= qemu_get_be32(f);
4541
    return v;
4542
}
4543

    
4544
typedef struct SaveStateEntry {
4545
    char idstr[256];
4546
    int instance_id;
4547
    int version_id;
4548
    SaveStateHandler *save_state;
4549
    LoadStateHandler *load_state;
4550
    void *opaque;
4551
    struct SaveStateEntry *next;
4552
} SaveStateEntry;
4553

    
4554
static SaveStateEntry *first_se;
4555

    
4556
int register_savevm(const char *idstr, 
4557
                    int instance_id, 
4558
                    int version_id,
4559
                    SaveStateHandler *save_state,
4560
                    LoadStateHandler *load_state,
4561
                    void *opaque)
4562
{
4563
    SaveStateEntry *se, **pse;
4564

    
4565
    se = qemu_malloc(sizeof(SaveStateEntry));
4566
    if (!se)
4567
        return -1;
4568
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4569
    se->instance_id = instance_id;
4570
    se->version_id = version_id;
4571
    se->save_state = save_state;
4572
    se->load_state = load_state;
4573
    se->opaque = opaque;
4574
    se->next = NULL;
4575

    
4576
    /* add at the end of list */
4577
    pse = &first_se;
4578
    while (*pse != NULL)
4579
        pse = &(*pse)->next;
4580
    *pse = se;
4581
    return 0;
4582
}
4583

    
4584
#define QEMU_VM_FILE_MAGIC   0x5145564d
4585
#define QEMU_VM_FILE_VERSION 0x00000002
4586

    
4587
int qemu_savevm_state(QEMUFile *f)
4588
{
4589
    SaveStateEntry *se;
4590
    int len, ret;
4591
    int64_t cur_pos, len_pos, total_len_pos;
4592

    
4593
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4594
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4595
    total_len_pos = qemu_ftell(f);
4596
    qemu_put_be64(f, 0); /* total size */
4597

    
4598
    for(se = first_se; se != NULL; se = se->next) {
4599
        /* ID string */
4600
        len = strlen(se->idstr);
4601
        qemu_put_byte(f, len);
4602
        qemu_put_buffer(f, se->idstr, len);
4603

    
4604
        qemu_put_be32(f, se->instance_id);
4605
        qemu_put_be32(f, se->version_id);
4606

    
4607
        /* record size: filled later */
4608
        len_pos = qemu_ftell(f);
4609
        qemu_put_be32(f, 0);
4610
        
4611
        se->save_state(f, se->opaque);
4612

    
4613
        /* fill record size */
4614
        cur_pos = qemu_ftell(f);
4615
        len = cur_pos - len_pos - 4;
4616
        qemu_fseek(f, len_pos, SEEK_SET);
4617
        qemu_put_be32(f, len);
4618
        qemu_fseek(f, cur_pos, SEEK_SET);
4619
    }
4620
    cur_pos = qemu_ftell(f);
4621
    qemu_fseek(f, total_len_pos, SEEK_SET);
4622
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4623
    qemu_fseek(f, cur_pos, SEEK_SET);
4624

    
4625
    ret = 0;
4626
    return ret;
4627
}
4628

    
4629
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4630
{
4631
    SaveStateEntry *se;
4632

    
4633
    for(se = first_se; se != NULL; se = se->next) {
4634
        if (!strcmp(se->idstr, idstr) && 
4635
            instance_id == se->instance_id)
4636
            return se;
4637
    }
4638
    return NULL;
4639
}
4640

    
4641
int qemu_loadvm_state(QEMUFile *f)
4642
{
4643
    SaveStateEntry *se;
4644
    int len, ret, instance_id, record_len, version_id;
4645
    int64_t total_len, end_pos, cur_pos;
4646
    unsigned int v;
4647
    char idstr[256];
4648
    
4649
    v = qemu_get_be32(f);
4650
    if (v != QEMU_VM_FILE_MAGIC)
4651
        goto fail;
4652
    v = qemu_get_be32(f);
4653
    if (v != QEMU_VM_FILE_VERSION) {
4654
    fail:
4655
        ret = -1;
4656
        goto the_end;
4657
    }
4658
    total_len = qemu_get_be64(f);
4659
    end_pos = total_len + qemu_ftell(f);
4660
    for(;;) {
4661
        if (qemu_ftell(f) >= end_pos)
4662
            break;
4663
        len = qemu_get_byte(f);
4664
        qemu_get_buffer(f, idstr, len);
4665
        idstr[len] = '\0';
4666
        instance_id = qemu_get_be32(f);
4667
        version_id = qemu_get_be32(f);
4668
        record_len = qemu_get_be32(f);
4669
#if 0
4670
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4671
               idstr, instance_id, version_id, record_len);
4672
#endif
4673
        cur_pos = qemu_ftell(f);
4674
        se = find_se(idstr, instance_id);
4675
        if (!se) {
4676
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4677
                    instance_id, idstr);
4678
        } else {
4679
            ret = se->load_state(f, se->opaque, version_id);
4680
            if (ret < 0) {
4681
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4682
                        instance_id, idstr);
4683
            }
4684
        }
4685
        /* always seek to exact end of record */
4686
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4687
    }
4688
    ret = 0;
4689
 the_end:
4690
    return ret;
4691
}
4692

    
4693
/* device can contain snapshots */
4694
static int bdrv_can_snapshot(BlockDriverState *bs)
4695
{
4696
    return (bs &&
4697
            !bdrv_is_removable(bs) &&
4698
            !bdrv_is_read_only(bs));
4699
}
4700

    
4701
/* device must be snapshots in order to have a reliable snapshot */
4702
static int bdrv_has_snapshot(BlockDriverState *bs)
4703
{
4704
    return (bs &&
4705
            !bdrv_is_removable(bs) &&
4706
            !bdrv_is_read_only(bs));
4707
}
4708

    
4709
static BlockDriverState *get_bs_snapshots(void)
4710
{
4711
    BlockDriverState *bs;
4712
    int i;
4713

    
4714
    if (bs_snapshots)
4715
        return bs_snapshots;
4716
    for(i = 0; i <= MAX_DISKS; i++) {
4717
        bs = bs_table[i];
4718
        if (bdrv_can_snapshot(bs))
4719
            goto ok;
4720
    }
4721
    return NULL;
4722
 ok:
4723
    bs_snapshots = bs;
4724
    return bs;
4725
}
4726

    
4727
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4728
                              const char *name)
4729
{
4730
    QEMUSnapshotInfo *sn_tab, *sn;
4731
    int nb_sns, i, ret;
4732
    
4733
    ret = -ENOENT;
4734
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4735
    if (nb_sns < 0)
4736
        return ret;
4737
    for(i = 0; i < nb_sns; i++) {
4738
        sn = &sn_tab[i];
4739
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4740
            *sn_info = *sn;
4741
            ret = 0;
4742
            break;
4743
        }
4744
    }
4745
    qemu_free(sn_tab);
4746
    return ret;
4747
}
4748

    
4749
void do_savevm(const char *name)
4750
{
4751
    BlockDriverState *bs, *bs1;
4752
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4753
    int must_delete, ret, i;
4754
    BlockDriverInfo bdi1, *bdi = &bdi1;
4755
    QEMUFile *f;
4756
    int saved_vm_running;
4757
#ifdef _WIN32
4758
    struct _timeb tb;
4759
#else
4760
    struct timeval tv;
4761
#endif
4762

    
4763
    bs = get_bs_snapshots();
4764
    if (!bs) {
4765
        term_printf("No block device can accept snapshots\n");
4766
        return;
4767
    }
4768

    
4769
    /* ??? Should this occur after vm_stop?  */
4770
    qemu_aio_flush();
4771

    
4772
    saved_vm_running = vm_running;
4773
    vm_stop(0);
4774
    
4775
    must_delete = 0;
4776
    if (name) {
4777
        ret = bdrv_snapshot_find(bs, old_sn, name);
4778
        if (ret >= 0) {
4779
            must_delete = 1;
4780
        }
4781
    }
4782
    memset(sn, 0, sizeof(*sn));
4783
    if (must_delete) {
4784
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4785
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4786
    } else {
4787
        if (name)
4788
            pstrcpy(sn->name, sizeof(sn->name), name);
4789
    }
4790

    
4791
    /* fill auxiliary fields */
4792
#ifdef _WIN32
4793
    _ftime(&tb);
4794
    sn->date_sec = tb.time;
4795
    sn->date_nsec = tb.millitm * 1000000;
4796
#else
4797
    gettimeofday(&tv, NULL);
4798
    sn->date_sec = tv.tv_sec;
4799
    sn->date_nsec = tv.tv_usec * 1000;
4800
#endif
4801
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4802
    
4803
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4804
        term_printf("Device %s does not support VM state snapshots\n",
4805
                    bdrv_get_device_name(bs));
4806
        goto the_end;
4807
    }
4808
    
4809
    /* save the VM state */
4810
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4811
    if (!f) {
4812
        term_printf("Could not open VM state file\n");
4813
        goto the_end;
4814
    }
4815
    ret = qemu_savevm_state(f);
4816
    sn->vm_state_size = qemu_ftell(f);
4817
    qemu_fclose(f);
4818
    if (ret < 0) {
4819
        term_printf("Error %d while writing VM\n", ret);
4820
        goto the_end;
4821
    }
4822
    
4823
    /* create the snapshots */
4824

    
4825
    for(i = 0; i < MAX_DISKS; i++) {
4826
        bs1 = bs_table[i];
4827
        if (bdrv_has_snapshot(bs1)) {
4828
            if (must_delete) {
4829
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4830
                if (ret < 0) {
4831
                    term_printf("Error while deleting snapshot on '%s'\n",
4832
                                bdrv_get_device_name(bs1));
4833
                }
4834
            }
4835
            ret = bdrv_snapshot_create(bs1, sn);
4836
            if (ret < 0) {
4837
                term_printf("Error while creating snapshot on '%s'\n",
4838
                            bdrv_get_device_name(bs1));
4839
            }
4840
        }
4841
    }
4842

    
4843
 the_end:
4844
    if (saved_vm_running)
4845
        vm_start();
4846
}
4847

    
4848
void do_loadvm(const char *name)
4849
{
4850
    BlockDriverState *bs, *bs1;
4851
    BlockDriverInfo bdi1, *bdi = &bdi1;
4852
    QEMUFile *f;
4853
    int i, ret;
4854
    int saved_vm_running;
4855

    
4856
    bs = get_bs_snapshots();
4857
    if (!bs) {
4858
        term_printf("No block device supports snapshots\n");
4859
        return;
4860
    }
4861
    
4862
    /* Flush all IO requests so they don't interfere with the new state.  */
4863
    qemu_aio_flush();
4864

    
4865
    saved_vm_running = vm_running;
4866
    vm_stop(0);
4867

    
4868
    for(i = 0; i <= MAX_DISKS; i++) {
4869
        bs1 = bs_table[i];
4870
        if (bdrv_has_snapshot(bs1)) {
4871
            ret = bdrv_snapshot_goto(bs1, name);
4872
            if (ret < 0) {
4873
                if (bs != bs1)
4874
                    term_printf("Warning: ");
4875
                switch(ret) {
4876
                case -ENOTSUP:
4877
                    term_printf("Snapshots not supported on device '%s'\n",
4878
                                bdrv_get_device_name(bs1));
4879
                    break;
4880
                case -ENOENT:
4881
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
4882
                                name, bdrv_get_device_name(bs1));
4883
                    break;
4884
                default:
4885
                    term_printf("Error %d while activating snapshot on '%s'\n",
4886
                                ret, bdrv_get_device_name(bs1));
4887
                    break;
4888
                }
4889
                /* fatal on snapshot block device */
4890
                if (bs == bs1)
4891
                    goto the_end;
4892
            }
4893
        }
4894
    }
4895

    
4896
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4897
        term_printf("Device %s does not support VM state snapshots\n",
4898
                    bdrv_get_device_name(bs));
4899
        return;
4900
    }
4901
    
4902
    /* restore the VM state */
4903
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4904
    if (!f) {
4905
        term_printf("Could not open VM state file\n");
4906
        goto the_end;
4907
    }
4908
    ret = qemu_loadvm_state(f);
4909
    qemu_fclose(f);
4910
    if (ret < 0) {
4911
        term_printf("Error %d while loading VM state\n", ret);
4912
    }
4913
 the_end:
4914
    if (saved_vm_running)
4915
        vm_start();
4916
}
4917

    
4918
void do_delvm(const char *name)
4919
{
4920
    BlockDriverState *bs, *bs1;
4921
    int i, ret;
4922

    
4923
    bs = get_bs_snapshots();
4924
    if (!bs) {
4925
        term_printf("No block device supports snapshots\n");
4926
        return;
4927
    }
4928
    
4929
    for(i = 0; i <= MAX_DISKS; i++) {
4930
        bs1 = bs_table[i];
4931
        if (bdrv_has_snapshot(bs1)) {
4932
            ret = bdrv_snapshot_delete(bs1, name);
4933
            if (ret < 0) {
4934
                if (ret == -ENOTSUP)
4935
                    term_printf("Snapshots not supported on device '%s'\n",
4936
                                bdrv_get_device_name(bs1));
4937
                else
4938
                    term_printf("Error %d while deleting snapshot on '%s'\n",
4939
                                ret, bdrv_get_device_name(bs1));
4940
            }
4941
        }
4942
    }
4943
}
4944

    
4945
void do_info_snapshots(void)
4946
{
4947
    BlockDriverState *bs, *bs1;
4948
    QEMUSnapshotInfo *sn_tab, *sn;
4949
    int nb_sns, i;
4950
    char buf[256];
4951

    
4952
    bs = get_bs_snapshots();
4953
    if (!bs) {
4954
        term_printf("No available block device supports snapshots\n");
4955
        return;
4956
    }
4957
    term_printf("Snapshot devices:");
4958
    for(i = 0; i <= MAX_DISKS; i++) {
4959
        bs1 = bs_table[i];
4960
        if (bdrv_has_snapshot(bs1)) {
4961
            if (bs == bs1)
4962
                term_printf(" %s", bdrv_get_device_name(bs1));
4963
        }
4964
    }
4965
    term_printf("\n");
4966

    
4967
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4968
    if (nb_sns < 0) {
4969
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4970
        return;
4971
    }
4972
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4973
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4974
    for(i = 0; i < nb_sns; i++) {
4975
        sn = &sn_tab[i];
4976
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4977
    }
4978
    qemu_free(sn_tab);
4979
}
4980

    
4981
/***********************************************************/
4982
/* cpu save/restore */
4983

    
4984
#if defined(TARGET_I386)
4985

    
4986
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4987
{
4988
    qemu_put_be32(f, dt->selector);
4989
    qemu_put_betl(f, dt->base);
4990
    qemu_put_be32(f, dt->limit);
4991
    qemu_put_be32(f, dt->flags);
4992
}
4993

    
4994
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4995
{
4996
    dt->selector = qemu_get_be32(f);
4997
    dt->base = qemu_get_betl(f);
4998
    dt->limit = qemu_get_be32(f);
4999
    dt->flags = qemu_get_be32(f);
5000
}
5001

    
5002
void cpu_save(QEMUFile *f, void *opaque)
5003
{
5004
    CPUState *env = opaque;
5005
    uint16_t fptag, fpus, fpuc, fpregs_format;
5006
    uint32_t hflags;
5007
    int i;
5008
    
5009
    for(i = 0; i < CPU_NB_REGS; i++)
5010
        qemu_put_betls(f, &env->regs[i]);
5011
    qemu_put_betls(f, &env->eip);
5012
    qemu_put_betls(f, &env->eflags);
5013
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5014
    qemu_put_be32s(f, &hflags);
5015
    
5016
    /* FPU */
5017
    fpuc = env->fpuc;
5018
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5019
    fptag = 0;
5020
    for(i = 0; i < 8; i++) {
5021
        fptag |= ((!env->fptags[i]) << i);
5022
    }
5023
    
5024
    qemu_put_be16s(f, &fpuc);
5025
    qemu_put_be16s(f, &fpus);
5026
    qemu_put_be16s(f, &fptag);
5027

    
5028
#ifdef USE_X86LDOUBLE
5029
    fpregs_format = 0;
5030
#else
5031
    fpregs_format = 1;
5032
#endif
5033
    qemu_put_be16s(f, &fpregs_format);
5034
    
5035
    for(i = 0; i < 8; i++) {
5036
#ifdef USE_X86LDOUBLE
5037
        {
5038
            uint64_t mant;
5039
            uint16_t exp;
5040
            /* we save the real CPU data (in case of MMX usage only 'mant'
5041
               contains the MMX register */
5042
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5043
            qemu_put_be64(f, mant);
5044
            qemu_put_be16(f, exp);
5045
        }
5046
#else
5047
        /* if we use doubles for float emulation, we save the doubles to
5048
           avoid losing information in case of MMX usage. It can give
5049
           problems if the image is restored on a CPU where long
5050
           doubles are used instead. */
5051
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5052
#endif
5053
    }
5054

    
5055
    for(i = 0; i < 6; i++)
5056
        cpu_put_seg(f, &env->segs[i]);
5057
    cpu_put_seg(f, &env->ldt);
5058
    cpu_put_seg(f, &env->tr);
5059
    cpu_put_seg(f, &env->gdt);
5060
    cpu_put_seg(f, &env->idt);
5061
    
5062
    qemu_put_be32s(f, &env->sysenter_cs);
5063
    qemu_put_be32s(f, &env->sysenter_esp);
5064
    qemu_put_be32s(f, &env->sysenter_eip);
5065
    
5066
    qemu_put_betls(f, &env->cr[0]);
5067
    qemu_put_betls(f, &env->cr[2]);
5068
    qemu_put_betls(f, &env->cr[3]);
5069
    qemu_put_betls(f, &env->cr[4]);
5070
    
5071
    for(i = 0; i < 8; i++)
5072
        qemu_put_betls(f, &env->dr[i]);
5073

    
5074
    /* MMU */
5075
    qemu_put_be32s(f, &env->a20_mask);
5076

    
5077
    /* XMM */
5078
    qemu_put_be32s(f, &env->mxcsr);
5079
    for(i = 0; i < CPU_NB_REGS; i++) {
5080
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5081
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5082
    }
5083

    
5084
#ifdef TARGET_X86_64
5085
    qemu_put_be64s(f, &env->efer);
5086
    qemu_put_be64s(f, &env->star);
5087
    qemu_put_be64s(f, &env->lstar);
5088
    qemu_put_be64s(f, &env->cstar);
5089
    qemu_put_be64s(f, &env->fmask);
5090
    qemu_put_be64s(f, &env->kernelgsbase);
5091
#endif
5092
    qemu_put_be32s(f, &env->smbase);
5093
}
5094

    
5095
#ifdef USE_X86LDOUBLE
5096
/* XXX: add that in a FPU generic layer */
5097
union x86_longdouble {
5098
    uint64_t mant;
5099
    uint16_t exp;
5100
};
5101

    
5102
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5103
#define EXPBIAS1 1023
5104
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5105
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5106

    
5107
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5108
{
5109
    int e;
5110
    /* mantissa */
5111
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5112
    /* exponent + sign */
5113
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5114
    e |= SIGND1(temp) >> 16;
5115
    p->exp = e;
5116
}
5117
#endif
5118

    
5119
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5120
{
5121
    CPUState *env = opaque;
5122
    int i, guess_mmx;
5123
    uint32_t hflags;
5124
    uint16_t fpus, fpuc, fptag, fpregs_format;
5125

    
5126
    if (version_id != 3 && version_id != 4)
5127
        return -EINVAL;
5128
    for(i = 0; i < CPU_NB_REGS; i++)
5129
        qemu_get_betls(f, &env->regs[i]);
5130
    qemu_get_betls(f, &env->eip);
5131
    qemu_get_betls(f, &env->eflags);
5132
    qemu_get_be32s(f, &hflags);
5133

    
5134
    qemu_get_be16s(f, &fpuc);
5135
    qemu_get_be16s(f, &fpus);
5136
    qemu_get_be16s(f, &fptag);
5137
    qemu_get_be16s(f, &fpregs_format);
5138
    
5139
    /* NOTE: we cannot always restore the FPU state if the image come
5140
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5141
       if we are in an MMX state to restore correctly in that case. */
5142
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5143
    for(i = 0; i < 8; i++) {
5144
        uint64_t mant;
5145
        uint16_t exp;
5146
        
5147
        switch(fpregs_format) {
5148
        case 0:
5149
            mant = qemu_get_be64(f);
5150
            exp = qemu_get_be16(f);
5151
#ifdef USE_X86LDOUBLE
5152
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5153
#else
5154
            /* difficult case */
5155
            if (guess_mmx)
5156
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5157
            else
5158
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5159
#endif
5160
            break;
5161
        case 1:
5162
            mant = qemu_get_be64(f);
5163
#ifdef USE_X86LDOUBLE
5164
            {
5165
                union x86_longdouble *p;
5166
                /* difficult case */
5167
                p = (void *)&env->fpregs[i];
5168
                if (guess_mmx) {
5169
                    p->mant = mant;
5170
                    p->exp = 0xffff;
5171
                } else {
5172
                    fp64_to_fp80(p, mant);
5173
                }
5174
            }
5175
#else
5176
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5177
#endif            
5178
            break;
5179
        default:
5180
            return -EINVAL;
5181
        }
5182
    }
5183

    
5184
    env->fpuc = fpuc;
5185
    /* XXX: restore FPU round state */
5186
    env->fpstt = (fpus >> 11) & 7;
5187
    env->fpus = fpus & ~0x3800;
5188
    fptag ^= 0xff;
5189
    for(i = 0; i < 8; i++) {
5190
        env->fptags[i] = (fptag >> i) & 1;
5191
    }
5192
    
5193
    for(i = 0; i < 6; i++)
5194
        cpu_get_seg(f, &env->segs[i]);
5195
    cpu_get_seg(f, &env->ldt);
5196
    cpu_get_seg(f, &env->tr);
5197
    cpu_get_seg(f, &env->gdt);
5198
    cpu_get_seg(f, &env->idt);
5199
    
5200
    qemu_get_be32s(f, &env->sysenter_cs);
5201
    qemu_get_be32s(f, &env->sysenter_esp);
5202
    qemu_get_be32s(f, &env->sysenter_eip);
5203
    
5204
    qemu_get_betls(f, &env->cr[0]);
5205
    qemu_get_betls(f, &env->cr[2]);
5206
    qemu_get_betls(f, &env->cr[3]);
5207
    qemu_get_betls(f, &env->cr[4]);
5208
    
5209
    for(i = 0; i < 8; i++)
5210
        qemu_get_betls(f, &env->dr[i]);
5211

    
5212
    /* MMU */
5213
    qemu_get_be32s(f, &env->a20_mask);
5214

    
5215
    qemu_get_be32s(f, &env->mxcsr);
5216
    for(i = 0; i < CPU_NB_REGS; i++) {
5217
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5218
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5219
    }
5220

    
5221
#ifdef TARGET_X86_64
5222
    qemu_get_be64s(f, &env->efer);
5223
    qemu_get_be64s(f, &env->star);
5224
    qemu_get_be64s(f, &env->lstar);
5225
    qemu_get_be64s(f, &env->cstar);
5226
    qemu_get_be64s(f, &env->fmask);
5227
    qemu_get_be64s(f, &env->kernelgsbase);
5228
#endif
5229
    if (version_id >= 4) 
5230
        qemu_get_be32s(f, &env->smbase);
5231

    
5232
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5233
    env->hflags = hflags;
5234
    tlb_flush(env, 1);
5235
    return 0;
5236
}
5237

    
5238
#elif defined(TARGET_PPC)
5239
void cpu_save(QEMUFile *f, void *opaque)
5240
{
5241
}
5242

    
5243
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5244
{
5245
    return 0;
5246
}
5247

    
5248
#elif defined(TARGET_MIPS)
5249
void cpu_save(QEMUFile *f, void *opaque)
5250
{
5251
}
5252

    
5253
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5254
{
5255
    return 0;
5256
}
5257

    
5258
#elif defined(TARGET_SPARC)
5259
void cpu_save(QEMUFile *f, void *opaque)
5260
{
5261
    CPUState *env = opaque;
5262
    int i;
5263
    uint32_t tmp;
5264

    
5265
    for(i = 0; i < 8; i++)
5266
        qemu_put_betls(f, &env->gregs[i]);
5267
    for(i = 0; i < NWINDOWS * 16; i++)
5268
        qemu_put_betls(f, &env->regbase[i]);
5269

    
5270
    /* FPU */
5271
    for(i = 0; i < TARGET_FPREGS; i++) {
5272
        union {
5273
            float32 f;
5274
            uint32_t i;
5275
        } u;
5276
        u.f = env->fpr[i];
5277
        qemu_put_be32(f, u.i);
5278
    }
5279

    
5280
    qemu_put_betls(f, &env->pc);
5281
    qemu_put_betls(f, &env->npc);
5282
    qemu_put_betls(f, &env->y);
5283
    tmp = GET_PSR(env);
5284
    qemu_put_be32(f, tmp);
5285
    qemu_put_betls(f, &env->fsr);
5286
    qemu_put_betls(f, &env->tbr);
5287
#ifndef TARGET_SPARC64
5288
    qemu_put_be32s(f, &env->wim);
5289
    /* MMU */
5290
    for(i = 0; i < 16; i++)
5291
        qemu_put_be32s(f, &env->mmuregs[i]);
5292
#endif
5293
}
5294

    
5295
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5296
{
5297
    CPUState *env = opaque;
5298
    int i;
5299
    uint32_t tmp;
5300

    
5301
    for(i = 0; i < 8; i++)
5302
        qemu_get_betls(f, &env->gregs[i]);
5303
    for(i = 0; i < NWINDOWS * 16; i++)
5304
        qemu_get_betls(f, &env->regbase[i]);
5305

    
5306
    /* FPU */
5307
    for(i = 0; i < TARGET_FPREGS; i++) {
5308
        union {
5309
            float32 f;
5310
            uint32_t i;
5311
        } u;
5312
        u.i = qemu_get_be32(f);
5313
        env->fpr[i] = u.f;
5314
    }
5315

    
5316
    qemu_get_betls(f, &env->pc);
5317
    qemu_get_betls(f, &env->npc);
5318
    qemu_get_betls(f, &env->y);
5319
    tmp = qemu_get_be32(f);
5320
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5321
                     correctly updated */
5322
    PUT_PSR(env, tmp);
5323
    qemu_get_betls(f, &env->fsr);
5324
    qemu_get_betls(f, &env->tbr);
5325
#ifndef TARGET_SPARC64
5326
    qemu_get_be32s(f, &env->wim);
5327
    /* MMU */
5328
    for(i = 0; i < 16; i++)
5329
        qemu_get_be32s(f, &env->mmuregs[i]);
5330
#endif
5331
    tlb_flush(env, 1);
5332
    return 0;
5333
}
5334

    
5335
#elif defined(TARGET_ARM)
5336

    
5337
/* ??? Need to implement these.  */
5338
void cpu_save(QEMUFile *f, void *opaque)
5339
{
5340
}
5341

    
5342
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5343
{
5344
    return 0;
5345
}
5346

    
5347
#else
5348

    
5349
#warning No CPU save/restore functions
5350

    
5351
#endif
5352

    
5353
/***********************************************************/
5354
/* ram save/restore */
5355

    
5356
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5357
{
5358
    int v;
5359

    
5360
    v = qemu_get_byte(f);
5361
    switch(v) {
5362
    case 0:
5363
        if (qemu_get_buffer(f, buf, len) != len)
5364
            return -EIO;
5365
        break;
5366
    case 1:
5367
        v = qemu_get_byte(f);
5368
        memset(buf, v, len);
5369
        break;
5370
    default:
5371
        return -EINVAL;
5372
    }
5373
    return 0;
5374
}
5375

    
5376
static int ram_load_v1(QEMUFile *f, void *opaque)
5377
{
5378
    int i, ret;
5379

    
5380
    if (qemu_get_be32(f) != phys_ram_size)
5381
        return -EINVAL;
5382
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5383
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5384
        if (ret)
5385
            return ret;
5386
    }
5387
    return 0;
5388
}
5389

    
5390
#define BDRV_HASH_BLOCK_SIZE 1024
5391
#define IOBUF_SIZE 4096
5392
#define RAM_CBLOCK_MAGIC 0xfabe
5393

    
5394
typedef struct RamCompressState {
5395
    z_stream zstream;
5396
    QEMUFile *f;
5397
    uint8_t buf[IOBUF_SIZE];
5398
} RamCompressState;
5399

    
5400
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5401
{
5402
    int ret;
5403
    memset(s, 0, sizeof(*s));
5404
    s->f = f;
5405
    ret = deflateInit2(&s->zstream, 1,
5406
                       Z_DEFLATED, 15, 
5407
                       9, Z_DEFAULT_STRATEGY);
5408
    if (ret != Z_OK)
5409
        return -1;
5410
    s->zstream.avail_out = IOBUF_SIZE;
5411
    s->zstream.next_out = s->buf;
5412
    return 0;
5413
}
5414

    
5415
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5416
{
5417
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5418
    qemu_put_be16(s->f, len);
5419
    qemu_put_buffer(s->f, buf, len);
5420
}
5421

    
5422
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5423
{
5424
    int ret;
5425

    
5426
    s->zstream.avail_in = len;
5427
    s->zstream.next_in = (uint8_t *)buf;
5428
    while (s->zstream.avail_in > 0) {
5429
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5430
        if (ret != Z_OK)
5431
            return -1;
5432
        if (s->zstream.avail_out == 0) {
5433
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5434
            s->zstream.avail_out = IOBUF_SIZE;
5435
            s->zstream.next_out = s->buf;
5436
        }
5437
    }
5438
    return 0;
5439
}
5440

    
5441
static void ram_compress_close(RamCompressState *s)
5442
{
5443
    int len, ret;
5444

    
5445
    /* compress last bytes */
5446
    for(;;) {
5447
        ret = deflate(&s->zstream, Z_FINISH);
5448
        if (ret == Z_OK || ret == Z_STREAM_END) {
5449
            len = IOBUF_SIZE - s->zstream.avail_out;
5450
            if (len > 0) {
5451
                ram_put_cblock(s, s->buf, len);
5452
            }
5453
            s->zstream.avail_out = IOBUF_SIZE;
5454
            s->zstream.next_out = s->buf;
5455
            if (ret == Z_STREAM_END)
5456
                break;
5457
        } else {
5458
            goto fail;
5459
        }
5460
    }
5461
fail:
5462
    deflateEnd(&s->zstream);
5463
}
5464

    
5465
typedef struct RamDecompressState {
5466
    z_stream zstream;
5467
    QEMUFile *f;
5468
    uint8_t buf[IOBUF_SIZE];
5469
} RamDecompressState;
5470

    
5471
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5472
{
5473
    int ret;
5474
    memset(s, 0, sizeof(*s));
5475
    s->f = f;
5476
    ret = inflateInit(&s->zstream);
5477
    if (ret != Z_OK)
5478
        return -1;
5479
    return 0;
5480
}
5481

    
5482
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5483
{
5484
    int ret, clen;
5485

    
5486
    s->zstream.avail_out = len;
5487
    s->zstream.next_out = buf;
5488
    while (s->zstream.avail_out > 0) {
5489
        if (s->zstream.avail_in == 0) {
5490
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5491
                return -1;
5492
            clen = qemu_get_be16(s->f);
5493
            if (clen > IOBUF_SIZE)
5494
                return -1;
5495
            qemu_get_buffer(s->f, s->buf, clen);
5496
            s->zstream.avail_in = clen;
5497
            s->zstream.next_in = s->buf;
5498
        }
5499
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5500
        if (ret != Z_OK && ret != Z_STREAM_END) {
5501
            return -1;
5502
        }
5503
    }
5504
    return 0;
5505
}
5506

    
5507
static void ram_decompress_close(RamDecompressState *s)
5508
{
5509
    inflateEnd(&s->zstream);
5510
}
5511

    
5512
static void ram_save(QEMUFile *f, void *opaque)
5513
{
5514
    int i;
5515
    RamCompressState s1, *s = &s1;
5516
    uint8_t buf[10];
5517
    
5518
    qemu_put_be32(f, phys_ram_size);
5519
    if (ram_compress_open(s, f) < 0)
5520
        return;
5521
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5522
#if 0
5523
        if (tight_savevm_enabled) {
5524
            int64_t sector_num;
5525
            int j;
5526

5527
            /* find if the memory block is available on a virtual
5528
               block device */
5529
            sector_num = -1;
5530
            for(j = 0; j < MAX_DISKS; j++) {
5531
                if (bs_table[j]) {
5532
                    sector_num = bdrv_hash_find(bs_table[j], 
5533
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5534
                    if (sector_num >= 0)
5535
                        break;
5536
                }
5537
            }
5538
            if (j == MAX_DISKS)
5539
                goto normal_compress;
5540
            buf[0] = 1;
5541
            buf[1] = j;
5542
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5543
            ram_compress_buf(s, buf, 10);
5544
        } else 
5545
#endif
5546
        {
5547
            //        normal_compress:
5548
            buf[0] = 0;
5549
            ram_compress_buf(s, buf, 1);
5550
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5551
        }
5552
    }
5553
    ram_compress_close(s);
5554
}
5555

    
5556
static int ram_load(QEMUFile *f, void *opaque, int version_id)
5557
{
5558
    RamDecompressState s1, *s = &s1;
5559
    uint8_t buf[10];
5560
    int i;
5561

    
5562
    if (version_id == 1)
5563
        return ram_load_v1(f, opaque);
5564
    if (version_id != 2)
5565
        return -EINVAL;
5566
    if (qemu_get_be32(f) != phys_ram_size)
5567
        return -EINVAL;
5568
    if (ram_decompress_open(s, f) < 0)
5569
        return -EINVAL;
5570
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5571
        if (ram_decompress_buf(s, buf, 1) < 0) {
5572
            fprintf(stderr, "Error while reading ram block header\n");
5573
            goto error;
5574
        }
5575
        if (buf[0] == 0) {
5576
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5577
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5578
                goto error;
5579
            }
5580
        } else 
5581
#if 0
5582
        if (buf[0] == 1) {
5583
            int bs_index;
5584
            int64_t sector_num;
5585

5586
            ram_decompress_buf(s, buf + 1, 9);
5587
            bs_index = buf[1];
5588
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5589
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5590
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
5591
                goto error;
5592
            }
5593
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5594
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5595
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5596
                        bs_index, sector_num);
5597
                goto error;
5598
            }
5599
        } else 
5600
#endif
5601
        {
5602
        error:
5603
            printf("Error block header\n");
5604
            return -EINVAL;
5605
        }
5606
    }
5607
    ram_decompress_close(s);
5608
    return 0;
5609
}
5610

    
5611
/***********************************************************/
5612
/* bottom halves (can be seen as timers which expire ASAP) */
5613

    
5614
struct QEMUBH {
5615
    QEMUBHFunc *cb;
5616
    void *opaque;
5617
    int scheduled;
5618
    QEMUBH *next;
5619
};
5620

    
5621
static QEMUBH *first_bh = NULL;
5622

    
5623
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5624
{
5625
    QEMUBH *bh;
5626
    bh = qemu_mallocz(sizeof(QEMUBH));
5627
    if (!bh)
5628
        return NULL;
5629
    bh->cb = cb;
5630
    bh->opaque = opaque;
5631
    return bh;
5632
}
5633

    
5634
int qemu_bh_poll(void)
5635
{
5636
    QEMUBH *bh, **pbh;
5637
    int ret;
5638

    
5639
    ret = 0;
5640
    for(;;) {
5641
        pbh = &first_bh;
5642
        bh = *pbh;
5643
        if (!bh)
5644
            break;
5645
        ret = 1;
5646
        *pbh = bh->next;
5647
        bh->scheduled = 0;
5648
        bh->cb(bh->opaque);
5649
    }
5650
    return ret;
5651
}
5652

    
5653
void qemu_bh_schedule(QEMUBH *bh)
5654
{
5655
    CPUState *env = cpu_single_env;
5656
    if (bh->scheduled)
5657
        return;
5658
    bh->scheduled = 1;
5659
    bh->next = first_bh;
5660
    first_bh = bh;
5661

    
5662
    /* stop the currently executing CPU to execute the BH ASAP */
5663
    if (env) {
5664
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5665
    }
5666
}
5667

    
5668
void qemu_bh_cancel(QEMUBH *bh)
5669
{
5670
    QEMUBH **pbh;
5671
    if (bh->scheduled) {
5672
        pbh = &first_bh;
5673
        while (*pbh != bh)
5674
            pbh = &(*pbh)->next;
5675
        *pbh = bh->next;
5676
        bh->scheduled = 0;
5677
    }
5678
}
5679

    
5680
void qemu_bh_delete(QEMUBH *bh)
5681
{
5682
    qemu_bh_cancel(bh);
5683
    qemu_free(bh);
5684
}
5685

    
5686
/***********************************************************/
5687
/* machine registration */
5688

    
5689
QEMUMachine *first_machine = NULL;
5690

    
5691
int qemu_register_machine(QEMUMachine *m)
5692
{
5693
    QEMUMachine **pm;
5694
    pm = &first_machine;
5695
    while (*pm != NULL)
5696
        pm = &(*pm)->next;
5697
    m->next = NULL;
5698
    *pm = m;
5699
    return 0;
5700
}
5701

    
5702
QEMUMachine *find_machine(const char *name)
5703
{
5704
    QEMUMachine *m;
5705

    
5706
    for(m = first_machine; m != NULL; m = m->next) {
5707
        if (!strcmp(m->name, name))
5708
            return m;
5709
    }
5710
    return NULL;
5711
}
5712

    
5713
/***********************************************************/
5714
/* main execution loop */
5715

    
5716
void gui_update(void *opaque)
5717
{
5718
    display_state.dpy_refresh(&display_state);
5719
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5720
}
5721

    
5722
struct vm_change_state_entry {
5723
    VMChangeStateHandler *cb;
5724
    void *opaque;
5725
    LIST_ENTRY (vm_change_state_entry) entries;
5726
};
5727

    
5728
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5729

    
5730
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5731
                                                     void *opaque)
5732
{
5733
    VMChangeStateEntry *e;
5734

    
5735
    e = qemu_mallocz(sizeof (*e));
5736
    if (!e)
5737
        return NULL;
5738

    
5739
    e->cb = cb;
5740
    e->opaque = opaque;
5741
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5742
    return e;
5743
}
5744

    
5745
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5746
{
5747
    LIST_REMOVE (e, entries);
5748
    qemu_free (e);
5749
}
5750

    
5751
static void vm_state_notify(int running)
5752
{
5753
    VMChangeStateEntry *e;
5754

    
5755
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5756
        e->cb(e->opaque, running);
5757
    }
5758
}
5759

    
5760
/* XXX: support several handlers */
5761
static VMStopHandler *vm_stop_cb;
5762
static void *vm_stop_opaque;
5763

    
5764
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5765
{
5766
    vm_stop_cb = cb;
5767
    vm_stop_opaque = opaque;
5768
    return 0;
5769
}
5770

    
5771
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5772
{
5773
    vm_stop_cb = NULL;
5774
}
5775

    
5776
void vm_start(void)
5777
{
5778
    if (!vm_running) {
5779
        cpu_enable_ticks();
5780
        vm_running = 1;
5781
        vm_state_notify(1);
5782
    }
5783
}
5784

    
5785
void vm_stop(int reason) 
5786
{
5787
    if (vm_running) {
5788
        cpu_disable_ticks();
5789
        vm_running = 0;
5790
        if (reason != 0) {
5791
            if (vm_stop_cb) {
5792
                vm_stop_cb(vm_stop_opaque, reason);
5793
            }
5794
        }
5795
        vm_state_notify(0);
5796
    }
5797
}
5798

    
5799
/* reset/shutdown handler */
5800

    
5801
typedef struct QEMUResetEntry {
5802
    QEMUResetHandler *func;
5803
    void *opaque;
5804
    struct QEMUResetEntry *next;
5805
} QEMUResetEntry;
5806

    
5807
static QEMUResetEntry *first_reset_entry;
5808
static int reset_requested;
5809
static int shutdown_requested;
5810
static int powerdown_requested;
5811

    
5812
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5813
{
5814
    QEMUResetEntry **pre, *re;
5815

    
5816
    pre = &first_reset_entry;
5817
    while (*pre != NULL)
5818
        pre = &(*pre)->next;
5819
    re = qemu_mallocz(sizeof(QEMUResetEntry));
5820
    re->func = func;
5821
    re->opaque = opaque;
5822
    re->next = NULL;
5823
    *pre = re;
5824
}
5825

    
5826
static void qemu_system_reset(void)
5827
{
5828
    QEMUResetEntry *re;
5829

    
5830
    /* reset all devices */
5831
    for(re = first_reset_entry; re != NULL; re = re->next) {
5832
        re->func(re->opaque);
5833
    }
5834
}
5835

    
5836
void qemu_system_reset_request(void)
5837
{
5838
    if (no_reboot) {
5839
        shutdown_requested = 1;
5840
    } else {
5841
        reset_requested = 1;
5842
    }
5843
    if (cpu_single_env)
5844
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5845
}
5846

    
5847
void qemu_system_shutdown_request(void)
5848
{
5849
    shutdown_requested = 1;
5850
    if (cpu_single_env)
5851
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5852
}
5853

    
5854
void qemu_system_powerdown_request(void)
5855
{
5856
    powerdown_requested = 1;
5857
    if (cpu_single_env)
5858
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5859
}
5860

    
5861
void main_loop_wait(int timeout)
5862
{
5863
    IOHandlerRecord *ioh, *ioh_next;
5864
    fd_set rfds, wfds, xfds;
5865
    int ret, nfds;
5866
    struct timeval tv;
5867
    PollingEntry *pe;
5868

    
5869

    
5870
    /* XXX: need to suppress polling by better using win32 events */
5871
    ret = 0;
5872
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5873
        ret |= pe->func(pe->opaque);
5874
    }
5875
#ifdef _WIN32
5876
    if (ret == 0 && timeout > 0) {
5877
        int err;
5878
        WaitObjects *w = &wait_objects;
5879
        
5880
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5881
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5882
            if (w->func[ret - WAIT_OBJECT_0])
5883
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5884
        } else if (ret == WAIT_TIMEOUT) {
5885
        } else {
5886
            err = GetLastError();
5887
            fprintf(stderr, "Wait error %d %d\n", ret, err);
5888
        }
5889
    }
5890
#endif
5891
    /* poll any events */
5892
    /* XXX: separate device handlers from system ones */
5893
    nfds = -1;
5894
    FD_ZERO(&rfds);
5895
    FD_ZERO(&wfds);
5896
    FD_ZERO(&xfds);
5897
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5898
        if (ioh->fd_read &&
5899
            (!ioh->fd_read_poll ||
5900
             ioh->fd_read_poll(ioh->opaque) != 0)) {
5901
            FD_SET(ioh->fd, &rfds);
5902
            if (ioh->fd > nfds)
5903
                nfds = ioh->fd;
5904
        }
5905
        if (ioh->fd_write) {
5906
            FD_SET(ioh->fd, &wfds);
5907
            if (ioh->fd > nfds)
5908
                nfds = ioh->fd;
5909
        }
5910
    }
5911
    
5912
    tv.tv_sec = 0;
5913
#ifdef _WIN32
5914
    tv.tv_usec = 0;
5915
#else
5916
    tv.tv_usec = timeout * 1000;
5917
#endif
5918
#if defined(CONFIG_SLIRP)
5919
    if (slirp_inited) {
5920
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5921
    }
5922
#endif
5923
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5924
    if (ret > 0) {
5925
        /* XXX: better handling of removal */
5926
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5927
            ioh_next = ioh->next;
5928
            if (FD_ISSET(ioh->fd, &rfds)) {
5929
                ioh->fd_read(ioh->opaque);
5930
            }
5931
            if (FD_ISSET(ioh->fd, &wfds)) {
5932
                ioh->fd_write(ioh->opaque);
5933
            }
5934
        }
5935
    }
5936
#if defined(CONFIG_SLIRP)
5937
    if (slirp_inited) {
5938
        if (ret < 0) {
5939
            FD_ZERO(&rfds);
5940
            FD_ZERO(&wfds);
5941
            FD_ZERO(&xfds);
5942
        }
5943
        slirp_select_poll(&rfds, &wfds, &xfds);
5944
    }
5945
#endif
5946
    qemu_aio_poll();
5947
    qemu_bh_poll();
5948

    
5949
    if (vm_running) {
5950
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
5951
                        qemu_get_clock(vm_clock));
5952
        /* run dma transfers, if any */
5953
        DMA_run();
5954
    }
5955
    
5956
    /* real time timers */
5957
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
5958
                    qemu_get_clock(rt_clock));
5959
}
5960

    
5961
static CPUState *cur_cpu;
5962

    
5963
int main_loop(void)
5964
{
5965
    int ret, timeout;
5966
#ifdef CONFIG_PROFILER
5967
    int64_t ti;
5968
#endif
5969
    CPUState *env;
5970

    
5971
    cur_cpu = first_cpu;
5972
    for(;;) {
5973
        if (vm_running) {
5974

    
5975
            env = cur_cpu;
5976
            for(;;) {
5977
                /* get next cpu */
5978
                env = env->next_cpu;
5979
                if (!env)
5980
                    env = first_cpu;
5981
#ifdef CONFIG_PROFILER
5982
                ti = profile_getclock();
5983
#endif
5984
                ret = cpu_exec(env);
5985
#ifdef CONFIG_PROFILER
5986
                qemu_time += profile_getclock() - ti;
5987
#endif
5988
                if (ret != EXCP_HALTED)
5989
                    break;
5990
                /* all CPUs are halted ? */
5991
                if (env == cur_cpu) {
5992
                    ret = EXCP_HLT;
5993
                    break;
5994
                }
5995
            }
5996
            cur_cpu = env;
5997

    
5998
            if (shutdown_requested) {
5999
                ret = EXCP_INTERRUPT;
6000
                break;
6001
            }
6002
            if (reset_requested) {
6003
                reset_requested = 0;
6004
                qemu_system_reset();
6005
                ret = EXCP_INTERRUPT;
6006
            }
6007
            if (powerdown_requested) {
6008
                powerdown_requested = 0;
6009
                qemu_system_powerdown();
6010
                ret = EXCP_INTERRUPT;
6011
            }
6012
            if (ret == EXCP_DEBUG) {
6013
                vm_stop(EXCP_DEBUG);
6014
            }
6015
            /* if hlt instruction, we wait until the next IRQ */
6016
            /* XXX: use timeout computed from timers */
6017
            if (ret == EXCP_HLT)
6018
                timeout = 10;
6019
            else
6020
                timeout = 0;
6021
        } else {
6022
            timeout = 10;
6023
        }
6024
#ifdef CONFIG_PROFILER
6025
        ti = profile_getclock();
6026
#endif
6027
        main_loop_wait(timeout);
6028
#ifdef CONFIG_PROFILER
6029
        dev_time += profile_getclock() - ti;
6030
#endif
6031
    }
6032
    cpu_disable_ticks();
6033
    return ret;
6034
}
6035

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

    
6168
#define HAS_ARG 0x0001
6169

    
6170
enum {
6171
    QEMU_OPTION_h,
6172

    
6173
    QEMU_OPTION_M,
6174
    QEMU_OPTION_fda,
6175
    QEMU_OPTION_fdb,
6176
    QEMU_OPTION_hda,
6177
    QEMU_OPTION_hdb,
6178
    QEMU_OPTION_hdc,
6179
    QEMU_OPTION_hdd,
6180
    QEMU_OPTION_cdrom,
6181
    QEMU_OPTION_boot,
6182
    QEMU_OPTION_snapshot,
6183
#ifdef TARGET_I386
6184
    QEMU_OPTION_no_fd_bootchk,
6185
#endif
6186
    QEMU_OPTION_m,
6187
    QEMU_OPTION_nographic,
6188
#ifdef HAS_AUDIO
6189
    QEMU_OPTION_audio_help,
6190
    QEMU_OPTION_soundhw,
6191
#endif
6192

    
6193
    QEMU_OPTION_net,
6194
    QEMU_OPTION_tftp,
6195
    QEMU_OPTION_smb,
6196
    QEMU_OPTION_redir,
6197

    
6198
    QEMU_OPTION_kernel,
6199
    QEMU_OPTION_append,
6200
    QEMU_OPTION_initrd,
6201

    
6202
    QEMU_OPTION_S,
6203
    QEMU_OPTION_s,
6204
    QEMU_OPTION_p,
6205
    QEMU_OPTION_d,
6206
    QEMU_OPTION_hdachs,
6207
    QEMU_OPTION_L,
6208
    QEMU_OPTION_no_code_copy,
6209
    QEMU_OPTION_k,
6210
    QEMU_OPTION_localtime,
6211
    QEMU_OPTION_cirrusvga,
6212
    QEMU_OPTION_g,
6213
    QEMU_OPTION_std_vga,
6214
    QEMU_OPTION_monitor,
6215
    QEMU_OPTION_serial,
6216
    QEMU_OPTION_parallel,
6217
    QEMU_OPTION_loadvm,
6218
    QEMU_OPTION_full_screen,
6219
    QEMU_OPTION_no_quit,
6220
    QEMU_OPTION_pidfile,
6221
    QEMU_OPTION_no_kqemu,
6222
    QEMU_OPTION_kernel_kqemu,
6223
    QEMU_OPTION_win2k_hack,
6224
    QEMU_OPTION_usb,
6225
    QEMU_OPTION_usbdevice,
6226
    QEMU_OPTION_smp,
6227
    QEMU_OPTION_vnc,
6228
    QEMU_OPTION_no_acpi,
6229
    QEMU_OPTION_no_reboot,
6230
    QEMU_OPTION_daemonize,
6231
    QEMU_OPTION_option_rom,
6232
    QEMU_OPTION_semihosting
6233
};
6234

    
6235
typedef struct QEMUOption {
6236
    const char *name;
6237
    int flags;
6238
    int index;
6239
} QEMUOption;
6240

    
6241
const QEMUOption qemu_options[] = {
6242
    { "h", 0, QEMU_OPTION_h },
6243

    
6244
    { "M", HAS_ARG, QEMU_OPTION_M },
6245
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6246
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6247
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6248
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6249
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6250
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6251
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6252
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6253
    { "snapshot", 0, QEMU_OPTION_snapshot },
6254
#ifdef TARGET_I386
6255
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6256
#endif
6257
    { "m", HAS_ARG, QEMU_OPTION_m },
6258
    { "nographic", 0, QEMU_OPTION_nographic },
6259
    { "k", HAS_ARG, QEMU_OPTION_k },
6260
#ifdef HAS_AUDIO
6261
    { "audio-help", 0, QEMU_OPTION_audio_help },
6262
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6263
#endif
6264

    
6265
    { "net", HAS_ARG, QEMU_OPTION_net},
6266
#ifdef CONFIG_SLIRP
6267
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6268
#ifndef _WIN32
6269
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6270
#endif
6271
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6272
#endif
6273

    
6274
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6275
    { "append", HAS_ARG, QEMU_OPTION_append },
6276
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6277

    
6278
    { "S", 0, QEMU_OPTION_S },
6279
    { "s", 0, QEMU_OPTION_s },
6280
    { "p", HAS_ARG, QEMU_OPTION_p },
6281
    { "d", HAS_ARG, QEMU_OPTION_d },
6282
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6283
    { "L", HAS_ARG, QEMU_OPTION_L },
6284
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6285
#ifdef USE_KQEMU
6286
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6287
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6288
#endif
6289
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6290
    { "g", 1, QEMU_OPTION_g },
6291
#endif
6292
    { "localtime", 0, QEMU_OPTION_localtime },
6293
    { "std-vga", 0, QEMU_OPTION_std_vga },
6294
    { "monitor", 1, QEMU_OPTION_monitor },
6295
    { "serial", 1, QEMU_OPTION_serial },
6296
    { "parallel", 1, QEMU_OPTION_parallel },
6297
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6298
    { "full-screen", 0, QEMU_OPTION_full_screen },
6299
#ifdef CONFIG_SDL
6300
    { "no-quit", 0, QEMU_OPTION_no_quit },
6301
#endif
6302
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6303
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6304
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6305
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6306
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6307

    
6308
    /* temporary options */
6309
    { "usb", 0, QEMU_OPTION_usb },
6310
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6311
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6312
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
6313
    { "daemonize", 0, QEMU_OPTION_daemonize },
6314
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6315
#if defined(TARGET_ARM)
6316
    { "semihosting", 0, QEMU_OPTION_semihosting },
6317
#endif
6318
    { NULL },
6319
};
6320

    
6321
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6322

    
6323
/* this stack is only used during signal handling */
6324
#define SIGNAL_STACK_SIZE 32768
6325

    
6326
static uint8_t *signal_stack;
6327

    
6328
#endif
6329

    
6330
/* password input */
6331

    
6332
static BlockDriverState *get_bdrv(int index)
6333
{
6334
    BlockDriverState *bs;
6335

    
6336
    if (index < 4) {
6337
        bs = bs_table[index];
6338
    } else if (index < 6) {
6339
        bs = fd_table[index - 4];
6340
    } else {
6341
        bs = NULL;
6342
    }
6343
    return bs;
6344
}
6345

    
6346
static void read_passwords(void)
6347
{
6348
    BlockDriverState *bs;
6349
    int i, j;
6350
    char password[256];
6351

    
6352
    for(i = 0; i < 6; i++) {
6353
        bs = get_bdrv(i);
6354
        if (bs && bdrv_is_encrypted(bs)) {
6355
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6356
            for(j = 0; j < 3; j++) {
6357
                monitor_readline("Password: ", 
6358
                                 1, password, sizeof(password));
6359
                if (bdrv_set_key(bs, password) == 0)
6360
                    break;
6361
                term_printf("invalid password\n");
6362
            }
6363
        }
6364
    }
6365
}
6366

    
6367
/* XXX: currently we cannot use simultaneously different CPUs */
6368
void register_machines(void)
6369
{
6370
#if defined(TARGET_I386)
6371
    qemu_register_machine(&pc_machine);
6372
    qemu_register_machine(&isapc_machine);
6373
#elif defined(TARGET_PPC)
6374
    qemu_register_machine(&heathrow_machine);
6375
    qemu_register_machine(&core99_machine);
6376
    qemu_register_machine(&prep_machine);
6377
#elif defined(TARGET_MIPS)
6378
    qemu_register_machine(&mips_machine);
6379
    qemu_register_machine(&mips_malta_machine);
6380
#elif defined(TARGET_SPARC)
6381
#ifdef TARGET_SPARC64
6382
    qemu_register_machine(&sun4u_machine);
6383
#else
6384
    qemu_register_machine(&sun4m_machine);
6385
#endif
6386
#elif defined(TARGET_ARM)
6387
    qemu_register_machine(&integratorcp926_machine);
6388
    qemu_register_machine(&integratorcp1026_machine);
6389
    qemu_register_machine(&versatilepb_machine);
6390
    qemu_register_machine(&versatileab_machine);
6391
    qemu_register_machine(&realview_machine);
6392
#elif defined(TARGET_SH4)
6393
    qemu_register_machine(&shix_machine);
6394
#else
6395
#error unsupported CPU
6396
#endif
6397
}
6398

    
6399
#ifdef HAS_AUDIO
6400
struct soundhw soundhw[] = {
6401
#ifdef TARGET_I386
6402
    {
6403
        "pcspk",
6404
        "PC speaker",
6405
        0,
6406
        1,
6407
        { .init_isa = pcspk_audio_init }
6408
    },
6409
#endif
6410
    {
6411
        "sb16",
6412
        "Creative Sound Blaster 16",
6413
        0,
6414
        1,
6415
        { .init_isa = SB16_init }
6416
    },
6417

    
6418
#ifdef CONFIG_ADLIB
6419
    {
6420
        "adlib",
6421
#ifdef HAS_YMF262
6422
        "Yamaha YMF262 (OPL3)",
6423
#else
6424
        "Yamaha YM3812 (OPL2)",
6425
#endif
6426
        0,
6427
        1,
6428
        { .init_isa = Adlib_init }
6429
    },
6430
#endif
6431

    
6432
#ifdef CONFIG_GUS
6433
    {
6434
        "gus",
6435
        "Gravis Ultrasound GF1",
6436
        0,
6437
        1,
6438
        { .init_isa = GUS_init }
6439
    },
6440
#endif
6441

    
6442
    {
6443
        "es1370",
6444
        "ENSONIQ AudioPCI ES1370",
6445
        0,
6446
        0,
6447
        { .init_pci = es1370_init }
6448
    },
6449

    
6450
    { NULL, NULL, 0, 0, { NULL } }
6451
};
6452

    
6453
static void select_soundhw (const char *optarg)
6454
{
6455
    struct soundhw *c;
6456

    
6457
    if (*optarg == '?') {
6458
    show_valid_cards:
6459

    
6460
        printf ("Valid sound card names (comma separated):\n");
6461
        for (c = soundhw; c->name; ++c) {
6462
            printf ("%-11s %s\n", c->name, c->descr);
6463
        }
6464
        printf ("\n-soundhw all will enable all of the above\n");
6465
        exit (*optarg != '?');
6466
    }
6467
    else {
6468
        size_t l;
6469
        const char *p;
6470
        char *e;
6471
        int bad_card = 0;
6472

    
6473
        if (!strcmp (optarg, "all")) {
6474
            for (c = soundhw; c->name; ++c) {
6475
                c->enabled = 1;
6476
            }
6477
            return;
6478
        }
6479

    
6480
        p = optarg;
6481
        while (*p) {
6482
            e = strchr (p, ',');
6483
            l = !e ? strlen (p) : (size_t) (e - p);
6484

    
6485
            for (c = soundhw; c->name; ++c) {
6486
                if (!strncmp (c->name, p, l)) {
6487
                    c->enabled = 1;
6488
                    break;
6489
                }
6490
            }
6491

    
6492
            if (!c->name) {
6493
                if (l > 80) {
6494
                    fprintf (stderr,
6495
                             "Unknown sound card name (too big to show)\n");
6496
                }
6497
                else {
6498
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
6499
                             (int) l, p);
6500
                }
6501
                bad_card = 1;
6502
            }
6503
            p += l + (e != NULL);
6504
        }
6505

    
6506
        if (bad_card)
6507
            goto show_valid_cards;
6508
    }
6509
}
6510
#endif
6511

    
6512
#ifdef _WIN32
6513
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6514
{
6515
    exit(STATUS_CONTROL_C_EXIT);
6516
    return TRUE;
6517
}
6518
#endif
6519

    
6520
#define MAX_NET_CLIENTS 32
6521

    
6522
int main(int argc, char **argv)
6523
{
6524
#ifdef CONFIG_GDBSTUB
6525
    int use_gdbstub, gdbstub_port;
6526
#endif
6527
    int i, cdrom_index;
6528
    int snapshot, linux_boot;
6529
    const char *initrd_filename;
6530
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6531
    const char *kernel_filename, *kernel_cmdline;
6532
    DisplayState *ds = &display_state;
6533
    int cyls, heads, secs, translation;
6534
    char net_clients[MAX_NET_CLIENTS][256];
6535
    int nb_net_clients;
6536
    int optind;
6537
    const char *r, *optarg;
6538
    CharDriverState *monitor_hd;
6539
    char monitor_device[128];
6540
    char serial_devices[MAX_SERIAL_PORTS][128];
6541
    int serial_device_index;
6542
    char parallel_devices[MAX_PARALLEL_PORTS][128];
6543
    int parallel_device_index;
6544
    const char *loadvm = NULL;
6545
    QEMUMachine *machine;
6546
    char usb_devices[MAX_USB_CMDLINE][128];
6547
    int usb_devices_index;
6548
    int fds[2];
6549

    
6550
    LIST_INIT (&vm_change_state_head);
6551
#ifndef _WIN32
6552
    {
6553
        struct sigaction act;
6554
        sigfillset(&act.sa_mask);
6555
        act.sa_flags = 0;
6556
        act.sa_handler = SIG_IGN;
6557
        sigaction(SIGPIPE, &act, NULL);
6558
    }
6559
#else
6560
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6561
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
6562
       QEMU to run on a single CPU */
6563
    {
6564
        HANDLE h;
6565
        DWORD mask, smask;
6566
        int i;
6567
        h = GetCurrentProcess();
6568
        if (GetProcessAffinityMask(h, &mask, &smask)) {
6569
            for(i = 0; i < 32; i++) {
6570
                if (mask & (1 << i))
6571
                    break;
6572
            }
6573
            if (i != 32) {
6574
                mask = 1 << i;
6575
                SetProcessAffinityMask(h, mask);
6576
            }
6577
        }
6578
    }
6579
#endif
6580

    
6581
    register_machines();
6582
    machine = first_machine;
6583
    initrd_filename = NULL;
6584
    for(i = 0; i < MAX_FD; i++)
6585
        fd_filename[i] = NULL;
6586
    for(i = 0; i < MAX_DISKS; i++)
6587
        hd_filename[i] = NULL;
6588
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6589
    vga_ram_size = VGA_RAM_SIZE;
6590
    bios_size = BIOS_SIZE;
6591
#ifdef CONFIG_GDBSTUB
6592
    use_gdbstub = 0;
6593
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
6594
#endif
6595
    snapshot = 0;
6596
    nographic = 0;
6597
    kernel_filename = NULL;
6598
    kernel_cmdline = "";
6599
#ifdef TARGET_PPC
6600
    cdrom_index = 1;
6601
#else
6602
    cdrom_index = 2;
6603
#endif
6604
    cyls = heads = secs = 0;
6605
    translation = BIOS_ATA_TRANSLATION_AUTO;
6606
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6607

    
6608
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6609
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
6610
        serial_devices[i][0] = '\0';
6611
    serial_device_index = 0;
6612
    
6613
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6614
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6615
        parallel_devices[i][0] = '\0';
6616
    parallel_device_index = 0;
6617
    
6618
    usb_devices_index = 0;
6619
    
6620
    nb_net_clients = 0;
6621

    
6622
    nb_nics = 0;
6623
    /* default mac address of the first network interface */
6624
    
6625
    optind = 1;
6626
    for(;;) {
6627
        if (optind >= argc)
6628
            break;
6629
        r = argv[optind];
6630
        if (r[0] != '-') {
6631
            hd_filename[0] = argv[optind++];
6632
        } else {
6633
            const QEMUOption *popt;
6634

    
6635
            optind++;
6636
            popt = qemu_options;
6637
            for(;;) {
6638
                if (!popt->name) {
6639
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
6640
                            argv[0], r);
6641
                    exit(1);
6642
                }
6643
                if (!strcmp(popt->name, r + 1))
6644
                    break;
6645
                popt++;
6646
            }
6647
            if (popt->flags & HAS_ARG) {
6648
                if (optind >= argc) {
6649
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
6650
                            argv[0], r);
6651
                    exit(1);
6652
                }
6653
                optarg = argv[optind++];
6654
            } else {
6655
                optarg = NULL;
6656
            }
6657

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

    
6985
#ifndef _WIN32
6986
    if (daemonize && !nographic && vnc_display == NULL) {
6987
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
6988
        daemonize = 0;
6989
    }
6990

    
6991
    if (daemonize) {
6992
        pid_t pid;
6993

    
6994
        if (pipe(fds) == -1)
6995
            exit(1);
6996

    
6997
        pid = fork();
6998
        if (pid > 0) {
6999
            uint8_t status;
7000
            ssize_t len;
7001

    
7002
            close(fds[1]);
7003

    
7004
        again:
7005
            len = read(fds[0], &status, 1);
7006
            if (len == -1 && (errno == EINTR))
7007
                goto again;
7008
            
7009
            if (len != 1 || status != 0)
7010
                exit(1);
7011
            else
7012
                exit(0);
7013
        } else if (pid < 0)
7014
            exit(1);
7015

    
7016
        setsid();
7017

    
7018
        pid = fork();
7019
        if (pid > 0)
7020
            exit(0);
7021
        else if (pid < 0)
7022
            exit(1);
7023

    
7024
        umask(027);
7025
        chdir("/");
7026

    
7027
        signal(SIGTSTP, SIG_IGN);
7028
        signal(SIGTTOU, SIG_IGN);
7029
        signal(SIGTTIN, SIG_IGN);
7030
    }
7031
#endif
7032

    
7033
#ifdef USE_KQEMU
7034
    if (smp_cpus > 1)
7035
        kqemu_allowed = 0;
7036
#endif
7037
    linux_boot = (kernel_filename != NULL);
7038

    
7039
    if (!linux_boot &&
7040
        hd_filename[0] == '\0' && 
7041
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7042
        fd_filename[0] == '\0')
7043
        help();
7044

    
7045
    /* boot to floppy or the default cd if no hard disk defined yet */
7046
    if (hd_filename[0] == '\0' && boot_device == 'c') {
7047
        if (fd_filename[0] != '\0')
7048
            boot_device = 'a';
7049
        else
7050
            boot_device = 'd';
7051
    }
7052

    
7053
    setvbuf(stdout, NULL, _IOLBF, 0);
7054
    
7055
    init_timers();
7056
    init_timer_alarm();
7057
    qemu_aio_init();
7058

    
7059
#ifdef _WIN32
7060
    socket_init();
7061
#endif
7062

    
7063
    /* init network clients */
7064
    if (nb_net_clients == 0) {
7065
        /* if no clients, we use a default config */
7066
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
7067
                "nic");
7068
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
7069
                "user");
7070
        nb_net_clients = 2;
7071
    }
7072

    
7073
    for(i = 0;i < nb_net_clients; i++) {
7074
        if (net_client_init(net_clients[i]) < 0)
7075
            exit(1);
7076
    }
7077

    
7078
#ifdef TARGET_I386
7079
    if (boot_device == 'n') {
7080
        for (i = 0; i < nb_nics; i++) {
7081
            const char *model = nd_table[i].model;
7082
            char buf[1024];
7083
            if (model == NULL)
7084
                model = "ne2k_pci";
7085
            snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7086
            if (get_image_size(buf) > 0) {
7087
                option_rom[nb_option_roms] = strdup(buf);
7088
                nb_option_roms++;
7089
                break;
7090
            }
7091
        }
7092
        if (i == nb_nics) {
7093
            fprintf(stderr, "No valid PXE rom found for network device\n");
7094
            exit(1);
7095
        }
7096
        boot_device = 'c'; /* to prevent confusion by the BIOS */
7097
    }
7098
#endif
7099

    
7100
    /* init the memory */
7101
    phys_ram_size = ram_size + vga_ram_size + bios_size;
7102

    
7103
    for (i = 0; i < nb_option_roms; i++) {
7104
        int ret = get_image_size(option_rom[i]);
7105
        if (ret == -1) {
7106
            fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7107
            exit(1);
7108
        }
7109
        phys_ram_size += ret;
7110
    }
7111

    
7112
    phys_ram_base = qemu_vmalloc(phys_ram_size);
7113
    if (!phys_ram_base) {
7114
        fprintf(stderr, "Could not allocate physical memory\n");
7115
        exit(1);
7116
    }
7117

    
7118
    /* we always create the cdrom drive, even if no disk is there */
7119
    bdrv_init();
7120
    if (cdrom_index >= 0) {
7121
        bs_table[cdrom_index] = bdrv_new("cdrom");
7122
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7123
    }
7124

    
7125
    /* open the virtual block devices */
7126
    for(i = 0; i < MAX_DISKS; i++) {
7127
        if (hd_filename[i]) {
7128
            if (!bs_table[i]) {
7129
                char buf[64];
7130
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7131
                bs_table[i] = bdrv_new(buf);
7132
            }
7133
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7134
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7135
                        hd_filename[i]);
7136
                exit(1);
7137
            }
7138
            if (i == 0 && cyls != 0) {
7139
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7140
                bdrv_set_translation_hint(bs_table[i], translation);
7141
            }
7142
        }
7143
    }
7144

    
7145
    /* we always create at least one floppy disk */
7146
    fd_table[0] = bdrv_new("fda");
7147
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7148

    
7149
    for(i = 0; i < MAX_FD; i++) {
7150
        if (fd_filename[i]) {
7151
            if (!fd_table[i]) {
7152
                char buf[64];
7153
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7154
                fd_table[i] = bdrv_new(buf);
7155
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7156
            }
7157
            if (fd_filename[i] != '\0') {
7158
                if (bdrv_open(fd_table[i], fd_filename[i],
7159
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7160
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7161
                            fd_filename[i]);
7162
                    exit(1);
7163
                }
7164
            }
7165
        }
7166
    }
7167

    
7168
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7169
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7170

    
7171
    init_ioports();
7172

    
7173
    /* terminal init */
7174
    if (nographic) {
7175
        dumb_display_init(ds);
7176
    } else if (vnc_display != NULL) {
7177
        vnc_display_init(ds, vnc_display);
7178
    } else {
7179
#if defined(CONFIG_SDL)
7180
        sdl_display_init(ds, full_screen);
7181
#elif defined(CONFIG_COCOA)
7182
        cocoa_display_init(ds, full_screen);
7183
#else
7184
        dumb_display_init(ds);
7185
#endif
7186
    }
7187

    
7188
    monitor_hd = qemu_chr_open(monitor_device);
7189
    if (!monitor_hd) {
7190
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7191
        exit(1);
7192
    }
7193
    monitor_init(monitor_hd, !nographic);
7194

    
7195
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7196
        const char *devname = serial_devices[i];
7197
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7198
            serial_hds[i] = qemu_chr_open(devname);
7199
            if (!serial_hds[i]) {
7200
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7201
                        devname);
7202
                exit(1);
7203
            }
7204
            if (!strcmp(devname, "vc"))
7205
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7206
        }
7207
    }
7208

    
7209
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7210
        const char *devname = parallel_devices[i];
7211
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7212
            parallel_hds[i] = qemu_chr_open(devname);
7213
            if (!parallel_hds[i]) {
7214
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7215
                        devname);
7216
                exit(1);
7217
            }
7218
            if (!strcmp(devname, "vc"))
7219
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7220
        }
7221
    }
7222

    
7223
    machine->init(ram_size, vga_ram_size, boot_device,
7224
                  ds, fd_filename, snapshot,
7225
                  kernel_filename, kernel_cmdline, initrd_filename);
7226

    
7227
    /* init USB devices */
7228
    if (usb_enabled) {
7229
        for(i = 0; i < usb_devices_index; i++) {
7230
            if (usb_device_add(usb_devices[i]) < 0) {
7231
                fprintf(stderr, "Warning: could not add USB device %s\n",
7232
                        usb_devices[i]);
7233
            }
7234
        }
7235
    }
7236

    
7237
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7238
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7239

    
7240
#ifdef CONFIG_GDBSTUB
7241
    if (use_gdbstub) {
7242
        if (gdbserver_start(gdbstub_port) < 0) {
7243
            fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
7244
                    gdbstub_port);
7245
            exit(1);
7246
        } else {
7247
            printf("Waiting gdb connection on port %d\n", gdbstub_port);
7248
        }
7249
    } else 
7250
#endif
7251
    if (loadvm)
7252
        do_loadvm(loadvm);
7253

    
7254
    {
7255
        /* XXX: simplify init */
7256
        read_passwords();
7257
        if (autostart) {
7258
            vm_start();
7259
        }
7260
    }
7261

    
7262
    if (daemonize) {
7263
        uint8_t status = 0;
7264
        ssize_t len;
7265
        int fd;
7266

    
7267
    again1:
7268
        len = write(fds[1], &status, 1);
7269
        if (len == -1 && (errno == EINTR))
7270
            goto again1;
7271

    
7272
        if (len != 1)
7273
            exit(1);
7274

    
7275
        fd = open("/dev/null", O_RDWR);
7276
        if (fd == -1)
7277
            exit(1);
7278

    
7279
        dup2(fd, 0);
7280
        dup2(fd, 1);
7281
        dup2(fd, 2);
7282

    
7283
        close(fd);
7284
    }
7285

    
7286
    main_loop();
7287
    quit_timers();
7288
    return 0;
7289
}