Statistics
| Branch: | Revision:

root / vl.c @ 563e3c6e

History | View | Annotate | Download (239.1 kB)

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

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

    
49
#ifndef _WIN32
50
#include <sys/times.h>
51
#include <sys/wait.h>
52
#include <termios.h>
53
#include <sys/poll.h>
54
#include <sys/mman.h>
55
#include <sys/ioctl.h>
56
#include <sys/socket.h>
57
#include <netinet/in.h>
58
#include <dirent.h>
59
#include <netdb.h>
60
#include <sys/select.h>
61
#include <arpa/inet.h>
62
#ifdef _BSD
63
#include <sys/stat.h>
64
#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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
405
/***********************************************************/
406

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

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

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

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

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

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

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

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

    
513
/***********************************************************/
514
/* keyboard/mouse */
515

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

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

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

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

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

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

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

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

    
555
    return s;
556
}
557

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

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

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

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

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

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

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

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

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

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

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

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

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

    
632
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
633
}
634

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

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

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

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

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

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

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

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

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

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

    
705
#define QEMU_TIMER_BASE 1000000000LL
706

    
707
#ifdef WIN32
708

    
709
static int64_t clock_freq;
710

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

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

    
730
#else
731

    
732
static int use_rt_clock;
733

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

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

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

    
780
/***********************************************************/
781
/* guest cycle counter */
782

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

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

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

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

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

    
842
/***********************************************************/
843
/* timers */
844

    
845
#define QEMU_TIMER_REALTIME 0
846
#define QEMU_TIMER_VIRTUAL  1
847

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

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

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

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

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

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

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

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

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

    
890
static struct qemu_alarm_timer *alarm_timer;
891

    
892
#ifdef _WIN32
893

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

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

    
904
#else
905

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

    
909
#ifdef __linux__
910

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

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

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

    
921
#endif /* __linux__ */
922

    
923
#endif /* _WIN32 */
924

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

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

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

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

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

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

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

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

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

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

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

    
1033
    arg = strdup(opt);
1034

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

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

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

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

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

    
1062
    free(arg);
1063

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

    
1074
QEMUClock *rt_clock;
1075
QEMUClock *vm_clock;
1076

    
1077
static QEMUTimer *active_timers[2];
1078

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

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

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

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

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

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

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

    
1131
    qemu_del_timer(ts);
1132

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1316
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1317

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

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

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

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

    
1346
    return delta;
1347
}
1348

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

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

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

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

    
1369
    return delta;
1370
}
1371

    
1372
#ifndef _WIN32
1373

    
1374
#if defined(__linux__)
1375

    
1376
#define RTC_FREQ 1024
1377

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

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

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

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

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

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

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

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

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

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

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

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

    
1438
    close(fd);
1439
}
1440

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

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

    
1463
    enable_sigio_timer(rtc_fd);
1464

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

    
1467
    return 0;
1468
}
1469

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

    
1474
    close(rtc_fd);
1475
}
1476

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

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

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

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

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

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

    
1499
        return -1;
1500
    }
1501

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

    
1504
    return 0;
1505
}
1506

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

    
1511
    timer_delete(host_timer);
1512
}
1513

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

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

    
1525
    nearest_delta_us = qemu_next_deadline_dyntick();
1526

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

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

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

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

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

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

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

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

    
1573
    return 0;
1574
}
1575

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

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

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

    
1586
#ifdef _WIN32
1587

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

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

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

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

    
1606
    timeBeginPeriod(data->period);
1607

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

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

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

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

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

    
1630
    return 0;
1631
}
1632

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

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

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

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

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

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

    
1655
    timeKillEvent(data->timerId);
1656

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

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

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

    
1672
#endif /* _WIN32 */
1673

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

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

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

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

    
1693
    alarm_timer = t;
1694
}
1695

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

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

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

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

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

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

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

    
1739
/***********************************************************/
1740
/* character device */
1741

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1861

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

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

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

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

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

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

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

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

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

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

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

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

    
2015
    mux_chr_accept_input (opaque);
2016

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

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

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

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

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

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

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

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

    
2084

    
2085
#ifdef _WIN32
2086

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

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

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

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

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

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

    
2136
#else
2137

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

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

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

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

    
2171
#ifndef _WIN32
2172

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

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

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

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

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

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

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

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

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

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

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

    
2243
    qemu_free(s);
2244
}
2245

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

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

    
2267
    qemu_chr_reset(chr);
2268

    
2269
    return chr;
2270
}
2271

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

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

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

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

    
2303

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

    
2307
#define TERM_FIFO_MAX_SIZE 1
2308

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2408
    return chr;
2409
}
2410

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

    
2419
        *amaster = *aslave = -1;
2420

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

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

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

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

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

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

    
2445
        return 0;
2446

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2624
    return chr;
2625
}
2626

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2884
static void pp_close(CharDriverState *chr)
2885
{
2886
    ParallelCharDriver *drv = chr->opaque;
2887
    int fd = drv->fd;
2888

    
2889
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2890
    ioctl(fd, PPRELEASE);
2891
    close(fd);
2892
    qemu_free(drv);
2893
}
2894

    
2895
static CharDriverState *qemu_chr_open_pp(const char *filename)
2896
{
2897
    CharDriverState *chr;
2898
    ParallelCharDriver *drv;
2899
    int fd;
2900

    
2901
    TFR(fd = open(filename, O_RDWR));
2902
    if (fd < 0)
2903
        return NULL;
2904

    
2905
    if (ioctl(fd, PPCLAIM) < 0) {
2906
        close(fd);
2907
        return NULL;
2908
    }
2909

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

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

    
2929
    qemu_chr_reset(chr);
2930

    
2931
    return chr;
2932
}
2933
#endif /* __linux__ */
2934

    
2935
#else /* _WIN32 */
2936

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

    
2945
#define NSENDBUF 2048
2946
#define NRECVBUF 2048
2947
#define MAXCONNECT 1
2948
#define NTIMEOUT 5000
2949

    
2950
static int win_chr_poll(void *opaque);
2951
static int win_chr_pipe_poll(void *opaque);
2952

    
2953
static void win_chr_close(CharDriverState *chr)
2954
{
2955
    WinCharState *s = chr->opaque;
2956

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

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

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

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

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

    
3008
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3009
    size = sizeof(COMMCONFIG);
3010
    GetDefaultCommConfig(filename, &comcfg, &size);
3011
    comcfg.dcb.DCBlength = sizeof(DCB);
3012
    CommConfigDialog(filename, NULL, &comcfg);
3013

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

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

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

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

    
3037
 fail:
3038
    win_chr_close(chr);
3039
    return -1;
3040
}
3041

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

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

    
3076
static int win_chr_read_poll(CharDriverState *chr)
3077
{
3078
    WinCharState *s = chr->opaque;
3079

    
3080
    s->max_size = qemu_chr_can_read(chr);
3081
    return s->max_size;
3082
}
3083

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

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

    
3101
    if (size > 0) {
3102
        qemu_chr_read(chr, buf, size);
3103
    }
3104
}
3105

    
3106
static void win_chr_read(CharDriverState *chr)
3107
{
3108
    WinCharState *s = chr->opaque;
3109

    
3110
    if (s->len > s->max_size)
3111
        s->len = s->max_size;
3112
    if (s->len == 0)
3113
        return;
3114

    
3115
    win_chr_readfile(chr);
3116
}
3117

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

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

    
3135
static CharDriverState *qemu_chr_open_win(const char *filename)
3136
{
3137
    CharDriverState *chr;
3138
    WinCharState *s;
3139

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

    
3152
    if (win_chr_init(chr, filename) < 0) {
3153
        free(s);
3154
        free(chr);
3155
        return NULL;
3156
    }
3157
    qemu_chr_reset(chr);
3158
    return chr;
3159
}
3160

    
3161
static int win_chr_pipe_poll(void *opaque)
3162
{
3163
    CharDriverState *chr = opaque;
3164
    WinCharState *s = chr->opaque;
3165
    DWORD size;
3166

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

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

    
3185
    s->fpipe = TRUE;
3186

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

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

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

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

    
3227
    if (ov.hEvent) {
3228
        CloseHandle(ov.hEvent);
3229
        ov.hEvent = NULL;
3230
    }
3231
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
3232
    return 0;
3233

    
3234
 fail:
3235
    win_chr_close(chr);
3236
    return -1;
3237
}
3238

    
3239

    
3240
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3241
{
3242
    CharDriverState *chr;
3243
    WinCharState *s;
3244

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

    
3257
    if (win_chr_pipe_init(chr, filename) < 0) {
3258
        free(s);
3259
        free(chr);
3260
        return NULL;
3261
    }
3262
    qemu_chr_reset(chr);
3263
    return chr;
3264
}
3265

    
3266
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3267
{
3268
    CharDriverState *chr;
3269
    WinCharState *s;
3270

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

    
3286
static CharDriverState *qemu_chr_open_win_con(const char *filename)
3287
{
3288
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3289
}
3290

    
3291
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3292
{
3293
    HANDLE fd_out;
3294

    
3295
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3296
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3297
    if (fd_out == INVALID_HANDLE_VALUE)
3298
        return NULL;
3299

    
3300
    return qemu_chr_open_win_file(fd_out);
3301
}
3302
#endif /* !_WIN32 */
3303

    
3304
/***********************************************************/
3305
/* UDP Net console */
3306

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

    
3316
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3317
{
3318
    NetCharDriver *s = chr->opaque;
3319

    
3320
    return sendto(s->fd, buf, len, 0,
3321
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3322
}
3323

    
3324
static int udp_chr_read_poll(void *opaque)
3325
{
3326
    CharDriverState *chr = opaque;
3327
    NetCharDriver *s = chr->opaque;
3328

    
3329
    s->max_size = qemu_chr_can_read(chr);
3330

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

    
3342
static void udp_chr_read(void *opaque)
3343
{
3344
    CharDriverState *chr = opaque;
3345
    NetCharDriver *s = chr->opaque;
3346

    
3347
    if (s->max_size == 0)
3348
        return;
3349
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3350
    s->bufptr = s->bufcnt;
3351
    if (s->bufcnt <= 0)
3352
        return;
3353

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

    
3362
static void udp_chr_update_read_handler(CharDriverState *chr)
3363
{
3364
    NetCharDriver *s = chr->opaque;
3365

    
3366
    if (s->fd >= 0) {
3367
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3368
                             udp_chr_read, NULL, chr);
3369
    }
3370
}
3371

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

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

    
3387
    chr = qemu_mallocz(sizeof(CharDriverState));
3388
    if (!chr)
3389
        goto return_err;
3390
    s = qemu_mallocz(sizeof(NetCharDriver));
3391
    if (!s)
3392
        goto return_err;
3393

    
3394
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3395
    if (fd < 0) {
3396
        perror("socket(PF_INET, SOCK_DGRAM)");
3397
        goto return_err;
3398
    }
3399

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

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

    
3411
    s->fd = fd;
3412
    s->bufcnt = 0;
3413
    s->bufptr = 0;
3414
    chr->opaque = s;
3415
    chr->chr_write = udp_chr_write;
3416
    chr->chr_update_read_handler = udp_chr_update_read_handler;
3417
    return chr;
3418

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

    
3429
/***********************************************************/
3430
/* TCP Net console */
3431

    
3432
typedef struct {
3433
    int fd, listen_fd;
3434
    int connected;
3435
    int max_size;
3436
    int do_telnetopt;
3437
    int do_nodelay;
3438
    int is_unix;
3439
} TCPCharDriver;
3440

    
3441
static void tcp_chr_accept(void *opaque);
3442

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

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

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

    
3479
    int i;
3480
    int j = 0;
3481

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

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

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

    
3544
static void tcp_chr_connect(void *opaque)
3545
{
3546
    CharDriverState *chr = opaque;
3547
    TCPCharDriver *s = chr->opaque;
3548

    
3549
    s->connected = 1;
3550
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3551
                         tcp_chr_read, NULL, chr);
3552
    qemu_chr_reset(chr);
3553
}
3554

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

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

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

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

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

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

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

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

    
3676
    chr = qemu_mallocz(sizeof(CharDriverState));
3677
    if (!chr)
3678
        goto fail;
3679
    s = qemu_mallocz(sizeof(TCPCharDriver));
3680
    if (!s)
3681
        goto fail;
3682

    
3683
#ifndef _WIN32
3684
    if (is_unix)
3685
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3686
    else
3687
#endif
3688
        fd = socket(PF_INET, SOCK_STREAM, 0);
3689

    
3690
    if (fd < 0)
3691
        goto fail;
3692

    
3693
    if (!is_waitconnect)
3694
        socket_set_nonblock(fd);
3695

    
3696
    s->connected = 0;
3697
    s->fd = -1;
3698
    s->listen_fd = -1;
3699
    s->is_unix = is_unix;
3700
    s->do_nodelay = do_nodelay && !is_unix;
3701

    
3702
    chr->opaque = s;
3703
    chr->chr_write = tcp_chr_write;
3704
    chr->chr_close = tcp_chr_close;
3705

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

    
3720
        ret = bind(fd, addr, addrlen);
3721
        if (ret < 0)
3722
            goto fail;
3723

    
3724
        ret = listen(fd, 0);
3725
        if (ret < 0)
3726
            goto fail;
3727

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

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

    
3766
    return chr;
3767
 fail:
3768
    if (fd >= 0)
3769
        closesocket(fd);
3770
    qemu_free(s);
3771
    qemu_free(chr);
3772
    return NULL;
3773
}
3774

    
3775
CharDriverState *qemu_chr_open(const char *filename)
3776
{
3777
    const char *p;
3778

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

    
3851
void qemu_chr_close(CharDriverState *chr)
3852
{
3853
    if (chr->chr_close)
3854
        chr->chr_close(chr);
3855
    qemu_free(chr);
3856
}
3857

    
3858
/***********************************************************/
3859
/* network device redirectors */
3860

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

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

    
3888
static int parse_macaddr(uint8_t *macaddr, const char *p)
3889
{
3890
    int i;
3891
    char *last_char;
3892
    long int offset;
3893

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

    
3917
    return -1;
3918
}
3919

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

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

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

    
3957
    if ((src_str = strchr(input_str,'@'))) {
3958
        *src_str = '\0';
3959
        src_str++;
3960
    }
3961

    
3962
    if (parse_host_port(haddr, host_str) < 0)
3963
        goto fail;
3964

    
3965
    if (!src_str || *src_str == '\0')
3966
        src_str = ":0";
3967

    
3968
    if (parse_host_port(saddr, src_str) < 0)
3969
        goto fail;
3970

    
3971
    free(str);
3972
    return(0);
3973

    
3974
fail:
3975
    free(str);
3976
    return -1;
3977
}
3978

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

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

    
4009
#ifndef _WIN32
4010
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4011
{
4012
    const char *p;
4013
    int len;
4014

    
4015
    len = MIN(108, strlen(str));
4016
    p = strchr(str, ',');
4017
    if (p)
4018
        len = MIN(len, p - str);
4019

    
4020
    memset(uaddr, 0, sizeof(*uaddr));
4021

    
4022
    uaddr->sun_family = AF_UNIX;
4023
    memcpy(uaddr->sun_path, str, len);
4024

    
4025
    return 0;
4026
}
4027
#endif
4028

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

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

    
4063
    vc->next = NULL;
4064
    pvc = &vlan->first_client;
4065
    while (*pvc != NULL)
4066
        pvc = &(*pvc)->next;
4067
    *pvc = vc;
4068
    return vc;
4069
}
4070

    
4071
void qemu_del_vlan_client(VLANClientState *vc)
4072
{
4073
    VLANClientState **pvc = &vc->vlan->first_client;
4074

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

    
4084
int qemu_can_send_packet(VLANClientState *vc1)
4085
{
4086
    VLANState *vlan = vc1->vlan;
4087
    VLANClientState *vc;
4088

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

    
4098
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4099
{
4100
    VLANState *vlan = vc1->vlan;
4101
    VLANClientState *vc;
4102

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

    
4114
#if defined(CONFIG_SLIRP)
4115

    
4116
/* slirp network adapter */
4117

    
4118
static int slirp_inited;
4119
static VLANClientState *slirp_vc;
4120

    
4121
int slirp_can_output(void)
4122
{
4123
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
4124
}
4125

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

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

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

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

    
4166
    if (!slirp_inited) {
4167
        slirp_inited = 1;
4168
        slirp_init();
4169
    }
4170

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

    
4182
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4183
        goto fail;
4184
    host_port = strtol(buf, &r, 0);
4185
    if (r == buf)
4186
        goto fail;
4187

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

    
4196
    guest_port = strtol(p, &r, 0);
4197
    if (r == p)
4198
        goto fail;
4199

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

    
4210
#ifndef _WIN32
4211

    
4212
char smb_dir[1024];
4213

    
4214
static void erase_dir(char *dir_name)
4215
{
4216
    DIR *d;
4217
    struct dirent *de;
4218
    char filename[1024];
4219

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

    
4239
/* automatic user mode samba server configuration */
4240
static void smb_exit(void)
4241
{
4242
    erase_dir(smb_dir);
4243
}
4244

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

    
4252
    if (!slirp_inited) {
4253
        slirp_inited = 1;
4254
        slirp_init();
4255
    }
4256

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

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

    
4294
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4295
             SMBD_COMMAND, smb_conf);
4296

    
4297
    slirp_add_exec(0, smb_cmdline, 4, 139);
4298
}
4299

    
4300
#endif /* !defined(_WIN32) */
4301
void do_info_slirp(void)
4302
{
4303
    slirp_stats();
4304
}
4305

    
4306
#endif /* CONFIG_SLIRP */
4307

    
4308
#if !defined(_WIN32)
4309

    
4310
typedef struct TAPState {
4311
    VLANClientState *vc;
4312
    int fd;
4313
    char down_script[1024];
4314
} TAPState;
4315

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

    
4329
static void tap_send(void *opaque)
4330
{
4331
    TAPState *s = opaque;
4332
    uint8_t buf[4096];
4333
    int size;
4334

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

    
4349
/* fd support */
4350

    
4351
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4352
{
4353
    TAPState *s;
4354

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

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

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

    
4378
    fstat(fd, &s);
4379
    dev = devname(s.st_rdev, S_IFCHR);
4380
    pstrcpy(ifname, ifname_size, dev);
4381

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

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

    
4404
    memset(&ifr, 0x0, sizeof(ifr));
4405

    
4406
    if( *dev ){
4407
       ptr = dev;
4408
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
4409
       ppa = atoi(ptr);
4410
    }
4411

    
4412
    /* Check if IP device was opened */
4413
    if( ip_fd )
4414
       close(ip_fd);
4415

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

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

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

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

    
4446
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4447
        syslog(LOG_ERR, "Can't get flags\n");
4448

    
4449
    snprintf (actual_name, 32, "tap%d", ppa);
4450
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4451

    
4452
    ifr.lifr_ppa = ppa;
4453
    /* Assign ppa according to the unit number returned by tun device */
4454

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

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

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

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

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

    
4490
    close (if_fd);
4491

    
4492
    memset(&ifr, 0x0, sizeof(ifr));
4493
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4494
    ifr.lifr_ip_muxid  = ip_muxid;
4495
    ifr.lifr_arp_muxid = arp_muxid;
4496

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

    
4504
    snprintf(dev, dev_size, "tap%d", ppa);
4505
    return tap_fd;
4506
}
4507

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

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

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

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

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

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

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

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

    
4616
#endif /* !_WIN32 */
4617

    
4618
#if defined(CONFIG_VDE)
4619
typedef struct VDEState {
4620
    VLANClientState *vc;
4621
    VDECONN *vde;
4622
} VDEState;
4623

    
4624
static void vde_to_qemu(void *opaque)
4625
{
4626
    VDEState *s = opaque;
4627
    uint8_t buf[4096];
4628
    int size;
4629

    
4630
    size = vde_recv(s->vde, buf, sizeof(buf), 0);
4631
    if (size > 0) {
4632
        qemu_send_packet(s->vc, buf, size);
4633
    }
4634
}
4635

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

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

    
4656
    struct vde_open_args args = {
4657
        .port = port,
4658
        .group = init_group,
4659
        .mode = mode,
4660
    };
4661

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

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

    
4689
typedef struct NetSocketListenState {
4690
    VLANState *vlan;
4691
    int fd;
4692
} NetSocketListenState;
4693

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

    
4701
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4702
    send_all(s->fd, buf, size);
4703
}
4704

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

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

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

    
4768
static void net_socket_send_dgram(void *opaque)
4769
{
4770
    NetSocketState *s = opaque;
4771
    int size;
4772

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

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

    
4795
    }
4796
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4797
    if (fd < 0) {
4798
        perror("socket(PF_INET, SOCK_DGRAM)");
4799
        return -1;
4800
    }
4801

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

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

    
4816
    /* Add host to multicast group */
4817
    imr.imr_multiaddr = mcastaddr->sin_addr;
4818
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4819

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

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

    
4836
    socket_set_nonblock(fd);
4837
    return fd;
4838
fail:
4839
    if (fd >= 0)
4840
        closesocket(fd);
4841
    return -1;
4842
}
4843

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

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

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

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

    
4883
    s = qemu_mallocz(sizeof(NetSocketState));
4884
    if (!s)
4885
        return NULL;
4886
    s->fd = fd;
4887

    
4888
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4889
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4890

    
4891
    /* mcast: save bound address as dst */
4892
    if (is_connected) s->dgram_dst=saddr;
4893

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

    
4901
static void net_socket_connect(void *opaque)
4902
{
4903
    NetSocketState *s = opaque;
4904
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4905
}
4906

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

    
4927
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4928
                                          int is_connected)
4929
{
4930
    int so_type=-1, optlen=sizeof(so_type);
4931

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

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

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

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

    
4983
    if (parse_host_port(&saddr, host_str) < 0)
4984
        return -1;
4985

    
4986
    s = qemu_mallocz(sizeof(NetSocketListenState));
4987
    if (!s)
4988
        return -1;
4989

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

    
4997
    /* allow fast reuse */
4998
    val = 1;
4999
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5000

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

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

    
5023
    if (parse_host_port(&saddr, host_str) < 0)
5024
        return -1;
5025

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

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

    
5064
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5065
{
5066
    NetSocketState *s;
5067
    int fd;
5068
    struct sockaddr_in saddr;
5069

    
5070
    if (parse_host_port(&saddr, host_str) < 0)
5071
        return -1;
5072

    
5073

    
5074
    fd = net_socket_mcast_create(&saddr);
5075
    if (fd < 0)
5076
        return -1;
5077

    
5078
    s = net_socket_fd_init(vlan, fd, 0);
5079
    if (!s)
5080
        return -1;
5081

    
5082
    s->dgram_dst = saddr;
5083

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

    
5089
}
5090

    
5091
static const char *get_opt_name(char *buf, int buf_size, const char *p)
5092
{
5093
    char *q;
5094

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

    
5104
    return p;
5105
}
5106

    
5107
static const char *get_opt_value(char *buf, int buf_size, const char *p)
5108
{
5109
    char *q;
5110

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

    
5125
    return p;
5126
}
5127

    
5128
static int get_param_value(char *buf, int buf_size,
5129
                           const char *tag, const char *str)
5130
{
5131
    const char *p;
5132
    char option[128];
5133

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

    
5153
static int check_params(char *buf, int buf_size,
5154
                        char **params, const char *str)
5155
{
5156
    const char *p;
5157
    int i;
5158

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

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

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

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

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

    
5325
    return ret;
5326
}
5327

    
5328
static int net_client_parse(const char *str)
5329
{
5330
    const char *p;
5331
    char *q;
5332
    char device[64];
5333

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

    
5345
    return net_client_init(device, p);
5346
}
5347

    
5348
void do_info_network(void)
5349
{
5350
    VLANState *vlan;
5351
    VLANClientState *vc;
5352

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

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

    
5371
static int drive_add(const char *file, const char *fmt, ...)
5372
{
5373
    va_list ap;
5374

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

    
5380
    drives_opt[nb_drives_opt].file = file;
5381
    va_start(ap, fmt);
5382
    vsnprintf(drives_opt[nb_drives_opt].opt,
5383
              sizeof(drives_opt[0].opt), fmt, ap);
5384
    va_end(ap);
5385

    
5386
    return nb_drives_opt++;
5387
}
5388

    
5389
int drive_get_index(BlockInterfaceType type, int bus, int unit)
5390
{
5391
    int index;
5392

    
5393
    /* seek interface, bus and unit */
5394

    
5395
    for (index = 0; index < nb_drives; index++)
5396
        if (drives_table[index].type == type &&
5397
            drives_table[index].bus == bus &&
5398
            drives_table[index].unit == unit)
5399
        return index;
5400

    
5401
    return -1;
5402
}
5403

    
5404
int drive_get_max_bus(BlockInterfaceType type)
5405
{
5406
    int max_bus;
5407
    int index;
5408

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

    
5418
static void bdrv_format_print(void *opaque, const char *name)
5419
{
5420
    fprintf(stderr, " %s", name);
5421
}
5422

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

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

    
5451
    file[0] = 0;
5452
    cyls = heads = secs = 0;
5453
    bus_id = 0;
5454
    unit_id = -1;
5455
    translation = BIOS_ATA_TRANSLATION_AUTO;
5456
    index = -1;
5457
    cache = 1;
5458

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

    
5475
    /* extract parameters */
5476

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

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

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

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

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

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

    
5535
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
5536
        secs = strtol(buf, NULL, 0);
5537
    }
5538

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

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

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

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

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

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

    
5625
    if (arg->file == NULL)
5626
        get_param_value(file, sizeof(file), "file", str);
5627
    else
5628
        pstrcpy(file, sizeof(file), arg->file);
5629

    
5630
    /* compute bus and unit according index */
5631

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

    
5648
    /* if user doesn't specify a unit_id,
5649
     * try to find the first free
5650
     */
5651

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

    
5663
    /* check unit id */
5664

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

    
5671
    /*
5672
     * ignore multiple definitions
5673
     */
5674

    
5675
    if (drive_get_index(type, bus_id, unit_id) != -1)
5676
        return 0;
5677

    
5678
    /* init */
5679

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

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

    
5735
/***********************************************************/
5736
/* USB devices */
5737

    
5738
static USBPort *used_usb_ports;
5739
static USBPort *free_usb_ports;
5740

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

    
5752
int usb_device_add_dev(USBDevice *dev)
5753
{
5754
    USBPort *port;
5755

    
5756
    /* Find a USB port to add the device to.  */
5757
    port = free_usb_ports;
5758
    if (!port->next) {
5759
        USBDevice *hub;
5760

    
5761
        /* Create a new hub and chain it on.  */
5762
        free_usb_ports = NULL;
5763
        port->next = used_usb_ports;
5764
        used_usb_ports = port;
5765

    
5766
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5767
        usb_attach(port, hub);
5768
        port = free_usb_ports;
5769
    }
5770

    
5771
    free_usb_ports = port->next;
5772
    port->next = used_usb_ports;
5773
    used_usb_ports = port;
5774
    usb_attach(port, dev);
5775
    return 0;
5776
}
5777

    
5778
static int usb_device_add(const char *devname)
5779
{
5780
    const char *p;
5781
    USBDevice *dev;
5782
    USBPort *port;
5783

    
5784
    if (!free_usb_ports)
5785
        return -1;
5786

    
5787
    if (strstart(devname, "host:", &p)) {
5788
        dev = usb_host_device_open(p);
5789
    } else if (!strcmp(devname, "mouse")) {
5790
        dev = usb_mouse_init();
5791
    } else if (!strcmp(devname, "tablet")) {
5792
        dev = usb_tablet_init();
5793
    } else if (!strcmp(devname, "keyboard")) {
5794
        dev = usb_keyboard_init();
5795
    } else if (strstart(devname, "disk:", &p)) {
5796
        dev = usb_msd_init(p);
5797
    } else if (!strcmp(devname, "wacom-tablet")) {
5798
        dev = usb_wacom_init();
5799
    } else if (strstart(devname, "serial:", &p)) {
5800
        dev = usb_serial_init(p);
5801
#ifdef CONFIG_BRLAPI
5802
    } else if (!strcmp(devname, "braille")) {
5803
        dev = usb_baum_init();
5804
#endif
5805
    } else if (strstart(devname, "net:", &p)) {
5806
        int nic = nb_nics;
5807

    
5808
        if (net_client_init("nic", p) < 0)
5809
            return -1;
5810
        nd_table[nic].model = "usb";
5811
        dev = usb_net_init(&nd_table[nic]);
5812
    } else {
5813
        return -1;
5814
    }
5815
    if (!dev)
5816
        return -1;
5817

    
5818
    return usb_device_add_dev(dev);
5819
}
5820

    
5821
int usb_device_del_addr(int bus_num, int addr)
5822
{
5823
    USBPort *port;
5824
    USBPort **lastp;
5825
    USBDevice *dev;
5826

    
5827
    if (!used_usb_ports)
5828
        return -1;
5829

    
5830
    if (bus_num != 0)
5831
        return -1;
5832

    
5833
    lastp = &used_usb_ports;
5834
    port = used_usb_ports;
5835
    while (port && port->dev->addr != addr) {
5836
        lastp = &port->next;
5837
        port = port->next;
5838
    }
5839

    
5840
    if (!port)
5841
        return -1;
5842

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

    
5852
static int usb_device_del(const char *devname)
5853
{
5854
    int bus_num, addr;
5855
    const char *p;
5856

    
5857
    if (!used_usb_ports)
5858
        return -1;
5859

    
5860
    p = strchr(devname, '.');
5861
    if (!p)
5862
        return -1;
5863
    bus_num = strtoul(devname, NULL, 0);
5864
    addr = strtoul(p + 1, NULL, 0);
5865

    
5866
    return usb_device_del_addr(bus_num, addr);
5867
}
5868

    
5869
void do_usb_add(const char *devname)
5870
{
5871
    usb_device_add(devname);
5872
}
5873

    
5874
void do_usb_del(const char *devname)
5875
{
5876
    usb_device_del(devname);
5877
}
5878

    
5879
void usb_info(void)
5880
{
5881
    USBDevice *dev;
5882
    USBPort *port;
5883
    const char *speed_str;
5884

    
5885
    if (!usb_enabled) {
5886
        term_printf("USB support not enabled\n");
5887
        return;
5888
    }
5889

    
5890
    for (port = used_usb_ports; port; port = port->next) {
5891
        dev = port->dev;
5892
        if (!dev)
5893
            continue;
5894
        switch(dev->speed) {
5895
        case USB_SPEED_LOW:
5896
            speed_str = "1.5";
5897
            break;
5898
        case USB_SPEED_FULL:
5899
            speed_str = "12";
5900
            break;
5901
        case USB_SPEED_HIGH:
5902
            speed_str = "480";
5903
            break;
5904
        default:
5905
            speed_str = "?";
5906
            break;
5907
        }
5908
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
5909
                    0, dev->addr, speed_str, dev->devname);
5910
    }
5911
}
5912

    
5913
/***********************************************************/
5914
/* PCMCIA/Cardbus */
5915

    
5916
static struct pcmcia_socket_entry_s {
5917
    struct pcmcia_socket_s *socket;
5918
    struct pcmcia_socket_entry_s *next;
5919
} *pcmcia_sockets = 0;
5920

    
5921
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5922
{
5923
    struct pcmcia_socket_entry_s *entry;
5924

    
5925
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5926
    entry->socket = socket;
5927
    entry->next = pcmcia_sockets;
5928
    pcmcia_sockets = entry;
5929
}
5930

    
5931
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5932
{
5933
    struct pcmcia_socket_entry_s *entry, **ptr;
5934

    
5935
    ptr = &pcmcia_sockets;
5936
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5937
        if (entry->socket == socket) {
5938
            *ptr = entry->next;
5939
            qemu_free(entry);
5940
        }
5941
}
5942

    
5943
void pcmcia_info(void)
5944
{
5945
    struct pcmcia_socket_entry_s *iter;
5946
    if (!pcmcia_sockets)
5947
        term_printf("No PCMCIA sockets\n");
5948

    
5949
    for (iter = pcmcia_sockets; iter; iter = iter->next)
5950
        term_printf("%s: %s\n", iter->socket->slot_string,
5951
                    iter->socket->attached ? iter->socket->card_string :
5952
                    "Empty");
5953
}
5954

    
5955
/***********************************************************/
5956
/* dumb display */
5957

    
5958
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5959
{
5960
}
5961

    
5962
static void dumb_resize(DisplayState *ds, int w, int h)
5963
{
5964
}
5965

    
5966
static void dumb_refresh(DisplayState *ds)
5967
{
5968
#if defined(CONFIG_SDL)
5969
    vga_hw_update();
5970
#endif
5971
}
5972

    
5973
static void dumb_display_init(DisplayState *ds)
5974
{
5975
    ds->data = NULL;
5976
    ds->linesize = 0;
5977
    ds->depth = 0;
5978
    ds->dpy_update = dumb_update;
5979
    ds->dpy_resize = dumb_resize;
5980
    ds->dpy_refresh = dumb_refresh;
5981
    ds->gui_timer_interval = 500;
5982
    ds->idle = 1;
5983
}
5984

    
5985
/***********************************************************/
5986
/* I/O handling */
5987

    
5988
#define MAX_IO_HANDLERS 64
5989

    
5990
typedef struct IOHandlerRecord {
5991
    int fd;
5992
    IOCanRWHandler *fd_read_poll;
5993
    IOHandler *fd_read;
5994
    IOHandler *fd_write;
5995
    int deleted;
5996
    void *opaque;
5997
    /* temporary data */
5998
    struct pollfd *ufd;
5999
    struct IOHandlerRecord *next;
6000
} IOHandlerRecord;
6001

    
6002
static IOHandlerRecord *first_io_handler;
6003

    
6004
/* XXX: fd_read_poll should be suppressed, but an API change is
6005
   necessary in the character devices to suppress fd_can_read(). */
6006
int qemu_set_fd_handler2(int fd,
6007
                         IOCanRWHandler *fd_read_poll,
6008
                         IOHandler *fd_read,
6009
                         IOHandler *fd_write,
6010
                         void *opaque)
6011
{
6012
    IOHandlerRecord **pioh, *ioh;
6013

    
6014
    if (!fd_read && !fd_write) {
6015
        pioh = &first_io_handler;
6016
        for(;;) {
6017
            ioh = *pioh;
6018
            if (ioh == NULL)
6019
                break;
6020
            if (ioh->fd == fd) {
6021
                ioh->deleted = 1;
6022
                break;
6023
            }
6024
            pioh = &ioh->next;
6025
        }
6026
    } else {
6027
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6028
            if (ioh->fd == fd)
6029
                goto found;
6030
        }
6031
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6032
        if (!ioh)
6033
            return -1;
6034
        ioh->next = first_io_handler;
6035
        first_io_handler = ioh;
6036
    found:
6037
        ioh->fd = fd;
6038
        ioh->fd_read_poll = fd_read_poll;
6039
        ioh->fd_read = fd_read;
6040
        ioh->fd_write = fd_write;
6041
        ioh->opaque = opaque;
6042
        ioh->deleted = 0;
6043
    }
6044
    return 0;
6045
}
6046

    
6047
int qemu_set_fd_handler(int fd,
6048
                        IOHandler *fd_read,
6049
                        IOHandler *fd_write,
6050
                        void *opaque)
6051
{
6052
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6053
}
6054

    
6055
/***********************************************************/
6056
/* Polling handling */
6057

    
6058
typedef struct PollingEntry {
6059
    PollingFunc *func;
6060
    void *opaque;
6061
    struct PollingEntry *next;
6062
} PollingEntry;
6063

    
6064
static PollingEntry *first_polling_entry;
6065

    
6066
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6067
{
6068
    PollingEntry **ppe, *pe;
6069
    pe = qemu_mallocz(sizeof(PollingEntry));
6070
    if (!pe)
6071
        return -1;
6072
    pe->func = func;
6073
    pe->opaque = opaque;
6074
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6075
    *ppe = pe;
6076
    return 0;
6077
}
6078

    
6079
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6080
{
6081
    PollingEntry **ppe, *pe;
6082
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6083
        pe = *ppe;
6084
        if (pe->func == func && pe->opaque == opaque) {
6085
            *ppe = pe->next;
6086
            qemu_free(pe);
6087
            break;
6088
        }
6089
    }
6090
}
6091

    
6092
#ifdef _WIN32
6093
/***********************************************************/
6094
/* Wait objects support */
6095
typedef struct WaitObjects {
6096
    int num;
6097
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6098
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6099
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6100
} WaitObjects;
6101

    
6102
static WaitObjects wait_objects = {0};
6103

    
6104
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6105
{
6106
    WaitObjects *w = &wait_objects;
6107

    
6108
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
6109
        return -1;
6110
    w->events[w->num] = handle;
6111
    w->func[w->num] = func;
6112
    w->opaque[w->num] = opaque;
6113
    w->num++;
6114
    return 0;
6115
}
6116

    
6117
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6118
{
6119
    int i, found;
6120
    WaitObjects *w = &wait_objects;
6121

    
6122
    found = 0;
6123
    for (i = 0; i < w->num; i++) {
6124
        if (w->events[i] == handle)
6125
            found = 1;
6126
        if (found) {
6127
            w->events[i] = w->events[i + 1];
6128
            w->func[i] = w->func[i + 1];
6129
            w->opaque[i] = w->opaque[i + 1];
6130
        }
6131
    }
6132
    if (found)
6133
        w->num--;
6134
}
6135
#endif
6136

    
6137
/***********************************************************/
6138
/* savevm/loadvm support */
6139

    
6140
#define IO_BUF_SIZE 32768
6141

    
6142
struct QEMUFile {
6143
    FILE *outfile;
6144
    BlockDriverState *bs;
6145
    int is_file;
6146
    int is_writable;
6147
    int64_t base_offset;
6148
    int64_t buf_offset; /* start of buffer when writing, end of buffer
6149
                           when reading */
6150
    int buf_index;
6151
    int buf_size; /* 0 when writing */
6152
    uint8_t buf[IO_BUF_SIZE];
6153
};
6154

    
6155
QEMUFile *qemu_fopen(const char *filename, const char *mode)
6156
{
6157
    QEMUFile *f;
6158

    
6159
    f = qemu_mallocz(sizeof(QEMUFile));
6160
    if (!f)
6161
        return NULL;
6162
    if (!strcmp(mode, "wb")) {
6163
        f->is_writable = 1;
6164
    } else if (!strcmp(mode, "rb")) {
6165
        f->is_writable = 0;
6166
    } else {
6167
        goto fail;
6168
    }
6169
    f->outfile = fopen(filename, mode);
6170
    if (!f->outfile)
6171
        goto fail;
6172
    f->is_file = 1;
6173
    return f;
6174
 fail:
6175
    if (f->outfile)
6176
        fclose(f->outfile);
6177
    qemu_free(f);
6178
    return NULL;
6179
}
6180

    
6181
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6182
{
6183
    QEMUFile *f;
6184

    
6185
    f = qemu_mallocz(sizeof(QEMUFile));
6186
    if (!f)
6187
        return NULL;
6188
    f->is_file = 0;
6189
    f->bs = bs;
6190
    f->is_writable = is_writable;
6191
    f->base_offset = offset;
6192
    return f;
6193
}
6194

    
6195
void qemu_fflush(QEMUFile *f)
6196
{
6197
    if (!f->is_writable)
6198
        return;
6199
    if (f->buf_index > 0) {
6200
        if (f->is_file) {
6201
            fseek(f->outfile, f->buf_offset, SEEK_SET);
6202
            fwrite(f->buf, 1, f->buf_index, f->outfile);
6203
        } else {
6204
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
6205
                        f->buf, f->buf_index);
6206
        }
6207
        f->buf_offset += f->buf_index;
6208
        f->buf_index = 0;
6209
    }
6210
}
6211

    
6212
static void qemu_fill_buffer(QEMUFile *f)
6213
{
6214
    int len;
6215

    
6216
    if (f->is_writable)
6217
        return;
6218
    if (f->is_file) {
6219
        fseek(f->outfile, f->buf_offset, SEEK_SET);
6220
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
6221
        if (len < 0)
6222
            len = 0;
6223
    } else {
6224
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
6225
                         f->buf, IO_BUF_SIZE);
6226
        if (len < 0)
6227
            len = 0;
6228
    }
6229
    f->buf_index = 0;
6230
    f->buf_size = len;
6231
    f->buf_offset += len;
6232
}
6233

    
6234
void qemu_fclose(QEMUFile *f)
6235
{
6236
    if (f->is_writable)
6237
        qemu_fflush(f);
6238
    if (f->is_file) {
6239
        fclose(f->outfile);
6240
    }
6241
    qemu_free(f);
6242
}
6243

    
6244
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6245
{
6246
    int l;
6247
    while (size > 0) {
6248
        l = IO_BUF_SIZE - f->buf_index;
6249
        if (l > size)
6250
            l = size;
6251
        memcpy(f->buf + f->buf_index, buf, l);
6252
        f->buf_index += l;
6253
        buf += l;
6254
        size -= l;
6255
        if (f->buf_index >= IO_BUF_SIZE)
6256
            qemu_fflush(f);
6257
    }
6258
}
6259

    
6260
void qemu_put_byte(QEMUFile *f, int v)
6261
{
6262
    f->buf[f->buf_index++] = v;
6263
    if (f->buf_index >= IO_BUF_SIZE)
6264
        qemu_fflush(f);
6265
}
6266

    
6267
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6268
{
6269
    int size, l;
6270

    
6271
    size = size1;
6272
    while (size > 0) {
6273
        l = f->buf_size - f->buf_index;
6274
        if (l == 0) {
6275
            qemu_fill_buffer(f);
6276
            l = f->buf_size - f->buf_index;
6277
            if (l == 0)
6278
                break;
6279
        }
6280
        if (l > size)
6281
            l = size;
6282
        memcpy(buf, f->buf + f->buf_index, l);
6283
        f->buf_index += l;
6284
        buf += l;
6285
        size -= l;
6286
    }
6287
    return size1 - size;
6288
}
6289

    
6290
int qemu_get_byte(QEMUFile *f)
6291
{
6292
    if (f->buf_index >= f->buf_size) {
6293
        qemu_fill_buffer(f);
6294
        if (f->buf_index >= f->buf_size)
6295
            return 0;
6296
    }
6297
    return f->buf[f->buf_index++];
6298
}
6299

    
6300
int64_t qemu_ftell(QEMUFile *f)
6301
{
6302
    return f->buf_offset - f->buf_size + f->buf_index;
6303
}
6304

    
6305
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6306
{
6307
    if (whence == SEEK_SET) {
6308
        /* nothing to do */
6309
    } else if (whence == SEEK_CUR) {
6310
        pos += qemu_ftell(f);
6311
    } else {
6312
        /* SEEK_END not supported */
6313
        return -1;
6314
    }
6315
    if (f->is_writable) {
6316
        qemu_fflush(f);
6317
        f->buf_offset = pos;
6318
    } else {
6319
        f->buf_offset = pos;
6320
        f->buf_index = 0;
6321
        f->buf_size = 0;
6322
    }
6323
    return pos;
6324
}
6325

    
6326
void qemu_put_be16(QEMUFile *f, unsigned int v)
6327
{
6328
    qemu_put_byte(f, v >> 8);
6329
    qemu_put_byte(f, v);
6330
}
6331

    
6332
void qemu_put_be32(QEMUFile *f, unsigned int v)
6333
{
6334
    qemu_put_byte(f, v >> 24);
6335
    qemu_put_byte(f, v >> 16);
6336
    qemu_put_byte(f, v >> 8);
6337
    qemu_put_byte(f, v);
6338
}
6339

    
6340
void qemu_put_be64(QEMUFile *f, uint64_t v)
6341
{
6342
    qemu_put_be32(f, v >> 32);
6343
    qemu_put_be32(f, v);
6344
}
6345

    
6346
unsigned int qemu_get_be16(QEMUFile *f)
6347
{
6348
    unsigned int v;
6349
    v = qemu_get_byte(f) << 8;
6350
    v |= qemu_get_byte(f);
6351
    return v;
6352
}
6353

    
6354
unsigned int qemu_get_be32(QEMUFile *f)
6355
{
6356
    unsigned int v;
6357
    v = qemu_get_byte(f) << 24;
6358
    v |= qemu_get_byte(f) << 16;
6359
    v |= qemu_get_byte(f) << 8;
6360
    v |= qemu_get_byte(f);
6361
    return v;
6362
}
6363

    
6364
uint64_t qemu_get_be64(QEMUFile *f)
6365
{
6366
    uint64_t v;
6367
    v = (uint64_t)qemu_get_be32(f) << 32;
6368
    v |= qemu_get_be32(f);
6369
    return v;
6370
}
6371

    
6372
typedef struct SaveStateEntry {
6373
    char idstr[256];
6374
    int instance_id;
6375
    int version_id;
6376
    SaveStateHandler *save_state;
6377
    LoadStateHandler *load_state;
6378
    void *opaque;
6379
    struct SaveStateEntry *next;
6380
} SaveStateEntry;
6381

    
6382
static SaveStateEntry *first_se;
6383

    
6384
/* TODO: Individual devices generally have very little idea about the rest
6385
   of the system, so instance_id should be removed/replaced.
6386
   Meanwhile pass -1 as instance_id if you do not already have a clearly
6387
   distinguishing id for all instances of your device class. */
6388
int register_savevm(const char *idstr,
6389
                    int instance_id,
6390
                    int version_id,
6391
                    SaveStateHandler *save_state,
6392
                    LoadStateHandler *load_state,
6393
                    void *opaque)
6394
{
6395
    SaveStateEntry *se, **pse;
6396

    
6397
    se = qemu_malloc(sizeof(SaveStateEntry));
6398
    if (!se)
6399
        return -1;
6400
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6401
    se->instance_id = (instance_id == -1) ? 0 : instance_id;
6402
    se->version_id = version_id;
6403
    se->save_state = save_state;
6404
    se->load_state = load_state;
6405
    se->opaque = opaque;
6406
    se->next = NULL;
6407

    
6408
    /* add at the end of list */
6409
    pse = &first_se;
6410
    while (*pse != NULL) {
6411
        if (instance_id == -1
6412
                && strcmp(se->idstr, (*pse)->idstr) == 0
6413
                && se->instance_id <= (*pse)->instance_id)
6414
            se->instance_id = (*pse)->instance_id + 1;
6415
        pse = &(*pse)->next;
6416
    }
6417
    *pse = se;
6418
    return 0;
6419
}
6420

    
6421
#define QEMU_VM_FILE_MAGIC   0x5145564d
6422
#define QEMU_VM_FILE_VERSION 0x00000002
6423

    
6424
static int qemu_savevm_state(QEMUFile *f)
6425
{
6426
    SaveStateEntry *se;
6427
    int len, ret;
6428
    int64_t cur_pos, len_pos, total_len_pos;
6429

    
6430
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6431
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6432
    total_len_pos = qemu_ftell(f);
6433
    qemu_put_be64(f, 0); /* total size */
6434

    
6435
    for(se = first_se; se != NULL; se = se->next) {
6436
        if (se->save_state == NULL)
6437
            /* this one has a loader only, for backwards compatibility */
6438
            continue;
6439

    
6440
        /* ID string */
6441
        len = strlen(se->idstr);
6442
        qemu_put_byte(f, len);
6443
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6444

    
6445
        qemu_put_be32(f, se->instance_id);
6446
        qemu_put_be32(f, se->version_id);
6447

    
6448
        /* record size: filled later */
6449
        len_pos = qemu_ftell(f);
6450
        qemu_put_be32(f, 0);
6451
        se->save_state(f, se->opaque);
6452

    
6453
        /* fill record size */
6454
        cur_pos = qemu_ftell(f);
6455
        len = cur_pos - len_pos - 4;
6456
        qemu_fseek(f, len_pos, SEEK_SET);
6457
        qemu_put_be32(f, len);
6458
        qemu_fseek(f, cur_pos, SEEK_SET);
6459
    }
6460
    cur_pos = qemu_ftell(f);
6461
    qemu_fseek(f, total_len_pos, SEEK_SET);
6462
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
6463
    qemu_fseek(f, cur_pos, SEEK_SET);
6464

    
6465
    ret = 0;
6466
    return ret;
6467
}
6468

    
6469
static SaveStateEntry *find_se(const char *idstr, int instance_id)
6470
{
6471
    SaveStateEntry *se;
6472

    
6473
    for(se = first_se; se != NULL; se = se->next) {
6474
        if (!strcmp(se->idstr, idstr) &&
6475
            instance_id == se->instance_id)
6476
            return se;
6477
    }
6478
    return NULL;
6479
}
6480

    
6481
static int qemu_loadvm_state(QEMUFile *f)
6482
{
6483
    SaveStateEntry *se;
6484
    int len, ret, instance_id, record_len, version_id;
6485
    int64_t total_len, end_pos, cur_pos;
6486
    unsigned int v;
6487
    char idstr[256];
6488

    
6489
    v = qemu_get_be32(f);
6490
    if (v != QEMU_VM_FILE_MAGIC)
6491
        goto fail;
6492
    v = qemu_get_be32(f);
6493
    if (v != QEMU_VM_FILE_VERSION) {
6494
    fail:
6495
        ret = -1;
6496
        goto the_end;
6497
    }
6498
    total_len = qemu_get_be64(f);
6499
    end_pos = total_len + qemu_ftell(f);
6500
    for(;;) {
6501
        if (qemu_ftell(f) >= end_pos)
6502
            break;
6503
        len = qemu_get_byte(f);
6504
        qemu_get_buffer(f, (uint8_t *)idstr, len);
6505
        idstr[len] = '\0';
6506
        instance_id = qemu_get_be32(f);
6507
        version_id = qemu_get_be32(f);
6508
        record_len = qemu_get_be32(f);
6509
#if 0
6510
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
6511
               idstr, instance_id, version_id, record_len);
6512
#endif
6513
        cur_pos = qemu_ftell(f);
6514
        se = find_se(idstr, instance_id);
6515
        if (!se) {
6516
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6517
                    instance_id, idstr);
6518
        } else {
6519
            ret = se->load_state(f, se->opaque, version_id);
6520
            if (ret < 0) {
6521
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6522
                        instance_id, idstr);
6523
            }
6524
        }
6525
        /* always seek to exact end of record */
6526
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6527
    }
6528
    ret = 0;
6529
 the_end:
6530
    return ret;
6531
}
6532

    
6533
/* device can contain snapshots */
6534
static int bdrv_can_snapshot(BlockDriverState *bs)
6535
{
6536
    return (bs &&
6537
            !bdrv_is_removable(bs) &&
6538
            !bdrv_is_read_only(bs));
6539
}
6540

    
6541
/* device must be snapshots in order to have a reliable snapshot */
6542
static int bdrv_has_snapshot(BlockDriverState *bs)
6543
{
6544
    return (bs &&
6545
            !bdrv_is_removable(bs) &&
6546
            !bdrv_is_read_only(bs));
6547
}
6548

    
6549
static BlockDriverState *get_bs_snapshots(void)
6550
{
6551
    BlockDriverState *bs;
6552
    int i;
6553

    
6554
    if (bs_snapshots)
6555
        return bs_snapshots;
6556
    for(i = 0; i <= nb_drives; i++) {
6557
        bs = drives_table[i].bdrv;
6558
        if (bdrv_can_snapshot(bs))
6559
            goto ok;
6560
    }
6561
    return NULL;
6562
 ok:
6563
    bs_snapshots = bs;
6564
    return bs;
6565
}
6566

    
6567
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6568
                              const char *name)
6569
{
6570
    QEMUSnapshotInfo *sn_tab, *sn;
6571
    int nb_sns, i, ret;
6572

    
6573
    ret = -ENOENT;
6574
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6575
    if (nb_sns < 0)
6576
        return ret;
6577
    for(i = 0; i < nb_sns; i++) {
6578
        sn = &sn_tab[i];
6579
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6580
            *sn_info = *sn;
6581
            ret = 0;
6582
            break;
6583
        }
6584
    }
6585
    qemu_free(sn_tab);
6586
    return ret;
6587
}
6588

    
6589
void do_savevm(const char *name)
6590
{
6591
    BlockDriverState *bs, *bs1;
6592
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6593
    int must_delete, ret, i;
6594
    BlockDriverInfo bdi1, *bdi = &bdi1;
6595
    QEMUFile *f;
6596
    int saved_vm_running;
6597
#ifdef _WIN32
6598
    struct _timeb tb;
6599
#else
6600
    struct timeval tv;
6601
#endif
6602

    
6603
    bs = get_bs_snapshots();
6604
    if (!bs) {
6605
        term_printf("No block device can accept snapshots\n");
6606
        return;
6607
    }
6608

    
6609
    /* ??? Should this occur after vm_stop?  */
6610
    qemu_aio_flush();
6611

    
6612
    saved_vm_running = vm_running;
6613
    vm_stop(0);
6614

    
6615
    must_delete = 0;
6616
    if (name) {
6617
        ret = bdrv_snapshot_find(bs, old_sn, name);
6618
        if (ret >= 0) {
6619
            must_delete = 1;
6620
        }
6621
    }
6622
    memset(sn, 0, sizeof(*sn));
6623
    if (must_delete) {
6624
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6625
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6626
    } else {
6627
        if (name)
6628
            pstrcpy(sn->name, sizeof(sn->name), name);
6629
    }
6630

    
6631
    /* fill auxiliary fields */
6632
#ifdef _WIN32
6633
    _ftime(&tb);
6634
    sn->date_sec = tb.time;
6635
    sn->date_nsec = tb.millitm * 1000000;
6636
#else
6637
    gettimeofday(&tv, NULL);
6638
    sn->date_sec = tv.tv_sec;
6639
    sn->date_nsec = tv.tv_usec * 1000;
6640
#endif
6641
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6642

    
6643
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6644
        term_printf("Device %s does not support VM state snapshots\n",
6645
                    bdrv_get_device_name(bs));
6646
        goto the_end;
6647
    }
6648

    
6649
    /* save the VM state */
6650
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6651
    if (!f) {
6652
        term_printf("Could not open VM state file\n");
6653
        goto the_end;
6654
    }
6655
    ret = qemu_savevm_state(f);
6656
    sn->vm_state_size = qemu_ftell(f);
6657
    qemu_fclose(f);
6658
    if (ret < 0) {
6659
        term_printf("Error %d while writing VM\n", ret);
6660
        goto the_end;
6661
    }
6662

    
6663
    /* create the snapshots */
6664

    
6665
    for(i = 0; i < nb_drives; i++) {
6666
        bs1 = drives_table[i].bdrv;
6667
        if (bdrv_has_snapshot(bs1)) {
6668
            if (must_delete) {
6669
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6670
                if (ret < 0) {
6671
                    term_printf("Error while deleting snapshot on '%s'\n",
6672
                                bdrv_get_device_name(bs1));
6673
                }
6674
            }
6675
            ret = bdrv_snapshot_create(bs1, sn);
6676
            if (ret < 0) {
6677
                term_printf("Error while creating snapshot on '%s'\n",
6678
                            bdrv_get_device_name(bs1));
6679
            }
6680
        }
6681
    }
6682

    
6683
 the_end:
6684
    if (saved_vm_running)
6685
        vm_start();
6686
}
6687

    
6688
void do_loadvm(const char *name)
6689
{
6690
    BlockDriverState *bs, *bs1;
6691
    BlockDriverInfo bdi1, *bdi = &bdi1;
6692
    QEMUFile *f;
6693
    int i, ret;
6694
    int saved_vm_running;
6695

    
6696
    bs = get_bs_snapshots();
6697
    if (!bs) {
6698
        term_printf("No block device supports snapshots\n");
6699
        return;
6700
    }
6701

    
6702
    /* Flush all IO requests so they don't interfere with the new state.  */
6703
    qemu_aio_flush();
6704

    
6705
    saved_vm_running = vm_running;
6706
    vm_stop(0);
6707

    
6708
    for(i = 0; i <= nb_drives; i++) {
6709
        bs1 = drives_table[i].bdrv;
6710
        if (bdrv_has_snapshot(bs1)) {
6711
            ret = bdrv_snapshot_goto(bs1, name);
6712
            if (ret < 0) {
6713
                if (bs != bs1)
6714
                    term_printf("Warning: ");
6715
                switch(ret) {
6716
                case -ENOTSUP:
6717
                    term_printf("Snapshots not supported on device '%s'\n",
6718
                                bdrv_get_device_name(bs1));
6719
                    break;
6720
                case -ENOENT:
6721
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
6722
                                name, bdrv_get_device_name(bs1));
6723
                    break;
6724
                default:
6725
                    term_printf("Error %d while activating snapshot on '%s'\n",
6726
                                ret, bdrv_get_device_name(bs1));
6727
                    break;
6728
                }
6729
                /* fatal on snapshot block device */
6730
                if (bs == bs1)
6731
                    goto the_end;
6732
            }
6733
        }
6734
    }
6735

    
6736
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6737
        term_printf("Device %s does not support VM state snapshots\n",
6738
                    bdrv_get_device_name(bs));
6739
        return;
6740
    }
6741

    
6742
    /* restore the VM state */
6743
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6744
    if (!f) {
6745
        term_printf("Could not open VM state file\n");
6746
        goto the_end;
6747
    }
6748
    ret = qemu_loadvm_state(f);
6749
    qemu_fclose(f);
6750
    if (ret < 0) {
6751
        term_printf("Error %d while loading VM state\n", ret);
6752
    }
6753
 the_end:
6754
    if (saved_vm_running)
6755
        vm_start();
6756
}
6757

    
6758
void do_delvm(const char *name)
6759
{
6760
    BlockDriverState *bs, *bs1;
6761
    int i, ret;
6762

    
6763
    bs = get_bs_snapshots();
6764
    if (!bs) {
6765
        term_printf("No block device supports snapshots\n");
6766
        return;
6767
    }
6768

    
6769
    for(i = 0; i <= nb_drives; i++) {
6770
        bs1 = drives_table[i].bdrv;
6771
        if (bdrv_has_snapshot(bs1)) {
6772
            ret = bdrv_snapshot_delete(bs1, name);
6773
            if (ret < 0) {
6774
                if (ret == -ENOTSUP)
6775
                    term_printf("Snapshots not supported on device '%s'\n",
6776
                                bdrv_get_device_name(bs1));
6777
                else
6778
                    term_printf("Error %d while deleting snapshot on '%s'\n",
6779
                                ret, bdrv_get_device_name(bs1));
6780
            }
6781
        }
6782
    }
6783
}
6784

    
6785
void do_info_snapshots(void)
6786
{
6787
    BlockDriverState *bs, *bs1;
6788
    QEMUSnapshotInfo *sn_tab, *sn;
6789
    int nb_sns, i;
6790
    char buf[256];
6791

    
6792
    bs = get_bs_snapshots();
6793
    if (!bs) {
6794
        term_printf("No available block device supports snapshots\n");
6795
        return;
6796
    }
6797
    term_printf("Snapshot devices:");
6798
    for(i = 0; i <= nb_drives; i++) {
6799
        bs1 = drives_table[i].bdrv;
6800
        if (bdrv_has_snapshot(bs1)) {
6801
            if (bs == bs1)
6802
                term_printf(" %s", bdrv_get_device_name(bs1));
6803
        }
6804
    }
6805
    term_printf("\n");
6806

    
6807
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6808
    if (nb_sns < 0) {
6809
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6810
        return;
6811
    }
6812
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6813
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6814
    for(i = 0; i < nb_sns; i++) {
6815
        sn = &sn_tab[i];
6816
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6817
    }
6818
    qemu_free(sn_tab);
6819
}
6820

    
6821
/***********************************************************/
6822
/* ram save/restore */
6823

    
6824
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6825
{
6826
    int v;
6827

    
6828
    v = qemu_get_byte(f);
6829
    switch(v) {
6830
    case 0:
6831
        if (qemu_get_buffer(f, buf, len) != len)
6832
            return -EIO;
6833
        break;
6834
    case 1:
6835
        v = qemu_get_byte(f);
6836
        memset(buf, v, len);
6837
        break;
6838
    default:
6839
        return -EINVAL;
6840
    }
6841
    return 0;
6842
}
6843

    
6844
static int ram_load_v1(QEMUFile *f, void *opaque)
6845
{
6846
    int ret;
6847
    ram_addr_t i;
6848

    
6849
    if (qemu_get_be32(f) != phys_ram_size)
6850
        return -EINVAL;
6851
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6852
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6853
        if (ret)
6854
            return ret;
6855
    }
6856
    return 0;
6857
}
6858

    
6859
#define BDRV_HASH_BLOCK_SIZE 1024
6860
#define IOBUF_SIZE 4096
6861
#define RAM_CBLOCK_MAGIC 0xfabe
6862

    
6863
typedef struct RamCompressState {
6864
    z_stream zstream;
6865
    QEMUFile *f;
6866
    uint8_t buf[IOBUF_SIZE];
6867
} RamCompressState;
6868

    
6869
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6870
{
6871
    int ret;
6872
    memset(s, 0, sizeof(*s));
6873
    s->f = f;
6874
    ret = deflateInit2(&s->zstream, 1,
6875
                       Z_DEFLATED, 15,
6876
                       9, Z_DEFAULT_STRATEGY);
6877
    if (ret != Z_OK)
6878
        return -1;
6879
    s->zstream.avail_out = IOBUF_SIZE;
6880
    s->zstream.next_out = s->buf;
6881
    return 0;
6882
}
6883

    
6884
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6885
{
6886
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6887
    qemu_put_be16(s->f, len);
6888
    qemu_put_buffer(s->f, buf, len);
6889
}
6890

    
6891
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6892
{
6893
    int ret;
6894

    
6895
    s->zstream.avail_in = len;
6896
    s->zstream.next_in = (uint8_t *)buf;
6897
    while (s->zstream.avail_in > 0) {
6898
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6899
        if (ret != Z_OK)
6900
            return -1;
6901
        if (s->zstream.avail_out == 0) {
6902
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6903
            s->zstream.avail_out = IOBUF_SIZE;
6904
            s->zstream.next_out = s->buf;
6905
        }
6906
    }
6907
    return 0;
6908
}
6909

    
6910
static void ram_compress_close(RamCompressState *s)
6911
{
6912
    int len, ret;
6913

    
6914
    /* compress last bytes */
6915
    for(;;) {
6916
        ret = deflate(&s->zstream, Z_FINISH);
6917
        if (ret == Z_OK || ret == Z_STREAM_END) {
6918
            len = IOBUF_SIZE - s->zstream.avail_out;
6919
            if (len > 0) {
6920
                ram_put_cblock(s, s->buf, len);
6921
            }
6922
            s->zstream.avail_out = IOBUF_SIZE;
6923
            s->zstream.next_out = s->buf;
6924
            if (ret == Z_STREAM_END)
6925
                break;
6926
        } else {
6927
            goto fail;
6928
        }
6929
    }
6930
fail:
6931
    deflateEnd(&s->zstream);
6932
}
6933

    
6934
typedef struct RamDecompressState {
6935
    z_stream zstream;
6936
    QEMUFile *f;
6937
    uint8_t buf[IOBUF_SIZE];
6938
} RamDecompressState;
6939

    
6940
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6941
{
6942
    int ret;
6943
    memset(s, 0, sizeof(*s));
6944
    s->f = f;
6945
    ret = inflateInit(&s->zstream);
6946
    if (ret != Z_OK)
6947
        return -1;
6948
    return 0;
6949
}
6950

    
6951
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6952
{
6953
    int ret, clen;
6954

    
6955
    s->zstream.avail_out = len;
6956
    s->zstream.next_out = buf;
6957
    while (s->zstream.avail_out > 0) {
6958
        if (s->zstream.avail_in == 0) {
6959
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6960
                return -1;
6961
            clen = qemu_get_be16(s->f);
6962
            if (clen > IOBUF_SIZE)
6963
                return -1;
6964
            qemu_get_buffer(s->f, s->buf, clen);
6965
            s->zstream.avail_in = clen;
6966
            s->zstream.next_in = s->buf;
6967
        }
6968
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6969
        if (ret != Z_OK && ret != Z_STREAM_END) {
6970
            return -1;
6971
        }
6972
    }
6973
    return 0;
6974
}
6975

    
6976
static void ram_decompress_close(RamDecompressState *s)
6977
{
6978
    inflateEnd(&s->zstream);
6979
}
6980

    
6981
static void ram_save(QEMUFile *f, void *opaque)
6982
{
6983
    ram_addr_t i;
6984
    RamCompressState s1, *s = &s1;
6985
    uint8_t buf[10];
6986

    
6987
    qemu_put_be32(f, phys_ram_size);
6988
    if (ram_compress_open(s, f) < 0)
6989
        return;
6990
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6991
#if 0
6992
        if (tight_savevm_enabled) {
6993
            int64_t sector_num;
6994
            int j;
6995

6996
            /* find if the memory block is available on a virtual
6997
               block device */
6998
            sector_num = -1;
6999
            for(j = 0; j < nb_drives; j++) {
7000
                sector_num = bdrv_hash_find(drives_table[j].bdrv,
7001
                                            phys_ram_base + i,
7002
                                            BDRV_HASH_BLOCK_SIZE);
7003
                if (sector_num >= 0)
7004
                    break;
7005
            }
7006
            if (j == nb_drives)
7007
                goto normal_compress;
7008
            buf[0] = 1;
7009
            buf[1] = j;
7010
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7011
            ram_compress_buf(s, buf, 10);
7012
        } else
7013
#endif
7014
        {
7015
            //        normal_compress:
7016
            buf[0] = 0;
7017
            ram_compress_buf(s, buf, 1);
7018
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7019
        }
7020
    }
7021
    ram_compress_close(s);
7022
}
7023

    
7024
static int ram_load(QEMUFile *f, void *opaque, int version_id)
7025
{
7026
    RamDecompressState s1, *s = &s1;
7027
    uint8_t buf[10];
7028
    ram_addr_t i;
7029

    
7030
    if (version_id == 1)
7031
        return ram_load_v1(f, opaque);
7032
    if (version_id != 2)
7033
        return -EINVAL;
7034
    if (qemu_get_be32(f) != phys_ram_size)
7035
        return -EINVAL;
7036
    if (ram_decompress_open(s, f) < 0)
7037
        return -EINVAL;
7038
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7039
        if (ram_decompress_buf(s, buf, 1) < 0) {
7040
            fprintf(stderr, "Error while reading ram block header\n");
7041
            goto error;
7042
        }
7043
        if (buf[0] == 0) {
7044
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7045
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7046
                goto error;
7047
            }
7048
        } else
7049
#if 0
7050
        if (buf[0] == 1) {
7051
            int bs_index;
7052
            int64_t sector_num;
7053

7054
            ram_decompress_buf(s, buf + 1, 9);
7055
            bs_index = buf[1];
7056
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7057
            if (bs_index >= nb_drives) {
7058
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
7059
                goto error;
7060
            }
7061
            if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7062
                          phys_ram_base + i,
7063
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7064
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7065
                        bs_index, sector_num);
7066
                goto error;
7067
            }
7068
        } else
7069
#endif
7070
        {
7071
        error:
7072
            printf("Error block header\n");
7073
            return -EINVAL;
7074
        }
7075
    }
7076
    ram_decompress_close(s);
7077
    return 0;
7078
}
7079

    
7080
/***********************************************************/
7081
/* bottom halves (can be seen as timers which expire ASAP) */
7082

    
7083
struct QEMUBH {
7084
    QEMUBHFunc *cb;
7085
    void *opaque;
7086
    int scheduled;
7087
    QEMUBH *next;
7088
};
7089

    
7090
static QEMUBH *first_bh = NULL;
7091

    
7092
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7093
{
7094
    QEMUBH *bh;
7095
    bh = qemu_mallocz(sizeof(QEMUBH));
7096
    if (!bh)
7097
        return NULL;
7098
    bh->cb = cb;
7099
    bh->opaque = opaque;
7100
    return bh;
7101
}
7102

    
7103
int qemu_bh_poll(void)
7104
{
7105
    QEMUBH *bh, **pbh;
7106
    int ret;
7107

    
7108
    ret = 0;
7109
    for(;;) {
7110
        pbh = &first_bh;
7111
        bh = *pbh;
7112
        if (!bh)
7113
            break;
7114
        ret = 1;
7115
        *pbh = bh->next;
7116
        bh->scheduled = 0;
7117
        bh->cb(bh->opaque);
7118
    }
7119
    return ret;
7120
}
7121

    
7122
void qemu_bh_schedule(QEMUBH *bh)
7123
{
7124
    CPUState *env = cpu_single_env;
7125
    if (bh->scheduled)
7126
        return;
7127
    bh->scheduled = 1;
7128
    bh->next = first_bh;
7129
    first_bh = bh;
7130

    
7131
    /* stop the currently executing CPU to execute the BH ASAP */
7132
    if (env) {
7133
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7134
    }
7135
}
7136

    
7137
void qemu_bh_cancel(QEMUBH *bh)
7138
{
7139
    QEMUBH **pbh;
7140
    if (bh->scheduled) {
7141
        pbh = &first_bh;
7142
        while (*pbh != bh)
7143
            pbh = &(*pbh)->next;
7144
        *pbh = bh->next;
7145
        bh->scheduled = 0;
7146
    }
7147
}
7148

    
7149
void qemu_bh_delete(QEMUBH *bh)
7150
{
7151
    qemu_bh_cancel(bh);
7152
    qemu_free(bh);
7153
}
7154

    
7155
/***********************************************************/
7156
/* machine registration */
7157

    
7158
QEMUMachine *first_machine = NULL;
7159

    
7160
int qemu_register_machine(QEMUMachine *m)
7161
{
7162
    QEMUMachine **pm;
7163
    pm = &first_machine;
7164
    while (*pm != NULL)
7165
        pm = &(*pm)->next;
7166
    m->next = NULL;
7167
    *pm = m;
7168
    return 0;
7169
}
7170

    
7171
static QEMUMachine *find_machine(const char *name)
7172
{
7173
    QEMUMachine *m;
7174

    
7175
    for(m = first_machine; m != NULL; m = m->next) {
7176
        if (!strcmp(m->name, name))
7177
            return m;
7178
    }
7179
    return NULL;
7180
}
7181

    
7182
/***********************************************************/
7183
/* main execution loop */
7184

    
7185
static void gui_update(void *opaque)
7186
{
7187
    DisplayState *ds = opaque;
7188
    ds->dpy_refresh(ds);
7189
    qemu_mod_timer(ds->gui_timer,
7190
        (ds->gui_timer_interval ?
7191
            ds->gui_timer_interval :
7192
            GUI_REFRESH_INTERVAL)
7193
        + qemu_get_clock(rt_clock));
7194
}
7195

    
7196
struct vm_change_state_entry {
7197
    VMChangeStateHandler *cb;
7198
    void *opaque;
7199
    LIST_ENTRY (vm_change_state_entry) entries;
7200
};
7201

    
7202
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7203

    
7204
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7205
                                                     void *opaque)
7206
{
7207
    VMChangeStateEntry *e;
7208

    
7209
    e = qemu_mallocz(sizeof (*e));
7210
    if (!e)
7211
        return NULL;
7212

    
7213
    e->cb = cb;
7214
    e->opaque = opaque;
7215
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7216
    return e;
7217
}
7218

    
7219
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7220
{
7221
    LIST_REMOVE (e, entries);
7222
    qemu_free (e);
7223
}
7224

    
7225
static void vm_state_notify(int running)
7226
{
7227
    VMChangeStateEntry *e;
7228

    
7229
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7230
        e->cb(e->opaque, running);
7231
    }
7232
}
7233

    
7234
/* XXX: support several handlers */
7235
static VMStopHandler *vm_stop_cb;
7236
static void *vm_stop_opaque;
7237

    
7238
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7239
{
7240
    vm_stop_cb = cb;
7241
    vm_stop_opaque = opaque;
7242
    return 0;
7243
}
7244

    
7245
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7246
{
7247
    vm_stop_cb = NULL;
7248
}
7249

    
7250
void vm_start(void)
7251
{
7252
    if (!vm_running) {
7253
        cpu_enable_ticks();
7254
        vm_running = 1;
7255
        vm_state_notify(1);
7256
        qemu_rearm_alarm_timer(alarm_timer);
7257
    }
7258
}
7259

    
7260
void vm_stop(int reason)
7261
{
7262
    if (vm_running) {
7263
        cpu_disable_ticks();
7264
        vm_running = 0;
7265
        if (reason != 0) {
7266
            if (vm_stop_cb) {
7267
                vm_stop_cb(vm_stop_opaque, reason);
7268
            }
7269
        }
7270
        vm_state_notify(0);
7271
    }
7272
}
7273

    
7274
/* reset/shutdown handler */
7275

    
7276
typedef struct QEMUResetEntry {
7277
    QEMUResetHandler *func;
7278
    void *opaque;
7279
    struct QEMUResetEntry *next;
7280
} QEMUResetEntry;
7281

    
7282
static QEMUResetEntry *first_reset_entry;
7283
static int reset_requested;
7284
static int shutdown_requested;
7285
static int powerdown_requested;
7286

    
7287
int qemu_shutdown_requested(void)
7288
{
7289
    int r = shutdown_requested;
7290
    shutdown_requested = 0;
7291
    return r;
7292
}
7293

    
7294
int qemu_reset_requested(void)
7295
{
7296
    int r = reset_requested;
7297
    reset_requested = 0;
7298
    return r;
7299
}
7300

    
7301
int qemu_powerdown_requested(void)
7302
{
7303
    int r = powerdown_requested;
7304
    powerdown_requested = 0;
7305
    return r;
7306
}
7307

    
7308
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7309
{
7310
    QEMUResetEntry **pre, *re;
7311

    
7312
    pre = &first_reset_entry;
7313
    while (*pre != NULL)
7314
        pre = &(*pre)->next;
7315
    re = qemu_mallocz(sizeof(QEMUResetEntry));
7316
    re->func = func;
7317
    re->opaque = opaque;
7318
    re->next = NULL;
7319
    *pre = re;
7320
}
7321

    
7322
void qemu_system_reset(void)
7323
{
7324
    QEMUResetEntry *re;
7325

    
7326
    /* reset all devices */
7327
    for(re = first_reset_entry; re != NULL; re = re->next) {
7328
        re->func(re->opaque);
7329
    }
7330
}
7331

    
7332
void qemu_system_reset_request(void)
7333
{
7334
    if (no_reboot) {
7335
        shutdown_requested = 1;
7336
    } else {
7337
        reset_requested = 1;
7338
    }
7339
    if (cpu_single_env)
7340
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7341
}
7342

    
7343
void qemu_system_shutdown_request(void)
7344
{
7345
    shutdown_requested = 1;
7346
    if (cpu_single_env)
7347
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7348
}
7349

    
7350
void qemu_system_powerdown_request(void)
7351
{
7352
    powerdown_requested = 1;
7353
    if (cpu_single_env)
7354
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7355
}
7356

    
7357
void main_loop_wait(int timeout)
7358
{
7359
    IOHandlerRecord *ioh;
7360
    fd_set rfds, wfds, xfds;
7361
    int ret, nfds;
7362
#ifdef _WIN32
7363
    int ret2, i;
7364
#endif
7365
    struct timeval tv;
7366
    PollingEntry *pe;
7367

    
7368

    
7369
    /* XXX: need to suppress polling by better using win32 events */
7370
    ret = 0;
7371
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7372
        ret |= pe->func(pe->opaque);
7373
    }
7374
#ifdef _WIN32
7375
    if (ret == 0) {
7376
        int err;
7377
        WaitObjects *w = &wait_objects;
7378

    
7379
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7380
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7381
            if (w->func[ret - WAIT_OBJECT_0])
7382
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7383

    
7384
            /* Check for additional signaled events */
7385
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7386

    
7387
                /* Check if event is signaled */
7388
                ret2 = WaitForSingleObject(w->events[i], 0);
7389
                if(ret2 == WAIT_OBJECT_0) {
7390
                    if (w->func[i])
7391
                        w->func[i](w->opaque[i]);
7392
                } else if (ret2 == WAIT_TIMEOUT) {
7393
                } else {
7394
                    err = GetLastError();
7395
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7396
                }
7397
            }
7398
        } else if (ret == WAIT_TIMEOUT) {
7399
        } else {
7400
            err = GetLastError();
7401
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7402
        }
7403
    }
7404
#endif
7405
    /* poll any events */
7406
    /* XXX: separate device handlers from system ones */
7407
    nfds = -1;
7408
    FD_ZERO(&rfds);
7409
    FD_ZERO(&wfds);
7410
    FD_ZERO(&xfds);
7411
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7412
        if (ioh->deleted)
7413
            continue;
7414
        if (ioh->fd_read &&
7415
            (!ioh->fd_read_poll ||
7416
             ioh->fd_read_poll(ioh->opaque) != 0)) {
7417
            FD_SET(ioh->fd, &rfds);
7418
            if (ioh->fd > nfds)
7419
                nfds = ioh->fd;
7420
        }
7421
        if (ioh->fd_write) {
7422
            FD_SET(ioh->fd, &wfds);
7423
            if (ioh->fd > nfds)
7424
                nfds = ioh->fd;
7425
        }
7426
    }
7427

    
7428
    tv.tv_sec = 0;
7429
#ifdef _WIN32
7430
    tv.tv_usec = 0;
7431
#else
7432
    tv.tv_usec = timeout * 1000;
7433
#endif
7434
#if defined(CONFIG_SLIRP)
7435
    if (slirp_inited) {
7436
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7437
    }
7438
#endif
7439
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7440
    if (ret > 0) {
7441
        IOHandlerRecord **pioh;
7442

    
7443
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7444
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7445
                ioh->fd_read(ioh->opaque);
7446
            }
7447
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7448
                ioh->fd_write(ioh->opaque);
7449
            }
7450
        }
7451

    
7452
        /* remove deleted IO handlers */
7453
        pioh = &first_io_handler;
7454
        while (*pioh) {
7455
            ioh = *pioh;
7456
            if (ioh->deleted) {
7457
                *pioh = ioh->next;
7458
                qemu_free(ioh);
7459
            } else
7460
                pioh = &ioh->next;
7461
        }
7462
    }
7463
#if defined(CONFIG_SLIRP)
7464
    if (slirp_inited) {
7465
        if (ret < 0) {
7466
            FD_ZERO(&rfds);
7467
            FD_ZERO(&wfds);
7468
            FD_ZERO(&xfds);
7469
        }
7470
        slirp_select_poll(&rfds, &wfds, &xfds);
7471
    }
7472
#endif
7473
    qemu_aio_poll();
7474

    
7475
    if (vm_running) {
7476
        if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7477
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7478
                        qemu_get_clock(vm_clock));
7479
        /* run dma transfers, if any */
7480
        DMA_run();
7481
    }
7482

    
7483
    /* real time timers */
7484
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7485
                    qemu_get_clock(rt_clock));
7486

    
7487
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7488
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7489
        qemu_rearm_alarm_timer(alarm_timer);
7490
    }
7491

    
7492
    /* Check bottom-halves last in case any of the earlier events triggered
7493
       them.  */
7494
    qemu_bh_poll();
7495

    
7496
}
7497

    
7498
static int main_loop(void)
7499
{
7500
    int ret, timeout;
7501
#ifdef CONFIG_PROFILER
7502
    int64_t ti;
7503
#endif
7504
    CPUState *env;
7505

    
7506
    cur_cpu = first_cpu;
7507
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7508
    for(;;) {
7509
        if (vm_running) {
7510

    
7511
            for(;;) {
7512
                /* get next cpu */
7513
                env = next_cpu;
7514
#ifdef CONFIG_PROFILER
7515
                ti = profile_getclock();
7516
#endif
7517
                if (use_icount) {
7518
                    int64_t count;
7519
                    int decr;
7520
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7521
                    env->icount_decr.u16.low = 0;
7522
                    env->icount_extra = 0;
7523
                    count = qemu_next_deadline();
7524
                    count = (count + (1 << icount_time_shift) - 1)
7525
                            >> icount_time_shift;
7526
                    qemu_icount += count;
7527
                    decr = (count > 0xffff) ? 0xffff : count;
7528
                    count -= decr;
7529
                    env->icount_decr.u16.low = decr;
7530
                    env->icount_extra = count;
7531
                }
7532
                ret = cpu_exec(env);
7533
#ifdef CONFIG_PROFILER
7534
                qemu_time += profile_getclock() - ti;
7535
#endif
7536
                if (use_icount) {
7537
                    /* Fold pending instructions back into the
7538
                       instruction counter, and clear the interrupt flag.  */
7539
                    qemu_icount -= (env->icount_decr.u16.low
7540
                                    + env->icount_extra);
7541
                    env->icount_decr.u32 = 0;
7542
                    env->icount_extra = 0;
7543
                }
7544
                next_cpu = env->next_cpu ?: first_cpu;
7545
                if (event_pending && likely(ret != EXCP_DEBUG)) {
7546
                    ret = EXCP_INTERRUPT;
7547
                    event_pending = 0;
7548
                    break;
7549
                }
7550
                if (ret == EXCP_HLT) {
7551
                    /* Give the next CPU a chance to run.  */
7552
                    cur_cpu = env;
7553
                    continue;
7554
                }
7555
                if (ret != EXCP_HALTED)
7556
                    break;
7557
                /* all CPUs are halted ? */
7558
                if (env == cur_cpu)
7559
                    break;
7560
            }
7561
            cur_cpu = env;
7562

    
7563
            if (shutdown_requested) {
7564
                ret = EXCP_INTERRUPT;
7565
                if (no_shutdown) {
7566
                    vm_stop(0);
7567
                    no_shutdown = 0;
7568
                }
7569
                else
7570
                    break;
7571
            }
7572
            if (reset_requested) {
7573
                reset_requested = 0;
7574
                qemu_system_reset();
7575
                ret = EXCP_INTERRUPT;
7576
            }
7577
            if (powerdown_requested) {
7578
                powerdown_requested = 0;
7579
                qemu_system_powerdown();
7580
                ret = EXCP_INTERRUPT;
7581
            }
7582
            if (unlikely(ret == EXCP_DEBUG)) {
7583
                vm_stop(EXCP_DEBUG);
7584
            }
7585
            /* If all cpus are halted then wait until the next IRQ */
7586
            /* XXX: use timeout computed from timers */
7587
            if (ret == EXCP_HALTED) {
7588
                if (use_icount) {
7589
                    int64_t add;
7590
                    int64_t delta;
7591
                    /* Advance virtual time to the next event.  */
7592
                    if (use_icount == 1) {
7593
                        /* When not using an adaptive execution frequency
7594
                           we tend to get badly out of sync with real time,
7595
                           so just delay for a reasonable amount of time.  */
7596
                        delta = 0;
7597
                    } else {
7598
                        delta = cpu_get_icount() - cpu_get_clock();
7599
                    }
7600
                    if (delta > 0) {
7601
                        /* If virtual time is ahead of real time then just
7602
                           wait for IO.  */
7603
                        timeout = (delta / 1000000) + 1;
7604
                    } else {
7605
                        /* Wait for either IO to occur or the next
7606
                           timer event.  */
7607
                        add = qemu_next_deadline();
7608
                        /* We advance the timer before checking for IO.
7609
                           Limit the amount we advance so that early IO
7610
                           activity won't get the guest too far ahead.  */
7611
                        if (add > 10000000)
7612
                            add = 10000000;
7613
                        delta += add;
7614
                        add = (add + (1 << icount_time_shift) - 1)
7615
                              >> icount_time_shift;
7616
                        qemu_icount += add;
7617
                        timeout = delta / 1000000;
7618
                        if (timeout < 0)
7619
                            timeout = 0;
7620
                    }
7621
                } else {
7622
                    timeout = 10;
7623
                }
7624
            } else {
7625
                timeout = 0;
7626
            }
7627
        } else {
7628
            if (shutdown_requested)
7629
                break;
7630
            timeout = 10;
7631
        }
7632
#ifdef CONFIG_PROFILER
7633
        ti = profile_getclock();
7634
#endif
7635
        main_loop_wait(timeout);
7636
#ifdef CONFIG_PROFILER
7637
        dev_time += profile_getclock() - ti;
7638
#endif
7639
    }
7640
    cpu_disable_ticks();
7641
    return ret;
7642
}
7643

    
7644
static void help(int exitcode)
7645
{
7646
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7647
           "usage: %s [options] [disk_image]\n"
7648
           "\n"
7649
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7650
           "\n"
7651
           "Standard options:\n"
7652
           "-M machine      select emulated machine (-M ? for list)\n"
7653
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7654
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7655
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7656
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7657
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7658
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7659
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7660
           "       [,cache=on|off][,format=f]\n"
7661
           "                use 'file' as a drive image\n"
7662
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7663
           "-sd file        use 'file' as SecureDigital card image\n"
7664
           "-pflash file    use 'file' as a parallel flash image\n"
7665
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7666
           "-snapshot       write to temporary files instead of disk image files\n"
7667
#ifdef CONFIG_SDL
7668
           "-no-frame       open SDL window without a frame and window decorations\n"
7669
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7670
           "-no-quit        disable SDL window close capability\n"
7671
#endif
7672
#ifdef TARGET_I386
7673
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7674
#endif
7675
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7676
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7677
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7678
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7679
#ifndef _WIN32
7680
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7681
#endif
7682
#ifdef HAS_AUDIO
7683
           "-audio-help     print list of audio drivers and their options\n"
7684
           "-soundhw c1,... enable audio support\n"
7685
           "                and only specified sound cards (comma separated list)\n"
7686
           "                use -soundhw ? to get the list of supported cards\n"
7687
           "                use -soundhw all to enable all of them\n"
7688
#endif
7689
           "-localtime      set the real time clock to local time [default=utc]\n"
7690
           "-full-screen    start in full screen\n"
7691
#ifdef TARGET_I386
7692
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7693
#endif
7694
           "-usb            enable the USB driver (will be the default soon)\n"
7695
           "-usbdevice name add the host or guest USB device 'name'\n"
7696
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7697
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7698
#endif
7699
           "-name string    set the name of the guest\n"
7700
           "\n"
7701
           "Network options:\n"
7702
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7703
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7704
#ifdef CONFIG_SLIRP
7705
           "-net user[,vlan=n][,hostname=host]\n"
7706
           "                connect the user mode network stack to VLAN 'n' and send\n"
7707
           "                hostname 'host' to DHCP clients\n"
7708
#endif
7709
#ifdef _WIN32
7710
           "-net tap[,vlan=n],ifname=name\n"
7711
           "                connect the host TAP network interface to VLAN 'n'\n"
7712
#else
7713
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7714
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7715
           "                network scripts 'file' (default=%s)\n"
7716
           "                and 'dfile' (default=%s);\n"
7717
           "                use '[down]script=no' to disable script execution;\n"
7718
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7719
#endif
7720
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7721
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7722
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7723
           "                connect the vlan 'n' to multicast maddr and port\n"
7724
#ifdef CONFIG_VDE
7725
           "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7726
           "                connect the vlan 'n' to port 'n' of a vde switch running\n"
7727
           "                on host and listening for incoming connections on 'socketpath'.\n"
7728
           "                Use group 'groupname' and mode 'octalmode' to change default\n"
7729
           "                ownership and permissions for communication port.\n"
7730
#endif
7731
           "-net none       use it alone to have zero network devices; if no -net option\n"
7732
           "                is provided, the default is '-net nic -net user'\n"
7733
           "\n"
7734
#ifdef CONFIG_SLIRP
7735
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7736
           "-bootp file     advertise file in BOOTP replies\n"
7737
#ifndef _WIN32
7738
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7739
#endif
7740
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7741
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7742
#endif
7743
           "\n"
7744
           "Linux boot specific:\n"
7745
           "-kernel bzImage use 'bzImage' as kernel image\n"
7746
           "-append cmdline use 'cmdline' as kernel command line\n"
7747
           "-initrd file    use 'file' as initial ram disk\n"
7748
           "\n"
7749
           "Debug/Expert options:\n"
7750
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7751
           "-serial dev     redirect the serial port to char device 'dev'\n"
7752
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7753
           "-pidfile file   Write PID to 'file'\n"
7754
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7755
           "-s              wait gdb connection to port\n"
7756
           "-p port         set gdb connection port [default=%s]\n"
7757
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7758
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7759
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7760
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7761
#ifdef USE_KQEMU
7762
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7763
           "-no-kqemu       disable KQEMU kernel module usage\n"
7764
#endif
7765
#ifdef TARGET_I386
7766
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7767
           "                (default is CL-GD5446 PCI VGA)\n"
7768
           "-no-acpi        disable ACPI\n"
7769
#endif
7770
#ifdef CONFIG_CURSES
7771
           "-curses         use a curses/ncurses interface instead of SDL\n"
7772
#endif
7773
           "-no-reboot      exit instead of rebooting\n"
7774
           "-no-shutdown    stop before shutdown\n"
7775
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
7776
           "-vnc display    start a VNC server on display\n"
7777
#ifndef _WIN32
7778
           "-daemonize      daemonize QEMU after initializing\n"
7779
#endif
7780
           "-option-rom rom load a file, rom, into the option ROM space\n"
7781
#ifdef TARGET_SPARC
7782
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7783
#endif
7784
           "-clock          force the use of the given methods for timer alarm.\n"
7785
           "                To see what timers are available use -clock ?\n"
7786
           "-startdate      select initial date of the clock\n"
7787
           "-icount [N|auto]\n"
7788
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7789
           "\n"
7790
           "During emulation, the following keys are useful:\n"
7791
           "ctrl-alt-f      toggle full screen\n"
7792
           "ctrl-alt-n      switch to virtual console 'n'\n"
7793
           "ctrl-alt        toggle mouse and keyboard grab\n"
7794
           "\n"
7795
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7796
           ,
7797
           "qemu",
7798
           DEFAULT_RAM_SIZE,
7799
#ifndef _WIN32
7800
           DEFAULT_NETWORK_SCRIPT,
7801
           DEFAULT_NETWORK_DOWN_SCRIPT,
7802
#endif
7803
           DEFAULT_GDBSTUB_PORT,
7804
           "/tmp/qemu.log");
7805
    exit(exitcode);
7806
}
7807

    
7808
#define HAS_ARG 0x0001
7809

    
7810
enum {
7811
    QEMU_OPTION_h,
7812

    
7813
    QEMU_OPTION_M,
7814
    QEMU_OPTION_cpu,
7815
    QEMU_OPTION_fda,
7816
    QEMU_OPTION_fdb,
7817
    QEMU_OPTION_hda,
7818
    QEMU_OPTION_hdb,
7819
    QEMU_OPTION_hdc,
7820
    QEMU_OPTION_hdd,
7821
    QEMU_OPTION_drive,
7822
    QEMU_OPTION_cdrom,
7823
    QEMU_OPTION_mtdblock,
7824
    QEMU_OPTION_sd,
7825
    QEMU_OPTION_pflash,
7826
    QEMU_OPTION_boot,
7827
    QEMU_OPTION_snapshot,
7828
#ifdef TARGET_I386
7829
    QEMU_OPTION_no_fd_bootchk,
7830
#endif
7831
    QEMU_OPTION_m,
7832
    QEMU_OPTION_nographic,
7833
    QEMU_OPTION_portrait,
7834
#ifdef HAS_AUDIO
7835
    QEMU_OPTION_audio_help,
7836
    QEMU_OPTION_soundhw,
7837
#endif
7838

    
7839
    QEMU_OPTION_net,
7840
    QEMU_OPTION_tftp,
7841
    QEMU_OPTION_bootp,
7842
    QEMU_OPTION_smb,
7843
    QEMU_OPTION_redir,
7844

    
7845
    QEMU_OPTION_kernel,
7846
    QEMU_OPTION_append,
7847
    QEMU_OPTION_initrd,
7848

    
7849
    QEMU_OPTION_S,
7850
    QEMU_OPTION_s,
7851
    QEMU_OPTION_p,
7852
    QEMU_OPTION_d,
7853
    QEMU_OPTION_hdachs,
7854
    QEMU_OPTION_L,
7855
    QEMU_OPTION_bios,
7856
    QEMU_OPTION_k,
7857
    QEMU_OPTION_localtime,
7858
    QEMU_OPTION_cirrusvga,
7859
    QEMU_OPTION_vmsvga,
7860
    QEMU_OPTION_g,
7861
    QEMU_OPTION_std_vga,
7862
    QEMU_OPTION_echr,
7863
    QEMU_OPTION_monitor,
7864
    QEMU_OPTION_serial,
7865
    QEMU_OPTION_parallel,
7866
    QEMU_OPTION_loadvm,
7867
    QEMU_OPTION_full_screen,
7868
    QEMU_OPTION_no_frame,
7869
    QEMU_OPTION_alt_grab,
7870
    QEMU_OPTION_no_quit,
7871
    QEMU_OPTION_pidfile,
7872
    QEMU_OPTION_no_kqemu,
7873
    QEMU_OPTION_kernel_kqemu,
7874
    QEMU_OPTION_win2k_hack,
7875
    QEMU_OPTION_usb,
7876
    QEMU_OPTION_usbdevice,
7877
    QEMU_OPTION_smp,
7878
    QEMU_OPTION_vnc,
7879
    QEMU_OPTION_no_acpi,
7880
    QEMU_OPTION_curses,
7881
    QEMU_OPTION_no_reboot,
7882
    QEMU_OPTION_no_shutdown,
7883
    QEMU_OPTION_show_cursor,
7884
    QEMU_OPTION_daemonize,
7885
    QEMU_OPTION_option_rom,
7886
    QEMU_OPTION_semihosting,
7887
    QEMU_OPTION_name,
7888
    QEMU_OPTION_prom_env,
7889
    QEMU_OPTION_old_param,
7890
    QEMU_OPTION_clock,
7891
    QEMU_OPTION_startdate,
7892
    QEMU_OPTION_tb_size,
7893
    QEMU_OPTION_icount,
7894
};
7895

    
7896
typedef struct QEMUOption {
7897
    const char *name;
7898
    int flags;
7899
    int index;
7900
} QEMUOption;
7901

    
7902
const QEMUOption qemu_options[] = {
7903
    { "h", 0, QEMU_OPTION_h },
7904
    { "help", 0, QEMU_OPTION_h },
7905

    
7906
    { "M", HAS_ARG, QEMU_OPTION_M },
7907
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7908
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7909
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7910
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7911
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7912
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7913
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7914
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7915
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7916
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7917
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7918
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7919
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7920
    { "snapshot", 0, QEMU_OPTION_snapshot },
7921
#ifdef TARGET_I386
7922
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7923
#endif
7924
    { "m", HAS_ARG, QEMU_OPTION_m },
7925
    { "nographic", 0, QEMU_OPTION_nographic },
7926
    { "portrait", 0, QEMU_OPTION_portrait },
7927
    { "k", HAS_ARG, QEMU_OPTION_k },
7928
#ifdef HAS_AUDIO
7929
    { "audio-help", 0, QEMU_OPTION_audio_help },
7930
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7931
#endif
7932

    
7933
    { "net", HAS_ARG, QEMU_OPTION_net},
7934
#ifdef CONFIG_SLIRP
7935
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7936
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7937
#ifndef _WIN32
7938
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7939
#endif
7940
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7941
#endif
7942

    
7943
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7944
    { "append", HAS_ARG, QEMU_OPTION_append },
7945
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7946

    
7947
    { "S", 0, QEMU_OPTION_S },
7948
    { "s", 0, QEMU_OPTION_s },
7949
    { "p", HAS_ARG, QEMU_OPTION_p },
7950
    { "d", HAS_ARG, QEMU_OPTION_d },
7951
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7952
    { "L", HAS_ARG, QEMU_OPTION_L },
7953
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7954
#ifdef USE_KQEMU
7955
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7956
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7957
#endif
7958
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7959
    { "g", 1, QEMU_OPTION_g },
7960
#endif
7961
    { "localtime", 0, QEMU_OPTION_localtime },
7962
    { "std-vga", 0, QEMU_OPTION_std_vga },
7963
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7964
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7965
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7966
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7967
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7968
    { "full-screen", 0, QEMU_OPTION_full_screen },
7969
#ifdef CONFIG_SDL
7970
    { "no-frame", 0, QEMU_OPTION_no_frame },
7971
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7972
    { "no-quit", 0, QEMU_OPTION_no_quit },
7973
#endif
7974
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7975
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7976
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7977
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7978
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7979
#ifdef CONFIG_CURSES
7980
    { "curses", 0, QEMU_OPTION_curses },
7981
#endif
7982

    
7983
    /* temporary options */
7984
    { "usb", 0, QEMU_OPTION_usb },
7985
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7986
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7987
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7988
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7989
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7990
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7991
    { "daemonize", 0, QEMU_OPTION_daemonize },
7992
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7993
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7994
    { "semihosting", 0, QEMU_OPTION_semihosting },
7995
#endif
7996
    { "name", HAS_ARG, QEMU_OPTION_name },
7997
#if defined(TARGET_SPARC)
7998
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7999
#endif
8000
#if defined(TARGET_ARM)
8001
    { "old-param", 0, QEMU_OPTION_old_param },
8002
#endif
8003
    { "clock", HAS_ARG, QEMU_OPTION_clock },
8004
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8005
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8006
    { "icount", HAS_ARG, QEMU_OPTION_icount },
8007
    { NULL },
8008
};
8009

    
8010
/* password input */
8011

    
8012
int qemu_key_check(BlockDriverState *bs, const char *name)
8013
{
8014
    char password[256];
8015
    int i;
8016

    
8017
    if (!bdrv_is_encrypted(bs))
8018
        return 0;
8019

    
8020
    term_printf("%s is encrypted.\n", name);
8021
    for(i = 0; i < 3; i++) {
8022
        monitor_readline("Password: ", 1, password, sizeof(password));
8023
        if (bdrv_set_key(bs, password) == 0)
8024
            return 0;
8025
        term_printf("invalid password\n");
8026
    }
8027
    return -EPERM;
8028
}
8029

    
8030
static BlockDriverState *get_bdrv(int index)
8031
{
8032
    if (index > nb_drives)
8033
        return NULL;
8034
    return drives_table[index].bdrv;
8035
}
8036

    
8037
static void read_passwords(void)
8038
{
8039
    BlockDriverState *bs;
8040
    int i;
8041

    
8042
    for(i = 0; i < 6; i++) {
8043
        bs = get_bdrv(i);
8044
        if (bs)
8045
            qemu_key_check(bs, bdrv_get_device_name(bs));
8046
    }
8047
}
8048

    
8049
#ifdef HAS_AUDIO
8050
struct soundhw soundhw[] = {
8051
#ifdef HAS_AUDIO_CHOICE
8052
#if defined(TARGET_I386) || defined(TARGET_MIPS)
8053
    {
8054
        "pcspk",
8055
        "PC speaker",
8056
        0,
8057
        1,
8058
        { .init_isa = pcspk_audio_init }
8059
    },
8060
#endif
8061
    {
8062
        "sb16",
8063
        "Creative Sound Blaster 16",
8064
        0,
8065
        1,
8066
        { .init_isa = SB16_init }
8067
    },
8068

    
8069
#ifdef CONFIG_CS4231A
8070
    {
8071
        "cs4231a",
8072
        "CS4231A",
8073
        0,
8074
        1,
8075
        { .init_isa = cs4231a_init }
8076
    },
8077
#endif
8078

    
8079
#ifdef CONFIG_ADLIB
8080
    {
8081
        "adlib",
8082
#ifdef HAS_YMF262
8083
        "Yamaha YMF262 (OPL3)",
8084
#else
8085
        "Yamaha YM3812 (OPL2)",
8086
#endif
8087
        0,
8088
        1,
8089
        { .init_isa = Adlib_init }
8090
    },
8091
#endif
8092

    
8093
#ifdef CONFIG_GUS
8094
    {
8095
        "gus",
8096
        "Gravis Ultrasound GF1",
8097
        0,
8098
        1,
8099
        { .init_isa = GUS_init }
8100
    },
8101
#endif
8102

    
8103
#ifdef CONFIG_AC97
8104
    {
8105
        "ac97",
8106
        "Intel 82801AA AC97 Audio",
8107
        0,
8108
        0,
8109
        { .init_pci = ac97_init }
8110
    },
8111
#endif
8112

    
8113
    {
8114
        "es1370",
8115
        "ENSONIQ AudioPCI ES1370",
8116
        0,
8117
        0,
8118
        { .init_pci = es1370_init }
8119
    },
8120
#endif
8121

    
8122
    { NULL, NULL, 0, 0, { NULL } }
8123
};
8124

    
8125
static void select_soundhw (const char *optarg)
8126
{
8127
    struct soundhw *c;
8128

    
8129
    if (*optarg == '?') {
8130
    show_valid_cards:
8131

    
8132
        printf ("Valid sound card names (comma separated):\n");
8133
        for (c = soundhw; c->name; ++c) {
8134
            printf ("%-11s %s\n", c->name, c->descr);
8135
        }
8136
        printf ("\n-soundhw all will enable all of the above\n");
8137
        exit (*optarg != '?');
8138
    }
8139
    else {
8140
        size_t l;
8141
        const char *p;
8142
        char *e;
8143
        int bad_card = 0;
8144

    
8145
        if (!strcmp (optarg, "all")) {
8146
            for (c = soundhw; c->name; ++c) {
8147
                c->enabled = 1;
8148
            }
8149
            return;
8150
        }
8151

    
8152
        p = optarg;
8153
        while (*p) {
8154
            e = strchr (p, ',');
8155
            l = !e ? strlen (p) : (size_t) (e - p);
8156

    
8157
            for (c = soundhw; c->name; ++c) {
8158
                if (!strncmp (c->name, p, l)) {
8159
                    c->enabled = 1;
8160
                    break;
8161
                }
8162
            }
8163

    
8164
            if (!c->name) {
8165
                if (l > 80) {
8166
                    fprintf (stderr,
8167
                             "Unknown sound card name (too big to show)\n");
8168
                }
8169
                else {
8170
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
8171
                             (int) l, p);
8172
                }
8173
                bad_card = 1;
8174
            }
8175
            p += l + (e != NULL);
8176
        }
8177

    
8178
        if (bad_card)
8179
            goto show_valid_cards;
8180
    }
8181
}
8182
#endif
8183

    
8184
#ifdef _WIN32
8185
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8186
{
8187
    exit(STATUS_CONTROL_C_EXIT);
8188
    return TRUE;
8189
}
8190
#endif
8191

    
8192
#define MAX_NET_CLIENTS 32
8193

    
8194
#ifndef _WIN32
8195

    
8196
static void termsig_handler(int signal)
8197
{
8198
    qemu_system_shutdown_request();
8199
}
8200

    
8201
void termsig_setup(void)
8202
{
8203
    struct sigaction act;
8204

    
8205
    memset(&act, 0, sizeof(act));
8206
    act.sa_handler = termsig_handler;
8207
    sigaction(SIGINT,  &act, NULL);
8208
    sigaction(SIGHUP,  &act, NULL);
8209
    sigaction(SIGTERM, &act, NULL);
8210
}
8211

    
8212
#endif
8213

    
8214
int main(int argc, char **argv)
8215
{
8216
#ifdef CONFIG_GDBSTUB
8217
    int use_gdbstub;
8218
    const char *gdbstub_port;
8219
#endif
8220
    uint32_t boot_devices_bitmap = 0;
8221
    int i;
8222
    int snapshot, linux_boot, net_boot;
8223
    const char *initrd_filename;
8224
    const char *kernel_filename, *kernel_cmdline;
8225
    const char *boot_devices = "";
8226
    DisplayState *ds = &display_state;
8227
    int cyls, heads, secs, translation;
8228
    const char *net_clients[MAX_NET_CLIENTS];
8229
    int nb_net_clients;
8230
    int hda_index;
8231
    int optind;
8232
    const char *r, *optarg;
8233
    CharDriverState *monitor_hd;
8234
    const char *monitor_device;
8235
    const char *serial_devices[MAX_SERIAL_PORTS];
8236
    int serial_device_index;
8237
    const char *parallel_devices[MAX_PARALLEL_PORTS];
8238
    int parallel_device_index;
8239
    const char *loadvm = NULL;
8240
    QEMUMachine *machine;
8241
    const char *cpu_model;
8242
    const char *usb_devices[MAX_USB_CMDLINE];
8243
    int usb_devices_index;
8244
    int fds[2];
8245
    int tb_size;
8246
    const char *pid_file = NULL;
8247
    VLANState *vlan;
8248

    
8249
    LIST_INIT (&vm_change_state_head);
8250
#ifndef _WIN32
8251
    {
8252
        struct sigaction act;
8253
        sigfillset(&act.sa_mask);
8254
        act.sa_flags = 0;
8255
        act.sa_handler = SIG_IGN;
8256
        sigaction(SIGPIPE, &act, NULL);
8257
    }
8258
#else
8259
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8260
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
8261
       QEMU to run on a single CPU */
8262
    {
8263
        HANDLE h;
8264
        DWORD mask, smask;
8265
        int i;
8266
        h = GetCurrentProcess();
8267
        if (GetProcessAffinityMask(h, &mask, &smask)) {
8268
            for(i = 0; i < 32; i++) {
8269
                if (mask & (1 << i))
8270
                    break;
8271
            }
8272
            if (i != 32) {
8273
                mask = 1 << i;
8274
                SetProcessAffinityMask(h, mask);
8275
            }
8276
        }
8277
    }
8278
#endif
8279

    
8280
    register_machines();
8281
    machine = first_machine;
8282
    cpu_model = NULL;
8283
    initrd_filename = NULL;
8284
    ram_size = 0;
8285
    vga_ram_size = VGA_RAM_SIZE;
8286
#ifdef CONFIG_GDBSTUB
8287
    use_gdbstub = 0;
8288
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
8289
#endif
8290
    snapshot = 0;
8291
    nographic = 0;
8292
    curses = 0;
8293
    kernel_filename = NULL;
8294
    kernel_cmdline = "";
8295
    cyls = heads = secs = 0;
8296
    translation = BIOS_ATA_TRANSLATION_AUTO;
8297
    monitor_device = "vc";
8298

    
8299
    serial_devices[0] = "vc:80Cx24C";
8300
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
8301
        serial_devices[i] = NULL;
8302
    serial_device_index = 0;
8303

    
8304
    parallel_devices[0] = "vc:640x480";
8305
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8306
        parallel_devices[i] = NULL;
8307
    parallel_device_index = 0;
8308

    
8309
    usb_devices_index = 0;
8310

    
8311
    nb_net_clients = 0;
8312
    nb_drives = 0;
8313
    nb_drives_opt = 0;
8314
    hda_index = -1;
8315

    
8316
    nb_nics = 0;
8317

    
8318
    tb_size = 0;
8319
    
8320
    optind = 1;
8321
    for(;;) {
8322
        if (optind >= argc)
8323
            break;
8324
        r = argv[optind];
8325
        if (r[0] != '-') {
8326
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8327
        } else {
8328
            const QEMUOption *popt;
8329

    
8330
            optind++;
8331
            /* Treat --foo the same as -foo.  */
8332
            if (r[1] == '-')
8333
                r++;
8334
            popt = qemu_options;
8335
            for(;;) {
8336
                if (!popt->name) {
8337
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
8338
                            argv[0], r);
8339
                    exit(1);
8340
                }
8341
                if (!strcmp(popt->name, r + 1))
8342
                    break;
8343
                popt++;
8344
            }
8345
            if (popt->flags & HAS_ARG) {
8346
                if (optind >= argc) {
8347
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
8348
                            argv[0], r);
8349
                    exit(1);
8350
                }
8351
                optarg = argv[optind++];
8352
            } else {
8353
                optarg = NULL;
8354
            }
8355

    
8356
            switch(popt->index) {
8357
            case QEMU_OPTION_M:
8358
                machine = find_machine(optarg);
8359
                if (!machine) {
8360
                    QEMUMachine *m;
8361
                    printf("Supported machines are:\n");
8362
                    for(m = first_machine; m != NULL; m = m->next) {
8363
                        printf("%-10s %s%s\n",
8364
                               m->name, m->desc,
8365
                               m == first_machine ? " (default)" : "");
8366
                    }
8367
                    exit(*optarg != '?');
8368
                }
8369
                break;
8370
            case QEMU_OPTION_cpu:
8371
                /* hw initialization will check this */
8372
                if (*optarg == '?') {
8373
/* XXX: implement xxx_cpu_list for targets that still miss it */
8374
#if defined(cpu_list)
8375
                    cpu_list(stdout, &fprintf);
8376
#endif
8377
                    exit(0);
8378
                } else {
8379
                    cpu_model = optarg;
8380
                }
8381
                break;
8382
            case QEMU_OPTION_initrd:
8383
                initrd_filename = optarg;
8384
                break;
8385
            case QEMU_OPTION_hda:
8386
                if (cyls == 0)
8387
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
8388
                else
8389
                    hda_index = drive_add(optarg, HD_ALIAS
8390
                             ",cyls=%d,heads=%d,secs=%d%s",
8391
                             0, cyls, heads, secs,
8392
                             translation == BIOS_ATA_TRANSLATION_LBA ?
8393
                                 ",trans=lba" :
8394
                             translation == BIOS_ATA_TRANSLATION_NONE ?
8395
                                 ",trans=none" : "");
8396
                 break;
8397
            case QEMU_OPTION_hdb:
8398
            case QEMU_OPTION_hdc:
8399
            case QEMU_OPTION_hdd:
8400
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8401
                break;
8402
            case QEMU_OPTION_drive:
8403
                drive_add(NULL, "%s", optarg);
8404
                break;
8405
            case QEMU_OPTION_mtdblock:
8406
                drive_add(optarg, MTD_ALIAS);
8407
                break;
8408
            case QEMU_OPTION_sd:
8409
                drive_add(optarg, SD_ALIAS);
8410
                break;
8411
            case QEMU_OPTION_pflash:
8412
                drive_add(optarg, PFLASH_ALIAS);
8413
                break;
8414
            case QEMU_OPTION_snapshot:
8415
                snapshot = 1;
8416
                break;
8417
            case QEMU_OPTION_hdachs:
8418
                {
8419
                    const char *p;
8420
                    p = optarg;
8421
                    cyls = strtol(p, (char **)&p, 0);
8422
                    if (cyls < 1 || cyls > 16383)
8423
                        goto chs_fail;
8424
                    if (*p != ',')
8425
                        goto chs_fail;
8426
                    p++;
8427
                    heads = strtol(p, (char **)&p, 0);
8428
                    if (heads < 1 || heads > 16)
8429
                        goto chs_fail;
8430
                    if (*p != ',')
8431
                        goto chs_fail;
8432
                    p++;
8433
                    secs = strtol(p, (char **)&p, 0);
8434
                    if (secs < 1 || secs > 63)
8435
                        goto chs_fail;
8436
                    if (*p == ',') {
8437
                        p++;
8438
                        if (!strcmp(p, "none"))
8439
                            translation = BIOS_ATA_TRANSLATION_NONE;
8440
                        else if (!strcmp(p, "lba"))
8441
                            translation = BIOS_ATA_TRANSLATION_LBA;
8442
                        else if (!strcmp(p, "auto"))
8443
                            translation = BIOS_ATA_TRANSLATION_AUTO;
8444
                        else
8445
                            goto chs_fail;
8446
                    } else if (*p != '\0') {
8447
                    chs_fail:
8448
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
8449
                        exit(1);
8450
                    }
8451
                    if (hda_index != -1)
8452
                        snprintf(drives_opt[hda_index].opt,
8453
                                 sizeof(drives_opt[hda_index].opt),
8454
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8455
                                 0, cyls, heads, secs,
8456
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
8457
                                         ",trans=lba" :
8458
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
8459
                                     ",trans=none" : "");
8460
                }
8461
                break;
8462
            case QEMU_OPTION_nographic:
8463
                nographic = 1;
8464
                break;
8465
#ifdef CONFIG_CURSES
8466
            case QEMU_OPTION_curses:
8467
                curses = 1;
8468
                break;
8469
#endif
8470
            case QEMU_OPTION_portrait:
8471
                graphic_rotate = 1;
8472
                break;
8473
            case QEMU_OPTION_kernel:
8474
                kernel_filename = optarg;
8475
                break;
8476
            case QEMU_OPTION_append:
8477
                kernel_cmdline = optarg;
8478
                break;
8479
            case QEMU_OPTION_cdrom:
8480
                drive_add(optarg, CDROM_ALIAS);
8481
                break;
8482
            case QEMU_OPTION_boot:
8483
                boot_devices = optarg;
8484
                /* We just do some generic consistency checks */
8485
                {
8486
                    /* Could easily be extended to 64 devices if needed */
8487
                    const char *p;
8488
                    
8489
                    boot_devices_bitmap = 0;
8490
                    for (p = boot_devices; *p != '\0'; p++) {
8491
                        /* Allowed boot devices are:
8492
                         * a b     : floppy disk drives
8493
                         * c ... f : IDE disk drives
8494
                         * g ... m : machine implementation dependant drives
8495
                         * n ... p : network devices
8496
                         * It's up to each machine implementation to check
8497
                         * if the given boot devices match the actual hardware
8498
                         * implementation and firmware features.
8499
                         */
8500
                        if (*p < 'a' || *p > 'q') {
8501
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
8502
                            exit(1);
8503
                        }
8504
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8505
                            fprintf(stderr,
8506
                                    "Boot device '%c' was given twice\n",*p);
8507
                            exit(1);
8508
                        }
8509
                        boot_devices_bitmap |= 1 << (*p - 'a');
8510
                    }
8511
                }
8512
                break;
8513
            case QEMU_OPTION_fda:
8514
            case QEMU_OPTION_fdb:
8515
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8516
                break;
8517
#ifdef TARGET_I386
8518
            case QEMU_OPTION_no_fd_bootchk:
8519
                fd_bootchk = 0;
8520
                break;
8521
#endif
8522
            case QEMU_OPTION_net:
8523
                if (nb_net_clients >= MAX_NET_CLIENTS) {
8524
                    fprintf(stderr, "qemu: too many network clients\n");
8525
                    exit(1);
8526
                }
8527
                net_clients[nb_net_clients] = optarg;
8528
                nb_net_clients++;
8529
                break;
8530
#ifdef CONFIG_SLIRP
8531
            case QEMU_OPTION_tftp:
8532
                tftp_prefix = optarg;
8533
                break;
8534
            case QEMU_OPTION_bootp:
8535
                bootp_filename = optarg;
8536
                break;
8537
#ifndef _WIN32
8538
            case QEMU_OPTION_smb:
8539
                net_slirp_smb(optarg);
8540
                break;
8541
#endif
8542
            case QEMU_OPTION_redir:
8543
                net_slirp_redir(optarg);
8544
                break;
8545
#endif
8546
#ifdef HAS_AUDIO
8547
            case QEMU_OPTION_audio_help:
8548
                AUD_help ();
8549
                exit (0);
8550
                break;
8551
            case QEMU_OPTION_soundhw:
8552
                select_soundhw (optarg);
8553
                break;
8554
#endif
8555
            case QEMU_OPTION_h:
8556
                help(0);
8557
                break;
8558
            case QEMU_OPTION_m: {
8559
                uint64_t value;
8560
                char *ptr;
8561

    
8562
                value = strtoul(optarg, &ptr, 10);
8563
                switch (*ptr) {
8564
                case 0: case 'M': case 'm':
8565
                    value <<= 20;
8566
                    break;
8567
                case 'G': case 'g':
8568
                    value <<= 30;
8569
                    break;
8570
                default:
8571
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8572
                    exit(1);
8573
                }
8574

    
8575
                /* On 32-bit hosts, QEMU is limited by virtual address space */
8576
                if (value > (2047 << 20)
8577
#ifndef USE_KQEMU
8578
                    && HOST_LONG_BITS == 32
8579
#endif
8580
                    ) {
8581
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8582
                    exit(1);
8583
                }
8584
                if (value != (uint64_t)(ram_addr_t)value) {
8585
                    fprintf(stderr, "qemu: ram size too large\n");
8586
                    exit(1);
8587
                }
8588
                ram_size = value;
8589
                break;
8590
            }
8591
            case QEMU_OPTION_d:
8592
                {
8593
                    int mask;
8594
                    CPULogItem *item;
8595

    
8596
                    mask = cpu_str_to_log_mask(optarg);
8597
                    if (!mask) {
8598
                        printf("Log items (comma separated):\n");
8599
                    for(item = cpu_log_items; item->mask != 0; item++) {
8600
                        printf("%-10s %s\n", item->name, item->help);
8601
                    }
8602
                    exit(1);
8603
                    }
8604
                    cpu_set_log(mask);
8605
                }
8606
                break;
8607
#ifdef CONFIG_GDBSTUB
8608
            case QEMU_OPTION_s:
8609
                use_gdbstub = 1;
8610
                break;
8611
            case QEMU_OPTION_p:
8612
                gdbstub_port = optarg;
8613
                break;
8614
#endif
8615
            case QEMU_OPTION_L:
8616
                bios_dir = optarg;
8617
                break;
8618
            case QEMU_OPTION_bios:
8619
                bios_name = optarg;
8620
                break;
8621
            case QEMU_OPTION_S:
8622
                autostart = 0;
8623
                break;
8624
            case QEMU_OPTION_k:
8625
                keyboard_layout = optarg;
8626
                break;
8627
            case QEMU_OPTION_localtime:
8628
                rtc_utc = 0;
8629
                break;
8630
            case QEMU_OPTION_cirrusvga:
8631
                cirrus_vga_enabled = 1;
8632
                vmsvga_enabled = 0;
8633
                break;
8634
            case QEMU_OPTION_vmsvga:
8635
                cirrus_vga_enabled = 0;
8636
                vmsvga_enabled = 1;
8637
                break;
8638
            case QEMU_OPTION_std_vga:
8639
                cirrus_vga_enabled = 0;
8640
                vmsvga_enabled = 0;
8641
                break;
8642
            case QEMU_OPTION_g:
8643
                {
8644
                    const char *p;
8645
                    int w, h, depth;
8646
                    p = optarg;
8647
                    w = strtol(p, (char **)&p, 10);
8648
                    if (w <= 0) {
8649
                    graphic_error:
8650
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8651
                        exit(1);
8652
                    }
8653
                    if (*p != 'x')
8654
                        goto graphic_error;
8655
                    p++;
8656
                    h = strtol(p, (char **)&p, 10);
8657
                    if (h <= 0)
8658
                        goto graphic_error;
8659
                    if (*p == 'x') {
8660
                        p++;
8661
                        depth = strtol(p, (char **)&p, 10);
8662
                        if (depth != 8 && depth != 15 && depth != 16 &&
8663
                            depth != 24 && depth != 32)
8664
                            goto graphic_error;
8665
                    } else if (*p == '\0') {
8666
                        depth = graphic_depth;
8667
                    } else {
8668
                        goto graphic_error;
8669
                    }
8670

    
8671
                    graphic_width = w;
8672
                    graphic_height = h;
8673
                    graphic_depth = depth;
8674
                }
8675
                break;
8676
            case QEMU_OPTION_echr:
8677
                {
8678
                    char *r;
8679
                    term_escape_char = strtol(optarg, &r, 0);
8680
                    if (r == optarg)
8681
                        printf("Bad argument to echr\n");
8682
                    break;
8683
                }
8684
            case QEMU_OPTION_monitor:
8685
                monitor_device = optarg;
8686
                break;
8687
            case QEMU_OPTION_serial:
8688
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8689
                    fprintf(stderr, "qemu: too many serial ports\n");
8690
                    exit(1);
8691
                }
8692
                serial_devices[serial_device_index] = optarg;
8693
                serial_device_index++;
8694
                break;
8695
            case QEMU_OPTION_parallel:
8696
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8697
                    fprintf(stderr, "qemu: too many parallel ports\n");
8698
                    exit(1);
8699
                }
8700
                parallel_devices[parallel_device_index] = optarg;
8701
                parallel_device_index++;
8702
                break;
8703
            case QEMU_OPTION_loadvm:
8704
                loadvm = optarg;
8705
                break;
8706
            case QEMU_OPTION_full_screen:
8707
                full_screen = 1;
8708
                break;
8709
#ifdef CONFIG_SDL
8710
            case QEMU_OPTION_no_frame:
8711
                no_frame = 1;
8712
                break;
8713
            case QEMU_OPTION_alt_grab:
8714
                alt_grab = 1;
8715
                break;
8716
            case QEMU_OPTION_no_quit:
8717
                no_quit = 1;
8718
                break;
8719
#endif
8720
            case QEMU_OPTION_pidfile:
8721
                pid_file = optarg;
8722
                break;
8723
#ifdef TARGET_I386
8724
            case QEMU_OPTION_win2k_hack:
8725
                win2k_install_hack = 1;
8726
                break;
8727
#endif
8728
#ifdef USE_KQEMU
8729
            case QEMU_OPTION_no_kqemu:
8730
                kqemu_allowed = 0;
8731
                break;
8732
            case QEMU_OPTION_kernel_kqemu:
8733
                kqemu_allowed = 2;
8734
                break;
8735
#endif
8736
            case QEMU_OPTION_usb:
8737
                usb_enabled = 1;
8738
                break;
8739
            case QEMU_OPTION_usbdevice:
8740
                usb_enabled = 1;
8741
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8742
                    fprintf(stderr, "Too many USB devices\n");
8743
                    exit(1);
8744
                }
8745
                usb_devices[usb_devices_index] = optarg;
8746
                usb_devices_index++;
8747
                break;
8748
            case QEMU_OPTION_smp:
8749
                smp_cpus = atoi(optarg);
8750
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8751
                    fprintf(stderr, "Invalid number of CPUs\n");
8752
                    exit(1);
8753
                }
8754
                break;
8755
            case QEMU_OPTION_vnc:
8756
                vnc_display = optarg;
8757
                break;
8758
            case QEMU_OPTION_no_acpi:
8759
                acpi_enabled = 0;
8760
                break;
8761
            case QEMU_OPTION_no_reboot:
8762
                no_reboot = 1;
8763
                break;
8764
            case QEMU_OPTION_no_shutdown:
8765
                no_shutdown = 1;
8766
                break;
8767
            case QEMU_OPTION_show_cursor:
8768
                cursor_hide = 0;
8769
                break;
8770
            case QEMU_OPTION_daemonize:
8771
                daemonize = 1;
8772
                break;
8773
            case QEMU_OPTION_option_rom:
8774
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8775
                    fprintf(stderr, "Too many option ROMs\n");
8776
                    exit(1);
8777
                }
8778
                option_rom[nb_option_roms] = optarg;
8779
                nb_option_roms++;
8780
                break;
8781
            case QEMU_OPTION_semihosting:
8782
                semihosting_enabled = 1;
8783
                break;
8784
            case QEMU_OPTION_name:
8785
                qemu_name = optarg;
8786
                break;
8787
#ifdef TARGET_SPARC
8788
            case QEMU_OPTION_prom_env:
8789
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8790
                    fprintf(stderr, "Too many prom variables\n");
8791
                    exit(1);
8792
                }
8793
                prom_envs[nb_prom_envs] = optarg;
8794
                nb_prom_envs++;
8795
                break;
8796
#endif
8797
#ifdef TARGET_ARM
8798
            case QEMU_OPTION_old_param:
8799
                old_param = 1;
8800
                break;
8801
#endif
8802
            case QEMU_OPTION_clock:
8803
                configure_alarms(optarg);
8804
                break;
8805
            case QEMU_OPTION_startdate:
8806
                {
8807
                    struct tm tm;
8808
                    time_t rtc_start_date;
8809
                    if (!strcmp(optarg, "now")) {
8810
                        rtc_date_offset = -1;
8811
                    } else {
8812
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8813
                               &tm.tm_year,
8814
                               &tm.tm_mon,
8815
                               &tm.tm_mday,
8816
                               &tm.tm_hour,
8817
                               &tm.tm_min,
8818
                               &tm.tm_sec) == 6) {
8819
                            /* OK */
8820
                        } else if (sscanf(optarg, "%d-%d-%d",
8821
                                          &tm.tm_year,
8822
                                          &tm.tm_mon,
8823
                                          &tm.tm_mday) == 3) {
8824
                            tm.tm_hour = 0;
8825
                            tm.tm_min = 0;
8826
                            tm.tm_sec = 0;
8827
                        } else {
8828
                            goto date_fail;
8829
                        }
8830
                        tm.tm_year -= 1900;
8831
                        tm.tm_mon--;
8832
                        rtc_start_date = mktimegm(&tm);
8833
                        if (rtc_start_date == -1) {
8834
                        date_fail:
8835
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8836
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8837
                            exit(1);
8838
                        }
8839
                        rtc_date_offset = time(NULL) - rtc_start_date;
8840
                    }
8841
                }
8842
                break;
8843
            case QEMU_OPTION_tb_size:
8844
                tb_size = strtol(optarg, NULL, 0);
8845
                if (tb_size < 0)
8846
                    tb_size = 0;
8847
                break;
8848
            case QEMU_OPTION_icount:
8849
                use_icount = 1;
8850
                if (strcmp(optarg, "auto") == 0) {
8851
                    icount_time_shift = -1;
8852
                } else {
8853
                    icount_time_shift = strtol(optarg, NULL, 0);
8854
                }
8855
                break;
8856
            }
8857
        }
8858
    }
8859

    
8860
    if (nographic) {
8861
       if (serial_device_index == 0)
8862
           serial_devices[0] = "stdio";
8863
       if (parallel_device_index == 0)
8864
           parallel_devices[0] = "null";
8865
       if (strncmp(monitor_device, "vc", 2) == 0)
8866
           monitor_device = "stdio";
8867
    }
8868

    
8869
#ifndef _WIN32
8870
    if (daemonize) {
8871
        pid_t pid;
8872

    
8873
        if (pipe(fds) == -1)
8874
            exit(1);
8875

    
8876
        pid = fork();
8877
        if (pid > 0) {
8878
            uint8_t status;
8879
            ssize_t len;
8880

    
8881
            close(fds[1]);
8882

    
8883
        again:
8884
            len = read(fds[0], &status, 1);
8885
            if (len == -1 && (errno == EINTR))
8886
                goto again;
8887

    
8888
            if (len != 1)
8889
                exit(1);
8890
            else if (status == 1) {
8891
                fprintf(stderr, "Could not acquire pidfile\n");
8892
                exit(1);
8893
            } else
8894
                exit(0);
8895
        } else if (pid < 0)
8896
            exit(1);
8897

    
8898
        setsid();
8899

    
8900
        pid = fork();
8901
        if (pid > 0)
8902
            exit(0);
8903
        else if (pid < 0)
8904
            exit(1);
8905

    
8906
        umask(027);
8907

    
8908
        signal(SIGTSTP, SIG_IGN);
8909
        signal(SIGTTOU, SIG_IGN);
8910
        signal(SIGTTIN, SIG_IGN);
8911
    }
8912
#endif
8913

    
8914
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8915
        if (daemonize) {
8916
            uint8_t status = 1;
8917
            write(fds[1], &status, 1);
8918
        } else
8919
            fprintf(stderr, "Could not acquire pid file\n");
8920
        exit(1);
8921
    }
8922

    
8923
#ifdef USE_KQEMU
8924
    if (smp_cpus > 1)
8925
        kqemu_allowed = 0;
8926
#endif
8927
    linux_boot = (kernel_filename != NULL);
8928
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8929

    
8930
    if (!linux_boot && net_boot == 0 &&
8931
        !machine->nodisk_ok && nb_drives_opt == 0)
8932
        help(1);
8933

    
8934
    if (!linux_boot && *kernel_cmdline != '\0') {
8935
        fprintf(stderr, "-append only allowed with -kernel option\n");
8936
        exit(1);
8937
    }
8938

    
8939
    if (!linux_boot && initrd_filename != NULL) {
8940
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
8941
        exit(1);
8942
    }
8943

    
8944
    /* boot to floppy or the default cd if no hard disk defined yet */
8945
    if (!boot_devices[0]) {
8946
        boot_devices = "cad";
8947
    }
8948
    setvbuf(stdout, NULL, _IOLBF, 0);
8949

    
8950
    init_timers();
8951
    init_timer_alarm();
8952
    qemu_aio_init();
8953
    if (use_icount && icount_time_shift < 0) {
8954
        use_icount = 2;
8955
        /* 125MIPS seems a reasonable initial guess at the guest speed.
8956
           It will be corrected fairly quickly anyway.  */
8957
        icount_time_shift = 3;
8958
        init_icount_adjust();
8959
    }
8960

    
8961
#ifdef _WIN32
8962
    socket_init();
8963
#endif
8964

    
8965
    /* init network clients */
8966
    if (nb_net_clients == 0) {
8967
        /* if no clients, we use a default config */
8968
        net_clients[0] = "nic";
8969
        net_clients[1] = "user";
8970
        nb_net_clients = 2;
8971
    }
8972

    
8973
    for(i = 0;i < nb_net_clients; i++) {
8974
        if (net_client_parse(net_clients[i]) < 0)
8975
            exit(1);
8976
    }
8977
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8978
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8979
            continue;
8980
        if (vlan->nb_guest_devs == 0)
8981
            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
8982
        if (vlan->nb_host_devs == 0)
8983
            fprintf(stderr,
8984
                    "Warning: vlan %d is not connected to host network\n",
8985
                    vlan->id);
8986
    }
8987

    
8988
#ifdef TARGET_I386
8989
    /* XXX: this should be moved in the PC machine instantiation code */
8990
    if (net_boot != 0) {
8991
        int netroms = 0;
8992
        for (i = 0; i < nb_nics && i < 4; i++) {
8993
            const char *model = nd_table[i].model;
8994
            char buf[1024];
8995
            if (net_boot & (1 << i)) {
8996
                if (model == NULL)
8997
                    model = "ne2k_pci";
8998
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8999
                if (get_image_size(buf) > 0) {
9000
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
9001
                        fprintf(stderr, "Too many option ROMs\n");
9002
                        exit(1);
9003
                    }
9004
                    option_rom[nb_option_roms] = strdup(buf);
9005
                    nb_option_roms++;
9006
                    netroms++;
9007
                }
9008
            }
9009
        }
9010
        if (netroms == 0) {
9011
            fprintf(stderr, "No valid PXE rom found for network device\n");
9012
            exit(1);
9013
        }
9014
    }
9015
#endif
9016

    
9017
    /* init the memory */
9018
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9019

    
9020
    if (machine->ram_require & RAMSIZE_FIXED) {
9021
        if (ram_size > 0) {
9022
            if (ram_size < phys_ram_size) {
9023
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9024
                                machine->name, (unsigned long long) phys_ram_size);
9025
                exit(-1);
9026
            }
9027

    
9028
            phys_ram_size = ram_size;
9029
        } else
9030
            ram_size = phys_ram_size;
9031
    } else {
9032
        if (ram_size == 0)
9033
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9034

    
9035
        phys_ram_size += ram_size;
9036
    }
9037

    
9038
    phys_ram_base = qemu_vmalloc(phys_ram_size);
9039
    if (!phys_ram_base) {
9040
        fprintf(stderr, "Could not allocate physical memory\n");
9041
        exit(1);
9042
    }
9043

    
9044
    /* init the dynamic translator */
9045
    cpu_exec_init_all(tb_size * 1024 * 1024);
9046

    
9047
    bdrv_init();
9048

    
9049
    /* we always create the cdrom drive, even if no disk is there */
9050

    
9051
    if (nb_drives_opt < MAX_DRIVES)
9052
        drive_add(NULL, CDROM_ALIAS);
9053

    
9054
    /* we always create at least one floppy */
9055

    
9056
    if (nb_drives_opt < MAX_DRIVES)
9057
        drive_add(NULL, FD_ALIAS, 0);
9058

    
9059
    /* we always create one sd slot, even if no card is in it */
9060

    
9061
    if (nb_drives_opt < MAX_DRIVES)
9062
        drive_add(NULL, SD_ALIAS);
9063

    
9064
    /* open the virtual block devices */
9065

    
9066
    for(i = 0; i < nb_drives_opt; i++)
9067
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9068
            exit(1);
9069

    
9070
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9071
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9072

    
9073
    /* terminal init */
9074
    memset(&display_state, 0, sizeof(display_state));
9075
    if (nographic) {
9076
        if (curses) {
9077
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9078
            exit(1);
9079
        }
9080
        /* nearly nothing to do */
9081
        dumb_display_init(ds);
9082
    } else if (vnc_display != NULL) {
9083
        vnc_display_init(ds);
9084
        if (vnc_display_open(ds, vnc_display) < 0)
9085
            exit(1);
9086
    } else
9087
#if defined(CONFIG_CURSES)
9088
    if (curses) {
9089
        curses_display_init(ds, full_screen);
9090
    } else
9091
#endif
9092
    {
9093
#if defined(CONFIG_SDL)
9094
        sdl_display_init(ds, full_screen, no_frame);
9095
#elif defined(CONFIG_COCOA)
9096
        cocoa_display_init(ds, full_screen);
9097
#else
9098
        dumb_display_init(ds);
9099
#endif
9100
    }
9101

    
9102
#ifndef _WIN32
9103
    /* must be after terminal init, SDL library changes signal handlers */
9104
    termsig_setup();
9105
#endif
9106

    
9107
    /* Maintain compatibility with multiple stdio monitors */
9108
    if (!strcmp(monitor_device,"stdio")) {
9109
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9110
            const char *devname = serial_devices[i];
9111
            if (devname && !strcmp(devname,"mon:stdio")) {
9112
                monitor_device = NULL;
9113
                break;
9114
            } else if (devname && !strcmp(devname,"stdio")) {
9115
                monitor_device = NULL;
9116
                serial_devices[i] = "mon:stdio";
9117
                break;
9118
            }
9119
        }
9120
    }
9121
    if (monitor_device) {
9122
        monitor_hd = qemu_chr_open(monitor_device);
9123
        if (!monitor_hd) {
9124
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9125
            exit(1);
9126
        }
9127
        monitor_init(monitor_hd, !nographic);
9128
    }
9129

    
9130
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9131
        const char *devname = serial_devices[i];
9132
        if (devname && strcmp(devname, "none")) {
9133
            serial_hds[i] = qemu_chr_open(devname);
9134
            if (!serial_hds[i]) {
9135
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
9136
                        devname);
9137
                exit(1);
9138
            }
9139
            if (strstart(devname, "vc", 0))
9140
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9141
        }
9142
    }
9143

    
9144
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9145
        const char *devname = parallel_devices[i];
9146
        if (devname && strcmp(devname, "none")) {
9147
            parallel_hds[i] = qemu_chr_open(devname);
9148
            if (!parallel_hds[i]) {
9149
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9150
                        devname);
9151
                exit(1);
9152
            }
9153
            if (strstart(devname, "vc", 0))
9154
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9155
        }
9156
    }
9157

    
9158
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
9159
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9160

    
9161
    /* init USB devices */
9162
    if (usb_enabled) {
9163
        for(i = 0; i < usb_devices_index; i++) {
9164
            if (usb_device_add(usb_devices[i]) < 0) {
9165
                fprintf(stderr, "Warning: could not add USB device %s\n",
9166
                        usb_devices[i]);
9167
            }
9168
        }
9169
    }
9170

    
9171
    if (display_state.dpy_refresh) {
9172
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9173
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9174
    }
9175

    
9176
#ifdef CONFIG_GDBSTUB
9177
    if (use_gdbstub) {
9178
        /* XXX: use standard host:port notation and modify options
9179
           accordingly. */
9180
        if (gdbserver_start(gdbstub_port) < 0) {
9181
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9182
                    gdbstub_port);
9183
            exit(1);
9184
        }
9185
    }
9186
#endif
9187

    
9188
    if (loadvm)
9189
        do_loadvm(loadvm);
9190

    
9191
    {
9192
        /* XXX: simplify init */
9193
        read_passwords();
9194
        if (autostart) {
9195
            vm_start();
9196
        }
9197
    }
9198

    
9199
    if (daemonize) {
9200
        uint8_t status = 0;
9201
        ssize_t len;
9202
        int fd;
9203

    
9204
    again1:
9205
        len = write(fds[1], &status, 1);
9206
        if (len == -1 && (errno == EINTR))
9207
            goto again1;
9208

    
9209
        if (len != 1)
9210
            exit(1);
9211

    
9212
        chdir("/");
9213
        TFR(fd = open("/dev/null", O_RDWR));
9214
        if (fd == -1)
9215
            exit(1);
9216

    
9217
        dup2(fd, 0);
9218
        dup2(fd, 1);
9219
        dup2(fd, 2);
9220

    
9221
        close(fd);
9222
    }
9223

    
9224
    main_loop();
9225
    quit_timers();
9226

    
9227
#if !defined(_WIN32)
9228
    /* close network clients */
9229
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9230
        VLANClientState *vc;
9231

    
9232
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9233
            if (vc->fd_read == tap_receive) {
9234
                char ifname[64];
9235
                TAPState *s = vc->opaque;
9236

    
9237
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9238
                    s->down_script[0])
9239
                    launch_script(s->down_script, ifname, s->fd);
9240
            }
9241
#if defined(CONFIG_VDE)
9242
            if (vc->fd_read == vde_from_qemu) {
9243
                VDEState *s = vc->opaque;
9244
                vde_close(s->vde);
9245
            }
9246
#endif
9247
        }
9248
    }
9249
#endif
9250
    return 0;
9251
}