Statistics
| Branch: | Revision:

root / vl.c @ f88e4b91

History | View | Annotate | Download (238.1 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2008 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 "hw/hw.h"
25
#include "hw/boards.h"
26
#include "hw/usb.h"
27
#include "hw/pcmcia.h"
28
#include "hw/pc.h"
29
#include "hw/audiodev.h"
30
#include "hw/isa.h"
31
#include "hw/baum.h"
32
#include "net.h"
33
#include "console.h"
34
#include "sysemu.h"
35
#include "gdbstub.h"
36
#include "qemu-timer.h"
37
#include "qemu-char.h"
38
#include "block.h"
39
#include "audio/audio.h"
40

    
41
#include <unistd.h>
42
#include <fcntl.h>
43
#include <signal.h>
44
#include <time.h>
45
#include <errno.h>
46
#include <sys/time.h>
47
#include <zlib.h>
48

    
49
#ifndef _WIN32
50
#include <sys/times.h>
51
#include <sys/wait.h>
52
#include <termios.h>
53
#include <sys/poll.h>
54
#include <sys/mman.h>
55
#include <sys/ioctl.h>
56
#include <sys/socket.h>
57
#include <netinet/in.h>
58
#include <dirent.h>
59
#include <netdb.h>
60
#include <sys/select.h>
61
#include <arpa/inet.h>
62
#ifdef _BSD
63
#include <sys/stat.h>
64
#ifndef __APPLE__
65
#include <libutil.h>
66
#endif
67
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68
#include <freebsd/stdlib.h>
69
#else
70
#ifndef __sun__
71
#include <linux/if.h>
72
#include <linux/if_tun.h>
73
#include <pty.h>
74
#include <malloc.h>
75
#include <linux/rtc.h>
76

    
77
/* For the benefit of older linux systems which don't supply it,
78
   we use a local copy of hpet.h. */
79
/* #include <linux/hpet.h> */
80
#include "hpet.h"
81

    
82
#include <linux/ppdev.h>
83
#include <linux/parport.h>
84
#else
85
#include <sys/stat.h>
86
#include <sys/ethernet.h>
87
#include <sys/sockio.h>
88
#include <netinet/arp.h>
89
#include <netinet/in.h>
90
#include <netinet/in_systm.h>
91
#include <netinet/ip.h>
92
#include <netinet/ip_icmp.h> // must come after ip.h
93
#include <netinet/udp.h>
94
#include <netinet/tcp.h>
95
#include <net/if.h>
96
#include <syslog.h>
97
#include <stropts.h>
98
#endif
99
#endif
100
#else
101
#include <winsock2.h>
102
int inet_aton(const char *cp, struct in_addr *ia);
103
#endif
104

    
105
#if defined(CONFIG_SLIRP)
106
#include "libslirp.h"
107
#endif
108

    
109
#if defined(CONFIG_VDE)
110
#include <libvdeplug.h>
111
#endif
112

    
113
#ifdef _WIN32
114
#include <malloc.h>
115
#include <sys/timeb.h>
116
#include <mmsystem.h>
117
#define getopt_long_only getopt_long
118
#define memalign(align, size) malloc(size)
119
#endif
120

    
121
#include "qemu_socket.h"
122

    
123
#ifdef CONFIG_SDL
124
#ifdef __APPLE__
125
#include <SDL/SDL.h>
126
#endif
127
#endif /* CONFIG_SDL */
128

    
129
#ifdef CONFIG_COCOA
130
#undef main
131
#define main qemu_main
132
#endif /* CONFIG_COCOA */
133

    
134
#include "disas.h"
135

    
136
#include "exec-all.h"
137

    
138
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139
#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
140
#ifdef __sun__
141
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
142
#else
143
#define SMBD_COMMAND "/usr/sbin/smbd"
144
#endif
145

    
146
//#define DEBUG_UNUSED_IOPORT
147
//#define DEBUG_IOPORT
148

    
149
#ifdef TARGET_PPC
150
#define DEFAULT_RAM_SIZE 144
151
#else
152
#define DEFAULT_RAM_SIZE 128
153
#endif
154
/* in ms */
155
#define GUI_REFRESH_INTERVAL 30
156

    
157
/* Max number of USB devices that can be specified on the commandline.  */
158
#define MAX_USB_CMDLINE 8
159

    
160
/* XXX: use a two level table to limit memory usage */
161
#define MAX_IOPORTS 65536
162

    
163
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
164
const char *bios_name = NULL;
165
void *ioport_opaque[MAX_IOPORTS];
166
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
167
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
168
/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
169
   to store the VM snapshots */
170
DriveInfo drives_table[MAX_DRIVES+1];
171
int nb_drives;
172
/* point to the block driver where the snapshots are managed */
173
BlockDriverState *bs_snapshots;
174
int vga_ram_size;
175
static DisplayState display_state;
176
int nographic;
177
int curses;
178
const char* keyboard_layout = NULL;
179
int64_t ticks_per_sec;
180
ram_addr_t ram_size;
181
int pit_min_timer_count = 0;
182
int nb_nics;
183
NICInfo nd_table[MAX_NICS];
184
int vm_running;
185
static int rtc_utc = 1;
186
static int rtc_date_offset = -1; /* -1 means no change */
187
int cirrus_vga_enabled = 1;
188
int vmsvga_enabled = 0;
189
#ifdef TARGET_SPARC
190
int graphic_width = 1024;
191
int graphic_height = 768;
192
int graphic_depth = 8;
193
#else
194
int graphic_width = 800;
195
int graphic_height = 600;
196
int graphic_depth = 15;
197
#endif
198
int full_screen = 0;
199
int no_frame = 0;
200
int no_quit = 0;
201
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
202
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
203
#ifdef TARGET_I386
204
int win2k_install_hack = 0;
205
#endif
206
int usb_enabled = 0;
207
static VLANState *first_vlan;
208
int smp_cpus = 1;
209
const char *vnc_display;
210
#if defined(TARGET_SPARC)
211
#define MAX_CPUS 16
212
#elif defined(TARGET_I386)
213
#define MAX_CPUS 255
214
#else
215
#define MAX_CPUS 1
216
#endif
217
int acpi_enabled = 1;
218
int fd_bootchk = 1;
219
int no_reboot = 0;
220
int no_shutdown = 0;
221
int cursor_hide = 1;
222
int graphic_rotate = 0;
223
int daemonize = 0;
224
const char *option_rom[MAX_OPTION_ROMS];
225
int nb_option_roms;
226
int semihosting_enabled = 0;
227
int autostart = 1;
228
#ifdef TARGET_ARM
229
int old_param = 0;
230
#endif
231
const char *qemu_name;
232
int alt_grab = 0;
233
#ifdef TARGET_SPARC
234
unsigned int nb_prom_envs = 0;
235
const char *prom_envs[MAX_PROM_ENVS];
236
#endif
237
int nb_drives_opt;
238
struct drive_opt {
239
    const char *file;
240
    char opt[1024];
241
} drives_opt[MAX_DRIVES];
242

    
243
static CPUState *cur_cpu;
244
static CPUState *next_cpu;
245
static int event_pending = 1;
246
/* Conversion factor from emulated instructions to virtual clock ticks.  */
247
static int icount_time_shift;
248
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
249
#define MAX_ICOUNT_SHIFT 10
250
/* Compensate for varying guest execution speed.  */
251
static int64_t qemu_icount_bias;
252
QEMUTimer *icount_rt_timer;
253
QEMUTimer *icount_vm_timer;
254

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

    
257
/***********************************************************/
258
/* x86 ISA bus support */
259

    
260
target_phys_addr_t isa_mem_base = 0;
261
PicState2 *isa_pic;
262

    
263
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
264
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
265

    
266
static uint32_t ioport_read(int index, uint32_t address)
267
{
268
    static IOPortReadFunc *default_func[3] = {
269
        default_ioport_readb,
270
        default_ioport_readw,
271
        default_ioport_readl
272
    };
273
    IOPortReadFunc *func = ioport_read_table[index][address];
274
    if (!func)
275
        func = default_func[index];
276
    return func(ioport_opaque[address], address);
277
}
278

    
279
static void ioport_write(int index, uint32_t address, uint32_t data)
280
{
281
    static IOPortWriteFunc *default_func[3] = {
282
        default_ioport_writeb,
283
        default_ioport_writew,
284
        default_ioport_writel
285
    };
286
    IOPortWriteFunc *func = ioport_write_table[index][address];
287
    if (!func)
288
        func = default_func[index];
289
    func(ioport_opaque[address], address, data);
290
}
291

    
292
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
293
{
294
#ifdef DEBUG_UNUSED_IOPORT
295
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
296
#endif
297
    return 0xff;
298
}
299

    
300
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
301
{
302
#ifdef DEBUG_UNUSED_IOPORT
303
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
304
#endif
305
}
306

    
307
/* default is to make two byte accesses */
308
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
309
{
310
    uint32_t data;
311
    data = ioport_read(0, address);
312
    address = (address + 1) & (MAX_IOPORTS - 1);
313
    data |= ioport_read(0, address) << 8;
314
    return data;
315
}
316

    
317
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
318
{
319
    ioport_write(0, address, data & 0xff);
320
    address = (address + 1) & (MAX_IOPORTS - 1);
321
    ioport_write(0, address, (data >> 8) & 0xff);
322
}
323

    
324
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
325
{
326
#ifdef DEBUG_UNUSED_IOPORT
327
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
328
#endif
329
    return 0xffffffff;
330
}
331

    
332
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
333
{
334
#ifdef DEBUG_UNUSED_IOPORT
335
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
336
#endif
337
}
338

    
339
/* size is the word size in byte */
340
int register_ioport_read(int start, int length, int size,
341
                         IOPortReadFunc *func, void *opaque)
342
{
343
    int i, bsize;
344

    
345
    if (size == 1) {
346
        bsize = 0;
347
    } else if (size == 2) {
348
        bsize = 1;
349
    } else if (size == 4) {
350
        bsize = 2;
351
    } else {
352
        hw_error("register_ioport_read: invalid size");
353
        return -1;
354
    }
355
    for(i = start; i < start + length; i += size) {
356
        ioport_read_table[bsize][i] = func;
357
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
358
            hw_error("register_ioport_read: invalid opaque");
359
        ioport_opaque[i] = opaque;
360
    }
361
    return 0;
362
}
363

    
364
/* size is the word size in byte */
365
int register_ioport_write(int start, int length, int size,
366
                          IOPortWriteFunc *func, void *opaque)
367
{
368
    int i, bsize;
369

    
370
    if (size == 1) {
371
        bsize = 0;
372
    } else if (size == 2) {
373
        bsize = 1;
374
    } else if (size == 4) {
375
        bsize = 2;
376
    } else {
377
        hw_error("register_ioport_write: invalid size");
378
        return -1;
379
    }
380
    for(i = start; i < start + length; i += size) {
381
        ioport_write_table[bsize][i] = func;
382
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
383
            hw_error("register_ioport_write: invalid opaque");
384
        ioport_opaque[i] = opaque;
385
    }
386
    return 0;
387
}
388

    
389
void isa_unassign_ioport(int start, int length)
390
{
391
    int i;
392

    
393
    for(i = start; i < start + length; i++) {
394
        ioport_read_table[0][i] = default_ioport_readb;
395
        ioport_read_table[1][i] = default_ioport_readw;
396
        ioport_read_table[2][i] = default_ioport_readl;
397

    
398
        ioport_write_table[0][i] = default_ioport_writeb;
399
        ioport_write_table[1][i] = default_ioport_writew;
400
        ioport_write_table[2][i] = default_ioport_writel;
401
    }
402
}
403

    
404
/***********************************************************/
405

    
406
void cpu_outb(CPUState *env, int addr, int val)
407
{
408
#ifdef DEBUG_IOPORT
409
    if (loglevel & CPU_LOG_IOPORT)
410
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
411
#endif
412
    ioport_write(0, addr, val);
413
#ifdef USE_KQEMU
414
    if (env)
415
        env->last_io_time = cpu_get_time_fast();
416
#endif
417
}
418

    
419
void cpu_outw(CPUState *env, int addr, int val)
420
{
421
#ifdef DEBUG_IOPORT
422
    if (loglevel & CPU_LOG_IOPORT)
423
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
424
#endif
425
    ioport_write(1, addr, val);
426
#ifdef USE_KQEMU
427
    if (env)
428
        env->last_io_time = cpu_get_time_fast();
429
#endif
430
}
431

    
432
void cpu_outl(CPUState *env, int addr, int val)
433
{
434
#ifdef DEBUG_IOPORT
435
    if (loglevel & CPU_LOG_IOPORT)
436
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
437
#endif
438
    ioport_write(2, addr, val);
439
#ifdef USE_KQEMU
440
    if (env)
441
        env->last_io_time = cpu_get_time_fast();
442
#endif
443
}
444

    
445
int cpu_inb(CPUState *env, int addr)
446
{
447
    int val;
448
    val = ioport_read(0, addr);
449
#ifdef DEBUG_IOPORT
450
    if (loglevel & CPU_LOG_IOPORT)
451
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
452
#endif
453
#ifdef USE_KQEMU
454
    if (env)
455
        env->last_io_time = cpu_get_time_fast();
456
#endif
457
    return val;
458
}
459

    
460
int cpu_inw(CPUState *env, int addr)
461
{
462
    int val;
463
    val = ioport_read(1, addr);
464
#ifdef DEBUG_IOPORT
465
    if (loglevel & CPU_LOG_IOPORT)
466
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
467
#endif
468
#ifdef USE_KQEMU
469
    if (env)
470
        env->last_io_time = cpu_get_time_fast();
471
#endif
472
    return val;
473
}
474

    
475
int cpu_inl(CPUState *env, int addr)
476
{
477
    int val;
478
    val = ioport_read(2, addr);
479
#ifdef DEBUG_IOPORT
480
    if (loglevel & CPU_LOG_IOPORT)
481
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
482
#endif
483
#ifdef USE_KQEMU
484
    if (env)
485
        env->last_io_time = cpu_get_time_fast();
486
#endif
487
    return val;
488
}
489

    
490
/***********************************************************/
491
void hw_error(const char *fmt, ...)
492
{
493
    va_list ap;
494
    CPUState *env;
495

    
496
    va_start(ap, fmt);
497
    fprintf(stderr, "qemu: hardware error: ");
498
    vfprintf(stderr, fmt, ap);
499
    fprintf(stderr, "\n");
500
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
501
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
502
#ifdef TARGET_I386
503
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
504
#else
505
        cpu_dump_state(env, stderr, fprintf, 0);
506
#endif
507
    }
508
    va_end(ap);
509
    abort();
510
}
511

    
512
/***********************************************************/
513
/* keyboard/mouse */
514

    
515
static QEMUPutKBDEvent *qemu_put_kbd_event;
516
static void *qemu_put_kbd_event_opaque;
517
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
518
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
519

    
520
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
521
{
522
    qemu_put_kbd_event_opaque = opaque;
523
    qemu_put_kbd_event = func;
524
}
525

    
526
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
527
                                                void *opaque, int absolute,
528
                                                const char *name)
529
{
530
    QEMUPutMouseEntry *s, *cursor;
531

    
532
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
533
    if (!s)
534
        return NULL;
535

    
536
    s->qemu_put_mouse_event = func;
537
    s->qemu_put_mouse_event_opaque = opaque;
538
    s->qemu_put_mouse_event_absolute = absolute;
539
    s->qemu_put_mouse_event_name = qemu_strdup(name);
540
    s->next = NULL;
541

    
542
    if (!qemu_put_mouse_event_head) {
543
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
544
        return s;
545
    }
546

    
547
    cursor = qemu_put_mouse_event_head;
548
    while (cursor->next != NULL)
549
        cursor = cursor->next;
550

    
551
    cursor->next = s;
552
    qemu_put_mouse_event_current = s;
553

    
554
    return s;
555
}
556

    
557
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
558
{
559
    QEMUPutMouseEntry *prev = NULL, *cursor;
560

    
561
    if (!qemu_put_mouse_event_head || entry == NULL)
562
        return;
563

    
564
    cursor = qemu_put_mouse_event_head;
565
    while (cursor != NULL && cursor != entry) {
566
        prev = cursor;
567
        cursor = cursor->next;
568
    }
569

    
570
    if (cursor == NULL) // does not exist or list empty
571
        return;
572
    else if (prev == NULL) { // entry is head
573
        qemu_put_mouse_event_head = cursor->next;
574
        if (qemu_put_mouse_event_current == entry)
575
            qemu_put_mouse_event_current = cursor->next;
576
        qemu_free(entry->qemu_put_mouse_event_name);
577
        qemu_free(entry);
578
        return;
579
    }
580

    
581
    prev->next = entry->next;
582

    
583
    if (qemu_put_mouse_event_current == entry)
584
        qemu_put_mouse_event_current = prev;
585

    
586
    qemu_free(entry->qemu_put_mouse_event_name);
587
    qemu_free(entry);
588
}
589

    
590
void kbd_put_keycode(int keycode)
591
{
592
    if (qemu_put_kbd_event) {
593
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
594
    }
595
}
596

    
597
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
598
{
599
    QEMUPutMouseEvent *mouse_event;
600
    void *mouse_event_opaque;
601
    int width;
602

    
603
    if (!qemu_put_mouse_event_current) {
604
        return;
605
    }
606

    
607
    mouse_event =
608
        qemu_put_mouse_event_current->qemu_put_mouse_event;
609
    mouse_event_opaque =
610
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
611

    
612
    if (mouse_event) {
613
        if (graphic_rotate) {
614
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
615
                width = 0x7fff;
616
            else
617
                width = graphic_width - 1;
618
            mouse_event(mouse_event_opaque,
619
                                 width - dy, dx, dz, buttons_state);
620
        } else
621
            mouse_event(mouse_event_opaque,
622
                                 dx, dy, dz, buttons_state);
623
    }
624
}
625

    
626
int kbd_mouse_is_absolute(void)
627
{
628
    if (!qemu_put_mouse_event_current)
629
        return 0;
630

    
631
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
632
}
633

    
634
void do_info_mice(void)
635
{
636
    QEMUPutMouseEntry *cursor;
637
    int index = 0;
638

    
639
    if (!qemu_put_mouse_event_head) {
640
        term_printf("No mouse devices connected\n");
641
        return;
642
    }
643

    
644
    term_printf("Mouse devices available:\n");
645
    cursor = qemu_put_mouse_event_head;
646
    while (cursor != NULL) {
647
        term_printf("%c Mouse #%d: %s\n",
648
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
649
                    index, cursor->qemu_put_mouse_event_name);
650
        index++;
651
        cursor = cursor->next;
652
    }
653
}
654

    
655
void do_mouse_set(int index)
656
{
657
    QEMUPutMouseEntry *cursor;
658
    int i = 0;
659

    
660
    if (!qemu_put_mouse_event_head) {
661
        term_printf("No mouse devices connected\n");
662
        return;
663
    }
664

    
665
    cursor = qemu_put_mouse_event_head;
666
    while (cursor != NULL && index != i) {
667
        i++;
668
        cursor = cursor->next;
669
    }
670

    
671
    if (cursor != NULL)
672
        qemu_put_mouse_event_current = cursor;
673
    else
674
        term_printf("Mouse at given index not found\n");
675
}
676

    
677
/* compute with 96 bit intermediate result: (a*b)/c */
678
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
679
{
680
    union {
681
        uint64_t ll;
682
        struct {
683
#ifdef WORDS_BIGENDIAN
684
            uint32_t high, low;
685
#else
686
            uint32_t low, high;
687
#endif
688
        } l;
689
    } u, res;
690
    uint64_t rl, rh;
691

    
692
    u.ll = a;
693
    rl = (uint64_t)u.l.low * (uint64_t)b;
694
    rh = (uint64_t)u.l.high * (uint64_t)b;
695
    rh += (rl >> 32);
696
    res.l.high = rh / c;
697
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
698
    return res.ll;
699
}
700

    
701
/***********************************************************/
702
/* real time host monotonic timer */
703

    
704
#define QEMU_TIMER_BASE 1000000000LL
705

    
706
#ifdef WIN32
707

    
708
static int64_t clock_freq;
709

    
710
static void init_get_clock(void)
711
{
712
    LARGE_INTEGER freq;
713
    int ret;
714
    ret = QueryPerformanceFrequency(&freq);
715
    if (ret == 0) {
716
        fprintf(stderr, "Could not calibrate ticks\n");
717
        exit(1);
718
    }
719
    clock_freq = freq.QuadPart;
720
}
721

    
722
static int64_t get_clock(void)
723
{
724
    LARGE_INTEGER ti;
725
    QueryPerformanceCounter(&ti);
726
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
727
}
728

    
729
#else
730

    
731
static int use_rt_clock;
732

    
733
static void init_get_clock(void)
734
{
735
    use_rt_clock = 0;
736
#if defined(__linux__)
737
    {
738
        struct timespec ts;
739
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
740
            use_rt_clock = 1;
741
        }
742
    }
743
#endif
744
}
745

    
746
static int64_t get_clock(void)
747
{
748
#if defined(__linux__)
749
    if (use_rt_clock) {
750
        struct timespec ts;
751
        clock_gettime(CLOCK_MONOTONIC, &ts);
752
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
753
    } else
754
#endif
755
    {
756
        /* XXX: using gettimeofday leads to problems if the date
757
           changes, so it should be avoided. */
758
        struct timeval tv;
759
        gettimeofday(&tv, NULL);
760
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
761
    }
762
}
763
#endif
764

    
765
/* Return the virtual CPU time, based on the instruction counter.  */
766
static int64_t cpu_get_icount(void)
767
{
768
    int64_t icount;
769
    CPUState *env = cpu_single_env;;
770
    icount = qemu_icount;
771
    if (env) {
772
        if (!can_do_io(env))
773
            fprintf(stderr, "Bad clock read\n");
774
        icount -= (env->icount_decr.u16.low + env->icount_extra);
775
    }
776
    return qemu_icount_bias + (icount << icount_time_shift);
777
}
778

    
779
/***********************************************************/
780
/* guest cycle counter */
781

    
782
static int64_t cpu_ticks_prev;
783
static int64_t cpu_ticks_offset;
784
static int64_t cpu_clock_offset;
785
static int cpu_ticks_enabled;
786

    
787
/* return the host CPU cycle counter and handle stop/restart */
788
int64_t cpu_get_ticks(void)
789
{
790
    if (use_icount) {
791
        return cpu_get_icount();
792
    }
793
    if (!cpu_ticks_enabled) {
794
        return cpu_ticks_offset;
795
    } else {
796
        int64_t ticks;
797
        ticks = cpu_get_real_ticks();
798
        if (cpu_ticks_prev > ticks) {
799
            /* Note: non increasing ticks may happen if the host uses
800
               software suspend */
801
            cpu_ticks_offset += cpu_ticks_prev - ticks;
802
        }
803
        cpu_ticks_prev = ticks;
804
        return ticks + cpu_ticks_offset;
805
    }
806
}
807

    
808
/* return the host CPU monotonic timer and handle stop/restart */
809
static int64_t cpu_get_clock(void)
810
{
811
    int64_t ti;
812
    if (!cpu_ticks_enabled) {
813
        return cpu_clock_offset;
814
    } else {
815
        ti = get_clock();
816
        return ti + cpu_clock_offset;
817
    }
818
}
819

    
820
/* enable cpu_get_ticks() */
821
void cpu_enable_ticks(void)
822
{
823
    if (!cpu_ticks_enabled) {
824
        cpu_ticks_offset -= cpu_get_real_ticks();
825
        cpu_clock_offset -= get_clock();
826
        cpu_ticks_enabled = 1;
827
    }
828
}
829

    
830
/* disable cpu_get_ticks() : the clock is stopped. You must not call
831
   cpu_get_ticks() after that.  */
832
void cpu_disable_ticks(void)
833
{
834
    if (cpu_ticks_enabled) {
835
        cpu_ticks_offset = cpu_get_ticks();
836
        cpu_clock_offset = cpu_get_clock();
837
        cpu_ticks_enabled = 0;
838
    }
839
}
840

    
841
/***********************************************************/
842
/* timers */
843

    
844
#define QEMU_TIMER_REALTIME 0
845
#define QEMU_TIMER_VIRTUAL  1
846

    
847
struct QEMUClock {
848
    int type;
849
    /* XXX: add frequency */
850
};
851

    
852
struct QEMUTimer {
853
    QEMUClock *clock;
854
    int64_t expire_time;
855
    QEMUTimerCB *cb;
856
    void *opaque;
857
    struct QEMUTimer *next;
858
};
859

    
860
struct qemu_alarm_timer {
861
    char const *name;
862
    unsigned int flags;
863

    
864
    int (*start)(struct qemu_alarm_timer *t);
865
    void (*stop)(struct qemu_alarm_timer *t);
866
    void (*rearm)(struct qemu_alarm_timer *t);
867
    void *priv;
868
};
869

    
870
#define ALARM_FLAG_DYNTICKS  0x1
871
#define ALARM_FLAG_EXPIRED   0x2
872

    
873
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
874
{
875
    return t->flags & ALARM_FLAG_DYNTICKS;
876
}
877

    
878
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
879
{
880
    if (!alarm_has_dynticks(t))
881
        return;
882

    
883
    t->rearm(t);
884
}
885

    
886
/* TODO: MIN_TIMER_REARM_US should be optimized */
887
#define MIN_TIMER_REARM_US 250
888

    
889
static struct qemu_alarm_timer *alarm_timer;
890

    
891
#ifdef _WIN32
892

    
893
struct qemu_alarm_win32 {
894
    MMRESULT timerId;
895
    HANDLE host_alarm;
896
    unsigned int period;
897
} alarm_win32_data = {0, NULL, -1};
898

    
899
static int win32_start_timer(struct qemu_alarm_timer *t);
900
static void win32_stop_timer(struct qemu_alarm_timer *t);
901
static void win32_rearm_timer(struct qemu_alarm_timer *t);
902

    
903
#else
904

    
905
static int unix_start_timer(struct qemu_alarm_timer *t);
906
static void unix_stop_timer(struct qemu_alarm_timer *t);
907

    
908
#ifdef __linux__
909

    
910
static int dynticks_start_timer(struct qemu_alarm_timer *t);
911
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
912
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
913

    
914
static int hpet_start_timer(struct qemu_alarm_timer *t);
915
static void hpet_stop_timer(struct qemu_alarm_timer *t);
916

    
917
static int rtc_start_timer(struct qemu_alarm_timer *t);
918
static void rtc_stop_timer(struct qemu_alarm_timer *t);
919

    
920
#endif /* __linux__ */
921

    
922
#endif /* _WIN32 */
923

    
924
/* Correlation between real and virtual time is always going to be
925
   fairly approximate, so ignore small variation.
926
   When the guest is idle real and virtual time will be aligned in
927
   the IO wait loop.  */
928
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
929

    
930
static void icount_adjust(void)
931
{
932
    int64_t cur_time;
933
    int64_t cur_icount;
934
    int64_t delta;
935
    static int64_t last_delta;
936
    /* If the VM is not running, then do nothing.  */
937
    if (!vm_running)
938
        return;
939

    
940
    cur_time = cpu_get_clock();
941
    cur_icount = qemu_get_clock(vm_clock);
942
    delta = cur_icount - cur_time;
943
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
944
    if (delta > 0
945
        && last_delta + ICOUNT_WOBBLE < delta * 2
946
        && icount_time_shift > 0) {
947
        /* The guest is getting too far ahead.  Slow time down.  */
948
        icount_time_shift--;
949
    }
950
    if (delta < 0
951
        && last_delta - ICOUNT_WOBBLE > delta * 2
952
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
953
        /* The guest is getting too far behind.  Speed time up.  */
954
        icount_time_shift++;
955
    }
956
    last_delta = delta;
957
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
958
}
959

    
960
static void icount_adjust_rt(void * opaque)
961
{
962
    qemu_mod_timer(icount_rt_timer,
963
                   qemu_get_clock(rt_clock) + 1000);
964
    icount_adjust();
965
}
966

    
967
static void icount_adjust_vm(void * opaque)
968
{
969
    qemu_mod_timer(icount_vm_timer,
970
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
971
    icount_adjust();
972
}
973

    
974
static void init_icount_adjust(void)
975
{
976
    /* Have both realtime and virtual time triggers for speed adjustment.
977
       The realtime trigger catches emulated time passing too slowly,
978
       the virtual time trigger catches emulated time passing too fast.
979
       Realtime triggers occur even when idle, so use them less frequently
980
       than VM triggers.  */
981
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
982
    qemu_mod_timer(icount_rt_timer,
983
                   qemu_get_clock(rt_clock) + 1000);
984
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
985
    qemu_mod_timer(icount_vm_timer,
986
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
987
}
988

    
989
static struct qemu_alarm_timer alarm_timers[] = {
990
#ifndef _WIN32
991
#ifdef __linux__
992
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
993
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
994
    /* HPET - if available - is preferred */
995
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
996
    /* ...otherwise try RTC */
997
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
998
#endif
999
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1000
#else
1001
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1002
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1003
    {"win32", 0, win32_start_timer,
1004
     win32_stop_timer, NULL, &alarm_win32_data},
1005
#endif
1006
    {NULL, }
1007
};
1008

    
1009
static void show_available_alarms(void)
1010
{
1011
    int i;
1012

    
1013
    printf("Available alarm timers, in order of precedence:\n");
1014
    for (i = 0; alarm_timers[i].name; i++)
1015
        printf("%s\n", alarm_timers[i].name);
1016
}
1017

    
1018
static void configure_alarms(char const *opt)
1019
{
1020
    int i;
1021
    int cur = 0;
1022
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1023
    char *arg;
1024
    char *name;
1025
    struct qemu_alarm_timer tmp;
1026

    
1027
    if (!strcmp(opt, "?")) {
1028
        show_available_alarms();
1029
        exit(0);
1030
    }
1031

    
1032
    arg = strdup(opt);
1033

    
1034
    /* Reorder the array */
1035
    name = strtok(arg, ",");
1036
    while (name) {
1037
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1038
            if (!strcmp(alarm_timers[i].name, name))
1039
                break;
1040
        }
1041

    
1042
        if (i == count) {
1043
            fprintf(stderr, "Unknown clock %s\n", name);
1044
            goto next;
1045
        }
1046

    
1047
        if (i < cur)
1048
            /* Ignore */
1049
            goto next;
1050

    
1051
        /* Swap */
1052
        tmp = alarm_timers[i];
1053
        alarm_timers[i] = alarm_timers[cur];
1054
        alarm_timers[cur] = tmp;
1055

    
1056
        cur++;
1057
next:
1058
        name = strtok(NULL, ",");
1059
    }
1060

    
1061
    free(arg);
1062

    
1063
    if (cur) {
1064
        /* Disable remaining timers */
1065
        for (i = cur; i < count; i++)
1066
            alarm_timers[i].name = NULL;
1067
    } else {
1068
        show_available_alarms();
1069
        exit(1);
1070
    }
1071
}
1072

    
1073
QEMUClock *rt_clock;
1074
QEMUClock *vm_clock;
1075

    
1076
static QEMUTimer *active_timers[2];
1077

    
1078
static QEMUClock *qemu_new_clock(int type)
1079
{
1080
    QEMUClock *clock;
1081
    clock = qemu_mallocz(sizeof(QEMUClock));
1082
    if (!clock)
1083
        return NULL;
1084
    clock->type = type;
1085
    return clock;
1086
}
1087

    
1088
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1089
{
1090
    QEMUTimer *ts;
1091

    
1092
    ts = qemu_mallocz(sizeof(QEMUTimer));
1093
    ts->clock = clock;
1094
    ts->cb = cb;
1095
    ts->opaque = opaque;
1096
    return ts;
1097
}
1098

    
1099
void qemu_free_timer(QEMUTimer *ts)
1100
{
1101
    qemu_free(ts);
1102
}
1103

    
1104
/* stop a timer, but do not dealloc it */
1105
void qemu_del_timer(QEMUTimer *ts)
1106
{
1107
    QEMUTimer **pt, *t;
1108

    
1109
    /* NOTE: this code must be signal safe because
1110
       qemu_timer_expired() can be called from a signal. */
1111
    pt = &active_timers[ts->clock->type];
1112
    for(;;) {
1113
        t = *pt;
1114
        if (!t)
1115
            break;
1116
        if (t == ts) {
1117
            *pt = t->next;
1118
            break;
1119
        }
1120
        pt = &t->next;
1121
    }
1122
}
1123

    
1124
/* modify the current timer so that it will be fired when current_time
1125
   >= expire_time. The corresponding callback will be called. */
1126
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1127
{
1128
    QEMUTimer **pt, *t;
1129

    
1130
    qemu_del_timer(ts);
1131

    
1132
    /* add the timer in the sorted list */
1133
    /* NOTE: this code must be signal safe because
1134
       qemu_timer_expired() can be called from a signal. */
1135
    pt = &active_timers[ts->clock->type];
1136
    for(;;) {
1137
        t = *pt;
1138
        if (!t)
1139
            break;
1140
        if (t->expire_time > expire_time)
1141
            break;
1142
        pt = &t->next;
1143
    }
1144
    ts->expire_time = expire_time;
1145
    ts->next = *pt;
1146
    *pt = ts;
1147

    
1148
    /* Rearm if necessary  */
1149
    if (pt == &active_timers[ts->clock->type]) {
1150
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1151
            qemu_rearm_alarm_timer(alarm_timer);
1152
        }
1153
        /* Interrupt execution to force deadline recalculation.  */
1154
        if (use_icount && cpu_single_env) {
1155
            cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1156
        }
1157
    }
1158
}
1159

    
1160
int qemu_timer_pending(QEMUTimer *ts)
1161
{
1162
    QEMUTimer *t;
1163
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1164
        if (t == ts)
1165
            return 1;
1166
    }
1167
    return 0;
1168
}
1169

    
1170
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1171
{
1172
    if (!timer_head)
1173
        return 0;
1174
    return (timer_head->expire_time <= current_time);
1175
}
1176

    
1177
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1178
{
1179
    QEMUTimer *ts;
1180

    
1181
    for(;;) {
1182
        ts = *ptimer_head;
1183
        if (!ts || ts->expire_time > current_time)
1184
            break;
1185
        /* remove timer from the list before calling the callback */
1186
        *ptimer_head = ts->next;
1187
        ts->next = NULL;
1188

    
1189
        /* run the callback (the timer list can be modified) */
1190
        ts->cb(ts->opaque);
1191
    }
1192
}
1193

    
1194
int64_t qemu_get_clock(QEMUClock *clock)
1195
{
1196
    switch(clock->type) {
1197
    case QEMU_TIMER_REALTIME:
1198
        return get_clock() / 1000000;
1199
    default:
1200
    case QEMU_TIMER_VIRTUAL:
1201
        if (use_icount) {
1202
            return cpu_get_icount();
1203
        } else {
1204
            return cpu_get_clock();
1205
        }
1206
    }
1207
}
1208

    
1209
static void init_timers(void)
1210
{
1211
    init_get_clock();
1212
    ticks_per_sec = QEMU_TIMER_BASE;
1213
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1214
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1215
}
1216

    
1217
/* save a timer */
1218
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1219
{
1220
    uint64_t expire_time;
1221

    
1222
    if (qemu_timer_pending(ts)) {
1223
        expire_time = ts->expire_time;
1224
    } else {
1225
        expire_time = -1;
1226
    }
1227
    qemu_put_be64(f, expire_time);
1228
}
1229

    
1230
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1231
{
1232
    uint64_t expire_time;
1233

    
1234
    expire_time = qemu_get_be64(f);
1235
    if (expire_time != -1) {
1236
        qemu_mod_timer(ts, expire_time);
1237
    } else {
1238
        qemu_del_timer(ts);
1239
    }
1240
}
1241

    
1242
static void timer_save(QEMUFile *f, void *opaque)
1243
{
1244
    if (cpu_ticks_enabled) {
1245
        hw_error("cannot save state if virtual timers are running");
1246
    }
1247
    qemu_put_be64(f, cpu_ticks_offset);
1248
    qemu_put_be64(f, ticks_per_sec);
1249
    qemu_put_be64(f, cpu_clock_offset);
1250
}
1251

    
1252
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1253
{
1254
    if (version_id != 1 && version_id != 2)
1255
        return -EINVAL;
1256
    if (cpu_ticks_enabled) {
1257
        return -EINVAL;
1258
    }
1259
    cpu_ticks_offset=qemu_get_be64(f);
1260
    ticks_per_sec=qemu_get_be64(f);
1261
    if (version_id == 2) {
1262
        cpu_clock_offset=qemu_get_be64(f);
1263
    }
1264
    return 0;
1265
}
1266

    
1267
#ifdef _WIN32
1268
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1269
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1270
#else
1271
static void host_alarm_handler(int host_signum)
1272
#endif
1273
{
1274
#if 0
1275
#define DISP_FREQ 1000
1276
    {
1277
        static int64_t delta_min = INT64_MAX;
1278
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1279
        static int count;
1280
        ti = qemu_get_clock(vm_clock);
1281
        if (last_clock != 0) {
1282
            delta = ti - last_clock;
1283
            if (delta < delta_min)
1284
                delta_min = delta;
1285
            if (delta > delta_max)
1286
                delta_max = delta;
1287
            delta_cum += delta;
1288
            if (++count == DISP_FREQ) {
1289
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1290
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1291
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1292
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1293
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1294
                count = 0;
1295
                delta_min = INT64_MAX;
1296
                delta_max = 0;
1297
                delta_cum = 0;
1298
            }
1299
        }
1300
        last_clock = ti;
1301
    }
1302
#endif
1303
    if (alarm_has_dynticks(alarm_timer) ||
1304
        (!use_icount &&
1305
            qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1306
                               qemu_get_clock(vm_clock))) ||
1307
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1308
                           qemu_get_clock(rt_clock))) {
1309
#ifdef _WIN32
1310
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1311
        SetEvent(data->host_alarm);
1312
#endif
1313
        CPUState *env = next_cpu;
1314

    
1315
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1316

    
1317
        if (env) {
1318
            /* stop the currently executing cpu because a timer occured */
1319
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1320
#ifdef USE_KQEMU
1321
            if (env->kqemu_enabled) {
1322
                kqemu_cpu_interrupt(env);
1323
            }
1324
#endif
1325
        }
1326
        event_pending = 1;
1327
    }
1328
}
1329

    
1330
static int64_t qemu_next_deadline(void)
1331
{
1332
    int64_t delta;
1333

    
1334
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1335
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1336
                     qemu_get_clock(vm_clock);
1337
    } else {
1338
        /* To avoid problems with overflow limit this to 2^32.  */
1339
        delta = INT32_MAX;
1340
    }
1341

    
1342
    if (delta < 0)
1343
        delta = 0;
1344

    
1345
    return delta;
1346
}
1347

    
1348
static uint64_t qemu_next_deadline_dyntick(void)
1349
{
1350
    int64_t delta;
1351
    int64_t rtdelta;
1352

    
1353
    if (use_icount)
1354
        delta = INT32_MAX;
1355
    else
1356
        delta = (qemu_next_deadline() + 999) / 1000;
1357

    
1358
    if (active_timers[QEMU_TIMER_REALTIME]) {
1359
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1360
                 qemu_get_clock(rt_clock))*1000;
1361
        if (rtdelta < delta)
1362
            delta = rtdelta;
1363
    }
1364

    
1365
    if (delta < MIN_TIMER_REARM_US)
1366
        delta = MIN_TIMER_REARM_US;
1367

    
1368
    return delta;
1369
}
1370

    
1371
#ifndef _WIN32
1372

    
1373
#if defined(__linux__)
1374

    
1375
#define RTC_FREQ 1024
1376

    
1377
static void enable_sigio_timer(int fd)
1378
{
1379
    struct sigaction act;
1380

    
1381
    /* timer signal */
1382
    sigfillset(&act.sa_mask);
1383
    act.sa_flags = 0;
1384
    act.sa_handler = host_alarm_handler;
1385

    
1386
    sigaction(SIGIO, &act, NULL);
1387
    fcntl(fd, F_SETFL, O_ASYNC);
1388
    fcntl(fd, F_SETOWN, getpid());
1389
}
1390

    
1391
static int hpet_start_timer(struct qemu_alarm_timer *t)
1392
{
1393
    struct hpet_info info;
1394
    int r, fd;
1395

    
1396
    fd = open("/dev/hpet", O_RDONLY);
1397
    if (fd < 0)
1398
        return -1;
1399

    
1400
    /* Set frequency */
1401
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1402
    if (r < 0) {
1403
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1404
                "error, but for better emulation accuracy type:\n"
1405
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1406
        goto fail;
1407
    }
1408

    
1409
    /* Check capabilities */
1410
    r = ioctl(fd, HPET_INFO, &info);
1411
    if (r < 0)
1412
        goto fail;
1413

    
1414
    /* Enable periodic mode */
1415
    r = ioctl(fd, HPET_EPI, 0);
1416
    if (info.hi_flags && (r < 0))
1417
        goto fail;
1418

    
1419
    /* Enable interrupt */
1420
    r = ioctl(fd, HPET_IE_ON, 0);
1421
    if (r < 0)
1422
        goto fail;
1423

    
1424
    enable_sigio_timer(fd);
1425
    t->priv = (void *)(long)fd;
1426

    
1427
    return 0;
1428
fail:
1429
    close(fd);
1430
    return -1;
1431
}
1432

    
1433
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1434
{
1435
    int fd = (long)t->priv;
1436

    
1437
    close(fd);
1438
}
1439

    
1440
static int rtc_start_timer(struct qemu_alarm_timer *t)
1441
{
1442
    int rtc_fd;
1443
    unsigned long current_rtc_freq = 0;
1444

    
1445
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1446
    if (rtc_fd < 0)
1447
        return -1;
1448
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1449
    if (current_rtc_freq != RTC_FREQ &&
1450
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1451
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1452
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1453
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1454
        goto fail;
1455
    }
1456
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1457
    fail:
1458
        close(rtc_fd);
1459
        return -1;
1460
    }
1461

    
1462
    enable_sigio_timer(rtc_fd);
1463

    
1464
    t->priv = (void *)(long)rtc_fd;
1465

    
1466
    return 0;
1467
}
1468

    
1469
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1470
{
1471
    int rtc_fd = (long)t->priv;
1472

    
1473
    close(rtc_fd);
1474
}
1475

    
1476
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1477
{
1478
    struct sigevent ev;
1479
    timer_t host_timer;
1480
    struct sigaction act;
1481

    
1482
    sigfillset(&act.sa_mask);
1483
    act.sa_flags = 0;
1484
    act.sa_handler = host_alarm_handler;
1485

    
1486
    sigaction(SIGALRM, &act, NULL);
1487

    
1488
    ev.sigev_value.sival_int = 0;
1489
    ev.sigev_notify = SIGEV_SIGNAL;
1490
    ev.sigev_signo = SIGALRM;
1491

    
1492
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1493
        perror("timer_create");
1494

    
1495
        /* disable dynticks */
1496
        fprintf(stderr, "Dynamic Ticks disabled\n");
1497

    
1498
        return -1;
1499
    }
1500

    
1501
    t->priv = (void *)host_timer;
1502

    
1503
    return 0;
1504
}
1505

    
1506
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1507
{
1508
    timer_t host_timer = (timer_t)t->priv;
1509

    
1510
    timer_delete(host_timer);
1511
}
1512

    
1513
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1514
{
1515
    timer_t host_timer = (timer_t)t->priv;
1516
    struct itimerspec timeout;
1517
    int64_t nearest_delta_us = INT64_MAX;
1518
    int64_t current_us;
1519

    
1520
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1521
                !active_timers[QEMU_TIMER_VIRTUAL])
1522
        return;
1523

    
1524
    nearest_delta_us = qemu_next_deadline_dyntick();
1525

    
1526
    /* check whether a timer is already running */
1527
    if (timer_gettime(host_timer, &timeout)) {
1528
        perror("gettime");
1529
        fprintf(stderr, "Internal timer error: aborting\n");
1530
        exit(1);
1531
    }
1532
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1533
    if (current_us && current_us <= nearest_delta_us)
1534
        return;
1535

    
1536
    timeout.it_interval.tv_sec = 0;
1537
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1538
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1539
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1540
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1541
        perror("settime");
1542
        fprintf(stderr, "Internal timer error: aborting\n");
1543
        exit(1);
1544
    }
1545
}
1546

    
1547
#endif /* defined(__linux__) */
1548

    
1549
static int unix_start_timer(struct qemu_alarm_timer *t)
1550
{
1551
    struct sigaction act;
1552
    struct itimerval itv;
1553
    int err;
1554

    
1555
    /* timer signal */
1556
    sigfillset(&act.sa_mask);
1557
    act.sa_flags = 0;
1558
    act.sa_handler = host_alarm_handler;
1559

    
1560
    sigaction(SIGALRM, &act, NULL);
1561

    
1562
    itv.it_interval.tv_sec = 0;
1563
    /* for i386 kernel 2.6 to get 1 ms */
1564
    itv.it_interval.tv_usec = 999;
1565
    itv.it_value.tv_sec = 0;
1566
    itv.it_value.tv_usec = 10 * 1000;
1567

    
1568
    err = setitimer(ITIMER_REAL, &itv, NULL);
1569
    if (err)
1570
        return -1;
1571

    
1572
    return 0;
1573
}
1574

    
1575
static void unix_stop_timer(struct qemu_alarm_timer *t)
1576
{
1577
    struct itimerval itv;
1578

    
1579
    memset(&itv, 0, sizeof(itv));
1580
    setitimer(ITIMER_REAL, &itv, NULL);
1581
}
1582

    
1583
#endif /* !defined(_WIN32) */
1584

    
1585
#ifdef _WIN32
1586

    
1587
static int win32_start_timer(struct qemu_alarm_timer *t)
1588
{
1589
    TIMECAPS tc;
1590
    struct qemu_alarm_win32 *data = t->priv;
1591
    UINT flags;
1592

    
1593
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1594
    if (!data->host_alarm) {
1595
        perror("Failed CreateEvent");
1596
        return -1;
1597
    }
1598

    
1599
    memset(&tc, 0, sizeof(tc));
1600
    timeGetDevCaps(&tc, sizeof(tc));
1601

    
1602
    if (data->period < tc.wPeriodMin)
1603
        data->period = tc.wPeriodMin;
1604

    
1605
    timeBeginPeriod(data->period);
1606

    
1607
    flags = TIME_CALLBACK_FUNCTION;
1608
    if (alarm_has_dynticks(t))
1609
        flags |= TIME_ONESHOT;
1610
    else
1611
        flags |= TIME_PERIODIC;
1612

    
1613
    data->timerId = timeSetEvent(1,         // interval (ms)
1614
                        data->period,       // resolution
1615
                        host_alarm_handler, // function
1616
                        (DWORD)t,           // parameter
1617
                        flags);
1618

    
1619
    if (!data->timerId) {
1620
        perror("Failed to initialize win32 alarm timer");
1621

    
1622
        timeEndPeriod(data->period);
1623
        CloseHandle(data->host_alarm);
1624
        return -1;
1625
    }
1626

    
1627
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1628

    
1629
    return 0;
1630
}
1631

    
1632
static void win32_stop_timer(struct qemu_alarm_timer *t)
1633
{
1634
    struct qemu_alarm_win32 *data = t->priv;
1635

    
1636
    timeKillEvent(data->timerId);
1637
    timeEndPeriod(data->period);
1638

    
1639
    CloseHandle(data->host_alarm);
1640
}
1641

    
1642
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1643
{
1644
    struct qemu_alarm_win32 *data = t->priv;
1645
    uint64_t nearest_delta_us;
1646

    
1647
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1648
                !active_timers[QEMU_TIMER_VIRTUAL])
1649
        return;
1650

    
1651
    nearest_delta_us = qemu_next_deadline_dyntick();
1652
    nearest_delta_us /= 1000;
1653

    
1654
    timeKillEvent(data->timerId);
1655

    
1656
    data->timerId = timeSetEvent(1,
1657
                        data->period,
1658
                        host_alarm_handler,
1659
                        (DWORD)t,
1660
                        TIME_ONESHOT | TIME_PERIODIC);
1661

    
1662
    if (!data->timerId) {
1663
        perror("Failed to re-arm win32 alarm timer");
1664

    
1665
        timeEndPeriod(data->period);
1666
        CloseHandle(data->host_alarm);
1667
        exit(1);
1668
    }
1669
}
1670

    
1671
#endif /* _WIN32 */
1672

    
1673
static void init_timer_alarm(void)
1674
{
1675
    struct qemu_alarm_timer *t;
1676
    int i, err = -1;
1677

    
1678
    for (i = 0; alarm_timers[i].name; i++) {
1679
        t = &alarm_timers[i];
1680

    
1681
        err = t->start(t);
1682
        if (!err)
1683
            break;
1684
    }
1685

    
1686
    if (err) {
1687
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1688
        fprintf(stderr, "Terminating\n");
1689
        exit(1);
1690
    }
1691

    
1692
    alarm_timer = t;
1693
}
1694

    
1695
static void quit_timers(void)
1696
{
1697
    alarm_timer->stop(alarm_timer);
1698
    alarm_timer = NULL;
1699
}
1700

    
1701
/***********************************************************/
1702
/* host time/date access */
1703
void qemu_get_timedate(struct tm *tm, int offset)
1704
{
1705
    time_t ti;
1706
    struct tm *ret;
1707

    
1708
    time(&ti);
1709
    ti += offset;
1710
    if (rtc_date_offset == -1) {
1711
        if (rtc_utc)
1712
            ret = gmtime(&ti);
1713
        else
1714
            ret = localtime(&ti);
1715
    } else {
1716
        ti -= rtc_date_offset;
1717
        ret = gmtime(&ti);
1718
    }
1719

    
1720
    memcpy(tm, ret, sizeof(struct tm));
1721
}
1722

    
1723
int qemu_timedate_diff(struct tm *tm)
1724
{
1725
    time_t seconds;
1726

    
1727
    if (rtc_date_offset == -1)
1728
        if (rtc_utc)
1729
            seconds = mktimegm(tm);
1730
        else
1731
            seconds = mktime(tm);
1732
    else
1733
        seconds = mktimegm(tm) + rtc_date_offset;
1734

    
1735
    return seconds - time(NULL);
1736
}
1737

    
1738
/***********************************************************/
1739
/* character device */
1740

    
1741
static void qemu_chr_event(CharDriverState *s, int event)
1742
{
1743
    if (!s->chr_event)
1744
        return;
1745
    s->chr_event(s->handler_opaque, event);
1746
}
1747

    
1748
static void qemu_chr_reset_bh(void *opaque)
1749
{
1750
    CharDriverState *s = opaque;
1751
    qemu_chr_event(s, CHR_EVENT_RESET);
1752
    qemu_bh_delete(s->bh);
1753
    s->bh = NULL;
1754
}
1755

    
1756
void qemu_chr_reset(CharDriverState *s)
1757
{
1758
    if (s->bh == NULL) {
1759
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1760
        qemu_bh_schedule(s->bh);
1761
    }
1762
}
1763

    
1764
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1765
{
1766
    return s->chr_write(s, buf, len);
1767
}
1768

    
1769
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1770
{
1771
    if (!s->chr_ioctl)
1772
        return -ENOTSUP;
1773
    return s->chr_ioctl(s, cmd, arg);
1774
}
1775

    
1776
int qemu_chr_can_read(CharDriverState *s)
1777
{
1778
    if (!s->chr_can_read)
1779
        return 0;
1780
    return s->chr_can_read(s->handler_opaque);
1781
}
1782

    
1783
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1784
{
1785
    s->chr_read(s->handler_opaque, buf, len);
1786
}
1787

    
1788
void qemu_chr_accept_input(CharDriverState *s)
1789
{
1790
    if (s->chr_accept_input)
1791
        s->chr_accept_input(s);
1792
}
1793

    
1794
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1795
{
1796
    char buf[4096];
1797
    va_list ap;
1798
    va_start(ap, fmt);
1799
    vsnprintf(buf, sizeof(buf), fmt, ap);
1800
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1801
    va_end(ap);
1802
}
1803

    
1804
void qemu_chr_send_event(CharDriverState *s, int event)
1805
{
1806
    if (s->chr_send_event)
1807
        s->chr_send_event(s, event);
1808
}
1809

    
1810
void qemu_chr_add_handlers(CharDriverState *s,
1811
                           IOCanRWHandler *fd_can_read,
1812
                           IOReadHandler *fd_read,
1813
                           IOEventHandler *fd_event,
1814
                           void *opaque)
1815
{
1816
    s->chr_can_read = fd_can_read;
1817
    s->chr_read = fd_read;
1818
    s->chr_event = fd_event;
1819
    s->handler_opaque = opaque;
1820
    if (s->chr_update_read_handler)
1821
        s->chr_update_read_handler(s);
1822
}
1823

    
1824
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1825
{
1826
    return len;
1827
}
1828

    
1829
static CharDriverState *qemu_chr_open_null(void)
1830
{
1831
    CharDriverState *chr;
1832

    
1833
    chr = qemu_mallocz(sizeof(CharDriverState));
1834
    if (!chr)
1835
        return NULL;
1836
    chr->chr_write = null_chr_write;
1837
    return chr;
1838
}
1839

    
1840
/* MUX driver for serial I/O splitting */
1841
static int term_timestamps;
1842
static int64_t term_timestamps_start;
1843
#define MAX_MUX 4
1844
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
1845
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1846
typedef struct {
1847
    IOCanRWHandler *chr_can_read[MAX_MUX];
1848
    IOReadHandler *chr_read[MAX_MUX];
1849
    IOEventHandler *chr_event[MAX_MUX];
1850
    void *ext_opaque[MAX_MUX];
1851
    CharDriverState *drv;
1852
    unsigned char buffer[MUX_BUFFER_SIZE];
1853
    int prod;
1854
    int cons;
1855
    int mux_cnt;
1856
    int term_got_escape;
1857
    int max_size;
1858
} MuxDriver;
1859

    
1860

    
1861
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1862
{
1863
    MuxDriver *d = chr->opaque;
1864
    int ret;
1865
    if (!term_timestamps) {
1866
        ret = d->drv->chr_write(d->drv, buf, len);
1867
    } else {
1868
        int i;
1869

    
1870
        ret = 0;
1871
        for(i = 0; i < len; i++) {
1872
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1873
            if (buf[i] == '\n') {
1874
                char buf1[64];
1875
                int64_t ti;
1876
                int secs;
1877

    
1878
                ti = get_clock();
1879
                if (term_timestamps_start == -1)
1880
                    term_timestamps_start = ti;
1881
                ti -= term_timestamps_start;
1882
                secs = ti / 1000000000;
1883
                snprintf(buf1, sizeof(buf1),
1884
                         "[%02d:%02d:%02d.%03d] ",
1885
                         secs / 3600,
1886
                         (secs / 60) % 60,
1887
                         secs % 60,
1888
                         (int)((ti / 1000000) % 1000));
1889
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1890
            }
1891
        }
1892
    }
1893
    return ret;
1894
}
1895

    
1896
static char *mux_help[] = {
1897
    "% h    print this help\n\r",
1898
    "% x    exit emulator\n\r",
1899
    "% s    save disk data back to file (if -snapshot)\n\r",
1900
    "% t    toggle console timestamps\n\r"
1901
    "% b    send break (magic sysrq)\n\r",
1902
    "% c    switch between console and monitor\n\r",
1903
    "% %  sends %\n\r",
1904
    NULL
1905
};
1906

    
1907
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1908
static void mux_print_help(CharDriverState *chr)
1909
{
1910
    int i, j;
1911
    char ebuf[15] = "Escape-Char";
1912
    char cbuf[50] = "\n\r";
1913

    
1914
    if (term_escape_char > 0 && term_escape_char < 26) {
1915
        sprintf(cbuf,"\n\r");
1916
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1917
    } else {
1918
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1919
            term_escape_char);
1920
    }
1921
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1922
    for (i = 0; mux_help[i] != NULL; i++) {
1923
        for (j=0; mux_help[i][j] != '\0'; j++) {
1924
            if (mux_help[i][j] == '%')
1925
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1926
            else
1927
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1928
        }
1929
    }
1930
}
1931

    
1932
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1933
{
1934
    if (d->term_got_escape) {
1935
        d->term_got_escape = 0;
1936
        if (ch == term_escape_char)
1937
            goto send_char;
1938
        switch(ch) {
1939
        case '?':
1940
        case 'h':
1941
            mux_print_help(chr);
1942
            break;
1943
        case 'x':
1944
            {
1945
                 char *term =  "QEMU: Terminated\n\r";
1946
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1947
                 exit(0);
1948
                 break;
1949
            }
1950
        case 's':
1951
            {
1952
                int i;
1953
                for (i = 0; i < nb_drives; i++) {
1954
                        bdrv_commit(drives_table[i].bdrv);
1955
                }
1956
            }
1957
            break;
1958
        case 'b':
1959
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1960
            break;
1961
        case 'c':
1962
            /* Switch to the next registered device */
1963
            chr->focus++;
1964
            if (chr->focus >= d->mux_cnt)
1965
                chr->focus = 0;
1966
            break;
1967
       case 't':
1968
           term_timestamps = !term_timestamps;
1969
           term_timestamps_start = -1;
1970
           break;
1971
        }
1972
    } else if (ch == term_escape_char) {
1973
        d->term_got_escape = 1;
1974
    } else {
1975
    send_char:
1976
        return 1;
1977
    }
1978
    return 0;
1979
}
1980

    
1981
static void mux_chr_accept_input(CharDriverState *chr)
1982
{
1983
    int m = chr->focus;
1984
    MuxDriver *d = chr->opaque;
1985

    
1986
    while (d->prod != d->cons &&
1987
           d->chr_can_read[m] &&
1988
           d->chr_can_read[m](d->ext_opaque[m])) {
1989
        d->chr_read[m](d->ext_opaque[m],
1990
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1991
    }
1992
}
1993

    
1994
static int mux_chr_can_read(void *opaque)
1995
{
1996
    CharDriverState *chr = opaque;
1997
    MuxDriver *d = chr->opaque;
1998

    
1999
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2000
        return 1;
2001
    if (d->chr_can_read[chr->focus])
2002
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2003
    return 0;
2004
}
2005

    
2006
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2007
{
2008
    CharDriverState *chr = opaque;
2009
    MuxDriver *d = chr->opaque;
2010
    int m = chr->focus;
2011
    int i;
2012

    
2013
    mux_chr_accept_input (opaque);
2014

    
2015
    for(i = 0; i < size; i++)
2016
        if (mux_proc_byte(chr, d, buf[i])) {
2017
            if (d->prod == d->cons &&
2018
                d->chr_can_read[m] &&
2019
                d->chr_can_read[m](d->ext_opaque[m]))
2020
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2021
            else
2022
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2023
        }
2024
}
2025

    
2026
static void mux_chr_event(void *opaque, int event)
2027
{
2028
    CharDriverState *chr = opaque;
2029
    MuxDriver *d = chr->opaque;
2030
    int i;
2031

    
2032
    /* Send the event to all registered listeners */
2033
    for (i = 0; i < d->mux_cnt; i++)
2034
        if (d->chr_event[i])
2035
            d->chr_event[i](d->ext_opaque[i], event);
2036
}
2037

    
2038
static void mux_chr_update_read_handler(CharDriverState *chr)
2039
{
2040
    MuxDriver *d = chr->opaque;
2041

    
2042
    if (d->mux_cnt >= MAX_MUX) {
2043
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2044
        return;
2045
    }
2046
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2047
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2048
    d->chr_read[d->mux_cnt] = chr->chr_read;
2049
    d->chr_event[d->mux_cnt] = chr->chr_event;
2050
    /* Fix up the real driver with mux routines */
2051
    if (d->mux_cnt == 0) {
2052
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2053
                              mux_chr_event, chr);
2054
    }
2055
    chr->focus = d->mux_cnt;
2056
    d->mux_cnt++;
2057
}
2058

    
2059
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2060
{
2061
    CharDriverState *chr;
2062
    MuxDriver *d;
2063

    
2064
    chr = qemu_mallocz(sizeof(CharDriverState));
2065
    if (!chr)
2066
        return NULL;
2067
    d = qemu_mallocz(sizeof(MuxDriver));
2068
    if (!d) {
2069
        free(chr);
2070
        return NULL;
2071
    }
2072

    
2073
    chr->opaque = d;
2074
    d->drv = drv;
2075
    chr->focus = -1;
2076
    chr->chr_write = mux_chr_write;
2077
    chr->chr_update_read_handler = mux_chr_update_read_handler;
2078
    chr->chr_accept_input = mux_chr_accept_input;
2079
    return chr;
2080
}
2081

    
2082

    
2083
#ifdef _WIN32
2084

    
2085
static void socket_cleanup(void)
2086
{
2087
    WSACleanup();
2088
}
2089

    
2090
static int socket_init(void)
2091
{
2092
    WSADATA Data;
2093
    int ret, err;
2094

    
2095
    ret = WSAStartup(MAKEWORD(2,2), &Data);
2096
    if (ret != 0) {
2097
        err = WSAGetLastError();
2098
        fprintf(stderr, "WSAStartup: %d\n", err);
2099
        return -1;
2100
    }
2101
    atexit(socket_cleanup);
2102
    return 0;
2103
}
2104

    
2105
static int send_all(int fd, const uint8_t *buf, int len1)
2106
{
2107
    int ret, len;
2108

    
2109
    len = len1;
2110
    while (len > 0) {
2111
        ret = send(fd, buf, len, 0);
2112
        if (ret < 0) {
2113
            int errno;
2114
            errno = WSAGetLastError();
2115
            if (errno != WSAEWOULDBLOCK) {
2116
                return -1;
2117
            }
2118
        } else if (ret == 0) {
2119
            break;
2120
        } else {
2121
            buf += ret;
2122
            len -= ret;
2123
        }
2124
    }
2125
    return len1 - len;
2126
}
2127

    
2128
void socket_set_nonblock(int fd)
2129
{
2130
    unsigned long opt = 1;
2131
    ioctlsocket(fd, FIONBIO, &opt);
2132
}
2133

    
2134
#else
2135

    
2136
static int unix_write(int fd, const uint8_t *buf, int len1)
2137
{
2138
    int ret, len;
2139

    
2140
    len = len1;
2141
    while (len > 0) {
2142
        ret = write(fd, buf, len);
2143
        if (ret < 0) {
2144
            if (errno != EINTR && errno != EAGAIN)
2145
                return -1;
2146
        } else if (ret == 0) {
2147
            break;
2148
        } else {
2149
            buf += ret;
2150
            len -= ret;
2151
        }
2152
    }
2153
    return len1 - len;
2154
}
2155

    
2156
static inline int send_all(int fd, const uint8_t *buf, int len1)
2157
{
2158
    return unix_write(fd, buf, len1);
2159
}
2160

    
2161
void socket_set_nonblock(int fd)
2162
{
2163
    int f;
2164
    f = fcntl(fd, F_GETFL);
2165
    fcntl(fd, F_SETFL, f | O_NONBLOCK);
2166
}
2167
#endif /* !_WIN32 */
2168

    
2169
#ifndef _WIN32
2170

    
2171
typedef struct {
2172
    int fd_in, fd_out;
2173
    int max_size;
2174
} FDCharDriver;
2175

    
2176
#define STDIO_MAX_CLIENTS 1
2177
static int stdio_nb_clients = 0;
2178

    
2179
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2180
{
2181
    FDCharDriver *s = chr->opaque;
2182
    return unix_write(s->fd_out, buf, len);
2183
}
2184

    
2185
static int fd_chr_read_poll(void *opaque)
2186
{
2187
    CharDriverState *chr = opaque;
2188
    FDCharDriver *s = chr->opaque;
2189

    
2190
    s->max_size = qemu_chr_can_read(chr);
2191
    return s->max_size;
2192
}
2193

    
2194
static void fd_chr_read(void *opaque)
2195
{
2196
    CharDriverState *chr = opaque;
2197
    FDCharDriver *s = chr->opaque;
2198
    int size, len;
2199
    uint8_t buf[1024];
2200

    
2201
    len = sizeof(buf);
2202
    if (len > s->max_size)
2203
        len = s->max_size;
2204
    if (len == 0)
2205
        return;
2206
    size = read(s->fd_in, buf, len);
2207
    if (size == 0) {
2208
        /* FD has been closed. Remove it from the active list.  */
2209
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2210
        return;
2211
    }
2212
    if (size > 0) {
2213
        qemu_chr_read(chr, buf, size);
2214
    }
2215
}
2216

    
2217
static void fd_chr_update_read_handler(CharDriverState *chr)
2218
{
2219
    FDCharDriver *s = chr->opaque;
2220

    
2221
    if (s->fd_in >= 0) {
2222
        if (nographic && s->fd_in == 0) {
2223
        } else {
2224
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2225
                                 fd_chr_read, NULL, chr);
2226
        }
2227
    }
2228
}
2229

    
2230
static void fd_chr_close(struct CharDriverState *chr)
2231
{
2232
    FDCharDriver *s = chr->opaque;
2233

    
2234
    if (s->fd_in >= 0) {
2235
        if (nographic && s->fd_in == 0) {
2236
        } else {
2237
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2238
        }
2239
    }
2240

    
2241
    qemu_free(s);
2242
}
2243

    
2244
/* open a character device to a unix fd */
2245
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2246
{
2247
    CharDriverState *chr;
2248
    FDCharDriver *s;
2249

    
2250
    chr = qemu_mallocz(sizeof(CharDriverState));
2251
    if (!chr)
2252
        return NULL;
2253
    s = qemu_mallocz(sizeof(FDCharDriver));
2254
    if (!s) {
2255
        free(chr);
2256
        return NULL;
2257
    }
2258
    s->fd_in = fd_in;
2259
    s->fd_out = fd_out;
2260
    chr->opaque = s;
2261
    chr->chr_write = fd_chr_write;
2262
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2263
    chr->chr_close = fd_chr_close;
2264

    
2265
    qemu_chr_reset(chr);
2266

    
2267
    return chr;
2268
}
2269

    
2270
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2271
{
2272
    int fd_out;
2273

    
2274
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2275
    if (fd_out < 0)
2276
        return NULL;
2277
    return qemu_chr_open_fd(-1, fd_out);
2278
}
2279

    
2280
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2281
{
2282
    int fd_in, fd_out;
2283
    char filename_in[256], filename_out[256];
2284

    
2285
    snprintf(filename_in, 256, "%s.in", filename);
2286
    snprintf(filename_out, 256, "%s.out", filename);
2287
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2288
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2289
    if (fd_in < 0 || fd_out < 0) {
2290
        if (fd_in >= 0)
2291
            close(fd_in);
2292
        if (fd_out >= 0)
2293
            close(fd_out);
2294
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2295
        if (fd_in < 0)
2296
            return NULL;
2297
    }
2298
    return qemu_chr_open_fd(fd_in, fd_out);
2299
}
2300

    
2301

    
2302
/* for STDIO, we handle the case where several clients use it
2303
   (nographic mode) */
2304

    
2305
#define TERM_FIFO_MAX_SIZE 1
2306

    
2307
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2308
static int term_fifo_size;
2309

    
2310
static int stdio_read_poll(void *opaque)
2311
{
2312
    CharDriverState *chr = opaque;
2313

    
2314
    /* try to flush the queue if needed */
2315
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2316
        qemu_chr_read(chr, term_fifo, 1);
2317
        term_fifo_size = 0;
2318
    }
2319
    /* see if we can absorb more chars */
2320
    if (term_fifo_size == 0)
2321
        return 1;
2322
    else
2323
        return 0;
2324
}
2325

    
2326
static void stdio_read(void *opaque)
2327
{
2328
    int size;
2329
    uint8_t buf[1];
2330
    CharDriverState *chr = opaque;
2331

    
2332
    size = read(0, buf, 1);
2333
    if (size == 0) {
2334
        /* stdin has been closed. Remove it from the active list.  */
2335
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2336
        return;
2337
    }
2338
    if (size > 0) {
2339
        if (qemu_chr_can_read(chr) > 0) {
2340
            qemu_chr_read(chr, buf, 1);
2341
        } else if (term_fifo_size == 0) {
2342
            term_fifo[term_fifo_size++] = buf[0];
2343
        }
2344
    }
2345
}
2346

    
2347
/* init terminal so that we can grab keys */
2348
static struct termios oldtty;
2349
static int old_fd0_flags;
2350
static int term_atexit_done;
2351

    
2352
static void term_exit(void)
2353
{
2354
    tcsetattr (0, TCSANOW, &oldtty);
2355
    fcntl(0, F_SETFL, old_fd0_flags);
2356
}
2357

    
2358
static void term_init(void)
2359
{
2360
    struct termios tty;
2361

    
2362
    tcgetattr (0, &tty);
2363
    oldtty = tty;
2364
    old_fd0_flags = fcntl(0, F_GETFL);
2365

    
2366
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2367
                          |INLCR|IGNCR|ICRNL|IXON);
2368
    tty.c_oflag |= OPOST;
2369
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2370
    /* if graphical mode, we allow Ctrl-C handling */
2371
    if (nographic)
2372
        tty.c_lflag &= ~ISIG;
2373
    tty.c_cflag &= ~(CSIZE|PARENB);
2374
    tty.c_cflag |= CS8;
2375
    tty.c_cc[VMIN] = 1;
2376
    tty.c_cc[VTIME] = 0;
2377

    
2378
    tcsetattr (0, TCSANOW, &tty);
2379

    
2380
    if (!term_atexit_done++)
2381
        atexit(term_exit);
2382

    
2383
    fcntl(0, F_SETFL, O_NONBLOCK);
2384
}
2385

    
2386
static void qemu_chr_close_stdio(struct CharDriverState *chr)
2387
{
2388
    term_exit();
2389
    stdio_nb_clients--;
2390
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2391
    fd_chr_close(chr);
2392
}
2393

    
2394
static CharDriverState *qemu_chr_open_stdio(void)
2395
{
2396
    CharDriverState *chr;
2397

    
2398
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2399
        return NULL;
2400
    chr = qemu_chr_open_fd(0, 1);
2401
    chr->chr_close = qemu_chr_close_stdio;
2402
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2403
    stdio_nb_clients++;
2404
    term_init();
2405

    
2406
    return chr;
2407
}
2408

    
2409
#ifdef __sun__
2410
/* Once Solaris has openpty(), this is going to be removed. */
2411
int openpty(int *amaster, int *aslave, char *name,
2412
            struct termios *termp, struct winsize *winp)
2413
{
2414
        const char *slave;
2415
        int mfd = -1, sfd = -1;
2416

    
2417
        *amaster = *aslave = -1;
2418

    
2419
        mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2420
        if (mfd < 0)
2421
                goto err;
2422

    
2423
        if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2424
                goto err;
2425

    
2426
        if ((slave = ptsname(mfd)) == NULL)
2427
                goto err;
2428

    
2429
        if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2430
                goto err;
2431

    
2432
        if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2433
            (termp != NULL && tcgetattr(sfd, termp) < 0))
2434
                goto err;
2435

    
2436
        if (amaster)
2437
                *amaster = mfd;
2438
        if (aslave)
2439
                *aslave = sfd;
2440
        if (winp)
2441
                ioctl(sfd, TIOCSWINSZ, winp);
2442

    
2443
        return 0;
2444

    
2445
err:
2446
        if (sfd != -1)
2447
                close(sfd);
2448
        close(mfd);
2449
        return -1;
2450
}
2451

    
2452
void cfmakeraw (struct termios *termios_p)
2453
{
2454
        termios_p->c_iflag &=
2455
                ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2456
        termios_p->c_oflag &= ~OPOST;
2457
        termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2458
        termios_p->c_cflag &= ~(CSIZE|PARENB);
2459
        termios_p->c_cflag |= CS8;
2460

    
2461
        termios_p->c_cc[VMIN] = 0;
2462
        termios_p->c_cc[VTIME] = 0;
2463
}
2464
#endif
2465

    
2466
#if defined(__linux__) || defined(__sun__)
2467

    
2468
typedef struct {
2469
    int fd;
2470
    int connected;
2471
    int polling;
2472
    int read_bytes;
2473
    QEMUTimer *timer;
2474
} PtyCharDriver;
2475

    
2476
static void pty_chr_update_read_handler(CharDriverState *chr);
2477
static void pty_chr_state(CharDriverState *chr, int connected);
2478

    
2479
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2480
{
2481
    PtyCharDriver *s = chr->opaque;
2482

    
2483
    if (!s->connected) {
2484
        /* guest sends data, check for (re-)connect */
2485
        pty_chr_update_read_handler(chr);
2486
        return 0;
2487
    }
2488
    return unix_write(s->fd, buf, len);
2489
}
2490

    
2491
static int pty_chr_read_poll(void *opaque)
2492
{
2493
    CharDriverState *chr = opaque;
2494
    PtyCharDriver *s = chr->opaque;
2495

    
2496
    s->read_bytes = qemu_chr_can_read(chr);
2497
    return s->read_bytes;
2498
}
2499

    
2500
static void pty_chr_read(void *opaque)
2501
{
2502
    CharDriverState *chr = opaque;
2503
    PtyCharDriver *s = chr->opaque;
2504
    int size, len;
2505
    uint8_t buf[1024];
2506

    
2507
    len = sizeof(buf);
2508
    if (len > s->read_bytes)
2509
        len = s->read_bytes;
2510
    if (len == 0)
2511
        return;
2512
    size = read(s->fd, buf, len);
2513
    if ((size == -1 && errno == EIO) ||
2514
        (size == 0)) {
2515
        pty_chr_state(chr, 0);
2516
        return;
2517
    }
2518
    if (size > 0) {
2519
        pty_chr_state(chr, 1);
2520
        qemu_chr_read(chr, buf, size);
2521
    }
2522
}
2523

    
2524
static void pty_chr_update_read_handler(CharDriverState *chr)
2525
{
2526
    PtyCharDriver *s = chr->opaque;
2527

    
2528
    qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2529
                         pty_chr_read, NULL, chr);
2530
    s->polling = 1;
2531
    /*
2532
     * Short timeout here: just need wait long enougth that qemu makes
2533
     * it through the poll loop once.  When reconnected we want a
2534
     * short timeout so we notice it almost instantly.  Otherwise
2535
     * read() gives us -EIO instantly, making pty_chr_state() reset the
2536
     * timeout to the normal (much longer) poll interval before the
2537
     * timer triggers.
2538
     */
2539
    qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2540
}
2541

    
2542
static void pty_chr_state(CharDriverState *chr, int connected)
2543
{
2544
    PtyCharDriver *s = chr->opaque;
2545

    
2546
    if (!connected) {
2547
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2548
        s->connected = 0;
2549
        s->polling = 0;
2550
        /* (re-)connect poll interval for idle guests: once per second.
2551
         * We check more frequently in case the guests sends data to
2552
         * the virtual device linked to our pty. */
2553
        qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2554
    } else {
2555
        if (!s->connected)
2556
            qemu_chr_reset(chr);
2557
        s->connected = 1;
2558
    }
2559
}
2560

    
2561
void pty_chr_timer(void *opaque)
2562
{
2563
    struct CharDriverState *chr = opaque;
2564
    PtyCharDriver *s = chr->opaque;
2565

    
2566
    if (s->connected)
2567
        return;
2568
    if (s->polling) {
2569
        /* If we arrive here without polling being cleared due
2570
         * read returning -EIO, then we are (re-)connected */
2571
        pty_chr_state(chr, 1);
2572
        return;
2573
    }
2574

    
2575
    /* Next poll ... */
2576
    pty_chr_update_read_handler(chr);
2577
}
2578

    
2579
static void pty_chr_close(struct CharDriverState *chr)
2580
{
2581
    PtyCharDriver *s = chr->opaque;
2582

    
2583
    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2584
    close(s->fd);
2585
    qemu_free(s);
2586
}
2587

    
2588
static CharDriverState *qemu_chr_open_pty(void)
2589
{
2590
    CharDriverState *chr;
2591
    PtyCharDriver *s;
2592
    struct termios tty;
2593
    int slave_fd;
2594

    
2595
    chr = qemu_mallocz(sizeof(CharDriverState));
2596
    if (!chr)
2597
        return NULL;
2598
    s = qemu_mallocz(sizeof(PtyCharDriver));
2599
    if (!s) {
2600
        qemu_free(chr);
2601
        return NULL;
2602
    }
2603

    
2604
    if (openpty(&s->fd, &slave_fd, NULL, NULL, NULL) < 0) {
2605
        return NULL;
2606
    }
2607

    
2608
    /* Set raw attributes on the pty. */
2609
    cfmakeraw(&tty);
2610
    tcsetattr(slave_fd, TCSAFLUSH, &tty);
2611
    close(slave_fd);
2612

    
2613
    fprintf(stderr, "char device redirected to %s\n", ptsname(s->fd));
2614

    
2615
    chr->opaque = s;
2616
    chr->chr_write = pty_chr_write;
2617
    chr->chr_update_read_handler = pty_chr_update_read_handler;
2618
    chr->chr_close = pty_chr_close;
2619

    
2620
    s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2621

    
2622
    return chr;
2623
}
2624

    
2625
static void tty_serial_init(int fd, int speed,
2626
                            int parity, int data_bits, int stop_bits)
2627
{
2628
    struct termios tty;
2629
    speed_t spd;
2630

    
2631
#if 0
2632
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2633
           speed, parity, data_bits, stop_bits);
2634
#endif
2635
    tcgetattr (fd, &tty);
2636

    
2637
#define MARGIN 1.1
2638
    if (speed <= 50 * MARGIN)
2639
        spd = B50;
2640
    else if (speed <= 75 * MARGIN)
2641
        spd = B75;
2642
    else if (speed <= 300 * MARGIN)
2643
        spd = B300;
2644
    else if (speed <= 600 * MARGIN)
2645
        spd = B600;
2646
    else if (speed <= 1200 * MARGIN)
2647
        spd = B1200;
2648
    else if (speed <= 2400 * MARGIN)
2649
        spd = B2400;
2650
    else if (speed <= 4800 * MARGIN)
2651
        spd = B4800;
2652
    else if (speed <= 9600 * MARGIN)
2653
        spd = B9600;
2654
    else if (speed <= 19200 * MARGIN)
2655
        spd = B19200;
2656
    else if (speed <= 38400 * MARGIN)
2657
        spd = B38400;
2658
    else if (speed <= 57600 * MARGIN)
2659
        spd = B57600;
2660
    else if (speed <= 115200 * MARGIN)
2661
        spd = B115200;
2662
    else
2663
        spd = B115200;
2664

    
2665
    cfsetispeed(&tty, spd);
2666
    cfsetospeed(&tty, spd);
2667

    
2668
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2669
                          |INLCR|IGNCR|ICRNL|IXON);
2670
    tty.c_oflag |= OPOST;
2671
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2672
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2673
    switch(data_bits) {
2674
    default:
2675
    case 8:
2676
        tty.c_cflag |= CS8;
2677
        break;
2678
    case 7:
2679
        tty.c_cflag |= CS7;
2680
        break;
2681
    case 6:
2682
        tty.c_cflag |= CS6;
2683
        break;
2684
    case 5:
2685
        tty.c_cflag |= CS5;
2686
        break;
2687
    }
2688
    switch(parity) {
2689
    default:
2690
    case 'N':
2691
        break;
2692
    case 'E':
2693
        tty.c_cflag |= PARENB;
2694
        break;
2695
    case 'O':
2696
        tty.c_cflag |= PARENB | PARODD;
2697
        break;
2698
    }
2699
    if (stop_bits == 2)
2700
        tty.c_cflag |= CSTOPB;
2701

    
2702
    tcsetattr (fd, TCSANOW, &tty);
2703
}
2704

    
2705
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2706
{
2707
    FDCharDriver *s = chr->opaque;
2708

    
2709
    switch(cmd) {
2710
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2711
        {
2712
            QEMUSerialSetParams *ssp = arg;
2713
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2714
                            ssp->data_bits, ssp->stop_bits);
2715
        }
2716
        break;
2717
    case CHR_IOCTL_SERIAL_SET_BREAK:
2718
        {
2719
            int enable = *(int *)arg;
2720
            if (enable)
2721
                tcsendbreak(s->fd_in, 1);
2722
        }
2723
        break;
2724
    case CHR_IOCTL_SERIAL_GET_TIOCM:
2725
        {
2726
            int sarg = 0;
2727
            int *targ = (int *)arg;
2728
            ioctl(s->fd_in, TIOCMGET, &sarg);
2729
            *targ = 0;
2730
            if (sarg | TIOCM_CTS)
2731
                *targ |= CHR_TIOCM_CTS;
2732
            if (sarg | TIOCM_CAR)
2733
                *targ |= CHR_TIOCM_CAR;
2734
            if (sarg | TIOCM_DSR)
2735
                *targ |= CHR_TIOCM_DSR;
2736
            if (sarg | TIOCM_RI)
2737
                *targ |= CHR_TIOCM_RI;
2738
            if (sarg | TIOCM_DTR)
2739
                *targ |= CHR_TIOCM_DTR;
2740
            if (sarg | TIOCM_RTS)
2741
                *targ |= CHR_TIOCM_RTS;
2742
        }
2743
        break;
2744
    case CHR_IOCTL_SERIAL_SET_TIOCM:
2745
        {
2746
            int sarg = *(int *)arg;
2747
            int targ = 0;
2748
            if (sarg | CHR_TIOCM_DTR)
2749
                targ |= TIOCM_DTR;
2750
            if (sarg | CHR_TIOCM_RTS)
2751
                targ |= TIOCM_RTS;
2752
            ioctl(s->fd_in, TIOCMSET, &targ);
2753
        }
2754
        break;
2755
    default:
2756
        return -ENOTSUP;
2757
    }
2758
    return 0;
2759
}
2760

    
2761
static CharDriverState *qemu_chr_open_tty(const char *filename)
2762
{
2763
    CharDriverState *chr;
2764
    int fd;
2765

    
2766
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2767
    tty_serial_init(fd, 115200, 'N', 8, 1);
2768
    chr = qemu_chr_open_fd(fd, fd);
2769
    if (!chr) {
2770
        close(fd);
2771
        return NULL;
2772
    }
2773
    chr->chr_ioctl = tty_serial_ioctl;
2774
    qemu_chr_reset(chr);
2775
    return chr;
2776
}
2777
#else  /* ! __linux__ && ! __sun__ */
2778
static CharDriverState *qemu_chr_open_pty(void)
2779
{
2780
    return NULL;
2781
}
2782
#endif /* __linux__ || __sun__ */
2783

    
2784
#if defined(__linux__)
2785
typedef struct {
2786
    int fd;
2787
    int mode;
2788
} ParallelCharDriver;
2789

    
2790
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2791
{
2792
    if (s->mode != mode) {
2793
        int m = mode;
2794
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2795
            return 0;
2796
        s->mode = mode;
2797
    }
2798
    return 1;
2799
}
2800

    
2801
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2802
{
2803
    ParallelCharDriver *drv = chr->opaque;
2804
    int fd = drv->fd;
2805
    uint8_t b;
2806

    
2807
    switch(cmd) {
2808
    case CHR_IOCTL_PP_READ_DATA:
2809
        if (ioctl(fd, PPRDATA, &b) < 0)
2810
            return -ENOTSUP;
2811
        *(uint8_t *)arg = b;
2812
        break;
2813
    case CHR_IOCTL_PP_WRITE_DATA:
2814
        b = *(uint8_t *)arg;
2815
        if (ioctl(fd, PPWDATA, &b) < 0)
2816
            return -ENOTSUP;
2817
        break;
2818
    case CHR_IOCTL_PP_READ_CONTROL:
2819
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2820
            return -ENOTSUP;
2821
        /* Linux gives only the lowest bits, and no way to know data
2822
           direction! For better compatibility set the fixed upper
2823
           bits. */
2824
        *(uint8_t *)arg = b | 0xc0;
2825
        break;
2826
    case CHR_IOCTL_PP_WRITE_CONTROL:
2827
        b = *(uint8_t *)arg;
2828
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2829
            return -ENOTSUP;
2830
        break;
2831
    case CHR_IOCTL_PP_READ_STATUS:
2832
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2833
            return -ENOTSUP;
2834
        *(uint8_t *)arg = b;
2835
        break;
2836
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2837
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2838
            struct ParallelIOArg *parg = arg;
2839
            int n = read(fd, parg->buffer, parg->count);
2840
            if (n != parg->count) {
2841
                return -EIO;
2842
            }
2843
        }
2844
        break;
2845
    case CHR_IOCTL_PP_EPP_READ:
2846
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2847
            struct ParallelIOArg *parg = arg;
2848
            int n = read(fd, parg->buffer, parg->count);
2849
            if (n != parg->count) {
2850
                return -EIO;
2851
            }
2852
        }
2853
        break;
2854
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2855
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2856
            struct ParallelIOArg *parg = arg;
2857
            int n = write(fd, parg->buffer, parg->count);
2858
            if (n != parg->count) {
2859
                return -EIO;
2860
            }
2861
        }
2862
        break;
2863
    case CHR_IOCTL_PP_EPP_WRITE:
2864
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2865
            struct ParallelIOArg *parg = arg;
2866
            int n = write(fd, parg->buffer, parg->count);
2867
            if (n != parg->count) {
2868
                return -EIO;
2869
            }
2870
        }
2871
        break;
2872
    default:
2873
        return -ENOTSUP;
2874
    }
2875
    return 0;
2876
}
2877

    
2878
static void pp_close(CharDriverState *chr)
2879
{
2880
    ParallelCharDriver *drv = chr->opaque;
2881
    int fd = drv->fd;
2882

    
2883
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2884
    ioctl(fd, PPRELEASE);
2885
    close(fd);
2886
    qemu_free(drv);
2887
}
2888

    
2889
static CharDriverState *qemu_chr_open_pp(const char *filename)
2890
{
2891
    CharDriverState *chr;
2892
    ParallelCharDriver *drv;
2893
    int fd;
2894

    
2895
    TFR(fd = open(filename, O_RDWR));
2896
    if (fd < 0)
2897
        return NULL;
2898

    
2899
    if (ioctl(fd, PPCLAIM) < 0) {
2900
        close(fd);
2901
        return NULL;
2902
    }
2903

    
2904
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2905
    if (!drv) {
2906
        close(fd);
2907
        return NULL;
2908
    }
2909
    drv->fd = fd;
2910
    drv->mode = IEEE1284_MODE_COMPAT;
2911

    
2912
    chr = qemu_mallocz(sizeof(CharDriverState));
2913
    if (!chr) {
2914
        qemu_free(drv);
2915
        close(fd);
2916
        return NULL;
2917
    }
2918
    chr->chr_write = null_chr_write;
2919
    chr->chr_ioctl = pp_ioctl;
2920
    chr->chr_close = pp_close;
2921
    chr->opaque = drv;
2922

    
2923
    qemu_chr_reset(chr);
2924

    
2925
    return chr;
2926
}
2927
#endif /* __linux__ */
2928

    
2929
#else /* _WIN32 */
2930

    
2931
typedef struct {
2932
    int max_size;
2933
    HANDLE hcom, hrecv, hsend;
2934
    OVERLAPPED orecv, osend;
2935
    BOOL fpipe;
2936
    DWORD len;
2937
} WinCharState;
2938

    
2939
#define NSENDBUF 2048
2940
#define NRECVBUF 2048
2941
#define MAXCONNECT 1
2942
#define NTIMEOUT 5000
2943

    
2944
static int win_chr_poll(void *opaque);
2945
static int win_chr_pipe_poll(void *opaque);
2946

    
2947
static void win_chr_close(CharDriverState *chr)
2948
{
2949
    WinCharState *s = chr->opaque;
2950

    
2951
    if (s->hsend) {
2952
        CloseHandle(s->hsend);
2953
        s->hsend = NULL;
2954
    }
2955
    if (s->hrecv) {
2956
        CloseHandle(s->hrecv);
2957
        s->hrecv = NULL;
2958
    }
2959
    if (s->hcom) {
2960
        CloseHandle(s->hcom);
2961
        s->hcom = NULL;
2962
    }
2963
    if (s->fpipe)
2964
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2965
    else
2966
        qemu_del_polling_cb(win_chr_poll, chr);
2967
}
2968

    
2969
static int win_chr_init(CharDriverState *chr, const char *filename)
2970
{
2971
    WinCharState *s = chr->opaque;
2972
    COMMCONFIG comcfg;
2973
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2974
    COMSTAT comstat;
2975
    DWORD size;
2976
    DWORD err;
2977

    
2978
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2979
    if (!s->hsend) {
2980
        fprintf(stderr, "Failed CreateEvent\n");
2981
        goto fail;
2982
    }
2983
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2984
    if (!s->hrecv) {
2985
        fprintf(stderr, "Failed CreateEvent\n");
2986
        goto fail;
2987
    }
2988

    
2989
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2990
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2991
    if (s->hcom == INVALID_HANDLE_VALUE) {
2992
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2993
        s->hcom = NULL;
2994
        goto fail;
2995
    }
2996

    
2997
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2998
        fprintf(stderr, "Failed SetupComm\n");
2999
        goto fail;
3000
    }
3001

    
3002
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3003
    size = sizeof(COMMCONFIG);
3004
    GetDefaultCommConfig(filename, &comcfg, &size);
3005
    comcfg.dcb.DCBlength = sizeof(DCB);
3006
    CommConfigDialog(filename, NULL, &comcfg);
3007

    
3008
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
3009
        fprintf(stderr, "Failed SetCommState\n");
3010
        goto fail;
3011
    }
3012

    
3013
    if (!SetCommMask(s->hcom, EV_ERR)) {
3014
        fprintf(stderr, "Failed SetCommMask\n");
3015
        goto fail;
3016
    }
3017

    
3018
    cto.ReadIntervalTimeout = MAXDWORD;
3019
    if (!SetCommTimeouts(s->hcom, &cto)) {
3020
        fprintf(stderr, "Failed SetCommTimeouts\n");
3021
        goto fail;
3022
    }
3023

    
3024
    if (!ClearCommError(s->hcom, &err, &comstat)) {
3025
        fprintf(stderr, "Failed ClearCommError\n");
3026
        goto fail;
3027
    }
3028
    qemu_add_polling_cb(win_chr_poll, chr);
3029
    return 0;
3030

    
3031
 fail:
3032
    win_chr_close(chr);
3033
    return -1;
3034
}
3035

    
3036
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3037
{
3038
    WinCharState *s = chr->opaque;
3039
    DWORD len, ret, size, err;
3040

    
3041
    len = len1;
3042
    ZeroMemory(&s->osend, sizeof(s->osend));
3043
    s->osend.hEvent = s->hsend;
3044
    while (len > 0) {
3045
        if (s->hsend)
3046
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3047
        else
3048
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
3049
        if (!ret) {
3050
            err = GetLastError();
3051
            if (err == ERROR_IO_PENDING) {
3052
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3053
                if (ret) {
3054
                    buf += size;
3055
                    len -= size;
3056
                } else {
3057
                    break;
3058
                }
3059
            } else {
3060
                break;
3061
            }
3062
        } else {
3063
            buf += size;
3064
            len -= size;
3065
        }
3066
    }
3067
    return len1 - len;
3068
}
3069

    
3070
static int win_chr_read_poll(CharDriverState *chr)
3071
{
3072
    WinCharState *s = chr->opaque;
3073

    
3074
    s->max_size = qemu_chr_can_read(chr);
3075
    return s->max_size;
3076
}
3077

    
3078
static void win_chr_readfile(CharDriverState *chr)
3079
{
3080
    WinCharState *s = chr->opaque;
3081
    int ret, err;
3082
    uint8_t buf[1024];
3083
    DWORD size;
3084

    
3085
    ZeroMemory(&s->orecv, sizeof(s->orecv));
3086
    s->orecv.hEvent = s->hrecv;
3087
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3088
    if (!ret) {
3089
        err = GetLastError();
3090
        if (err == ERROR_IO_PENDING) {
3091
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3092
        }
3093
    }
3094

    
3095
    if (size > 0) {
3096
        qemu_chr_read(chr, buf, size);
3097
    }
3098
}
3099

    
3100
static void win_chr_read(CharDriverState *chr)
3101
{
3102
    WinCharState *s = chr->opaque;
3103

    
3104
    if (s->len > s->max_size)
3105
        s->len = s->max_size;
3106
    if (s->len == 0)
3107
        return;
3108

    
3109
    win_chr_readfile(chr);
3110
}
3111

    
3112
static int win_chr_poll(void *opaque)
3113
{
3114
    CharDriverState *chr = opaque;
3115
    WinCharState *s = chr->opaque;
3116
    COMSTAT status;
3117
    DWORD comerr;
3118

    
3119
    ClearCommError(s->hcom, &comerr, &status);
3120
    if (status.cbInQue > 0) {
3121
        s->len = status.cbInQue;
3122
        win_chr_read_poll(chr);
3123
        win_chr_read(chr);
3124
        return 1;
3125
    }
3126
    return 0;
3127
}
3128

    
3129
static CharDriverState *qemu_chr_open_win(const char *filename)
3130
{
3131
    CharDriverState *chr;
3132
    WinCharState *s;
3133

    
3134
    chr = qemu_mallocz(sizeof(CharDriverState));
3135
    if (!chr)
3136
        return NULL;
3137
    s = qemu_mallocz(sizeof(WinCharState));
3138
    if (!s) {
3139
        free(chr);
3140
        return NULL;
3141
    }
3142
    chr->opaque = s;
3143
    chr->chr_write = win_chr_write;
3144
    chr->chr_close = win_chr_close;
3145

    
3146
    if (win_chr_init(chr, filename) < 0) {
3147
        free(s);
3148
        free(chr);
3149
        return NULL;
3150
    }
3151
    qemu_chr_reset(chr);
3152
    return chr;
3153
}
3154

    
3155
static int win_chr_pipe_poll(void *opaque)
3156
{
3157
    CharDriverState *chr = opaque;
3158
    WinCharState *s = chr->opaque;
3159
    DWORD size;
3160

    
3161
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3162
    if (size > 0) {
3163
        s->len = size;
3164
        win_chr_read_poll(chr);
3165
        win_chr_read(chr);
3166
        return 1;
3167
    }
3168
    return 0;
3169
}
3170

    
3171
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3172
{
3173
    WinCharState *s = chr->opaque;
3174
    OVERLAPPED ov;
3175
    int ret;
3176
    DWORD size;
3177
    char openname[256];
3178

    
3179
    s->fpipe = TRUE;
3180

    
3181
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3182
    if (!s->hsend) {
3183
        fprintf(stderr, "Failed CreateEvent\n");
3184
        goto fail;
3185
    }
3186
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3187
    if (!s->hrecv) {
3188
        fprintf(stderr, "Failed CreateEvent\n");
3189
        goto fail;
3190
    }
3191

    
3192
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3193
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3194
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3195
                              PIPE_WAIT,
3196
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3197
    if (s->hcom == INVALID_HANDLE_VALUE) {
3198
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3199
        s->hcom = NULL;
3200
        goto fail;
3201
    }
3202

    
3203
    ZeroMemory(&ov, sizeof(ov));
3204
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3205
    ret = ConnectNamedPipe(s->hcom, &ov);
3206
    if (ret) {
3207
        fprintf(stderr, "Failed ConnectNamedPipe\n");
3208
        goto fail;
3209
    }
3210

    
3211
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3212
    if (!ret) {
3213
        fprintf(stderr, "Failed GetOverlappedResult\n");
3214
        if (ov.hEvent) {
3215
            CloseHandle(ov.hEvent);
3216
            ov.hEvent = NULL;
3217
        }
3218
        goto fail;
3219
    }
3220

    
3221
    if (ov.hEvent) {
3222
        CloseHandle(ov.hEvent);
3223
        ov.hEvent = NULL;
3224
    }
3225
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
3226
    return 0;
3227

    
3228
 fail:
3229
    win_chr_close(chr);
3230
    return -1;
3231
}
3232

    
3233

    
3234
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3235
{
3236
    CharDriverState *chr;
3237
    WinCharState *s;
3238

    
3239
    chr = qemu_mallocz(sizeof(CharDriverState));
3240
    if (!chr)
3241
        return NULL;
3242
    s = qemu_mallocz(sizeof(WinCharState));
3243
    if (!s) {
3244
        free(chr);
3245
        return NULL;
3246
    }
3247
    chr->opaque = s;
3248
    chr->chr_write = win_chr_write;
3249
    chr->chr_close = win_chr_close;
3250

    
3251
    if (win_chr_pipe_init(chr, filename) < 0) {
3252
        free(s);
3253
        free(chr);
3254
        return NULL;
3255
    }
3256
    qemu_chr_reset(chr);
3257
    return chr;
3258
}
3259

    
3260
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3261
{
3262
    CharDriverState *chr;
3263
    WinCharState *s;
3264

    
3265
    chr = qemu_mallocz(sizeof(CharDriverState));
3266
    if (!chr)
3267
        return NULL;
3268
    s = qemu_mallocz(sizeof(WinCharState));
3269
    if (!s) {
3270
        free(chr);
3271
        return NULL;
3272
    }
3273
    s->hcom = fd_out;
3274
    chr->opaque = s;
3275
    chr->chr_write = win_chr_write;
3276
    qemu_chr_reset(chr);
3277
    return chr;
3278
}
3279

    
3280
static CharDriverState *qemu_chr_open_win_con(const char *filename)
3281
{
3282
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3283
}
3284

    
3285
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3286
{
3287
    HANDLE fd_out;
3288

    
3289
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3290
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3291
    if (fd_out == INVALID_HANDLE_VALUE)
3292
        return NULL;
3293

    
3294
    return qemu_chr_open_win_file(fd_out);
3295
}
3296
#endif /* !_WIN32 */
3297

    
3298
/***********************************************************/
3299
/* UDP Net console */
3300

    
3301
typedef struct {
3302
    int fd;
3303
    struct sockaddr_in daddr;
3304
    uint8_t buf[1024];
3305
    int bufcnt;
3306
    int bufptr;
3307
    int max_size;
3308
} NetCharDriver;
3309

    
3310
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3311
{
3312
    NetCharDriver *s = chr->opaque;
3313

    
3314
    return sendto(s->fd, buf, len, 0,
3315
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3316
}
3317

    
3318
static int udp_chr_read_poll(void *opaque)
3319
{
3320
    CharDriverState *chr = opaque;
3321
    NetCharDriver *s = chr->opaque;
3322

    
3323
    s->max_size = qemu_chr_can_read(chr);
3324

    
3325
    /* If there were any stray characters in the queue process them
3326
     * first
3327
     */
3328
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3329
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3330
        s->bufptr++;
3331
        s->max_size = qemu_chr_can_read(chr);
3332
    }
3333
    return s->max_size;
3334
}
3335

    
3336
static void udp_chr_read(void *opaque)
3337
{
3338
    CharDriverState *chr = opaque;
3339
    NetCharDriver *s = chr->opaque;
3340

    
3341
    if (s->max_size == 0)
3342
        return;
3343
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3344
    s->bufptr = s->bufcnt;
3345
    if (s->bufcnt <= 0)
3346
        return;
3347

    
3348
    s->bufptr = 0;
3349
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3350
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3351
        s->bufptr++;
3352
        s->max_size = qemu_chr_can_read(chr);
3353
    }
3354
}
3355

    
3356
static void udp_chr_update_read_handler(CharDriverState *chr)
3357
{
3358
    NetCharDriver *s = chr->opaque;
3359

    
3360
    if (s->fd >= 0) {
3361
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3362
                             udp_chr_read, NULL, chr);
3363
    }
3364
}
3365

    
3366
int parse_host_port(struct sockaddr_in *saddr, const char *str);
3367
#ifndef _WIN32
3368
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3369
#endif
3370
int parse_host_src_port(struct sockaddr_in *haddr,
3371
                        struct sockaddr_in *saddr,
3372
                        const char *str);
3373

    
3374
static CharDriverState *qemu_chr_open_udp(const char *def)
3375
{
3376
    CharDriverState *chr = NULL;
3377
    NetCharDriver *s = NULL;
3378
    int fd = -1;
3379
    struct sockaddr_in saddr;
3380

    
3381
    chr = qemu_mallocz(sizeof(CharDriverState));
3382
    if (!chr)
3383
        goto return_err;
3384
    s = qemu_mallocz(sizeof(NetCharDriver));
3385
    if (!s)
3386
        goto return_err;
3387

    
3388
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3389
    if (fd < 0) {
3390
        perror("socket(PF_INET, SOCK_DGRAM)");
3391
        goto return_err;
3392
    }
3393

    
3394
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3395
        printf("Could not parse: %s\n", def);
3396
        goto return_err;
3397
    }
3398

    
3399
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3400
    {
3401
        perror("bind");
3402
        goto return_err;
3403
    }
3404

    
3405
    s->fd = fd;
3406
    s->bufcnt = 0;
3407
    s->bufptr = 0;
3408
    chr->opaque = s;
3409
    chr->chr_write = udp_chr_write;
3410
    chr->chr_update_read_handler = udp_chr_update_read_handler;
3411
    return chr;
3412

    
3413
return_err:
3414
    if (chr)
3415
        free(chr);
3416
    if (s)
3417
        free(s);
3418
    if (fd >= 0)
3419
        closesocket(fd);
3420
    return NULL;
3421
}
3422

    
3423
/***********************************************************/
3424
/* TCP Net console */
3425

    
3426
typedef struct {
3427
    int fd, listen_fd;
3428
    int connected;
3429
    int max_size;
3430
    int do_telnetopt;
3431
    int do_nodelay;
3432
    int is_unix;
3433
} TCPCharDriver;
3434

    
3435
static void tcp_chr_accept(void *opaque);
3436

    
3437
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3438
{
3439
    TCPCharDriver *s = chr->opaque;
3440
    if (s->connected) {
3441
        return send_all(s->fd, buf, len);
3442
    } else {
3443
        /* XXX: indicate an error ? */
3444
        return len;
3445
    }
3446
}
3447

    
3448
static int tcp_chr_read_poll(void *opaque)
3449
{
3450
    CharDriverState *chr = opaque;
3451
    TCPCharDriver *s = chr->opaque;
3452
    if (!s->connected)
3453
        return 0;
3454
    s->max_size = qemu_chr_can_read(chr);
3455
    return s->max_size;
3456
}
3457

    
3458
#define IAC 255
3459
#define IAC_BREAK 243
3460
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3461
                                      TCPCharDriver *s,
3462
                                      uint8_t *buf, int *size)
3463
{
3464
    /* Handle any telnet client's basic IAC options to satisfy char by
3465
     * char mode with no echo.  All IAC options will be removed from
3466
     * the buf and the do_telnetopt variable will be used to track the
3467
     * state of the width of the IAC information.
3468
     *
3469
     * IAC commands come in sets of 3 bytes with the exception of the
3470
     * "IAC BREAK" command and the double IAC.
3471
     */
3472

    
3473
    int i;
3474
    int j = 0;
3475

    
3476
    for (i = 0; i < *size; i++) {
3477
        if (s->do_telnetopt > 1) {
3478
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3479
                /* Double IAC means send an IAC */
3480
                if (j != i)
3481
                    buf[j] = buf[i];
3482
                j++;
3483
                s->do_telnetopt = 1;
3484
            } else {
3485
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3486
                    /* Handle IAC break commands by sending a serial break */
3487
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3488
                    s->do_telnetopt++;
3489
                }
3490
                s->do_telnetopt++;
3491
            }
3492
            if (s->do_telnetopt >= 4) {
3493
                s->do_telnetopt = 1;
3494
            }
3495
        } else {
3496
            if ((unsigned char)buf[i] == IAC) {
3497
                s->do_telnetopt = 2;
3498
            } else {
3499
                if (j != i)
3500
                    buf[j] = buf[i];
3501
                j++;
3502
            }
3503
        }
3504
    }
3505
    *size = j;
3506
}
3507

    
3508
static void tcp_chr_read(void *opaque)
3509
{
3510
    CharDriverState *chr = opaque;
3511
    TCPCharDriver *s = chr->opaque;
3512
    uint8_t buf[1024];
3513
    int len, size;
3514

    
3515
    if (!s->connected || s->max_size <= 0)
3516
        return;
3517
    len = sizeof(buf);
3518
    if (len > s->max_size)
3519
        len = s->max_size;
3520
    size = recv(s->fd, buf, len, 0);
3521
    if (size == 0) {
3522
        /* connection closed */
3523
        s->connected = 0;
3524
        if (s->listen_fd >= 0) {
3525
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3526
        }
3527
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3528
        closesocket(s->fd);
3529
        s->fd = -1;
3530
    } else if (size > 0) {
3531
        if (s->do_telnetopt)
3532
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3533
        if (size > 0)
3534
            qemu_chr_read(chr, buf, size);
3535
    }
3536
}
3537

    
3538
static void tcp_chr_connect(void *opaque)
3539
{
3540
    CharDriverState *chr = opaque;
3541
    TCPCharDriver *s = chr->opaque;
3542

    
3543
    s->connected = 1;
3544
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3545
                         tcp_chr_read, NULL, chr);
3546
    qemu_chr_reset(chr);
3547
}
3548

    
3549
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3550
static void tcp_chr_telnet_init(int fd)
3551
{
3552
    char buf[3];
3553
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3554
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3555
    send(fd, (char *)buf, 3, 0);
3556
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3557
    send(fd, (char *)buf, 3, 0);
3558
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3559
    send(fd, (char *)buf, 3, 0);
3560
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3561
    send(fd, (char *)buf, 3, 0);
3562
}
3563

    
3564
static void socket_set_nodelay(int fd)
3565
{
3566
    int val = 1;
3567
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3568
}
3569

    
3570
static void tcp_chr_accept(void *opaque)
3571
{
3572
    CharDriverState *chr = opaque;
3573
    TCPCharDriver *s = chr->opaque;
3574
    struct sockaddr_in saddr;
3575
#ifndef _WIN32
3576
    struct sockaddr_un uaddr;
3577
#endif
3578
    struct sockaddr *addr;
3579
    socklen_t len;
3580
    int fd;
3581

    
3582
    for(;;) {
3583
#ifndef _WIN32
3584
        if (s->is_unix) {
3585
            len = sizeof(uaddr);
3586
            addr = (struct sockaddr *)&uaddr;
3587
        } else
3588
#endif
3589
        {
3590
            len = sizeof(saddr);
3591
            addr = (struct sockaddr *)&saddr;
3592
        }
3593
        fd = accept(s->listen_fd, addr, &len);
3594
        if (fd < 0 && errno != EINTR) {
3595
            return;
3596
        } else if (fd >= 0) {
3597
            if (s->do_telnetopt)
3598
                tcp_chr_telnet_init(fd);
3599
            break;
3600
        }
3601
    }
3602
    socket_set_nonblock(fd);
3603
    if (s->do_nodelay)
3604
        socket_set_nodelay(fd);
3605
    s->fd = fd;
3606
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3607
    tcp_chr_connect(chr);
3608
}
3609

    
3610
static void tcp_chr_close(CharDriverState *chr)
3611
{
3612
    TCPCharDriver *s = chr->opaque;
3613
    if (s->fd >= 0)
3614
        closesocket(s->fd);
3615
    if (s->listen_fd >= 0)
3616
        closesocket(s->listen_fd);
3617
    qemu_free(s);
3618
}
3619

    
3620
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3621
                                          int is_telnet,
3622
                                          int is_unix)
3623
{
3624
    CharDriverState *chr = NULL;
3625
    TCPCharDriver *s = NULL;
3626
    int fd = -1, ret, err, val;
3627
    int is_listen = 0;
3628
    int is_waitconnect = 1;
3629
    int do_nodelay = 0;
3630
    const char *ptr;
3631
    struct sockaddr_in saddr;
3632
#ifndef _WIN32
3633
    struct sockaddr_un uaddr;
3634
#endif
3635
    struct sockaddr *addr;
3636
    socklen_t addrlen;
3637

    
3638
#ifndef _WIN32
3639
    if (is_unix) {
3640
        addr = (struct sockaddr *)&uaddr;
3641
        addrlen = sizeof(uaddr);
3642
        if (parse_unix_path(&uaddr, host_str) < 0)
3643
            goto fail;
3644
    } else
3645
#endif
3646
    {
3647
        addr = (struct sockaddr *)&saddr;
3648
        addrlen = sizeof(saddr);
3649
        if (parse_host_port(&saddr, host_str) < 0)
3650
            goto fail;
3651
    }
3652

    
3653
    ptr = host_str;
3654
    while((ptr = strchr(ptr,','))) {
3655
        ptr++;
3656
        if (!strncmp(ptr,"server",6)) {
3657
            is_listen = 1;
3658
        } else if (!strncmp(ptr,"nowait",6)) {
3659
            is_waitconnect = 0;
3660
        } else if (!strncmp(ptr,"nodelay",6)) {
3661
            do_nodelay = 1;
3662
        } else {
3663
            printf("Unknown option: %s\n", ptr);
3664
            goto fail;
3665
        }
3666
    }
3667
    if (!is_listen)
3668
        is_waitconnect = 0;
3669

    
3670
    chr = qemu_mallocz(sizeof(CharDriverState));
3671
    if (!chr)
3672
        goto fail;
3673
    s = qemu_mallocz(sizeof(TCPCharDriver));
3674
    if (!s)
3675
        goto fail;
3676

    
3677
#ifndef _WIN32
3678
    if (is_unix)
3679
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3680
    else
3681
#endif
3682
        fd = socket(PF_INET, SOCK_STREAM, 0);
3683

    
3684
    if (fd < 0)
3685
        goto fail;
3686

    
3687
    if (!is_waitconnect)
3688
        socket_set_nonblock(fd);
3689

    
3690
    s->connected = 0;
3691
    s->fd = -1;
3692
    s->listen_fd = -1;
3693
    s->is_unix = is_unix;
3694
    s->do_nodelay = do_nodelay && !is_unix;
3695

    
3696
    chr->opaque = s;
3697
    chr->chr_write = tcp_chr_write;
3698
    chr->chr_close = tcp_chr_close;
3699

    
3700
    if (is_listen) {
3701
        /* allow fast reuse */
3702
#ifndef _WIN32
3703
        if (is_unix) {
3704
            char path[109];
3705
            pstrcpy(path, sizeof(path), uaddr.sun_path);
3706
            unlink(path);
3707
        } else
3708
#endif
3709
        {
3710
            val = 1;
3711
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3712
        }
3713

    
3714
        ret = bind(fd, addr, addrlen);
3715
        if (ret < 0)
3716
            goto fail;
3717

    
3718
        ret = listen(fd, 0);
3719
        if (ret < 0)
3720
            goto fail;
3721

    
3722
        s->listen_fd = fd;
3723
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3724
        if (is_telnet)
3725
            s->do_telnetopt = 1;
3726
    } else {
3727
        for(;;) {
3728
            ret = connect(fd, addr, addrlen);
3729
            if (ret < 0) {
3730
                err = socket_error();
3731
                if (err == EINTR || err == EWOULDBLOCK) {
3732
                } else if (err == EINPROGRESS) {
3733
                    break;
3734
#ifdef _WIN32
3735
                } else if (err == WSAEALREADY) {
3736
                    break;
3737
#endif
3738
                } else {
3739
                    goto fail;
3740
                }
3741
            } else {
3742
                s->connected = 1;
3743
                break;
3744
            }
3745
        }
3746
        s->fd = fd;
3747
        socket_set_nodelay(fd);
3748
        if (s->connected)
3749
            tcp_chr_connect(chr);
3750
        else
3751
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3752
    }
3753

    
3754
    if (is_listen && is_waitconnect) {
3755
        printf("QEMU waiting for connection on: %s\n", host_str);
3756
        tcp_chr_accept(chr);
3757
        socket_set_nonblock(s->listen_fd);
3758
    }
3759

    
3760
    return chr;
3761
 fail:
3762
    if (fd >= 0)
3763
        closesocket(fd);
3764
    qemu_free(s);
3765
    qemu_free(chr);
3766
    return NULL;
3767
}
3768

    
3769
CharDriverState *qemu_chr_open(const char *filename)
3770
{
3771
    const char *p;
3772

    
3773
    if (!strcmp(filename, "vc")) {
3774
        return text_console_init(&display_state, 0);
3775
    } else if (strstart(filename, "vc:", &p)) {
3776
        return text_console_init(&display_state, p);
3777
    } else if (!strcmp(filename, "null")) {
3778
        return qemu_chr_open_null();
3779
    } else
3780
    if (strstart(filename, "tcp:", &p)) {
3781
        return qemu_chr_open_tcp(p, 0, 0);
3782
    } else
3783
    if (strstart(filename, "telnet:", &p)) {
3784
        return qemu_chr_open_tcp(p, 1, 0);
3785
    } else
3786
    if (strstart(filename, "udp:", &p)) {
3787
        return qemu_chr_open_udp(p);
3788
    } else
3789
    if (strstart(filename, "mon:", &p)) {
3790
        CharDriverState *drv = qemu_chr_open(p);
3791
        if (drv) {
3792
            drv = qemu_chr_open_mux(drv);
3793
            monitor_init(drv, !nographic);
3794
            return drv;
3795
        }
3796
        printf("Unable to open driver: %s\n", p);
3797
        return 0;
3798
    } else
3799
#ifndef _WIN32
3800
    if (strstart(filename, "unix:", &p)) {
3801
        return qemu_chr_open_tcp(p, 0, 1);
3802
    } else if (strstart(filename, "file:", &p)) {
3803
        return qemu_chr_open_file_out(p);
3804
    } else if (strstart(filename, "pipe:", &p)) {
3805
        return qemu_chr_open_pipe(p);
3806
    } else if (!strcmp(filename, "pty")) {
3807
        return qemu_chr_open_pty();
3808
    } else if (!strcmp(filename, "stdio")) {
3809
        return qemu_chr_open_stdio();
3810
    } else
3811
#if defined(__linux__)
3812
    if (strstart(filename, "/dev/parport", NULL)) {
3813
        return qemu_chr_open_pp(filename);
3814
    } else
3815
#endif
3816
#if defined(__linux__) || defined(__sun__)
3817
    if (strstart(filename, "/dev/", NULL)) {
3818
        return qemu_chr_open_tty(filename);
3819
    } else
3820
#endif
3821
#else /* !_WIN32 */
3822
    if (strstart(filename, "COM", NULL)) {
3823
        return qemu_chr_open_win(filename);
3824
    } else
3825
    if (strstart(filename, "pipe:", &p)) {
3826
        return qemu_chr_open_win_pipe(p);
3827
    } else
3828
    if (strstart(filename, "con:", NULL)) {
3829
        return qemu_chr_open_win_con(filename);
3830
    } else
3831
    if (strstart(filename, "file:", &p)) {
3832
        return qemu_chr_open_win_file_out(p);
3833
    } else
3834
#endif
3835
#ifdef CONFIG_BRLAPI
3836
    if (!strcmp(filename, "braille")) {
3837
        return chr_baum_init();
3838
    } else
3839
#endif
3840
    {
3841
        return NULL;
3842
    }
3843
}
3844

    
3845
void qemu_chr_close(CharDriverState *chr)
3846
{
3847
    if (chr->chr_close)
3848
        chr->chr_close(chr);
3849
    qemu_free(chr);
3850
}
3851

    
3852
/***********************************************************/
3853
/* network device redirectors */
3854

    
3855
__attribute__ (( unused ))
3856
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3857
{
3858
    int len, i, j, c;
3859

    
3860
    for(i=0;i<size;i+=16) {
3861
        len = size - i;
3862
        if (len > 16)
3863
            len = 16;
3864
        fprintf(f, "%08x ", i);
3865
        for(j=0;j<16;j++) {
3866
            if (j < len)
3867
                fprintf(f, " %02x", buf[i+j]);
3868
            else
3869
                fprintf(f, "   ");
3870
        }
3871
        fprintf(f, " ");
3872
        for(j=0;j<len;j++) {
3873
            c = buf[i+j];
3874
            if (c < ' ' || c > '~')
3875
                c = '.';
3876
            fprintf(f, "%c", c);
3877
        }
3878
        fprintf(f, "\n");
3879
    }
3880
}
3881

    
3882
static int parse_macaddr(uint8_t *macaddr, const char *p)
3883
{
3884
    int i;
3885
    char *last_char;
3886
    long int offset;
3887

    
3888
    errno = 0;
3889
    offset = strtol(p, &last_char, 0);    
3890
    if (0 == errno && '\0' == *last_char &&
3891
            offset >= 0 && offset <= 0xFFFFFF) {
3892
        macaddr[3] = (offset & 0xFF0000) >> 16;
3893
        macaddr[4] = (offset & 0xFF00) >> 8;
3894
        macaddr[5] = offset & 0xFF;
3895
        return 0;
3896
    } else {
3897
        for(i = 0; i < 6; i++) {
3898
            macaddr[i] = strtol(p, (char **)&p, 16);
3899
            if (i == 5) {
3900
                if (*p != '\0')
3901
                    return -1;
3902
            } else {
3903
                if (*p != ':' && *p != '-')
3904
                    return -1;
3905
                p++;
3906
            }
3907
        }
3908
        return 0;    
3909
    }
3910

    
3911
    return -1;
3912
}
3913

    
3914
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3915
{
3916
    const char *p, *p1;
3917
    int len;
3918
    p = *pp;
3919
    p1 = strchr(p, sep);
3920
    if (!p1)
3921
        return -1;
3922
    len = p1 - p;
3923
    p1++;
3924
    if (buf_size > 0) {
3925
        if (len > buf_size - 1)
3926
            len = buf_size - 1;
3927
        memcpy(buf, p, len);
3928
        buf[len] = '\0';
3929
    }
3930
    *pp = p1;
3931
    return 0;
3932
}
3933

    
3934
int parse_host_src_port(struct sockaddr_in *haddr,
3935
                        struct sockaddr_in *saddr,
3936
                        const char *input_str)
3937
{
3938
    char *str = strdup(input_str);
3939
    char *host_str = str;
3940
    char *src_str;
3941
    char *ptr;
3942

    
3943
    /*
3944
     * Chop off any extra arguments at the end of the string which
3945
     * would start with a comma, then fill in the src port information
3946
     * if it was provided else use the "any address" and "any port".
3947
     */
3948
    if ((ptr = strchr(str,',')))
3949
        *ptr = '\0';
3950

    
3951
    if ((src_str = strchr(input_str,'@'))) {
3952
        *src_str = '\0';
3953
        src_str++;
3954
    }
3955

    
3956
    if (parse_host_port(haddr, host_str) < 0)
3957
        goto fail;
3958

    
3959
    if (!src_str || *src_str == '\0')
3960
        src_str = ":0";
3961

    
3962
    if (parse_host_port(saddr, src_str) < 0)
3963
        goto fail;
3964

    
3965
    free(str);
3966
    return(0);
3967

    
3968
fail:
3969
    free(str);
3970
    return -1;
3971
}
3972

    
3973
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3974
{
3975
    char buf[512];
3976
    struct hostent *he;
3977
    const char *p, *r;
3978
    int port;
3979

    
3980
    p = str;
3981
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3982
        return -1;
3983
    saddr->sin_family = AF_INET;
3984
    if (buf[0] == '\0') {
3985
        saddr->sin_addr.s_addr = 0;
3986
    } else {
3987
        if (isdigit(buf[0])) {
3988
            if (!inet_aton(buf, &saddr->sin_addr))
3989
                return -1;
3990
        } else {
3991
            if ((he = gethostbyname(buf)) == NULL)
3992
                return - 1;
3993
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3994
        }
3995
    }
3996
    port = strtol(p, (char **)&r, 0);
3997
    if (r == p)
3998
        return -1;
3999
    saddr->sin_port = htons(port);
4000
    return 0;
4001
}
4002

    
4003
#ifndef _WIN32
4004
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4005
{
4006
    const char *p;
4007
    int len;
4008

    
4009
    len = MIN(108, strlen(str));
4010
    p = strchr(str, ',');
4011
    if (p)
4012
        len = MIN(len, p - str);
4013

    
4014
    memset(uaddr, 0, sizeof(*uaddr));
4015

    
4016
    uaddr->sun_family = AF_UNIX;
4017
    memcpy(uaddr->sun_path, str, len);
4018

    
4019
    return 0;
4020
}
4021
#endif
4022

    
4023
/* find or alloc a new VLAN */
4024
VLANState *qemu_find_vlan(int id)
4025
{
4026
    VLANState **pvlan, *vlan;
4027
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4028
        if (vlan->id == id)
4029
            return vlan;
4030
    }
4031
    vlan = qemu_mallocz(sizeof(VLANState));
4032
    if (!vlan)
4033
        return NULL;
4034
    vlan->id = id;
4035
    vlan->next = NULL;
4036
    pvlan = &first_vlan;
4037
    while (*pvlan != NULL)
4038
        pvlan = &(*pvlan)->next;
4039
    *pvlan = vlan;
4040
    return vlan;
4041
}
4042

    
4043
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4044
                                      IOReadHandler *fd_read,
4045
                                      IOCanRWHandler *fd_can_read,
4046
                                      void *opaque)
4047
{
4048
    VLANClientState *vc, **pvc;
4049
    vc = qemu_mallocz(sizeof(VLANClientState));
4050
    if (!vc)
4051
        return NULL;
4052
    vc->fd_read = fd_read;
4053
    vc->fd_can_read = fd_can_read;
4054
    vc->opaque = opaque;
4055
    vc->vlan = vlan;
4056

    
4057
    vc->next = NULL;
4058
    pvc = &vlan->first_client;
4059
    while (*pvc != NULL)
4060
        pvc = &(*pvc)->next;
4061
    *pvc = vc;
4062
    return vc;
4063
}
4064

    
4065
void qemu_del_vlan_client(VLANClientState *vc)
4066
{
4067
    VLANClientState **pvc = &vc->vlan->first_client;
4068

    
4069
    while (*pvc != NULL)
4070
        if (*pvc == vc) {
4071
            *pvc = vc->next;
4072
            free(vc);
4073
            break;
4074
        } else
4075
            pvc = &(*pvc)->next;
4076
}
4077

    
4078
int qemu_can_send_packet(VLANClientState *vc1)
4079
{
4080
    VLANState *vlan = vc1->vlan;
4081
    VLANClientState *vc;
4082

    
4083
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4084
        if (vc != vc1) {
4085
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4086
                return 1;
4087
        }
4088
    }
4089
    return 0;
4090
}
4091

    
4092
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4093
{
4094
    VLANState *vlan = vc1->vlan;
4095
    VLANClientState *vc;
4096

    
4097
#if 0
4098
    printf("vlan %d send:\n", vlan->id);
4099
    hex_dump(stdout, buf, size);
4100
#endif
4101
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4102
        if (vc != vc1) {
4103
            vc->fd_read(vc->opaque, buf, size);
4104
        }
4105
    }
4106
}
4107

    
4108
#if defined(CONFIG_SLIRP)
4109

    
4110
/* slirp network adapter */
4111

    
4112
static int slirp_inited;
4113
static VLANClientState *slirp_vc;
4114

    
4115
int slirp_can_output(void)
4116
{
4117
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
4118
}
4119

    
4120
void slirp_output(const uint8_t *pkt, int pkt_len)
4121
{
4122
#if 0
4123
    printf("slirp output:\n");
4124
    hex_dump(stdout, pkt, pkt_len);
4125
#endif
4126
    if (!slirp_vc)
4127
        return;
4128
    qemu_send_packet(slirp_vc, pkt, pkt_len);
4129
}
4130

    
4131
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4132
{
4133
#if 0
4134
    printf("slirp input:\n");
4135
    hex_dump(stdout, buf, size);
4136
#endif
4137
    slirp_input(buf, size);
4138
}
4139

    
4140
static int net_slirp_init(VLANState *vlan)
4141
{
4142
    if (!slirp_inited) {
4143
        slirp_inited = 1;
4144
        slirp_init();
4145
    }
4146
    slirp_vc = qemu_new_vlan_client(vlan,
4147
                                    slirp_receive, NULL, NULL);
4148
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4149
    return 0;
4150
}
4151

    
4152
static void net_slirp_redir(const char *redir_str)
4153
{
4154
    int is_udp;
4155
    char buf[256], *r;
4156
    const char *p;
4157
    struct in_addr guest_addr;
4158
    int host_port, guest_port;
4159

    
4160
    if (!slirp_inited) {
4161
        slirp_inited = 1;
4162
        slirp_init();
4163
    }
4164

    
4165
    p = redir_str;
4166
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4167
        goto fail;
4168
    if (!strcmp(buf, "tcp")) {
4169
        is_udp = 0;
4170
    } else if (!strcmp(buf, "udp")) {
4171
        is_udp = 1;
4172
    } else {
4173
        goto fail;
4174
    }
4175

    
4176
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4177
        goto fail;
4178
    host_port = strtol(buf, &r, 0);
4179
    if (r == buf)
4180
        goto fail;
4181

    
4182
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4183
        goto fail;
4184
    if (buf[0] == '\0') {
4185
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
4186
    }
4187
    if (!inet_aton(buf, &guest_addr))
4188
        goto fail;
4189

    
4190
    guest_port = strtol(p, &r, 0);
4191
    if (r == p)
4192
        goto fail;
4193

    
4194
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4195
        fprintf(stderr, "qemu: could not set up redirection\n");
4196
        exit(1);
4197
    }
4198
    return;
4199
 fail:
4200
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4201
    exit(1);
4202
}
4203

    
4204
#ifndef _WIN32
4205

    
4206
char smb_dir[1024];
4207

    
4208
static void erase_dir(char *dir_name)
4209
{
4210
    DIR *d;
4211
    struct dirent *de;
4212
    char filename[1024];
4213

    
4214
    /* erase all the files in the directory */
4215
    if ((d = opendir(dir_name)) != 0) {
4216
        for(;;) {
4217
            de = readdir(d);
4218
            if (!de)
4219
                break;
4220
            if (strcmp(de->d_name, ".") != 0 &&
4221
                strcmp(de->d_name, "..") != 0) {
4222
                snprintf(filename, sizeof(filename), "%s/%s",
4223
                         smb_dir, de->d_name);
4224
                if (unlink(filename) != 0)  /* is it a directory? */
4225
                    erase_dir(filename);
4226
            }
4227
        }
4228
        closedir(d);
4229
        rmdir(dir_name);
4230
    }
4231
}
4232

    
4233
/* automatic user mode samba server configuration */
4234
static void smb_exit(void)
4235
{
4236
    erase_dir(smb_dir);
4237
}
4238

    
4239
/* automatic user mode samba server configuration */
4240
static void net_slirp_smb(const char *exported_dir)
4241
{
4242
    char smb_conf[1024];
4243
    char smb_cmdline[1024];
4244
    FILE *f;
4245

    
4246
    if (!slirp_inited) {
4247
        slirp_inited = 1;
4248
        slirp_init();
4249
    }
4250

    
4251
    /* XXX: better tmp dir construction */
4252
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4253
    if (mkdir(smb_dir, 0700) < 0) {
4254
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4255
        exit(1);
4256
    }
4257
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4258

    
4259
    f = fopen(smb_conf, "w");
4260
    if (!f) {
4261
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4262
        exit(1);
4263
    }
4264
    fprintf(f,
4265
            "[global]\n"
4266
            "private dir=%s\n"
4267
            "smb ports=0\n"
4268
            "socket address=127.0.0.1\n"
4269
            "pid directory=%s\n"
4270
            "lock directory=%s\n"
4271
            "log file=%s/log.smbd\n"
4272
            "smb passwd file=%s/smbpasswd\n"
4273
            "security = share\n"
4274
            "[qemu]\n"
4275
            "path=%s\n"
4276
            "read only=no\n"
4277
            "guest ok=yes\n",
4278
            smb_dir,
4279
            smb_dir,
4280
            smb_dir,
4281
            smb_dir,
4282
            smb_dir,
4283
            exported_dir
4284
            );
4285
    fclose(f);
4286
    atexit(smb_exit);
4287

    
4288
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4289
             SMBD_COMMAND, smb_conf);
4290

    
4291
    slirp_add_exec(0, smb_cmdline, 4, 139);
4292
}
4293

    
4294
#endif /* !defined(_WIN32) */
4295
void do_info_slirp(void)
4296
{
4297
    slirp_stats();
4298
}
4299

    
4300
#endif /* CONFIG_SLIRP */
4301

    
4302
#if !defined(_WIN32)
4303

    
4304
typedef struct TAPState {
4305
    VLANClientState *vc;
4306
    int fd;
4307
    char down_script[1024];
4308
} TAPState;
4309

    
4310
static void tap_receive(void *opaque, const uint8_t *buf, int size)
4311
{
4312
    TAPState *s = opaque;
4313
    int ret;
4314
    for(;;) {
4315
        ret = write(s->fd, buf, size);
4316
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4317
        } else {
4318
            break;
4319
        }
4320
    }
4321
}
4322

    
4323
static void tap_send(void *opaque)
4324
{
4325
    TAPState *s = opaque;
4326
    uint8_t buf[4096];
4327
    int size;
4328

    
4329
#ifdef __sun__
4330
    struct strbuf sbuf;
4331
    int f = 0;
4332
    sbuf.maxlen = sizeof(buf);
4333
    sbuf.buf = buf;
4334
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4335
#else
4336
    size = read(s->fd, buf, sizeof(buf));
4337
#endif
4338
    if (size > 0) {
4339
        qemu_send_packet(s->vc, buf, size);
4340
    }
4341
}
4342

    
4343
/* fd support */
4344

    
4345
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4346
{
4347
    TAPState *s;
4348

    
4349
    s = qemu_mallocz(sizeof(TAPState));
4350
    if (!s)
4351
        return NULL;
4352
    s->fd = fd;
4353
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4354
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4355
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4356
    return s;
4357
}
4358

    
4359
#if defined (_BSD) || defined (__FreeBSD_kernel__)
4360
static int tap_open(char *ifname, int ifname_size)
4361
{
4362
    int fd;
4363
    char *dev;
4364
    struct stat s;
4365

    
4366
    TFR(fd = open("/dev/tap", O_RDWR));
4367
    if (fd < 0) {
4368
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4369
        return -1;
4370
    }
4371

    
4372
    fstat(fd, &s);
4373
    dev = devname(s.st_rdev, S_IFCHR);
4374
    pstrcpy(ifname, ifname_size, dev);
4375

    
4376
    fcntl(fd, F_SETFL, O_NONBLOCK);
4377
    return fd;
4378
}
4379
#elif defined(__sun__)
4380
#define TUNNEWPPA       (('T'<<16) | 0x0001)
4381
/*
4382
 * Allocate TAP device, returns opened fd.
4383
 * Stores dev name in the first arg(must be large enough).
4384
 */
4385
int tap_alloc(char *dev)
4386
{
4387
    int tap_fd, if_fd, ppa = -1;
4388
    static int ip_fd = 0;
4389
    char *ptr;
4390

    
4391
    static int arp_fd = 0;
4392
    int ip_muxid, arp_muxid;
4393
    struct strioctl  strioc_if, strioc_ppa;
4394
    int link_type = I_PLINK;;
4395
    struct lifreq ifr;
4396
    char actual_name[32] = "";
4397

    
4398
    memset(&ifr, 0x0, sizeof(ifr));
4399

    
4400
    if( *dev ){
4401
       ptr = dev;
4402
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
4403
       ppa = atoi(ptr);
4404
    }
4405

    
4406
    /* Check if IP device was opened */
4407
    if( ip_fd )
4408
       close(ip_fd);
4409

    
4410
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4411
    if (ip_fd < 0) {
4412
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4413
       return -1;
4414
    }
4415

    
4416
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4417
    if (tap_fd < 0) {
4418
       syslog(LOG_ERR, "Can't open /dev/tap");
4419
       return -1;
4420
    }
4421

    
4422
    /* Assign a new PPA and get its unit number. */
4423
    strioc_ppa.ic_cmd = TUNNEWPPA;
4424
    strioc_ppa.ic_timout = 0;
4425
    strioc_ppa.ic_len = sizeof(ppa);
4426
    strioc_ppa.ic_dp = (char *)&ppa;
4427
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4428
       syslog (LOG_ERR, "Can't assign new interface");
4429

    
4430
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4431
    if (if_fd < 0) {
4432
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
4433
       return -1;
4434
    }
4435
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
4436
       syslog(LOG_ERR, "Can't push IP module");
4437
       return -1;
4438
    }
4439

    
4440
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4441
        syslog(LOG_ERR, "Can't get flags\n");
4442

    
4443
    snprintf (actual_name, 32, "tap%d", ppa);
4444
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4445

    
4446
    ifr.lifr_ppa = ppa;
4447
    /* Assign ppa according to the unit number returned by tun device */
4448

    
4449
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4450
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
4451
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4452
        syslog (LOG_ERR, "Can't get flags\n");
4453
    /* Push arp module to if_fd */
4454
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
4455
        syslog (LOG_ERR, "Can't push ARP module (2)");
4456

    
4457
    /* Push arp module to ip_fd */
4458
    if (ioctl (ip_fd, I_POP, NULL) < 0)
4459
        syslog (LOG_ERR, "I_POP failed\n");
4460
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4461
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
4462
    /* Open arp_fd */
4463
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4464
    if (arp_fd < 0)
4465
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4466

    
4467
    /* Set ifname to arp */
4468
    strioc_if.ic_cmd = SIOCSLIFNAME;
4469
    strioc_if.ic_timout = 0;
4470
    strioc_if.ic_len = sizeof(ifr);
4471
    strioc_if.ic_dp = (char *)&ifr;
4472
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4473
        syslog (LOG_ERR, "Can't set ifname to arp\n");
4474
    }
4475

    
4476
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4477
       syslog(LOG_ERR, "Can't link TAP device to IP");
4478
       return -1;
4479
    }
4480

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

    
4484
    close (if_fd);
4485

    
4486
    memset(&ifr, 0x0, sizeof(ifr));
4487
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4488
    ifr.lifr_ip_muxid  = ip_muxid;
4489
    ifr.lifr_arp_muxid = arp_muxid;
4490

    
4491
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4492
    {
4493
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4494
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4495
      syslog (LOG_ERR, "Can't set multiplexor id");
4496
    }
4497

    
4498
    sprintf(dev, "tap%d", ppa);
4499
    return tap_fd;
4500
}
4501

    
4502
static int tap_open(char *ifname, int ifname_size)
4503
{
4504
    char  dev[10]="";
4505
    int fd;
4506
    if( (fd = tap_alloc(dev)) < 0 ){
4507
       fprintf(stderr, "Cannot allocate TAP device\n");
4508
       return -1;
4509
    }
4510
    pstrcpy(ifname, ifname_size, dev);
4511
    fcntl(fd, F_SETFL, O_NONBLOCK);
4512
    return fd;
4513
}
4514
#else
4515
static int tap_open(char *ifname, int ifname_size)
4516
{
4517
    struct ifreq ifr;
4518
    int fd, ret;
4519

    
4520
    TFR(fd = open("/dev/net/tun", O_RDWR));
4521
    if (fd < 0) {
4522
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4523
        return -1;
4524
    }
4525
    memset(&ifr, 0, sizeof(ifr));
4526
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4527
    if (ifname[0] != '\0')
4528
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4529
    else
4530
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4531
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4532
    if (ret != 0) {
4533
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4534
        close(fd);
4535
        return -1;
4536
    }
4537
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4538
    fcntl(fd, F_SETFL, O_NONBLOCK);
4539
    return fd;
4540
}
4541
#endif
4542

    
4543
static int launch_script(const char *setup_script, const char *ifname, int fd)
4544
{
4545
    int pid, status;
4546
    char *args[3];
4547
    char **parg;
4548

    
4549
        /* try to launch network script */
4550
        pid = fork();
4551
        if (pid >= 0) {
4552
            if (pid == 0) {
4553
                int open_max = sysconf (_SC_OPEN_MAX), i;
4554
                for (i = 0; i < open_max; i++)
4555
                    if (i != STDIN_FILENO &&
4556
                        i != STDOUT_FILENO &&
4557
                        i != STDERR_FILENO &&
4558
                        i != fd)
4559
                        close(i);
4560

    
4561
                parg = args;
4562
                *parg++ = (char *)setup_script;
4563
                *parg++ = (char *)ifname;
4564
                *parg++ = NULL;
4565
                execv(setup_script, args);
4566
                _exit(1);
4567
            }
4568
            while (waitpid(pid, &status, 0) != pid);
4569
            if (!WIFEXITED(status) ||
4570
                WEXITSTATUS(status) != 0) {
4571
                fprintf(stderr, "%s: could not launch network script\n",
4572
                        setup_script);
4573
                return -1;
4574
            }
4575
        }
4576
    return 0;
4577
}
4578

    
4579
static int net_tap_init(VLANState *vlan, const char *ifname1,
4580
                        const char *setup_script, const char *down_script)
4581
{
4582
    TAPState *s;
4583
    int fd;
4584
    char ifname[128];
4585

    
4586
    if (ifname1 != NULL)
4587
        pstrcpy(ifname, sizeof(ifname), ifname1);
4588
    else
4589
        ifname[0] = '\0';
4590
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4591
    if (fd < 0)
4592
        return -1;
4593

    
4594
    if (!setup_script || !strcmp(setup_script, "no"))
4595
        setup_script = "";
4596
    if (setup_script[0] != '\0') {
4597
        if (launch_script(setup_script, ifname, fd))
4598
            return -1;
4599
    }
4600
    s = net_tap_fd_init(vlan, fd);
4601
    if (!s)
4602
        return -1;
4603
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4604
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4605
    if (down_script && strcmp(down_script, "no"))
4606
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4607
    return 0;
4608
}
4609

    
4610
#endif /* !_WIN32 */
4611

    
4612
#if defined(CONFIG_VDE)
4613
typedef struct VDEState {
4614
    VLANClientState *vc;
4615
    VDECONN *vde;
4616
} VDEState;
4617

    
4618
static void vde_to_qemu(void *opaque)
4619
{
4620
    VDEState *s = opaque;
4621
    uint8_t buf[4096];
4622
    int size;
4623

    
4624
    size = vde_recv(s->vde, buf, sizeof(buf), 0);
4625
    if (size > 0) {
4626
        qemu_send_packet(s->vc, buf, size);
4627
    }
4628
}
4629

    
4630
static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4631
{
4632
    VDEState *s = opaque;
4633
    int ret;
4634
    for(;;) {
4635
        ret = vde_send(s->vde, buf, size, 0);
4636
        if (ret < 0 && errno == EINTR) {
4637
        } else {
4638
            break;
4639
        }
4640
    }
4641
}
4642

    
4643
static int net_vde_init(VLANState *vlan, const char *sock, int port,
4644
                        const char *group, int mode)
4645
{
4646
    VDEState *s;
4647
    char *init_group = strlen(group) ? (char *)group : NULL;
4648
    char *init_sock = strlen(sock) ? (char *)sock : NULL;
4649

    
4650
    struct vde_open_args args = {
4651
        .port = port,
4652
        .group = init_group,
4653
        .mode = mode,
4654
    };
4655

    
4656
    s = qemu_mallocz(sizeof(VDEState));
4657
    if (!s)
4658
        return -1;
4659
    s->vde = vde_open(init_sock, "QEMU", &args);
4660
    if (!s->vde){
4661
        free(s);
4662
        return -1;
4663
    }
4664
    s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4665
    qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4666
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4667
             sock, vde_datafd(s->vde));
4668
    return 0;
4669
}
4670
#endif
4671

    
4672
/* network connection */
4673
typedef struct NetSocketState {
4674
    VLANClientState *vc;
4675
    int fd;
4676
    int state; /* 0 = getting length, 1 = getting data */
4677
    int index;
4678
    int packet_len;
4679
    uint8_t buf[4096];
4680
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4681
} NetSocketState;
4682

    
4683
typedef struct NetSocketListenState {
4684
    VLANState *vlan;
4685
    int fd;
4686
} NetSocketListenState;
4687

    
4688
/* XXX: we consider we can send the whole packet without blocking */
4689
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4690
{
4691
    NetSocketState *s = opaque;
4692
    uint32_t len;
4693
    len = htonl(size);
4694

    
4695
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4696
    send_all(s->fd, buf, size);
4697
}
4698

    
4699
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4700
{
4701
    NetSocketState *s = opaque;
4702
    sendto(s->fd, buf, size, 0,
4703
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4704
}
4705

    
4706
static void net_socket_send(void *opaque)
4707
{
4708
    NetSocketState *s = opaque;
4709
    int l, size, err;
4710
    uint8_t buf1[4096];
4711
    const uint8_t *buf;
4712

    
4713
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4714
    if (size < 0) {
4715
        err = socket_error();
4716
        if (err != EWOULDBLOCK)
4717
            goto eoc;
4718
    } else if (size == 0) {
4719
        /* end of connection */
4720
    eoc:
4721
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4722
        closesocket(s->fd);
4723
        return;
4724
    }
4725
    buf = buf1;
4726
    while (size > 0) {
4727
        /* reassemble a packet from the network */
4728
        switch(s->state) {
4729
        case 0:
4730
            l = 4 - s->index;
4731
            if (l > size)
4732
                l = size;
4733
            memcpy(s->buf + s->index, buf, l);
4734
            buf += l;
4735
            size -= l;
4736
            s->index += l;
4737
            if (s->index == 4) {
4738
                /* got length */
4739
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4740
                s->index = 0;
4741
                s->state = 1;
4742
            }
4743
            break;
4744
        case 1:
4745
            l = s->packet_len - s->index;
4746
            if (l > size)
4747
                l = size;
4748
            memcpy(s->buf + s->index, buf, l);
4749
            s->index += l;
4750
            buf += l;
4751
            size -= l;
4752
            if (s->index >= s->packet_len) {
4753
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4754
                s->index = 0;
4755
                s->state = 0;
4756
            }
4757
            break;
4758
        }
4759
    }
4760
}
4761

    
4762
static void net_socket_send_dgram(void *opaque)
4763
{
4764
    NetSocketState *s = opaque;
4765
    int size;
4766

    
4767
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4768
    if (size < 0)
4769
        return;
4770
    if (size == 0) {
4771
        /* end of connection */
4772
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4773
        return;
4774
    }
4775
    qemu_send_packet(s->vc, s->buf, size);
4776
}
4777

    
4778
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4779
{
4780
    struct ip_mreq imr;
4781
    int fd;
4782
    int val, ret;
4783
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4784
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4785
                inet_ntoa(mcastaddr->sin_addr),
4786
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4787
        return -1;
4788

    
4789
    }
4790
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4791
    if (fd < 0) {
4792
        perror("socket(PF_INET, SOCK_DGRAM)");
4793
        return -1;
4794
    }
4795

    
4796
    val = 1;
4797
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4798
                   (const char *)&val, sizeof(val));
4799
    if (ret < 0) {
4800
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4801
        goto fail;
4802
    }
4803

    
4804
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4805
    if (ret < 0) {
4806
        perror("bind");
4807
        goto fail;
4808
    }
4809

    
4810
    /* Add host to multicast group */
4811
    imr.imr_multiaddr = mcastaddr->sin_addr;
4812
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4813

    
4814
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4815
                     (const char *)&imr, sizeof(struct ip_mreq));
4816
    if (ret < 0) {
4817
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4818
        goto fail;
4819
    }
4820

    
4821
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4822
    val = 1;
4823
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4824
                   (const char *)&val, sizeof(val));
4825
    if (ret < 0) {
4826
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4827
        goto fail;
4828
    }
4829

    
4830
    socket_set_nonblock(fd);
4831
    return fd;
4832
fail:
4833
    if (fd >= 0)
4834
        closesocket(fd);
4835
    return -1;
4836
}
4837

    
4838
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4839
                                          int is_connected)
4840
{
4841
    struct sockaddr_in saddr;
4842
    int newfd;
4843
    socklen_t saddr_len;
4844
    NetSocketState *s;
4845

    
4846
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4847
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4848
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4849
     */
4850

    
4851
    if (is_connected) {
4852
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4853
            /* must be bound */
4854
            if (saddr.sin_addr.s_addr==0) {
4855
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4856
                        fd);
4857
                return NULL;
4858
            }
4859
            /* clone dgram socket */
4860
            newfd = net_socket_mcast_create(&saddr);
4861
            if (newfd < 0) {
4862
                /* error already reported by net_socket_mcast_create() */
4863
                close(fd);
4864
                return NULL;
4865
            }
4866
            /* clone newfd to fd, close newfd */
4867
            dup2(newfd, fd);
4868
            close(newfd);
4869

    
4870
        } else {
4871
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4872
                    fd, strerror(errno));
4873
            return NULL;
4874
        }
4875
    }
4876

    
4877
    s = qemu_mallocz(sizeof(NetSocketState));
4878
    if (!s)
4879
        return NULL;
4880
    s->fd = fd;
4881

    
4882
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4883
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4884

    
4885
    /* mcast: save bound address as dst */
4886
    if (is_connected) s->dgram_dst=saddr;
4887

    
4888
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4889
            "socket: fd=%d (%s mcast=%s:%d)",
4890
            fd, is_connected? "cloned" : "",
4891
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4892
    return s;
4893
}
4894

    
4895
static void net_socket_connect(void *opaque)
4896
{
4897
    NetSocketState *s = opaque;
4898
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4899
}
4900

    
4901
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4902
                                          int is_connected)
4903
{
4904
    NetSocketState *s;
4905
    s = qemu_mallocz(sizeof(NetSocketState));
4906
    if (!s)
4907
        return NULL;
4908
    s->fd = fd;
4909
    s->vc = qemu_new_vlan_client(vlan,
4910
                                 net_socket_receive, NULL, s);
4911
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4912
             "socket: fd=%d", fd);
4913
    if (is_connected) {
4914
        net_socket_connect(s);
4915
    } else {
4916
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4917
    }
4918
    return s;
4919
}
4920

    
4921
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4922
                                          int is_connected)
4923
{
4924
    int so_type=-1, optlen=sizeof(so_type);
4925

    
4926
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4927
        (socklen_t *)&optlen)< 0) {
4928
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4929
        return NULL;
4930
    }
4931
    switch(so_type) {
4932
    case SOCK_DGRAM:
4933
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4934
    case SOCK_STREAM:
4935
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4936
    default:
4937
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4938
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4939
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4940
    }
4941
    return NULL;
4942
}
4943

    
4944
static void net_socket_accept(void *opaque)
4945
{
4946
    NetSocketListenState *s = opaque;
4947
    NetSocketState *s1;
4948
    struct sockaddr_in saddr;
4949
    socklen_t len;
4950
    int fd;
4951

    
4952
    for(;;) {
4953
        len = sizeof(saddr);
4954
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4955
        if (fd < 0 && errno != EINTR) {
4956
            return;
4957
        } else if (fd >= 0) {
4958
            break;
4959
        }
4960
    }
4961
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4962
    if (!s1) {
4963
        closesocket(fd);
4964
    } else {
4965
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4966
                 "socket: connection from %s:%d",
4967
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4968
    }
4969
}
4970

    
4971
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4972
{
4973
    NetSocketListenState *s;
4974
    int fd, val, ret;
4975
    struct sockaddr_in saddr;
4976

    
4977
    if (parse_host_port(&saddr, host_str) < 0)
4978
        return -1;
4979

    
4980
    s = qemu_mallocz(sizeof(NetSocketListenState));
4981
    if (!s)
4982
        return -1;
4983

    
4984
    fd = socket(PF_INET, SOCK_STREAM, 0);
4985
    if (fd < 0) {
4986
        perror("socket");
4987
        return -1;
4988
    }
4989
    socket_set_nonblock(fd);
4990

    
4991
    /* allow fast reuse */
4992
    val = 1;
4993
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4994

    
4995
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4996
    if (ret < 0) {
4997
        perror("bind");
4998
        return -1;
4999
    }
5000
    ret = listen(fd, 0);
5001
    if (ret < 0) {
5002
        perror("listen");
5003
        return -1;
5004
    }
5005
    s->vlan = vlan;
5006
    s->fd = fd;
5007
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5008
    return 0;
5009
}
5010

    
5011
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5012
{
5013
    NetSocketState *s;
5014
    int fd, connected, ret, err;
5015
    struct sockaddr_in saddr;
5016

    
5017
    if (parse_host_port(&saddr, host_str) < 0)
5018
        return -1;
5019

    
5020
    fd = socket(PF_INET, SOCK_STREAM, 0);
5021
    if (fd < 0) {
5022
        perror("socket");
5023
        return -1;
5024
    }
5025
    socket_set_nonblock(fd);
5026

    
5027
    connected = 0;
5028
    for(;;) {
5029
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5030
        if (ret < 0) {
5031
            err = socket_error();
5032
            if (err == EINTR || err == EWOULDBLOCK) {
5033
            } else if (err == EINPROGRESS) {
5034
                break;
5035
#ifdef _WIN32
5036
            } else if (err == WSAEALREADY) {
5037
                break;
5038
#endif
5039
            } else {
5040
                perror("connect");
5041
                closesocket(fd);
5042
                return -1;
5043
            }
5044
        } else {
5045
            connected = 1;
5046
            break;
5047
        }
5048
    }
5049
    s = net_socket_fd_init(vlan, fd, connected);
5050
    if (!s)
5051
        return -1;
5052
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5053
             "socket: connect to %s:%d",
5054
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5055
    return 0;
5056
}
5057

    
5058
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5059
{
5060
    NetSocketState *s;
5061
    int fd;
5062
    struct sockaddr_in saddr;
5063

    
5064
    if (parse_host_port(&saddr, host_str) < 0)
5065
        return -1;
5066

    
5067

    
5068
    fd = net_socket_mcast_create(&saddr);
5069
    if (fd < 0)
5070
        return -1;
5071

    
5072
    s = net_socket_fd_init(vlan, fd, 0);
5073
    if (!s)
5074
        return -1;
5075

    
5076
    s->dgram_dst = saddr;
5077

    
5078
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5079
             "socket: mcast=%s:%d",
5080
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5081
    return 0;
5082

    
5083
}
5084

    
5085
static const char *get_opt_name(char *buf, int buf_size, const char *p)
5086
{
5087
    char *q;
5088

    
5089
    q = buf;
5090
    while (*p != '\0' && *p != '=') {
5091
        if (q && (q - buf) < buf_size - 1)
5092
            *q++ = *p;
5093
        p++;
5094
    }
5095
    if (q)
5096
        *q = '\0';
5097

    
5098
    return p;
5099
}
5100

    
5101
static const char *get_opt_value(char *buf, int buf_size, const char *p)
5102
{
5103
    char *q;
5104

    
5105
    q = buf;
5106
    while (*p != '\0') {
5107
        if (*p == ',') {
5108
            if (*(p + 1) != ',')
5109
                break;
5110
            p++;
5111
        }
5112
        if (q && (q - buf) < buf_size - 1)
5113
            *q++ = *p;
5114
        p++;
5115
    }
5116
    if (q)
5117
        *q = '\0';
5118

    
5119
    return p;
5120
}
5121

    
5122
static int get_param_value(char *buf, int buf_size,
5123
                           const char *tag, const char *str)
5124
{
5125
    const char *p;
5126
    char option[128];
5127

    
5128
    p = str;
5129
    for(;;) {
5130
        p = get_opt_name(option, sizeof(option), p);
5131
        if (*p != '=')
5132
            break;
5133
        p++;
5134
        if (!strcmp(tag, option)) {
5135
            (void)get_opt_value(buf, buf_size, p);
5136
            return strlen(buf);
5137
        } else {
5138
            p = get_opt_value(NULL, 0, p);
5139
        }
5140
        if (*p != ',')
5141
            break;
5142
        p++;
5143
    }
5144
    return 0;
5145
}
5146

    
5147
static int check_params(char *buf, int buf_size,
5148
                        char **params, const char *str)
5149
{
5150
    const char *p;
5151
    int i;
5152

    
5153
    p = str;
5154
    for(;;) {
5155
        p = get_opt_name(buf, buf_size, p);
5156
        if (*p != '=')
5157
            return -1;
5158
        p++;
5159
        for(i = 0; params[i] != NULL; i++)
5160
            if (!strcmp(params[i], buf))
5161
                break;
5162
        if (params[i] == NULL)
5163
            return -1;
5164
        p = get_opt_value(NULL, 0, p);
5165
        if (*p != ',')
5166
            break;
5167
        p++;
5168
    }
5169
    return 0;
5170
}
5171

    
5172
static int net_client_init(const char *device, const char *p)
5173
{
5174
    char buf[1024];
5175
    int vlan_id, ret;
5176
    VLANState *vlan;
5177

    
5178
    vlan_id = 0;
5179
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5180
        vlan_id = strtol(buf, NULL, 0);
5181
    }
5182
    vlan = qemu_find_vlan(vlan_id);
5183
    if (!vlan) {
5184
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5185
        return -1;
5186
    }
5187
    if (!strcmp(device, "nic")) {
5188
        NICInfo *nd;
5189
        uint8_t *macaddr;
5190

    
5191
        if (nb_nics >= MAX_NICS) {
5192
            fprintf(stderr, "Too Many NICs\n");
5193
            return -1;
5194
        }
5195
        nd = &nd_table[nb_nics];
5196
        macaddr = nd->macaddr;
5197
        macaddr[0] = 0x52;
5198
        macaddr[1] = 0x54;
5199
        macaddr[2] = 0x00;
5200
        macaddr[3] = 0x12;
5201
        macaddr[4] = 0x34;
5202
        macaddr[5] = 0x56 + nb_nics;
5203

    
5204
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5205
            if (parse_macaddr(macaddr, buf) < 0) {
5206
                fprintf(stderr, "invalid syntax for ethernet address\n");
5207
                return -1;
5208
            }
5209
        }
5210
        if (get_param_value(buf, sizeof(buf), "model", p)) {
5211
            nd->model = strdup(buf);
5212
        }
5213
        nd->vlan = vlan;
5214
        nb_nics++;
5215
        vlan->nb_guest_devs++;
5216
        ret = 0;
5217
    } else
5218
    if (!strcmp(device, "none")) {
5219
        /* does nothing. It is needed to signal that no network cards
5220
           are wanted */
5221
        ret = 0;
5222
    } else
5223
#ifdef CONFIG_SLIRP
5224
    if (!strcmp(device, "user")) {
5225
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5226
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5227
        }
5228
        vlan->nb_host_devs++;
5229
        ret = net_slirp_init(vlan);
5230
    } else
5231
#endif
5232
#ifdef _WIN32
5233
    if (!strcmp(device, "tap")) {
5234
        char ifname[64];
5235
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5236
            fprintf(stderr, "tap: no interface name\n");
5237
            return -1;
5238
        }
5239
        vlan->nb_host_devs++;
5240
        ret = tap_win32_init(vlan, ifname);
5241
    } else
5242
#else
5243
    if (!strcmp(device, "tap")) {
5244
        char ifname[64];
5245
        char setup_script[1024], down_script[1024];
5246
        int fd;
5247
        vlan->nb_host_devs++;
5248
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5249
            fd = strtol(buf, NULL, 0);
5250
            fcntl(fd, F_SETFL, O_NONBLOCK);
5251
            ret = -1;
5252
            if (net_tap_fd_init(vlan, fd))
5253
                ret = 0;
5254
        } else {
5255
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5256
                ifname[0] = '\0';
5257
            }
5258
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5259
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5260
            }
5261
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5262
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5263
            }
5264
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
5265
        }
5266
    } else
5267
#endif
5268
    if (!strcmp(device, "socket")) {
5269
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5270
            int fd;
5271
            fd = strtol(buf, NULL, 0);
5272
            ret = -1;
5273
            if (net_socket_fd_init(vlan, fd, 1))
5274
                ret = 0;
5275
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5276
            ret = net_socket_listen_init(vlan, buf);
5277
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5278
            ret = net_socket_connect_init(vlan, buf);
5279
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5280
            ret = net_socket_mcast_init(vlan, buf);
5281
        } else {
5282
            fprintf(stderr, "Unknown socket options: %s\n", p);
5283
            return -1;
5284
        }
5285
        vlan->nb_host_devs++;
5286
    } else
5287
#ifdef CONFIG_VDE
5288
    if (!strcmp(device, "vde")) {
5289
        char vde_sock[1024], vde_group[512];
5290
        int vde_port, vde_mode;
5291
        vlan->nb_host_devs++;
5292
        if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5293
            vde_sock[0] = '\0';
5294
        }
5295
        if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5296
            vde_port = strtol(buf, NULL, 10);
5297
        } else {
5298
            vde_port = 0;
5299
        }
5300
        if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5301
            vde_group[0] = '\0';
5302
        }
5303
        if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5304
            vde_mode = strtol(buf, NULL, 8);
5305
        } else {
5306
            vde_mode = 0700;
5307
        }
5308
        ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5309
    } else
5310
#endif
5311
    {
5312
        fprintf(stderr, "Unknown network device: %s\n", device);
5313
        return -1;
5314
    }
5315
    if (ret < 0) {
5316
        fprintf(stderr, "Could not initialize device '%s'\n", device);
5317
    }
5318

    
5319
    return ret;
5320
}
5321

    
5322
static int net_client_parse(const char *str)
5323
{
5324
    const char *p;
5325
    char *q;
5326
    char device[64];
5327

    
5328
    p = str;
5329
    q = device;
5330
    while (*p != '\0' && *p != ',') {
5331
        if ((q - device) < sizeof(device) - 1)
5332
            *q++ = *p;
5333
        p++;
5334
    }
5335
    *q = '\0';
5336
    if (*p == ',')
5337
        p++;
5338

    
5339
    return net_client_init(device, p);
5340
}
5341

    
5342
void do_info_network(void)
5343
{
5344
    VLANState *vlan;
5345
    VLANClientState *vc;
5346

    
5347
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5348
        term_printf("VLAN %d devices:\n", vlan->id);
5349
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5350
            term_printf("  %s\n", vc->info_str);
5351
    }
5352
}
5353

    
5354
#define HD_ALIAS "index=%d,media=disk"
5355
#ifdef TARGET_PPC
5356
#define CDROM_ALIAS "index=1,media=cdrom"
5357
#else
5358
#define CDROM_ALIAS "index=2,media=cdrom"
5359
#endif
5360
#define FD_ALIAS "index=%d,if=floppy"
5361
#define PFLASH_ALIAS "if=pflash"
5362
#define MTD_ALIAS "if=mtd"
5363
#define SD_ALIAS "index=0,if=sd"
5364

    
5365
static int drive_add(const char *file, const char *fmt, ...)
5366
{
5367
    va_list ap;
5368

    
5369
    if (nb_drives_opt >= MAX_DRIVES) {
5370
        fprintf(stderr, "qemu: too many drives\n");
5371
        exit(1);
5372
    }
5373

    
5374
    drives_opt[nb_drives_opt].file = file;
5375
    va_start(ap, fmt);
5376
    vsnprintf(drives_opt[nb_drives_opt].opt,
5377
              sizeof(drives_opt[0].opt), fmt, ap);
5378
    va_end(ap);
5379

    
5380
    return nb_drives_opt++;
5381
}
5382

    
5383
int drive_get_index(BlockInterfaceType type, int bus, int unit)
5384
{
5385
    int index;
5386

    
5387
    /* seek interface, bus and unit */
5388

    
5389
    for (index = 0; index < nb_drives; index++)
5390
        if (drives_table[index].type == type &&
5391
            drives_table[index].bus == bus &&
5392
            drives_table[index].unit == unit)
5393
        return index;
5394

    
5395
    return -1;
5396
}
5397

    
5398
int drive_get_max_bus(BlockInterfaceType type)
5399
{
5400
    int max_bus;
5401
    int index;
5402

    
5403
    max_bus = -1;
5404
    for (index = 0; index < nb_drives; index++) {
5405
        if(drives_table[index].type == type &&
5406
           drives_table[index].bus > max_bus)
5407
            max_bus = drives_table[index].bus;
5408
    }
5409
    return max_bus;
5410
}
5411

    
5412
static void bdrv_format_print(void *opaque, const char *name)
5413
{
5414
    fprintf(stderr, " %s", name);
5415
}
5416

    
5417
static int drive_init(struct drive_opt *arg, int snapshot,
5418
                      QEMUMachine *machine)
5419
{
5420
    char buf[128];
5421
    char file[1024];
5422
    char devname[128];
5423
    const char *mediastr = "";
5424
    BlockInterfaceType type;
5425
    enum { MEDIA_DISK, MEDIA_CDROM } media;
5426
    int bus_id, unit_id;
5427
    int cyls, heads, secs, translation;
5428
    BlockDriverState *bdrv;
5429
    BlockDriver *drv = NULL;
5430
    int max_devs;
5431
    int index;
5432
    int cache;
5433
    int bdrv_flags;
5434
    char *str = arg->opt;
5435
    char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5436
                       "secs", "trans", "media", "snapshot", "file",
5437
                       "cache", "format", NULL };
5438

    
5439
    if (check_params(buf, sizeof(buf), params, str) < 0) {
5440
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5441
                         buf, str);
5442
         return -1;
5443
    }
5444

    
5445
    file[0] = 0;
5446
    cyls = heads = secs = 0;
5447
    bus_id = 0;
5448
    unit_id = -1;
5449
    translation = BIOS_ATA_TRANSLATION_AUTO;
5450
    index = -1;
5451
    cache = 1;
5452

    
5453
    if (!strcmp(machine->name, "realview") ||
5454
        !strcmp(machine->name, "SS-5") ||
5455
        !strcmp(machine->name, "SS-10") ||
5456
        !strcmp(machine->name, "SS-600MP") ||
5457
        !strcmp(machine->name, "versatilepb") ||
5458
        !strcmp(machine->name, "versatileab")) {
5459
        type = IF_SCSI;
5460
        max_devs = MAX_SCSI_DEVS;
5461
        strcpy(devname, "scsi");
5462
    } else {
5463
        type = IF_IDE;
5464
        max_devs = MAX_IDE_DEVS;
5465
        strcpy(devname, "ide");
5466
    }
5467
    media = MEDIA_DISK;
5468

    
5469
    /* extract parameters */
5470

    
5471
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
5472
        bus_id = strtol(buf, NULL, 0);
5473
        if (bus_id < 0) {
5474
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5475
            return -1;
5476
        }
5477
    }
5478

    
5479
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
5480
        unit_id = strtol(buf, NULL, 0);
5481
        if (unit_id < 0) {
5482
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5483
            return -1;
5484
        }
5485
    }
5486

    
5487
    if (get_param_value(buf, sizeof(buf), "if", str)) {
5488
        pstrcpy(devname, sizeof(devname), buf);
5489
        if (!strcmp(buf, "ide")) {
5490
            type = IF_IDE;
5491
            max_devs = MAX_IDE_DEVS;
5492
        } else if (!strcmp(buf, "scsi")) {
5493
            type = IF_SCSI;
5494
            max_devs = MAX_SCSI_DEVS;
5495
        } else if (!strcmp(buf, "floppy")) {
5496
            type = IF_FLOPPY;
5497
            max_devs = 0;
5498
        } else if (!strcmp(buf, "pflash")) {
5499
            type = IF_PFLASH;
5500
            max_devs = 0;
5501
        } else if (!strcmp(buf, "mtd")) {
5502
            type = IF_MTD;
5503
            max_devs = 0;
5504
        } else if (!strcmp(buf, "sd")) {
5505
            type = IF_SD;
5506
            max_devs = 0;
5507
        } else {
5508
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5509
            return -1;
5510
        }
5511
    }
5512

    
5513
    if (get_param_value(buf, sizeof(buf), "index", str)) {
5514
        index = strtol(buf, NULL, 0);
5515
        if (index < 0) {
5516
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
5517
            return -1;
5518
        }
5519
    }
5520

    
5521
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5522
        cyls = strtol(buf, NULL, 0);
5523
    }
5524

    
5525
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
5526
        heads = strtol(buf, NULL, 0);
5527
    }
5528

    
5529
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
5530
        secs = strtol(buf, NULL, 0);
5531
    }
5532

    
5533
    if (cyls || heads || secs) {
5534
        if (cyls < 1 || cyls > 16383) {
5535
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5536
            return -1;
5537
        }
5538
        if (heads < 1 || heads > 16) {
5539
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5540
            return -1;
5541
        }
5542
        if (secs < 1 || secs > 63) {
5543
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5544
            return -1;
5545
        }
5546
    }
5547

    
5548
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
5549
        if (!cyls) {
5550
            fprintf(stderr,
5551
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
5552
                    str);
5553
            return -1;
5554
        }
5555
        if (!strcmp(buf, "none"))
5556
            translation = BIOS_ATA_TRANSLATION_NONE;
5557
        else if (!strcmp(buf, "lba"))
5558
            translation = BIOS_ATA_TRANSLATION_LBA;
5559
        else if (!strcmp(buf, "auto"))
5560
            translation = BIOS_ATA_TRANSLATION_AUTO;
5561
        else {
5562
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5563
            return -1;
5564
        }
5565
    }
5566

    
5567
    if (get_param_value(buf, sizeof(buf), "media", str)) {
5568
        if (!strcmp(buf, "disk")) {
5569
            media = MEDIA_DISK;
5570
        } else if (!strcmp(buf, "cdrom")) {
5571
            if (cyls || secs || heads) {
5572
                fprintf(stderr,
5573
                        "qemu: '%s' invalid physical CHS format\n", str);
5574
                return -1;
5575
            }
5576
            media = MEDIA_CDROM;
5577
        } else {
5578
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
5579
            return -1;
5580
        }
5581
    }
5582

    
5583
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5584
        if (!strcmp(buf, "on"))
5585
            snapshot = 1;
5586
        else if (!strcmp(buf, "off"))
5587
            snapshot = 0;
5588
        else {
5589
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5590
            return -1;
5591
        }
5592
    }
5593

    
5594
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
5595
        if (!strcmp(buf, "off"))
5596
            cache = 0;
5597
        else if (!strcmp(buf, "on"))
5598
            cache = 1;
5599
        else {
5600
           fprintf(stderr, "qemu: invalid cache option\n");
5601
           return -1;
5602
        }
5603
    }
5604

    
5605
    if (get_param_value(buf, sizeof(buf), "format", str)) {
5606
       if (strcmp(buf, "?") == 0) {
5607
            fprintf(stderr, "qemu: Supported formats:");
5608
            bdrv_iterate_format(bdrv_format_print, NULL);
5609
            fprintf(stderr, "\n");
5610
            return -1;
5611
        }
5612
        drv = bdrv_find_format(buf);
5613
        if (!drv) {
5614
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5615
            return -1;
5616
        }
5617
    }
5618

    
5619
    if (arg->file == NULL)
5620
        get_param_value(file, sizeof(file), "file", str);
5621
    else
5622
        pstrcpy(file, sizeof(file), arg->file);
5623

    
5624
    /* compute bus and unit according index */
5625

    
5626
    if (index != -1) {
5627
        if (bus_id != 0 || unit_id != -1) {
5628
            fprintf(stderr,
5629
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
5630
            return -1;
5631
        }
5632
        if (max_devs == 0)
5633
        {
5634
            unit_id = index;
5635
            bus_id = 0;
5636
        } else {
5637
            unit_id = index % max_devs;
5638
            bus_id = index / max_devs;
5639
        }
5640
    }
5641

    
5642
    /* if user doesn't specify a unit_id,
5643
     * try to find the first free
5644
     */
5645

    
5646
    if (unit_id == -1) {
5647
       unit_id = 0;
5648
       while (drive_get_index(type, bus_id, unit_id) != -1) {
5649
           unit_id++;
5650
           if (max_devs && unit_id >= max_devs) {
5651
               unit_id -= max_devs;
5652
               bus_id++;
5653
           }
5654
       }
5655
    }
5656

    
5657
    /* check unit id */
5658

    
5659
    if (max_devs && unit_id >= max_devs) {
5660
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5661
                        str, unit_id, max_devs - 1);
5662
        return -1;
5663
    }
5664

    
5665
    /*
5666
     * ignore multiple definitions
5667
     */
5668

    
5669
    if (drive_get_index(type, bus_id, unit_id) != -1)
5670
        return 0;
5671

    
5672
    /* init */
5673

    
5674
    if (type == IF_IDE || type == IF_SCSI)
5675
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5676
    if (max_devs)
5677
        snprintf(buf, sizeof(buf), "%s%i%s%i",
5678
                 devname, bus_id, mediastr, unit_id);
5679
    else
5680
        snprintf(buf, sizeof(buf), "%s%s%i",
5681
                 devname, mediastr, unit_id);
5682
    bdrv = bdrv_new(buf);
5683
    drives_table[nb_drives].bdrv = bdrv;
5684
    drives_table[nb_drives].type = type;
5685
    drives_table[nb_drives].bus = bus_id;
5686
    drives_table[nb_drives].unit = unit_id;
5687
    nb_drives++;
5688

    
5689
    switch(type) {
5690
    case IF_IDE:
5691
    case IF_SCSI:
5692
        switch(media) {
5693
        case MEDIA_DISK:
5694
            if (cyls != 0) {
5695
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5696
                bdrv_set_translation_hint(bdrv, translation);
5697
            }
5698
            break;
5699
        case MEDIA_CDROM:
5700
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5701
            break;
5702
        }
5703
        break;
5704
    case IF_SD:
5705
        /* FIXME: This isn't really a floppy, but it's a reasonable
5706
           approximation.  */
5707
    case IF_FLOPPY:
5708
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5709
        break;
5710
    case IF_PFLASH:
5711
    case IF_MTD:
5712
        break;
5713
    }
5714
    if (!file[0])
5715
        return 0;
5716
    bdrv_flags = 0;
5717
    if (snapshot)
5718
        bdrv_flags |= BDRV_O_SNAPSHOT;
5719
    if (!cache)
5720
        bdrv_flags |= BDRV_O_DIRECT;
5721
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
5722
        fprintf(stderr, "qemu: could not open disk image %s\n",
5723
                        file);
5724
        return -1;
5725
    }
5726
    return 0;
5727
}
5728

    
5729
/***********************************************************/
5730
/* USB devices */
5731

    
5732
static USBPort *used_usb_ports;
5733
static USBPort *free_usb_ports;
5734

    
5735
/* ??? Maybe change this to register a hub to keep track of the topology.  */
5736
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5737
                            usb_attachfn attach)
5738
{
5739
    port->opaque = opaque;
5740
    port->index = index;
5741
    port->attach = attach;
5742
    port->next = free_usb_ports;
5743
    free_usb_ports = port;
5744
}
5745

    
5746
static int usb_device_add(const char *devname)
5747
{
5748
    const char *p;
5749
    USBDevice *dev;
5750
    USBPort *port;
5751

    
5752
    if (!free_usb_ports)
5753
        return -1;
5754

    
5755
    if (strstart(devname, "host:", &p)) {
5756
        dev = usb_host_device_open(p);
5757
    } else if (!strcmp(devname, "mouse")) {
5758
        dev = usb_mouse_init();
5759
    } else if (!strcmp(devname, "tablet")) {
5760
        dev = usb_tablet_init();
5761
    } else if (!strcmp(devname, "keyboard")) {
5762
        dev = usb_keyboard_init();
5763
    } else if (strstart(devname, "disk:", &p)) {
5764
        dev = usb_msd_init(p);
5765
    } else if (!strcmp(devname, "wacom-tablet")) {
5766
        dev = usb_wacom_init();
5767
    } else if (strstart(devname, "serial:", &p)) {
5768
        dev = usb_serial_init(p);
5769
#ifdef CONFIG_BRLAPI
5770
    } else if (!strcmp(devname, "braille")) {
5771
        dev = usb_baum_init();
5772
#endif
5773
    } else if (strstart(devname, "net:", &p)) {
5774
        int nic = nb_nics;
5775

    
5776
        if (net_client_init("nic", p) < 0)
5777
            return -1;
5778
        nd_table[nic].model = "usb";
5779
        dev = usb_net_init(&nd_table[nic]);
5780
    } else {
5781
        return -1;
5782
    }
5783
    if (!dev)
5784
        return -1;
5785

    
5786
    /* Find a USB port to add the device to.  */
5787
    port = free_usb_ports;
5788
    if (!port->next) {
5789
        USBDevice *hub;
5790

    
5791
        /* Create a new hub and chain it on.  */
5792
        free_usb_ports = NULL;
5793
        port->next = used_usb_ports;
5794
        used_usb_ports = port;
5795

    
5796
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5797
        usb_attach(port, hub);
5798
        port = free_usb_ports;
5799
    }
5800

    
5801
    free_usb_ports = port->next;
5802
    port->next = used_usb_ports;
5803
    used_usb_ports = port;
5804
    usb_attach(port, dev);
5805
    return 0;
5806
}
5807

    
5808
static int usb_device_del(const char *devname)
5809
{
5810
    USBPort *port;
5811
    USBPort **lastp;
5812
    USBDevice *dev;
5813
    int bus_num, addr;
5814
    const char *p;
5815

    
5816
    if (!used_usb_ports)
5817
        return -1;
5818

    
5819
    p = strchr(devname, '.');
5820
    if (!p)
5821
        return -1;
5822
    bus_num = strtoul(devname, NULL, 0);
5823
    addr = strtoul(p + 1, NULL, 0);
5824
    if (bus_num != 0)
5825
        return -1;
5826

    
5827
    lastp = &used_usb_ports;
5828
    port = used_usb_ports;
5829
    while (port && port->dev->addr != addr) {
5830
        lastp = &port->next;
5831
        port = port->next;
5832
    }
5833

    
5834
    if (!port)
5835
        return -1;
5836

    
5837
    dev = port->dev;
5838
    *lastp = port->next;
5839
    usb_attach(port, NULL);
5840
    dev->handle_destroy(dev);
5841
    port->next = free_usb_ports;
5842
    free_usb_ports = port;
5843
    return 0;
5844
}
5845

    
5846
void do_usb_add(const char *devname)
5847
{
5848
    int ret;
5849
    ret = usb_device_add(devname);
5850
    if (ret < 0)
5851
        term_printf("Could not add USB device '%s'\n", devname);
5852
}
5853

    
5854
void do_usb_del(const char *devname)
5855
{
5856
    int ret;
5857
    ret = usb_device_del(devname);
5858
    if (ret < 0)
5859
        term_printf("Could not remove USB device '%s'\n", devname);
5860
}
5861

    
5862
void usb_info(void)
5863
{
5864
    USBDevice *dev;
5865
    USBPort *port;
5866
    const char *speed_str;
5867

    
5868
    if (!usb_enabled) {
5869
        term_printf("USB support not enabled\n");
5870
        return;
5871
    }
5872

    
5873
    for (port = used_usb_ports; port; port = port->next) {
5874
        dev = port->dev;
5875
        if (!dev)
5876
            continue;
5877
        switch(dev->speed) {
5878
        case USB_SPEED_LOW:
5879
            speed_str = "1.5";
5880
            break;
5881
        case USB_SPEED_FULL:
5882
            speed_str = "12";
5883
            break;
5884
        case USB_SPEED_HIGH:
5885
            speed_str = "480";
5886
            break;
5887
        default:
5888
            speed_str = "?";
5889
            break;
5890
        }
5891
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
5892
                    0, dev->addr, speed_str, dev->devname);
5893
    }
5894
}
5895

    
5896
/***********************************************************/
5897
/* PCMCIA/Cardbus */
5898

    
5899
static struct pcmcia_socket_entry_s {
5900
    struct pcmcia_socket_s *socket;
5901
    struct pcmcia_socket_entry_s *next;
5902
} *pcmcia_sockets = 0;
5903

    
5904
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5905
{
5906
    struct pcmcia_socket_entry_s *entry;
5907

    
5908
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5909
    entry->socket = socket;
5910
    entry->next = pcmcia_sockets;
5911
    pcmcia_sockets = entry;
5912
}
5913

    
5914
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5915
{
5916
    struct pcmcia_socket_entry_s *entry, **ptr;
5917

    
5918
    ptr = &pcmcia_sockets;
5919
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5920
        if (entry->socket == socket) {
5921
            *ptr = entry->next;
5922
            qemu_free(entry);
5923
        }
5924
}
5925

    
5926
void pcmcia_info(void)
5927
{
5928
    struct pcmcia_socket_entry_s *iter;
5929
    if (!pcmcia_sockets)
5930
        term_printf("No PCMCIA sockets\n");
5931

    
5932
    for (iter = pcmcia_sockets; iter; iter = iter->next)
5933
        term_printf("%s: %s\n", iter->socket->slot_string,
5934
                    iter->socket->attached ? iter->socket->card_string :
5935
                    "Empty");
5936
}
5937

    
5938
/***********************************************************/
5939
/* dumb display */
5940

    
5941
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5942
{
5943
}
5944

    
5945
static void dumb_resize(DisplayState *ds, int w, int h)
5946
{
5947
}
5948

    
5949
static void dumb_refresh(DisplayState *ds)
5950
{
5951
#if defined(CONFIG_SDL)
5952
    vga_hw_update();
5953
#endif
5954
}
5955

    
5956
static void dumb_display_init(DisplayState *ds)
5957
{
5958
    ds->data = NULL;
5959
    ds->linesize = 0;
5960
    ds->depth = 0;
5961
    ds->dpy_update = dumb_update;
5962
    ds->dpy_resize = dumb_resize;
5963
    ds->dpy_refresh = dumb_refresh;
5964
}
5965

    
5966
/***********************************************************/
5967
/* I/O handling */
5968

    
5969
#define MAX_IO_HANDLERS 64
5970

    
5971
typedef struct IOHandlerRecord {
5972
    int fd;
5973
    IOCanRWHandler *fd_read_poll;
5974
    IOHandler *fd_read;
5975
    IOHandler *fd_write;
5976
    int deleted;
5977
    void *opaque;
5978
    /* temporary data */
5979
    struct pollfd *ufd;
5980
    struct IOHandlerRecord *next;
5981
} IOHandlerRecord;
5982

    
5983
static IOHandlerRecord *first_io_handler;
5984

    
5985
/* XXX: fd_read_poll should be suppressed, but an API change is
5986
   necessary in the character devices to suppress fd_can_read(). */
5987
int qemu_set_fd_handler2(int fd,
5988
                         IOCanRWHandler *fd_read_poll,
5989
                         IOHandler *fd_read,
5990
                         IOHandler *fd_write,
5991
                         void *opaque)
5992
{
5993
    IOHandlerRecord **pioh, *ioh;
5994

    
5995
    if (!fd_read && !fd_write) {
5996
        pioh = &first_io_handler;
5997
        for(;;) {
5998
            ioh = *pioh;
5999
            if (ioh == NULL)
6000
                break;
6001
            if (ioh->fd == fd) {
6002
                ioh->deleted = 1;
6003
                break;
6004
            }
6005
            pioh = &ioh->next;
6006
        }
6007
    } else {
6008
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6009
            if (ioh->fd == fd)
6010
                goto found;
6011
        }
6012
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6013
        if (!ioh)
6014
            return -1;
6015
        ioh->next = first_io_handler;
6016
        first_io_handler = ioh;
6017
    found:
6018
        ioh->fd = fd;
6019
        ioh->fd_read_poll = fd_read_poll;
6020
        ioh->fd_read = fd_read;
6021
        ioh->fd_write = fd_write;
6022
        ioh->opaque = opaque;
6023
        ioh->deleted = 0;
6024
    }
6025
    return 0;
6026
}
6027

    
6028
int qemu_set_fd_handler(int fd,
6029
                        IOHandler *fd_read,
6030
                        IOHandler *fd_write,
6031
                        void *opaque)
6032
{
6033
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6034
}
6035

    
6036
/***********************************************************/
6037
/* Polling handling */
6038

    
6039
typedef struct PollingEntry {
6040
    PollingFunc *func;
6041
    void *opaque;
6042
    struct PollingEntry *next;
6043
} PollingEntry;
6044

    
6045
static PollingEntry *first_polling_entry;
6046

    
6047
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6048
{
6049
    PollingEntry **ppe, *pe;
6050
    pe = qemu_mallocz(sizeof(PollingEntry));
6051
    if (!pe)
6052
        return -1;
6053
    pe->func = func;
6054
    pe->opaque = opaque;
6055
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6056
    *ppe = pe;
6057
    return 0;
6058
}
6059

    
6060
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6061
{
6062
    PollingEntry **ppe, *pe;
6063
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6064
        pe = *ppe;
6065
        if (pe->func == func && pe->opaque == opaque) {
6066
            *ppe = pe->next;
6067
            qemu_free(pe);
6068
            break;
6069
        }
6070
    }
6071
}
6072

    
6073
#ifdef _WIN32
6074
/***********************************************************/
6075
/* Wait objects support */
6076
typedef struct WaitObjects {
6077
    int num;
6078
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6079
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6080
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6081
} WaitObjects;
6082

    
6083
static WaitObjects wait_objects = {0};
6084

    
6085
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6086
{
6087
    WaitObjects *w = &wait_objects;
6088

    
6089
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
6090
        return -1;
6091
    w->events[w->num] = handle;
6092
    w->func[w->num] = func;
6093
    w->opaque[w->num] = opaque;
6094
    w->num++;
6095
    return 0;
6096
}
6097

    
6098
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6099
{
6100
    int i, found;
6101
    WaitObjects *w = &wait_objects;
6102

    
6103
    found = 0;
6104
    for (i = 0; i < w->num; i++) {
6105
        if (w->events[i] == handle)
6106
            found = 1;
6107
        if (found) {
6108
            w->events[i] = w->events[i + 1];
6109
            w->func[i] = w->func[i + 1];
6110
            w->opaque[i] = w->opaque[i + 1];
6111
        }
6112
    }
6113
    if (found)
6114
        w->num--;
6115
}
6116
#endif
6117

    
6118
/***********************************************************/
6119
/* savevm/loadvm support */
6120

    
6121
#define IO_BUF_SIZE 32768
6122

    
6123
struct QEMUFile {
6124
    FILE *outfile;
6125
    BlockDriverState *bs;
6126
    int is_file;
6127
    int is_writable;
6128
    int64_t base_offset;
6129
    int64_t buf_offset; /* start of buffer when writing, end of buffer
6130
                           when reading */
6131
    int buf_index;
6132
    int buf_size; /* 0 when writing */
6133
    uint8_t buf[IO_BUF_SIZE];
6134
};
6135

    
6136
QEMUFile *qemu_fopen(const char *filename, const char *mode)
6137
{
6138
    QEMUFile *f;
6139

    
6140
    f = qemu_mallocz(sizeof(QEMUFile));
6141
    if (!f)
6142
        return NULL;
6143
    if (!strcmp(mode, "wb")) {
6144
        f->is_writable = 1;
6145
    } else if (!strcmp(mode, "rb")) {
6146
        f->is_writable = 0;
6147
    } else {
6148
        goto fail;
6149
    }
6150
    f->outfile = fopen(filename, mode);
6151
    if (!f->outfile)
6152
        goto fail;
6153
    f->is_file = 1;
6154
    return f;
6155
 fail:
6156
    if (f->outfile)
6157
        fclose(f->outfile);
6158
    qemu_free(f);
6159
    return NULL;
6160
}
6161

    
6162
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6163
{
6164
    QEMUFile *f;
6165

    
6166
    f = qemu_mallocz(sizeof(QEMUFile));
6167
    if (!f)
6168
        return NULL;
6169
    f->is_file = 0;
6170
    f->bs = bs;
6171
    f->is_writable = is_writable;
6172
    f->base_offset = offset;
6173
    return f;
6174
}
6175

    
6176
void qemu_fflush(QEMUFile *f)
6177
{
6178
    if (!f->is_writable)
6179
        return;
6180
    if (f->buf_index > 0) {
6181
        if (f->is_file) {
6182
            fseek(f->outfile, f->buf_offset, SEEK_SET);
6183
            fwrite(f->buf, 1, f->buf_index, f->outfile);
6184
        } else {
6185
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
6186
                        f->buf, f->buf_index);
6187
        }
6188
        f->buf_offset += f->buf_index;
6189
        f->buf_index = 0;
6190
    }
6191
}
6192

    
6193
static void qemu_fill_buffer(QEMUFile *f)
6194
{
6195
    int len;
6196

    
6197
    if (f->is_writable)
6198
        return;
6199
    if (f->is_file) {
6200
        fseek(f->outfile, f->buf_offset, SEEK_SET);
6201
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
6202
        if (len < 0)
6203
            len = 0;
6204
    } else {
6205
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
6206
                         f->buf, IO_BUF_SIZE);
6207
        if (len < 0)
6208
            len = 0;
6209
    }
6210
    f->buf_index = 0;
6211
    f->buf_size = len;
6212
    f->buf_offset += len;
6213
}
6214

    
6215
void qemu_fclose(QEMUFile *f)
6216
{
6217
    if (f->is_writable)
6218
        qemu_fflush(f);
6219
    if (f->is_file) {
6220
        fclose(f->outfile);
6221
    }
6222
    qemu_free(f);
6223
}
6224

    
6225
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6226
{
6227
    int l;
6228
    while (size > 0) {
6229
        l = IO_BUF_SIZE - f->buf_index;
6230
        if (l > size)
6231
            l = size;
6232
        memcpy(f->buf + f->buf_index, buf, l);
6233
        f->buf_index += l;
6234
        buf += l;
6235
        size -= l;
6236
        if (f->buf_index >= IO_BUF_SIZE)
6237
            qemu_fflush(f);
6238
    }
6239
}
6240

    
6241
void qemu_put_byte(QEMUFile *f, int v)
6242
{
6243
    f->buf[f->buf_index++] = v;
6244
    if (f->buf_index >= IO_BUF_SIZE)
6245
        qemu_fflush(f);
6246
}
6247

    
6248
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6249
{
6250
    int size, l;
6251

    
6252
    size = size1;
6253
    while (size > 0) {
6254
        l = f->buf_size - f->buf_index;
6255
        if (l == 0) {
6256
            qemu_fill_buffer(f);
6257
            l = f->buf_size - f->buf_index;
6258
            if (l == 0)
6259
                break;
6260
        }
6261
        if (l > size)
6262
            l = size;
6263
        memcpy(buf, f->buf + f->buf_index, l);
6264
        f->buf_index += l;
6265
        buf += l;
6266
        size -= l;
6267
    }
6268
    return size1 - size;
6269
}
6270

    
6271
int qemu_get_byte(QEMUFile *f)
6272
{
6273
    if (f->buf_index >= f->buf_size) {
6274
        qemu_fill_buffer(f);
6275
        if (f->buf_index >= f->buf_size)
6276
            return 0;
6277
    }
6278
    return f->buf[f->buf_index++];
6279
}
6280

    
6281
int64_t qemu_ftell(QEMUFile *f)
6282
{
6283
    return f->buf_offset - f->buf_size + f->buf_index;
6284
}
6285

    
6286
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6287
{
6288
    if (whence == SEEK_SET) {
6289
        /* nothing to do */
6290
    } else if (whence == SEEK_CUR) {
6291
        pos += qemu_ftell(f);
6292
    } else {
6293
        /* SEEK_END not supported */
6294
        return -1;
6295
    }
6296
    if (f->is_writable) {
6297
        qemu_fflush(f);
6298
        f->buf_offset = pos;
6299
    } else {
6300
        f->buf_offset = pos;
6301
        f->buf_index = 0;
6302
        f->buf_size = 0;
6303
    }
6304
    return pos;
6305
}
6306

    
6307
void qemu_put_be16(QEMUFile *f, unsigned int v)
6308
{
6309
    qemu_put_byte(f, v >> 8);
6310
    qemu_put_byte(f, v);
6311
}
6312

    
6313
void qemu_put_be32(QEMUFile *f, unsigned int v)
6314
{
6315
    qemu_put_byte(f, v >> 24);
6316
    qemu_put_byte(f, v >> 16);
6317
    qemu_put_byte(f, v >> 8);
6318
    qemu_put_byte(f, v);
6319
}
6320

    
6321
void qemu_put_be64(QEMUFile *f, uint64_t v)
6322
{
6323
    qemu_put_be32(f, v >> 32);
6324
    qemu_put_be32(f, v);
6325
}
6326

    
6327
unsigned int qemu_get_be16(QEMUFile *f)
6328
{
6329
    unsigned int v;
6330
    v = qemu_get_byte(f) << 8;
6331
    v |= qemu_get_byte(f);
6332
    return v;
6333
}
6334

    
6335
unsigned int qemu_get_be32(QEMUFile *f)
6336
{
6337
    unsigned int v;
6338
    v = qemu_get_byte(f) << 24;
6339
    v |= qemu_get_byte(f) << 16;
6340
    v |= qemu_get_byte(f) << 8;
6341
    v |= qemu_get_byte(f);
6342
    return v;
6343
}
6344

    
6345
uint64_t qemu_get_be64(QEMUFile *f)
6346
{
6347
    uint64_t v;
6348
    v = (uint64_t)qemu_get_be32(f) << 32;
6349
    v |= qemu_get_be32(f);
6350
    return v;
6351
}
6352

    
6353
typedef struct SaveStateEntry {
6354
    char idstr[256];
6355
    int instance_id;
6356
    int version_id;
6357
    SaveStateHandler *save_state;
6358
    LoadStateHandler *load_state;
6359
    void *opaque;
6360
    struct SaveStateEntry *next;
6361
} SaveStateEntry;
6362

    
6363
static SaveStateEntry *first_se;
6364

    
6365
/* TODO: Individual devices generally have very little idea about the rest
6366
   of the system, so instance_id should be removed/replaced.
6367
   Meanwhile pass -1 as instance_id if you do not already have a clearly
6368
   distinguishing id for all instances of your device class. */
6369
int register_savevm(const char *idstr,
6370
                    int instance_id,
6371
                    int version_id,
6372
                    SaveStateHandler *save_state,
6373
                    LoadStateHandler *load_state,
6374
                    void *opaque)
6375
{
6376
    SaveStateEntry *se, **pse;
6377

    
6378
    se = qemu_malloc(sizeof(SaveStateEntry));
6379
    if (!se)
6380
        return -1;
6381
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6382
    se->instance_id = (instance_id == -1) ? 0 : instance_id;
6383
    se->version_id = version_id;
6384
    se->save_state = save_state;
6385
    se->load_state = load_state;
6386
    se->opaque = opaque;
6387
    se->next = NULL;
6388

    
6389
    /* add at the end of list */
6390
    pse = &first_se;
6391
    while (*pse != NULL) {
6392
        if (instance_id == -1
6393
                && strcmp(se->idstr, (*pse)->idstr) == 0
6394
                && se->instance_id <= (*pse)->instance_id)
6395
            se->instance_id = (*pse)->instance_id + 1;
6396
        pse = &(*pse)->next;
6397
    }
6398
    *pse = se;
6399
    return 0;
6400
}
6401

    
6402
#define QEMU_VM_FILE_MAGIC   0x5145564d
6403
#define QEMU_VM_FILE_VERSION 0x00000002
6404

    
6405
static int qemu_savevm_state(QEMUFile *f)
6406
{
6407
    SaveStateEntry *se;
6408
    int len, ret;
6409
    int64_t cur_pos, len_pos, total_len_pos;
6410

    
6411
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6412
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6413
    total_len_pos = qemu_ftell(f);
6414
    qemu_put_be64(f, 0); /* total size */
6415

    
6416
    for(se = first_se; se != NULL; se = se->next) {
6417
        if (se->save_state == NULL)
6418
            /* this one has a loader only, for backwards compatibility */
6419
            continue;
6420

    
6421
        /* ID string */
6422
        len = strlen(se->idstr);
6423
        qemu_put_byte(f, len);
6424
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6425

    
6426
        qemu_put_be32(f, se->instance_id);
6427
        qemu_put_be32(f, se->version_id);
6428

    
6429
        /* record size: filled later */
6430
        len_pos = qemu_ftell(f);
6431
        qemu_put_be32(f, 0);
6432
        se->save_state(f, se->opaque);
6433

    
6434
        /* fill record size */
6435
        cur_pos = qemu_ftell(f);
6436
        len = cur_pos - len_pos - 4;
6437
        qemu_fseek(f, len_pos, SEEK_SET);
6438
        qemu_put_be32(f, len);
6439
        qemu_fseek(f, cur_pos, SEEK_SET);
6440
    }
6441
    cur_pos = qemu_ftell(f);
6442
    qemu_fseek(f, total_len_pos, SEEK_SET);
6443
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
6444
    qemu_fseek(f, cur_pos, SEEK_SET);
6445

    
6446
    ret = 0;
6447
    return ret;
6448
}
6449

    
6450
static SaveStateEntry *find_se(const char *idstr, int instance_id)
6451
{
6452
    SaveStateEntry *se;
6453

    
6454
    for(se = first_se; se != NULL; se = se->next) {
6455
        if (!strcmp(se->idstr, idstr) &&
6456
            instance_id == se->instance_id)
6457
            return se;
6458
    }
6459
    return NULL;
6460
}
6461

    
6462
static int qemu_loadvm_state(QEMUFile *f)
6463
{
6464
    SaveStateEntry *se;
6465
    int len, ret, instance_id, record_len, version_id;
6466
    int64_t total_len, end_pos, cur_pos;
6467
    unsigned int v;
6468
    char idstr[256];
6469

    
6470
    v = qemu_get_be32(f);
6471
    if (v != QEMU_VM_FILE_MAGIC)
6472
        goto fail;
6473
    v = qemu_get_be32(f);
6474
    if (v != QEMU_VM_FILE_VERSION) {
6475
    fail:
6476
        ret = -1;
6477
        goto the_end;
6478
    }
6479
    total_len = qemu_get_be64(f);
6480
    end_pos = total_len + qemu_ftell(f);
6481
    for(;;) {
6482
        if (qemu_ftell(f) >= end_pos)
6483
            break;
6484
        len = qemu_get_byte(f);
6485
        qemu_get_buffer(f, (uint8_t *)idstr, len);
6486
        idstr[len] = '\0';
6487
        instance_id = qemu_get_be32(f);
6488
        version_id = qemu_get_be32(f);
6489
        record_len = qemu_get_be32(f);
6490
#if 0
6491
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
6492
               idstr, instance_id, version_id, record_len);
6493
#endif
6494
        cur_pos = qemu_ftell(f);
6495
        se = find_se(idstr, instance_id);
6496
        if (!se) {
6497
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6498
                    instance_id, idstr);
6499
        } else {
6500
            ret = se->load_state(f, se->opaque, version_id);
6501
            if (ret < 0) {
6502
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6503
                        instance_id, idstr);
6504
            }
6505
        }
6506
        /* always seek to exact end of record */
6507
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6508
    }
6509
    ret = 0;
6510
 the_end:
6511
    return ret;
6512
}
6513

    
6514
/* device can contain snapshots */
6515
static int bdrv_can_snapshot(BlockDriverState *bs)
6516
{
6517
    return (bs &&
6518
            !bdrv_is_removable(bs) &&
6519
            !bdrv_is_read_only(bs));
6520
}
6521

    
6522
/* device must be snapshots in order to have a reliable snapshot */
6523
static int bdrv_has_snapshot(BlockDriverState *bs)
6524
{
6525
    return (bs &&
6526
            !bdrv_is_removable(bs) &&
6527
            !bdrv_is_read_only(bs));
6528
}
6529

    
6530
static BlockDriverState *get_bs_snapshots(void)
6531
{
6532
    BlockDriverState *bs;
6533
    int i;
6534

    
6535
    if (bs_snapshots)
6536
        return bs_snapshots;
6537
    for(i = 0; i <= nb_drives; i++) {
6538
        bs = drives_table[i].bdrv;
6539
        if (bdrv_can_snapshot(bs))
6540
            goto ok;
6541
    }
6542
    return NULL;
6543
 ok:
6544
    bs_snapshots = bs;
6545
    return bs;
6546
}
6547

    
6548
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6549
                              const char *name)
6550
{
6551
    QEMUSnapshotInfo *sn_tab, *sn;
6552
    int nb_sns, i, ret;
6553

    
6554
    ret = -ENOENT;
6555
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6556
    if (nb_sns < 0)
6557
        return ret;
6558
    for(i = 0; i < nb_sns; i++) {
6559
        sn = &sn_tab[i];
6560
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6561
            *sn_info = *sn;
6562
            ret = 0;
6563
            break;
6564
        }
6565
    }
6566
    qemu_free(sn_tab);
6567
    return ret;
6568
}
6569

    
6570
void do_savevm(const char *name)
6571
{
6572
    BlockDriverState *bs, *bs1;
6573
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6574
    int must_delete, ret, i;
6575
    BlockDriverInfo bdi1, *bdi = &bdi1;
6576
    QEMUFile *f;
6577
    int saved_vm_running;
6578
#ifdef _WIN32
6579
    struct _timeb tb;
6580
#else
6581
    struct timeval tv;
6582
#endif
6583

    
6584
    bs = get_bs_snapshots();
6585
    if (!bs) {
6586
        term_printf("No block device can accept snapshots\n");
6587
        return;
6588
    }
6589

    
6590
    /* ??? Should this occur after vm_stop?  */
6591
    qemu_aio_flush();
6592

    
6593
    saved_vm_running = vm_running;
6594
    vm_stop(0);
6595

    
6596
    must_delete = 0;
6597
    if (name) {
6598
        ret = bdrv_snapshot_find(bs, old_sn, name);
6599
        if (ret >= 0) {
6600
            must_delete = 1;
6601
        }
6602
    }
6603
    memset(sn, 0, sizeof(*sn));
6604
    if (must_delete) {
6605
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6606
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6607
    } else {
6608
        if (name)
6609
            pstrcpy(sn->name, sizeof(sn->name), name);
6610
    }
6611

    
6612
    /* fill auxiliary fields */
6613
#ifdef _WIN32
6614
    _ftime(&tb);
6615
    sn->date_sec = tb.time;
6616
    sn->date_nsec = tb.millitm * 1000000;
6617
#else
6618
    gettimeofday(&tv, NULL);
6619
    sn->date_sec = tv.tv_sec;
6620
    sn->date_nsec = tv.tv_usec * 1000;
6621
#endif
6622
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6623

    
6624
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6625
        term_printf("Device %s does not support VM state snapshots\n",
6626
                    bdrv_get_device_name(bs));
6627
        goto the_end;
6628
    }
6629

    
6630
    /* save the VM state */
6631
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6632
    if (!f) {
6633
        term_printf("Could not open VM state file\n");
6634
        goto the_end;
6635
    }
6636
    ret = qemu_savevm_state(f);
6637
    sn->vm_state_size = qemu_ftell(f);
6638
    qemu_fclose(f);
6639
    if (ret < 0) {
6640
        term_printf("Error %d while writing VM\n", ret);
6641
        goto the_end;
6642
    }
6643

    
6644
    /* create the snapshots */
6645

    
6646
    for(i = 0; i < nb_drives; i++) {
6647
        bs1 = drives_table[i].bdrv;
6648
        if (bdrv_has_snapshot(bs1)) {
6649
            if (must_delete) {
6650
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6651
                if (ret < 0) {
6652
                    term_printf("Error while deleting snapshot on '%s'\n",
6653
                                bdrv_get_device_name(bs1));
6654
                }
6655
            }
6656
            ret = bdrv_snapshot_create(bs1, sn);
6657
            if (ret < 0) {
6658
                term_printf("Error while creating snapshot on '%s'\n",
6659
                            bdrv_get_device_name(bs1));
6660
            }
6661
        }
6662
    }
6663

    
6664
 the_end:
6665
    if (saved_vm_running)
6666
        vm_start();
6667
}
6668

    
6669
void do_loadvm(const char *name)
6670
{
6671
    BlockDriverState *bs, *bs1;
6672
    BlockDriverInfo bdi1, *bdi = &bdi1;
6673
    QEMUFile *f;
6674
    int i, ret;
6675
    int saved_vm_running;
6676

    
6677
    bs = get_bs_snapshots();
6678
    if (!bs) {
6679
        term_printf("No block device supports snapshots\n");
6680
        return;
6681
    }
6682

    
6683
    /* Flush all IO requests so they don't interfere with the new state.  */
6684
    qemu_aio_flush();
6685

    
6686
    saved_vm_running = vm_running;
6687
    vm_stop(0);
6688

    
6689
    for(i = 0; i <= nb_drives; i++) {
6690
        bs1 = drives_table[i].bdrv;
6691
        if (bdrv_has_snapshot(bs1)) {
6692
            ret = bdrv_snapshot_goto(bs1, name);
6693
            if (ret < 0) {
6694
                if (bs != bs1)
6695
                    term_printf("Warning: ");
6696
                switch(ret) {
6697
                case -ENOTSUP:
6698
                    term_printf("Snapshots not supported on device '%s'\n",
6699
                                bdrv_get_device_name(bs1));
6700
                    break;
6701
                case -ENOENT:
6702
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
6703
                                name, bdrv_get_device_name(bs1));
6704
                    break;
6705
                default:
6706
                    term_printf("Error %d while activating snapshot on '%s'\n",
6707
                                ret, bdrv_get_device_name(bs1));
6708
                    break;
6709
                }
6710
                /* fatal on snapshot block device */
6711
                if (bs == bs1)
6712
                    goto the_end;
6713
            }
6714
        }
6715
    }
6716

    
6717
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6718
        term_printf("Device %s does not support VM state snapshots\n",
6719
                    bdrv_get_device_name(bs));
6720
        return;
6721
    }
6722

    
6723
    /* restore the VM state */
6724
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6725
    if (!f) {
6726
        term_printf("Could not open VM state file\n");
6727
        goto the_end;
6728
    }
6729
    ret = qemu_loadvm_state(f);
6730
    qemu_fclose(f);
6731
    if (ret < 0) {
6732
        term_printf("Error %d while loading VM state\n", ret);
6733
    }
6734
 the_end:
6735
    if (saved_vm_running)
6736
        vm_start();
6737
}
6738

    
6739
void do_delvm(const char *name)
6740
{
6741
    BlockDriverState *bs, *bs1;
6742
    int i, ret;
6743

    
6744
    bs = get_bs_snapshots();
6745
    if (!bs) {
6746
        term_printf("No block device supports snapshots\n");
6747
        return;
6748
    }
6749

    
6750
    for(i = 0; i <= nb_drives; i++) {
6751
        bs1 = drives_table[i].bdrv;
6752
        if (bdrv_has_snapshot(bs1)) {
6753
            ret = bdrv_snapshot_delete(bs1, name);
6754
            if (ret < 0) {
6755
                if (ret == -ENOTSUP)
6756
                    term_printf("Snapshots not supported on device '%s'\n",
6757
                                bdrv_get_device_name(bs1));
6758
                else
6759
                    term_printf("Error %d while deleting snapshot on '%s'\n",
6760
                                ret, bdrv_get_device_name(bs1));
6761
            }
6762
        }
6763
    }
6764
}
6765

    
6766
void do_info_snapshots(void)
6767
{
6768
    BlockDriverState *bs, *bs1;
6769
    QEMUSnapshotInfo *sn_tab, *sn;
6770
    int nb_sns, i;
6771
    char buf[256];
6772

    
6773
    bs = get_bs_snapshots();
6774
    if (!bs) {
6775
        term_printf("No available block device supports snapshots\n");
6776
        return;
6777
    }
6778
    term_printf("Snapshot devices:");
6779
    for(i = 0; i <= nb_drives; i++) {
6780
        bs1 = drives_table[i].bdrv;
6781
        if (bdrv_has_snapshot(bs1)) {
6782
            if (bs == bs1)
6783
                term_printf(" %s", bdrv_get_device_name(bs1));
6784
        }
6785
    }
6786
    term_printf("\n");
6787

    
6788
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6789
    if (nb_sns < 0) {
6790
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6791
        return;
6792
    }
6793
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6794
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6795
    for(i = 0; i < nb_sns; i++) {
6796
        sn = &sn_tab[i];
6797
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6798
    }
6799
    qemu_free(sn_tab);
6800
}
6801

    
6802
/***********************************************************/
6803
/* ram save/restore */
6804

    
6805
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6806
{
6807
    int v;
6808

    
6809
    v = qemu_get_byte(f);
6810
    switch(v) {
6811
    case 0:
6812
        if (qemu_get_buffer(f, buf, len) != len)
6813
            return -EIO;
6814
        break;
6815
    case 1:
6816
        v = qemu_get_byte(f);
6817
        memset(buf, v, len);
6818
        break;
6819
    default:
6820
        return -EINVAL;
6821
    }
6822
    return 0;
6823
}
6824

    
6825
static int ram_load_v1(QEMUFile *f, void *opaque)
6826
{
6827
    int ret;
6828
    ram_addr_t i;
6829

    
6830
    if (qemu_get_be32(f) != phys_ram_size)
6831
        return -EINVAL;
6832
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6833
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6834
        if (ret)
6835
            return ret;
6836
    }
6837
    return 0;
6838
}
6839

    
6840
#define BDRV_HASH_BLOCK_SIZE 1024
6841
#define IOBUF_SIZE 4096
6842
#define RAM_CBLOCK_MAGIC 0xfabe
6843

    
6844
typedef struct RamCompressState {
6845
    z_stream zstream;
6846
    QEMUFile *f;
6847
    uint8_t buf[IOBUF_SIZE];
6848
} RamCompressState;
6849

    
6850
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6851
{
6852
    int ret;
6853
    memset(s, 0, sizeof(*s));
6854
    s->f = f;
6855
    ret = deflateInit2(&s->zstream, 1,
6856
                       Z_DEFLATED, 15,
6857
                       9, Z_DEFAULT_STRATEGY);
6858
    if (ret != Z_OK)
6859
        return -1;
6860
    s->zstream.avail_out = IOBUF_SIZE;
6861
    s->zstream.next_out = s->buf;
6862
    return 0;
6863
}
6864

    
6865
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6866
{
6867
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6868
    qemu_put_be16(s->f, len);
6869
    qemu_put_buffer(s->f, buf, len);
6870
}
6871

    
6872
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6873
{
6874
    int ret;
6875

    
6876
    s->zstream.avail_in = len;
6877
    s->zstream.next_in = (uint8_t *)buf;
6878
    while (s->zstream.avail_in > 0) {
6879
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6880
        if (ret != Z_OK)
6881
            return -1;
6882
        if (s->zstream.avail_out == 0) {
6883
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6884
            s->zstream.avail_out = IOBUF_SIZE;
6885
            s->zstream.next_out = s->buf;
6886
        }
6887
    }
6888
    return 0;
6889
}
6890

    
6891
static void ram_compress_close(RamCompressState *s)
6892
{
6893
    int len, ret;
6894

    
6895
    /* compress last bytes */
6896
    for(;;) {
6897
        ret = deflate(&s->zstream, Z_FINISH);
6898
        if (ret == Z_OK || ret == Z_STREAM_END) {
6899
            len = IOBUF_SIZE - s->zstream.avail_out;
6900
            if (len > 0) {
6901
                ram_put_cblock(s, s->buf, len);
6902
            }
6903
            s->zstream.avail_out = IOBUF_SIZE;
6904
            s->zstream.next_out = s->buf;
6905
            if (ret == Z_STREAM_END)
6906
                break;
6907
        } else {
6908
            goto fail;
6909
        }
6910
    }
6911
fail:
6912
    deflateEnd(&s->zstream);
6913
}
6914

    
6915
typedef struct RamDecompressState {
6916
    z_stream zstream;
6917
    QEMUFile *f;
6918
    uint8_t buf[IOBUF_SIZE];
6919
} RamDecompressState;
6920

    
6921
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6922
{
6923
    int ret;
6924
    memset(s, 0, sizeof(*s));
6925
    s->f = f;
6926
    ret = inflateInit(&s->zstream);
6927
    if (ret != Z_OK)
6928
        return -1;
6929
    return 0;
6930
}
6931

    
6932
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6933
{
6934
    int ret, clen;
6935

    
6936
    s->zstream.avail_out = len;
6937
    s->zstream.next_out = buf;
6938
    while (s->zstream.avail_out > 0) {
6939
        if (s->zstream.avail_in == 0) {
6940
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6941
                return -1;
6942
            clen = qemu_get_be16(s->f);
6943
            if (clen > IOBUF_SIZE)
6944
                return -1;
6945
            qemu_get_buffer(s->f, s->buf, clen);
6946
            s->zstream.avail_in = clen;
6947
            s->zstream.next_in = s->buf;
6948
        }
6949
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6950
        if (ret != Z_OK && ret != Z_STREAM_END) {
6951
            return -1;
6952
        }
6953
    }
6954
    return 0;
6955
}
6956

    
6957
static void ram_decompress_close(RamDecompressState *s)
6958
{
6959
    inflateEnd(&s->zstream);
6960
}
6961

    
6962
static void ram_save(QEMUFile *f, void *opaque)
6963
{
6964
    ram_addr_t i;
6965
    RamCompressState s1, *s = &s1;
6966
    uint8_t buf[10];
6967

    
6968
    qemu_put_be32(f, phys_ram_size);
6969
    if (ram_compress_open(s, f) < 0)
6970
        return;
6971
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6972
#if 0
6973
        if (tight_savevm_enabled) {
6974
            int64_t sector_num;
6975
            int j;
6976

6977
            /* find if the memory block is available on a virtual
6978
               block device */
6979
            sector_num = -1;
6980
            for(j = 0; j < nb_drives; j++) {
6981
                sector_num = bdrv_hash_find(drives_table[j].bdrv,
6982
                                            phys_ram_base + i,
6983
                                            BDRV_HASH_BLOCK_SIZE);
6984
                if (sector_num >= 0)
6985
                    break;
6986
            }
6987
            if (j == nb_drives)
6988
                goto normal_compress;
6989
            buf[0] = 1;
6990
            buf[1] = j;
6991
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6992
            ram_compress_buf(s, buf, 10);
6993
        } else
6994
#endif
6995
        {
6996
            //        normal_compress:
6997
            buf[0] = 0;
6998
            ram_compress_buf(s, buf, 1);
6999
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7000
        }
7001
    }
7002
    ram_compress_close(s);
7003
}
7004

    
7005
static int ram_load(QEMUFile *f, void *opaque, int version_id)
7006
{
7007
    RamDecompressState s1, *s = &s1;
7008
    uint8_t buf[10];
7009
    ram_addr_t i;
7010

    
7011
    if (version_id == 1)
7012
        return ram_load_v1(f, opaque);
7013
    if (version_id != 2)
7014
        return -EINVAL;
7015
    if (qemu_get_be32(f) != phys_ram_size)
7016
        return -EINVAL;
7017
    if (ram_decompress_open(s, f) < 0)
7018
        return -EINVAL;
7019
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7020
        if (ram_decompress_buf(s, buf, 1) < 0) {
7021
            fprintf(stderr, "Error while reading ram block header\n");
7022
            goto error;
7023
        }
7024
        if (buf[0] == 0) {
7025
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7026
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7027
                goto error;
7028
            }
7029
        } else
7030
#if 0
7031
        if (buf[0] == 1) {
7032
            int bs_index;
7033
            int64_t sector_num;
7034

7035
            ram_decompress_buf(s, buf + 1, 9);
7036
            bs_index = buf[1];
7037
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7038
            if (bs_index >= nb_drives) {
7039
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
7040
                goto error;
7041
            }
7042
            if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7043
                          phys_ram_base + i,
7044
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7045
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7046
                        bs_index, sector_num);
7047
                goto error;
7048
            }
7049
        } else
7050
#endif
7051
        {
7052
        error:
7053
            printf("Error block header\n");
7054
            return -EINVAL;
7055
        }
7056
    }
7057
    ram_decompress_close(s);
7058
    return 0;
7059
}
7060

    
7061
/***********************************************************/
7062
/* bottom halves (can be seen as timers which expire ASAP) */
7063

    
7064
struct QEMUBH {
7065
    QEMUBHFunc *cb;
7066
    void *opaque;
7067
    int scheduled;
7068
    QEMUBH *next;
7069
};
7070

    
7071
static QEMUBH *first_bh = NULL;
7072

    
7073
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7074
{
7075
    QEMUBH *bh;
7076
    bh = qemu_mallocz(sizeof(QEMUBH));
7077
    if (!bh)
7078
        return NULL;
7079
    bh->cb = cb;
7080
    bh->opaque = opaque;
7081
    return bh;
7082
}
7083

    
7084
int qemu_bh_poll(void)
7085
{
7086
    QEMUBH *bh, **pbh;
7087
    int ret;
7088

    
7089
    ret = 0;
7090
    for(;;) {
7091
        pbh = &first_bh;
7092
        bh = *pbh;
7093
        if (!bh)
7094
            break;
7095
        ret = 1;
7096
        *pbh = bh->next;
7097
        bh->scheduled = 0;
7098
        bh->cb(bh->opaque);
7099
    }
7100
    return ret;
7101
}
7102

    
7103
void qemu_bh_schedule(QEMUBH *bh)
7104
{
7105
    CPUState *env = cpu_single_env;
7106
    if (bh->scheduled)
7107
        return;
7108
    bh->scheduled = 1;
7109
    bh->next = first_bh;
7110
    first_bh = bh;
7111

    
7112
    /* stop the currently executing CPU to execute the BH ASAP */
7113
    if (env) {
7114
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7115
    }
7116
}
7117

    
7118
void qemu_bh_cancel(QEMUBH *bh)
7119
{
7120
    QEMUBH **pbh;
7121
    if (bh->scheduled) {
7122
        pbh = &first_bh;
7123
        while (*pbh != bh)
7124
            pbh = &(*pbh)->next;
7125
        *pbh = bh->next;
7126
        bh->scheduled = 0;
7127
    }
7128
}
7129

    
7130
void qemu_bh_delete(QEMUBH *bh)
7131
{
7132
    qemu_bh_cancel(bh);
7133
    qemu_free(bh);
7134
}
7135

    
7136
/***********************************************************/
7137
/* machine registration */
7138

    
7139
QEMUMachine *first_machine = NULL;
7140

    
7141
int qemu_register_machine(QEMUMachine *m)
7142
{
7143
    QEMUMachine **pm;
7144
    pm = &first_machine;
7145
    while (*pm != NULL)
7146
        pm = &(*pm)->next;
7147
    m->next = NULL;
7148
    *pm = m;
7149
    return 0;
7150
}
7151

    
7152
static QEMUMachine *find_machine(const char *name)
7153
{
7154
    QEMUMachine *m;
7155

    
7156
    for(m = first_machine; m != NULL; m = m->next) {
7157
        if (!strcmp(m->name, name))
7158
            return m;
7159
    }
7160
    return NULL;
7161
}
7162

    
7163
/***********************************************************/
7164
/* main execution loop */
7165

    
7166
static void gui_update(void *opaque)
7167
{
7168
    DisplayState *ds = opaque;
7169
    ds->dpy_refresh(ds);
7170
    qemu_mod_timer(ds->gui_timer,
7171
        (ds->gui_timer_interval ?
7172
            ds->gui_timer_interval :
7173
            GUI_REFRESH_INTERVAL)
7174
        + qemu_get_clock(rt_clock));
7175
}
7176

    
7177
struct vm_change_state_entry {
7178
    VMChangeStateHandler *cb;
7179
    void *opaque;
7180
    LIST_ENTRY (vm_change_state_entry) entries;
7181
};
7182

    
7183
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7184

    
7185
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7186
                                                     void *opaque)
7187
{
7188
    VMChangeStateEntry *e;
7189

    
7190
    e = qemu_mallocz(sizeof (*e));
7191
    if (!e)
7192
        return NULL;
7193

    
7194
    e->cb = cb;
7195
    e->opaque = opaque;
7196
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7197
    return e;
7198
}
7199

    
7200
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7201
{
7202
    LIST_REMOVE (e, entries);
7203
    qemu_free (e);
7204
}
7205

    
7206
static void vm_state_notify(int running)
7207
{
7208
    VMChangeStateEntry *e;
7209

    
7210
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7211
        e->cb(e->opaque, running);
7212
    }
7213
}
7214

    
7215
/* XXX: support several handlers */
7216
static VMStopHandler *vm_stop_cb;
7217
static void *vm_stop_opaque;
7218

    
7219
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7220
{
7221
    vm_stop_cb = cb;
7222
    vm_stop_opaque = opaque;
7223
    return 0;
7224
}
7225

    
7226
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7227
{
7228
    vm_stop_cb = NULL;
7229
}
7230

    
7231
void vm_start(void)
7232
{
7233
    if (!vm_running) {
7234
        cpu_enable_ticks();
7235
        vm_running = 1;
7236
        vm_state_notify(1);
7237
        qemu_rearm_alarm_timer(alarm_timer);
7238
    }
7239
}
7240

    
7241
void vm_stop(int reason)
7242
{
7243
    if (vm_running) {
7244
        cpu_disable_ticks();
7245
        vm_running = 0;
7246
        if (reason != 0) {
7247
            if (vm_stop_cb) {
7248
                vm_stop_cb(vm_stop_opaque, reason);
7249
            }
7250
        }
7251
        vm_state_notify(0);
7252
    }
7253
}
7254

    
7255
/* reset/shutdown handler */
7256

    
7257
typedef struct QEMUResetEntry {
7258
    QEMUResetHandler *func;
7259
    void *opaque;
7260
    struct QEMUResetEntry *next;
7261
} QEMUResetEntry;
7262

    
7263
static QEMUResetEntry *first_reset_entry;
7264
static int reset_requested;
7265
static int shutdown_requested;
7266
static int powerdown_requested;
7267

    
7268
int qemu_shutdown_requested(void)
7269
{
7270
    int r = shutdown_requested;
7271
    shutdown_requested = 0;
7272
    return r;
7273
}
7274

    
7275
int qemu_reset_requested(void)
7276
{
7277
    int r = reset_requested;
7278
    reset_requested = 0;
7279
    return r;
7280
}
7281

    
7282
int qemu_powerdown_requested(void)
7283
{
7284
    int r = powerdown_requested;
7285
    powerdown_requested = 0;
7286
    return r;
7287
}
7288

    
7289
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7290
{
7291
    QEMUResetEntry **pre, *re;
7292

    
7293
    pre = &first_reset_entry;
7294
    while (*pre != NULL)
7295
        pre = &(*pre)->next;
7296
    re = qemu_mallocz(sizeof(QEMUResetEntry));
7297
    re->func = func;
7298
    re->opaque = opaque;
7299
    re->next = NULL;
7300
    *pre = re;
7301
}
7302

    
7303
void qemu_system_reset(void)
7304
{
7305
    QEMUResetEntry *re;
7306

    
7307
    /* reset all devices */
7308
    for(re = first_reset_entry; re != NULL; re = re->next) {
7309
        re->func(re->opaque);
7310
    }
7311
}
7312

    
7313
void qemu_system_reset_request(void)
7314
{
7315
    if (no_reboot) {
7316
        shutdown_requested = 1;
7317
    } else {
7318
        reset_requested = 1;
7319
    }
7320
    if (cpu_single_env)
7321
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7322
}
7323

    
7324
void qemu_system_shutdown_request(void)
7325
{
7326
    shutdown_requested = 1;
7327
    if (cpu_single_env)
7328
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7329
}
7330

    
7331
void qemu_system_powerdown_request(void)
7332
{
7333
    powerdown_requested = 1;
7334
    if (cpu_single_env)
7335
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7336
}
7337

    
7338
void main_loop_wait(int timeout)
7339
{
7340
    IOHandlerRecord *ioh;
7341
    fd_set rfds, wfds, xfds;
7342
    int ret, nfds;
7343
#ifdef _WIN32
7344
    int ret2, i;
7345
#endif
7346
    struct timeval tv;
7347
    PollingEntry *pe;
7348

    
7349

    
7350
    /* XXX: need to suppress polling by better using win32 events */
7351
    ret = 0;
7352
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7353
        ret |= pe->func(pe->opaque);
7354
    }
7355
#ifdef _WIN32
7356
    if (ret == 0) {
7357
        int err;
7358
        WaitObjects *w = &wait_objects;
7359

    
7360
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7361
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7362
            if (w->func[ret - WAIT_OBJECT_0])
7363
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7364

    
7365
            /* Check for additional signaled events */
7366
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7367

    
7368
                /* Check if event is signaled */
7369
                ret2 = WaitForSingleObject(w->events[i], 0);
7370
                if(ret2 == WAIT_OBJECT_0) {
7371
                    if (w->func[i])
7372
                        w->func[i](w->opaque[i]);
7373
                } else if (ret2 == WAIT_TIMEOUT) {
7374
                } else {
7375
                    err = GetLastError();
7376
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7377
                }
7378
            }
7379
        } else if (ret == WAIT_TIMEOUT) {
7380
        } else {
7381
            err = GetLastError();
7382
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7383
        }
7384
    }
7385
#endif
7386
    /* poll any events */
7387
    /* XXX: separate device handlers from system ones */
7388
    nfds = -1;
7389
    FD_ZERO(&rfds);
7390
    FD_ZERO(&wfds);
7391
    FD_ZERO(&xfds);
7392
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7393
        if (ioh->deleted)
7394
            continue;
7395
        if (ioh->fd_read &&
7396
            (!ioh->fd_read_poll ||
7397
             ioh->fd_read_poll(ioh->opaque) != 0)) {
7398
            FD_SET(ioh->fd, &rfds);
7399
            if (ioh->fd > nfds)
7400
                nfds = ioh->fd;
7401
        }
7402
        if (ioh->fd_write) {
7403
            FD_SET(ioh->fd, &wfds);
7404
            if (ioh->fd > nfds)
7405
                nfds = ioh->fd;
7406
        }
7407
    }
7408

    
7409
    tv.tv_sec = 0;
7410
#ifdef _WIN32
7411
    tv.tv_usec = 0;
7412
#else
7413
    tv.tv_usec = timeout * 1000;
7414
#endif
7415
#if defined(CONFIG_SLIRP)
7416
    if (slirp_inited) {
7417
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7418
    }
7419
#endif
7420
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7421
    if (ret > 0) {
7422
        IOHandlerRecord **pioh;
7423

    
7424
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7425
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7426
                ioh->fd_read(ioh->opaque);
7427
            }
7428
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7429
                ioh->fd_write(ioh->opaque);
7430
            }
7431
        }
7432

    
7433
        /* remove deleted IO handlers */
7434
        pioh = &first_io_handler;
7435
        while (*pioh) {
7436
            ioh = *pioh;
7437
            if (ioh->deleted) {
7438
                *pioh = ioh->next;
7439
                qemu_free(ioh);
7440
            } else
7441
                pioh = &ioh->next;
7442
        }
7443
    }
7444
#if defined(CONFIG_SLIRP)
7445
    if (slirp_inited) {
7446
        if (ret < 0) {
7447
            FD_ZERO(&rfds);
7448
            FD_ZERO(&wfds);
7449
            FD_ZERO(&xfds);
7450
        }
7451
        slirp_select_poll(&rfds, &wfds, &xfds);
7452
    }
7453
#endif
7454
    qemu_aio_poll();
7455

    
7456
    if (vm_running) {
7457
        if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7458
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7459
                        qemu_get_clock(vm_clock));
7460
        /* run dma transfers, if any */
7461
        DMA_run();
7462
    }
7463

    
7464
    /* real time timers */
7465
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7466
                    qemu_get_clock(rt_clock));
7467

    
7468
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7469
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7470
        qemu_rearm_alarm_timer(alarm_timer);
7471
    }
7472

    
7473
    /* Check bottom-halves last in case any of the earlier events triggered
7474
       them.  */
7475
    qemu_bh_poll();
7476

    
7477
}
7478

    
7479
static int main_loop(void)
7480
{
7481
    int ret, timeout;
7482
#ifdef CONFIG_PROFILER
7483
    int64_t ti;
7484
#endif
7485
    CPUState *env;
7486

    
7487
    cur_cpu = first_cpu;
7488
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7489
    for(;;) {
7490
        if (vm_running) {
7491

    
7492
            for(;;) {
7493
                /* get next cpu */
7494
                env = next_cpu;
7495
#ifdef CONFIG_PROFILER
7496
                ti = profile_getclock();
7497
#endif
7498
                if (use_icount) {
7499
                    int64_t count;
7500
                    int decr;
7501
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7502
                    env->icount_decr.u16.low = 0;
7503
                    env->icount_extra = 0;
7504
                    count = qemu_next_deadline();
7505
                    count = (count + (1 << icount_time_shift) - 1)
7506
                            >> icount_time_shift;
7507
                    qemu_icount += count;
7508
                    decr = (count > 0xffff) ? 0xffff : count;
7509
                    count -= decr;
7510
                    env->icount_decr.u16.low = decr;
7511
                    env->icount_extra = count;
7512
                }
7513
                ret = cpu_exec(env);
7514
#ifdef CONFIG_PROFILER
7515
                qemu_time += profile_getclock() - ti;
7516
#endif
7517
                if (use_icount) {
7518
                    /* Fold pending instructions back into the
7519
                       instruction counter, and clear the interrupt flag.  */
7520
                    qemu_icount -= (env->icount_decr.u16.low
7521
                                    + env->icount_extra);
7522
                    env->icount_decr.u32 = 0;
7523
                    env->icount_extra = 0;
7524
                }
7525
                next_cpu = env->next_cpu ?: first_cpu;
7526
                if (event_pending && likely(ret != EXCP_DEBUG)) {
7527
                    ret = EXCP_INTERRUPT;
7528
                    event_pending = 0;
7529
                    break;
7530
                }
7531
                if (ret == EXCP_HLT) {
7532
                    /* Give the next CPU a chance to run.  */
7533
                    cur_cpu = env;
7534
                    continue;
7535
                }
7536
                if (ret != EXCP_HALTED)
7537
                    break;
7538
                /* all CPUs are halted ? */
7539
                if (env == cur_cpu)
7540
                    break;
7541
            }
7542
            cur_cpu = env;
7543

    
7544
            if (shutdown_requested) {
7545
                ret = EXCP_INTERRUPT;
7546
                if (no_shutdown) {
7547
                    vm_stop(0);
7548
                    no_shutdown = 0;
7549
                }
7550
                else
7551
                    break;
7552
            }
7553
            if (reset_requested) {
7554
                reset_requested = 0;
7555
                qemu_system_reset();
7556
                ret = EXCP_INTERRUPT;
7557
            }
7558
            if (powerdown_requested) {
7559
                powerdown_requested = 0;
7560
                qemu_system_powerdown();
7561
                ret = EXCP_INTERRUPT;
7562
            }
7563
            if (unlikely(ret == EXCP_DEBUG)) {
7564
                vm_stop(EXCP_DEBUG);
7565
            }
7566
            /* If all cpus are halted then wait until the next IRQ */
7567
            /* XXX: use timeout computed from timers */
7568
            if (ret == EXCP_HALTED) {
7569
                if (use_icount) {
7570
                    int64_t add;
7571
                    int64_t delta;
7572
                    /* Advance virtual time to the next event.  */
7573
                    if (use_icount == 1) {
7574
                        /* When not using an adaptive execution frequency
7575
                           we tend to get badly out of sync with real time,
7576
                           so just delay for a reasonable amount of time.  */
7577
                        delta = 0;
7578
                    } else {
7579
                        delta = cpu_get_icount() - cpu_get_clock();
7580
                    }
7581
                    if (delta > 0) {
7582
                        /* If virtual time is ahead of real time then just
7583
                           wait for IO.  */
7584
                        timeout = (delta / 1000000) + 1;
7585
                    } else {
7586
                        /* Wait for either IO to occur or the next
7587
                           timer event.  */
7588
                        add = qemu_next_deadline();
7589
                        /* We advance the timer before checking for IO.
7590
                           Limit the amount we advance so that early IO
7591
                           activity won't get the guest too far ahead.  */
7592
                        if (add > 10000000)
7593
                            add = 10000000;
7594
                        delta += add;
7595
                        add = (add + (1 << icount_time_shift) - 1)
7596
                              >> icount_time_shift;
7597
                        qemu_icount += add;
7598
                        timeout = delta / 1000000;
7599
                        if (timeout < 0)
7600
                            timeout = 0;
7601
                    }
7602
                } else {
7603
                    timeout = 10;
7604
                }
7605
            } else {
7606
                timeout = 0;
7607
            }
7608
        } else {
7609
            timeout = 10;
7610
        }
7611
#ifdef CONFIG_PROFILER
7612
        ti = profile_getclock();
7613
#endif
7614
        main_loop_wait(timeout);
7615
#ifdef CONFIG_PROFILER
7616
        dev_time += profile_getclock() - ti;
7617
#endif
7618
    }
7619
    cpu_disable_ticks();
7620
    return ret;
7621
}
7622

    
7623
static void help(int exitcode)
7624
{
7625
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7626
           "usage: %s [options] [disk_image]\n"
7627
           "\n"
7628
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7629
           "\n"
7630
           "Standard options:\n"
7631
           "-M machine      select emulated machine (-M ? for list)\n"
7632
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7633
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7634
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7635
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7636
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7637
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7638
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7639
           "       [,cache=on|off][,format=f]\n"
7640
           "                use 'file' as a drive image\n"
7641
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7642
           "-sd file        use 'file' as SecureDigital card image\n"
7643
           "-pflash file    use 'file' as a parallel flash image\n"
7644
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7645
           "-snapshot       write to temporary files instead of disk image files\n"
7646
#ifdef CONFIG_SDL
7647
           "-no-frame       open SDL window without a frame and window decorations\n"
7648
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7649
           "-no-quit        disable SDL window close capability\n"
7650
#endif
7651
#ifdef TARGET_I386
7652
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7653
#endif
7654
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7655
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7656
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7657
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7658
#ifndef _WIN32
7659
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7660
#endif
7661
#ifdef HAS_AUDIO
7662
           "-audio-help     print list of audio drivers and their options\n"
7663
           "-soundhw c1,... enable audio support\n"
7664
           "                and only specified sound cards (comma separated list)\n"
7665
           "                use -soundhw ? to get the list of supported cards\n"
7666
           "                use -soundhw all to enable all of them\n"
7667
#endif
7668
           "-localtime      set the real time clock to local time [default=utc]\n"
7669
           "-full-screen    start in full screen\n"
7670
#ifdef TARGET_I386
7671
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7672
#endif
7673
           "-usb            enable the USB driver (will be the default soon)\n"
7674
           "-usbdevice name add the host or guest USB device 'name'\n"
7675
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7676
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7677
#endif
7678
           "-name string    set the name of the guest\n"
7679
           "\n"
7680
           "Network options:\n"
7681
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7682
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7683
#ifdef CONFIG_SLIRP
7684
           "-net user[,vlan=n][,hostname=host]\n"
7685
           "                connect the user mode network stack to VLAN 'n' and send\n"
7686
           "                hostname 'host' to DHCP clients\n"
7687
#endif
7688
#ifdef _WIN32
7689
           "-net tap[,vlan=n],ifname=name\n"
7690
           "                connect the host TAP network interface to VLAN 'n'\n"
7691
#else
7692
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7693
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7694
           "                network scripts 'file' (default=%s)\n"
7695
           "                and 'dfile' (default=%s);\n"
7696
           "                use '[down]script=no' to disable script execution;\n"
7697
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7698
#endif
7699
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7700
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7701
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7702
           "                connect the vlan 'n' to multicast maddr and port\n"
7703
#ifdef CONFIG_VDE
7704
           "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7705
           "                connect the vlan 'n' to port 'n' of a vde switch running\n"
7706
           "                on host and listening for incoming connections on 'socketpath'.\n"
7707
           "                Use group 'groupname' and mode 'octalmode' to change default\n"
7708
           "                ownership and permissions for communication port.\n"
7709
#endif
7710
           "-net none       use it alone to have zero network devices; if no -net option\n"
7711
           "                is provided, the default is '-net nic -net user'\n"
7712
           "\n"
7713
#ifdef CONFIG_SLIRP
7714
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7715
           "-bootp file     advertise file in BOOTP replies\n"
7716
#ifndef _WIN32
7717
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7718
#endif
7719
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7720
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7721
#endif
7722
           "\n"
7723
           "Linux boot specific:\n"
7724
           "-kernel bzImage use 'bzImage' as kernel image\n"
7725
           "-append cmdline use 'cmdline' as kernel command line\n"
7726
           "-initrd file    use 'file' as initial ram disk\n"
7727
           "\n"
7728
           "Debug/Expert options:\n"
7729
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7730
           "-serial dev     redirect the serial port to char device 'dev'\n"
7731
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7732
           "-pidfile file   Write PID to 'file'\n"
7733
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7734
           "-s              wait gdb connection to port\n"
7735
           "-p port         set gdb connection port [default=%s]\n"
7736
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7737
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7738
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7739
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7740
#ifdef USE_KQEMU
7741
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7742
           "-no-kqemu       disable KQEMU kernel module usage\n"
7743
#endif
7744
#ifdef TARGET_I386
7745
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7746
           "                (default is CL-GD5446 PCI VGA)\n"
7747
           "-no-acpi        disable ACPI\n"
7748
#endif
7749
#ifdef CONFIG_CURSES
7750
           "-curses         use a curses/ncurses interface instead of SDL\n"
7751
#endif
7752
           "-no-reboot      exit instead of rebooting\n"
7753
           "-no-shutdown    stop before shutdown\n"
7754
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
7755
           "-vnc display    start a VNC server on display\n"
7756
#ifndef _WIN32
7757
           "-daemonize      daemonize QEMU after initializing\n"
7758
#endif
7759
           "-option-rom rom load a file, rom, into the option ROM space\n"
7760
#ifdef TARGET_SPARC
7761
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7762
#endif
7763
           "-clock          force the use of the given methods for timer alarm.\n"
7764
           "                To see what timers are available use -clock ?\n"
7765
           "-startdate      select initial date of the clock\n"
7766
           "-icount [N|auto]\n"
7767
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7768
           "\n"
7769
           "During emulation, the following keys are useful:\n"
7770
           "ctrl-alt-f      toggle full screen\n"
7771
           "ctrl-alt-n      switch to virtual console 'n'\n"
7772
           "ctrl-alt        toggle mouse and keyboard grab\n"
7773
           "\n"
7774
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7775
           ,
7776
           "qemu",
7777
           DEFAULT_RAM_SIZE,
7778
#ifndef _WIN32
7779
           DEFAULT_NETWORK_SCRIPT,
7780
           DEFAULT_NETWORK_DOWN_SCRIPT,
7781
#endif
7782
           DEFAULT_GDBSTUB_PORT,
7783
           "/tmp/qemu.log");
7784
    exit(exitcode);
7785
}
7786

    
7787
#define HAS_ARG 0x0001
7788

    
7789
enum {
7790
    QEMU_OPTION_h,
7791

    
7792
    QEMU_OPTION_M,
7793
    QEMU_OPTION_cpu,
7794
    QEMU_OPTION_fda,
7795
    QEMU_OPTION_fdb,
7796
    QEMU_OPTION_hda,
7797
    QEMU_OPTION_hdb,
7798
    QEMU_OPTION_hdc,
7799
    QEMU_OPTION_hdd,
7800
    QEMU_OPTION_drive,
7801
    QEMU_OPTION_cdrom,
7802
    QEMU_OPTION_mtdblock,
7803
    QEMU_OPTION_sd,
7804
    QEMU_OPTION_pflash,
7805
    QEMU_OPTION_boot,
7806
    QEMU_OPTION_snapshot,
7807
#ifdef TARGET_I386
7808
    QEMU_OPTION_no_fd_bootchk,
7809
#endif
7810
    QEMU_OPTION_m,
7811
    QEMU_OPTION_nographic,
7812
    QEMU_OPTION_portrait,
7813
#ifdef HAS_AUDIO
7814
    QEMU_OPTION_audio_help,
7815
    QEMU_OPTION_soundhw,
7816
#endif
7817

    
7818
    QEMU_OPTION_net,
7819
    QEMU_OPTION_tftp,
7820
    QEMU_OPTION_bootp,
7821
    QEMU_OPTION_smb,
7822
    QEMU_OPTION_redir,
7823

    
7824
    QEMU_OPTION_kernel,
7825
    QEMU_OPTION_append,
7826
    QEMU_OPTION_initrd,
7827

    
7828
    QEMU_OPTION_S,
7829
    QEMU_OPTION_s,
7830
    QEMU_OPTION_p,
7831
    QEMU_OPTION_d,
7832
    QEMU_OPTION_hdachs,
7833
    QEMU_OPTION_L,
7834
    QEMU_OPTION_bios,
7835
    QEMU_OPTION_k,
7836
    QEMU_OPTION_localtime,
7837
    QEMU_OPTION_cirrusvga,
7838
    QEMU_OPTION_vmsvga,
7839
    QEMU_OPTION_g,
7840
    QEMU_OPTION_std_vga,
7841
    QEMU_OPTION_echr,
7842
    QEMU_OPTION_monitor,
7843
    QEMU_OPTION_serial,
7844
    QEMU_OPTION_parallel,
7845
    QEMU_OPTION_loadvm,
7846
    QEMU_OPTION_full_screen,
7847
    QEMU_OPTION_no_frame,
7848
    QEMU_OPTION_alt_grab,
7849
    QEMU_OPTION_no_quit,
7850
    QEMU_OPTION_pidfile,
7851
    QEMU_OPTION_no_kqemu,
7852
    QEMU_OPTION_kernel_kqemu,
7853
    QEMU_OPTION_win2k_hack,
7854
    QEMU_OPTION_usb,
7855
    QEMU_OPTION_usbdevice,
7856
    QEMU_OPTION_smp,
7857
    QEMU_OPTION_vnc,
7858
    QEMU_OPTION_no_acpi,
7859
    QEMU_OPTION_curses,
7860
    QEMU_OPTION_no_reboot,
7861
    QEMU_OPTION_no_shutdown,
7862
    QEMU_OPTION_show_cursor,
7863
    QEMU_OPTION_daemonize,
7864
    QEMU_OPTION_option_rom,
7865
    QEMU_OPTION_semihosting,
7866
    QEMU_OPTION_name,
7867
    QEMU_OPTION_prom_env,
7868
    QEMU_OPTION_old_param,
7869
    QEMU_OPTION_clock,
7870
    QEMU_OPTION_startdate,
7871
    QEMU_OPTION_tb_size,
7872
    QEMU_OPTION_icount,
7873
};
7874

    
7875
typedef struct QEMUOption {
7876
    const char *name;
7877
    int flags;
7878
    int index;
7879
} QEMUOption;
7880

    
7881
const QEMUOption qemu_options[] = {
7882
    { "h", 0, QEMU_OPTION_h },
7883
    { "help", 0, QEMU_OPTION_h },
7884

    
7885
    { "M", HAS_ARG, QEMU_OPTION_M },
7886
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7887
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7888
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7889
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7890
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7891
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7892
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7893
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7894
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7895
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7896
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7897
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7898
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7899
    { "snapshot", 0, QEMU_OPTION_snapshot },
7900
#ifdef TARGET_I386
7901
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7902
#endif
7903
    { "m", HAS_ARG, QEMU_OPTION_m },
7904
    { "nographic", 0, QEMU_OPTION_nographic },
7905
    { "portrait", 0, QEMU_OPTION_portrait },
7906
    { "k", HAS_ARG, QEMU_OPTION_k },
7907
#ifdef HAS_AUDIO
7908
    { "audio-help", 0, QEMU_OPTION_audio_help },
7909
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7910
#endif
7911

    
7912
    { "net", HAS_ARG, QEMU_OPTION_net},
7913
#ifdef CONFIG_SLIRP
7914
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7915
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7916
#ifndef _WIN32
7917
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7918
#endif
7919
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7920
#endif
7921

    
7922
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7923
    { "append", HAS_ARG, QEMU_OPTION_append },
7924
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7925

    
7926
    { "S", 0, QEMU_OPTION_S },
7927
    { "s", 0, QEMU_OPTION_s },
7928
    { "p", HAS_ARG, QEMU_OPTION_p },
7929
    { "d", HAS_ARG, QEMU_OPTION_d },
7930
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7931
    { "L", HAS_ARG, QEMU_OPTION_L },
7932
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7933
#ifdef USE_KQEMU
7934
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7935
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7936
#endif
7937
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7938
    { "g", 1, QEMU_OPTION_g },
7939
#endif
7940
    { "localtime", 0, QEMU_OPTION_localtime },
7941
    { "std-vga", 0, QEMU_OPTION_std_vga },
7942
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7943
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7944
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7945
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7946
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7947
    { "full-screen", 0, QEMU_OPTION_full_screen },
7948
#ifdef CONFIG_SDL
7949
    { "no-frame", 0, QEMU_OPTION_no_frame },
7950
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7951
    { "no-quit", 0, QEMU_OPTION_no_quit },
7952
#endif
7953
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7954
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7955
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7956
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7957
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7958
#ifdef CONFIG_CURSES
7959
    { "curses", 0, QEMU_OPTION_curses },
7960
#endif
7961

    
7962
    /* temporary options */
7963
    { "usb", 0, QEMU_OPTION_usb },
7964
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7965
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7966
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7967
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7968
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7969
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7970
    { "daemonize", 0, QEMU_OPTION_daemonize },
7971
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7972
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7973
    { "semihosting", 0, QEMU_OPTION_semihosting },
7974
#endif
7975
    { "name", HAS_ARG, QEMU_OPTION_name },
7976
#if defined(TARGET_SPARC)
7977
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7978
#endif
7979
#if defined(TARGET_ARM)
7980
    { "old-param", 0, QEMU_OPTION_old_param },
7981
#endif
7982
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7983
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7984
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
7985
    { "icount", HAS_ARG, QEMU_OPTION_icount },
7986
    { NULL },
7987
};
7988

    
7989
/* password input */
7990

    
7991
int qemu_key_check(BlockDriverState *bs, const char *name)
7992
{
7993
    char password[256];
7994
    int i;
7995

    
7996
    if (!bdrv_is_encrypted(bs))
7997
        return 0;
7998

    
7999
    term_printf("%s is encrypted.\n", name);
8000
    for(i = 0; i < 3; i++) {
8001
        monitor_readline("Password: ", 1, password, sizeof(password));
8002
        if (bdrv_set_key(bs, password) == 0)
8003
            return 0;
8004
        term_printf("invalid password\n");
8005
    }
8006
    return -EPERM;
8007
}
8008

    
8009
static void read_passwords(void)
8010
{
8011
    BlockDriverState *bs;
8012
    int i;
8013

    
8014
    for(i = 0; i < nb_drives; i++) {
8015
        bs = drives_table[i].bdrv;
8016
        qemu_key_check(bs, bdrv_get_device_name(bs));
8017
    }
8018
}
8019

    
8020
#ifdef HAS_AUDIO
8021
struct soundhw soundhw[] = {
8022
#ifdef HAS_AUDIO_CHOICE
8023
#if defined(TARGET_I386) || defined(TARGET_MIPS)
8024
    {
8025
        "pcspk",
8026
        "PC speaker",
8027
        0,
8028
        1,
8029
        { .init_isa = pcspk_audio_init }
8030
    },
8031
#endif
8032
    {
8033
        "sb16",
8034
        "Creative Sound Blaster 16",
8035
        0,
8036
        1,
8037
        { .init_isa = SB16_init }
8038
    },
8039

    
8040
#ifdef CONFIG_CS4231A
8041
    {
8042
        "cs4231a",
8043
        "CS4231A",
8044
        0,
8045
        1,
8046
        { .init_isa = cs4231a_init }
8047
    },
8048
#endif
8049

    
8050
#ifdef CONFIG_ADLIB
8051
    {
8052
        "adlib",
8053
#ifdef HAS_YMF262
8054
        "Yamaha YMF262 (OPL3)",
8055
#else
8056
        "Yamaha YM3812 (OPL2)",
8057
#endif
8058
        0,
8059
        1,
8060
        { .init_isa = Adlib_init }
8061
    },
8062
#endif
8063

    
8064
#ifdef CONFIG_GUS
8065
    {
8066
        "gus",
8067
        "Gravis Ultrasound GF1",
8068
        0,
8069
        1,
8070
        { .init_isa = GUS_init }
8071
    },
8072
#endif
8073

    
8074
#ifdef CONFIG_AC97
8075
    {
8076
        "ac97",
8077
        "Intel 82801AA AC97 Audio",
8078
        0,
8079
        0,
8080
        { .init_pci = ac97_init }
8081
    },
8082
#endif
8083

    
8084
    {
8085
        "es1370",
8086
        "ENSONIQ AudioPCI ES1370",
8087
        0,
8088
        0,
8089
        { .init_pci = es1370_init }
8090
    },
8091
#endif
8092

    
8093
    { NULL, NULL, 0, 0, { NULL } }
8094
};
8095

    
8096
static void select_soundhw (const char *optarg)
8097
{
8098
    struct soundhw *c;
8099

    
8100
    if (*optarg == '?') {
8101
    show_valid_cards:
8102

    
8103
        printf ("Valid sound card names (comma separated):\n");
8104
        for (c = soundhw; c->name; ++c) {
8105
            printf ("%-11s %s\n", c->name, c->descr);
8106
        }
8107
        printf ("\n-soundhw all will enable all of the above\n");
8108
        exit (*optarg != '?');
8109
    }
8110
    else {
8111
        size_t l;
8112
        const char *p;
8113
        char *e;
8114
        int bad_card = 0;
8115

    
8116
        if (!strcmp (optarg, "all")) {
8117
            for (c = soundhw; c->name; ++c) {
8118
                c->enabled = 1;
8119
            }
8120
            return;
8121
        }
8122

    
8123
        p = optarg;
8124
        while (*p) {
8125
            e = strchr (p, ',');
8126
            l = !e ? strlen (p) : (size_t) (e - p);
8127

    
8128
            for (c = soundhw; c->name; ++c) {
8129
                if (!strncmp (c->name, p, l)) {
8130
                    c->enabled = 1;
8131
                    break;
8132
                }
8133
            }
8134

    
8135
            if (!c->name) {
8136
                if (l > 80) {
8137
                    fprintf (stderr,
8138
                             "Unknown sound card name (too big to show)\n");
8139
                }
8140
                else {
8141
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
8142
                             (int) l, p);
8143
                }
8144
                bad_card = 1;
8145
            }
8146
            p += l + (e != NULL);
8147
        }
8148

    
8149
        if (bad_card)
8150
            goto show_valid_cards;
8151
    }
8152
}
8153
#endif
8154

    
8155
#ifdef _WIN32
8156
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8157
{
8158
    exit(STATUS_CONTROL_C_EXIT);
8159
    return TRUE;
8160
}
8161
#endif
8162

    
8163
#define MAX_NET_CLIENTS 32
8164

    
8165
int main(int argc, char **argv)
8166
{
8167
#ifdef CONFIG_GDBSTUB
8168
    int use_gdbstub;
8169
    const char *gdbstub_port;
8170
#endif
8171
    uint32_t boot_devices_bitmap = 0;
8172
    int i;
8173
    int snapshot, linux_boot, net_boot;
8174
    const char *initrd_filename;
8175
    const char *kernel_filename, *kernel_cmdline;
8176
    const char *boot_devices = "";
8177
    DisplayState *ds = &display_state;
8178
    int cyls, heads, secs, translation;
8179
    const char *net_clients[MAX_NET_CLIENTS];
8180
    int nb_net_clients;
8181
    int hda_index;
8182
    int optind;
8183
    const char *r, *optarg;
8184
    CharDriverState *monitor_hd;
8185
    int has_monitor;
8186
    const char *monitor_device;
8187
    const char *serial_devices[MAX_SERIAL_PORTS];
8188
    int serial_device_index;
8189
    const char *parallel_devices[MAX_PARALLEL_PORTS];
8190
    int parallel_device_index;
8191
    const char *loadvm = NULL;
8192
    QEMUMachine *machine;
8193
    const char *cpu_model;
8194
    const char *usb_devices[MAX_USB_CMDLINE];
8195
    int usb_devices_index;
8196
    int fds[2];
8197
    int tb_size;
8198
    const char *pid_file = NULL;
8199
    VLANState *vlan;
8200

    
8201
    LIST_INIT (&vm_change_state_head);
8202
#ifndef _WIN32
8203
    {
8204
        struct sigaction act;
8205
        sigfillset(&act.sa_mask);
8206
        act.sa_flags = 0;
8207
        act.sa_handler = SIG_IGN;
8208
        sigaction(SIGPIPE, &act, NULL);
8209
    }
8210
#else
8211
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8212
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
8213
       QEMU to run on a single CPU */
8214
    {
8215
        HANDLE h;
8216
        DWORD mask, smask;
8217
        int i;
8218
        h = GetCurrentProcess();
8219
        if (GetProcessAffinityMask(h, &mask, &smask)) {
8220
            for(i = 0; i < 32; i++) {
8221
                if (mask & (1 << i))
8222
                    break;
8223
            }
8224
            if (i != 32) {
8225
                mask = 1 << i;
8226
                SetProcessAffinityMask(h, mask);
8227
            }
8228
        }
8229
    }
8230
#endif
8231

    
8232
    register_machines();
8233
    machine = first_machine;
8234
    cpu_model = NULL;
8235
    initrd_filename = NULL;
8236
    ram_size = 0;
8237
    vga_ram_size = VGA_RAM_SIZE;
8238
#ifdef CONFIG_GDBSTUB
8239
    use_gdbstub = 0;
8240
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
8241
#endif
8242
    snapshot = 0;
8243
    nographic = 0;
8244
    curses = 0;
8245
    kernel_filename = NULL;
8246
    kernel_cmdline = "";
8247
    cyls = heads = secs = 0;
8248
    translation = BIOS_ATA_TRANSLATION_AUTO;
8249
    monitor_device = "vc";
8250

    
8251
    serial_devices[0] = "vc:80Cx24C";
8252
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
8253
        serial_devices[i] = NULL;
8254
    serial_device_index = 0;
8255

    
8256
    parallel_devices[0] = "vc:640x480";
8257
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8258
        parallel_devices[i] = NULL;
8259
    parallel_device_index = 0;
8260

    
8261
    usb_devices_index = 0;
8262

    
8263
    nb_net_clients = 0;
8264
    nb_drives = 0;
8265
    nb_drives_opt = 0;
8266
    hda_index = -1;
8267

    
8268
    nb_nics = 0;
8269

    
8270
    tb_size = 0;
8271
    
8272
    optind = 1;
8273
    for(;;) {
8274
        if (optind >= argc)
8275
            break;
8276
        r = argv[optind];
8277
        if (r[0] != '-') {
8278
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8279
        } else {
8280
            const QEMUOption *popt;
8281

    
8282
            optind++;
8283
            /* Treat --foo the same as -foo.  */
8284
            if (r[1] == '-')
8285
                r++;
8286
            popt = qemu_options;
8287
            for(;;) {
8288
                if (!popt->name) {
8289
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
8290
                            argv[0], r);
8291
                    exit(1);
8292
                }
8293
                if (!strcmp(popt->name, r + 1))
8294
                    break;
8295
                popt++;
8296
            }
8297
            if (popt->flags & HAS_ARG) {
8298
                if (optind >= argc) {
8299
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
8300
                            argv[0], r);
8301
                    exit(1);
8302
                }
8303
                optarg = argv[optind++];
8304
            } else {
8305
                optarg = NULL;
8306
            }
8307

    
8308
            switch(popt->index) {
8309
            case QEMU_OPTION_M:
8310
                machine = find_machine(optarg);
8311
                if (!machine) {
8312
                    QEMUMachine *m;
8313
                    printf("Supported machines are:\n");
8314
                    for(m = first_machine; m != NULL; m = m->next) {
8315
                        printf("%-10s %s%s\n",
8316
                               m->name, m->desc,
8317
                               m == first_machine ? " (default)" : "");
8318
                    }
8319
                    exit(*optarg != '?');
8320
                }
8321
                break;
8322
            case QEMU_OPTION_cpu:
8323
                /* hw initialization will check this */
8324
                if (*optarg == '?') {
8325
/* XXX: implement xxx_cpu_list for targets that still miss it */
8326
#if defined(cpu_list)
8327
                    cpu_list(stdout, &fprintf);
8328
#endif
8329
                    exit(0);
8330
                } else {
8331
                    cpu_model = optarg;
8332
                }
8333
                break;
8334
            case QEMU_OPTION_initrd:
8335
                initrd_filename = optarg;
8336
                break;
8337
            case QEMU_OPTION_hda:
8338
                if (cyls == 0)
8339
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
8340
                else
8341
                    hda_index = drive_add(optarg, HD_ALIAS
8342
                             ",cyls=%d,heads=%d,secs=%d%s",
8343
                             0, cyls, heads, secs,
8344
                             translation == BIOS_ATA_TRANSLATION_LBA ?
8345
                                 ",trans=lba" :
8346
                             translation == BIOS_ATA_TRANSLATION_NONE ?
8347
                                 ",trans=none" : "");
8348
                 break;
8349
            case QEMU_OPTION_hdb:
8350
            case QEMU_OPTION_hdc:
8351
            case QEMU_OPTION_hdd:
8352
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8353
                break;
8354
            case QEMU_OPTION_drive:
8355
                drive_add(NULL, "%s", optarg);
8356
                break;
8357
            case QEMU_OPTION_mtdblock:
8358
                drive_add(optarg, MTD_ALIAS);
8359
                break;
8360
            case QEMU_OPTION_sd:
8361
                drive_add(optarg, SD_ALIAS);
8362
                break;
8363
            case QEMU_OPTION_pflash:
8364
                drive_add(optarg, PFLASH_ALIAS);
8365
                break;
8366
            case QEMU_OPTION_snapshot:
8367
                snapshot = 1;
8368
                break;
8369
            case QEMU_OPTION_hdachs:
8370
                {
8371
                    const char *p;
8372
                    p = optarg;
8373
                    cyls = strtol(p, (char **)&p, 0);
8374
                    if (cyls < 1 || cyls > 16383)
8375
                        goto chs_fail;
8376
                    if (*p != ',')
8377
                        goto chs_fail;
8378
                    p++;
8379
                    heads = strtol(p, (char **)&p, 0);
8380
                    if (heads < 1 || heads > 16)
8381
                        goto chs_fail;
8382
                    if (*p != ',')
8383
                        goto chs_fail;
8384
                    p++;
8385
                    secs = strtol(p, (char **)&p, 0);
8386
                    if (secs < 1 || secs > 63)
8387
                        goto chs_fail;
8388
                    if (*p == ',') {
8389
                        p++;
8390
                        if (!strcmp(p, "none"))
8391
                            translation = BIOS_ATA_TRANSLATION_NONE;
8392
                        else if (!strcmp(p, "lba"))
8393
                            translation = BIOS_ATA_TRANSLATION_LBA;
8394
                        else if (!strcmp(p, "auto"))
8395
                            translation = BIOS_ATA_TRANSLATION_AUTO;
8396
                        else
8397
                            goto chs_fail;
8398
                    } else if (*p != '\0') {
8399
                    chs_fail:
8400
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
8401
                        exit(1);
8402
                    }
8403
                    if (hda_index != -1)
8404
                        snprintf(drives_opt[hda_index].opt,
8405
                                 sizeof(drives_opt[hda_index].opt),
8406
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8407
                                 0, cyls, heads, secs,
8408
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
8409
                                         ",trans=lba" :
8410
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
8411
                                     ",trans=none" : "");
8412
                }
8413
                break;
8414
            case QEMU_OPTION_nographic:
8415
                nographic = 1;
8416
                break;
8417
#ifdef CONFIG_CURSES
8418
            case QEMU_OPTION_curses:
8419
                curses = 1;
8420
                break;
8421
#endif
8422
            case QEMU_OPTION_portrait:
8423
                graphic_rotate = 1;
8424
                break;
8425
            case QEMU_OPTION_kernel:
8426
                kernel_filename = optarg;
8427
                break;
8428
            case QEMU_OPTION_append:
8429
                kernel_cmdline = optarg;
8430
                break;
8431
            case QEMU_OPTION_cdrom:
8432
                drive_add(optarg, CDROM_ALIAS);
8433
                break;
8434
            case QEMU_OPTION_boot:
8435
                boot_devices = optarg;
8436
                /* We just do some generic consistency checks */
8437
                {
8438
                    /* Could easily be extended to 64 devices if needed */
8439
                    const char *p;
8440
                    
8441
                    boot_devices_bitmap = 0;
8442
                    for (p = boot_devices; *p != '\0'; p++) {
8443
                        /* Allowed boot devices are:
8444
                         * a b     : floppy disk drives
8445
                         * c ... f : IDE disk drives
8446
                         * g ... m : machine implementation dependant drives
8447
                         * n ... p : network devices
8448
                         * It's up to each machine implementation to check
8449
                         * if the given boot devices match the actual hardware
8450
                         * implementation and firmware features.
8451
                         */
8452
                        if (*p < 'a' || *p > 'q') {
8453
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
8454
                            exit(1);
8455
                        }
8456
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8457
                            fprintf(stderr,
8458
                                    "Boot device '%c' was given twice\n",*p);
8459
                            exit(1);
8460
                        }
8461
                        boot_devices_bitmap |= 1 << (*p - 'a');
8462
                    }
8463
                }
8464
                break;
8465
            case QEMU_OPTION_fda:
8466
            case QEMU_OPTION_fdb:
8467
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8468
                break;
8469
#ifdef TARGET_I386
8470
            case QEMU_OPTION_no_fd_bootchk:
8471
                fd_bootchk = 0;
8472
                break;
8473
#endif
8474
            case QEMU_OPTION_net:
8475
                if (nb_net_clients >= MAX_NET_CLIENTS) {
8476
                    fprintf(stderr, "qemu: too many network clients\n");
8477
                    exit(1);
8478
                }
8479
                net_clients[nb_net_clients] = optarg;
8480
                nb_net_clients++;
8481
                break;
8482
#ifdef CONFIG_SLIRP
8483
            case QEMU_OPTION_tftp:
8484
                tftp_prefix = optarg;
8485
                break;
8486
            case QEMU_OPTION_bootp:
8487
                bootp_filename = optarg;
8488
                break;
8489
#ifndef _WIN32
8490
            case QEMU_OPTION_smb:
8491
                net_slirp_smb(optarg);
8492
                break;
8493
#endif
8494
            case QEMU_OPTION_redir:
8495
                net_slirp_redir(optarg);
8496
                break;
8497
#endif
8498
#ifdef HAS_AUDIO
8499
            case QEMU_OPTION_audio_help:
8500
                AUD_help ();
8501
                exit (0);
8502
                break;
8503
            case QEMU_OPTION_soundhw:
8504
                select_soundhw (optarg);
8505
                break;
8506
#endif
8507
            case QEMU_OPTION_h:
8508
                help(0);
8509
                break;
8510
            case QEMU_OPTION_m: {
8511
                uint64_t value;
8512
                char *ptr;
8513

    
8514
                value = strtoul(optarg, &ptr, 10);
8515
                switch (*ptr) {
8516
                case 0: case 'M': case 'm':
8517
                    value <<= 20;
8518
                    break;
8519
                case 'G': case 'g':
8520
                    value <<= 30;
8521
                    break;
8522
                default:
8523
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8524
                    exit(1);
8525
                }
8526

    
8527
                /* On 32-bit hosts, QEMU is limited by virtual address space */
8528
                if (value > (2047 << 20)
8529
#ifndef USE_KQEMU
8530
                    && HOST_LONG_BITS == 32
8531
#endif
8532
                    ) {
8533
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8534
                    exit(1);
8535
                }
8536
                if (value != (uint64_t)(ram_addr_t)value) {
8537
                    fprintf(stderr, "qemu: ram size too large\n");
8538
                    exit(1);
8539
                }
8540
                ram_size = value;
8541
                break;
8542
            }
8543
            case QEMU_OPTION_d:
8544
                {
8545
                    int mask;
8546
                    CPULogItem *item;
8547

    
8548
                    mask = cpu_str_to_log_mask(optarg);
8549
                    if (!mask) {
8550
                        printf("Log items (comma separated):\n");
8551
                    for(item = cpu_log_items; item->mask != 0; item++) {
8552
                        printf("%-10s %s\n", item->name, item->help);
8553
                    }
8554
                    exit(1);
8555
                    }
8556
                    cpu_set_log(mask);
8557
                }
8558
                break;
8559
#ifdef CONFIG_GDBSTUB
8560
            case QEMU_OPTION_s:
8561
                use_gdbstub = 1;
8562
                break;
8563
            case QEMU_OPTION_p:
8564
                gdbstub_port = optarg;
8565
                break;
8566
#endif
8567
            case QEMU_OPTION_L:
8568
                bios_dir = optarg;
8569
                break;
8570
            case QEMU_OPTION_bios:
8571
                bios_name = optarg;
8572
                break;
8573
            case QEMU_OPTION_S:
8574
                autostart = 0;
8575
                break;
8576
            case QEMU_OPTION_k:
8577
                keyboard_layout = optarg;
8578
                break;
8579
            case QEMU_OPTION_localtime:
8580
                rtc_utc = 0;
8581
                break;
8582
            case QEMU_OPTION_cirrusvga:
8583
                cirrus_vga_enabled = 1;
8584
                vmsvga_enabled = 0;
8585
                break;
8586
            case QEMU_OPTION_vmsvga:
8587
                cirrus_vga_enabled = 0;
8588
                vmsvga_enabled = 1;
8589
                break;
8590
            case QEMU_OPTION_std_vga:
8591
                cirrus_vga_enabled = 0;
8592
                vmsvga_enabled = 0;
8593
                break;
8594
            case QEMU_OPTION_g:
8595
                {
8596
                    const char *p;
8597
                    int w, h, depth;
8598
                    p = optarg;
8599
                    w = strtol(p, (char **)&p, 10);
8600
                    if (w <= 0) {
8601
                    graphic_error:
8602
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8603
                        exit(1);
8604
                    }
8605
                    if (*p != 'x')
8606
                        goto graphic_error;
8607
                    p++;
8608
                    h = strtol(p, (char **)&p, 10);
8609
                    if (h <= 0)
8610
                        goto graphic_error;
8611
                    if (*p == 'x') {
8612
                        p++;
8613
                        depth = strtol(p, (char **)&p, 10);
8614
                        if (depth != 8 && depth != 15 && depth != 16 &&
8615
                            depth != 24 && depth != 32)
8616
                            goto graphic_error;
8617
                    } else if (*p == '\0') {
8618
                        depth = graphic_depth;
8619
                    } else {
8620
                        goto graphic_error;
8621
                    }
8622

    
8623
                    graphic_width = w;
8624
                    graphic_height = h;
8625
                    graphic_depth = depth;
8626
                }
8627
                break;
8628
            case QEMU_OPTION_echr:
8629
                {
8630
                    char *r;
8631
                    term_escape_char = strtol(optarg, &r, 0);
8632
                    if (r == optarg)
8633
                        printf("Bad argument to echr\n");
8634
                    break;
8635
                }
8636
            case QEMU_OPTION_monitor:
8637
                monitor_device = optarg;
8638
                break;
8639
            case QEMU_OPTION_serial:
8640
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8641
                    fprintf(stderr, "qemu: too many serial ports\n");
8642
                    exit(1);
8643
                }
8644
                serial_devices[serial_device_index] = optarg;
8645
                serial_device_index++;
8646
                break;
8647
            case QEMU_OPTION_parallel:
8648
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8649
                    fprintf(stderr, "qemu: too many parallel ports\n");
8650
                    exit(1);
8651
                }
8652
                parallel_devices[parallel_device_index] = optarg;
8653
                parallel_device_index++;
8654
                break;
8655
            case QEMU_OPTION_loadvm:
8656
                loadvm = optarg;
8657
                break;
8658
            case QEMU_OPTION_full_screen:
8659
                full_screen = 1;
8660
                break;
8661
#ifdef CONFIG_SDL
8662
            case QEMU_OPTION_no_frame:
8663
                no_frame = 1;
8664
                break;
8665
            case QEMU_OPTION_alt_grab:
8666
                alt_grab = 1;
8667
                break;
8668
            case QEMU_OPTION_no_quit:
8669
                no_quit = 1;
8670
                break;
8671
#endif
8672
            case QEMU_OPTION_pidfile:
8673
                pid_file = optarg;
8674
                break;
8675
#ifdef TARGET_I386
8676
            case QEMU_OPTION_win2k_hack:
8677
                win2k_install_hack = 1;
8678
                break;
8679
#endif
8680
#ifdef USE_KQEMU
8681
            case QEMU_OPTION_no_kqemu:
8682
                kqemu_allowed = 0;
8683
                break;
8684
            case QEMU_OPTION_kernel_kqemu:
8685
                kqemu_allowed = 2;
8686
                break;
8687
#endif
8688
            case QEMU_OPTION_usb:
8689
                usb_enabled = 1;
8690
                break;
8691
            case QEMU_OPTION_usbdevice:
8692
                usb_enabled = 1;
8693
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8694
                    fprintf(stderr, "Too many USB devices\n");
8695
                    exit(1);
8696
                }
8697
                usb_devices[usb_devices_index] = optarg;
8698
                usb_devices_index++;
8699
                break;
8700
            case QEMU_OPTION_smp:
8701
                smp_cpus = atoi(optarg);
8702
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8703
                    fprintf(stderr, "Invalid number of CPUs\n");
8704
                    exit(1);
8705
                }
8706
                break;
8707
            case QEMU_OPTION_vnc:
8708
                vnc_display = optarg;
8709
                break;
8710
            case QEMU_OPTION_no_acpi:
8711
                acpi_enabled = 0;
8712
                break;
8713
            case QEMU_OPTION_no_reboot:
8714
                no_reboot = 1;
8715
                break;
8716
            case QEMU_OPTION_no_shutdown:
8717
                no_shutdown = 1;
8718
                break;
8719
            case QEMU_OPTION_show_cursor:
8720
                cursor_hide = 0;
8721
                break;
8722
            case QEMU_OPTION_daemonize:
8723
                daemonize = 1;
8724
                break;
8725
            case QEMU_OPTION_option_rom:
8726
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8727
                    fprintf(stderr, "Too many option ROMs\n");
8728
                    exit(1);
8729
                }
8730
                option_rom[nb_option_roms] = optarg;
8731
                nb_option_roms++;
8732
                break;
8733
            case QEMU_OPTION_semihosting:
8734
                semihosting_enabled = 1;
8735
                break;
8736
            case QEMU_OPTION_name:
8737
                qemu_name = optarg;
8738
                break;
8739
#ifdef TARGET_SPARC
8740
            case QEMU_OPTION_prom_env:
8741
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8742
                    fprintf(stderr, "Too many prom variables\n");
8743
                    exit(1);
8744
                }
8745
                prom_envs[nb_prom_envs] = optarg;
8746
                nb_prom_envs++;
8747
                break;
8748
#endif
8749
#ifdef TARGET_ARM
8750
            case QEMU_OPTION_old_param:
8751
                old_param = 1;
8752
                break;
8753
#endif
8754
            case QEMU_OPTION_clock:
8755
                configure_alarms(optarg);
8756
                break;
8757
            case QEMU_OPTION_startdate:
8758
                {
8759
                    struct tm tm;
8760
                    time_t rtc_start_date;
8761
                    if (!strcmp(optarg, "now")) {
8762
                        rtc_date_offset = -1;
8763
                    } else {
8764
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8765
                               &tm.tm_year,
8766
                               &tm.tm_mon,
8767
                               &tm.tm_mday,
8768
                               &tm.tm_hour,
8769
                               &tm.tm_min,
8770
                               &tm.tm_sec) == 6) {
8771
                            /* OK */
8772
                        } else if (sscanf(optarg, "%d-%d-%d",
8773
                                          &tm.tm_year,
8774
                                          &tm.tm_mon,
8775
                                          &tm.tm_mday) == 3) {
8776
                            tm.tm_hour = 0;
8777
                            tm.tm_min = 0;
8778
                            tm.tm_sec = 0;
8779
                        } else {
8780
                            goto date_fail;
8781
                        }
8782
                        tm.tm_year -= 1900;
8783
                        tm.tm_mon--;
8784
                        rtc_start_date = mktimegm(&tm);
8785
                        if (rtc_start_date == -1) {
8786
                        date_fail:
8787
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8788
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8789
                            exit(1);
8790
                        }
8791
                        rtc_date_offset = time(NULL) - rtc_start_date;
8792
                    }
8793
                }
8794
                break;
8795
            case QEMU_OPTION_tb_size:
8796
                tb_size = strtol(optarg, NULL, 0);
8797
                if (tb_size < 0)
8798
                    tb_size = 0;
8799
                break;
8800
            case QEMU_OPTION_icount:
8801
                use_icount = 1;
8802
                if (strcmp(optarg, "auto") == 0) {
8803
                    icount_time_shift = -1;
8804
                } else {
8805
                    icount_time_shift = strtol(optarg, NULL, 0);
8806
                }
8807
                break;
8808
            }
8809
        }
8810
    }
8811

    
8812
    if (nographic) {
8813
       if (serial_device_index == 0)
8814
           serial_devices[0] = "stdio";
8815
       if (parallel_device_index == 0)
8816
           parallel_devices[0] = "null";
8817
       if (strncmp(monitor_device, "vc", 2) == 0)
8818
           monitor_device = "stdio";
8819
    }
8820

    
8821
#ifndef _WIN32
8822
    if (daemonize) {
8823
        pid_t pid;
8824

    
8825
        if (pipe(fds) == -1)
8826
            exit(1);
8827

    
8828
        pid = fork();
8829
        if (pid > 0) {
8830
            uint8_t status;
8831
            ssize_t len;
8832

    
8833
            close(fds[1]);
8834

    
8835
        again:
8836
            len = read(fds[0], &status, 1);
8837
            if (len == -1 && (errno == EINTR))
8838
                goto again;
8839

    
8840
            if (len != 1)
8841
                exit(1);
8842
            else if (status == 1) {
8843
                fprintf(stderr, "Could not acquire pidfile\n");
8844
                exit(1);
8845
            } else
8846
                exit(0);
8847
        } else if (pid < 0)
8848
            exit(1);
8849

    
8850
        setsid();
8851

    
8852
        pid = fork();
8853
        if (pid > 0)
8854
            exit(0);
8855
        else if (pid < 0)
8856
            exit(1);
8857

    
8858
        umask(027);
8859

    
8860
        signal(SIGTSTP, SIG_IGN);
8861
        signal(SIGTTOU, SIG_IGN);
8862
        signal(SIGTTIN, SIG_IGN);
8863
    }
8864
#endif
8865

    
8866
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8867
        if (daemonize) {
8868
            uint8_t status = 1;
8869
            write(fds[1], &status, 1);
8870
        } else
8871
            fprintf(stderr, "Could not acquire pid file\n");
8872
        exit(1);
8873
    }
8874

    
8875
#ifdef USE_KQEMU
8876
    if (smp_cpus > 1)
8877
        kqemu_allowed = 0;
8878
#endif
8879
    linux_boot = (kernel_filename != NULL);
8880
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8881

    
8882
    if (!linux_boot && net_boot == 0 &&
8883
        !machine->nodisk_ok && nb_drives_opt == 0)
8884
        help(1);
8885

    
8886
    if (!linux_boot && *kernel_cmdline != '\0') {
8887
        fprintf(stderr, "-append only allowed with -kernel option\n");
8888
        exit(1);
8889
    }
8890

    
8891
    if (!linux_boot && initrd_filename != NULL) {
8892
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
8893
        exit(1);
8894
    }
8895

    
8896
    /* boot to floppy or the default cd if no hard disk defined yet */
8897
    if (!boot_devices[0]) {
8898
        boot_devices = "cad";
8899
    }
8900
    setvbuf(stdout, NULL, _IOLBF, 0);
8901

    
8902
    init_timers();
8903
    init_timer_alarm();
8904
    qemu_aio_init();
8905
    if (use_icount && icount_time_shift < 0) {
8906
        use_icount = 2;
8907
        /* 125MIPS seems a reasonable initial guess at the guest speed.
8908
           It will be corrected fairly quickly anyway.  */
8909
        icount_time_shift = 3;
8910
        init_icount_adjust();
8911
    }
8912

    
8913
#ifdef _WIN32
8914
    socket_init();
8915
#endif
8916

    
8917
    /* init network clients */
8918
    if (nb_net_clients == 0) {
8919
        /* if no clients, we use a default config */
8920
        net_clients[0] = "nic";
8921
        net_clients[1] = "user";
8922
        nb_net_clients = 2;
8923
    }
8924

    
8925
    for(i = 0;i < nb_net_clients; i++) {
8926
        if (net_client_parse(net_clients[i]) < 0)
8927
            exit(1);
8928
    }
8929
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8930
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8931
            continue;
8932
        if (vlan->nb_guest_devs == 0)
8933
            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
8934
        if (vlan->nb_host_devs == 0)
8935
            fprintf(stderr,
8936
                    "Warning: vlan %d is not connected to host network\n",
8937
                    vlan->id);
8938
    }
8939

    
8940
#ifdef TARGET_I386
8941
    /* XXX: this should be moved in the PC machine instantiation code */
8942
    if (net_boot != 0) {
8943
        int netroms = 0;
8944
        for (i = 0; i < nb_nics && i < 4; i++) {
8945
            const char *model = nd_table[i].model;
8946
            char buf[1024];
8947
            if (net_boot & (1 << i)) {
8948
                if (model == NULL)
8949
                    model = "ne2k_pci";
8950
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8951
                if (get_image_size(buf) > 0) {
8952
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8953
                        fprintf(stderr, "Too many option ROMs\n");
8954
                        exit(1);
8955
                    }
8956
                    option_rom[nb_option_roms] = strdup(buf);
8957
                    nb_option_roms++;
8958
                    netroms++;
8959
                }
8960
            }
8961
        }
8962
        if (netroms == 0) {
8963
            fprintf(stderr, "No valid PXE rom found for network device\n");
8964
            exit(1);
8965
        }
8966
    }
8967
#endif
8968

    
8969
    /* init the memory */
8970
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
8971

    
8972
    if (machine->ram_require & RAMSIZE_FIXED) {
8973
        if (ram_size > 0) {
8974
            if (ram_size < phys_ram_size) {
8975
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
8976
                                machine->name, (unsigned long long) phys_ram_size);
8977
                exit(-1);
8978
            }
8979

    
8980
            phys_ram_size = ram_size;
8981
        } else
8982
            ram_size = phys_ram_size;
8983
    } else {
8984
        if (ram_size == 0)
8985
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8986

    
8987
        phys_ram_size += ram_size;
8988
    }
8989

    
8990
    phys_ram_base = qemu_vmalloc(phys_ram_size);
8991
    if (!phys_ram_base) {
8992
        fprintf(stderr, "Could not allocate physical memory\n");
8993
        exit(1);
8994
    }
8995

    
8996
    /* init the dynamic translator */
8997
    cpu_exec_init_all(tb_size * 1024 * 1024);
8998

    
8999
    bdrv_init();
9000

    
9001
    /* we always create the cdrom drive, even if no disk is there */
9002

    
9003
    if (nb_drives_opt < MAX_DRIVES)
9004
        drive_add(NULL, CDROM_ALIAS);
9005

    
9006
    /* we always create at least one floppy */
9007

    
9008
    if (nb_drives_opt < MAX_DRIVES)
9009
        drive_add(NULL, FD_ALIAS, 0);
9010

    
9011
    /* we always create one sd slot, even if no card is in it */
9012

    
9013
    if (nb_drives_opt < MAX_DRIVES)
9014
        drive_add(NULL, SD_ALIAS);
9015

    
9016
    /* open the virtual block devices */
9017

    
9018
    for(i = 0; i < nb_drives_opt; i++)
9019
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9020
            exit(1);
9021

    
9022
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9023
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9024

    
9025
    /* terminal init */
9026
    memset(&display_state, 0, sizeof(display_state));
9027
    if (nographic) {
9028
        if (curses) {
9029
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9030
            exit(1);
9031
        }
9032
        /* nearly nothing to do */
9033
        dumb_display_init(ds);
9034
    } else if (vnc_display != NULL) {
9035
        vnc_display_init(ds);
9036
        if (vnc_display_open(ds, vnc_display) < 0)
9037
            exit(1);
9038
    } else
9039
#if defined(CONFIG_CURSES)
9040
    if (curses) {
9041
        curses_display_init(ds, full_screen);
9042
    } else
9043
#endif
9044
    {
9045
#if defined(CONFIG_SDL)
9046
        sdl_display_init(ds, full_screen, no_frame);
9047
#elif defined(CONFIG_COCOA)
9048
        cocoa_display_init(ds, full_screen);
9049
#else
9050
        dumb_display_init(ds);
9051
#endif
9052
    }
9053

    
9054
    /* Maintain compatibility with multiple stdio monitors */
9055

    
9056
    has_monitor = 0;
9057
    if (!strcmp(monitor_device,"stdio")) {
9058
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9059
            const char *devname = serial_devices[i];
9060
            if (devname && !strcmp(devname,"mon:stdio")) {
9061
                monitor_device = NULL;
9062
                break;
9063
            } else if (devname && !strcmp(devname,"stdio")) {
9064
                monitor_device = NULL;
9065
                serial_devices[i] = "mon:stdio";
9066
                break;
9067
            }
9068
        }
9069
        has_monitor = 1;
9070
    }
9071
    if (monitor_device) {
9072
        monitor_hd = qemu_chr_open(monitor_device);
9073
        if (!monitor_hd) {
9074
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9075
            exit(1);
9076
        }
9077
        monitor_init(monitor_hd, !nographic);
9078
        has_monitor = 1;
9079
    }
9080

    
9081
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9082
        const char *devname = serial_devices[i];
9083
        if (devname && strcmp(devname, "none")) {
9084
            serial_hds[i] = qemu_chr_open(devname);
9085
            if (!serial_hds[i]) {
9086
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
9087
                        devname);
9088
                exit(1);
9089
            }
9090
            if (strstart(devname, "vc", 0))
9091
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9092
        }
9093
    }
9094

    
9095
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9096
        const char *devname = parallel_devices[i];
9097
        if (devname && strcmp(devname, "none")) {
9098
            parallel_hds[i] = qemu_chr_open(devname);
9099
            if (!parallel_hds[i]) {
9100
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9101
                        devname);
9102
                exit(1);
9103
            }
9104
            if (strstart(devname, "vc", 0))
9105
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9106
        }
9107
    }
9108

    
9109
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
9110
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9111

    
9112
    /* init USB devices */
9113
    if (usb_enabled) {
9114
        for(i = 0; i < usb_devices_index; i++) {
9115
            if (usb_device_add(usb_devices[i]) < 0) {
9116
                fprintf(stderr, "Warning: could not add USB device %s\n",
9117
                        usb_devices[i]);
9118
            }
9119
        }
9120
    }
9121

    
9122
    if (display_state.dpy_refresh) {
9123
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9124
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9125
    }
9126

    
9127
#ifdef CONFIG_GDBSTUB
9128
    if (use_gdbstub) {
9129
        /* XXX: use standard host:port notation and modify options
9130
           accordingly. */
9131
        if (gdbserver_start(gdbstub_port) < 0) {
9132
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9133
                    gdbstub_port);
9134
            exit(1);
9135
        }
9136
    }
9137
#endif
9138

    
9139
    read_passwords();
9140

    
9141
    if (has_monitor)
9142
        monitor_start_input();
9143

    
9144
    if (loadvm)
9145
        do_loadvm(loadvm);
9146

    
9147
    {
9148
        /* XXX: simplify init */
9149
        if (autostart) {
9150
            vm_start();
9151
        }
9152
    }
9153

    
9154
    if (daemonize) {
9155
        uint8_t status = 0;
9156
        ssize_t len;
9157
        int fd;
9158

    
9159
    again1:
9160
        len = write(fds[1], &status, 1);
9161
        if (len == -1 && (errno == EINTR))
9162
            goto again1;
9163

    
9164
        if (len != 1)
9165
            exit(1);
9166

    
9167
        chdir("/");
9168
        TFR(fd = open("/dev/null", O_RDWR));
9169
        if (fd == -1)
9170
            exit(1);
9171

    
9172
        dup2(fd, 0);
9173
        dup2(fd, 1);
9174
        dup2(fd, 2);
9175

    
9176
        close(fd);
9177
    }
9178

    
9179
    main_loop();
9180
    quit_timers();
9181

    
9182
#if !defined(_WIN32)
9183
    /* close network clients */
9184
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9185
        VLANClientState *vc;
9186

    
9187
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9188
            if (vc->fd_read == tap_receive) {
9189
                char ifname[64];
9190
                TAPState *s = vc->opaque;
9191

    
9192
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9193
                    s->down_script[0])
9194
                    launch_script(s->down_script, ifname, s->fd);
9195
            }
9196
#if defined(CONFIG_VDE)
9197
            if (vc->fd_read == vde_from_qemu) {
9198
                VDEState *s = vc->opaque;
9199
                vde_close(s->vde);
9200
            }
9201
#endif
9202
        }
9203
    }
9204
#endif
9205
    return 0;
9206
}