Statistics
| Branch: | Revision:

root / vl.c @ 83ab7950

History | View | Annotate | Download (238.3 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
#if !defined(__APPLE__) && !defined(__OpenBSD__)
65
#include <libutil.h>
66
#endif
67
#ifdef __OpenBSD__
68
#include <net/if.h>
69
#endif
70
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
71
#include <freebsd/stdlib.h>
72
#else
73
#ifndef __sun__
74
#include <linux/if.h>
75
#include <linux/if_tun.h>
76
#include <pty.h>
77
#include <malloc.h>
78
#include <linux/rtc.h>
79

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

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

    
108
#if defined(CONFIG_SLIRP)
109
#include "libslirp.h"
110
#endif
111

    
112
#if defined(CONFIG_VDE)
113
#include <libvdeplug.h>
114
#endif
115

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

    
124
#include "qemu_socket.h"
125

    
126
#ifdef CONFIG_SDL
127
#ifdef __APPLE__
128
#include <SDL/SDL.h>
129
#endif
130
#endif /* CONFIG_SDL */
131

    
132
#ifdef CONFIG_COCOA
133
#undef main
134
#define main qemu_main
135
#endif /* CONFIG_COCOA */
136

    
137
#include "disas.h"
138

    
139
#include "exec-all.h"
140

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

    
149
//#define DEBUG_UNUSED_IOPORT
150
//#define DEBUG_IOPORT
151

    
152
#ifdef TARGET_PPC
153
#define DEFAULT_RAM_SIZE 144
154
#else
155
#define DEFAULT_RAM_SIZE 128
156
#endif
157
/* in ms */
158
#define GUI_REFRESH_INTERVAL 30
159

    
160
/* Max number of USB devices that can be specified on the commandline.  */
161
#define MAX_USB_CMDLINE 8
162

    
163
/* XXX: use a two level table to limit memory usage */
164
#define MAX_IOPORTS 65536
165

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

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

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

    
260
/***********************************************************/
261
/* x86 ISA bus support */
262

    
263
target_phys_addr_t isa_mem_base = 0;
264
PicState2 *isa_pic;
265

    
266
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
267
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
268

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

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

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

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

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

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

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

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

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

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

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

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

    
392
void isa_unassign_ioport(int start, int length)
393
{
394
    int i;
395

    
396
    for(i = start; i < start + length; i++) {
397
        ioport_read_table[0][i] = default_ioport_readb;
398
        ioport_read_table[1][i] = default_ioport_readw;
399
        ioport_read_table[2][i] = default_ioport_readl;
400

    
401
        ioport_write_table[0][i] = default_ioport_writeb;
402
        ioport_write_table[1][i] = default_ioport_writew;
403
        ioport_write_table[2][i] = default_ioport_writel;
404
    }
405
}
406

    
407
/***********************************************************/
408

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

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

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

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

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

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

    
493
/***********************************************************/
494
void hw_error(const char *fmt, ...)
495
{
496
    va_list ap;
497
    CPUState *env;
498

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

    
515
/***********************************************************/
516
/* keyboard/mouse */
517

    
518
static QEMUPutKBDEvent *qemu_put_kbd_event;
519
static void *qemu_put_kbd_event_opaque;
520
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
521
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
522

    
523
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
524
{
525
    qemu_put_kbd_event_opaque = opaque;
526
    qemu_put_kbd_event = func;
527
}
528

    
529
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
530
                                                void *opaque, int absolute,
531
                                                const char *name)
532
{
533
    QEMUPutMouseEntry *s, *cursor;
534

    
535
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
536
    if (!s)
537
        return NULL;
538

    
539
    s->qemu_put_mouse_event = func;
540
    s->qemu_put_mouse_event_opaque = opaque;
541
    s->qemu_put_mouse_event_absolute = absolute;
542
    s->qemu_put_mouse_event_name = qemu_strdup(name);
543
    s->next = NULL;
544

    
545
    if (!qemu_put_mouse_event_head) {
546
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
547
        return s;
548
    }
549

    
550
    cursor = qemu_put_mouse_event_head;
551
    while (cursor->next != NULL)
552
        cursor = cursor->next;
553

    
554
    cursor->next = s;
555
    qemu_put_mouse_event_current = s;
556

    
557
    return s;
558
}
559

    
560
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
561
{
562
    QEMUPutMouseEntry *prev = NULL, *cursor;
563

    
564
    if (!qemu_put_mouse_event_head || entry == NULL)
565
        return;
566

    
567
    cursor = qemu_put_mouse_event_head;
568
    while (cursor != NULL && cursor != entry) {
569
        prev = cursor;
570
        cursor = cursor->next;
571
    }
572

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

    
584
    prev->next = entry->next;
585

    
586
    if (qemu_put_mouse_event_current == entry)
587
        qemu_put_mouse_event_current = prev;
588

    
589
    qemu_free(entry->qemu_put_mouse_event_name);
590
    qemu_free(entry);
591
}
592

    
593
void kbd_put_keycode(int keycode)
594
{
595
    if (qemu_put_kbd_event) {
596
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
597
    }
598
}
599

    
600
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
601
{
602
    QEMUPutMouseEvent *mouse_event;
603
    void *mouse_event_opaque;
604
    int width;
605

    
606
    if (!qemu_put_mouse_event_current) {
607
        return;
608
    }
609

    
610
    mouse_event =
611
        qemu_put_mouse_event_current->qemu_put_mouse_event;
612
    mouse_event_opaque =
613
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
614

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

    
629
int kbd_mouse_is_absolute(void)
630
{
631
    if (!qemu_put_mouse_event_current)
632
        return 0;
633

    
634
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
635
}
636

    
637
void do_info_mice(void)
638
{
639
    QEMUPutMouseEntry *cursor;
640
    int index = 0;
641

    
642
    if (!qemu_put_mouse_event_head) {
643
        term_printf("No mouse devices connected\n");
644
        return;
645
    }
646

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

    
658
void do_mouse_set(int index)
659
{
660
    QEMUPutMouseEntry *cursor;
661
    int i = 0;
662

    
663
    if (!qemu_put_mouse_event_head) {
664
        term_printf("No mouse devices connected\n");
665
        return;
666
    }
667

    
668
    cursor = qemu_put_mouse_event_head;
669
    while (cursor != NULL && index != i) {
670
        i++;
671
        cursor = cursor->next;
672
    }
673

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

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

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

    
704
/***********************************************************/
705
/* real time host monotonic timer */
706

    
707
#define QEMU_TIMER_BASE 1000000000LL
708

    
709
#ifdef WIN32
710

    
711
static int64_t clock_freq;
712

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

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

    
732
#else
733

    
734
static int use_rt_clock;
735

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

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

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

    
782
/***********************************************************/
783
/* guest cycle counter */
784

    
785
static int64_t cpu_ticks_prev;
786
static int64_t cpu_ticks_offset;
787
static int64_t cpu_clock_offset;
788
static int cpu_ticks_enabled;
789

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

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

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

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

    
844
/***********************************************************/
845
/* timers */
846

    
847
#define QEMU_TIMER_REALTIME 0
848
#define QEMU_TIMER_VIRTUAL  1
849

    
850
struct QEMUClock {
851
    int type;
852
    /* XXX: add frequency */
853
};
854

    
855
struct QEMUTimer {
856
    QEMUClock *clock;
857
    int64_t expire_time;
858
    QEMUTimerCB *cb;
859
    void *opaque;
860
    struct QEMUTimer *next;
861
};
862

    
863
struct qemu_alarm_timer {
864
    char const *name;
865
    unsigned int flags;
866

    
867
    int (*start)(struct qemu_alarm_timer *t);
868
    void (*stop)(struct qemu_alarm_timer *t);
869
    void (*rearm)(struct qemu_alarm_timer *t);
870
    void *priv;
871
};
872

    
873
#define ALARM_FLAG_DYNTICKS  0x1
874
#define ALARM_FLAG_EXPIRED   0x2
875

    
876
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
877
{
878
    return t->flags & ALARM_FLAG_DYNTICKS;
879
}
880

    
881
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
882
{
883
    if (!alarm_has_dynticks(t))
884
        return;
885

    
886
    t->rearm(t);
887
}
888

    
889
/* TODO: MIN_TIMER_REARM_US should be optimized */
890
#define MIN_TIMER_REARM_US 250
891

    
892
static struct qemu_alarm_timer *alarm_timer;
893

    
894
#ifdef _WIN32
895

    
896
struct qemu_alarm_win32 {
897
    MMRESULT timerId;
898
    HANDLE host_alarm;
899
    unsigned int period;
900
} alarm_win32_data = {0, NULL, -1};
901

    
902
static int win32_start_timer(struct qemu_alarm_timer *t);
903
static void win32_stop_timer(struct qemu_alarm_timer *t);
904
static void win32_rearm_timer(struct qemu_alarm_timer *t);
905

    
906
#else
907

    
908
static int unix_start_timer(struct qemu_alarm_timer *t);
909
static void unix_stop_timer(struct qemu_alarm_timer *t);
910

    
911
#ifdef __linux__
912

    
913
static int dynticks_start_timer(struct qemu_alarm_timer *t);
914
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
915
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
916

    
917
static int hpet_start_timer(struct qemu_alarm_timer *t);
918
static void hpet_stop_timer(struct qemu_alarm_timer *t);
919

    
920
static int rtc_start_timer(struct qemu_alarm_timer *t);
921
static void rtc_stop_timer(struct qemu_alarm_timer *t);
922

    
923
#endif /* __linux__ */
924

    
925
#endif /* _WIN32 */
926

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

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

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

    
963
static void icount_adjust_rt(void * opaque)
964
{
965
    qemu_mod_timer(icount_rt_timer,
966
                   qemu_get_clock(rt_clock) + 1000);
967
    icount_adjust();
968
}
969

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

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

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

    
1012
static void show_available_alarms(void)
1013
{
1014
    int i;
1015

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

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

    
1030
    if (!strcmp(opt, "?")) {
1031
        show_available_alarms();
1032
        exit(0);
1033
    }
1034

    
1035
    arg = strdup(opt);
1036

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

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

    
1050
        if (i < cur)
1051
            /* Ignore */
1052
            goto next;
1053

    
1054
        /* Swap */
1055
        tmp = alarm_timers[i];
1056
        alarm_timers[i] = alarm_timers[cur];
1057
        alarm_timers[cur] = tmp;
1058

    
1059
        cur++;
1060
next:
1061
        name = strtok(NULL, ",");
1062
    }
1063

    
1064
    free(arg);
1065

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

    
1076
QEMUClock *rt_clock;
1077
QEMUClock *vm_clock;
1078

    
1079
static QEMUTimer *active_timers[2];
1080

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

    
1091
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1092
{
1093
    QEMUTimer *ts;
1094

    
1095
    ts = qemu_mallocz(sizeof(QEMUTimer));
1096
    ts->clock = clock;
1097
    ts->cb = cb;
1098
    ts->opaque = opaque;
1099
    return ts;
1100
}
1101

    
1102
void qemu_free_timer(QEMUTimer *ts)
1103
{
1104
    qemu_free(ts);
1105
}
1106

    
1107
/* stop a timer, but do not dealloc it */
1108
void qemu_del_timer(QEMUTimer *ts)
1109
{
1110
    QEMUTimer **pt, *t;
1111

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

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

    
1133
    qemu_del_timer(ts);
1134

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

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

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

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

    
1180
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1181
{
1182
    QEMUTimer *ts;
1183

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

    
1192
        /* run the callback (the timer list can be modified) */
1193
        ts->cb(ts->opaque);
1194
    }
1195
}
1196

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

    
1212
static void init_timers(void)
1213
{
1214
    init_get_clock();
1215
    ticks_per_sec = QEMU_TIMER_BASE;
1216
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1217
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1218
}
1219

    
1220
/* save a timer */
1221
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1222
{
1223
    uint64_t expire_time;
1224

    
1225
    if (qemu_timer_pending(ts)) {
1226
        expire_time = ts->expire_time;
1227
    } else {
1228
        expire_time = -1;
1229
    }
1230
    qemu_put_be64(f, expire_time);
1231
}
1232

    
1233
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1234
{
1235
    uint64_t expire_time;
1236

    
1237
    expire_time = qemu_get_be64(f);
1238
    if (expire_time != -1) {
1239
        qemu_mod_timer(ts, expire_time);
1240
    } else {
1241
        qemu_del_timer(ts);
1242
    }
1243
}
1244

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

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

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

    
1318
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1319

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

    
1333
static int64_t qemu_next_deadline(void)
1334
{
1335
    int64_t delta;
1336

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

    
1345
    if (delta < 0)
1346
        delta = 0;
1347

    
1348
    return delta;
1349
}
1350

    
1351
static uint64_t qemu_next_deadline_dyntick(void)
1352
{
1353
    int64_t delta;
1354
    int64_t rtdelta;
1355

    
1356
    if (use_icount)
1357
        delta = INT32_MAX;
1358
    else
1359
        delta = (qemu_next_deadline() + 999) / 1000;
1360

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

    
1368
    if (delta < MIN_TIMER_REARM_US)
1369
        delta = MIN_TIMER_REARM_US;
1370

    
1371
    return delta;
1372
}
1373

    
1374
#ifndef _WIN32
1375

    
1376
#if defined(__linux__)
1377

    
1378
#define RTC_FREQ 1024
1379

    
1380
static void enable_sigio_timer(int fd)
1381
{
1382
    struct sigaction act;
1383

    
1384
    /* timer signal */
1385
    sigfillset(&act.sa_mask);
1386
    act.sa_flags = 0;
1387
    act.sa_handler = host_alarm_handler;
1388

    
1389
    sigaction(SIGIO, &act, NULL);
1390
    fcntl(fd, F_SETFL, O_ASYNC);
1391
    fcntl(fd, F_SETOWN, getpid());
1392
}
1393

    
1394
static int hpet_start_timer(struct qemu_alarm_timer *t)
1395
{
1396
    struct hpet_info info;
1397
    int r, fd;
1398

    
1399
    fd = open("/dev/hpet", O_RDONLY);
1400
    if (fd < 0)
1401
        return -1;
1402

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

    
1412
    /* Check capabilities */
1413
    r = ioctl(fd, HPET_INFO, &info);
1414
    if (r < 0)
1415
        goto fail;
1416

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

    
1422
    /* Enable interrupt */
1423
    r = ioctl(fd, HPET_IE_ON, 0);
1424
    if (r < 0)
1425
        goto fail;
1426

    
1427
    enable_sigio_timer(fd);
1428
    t->priv = (void *)(long)fd;
1429

    
1430
    return 0;
1431
fail:
1432
    close(fd);
1433
    return -1;
1434
}
1435

    
1436
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1437
{
1438
    int fd = (long)t->priv;
1439

    
1440
    close(fd);
1441
}
1442

    
1443
static int rtc_start_timer(struct qemu_alarm_timer *t)
1444
{
1445
    int rtc_fd;
1446
    unsigned long current_rtc_freq = 0;
1447

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

    
1465
    enable_sigio_timer(rtc_fd);
1466

    
1467
    t->priv = (void *)(long)rtc_fd;
1468

    
1469
    return 0;
1470
}
1471

    
1472
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1473
{
1474
    int rtc_fd = (long)t->priv;
1475

    
1476
    close(rtc_fd);
1477
}
1478

    
1479
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1480
{
1481
    struct sigevent ev;
1482
    timer_t host_timer;
1483
    struct sigaction act;
1484

    
1485
    sigfillset(&act.sa_mask);
1486
    act.sa_flags = 0;
1487
    act.sa_handler = host_alarm_handler;
1488

    
1489
    sigaction(SIGALRM, &act, NULL);
1490

    
1491
    ev.sigev_value.sival_int = 0;
1492
    ev.sigev_notify = SIGEV_SIGNAL;
1493
    ev.sigev_signo = SIGALRM;
1494

    
1495
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1496
        perror("timer_create");
1497

    
1498
        /* disable dynticks */
1499
        fprintf(stderr, "Dynamic Ticks disabled\n");
1500

    
1501
        return -1;
1502
    }
1503

    
1504
    t->priv = (void *)host_timer;
1505

    
1506
    return 0;
1507
}
1508

    
1509
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1510
{
1511
    timer_t host_timer = (timer_t)t->priv;
1512

    
1513
    timer_delete(host_timer);
1514
}
1515

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

    
1523
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1524
                !active_timers[QEMU_TIMER_VIRTUAL])
1525
        return;
1526

    
1527
    nearest_delta_us = qemu_next_deadline_dyntick();
1528

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

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

    
1550
#endif /* defined(__linux__) */
1551

    
1552
static int unix_start_timer(struct qemu_alarm_timer *t)
1553
{
1554
    struct sigaction act;
1555
    struct itimerval itv;
1556
    int err;
1557

    
1558
    /* timer signal */
1559
    sigfillset(&act.sa_mask);
1560
    act.sa_flags = 0;
1561
    act.sa_handler = host_alarm_handler;
1562

    
1563
    sigaction(SIGALRM, &act, NULL);
1564

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

    
1571
    err = setitimer(ITIMER_REAL, &itv, NULL);
1572
    if (err)
1573
        return -1;
1574

    
1575
    return 0;
1576
}
1577

    
1578
static void unix_stop_timer(struct qemu_alarm_timer *t)
1579
{
1580
    struct itimerval itv;
1581

    
1582
    memset(&itv, 0, sizeof(itv));
1583
    setitimer(ITIMER_REAL, &itv, NULL);
1584
}
1585

    
1586
#endif /* !defined(_WIN32) */
1587

    
1588
#ifdef _WIN32
1589

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

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

    
1602
    memset(&tc, 0, sizeof(tc));
1603
    timeGetDevCaps(&tc, sizeof(tc));
1604

    
1605
    if (data->period < tc.wPeriodMin)
1606
        data->period = tc.wPeriodMin;
1607

    
1608
    timeBeginPeriod(data->period);
1609

    
1610
    flags = TIME_CALLBACK_FUNCTION;
1611
    if (alarm_has_dynticks(t))
1612
        flags |= TIME_ONESHOT;
1613
    else
1614
        flags |= TIME_PERIODIC;
1615

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

    
1622
    if (!data->timerId) {
1623
        perror("Failed to initialize win32 alarm timer");
1624

    
1625
        timeEndPeriod(data->period);
1626
        CloseHandle(data->host_alarm);
1627
        return -1;
1628
    }
1629

    
1630
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1631

    
1632
    return 0;
1633
}
1634

    
1635
static void win32_stop_timer(struct qemu_alarm_timer *t)
1636
{
1637
    struct qemu_alarm_win32 *data = t->priv;
1638

    
1639
    timeKillEvent(data->timerId);
1640
    timeEndPeriod(data->period);
1641

    
1642
    CloseHandle(data->host_alarm);
1643
}
1644

    
1645
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1646
{
1647
    struct qemu_alarm_win32 *data = t->priv;
1648
    uint64_t nearest_delta_us;
1649

    
1650
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1651
                !active_timers[QEMU_TIMER_VIRTUAL])
1652
        return;
1653

    
1654
    nearest_delta_us = qemu_next_deadline_dyntick();
1655
    nearest_delta_us /= 1000;
1656

    
1657
    timeKillEvent(data->timerId);
1658

    
1659
    data->timerId = timeSetEvent(1,
1660
                        data->period,
1661
                        host_alarm_handler,
1662
                        (DWORD)t,
1663
                        TIME_ONESHOT | TIME_PERIODIC);
1664

    
1665
    if (!data->timerId) {
1666
        perror("Failed to re-arm win32 alarm timer");
1667

    
1668
        timeEndPeriod(data->period);
1669
        CloseHandle(data->host_alarm);
1670
        exit(1);
1671
    }
1672
}
1673

    
1674
#endif /* _WIN32 */
1675

    
1676
static void init_timer_alarm(void)
1677
{
1678
    struct qemu_alarm_timer *t;
1679
    int i, err = -1;
1680

    
1681
    for (i = 0; alarm_timers[i].name; i++) {
1682
        t = &alarm_timers[i];
1683

    
1684
        err = t->start(t);
1685
        if (!err)
1686
            break;
1687
    }
1688

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

    
1695
    alarm_timer = t;
1696
}
1697

    
1698
static void quit_timers(void)
1699
{
1700
    alarm_timer->stop(alarm_timer);
1701
    alarm_timer = NULL;
1702
}
1703

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

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

    
1723
    memcpy(tm, ret, sizeof(struct tm));
1724
}
1725

    
1726
int qemu_timedate_diff(struct tm *tm)
1727
{
1728
    time_t seconds;
1729

    
1730
    if (rtc_date_offset == -1)
1731
        if (rtc_utc)
1732
            seconds = mktimegm(tm);
1733
        else
1734
            seconds = mktime(tm);
1735
    else
1736
        seconds = mktimegm(tm) + rtc_date_offset;
1737

    
1738
    return seconds - time(NULL);
1739
}
1740

    
1741
/***********************************************************/
1742
/* character device */
1743

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

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

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

    
1767
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1768
{
1769
    return s->chr_write(s, buf, len);
1770
}
1771

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

    
1779
int qemu_chr_can_read(CharDriverState *s)
1780
{
1781
    if (!s->chr_can_read)
1782
        return 0;
1783
    return s->chr_can_read(s->handler_opaque);
1784
}
1785

    
1786
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1787
{
1788
    s->chr_read(s->handler_opaque, buf, len);
1789
}
1790

    
1791
void qemu_chr_accept_input(CharDriverState *s)
1792
{
1793
    if (s->chr_accept_input)
1794
        s->chr_accept_input(s);
1795
}
1796

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

    
1807
void qemu_chr_send_event(CharDriverState *s, int event)
1808
{
1809
    if (s->chr_send_event)
1810
        s->chr_send_event(s, event);
1811
}
1812

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

    
1827
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1828
{
1829
    return len;
1830
}
1831

    
1832
static CharDriverState *qemu_chr_open_null(void)
1833
{
1834
    CharDriverState *chr;
1835

    
1836
    chr = qemu_mallocz(sizeof(CharDriverState));
1837
    if (!chr)
1838
        return NULL;
1839
    chr->chr_write = null_chr_write;
1840
    return chr;
1841
}
1842

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

    
1863

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

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

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

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

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

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

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

    
1984
static void mux_chr_accept_input(CharDriverState *chr)
1985
{
1986
    int m = chr->focus;
1987
    MuxDriver *d = chr->opaque;
1988

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

    
1997
static int mux_chr_can_read(void *opaque)
1998
{
1999
    CharDriverState *chr = opaque;
2000
    MuxDriver *d = chr->opaque;
2001

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

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

    
2016
    mux_chr_accept_input (opaque);
2017

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

    
2029
static void mux_chr_event(void *opaque, int event)
2030
{
2031
    CharDriverState *chr = opaque;
2032
    MuxDriver *d = chr->opaque;
2033
    int i;
2034

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

    
2041
static void mux_chr_update_read_handler(CharDriverState *chr)
2042
{
2043
    MuxDriver *d = chr->opaque;
2044

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

    
2062
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2063
{
2064
    CharDriverState *chr;
2065
    MuxDriver *d;
2066

    
2067
    chr = qemu_mallocz(sizeof(CharDriverState));
2068
    if (!chr)
2069
        return NULL;
2070
    d = qemu_mallocz(sizeof(MuxDriver));
2071
    if (!d) {
2072
        free(chr);
2073
        return NULL;
2074
    }
2075

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

    
2085

    
2086
#ifdef _WIN32
2087

    
2088
static void socket_cleanup(void)
2089
{
2090
    WSACleanup();
2091
}
2092

    
2093
static int socket_init(void)
2094
{
2095
    WSADATA Data;
2096
    int ret, err;
2097

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

    
2108
static int send_all(int fd, const uint8_t *buf, int len1)
2109
{
2110
    int ret, len;
2111

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

    
2131
void socket_set_nonblock(int fd)
2132
{
2133
    unsigned long opt = 1;
2134
    ioctlsocket(fd, FIONBIO, &opt);
2135
}
2136

    
2137
#else
2138

    
2139
static int unix_write(int fd, const uint8_t *buf, int len1)
2140
{
2141
    int ret, len;
2142

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

    
2159
static inline int send_all(int fd, const uint8_t *buf, int len1)
2160
{
2161
    return unix_write(fd, buf, len1);
2162
}
2163

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

    
2172
#ifndef _WIN32
2173

    
2174
typedef struct {
2175
    int fd_in, fd_out;
2176
    int max_size;
2177
} FDCharDriver;
2178

    
2179
#define STDIO_MAX_CLIENTS 1
2180
static int stdio_nb_clients = 0;
2181

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

    
2188
static int fd_chr_read_poll(void *opaque)
2189
{
2190
    CharDriverState *chr = opaque;
2191
    FDCharDriver *s = chr->opaque;
2192

    
2193
    s->max_size = qemu_chr_can_read(chr);
2194
    return s->max_size;
2195
}
2196

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

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

    
2220
static void fd_chr_update_read_handler(CharDriverState *chr)
2221
{
2222
    FDCharDriver *s = chr->opaque;
2223

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

    
2233
static void fd_chr_close(struct CharDriverState *chr)
2234
{
2235
    FDCharDriver *s = chr->opaque;
2236

    
2237
    if (s->fd_in >= 0) {
2238
        if (nographic && s->fd_in == 0) {
2239
        } else {
2240
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2241
        }
2242
    }
2243

    
2244
    qemu_free(s);
2245
}
2246

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

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

    
2268
    qemu_chr_reset(chr);
2269

    
2270
    return chr;
2271
}
2272

    
2273
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2274
{
2275
    int fd_out;
2276

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

    
2283
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2284
{
2285
    int fd_in, fd_out;
2286
    char filename_in[256], filename_out[256];
2287

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

    
2304

    
2305
/* for STDIO, we handle the case where several clients use it
2306
   (nographic mode) */
2307

    
2308
#define TERM_FIFO_MAX_SIZE 1
2309

    
2310
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2311
static int term_fifo_size;
2312

    
2313
static int stdio_read_poll(void *opaque)
2314
{
2315
    CharDriverState *chr = opaque;
2316

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

    
2329
static void stdio_read(void *opaque)
2330
{
2331
    int size;
2332
    uint8_t buf[1];
2333
    CharDriverState *chr = opaque;
2334

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

    
2350
/* init terminal so that we can grab keys */
2351
static struct termios oldtty;
2352
static int old_fd0_flags;
2353
static int term_atexit_done;
2354

    
2355
static void term_exit(void)
2356
{
2357
    tcsetattr (0, TCSANOW, &oldtty);
2358
    fcntl(0, F_SETFL, old_fd0_flags);
2359
}
2360

    
2361
static void term_init(void)
2362
{
2363
    struct termios tty;
2364

    
2365
    tcgetattr (0, &tty);
2366
    oldtty = tty;
2367
    old_fd0_flags = fcntl(0, F_GETFL);
2368

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

    
2381
    tcsetattr (0, TCSANOW, &tty);
2382

    
2383
    if (!term_atexit_done++)
2384
        atexit(term_exit);
2385

    
2386
    fcntl(0, F_SETFL, O_NONBLOCK);
2387
}
2388

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

    
2397
static CharDriverState *qemu_chr_open_stdio(void)
2398
{
2399
    CharDriverState *chr;
2400

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

    
2409
    return chr;
2410
}
2411

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

    
2420
        *amaster = *aslave = -1;
2421

    
2422
        mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2423
        if (mfd < 0)
2424
                goto err;
2425

    
2426
        if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2427
                goto err;
2428

    
2429
        if ((slave = ptsname(mfd)) == NULL)
2430
                goto err;
2431

    
2432
        if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2433
                goto err;
2434

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

    
2439
        if (amaster)
2440
                *amaster = mfd;
2441
        if (aslave)
2442
                *aslave = sfd;
2443
        if (winp)
2444
                ioctl(sfd, TIOCSWINSZ, winp);
2445

    
2446
        return 0;
2447

    
2448
err:
2449
        if (sfd != -1)
2450
                close(sfd);
2451
        close(mfd);
2452
        return -1;
2453
}
2454

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

    
2464
        termios_p->c_cc[VMIN] = 0;
2465
        termios_p->c_cc[VTIME] = 0;
2466
}
2467
#endif
2468

    
2469
#if defined(__linux__) || defined(__sun__)
2470

    
2471
typedef struct {
2472
    int fd;
2473
    int connected;
2474
    int polling;
2475
    int read_bytes;
2476
    QEMUTimer *timer;
2477
} PtyCharDriver;
2478

    
2479
static void pty_chr_update_read_handler(CharDriverState *chr);
2480
static void pty_chr_state(CharDriverState *chr, int connected);
2481

    
2482
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2483
{
2484
    PtyCharDriver *s = chr->opaque;
2485

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

    
2494
static int pty_chr_read_poll(void *opaque)
2495
{
2496
    CharDriverState *chr = opaque;
2497
    PtyCharDriver *s = chr->opaque;
2498

    
2499
    s->read_bytes = qemu_chr_can_read(chr);
2500
    return s->read_bytes;
2501
}
2502

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

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

    
2527
static void pty_chr_update_read_handler(CharDriverState *chr)
2528
{
2529
    PtyCharDriver *s = chr->opaque;
2530

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

    
2545
static void pty_chr_state(CharDriverState *chr, int connected)
2546
{
2547
    PtyCharDriver *s = chr->opaque;
2548

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

    
2564
static void pty_chr_timer(void *opaque)
2565
{
2566
    struct CharDriverState *chr = opaque;
2567
    PtyCharDriver *s = chr->opaque;
2568

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

    
2578
    /* Next poll ... */
2579
    pty_chr_update_read_handler(chr);
2580
}
2581

    
2582
static void pty_chr_close(struct CharDriverState *chr)
2583
{
2584
    PtyCharDriver *s = chr->opaque;
2585

    
2586
    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2587
    close(s->fd);
2588
    qemu_free(s);
2589
}
2590

    
2591
static CharDriverState *qemu_chr_open_pty(void)
2592
{
2593
    CharDriverState *chr;
2594
    PtyCharDriver *s;
2595
    struct termios tty;
2596
    int slave_fd;
2597

    
2598
    chr = qemu_mallocz(sizeof(CharDriverState));
2599
    if (!chr)
2600
        return NULL;
2601
    s = qemu_mallocz(sizeof(PtyCharDriver));
2602
    if (!s) {
2603
        qemu_free(chr);
2604
        return NULL;
2605
    }
2606

    
2607
    if (openpty(&s->fd, &slave_fd, NULL, NULL, NULL) < 0) {
2608
        return NULL;
2609
    }
2610

    
2611
    /* Set raw attributes on the pty. */
2612
    cfmakeraw(&tty);
2613
    tcsetattr(slave_fd, TCSAFLUSH, &tty);
2614
    close(slave_fd);
2615

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

    
2618
    chr->opaque = s;
2619
    chr->chr_write = pty_chr_write;
2620
    chr->chr_update_read_handler = pty_chr_update_read_handler;
2621
    chr->chr_close = pty_chr_close;
2622

    
2623
    s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2624

    
2625
    return chr;
2626
}
2627

    
2628
static void tty_serial_init(int fd, int speed,
2629
                            int parity, int data_bits, int stop_bits)
2630
{
2631
    struct termios tty;
2632
    speed_t spd;
2633

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

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

    
2668
    cfsetispeed(&tty, spd);
2669
    cfsetospeed(&tty, spd);
2670

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

    
2705
    tcsetattr (fd, TCSANOW, &tty);
2706
}
2707

    
2708
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2709
{
2710
    FDCharDriver *s = chr->opaque;
2711

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

    
2764
static CharDriverState *qemu_chr_open_tty(const char *filename)
2765
{
2766
    CharDriverState *chr;
2767
    int fd;
2768

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

    
2787
#if defined(__linux__)
2788
typedef struct {
2789
    int fd;
2790
    int mode;
2791
} ParallelCharDriver;
2792

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

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

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

    
2881
static void pp_close(CharDriverState *chr)
2882
{
2883
    ParallelCharDriver *drv = chr->opaque;
2884
    int fd = drv->fd;
2885

    
2886
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2887
    ioctl(fd, PPRELEASE);
2888
    close(fd);
2889
    qemu_free(drv);
2890
}
2891

    
2892
static CharDriverState *qemu_chr_open_pp(const char *filename)
2893
{
2894
    CharDriverState *chr;
2895
    ParallelCharDriver *drv;
2896
    int fd;
2897

    
2898
    TFR(fd = open(filename, O_RDWR));
2899
    if (fd < 0)
2900
        return NULL;
2901

    
2902
    if (ioctl(fd, PPCLAIM) < 0) {
2903
        close(fd);
2904
        return NULL;
2905
    }
2906

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

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

    
2926
    qemu_chr_reset(chr);
2927

    
2928
    return chr;
2929
}
2930
#endif /* __linux__ */
2931

    
2932
#else /* _WIN32 */
2933

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

    
2942
#define NSENDBUF 2048
2943
#define NRECVBUF 2048
2944
#define MAXCONNECT 1
2945
#define NTIMEOUT 5000
2946

    
2947
static int win_chr_poll(void *opaque);
2948
static int win_chr_pipe_poll(void *opaque);
2949

    
2950
static void win_chr_close(CharDriverState *chr)
2951
{
2952
    WinCharState *s = chr->opaque;
2953

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

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

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

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

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

    
3005
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3006
    size = sizeof(COMMCONFIG);
3007
    GetDefaultCommConfig(filename, &comcfg, &size);
3008
    comcfg.dcb.DCBlength = sizeof(DCB);
3009
    CommConfigDialog(filename, NULL, &comcfg);
3010

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

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

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

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

    
3034
 fail:
3035
    win_chr_close(chr);
3036
    return -1;
3037
}
3038

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

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

    
3073
static int win_chr_read_poll(CharDriverState *chr)
3074
{
3075
    WinCharState *s = chr->opaque;
3076

    
3077
    s->max_size = qemu_chr_can_read(chr);
3078
    return s->max_size;
3079
}
3080

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

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

    
3098
    if (size > 0) {
3099
        qemu_chr_read(chr, buf, size);
3100
    }
3101
}
3102

    
3103
static void win_chr_read(CharDriverState *chr)
3104
{
3105
    WinCharState *s = chr->opaque;
3106

    
3107
    if (s->len > s->max_size)
3108
        s->len = s->max_size;
3109
    if (s->len == 0)
3110
        return;
3111

    
3112
    win_chr_readfile(chr);
3113
}
3114

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

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

    
3132
static CharDriverState *qemu_chr_open_win(const char *filename)
3133
{
3134
    CharDriverState *chr;
3135
    WinCharState *s;
3136

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

    
3149
    if (win_chr_init(chr, filename) < 0) {
3150
        free(s);
3151
        free(chr);
3152
        return NULL;
3153
    }
3154
    qemu_chr_reset(chr);
3155
    return chr;
3156
}
3157

    
3158
static int win_chr_pipe_poll(void *opaque)
3159
{
3160
    CharDriverState *chr = opaque;
3161
    WinCharState *s = chr->opaque;
3162
    DWORD size;
3163

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

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

    
3182
    s->fpipe = TRUE;
3183

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

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

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

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

    
3224
    if (ov.hEvent) {
3225
        CloseHandle(ov.hEvent);
3226
        ov.hEvent = NULL;
3227
    }
3228
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
3229
    return 0;
3230

    
3231
 fail:
3232
    win_chr_close(chr);
3233
    return -1;
3234
}
3235

    
3236

    
3237
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3238
{
3239
    CharDriverState *chr;
3240
    WinCharState *s;
3241

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

    
3254
    if (win_chr_pipe_init(chr, filename) < 0) {
3255
        free(s);
3256
        free(chr);
3257
        return NULL;
3258
    }
3259
    qemu_chr_reset(chr);
3260
    return chr;
3261
}
3262

    
3263
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3264
{
3265
    CharDriverState *chr;
3266
    WinCharState *s;
3267

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

    
3283
static CharDriverState *qemu_chr_open_win_con(const char *filename)
3284
{
3285
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3286
}
3287

    
3288
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3289
{
3290
    HANDLE fd_out;
3291

    
3292
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3293
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3294
    if (fd_out == INVALID_HANDLE_VALUE)
3295
        return NULL;
3296

    
3297
    return qemu_chr_open_win_file(fd_out);
3298
}
3299
#endif /* !_WIN32 */
3300

    
3301
/***********************************************************/
3302
/* UDP Net console */
3303

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

    
3313
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3314
{
3315
    NetCharDriver *s = chr->opaque;
3316

    
3317
    return sendto(s->fd, buf, len, 0,
3318
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3319
}
3320

    
3321
static int udp_chr_read_poll(void *opaque)
3322
{
3323
    CharDriverState *chr = opaque;
3324
    NetCharDriver *s = chr->opaque;
3325

    
3326
    s->max_size = qemu_chr_can_read(chr);
3327

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

    
3339
static void udp_chr_read(void *opaque)
3340
{
3341
    CharDriverState *chr = opaque;
3342
    NetCharDriver *s = chr->opaque;
3343

    
3344
    if (s->max_size == 0)
3345
        return;
3346
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3347
    s->bufptr = s->bufcnt;
3348
    if (s->bufcnt <= 0)
3349
        return;
3350

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

    
3359
static void udp_chr_update_read_handler(CharDriverState *chr)
3360
{
3361
    NetCharDriver *s = chr->opaque;
3362

    
3363
    if (s->fd >= 0) {
3364
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3365
                             udp_chr_read, NULL, chr);
3366
    }
3367
}
3368

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

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

    
3384
    chr = qemu_mallocz(sizeof(CharDriverState));
3385
    if (!chr)
3386
        goto return_err;
3387
    s = qemu_mallocz(sizeof(NetCharDriver));
3388
    if (!s)
3389
        goto return_err;
3390

    
3391
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3392
    if (fd < 0) {
3393
        perror("socket(PF_INET, SOCK_DGRAM)");
3394
        goto return_err;
3395
    }
3396

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

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

    
3408
    s->fd = fd;
3409
    s->bufcnt = 0;
3410
    s->bufptr = 0;
3411
    chr->opaque = s;
3412
    chr->chr_write = udp_chr_write;
3413
    chr->chr_update_read_handler = udp_chr_update_read_handler;
3414
    return chr;
3415

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

    
3426
/***********************************************************/
3427
/* TCP Net console */
3428

    
3429
typedef struct {
3430
    int fd, listen_fd;
3431
    int connected;
3432
    int max_size;
3433
    int do_telnetopt;
3434
    int do_nodelay;
3435
    int is_unix;
3436
} TCPCharDriver;
3437

    
3438
static void tcp_chr_accept(void *opaque);
3439

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

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

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

    
3476
    int i;
3477
    int j = 0;
3478

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

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

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

    
3541
static void tcp_chr_connect(void *opaque)
3542
{
3543
    CharDriverState *chr = opaque;
3544
    TCPCharDriver *s = chr->opaque;
3545

    
3546
    s->connected = 1;
3547
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3548
                         tcp_chr_read, NULL, chr);
3549
    qemu_chr_reset(chr);
3550
}
3551

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

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

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

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

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

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

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

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

    
3673
    chr = qemu_mallocz(sizeof(CharDriverState));
3674
    if (!chr)
3675
        goto fail;
3676
    s = qemu_mallocz(sizeof(TCPCharDriver));
3677
    if (!s)
3678
        goto fail;
3679

    
3680
#ifndef _WIN32
3681
    if (is_unix)
3682
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3683
    else
3684
#endif
3685
        fd = socket(PF_INET, SOCK_STREAM, 0);
3686

    
3687
    if (fd < 0)
3688
        goto fail;
3689

    
3690
    if (!is_waitconnect)
3691
        socket_set_nonblock(fd);
3692

    
3693
    s->connected = 0;
3694
    s->fd = -1;
3695
    s->listen_fd = -1;
3696
    s->is_unix = is_unix;
3697
    s->do_nodelay = do_nodelay && !is_unix;
3698

    
3699
    chr->opaque = s;
3700
    chr->chr_write = tcp_chr_write;
3701
    chr->chr_close = tcp_chr_close;
3702

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

    
3717
        ret = bind(fd, addr, addrlen);
3718
        if (ret < 0)
3719
            goto fail;
3720

    
3721
        ret = listen(fd, 0);
3722
        if (ret < 0)
3723
            goto fail;
3724

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

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

    
3763
    return chr;
3764
 fail:
3765
    if (fd >= 0)
3766
        closesocket(fd);
3767
    qemu_free(s);
3768
    qemu_free(chr);
3769
    return NULL;
3770
}
3771

    
3772
CharDriverState *qemu_chr_open(const char *filename)
3773
{
3774
    const char *p;
3775

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

    
3848
void qemu_chr_close(CharDriverState *chr)
3849
{
3850
    if (chr->chr_close)
3851
        chr->chr_close(chr);
3852
    qemu_free(chr);
3853
}
3854

    
3855
/***********************************************************/
3856
/* network device redirectors */
3857

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

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

    
3885
static int parse_macaddr(uint8_t *macaddr, const char *p)
3886
{
3887
    int i;
3888
    char *last_char;
3889
    long int offset;
3890

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

    
3914
    return -1;
3915
}
3916

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

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

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

    
3954
    if ((src_str = strchr(input_str,'@'))) {
3955
        *src_str = '\0';
3956
        src_str++;
3957
    }
3958

    
3959
    if (parse_host_port(haddr, host_str) < 0)
3960
        goto fail;
3961

    
3962
    if (!src_str || *src_str == '\0')
3963
        src_str = ":0";
3964

    
3965
    if (parse_host_port(saddr, src_str) < 0)
3966
        goto fail;
3967

    
3968
    free(str);
3969
    return(0);
3970

    
3971
fail:
3972
    free(str);
3973
    return -1;
3974
}
3975

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

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

    
4006
#ifndef _WIN32
4007
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4008
{
4009
    const char *p;
4010
    int len;
4011

    
4012
    len = MIN(108, strlen(str));
4013
    p = strchr(str, ',');
4014
    if (p)
4015
        len = MIN(len, p - str);
4016

    
4017
    memset(uaddr, 0, sizeof(*uaddr));
4018

    
4019
    uaddr->sun_family = AF_UNIX;
4020
    memcpy(uaddr->sun_path, str, len);
4021

    
4022
    return 0;
4023
}
4024
#endif
4025

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

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

    
4060
    vc->next = NULL;
4061
    pvc = &vlan->first_client;
4062
    while (*pvc != NULL)
4063
        pvc = &(*pvc)->next;
4064
    *pvc = vc;
4065
    return vc;
4066
}
4067

    
4068
void qemu_del_vlan_client(VLANClientState *vc)
4069
{
4070
    VLANClientState **pvc = &vc->vlan->first_client;
4071

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

    
4081
int qemu_can_send_packet(VLANClientState *vc1)
4082
{
4083
    VLANState *vlan = vc1->vlan;
4084
    VLANClientState *vc;
4085

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

    
4095
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4096
{
4097
    VLANState *vlan = vc1->vlan;
4098
    VLANClientState *vc;
4099

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

    
4111
#if defined(CONFIG_SLIRP)
4112

    
4113
/* slirp network adapter */
4114

    
4115
static int slirp_inited;
4116
static VLANClientState *slirp_vc;
4117

    
4118
int slirp_can_output(void)
4119
{
4120
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
4121
}
4122

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

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

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

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

    
4163
    if (!slirp_inited) {
4164
        slirp_inited = 1;
4165
        slirp_init();
4166
    }
4167

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

    
4179
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4180
        goto fail;
4181
    host_port = strtol(buf, &r, 0);
4182
    if (r == buf)
4183
        goto fail;
4184

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

    
4193
    guest_port = strtol(p, &r, 0);
4194
    if (r == p)
4195
        goto fail;
4196

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

    
4207
#ifndef _WIN32
4208

    
4209
char smb_dir[1024];
4210

    
4211
static void erase_dir(char *dir_name)
4212
{
4213
    DIR *d;
4214
    struct dirent *de;
4215
    char filename[1024];
4216

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

    
4236
/* automatic user mode samba server configuration */
4237
static void smb_exit(void)
4238
{
4239
    erase_dir(smb_dir);
4240
}
4241

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

    
4249
    if (!slirp_inited) {
4250
        slirp_inited = 1;
4251
        slirp_init();
4252
    }
4253

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

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

    
4291
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4292
             SMBD_COMMAND, smb_conf);
4293

    
4294
    slirp_add_exec(0, smb_cmdline, 4, 139);
4295
}
4296

    
4297
#endif /* !defined(_WIN32) */
4298
void do_info_slirp(void)
4299
{
4300
    slirp_stats();
4301
}
4302

    
4303
#endif /* CONFIG_SLIRP */
4304

    
4305
#if !defined(_WIN32)
4306

    
4307
typedef struct TAPState {
4308
    VLANClientState *vc;
4309
    int fd;
4310
    char down_script[1024];
4311
} TAPState;
4312

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

    
4326
static void tap_send(void *opaque)
4327
{
4328
    TAPState *s = opaque;
4329
    uint8_t buf[4096];
4330
    int size;
4331

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

    
4346
/* fd support */
4347

    
4348
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4349
{
4350
    TAPState *s;
4351

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

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

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

    
4375
    fstat(fd, &s);
4376
    dev = devname(s.st_rdev, S_IFCHR);
4377
    pstrcpy(ifname, ifname_size, dev);
4378

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

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

    
4401
    memset(&ifr, 0x0, sizeof(ifr));
4402

    
4403
    if( *dev ){
4404
       ptr = dev;
4405
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
4406
       ppa = atoi(ptr);
4407
    }
4408

    
4409
    /* Check if IP device was opened */
4410
    if( ip_fd )
4411
       close(ip_fd);
4412

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

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

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

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

    
4443
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4444
        syslog(LOG_ERR, "Can't get flags\n");
4445

    
4446
    snprintf (actual_name, 32, "tap%d", ppa);
4447
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4448

    
4449
    ifr.lifr_ppa = ppa;
4450
    /* Assign ppa according to the unit number returned by tun device */
4451

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

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

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

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

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

    
4487
    close (if_fd);
4488

    
4489
    memset(&ifr, 0x0, sizeof(ifr));
4490
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4491
    ifr.lifr_ip_muxid  = ip_muxid;
4492
    ifr.lifr_arp_muxid = arp_muxid;
4493

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

    
4501
    sprintf(dev, "tap%d", ppa);
4502
    return tap_fd;
4503
}
4504

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

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

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

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

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

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

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

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

    
4613
#endif /* !_WIN32 */
4614

    
4615
#if defined(CONFIG_VDE)
4616
typedef struct VDEState {
4617
    VLANClientState *vc;
4618
    VDECONN *vde;
4619
} VDEState;
4620

    
4621
static void vde_to_qemu(void *opaque)
4622
{
4623
    VDEState *s = opaque;
4624
    uint8_t buf[4096];
4625
    int size;
4626

    
4627
    size = vde_recv(s->vde, buf, sizeof(buf), 0);
4628
    if (size > 0) {
4629
        qemu_send_packet(s->vc, buf, size);
4630
    }
4631
}
4632

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

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

    
4653
    struct vde_open_args args = {
4654
        .port = port,
4655
        .group = init_group,
4656
        .mode = mode,
4657
    };
4658

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

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

    
4686
typedef struct NetSocketListenState {
4687
    VLANState *vlan;
4688
    int fd;
4689
} NetSocketListenState;
4690

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

    
4698
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4699
    send_all(s->fd, buf, size);
4700
}
4701

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

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

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

    
4765
static void net_socket_send_dgram(void *opaque)
4766
{
4767
    NetSocketState *s = opaque;
4768
    int size;
4769

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

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

    
4792
    }
4793
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4794
    if (fd < 0) {
4795
        perror("socket(PF_INET, SOCK_DGRAM)");
4796
        return -1;
4797
    }
4798

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

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

    
4813
    /* Add host to multicast group */
4814
    imr.imr_multiaddr = mcastaddr->sin_addr;
4815
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4816

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

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

    
4833
    socket_set_nonblock(fd);
4834
    return fd;
4835
fail:
4836
    if (fd >= 0)
4837
        closesocket(fd);
4838
    return -1;
4839
}
4840

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

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

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

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

    
4880
    s = qemu_mallocz(sizeof(NetSocketState));
4881
    if (!s)
4882
        return NULL;
4883
    s->fd = fd;
4884

    
4885
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4886
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4887

    
4888
    /* mcast: save bound address as dst */
4889
    if (is_connected) s->dgram_dst=saddr;
4890

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

    
4898
static void net_socket_connect(void *opaque)
4899
{
4900
    NetSocketState *s = opaque;
4901
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4902
}
4903

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

    
4924
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4925
                                          int is_connected)
4926
{
4927
    int so_type=-1, optlen=sizeof(so_type);
4928

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

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

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

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

    
4980
    if (parse_host_port(&saddr, host_str) < 0)
4981
        return -1;
4982

    
4983
    s = qemu_mallocz(sizeof(NetSocketListenState));
4984
    if (!s)
4985
        return -1;
4986

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

    
4994
    /* allow fast reuse */
4995
    val = 1;
4996
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4997

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

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

    
5020
    if (parse_host_port(&saddr, host_str) < 0)
5021
        return -1;
5022

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

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

    
5061
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5062
{
5063
    NetSocketState *s;
5064
    int fd;
5065
    struct sockaddr_in saddr;
5066

    
5067
    if (parse_host_port(&saddr, host_str) < 0)
5068
        return -1;
5069

    
5070

    
5071
    fd = net_socket_mcast_create(&saddr);
5072
    if (fd < 0)
5073
        return -1;
5074

    
5075
    s = net_socket_fd_init(vlan, fd, 0);
5076
    if (!s)
5077
        return -1;
5078

    
5079
    s->dgram_dst = saddr;
5080

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

    
5086
}
5087

    
5088
static const char *get_opt_name(char *buf, int buf_size, const char *p)
5089
{
5090
    char *q;
5091

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

    
5101
    return p;
5102
}
5103

    
5104
static const char *get_opt_value(char *buf, int buf_size, const char *p)
5105
{
5106
    char *q;
5107

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

    
5122
    return p;
5123
}
5124

    
5125
static int get_param_value(char *buf, int buf_size,
5126
                           const char *tag, const char *str)
5127
{
5128
    const char *p;
5129
    char option[128];
5130

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

    
5150
static int check_params(char *buf, int buf_size,
5151
                        char **params, const char *str)
5152
{
5153
    const char *p;
5154
    int i;
5155

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

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

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

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

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

    
5322
    return ret;
5323
}
5324

    
5325
static int net_client_parse(const char *str)
5326
{
5327
    const char *p;
5328
    char *q;
5329
    char device[64];
5330

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

    
5342
    return net_client_init(device, p);
5343
}
5344

    
5345
void do_info_network(void)
5346
{
5347
    VLANState *vlan;
5348
    VLANClientState *vc;
5349

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

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

    
5368
static int drive_add(const char *file, const char *fmt, ...)
5369
{
5370
    va_list ap;
5371

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

    
5377
    drives_opt[nb_drives_opt].file = file;
5378
    va_start(ap, fmt);
5379
    vsnprintf(drives_opt[nb_drives_opt].opt,
5380
              sizeof(drives_opt[0].opt), fmt, ap);
5381
    va_end(ap);
5382

    
5383
    return nb_drives_opt++;
5384
}
5385

    
5386
int drive_get_index(BlockInterfaceType type, int bus, int unit)
5387
{
5388
    int index;
5389

    
5390
    /* seek interface, bus and unit */
5391

    
5392
    for (index = 0; index < nb_drives; index++)
5393
        if (drives_table[index].type == type &&
5394
            drives_table[index].bus == bus &&
5395
            drives_table[index].unit == unit)
5396
        return index;
5397

    
5398
    return -1;
5399
}
5400

    
5401
int drive_get_max_bus(BlockInterfaceType type)
5402
{
5403
    int max_bus;
5404
    int index;
5405

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

    
5415
static void bdrv_format_print(void *opaque, const char *name)
5416
{
5417
    fprintf(stderr, " %s", name);
5418
}
5419

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

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

    
5448
    file[0] = 0;
5449
    cyls = heads = secs = 0;
5450
    bus_id = 0;
5451
    unit_id = -1;
5452
    translation = BIOS_ATA_TRANSLATION_AUTO;
5453
    index = -1;
5454
    cache = 1;
5455

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

    
5472
    /* extract parameters */
5473

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

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

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

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

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

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

    
5532
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
5533
        secs = strtol(buf, NULL, 0);
5534
    }
5535

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

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

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

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

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

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

    
5622
    if (arg->file == NULL)
5623
        get_param_value(file, sizeof(file), "file", str);
5624
    else
5625
        pstrcpy(file, sizeof(file), arg->file);
5626

    
5627
    /* compute bus and unit according index */
5628

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

    
5645
    /* if user doesn't specify a unit_id,
5646
     * try to find the first free
5647
     */
5648

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

    
5660
    /* check unit id */
5661

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

    
5668
    /*
5669
     * ignore multiple definitions
5670
     */
5671

    
5672
    if (drive_get_index(type, bus_id, unit_id) != -1)
5673
        return 0;
5674

    
5675
    /* init */
5676

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

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

    
5732
/***********************************************************/
5733
/* USB devices */
5734

    
5735
static USBPort *used_usb_ports;
5736
static USBPort *free_usb_ports;
5737

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

    
5749
static int usb_device_add(const char *devname)
5750
{
5751
    const char *p;
5752
    USBDevice *dev;
5753
    USBPort *port;
5754

    
5755
    if (!free_usb_ports)
5756
        return -1;
5757

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

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

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

    
5794
        /* Create a new hub and chain it on.  */
5795
        free_usb_ports = NULL;
5796
        port->next = used_usb_ports;
5797
        used_usb_ports = port;
5798

    
5799
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5800
        usb_attach(port, hub);
5801
        port = free_usb_ports;
5802
    }
5803

    
5804
    free_usb_ports = port->next;
5805
    port->next = used_usb_ports;
5806
    used_usb_ports = port;
5807
    usb_attach(port, dev);
5808
    return 0;
5809
}
5810

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

    
5819
    if (!used_usb_ports)
5820
        return -1;
5821

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

    
5830
    lastp = &used_usb_ports;
5831
    port = used_usb_ports;
5832
    while (port && port->dev->addr != addr) {
5833
        lastp = &port->next;
5834
        port = port->next;
5835
    }
5836

    
5837
    if (!port)
5838
        return -1;
5839

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

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

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

    
5865
void usb_info(void)
5866
{
5867
    USBDevice *dev;
5868
    USBPort *port;
5869
    const char *speed_str;
5870

    
5871
    if (!usb_enabled) {
5872
        term_printf("USB support not enabled\n");
5873
        return;
5874
    }
5875

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

    
5899
/***********************************************************/
5900
/* PCMCIA/Cardbus */
5901

    
5902
static struct pcmcia_socket_entry_s {
5903
    struct pcmcia_socket_s *socket;
5904
    struct pcmcia_socket_entry_s *next;
5905
} *pcmcia_sockets = 0;
5906

    
5907
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5908
{
5909
    struct pcmcia_socket_entry_s *entry;
5910

    
5911
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5912
    entry->socket = socket;
5913
    entry->next = pcmcia_sockets;
5914
    pcmcia_sockets = entry;
5915
}
5916

    
5917
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5918
{
5919
    struct pcmcia_socket_entry_s *entry, **ptr;
5920

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

    
5929
void pcmcia_info(void)
5930
{
5931
    struct pcmcia_socket_entry_s *iter;
5932
    if (!pcmcia_sockets)
5933
        term_printf("No PCMCIA sockets\n");
5934

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

    
5941
/***********************************************************/
5942
/* dumb display */
5943

    
5944
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5945
{
5946
}
5947

    
5948
static void dumb_resize(DisplayState *ds, int w, int h)
5949
{
5950
}
5951

    
5952
static void dumb_refresh(DisplayState *ds)
5953
{
5954
#if defined(CONFIG_SDL)
5955
    vga_hw_update();
5956
#endif
5957
}
5958

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

    
5969
/***********************************************************/
5970
/* I/O handling */
5971

    
5972
#define MAX_IO_HANDLERS 64
5973

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

    
5986
static IOHandlerRecord *first_io_handler;
5987

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

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

    
6031
int qemu_set_fd_handler(int fd,
6032
                        IOHandler *fd_read,
6033
                        IOHandler *fd_write,
6034
                        void *opaque)
6035
{
6036
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6037
}
6038

    
6039
/***********************************************************/
6040
/* Polling handling */
6041

    
6042
typedef struct PollingEntry {
6043
    PollingFunc *func;
6044
    void *opaque;
6045
    struct PollingEntry *next;
6046
} PollingEntry;
6047

    
6048
static PollingEntry *first_polling_entry;
6049

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

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

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

    
6086
static WaitObjects wait_objects = {0};
6087

    
6088
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6089
{
6090
    WaitObjects *w = &wait_objects;
6091

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

    
6101
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6102
{
6103
    int i, found;
6104
    WaitObjects *w = &wait_objects;
6105

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

    
6121
/***********************************************************/
6122
/* savevm/loadvm support */
6123

    
6124
#define IO_BUF_SIZE 32768
6125

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

    
6139
QEMUFile *qemu_fopen(const char *filename, const char *mode)
6140
{
6141
    QEMUFile *f;
6142

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

    
6165
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6166
{
6167
    QEMUFile *f;
6168

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

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

    
6196
static void qemu_fill_buffer(QEMUFile *f)
6197
{
6198
    int len;
6199

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

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

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

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

    
6251
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6252
{
6253
    int size, l;
6254

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

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

    
6284
int64_t qemu_ftell(QEMUFile *f)
6285
{
6286
    return f->buf_offset - f->buf_size + f->buf_index;
6287
}
6288

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

    
6310
void qemu_put_be16(QEMUFile *f, unsigned int v)
6311
{
6312
    qemu_put_byte(f, v >> 8);
6313
    qemu_put_byte(f, v);
6314
}
6315

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

    
6324
void qemu_put_be64(QEMUFile *f, uint64_t v)
6325
{
6326
    qemu_put_be32(f, v >> 32);
6327
    qemu_put_be32(f, v);
6328
}
6329

    
6330
unsigned int qemu_get_be16(QEMUFile *f)
6331
{
6332
    unsigned int v;
6333
    v = qemu_get_byte(f) << 8;
6334
    v |= qemu_get_byte(f);
6335
    return v;
6336
}
6337

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

    
6348
uint64_t qemu_get_be64(QEMUFile *f)
6349
{
6350
    uint64_t v;
6351
    v = (uint64_t)qemu_get_be32(f) << 32;
6352
    v |= qemu_get_be32(f);
6353
    return v;
6354
}
6355

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

    
6366
static SaveStateEntry *first_se;
6367

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

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

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

    
6405
#define QEMU_VM_FILE_MAGIC   0x5145564d
6406
#define QEMU_VM_FILE_VERSION 0x00000002
6407

    
6408
static int qemu_savevm_state(QEMUFile *f)
6409
{
6410
    SaveStateEntry *se;
6411
    int len, ret;
6412
    int64_t cur_pos, len_pos, total_len_pos;
6413

    
6414
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6415
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6416
    total_len_pos = qemu_ftell(f);
6417
    qemu_put_be64(f, 0); /* total size */
6418

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

    
6424
        /* ID string */
6425
        len = strlen(se->idstr);
6426
        qemu_put_byte(f, len);
6427
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6428

    
6429
        qemu_put_be32(f, se->instance_id);
6430
        qemu_put_be32(f, se->version_id);
6431

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

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

    
6449
    ret = 0;
6450
    return ret;
6451
}
6452

    
6453
static SaveStateEntry *find_se(const char *idstr, int instance_id)
6454
{
6455
    SaveStateEntry *se;
6456

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

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

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

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

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

    
6533
static BlockDriverState *get_bs_snapshots(void)
6534
{
6535
    BlockDriverState *bs;
6536
    int i;
6537

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

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

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

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

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

    
6593
    /* ??? Should this occur after vm_stop?  */
6594
    qemu_aio_flush();
6595

    
6596
    saved_vm_running = vm_running;
6597
    vm_stop(0);
6598

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

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

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

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

    
6647
    /* create the snapshots */
6648

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

    
6667
 the_end:
6668
    if (saved_vm_running)
6669
        vm_start();
6670
}
6671

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

    
6680
    bs = get_bs_snapshots();
6681
    if (!bs) {
6682
        term_printf("No block device supports snapshots\n");
6683
        return;
6684
    }
6685

    
6686
    /* Flush all IO requests so they don't interfere with the new state.  */
6687
    qemu_aio_flush();
6688

    
6689
    saved_vm_running = vm_running;
6690
    vm_stop(0);
6691

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

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

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

    
6742
void do_delvm(const char *name)
6743
{
6744
    BlockDriverState *bs, *bs1;
6745
    int i, ret;
6746

    
6747
    bs = get_bs_snapshots();
6748
    if (!bs) {
6749
        term_printf("No block device supports snapshots\n");
6750
        return;
6751
    }
6752

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

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

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

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

    
6805
/***********************************************************/
6806
/* ram save/restore */
6807

    
6808
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6809
{
6810
    int v;
6811

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

    
6828
static int ram_load_v1(QEMUFile *f, void *opaque)
6829
{
6830
    int ret;
6831
    ram_addr_t i;
6832

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

    
6843
#define BDRV_HASH_BLOCK_SIZE 1024
6844
#define IOBUF_SIZE 4096
6845
#define RAM_CBLOCK_MAGIC 0xfabe
6846

    
6847
typedef struct RamCompressState {
6848
    z_stream zstream;
6849
    QEMUFile *f;
6850
    uint8_t buf[IOBUF_SIZE];
6851
} RamCompressState;
6852

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

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

    
6875
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6876
{
6877
    int ret;
6878

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

    
6894
static void ram_compress_close(RamCompressState *s)
6895
{
6896
    int len, ret;
6897

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

    
6918
typedef struct RamDecompressState {
6919
    z_stream zstream;
6920
    QEMUFile *f;
6921
    uint8_t buf[IOBUF_SIZE];
6922
} RamDecompressState;
6923

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

    
6935
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6936
{
6937
    int ret, clen;
6938

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

    
6960
static void ram_decompress_close(RamDecompressState *s)
6961
{
6962
    inflateEnd(&s->zstream);
6963
}
6964

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

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

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

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

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

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

    
7064
/***********************************************************/
7065
/* bottom halves (can be seen as timers which expire ASAP) */
7066

    
7067
struct QEMUBH {
7068
    QEMUBHFunc *cb;
7069
    void *opaque;
7070
    int scheduled;
7071
    QEMUBH *next;
7072
};
7073

    
7074
static QEMUBH *first_bh = NULL;
7075

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

    
7087
int qemu_bh_poll(void)
7088
{
7089
    QEMUBH *bh, **pbh;
7090
    int ret;
7091

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

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

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

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

    
7133
void qemu_bh_delete(QEMUBH *bh)
7134
{
7135
    qemu_bh_cancel(bh);
7136
    qemu_free(bh);
7137
}
7138

    
7139
/***********************************************************/
7140
/* machine registration */
7141

    
7142
QEMUMachine *first_machine = NULL;
7143

    
7144
int qemu_register_machine(QEMUMachine *m)
7145
{
7146
    QEMUMachine **pm;
7147
    pm = &first_machine;
7148
    while (*pm != NULL)
7149
        pm = &(*pm)->next;
7150
    m->next = NULL;
7151
    *pm = m;
7152
    return 0;
7153
}
7154

    
7155
static QEMUMachine *find_machine(const char *name)
7156
{
7157
    QEMUMachine *m;
7158

    
7159
    for(m = first_machine; m != NULL; m = m->next) {
7160
        if (!strcmp(m->name, name))
7161
            return m;
7162
    }
7163
    return NULL;
7164
}
7165

    
7166
/***********************************************************/
7167
/* main execution loop */
7168

    
7169
static void gui_update(void *opaque)
7170
{
7171
    DisplayState *ds = opaque;
7172
    ds->dpy_refresh(ds);
7173
    qemu_mod_timer(ds->gui_timer,
7174
        (ds->gui_timer_interval ?
7175
            ds->gui_timer_interval :
7176
            GUI_REFRESH_INTERVAL)
7177
        + qemu_get_clock(rt_clock));
7178
}
7179

    
7180
struct vm_change_state_entry {
7181
    VMChangeStateHandler *cb;
7182
    void *opaque;
7183
    LIST_ENTRY (vm_change_state_entry) entries;
7184
};
7185

    
7186
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7187

    
7188
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7189
                                                     void *opaque)
7190
{
7191
    VMChangeStateEntry *e;
7192

    
7193
    e = qemu_mallocz(sizeof (*e));
7194
    if (!e)
7195
        return NULL;
7196

    
7197
    e->cb = cb;
7198
    e->opaque = opaque;
7199
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7200
    return e;
7201
}
7202

    
7203
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7204
{
7205
    LIST_REMOVE (e, entries);
7206
    qemu_free (e);
7207
}
7208

    
7209
static void vm_state_notify(int running)
7210
{
7211
    VMChangeStateEntry *e;
7212

    
7213
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7214
        e->cb(e->opaque, running);
7215
    }
7216
}
7217

    
7218
/* XXX: support several handlers */
7219
static VMStopHandler *vm_stop_cb;
7220
static void *vm_stop_opaque;
7221

    
7222
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7223
{
7224
    vm_stop_cb = cb;
7225
    vm_stop_opaque = opaque;
7226
    return 0;
7227
}
7228

    
7229
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7230
{
7231
    vm_stop_cb = NULL;
7232
}
7233

    
7234
void vm_start(void)
7235
{
7236
    if (!vm_running) {
7237
        cpu_enable_ticks();
7238
        vm_running = 1;
7239
        vm_state_notify(1);
7240
        qemu_rearm_alarm_timer(alarm_timer);
7241
    }
7242
}
7243

    
7244
void vm_stop(int reason)
7245
{
7246
    if (vm_running) {
7247
        cpu_disable_ticks();
7248
        vm_running = 0;
7249
        if (reason != 0) {
7250
            if (vm_stop_cb) {
7251
                vm_stop_cb(vm_stop_opaque, reason);
7252
            }
7253
        }
7254
        vm_state_notify(0);
7255
    }
7256
}
7257

    
7258
/* reset/shutdown handler */
7259

    
7260
typedef struct QEMUResetEntry {
7261
    QEMUResetHandler *func;
7262
    void *opaque;
7263
    struct QEMUResetEntry *next;
7264
} QEMUResetEntry;
7265

    
7266
static QEMUResetEntry *first_reset_entry;
7267
static int reset_requested;
7268
static int shutdown_requested;
7269
static int powerdown_requested;
7270

    
7271
int qemu_shutdown_requested(void)
7272
{
7273
    int r = shutdown_requested;
7274
    shutdown_requested = 0;
7275
    return r;
7276
}
7277

    
7278
int qemu_reset_requested(void)
7279
{
7280
    int r = reset_requested;
7281
    reset_requested = 0;
7282
    return r;
7283
}
7284

    
7285
int qemu_powerdown_requested(void)
7286
{
7287
    int r = powerdown_requested;
7288
    powerdown_requested = 0;
7289
    return r;
7290
}
7291

    
7292
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7293
{
7294
    QEMUResetEntry **pre, *re;
7295

    
7296
    pre = &first_reset_entry;
7297
    while (*pre != NULL)
7298
        pre = &(*pre)->next;
7299
    re = qemu_mallocz(sizeof(QEMUResetEntry));
7300
    re->func = func;
7301
    re->opaque = opaque;
7302
    re->next = NULL;
7303
    *pre = re;
7304
}
7305

    
7306
void qemu_system_reset(void)
7307
{
7308
    QEMUResetEntry *re;
7309

    
7310
    /* reset all devices */
7311
    for(re = first_reset_entry; re != NULL; re = re->next) {
7312
        re->func(re->opaque);
7313
    }
7314
}
7315

    
7316
void qemu_system_reset_request(void)
7317
{
7318
    if (no_reboot) {
7319
        shutdown_requested = 1;
7320
    } else {
7321
        reset_requested = 1;
7322
    }
7323
    if (cpu_single_env)
7324
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7325
}
7326

    
7327
void qemu_system_shutdown_request(void)
7328
{
7329
    shutdown_requested = 1;
7330
    if (cpu_single_env)
7331
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7332
}
7333

    
7334
void qemu_system_powerdown_request(void)
7335
{
7336
    powerdown_requested = 1;
7337
    if (cpu_single_env)
7338
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7339
}
7340

    
7341
void main_loop_wait(int timeout)
7342
{
7343
    IOHandlerRecord *ioh;
7344
    fd_set rfds, wfds, xfds;
7345
    int ret, nfds;
7346
#ifdef _WIN32
7347
    int ret2, i;
7348
#endif
7349
    struct timeval tv;
7350
    PollingEntry *pe;
7351

    
7352

    
7353
    /* XXX: need to suppress polling by better using win32 events */
7354
    ret = 0;
7355
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7356
        ret |= pe->func(pe->opaque);
7357
    }
7358
#ifdef _WIN32
7359
    if (ret == 0) {
7360
        int err;
7361
        WaitObjects *w = &wait_objects;
7362

    
7363
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7364
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7365
            if (w->func[ret - WAIT_OBJECT_0])
7366
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7367

    
7368
            /* Check for additional signaled events */
7369
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7370

    
7371
                /* Check if event is signaled */
7372
                ret2 = WaitForSingleObject(w->events[i], 0);
7373
                if(ret2 == WAIT_OBJECT_0) {
7374
                    if (w->func[i])
7375
                        w->func[i](w->opaque[i]);
7376
                } else if (ret2 == WAIT_TIMEOUT) {
7377
                } else {
7378
                    err = GetLastError();
7379
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7380
                }
7381
            }
7382
        } else if (ret == WAIT_TIMEOUT) {
7383
        } else {
7384
            err = GetLastError();
7385
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7386
        }
7387
    }
7388
#endif
7389
    /* poll any events */
7390
    /* XXX: separate device handlers from system ones */
7391
    nfds = -1;
7392
    FD_ZERO(&rfds);
7393
    FD_ZERO(&wfds);
7394
    FD_ZERO(&xfds);
7395
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7396
        if (ioh->deleted)
7397
            continue;
7398
        if (ioh->fd_read &&
7399
            (!ioh->fd_read_poll ||
7400
             ioh->fd_read_poll(ioh->opaque) != 0)) {
7401
            FD_SET(ioh->fd, &rfds);
7402
            if (ioh->fd > nfds)
7403
                nfds = ioh->fd;
7404
        }
7405
        if (ioh->fd_write) {
7406
            FD_SET(ioh->fd, &wfds);
7407
            if (ioh->fd > nfds)
7408
                nfds = ioh->fd;
7409
        }
7410
    }
7411

    
7412
    tv.tv_sec = 0;
7413
#ifdef _WIN32
7414
    tv.tv_usec = 0;
7415
#else
7416
    tv.tv_usec = timeout * 1000;
7417
#endif
7418
#if defined(CONFIG_SLIRP)
7419
    if (slirp_inited) {
7420
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7421
    }
7422
#endif
7423
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7424
    if (ret > 0) {
7425
        IOHandlerRecord **pioh;
7426

    
7427
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7428
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7429
                ioh->fd_read(ioh->opaque);
7430
            }
7431
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7432
                ioh->fd_write(ioh->opaque);
7433
            }
7434
        }
7435

    
7436
        /* remove deleted IO handlers */
7437
        pioh = &first_io_handler;
7438
        while (*pioh) {
7439
            ioh = *pioh;
7440
            if (ioh->deleted) {
7441
                *pioh = ioh->next;
7442
                qemu_free(ioh);
7443
            } else
7444
                pioh = &ioh->next;
7445
        }
7446
    }
7447
#if defined(CONFIG_SLIRP)
7448
    if (slirp_inited) {
7449
        if (ret < 0) {
7450
            FD_ZERO(&rfds);
7451
            FD_ZERO(&wfds);
7452
            FD_ZERO(&xfds);
7453
        }
7454
        slirp_select_poll(&rfds, &wfds, &xfds);
7455
    }
7456
#endif
7457
    qemu_aio_poll();
7458

    
7459
    if (vm_running) {
7460
        if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7461
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7462
                        qemu_get_clock(vm_clock));
7463
        /* run dma transfers, if any */
7464
        DMA_run();
7465
    }
7466

    
7467
    /* real time timers */
7468
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7469
                    qemu_get_clock(rt_clock));
7470

    
7471
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7472
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7473
        qemu_rearm_alarm_timer(alarm_timer);
7474
    }
7475

    
7476
    /* Check bottom-halves last in case any of the earlier events triggered
7477
       them.  */
7478
    qemu_bh_poll();
7479

    
7480
}
7481

    
7482
static int main_loop(void)
7483
{
7484
    int ret, timeout;
7485
#ifdef CONFIG_PROFILER
7486
    int64_t ti;
7487
#endif
7488
    CPUState *env;
7489

    
7490
    cur_cpu = first_cpu;
7491
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7492
    for(;;) {
7493
        if (vm_running) {
7494

    
7495
            for(;;) {
7496
                /* get next cpu */
7497
                env = next_cpu;
7498
#ifdef CONFIG_PROFILER
7499
                ti = profile_getclock();
7500
#endif
7501
                if (use_icount) {
7502
                    int64_t count;
7503
                    int decr;
7504
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7505
                    env->icount_decr.u16.low = 0;
7506
                    env->icount_extra = 0;
7507
                    count = qemu_next_deadline();
7508
                    count = (count + (1 << icount_time_shift) - 1)
7509
                            >> icount_time_shift;
7510
                    qemu_icount += count;
7511
                    decr = (count > 0xffff) ? 0xffff : count;
7512
                    count -= decr;
7513
                    env->icount_decr.u16.low = decr;
7514
                    env->icount_extra = count;
7515
                }
7516
                ret = cpu_exec(env);
7517
#ifdef CONFIG_PROFILER
7518
                qemu_time += profile_getclock() - ti;
7519
#endif
7520
                if (use_icount) {
7521
                    /* Fold pending instructions back into the
7522
                       instruction counter, and clear the interrupt flag.  */
7523
                    qemu_icount -= (env->icount_decr.u16.low
7524
                                    + env->icount_extra);
7525
                    env->icount_decr.u32 = 0;
7526
                    env->icount_extra = 0;
7527
                }
7528
                next_cpu = env->next_cpu ?: first_cpu;
7529
                if (event_pending && likely(ret != EXCP_DEBUG)) {
7530
                    ret = EXCP_INTERRUPT;
7531
                    event_pending = 0;
7532
                    break;
7533
                }
7534
                if (ret == EXCP_HLT) {
7535
                    /* Give the next CPU a chance to run.  */
7536
                    cur_cpu = env;
7537
                    continue;
7538
                }
7539
                if (ret != EXCP_HALTED)
7540
                    break;
7541
                /* all CPUs are halted ? */
7542
                if (env == cur_cpu)
7543
                    break;
7544
            }
7545
            cur_cpu = env;
7546

    
7547
            if (shutdown_requested) {
7548
                ret = EXCP_INTERRUPT;
7549
                if (no_shutdown) {
7550
                    vm_stop(0);
7551
                    no_shutdown = 0;
7552
                }
7553
                else
7554
                    break;
7555
            }
7556
            if (reset_requested) {
7557
                reset_requested = 0;
7558
                qemu_system_reset();
7559
                ret = EXCP_INTERRUPT;
7560
            }
7561
            if (powerdown_requested) {
7562
                powerdown_requested = 0;
7563
                qemu_system_powerdown();
7564
                ret = EXCP_INTERRUPT;
7565
            }
7566
            if (unlikely(ret == EXCP_DEBUG)) {
7567
                vm_stop(EXCP_DEBUG);
7568
            }
7569
            /* If all cpus are halted then wait until the next IRQ */
7570
            /* XXX: use timeout computed from timers */
7571
            if (ret == EXCP_HALTED) {
7572
                if (use_icount) {
7573
                    int64_t add;
7574
                    int64_t delta;
7575
                    /* Advance virtual time to the next event.  */
7576
                    if (use_icount == 1) {
7577
                        /* When not using an adaptive execution frequency
7578
                           we tend to get badly out of sync with real time,
7579
                           so just delay for a reasonable amount of time.  */
7580
                        delta = 0;
7581
                    } else {
7582
                        delta = cpu_get_icount() - cpu_get_clock();
7583
                    }
7584
                    if (delta > 0) {
7585
                        /* If virtual time is ahead of real time then just
7586
                           wait for IO.  */
7587
                        timeout = (delta / 1000000) + 1;
7588
                    } else {
7589
                        /* Wait for either IO to occur or the next
7590
                           timer event.  */
7591
                        add = qemu_next_deadline();
7592
                        /* We advance the timer before checking for IO.
7593
                           Limit the amount we advance so that early IO
7594
                           activity won't get the guest too far ahead.  */
7595
                        if (add > 10000000)
7596
                            add = 10000000;
7597
                        delta += add;
7598
                        add = (add + (1 << icount_time_shift) - 1)
7599
                              >> icount_time_shift;
7600
                        qemu_icount += add;
7601
                        timeout = delta / 1000000;
7602
                        if (timeout < 0)
7603
                            timeout = 0;
7604
                    }
7605
                } else {
7606
                    timeout = 10;
7607
                }
7608
            } else {
7609
                timeout = 0;
7610
            }
7611
        } else {
7612
            timeout = 10;
7613
        }
7614
#ifdef CONFIG_PROFILER
7615
        ti = profile_getclock();
7616
#endif
7617
        main_loop_wait(timeout);
7618
#ifdef CONFIG_PROFILER
7619
        dev_time += profile_getclock() - ti;
7620
#endif
7621
    }
7622
    cpu_disable_ticks();
7623
    return ret;
7624
}
7625

    
7626
static void help(int exitcode)
7627
{
7628
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7629
           "usage: %s [options] [disk_image]\n"
7630
           "\n"
7631
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7632
           "\n"
7633
           "Standard options:\n"
7634
           "-M machine      select emulated machine (-M ? for list)\n"
7635
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7636
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7637
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7638
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7639
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7640
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7641
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7642
           "       [,cache=on|off][,format=f]\n"
7643
           "                use 'file' as a drive image\n"
7644
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7645
           "-sd file        use 'file' as SecureDigital card image\n"
7646
           "-pflash file    use 'file' as a parallel flash image\n"
7647
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7648
           "-snapshot       write to temporary files instead of disk image files\n"
7649
#ifdef CONFIG_SDL
7650
           "-no-frame       open SDL window without a frame and window decorations\n"
7651
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7652
           "-no-quit        disable SDL window close capability\n"
7653
#endif
7654
#ifdef TARGET_I386
7655
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7656
#endif
7657
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7658
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7659
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7660
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7661
#ifndef _WIN32
7662
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7663
#endif
7664
#ifdef HAS_AUDIO
7665
           "-audio-help     print list of audio drivers and their options\n"
7666
           "-soundhw c1,... enable audio support\n"
7667
           "                and only specified sound cards (comma separated list)\n"
7668
           "                use -soundhw ? to get the list of supported cards\n"
7669
           "                use -soundhw all to enable all of them\n"
7670
#endif
7671
           "-localtime      set the real time clock to local time [default=utc]\n"
7672
           "-full-screen    start in full screen\n"
7673
#ifdef TARGET_I386
7674
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7675
#endif
7676
           "-usb            enable the USB driver (will be the default soon)\n"
7677
           "-usbdevice name add the host or guest USB device 'name'\n"
7678
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7679
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7680
#endif
7681
           "-name string    set the name of the guest\n"
7682
           "\n"
7683
           "Network options:\n"
7684
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7685
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7686
#ifdef CONFIG_SLIRP
7687
           "-net user[,vlan=n][,hostname=host]\n"
7688
           "                connect the user mode network stack to VLAN 'n' and send\n"
7689
           "                hostname 'host' to DHCP clients\n"
7690
#endif
7691
#ifdef _WIN32
7692
           "-net tap[,vlan=n],ifname=name\n"
7693
           "                connect the host TAP network interface to VLAN 'n'\n"
7694
#else
7695
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7696
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7697
           "                network scripts 'file' (default=%s)\n"
7698
           "                and 'dfile' (default=%s);\n"
7699
           "                use '[down]script=no' to disable script execution;\n"
7700
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7701
#endif
7702
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7703
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7704
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7705
           "                connect the vlan 'n' to multicast maddr and port\n"
7706
#ifdef CONFIG_VDE
7707
           "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7708
           "                connect the vlan 'n' to port 'n' of a vde switch running\n"
7709
           "                on host and listening for incoming connections on 'socketpath'.\n"
7710
           "                Use group 'groupname' and mode 'octalmode' to change default\n"
7711
           "                ownership and permissions for communication port.\n"
7712
#endif
7713
           "-net none       use it alone to have zero network devices; if no -net option\n"
7714
           "                is provided, the default is '-net nic -net user'\n"
7715
           "\n"
7716
#ifdef CONFIG_SLIRP
7717
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7718
           "-bootp file     advertise file in BOOTP replies\n"
7719
#ifndef _WIN32
7720
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7721
#endif
7722
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7723
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7724
#endif
7725
           "\n"
7726
           "Linux boot specific:\n"
7727
           "-kernel bzImage use 'bzImage' as kernel image\n"
7728
           "-append cmdline use 'cmdline' as kernel command line\n"
7729
           "-initrd file    use 'file' as initial ram disk\n"
7730
           "\n"
7731
           "Debug/Expert options:\n"
7732
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7733
           "-serial dev     redirect the serial port to char device 'dev'\n"
7734
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7735
           "-pidfile file   Write PID to 'file'\n"
7736
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7737
           "-s              wait gdb connection to port\n"
7738
           "-p port         set gdb connection port [default=%s]\n"
7739
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7740
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7741
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7742
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7743
#ifdef USE_KQEMU
7744
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7745
           "-no-kqemu       disable KQEMU kernel module usage\n"
7746
#endif
7747
#ifdef TARGET_I386
7748
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7749
           "                (default is CL-GD5446 PCI VGA)\n"
7750
           "-no-acpi        disable ACPI\n"
7751
#endif
7752
#ifdef CONFIG_CURSES
7753
           "-curses         use a curses/ncurses interface instead of SDL\n"
7754
#endif
7755
           "-no-reboot      exit instead of rebooting\n"
7756
           "-no-shutdown    stop before shutdown\n"
7757
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
7758
           "-vnc display    start a VNC server on display\n"
7759
#ifndef _WIN32
7760
           "-daemonize      daemonize QEMU after initializing\n"
7761
#endif
7762
           "-option-rom rom load a file, rom, into the option ROM space\n"
7763
#ifdef TARGET_SPARC
7764
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7765
#endif
7766
           "-clock          force the use of the given methods for timer alarm.\n"
7767
           "                To see what timers are available use -clock ?\n"
7768
           "-startdate      select initial date of the clock\n"
7769
           "-icount [N|auto]\n"
7770
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7771
           "\n"
7772
           "During emulation, the following keys are useful:\n"
7773
           "ctrl-alt-f      toggle full screen\n"
7774
           "ctrl-alt-n      switch to virtual console 'n'\n"
7775
           "ctrl-alt        toggle mouse and keyboard grab\n"
7776
           "\n"
7777
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7778
           ,
7779
           "qemu",
7780
           DEFAULT_RAM_SIZE,
7781
#ifndef _WIN32
7782
           DEFAULT_NETWORK_SCRIPT,
7783
           DEFAULT_NETWORK_DOWN_SCRIPT,
7784
#endif
7785
           DEFAULT_GDBSTUB_PORT,
7786
           "/tmp/qemu.log");
7787
    exit(exitcode);
7788
}
7789

    
7790
#define HAS_ARG 0x0001
7791

    
7792
enum {
7793
    QEMU_OPTION_h,
7794

    
7795
    QEMU_OPTION_M,
7796
    QEMU_OPTION_cpu,
7797
    QEMU_OPTION_fda,
7798
    QEMU_OPTION_fdb,
7799
    QEMU_OPTION_hda,
7800
    QEMU_OPTION_hdb,
7801
    QEMU_OPTION_hdc,
7802
    QEMU_OPTION_hdd,
7803
    QEMU_OPTION_drive,
7804
    QEMU_OPTION_cdrom,
7805
    QEMU_OPTION_mtdblock,
7806
    QEMU_OPTION_sd,
7807
    QEMU_OPTION_pflash,
7808
    QEMU_OPTION_boot,
7809
    QEMU_OPTION_snapshot,
7810
#ifdef TARGET_I386
7811
    QEMU_OPTION_no_fd_bootchk,
7812
#endif
7813
    QEMU_OPTION_m,
7814
    QEMU_OPTION_nographic,
7815
    QEMU_OPTION_portrait,
7816
#ifdef HAS_AUDIO
7817
    QEMU_OPTION_audio_help,
7818
    QEMU_OPTION_soundhw,
7819
#endif
7820

    
7821
    QEMU_OPTION_net,
7822
    QEMU_OPTION_tftp,
7823
    QEMU_OPTION_bootp,
7824
    QEMU_OPTION_smb,
7825
    QEMU_OPTION_redir,
7826

    
7827
    QEMU_OPTION_kernel,
7828
    QEMU_OPTION_append,
7829
    QEMU_OPTION_initrd,
7830

    
7831
    QEMU_OPTION_S,
7832
    QEMU_OPTION_s,
7833
    QEMU_OPTION_p,
7834
    QEMU_OPTION_d,
7835
    QEMU_OPTION_hdachs,
7836
    QEMU_OPTION_L,
7837
    QEMU_OPTION_bios,
7838
    QEMU_OPTION_k,
7839
    QEMU_OPTION_localtime,
7840
    QEMU_OPTION_cirrusvga,
7841
    QEMU_OPTION_vmsvga,
7842
    QEMU_OPTION_g,
7843
    QEMU_OPTION_std_vga,
7844
    QEMU_OPTION_echr,
7845
    QEMU_OPTION_monitor,
7846
    QEMU_OPTION_serial,
7847
    QEMU_OPTION_parallel,
7848
    QEMU_OPTION_loadvm,
7849
    QEMU_OPTION_full_screen,
7850
    QEMU_OPTION_no_frame,
7851
    QEMU_OPTION_alt_grab,
7852
    QEMU_OPTION_no_quit,
7853
    QEMU_OPTION_pidfile,
7854
    QEMU_OPTION_no_kqemu,
7855
    QEMU_OPTION_kernel_kqemu,
7856
    QEMU_OPTION_win2k_hack,
7857
    QEMU_OPTION_usb,
7858
    QEMU_OPTION_usbdevice,
7859
    QEMU_OPTION_smp,
7860
    QEMU_OPTION_vnc,
7861
    QEMU_OPTION_no_acpi,
7862
    QEMU_OPTION_curses,
7863
    QEMU_OPTION_no_reboot,
7864
    QEMU_OPTION_no_shutdown,
7865
    QEMU_OPTION_show_cursor,
7866
    QEMU_OPTION_daemonize,
7867
    QEMU_OPTION_option_rom,
7868
    QEMU_OPTION_semihosting,
7869
    QEMU_OPTION_name,
7870
    QEMU_OPTION_prom_env,
7871
    QEMU_OPTION_old_param,
7872
    QEMU_OPTION_clock,
7873
    QEMU_OPTION_startdate,
7874
    QEMU_OPTION_tb_size,
7875
    QEMU_OPTION_icount,
7876
};
7877

    
7878
typedef struct QEMUOption {
7879
    const char *name;
7880
    int flags;
7881
    int index;
7882
} QEMUOption;
7883

    
7884
const QEMUOption qemu_options[] = {
7885
    { "h", 0, QEMU_OPTION_h },
7886
    { "help", 0, QEMU_OPTION_h },
7887

    
7888
    { "M", HAS_ARG, QEMU_OPTION_M },
7889
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7890
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7891
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7892
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7893
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7894
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7895
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7896
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7897
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7898
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7899
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7900
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7901
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7902
    { "snapshot", 0, QEMU_OPTION_snapshot },
7903
#ifdef TARGET_I386
7904
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7905
#endif
7906
    { "m", HAS_ARG, QEMU_OPTION_m },
7907
    { "nographic", 0, QEMU_OPTION_nographic },
7908
    { "portrait", 0, QEMU_OPTION_portrait },
7909
    { "k", HAS_ARG, QEMU_OPTION_k },
7910
#ifdef HAS_AUDIO
7911
    { "audio-help", 0, QEMU_OPTION_audio_help },
7912
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7913
#endif
7914

    
7915
    { "net", HAS_ARG, QEMU_OPTION_net},
7916
#ifdef CONFIG_SLIRP
7917
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7918
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7919
#ifndef _WIN32
7920
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7921
#endif
7922
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7923
#endif
7924

    
7925
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7926
    { "append", HAS_ARG, QEMU_OPTION_append },
7927
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7928

    
7929
    { "S", 0, QEMU_OPTION_S },
7930
    { "s", 0, QEMU_OPTION_s },
7931
    { "p", HAS_ARG, QEMU_OPTION_p },
7932
    { "d", HAS_ARG, QEMU_OPTION_d },
7933
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7934
    { "L", HAS_ARG, QEMU_OPTION_L },
7935
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7936
#ifdef USE_KQEMU
7937
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7938
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7939
#endif
7940
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7941
    { "g", 1, QEMU_OPTION_g },
7942
#endif
7943
    { "localtime", 0, QEMU_OPTION_localtime },
7944
    { "std-vga", 0, QEMU_OPTION_std_vga },
7945
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7946
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7947
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7948
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7949
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7950
    { "full-screen", 0, QEMU_OPTION_full_screen },
7951
#ifdef CONFIG_SDL
7952
    { "no-frame", 0, QEMU_OPTION_no_frame },
7953
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7954
    { "no-quit", 0, QEMU_OPTION_no_quit },
7955
#endif
7956
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7957
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7958
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7959
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7960
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7961
#ifdef CONFIG_CURSES
7962
    { "curses", 0, QEMU_OPTION_curses },
7963
#endif
7964

    
7965
    /* temporary options */
7966
    { "usb", 0, QEMU_OPTION_usb },
7967
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7968
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7969
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7970
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7971
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7972
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7973
    { "daemonize", 0, QEMU_OPTION_daemonize },
7974
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7975
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7976
    { "semihosting", 0, QEMU_OPTION_semihosting },
7977
#endif
7978
    { "name", HAS_ARG, QEMU_OPTION_name },
7979
#if defined(TARGET_SPARC)
7980
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7981
#endif
7982
#if defined(TARGET_ARM)
7983
    { "old-param", 0, QEMU_OPTION_old_param },
7984
#endif
7985
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7986
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7987
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
7988
    { "icount", HAS_ARG, QEMU_OPTION_icount },
7989
    { NULL },
7990
};
7991

    
7992
/* password input */
7993

    
7994
int qemu_key_check(BlockDriverState *bs, const char *name)
7995
{
7996
    char password[256];
7997
    int i;
7998

    
7999
    if (!bdrv_is_encrypted(bs))
8000
        return 0;
8001

    
8002
    term_printf("%s is encrypted.\n", name);
8003
    for(i = 0; i < 3; i++) {
8004
        monitor_readline("Password: ", 1, password, sizeof(password));
8005
        if (bdrv_set_key(bs, password) == 0)
8006
            return 0;
8007
        term_printf("invalid password\n");
8008
    }
8009
    return -EPERM;
8010
}
8011

    
8012
static BlockDriverState *get_bdrv(int index)
8013
{
8014
    if (index > nb_drives)
8015
        return NULL;
8016
    return drives_table[index].bdrv;
8017
}
8018

    
8019
static void read_passwords(void)
8020
{
8021
    BlockDriverState *bs;
8022
    int i;
8023

    
8024
    for(i = 0; i < 6; i++) {
8025
        bs = get_bdrv(i);
8026
        if (bs)
8027
            qemu_key_check(bs, bdrv_get_device_name(bs));
8028
    }
8029
}
8030

    
8031
#ifdef HAS_AUDIO
8032
struct soundhw soundhw[] = {
8033
#ifdef HAS_AUDIO_CHOICE
8034
#if defined(TARGET_I386) || defined(TARGET_MIPS)
8035
    {
8036
        "pcspk",
8037
        "PC speaker",
8038
        0,
8039
        1,
8040
        { .init_isa = pcspk_audio_init }
8041
    },
8042
#endif
8043
    {
8044
        "sb16",
8045
        "Creative Sound Blaster 16",
8046
        0,
8047
        1,
8048
        { .init_isa = SB16_init }
8049
    },
8050

    
8051
#ifdef CONFIG_CS4231A
8052
    {
8053
        "cs4231a",
8054
        "CS4231A",
8055
        0,
8056
        1,
8057
        { .init_isa = cs4231a_init }
8058
    },
8059
#endif
8060

    
8061
#ifdef CONFIG_ADLIB
8062
    {
8063
        "adlib",
8064
#ifdef HAS_YMF262
8065
        "Yamaha YMF262 (OPL3)",
8066
#else
8067
        "Yamaha YM3812 (OPL2)",
8068
#endif
8069
        0,
8070
        1,
8071
        { .init_isa = Adlib_init }
8072
    },
8073
#endif
8074

    
8075
#ifdef CONFIG_GUS
8076
    {
8077
        "gus",
8078
        "Gravis Ultrasound GF1",
8079
        0,
8080
        1,
8081
        { .init_isa = GUS_init }
8082
    },
8083
#endif
8084

    
8085
#ifdef CONFIG_AC97
8086
    {
8087
        "ac97",
8088
        "Intel 82801AA AC97 Audio",
8089
        0,
8090
        0,
8091
        { .init_pci = ac97_init }
8092
    },
8093
#endif
8094

    
8095
    {
8096
        "es1370",
8097
        "ENSONIQ AudioPCI ES1370",
8098
        0,
8099
        0,
8100
        { .init_pci = es1370_init }
8101
    },
8102
#endif
8103

    
8104
    { NULL, NULL, 0, 0, { NULL } }
8105
};
8106

    
8107
static void select_soundhw (const char *optarg)
8108
{
8109
    struct soundhw *c;
8110

    
8111
    if (*optarg == '?') {
8112
    show_valid_cards:
8113

    
8114
        printf ("Valid sound card names (comma separated):\n");
8115
        for (c = soundhw; c->name; ++c) {
8116
            printf ("%-11s %s\n", c->name, c->descr);
8117
        }
8118
        printf ("\n-soundhw all will enable all of the above\n");
8119
        exit (*optarg != '?');
8120
    }
8121
    else {
8122
        size_t l;
8123
        const char *p;
8124
        char *e;
8125
        int bad_card = 0;
8126

    
8127
        if (!strcmp (optarg, "all")) {
8128
            for (c = soundhw; c->name; ++c) {
8129
                c->enabled = 1;
8130
            }
8131
            return;
8132
        }
8133

    
8134
        p = optarg;
8135
        while (*p) {
8136
            e = strchr (p, ',');
8137
            l = !e ? strlen (p) : (size_t) (e - p);
8138

    
8139
            for (c = soundhw; c->name; ++c) {
8140
                if (!strncmp (c->name, p, l)) {
8141
                    c->enabled = 1;
8142
                    break;
8143
                }
8144
            }
8145

    
8146
            if (!c->name) {
8147
                if (l > 80) {
8148
                    fprintf (stderr,
8149
                             "Unknown sound card name (too big to show)\n");
8150
                }
8151
                else {
8152
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
8153
                             (int) l, p);
8154
                }
8155
                bad_card = 1;
8156
            }
8157
            p += l + (e != NULL);
8158
        }
8159

    
8160
        if (bad_card)
8161
            goto show_valid_cards;
8162
    }
8163
}
8164
#endif
8165

    
8166
#ifdef _WIN32
8167
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8168
{
8169
    exit(STATUS_CONTROL_C_EXIT);
8170
    return TRUE;
8171
}
8172
#endif
8173

    
8174
#define MAX_NET_CLIENTS 32
8175

    
8176
int main(int argc, char **argv)
8177
{
8178
#ifdef CONFIG_GDBSTUB
8179
    int use_gdbstub;
8180
    const char *gdbstub_port;
8181
#endif
8182
    uint32_t boot_devices_bitmap = 0;
8183
    int i;
8184
    int snapshot, linux_boot, net_boot;
8185
    const char *initrd_filename;
8186
    const char *kernel_filename, *kernel_cmdline;
8187
    const char *boot_devices = "";
8188
    DisplayState *ds = &display_state;
8189
    int cyls, heads, secs, translation;
8190
    const char *net_clients[MAX_NET_CLIENTS];
8191
    int nb_net_clients;
8192
    int hda_index;
8193
    int optind;
8194
    const char *r, *optarg;
8195
    CharDriverState *monitor_hd;
8196
    const char *monitor_device;
8197
    const char *serial_devices[MAX_SERIAL_PORTS];
8198
    int serial_device_index;
8199
    const char *parallel_devices[MAX_PARALLEL_PORTS];
8200
    int parallel_device_index;
8201
    const char *loadvm = NULL;
8202
    QEMUMachine *machine;
8203
    const char *cpu_model;
8204
    const char *usb_devices[MAX_USB_CMDLINE];
8205
    int usb_devices_index;
8206
    int fds[2];
8207
    int tb_size;
8208
    const char *pid_file = NULL;
8209
    VLANState *vlan;
8210

    
8211
    LIST_INIT (&vm_change_state_head);
8212
#ifndef _WIN32
8213
    {
8214
        struct sigaction act;
8215
        sigfillset(&act.sa_mask);
8216
        act.sa_flags = 0;
8217
        act.sa_handler = SIG_IGN;
8218
        sigaction(SIGPIPE, &act, NULL);
8219
    }
8220
#else
8221
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8222
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
8223
       QEMU to run on a single CPU */
8224
    {
8225
        HANDLE h;
8226
        DWORD mask, smask;
8227
        int i;
8228
        h = GetCurrentProcess();
8229
        if (GetProcessAffinityMask(h, &mask, &smask)) {
8230
            for(i = 0; i < 32; i++) {
8231
                if (mask & (1 << i))
8232
                    break;
8233
            }
8234
            if (i != 32) {
8235
                mask = 1 << i;
8236
                SetProcessAffinityMask(h, mask);
8237
            }
8238
        }
8239
    }
8240
#endif
8241

    
8242
    register_machines();
8243
    machine = first_machine;
8244
    cpu_model = NULL;
8245
    initrd_filename = NULL;
8246
    ram_size = 0;
8247
    vga_ram_size = VGA_RAM_SIZE;
8248
#ifdef CONFIG_GDBSTUB
8249
    use_gdbstub = 0;
8250
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
8251
#endif
8252
    snapshot = 0;
8253
    nographic = 0;
8254
    curses = 0;
8255
    kernel_filename = NULL;
8256
    kernel_cmdline = "";
8257
    cyls = heads = secs = 0;
8258
    translation = BIOS_ATA_TRANSLATION_AUTO;
8259
    monitor_device = "vc";
8260

    
8261
    serial_devices[0] = "vc:80Cx24C";
8262
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
8263
        serial_devices[i] = NULL;
8264
    serial_device_index = 0;
8265

    
8266
    parallel_devices[0] = "vc:640x480";
8267
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8268
        parallel_devices[i] = NULL;
8269
    parallel_device_index = 0;
8270

    
8271
    usb_devices_index = 0;
8272

    
8273
    nb_net_clients = 0;
8274
    nb_drives = 0;
8275
    nb_drives_opt = 0;
8276
    hda_index = -1;
8277

    
8278
    nb_nics = 0;
8279

    
8280
    tb_size = 0;
8281
    
8282
    optind = 1;
8283
    for(;;) {
8284
        if (optind >= argc)
8285
            break;
8286
        r = argv[optind];
8287
        if (r[0] != '-') {
8288
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8289
        } else {
8290
            const QEMUOption *popt;
8291

    
8292
            optind++;
8293
            /* Treat --foo the same as -foo.  */
8294
            if (r[1] == '-')
8295
                r++;
8296
            popt = qemu_options;
8297
            for(;;) {
8298
                if (!popt->name) {
8299
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
8300
                            argv[0], r);
8301
                    exit(1);
8302
                }
8303
                if (!strcmp(popt->name, r + 1))
8304
                    break;
8305
                popt++;
8306
            }
8307
            if (popt->flags & HAS_ARG) {
8308
                if (optind >= argc) {
8309
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
8310
                            argv[0], r);
8311
                    exit(1);
8312
                }
8313
                optarg = argv[optind++];
8314
            } else {
8315
                optarg = NULL;
8316
            }
8317

    
8318
            switch(popt->index) {
8319
            case QEMU_OPTION_M:
8320
                machine = find_machine(optarg);
8321
                if (!machine) {
8322
                    QEMUMachine *m;
8323
                    printf("Supported machines are:\n");
8324
                    for(m = first_machine; m != NULL; m = m->next) {
8325
                        printf("%-10s %s%s\n",
8326
                               m->name, m->desc,
8327
                               m == first_machine ? " (default)" : "");
8328
                    }
8329
                    exit(*optarg != '?');
8330
                }
8331
                break;
8332
            case QEMU_OPTION_cpu:
8333
                /* hw initialization will check this */
8334
                if (*optarg == '?') {
8335
/* XXX: implement xxx_cpu_list for targets that still miss it */
8336
#if defined(cpu_list)
8337
                    cpu_list(stdout, &fprintf);
8338
#endif
8339
                    exit(0);
8340
                } else {
8341
                    cpu_model = optarg;
8342
                }
8343
                break;
8344
            case QEMU_OPTION_initrd:
8345
                initrd_filename = optarg;
8346
                break;
8347
            case QEMU_OPTION_hda:
8348
                if (cyls == 0)
8349
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
8350
                else
8351
                    hda_index = drive_add(optarg, HD_ALIAS
8352
                             ",cyls=%d,heads=%d,secs=%d%s",
8353
                             0, cyls, heads, secs,
8354
                             translation == BIOS_ATA_TRANSLATION_LBA ?
8355
                                 ",trans=lba" :
8356
                             translation == BIOS_ATA_TRANSLATION_NONE ?
8357
                                 ",trans=none" : "");
8358
                 break;
8359
            case QEMU_OPTION_hdb:
8360
            case QEMU_OPTION_hdc:
8361
            case QEMU_OPTION_hdd:
8362
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8363
                break;
8364
            case QEMU_OPTION_drive:
8365
                drive_add(NULL, "%s", optarg);
8366
                break;
8367
            case QEMU_OPTION_mtdblock:
8368
                drive_add(optarg, MTD_ALIAS);
8369
                break;
8370
            case QEMU_OPTION_sd:
8371
                drive_add(optarg, SD_ALIAS);
8372
                break;
8373
            case QEMU_OPTION_pflash:
8374
                drive_add(optarg, PFLASH_ALIAS);
8375
                break;
8376
            case QEMU_OPTION_snapshot:
8377
                snapshot = 1;
8378
                break;
8379
            case QEMU_OPTION_hdachs:
8380
                {
8381
                    const char *p;
8382
                    p = optarg;
8383
                    cyls = strtol(p, (char **)&p, 0);
8384
                    if (cyls < 1 || cyls > 16383)
8385
                        goto chs_fail;
8386
                    if (*p != ',')
8387
                        goto chs_fail;
8388
                    p++;
8389
                    heads = strtol(p, (char **)&p, 0);
8390
                    if (heads < 1 || heads > 16)
8391
                        goto chs_fail;
8392
                    if (*p != ',')
8393
                        goto chs_fail;
8394
                    p++;
8395
                    secs = strtol(p, (char **)&p, 0);
8396
                    if (secs < 1 || secs > 63)
8397
                        goto chs_fail;
8398
                    if (*p == ',') {
8399
                        p++;
8400
                        if (!strcmp(p, "none"))
8401
                            translation = BIOS_ATA_TRANSLATION_NONE;
8402
                        else if (!strcmp(p, "lba"))
8403
                            translation = BIOS_ATA_TRANSLATION_LBA;
8404
                        else if (!strcmp(p, "auto"))
8405
                            translation = BIOS_ATA_TRANSLATION_AUTO;
8406
                        else
8407
                            goto chs_fail;
8408
                    } else if (*p != '\0') {
8409
                    chs_fail:
8410
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
8411
                        exit(1);
8412
                    }
8413
                    if (hda_index != -1)
8414
                        snprintf(drives_opt[hda_index].opt,
8415
                                 sizeof(drives_opt[hda_index].opt),
8416
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8417
                                 0, cyls, heads, secs,
8418
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
8419
                                         ",trans=lba" :
8420
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
8421
                                     ",trans=none" : "");
8422
                }
8423
                break;
8424
            case QEMU_OPTION_nographic:
8425
                nographic = 1;
8426
                break;
8427
#ifdef CONFIG_CURSES
8428
            case QEMU_OPTION_curses:
8429
                curses = 1;
8430
                break;
8431
#endif
8432
            case QEMU_OPTION_portrait:
8433
                graphic_rotate = 1;
8434
                break;
8435
            case QEMU_OPTION_kernel:
8436
                kernel_filename = optarg;
8437
                break;
8438
            case QEMU_OPTION_append:
8439
                kernel_cmdline = optarg;
8440
                break;
8441
            case QEMU_OPTION_cdrom:
8442
                drive_add(optarg, CDROM_ALIAS);
8443
                break;
8444
            case QEMU_OPTION_boot:
8445
                boot_devices = optarg;
8446
                /* We just do some generic consistency checks */
8447
                {
8448
                    /* Could easily be extended to 64 devices if needed */
8449
                    const char *p;
8450
                    
8451
                    boot_devices_bitmap = 0;
8452
                    for (p = boot_devices; *p != '\0'; p++) {
8453
                        /* Allowed boot devices are:
8454
                         * a b     : floppy disk drives
8455
                         * c ... f : IDE disk drives
8456
                         * g ... m : machine implementation dependant drives
8457
                         * n ... p : network devices
8458
                         * It's up to each machine implementation to check
8459
                         * if the given boot devices match the actual hardware
8460
                         * implementation and firmware features.
8461
                         */
8462
                        if (*p < 'a' || *p > 'q') {
8463
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
8464
                            exit(1);
8465
                        }
8466
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8467
                            fprintf(stderr,
8468
                                    "Boot device '%c' was given twice\n",*p);
8469
                            exit(1);
8470
                        }
8471
                        boot_devices_bitmap |= 1 << (*p - 'a');
8472
                    }
8473
                }
8474
                break;
8475
            case QEMU_OPTION_fda:
8476
            case QEMU_OPTION_fdb:
8477
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8478
                break;
8479
#ifdef TARGET_I386
8480
            case QEMU_OPTION_no_fd_bootchk:
8481
                fd_bootchk = 0;
8482
                break;
8483
#endif
8484
            case QEMU_OPTION_net:
8485
                if (nb_net_clients >= MAX_NET_CLIENTS) {
8486
                    fprintf(stderr, "qemu: too many network clients\n");
8487
                    exit(1);
8488
                }
8489
                net_clients[nb_net_clients] = optarg;
8490
                nb_net_clients++;
8491
                break;
8492
#ifdef CONFIG_SLIRP
8493
            case QEMU_OPTION_tftp:
8494
                tftp_prefix = optarg;
8495
                break;
8496
            case QEMU_OPTION_bootp:
8497
                bootp_filename = optarg;
8498
                break;
8499
#ifndef _WIN32
8500
            case QEMU_OPTION_smb:
8501
                net_slirp_smb(optarg);
8502
                break;
8503
#endif
8504
            case QEMU_OPTION_redir:
8505
                net_slirp_redir(optarg);
8506
                break;
8507
#endif
8508
#ifdef HAS_AUDIO
8509
            case QEMU_OPTION_audio_help:
8510
                AUD_help ();
8511
                exit (0);
8512
                break;
8513
            case QEMU_OPTION_soundhw:
8514
                select_soundhw (optarg);
8515
                break;
8516
#endif
8517
            case QEMU_OPTION_h:
8518
                help(0);
8519
                break;
8520
            case QEMU_OPTION_m: {
8521
                uint64_t value;
8522
                char *ptr;
8523

    
8524
                value = strtoul(optarg, &ptr, 10);
8525
                switch (*ptr) {
8526
                case 0: case 'M': case 'm':
8527
                    value <<= 20;
8528
                    break;
8529
                case 'G': case 'g':
8530
                    value <<= 30;
8531
                    break;
8532
                default:
8533
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8534
                    exit(1);
8535
                }
8536

    
8537
                /* On 32-bit hosts, QEMU is limited by virtual address space */
8538
                if (value > (2047 << 20)
8539
#ifndef USE_KQEMU
8540
                    && HOST_LONG_BITS == 32
8541
#endif
8542
                    ) {
8543
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8544
                    exit(1);
8545
                }
8546
                if (value != (uint64_t)(ram_addr_t)value) {
8547
                    fprintf(stderr, "qemu: ram size too large\n");
8548
                    exit(1);
8549
                }
8550
                ram_size = value;
8551
                break;
8552
            }
8553
            case QEMU_OPTION_d:
8554
                {
8555
                    int mask;
8556
                    CPULogItem *item;
8557

    
8558
                    mask = cpu_str_to_log_mask(optarg);
8559
                    if (!mask) {
8560
                        printf("Log items (comma separated):\n");
8561
                    for(item = cpu_log_items; item->mask != 0; item++) {
8562
                        printf("%-10s %s\n", item->name, item->help);
8563
                    }
8564
                    exit(1);
8565
                    }
8566
                    cpu_set_log(mask);
8567
                }
8568
                break;
8569
#ifdef CONFIG_GDBSTUB
8570
            case QEMU_OPTION_s:
8571
                use_gdbstub = 1;
8572
                break;
8573
            case QEMU_OPTION_p:
8574
                gdbstub_port = optarg;
8575
                break;
8576
#endif
8577
            case QEMU_OPTION_L:
8578
                bios_dir = optarg;
8579
                break;
8580
            case QEMU_OPTION_bios:
8581
                bios_name = optarg;
8582
                break;
8583
            case QEMU_OPTION_S:
8584
                autostart = 0;
8585
                break;
8586
            case QEMU_OPTION_k:
8587
                keyboard_layout = optarg;
8588
                break;
8589
            case QEMU_OPTION_localtime:
8590
                rtc_utc = 0;
8591
                break;
8592
            case QEMU_OPTION_cirrusvga:
8593
                cirrus_vga_enabled = 1;
8594
                vmsvga_enabled = 0;
8595
                break;
8596
            case QEMU_OPTION_vmsvga:
8597
                cirrus_vga_enabled = 0;
8598
                vmsvga_enabled = 1;
8599
                break;
8600
            case QEMU_OPTION_std_vga:
8601
                cirrus_vga_enabled = 0;
8602
                vmsvga_enabled = 0;
8603
                break;
8604
            case QEMU_OPTION_g:
8605
                {
8606
                    const char *p;
8607
                    int w, h, depth;
8608
                    p = optarg;
8609
                    w = strtol(p, (char **)&p, 10);
8610
                    if (w <= 0) {
8611
                    graphic_error:
8612
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8613
                        exit(1);
8614
                    }
8615
                    if (*p != 'x')
8616
                        goto graphic_error;
8617
                    p++;
8618
                    h = strtol(p, (char **)&p, 10);
8619
                    if (h <= 0)
8620
                        goto graphic_error;
8621
                    if (*p == 'x') {
8622
                        p++;
8623
                        depth = strtol(p, (char **)&p, 10);
8624
                        if (depth != 8 && depth != 15 && depth != 16 &&
8625
                            depth != 24 && depth != 32)
8626
                            goto graphic_error;
8627
                    } else if (*p == '\0') {
8628
                        depth = graphic_depth;
8629
                    } else {
8630
                        goto graphic_error;
8631
                    }
8632

    
8633
                    graphic_width = w;
8634
                    graphic_height = h;
8635
                    graphic_depth = depth;
8636
                }
8637
                break;
8638
            case QEMU_OPTION_echr:
8639
                {
8640
                    char *r;
8641
                    term_escape_char = strtol(optarg, &r, 0);
8642
                    if (r == optarg)
8643
                        printf("Bad argument to echr\n");
8644
                    break;
8645
                }
8646
            case QEMU_OPTION_monitor:
8647
                monitor_device = optarg;
8648
                break;
8649
            case QEMU_OPTION_serial:
8650
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8651
                    fprintf(stderr, "qemu: too many serial ports\n");
8652
                    exit(1);
8653
                }
8654
                serial_devices[serial_device_index] = optarg;
8655
                serial_device_index++;
8656
                break;
8657
            case QEMU_OPTION_parallel:
8658
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8659
                    fprintf(stderr, "qemu: too many parallel ports\n");
8660
                    exit(1);
8661
                }
8662
                parallel_devices[parallel_device_index] = optarg;
8663
                parallel_device_index++;
8664
                break;
8665
            case QEMU_OPTION_loadvm:
8666
                loadvm = optarg;
8667
                break;
8668
            case QEMU_OPTION_full_screen:
8669
                full_screen = 1;
8670
                break;
8671
#ifdef CONFIG_SDL
8672
            case QEMU_OPTION_no_frame:
8673
                no_frame = 1;
8674
                break;
8675
            case QEMU_OPTION_alt_grab:
8676
                alt_grab = 1;
8677
                break;
8678
            case QEMU_OPTION_no_quit:
8679
                no_quit = 1;
8680
                break;
8681
#endif
8682
            case QEMU_OPTION_pidfile:
8683
                pid_file = optarg;
8684
                break;
8685
#ifdef TARGET_I386
8686
            case QEMU_OPTION_win2k_hack:
8687
                win2k_install_hack = 1;
8688
                break;
8689
#endif
8690
#ifdef USE_KQEMU
8691
            case QEMU_OPTION_no_kqemu:
8692
                kqemu_allowed = 0;
8693
                break;
8694
            case QEMU_OPTION_kernel_kqemu:
8695
                kqemu_allowed = 2;
8696
                break;
8697
#endif
8698
            case QEMU_OPTION_usb:
8699
                usb_enabled = 1;
8700
                break;
8701
            case QEMU_OPTION_usbdevice:
8702
                usb_enabled = 1;
8703
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8704
                    fprintf(stderr, "Too many USB devices\n");
8705
                    exit(1);
8706
                }
8707
                usb_devices[usb_devices_index] = optarg;
8708
                usb_devices_index++;
8709
                break;
8710
            case QEMU_OPTION_smp:
8711
                smp_cpus = atoi(optarg);
8712
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8713
                    fprintf(stderr, "Invalid number of CPUs\n");
8714
                    exit(1);
8715
                }
8716
                break;
8717
            case QEMU_OPTION_vnc:
8718
                vnc_display = optarg;
8719
                break;
8720
            case QEMU_OPTION_no_acpi:
8721
                acpi_enabled = 0;
8722
                break;
8723
            case QEMU_OPTION_no_reboot:
8724
                no_reboot = 1;
8725
                break;
8726
            case QEMU_OPTION_no_shutdown:
8727
                no_shutdown = 1;
8728
                break;
8729
            case QEMU_OPTION_show_cursor:
8730
                cursor_hide = 0;
8731
                break;
8732
            case QEMU_OPTION_daemonize:
8733
                daemonize = 1;
8734
                break;
8735
            case QEMU_OPTION_option_rom:
8736
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8737
                    fprintf(stderr, "Too many option ROMs\n");
8738
                    exit(1);
8739
                }
8740
                option_rom[nb_option_roms] = optarg;
8741
                nb_option_roms++;
8742
                break;
8743
            case QEMU_OPTION_semihosting:
8744
                semihosting_enabled = 1;
8745
                break;
8746
            case QEMU_OPTION_name:
8747
                qemu_name = optarg;
8748
                break;
8749
#ifdef TARGET_SPARC
8750
            case QEMU_OPTION_prom_env:
8751
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8752
                    fprintf(stderr, "Too many prom variables\n");
8753
                    exit(1);
8754
                }
8755
                prom_envs[nb_prom_envs] = optarg;
8756
                nb_prom_envs++;
8757
                break;
8758
#endif
8759
#ifdef TARGET_ARM
8760
            case QEMU_OPTION_old_param:
8761
                old_param = 1;
8762
                break;
8763
#endif
8764
            case QEMU_OPTION_clock:
8765
                configure_alarms(optarg);
8766
                break;
8767
            case QEMU_OPTION_startdate:
8768
                {
8769
                    struct tm tm;
8770
                    time_t rtc_start_date;
8771
                    if (!strcmp(optarg, "now")) {
8772
                        rtc_date_offset = -1;
8773
                    } else {
8774
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8775
                               &tm.tm_year,
8776
                               &tm.tm_mon,
8777
                               &tm.tm_mday,
8778
                               &tm.tm_hour,
8779
                               &tm.tm_min,
8780
                               &tm.tm_sec) == 6) {
8781
                            /* OK */
8782
                        } else if (sscanf(optarg, "%d-%d-%d",
8783
                                          &tm.tm_year,
8784
                                          &tm.tm_mon,
8785
                                          &tm.tm_mday) == 3) {
8786
                            tm.tm_hour = 0;
8787
                            tm.tm_min = 0;
8788
                            tm.tm_sec = 0;
8789
                        } else {
8790
                            goto date_fail;
8791
                        }
8792
                        tm.tm_year -= 1900;
8793
                        tm.tm_mon--;
8794
                        rtc_start_date = mktimegm(&tm);
8795
                        if (rtc_start_date == -1) {
8796
                        date_fail:
8797
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8798
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8799
                            exit(1);
8800
                        }
8801
                        rtc_date_offset = time(NULL) - rtc_start_date;
8802
                    }
8803
                }
8804
                break;
8805
            case QEMU_OPTION_tb_size:
8806
                tb_size = strtol(optarg, NULL, 0);
8807
                if (tb_size < 0)
8808
                    tb_size = 0;
8809
                break;
8810
            case QEMU_OPTION_icount:
8811
                use_icount = 1;
8812
                if (strcmp(optarg, "auto") == 0) {
8813
                    icount_time_shift = -1;
8814
                } else {
8815
                    icount_time_shift = strtol(optarg, NULL, 0);
8816
                }
8817
                break;
8818
            }
8819
        }
8820
    }
8821

    
8822
    if (nographic) {
8823
       if (serial_device_index == 0)
8824
           serial_devices[0] = "stdio";
8825
       if (parallel_device_index == 0)
8826
           parallel_devices[0] = "null";
8827
       if (strncmp(monitor_device, "vc", 2) == 0)
8828
           monitor_device = "stdio";
8829
    }
8830

    
8831
#ifndef _WIN32
8832
    if (daemonize) {
8833
        pid_t pid;
8834

    
8835
        if (pipe(fds) == -1)
8836
            exit(1);
8837

    
8838
        pid = fork();
8839
        if (pid > 0) {
8840
            uint8_t status;
8841
            ssize_t len;
8842

    
8843
            close(fds[1]);
8844

    
8845
        again:
8846
            len = read(fds[0], &status, 1);
8847
            if (len == -1 && (errno == EINTR))
8848
                goto again;
8849

    
8850
            if (len != 1)
8851
                exit(1);
8852
            else if (status == 1) {
8853
                fprintf(stderr, "Could not acquire pidfile\n");
8854
                exit(1);
8855
            } else
8856
                exit(0);
8857
        } else if (pid < 0)
8858
            exit(1);
8859

    
8860
        setsid();
8861

    
8862
        pid = fork();
8863
        if (pid > 0)
8864
            exit(0);
8865
        else if (pid < 0)
8866
            exit(1);
8867

    
8868
        umask(027);
8869

    
8870
        signal(SIGTSTP, SIG_IGN);
8871
        signal(SIGTTOU, SIG_IGN);
8872
        signal(SIGTTIN, SIG_IGN);
8873
    }
8874
#endif
8875

    
8876
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8877
        if (daemonize) {
8878
            uint8_t status = 1;
8879
            write(fds[1], &status, 1);
8880
        } else
8881
            fprintf(stderr, "Could not acquire pid file\n");
8882
        exit(1);
8883
    }
8884

    
8885
#ifdef USE_KQEMU
8886
    if (smp_cpus > 1)
8887
        kqemu_allowed = 0;
8888
#endif
8889
    linux_boot = (kernel_filename != NULL);
8890
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8891

    
8892
    if (!linux_boot && net_boot == 0 &&
8893
        !machine->nodisk_ok && nb_drives_opt == 0)
8894
        help(1);
8895

    
8896
    if (!linux_boot && *kernel_cmdline != '\0') {
8897
        fprintf(stderr, "-append only allowed with -kernel option\n");
8898
        exit(1);
8899
    }
8900

    
8901
    if (!linux_boot && initrd_filename != NULL) {
8902
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
8903
        exit(1);
8904
    }
8905

    
8906
    /* boot to floppy or the default cd if no hard disk defined yet */
8907
    if (!boot_devices[0]) {
8908
        boot_devices = "cad";
8909
    }
8910
    setvbuf(stdout, NULL, _IOLBF, 0);
8911

    
8912
    init_timers();
8913
    init_timer_alarm();
8914
    qemu_aio_init();
8915
    if (use_icount && icount_time_shift < 0) {
8916
        use_icount = 2;
8917
        /* 125MIPS seems a reasonable initial guess at the guest speed.
8918
           It will be corrected fairly quickly anyway.  */
8919
        icount_time_shift = 3;
8920
        init_icount_adjust();
8921
    }
8922

    
8923
#ifdef _WIN32
8924
    socket_init();
8925
#endif
8926

    
8927
    /* init network clients */
8928
    if (nb_net_clients == 0) {
8929
        /* if no clients, we use a default config */
8930
        net_clients[0] = "nic";
8931
        net_clients[1] = "user";
8932
        nb_net_clients = 2;
8933
    }
8934

    
8935
    for(i = 0;i < nb_net_clients; i++) {
8936
        if (net_client_parse(net_clients[i]) < 0)
8937
            exit(1);
8938
    }
8939
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8940
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8941
            continue;
8942
        if (vlan->nb_guest_devs == 0)
8943
            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
8944
        if (vlan->nb_host_devs == 0)
8945
            fprintf(stderr,
8946
                    "Warning: vlan %d is not connected to host network\n",
8947
                    vlan->id);
8948
    }
8949

    
8950
#ifdef TARGET_I386
8951
    /* XXX: this should be moved in the PC machine instantiation code */
8952
    if (net_boot != 0) {
8953
        int netroms = 0;
8954
        for (i = 0; i < nb_nics && i < 4; i++) {
8955
            const char *model = nd_table[i].model;
8956
            char buf[1024];
8957
            if (net_boot & (1 << i)) {
8958
                if (model == NULL)
8959
                    model = "ne2k_pci";
8960
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8961
                if (get_image_size(buf) > 0) {
8962
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8963
                        fprintf(stderr, "Too many option ROMs\n");
8964
                        exit(1);
8965
                    }
8966
                    option_rom[nb_option_roms] = strdup(buf);
8967
                    nb_option_roms++;
8968
                    netroms++;
8969
                }
8970
            }
8971
        }
8972
        if (netroms == 0) {
8973
            fprintf(stderr, "No valid PXE rom found for network device\n");
8974
            exit(1);
8975
        }
8976
    }
8977
#endif
8978

    
8979
    /* init the memory */
8980
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
8981

    
8982
    if (machine->ram_require & RAMSIZE_FIXED) {
8983
        if (ram_size > 0) {
8984
            if (ram_size < phys_ram_size) {
8985
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
8986
                                machine->name, (unsigned long long) phys_ram_size);
8987
                exit(-1);
8988
            }
8989

    
8990
            phys_ram_size = ram_size;
8991
        } else
8992
            ram_size = phys_ram_size;
8993
    } else {
8994
        if (ram_size == 0)
8995
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8996

    
8997
        phys_ram_size += ram_size;
8998
    }
8999

    
9000
    phys_ram_base = qemu_vmalloc(phys_ram_size);
9001
    if (!phys_ram_base) {
9002
        fprintf(stderr, "Could not allocate physical memory\n");
9003
        exit(1);
9004
    }
9005

    
9006
    /* init the dynamic translator */
9007
    cpu_exec_init_all(tb_size * 1024 * 1024);
9008

    
9009
    bdrv_init();
9010

    
9011
    /* we always create the cdrom drive, even if no disk is there */
9012

    
9013
    if (nb_drives_opt < MAX_DRIVES)
9014
        drive_add(NULL, CDROM_ALIAS);
9015

    
9016
    /* we always create at least one floppy */
9017

    
9018
    if (nb_drives_opt < MAX_DRIVES)
9019
        drive_add(NULL, FD_ALIAS, 0);
9020

    
9021
    /* we always create one sd slot, even if no card is in it */
9022

    
9023
    if (nb_drives_opt < MAX_DRIVES)
9024
        drive_add(NULL, SD_ALIAS);
9025

    
9026
    /* open the virtual block devices */
9027

    
9028
    for(i = 0; i < nb_drives_opt; i++)
9029
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9030
            exit(1);
9031

    
9032
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9033
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9034

    
9035
    /* terminal init */
9036
    memset(&display_state, 0, sizeof(display_state));
9037
    if (nographic) {
9038
        if (curses) {
9039
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9040
            exit(1);
9041
        }
9042
        /* nearly nothing to do */
9043
        dumb_display_init(ds);
9044
    } else if (vnc_display != NULL) {
9045
        vnc_display_init(ds);
9046
        if (vnc_display_open(ds, vnc_display) < 0)
9047
            exit(1);
9048
    } else
9049
#if defined(CONFIG_CURSES)
9050
    if (curses) {
9051
        curses_display_init(ds, full_screen);
9052
    } else
9053
#endif
9054
    {
9055
#if defined(CONFIG_SDL)
9056
        sdl_display_init(ds, full_screen, no_frame);
9057
#elif defined(CONFIG_COCOA)
9058
        cocoa_display_init(ds, full_screen);
9059
#else
9060
        dumb_display_init(ds);
9061
#endif
9062
    }
9063

    
9064
    /* Maintain compatibility with multiple stdio monitors */
9065
    if (!strcmp(monitor_device,"stdio")) {
9066
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9067
            const char *devname = serial_devices[i];
9068
            if (devname && !strcmp(devname,"mon:stdio")) {
9069
                monitor_device = NULL;
9070
                break;
9071
            } else if (devname && !strcmp(devname,"stdio")) {
9072
                monitor_device = NULL;
9073
                serial_devices[i] = "mon:stdio";
9074
                break;
9075
            }
9076
        }
9077
    }
9078
    if (monitor_device) {
9079
        monitor_hd = qemu_chr_open(monitor_device);
9080
        if (!monitor_hd) {
9081
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9082
            exit(1);
9083
        }
9084
        monitor_init(monitor_hd, !nographic);
9085
    }
9086

    
9087
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9088
        const char *devname = serial_devices[i];
9089
        if (devname && strcmp(devname, "none")) {
9090
            serial_hds[i] = qemu_chr_open(devname);
9091
            if (!serial_hds[i]) {
9092
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
9093
                        devname);
9094
                exit(1);
9095
            }
9096
            if (strstart(devname, "vc", 0))
9097
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9098
        }
9099
    }
9100

    
9101
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9102
        const char *devname = parallel_devices[i];
9103
        if (devname && strcmp(devname, "none")) {
9104
            parallel_hds[i] = qemu_chr_open(devname);
9105
            if (!parallel_hds[i]) {
9106
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9107
                        devname);
9108
                exit(1);
9109
            }
9110
            if (strstart(devname, "vc", 0))
9111
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9112
        }
9113
    }
9114

    
9115
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
9116
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9117

    
9118
    /* init USB devices */
9119
    if (usb_enabled) {
9120
        for(i = 0; i < usb_devices_index; i++) {
9121
            if (usb_device_add(usb_devices[i]) < 0) {
9122
                fprintf(stderr, "Warning: could not add USB device %s\n",
9123
                        usb_devices[i]);
9124
            }
9125
        }
9126
    }
9127

    
9128
    if (display_state.dpy_refresh) {
9129
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9130
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9131
    }
9132

    
9133
#ifdef CONFIG_GDBSTUB
9134
    if (use_gdbstub) {
9135
        /* XXX: use standard host:port notation and modify options
9136
           accordingly. */
9137
        if (gdbserver_start(gdbstub_port) < 0) {
9138
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9139
                    gdbstub_port);
9140
            exit(1);
9141
        }
9142
    }
9143
#endif
9144

    
9145
    if (loadvm)
9146
        do_loadvm(loadvm);
9147

    
9148
    {
9149
        /* XXX: simplify init */
9150
        read_passwords();
9151
        if (autostart) {
9152
            vm_start();
9153
        }
9154
    }
9155

    
9156
    if (daemonize) {
9157
        uint8_t status = 0;
9158
        ssize_t len;
9159
        int fd;
9160

    
9161
    again1:
9162
        len = write(fds[1], &status, 1);
9163
        if (len == -1 && (errno == EINTR))
9164
            goto again1;
9165

    
9166
        if (len != 1)
9167
            exit(1);
9168

    
9169
        chdir("/");
9170
        TFR(fd = open("/dev/null", O_RDWR));
9171
        if (fd == -1)
9172
            exit(1);
9173

    
9174
        dup2(fd, 0);
9175
        dup2(fd, 1);
9176
        dup2(fd, 2);
9177

    
9178
        close(fd);
9179
    }
9180

    
9181
    main_loop();
9182
    quit_timers();
9183

    
9184
#if !defined(_WIN32)
9185
    /* close network clients */
9186
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9187
        VLANClientState *vc;
9188

    
9189
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9190
            if (vc->fd_read == tap_receive) {
9191
                char ifname[64];
9192
                TAPState *s = vc->opaque;
9193

    
9194
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9195
                    s->down_script[0])
9196
                    launch_script(s->down_script, ifname, s->fd);
9197
            }
9198
#if defined(CONFIG_VDE)
9199
            if (vc->fd_read == vde_from_qemu) {
9200
                VDEState *s = vc->opaque;
9201
                vde_close(s->vde);
9202
            }
9203
#endif
9204
        }
9205
    }
9206
#endif
9207
    return 0;
9208
}