Statistics
| Branch: | Revision:

root / vl.c @ 7ed9eba3

History | View | Annotate | Download (238.9 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_EPP_READ_ADDR:
2839
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2840
            struct ParallelIOArg *parg = arg;
2841
            int n = read(fd, parg->buffer, parg->count);
2842
            if (n != parg->count) {
2843
                return -EIO;
2844
            }
2845
        }
2846
        break;
2847
    case CHR_IOCTL_PP_EPP_READ:
2848
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2849
            struct ParallelIOArg *parg = arg;
2850
            int n = read(fd, parg->buffer, parg->count);
2851
            if (n != parg->count) {
2852
                return -EIO;
2853
            }
2854
        }
2855
        break;
2856
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2857
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2858
            struct ParallelIOArg *parg = arg;
2859
            int n = write(fd, parg->buffer, parg->count);
2860
            if (n != parg->count) {
2861
                return -EIO;
2862
            }
2863
        }
2864
        break;
2865
    case CHR_IOCTL_PP_EPP_WRITE:
2866
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2867
            struct ParallelIOArg *parg = arg;
2868
            int n = write(fd, parg->buffer, parg->count);
2869
            if (n != parg->count) {
2870
                return -EIO;
2871
            }
2872
        }
2873
        break;
2874
    default:
2875
        return -ENOTSUP;
2876
    }
2877
    return 0;
2878
}
2879

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

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

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

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

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

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

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

    
2925
    qemu_chr_reset(chr);
2926

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

    
2931
#else /* _WIN32 */
2932

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3111
    win_chr_readfile(chr);
3112
}
3113

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

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

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

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

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

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

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

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

    
3181
    s->fpipe = TRUE;
3182

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

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

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

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

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

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

    
3235

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

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

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

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

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

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

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

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

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

    
3300
/***********************************************************/
3301
/* UDP Net console */
3302

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3425
/***********************************************************/
3426
/* TCP Net console */
3427

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

    
3437
static void tcp_chr_accept(void *opaque);
3438

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

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

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

    
3475
    int i;
3476
    int j = 0;
3477

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3854
/***********************************************************/
3855
/* network device redirectors */
3856

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

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

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

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

    
3913
    return -1;
3914
}
3915

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4021
    return 0;
4022
}
4023
#endif
4024

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

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

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

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

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

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

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

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

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

    
4110
#if defined(CONFIG_SLIRP)
4111

    
4112
/* slirp network adapter */
4113

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

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

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

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

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

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

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

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

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

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

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

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

    
4206
#ifndef _WIN32
4207

    
4208
char smb_dir[1024];
4209

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

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

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

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

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

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

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

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

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

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

    
4302
#endif /* CONFIG_SLIRP */
4303

    
4304
#if !defined(_WIN32)
4305

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

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

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

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

    
4345
/* fd support */
4346

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4486
    close (if_fd);
4487

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

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

    
4500
    snprintf(dev, dev_size, "tap%d", ppa);
4501
    return tap_fd;
4502
}
4503

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

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

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

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

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

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

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

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

    
4612
#endif /* !_WIN32 */
4613

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5069

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

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

    
5078
    s->dgram_dst = saddr;
5079

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

    
5085
}
5086

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

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

    
5100
    return p;
5101
}
5102

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

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

    
5121
    return p;
5122
}
5123

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

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

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

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

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

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

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

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

    
5321
    return ret;
5322
}
5323

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

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

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

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

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

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

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

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

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

    
5382
    return nb_drives_opt++;
5383
}
5384

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

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

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

    
5397
    return -1;
5398
}
5399

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

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

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

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

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

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

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

    
5471
    /* extract parameters */
5472

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
5659
    /* check unit id */
5660

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

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

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

    
5674
    /* init */
5675

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

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

    
5731
/***********************************************************/
5732
/* USB devices */
5733

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

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

    
5748
int usb_device_add_dev(USBDevice *dev)
5749
{
5750
    USBPort *port;
5751

    
5752
    /* Find a USB port to add the device to.  */
5753
    port = free_usb_ports;
5754
    if (!port->next) {
5755
        USBDevice *hub;
5756

    
5757
        /* Create a new hub and chain it on.  */
5758
        free_usb_ports = NULL;
5759
        port->next = used_usb_ports;
5760
        used_usb_ports = port;
5761

    
5762
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5763
        usb_attach(port, hub);
5764
        port = free_usb_ports;
5765
    }
5766

    
5767
    free_usb_ports = port->next;
5768
    port->next = used_usb_ports;
5769
    used_usb_ports = port;
5770
    usb_attach(port, dev);
5771
    return 0;
5772
}
5773

    
5774
static int usb_device_add(const char *devname)
5775
{
5776
    const char *p;
5777
    USBDevice *dev;
5778
    USBPort *port;
5779

    
5780
    if (!free_usb_ports)
5781
        return -1;
5782

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

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

    
5814
    return usb_device_add_dev(dev);
5815
}
5816

    
5817
int usb_device_del_addr(int bus_num, int addr)
5818
{
5819
    USBPort *port;
5820
    USBPort **lastp;
5821
    USBDevice *dev;
5822

    
5823
    if (!used_usb_ports)
5824
        return -1;
5825

    
5826
    if (bus_num != 0)
5827
        return -1;
5828

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

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

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

    
5848
static int usb_device_del(const char *devname)
5849
{
5850
    int bus_num, addr;
5851
    const char *p;
5852

    
5853
    if (!used_usb_ports)
5854
        return -1;
5855

    
5856
    p = strchr(devname, '.');
5857
    if (!p)
5858
        return -1;
5859
    bus_num = strtoul(devname, NULL, 0);
5860
    addr = strtoul(p + 1, NULL, 0);
5861

    
5862
    return usb_device_del_addr(bus_num, addr);
5863
}
5864

    
5865
void do_usb_add(const char *devname)
5866
{
5867
    usb_device_add(devname);
5868
}
5869

    
5870
void do_usb_del(const char *devname)
5871
{
5872
    usb_device_del(devname);
5873
}
5874

    
5875
void usb_info(void)
5876
{
5877
    USBDevice *dev;
5878
    USBPort *port;
5879
    const char *speed_str;
5880

    
5881
    if (!usb_enabled) {
5882
        term_printf("USB support not enabled\n");
5883
        return;
5884
    }
5885

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

    
5909
/***********************************************************/
5910
/* PCMCIA/Cardbus */
5911

    
5912
static struct pcmcia_socket_entry_s {
5913
    struct pcmcia_socket_s *socket;
5914
    struct pcmcia_socket_entry_s *next;
5915
} *pcmcia_sockets = 0;
5916

    
5917
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5918
{
5919
    struct pcmcia_socket_entry_s *entry;
5920

    
5921
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5922
    entry->socket = socket;
5923
    entry->next = pcmcia_sockets;
5924
    pcmcia_sockets = entry;
5925
}
5926

    
5927
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5928
{
5929
    struct pcmcia_socket_entry_s *entry, **ptr;
5930

    
5931
    ptr = &pcmcia_sockets;
5932
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5933
        if (entry->socket == socket) {
5934
            *ptr = entry->next;
5935
            qemu_free(entry);
5936
        }
5937
}
5938

    
5939
void pcmcia_info(void)
5940
{
5941
    struct pcmcia_socket_entry_s *iter;
5942
    if (!pcmcia_sockets)
5943
        term_printf("No PCMCIA sockets\n");
5944

    
5945
    for (iter = pcmcia_sockets; iter; iter = iter->next)
5946
        term_printf("%s: %s\n", iter->socket->slot_string,
5947
                    iter->socket->attached ? iter->socket->card_string :
5948
                    "Empty");
5949
}
5950

    
5951
/***********************************************************/
5952
/* dumb display */
5953

    
5954
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5955
{
5956
}
5957

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

    
5962
static void dumb_refresh(DisplayState *ds)
5963
{
5964
#if defined(CONFIG_SDL)
5965
    vga_hw_update();
5966
#endif
5967
}
5968

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

    
5981
/***********************************************************/
5982
/* I/O handling */
5983

    
5984
#define MAX_IO_HANDLERS 64
5985

    
5986
typedef struct IOHandlerRecord {
5987
    int fd;
5988
    IOCanRWHandler *fd_read_poll;
5989
    IOHandler *fd_read;
5990
    IOHandler *fd_write;
5991
    int deleted;
5992
    void *opaque;
5993
    /* temporary data */
5994
    struct pollfd *ufd;
5995
    struct IOHandlerRecord *next;
5996
} IOHandlerRecord;
5997

    
5998
static IOHandlerRecord *first_io_handler;
5999

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

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

    
6043
int qemu_set_fd_handler(int fd,
6044
                        IOHandler *fd_read,
6045
                        IOHandler *fd_write,
6046
                        void *opaque)
6047
{
6048
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6049
}
6050

    
6051
/***********************************************************/
6052
/* Polling handling */
6053

    
6054
typedef struct PollingEntry {
6055
    PollingFunc *func;
6056
    void *opaque;
6057
    struct PollingEntry *next;
6058
} PollingEntry;
6059

    
6060
static PollingEntry *first_polling_entry;
6061

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

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

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

    
6098
static WaitObjects wait_objects = {0};
6099

    
6100
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6101
{
6102
    WaitObjects *w = &wait_objects;
6103

    
6104
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
6105
        return -1;
6106
    w->events[w->num] = handle;
6107
    w->func[w->num] = func;
6108
    w->opaque[w->num] = opaque;
6109
    w->num++;
6110
    return 0;
6111
}
6112

    
6113
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6114
{
6115
    int i, found;
6116
    WaitObjects *w = &wait_objects;
6117

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

    
6133
/***********************************************************/
6134
/* savevm/loadvm support */
6135

    
6136
#define IO_BUF_SIZE 32768
6137

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

    
6151
QEMUFile *qemu_fopen(const char *filename, const char *mode)
6152
{
6153
    QEMUFile *f;
6154

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

    
6177
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6178
{
6179
    QEMUFile *f;
6180

    
6181
    f = qemu_mallocz(sizeof(QEMUFile));
6182
    if (!f)
6183
        return NULL;
6184
    f->is_file = 0;
6185
    f->bs = bs;
6186
    f->is_writable = is_writable;
6187
    f->base_offset = offset;
6188
    return f;
6189
}
6190

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

    
6208
static void qemu_fill_buffer(QEMUFile *f)
6209
{
6210
    int len;
6211

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

    
6230
void qemu_fclose(QEMUFile *f)
6231
{
6232
    if (f->is_writable)
6233
        qemu_fflush(f);
6234
    if (f->is_file) {
6235
        fclose(f->outfile);
6236
    }
6237
    qemu_free(f);
6238
}
6239

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

    
6256
void qemu_put_byte(QEMUFile *f, int v)
6257
{
6258
    f->buf[f->buf_index++] = v;
6259
    if (f->buf_index >= IO_BUF_SIZE)
6260
        qemu_fflush(f);
6261
}
6262

    
6263
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6264
{
6265
    int size, l;
6266

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

    
6286
int qemu_get_byte(QEMUFile *f)
6287
{
6288
    if (f->buf_index >= f->buf_size) {
6289
        qemu_fill_buffer(f);
6290
        if (f->buf_index >= f->buf_size)
6291
            return 0;
6292
    }
6293
    return f->buf[f->buf_index++];
6294
}
6295

    
6296
int64_t qemu_ftell(QEMUFile *f)
6297
{
6298
    return f->buf_offset - f->buf_size + f->buf_index;
6299
}
6300

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

    
6322
void qemu_put_be16(QEMUFile *f, unsigned int v)
6323
{
6324
    qemu_put_byte(f, v >> 8);
6325
    qemu_put_byte(f, v);
6326
}
6327

    
6328
void qemu_put_be32(QEMUFile *f, unsigned int v)
6329
{
6330
    qemu_put_byte(f, v >> 24);
6331
    qemu_put_byte(f, v >> 16);
6332
    qemu_put_byte(f, v >> 8);
6333
    qemu_put_byte(f, v);
6334
}
6335

    
6336
void qemu_put_be64(QEMUFile *f, uint64_t v)
6337
{
6338
    qemu_put_be32(f, v >> 32);
6339
    qemu_put_be32(f, v);
6340
}
6341

    
6342
unsigned int qemu_get_be16(QEMUFile *f)
6343
{
6344
    unsigned int v;
6345
    v = qemu_get_byte(f) << 8;
6346
    v |= qemu_get_byte(f);
6347
    return v;
6348
}
6349

    
6350
unsigned int qemu_get_be32(QEMUFile *f)
6351
{
6352
    unsigned int v;
6353
    v = qemu_get_byte(f) << 24;
6354
    v |= qemu_get_byte(f) << 16;
6355
    v |= qemu_get_byte(f) << 8;
6356
    v |= qemu_get_byte(f);
6357
    return v;
6358
}
6359

    
6360
uint64_t qemu_get_be64(QEMUFile *f)
6361
{
6362
    uint64_t v;
6363
    v = (uint64_t)qemu_get_be32(f) << 32;
6364
    v |= qemu_get_be32(f);
6365
    return v;
6366
}
6367

    
6368
typedef struct SaveStateEntry {
6369
    char idstr[256];
6370
    int instance_id;
6371
    int version_id;
6372
    SaveStateHandler *save_state;
6373
    LoadStateHandler *load_state;
6374
    void *opaque;
6375
    struct SaveStateEntry *next;
6376
} SaveStateEntry;
6377

    
6378
static SaveStateEntry *first_se;
6379

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

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

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

    
6417
#define QEMU_VM_FILE_MAGIC   0x5145564d
6418
#define QEMU_VM_FILE_VERSION 0x00000002
6419

    
6420
static int qemu_savevm_state(QEMUFile *f)
6421
{
6422
    SaveStateEntry *se;
6423
    int len, ret;
6424
    int64_t cur_pos, len_pos, total_len_pos;
6425

    
6426
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6427
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6428
    total_len_pos = qemu_ftell(f);
6429
    qemu_put_be64(f, 0); /* total size */
6430

    
6431
    for(se = first_se; se != NULL; se = se->next) {
6432
        if (se->save_state == NULL)
6433
            /* this one has a loader only, for backwards compatibility */
6434
            continue;
6435

    
6436
        /* ID string */
6437
        len = strlen(se->idstr);
6438
        qemu_put_byte(f, len);
6439
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6440

    
6441
        qemu_put_be32(f, se->instance_id);
6442
        qemu_put_be32(f, se->version_id);
6443

    
6444
        /* record size: filled later */
6445
        len_pos = qemu_ftell(f);
6446
        qemu_put_be32(f, 0);
6447
        se->save_state(f, se->opaque);
6448

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

    
6461
    ret = 0;
6462
    return ret;
6463
}
6464

    
6465
static SaveStateEntry *find_se(const char *idstr, int instance_id)
6466
{
6467
    SaveStateEntry *se;
6468

    
6469
    for(se = first_se; se != NULL; se = se->next) {
6470
        if (!strcmp(se->idstr, idstr) &&
6471
            instance_id == se->instance_id)
6472
            return se;
6473
    }
6474
    return NULL;
6475
}
6476

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

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

    
6529
/* device can contain snapshots */
6530
static int bdrv_can_snapshot(BlockDriverState *bs)
6531
{
6532
    return (bs &&
6533
            !bdrv_is_removable(bs) &&
6534
            !bdrv_is_read_only(bs));
6535
}
6536

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

    
6545
static BlockDriverState *get_bs_snapshots(void)
6546
{
6547
    BlockDriverState *bs;
6548
    int i;
6549

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

    
6563
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6564
                              const char *name)
6565
{
6566
    QEMUSnapshotInfo *sn_tab, *sn;
6567
    int nb_sns, i, ret;
6568

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

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

    
6599
    bs = get_bs_snapshots();
6600
    if (!bs) {
6601
        term_printf("No block device can accept snapshots\n");
6602
        return;
6603
    }
6604

    
6605
    /* ??? Should this occur after vm_stop?  */
6606
    qemu_aio_flush();
6607

    
6608
    saved_vm_running = vm_running;
6609
    vm_stop(0);
6610

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

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

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

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

    
6659
    /* create the snapshots */
6660

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

    
6679
 the_end:
6680
    if (saved_vm_running)
6681
        vm_start();
6682
}
6683

    
6684
void do_loadvm(const char *name)
6685
{
6686
    BlockDriverState *bs, *bs1;
6687
    BlockDriverInfo bdi1, *bdi = &bdi1;
6688
    QEMUFile *f;
6689
    int i, ret;
6690
    int saved_vm_running;
6691

    
6692
    bs = get_bs_snapshots();
6693
    if (!bs) {
6694
        term_printf("No block device supports snapshots\n");
6695
        return;
6696
    }
6697

    
6698
    /* Flush all IO requests so they don't interfere with the new state.  */
6699
    qemu_aio_flush();
6700

    
6701
    saved_vm_running = vm_running;
6702
    vm_stop(0);
6703

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

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

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

    
6754
void do_delvm(const char *name)
6755
{
6756
    BlockDriverState *bs, *bs1;
6757
    int i, ret;
6758

    
6759
    bs = get_bs_snapshots();
6760
    if (!bs) {
6761
        term_printf("No block device supports snapshots\n");
6762
        return;
6763
    }
6764

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

    
6781
void do_info_snapshots(void)
6782
{
6783
    BlockDriverState *bs, *bs1;
6784
    QEMUSnapshotInfo *sn_tab, *sn;
6785
    int nb_sns, i;
6786
    char buf[256];
6787

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

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

    
6817
/***********************************************************/
6818
/* ram save/restore */
6819

    
6820
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6821
{
6822
    int v;
6823

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

    
6840
static int ram_load_v1(QEMUFile *f, void *opaque)
6841
{
6842
    int ret;
6843
    ram_addr_t i;
6844

    
6845
    if (qemu_get_be32(f) != phys_ram_size)
6846
        return -EINVAL;
6847
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6848
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6849
        if (ret)
6850
            return ret;
6851
    }
6852
    return 0;
6853
}
6854

    
6855
#define BDRV_HASH_BLOCK_SIZE 1024
6856
#define IOBUF_SIZE 4096
6857
#define RAM_CBLOCK_MAGIC 0xfabe
6858

    
6859
typedef struct RamCompressState {
6860
    z_stream zstream;
6861
    QEMUFile *f;
6862
    uint8_t buf[IOBUF_SIZE];
6863
} RamCompressState;
6864

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

    
6880
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6881
{
6882
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6883
    qemu_put_be16(s->f, len);
6884
    qemu_put_buffer(s->f, buf, len);
6885
}
6886

    
6887
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6888
{
6889
    int ret;
6890

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

    
6906
static void ram_compress_close(RamCompressState *s)
6907
{
6908
    int len, ret;
6909

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

    
6930
typedef struct RamDecompressState {
6931
    z_stream zstream;
6932
    QEMUFile *f;
6933
    uint8_t buf[IOBUF_SIZE];
6934
} RamDecompressState;
6935

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

    
6947
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6948
{
6949
    int ret, clen;
6950

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

    
6972
static void ram_decompress_close(RamDecompressState *s)
6973
{
6974
    inflateEnd(&s->zstream);
6975
}
6976

    
6977
static void ram_save(QEMUFile *f, void *opaque)
6978
{
6979
    ram_addr_t i;
6980
    RamCompressState s1, *s = &s1;
6981
    uint8_t buf[10];
6982

    
6983
    qemu_put_be32(f, phys_ram_size);
6984
    if (ram_compress_open(s, f) < 0)
6985
        return;
6986
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6987
#if 0
6988
        if (tight_savevm_enabled) {
6989
            int64_t sector_num;
6990
            int j;
6991

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

    
7020
static int ram_load(QEMUFile *f, void *opaque, int version_id)
7021
{
7022
    RamDecompressState s1, *s = &s1;
7023
    uint8_t buf[10];
7024
    ram_addr_t i;
7025

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

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

    
7076
/***********************************************************/
7077
/* bottom halves (can be seen as timers which expire ASAP) */
7078

    
7079
struct QEMUBH {
7080
    QEMUBHFunc *cb;
7081
    void *opaque;
7082
    int scheduled;
7083
    QEMUBH *next;
7084
};
7085

    
7086
static QEMUBH *first_bh = NULL;
7087

    
7088
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7089
{
7090
    QEMUBH *bh;
7091
    bh = qemu_mallocz(sizeof(QEMUBH));
7092
    if (!bh)
7093
        return NULL;
7094
    bh->cb = cb;
7095
    bh->opaque = opaque;
7096
    return bh;
7097
}
7098

    
7099
int qemu_bh_poll(void)
7100
{
7101
    QEMUBH *bh, **pbh;
7102
    int ret;
7103

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

    
7118
void qemu_bh_schedule(QEMUBH *bh)
7119
{
7120
    CPUState *env = cpu_single_env;
7121
    if (bh->scheduled)
7122
        return;
7123
    bh->scheduled = 1;
7124
    bh->next = first_bh;
7125
    first_bh = bh;
7126

    
7127
    /* stop the currently executing CPU to execute the BH ASAP */
7128
    if (env) {
7129
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7130
    }
7131
}
7132

    
7133
void qemu_bh_cancel(QEMUBH *bh)
7134
{
7135
    QEMUBH **pbh;
7136
    if (bh->scheduled) {
7137
        pbh = &first_bh;
7138
        while (*pbh != bh)
7139
            pbh = &(*pbh)->next;
7140
        *pbh = bh->next;
7141
        bh->scheduled = 0;
7142
    }
7143
}
7144

    
7145
void qemu_bh_delete(QEMUBH *bh)
7146
{
7147
    qemu_bh_cancel(bh);
7148
    qemu_free(bh);
7149
}
7150

    
7151
/***********************************************************/
7152
/* machine registration */
7153

    
7154
QEMUMachine *first_machine = NULL;
7155

    
7156
int qemu_register_machine(QEMUMachine *m)
7157
{
7158
    QEMUMachine **pm;
7159
    pm = &first_machine;
7160
    while (*pm != NULL)
7161
        pm = &(*pm)->next;
7162
    m->next = NULL;
7163
    *pm = m;
7164
    return 0;
7165
}
7166

    
7167
static QEMUMachine *find_machine(const char *name)
7168
{
7169
    QEMUMachine *m;
7170

    
7171
    for(m = first_machine; m != NULL; m = m->next) {
7172
        if (!strcmp(m->name, name))
7173
            return m;
7174
    }
7175
    return NULL;
7176
}
7177

    
7178
/***********************************************************/
7179
/* main execution loop */
7180

    
7181
static void gui_update(void *opaque)
7182
{
7183
    DisplayState *ds = opaque;
7184
    ds->dpy_refresh(ds);
7185
    qemu_mod_timer(ds->gui_timer,
7186
        (ds->gui_timer_interval ?
7187
            ds->gui_timer_interval :
7188
            GUI_REFRESH_INTERVAL)
7189
        + qemu_get_clock(rt_clock));
7190
}
7191

    
7192
struct vm_change_state_entry {
7193
    VMChangeStateHandler *cb;
7194
    void *opaque;
7195
    LIST_ENTRY (vm_change_state_entry) entries;
7196
};
7197

    
7198
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7199

    
7200
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7201
                                                     void *opaque)
7202
{
7203
    VMChangeStateEntry *e;
7204

    
7205
    e = qemu_mallocz(sizeof (*e));
7206
    if (!e)
7207
        return NULL;
7208

    
7209
    e->cb = cb;
7210
    e->opaque = opaque;
7211
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7212
    return e;
7213
}
7214

    
7215
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7216
{
7217
    LIST_REMOVE (e, entries);
7218
    qemu_free (e);
7219
}
7220

    
7221
static void vm_state_notify(int running)
7222
{
7223
    VMChangeStateEntry *e;
7224

    
7225
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7226
        e->cb(e->opaque, running);
7227
    }
7228
}
7229

    
7230
/* XXX: support several handlers */
7231
static VMStopHandler *vm_stop_cb;
7232
static void *vm_stop_opaque;
7233

    
7234
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7235
{
7236
    vm_stop_cb = cb;
7237
    vm_stop_opaque = opaque;
7238
    return 0;
7239
}
7240

    
7241
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7242
{
7243
    vm_stop_cb = NULL;
7244
}
7245

    
7246
void vm_start(void)
7247
{
7248
    if (!vm_running) {
7249
        cpu_enable_ticks();
7250
        vm_running = 1;
7251
        vm_state_notify(1);
7252
        qemu_rearm_alarm_timer(alarm_timer);
7253
    }
7254
}
7255

    
7256
void vm_stop(int reason)
7257
{
7258
    if (vm_running) {
7259
        cpu_disable_ticks();
7260
        vm_running = 0;
7261
        if (reason != 0) {
7262
            if (vm_stop_cb) {
7263
                vm_stop_cb(vm_stop_opaque, reason);
7264
            }
7265
        }
7266
        vm_state_notify(0);
7267
    }
7268
}
7269

    
7270
/* reset/shutdown handler */
7271

    
7272
typedef struct QEMUResetEntry {
7273
    QEMUResetHandler *func;
7274
    void *opaque;
7275
    struct QEMUResetEntry *next;
7276
} QEMUResetEntry;
7277

    
7278
static QEMUResetEntry *first_reset_entry;
7279
static int reset_requested;
7280
static int shutdown_requested;
7281
static int powerdown_requested;
7282

    
7283
int qemu_shutdown_requested(void)
7284
{
7285
    int r = shutdown_requested;
7286
    shutdown_requested = 0;
7287
    return r;
7288
}
7289

    
7290
int qemu_reset_requested(void)
7291
{
7292
    int r = reset_requested;
7293
    reset_requested = 0;
7294
    return r;
7295
}
7296

    
7297
int qemu_powerdown_requested(void)
7298
{
7299
    int r = powerdown_requested;
7300
    powerdown_requested = 0;
7301
    return r;
7302
}
7303

    
7304
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7305
{
7306
    QEMUResetEntry **pre, *re;
7307

    
7308
    pre = &first_reset_entry;
7309
    while (*pre != NULL)
7310
        pre = &(*pre)->next;
7311
    re = qemu_mallocz(sizeof(QEMUResetEntry));
7312
    re->func = func;
7313
    re->opaque = opaque;
7314
    re->next = NULL;
7315
    *pre = re;
7316
}
7317

    
7318
void qemu_system_reset(void)
7319
{
7320
    QEMUResetEntry *re;
7321

    
7322
    /* reset all devices */
7323
    for(re = first_reset_entry; re != NULL; re = re->next) {
7324
        re->func(re->opaque);
7325
    }
7326
}
7327

    
7328
void qemu_system_reset_request(void)
7329
{
7330
    if (no_reboot) {
7331
        shutdown_requested = 1;
7332
    } else {
7333
        reset_requested = 1;
7334
    }
7335
    if (cpu_single_env)
7336
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7337
}
7338

    
7339
void qemu_system_shutdown_request(void)
7340
{
7341
    shutdown_requested = 1;
7342
    if (cpu_single_env)
7343
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7344
}
7345

    
7346
void qemu_system_powerdown_request(void)
7347
{
7348
    powerdown_requested = 1;
7349
    if (cpu_single_env)
7350
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7351
}
7352

    
7353
void main_loop_wait(int timeout)
7354
{
7355
    IOHandlerRecord *ioh;
7356
    fd_set rfds, wfds, xfds;
7357
    int ret, nfds;
7358
#ifdef _WIN32
7359
    int ret2, i;
7360
#endif
7361
    struct timeval tv;
7362
    PollingEntry *pe;
7363

    
7364

    
7365
    /* XXX: need to suppress polling by better using win32 events */
7366
    ret = 0;
7367
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7368
        ret |= pe->func(pe->opaque);
7369
    }
7370
#ifdef _WIN32
7371
    if (ret == 0) {
7372
        int err;
7373
        WaitObjects *w = &wait_objects;
7374

    
7375
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7376
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7377
            if (w->func[ret - WAIT_OBJECT_0])
7378
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7379

    
7380
            /* Check for additional signaled events */
7381
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7382

    
7383
                /* Check if event is signaled */
7384
                ret2 = WaitForSingleObject(w->events[i], 0);
7385
                if(ret2 == WAIT_OBJECT_0) {
7386
                    if (w->func[i])
7387
                        w->func[i](w->opaque[i]);
7388
                } else if (ret2 == WAIT_TIMEOUT) {
7389
                } else {
7390
                    err = GetLastError();
7391
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7392
                }
7393
            }
7394
        } else if (ret == WAIT_TIMEOUT) {
7395
        } else {
7396
            err = GetLastError();
7397
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7398
        }
7399
    }
7400
#endif
7401
    /* poll any events */
7402
    /* XXX: separate device handlers from system ones */
7403
    nfds = -1;
7404
    FD_ZERO(&rfds);
7405
    FD_ZERO(&wfds);
7406
    FD_ZERO(&xfds);
7407
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7408
        if (ioh->deleted)
7409
            continue;
7410
        if (ioh->fd_read &&
7411
            (!ioh->fd_read_poll ||
7412
             ioh->fd_read_poll(ioh->opaque) != 0)) {
7413
            FD_SET(ioh->fd, &rfds);
7414
            if (ioh->fd > nfds)
7415
                nfds = ioh->fd;
7416
        }
7417
        if (ioh->fd_write) {
7418
            FD_SET(ioh->fd, &wfds);
7419
            if (ioh->fd > nfds)
7420
                nfds = ioh->fd;
7421
        }
7422
    }
7423

    
7424
    tv.tv_sec = 0;
7425
#ifdef _WIN32
7426
    tv.tv_usec = 0;
7427
#else
7428
    tv.tv_usec = timeout * 1000;
7429
#endif
7430
#if defined(CONFIG_SLIRP)
7431
    if (slirp_inited) {
7432
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7433
    }
7434
#endif
7435
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7436
    if (ret > 0) {
7437
        IOHandlerRecord **pioh;
7438

    
7439
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7440
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7441
                ioh->fd_read(ioh->opaque);
7442
            }
7443
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7444
                ioh->fd_write(ioh->opaque);
7445
            }
7446
        }
7447

    
7448
        /* remove deleted IO handlers */
7449
        pioh = &first_io_handler;
7450
        while (*pioh) {
7451
            ioh = *pioh;
7452
            if (ioh->deleted) {
7453
                *pioh = ioh->next;
7454
                qemu_free(ioh);
7455
            } else
7456
                pioh = &ioh->next;
7457
        }
7458
    }
7459
#if defined(CONFIG_SLIRP)
7460
    if (slirp_inited) {
7461
        if (ret < 0) {
7462
            FD_ZERO(&rfds);
7463
            FD_ZERO(&wfds);
7464
            FD_ZERO(&xfds);
7465
        }
7466
        slirp_select_poll(&rfds, &wfds, &xfds);
7467
    }
7468
#endif
7469
    qemu_aio_poll();
7470

    
7471
    if (vm_running) {
7472
        if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7473
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7474
                        qemu_get_clock(vm_clock));
7475
        /* run dma transfers, if any */
7476
        DMA_run();
7477
    }
7478

    
7479
    /* real time timers */
7480
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7481
                    qemu_get_clock(rt_clock));
7482

    
7483
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7484
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7485
        qemu_rearm_alarm_timer(alarm_timer);
7486
    }
7487

    
7488
    /* Check bottom-halves last in case any of the earlier events triggered
7489
       them.  */
7490
    qemu_bh_poll();
7491

    
7492
}
7493

    
7494
static int main_loop(void)
7495
{
7496
    int ret, timeout;
7497
#ifdef CONFIG_PROFILER
7498
    int64_t ti;
7499
#endif
7500
    CPUState *env;
7501

    
7502
    cur_cpu = first_cpu;
7503
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7504
    for(;;) {
7505
        if (vm_running) {
7506

    
7507
            for(;;) {
7508
                /* get next cpu */
7509
                env = next_cpu;
7510
#ifdef CONFIG_PROFILER
7511
                ti = profile_getclock();
7512
#endif
7513
                if (use_icount) {
7514
                    int64_t count;
7515
                    int decr;
7516
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7517
                    env->icount_decr.u16.low = 0;
7518
                    env->icount_extra = 0;
7519
                    count = qemu_next_deadline();
7520
                    count = (count + (1 << icount_time_shift) - 1)
7521
                            >> icount_time_shift;
7522
                    qemu_icount += count;
7523
                    decr = (count > 0xffff) ? 0xffff : count;
7524
                    count -= decr;
7525
                    env->icount_decr.u16.low = decr;
7526
                    env->icount_extra = count;
7527
                }
7528
                ret = cpu_exec(env);
7529
#ifdef CONFIG_PROFILER
7530
                qemu_time += profile_getclock() - ti;
7531
#endif
7532
                if (use_icount) {
7533
                    /* Fold pending instructions back into the
7534
                       instruction counter, and clear the interrupt flag.  */
7535
                    qemu_icount -= (env->icount_decr.u16.low
7536
                                    + env->icount_extra);
7537
                    env->icount_decr.u32 = 0;
7538
                    env->icount_extra = 0;
7539
                }
7540
                next_cpu = env->next_cpu ?: first_cpu;
7541
                if (event_pending && likely(ret != EXCP_DEBUG)) {
7542
                    ret = EXCP_INTERRUPT;
7543
                    event_pending = 0;
7544
                    break;
7545
                }
7546
                if (ret == EXCP_HLT) {
7547
                    /* Give the next CPU a chance to run.  */
7548
                    cur_cpu = env;
7549
                    continue;
7550
                }
7551
                if (ret != EXCP_HALTED)
7552
                    break;
7553
                /* all CPUs are halted ? */
7554
                if (env == cur_cpu)
7555
                    break;
7556
            }
7557
            cur_cpu = env;
7558

    
7559
            if (shutdown_requested) {
7560
                ret = EXCP_INTERRUPT;
7561
                if (no_shutdown) {
7562
                    vm_stop(0);
7563
                    no_shutdown = 0;
7564
                }
7565
                else
7566
                    break;
7567
            }
7568
            if (reset_requested) {
7569
                reset_requested = 0;
7570
                qemu_system_reset();
7571
                ret = EXCP_INTERRUPT;
7572
            }
7573
            if (powerdown_requested) {
7574
                powerdown_requested = 0;
7575
                qemu_system_powerdown();
7576
                ret = EXCP_INTERRUPT;
7577
            }
7578
            if (unlikely(ret == EXCP_DEBUG)) {
7579
                vm_stop(EXCP_DEBUG);
7580
            }
7581
            /* If all cpus are halted then wait until the next IRQ */
7582
            /* XXX: use timeout computed from timers */
7583
            if (ret == EXCP_HALTED) {
7584
                if (use_icount) {
7585
                    int64_t add;
7586
                    int64_t delta;
7587
                    /* Advance virtual time to the next event.  */
7588
                    if (use_icount == 1) {
7589
                        /* When not using an adaptive execution frequency
7590
                           we tend to get badly out of sync with real time,
7591
                           so just delay for a reasonable amount of time.  */
7592
                        delta = 0;
7593
                    } else {
7594
                        delta = cpu_get_icount() - cpu_get_clock();
7595
                    }
7596
                    if (delta > 0) {
7597
                        /* If virtual time is ahead of real time then just
7598
                           wait for IO.  */
7599
                        timeout = (delta / 1000000) + 1;
7600
                    } else {
7601
                        /* Wait for either IO to occur or the next
7602
                           timer event.  */
7603
                        add = qemu_next_deadline();
7604
                        /* We advance the timer before checking for IO.
7605
                           Limit the amount we advance so that early IO
7606
                           activity won't get the guest too far ahead.  */
7607
                        if (add > 10000000)
7608
                            add = 10000000;
7609
                        delta += add;
7610
                        add = (add + (1 << icount_time_shift) - 1)
7611
                              >> icount_time_shift;
7612
                        qemu_icount += add;
7613
                        timeout = delta / 1000000;
7614
                        if (timeout < 0)
7615
                            timeout = 0;
7616
                    }
7617
                } else {
7618
                    timeout = 10;
7619
                }
7620
            } else {
7621
                timeout = 0;
7622
            }
7623
        } else {
7624
            if (shutdown_requested)
7625
                break;
7626
            timeout = 10;
7627
        }
7628
#ifdef CONFIG_PROFILER
7629
        ti = profile_getclock();
7630
#endif
7631
        main_loop_wait(timeout);
7632
#ifdef CONFIG_PROFILER
7633
        dev_time += profile_getclock() - ti;
7634
#endif
7635
    }
7636
    cpu_disable_ticks();
7637
    return ret;
7638
}
7639

    
7640
static void help(int exitcode)
7641
{
7642
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7643
           "usage: %s [options] [disk_image]\n"
7644
           "\n"
7645
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7646
           "\n"
7647
           "Standard options:\n"
7648
           "-M machine      select emulated machine (-M ? for list)\n"
7649
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7650
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7651
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7652
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7653
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7654
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7655
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7656
           "       [,cache=on|off][,format=f]\n"
7657
           "                use 'file' as a drive image\n"
7658
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7659
           "-sd file        use 'file' as SecureDigital card image\n"
7660
           "-pflash file    use 'file' as a parallel flash image\n"
7661
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7662
           "-snapshot       write to temporary files instead of disk image files\n"
7663
#ifdef CONFIG_SDL
7664
           "-no-frame       open SDL window without a frame and window decorations\n"
7665
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7666
           "-no-quit        disable SDL window close capability\n"
7667
#endif
7668
#ifdef TARGET_I386
7669
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7670
#endif
7671
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7672
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7673
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7674
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7675
#ifndef _WIN32
7676
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7677
#endif
7678
#ifdef HAS_AUDIO
7679
           "-audio-help     print list of audio drivers and their options\n"
7680
           "-soundhw c1,... enable audio support\n"
7681
           "                and only specified sound cards (comma separated list)\n"
7682
           "                use -soundhw ? to get the list of supported cards\n"
7683
           "                use -soundhw all to enable all of them\n"
7684
#endif
7685
           "-localtime      set the real time clock to local time [default=utc]\n"
7686
           "-full-screen    start in full screen\n"
7687
#ifdef TARGET_I386
7688
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7689
#endif
7690
           "-usb            enable the USB driver (will be the default soon)\n"
7691
           "-usbdevice name add the host or guest USB device 'name'\n"
7692
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7693
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7694
#endif
7695
           "-name string    set the name of the guest\n"
7696
           "\n"
7697
           "Network options:\n"
7698
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7699
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7700
#ifdef CONFIG_SLIRP
7701
           "-net user[,vlan=n][,hostname=host]\n"
7702
           "                connect the user mode network stack to VLAN 'n' and send\n"
7703
           "                hostname 'host' to DHCP clients\n"
7704
#endif
7705
#ifdef _WIN32
7706
           "-net tap[,vlan=n],ifname=name\n"
7707
           "                connect the host TAP network interface to VLAN 'n'\n"
7708
#else
7709
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7710
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7711
           "                network scripts 'file' (default=%s)\n"
7712
           "                and 'dfile' (default=%s);\n"
7713
           "                use '[down]script=no' to disable script execution;\n"
7714
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7715
#endif
7716
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7717
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7718
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7719
           "                connect the vlan 'n' to multicast maddr and port\n"
7720
#ifdef CONFIG_VDE
7721
           "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7722
           "                connect the vlan 'n' to port 'n' of a vde switch running\n"
7723
           "                on host and listening for incoming connections on 'socketpath'.\n"
7724
           "                Use group 'groupname' and mode 'octalmode' to change default\n"
7725
           "                ownership and permissions for communication port.\n"
7726
#endif
7727
           "-net none       use it alone to have zero network devices; if no -net option\n"
7728
           "                is provided, the default is '-net nic -net user'\n"
7729
           "\n"
7730
#ifdef CONFIG_SLIRP
7731
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7732
           "-bootp file     advertise file in BOOTP replies\n"
7733
#ifndef _WIN32
7734
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7735
#endif
7736
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7737
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7738
#endif
7739
           "\n"
7740
           "Linux boot specific:\n"
7741
           "-kernel bzImage use 'bzImage' as kernel image\n"
7742
           "-append cmdline use 'cmdline' as kernel command line\n"
7743
           "-initrd file    use 'file' as initial ram disk\n"
7744
           "\n"
7745
           "Debug/Expert options:\n"
7746
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7747
           "-serial dev     redirect the serial port to char device 'dev'\n"
7748
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7749
           "-pidfile file   Write PID to 'file'\n"
7750
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7751
           "-s              wait gdb connection to port\n"
7752
           "-p port         set gdb connection port [default=%s]\n"
7753
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7754
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7755
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7756
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7757
#ifdef USE_KQEMU
7758
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7759
           "-no-kqemu       disable KQEMU kernel module usage\n"
7760
#endif
7761
#ifdef TARGET_I386
7762
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7763
           "                (default is CL-GD5446 PCI VGA)\n"
7764
           "-no-acpi        disable ACPI\n"
7765
#endif
7766
#ifdef CONFIG_CURSES
7767
           "-curses         use a curses/ncurses interface instead of SDL\n"
7768
#endif
7769
           "-no-reboot      exit instead of rebooting\n"
7770
           "-no-shutdown    stop before shutdown\n"
7771
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
7772
           "-vnc display    start a VNC server on display\n"
7773
#ifndef _WIN32
7774
           "-daemonize      daemonize QEMU after initializing\n"
7775
#endif
7776
           "-option-rom rom load a file, rom, into the option ROM space\n"
7777
#ifdef TARGET_SPARC
7778
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7779
#endif
7780
           "-clock          force the use of the given methods for timer alarm.\n"
7781
           "                To see what timers are available use -clock ?\n"
7782
           "-startdate      select initial date of the clock\n"
7783
           "-icount [N|auto]\n"
7784
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7785
           "\n"
7786
           "During emulation, the following keys are useful:\n"
7787
           "ctrl-alt-f      toggle full screen\n"
7788
           "ctrl-alt-n      switch to virtual console 'n'\n"
7789
           "ctrl-alt        toggle mouse and keyboard grab\n"
7790
           "\n"
7791
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7792
           ,
7793
           "qemu",
7794
           DEFAULT_RAM_SIZE,
7795
#ifndef _WIN32
7796
           DEFAULT_NETWORK_SCRIPT,
7797
           DEFAULT_NETWORK_DOWN_SCRIPT,
7798
#endif
7799
           DEFAULT_GDBSTUB_PORT,
7800
           "/tmp/qemu.log");
7801
    exit(exitcode);
7802
}
7803

    
7804
#define HAS_ARG 0x0001
7805

    
7806
enum {
7807
    QEMU_OPTION_h,
7808

    
7809
    QEMU_OPTION_M,
7810
    QEMU_OPTION_cpu,
7811
    QEMU_OPTION_fda,
7812
    QEMU_OPTION_fdb,
7813
    QEMU_OPTION_hda,
7814
    QEMU_OPTION_hdb,
7815
    QEMU_OPTION_hdc,
7816
    QEMU_OPTION_hdd,
7817
    QEMU_OPTION_drive,
7818
    QEMU_OPTION_cdrom,
7819
    QEMU_OPTION_mtdblock,
7820
    QEMU_OPTION_sd,
7821
    QEMU_OPTION_pflash,
7822
    QEMU_OPTION_boot,
7823
    QEMU_OPTION_snapshot,
7824
#ifdef TARGET_I386
7825
    QEMU_OPTION_no_fd_bootchk,
7826
#endif
7827
    QEMU_OPTION_m,
7828
    QEMU_OPTION_nographic,
7829
    QEMU_OPTION_portrait,
7830
#ifdef HAS_AUDIO
7831
    QEMU_OPTION_audio_help,
7832
    QEMU_OPTION_soundhw,
7833
#endif
7834

    
7835
    QEMU_OPTION_net,
7836
    QEMU_OPTION_tftp,
7837
    QEMU_OPTION_bootp,
7838
    QEMU_OPTION_smb,
7839
    QEMU_OPTION_redir,
7840

    
7841
    QEMU_OPTION_kernel,
7842
    QEMU_OPTION_append,
7843
    QEMU_OPTION_initrd,
7844

    
7845
    QEMU_OPTION_S,
7846
    QEMU_OPTION_s,
7847
    QEMU_OPTION_p,
7848
    QEMU_OPTION_d,
7849
    QEMU_OPTION_hdachs,
7850
    QEMU_OPTION_L,
7851
    QEMU_OPTION_bios,
7852
    QEMU_OPTION_k,
7853
    QEMU_OPTION_localtime,
7854
    QEMU_OPTION_cirrusvga,
7855
    QEMU_OPTION_vmsvga,
7856
    QEMU_OPTION_g,
7857
    QEMU_OPTION_std_vga,
7858
    QEMU_OPTION_echr,
7859
    QEMU_OPTION_monitor,
7860
    QEMU_OPTION_serial,
7861
    QEMU_OPTION_parallel,
7862
    QEMU_OPTION_loadvm,
7863
    QEMU_OPTION_full_screen,
7864
    QEMU_OPTION_no_frame,
7865
    QEMU_OPTION_alt_grab,
7866
    QEMU_OPTION_no_quit,
7867
    QEMU_OPTION_pidfile,
7868
    QEMU_OPTION_no_kqemu,
7869
    QEMU_OPTION_kernel_kqemu,
7870
    QEMU_OPTION_win2k_hack,
7871
    QEMU_OPTION_usb,
7872
    QEMU_OPTION_usbdevice,
7873
    QEMU_OPTION_smp,
7874
    QEMU_OPTION_vnc,
7875
    QEMU_OPTION_no_acpi,
7876
    QEMU_OPTION_curses,
7877
    QEMU_OPTION_no_reboot,
7878
    QEMU_OPTION_no_shutdown,
7879
    QEMU_OPTION_show_cursor,
7880
    QEMU_OPTION_daemonize,
7881
    QEMU_OPTION_option_rom,
7882
    QEMU_OPTION_semihosting,
7883
    QEMU_OPTION_name,
7884
    QEMU_OPTION_prom_env,
7885
    QEMU_OPTION_old_param,
7886
    QEMU_OPTION_clock,
7887
    QEMU_OPTION_startdate,
7888
    QEMU_OPTION_tb_size,
7889
    QEMU_OPTION_icount,
7890
};
7891

    
7892
typedef struct QEMUOption {
7893
    const char *name;
7894
    int flags;
7895
    int index;
7896
} QEMUOption;
7897

    
7898
const QEMUOption qemu_options[] = {
7899
    { "h", 0, QEMU_OPTION_h },
7900
    { "help", 0, QEMU_OPTION_h },
7901

    
7902
    { "M", HAS_ARG, QEMU_OPTION_M },
7903
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7904
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7905
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7906
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7907
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7908
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7909
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7910
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7911
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7912
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7913
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7914
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7915
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7916
    { "snapshot", 0, QEMU_OPTION_snapshot },
7917
#ifdef TARGET_I386
7918
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7919
#endif
7920
    { "m", HAS_ARG, QEMU_OPTION_m },
7921
    { "nographic", 0, QEMU_OPTION_nographic },
7922
    { "portrait", 0, QEMU_OPTION_portrait },
7923
    { "k", HAS_ARG, QEMU_OPTION_k },
7924
#ifdef HAS_AUDIO
7925
    { "audio-help", 0, QEMU_OPTION_audio_help },
7926
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7927
#endif
7928

    
7929
    { "net", HAS_ARG, QEMU_OPTION_net},
7930
#ifdef CONFIG_SLIRP
7931
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7932
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7933
#ifndef _WIN32
7934
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7935
#endif
7936
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7937
#endif
7938

    
7939
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7940
    { "append", HAS_ARG, QEMU_OPTION_append },
7941
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7942

    
7943
    { "S", 0, QEMU_OPTION_S },
7944
    { "s", 0, QEMU_OPTION_s },
7945
    { "p", HAS_ARG, QEMU_OPTION_p },
7946
    { "d", HAS_ARG, QEMU_OPTION_d },
7947
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7948
    { "L", HAS_ARG, QEMU_OPTION_L },
7949
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7950
#ifdef USE_KQEMU
7951
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7952
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7953
#endif
7954
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7955
    { "g", 1, QEMU_OPTION_g },
7956
#endif
7957
    { "localtime", 0, QEMU_OPTION_localtime },
7958
    { "std-vga", 0, QEMU_OPTION_std_vga },
7959
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7960
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7961
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7962
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7963
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7964
    { "full-screen", 0, QEMU_OPTION_full_screen },
7965
#ifdef CONFIG_SDL
7966
    { "no-frame", 0, QEMU_OPTION_no_frame },
7967
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7968
    { "no-quit", 0, QEMU_OPTION_no_quit },
7969
#endif
7970
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7971
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7972
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7973
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7974
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7975
#ifdef CONFIG_CURSES
7976
    { "curses", 0, QEMU_OPTION_curses },
7977
#endif
7978

    
7979
    /* temporary options */
7980
    { "usb", 0, QEMU_OPTION_usb },
7981
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7982
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7983
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7984
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7985
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7986
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7987
    { "daemonize", 0, QEMU_OPTION_daemonize },
7988
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7989
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7990
    { "semihosting", 0, QEMU_OPTION_semihosting },
7991
#endif
7992
    { "name", HAS_ARG, QEMU_OPTION_name },
7993
#if defined(TARGET_SPARC)
7994
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7995
#endif
7996
#if defined(TARGET_ARM)
7997
    { "old-param", 0, QEMU_OPTION_old_param },
7998
#endif
7999
    { "clock", HAS_ARG, QEMU_OPTION_clock },
8000
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8001
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8002
    { "icount", HAS_ARG, QEMU_OPTION_icount },
8003
    { NULL },
8004
};
8005

    
8006
/* password input */
8007

    
8008
int qemu_key_check(BlockDriverState *bs, const char *name)
8009
{
8010
    char password[256];
8011
    int i;
8012

    
8013
    if (!bdrv_is_encrypted(bs))
8014
        return 0;
8015

    
8016
    term_printf("%s is encrypted.\n", name);
8017
    for(i = 0; i < 3; i++) {
8018
        monitor_readline("Password: ", 1, password, sizeof(password));
8019
        if (bdrv_set_key(bs, password) == 0)
8020
            return 0;
8021
        term_printf("invalid password\n");
8022
    }
8023
    return -EPERM;
8024
}
8025

    
8026
static BlockDriverState *get_bdrv(int index)
8027
{
8028
    if (index > nb_drives)
8029
        return NULL;
8030
    return drives_table[index].bdrv;
8031
}
8032

    
8033
static void read_passwords(void)
8034
{
8035
    BlockDriverState *bs;
8036
    int i;
8037

    
8038
    for(i = 0; i < 6; i++) {
8039
        bs = get_bdrv(i);
8040
        if (bs)
8041
            qemu_key_check(bs, bdrv_get_device_name(bs));
8042
    }
8043
}
8044

    
8045
#ifdef HAS_AUDIO
8046
struct soundhw soundhw[] = {
8047
#ifdef HAS_AUDIO_CHOICE
8048
#if defined(TARGET_I386) || defined(TARGET_MIPS)
8049
    {
8050
        "pcspk",
8051
        "PC speaker",
8052
        0,
8053
        1,
8054
        { .init_isa = pcspk_audio_init }
8055
    },
8056
#endif
8057
    {
8058
        "sb16",
8059
        "Creative Sound Blaster 16",
8060
        0,
8061
        1,
8062
        { .init_isa = SB16_init }
8063
    },
8064

    
8065
#ifdef CONFIG_CS4231A
8066
    {
8067
        "cs4231a",
8068
        "CS4231A",
8069
        0,
8070
        1,
8071
        { .init_isa = cs4231a_init }
8072
    },
8073
#endif
8074

    
8075
#ifdef CONFIG_ADLIB
8076
    {
8077
        "adlib",
8078
#ifdef HAS_YMF262
8079
        "Yamaha YMF262 (OPL3)",
8080
#else
8081
        "Yamaha YM3812 (OPL2)",
8082
#endif
8083
        0,
8084
        1,
8085
        { .init_isa = Adlib_init }
8086
    },
8087
#endif
8088

    
8089
#ifdef CONFIG_GUS
8090
    {
8091
        "gus",
8092
        "Gravis Ultrasound GF1",
8093
        0,
8094
        1,
8095
        { .init_isa = GUS_init }
8096
    },
8097
#endif
8098

    
8099
#ifdef CONFIG_AC97
8100
    {
8101
        "ac97",
8102
        "Intel 82801AA AC97 Audio",
8103
        0,
8104
        0,
8105
        { .init_pci = ac97_init }
8106
    },
8107
#endif
8108

    
8109
    {
8110
        "es1370",
8111
        "ENSONIQ AudioPCI ES1370",
8112
        0,
8113
        0,
8114
        { .init_pci = es1370_init }
8115
    },
8116
#endif
8117

    
8118
    { NULL, NULL, 0, 0, { NULL } }
8119
};
8120

    
8121
static void select_soundhw (const char *optarg)
8122
{
8123
    struct soundhw *c;
8124

    
8125
    if (*optarg == '?') {
8126
    show_valid_cards:
8127

    
8128
        printf ("Valid sound card names (comma separated):\n");
8129
        for (c = soundhw; c->name; ++c) {
8130
            printf ("%-11s %s\n", c->name, c->descr);
8131
        }
8132
        printf ("\n-soundhw all will enable all of the above\n");
8133
        exit (*optarg != '?');
8134
    }
8135
    else {
8136
        size_t l;
8137
        const char *p;
8138
        char *e;
8139
        int bad_card = 0;
8140

    
8141
        if (!strcmp (optarg, "all")) {
8142
            for (c = soundhw; c->name; ++c) {
8143
                c->enabled = 1;
8144
            }
8145
            return;
8146
        }
8147

    
8148
        p = optarg;
8149
        while (*p) {
8150
            e = strchr (p, ',');
8151
            l = !e ? strlen (p) : (size_t) (e - p);
8152

    
8153
            for (c = soundhw; c->name; ++c) {
8154
                if (!strncmp (c->name, p, l)) {
8155
                    c->enabled = 1;
8156
                    break;
8157
                }
8158
            }
8159

    
8160
            if (!c->name) {
8161
                if (l > 80) {
8162
                    fprintf (stderr,
8163
                             "Unknown sound card name (too big to show)\n");
8164
                }
8165
                else {
8166
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
8167
                             (int) l, p);
8168
                }
8169
                bad_card = 1;
8170
            }
8171
            p += l + (e != NULL);
8172
        }
8173

    
8174
        if (bad_card)
8175
            goto show_valid_cards;
8176
    }
8177
}
8178
#endif
8179

    
8180
#ifdef _WIN32
8181
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8182
{
8183
    exit(STATUS_CONTROL_C_EXIT);
8184
    return TRUE;
8185
}
8186
#endif
8187

    
8188
#define MAX_NET_CLIENTS 32
8189

    
8190
#ifndef _WIN32
8191

    
8192
static void termsig_handler(int signal)
8193
{
8194
    qemu_system_shutdown_request();
8195
}
8196

    
8197
void termsig_setup(void)
8198
{
8199
    struct sigaction act;
8200

    
8201
    memset(&act, 0, sizeof(act));
8202
    act.sa_handler = termsig_handler;
8203
    sigaction(SIGINT,  &act, NULL);
8204
    sigaction(SIGHUP,  &act, NULL);
8205
    sigaction(SIGTERM, &act, NULL);
8206
}
8207

    
8208
#endif
8209

    
8210
int main(int argc, char **argv)
8211
{
8212
#ifdef CONFIG_GDBSTUB
8213
    int use_gdbstub;
8214
    const char *gdbstub_port;
8215
#endif
8216
    uint32_t boot_devices_bitmap = 0;
8217
    int i;
8218
    int snapshot, linux_boot, net_boot;
8219
    const char *initrd_filename;
8220
    const char *kernel_filename, *kernel_cmdline;
8221
    const char *boot_devices = "";
8222
    DisplayState *ds = &display_state;
8223
    int cyls, heads, secs, translation;
8224
    const char *net_clients[MAX_NET_CLIENTS];
8225
    int nb_net_clients;
8226
    int hda_index;
8227
    int optind;
8228
    const char *r, *optarg;
8229
    CharDriverState *monitor_hd;
8230
    const char *monitor_device;
8231
    const char *serial_devices[MAX_SERIAL_PORTS];
8232
    int serial_device_index;
8233
    const char *parallel_devices[MAX_PARALLEL_PORTS];
8234
    int parallel_device_index;
8235
    const char *loadvm = NULL;
8236
    QEMUMachine *machine;
8237
    const char *cpu_model;
8238
    const char *usb_devices[MAX_USB_CMDLINE];
8239
    int usb_devices_index;
8240
    int fds[2];
8241
    int tb_size;
8242
    const char *pid_file = NULL;
8243
    VLANState *vlan;
8244

    
8245
    LIST_INIT (&vm_change_state_head);
8246
#ifndef _WIN32
8247
    {
8248
        struct sigaction act;
8249
        sigfillset(&act.sa_mask);
8250
        act.sa_flags = 0;
8251
        act.sa_handler = SIG_IGN;
8252
        sigaction(SIGPIPE, &act, NULL);
8253
    }
8254
#else
8255
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8256
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
8257
       QEMU to run on a single CPU */
8258
    {
8259
        HANDLE h;
8260
        DWORD mask, smask;
8261
        int i;
8262
        h = GetCurrentProcess();
8263
        if (GetProcessAffinityMask(h, &mask, &smask)) {
8264
            for(i = 0; i < 32; i++) {
8265
                if (mask & (1 << i))
8266
                    break;
8267
            }
8268
            if (i != 32) {
8269
                mask = 1 << i;
8270
                SetProcessAffinityMask(h, mask);
8271
            }
8272
        }
8273
    }
8274
#endif
8275

    
8276
    register_machines();
8277
    machine = first_machine;
8278
    cpu_model = NULL;
8279
    initrd_filename = NULL;
8280
    ram_size = 0;
8281
    vga_ram_size = VGA_RAM_SIZE;
8282
#ifdef CONFIG_GDBSTUB
8283
    use_gdbstub = 0;
8284
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
8285
#endif
8286
    snapshot = 0;
8287
    nographic = 0;
8288
    curses = 0;
8289
    kernel_filename = NULL;
8290
    kernel_cmdline = "";
8291
    cyls = heads = secs = 0;
8292
    translation = BIOS_ATA_TRANSLATION_AUTO;
8293
    monitor_device = "vc";
8294

    
8295
    serial_devices[0] = "vc:80Cx24C";
8296
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
8297
        serial_devices[i] = NULL;
8298
    serial_device_index = 0;
8299

    
8300
    parallel_devices[0] = "vc:640x480";
8301
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8302
        parallel_devices[i] = NULL;
8303
    parallel_device_index = 0;
8304

    
8305
    usb_devices_index = 0;
8306

    
8307
    nb_net_clients = 0;
8308
    nb_drives = 0;
8309
    nb_drives_opt = 0;
8310
    hda_index = -1;
8311

    
8312
    nb_nics = 0;
8313

    
8314
    tb_size = 0;
8315
    
8316
    optind = 1;
8317
    for(;;) {
8318
        if (optind >= argc)
8319
            break;
8320
        r = argv[optind];
8321
        if (r[0] != '-') {
8322
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8323
        } else {
8324
            const QEMUOption *popt;
8325

    
8326
            optind++;
8327
            /* Treat --foo the same as -foo.  */
8328
            if (r[1] == '-')
8329
                r++;
8330
            popt = qemu_options;
8331
            for(;;) {
8332
                if (!popt->name) {
8333
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
8334
                            argv[0], r);
8335
                    exit(1);
8336
                }
8337
                if (!strcmp(popt->name, r + 1))
8338
                    break;
8339
                popt++;
8340
            }
8341
            if (popt->flags & HAS_ARG) {
8342
                if (optind >= argc) {
8343
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
8344
                            argv[0], r);
8345
                    exit(1);
8346
                }
8347
                optarg = argv[optind++];
8348
            } else {
8349
                optarg = NULL;
8350
            }
8351

    
8352
            switch(popt->index) {
8353
            case QEMU_OPTION_M:
8354
                machine = find_machine(optarg);
8355
                if (!machine) {
8356
                    QEMUMachine *m;
8357
                    printf("Supported machines are:\n");
8358
                    for(m = first_machine; m != NULL; m = m->next) {
8359
                        printf("%-10s %s%s\n",
8360
                               m->name, m->desc,
8361
                               m == first_machine ? " (default)" : "");
8362
                    }
8363
                    exit(*optarg != '?');
8364
                }
8365
                break;
8366
            case QEMU_OPTION_cpu:
8367
                /* hw initialization will check this */
8368
                if (*optarg == '?') {
8369
/* XXX: implement xxx_cpu_list for targets that still miss it */
8370
#if defined(cpu_list)
8371
                    cpu_list(stdout, &fprintf);
8372
#endif
8373
                    exit(0);
8374
                } else {
8375
                    cpu_model = optarg;
8376
                }
8377
                break;
8378
            case QEMU_OPTION_initrd:
8379
                initrd_filename = optarg;
8380
                break;
8381
            case QEMU_OPTION_hda:
8382
                if (cyls == 0)
8383
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
8384
                else
8385
                    hda_index = drive_add(optarg, HD_ALIAS
8386
                             ",cyls=%d,heads=%d,secs=%d%s",
8387
                             0, cyls, heads, secs,
8388
                             translation == BIOS_ATA_TRANSLATION_LBA ?
8389
                                 ",trans=lba" :
8390
                             translation == BIOS_ATA_TRANSLATION_NONE ?
8391
                                 ",trans=none" : "");
8392
                 break;
8393
            case QEMU_OPTION_hdb:
8394
            case QEMU_OPTION_hdc:
8395
            case QEMU_OPTION_hdd:
8396
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8397
                break;
8398
            case QEMU_OPTION_drive:
8399
                drive_add(NULL, "%s", optarg);
8400
                break;
8401
            case QEMU_OPTION_mtdblock:
8402
                drive_add(optarg, MTD_ALIAS);
8403
                break;
8404
            case QEMU_OPTION_sd:
8405
                drive_add(optarg, SD_ALIAS);
8406
                break;
8407
            case QEMU_OPTION_pflash:
8408
                drive_add(optarg, PFLASH_ALIAS);
8409
                break;
8410
            case QEMU_OPTION_snapshot:
8411
                snapshot = 1;
8412
                break;
8413
            case QEMU_OPTION_hdachs:
8414
                {
8415
                    const char *p;
8416
                    p = optarg;
8417
                    cyls = strtol(p, (char **)&p, 0);
8418
                    if (cyls < 1 || cyls > 16383)
8419
                        goto chs_fail;
8420
                    if (*p != ',')
8421
                        goto chs_fail;
8422
                    p++;
8423
                    heads = strtol(p, (char **)&p, 0);
8424
                    if (heads < 1 || heads > 16)
8425
                        goto chs_fail;
8426
                    if (*p != ',')
8427
                        goto chs_fail;
8428
                    p++;
8429
                    secs = strtol(p, (char **)&p, 0);
8430
                    if (secs < 1 || secs > 63)
8431
                        goto chs_fail;
8432
                    if (*p == ',') {
8433
                        p++;
8434
                        if (!strcmp(p, "none"))
8435
                            translation = BIOS_ATA_TRANSLATION_NONE;
8436
                        else if (!strcmp(p, "lba"))
8437
                            translation = BIOS_ATA_TRANSLATION_LBA;
8438
                        else if (!strcmp(p, "auto"))
8439
                            translation = BIOS_ATA_TRANSLATION_AUTO;
8440
                        else
8441
                            goto chs_fail;
8442
                    } else if (*p != '\0') {
8443
                    chs_fail:
8444
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
8445
                        exit(1);
8446
                    }
8447
                    if (hda_index != -1)
8448
                        snprintf(drives_opt[hda_index].opt,
8449
                                 sizeof(drives_opt[hda_index].opt),
8450
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8451
                                 0, cyls, heads, secs,
8452
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
8453
                                         ",trans=lba" :
8454
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
8455
                                     ",trans=none" : "");
8456
                }
8457
                break;
8458
            case QEMU_OPTION_nographic:
8459
                nographic = 1;
8460
                break;
8461
#ifdef CONFIG_CURSES
8462
            case QEMU_OPTION_curses:
8463
                curses = 1;
8464
                break;
8465
#endif
8466
            case QEMU_OPTION_portrait:
8467
                graphic_rotate = 1;
8468
                break;
8469
            case QEMU_OPTION_kernel:
8470
                kernel_filename = optarg;
8471
                break;
8472
            case QEMU_OPTION_append:
8473
                kernel_cmdline = optarg;
8474
                break;
8475
            case QEMU_OPTION_cdrom:
8476
                drive_add(optarg, CDROM_ALIAS);
8477
                break;
8478
            case QEMU_OPTION_boot:
8479
                boot_devices = optarg;
8480
                /* We just do some generic consistency checks */
8481
                {
8482
                    /* Could easily be extended to 64 devices if needed */
8483
                    const char *p;
8484
                    
8485
                    boot_devices_bitmap = 0;
8486
                    for (p = boot_devices; *p != '\0'; p++) {
8487
                        /* Allowed boot devices are:
8488
                         * a b     : floppy disk drives
8489
                         * c ... f : IDE disk drives
8490
                         * g ... m : machine implementation dependant drives
8491
                         * n ... p : network devices
8492
                         * It's up to each machine implementation to check
8493
                         * if the given boot devices match the actual hardware
8494
                         * implementation and firmware features.
8495
                         */
8496
                        if (*p < 'a' || *p > 'q') {
8497
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
8498
                            exit(1);
8499
                        }
8500
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8501
                            fprintf(stderr,
8502
                                    "Boot device '%c' was given twice\n",*p);
8503
                            exit(1);
8504
                        }
8505
                        boot_devices_bitmap |= 1 << (*p - 'a');
8506
                    }
8507
                }
8508
                break;
8509
            case QEMU_OPTION_fda:
8510
            case QEMU_OPTION_fdb:
8511
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8512
                break;
8513
#ifdef TARGET_I386
8514
            case QEMU_OPTION_no_fd_bootchk:
8515
                fd_bootchk = 0;
8516
                break;
8517
#endif
8518
            case QEMU_OPTION_net:
8519
                if (nb_net_clients >= MAX_NET_CLIENTS) {
8520
                    fprintf(stderr, "qemu: too many network clients\n");
8521
                    exit(1);
8522
                }
8523
                net_clients[nb_net_clients] = optarg;
8524
                nb_net_clients++;
8525
                break;
8526
#ifdef CONFIG_SLIRP
8527
            case QEMU_OPTION_tftp:
8528
                tftp_prefix = optarg;
8529
                break;
8530
            case QEMU_OPTION_bootp:
8531
                bootp_filename = optarg;
8532
                break;
8533
#ifndef _WIN32
8534
            case QEMU_OPTION_smb:
8535
                net_slirp_smb(optarg);
8536
                break;
8537
#endif
8538
            case QEMU_OPTION_redir:
8539
                net_slirp_redir(optarg);
8540
                break;
8541
#endif
8542
#ifdef HAS_AUDIO
8543
            case QEMU_OPTION_audio_help:
8544
                AUD_help ();
8545
                exit (0);
8546
                break;
8547
            case QEMU_OPTION_soundhw:
8548
                select_soundhw (optarg);
8549
                break;
8550
#endif
8551
            case QEMU_OPTION_h:
8552
                help(0);
8553
                break;
8554
            case QEMU_OPTION_m: {
8555
                uint64_t value;
8556
                char *ptr;
8557

    
8558
                value = strtoul(optarg, &ptr, 10);
8559
                switch (*ptr) {
8560
                case 0: case 'M': case 'm':
8561
                    value <<= 20;
8562
                    break;
8563
                case 'G': case 'g':
8564
                    value <<= 30;
8565
                    break;
8566
                default:
8567
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8568
                    exit(1);
8569
                }
8570

    
8571
                /* On 32-bit hosts, QEMU is limited by virtual address space */
8572
                if (value > (2047 << 20)
8573
#ifndef USE_KQEMU
8574
                    && HOST_LONG_BITS == 32
8575
#endif
8576
                    ) {
8577
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8578
                    exit(1);
8579
                }
8580
                if (value != (uint64_t)(ram_addr_t)value) {
8581
                    fprintf(stderr, "qemu: ram size too large\n");
8582
                    exit(1);
8583
                }
8584
                ram_size = value;
8585
                break;
8586
            }
8587
            case QEMU_OPTION_d:
8588
                {
8589
                    int mask;
8590
                    CPULogItem *item;
8591

    
8592
                    mask = cpu_str_to_log_mask(optarg);
8593
                    if (!mask) {
8594
                        printf("Log items (comma separated):\n");
8595
                    for(item = cpu_log_items; item->mask != 0; item++) {
8596
                        printf("%-10s %s\n", item->name, item->help);
8597
                    }
8598
                    exit(1);
8599
                    }
8600
                    cpu_set_log(mask);
8601
                }
8602
                break;
8603
#ifdef CONFIG_GDBSTUB
8604
            case QEMU_OPTION_s:
8605
                use_gdbstub = 1;
8606
                break;
8607
            case QEMU_OPTION_p:
8608
                gdbstub_port = optarg;
8609
                break;
8610
#endif
8611
            case QEMU_OPTION_L:
8612
                bios_dir = optarg;
8613
                break;
8614
            case QEMU_OPTION_bios:
8615
                bios_name = optarg;
8616
                break;
8617
            case QEMU_OPTION_S:
8618
                autostart = 0;
8619
                break;
8620
            case QEMU_OPTION_k:
8621
                keyboard_layout = optarg;
8622
                break;
8623
            case QEMU_OPTION_localtime:
8624
                rtc_utc = 0;
8625
                break;
8626
            case QEMU_OPTION_cirrusvga:
8627
                cirrus_vga_enabled = 1;
8628
                vmsvga_enabled = 0;
8629
                break;
8630
            case QEMU_OPTION_vmsvga:
8631
                cirrus_vga_enabled = 0;
8632
                vmsvga_enabled = 1;
8633
                break;
8634
            case QEMU_OPTION_std_vga:
8635
                cirrus_vga_enabled = 0;
8636
                vmsvga_enabled = 0;
8637
                break;
8638
            case QEMU_OPTION_g:
8639
                {
8640
                    const char *p;
8641
                    int w, h, depth;
8642
                    p = optarg;
8643
                    w = strtol(p, (char **)&p, 10);
8644
                    if (w <= 0) {
8645
                    graphic_error:
8646
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8647
                        exit(1);
8648
                    }
8649
                    if (*p != 'x')
8650
                        goto graphic_error;
8651
                    p++;
8652
                    h = strtol(p, (char **)&p, 10);
8653
                    if (h <= 0)
8654
                        goto graphic_error;
8655
                    if (*p == 'x') {
8656
                        p++;
8657
                        depth = strtol(p, (char **)&p, 10);
8658
                        if (depth != 8 && depth != 15 && depth != 16 &&
8659
                            depth != 24 && depth != 32)
8660
                            goto graphic_error;
8661
                    } else if (*p == '\0') {
8662
                        depth = graphic_depth;
8663
                    } else {
8664
                        goto graphic_error;
8665
                    }
8666

    
8667
                    graphic_width = w;
8668
                    graphic_height = h;
8669
                    graphic_depth = depth;
8670
                }
8671
                break;
8672
            case QEMU_OPTION_echr:
8673
                {
8674
                    char *r;
8675
                    term_escape_char = strtol(optarg, &r, 0);
8676
                    if (r == optarg)
8677
                        printf("Bad argument to echr\n");
8678
                    break;
8679
                }
8680
            case QEMU_OPTION_monitor:
8681
                monitor_device = optarg;
8682
                break;
8683
            case QEMU_OPTION_serial:
8684
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8685
                    fprintf(stderr, "qemu: too many serial ports\n");
8686
                    exit(1);
8687
                }
8688
                serial_devices[serial_device_index] = optarg;
8689
                serial_device_index++;
8690
                break;
8691
            case QEMU_OPTION_parallel:
8692
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8693
                    fprintf(stderr, "qemu: too many parallel ports\n");
8694
                    exit(1);
8695
                }
8696
                parallel_devices[parallel_device_index] = optarg;
8697
                parallel_device_index++;
8698
                break;
8699
            case QEMU_OPTION_loadvm:
8700
                loadvm = optarg;
8701
                break;
8702
            case QEMU_OPTION_full_screen:
8703
                full_screen = 1;
8704
                break;
8705
#ifdef CONFIG_SDL
8706
            case QEMU_OPTION_no_frame:
8707
                no_frame = 1;
8708
                break;
8709
            case QEMU_OPTION_alt_grab:
8710
                alt_grab = 1;
8711
                break;
8712
            case QEMU_OPTION_no_quit:
8713
                no_quit = 1;
8714
                break;
8715
#endif
8716
            case QEMU_OPTION_pidfile:
8717
                pid_file = optarg;
8718
                break;
8719
#ifdef TARGET_I386
8720
            case QEMU_OPTION_win2k_hack:
8721
                win2k_install_hack = 1;
8722
                break;
8723
#endif
8724
#ifdef USE_KQEMU
8725
            case QEMU_OPTION_no_kqemu:
8726
                kqemu_allowed = 0;
8727
                break;
8728
            case QEMU_OPTION_kernel_kqemu:
8729
                kqemu_allowed = 2;
8730
                break;
8731
#endif
8732
            case QEMU_OPTION_usb:
8733
                usb_enabled = 1;
8734
                break;
8735
            case QEMU_OPTION_usbdevice:
8736
                usb_enabled = 1;
8737
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8738
                    fprintf(stderr, "Too many USB devices\n");
8739
                    exit(1);
8740
                }
8741
                usb_devices[usb_devices_index] = optarg;
8742
                usb_devices_index++;
8743
                break;
8744
            case QEMU_OPTION_smp:
8745
                smp_cpus = atoi(optarg);
8746
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8747
                    fprintf(stderr, "Invalid number of CPUs\n");
8748
                    exit(1);
8749
                }
8750
                break;
8751
            case QEMU_OPTION_vnc:
8752
                vnc_display = optarg;
8753
                break;
8754
            case QEMU_OPTION_no_acpi:
8755
                acpi_enabled = 0;
8756
                break;
8757
            case QEMU_OPTION_no_reboot:
8758
                no_reboot = 1;
8759
                break;
8760
            case QEMU_OPTION_no_shutdown:
8761
                no_shutdown = 1;
8762
                break;
8763
            case QEMU_OPTION_show_cursor:
8764
                cursor_hide = 0;
8765
                break;
8766
            case QEMU_OPTION_daemonize:
8767
                daemonize = 1;
8768
                break;
8769
            case QEMU_OPTION_option_rom:
8770
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8771
                    fprintf(stderr, "Too many option ROMs\n");
8772
                    exit(1);
8773
                }
8774
                option_rom[nb_option_roms] = optarg;
8775
                nb_option_roms++;
8776
                break;
8777
            case QEMU_OPTION_semihosting:
8778
                semihosting_enabled = 1;
8779
                break;
8780
            case QEMU_OPTION_name:
8781
                qemu_name = optarg;
8782
                break;
8783
#ifdef TARGET_SPARC
8784
            case QEMU_OPTION_prom_env:
8785
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8786
                    fprintf(stderr, "Too many prom variables\n");
8787
                    exit(1);
8788
                }
8789
                prom_envs[nb_prom_envs] = optarg;
8790
                nb_prom_envs++;
8791
                break;
8792
#endif
8793
#ifdef TARGET_ARM
8794
            case QEMU_OPTION_old_param:
8795
                old_param = 1;
8796
                break;
8797
#endif
8798
            case QEMU_OPTION_clock:
8799
                configure_alarms(optarg);
8800
                break;
8801
            case QEMU_OPTION_startdate:
8802
                {
8803
                    struct tm tm;
8804
                    time_t rtc_start_date;
8805
                    if (!strcmp(optarg, "now")) {
8806
                        rtc_date_offset = -1;
8807
                    } else {
8808
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8809
                               &tm.tm_year,
8810
                               &tm.tm_mon,
8811
                               &tm.tm_mday,
8812
                               &tm.tm_hour,
8813
                               &tm.tm_min,
8814
                               &tm.tm_sec) == 6) {
8815
                            /* OK */
8816
                        } else if (sscanf(optarg, "%d-%d-%d",
8817
                                          &tm.tm_year,
8818
                                          &tm.tm_mon,
8819
                                          &tm.tm_mday) == 3) {
8820
                            tm.tm_hour = 0;
8821
                            tm.tm_min = 0;
8822
                            tm.tm_sec = 0;
8823
                        } else {
8824
                            goto date_fail;
8825
                        }
8826
                        tm.tm_year -= 1900;
8827
                        tm.tm_mon--;
8828
                        rtc_start_date = mktimegm(&tm);
8829
                        if (rtc_start_date == -1) {
8830
                        date_fail:
8831
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8832
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8833
                            exit(1);
8834
                        }
8835
                        rtc_date_offset = time(NULL) - rtc_start_date;
8836
                    }
8837
                }
8838
                break;
8839
            case QEMU_OPTION_tb_size:
8840
                tb_size = strtol(optarg, NULL, 0);
8841
                if (tb_size < 0)
8842
                    tb_size = 0;
8843
                break;
8844
            case QEMU_OPTION_icount:
8845
                use_icount = 1;
8846
                if (strcmp(optarg, "auto") == 0) {
8847
                    icount_time_shift = -1;
8848
                } else {
8849
                    icount_time_shift = strtol(optarg, NULL, 0);
8850
                }
8851
                break;
8852
            }
8853
        }
8854
    }
8855

    
8856
    if (nographic) {
8857
       if (serial_device_index == 0)
8858
           serial_devices[0] = "stdio";
8859
       if (parallel_device_index == 0)
8860
           parallel_devices[0] = "null";
8861
       if (strncmp(monitor_device, "vc", 2) == 0)
8862
           monitor_device = "stdio";
8863
    }
8864

    
8865
#ifndef _WIN32
8866
    if (daemonize) {
8867
        pid_t pid;
8868

    
8869
        if (pipe(fds) == -1)
8870
            exit(1);
8871

    
8872
        pid = fork();
8873
        if (pid > 0) {
8874
            uint8_t status;
8875
            ssize_t len;
8876

    
8877
            close(fds[1]);
8878

    
8879
        again:
8880
            len = read(fds[0], &status, 1);
8881
            if (len == -1 && (errno == EINTR))
8882
                goto again;
8883

    
8884
            if (len != 1)
8885
                exit(1);
8886
            else if (status == 1) {
8887
                fprintf(stderr, "Could not acquire pidfile\n");
8888
                exit(1);
8889
            } else
8890
                exit(0);
8891
        } else if (pid < 0)
8892
            exit(1);
8893

    
8894
        setsid();
8895

    
8896
        pid = fork();
8897
        if (pid > 0)
8898
            exit(0);
8899
        else if (pid < 0)
8900
            exit(1);
8901

    
8902
        umask(027);
8903

    
8904
        signal(SIGTSTP, SIG_IGN);
8905
        signal(SIGTTOU, SIG_IGN);
8906
        signal(SIGTTIN, SIG_IGN);
8907
    }
8908
#endif
8909

    
8910
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8911
        if (daemonize) {
8912
            uint8_t status = 1;
8913
            write(fds[1], &status, 1);
8914
        } else
8915
            fprintf(stderr, "Could not acquire pid file\n");
8916
        exit(1);
8917
    }
8918

    
8919
#ifdef USE_KQEMU
8920
    if (smp_cpus > 1)
8921
        kqemu_allowed = 0;
8922
#endif
8923
    linux_boot = (kernel_filename != NULL);
8924
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8925

    
8926
    if (!linux_boot && net_boot == 0 &&
8927
        !machine->nodisk_ok && nb_drives_opt == 0)
8928
        help(1);
8929

    
8930
    if (!linux_boot && *kernel_cmdline != '\0') {
8931
        fprintf(stderr, "-append only allowed with -kernel option\n");
8932
        exit(1);
8933
    }
8934

    
8935
    if (!linux_boot && initrd_filename != NULL) {
8936
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
8937
        exit(1);
8938
    }
8939

    
8940
    /* boot to floppy or the default cd if no hard disk defined yet */
8941
    if (!boot_devices[0]) {
8942
        boot_devices = "cad";
8943
    }
8944
    setvbuf(stdout, NULL, _IOLBF, 0);
8945

    
8946
    init_timers();
8947
    init_timer_alarm();
8948
    qemu_aio_init();
8949
    if (use_icount && icount_time_shift < 0) {
8950
        use_icount = 2;
8951
        /* 125MIPS seems a reasonable initial guess at the guest speed.
8952
           It will be corrected fairly quickly anyway.  */
8953
        icount_time_shift = 3;
8954
        init_icount_adjust();
8955
    }
8956

    
8957
#ifdef _WIN32
8958
    socket_init();
8959
#endif
8960

    
8961
    /* init network clients */
8962
    if (nb_net_clients == 0) {
8963
        /* if no clients, we use a default config */
8964
        net_clients[0] = "nic";
8965
        net_clients[1] = "user";
8966
        nb_net_clients = 2;
8967
    }
8968

    
8969
    for(i = 0;i < nb_net_clients; i++) {
8970
        if (net_client_parse(net_clients[i]) < 0)
8971
            exit(1);
8972
    }
8973
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8974
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8975
            continue;
8976
        if (vlan->nb_guest_devs == 0)
8977
            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
8978
        if (vlan->nb_host_devs == 0)
8979
            fprintf(stderr,
8980
                    "Warning: vlan %d is not connected to host network\n",
8981
                    vlan->id);
8982
    }
8983

    
8984
#ifdef TARGET_I386
8985
    /* XXX: this should be moved in the PC machine instantiation code */
8986
    if (net_boot != 0) {
8987
        int netroms = 0;
8988
        for (i = 0; i < nb_nics && i < 4; i++) {
8989
            const char *model = nd_table[i].model;
8990
            char buf[1024];
8991
            if (net_boot & (1 << i)) {
8992
                if (model == NULL)
8993
                    model = "ne2k_pci";
8994
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8995
                if (get_image_size(buf) > 0) {
8996
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8997
                        fprintf(stderr, "Too many option ROMs\n");
8998
                        exit(1);
8999
                    }
9000
                    option_rom[nb_option_roms] = strdup(buf);
9001
                    nb_option_roms++;
9002
                    netroms++;
9003
                }
9004
            }
9005
        }
9006
        if (netroms == 0) {
9007
            fprintf(stderr, "No valid PXE rom found for network device\n");
9008
            exit(1);
9009
        }
9010
    }
9011
#endif
9012

    
9013
    /* init the memory */
9014
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9015

    
9016
    if (machine->ram_require & RAMSIZE_FIXED) {
9017
        if (ram_size > 0) {
9018
            if (ram_size < phys_ram_size) {
9019
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9020
                                machine->name, (unsigned long long) phys_ram_size);
9021
                exit(-1);
9022
            }
9023

    
9024
            phys_ram_size = ram_size;
9025
        } else
9026
            ram_size = phys_ram_size;
9027
    } else {
9028
        if (ram_size == 0)
9029
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9030

    
9031
        phys_ram_size += ram_size;
9032
    }
9033

    
9034
    phys_ram_base = qemu_vmalloc(phys_ram_size);
9035
    if (!phys_ram_base) {
9036
        fprintf(stderr, "Could not allocate physical memory\n");
9037
        exit(1);
9038
    }
9039

    
9040
    /* init the dynamic translator */
9041
    cpu_exec_init_all(tb_size * 1024 * 1024);
9042

    
9043
    bdrv_init();
9044

    
9045
    /* we always create the cdrom drive, even if no disk is there */
9046

    
9047
    if (nb_drives_opt < MAX_DRIVES)
9048
        drive_add(NULL, CDROM_ALIAS);
9049

    
9050
    /* we always create at least one floppy */
9051

    
9052
    if (nb_drives_opt < MAX_DRIVES)
9053
        drive_add(NULL, FD_ALIAS, 0);
9054

    
9055
    /* we always create one sd slot, even if no card is in it */
9056

    
9057
    if (nb_drives_opt < MAX_DRIVES)
9058
        drive_add(NULL, SD_ALIAS);
9059

    
9060
    /* open the virtual block devices */
9061

    
9062
    for(i = 0; i < nb_drives_opt; i++)
9063
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9064
            exit(1);
9065

    
9066
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9067
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9068

    
9069
    /* terminal init */
9070
    memset(&display_state, 0, sizeof(display_state));
9071
    if (nographic) {
9072
        if (curses) {
9073
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9074
            exit(1);
9075
        }
9076
        /* nearly nothing to do */
9077
        dumb_display_init(ds);
9078
    } else if (vnc_display != NULL) {
9079
        vnc_display_init(ds);
9080
        if (vnc_display_open(ds, vnc_display) < 0)
9081
            exit(1);
9082
    } else
9083
#if defined(CONFIG_CURSES)
9084
    if (curses) {
9085
        curses_display_init(ds, full_screen);
9086
    } else
9087
#endif
9088
    {
9089
#if defined(CONFIG_SDL)
9090
        sdl_display_init(ds, full_screen, no_frame);
9091
#elif defined(CONFIG_COCOA)
9092
        cocoa_display_init(ds, full_screen);
9093
#else
9094
        dumb_display_init(ds);
9095
#endif
9096
    }
9097

    
9098
#ifndef _WIN32
9099
    /* must be after terminal init, SDL library changes signal handlers */
9100
    termsig_setup();
9101
#endif
9102

    
9103
    /* Maintain compatibility with multiple stdio monitors */
9104
    if (!strcmp(monitor_device,"stdio")) {
9105
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9106
            const char *devname = serial_devices[i];
9107
            if (devname && !strcmp(devname,"mon:stdio")) {
9108
                monitor_device = NULL;
9109
                break;
9110
            } else if (devname && !strcmp(devname,"stdio")) {
9111
                monitor_device = NULL;
9112
                serial_devices[i] = "mon:stdio";
9113
                break;
9114
            }
9115
        }
9116
    }
9117
    if (monitor_device) {
9118
        monitor_hd = qemu_chr_open(monitor_device);
9119
        if (!monitor_hd) {
9120
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9121
            exit(1);
9122
        }
9123
        monitor_init(monitor_hd, !nographic);
9124
    }
9125

    
9126
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9127
        const char *devname = serial_devices[i];
9128
        if (devname && strcmp(devname, "none")) {
9129
            serial_hds[i] = qemu_chr_open(devname);
9130
            if (!serial_hds[i]) {
9131
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
9132
                        devname);
9133
                exit(1);
9134
            }
9135
            if (strstart(devname, "vc", 0))
9136
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9137
        }
9138
    }
9139

    
9140
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9141
        const char *devname = parallel_devices[i];
9142
        if (devname && strcmp(devname, "none")) {
9143
            parallel_hds[i] = qemu_chr_open(devname);
9144
            if (!parallel_hds[i]) {
9145
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9146
                        devname);
9147
                exit(1);
9148
            }
9149
            if (strstart(devname, "vc", 0))
9150
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9151
        }
9152
    }
9153

    
9154
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
9155
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9156

    
9157
    /* init USB devices */
9158
    if (usb_enabled) {
9159
        for(i = 0; i < usb_devices_index; i++) {
9160
            if (usb_device_add(usb_devices[i]) < 0) {
9161
                fprintf(stderr, "Warning: could not add USB device %s\n",
9162
                        usb_devices[i]);
9163
            }
9164
        }
9165
    }
9166

    
9167
    if (display_state.dpy_refresh) {
9168
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9169
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9170
    }
9171

    
9172
#ifdef CONFIG_GDBSTUB
9173
    if (use_gdbstub) {
9174
        /* XXX: use standard host:port notation and modify options
9175
           accordingly. */
9176
        if (gdbserver_start(gdbstub_port) < 0) {
9177
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9178
                    gdbstub_port);
9179
            exit(1);
9180
        }
9181
    }
9182
#endif
9183

    
9184
    if (loadvm)
9185
        do_loadvm(loadvm);
9186

    
9187
    {
9188
        /* XXX: simplify init */
9189
        read_passwords();
9190
        if (autostart) {
9191
            vm_start();
9192
        }
9193
    }
9194

    
9195
    if (daemonize) {
9196
        uint8_t status = 0;
9197
        ssize_t len;
9198
        int fd;
9199

    
9200
    again1:
9201
        len = write(fds[1], &status, 1);
9202
        if (len == -1 && (errno == EINTR))
9203
            goto again1;
9204

    
9205
        if (len != 1)
9206
            exit(1);
9207

    
9208
        chdir("/");
9209
        TFR(fd = open("/dev/null", O_RDWR));
9210
        if (fd == -1)
9211
            exit(1);
9212

    
9213
        dup2(fd, 0);
9214
        dup2(fd, 1);
9215
        dup2(fd, 2);
9216

    
9217
        close(fd);
9218
    }
9219

    
9220
    main_loop();
9221
    quit_timers();
9222

    
9223
#if !defined(_WIN32)
9224
    /* close network clients */
9225
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9226
        VLANClientState *vc;
9227

    
9228
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9229
            if (vc->fd_read == tap_receive) {
9230
                char ifname[64];
9231
                TAPState *s = vc->opaque;
9232

    
9233
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9234
                    s->down_script[0])
9235
                    launch_script(s->down_script, ifname, s->fd);
9236
            }
9237
#if defined(CONFIG_VDE)
9238
            if (vc->fd_read == vde_from_qemu) {
9239
                VDEState *s = vc->opaque;
9240
                vde_close(s->vde);
9241
            }
9242
#endif
9243
        }
9244
    }
9245
#endif
9246
    return 0;
9247
}