Statistics
| Branch: | Revision:

root / vl.c @ 5867c88a

History | View | Annotate | Download (189.5 kB)

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

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

    
34
#ifndef _WIN32
35
#include <sys/times.h>
36
#include <sys/wait.h>
37
#include <termios.h>
38
#include <sys/poll.h>
39
#include <sys/mman.h>
40
#include <sys/ioctl.h>
41
#include <sys/socket.h>
42
#include <netinet/in.h>
43
#include <dirent.h>
44
#include <netdb.h>
45
#ifdef _BSD
46
#include <sys/stat.h>
47
#ifndef __APPLE__
48
#include <libutil.h>
49
#endif
50
#else
51
#ifndef __sun__
52
#include <linux/if.h>
53
#include <linux/if_tun.h>
54
#include <pty.h>
55
#include <malloc.h>
56
#include <linux/rtc.h>
57
#include <linux/ppdev.h>
58
#include <linux/parport.h>
59
#else
60
#include <sys/stat.h>
61
#include <sys/ethernet.h>
62
#include <sys/sockio.h>
63
#include <arpa/inet.h>
64
#include <netinet/arp.h>
65
#include <netinet/in.h>
66
#include <netinet/in_systm.h>
67
#include <netinet/ip.h>
68
#include <netinet/ip_icmp.h> // must come after ip.h
69
#include <netinet/udp.h>
70
#include <netinet/tcp.h>
71
#include <net/if.h>
72
#include <syslog.h>
73
#include <stropts.h>
74
#endif
75
#endif
76
#endif
77

    
78
#if defined(CONFIG_SLIRP)
79
#include "libslirp.h"
80
#endif
81

    
82
#ifdef _WIN32
83
#include <malloc.h>
84
#include <sys/timeb.h>
85
#include <windows.h>
86
#define getopt_long_only getopt_long
87
#define memalign(align, size) malloc(size)
88
#endif
89

    
90
#include "qemu_socket.h"
91

    
92
#ifdef CONFIG_SDL
93
#ifdef __APPLE__
94
#include <SDL/SDL.h>
95
#endif
96
#endif /* CONFIG_SDL */
97

    
98
#ifdef CONFIG_COCOA
99
#undef main
100
#define main qemu_main
101
#endif /* CONFIG_COCOA */
102

    
103
#include "disas.h"
104

    
105
#include "exec-all.h"
106

    
107
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
108
#ifdef __sun__
109
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110
#else
111
#define SMBD_COMMAND "/usr/sbin/smbd"
112
#endif
113

    
114
//#define DEBUG_UNUSED_IOPORT
115
//#define DEBUG_IOPORT
116

    
117
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
118

    
119
#ifdef TARGET_PPC
120
#define DEFAULT_RAM_SIZE 144
121
#else
122
#define DEFAULT_RAM_SIZE 128
123
#endif
124
/* in ms */
125
#define GUI_REFRESH_INTERVAL 30
126

    
127
/* Max number of USB devices that can be specified on the commandline.  */
128
#define MAX_USB_CMDLINE 8
129

    
130
/* XXX: use a two level table to limit memory usage */
131
#define MAX_IOPORTS 65536
132

    
133
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134
char phys_ram_file[1024];
135
void *ioport_opaque[MAX_IOPORTS];
136
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138
/* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139
   to store the VM snapshots */
140
BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
141
/* point to the block driver where the snapshots are managed */
142
BlockDriverState *bs_snapshots;
143
int vga_ram_size;
144
static DisplayState display_state;
145
int nographic;
146
const char* keyboard_layout = NULL;
147
int64_t ticks_per_sec;
148
int boot_device = 'c';
149
int ram_size;
150
int pit_min_timer_count = 0;
151
int nb_nics;
152
NICInfo nd_table[MAX_NICS];
153
QEMUTimer *gui_timer;
154
int vm_running;
155
int rtc_utc = 1;
156
int cirrus_vga_enabled = 1;
157
#ifdef TARGET_SPARC
158
int graphic_width = 1024;
159
int graphic_height = 768;
160
#else
161
int graphic_width = 800;
162
int graphic_height = 600;
163
#endif
164
int graphic_depth = 15;
165
int full_screen = 0;
166
int no_quit = 0;
167
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
168
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
169
#ifdef TARGET_I386
170
int win2k_install_hack = 0;
171
#endif
172
int usb_enabled = 0;
173
static VLANState *first_vlan;
174
int smp_cpus = 1;
175
const char *vnc_display;
176
#if defined(TARGET_SPARC)
177
#define MAX_CPUS 16
178
#elif defined(TARGET_I386)
179
#define MAX_CPUS 255
180
#else
181
#define MAX_CPUS 1
182
#endif
183
int acpi_enabled = 1;
184
int fd_bootchk = 1;
185
int no_reboot = 0;
186
int daemonize = 0;
187
const char *option_rom[MAX_OPTION_ROMS];
188
int nb_option_roms;
189
int semihosting_enabled = 0;
190
int autostart = 1;
191

    
192
/***********************************************************/
193
/* x86 ISA bus support */
194

    
195
target_phys_addr_t isa_mem_base = 0;
196
PicState2 *isa_pic;
197

    
198
uint32_t default_ioport_readb(void *opaque, uint32_t address)
199
{
200
#ifdef DEBUG_UNUSED_IOPORT
201
    fprintf(stderr, "inb: port=0x%04x\n", address);
202
#endif
203
    return 0xff;
204
}
205

    
206
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
207
{
208
#ifdef DEBUG_UNUSED_IOPORT
209
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
210
#endif
211
}
212

    
213
/* default is to make two byte accesses */
214
uint32_t default_ioport_readw(void *opaque, uint32_t address)
215
{
216
    uint32_t data;
217
    data = ioport_read_table[0][address](ioport_opaque[address], address);
218
    address = (address + 1) & (MAX_IOPORTS - 1);
219
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
220
    return data;
221
}
222

    
223
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
224
{
225
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
226
    address = (address + 1) & (MAX_IOPORTS - 1);
227
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
228
}
229

    
230
uint32_t default_ioport_readl(void *opaque, uint32_t address)
231
{
232
#ifdef DEBUG_UNUSED_IOPORT
233
    fprintf(stderr, "inl: port=0x%04x\n", address);
234
#endif
235
    return 0xffffffff;
236
}
237

    
238
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
239
{
240
#ifdef DEBUG_UNUSED_IOPORT
241
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
242
#endif
243
}
244

    
245
void init_ioports(void)
246
{
247
    int i;
248

    
249
    for(i = 0; i < MAX_IOPORTS; i++) {
250
        ioport_read_table[0][i] = default_ioport_readb;
251
        ioport_write_table[0][i] = default_ioport_writeb;
252
        ioport_read_table[1][i] = default_ioport_readw;
253
        ioport_write_table[1][i] = default_ioport_writew;
254
        ioport_read_table[2][i] = default_ioport_readl;
255
        ioport_write_table[2][i] = default_ioport_writel;
256
    }
257
}
258

    
259
/* size is the word size in byte */
260
int register_ioport_read(int start, int length, int size, 
261
                         IOPortReadFunc *func, void *opaque)
262
{
263
    int i, bsize;
264

    
265
    if (size == 1) {
266
        bsize = 0;
267
    } else if (size == 2) {
268
        bsize = 1;
269
    } else if (size == 4) {
270
        bsize = 2;
271
    } else {
272
        hw_error("register_ioport_read: invalid size");
273
        return -1;
274
    }
275
    for(i = start; i < start + length; i += size) {
276
        ioport_read_table[bsize][i] = func;
277
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
278
            hw_error("register_ioport_read: invalid opaque");
279
        ioport_opaque[i] = opaque;
280
    }
281
    return 0;
282
}
283

    
284
/* size is the word size in byte */
285
int register_ioport_write(int start, int length, int size, 
286
                          IOPortWriteFunc *func, void *opaque)
287
{
288
    int i, bsize;
289

    
290
    if (size == 1) {
291
        bsize = 0;
292
    } else if (size == 2) {
293
        bsize = 1;
294
    } else if (size == 4) {
295
        bsize = 2;
296
    } else {
297
        hw_error("register_ioport_write: invalid size");
298
        return -1;
299
    }
300
    for(i = start; i < start + length; i += size) {
301
        ioport_write_table[bsize][i] = func;
302
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
303
            hw_error("register_ioport_write: invalid opaque");
304
        ioport_opaque[i] = opaque;
305
    }
306
    return 0;
307
}
308

    
309
void isa_unassign_ioport(int start, int length)
310
{
311
    int i;
312

    
313
    for(i = start; i < start + length; i++) {
314
        ioport_read_table[0][i] = default_ioport_readb;
315
        ioport_read_table[1][i] = default_ioport_readw;
316
        ioport_read_table[2][i] = default_ioport_readl;
317

    
318
        ioport_write_table[0][i] = default_ioport_writeb;
319
        ioport_write_table[1][i] = default_ioport_writew;
320
        ioport_write_table[2][i] = default_ioport_writel;
321
    }
322
}
323

    
324
/***********************************************************/
325

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

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

    
352
void cpu_outl(CPUState *env, int addr, int val)
353
{
354
#ifdef DEBUG_IOPORT
355
    if (loglevel & CPU_LOG_IOPORT)
356
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
357
#endif
358
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
359
#ifdef USE_KQEMU
360
    if (env)
361
        env->last_io_time = cpu_get_time_fast();
362
#endif
363
}
364

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

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

    
395
int cpu_inl(CPUState *env, int addr)
396
{
397
    int val;
398
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
399
#ifdef DEBUG_IOPORT
400
    if (loglevel & CPU_LOG_IOPORT)
401
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
402
#endif
403
#ifdef USE_KQEMU
404
    if (env)
405
        env->last_io_time = cpu_get_time_fast();
406
#endif
407
    return val;
408
}
409

    
410
/***********************************************************/
411
void hw_error(const char *fmt, ...)
412
{
413
    va_list ap;
414
    CPUState *env;
415

    
416
    va_start(ap, fmt);
417
    fprintf(stderr, "qemu: hardware error: ");
418
    vfprintf(stderr, fmt, ap);
419
    fprintf(stderr, "\n");
420
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
421
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
422
#ifdef TARGET_I386
423
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
424
#else
425
        cpu_dump_state(env, stderr, fprintf, 0);
426
#endif
427
    }
428
    va_end(ap);
429
    abort();
430
}
431

    
432
/***********************************************************/
433
/* keyboard/mouse */
434

    
435
static QEMUPutKBDEvent *qemu_put_kbd_event;
436
static void *qemu_put_kbd_event_opaque;
437
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
438
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
439

    
440
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
441
{
442
    qemu_put_kbd_event_opaque = opaque;
443
    qemu_put_kbd_event = func;
444
}
445

    
446
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
447
                                                void *opaque, int absolute,
448
                                                const char *name)
449
{
450
    QEMUPutMouseEntry *s, *cursor;
451

    
452
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
453
    if (!s)
454
        return NULL;
455

    
456
    s->qemu_put_mouse_event = func;
457
    s->qemu_put_mouse_event_opaque = opaque;
458
    s->qemu_put_mouse_event_absolute = absolute;
459
    s->qemu_put_mouse_event_name = qemu_strdup(name);
460
    s->next = NULL;
461

    
462
    if (!qemu_put_mouse_event_head) {
463
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
464
        return s;
465
    }
466

    
467
    cursor = qemu_put_mouse_event_head;
468
    while (cursor->next != NULL)
469
        cursor = cursor->next;
470

    
471
    cursor->next = s;
472
    qemu_put_mouse_event_current = s;
473

    
474
    return s;
475
}
476

    
477
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
478
{
479
    QEMUPutMouseEntry *prev = NULL, *cursor;
480

    
481
    if (!qemu_put_mouse_event_head || entry == NULL)
482
        return;
483

    
484
    cursor = qemu_put_mouse_event_head;
485
    while (cursor != NULL && cursor != entry) {
486
        prev = cursor;
487
        cursor = cursor->next;
488
    }
489

    
490
    if (cursor == NULL) // does not exist or list empty
491
        return;
492
    else if (prev == NULL) { // entry is head
493
        qemu_put_mouse_event_head = cursor->next;
494
        if (qemu_put_mouse_event_current == entry)
495
            qemu_put_mouse_event_current = cursor->next;
496
        qemu_free(entry->qemu_put_mouse_event_name);
497
        qemu_free(entry);
498
        return;
499
    }
500

    
501
    prev->next = entry->next;
502

    
503
    if (qemu_put_mouse_event_current == entry)
504
        qemu_put_mouse_event_current = prev;
505

    
506
    qemu_free(entry->qemu_put_mouse_event_name);
507
    qemu_free(entry);
508
}
509

    
510
void kbd_put_keycode(int keycode)
511
{
512
    if (qemu_put_kbd_event) {
513
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
514
    }
515
}
516

    
517
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
518
{
519
    QEMUPutMouseEvent *mouse_event;
520
    void *mouse_event_opaque;
521

    
522
    if (!qemu_put_mouse_event_current) {
523
        return;
524
    }
525

    
526
    mouse_event =
527
        qemu_put_mouse_event_current->qemu_put_mouse_event;
528
    mouse_event_opaque =
529
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
530

    
531
    if (mouse_event) {
532
        mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
533
    }
534
}
535

    
536
int kbd_mouse_is_absolute(void)
537
{
538
    if (!qemu_put_mouse_event_current)
539
        return 0;
540

    
541
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
542
}
543

    
544
void do_info_mice(void)
545
{
546
    QEMUPutMouseEntry *cursor;
547
    int index = 0;
548

    
549
    if (!qemu_put_mouse_event_head) {
550
        term_printf("No mouse devices connected\n");
551
        return;
552
    }
553

    
554
    term_printf("Mouse devices available:\n");
555
    cursor = qemu_put_mouse_event_head;
556
    while (cursor != NULL) {
557
        term_printf("%c Mouse #%d: %s\n",
558
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
559
                    index, cursor->qemu_put_mouse_event_name);
560
        index++;
561
        cursor = cursor->next;
562
    }
563
}
564

    
565
void do_mouse_set(int index)
566
{
567
    QEMUPutMouseEntry *cursor;
568
    int i = 0;
569

    
570
    if (!qemu_put_mouse_event_head) {
571
        term_printf("No mouse devices connected\n");
572
        return;
573
    }
574

    
575
    cursor = qemu_put_mouse_event_head;
576
    while (cursor != NULL && index != i) {
577
        i++;
578
        cursor = cursor->next;
579
    }
580

    
581
    if (cursor != NULL)
582
        qemu_put_mouse_event_current = cursor;
583
    else
584
        term_printf("Mouse at given index not found\n");
585
}
586

    
587
/* compute with 96 bit intermediate result: (a*b)/c */
588
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
589
{
590
    union {
591
        uint64_t ll;
592
        struct {
593
#ifdef WORDS_BIGENDIAN
594
            uint32_t high, low;
595
#else
596
            uint32_t low, high;
597
#endif            
598
        } l;
599
    } u, res;
600
    uint64_t rl, rh;
601

    
602
    u.ll = a;
603
    rl = (uint64_t)u.l.low * (uint64_t)b;
604
    rh = (uint64_t)u.l.high * (uint64_t)b;
605
    rh += (rl >> 32);
606
    res.l.high = rh / c;
607
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
608
    return res.ll;
609
}
610

    
611
/***********************************************************/
612
/* real time host monotonic timer */
613

    
614
#define QEMU_TIMER_BASE 1000000000LL
615

    
616
#ifdef WIN32
617

    
618
static int64_t clock_freq;
619

    
620
static void init_get_clock(void)
621
{
622
    LARGE_INTEGER freq;
623
    int ret;
624
    ret = QueryPerformanceFrequency(&freq);
625
    if (ret == 0) {
626
        fprintf(stderr, "Could not calibrate ticks\n");
627
        exit(1);
628
    }
629
    clock_freq = freq.QuadPart;
630
}
631

    
632
static int64_t get_clock(void)
633
{
634
    LARGE_INTEGER ti;
635
    QueryPerformanceCounter(&ti);
636
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
637
}
638

    
639
#else
640

    
641
static int use_rt_clock;
642

    
643
static void init_get_clock(void)
644
{
645
    use_rt_clock = 0;
646
#if defined(__linux__)
647
    {
648
        struct timespec ts;
649
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
650
            use_rt_clock = 1;
651
        }
652
    }
653
#endif
654
}
655

    
656
static int64_t get_clock(void)
657
{
658
#if defined(__linux__)
659
    if (use_rt_clock) {
660
        struct timespec ts;
661
        clock_gettime(CLOCK_MONOTONIC, &ts);
662
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
663
    } else 
664
#endif
665
    {
666
        /* XXX: using gettimeofday leads to problems if the date
667
           changes, so it should be avoided. */
668
        struct timeval tv;
669
        gettimeofday(&tv, NULL);
670
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
671
    }
672
}
673

    
674
#endif
675

    
676
/***********************************************************/
677
/* guest cycle counter */
678

    
679
static int64_t cpu_ticks_prev;
680
static int64_t cpu_ticks_offset;
681
static int64_t cpu_clock_offset;
682
static int cpu_ticks_enabled;
683

    
684
/* return the host CPU cycle counter and handle stop/restart */
685
int64_t cpu_get_ticks(void)
686
{
687
    if (!cpu_ticks_enabled) {
688
        return cpu_ticks_offset;
689
    } else {
690
        int64_t ticks;
691
        ticks = cpu_get_real_ticks();
692
        if (cpu_ticks_prev > ticks) {
693
            /* Note: non increasing ticks may happen if the host uses
694
               software suspend */
695
            cpu_ticks_offset += cpu_ticks_prev - ticks;
696
        }
697
        cpu_ticks_prev = ticks;
698
        return ticks + cpu_ticks_offset;
699
    }
700
}
701

    
702
/* return the host CPU monotonic timer and handle stop/restart */
703
static int64_t cpu_get_clock(void)
704
{
705
    int64_t ti;
706
    if (!cpu_ticks_enabled) {
707
        return cpu_clock_offset;
708
    } else {
709
        ti = get_clock();
710
        return ti + cpu_clock_offset;
711
    }
712
}
713

    
714
/* enable cpu_get_ticks() */
715
void cpu_enable_ticks(void)
716
{
717
    if (!cpu_ticks_enabled) {
718
        cpu_ticks_offset -= cpu_get_real_ticks();
719
        cpu_clock_offset -= get_clock();
720
        cpu_ticks_enabled = 1;
721
    }
722
}
723

    
724
/* disable cpu_get_ticks() : the clock is stopped. You must not call
725
   cpu_get_ticks() after that.  */
726
void cpu_disable_ticks(void)
727
{
728
    if (cpu_ticks_enabled) {
729
        cpu_ticks_offset = cpu_get_ticks();
730
        cpu_clock_offset = cpu_get_clock();
731
        cpu_ticks_enabled = 0;
732
    }
733
}
734

    
735
/***********************************************************/
736
/* timers */
737
 
738
#define QEMU_TIMER_REALTIME 0
739
#define QEMU_TIMER_VIRTUAL  1
740

    
741
struct QEMUClock {
742
    int type;
743
    /* XXX: add frequency */
744
};
745

    
746
struct QEMUTimer {
747
    QEMUClock *clock;
748
    int64_t expire_time;
749
    QEMUTimerCB *cb;
750
    void *opaque;
751
    struct QEMUTimer *next;
752
};
753

    
754
QEMUClock *rt_clock;
755
QEMUClock *vm_clock;
756

    
757
static QEMUTimer *active_timers[2];
758
#ifdef _WIN32
759
static MMRESULT timerID;
760
static HANDLE host_alarm = NULL;
761
static unsigned int period = 1;
762
#else
763
/* frequency of the times() clock tick */
764
static int timer_freq;
765
#endif
766

    
767
QEMUClock *qemu_new_clock(int type)
768
{
769
    QEMUClock *clock;
770
    clock = qemu_mallocz(sizeof(QEMUClock));
771
    if (!clock)
772
        return NULL;
773
    clock->type = type;
774
    return clock;
775
}
776

    
777
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
778
{
779
    QEMUTimer *ts;
780

    
781
    ts = qemu_mallocz(sizeof(QEMUTimer));
782
    ts->clock = clock;
783
    ts->cb = cb;
784
    ts->opaque = opaque;
785
    return ts;
786
}
787

    
788
void qemu_free_timer(QEMUTimer *ts)
789
{
790
    qemu_free(ts);
791
}
792

    
793
/* stop a timer, but do not dealloc it */
794
void qemu_del_timer(QEMUTimer *ts)
795
{
796
    QEMUTimer **pt, *t;
797

    
798
    /* NOTE: this code must be signal safe because
799
       qemu_timer_expired() can be called from a signal. */
800
    pt = &active_timers[ts->clock->type];
801
    for(;;) {
802
        t = *pt;
803
        if (!t)
804
            break;
805
        if (t == ts) {
806
            *pt = t->next;
807
            break;
808
        }
809
        pt = &t->next;
810
    }
811
}
812

    
813
/* modify the current timer so that it will be fired when current_time
814
   >= expire_time. The corresponding callback will be called. */
815
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
816
{
817
    QEMUTimer **pt, *t;
818

    
819
    qemu_del_timer(ts);
820

    
821
    /* add the timer in the sorted list */
822
    /* NOTE: this code must be signal safe because
823
       qemu_timer_expired() can be called from a signal. */
824
    pt = &active_timers[ts->clock->type];
825
    for(;;) {
826
        t = *pt;
827
        if (!t)
828
            break;
829
        if (t->expire_time > expire_time) 
830
            break;
831
        pt = &t->next;
832
    }
833
    ts->expire_time = expire_time;
834
    ts->next = *pt;
835
    *pt = ts;
836
}
837

    
838
int qemu_timer_pending(QEMUTimer *ts)
839
{
840
    QEMUTimer *t;
841
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
842
        if (t == ts)
843
            return 1;
844
    }
845
    return 0;
846
}
847

    
848
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
849
{
850
    if (!timer_head)
851
        return 0;
852
    return (timer_head->expire_time <= current_time);
853
}
854

    
855
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
856
{
857
    QEMUTimer *ts;
858
    
859
    for(;;) {
860
        ts = *ptimer_head;
861
        if (!ts || ts->expire_time > current_time)
862
            break;
863
        /* remove timer from the list before calling the callback */
864
        *ptimer_head = ts->next;
865
        ts->next = NULL;
866
        
867
        /* run the callback (the timer list can be modified) */
868
        ts->cb(ts->opaque);
869
    }
870
}
871

    
872
int64_t qemu_get_clock(QEMUClock *clock)
873
{
874
    switch(clock->type) {
875
    case QEMU_TIMER_REALTIME:
876
        return get_clock() / 1000000;
877
    default:
878
    case QEMU_TIMER_VIRTUAL:
879
        return cpu_get_clock();
880
    }
881
}
882

    
883
static void init_timers(void)
884
{
885
    init_get_clock();
886
    ticks_per_sec = QEMU_TIMER_BASE;
887
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
888
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
889
}
890

    
891
/* save a timer */
892
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
893
{
894
    uint64_t expire_time;
895

    
896
    if (qemu_timer_pending(ts)) {
897
        expire_time = ts->expire_time;
898
    } else {
899
        expire_time = -1;
900
    }
901
    qemu_put_be64(f, expire_time);
902
}
903

    
904
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
905
{
906
    uint64_t expire_time;
907

    
908
    expire_time = qemu_get_be64(f);
909
    if (expire_time != -1) {
910
        qemu_mod_timer(ts, expire_time);
911
    } else {
912
        qemu_del_timer(ts);
913
    }
914
}
915

    
916
static void timer_save(QEMUFile *f, void *opaque)
917
{
918
    if (cpu_ticks_enabled) {
919
        hw_error("cannot save state if virtual timers are running");
920
    }
921
    qemu_put_be64s(f, &cpu_ticks_offset);
922
    qemu_put_be64s(f, &ticks_per_sec);
923
    qemu_put_be64s(f, &cpu_clock_offset);
924
}
925

    
926
static int timer_load(QEMUFile *f, void *opaque, int version_id)
927
{
928
    if (version_id != 1 && version_id != 2)
929
        return -EINVAL;
930
    if (cpu_ticks_enabled) {
931
        return -EINVAL;
932
    }
933
    qemu_get_be64s(f, &cpu_ticks_offset);
934
    qemu_get_be64s(f, &ticks_per_sec);
935
    if (version_id == 2) {
936
        qemu_get_be64s(f, &cpu_clock_offset);
937
    }
938
    return 0;
939
}
940

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

    
997
#ifndef _WIN32
998

    
999
#if defined(__linux__)
1000

    
1001
#define RTC_FREQ 1024
1002

    
1003
static int rtc_fd;
1004

    
1005
static int start_rtc_timer(void)
1006
{
1007
    rtc_fd = open("/dev/rtc", O_RDONLY);
1008
    if (rtc_fd < 0)
1009
        return -1;
1010
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1011
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1012
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1013
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1014
        goto fail;
1015
    }
1016
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1017
    fail:
1018
        close(rtc_fd);
1019
        return -1;
1020
    }
1021
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1022
    return 0;
1023
}
1024

    
1025
#else
1026

    
1027
static int start_rtc_timer(void)
1028
{
1029
    return -1;
1030
}
1031

    
1032
#endif /* !defined(__linux__) */
1033

    
1034
#endif /* !defined(_WIN32) */
1035

    
1036
static void init_timer_alarm(void)
1037
{
1038
#ifdef _WIN32
1039
    {
1040
        int count=0;
1041
        TIMECAPS tc;
1042

    
1043
        ZeroMemory(&tc, sizeof(TIMECAPS));
1044
        timeGetDevCaps(&tc, sizeof(TIMECAPS));
1045
        if (period < tc.wPeriodMin)
1046
            period = tc.wPeriodMin;
1047
        timeBeginPeriod(period);
1048
        timerID = timeSetEvent(1,     // interval (ms)
1049
                               period,     // resolution
1050
                               host_alarm_handler, // function
1051
                               (DWORD)&count,  // user parameter
1052
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1053
         if( !timerID ) {
1054
            perror("failed timer alarm");
1055
            exit(1);
1056
         }
1057
        host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1058
        if (!host_alarm) {
1059
            perror("failed CreateEvent");
1060
            exit(1);
1061
        }
1062
        qemu_add_wait_object(host_alarm, NULL, NULL);
1063
    }
1064
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1065
#else
1066
    {
1067
        struct sigaction act;
1068
        struct itimerval itv;
1069
        
1070
        /* get times() syscall frequency */
1071
        timer_freq = sysconf(_SC_CLK_TCK);
1072
        
1073
        /* timer signal */
1074
        sigfillset(&act.sa_mask);
1075
       act.sa_flags = 0;
1076
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1077
        act.sa_flags |= SA_ONSTACK;
1078
#endif
1079
        act.sa_handler = host_alarm_handler;
1080
        sigaction(SIGALRM, &act, NULL);
1081

    
1082
        itv.it_interval.tv_sec = 0;
1083
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1084
        itv.it_value.tv_sec = 0;
1085
        itv.it_value.tv_usec = 10 * 1000;
1086
        setitimer(ITIMER_REAL, &itv, NULL);
1087
        /* we probe the tick duration of the kernel to inform the user if
1088
           the emulated kernel requested a too high timer frequency */
1089
        getitimer(ITIMER_REAL, &itv);
1090

    
1091
#if defined(__linux__)
1092
        /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1093
           have timers with 1 ms resolution. The correct solution will
1094
           be to use the POSIX real time timers available in recent
1095
           2.6 kernels */
1096
        if (itv.it_interval.tv_usec > 1000 || 1) {
1097
            /* try to use /dev/rtc to have a faster timer */
1098
            if (start_rtc_timer() < 0)
1099
                goto use_itimer;
1100
            /* disable itimer */
1101
            itv.it_interval.tv_sec = 0;
1102
            itv.it_interval.tv_usec = 0;
1103
            itv.it_value.tv_sec = 0;
1104
            itv.it_value.tv_usec = 0;
1105
            setitimer(ITIMER_REAL, &itv, NULL);
1106

    
1107
            /* use the RTC */
1108
            sigaction(SIGIO, &act, NULL);
1109
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1110
            fcntl(rtc_fd, F_SETOWN, getpid());
1111
        } else 
1112
#endif /* defined(__linux__) */
1113
        {
1114
        use_itimer:
1115
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1116
                                   PIT_FREQ) / 1000000;
1117
        }
1118
    }
1119
#endif
1120
}
1121

    
1122
void quit_timers(void)
1123
{
1124
#ifdef _WIN32
1125
    timeKillEvent(timerID);
1126
    timeEndPeriod(period);
1127
    if (host_alarm) {
1128
        CloseHandle(host_alarm);
1129
        host_alarm = NULL;
1130
    }
1131
#endif
1132
}
1133

    
1134
/***********************************************************/
1135
/* character device */
1136

    
1137
static void qemu_chr_event(CharDriverState *s, int event)
1138
{
1139
    if (!s->chr_event)
1140
        return;
1141
    s->chr_event(s->handler_opaque, event);
1142
}
1143

    
1144
static void qemu_chr_reset_bh(void *opaque)
1145
{
1146
    CharDriverState *s = opaque;
1147
    qemu_chr_event(s, CHR_EVENT_RESET);
1148
    qemu_bh_delete(s->bh);
1149
    s->bh = NULL;
1150
}
1151

    
1152
void qemu_chr_reset(CharDriverState *s)
1153
{
1154
    if (s->bh == NULL) {
1155
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1156
        qemu_bh_schedule(s->bh);
1157
    }
1158
}
1159

    
1160
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1161
{
1162
    return s->chr_write(s, buf, len);
1163
}
1164

    
1165
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1166
{
1167
    if (!s->chr_ioctl)
1168
        return -ENOTSUP;
1169
    return s->chr_ioctl(s, cmd, arg);
1170
}
1171

    
1172
int qemu_chr_can_read(CharDriverState *s)
1173
{
1174
    if (!s->chr_can_read)
1175
        return 0;
1176
    return s->chr_can_read(s->handler_opaque);
1177
}
1178

    
1179
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1180
{
1181
    s->chr_read(s->handler_opaque, buf, len);
1182
}
1183

    
1184

    
1185
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1186
{
1187
    char buf[4096];
1188
    va_list ap;
1189
    va_start(ap, fmt);
1190
    vsnprintf(buf, sizeof(buf), fmt, ap);
1191
    qemu_chr_write(s, buf, strlen(buf));
1192
    va_end(ap);
1193
}
1194

    
1195
void qemu_chr_send_event(CharDriverState *s, int event)
1196
{
1197
    if (s->chr_send_event)
1198
        s->chr_send_event(s, event);
1199
}
1200

    
1201
void qemu_chr_add_handlers(CharDriverState *s, 
1202
                           IOCanRWHandler *fd_can_read, 
1203
                           IOReadHandler *fd_read,
1204
                           IOEventHandler *fd_event,
1205
                           void *opaque)
1206
{
1207
    s->chr_can_read = fd_can_read;
1208
    s->chr_read = fd_read;
1209
    s->chr_event = fd_event;
1210
    s->handler_opaque = opaque;
1211
    if (s->chr_update_read_handler)
1212
        s->chr_update_read_handler(s);
1213
}
1214
             
1215
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1216
{
1217
    return len;
1218
}
1219

    
1220
static CharDriverState *qemu_chr_open_null(void)
1221
{
1222
    CharDriverState *chr;
1223

    
1224
    chr = qemu_mallocz(sizeof(CharDriverState));
1225
    if (!chr)
1226
        return NULL;
1227
    chr->chr_write = null_chr_write;
1228
    return chr;
1229
}
1230

    
1231
#ifdef _WIN32
1232

    
1233
static void socket_cleanup(void)
1234
{
1235
    WSACleanup();
1236
}
1237

    
1238
static int socket_init(void)
1239
{
1240
    WSADATA Data;
1241
    int ret, err;
1242

    
1243
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1244
    if (ret != 0) {
1245
        err = WSAGetLastError();
1246
        fprintf(stderr, "WSAStartup: %d\n", err);
1247
        return -1;
1248
    }
1249
    atexit(socket_cleanup);
1250
    return 0;
1251
}
1252

    
1253
static int send_all(int fd, const uint8_t *buf, int len1)
1254
{
1255
    int ret, len;
1256
    
1257
    len = len1;
1258
    while (len > 0) {
1259
        ret = send(fd, buf, len, 0);
1260
        if (ret < 0) {
1261
            int errno;
1262
            errno = WSAGetLastError();
1263
            if (errno != WSAEWOULDBLOCK) {
1264
                return -1;
1265
            }
1266
        } else if (ret == 0) {
1267
            break;
1268
        } else {
1269
            buf += ret;
1270
            len -= ret;
1271
        }
1272
    }
1273
    return len1 - len;
1274
}
1275

    
1276
void socket_set_nonblock(int fd)
1277
{
1278
    unsigned long opt = 1;
1279
    ioctlsocket(fd, FIONBIO, &opt);
1280
}
1281

    
1282
#else
1283

    
1284
static int unix_write(int fd, const uint8_t *buf, int len1)
1285
{
1286
    int ret, len;
1287

    
1288
    len = len1;
1289
    while (len > 0) {
1290
        ret = write(fd, buf, len);
1291
        if (ret < 0) {
1292
            if (errno != EINTR && errno != EAGAIN)
1293
                return -1;
1294
        } else if (ret == 0) {
1295
            break;
1296
        } else {
1297
            buf += ret;
1298
            len -= ret;
1299
        }
1300
    }
1301
    return len1 - len;
1302
}
1303

    
1304
static inline int send_all(int fd, const uint8_t *buf, int len1)
1305
{
1306
    return unix_write(fd, buf, len1);
1307
}
1308

    
1309
void socket_set_nonblock(int fd)
1310
{
1311
    fcntl(fd, F_SETFL, O_NONBLOCK);
1312
}
1313
#endif /* !_WIN32 */
1314

    
1315
#ifndef _WIN32
1316

    
1317
typedef struct {
1318
    int fd_in, fd_out;
1319
    int max_size;
1320
} FDCharDriver;
1321

    
1322
#define STDIO_MAX_CLIENTS 2
1323

    
1324
static int stdio_nb_clients;
1325
static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1326

    
1327
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1328
{
1329
    FDCharDriver *s = chr->opaque;
1330
    return unix_write(s->fd_out, buf, len);
1331
}
1332

    
1333
static int fd_chr_read_poll(void *opaque)
1334
{
1335
    CharDriverState *chr = opaque;
1336
    FDCharDriver *s = chr->opaque;
1337

    
1338
    s->max_size = qemu_chr_can_read(chr);
1339
    return s->max_size;
1340
}
1341

    
1342
static void fd_chr_read(void *opaque)
1343
{
1344
    CharDriverState *chr = opaque;
1345
    FDCharDriver *s = chr->opaque;
1346
    int size, len;
1347
    uint8_t buf[1024];
1348
    
1349
    len = sizeof(buf);
1350
    if (len > s->max_size)
1351
        len = s->max_size;
1352
    if (len == 0)
1353
        return;
1354
    size = read(s->fd_in, buf, len);
1355
    if (size == 0) {
1356
        /* FD has been closed. Remove it from the active list.  */
1357
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1358
        return;
1359
    }
1360
    if (size > 0) {
1361
        qemu_chr_read(chr, buf, size);
1362
    }
1363
}
1364

    
1365
static void fd_chr_update_read_handler(CharDriverState *chr)
1366
{
1367
    FDCharDriver *s = chr->opaque;
1368

    
1369
    if (s->fd_in >= 0) {
1370
        if (nographic && s->fd_in == 0) {
1371
        } else {
1372
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1373
                                 fd_chr_read, NULL, chr);
1374
        }
1375
    }
1376
}
1377

    
1378
/* open a character device to a unix fd */
1379
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1380
{
1381
    CharDriverState *chr;
1382
    FDCharDriver *s;
1383

    
1384
    chr = qemu_mallocz(sizeof(CharDriverState));
1385
    if (!chr)
1386
        return NULL;
1387
    s = qemu_mallocz(sizeof(FDCharDriver));
1388
    if (!s) {
1389
        free(chr);
1390
        return NULL;
1391
    }
1392
    s->fd_in = fd_in;
1393
    s->fd_out = fd_out;
1394
    chr->opaque = s;
1395
    chr->chr_write = fd_chr_write;
1396
    chr->chr_update_read_handler = fd_chr_update_read_handler;
1397

    
1398
    qemu_chr_reset(chr);
1399

    
1400
    return chr;
1401
}
1402

    
1403
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1404
{
1405
    int fd_out;
1406

    
1407
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1408
    if (fd_out < 0)
1409
        return NULL;
1410
    return qemu_chr_open_fd(-1, fd_out);
1411
}
1412

    
1413
static CharDriverState *qemu_chr_open_pipe(const char *filename)
1414
{
1415
    int fd_in, fd_out;
1416
    char filename_in[256], filename_out[256];
1417

    
1418
    snprintf(filename_in, 256, "%s.in", filename);
1419
    snprintf(filename_out, 256, "%s.out", filename);
1420
    fd_in = open(filename_in, O_RDWR | O_BINARY);
1421
    fd_out = open(filename_out, O_RDWR | O_BINARY);
1422
    if (fd_in < 0 || fd_out < 0) {
1423
        if (fd_in >= 0)
1424
            close(fd_in);
1425
        if (fd_out >= 0)
1426
            close(fd_out);
1427
        fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1428
        if (fd_in < 0)
1429
            return NULL;
1430
    }
1431
    return qemu_chr_open_fd(fd_in, fd_out);
1432
}
1433

    
1434

    
1435
/* for STDIO, we handle the case where several clients use it
1436
   (nographic mode) */
1437

    
1438
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1439

    
1440
#define TERM_FIFO_MAX_SIZE 1
1441

    
1442
static int term_got_escape, client_index;
1443
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1444
static int term_fifo_size;
1445
static int term_timestamps;
1446
static int64_t term_timestamps_start;
1447

    
1448
void term_print_help(void)
1449
{
1450
    printf("\n"
1451
           "C-a h    print this help\n"
1452
           "C-a x    exit emulator\n"
1453
           "C-a s    save disk data back to file (if -snapshot)\n"
1454
           "C-a b    send break (magic sysrq)\n"
1455
           "C-a t    toggle console timestamps\n"
1456
           "C-a c    switch between console and monitor\n"
1457
           "C-a C-a  send C-a\n"
1458
           );
1459
}
1460

    
1461
/* called when a char is received */
1462
static void stdio_received_byte(int ch)
1463
{
1464
    if (term_got_escape) {
1465
        term_got_escape = 0;
1466
        switch(ch) {
1467
        case 'h':
1468
            term_print_help();
1469
            break;
1470
        case 'x':
1471
            exit(0);
1472
            break;
1473
        case 's': 
1474
            {
1475
                int i;
1476
                for (i = 0; i < MAX_DISKS; i++) {
1477
                    if (bs_table[i])
1478
                        bdrv_commit(bs_table[i]);
1479
                }
1480
            }
1481
            break;
1482
        case 'b':
1483
            if (client_index < stdio_nb_clients) {
1484
                CharDriverState *chr;
1485
                FDCharDriver *s;
1486

    
1487
                chr = stdio_clients[client_index];
1488
                s = chr->opaque;
1489
                qemu_chr_event(chr, CHR_EVENT_BREAK);
1490
            }
1491
            break;
1492
        case 'c':
1493
            client_index++;
1494
            if (client_index >= stdio_nb_clients)
1495
                client_index = 0;
1496
            if (client_index == 0) {
1497
                /* send a new line in the monitor to get the prompt */
1498
                ch = '\r';
1499
                goto send_char;
1500
            }
1501
            break;
1502
        case 't':
1503
            term_timestamps = !term_timestamps;
1504
            term_timestamps_start = -1;
1505
            break;
1506
        case TERM_ESCAPE:
1507
            goto send_char;
1508
        }
1509
    } else if (ch == TERM_ESCAPE) {
1510
        term_got_escape = 1;
1511
    } else {
1512
    send_char:
1513
        if (client_index < stdio_nb_clients) {
1514
            uint8_t buf[1];
1515
            CharDriverState *chr;
1516
            
1517
            chr = stdio_clients[client_index];
1518
            if (qemu_chr_can_read(chr) > 0) {
1519
                buf[0] = ch;
1520
                qemu_chr_read(chr, buf, 1);
1521
            } else if (term_fifo_size == 0) {
1522
                term_fifo[term_fifo_size++] = ch;
1523
            }
1524
        }
1525
    }
1526
}
1527

    
1528
static int stdio_read_poll(void *opaque)
1529
{
1530
    CharDriverState *chr;
1531

    
1532
    if (client_index < stdio_nb_clients) {
1533
        chr = stdio_clients[client_index];
1534
        /* try to flush the queue if needed */
1535
        if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1536
            qemu_chr_read(chr, term_fifo, 1);
1537
            term_fifo_size = 0;
1538
        }
1539
        /* see if we can absorb more chars */
1540
        if (term_fifo_size == 0)
1541
            return 1;
1542
        else
1543
            return 0;
1544
    } else {
1545
        return 1;
1546
    }
1547
}
1548

    
1549
static void stdio_read(void *opaque)
1550
{
1551
    int size;
1552
    uint8_t buf[1];
1553
    
1554
    size = read(0, buf, 1);
1555
    if (size == 0) {
1556
        /* stdin has been closed. Remove it from the active list.  */
1557
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1558
        return;
1559
    }
1560
    if (size > 0)
1561
        stdio_received_byte(buf[0]);
1562
}
1563

    
1564
static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1565
{
1566
    FDCharDriver *s = chr->opaque;
1567
    if (!term_timestamps) {
1568
        return unix_write(s->fd_out, buf, len);
1569
    } else {
1570
        int i;
1571
        char buf1[64];
1572

    
1573
        for(i = 0; i < len; i++) {
1574
            unix_write(s->fd_out, buf + i, 1);
1575
            if (buf[i] == '\n') {
1576
                int64_t ti;
1577
                int secs;
1578

    
1579
                ti = get_clock();
1580
                if (term_timestamps_start == -1)
1581
                    term_timestamps_start = ti;
1582
                ti -= term_timestamps_start;
1583
                secs = ti / 1000000000;
1584
                snprintf(buf1, sizeof(buf1), 
1585
                         "[%02d:%02d:%02d.%03d] ",
1586
                         secs / 3600,
1587
                         (secs / 60) % 60,
1588
                         secs % 60,
1589
                         (int)((ti / 1000000) % 1000));
1590
                unix_write(s->fd_out, buf1, strlen(buf1));
1591
            }
1592
        }
1593
        return len;
1594
    }
1595
}
1596

    
1597
/* init terminal so that we can grab keys */
1598
static struct termios oldtty;
1599
static int old_fd0_flags;
1600

    
1601
static void term_exit(void)
1602
{
1603
    tcsetattr (0, TCSANOW, &oldtty);
1604
    fcntl(0, F_SETFL, old_fd0_flags);
1605
}
1606

    
1607
static void term_init(void)
1608
{
1609
    struct termios tty;
1610

    
1611
    tcgetattr (0, &tty);
1612
    oldtty = tty;
1613
    old_fd0_flags = fcntl(0, F_GETFL);
1614

    
1615
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1616
                          |INLCR|IGNCR|ICRNL|IXON);
1617
    tty.c_oflag |= OPOST;
1618
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1619
    /* if graphical mode, we allow Ctrl-C handling */
1620
    if (nographic)
1621
        tty.c_lflag &= ~ISIG;
1622
    tty.c_cflag &= ~(CSIZE|PARENB);
1623
    tty.c_cflag |= CS8;
1624
    tty.c_cc[VMIN] = 1;
1625
    tty.c_cc[VTIME] = 0;
1626
    
1627
    tcsetattr (0, TCSANOW, &tty);
1628

    
1629
    atexit(term_exit);
1630

    
1631
    fcntl(0, F_SETFL, O_NONBLOCK);
1632
}
1633

    
1634
static CharDriverState *qemu_chr_open_stdio(void)
1635
{
1636
    CharDriverState *chr;
1637

    
1638
    if (nographic) {
1639
        if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1640
            return NULL;
1641
        chr = qemu_chr_open_fd(0, 1);
1642
        chr->chr_write = stdio_write;
1643
        if (stdio_nb_clients == 0)
1644
            qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1645
        client_index = stdio_nb_clients;
1646
    } else {
1647
        if (stdio_nb_clients != 0)
1648
            return NULL;
1649
        chr = qemu_chr_open_fd(0, 1);
1650
    }
1651
    stdio_clients[stdio_nb_clients++] = chr;
1652
    if (stdio_nb_clients == 1) {
1653
        /* set the terminal in raw mode */
1654
        term_init();
1655
    }
1656
    return chr;
1657
}
1658

    
1659
#if defined(__linux__)
1660
static CharDriverState *qemu_chr_open_pty(void)
1661
{
1662
    struct termios tty;
1663
    char slave_name[1024];
1664
    int master_fd, slave_fd;
1665
    
1666
    /* Not satisfying */
1667
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1668
        return NULL;
1669
    }
1670
    
1671
    /* Disabling local echo and line-buffered output */
1672
    tcgetattr (master_fd, &tty);
1673
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1674
    tty.c_cc[VMIN] = 1;
1675
    tty.c_cc[VTIME] = 0;
1676
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1677

    
1678
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1679
    return qemu_chr_open_fd(master_fd, master_fd);
1680
}
1681

    
1682
static void tty_serial_init(int fd, int speed, 
1683
                            int parity, int data_bits, int stop_bits)
1684
{
1685
    struct termios tty;
1686
    speed_t spd;
1687

    
1688
#if 0
1689
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1690
           speed, parity, data_bits, stop_bits);
1691
#endif
1692
    tcgetattr (fd, &tty);
1693

    
1694
    switch(speed) {
1695
    case 50:
1696
        spd = B50;
1697
        break;
1698
    case 75:
1699
        spd = B75;
1700
        break;
1701
    case 300:
1702
        spd = B300;
1703
        break;
1704
    case 600:
1705
        spd = B600;
1706
        break;
1707
    case 1200:
1708
        spd = B1200;
1709
        break;
1710
    case 2400:
1711
        spd = B2400;
1712
        break;
1713
    case 4800:
1714
        spd = B4800;
1715
        break;
1716
    case 9600:
1717
        spd = B9600;
1718
        break;
1719
    case 19200:
1720
        spd = B19200;
1721
        break;
1722
    case 38400:
1723
        spd = B38400;
1724
        break;
1725
    case 57600:
1726
        spd = B57600;
1727
        break;
1728
    default:
1729
    case 115200:
1730
        spd = B115200;
1731
        break;
1732
    }
1733

    
1734
    cfsetispeed(&tty, spd);
1735
    cfsetospeed(&tty, spd);
1736

    
1737
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1738
                          |INLCR|IGNCR|ICRNL|IXON);
1739
    tty.c_oflag |= OPOST;
1740
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1741
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1742
    switch(data_bits) {
1743
    default:
1744
    case 8:
1745
        tty.c_cflag |= CS8;
1746
        break;
1747
    case 7:
1748
        tty.c_cflag |= CS7;
1749
        break;
1750
    case 6:
1751
        tty.c_cflag |= CS6;
1752
        break;
1753
    case 5:
1754
        tty.c_cflag |= CS5;
1755
        break;
1756
    }
1757
    switch(parity) {
1758
    default:
1759
    case 'N':
1760
        break;
1761
    case 'E':
1762
        tty.c_cflag |= PARENB;
1763
        break;
1764
    case 'O':
1765
        tty.c_cflag |= PARENB | PARODD;
1766
        break;
1767
    }
1768
    if (stop_bits == 2)
1769
        tty.c_cflag |= CSTOPB;
1770
    
1771
    tcsetattr (fd, TCSANOW, &tty);
1772
}
1773

    
1774
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1775
{
1776
    FDCharDriver *s = chr->opaque;
1777
    
1778
    switch(cmd) {
1779
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1780
        {
1781
            QEMUSerialSetParams *ssp = arg;
1782
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1783
                            ssp->data_bits, ssp->stop_bits);
1784
        }
1785
        break;
1786
    case CHR_IOCTL_SERIAL_SET_BREAK:
1787
        {
1788
            int enable = *(int *)arg;
1789
            if (enable)
1790
                tcsendbreak(s->fd_in, 1);
1791
        }
1792
        break;
1793
    default:
1794
        return -ENOTSUP;
1795
    }
1796
    return 0;
1797
}
1798

    
1799
static CharDriverState *qemu_chr_open_tty(const char *filename)
1800
{
1801
    CharDriverState *chr;
1802
    int fd;
1803

    
1804
    fd = open(filename, O_RDWR | O_NONBLOCK);
1805
    if (fd < 0)
1806
        return NULL;
1807
    fcntl(fd, F_SETFL, O_NONBLOCK);
1808
    tty_serial_init(fd, 115200, 'N', 8, 1);
1809
    chr = qemu_chr_open_fd(fd, fd);
1810
    if (!chr)
1811
        return NULL;
1812
    chr->chr_ioctl = tty_serial_ioctl;
1813
    qemu_chr_reset(chr);
1814
    return chr;
1815
}
1816

    
1817
typedef struct {
1818
    int fd;
1819
    int mode;
1820
} ParallelCharDriver;
1821

    
1822
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1823
{
1824
    if (s->mode != mode) {
1825
        int m = mode;
1826
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1827
            return 0;
1828
        s->mode = mode;
1829
    }
1830
    return 1;
1831
}
1832

    
1833
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1834
{
1835
    ParallelCharDriver *drv = chr->opaque;
1836
    int fd = drv->fd;
1837
    uint8_t b;
1838

    
1839
    switch(cmd) {
1840
    case CHR_IOCTL_PP_READ_DATA:
1841
        if (ioctl(fd, PPRDATA, &b) < 0)
1842
            return -ENOTSUP;
1843
        *(uint8_t *)arg = b;
1844
        break;
1845
    case CHR_IOCTL_PP_WRITE_DATA:
1846
        b = *(uint8_t *)arg;
1847
        if (ioctl(fd, PPWDATA, &b) < 0)
1848
            return -ENOTSUP;
1849
        break;
1850
    case CHR_IOCTL_PP_READ_CONTROL:
1851
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1852
            return -ENOTSUP;
1853
        /* Linux gives only the lowest bits, and no way to know data
1854
           direction! For better compatibility set the fixed upper
1855
           bits. */
1856
        *(uint8_t *)arg = b | 0xc0;
1857
        break;
1858
    case CHR_IOCTL_PP_WRITE_CONTROL:
1859
        b = *(uint8_t *)arg;
1860
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1861
            return -ENOTSUP;
1862
        break;
1863
    case CHR_IOCTL_PP_READ_STATUS:
1864
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1865
            return -ENOTSUP;
1866
        *(uint8_t *)arg = b;
1867
        break;
1868
    case CHR_IOCTL_PP_EPP_READ_ADDR:
1869
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1870
            struct ParallelIOArg *parg = arg;
1871
            int n = read(fd, parg->buffer, parg->count);
1872
            if (n != parg->count) {
1873
                return -EIO;
1874
            }
1875
        }
1876
        break;
1877
    case CHR_IOCTL_PP_EPP_READ:
1878
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1879
            struct ParallelIOArg *parg = arg;
1880
            int n = read(fd, parg->buffer, parg->count);
1881
            if (n != parg->count) {
1882
                return -EIO;
1883
            }
1884
        }
1885
        break;
1886
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1887
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1888
            struct ParallelIOArg *parg = arg;
1889
            int n = write(fd, parg->buffer, parg->count);
1890
            if (n != parg->count) {
1891
                return -EIO;
1892
            }
1893
        }
1894
        break;
1895
    case CHR_IOCTL_PP_EPP_WRITE:
1896
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1897
            struct ParallelIOArg *parg = arg;
1898
            int n = write(fd, parg->buffer, parg->count);
1899
            if (n != parg->count) {
1900
                return -EIO;
1901
            }
1902
        }
1903
        break;
1904
    default:
1905
        return -ENOTSUP;
1906
    }
1907
    return 0;
1908
}
1909

    
1910
static void pp_close(CharDriverState *chr)
1911
{
1912
    ParallelCharDriver *drv = chr->opaque;
1913
    int fd = drv->fd;
1914

    
1915
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
1916
    ioctl(fd, PPRELEASE);
1917
    close(fd);
1918
    qemu_free(drv);
1919
}
1920

    
1921
static CharDriverState *qemu_chr_open_pp(const char *filename)
1922
{
1923
    CharDriverState *chr;
1924
    ParallelCharDriver *drv;
1925
    int fd;
1926

    
1927
    fd = open(filename, O_RDWR);
1928
    if (fd < 0)
1929
        return NULL;
1930

    
1931
    if (ioctl(fd, PPCLAIM) < 0) {
1932
        close(fd);
1933
        return NULL;
1934
    }
1935

    
1936
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
1937
    if (!drv) {
1938
        close(fd);
1939
        return NULL;
1940
    }
1941
    drv->fd = fd;
1942
    drv->mode = IEEE1284_MODE_COMPAT;
1943

    
1944
    chr = qemu_mallocz(sizeof(CharDriverState));
1945
    if (!chr) {
1946
        qemu_free(drv);
1947
        close(fd);
1948
        return NULL;
1949
    }
1950
    chr->chr_write = null_chr_write;
1951
    chr->chr_ioctl = pp_ioctl;
1952
    chr->chr_close = pp_close;
1953
    chr->opaque = drv;
1954

    
1955
    qemu_chr_reset(chr);
1956

    
1957
    return chr;
1958
}
1959

    
1960
#else
1961
static CharDriverState *qemu_chr_open_pty(void)
1962
{
1963
    return NULL;
1964
}
1965
#endif
1966

    
1967
#endif /* !defined(_WIN32) */
1968

    
1969
#ifdef _WIN32
1970
typedef struct {
1971
    int max_size;
1972
    HANDLE hcom, hrecv, hsend;
1973
    OVERLAPPED orecv, osend;
1974
    BOOL fpipe;
1975
    DWORD len;
1976
} WinCharState;
1977

    
1978
#define NSENDBUF 2048
1979
#define NRECVBUF 2048
1980
#define MAXCONNECT 1
1981
#define NTIMEOUT 5000
1982

    
1983
static int win_chr_poll(void *opaque);
1984
static int win_chr_pipe_poll(void *opaque);
1985

    
1986
static void win_chr_close(CharDriverState *chr)
1987
{
1988
    WinCharState *s = chr->opaque;
1989

    
1990
    if (s->hsend) {
1991
        CloseHandle(s->hsend);
1992
        s->hsend = NULL;
1993
    }
1994
    if (s->hrecv) {
1995
        CloseHandle(s->hrecv);
1996
        s->hrecv = NULL;
1997
    }
1998
    if (s->hcom) {
1999
        CloseHandle(s->hcom);
2000
        s->hcom = NULL;
2001
    }
2002
    if (s->fpipe)
2003
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2004
    else
2005
        qemu_del_polling_cb(win_chr_poll, chr);
2006
}
2007

    
2008
static int win_chr_init(CharDriverState *chr, const char *filename)
2009
{
2010
    WinCharState *s = chr->opaque;
2011
    COMMCONFIG comcfg;
2012
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2013
    COMSTAT comstat;
2014
    DWORD size;
2015
    DWORD err;
2016
    
2017
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2018
    if (!s->hsend) {
2019
        fprintf(stderr, "Failed CreateEvent\n");
2020
        goto fail;
2021
    }
2022
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2023
    if (!s->hrecv) {
2024
        fprintf(stderr, "Failed CreateEvent\n");
2025
        goto fail;
2026
    }
2027

    
2028
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2029
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2030
    if (s->hcom == INVALID_HANDLE_VALUE) {
2031
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2032
        s->hcom = NULL;
2033
        goto fail;
2034
    }
2035
    
2036
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2037
        fprintf(stderr, "Failed SetupComm\n");
2038
        goto fail;
2039
    }
2040
    
2041
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2042
    size = sizeof(COMMCONFIG);
2043
    GetDefaultCommConfig(filename, &comcfg, &size);
2044
    comcfg.dcb.DCBlength = sizeof(DCB);
2045
    CommConfigDialog(filename, NULL, &comcfg);
2046

    
2047
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2048
        fprintf(stderr, "Failed SetCommState\n");
2049
        goto fail;
2050
    }
2051

    
2052
    if (!SetCommMask(s->hcom, EV_ERR)) {
2053
        fprintf(stderr, "Failed SetCommMask\n");
2054
        goto fail;
2055
    }
2056

    
2057
    cto.ReadIntervalTimeout = MAXDWORD;
2058
    if (!SetCommTimeouts(s->hcom, &cto)) {
2059
        fprintf(stderr, "Failed SetCommTimeouts\n");
2060
        goto fail;
2061
    }
2062
    
2063
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2064
        fprintf(stderr, "Failed ClearCommError\n");
2065
        goto fail;
2066
    }
2067
    qemu_add_polling_cb(win_chr_poll, chr);
2068
    return 0;
2069

    
2070
 fail:
2071
    win_chr_close(chr);
2072
    return -1;
2073
}
2074

    
2075
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2076
{
2077
    WinCharState *s = chr->opaque;
2078
    DWORD len, ret, size, err;
2079

    
2080
    len = len1;
2081
    ZeroMemory(&s->osend, sizeof(s->osend));
2082
    s->osend.hEvent = s->hsend;
2083
    while (len > 0) {
2084
        if (s->hsend)
2085
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2086
        else
2087
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2088
        if (!ret) {
2089
            err = GetLastError();
2090
            if (err == ERROR_IO_PENDING) {
2091
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2092
                if (ret) {
2093
                    buf += size;
2094
                    len -= size;
2095
                } else {
2096
                    break;
2097
                }
2098
            } else {
2099
                break;
2100
            }
2101
        } else {
2102
            buf += size;
2103
            len -= size;
2104
        }
2105
    }
2106
    return len1 - len;
2107
}
2108

    
2109
static int win_chr_read_poll(CharDriverState *chr)
2110
{
2111
    WinCharState *s = chr->opaque;
2112

    
2113
    s->max_size = qemu_chr_can_read(chr);
2114
    return s->max_size;
2115
}
2116

    
2117
static void win_chr_readfile(CharDriverState *chr)
2118
{
2119
    WinCharState *s = chr->opaque;
2120
    int ret, err;
2121
    uint8_t buf[1024];
2122
    DWORD size;
2123
    
2124
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2125
    s->orecv.hEvent = s->hrecv;
2126
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2127
    if (!ret) {
2128
        err = GetLastError();
2129
        if (err == ERROR_IO_PENDING) {
2130
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2131
        }
2132
    }
2133

    
2134
    if (size > 0) {
2135
        qemu_chr_read(chr, buf, size);
2136
    }
2137
}
2138

    
2139
static void win_chr_read(CharDriverState *chr)
2140
{
2141
    WinCharState *s = chr->opaque;
2142

    
2143
    if (s->len > s->max_size)
2144
        s->len = s->max_size;
2145
    if (s->len == 0)
2146
        return;
2147
    
2148
    win_chr_readfile(chr);
2149
}
2150

    
2151
static int win_chr_poll(void *opaque)
2152
{
2153
    CharDriverState *chr = opaque;
2154
    WinCharState *s = chr->opaque;
2155
    COMSTAT status;
2156
    DWORD comerr;
2157
    
2158
    ClearCommError(s->hcom, &comerr, &status);
2159
    if (status.cbInQue > 0) {
2160
        s->len = status.cbInQue;
2161
        win_chr_read_poll(chr);
2162
        win_chr_read(chr);
2163
        return 1;
2164
    }
2165
    return 0;
2166
}
2167

    
2168
static CharDriverState *qemu_chr_open_win(const char *filename)
2169
{
2170
    CharDriverState *chr;
2171
    WinCharState *s;
2172
    
2173
    chr = qemu_mallocz(sizeof(CharDriverState));
2174
    if (!chr)
2175
        return NULL;
2176
    s = qemu_mallocz(sizeof(WinCharState));
2177
    if (!s) {
2178
        free(chr);
2179
        return NULL;
2180
    }
2181
    chr->opaque = s;
2182
    chr->chr_write = win_chr_write;
2183
    chr->chr_close = win_chr_close;
2184

    
2185
    if (win_chr_init(chr, filename) < 0) {
2186
        free(s);
2187
        free(chr);
2188
        return NULL;
2189
    }
2190
    qemu_chr_reset(chr);
2191
    return chr;
2192
}
2193

    
2194
static int win_chr_pipe_poll(void *opaque)
2195
{
2196
    CharDriverState *chr = opaque;
2197
    WinCharState *s = chr->opaque;
2198
    DWORD size;
2199

    
2200
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2201
    if (size > 0) {
2202
        s->len = size;
2203
        win_chr_read_poll(chr);
2204
        win_chr_read(chr);
2205
        return 1;
2206
    }
2207
    return 0;
2208
}
2209

    
2210
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2211
{
2212
    WinCharState *s = chr->opaque;
2213
    OVERLAPPED ov;
2214
    int ret;
2215
    DWORD size;
2216
    char openname[256];
2217
    
2218
    s->fpipe = TRUE;
2219

    
2220
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2221
    if (!s->hsend) {
2222
        fprintf(stderr, "Failed CreateEvent\n");
2223
        goto fail;
2224
    }
2225
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2226
    if (!s->hrecv) {
2227
        fprintf(stderr, "Failed CreateEvent\n");
2228
        goto fail;
2229
    }
2230
    
2231
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2232
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2233
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2234
                              PIPE_WAIT,
2235
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2236
    if (s->hcom == INVALID_HANDLE_VALUE) {
2237
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2238
        s->hcom = NULL;
2239
        goto fail;
2240
    }
2241

    
2242
    ZeroMemory(&ov, sizeof(ov));
2243
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2244
    ret = ConnectNamedPipe(s->hcom, &ov);
2245
    if (ret) {
2246
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2247
        goto fail;
2248
    }
2249

    
2250
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2251
    if (!ret) {
2252
        fprintf(stderr, "Failed GetOverlappedResult\n");
2253
        if (ov.hEvent) {
2254
            CloseHandle(ov.hEvent);
2255
            ov.hEvent = NULL;
2256
        }
2257
        goto fail;
2258
    }
2259

    
2260
    if (ov.hEvent) {
2261
        CloseHandle(ov.hEvent);
2262
        ov.hEvent = NULL;
2263
    }
2264
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2265
    return 0;
2266

    
2267
 fail:
2268
    win_chr_close(chr);
2269
    return -1;
2270
}
2271

    
2272

    
2273
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2274
{
2275
    CharDriverState *chr;
2276
    WinCharState *s;
2277

    
2278
    chr = qemu_mallocz(sizeof(CharDriverState));
2279
    if (!chr)
2280
        return NULL;
2281
    s = qemu_mallocz(sizeof(WinCharState));
2282
    if (!s) {
2283
        free(chr);
2284
        return NULL;
2285
    }
2286
    chr->opaque = s;
2287
    chr->chr_write = win_chr_write;
2288
    chr->chr_close = win_chr_close;
2289
    
2290
    if (win_chr_pipe_init(chr, filename) < 0) {
2291
        free(s);
2292
        free(chr);
2293
        return NULL;
2294
    }
2295
    qemu_chr_reset(chr);
2296
    return chr;
2297
}
2298

    
2299
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2300
{
2301
    CharDriverState *chr;
2302
    WinCharState *s;
2303

    
2304
    chr = qemu_mallocz(sizeof(CharDriverState));
2305
    if (!chr)
2306
        return NULL;
2307
    s = qemu_mallocz(sizeof(WinCharState));
2308
    if (!s) {
2309
        free(chr);
2310
        return NULL;
2311
    }
2312
    s->hcom = fd_out;
2313
    chr->opaque = s;
2314
    chr->chr_write = win_chr_write;
2315
    qemu_chr_reset(chr);
2316
    return chr;
2317
}
2318
    
2319
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2320
{
2321
    HANDLE fd_out;
2322
    
2323
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2324
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2325
    if (fd_out == INVALID_HANDLE_VALUE)
2326
        return NULL;
2327

    
2328
    return qemu_chr_open_win_file(fd_out);
2329
}
2330
#endif
2331

    
2332
/***********************************************************/
2333
/* UDP Net console */
2334

    
2335
typedef struct {
2336
    int fd;
2337
    struct sockaddr_in daddr;
2338
    char buf[1024];
2339
    int bufcnt;
2340
    int bufptr;
2341
    int max_size;
2342
} NetCharDriver;
2343

    
2344
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2345
{
2346
    NetCharDriver *s = chr->opaque;
2347

    
2348
    return sendto(s->fd, buf, len, 0,
2349
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2350
}
2351

    
2352
static int udp_chr_read_poll(void *opaque)
2353
{
2354
    CharDriverState *chr = opaque;
2355
    NetCharDriver *s = chr->opaque;
2356

    
2357
    s->max_size = qemu_chr_can_read(chr);
2358

    
2359
    /* If there were any stray characters in the queue process them
2360
     * first
2361
     */
2362
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2363
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2364
        s->bufptr++;
2365
        s->max_size = qemu_chr_can_read(chr);
2366
    }
2367
    return s->max_size;
2368
}
2369

    
2370
static void udp_chr_read(void *opaque)
2371
{
2372
    CharDriverState *chr = opaque;
2373
    NetCharDriver *s = chr->opaque;
2374

    
2375
    if (s->max_size == 0)
2376
        return;
2377
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2378
    s->bufptr = s->bufcnt;
2379
    if (s->bufcnt <= 0)
2380
        return;
2381

    
2382
    s->bufptr = 0;
2383
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2384
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2385
        s->bufptr++;
2386
        s->max_size = qemu_chr_can_read(chr);
2387
    }
2388
}
2389

    
2390
static void udp_chr_update_read_handler(CharDriverState *chr)
2391
{
2392
    NetCharDriver *s = chr->opaque;
2393

    
2394
    if (s->fd >= 0) {
2395
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2396
                             udp_chr_read, NULL, chr);
2397
    }
2398
}
2399

    
2400
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2401
#ifndef _WIN32
2402
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2403
#endif
2404
int parse_host_src_port(struct sockaddr_in *haddr,
2405
                        struct sockaddr_in *saddr,
2406
                        const char *str);
2407

    
2408
static CharDriverState *qemu_chr_open_udp(const char *def)
2409
{
2410
    CharDriverState *chr = NULL;
2411
    NetCharDriver *s = NULL;
2412
    int fd = -1;
2413
    struct sockaddr_in saddr;
2414

    
2415
    chr = qemu_mallocz(sizeof(CharDriverState));
2416
    if (!chr)
2417
        goto return_err;
2418
    s = qemu_mallocz(sizeof(NetCharDriver));
2419
    if (!s)
2420
        goto return_err;
2421

    
2422
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2423
    if (fd < 0) {
2424
        perror("socket(PF_INET, SOCK_DGRAM)");
2425
        goto return_err;
2426
    }
2427

    
2428
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2429
        printf("Could not parse: %s\n", def);
2430
        goto return_err;
2431
    }
2432

    
2433
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2434
    {
2435
        perror("bind");
2436
        goto return_err;
2437
    }
2438

    
2439
    s->fd = fd;
2440
    s->bufcnt = 0;
2441
    s->bufptr = 0;
2442
    chr->opaque = s;
2443
    chr->chr_write = udp_chr_write;
2444
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2445
    return chr;
2446

    
2447
return_err:
2448
    if (chr)
2449
        free(chr);
2450
    if (s)
2451
        free(s);
2452
    if (fd >= 0)
2453
        closesocket(fd);
2454
    return NULL;
2455
}
2456

    
2457
/***********************************************************/
2458
/* TCP Net console */
2459

    
2460
typedef struct {
2461
    int fd, listen_fd;
2462
    int connected;
2463
    int max_size;
2464
    int do_telnetopt;
2465
    int do_nodelay;
2466
    int is_unix;
2467
} TCPCharDriver;
2468

    
2469
static void tcp_chr_accept(void *opaque);
2470

    
2471
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2472
{
2473
    TCPCharDriver *s = chr->opaque;
2474
    if (s->connected) {
2475
        return send_all(s->fd, buf, len);
2476
    } else {
2477
        /* XXX: indicate an error ? */
2478
        return len;
2479
    }
2480
}
2481

    
2482
static int tcp_chr_read_poll(void *opaque)
2483
{
2484
    CharDriverState *chr = opaque;
2485
    TCPCharDriver *s = chr->opaque;
2486
    if (!s->connected)
2487
        return 0;
2488
    s->max_size = qemu_chr_can_read(chr);
2489
    return s->max_size;
2490
}
2491

    
2492
#define IAC 255
2493
#define IAC_BREAK 243
2494
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2495
                                      TCPCharDriver *s,
2496
                                      char *buf, int *size)
2497
{
2498
    /* Handle any telnet client's basic IAC options to satisfy char by
2499
     * char mode with no echo.  All IAC options will be removed from
2500
     * the buf and the do_telnetopt variable will be used to track the
2501
     * state of the width of the IAC information.
2502
     *
2503
     * IAC commands come in sets of 3 bytes with the exception of the
2504
     * "IAC BREAK" command and the double IAC.
2505
     */
2506

    
2507
    int i;
2508
    int j = 0;
2509

    
2510
    for (i = 0; i < *size; i++) {
2511
        if (s->do_telnetopt > 1) {
2512
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2513
                /* Double IAC means send an IAC */
2514
                if (j != i)
2515
                    buf[j] = buf[i];
2516
                j++;
2517
                s->do_telnetopt = 1;
2518
            } else {
2519
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2520
                    /* Handle IAC break commands by sending a serial break */
2521
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
2522
                    s->do_telnetopt++;
2523
                }
2524
                s->do_telnetopt++;
2525
            }
2526
            if (s->do_telnetopt >= 4) {
2527
                s->do_telnetopt = 1;
2528
            }
2529
        } else {
2530
            if ((unsigned char)buf[i] == IAC) {
2531
                s->do_telnetopt = 2;
2532
            } else {
2533
                if (j != i)
2534
                    buf[j] = buf[i];
2535
                j++;
2536
            }
2537
        }
2538
    }
2539
    *size = j;
2540
}
2541

    
2542
static void tcp_chr_read(void *opaque)
2543
{
2544
    CharDriverState *chr = opaque;
2545
    TCPCharDriver *s = chr->opaque;
2546
    uint8_t buf[1024];
2547
    int len, size;
2548

    
2549
    if (!s->connected || s->max_size <= 0)
2550
        return;
2551
    len = sizeof(buf);
2552
    if (len > s->max_size)
2553
        len = s->max_size;
2554
    size = recv(s->fd, buf, len, 0);
2555
    if (size == 0) {
2556
        /* connection closed */
2557
        s->connected = 0;
2558
        if (s->listen_fd >= 0) {
2559
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2560
        }
2561
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2562
        closesocket(s->fd);
2563
        s->fd = -1;
2564
    } else if (size > 0) {
2565
        if (s->do_telnetopt)
2566
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2567
        if (size > 0)
2568
            qemu_chr_read(chr, buf, size);
2569
    }
2570
}
2571

    
2572
static void tcp_chr_connect(void *opaque)
2573
{
2574
    CharDriverState *chr = opaque;
2575
    TCPCharDriver *s = chr->opaque;
2576

    
2577
    s->connected = 1;
2578
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2579
                         tcp_chr_read, NULL, chr);
2580
    qemu_chr_reset(chr);
2581
}
2582

    
2583
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2584
static void tcp_chr_telnet_init(int fd)
2585
{
2586
    char buf[3];
2587
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2588
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2589
    send(fd, (char *)buf, 3, 0);
2590
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2591
    send(fd, (char *)buf, 3, 0);
2592
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2593
    send(fd, (char *)buf, 3, 0);
2594
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2595
    send(fd, (char *)buf, 3, 0);
2596
}
2597

    
2598
static void socket_set_nodelay(int fd)
2599
{
2600
    int val = 1;
2601
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2602
}
2603

    
2604
static void tcp_chr_accept(void *opaque)
2605
{
2606
    CharDriverState *chr = opaque;
2607
    TCPCharDriver *s = chr->opaque;
2608
    struct sockaddr_in saddr;
2609
#ifndef _WIN32
2610
    struct sockaddr_un uaddr;
2611
#endif
2612
    struct sockaddr *addr;
2613
    socklen_t len;
2614
    int fd;
2615

    
2616
    for(;;) {
2617
#ifndef _WIN32
2618
        if (s->is_unix) {
2619
            len = sizeof(uaddr);
2620
            addr = (struct sockaddr *)&uaddr;
2621
        } else
2622
#endif
2623
        {
2624
            len = sizeof(saddr);
2625
            addr = (struct sockaddr *)&saddr;
2626
        }
2627
        fd = accept(s->listen_fd, addr, &len);
2628
        if (fd < 0 && errno != EINTR) {
2629
            return;
2630
        } else if (fd >= 0) {
2631
            if (s->do_telnetopt)
2632
                tcp_chr_telnet_init(fd);
2633
            break;
2634
        }
2635
    }
2636
    socket_set_nonblock(fd);
2637
    if (s->do_nodelay)
2638
        socket_set_nodelay(fd);
2639
    s->fd = fd;
2640
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2641
    tcp_chr_connect(chr);
2642
}
2643

    
2644
static void tcp_chr_close(CharDriverState *chr)
2645
{
2646
    TCPCharDriver *s = chr->opaque;
2647
    if (s->fd >= 0)
2648
        closesocket(s->fd);
2649
    if (s->listen_fd >= 0)
2650
        closesocket(s->listen_fd);
2651
    qemu_free(s);
2652
}
2653

    
2654
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2655
                                          int is_telnet,
2656
                                          int is_unix)
2657
{
2658
    CharDriverState *chr = NULL;
2659
    TCPCharDriver *s = NULL;
2660
    int fd = -1, ret, err, val;
2661
    int is_listen = 0;
2662
    int is_waitconnect = 1;
2663
    int do_nodelay = 0;
2664
    const char *ptr;
2665
    struct sockaddr_in saddr;
2666
#ifndef _WIN32
2667
    struct sockaddr_un uaddr;
2668
#endif
2669
    struct sockaddr *addr;
2670
    socklen_t addrlen;
2671

    
2672
#ifndef _WIN32
2673
    if (is_unix) {
2674
        addr = (struct sockaddr *)&uaddr;
2675
        addrlen = sizeof(uaddr);
2676
        if (parse_unix_path(&uaddr, host_str) < 0)
2677
            goto fail;
2678
    } else
2679
#endif
2680
    {
2681
        addr = (struct sockaddr *)&saddr;
2682
        addrlen = sizeof(saddr);
2683
        if (parse_host_port(&saddr, host_str) < 0)
2684
            goto fail;
2685
    }
2686

    
2687
    ptr = host_str;
2688
    while((ptr = strchr(ptr,','))) {
2689
        ptr++;
2690
        if (!strncmp(ptr,"server",6)) {
2691
            is_listen = 1;
2692
        } else if (!strncmp(ptr,"nowait",6)) {
2693
            is_waitconnect = 0;
2694
        } else if (!strncmp(ptr,"nodelay",6)) {
2695
            do_nodelay = 1;
2696
        } else {
2697
            printf("Unknown option: %s\n", ptr);
2698
            goto fail;
2699
        }
2700
    }
2701
    if (!is_listen)
2702
        is_waitconnect = 0;
2703

    
2704
    chr = qemu_mallocz(sizeof(CharDriverState));
2705
    if (!chr)
2706
        goto fail;
2707
    s = qemu_mallocz(sizeof(TCPCharDriver));
2708
    if (!s)
2709
        goto fail;
2710

    
2711
#ifndef _WIN32
2712
    if (is_unix)
2713
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2714
    else
2715
#endif
2716
        fd = socket(PF_INET, SOCK_STREAM, 0);
2717
        
2718
    if (fd < 0) 
2719
        goto fail;
2720

    
2721
    if (!is_waitconnect)
2722
        socket_set_nonblock(fd);
2723

    
2724
    s->connected = 0;
2725
    s->fd = -1;
2726
    s->listen_fd = -1;
2727
    s->is_unix = is_unix;
2728
    s->do_nodelay = do_nodelay && !is_unix;
2729

    
2730
    chr->opaque = s;
2731
    chr->chr_write = tcp_chr_write;
2732
    chr->chr_close = tcp_chr_close;
2733

    
2734
    if (is_listen) {
2735
        /* allow fast reuse */
2736
#ifndef _WIN32
2737
        if (is_unix) {
2738
            char path[109];
2739
            strncpy(path, uaddr.sun_path, 108);
2740
            path[108] = 0;
2741
            unlink(path);
2742
        } else
2743
#endif
2744
        {
2745
            val = 1;
2746
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2747
        }
2748
        
2749
        ret = bind(fd, addr, addrlen);
2750
        if (ret < 0)
2751
            goto fail;
2752

    
2753
        ret = listen(fd, 0);
2754
        if (ret < 0)
2755
            goto fail;
2756

    
2757
        s->listen_fd = fd;
2758
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2759
        if (is_telnet)
2760
            s->do_telnetopt = 1;
2761
    } else {
2762
        for(;;) {
2763
            ret = connect(fd, addr, addrlen);
2764
            if (ret < 0) {
2765
                err = socket_error();
2766
                if (err == EINTR || err == EWOULDBLOCK) {
2767
                } else if (err == EINPROGRESS) {
2768
                    break;
2769
                } else {
2770
                    goto fail;
2771
                }
2772
            } else {
2773
                s->connected = 1;
2774
                break;
2775
            }
2776
        }
2777
        s->fd = fd;
2778
        socket_set_nodelay(fd);
2779
        if (s->connected)
2780
            tcp_chr_connect(chr);
2781
        else
2782
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2783
    }
2784
    
2785
    if (is_listen && is_waitconnect) {
2786
        printf("QEMU waiting for connection on: %s\n", host_str);
2787
        tcp_chr_accept(chr);
2788
        socket_set_nonblock(s->listen_fd);
2789
    }
2790

    
2791
    return chr;
2792
 fail:
2793
    if (fd >= 0)
2794
        closesocket(fd);
2795
    qemu_free(s);
2796
    qemu_free(chr);
2797
    return NULL;
2798
}
2799

    
2800
CharDriverState *qemu_chr_open(const char *filename)
2801
{
2802
    const char *p;
2803

    
2804
    if (!strcmp(filename, "vc")) {
2805
        return text_console_init(&display_state);
2806
    } else if (!strcmp(filename, "null")) {
2807
        return qemu_chr_open_null();
2808
    } else 
2809
    if (strstart(filename, "tcp:", &p)) {
2810
        return qemu_chr_open_tcp(p, 0, 0);
2811
    } else
2812
    if (strstart(filename, "telnet:", &p)) {
2813
        return qemu_chr_open_tcp(p, 1, 0);
2814
    } else
2815
    if (strstart(filename, "udp:", &p)) {
2816
        return qemu_chr_open_udp(p);
2817
    } else
2818
#ifndef _WIN32
2819
    if (strstart(filename, "unix:", &p)) {
2820
        return qemu_chr_open_tcp(p, 0, 1);
2821
    } else if (strstart(filename, "file:", &p)) {
2822
        return qemu_chr_open_file_out(p);
2823
    } else if (strstart(filename, "pipe:", &p)) {
2824
        return qemu_chr_open_pipe(p);
2825
    } else if (!strcmp(filename, "pty")) {
2826
        return qemu_chr_open_pty();
2827
    } else if (!strcmp(filename, "stdio")) {
2828
        return qemu_chr_open_stdio();
2829
    } else 
2830
#endif
2831
#if defined(__linux__)
2832
    if (strstart(filename, "/dev/parport", NULL)) {
2833
        return qemu_chr_open_pp(filename);
2834
    } else 
2835
    if (strstart(filename, "/dev/", NULL)) {
2836
        return qemu_chr_open_tty(filename);
2837
    } else 
2838
#endif
2839
#ifdef _WIN32
2840
    if (strstart(filename, "COM", NULL)) {
2841
        return qemu_chr_open_win(filename);
2842
    } else
2843
    if (strstart(filename, "pipe:", &p)) {
2844
        return qemu_chr_open_win_pipe(p);
2845
    } else
2846
    if (strstart(filename, "file:", &p)) {
2847
        return qemu_chr_open_win_file_out(p);
2848
    }
2849
#endif
2850
    {
2851
        return NULL;
2852
    }
2853
}
2854

    
2855
void qemu_chr_close(CharDriverState *chr)
2856
{
2857
    if (chr->chr_close)
2858
        chr->chr_close(chr);
2859
}
2860

    
2861
/***********************************************************/
2862
/* network device redirectors */
2863

    
2864
void hex_dump(FILE *f, const uint8_t *buf, int size)
2865
{
2866
    int len, i, j, c;
2867

    
2868
    for(i=0;i<size;i+=16) {
2869
        len = size - i;
2870
        if (len > 16)
2871
            len = 16;
2872
        fprintf(f, "%08x ", i);
2873
        for(j=0;j<16;j++) {
2874
            if (j < len)
2875
                fprintf(f, " %02x", buf[i+j]);
2876
            else
2877
                fprintf(f, "   ");
2878
        }
2879
        fprintf(f, " ");
2880
        for(j=0;j<len;j++) {
2881
            c = buf[i+j];
2882
            if (c < ' ' || c > '~')
2883
                c = '.';
2884
            fprintf(f, "%c", c);
2885
        }
2886
        fprintf(f, "\n");
2887
    }
2888
}
2889

    
2890
static int parse_macaddr(uint8_t *macaddr, const char *p)
2891
{
2892
    int i;
2893
    for(i = 0; i < 6; i++) {
2894
        macaddr[i] = strtol(p, (char **)&p, 16);
2895
        if (i == 5) {
2896
            if (*p != '\0') 
2897
                return -1;
2898
        } else {
2899
            if (*p != ':') 
2900
                return -1;
2901
            p++;
2902
        }
2903
    }
2904
    return 0;
2905
}
2906

    
2907
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2908
{
2909
    const char *p, *p1;
2910
    int len;
2911
    p = *pp;
2912
    p1 = strchr(p, sep);
2913
    if (!p1)
2914
        return -1;
2915
    len = p1 - p;
2916
    p1++;
2917
    if (buf_size > 0) {
2918
        if (len > buf_size - 1)
2919
            len = buf_size - 1;
2920
        memcpy(buf, p, len);
2921
        buf[len] = '\0';
2922
    }
2923
    *pp = p1;
2924
    return 0;
2925
}
2926

    
2927
int parse_host_src_port(struct sockaddr_in *haddr,
2928
                        struct sockaddr_in *saddr,
2929
                        const char *input_str)
2930
{
2931
    char *str = strdup(input_str);
2932
    char *host_str = str;
2933
    char *src_str;
2934
    char *ptr;
2935

    
2936
    /*
2937
     * Chop off any extra arguments at the end of the string which
2938
     * would start with a comma, then fill in the src port information
2939
     * if it was provided else use the "any address" and "any port".
2940
     */
2941
    if ((ptr = strchr(str,',')))
2942
        *ptr = '\0';
2943

    
2944
    if ((src_str = strchr(input_str,'@'))) {
2945
        *src_str = '\0';
2946
        src_str++;
2947
    }
2948

    
2949
    if (parse_host_port(haddr, host_str) < 0)
2950
        goto fail;
2951

    
2952
    if (!src_str || *src_str == '\0')
2953
        src_str = ":0";
2954

    
2955
    if (parse_host_port(saddr, src_str) < 0)
2956
        goto fail;
2957

    
2958
    free(str);
2959
    return(0);
2960

    
2961
fail:
2962
    free(str);
2963
    return -1;
2964
}
2965

    
2966
int parse_host_port(struct sockaddr_in *saddr, const char *str)
2967
{
2968
    char buf[512];
2969
    struct hostent *he;
2970
    const char *p, *r;
2971
    int port;
2972

    
2973
    p = str;
2974
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2975
        return -1;
2976
    saddr->sin_family = AF_INET;
2977
    if (buf[0] == '\0') {
2978
        saddr->sin_addr.s_addr = 0;
2979
    } else {
2980
        if (isdigit(buf[0])) {
2981
            if (!inet_aton(buf, &saddr->sin_addr))
2982
                return -1;
2983
        } else {
2984
            if ((he = gethostbyname(buf)) == NULL)
2985
                return - 1;
2986
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
2987
        }
2988
    }
2989
    port = strtol(p, (char **)&r, 0);
2990
    if (r == p)
2991
        return -1;
2992
    saddr->sin_port = htons(port);
2993
    return 0;
2994
}
2995

    
2996
#ifndef _WIN32
2997
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2998
{
2999
    const char *p;
3000
    int len;
3001

    
3002
    len = MIN(108, strlen(str));
3003
    p = strchr(str, ',');
3004
    if (p)
3005
        len = MIN(len, p - str);
3006

    
3007
    memset(uaddr, 0, sizeof(*uaddr));
3008

    
3009
    uaddr->sun_family = AF_UNIX;
3010
    memcpy(uaddr->sun_path, str, len);
3011

    
3012
    return 0;
3013
}
3014
#endif
3015

    
3016
/* find or alloc a new VLAN */
3017
VLANState *qemu_find_vlan(int id)
3018
{
3019
    VLANState **pvlan, *vlan;
3020
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3021
        if (vlan->id == id)
3022
            return vlan;
3023
    }
3024
    vlan = qemu_mallocz(sizeof(VLANState));
3025
    if (!vlan)
3026
        return NULL;
3027
    vlan->id = id;
3028
    vlan->next = NULL;
3029
    pvlan = &first_vlan;
3030
    while (*pvlan != NULL)
3031
        pvlan = &(*pvlan)->next;
3032
    *pvlan = vlan;
3033
    return vlan;
3034
}
3035

    
3036
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3037
                                      IOReadHandler *fd_read,
3038
                                      IOCanRWHandler *fd_can_read,
3039
                                      void *opaque)
3040
{
3041
    VLANClientState *vc, **pvc;
3042
    vc = qemu_mallocz(sizeof(VLANClientState));
3043
    if (!vc)
3044
        return NULL;
3045
    vc->fd_read = fd_read;
3046
    vc->fd_can_read = fd_can_read;
3047
    vc->opaque = opaque;
3048
    vc->vlan = vlan;
3049

    
3050
    vc->next = NULL;
3051
    pvc = &vlan->first_client;
3052
    while (*pvc != NULL)
3053
        pvc = &(*pvc)->next;
3054
    *pvc = vc;
3055
    return vc;
3056
}
3057

    
3058
int qemu_can_send_packet(VLANClientState *vc1)
3059
{
3060
    VLANState *vlan = vc1->vlan;
3061
    VLANClientState *vc;
3062

    
3063
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3064
        if (vc != vc1) {
3065
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3066
                return 0;
3067
        }
3068
    }
3069
    return 1;
3070
}
3071

    
3072
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3073
{
3074
    VLANState *vlan = vc1->vlan;
3075
    VLANClientState *vc;
3076

    
3077
#if 0
3078
    printf("vlan %d send:\n", vlan->id);
3079
    hex_dump(stdout, buf, size);
3080
#endif
3081
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3082
        if (vc != vc1) {
3083
            vc->fd_read(vc->opaque, buf, size);
3084
        }
3085
    }
3086
}
3087

    
3088
#if defined(CONFIG_SLIRP)
3089

    
3090
/* slirp network adapter */
3091

    
3092
static int slirp_inited;
3093
static VLANClientState *slirp_vc;
3094

    
3095
int slirp_can_output(void)
3096
{
3097
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3098
}
3099

    
3100
void slirp_output(const uint8_t *pkt, int pkt_len)
3101
{
3102
#if 0
3103
    printf("slirp output:\n");
3104
    hex_dump(stdout, pkt, pkt_len);
3105
#endif
3106
    if (!slirp_vc)
3107
        return;
3108
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3109
}
3110

    
3111
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3112
{
3113
#if 0
3114
    printf("slirp input:\n");
3115
    hex_dump(stdout, buf, size);
3116
#endif
3117
    slirp_input(buf, size);
3118
}
3119

    
3120
static int net_slirp_init(VLANState *vlan)
3121
{
3122
    if (!slirp_inited) {
3123
        slirp_inited = 1;
3124
        slirp_init();
3125
    }
3126
    slirp_vc = qemu_new_vlan_client(vlan, 
3127
                                    slirp_receive, NULL, NULL);
3128
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3129
    return 0;
3130
}
3131

    
3132
static void net_slirp_redir(const char *redir_str)
3133
{
3134
    int is_udp;
3135
    char buf[256], *r;
3136
    const char *p;
3137
    struct in_addr guest_addr;
3138
    int host_port, guest_port;
3139
    
3140
    if (!slirp_inited) {
3141
        slirp_inited = 1;
3142
        slirp_init();
3143
    }
3144

    
3145
    p = redir_str;
3146
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3147
        goto fail;
3148
    if (!strcmp(buf, "tcp")) {
3149
        is_udp = 0;
3150
    } else if (!strcmp(buf, "udp")) {
3151
        is_udp = 1;
3152
    } else {
3153
        goto fail;
3154
    }
3155

    
3156
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3157
        goto fail;
3158
    host_port = strtol(buf, &r, 0);
3159
    if (r == buf)
3160
        goto fail;
3161

    
3162
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3163
        goto fail;
3164
    if (buf[0] == '\0') {
3165
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3166
    }
3167
    if (!inet_aton(buf, &guest_addr))
3168
        goto fail;
3169
    
3170
    guest_port = strtol(p, &r, 0);
3171
    if (r == p)
3172
        goto fail;
3173
    
3174
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3175
        fprintf(stderr, "qemu: could not set up redirection\n");
3176
        exit(1);
3177
    }
3178
    return;
3179
 fail:
3180
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3181
    exit(1);
3182
}
3183
    
3184
#ifndef _WIN32
3185

    
3186
char smb_dir[1024];
3187

    
3188
static void smb_exit(void)
3189
{
3190
    DIR *d;
3191
    struct dirent *de;
3192
    char filename[1024];
3193

    
3194
    /* erase all the files in the directory */
3195
    d = opendir(smb_dir);
3196
    for(;;) {
3197
        de = readdir(d);
3198
        if (!de)
3199
            break;
3200
        if (strcmp(de->d_name, ".") != 0 &&
3201
            strcmp(de->d_name, "..") != 0) {
3202
            snprintf(filename, sizeof(filename), "%s/%s", 
3203
                     smb_dir, de->d_name);
3204
            unlink(filename);
3205
        }
3206
    }
3207
    closedir(d);
3208
    rmdir(smb_dir);
3209
}
3210

    
3211
/* automatic user mode samba server configuration */
3212
void net_slirp_smb(const char *exported_dir)
3213
{
3214
    char smb_conf[1024];
3215
    char smb_cmdline[1024];
3216
    FILE *f;
3217

    
3218
    if (!slirp_inited) {
3219
        slirp_inited = 1;
3220
        slirp_init();
3221
    }
3222

    
3223
    /* XXX: better tmp dir construction */
3224
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3225
    if (mkdir(smb_dir, 0700) < 0) {
3226
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3227
        exit(1);
3228
    }
3229
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3230
    
3231
    f = fopen(smb_conf, "w");
3232
    if (!f) {
3233
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3234
        exit(1);
3235
    }
3236
    fprintf(f, 
3237
            "[global]\n"
3238
            "private dir=%s\n"
3239
            "smb ports=0\n"
3240
            "socket address=127.0.0.1\n"
3241
            "pid directory=%s\n"
3242
            "lock directory=%s\n"
3243
            "log file=%s/log.smbd\n"
3244
            "smb passwd file=%s/smbpasswd\n"
3245
            "security = share\n"
3246
            "[qemu]\n"
3247
            "path=%s\n"
3248
            "read only=no\n"
3249
            "guest ok=yes\n",
3250
            smb_dir,
3251
            smb_dir,
3252
            smb_dir,
3253
            smb_dir,
3254
            smb_dir,
3255
            exported_dir
3256
            );
3257
    fclose(f);
3258
    atexit(smb_exit);
3259

    
3260
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3261
             SMBD_COMMAND, smb_conf);
3262
    
3263
    slirp_add_exec(0, smb_cmdline, 4, 139);
3264
}
3265

    
3266
#endif /* !defined(_WIN32) */
3267

    
3268
#endif /* CONFIG_SLIRP */
3269

    
3270
#if !defined(_WIN32)
3271

    
3272
typedef struct TAPState {
3273
    VLANClientState *vc;
3274
    int fd;
3275
} TAPState;
3276

    
3277
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3278
{
3279
    TAPState *s = opaque;
3280
    int ret;
3281
    for(;;) {
3282
        ret = write(s->fd, buf, size);
3283
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3284
        } else {
3285
            break;
3286
        }
3287
    }
3288
}
3289

    
3290
static void tap_send(void *opaque)
3291
{
3292
    TAPState *s = opaque;
3293
    uint8_t buf[4096];
3294
    int size;
3295

    
3296
#ifdef __sun__
3297
    struct strbuf sbuf;
3298
    int f = 0;
3299
    sbuf.maxlen = sizeof(buf);
3300
    sbuf.buf = buf;
3301
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3302
#else
3303
    size = read(s->fd, buf, sizeof(buf));
3304
#endif
3305
    if (size > 0) {
3306
        qemu_send_packet(s->vc, buf, size);
3307
    }
3308
}
3309

    
3310
/* fd support */
3311

    
3312
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3313
{
3314
    TAPState *s;
3315

    
3316
    s = qemu_mallocz(sizeof(TAPState));
3317
    if (!s)
3318
        return NULL;
3319
    s->fd = fd;
3320
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3321
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3322
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3323
    return s;
3324
}
3325

    
3326
#ifdef _BSD
3327
static int tap_open(char *ifname, int ifname_size)
3328
{
3329
    int fd;
3330
    char *dev;
3331
    struct stat s;
3332

    
3333
    fd = open("/dev/tap", O_RDWR);
3334
    if (fd < 0) {
3335
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3336
        return -1;
3337
    }
3338

    
3339
    fstat(fd, &s);
3340
    dev = devname(s.st_rdev, S_IFCHR);
3341
    pstrcpy(ifname, ifname_size, dev);
3342

    
3343
    fcntl(fd, F_SETFL, O_NONBLOCK);
3344
    return fd;
3345
}
3346
#elif defined(__sun__)
3347
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3348
/* 
3349
 * Allocate TAP device, returns opened fd. 
3350
 * Stores dev name in the first arg(must be large enough).
3351
 */  
3352
int tap_alloc(char *dev)
3353
{
3354
    int tap_fd, if_fd, ppa = -1;
3355
    static int ip_fd = 0;
3356
    char *ptr;
3357

    
3358
    static int arp_fd = 0;
3359
    int ip_muxid, arp_muxid;
3360
    struct strioctl  strioc_if, strioc_ppa;
3361
    int link_type = I_PLINK;;
3362
    struct lifreq ifr;
3363
    char actual_name[32] = "";
3364

    
3365
    memset(&ifr, 0x0, sizeof(ifr));
3366

    
3367
    if( *dev ){
3368
       ptr = dev;        
3369
       while( *ptr && !isdigit((int)*ptr) ) ptr++; 
3370
       ppa = atoi(ptr);
3371
    }
3372

    
3373
    /* Check if IP device was opened */
3374
    if( ip_fd )
3375
       close(ip_fd);
3376

    
3377
    if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3378
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3379
       return -1;
3380
    }
3381

    
3382
    if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3383
       syslog(LOG_ERR, "Can't open /dev/tap");
3384
       return -1;
3385
    }
3386

    
3387
    /* Assign a new PPA and get its unit number. */
3388
    strioc_ppa.ic_cmd = TUNNEWPPA;
3389
    strioc_ppa.ic_timout = 0;
3390
    strioc_ppa.ic_len = sizeof(ppa);
3391
    strioc_ppa.ic_dp = (char *)&ppa;
3392
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3393
       syslog (LOG_ERR, "Can't assign new interface");
3394

    
3395
    if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3396
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3397
       return -1;
3398
    }
3399
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3400
       syslog(LOG_ERR, "Can't push IP module");
3401
       return -1;
3402
    }
3403

    
3404
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3405
        syslog(LOG_ERR, "Can't get flags\n");
3406

    
3407
    snprintf (actual_name, 32, "tap%d", ppa);
3408
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3409

    
3410
    ifr.lifr_ppa = ppa;
3411
    /* Assign ppa according to the unit number returned by tun device */
3412

    
3413
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3414
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
3415
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3416
        syslog (LOG_ERR, "Can't get flags\n");
3417
    /* Push arp module to if_fd */
3418
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
3419
        syslog (LOG_ERR, "Can't push ARP module (2)");
3420

    
3421
    /* Push arp module to ip_fd */
3422
    if (ioctl (ip_fd, I_POP, NULL) < 0)
3423
        syslog (LOG_ERR, "I_POP failed\n");
3424
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3425
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
3426
    /* Open arp_fd */
3427
    if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3428
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3429

    
3430
    /* Set ifname to arp */
3431
    strioc_if.ic_cmd = SIOCSLIFNAME;
3432
    strioc_if.ic_timout = 0;
3433
    strioc_if.ic_len = sizeof(ifr);
3434
    strioc_if.ic_dp = (char *)&ifr;
3435
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3436
        syslog (LOG_ERR, "Can't set ifname to arp\n");
3437
    }
3438

    
3439
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3440
       syslog(LOG_ERR, "Can't link TAP device to IP");
3441
       return -1;
3442
    }
3443

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

    
3447
    close (if_fd);
3448

    
3449
    memset(&ifr, 0x0, sizeof(ifr));
3450
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3451
    ifr.lifr_ip_muxid  = ip_muxid;
3452
    ifr.lifr_arp_muxid = arp_muxid;
3453

    
3454
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3455
    {
3456
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
3457
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
3458
      syslog (LOG_ERR, "Can't set multiplexor id");
3459
    }
3460

    
3461
    sprintf(dev, "tap%d", ppa);
3462
    return tap_fd;
3463
}
3464

    
3465
static int tap_open(char *ifname, int ifname_size)
3466
{
3467
    char  dev[10]="";
3468
    int fd;
3469
    if( (fd = tap_alloc(dev)) < 0 ){
3470
       fprintf(stderr, "Cannot allocate TAP device\n");
3471
       return -1;
3472
    }
3473
    pstrcpy(ifname, ifname_size, dev);
3474
    fcntl(fd, F_SETFL, O_NONBLOCK);
3475
    return fd;
3476
}
3477
#else
3478
static int tap_open(char *ifname, int ifname_size)
3479
{
3480
    struct ifreq ifr;
3481
    int fd, ret;
3482
    
3483
    fd = open("/dev/net/tun", O_RDWR);
3484
    if (fd < 0) {
3485
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3486
        return -1;
3487
    }
3488
    memset(&ifr, 0, sizeof(ifr));
3489
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3490
    if (ifname[0] != '\0')
3491
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3492
    else
3493
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3494
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3495
    if (ret != 0) {
3496
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3497
        close(fd);
3498
        return -1;
3499
    }
3500
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3501
    fcntl(fd, F_SETFL, O_NONBLOCK);
3502
    return fd;
3503
}
3504
#endif
3505

    
3506
static int net_tap_init(VLANState *vlan, const char *ifname1,
3507
                        const char *setup_script)
3508
{
3509
    TAPState *s;
3510
    int pid, status, fd;
3511
    char *args[3];
3512
    char **parg;
3513
    char ifname[128];
3514

    
3515
    if (ifname1 != NULL)
3516
        pstrcpy(ifname, sizeof(ifname), ifname1);
3517
    else
3518
        ifname[0] = '\0';
3519
    fd = tap_open(ifname, sizeof(ifname));
3520
    if (fd < 0)
3521
        return -1;
3522

    
3523
    if (!setup_script || !strcmp(setup_script, "no"))
3524
        setup_script = "";
3525
    if (setup_script[0] != '\0') {
3526
        /* try to launch network init script */
3527
        pid = fork();
3528
        if (pid >= 0) {
3529
            if (pid == 0) {
3530
                parg = args;
3531
                *parg++ = (char *)setup_script;
3532
                *parg++ = ifname;
3533
                *parg++ = NULL;
3534
                execv(setup_script, args);
3535
                _exit(1);
3536
            }
3537
            while (waitpid(pid, &status, 0) != pid);
3538
            if (!WIFEXITED(status) ||
3539
                WEXITSTATUS(status) != 0) {
3540
                fprintf(stderr, "%s: could not launch network script\n",
3541
                        setup_script);
3542
                return -1;
3543
            }
3544
        }
3545
    }
3546
    s = net_tap_fd_init(vlan, fd);
3547
    if (!s)
3548
        return -1;
3549
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3550
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3551
    return 0;
3552
}
3553

    
3554
#endif /* !_WIN32 */
3555

    
3556
/* network connection */
3557
typedef struct NetSocketState {
3558
    VLANClientState *vc;
3559
    int fd;
3560
    int state; /* 0 = getting length, 1 = getting data */
3561
    int index;
3562
    int packet_len;
3563
    uint8_t buf[4096];
3564
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3565
} NetSocketState;
3566

    
3567
typedef struct NetSocketListenState {
3568
    VLANState *vlan;
3569
    int fd;
3570
} NetSocketListenState;
3571

    
3572
/* XXX: we consider we can send the whole packet without blocking */
3573
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3574
{
3575
    NetSocketState *s = opaque;
3576
    uint32_t len;
3577
    len = htonl(size);
3578

    
3579
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3580
    send_all(s->fd, buf, size);
3581
}
3582

    
3583
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3584
{
3585
    NetSocketState *s = opaque;
3586
    sendto(s->fd, buf, size, 0, 
3587
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3588
}
3589

    
3590
static void net_socket_send(void *opaque)
3591
{
3592
    NetSocketState *s = opaque;
3593
    int l, size, err;
3594
    uint8_t buf1[4096];
3595
    const uint8_t *buf;
3596

    
3597
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3598
    if (size < 0) {
3599
        err = socket_error();
3600
        if (err != EWOULDBLOCK) 
3601
            goto eoc;
3602
    } else if (size == 0) {
3603
        /* end of connection */
3604
    eoc:
3605
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3606
        closesocket(s->fd);
3607
        return;
3608
    }
3609
    buf = buf1;
3610
    while (size > 0) {
3611
        /* reassemble a packet from the network */
3612
        switch(s->state) {
3613
        case 0:
3614
            l = 4 - s->index;
3615
            if (l > size)
3616
                l = size;
3617
            memcpy(s->buf + s->index, buf, l);
3618
            buf += l;
3619
            size -= l;
3620
            s->index += l;
3621
            if (s->index == 4) {
3622
                /* got length */
3623
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3624
                s->index = 0;
3625
                s->state = 1;
3626
            }
3627
            break;
3628
        case 1:
3629
            l = s->packet_len - s->index;
3630
            if (l > size)
3631
                l = size;
3632
            memcpy(s->buf + s->index, buf, l);
3633
            s->index += l;
3634
            buf += l;
3635
            size -= l;
3636
            if (s->index >= s->packet_len) {
3637
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3638
                s->index = 0;
3639
                s->state = 0;
3640
            }
3641
            break;
3642
        }
3643
    }
3644
}
3645

    
3646
static void net_socket_send_dgram(void *opaque)
3647
{
3648
    NetSocketState *s = opaque;
3649
    int size;
3650

    
3651
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3652
    if (size < 0) 
3653
        return;
3654
    if (size == 0) {
3655
        /* end of connection */
3656
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3657
        return;
3658
    }
3659
    qemu_send_packet(s->vc, s->buf, size);
3660
}
3661

    
3662
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3663
{
3664
    struct ip_mreq imr;
3665
    int fd;
3666
    int val, ret;
3667
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3668
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3669
                inet_ntoa(mcastaddr->sin_addr), 
3670
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3671
        return -1;
3672

    
3673
    }
3674
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3675
    if (fd < 0) {
3676
        perror("socket(PF_INET, SOCK_DGRAM)");
3677
        return -1;
3678
    }
3679

    
3680
    val = 1;
3681
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3682
                   (const char *)&val, sizeof(val));
3683
    if (ret < 0) {
3684
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3685
        goto fail;
3686
    }
3687

    
3688
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3689
    if (ret < 0) {
3690
        perror("bind");
3691
        goto fail;
3692
    }
3693
    
3694
    /* Add host to multicast group */
3695
    imr.imr_multiaddr = mcastaddr->sin_addr;
3696
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3697

    
3698
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3699
                     (const char *)&imr, sizeof(struct ip_mreq));
3700
    if (ret < 0) {
3701
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3702
        goto fail;
3703
    }
3704

    
3705
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3706
    val = 1;
3707
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3708
                   (const char *)&val, sizeof(val));
3709
    if (ret < 0) {
3710
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3711
        goto fail;
3712
    }
3713

    
3714
    socket_set_nonblock(fd);
3715
    return fd;
3716
fail:
3717
    if (fd >= 0) 
3718
        closesocket(fd);
3719
    return -1;
3720
}
3721

    
3722
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3723
                                          int is_connected)
3724
{
3725
    struct sockaddr_in saddr;
3726
    int newfd;
3727
    socklen_t saddr_len;
3728
    NetSocketState *s;
3729

    
3730
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3731
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3732
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3733
     */
3734

    
3735
    if (is_connected) {
3736
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3737
            /* must be bound */
3738
            if (saddr.sin_addr.s_addr==0) {
3739
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3740
                        fd);
3741
                return NULL;
3742
            }
3743
            /* clone dgram socket */
3744
            newfd = net_socket_mcast_create(&saddr);
3745
            if (newfd < 0) {
3746
                /* error already reported by net_socket_mcast_create() */
3747
                close(fd);
3748
                return NULL;
3749
            }
3750
            /* clone newfd to fd, close newfd */
3751
            dup2(newfd, fd);
3752
            close(newfd);
3753
        
3754
        } else {
3755
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3756
                    fd, strerror(errno));
3757
            return NULL;
3758
        }
3759
    }
3760

    
3761
    s = qemu_mallocz(sizeof(NetSocketState));
3762
    if (!s)
3763
        return NULL;
3764
    s->fd = fd;
3765

    
3766
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3767
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3768

    
3769
    /* mcast: save bound address as dst */
3770
    if (is_connected) s->dgram_dst=saddr;
3771

    
3772
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3773
            "socket: fd=%d (%s mcast=%s:%d)", 
3774
            fd, is_connected? "cloned" : "",
3775
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3776
    return s;
3777
}
3778

    
3779
static void net_socket_connect(void *opaque)
3780
{
3781
    NetSocketState *s = opaque;
3782
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3783
}
3784

    
3785
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3786
                                          int is_connected)
3787
{
3788
    NetSocketState *s;
3789
    s = qemu_mallocz(sizeof(NetSocketState));
3790
    if (!s)
3791
        return NULL;
3792
    s->fd = fd;
3793
    s->vc = qemu_new_vlan_client(vlan, 
3794
                                 net_socket_receive, NULL, s);
3795
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3796
             "socket: fd=%d", fd);
3797
    if (is_connected) {
3798
        net_socket_connect(s);
3799
    } else {
3800
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3801
    }
3802
    return s;
3803
}
3804

    
3805
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3806
                                          int is_connected)
3807
{
3808
    int so_type=-1, optlen=sizeof(so_type);
3809

    
3810
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3811
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3812
        return NULL;
3813
    }
3814
    switch(so_type) {
3815
    case SOCK_DGRAM:
3816
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3817
    case SOCK_STREAM:
3818
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3819
    default:
3820
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3821
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3822
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3823
    }
3824
    return NULL;
3825
}
3826

    
3827
static void net_socket_accept(void *opaque)
3828
{
3829
    NetSocketListenState *s = opaque;    
3830
    NetSocketState *s1;
3831
    struct sockaddr_in saddr;
3832
    socklen_t len;
3833
    int fd;
3834

    
3835
    for(;;) {
3836
        len = sizeof(saddr);
3837
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3838
        if (fd < 0 && errno != EINTR) {
3839
            return;
3840
        } else if (fd >= 0) {
3841
            break;
3842
        }
3843
    }
3844
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3845
    if (!s1) {
3846
        closesocket(fd);
3847
    } else {
3848
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3849
                 "socket: connection from %s:%d", 
3850
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3851
    }
3852
}
3853

    
3854
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3855
{
3856
    NetSocketListenState *s;
3857
    int fd, val, ret;
3858
    struct sockaddr_in saddr;
3859

    
3860
    if (parse_host_port(&saddr, host_str) < 0)
3861
        return -1;
3862
    
3863
    s = qemu_mallocz(sizeof(NetSocketListenState));
3864
    if (!s)
3865
        return -1;
3866

    
3867
    fd = socket(PF_INET, SOCK_STREAM, 0);
3868
    if (fd < 0) {
3869
        perror("socket");
3870
        return -1;
3871
    }
3872
    socket_set_nonblock(fd);
3873

    
3874
    /* allow fast reuse */
3875
    val = 1;
3876
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3877
    
3878
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3879
    if (ret < 0) {
3880
        perror("bind");
3881
        return -1;
3882
    }
3883
    ret = listen(fd, 0);
3884
    if (ret < 0) {
3885
        perror("listen");
3886
        return -1;
3887
    }
3888
    s->vlan = vlan;
3889
    s->fd = fd;
3890
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3891
    return 0;
3892
}
3893

    
3894
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3895
{
3896
    NetSocketState *s;
3897
    int fd, connected, ret, err;
3898
    struct sockaddr_in saddr;
3899

    
3900
    if (parse_host_port(&saddr, host_str) < 0)
3901
        return -1;
3902

    
3903
    fd = socket(PF_INET, SOCK_STREAM, 0);
3904
    if (fd < 0) {
3905
        perror("socket");
3906
        return -1;
3907
    }
3908
    socket_set_nonblock(fd);
3909

    
3910
    connected = 0;
3911
    for(;;) {
3912
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3913
        if (ret < 0) {
3914
            err = socket_error();
3915
            if (err == EINTR || err == EWOULDBLOCK) {
3916
            } else if (err == EINPROGRESS) {
3917
                break;
3918
            } else {
3919
                perror("connect");
3920
                closesocket(fd);
3921
                return -1;
3922
            }
3923
        } else {
3924
            connected = 1;
3925
            break;
3926
        }
3927
    }
3928
    s = net_socket_fd_init(vlan, fd, connected);
3929
    if (!s)
3930
        return -1;
3931
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3932
             "socket: connect to %s:%d", 
3933
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3934
    return 0;
3935
}
3936

    
3937
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3938
{
3939
    NetSocketState *s;
3940
    int fd;
3941
    struct sockaddr_in saddr;
3942

    
3943
    if (parse_host_port(&saddr, host_str) < 0)
3944
        return -1;
3945

    
3946

    
3947
    fd = net_socket_mcast_create(&saddr);
3948
    if (fd < 0)
3949
        return -1;
3950

    
3951
    s = net_socket_fd_init(vlan, fd, 0);
3952
    if (!s)
3953
        return -1;
3954

    
3955
    s->dgram_dst = saddr;
3956
    
3957
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3958
             "socket: mcast=%s:%d", 
3959
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3960
    return 0;
3961

    
3962
}
3963

    
3964
static int get_param_value(char *buf, int buf_size,
3965
                           const char *tag, const char *str)
3966
{
3967
    const char *p;
3968
    char *q;
3969
    char option[128];
3970

    
3971
    p = str;
3972
    for(;;) {
3973
        q = option;
3974
        while (*p != '\0' && *p != '=') {
3975
            if ((q - option) < sizeof(option) - 1)
3976
                *q++ = *p;
3977
            p++;
3978
        }
3979
        *q = '\0';
3980
        if (*p != '=')
3981
            break;
3982
        p++;
3983
        if (!strcmp(tag, option)) {
3984
            q = buf;
3985
            while (*p != '\0' && *p != ',') {
3986
                if ((q - buf) < buf_size - 1)
3987
                    *q++ = *p;
3988
                p++;
3989
            }
3990
            *q = '\0';
3991
            return q - buf;
3992
        } else {
3993
            while (*p != '\0' && *p != ',') {
3994
                p++;
3995
            }
3996
        }
3997
        if (*p != ',')
3998
            break;
3999
        p++;
4000
    }
4001
    return 0;
4002
}
4003

    
4004
static int net_client_init(const char *str)
4005
{
4006
    const char *p;
4007
    char *q;
4008
    char device[64];
4009
    char buf[1024];
4010
    int vlan_id, ret;
4011
    VLANState *vlan;
4012

    
4013
    p = str;
4014
    q = device;
4015
    while (*p != '\0' && *p != ',') {
4016
        if ((q - device) < sizeof(device) - 1)
4017
            *q++ = *p;
4018
        p++;
4019
    }
4020
    *q = '\0';
4021
    if (*p == ',')
4022
        p++;
4023
    vlan_id = 0;
4024
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4025
        vlan_id = strtol(buf, NULL, 0);
4026
    }
4027
    vlan = qemu_find_vlan(vlan_id);
4028
    if (!vlan) {
4029
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4030
        return -1;
4031
    }
4032
    if (!strcmp(device, "nic")) {
4033
        NICInfo *nd;
4034
        uint8_t *macaddr;
4035

    
4036
        if (nb_nics >= MAX_NICS) {
4037
            fprintf(stderr, "Too Many NICs\n");
4038
            return -1;
4039
        }
4040
        nd = &nd_table[nb_nics];
4041
        macaddr = nd->macaddr;
4042
        macaddr[0] = 0x52;
4043
        macaddr[1] = 0x54;
4044
        macaddr[2] = 0x00;
4045
        macaddr[3] = 0x12;
4046
        macaddr[4] = 0x34;
4047
        macaddr[5] = 0x56 + nb_nics;
4048

    
4049
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4050
            if (parse_macaddr(macaddr, buf) < 0) {
4051
                fprintf(stderr, "invalid syntax for ethernet address\n");
4052
                return -1;
4053
            }
4054
        }
4055
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4056
            nd->model = strdup(buf);
4057
        }
4058
        nd->vlan = vlan;
4059
        nb_nics++;
4060
        ret = 0;
4061
    } else
4062
    if (!strcmp(device, "none")) {
4063
        /* does nothing. It is needed to signal that no network cards
4064
           are wanted */
4065
        ret = 0;
4066
    } else
4067
#ifdef CONFIG_SLIRP
4068
    if (!strcmp(device, "user")) {
4069
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4070
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4071
        }
4072
        ret = net_slirp_init(vlan);
4073
    } else
4074
#endif
4075
#ifdef _WIN32
4076
    if (!strcmp(device, "tap")) {
4077
        char ifname[64];
4078
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4079
            fprintf(stderr, "tap: no interface name\n");
4080
            return -1;
4081
        }
4082
        ret = tap_win32_init(vlan, ifname);
4083
    } else
4084
#else
4085
    if (!strcmp(device, "tap")) {
4086
        char ifname[64];
4087
        char setup_script[1024];
4088
        int fd;
4089
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4090
            fd = strtol(buf, NULL, 0);
4091
            ret = -1;
4092
            if (net_tap_fd_init(vlan, fd))
4093
                ret = 0;
4094
        } else {
4095
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4096
                ifname[0] = '\0';
4097
            }
4098
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4099
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4100
            }
4101
            ret = net_tap_init(vlan, ifname, setup_script);
4102
        }
4103
    } else
4104
#endif
4105
    if (!strcmp(device, "socket")) {
4106
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4107
            int fd;
4108
            fd = strtol(buf, NULL, 0);
4109
            ret = -1;
4110
            if (net_socket_fd_init(vlan, fd, 1))
4111
                ret = 0;
4112
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4113
            ret = net_socket_listen_init(vlan, buf);
4114
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4115
            ret = net_socket_connect_init(vlan, buf);
4116
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4117
            ret = net_socket_mcast_init(vlan, buf);
4118
        } else {
4119
            fprintf(stderr, "Unknown socket options: %s\n", p);
4120
            return -1;
4121
        }
4122
    } else
4123
    {
4124
        fprintf(stderr, "Unknown network device: %s\n", device);
4125
        return -1;
4126
    }
4127
    if (ret < 0) {
4128
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4129
    }
4130
    
4131
    return ret;
4132
}
4133

    
4134
void do_info_network(void)
4135
{
4136
    VLANState *vlan;
4137
    VLANClientState *vc;
4138

    
4139
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4140
        term_printf("VLAN %d devices:\n", vlan->id);
4141
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4142
            term_printf("  %s\n", vc->info_str);
4143
    }
4144
}
4145

    
4146
/***********************************************************/
4147
/* USB devices */
4148

    
4149
static USBPort *used_usb_ports;
4150
static USBPort *free_usb_ports;
4151

    
4152
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4153
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4154
                            usb_attachfn attach)
4155
{
4156
    port->opaque = opaque;
4157
    port->index = index;
4158
    port->attach = attach;
4159
    port->next = free_usb_ports;
4160
    free_usb_ports = port;
4161
}
4162

    
4163
static int usb_device_add(const char *devname)
4164
{
4165
    const char *p;
4166
    USBDevice *dev;
4167
    USBPort *port;
4168

    
4169
    if (!free_usb_ports)
4170
        return -1;
4171

    
4172
    if (strstart(devname, "host:", &p)) {
4173
        dev = usb_host_device_open(p);
4174
    } else if (!strcmp(devname, "mouse")) {
4175
        dev = usb_mouse_init();
4176
    } else if (!strcmp(devname, "tablet")) {
4177
        dev = usb_tablet_init();
4178
    } else if (strstart(devname, "disk:", &p)) {
4179
        dev = usb_msd_init(p);
4180
    } else {
4181
        return -1;
4182
    }
4183
    if (!dev)
4184
        return -1;
4185

    
4186
    /* Find a USB port to add the device to.  */
4187
    port = free_usb_ports;
4188
    if (!port->next) {
4189
        USBDevice *hub;
4190

    
4191
        /* Create a new hub and chain it on.  */
4192
        free_usb_ports = NULL;
4193
        port->next = used_usb_ports;
4194
        used_usb_ports = port;
4195

    
4196
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4197
        usb_attach(port, hub);
4198
        port = free_usb_ports;
4199
    }
4200

    
4201
    free_usb_ports = port->next;
4202
    port->next = used_usb_ports;
4203
    used_usb_ports = port;
4204
    usb_attach(port, dev);
4205
    return 0;
4206
}
4207

    
4208
static int usb_device_del(const char *devname)
4209
{
4210
    USBPort *port;
4211
    USBPort **lastp;
4212
    USBDevice *dev;
4213
    int bus_num, addr;
4214
    const char *p;
4215

    
4216
    if (!used_usb_ports)
4217
        return -1;
4218

    
4219
    p = strchr(devname, '.');
4220
    if (!p) 
4221
        return -1;
4222
    bus_num = strtoul(devname, NULL, 0);
4223
    addr = strtoul(p + 1, NULL, 0);
4224
    if (bus_num != 0)
4225
        return -1;
4226

    
4227
    lastp = &used_usb_ports;
4228
    port = used_usb_ports;
4229
    while (port && port->dev->addr != addr) {
4230
        lastp = &port->next;
4231
        port = port->next;
4232
    }
4233

    
4234
    if (!port)
4235
        return -1;
4236

    
4237
    dev = port->dev;
4238
    *lastp = port->next;
4239
    usb_attach(port, NULL);
4240
    dev->handle_destroy(dev);
4241
    port->next = free_usb_ports;
4242
    free_usb_ports = port;
4243
    return 0;
4244
}
4245

    
4246
void do_usb_add(const char *devname)
4247
{
4248
    int ret;
4249
    ret = usb_device_add(devname);
4250
    if (ret < 0) 
4251
        term_printf("Could not add USB device '%s'\n", devname);
4252
}
4253

    
4254
void do_usb_del(const char *devname)
4255
{
4256
    int ret;
4257
    ret = usb_device_del(devname);
4258
    if (ret < 0) 
4259
        term_printf("Could not remove USB device '%s'\n", devname);
4260
}
4261

    
4262
void usb_info(void)
4263
{
4264
    USBDevice *dev;
4265
    USBPort *port;
4266
    const char *speed_str;
4267

    
4268
    if (!usb_enabled) {
4269
        term_printf("USB support not enabled\n");
4270
        return;
4271
    }
4272

    
4273
    for (port = used_usb_ports; port; port = port->next) {
4274
        dev = port->dev;
4275
        if (!dev)
4276
            continue;
4277
        switch(dev->speed) {
4278
        case USB_SPEED_LOW: 
4279
            speed_str = "1.5"; 
4280
            break;
4281
        case USB_SPEED_FULL: 
4282
            speed_str = "12"; 
4283
            break;
4284
        case USB_SPEED_HIGH: 
4285
            speed_str = "480"; 
4286
            break;
4287
        default:
4288
            speed_str = "?"; 
4289
            break;
4290
        }
4291
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4292
                    0, dev->addr, speed_str, dev->devname);
4293
    }
4294
}
4295

    
4296
/***********************************************************/
4297
/* pid file */
4298

    
4299
static char *pid_filename;
4300

    
4301
/* Remove PID file. Called on normal exit */
4302

    
4303
static void remove_pidfile(void) 
4304
{
4305
    unlink (pid_filename);
4306
}
4307

    
4308
static void create_pidfile(const char *filename)
4309
{
4310
    struct stat pidstat;
4311
    FILE *f;
4312

    
4313
    /* Try to write our PID to the named file */
4314
    if (stat(filename, &pidstat) < 0) {
4315
        if (errno == ENOENT) {
4316
            if ((f = fopen (filename, "w")) == NULL) {
4317
                perror("Opening pidfile");
4318
                exit(1);
4319
            }
4320
            fprintf(f, "%d\n", getpid());
4321
            fclose(f);
4322
            pid_filename = qemu_strdup(filename);
4323
            if (!pid_filename) {
4324
                fprintf(stderr, "Could not save PID filename");
4325
                exit(1);
4326
            }
4327
            atexit(remove_pidfile);
4328
        }
4329
    } else {
4330
        fprintf(stderr, "%s already exists. Remove it and try again.\n", 
4331
                filename);
4332
        exit(1);
4333
    }
4334
}
4335

    
4336
/***********************************************************/
4337
/* dumb display */
4338

    
4339
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4340
{
4341
}
4342

    
4343
static void dumb_resize(DisplayState *ds, int w, int h)
4344
{
4345
}
4346

    
4347
static void dumb_refresh(DisplayState *ds)
4348
{
4349
    vga_hw_update();
4350
}
4351

    
4352
void dumb_display_init(DisplayState *ds)
4353
{
4354
    ds->data = NULL;
4355
    ds->linesize = 0;
4356
    ds->depth = 0;
4357
    ds->dpy_update = dumb_update;
4358
    ds->dpy_resize = dumb_resize;
4359
    ds->dpy_refresh = dumb_refresh;
4360
}
4361

    
4362
/***********************************************************/
4363
/* I/O handling */
4364

    
4365
#define MAX_IO_HANDLERS 64
4366

    
4367
typedef struct IOHandlerRecord {
4368
    int fd;
4369
    IOCanRWHandler *fd_read_poll;
4370
    IOHandler *fd_read;
4371
    IOHandler *fd_write;
4372
    void *opaque;
4373
    /* temporary data */
4374
    struct pollfd *ufd;
4375
    struct IOHandlerRecord *next;
4376
} IOHandlerRecord;
4377

    
4378
static IOHandlerRecord *first_io_handler;
4379

    
4380
/* XXX: fd_read_poll should be suppressed, but an API change is
4381
   necessary in the character devices to suppress fd_can_read(). */
4382
int qemu_set_fd_handler2(int fd, 
4383
                         IOCanRWHandler *fd_read_poll, 
4384
                         IOHandler *fd_read, 
4385
                         IOHandler *fd_write, 
4386
                         void *opaque)
4387
{
4388
    IOHandlerRecord **pioh, *ioh;
4389

    
4390
    if (!fd_read && !fd_write) {
4391
        pioh = &first_io_handler;
4392
        for(;;) {
4393
            ioh = *pioh;
4394
            if (ioh == NULL)
4395
                break;
4396
            if (ioh->fd == fd) {
4397
                *pioh = ioh->next;
4398
                qemu_free(ioh);
4399
                break;
4400
            }
4401
            pioh = &ioh->next;
4402
        }
4403
    } else {
4404
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4405
            if (ioh->fd == fd)
4406
                goto found;
4407
        }
4408
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4409
        if (!ioh)
4410
            return -1;
4411
        ioh->next = first_io_handler;
4412
        first_io_handler = ioh;
4413
    found:
4414
        ioh->fd = fd;
4415
        ioh->fd_read_poll = fd_read_poll;
4416
        ioh->fd_read = fd_read;
4417
        ioh->fd_write = fd_write;
4418
        ioh->opaque = opaque;
4419
    }
4420
    return 0;
4421
}
4422

    
4423
int qemu_set_fd_handler(int fd, 
4424
                        IOHandler *fd_read, 
4425
                        IOHandler *fd_write, 
4426
                        void *opaque)
4427
{
4428
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4429
}
4430

    
4431
/***********************************************************/
4432
/* Polling handling */
4433

    
4434
typedef struct PollingEntry {
4435
    PollingFunc *func;
4436
    void *opaque;
4437
    struct PollingEntry *next;
4438
} PollingEntry;
4439

    
4440
static PollingEntry *first_polling_entry;
4441

    
4442
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4443
{
4444
    PollingEntry **ppe, *pe;
4445
    pe = qemu_mallocz(sizeof(PollingEntry));
4446
    if (!pe)
4447
        return -1;
4448
    pe->func = func;
4449
    pe->opaque = opaque;
4450
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4451
    *ppe = pe;
4452
    return 0;
4453
}
4454

    
4455
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4456
{
4457
    PollingEntry **ppe, *pe;
4458
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4459
        pe = *ppe;
4460
        if (pe->func == func && pe->opaque == opaque) {
4461
            *ppe = pe->next;
4462
            qemu_free(pe);
4463
            break;
4464
        }
4465
    }
4466
}
4467

    
4468
#ifdef _WIN32
4469
/***********************************************************/
4470
/* Wait objects support */
4471
typedef struct WaitObjects {
4472
    int num;
4473
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4474
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4475
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4476
} WaitObjects;
4477

    
4478
static WaitObjects wait_objects = {0};
4479
    
4480
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4481
{
4482
    WaitObjects *w = &wait_objects;
4483

    
4484
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4485
        return -1;
4486
    w->events[w->num] = handle;
4487
    w->func[w->num] = func;
4488
    w->opaque[w->num] = opaque;
4489
    w->num++;
4490
    return 0;
4491
}
4492

    
4493
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4494
{
4495
    int i, found;
4496
    WaitObjects *w = &wait_objects;
4497

    
4498
    found = 0;
4499
    for (i = 0; i < w->num; i++) {
4500
        if (w->events[i] == handle)
4501
            found = 1;
4502
        if (found) {
4503
            w->events[i] = w->events[i + 1];
4504
            w->func[i] = w->func[i + 1];
4505
            w->opaque[i] = w->opaque[i + 1];
4506
        }            
4507
    }
4508
    if (found)
4509
        w->num--;
4510
}
4511
#endif
4512

    
4513
/***********************************************************/
4514
/* savevm/loadvm support */
4515

    
4516
#define IO_BUF_SIZE 32768
4517

    
4518
struct QEMUFile {
4519
    FILE *outfile;
4520
    BlockDriverState *bs;
4521
    int is_file;
4522
    int is_writable;
4523
    int64_t base_offset;
4524
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4525
                           when reading */
4526
    int buf_index;
4527
    int buf_size; /* 0 when writing */
4528
    uint8_t buf[IO_BUF_SIZE];
4529
};
4530

    
4531
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4532
{
4533
    QEMUFile *f;
4534

    
4535
    f = qemu_mallocz(sizeof(QEMUFile));
4536
    if (!f)
4537
        return NULL;
4538
    if (!strcmp(mode, "wb")) {
4539
        f->is_writable = 1;
4540
    } else if (!strcmp(mode, "rb")) {
4541
        f->is_writable = 0;
4542
    } else {
4543
        goto fail;
4544
    }
4545
    f->outfile = fopen(filename, mode);
4546
    if (!f->outfile)
4547
        goto fail;
4548
    f->is_file = 1;
4549
    return f;
4550
 fail:
4551
    if (f->outfile)
4552
        fclose(f->outfile);
4553
    qemu_free(f);
4554
    return NULL;
4555
}
4556

    
4557
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4558
{
4559
    QEMUFile *f;
4560

    
4561
    f = qemu_mallocz(sizeof(QEMUFile));
4562
    if (!f)
4563
        return NULL;
4564
    f->is_file = 0;
4565
    f->bs = bs;
4566
    f->is_writable = is_writable;
4567
    f->base_offset = offset;
4568
    return f;
4569
}
4570

    
4571
void qemu_fflush(QEMUFile *f)
4572
{
4573
    if (!f->is_writable)
4574
        return;
4575
    if (f->buf_index > 0) {
4576
        if (f->is_file) {
4577
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4578
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4579
        } else {
4580
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4581
                        f->buf, f->buf_index);
4582
        }
4583
        f->buf_offset += f->buf_index;
4584
        f->buf_index = 0;
4585
    }
4586
}
4587

    
4588
static void qemu_fill_buffer(QEMUFile *f)
4589
{
4590
    int len;
4591

    
4592
    if (f->is_writable)
4593
        return;
4594
    if (f->is_file) {
4595
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4596
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4597
        if (len < 0)
4598
            len = 0;
4599
    } else {
4600
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4601
                         f->buf, IO_BUF_SIZE);
4602
        if (len < 0)
4603
            len = 0;
4604
    }
4605
    f->buf_index = 0;
4606
    f->buf_size = len;
4607
    f->buf_offset += len;
4608
}
4609

    
4610
void qemu_fclose(QEMUFile *f)
4611
{
4612
    if (f->is_writable)
4613
        qemu_fflush(f);
4614
    if (f->is_file) {
4615
        fclose(f->outfile);
4616
    }
4617
    qemu_free(f);
4618
}
4619

    
4620
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4621
{
4622
    int l;
4623
    while (size > 0) {
4624
        l = IO_BUF_SIZE - f->buf_index;
4625
        if (l > size)
4626
            l = size;
4627
        memcpy(f->buf + f->buf_index, buf, l);
4628
        f->buf_index += l;
4629
        buf += l;
4630
        size -= l;
4631
        if (f->buf_index >= IO_BUF_SIZE)
4632
            qemu_fflush(f);
4633
    }
4634
}
4635

    
4636
void qemu_put_byte(QEMUFile *f, int v)
4637
{
4638
    f->buf[f->buf_index++] = v;
4639
    if (f->buf_index >= IO_BUF_SIZE)
4640
        qemu_fflush(f);
4641
}
4642

    
4643
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4644
{
4645
    int size, l;
4646

    
4647
    size = size1;
4648
    while (size > 0) {
4649
        l = f->buf_size - f->buf_index;
4650
        if (l == 0) {
4651
            qemu_fill_buffer(f);
4652
            l = f->buf_size - f->buf_index;
4653
            if (l == 0)
4654
                break;
4655
        }
4656
        if (l > size)
4657
            l = size;
4658
        memcpy(buf, f->buf + f->buf_index, l);
4659
        f->buf_index += l;
4660
        buf += l;
4661
        size -= l;
4662
    }
4663
    return size1 - size;
4664
}
4665

    
4666
int qemu_get_byte(QEMUFile *f)
4667
{
4668
    if (f->buf_index >= f->buf_size) {
4669
        qemu_fill_buffer(f);
4670
        if (f->buf_index >= f->buf_size)
4671
            return 0;
4672
    }
4673
    return f->buf[f->buf_index++];
4674
}
4675

    
4676
int64_t qemu_ftell(QEMUFile *f)
4677
{
4678
    return f->buf_offset - f->buf_size + f->buf_index;
4679
}
4680

    
4681
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4682
{
4683
    if (whence == SEEK_SET) {
4684
        /* nothing to do */
4685
    } else if (whence == SEEK_CUR) {
4686
        pos += qemu_ftell(f);
4687
    } else {
4688
        /* SEEK_END not supported */
4689
        return -1;
4690
    }
4691
    if (f->is_writable) {
4692
        qemu_fflush(f);
4693
        f->buf_offset = pos;
4694
    } else {
4695
        f->buf_offset = pos;
4696
        f->buf_index = 0;
4697
        f->buf_size = 0;
4698
    }
4699
    return pos;
4700
}
4701

    
4702
void qemu_put_be16(QEMUFile *f, unsigned int v)
4703
{
4704
    qemu_put_byte(f, v >> 8);
4705
    qemu_put_byte(f, v);
4706
}
4707

    
4708
void qemu_put_be32(QEMUFile *f, unsigned int v)
4709
{
4710
    qemu_put_byte(f, v >> 24);
4711
    qemu_put_byte(f, v >> 16);
4712
    qemu_put_byte(f, v >> 8);
4713
    qemu_put_byte(f, v);
4714
}
4715

    
4716
void qemu_put_be64(QEMUFile *f, uint64_t v)
4717
{
4718
    qemu_put_be32(f, v >> 32);
4719
    qemu_put_be32(f, v);
4720
}
4721

    
4722
unsigned int qemu_get_be16(QEMUFile *f)
4723
{
4724
    unsigned int v;
4725
    v = qemu_get_byte(f) << 8;
4726
    v |= qemu_get_byte(f);
4727
    return v;
4728
}
4729

    
4730
unsigned int qemu_get_be32(QEMUFile *f)
4731
{
4732
    unsigned int v;
4733
    v = qemu_get_byte(f) << 24;
4734
    v |= qemu_get_byte(f) << 16;
4735
    v |= qemu_get_byte(f) << 8;
4736
    v |= qemu_get_byte(f);
4737
    return v;
4738
}
4739

    
4740
uint64_t qemu_get_be64(QEMUFile *f)
4741
{
4742
    uint64_t v;
4743
    v = (uint64_t)qemu_get_be32(f) << 32;
4744
    v |= qemu_get_be32(f);
4745
    return v;
4746
}
4747

    
4748
typedef struct SaveStateEntry {
4749
    char idstr[256];
4750
    int instance_id;
4751
    int version_id;
4752
    SaveStateHandler *save_state;
4753
    LoadStateHandler *load_state;
4754
    void *opaque;
4755
    struct SaveStateEntry *next;
4756
} SaveStateEntry;
4757

    
4758
static SaveStateEntry *first_se;
4759

    
4760
int register_savevm(const char *idstr, 
4761
                    int instance_id, 
4762
                    int version_id,
4763
                    SaveStateHandler *save_state,
4764
                    LoadStateHandler *load_state,
4765
                    void *opaque)
4766
{
4767
    SaveStateEntry *se, **pse;
4768

    
4769
    se = qemu_malloc(sizeof(SaveStateEntry));
4770
    if (!se)
4771
        return -1;
4772
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4773
    se->instance_id = instance_id;
4774
    se->version_id = version_id;
4775
    se->save_state = save_state;
4776
    se->load_state = load_state;
4777
    se->opaque = opaque;
4778
    se->next = NULL;
4779

    
4780
    /* add at the end of list */
4781
    pse = &first_se;
4782
    while (*pse != NULL)
4783
        pse = &(*pse)->next;
4784
    *pse = se;
4785
    return 0;
4786
}
4787

    
4788
#define QEMU_VM_FILE_MAGIC   0x5145564d
4789
#define QEMU_VM_FILE_VERSION 0x00000002
4790

    
4791
int qemu_savevm_state(QEMUFile *f)
4792
{
4793
    SaveStateEntry *se;
4794
    int len, ret;
4795
    int64_t cur_pos, len_pos, total_len_pos;
4796

    
4797
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4798
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4799
    total_len_pos = qemu_ftell(f);
4800
    qemu_put_be64(f, 0); /* total size */
4801

    
4802
    for(se = first_se; se != NULL; se = se->next) {
4803
        /* ID string */
4804
        len = strlen(se->idstr);
4805
        qemu_put_byte(f, len);
4806
        qemu_put_buffer(f, se->idstr, len);
4807

    
4808
        qemu_put_be32(f, se->instance_id);
4809
        qemu_put_be32(f, se->version_id);
4810

    
4811
        /* record size: filled later */
4812
        len_pos = qemu_ftell(f);
4813
        qemu_put_be32(f, 0);
4814
        
4815
        se->save_state(f, se->opaque);
4816

    
4817
        /* fill record size */
4818
        cur_pos = qemu_ftell(f);
4819
        len = cur_pos - len_pos - 4;
4820
        qemu_fseek(f, len_pos, SEEK_SET);
4821
        qemu_put_be32(f, len);
4822
        qemu_fseek(f, cur_pos, SEEK_SET);
4823
    }
4824
    cur_pos = qemu_ftell(f);
4825
    qemu_fseek(f, total_len_pos, SEEK_SET);
4826
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4827
    qemu_fseek(f, cur_pos, SEEK_SET);
4828

    
4829
    ret = 0;
4830
    return ret;
4831
}
4832

    
4833
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4834
{
4835
    SaveStateEntry *se;
4836

    
4837
    for(se = first_se; se != NULL; se = se->next) {
4838
        if (!strcmp(se->idstr, idstr) && 
4839
            instance_id == se->instance_id)
4840
            return se;
4841
    }
4842
    return NULL;
4843
}
4844

    
4845
int qemu_loadvm_state(QEMUFile *f)
4846
{
4847
    SaveStateEntry *se;
4848
    int len, ret, instance_id, record_len, version_id;
4849
    int64_t total_len, end_pos, cur_pos;
4850
    unsigned int v;
4851
    char idstr[256];
4852
    
4853
    v = qemu_get_be32(f);
4854
    if (v != QEMU_VM_FILE_MAGIC)
4855
        goto fail;
4856
    v = qemu_get_be32(f);
4857
    if (v != QEMU_VM_FILE_VERSION) {
4858
    fail:
4859
        ret = -1;
4860
        goto the_end;
4861
    }
4862
    total_len = qemu_get_be64(f);
4863
    end_pos = total_len + qemu_ftell(f);
4864
    for(;;) {
4865
        if (qemu_ftell(f) >= end_pos)
4866
            break;
4867
        len = qemu_get_byte(f);
4868
        qemu_get_buffer(f, idstr, len);
4869
        idstr[len] = '\0';
4870
        instance_id = qemu_get_be32(f);
4871
        version_id = qemu_get_be32(f);
4872
        record_len = qemu_get_be32(f);
4873
#if 0
4874
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4875
               idstr, instance_id, version_id, record_len);
4876
#endif
4877
        cur_pos = qemu_ftell(f);
4878
        se = find_se(idstr, instance_id);
4879
        if (!se) {
4880
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4881
                    instance_id, idstr);
4882
        } else {
4883
            ret = se->load_state(f, se->opaque, version_id);
4884
            if (ret < 0) {
4885
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4886
                        instance_id, idstr);
4887
            }
4888
        }
4889
        /* always seek to exact end of record */
4890
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4891
    }
4892
    ret = 0;
4893
 the_end:
4894
    return ret;
4895
}
4896

    
4897
/* device can contain snapshots */
4898
static int bdrv_can_snapshot(BlockDriverState *bs)
4899
{
4900
    return (bs &&
4901
            !bdrv_is_removable(bs) &&
4902
            !bdrv_is_read_only(bs));
4903
}
4904

    
4905
/* device must be snapshots in order to have a reliable snapshot */
4906
static int bdrv_has_snapshot(BlockDriverState *bs)
4907
{
4908
    return (bs &&
4909
            !bdrv_is_removable(bs) &&
4910
            !bdrv_is_read_only(bs));
4911
}
4912

    
4913
static BlockDriverState *get_bs_snapshots(void)
4914
{
4915
    BlockDriverState *bs;
4916
    int i;
4917

    
4918
    if (bs_snapshots)
4919
        return bs_snapshots;
4920
    for(i = 0; i <= MAX_DISKS; i++) {
4921
        bs = bs_table[i];
4922
        if (bdrv_can_snapshot(bs))
4923
            goto ok;
4924
    }
4925
    return NULL;
4926
 ok:
4927
    bs_snapshots = bs;
4928
    return bs;
4929
}
4930

    
4931
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4932
                              const char *name)
4933
{
4934
    QEMUSnapshotInfo *sn_tab, *sn;
4935
    int nb_sns, i, ret;
4936
    
4937
    ret = -ENOENT;
4938
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4939
    if (nb_sns < 0)
4940
        return ret;
4941
    for(i = 0; i < nb_sns; i++) {
4942
        sn = &sn_tab[i];
4943
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4944
            *sn_info = *sn;
4945
            ret = 0;
4946
            break;
4947
        }
4948
    }
4949
    qemu_free(sn_tab);
4950
    return ret;
4951
}
4952

    
4953
void do_savevm(const char *name)
4954
{
4955
    BlockDriverState *bs, *bs1;
4956
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4957
    int must_delete, ret, i;
4958
    BlockDriverInfo bdi1, *bdi = &bdi1;
4959
    QEMUFile *f;
4960
    int saved_vm_running;
4961
#ifdef _WIN32
4962
    struct _timeb tb;
4963
#else
4964
    struct timeval tv;
4965
#endif
4966

    
4967
    bs = get_bs_snapshots();
4968
    if (!bs) {
4969
        term_printf("No block device can accept snapshots\n");
4970
        return;
4971
    }
4972

    
4973
    /* ??? Should this occur after vm_stop?  */
4974
    qemu_aio_flush();
4975

    
4976
    saved_vm_running = vm_running;
4977
    vm_stop(0);
4978
    
4979
    must_delete = 0;
4980
    if (name) {
4981
        ret = bdrv_snapshot_find(bs, old_sn, name);
4982
        if (ret >= 0) {
4983
            must_delete = 1;
4984
        }
4985
    }
4986
    memset(sn, 0, sizeof(*sn));
4987
    if (must_delete) {
4988
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4989
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4990
    } else {
4991
        if (name)
4992
            pstrcpy(sn->name, sizeof(sn->name), name);
4993
    }
4994

    
4995
    /* fill auxiliary fields */
4996
#ifdef _WIN32
4997
    _ftime(&tb);
4998
    sn->date_sec = tb.time;
4999
    sn->date_nsec = tb.millitm * 1000000;
5000
#else
5001
    gettimeofday(&tv, NULL);
5002
    sn->date_sec = tv.tv_sec;
5003
    sn->date_nsec = tv.tv_usec * 1000;
5004
#endif
5005
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5006
    
5007
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5008
        term_printf("Device %s does not support VM state snapshots\n",
5009
                    bdrv_get_device_name(bs));
5010
        goto the_end;
5011
    }
5012
    
5013
    /* save the VM state */
5014
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5015
    if (!f) {
5016
        term_printf("Could not open VM state file\n");
5017
        goto the_end;
5018
    }
5019
    ret = qemu_savevm_state(f);
5020
    sn->vm_state_size = qemu_ftell(f);
5021
    qemu_fclose(f);
5022
    if (ret < 0) {
5023
        term_printf("Error %d while writing VM\n", ret);
5024
        goto the_end;
5025
    }
5026
    
5027
    /* create the snapshots */
5028

    
5029
    for(i = 0; i < MAX_DISKS; i++) {
5030
        bs1 = bs_table[i];
5031
        if (bdrv_has_snapshot(bs1)) {
5032
            if (must_delete) {
5033
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5034
                if (ret < 0) {
5035
                    term_printf("Error while deleting snapshot on '%s'\n",
5036
                                bdrv_get_device_name(bs1));
5037
                }
5038
            }
5039
            ret = bdrv_snapshot_create(bs1, sn);
5040
            if (ret < 0) {
5041
                term_printf("Error while creating snapshot on '%s'\n",
5042
                            bdrv_get_device_name(bs1));
5043
            }
5044
        }
5045
    }
5046

    
5047
 the_end:
5048
    if (saved_vm_running)
5049
        vm_start();
5050
}
5051

    
5052
void do_loadvm(const char *name)
5053
{
5054
    BlockDriverState *bs, *bs1;
5055
    BlockDriverInfo bdi1, *bdi = &bdi1;
5056
    QEMUFile *f;
5057
    int i, ret;
5058
    int saved_vm_running;
5059

    
5060
    bs = get_bs_snapshots();
5061
    if (!bs) {
5062
        term_printf("No block device supports snapshots\n");
5063
        return;
5064
    }
5065
    
5066
    /* Flush all IO requests so they don't interfere with the new state.  */
5067
    qemu_aio_flush();
5068

    
5069
    saved_vm_running = vm_running;
5070
    vm_stop(0);
5071

    
5072
    for(i = 0; i <= MAX_DISKS; i++) {
5073
        bs1 = bs_table[i];
5074
        if (bdrv_has_snapshot(bs1)) {
5075
            ret = bdrv_snapshot_goto(bs1, name);
5076
            if (ret < 0) {
5077
                if (bs != bs1)
5078
                    term_printf("Warning: ");
5079
                switch(ret) {
5080
                case -ENOTSUP:
5081
                    term_printf("Snapshots not supported on device '%s'\n",
5082
                                bdrv_get_device_name(bs1));
5083
                    break;
5084
                case -ENOENT:
5085
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
5086
                                name, bdrv_get_device_name(bs1));
5087
                    break;
5088
                default:
5089
                    term_printf("Error %d while activating snapshot on '%s'\n",
5090
                                ret, bdrv_get_device_name(bs1));
5091
                    break;
5092
                }
5093
                /* fatal on snapshot block device */
5094
                if (bs == bs1)
5095
                    goto the_end;
5096
            }
5097
        }
5098
    }
5099

    
5100
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5101
        term_printf("Device %s does not support VM state snapshots\n",
5102
                    bdrv_get_device_name(bs));
5103
        return;
5104
    }
5105
    
5106
    /* restore the VM state */
5107
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5108
    if (!f) {
5109
        term_printf("Could not open VM state file\n");
5110
        goto the_end;
5111
    }
5112
    ret = qemu_loadvm_state(f);
5113
    qemu_fclose(f);
5114
    if (ret < 0) {
5115
        term_printf("Error %d while loading VM state\n", ret);
5116
    }
5117
 the_end:
5118
    if (saved_vm_running)
5119
        vm_start();
5120
}
5121

    
5122
void do_delvm(const char *name)
5123
{
5124
    BlockDriverState *bs, *bs1;
5125
    int i, ret;
5126

    
5127
    bs = get_bs_snapshots();
5128
    if (!bs) {
5129
        term_printf("No block device supports snapshots\n");
5130
        return;
5131
    }
5132
    
5133
    for(i = 0; i <= MAX_DISKS; i++) {
5134
        bs1 = bs_table[i];
5135
        if (bdrv_has_snapshot(bs1)) {
5136
            ret = bdrv_snapshot_delete(bs1, name);
5137
            if (ret < 0) {
5138
                if (ret == -ENOTSUP)
5139
                    term_printf("Snapshots not supported on device '%s'\n",
5140
                                bdrv_get_device_name(bs1));
5141
                else
5142
                    term_printf("Error %d while deleting snapshot on '%s'\n",
5143
                                ret, bdrv_get_device_name(bs1));
5144
            }
5145
        }
5146
    }
5147
}
5148

    
5149
void do_info_snapshots(void)
5150
{
5151
    BlockDriverState *bs, *bs1;
5152
    QEMUSnapshotInfo *sn_tab, *sn;
5153
    int nb_sns, i;
5154
    char buf[256];
5155

    
5156
    bs = get_bs_snapshots();
5157
    if (!bs) {
5158
        term_printf("No available block device supports snapshots\n");
5159
        return;
5160
    }
5161
    term_printf("Snapshot devices:");
5162
    for(i = 0; i <= MAX_DISKS; i++) {
5163
        bs1 = bs_table[i];
5164
        if (bdrv_has_snapshot(bs1)) {
5165
            if (bs == bs1)
5166
                term_printf(" %s", bdrv_get_device_name(bs1));
5167
        }
5168
    }
5169
    term_printf("\n");
5170

    
5171
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5172
    if (nb_sns < 0) {
5173
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5174
        return;
5175
    }
5176
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5177
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5178
    for(i = 0; i < nb_sns; i++) {
5179
        sn = &sn_tab[i];
5180
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5181
    }
5182
    qemu_free(sn_tab);
5183
}
5184

    
5185
/***********************************************************/
5186
/* cpu save/restore */
5187

    
5188
#if defined(TARGET_I386)
5189

    
5190
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5191
{
5192
    qemu_put_be32(f, dt->selector);
5193
    qemu_put_betl(f, dt->base);
5194
    qemu_put_be32(f, dt->limit);
5195
    qemu_put_be32(f, dt->flags);
5196
}
5197

    
5198
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5199
{
5200
    dt->selector = qemu_get_be32(f);
5201
    dt->base = qemu_get_betl(f);
5202
    dt->limit = qemu_get_be32(f);
5203
    dt->flags = qemu_get_be32(f);
5204
}
5205

    
5206
void cpu_save(QEMUFile *f, void *opaque)
5207
{
5208
    CPUState *env = opaque;
5209
    uint16_t fptag, fpus, fpuc, fpregs_format;
5210
    uint32_t hflags;
5211
    int i;
5212
    
5213
    for(i = 0; i < CPU_NB_REGS; i++)
5214
        qemu_put_betls(f, &env->regs[i]);
5215
    qemu_put_betls(f, &env->eip);
5216
    qemu_put_betls(f, &env->eflags);
5217
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5218
    qemu_put_be32s(f, &hflags);
5219
    
5220
    /* FPU */
5221
    fpuc = env->fpuc;
5222
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5223
    fptag = 0;
5224
    for(i = 0; i < 8; i++) {
5225
        fptag |= ((!env->fptags[i]) << i);
5226
    }
5227
    
5228
    qemu_put_be16s(f, &fpuc);
5229
    qemu_put_be16s(f, &fpus);
5230
    qemu_put_be16s(f, &fptag);
5231

    
5232
#ifdef USE_X86LDOUBLE
5233
    fpregs_format = 0;
5234
#else
5235
    fpregs_format = 1;
5236
#endif
5237
    qemu_put_be16s(f, &fpregs_format);
5238
    
5239
    for(i = 0; i < 8; i++) {
5240
#ifdef USE_X86LDOUBLE
5241
        {
5242
            uint64_t mant;
5243
            uint16_t exp;
5244
            /* we save the real CPU data (in case of MMX usage only 'mant'
5245
               contains the MMX register */
5246
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5247
            qemu_put_be64(f, mant);
5248
            qemu_put_be16(f, exp);
5249
        }
5250
#else
5251
        /* if we use doubles for float emulation, we save the doubles to
5252
           avoid losing information in case of MMX usage. It can give
5253
           problems if the image is restored on a CPU where long
5254
           doubles are used instead. */
5255
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5256
#endif
5257
    }
5258

    
5259
    for(i = 0; i < 6; i++)
5260
        cpu_put_seg(f, &env->segs[i]);
5261
    cpu_put_seg(f, &env->ldt);
5262
    cpu_put_seg(f, &env->tr);
5263
    cpu_put_seg(f, &env->gdt);
5264
    cpu_put_seg(f, &env->idt);
5265
    
5266
    qemu_put_be32s(f, &env->sysenter_cs);
5267
    qemu_put_be32s(f, &env->sysenter_esp);
5268
    qemu_put_be32s(f, &env->sysenter_eip);
5269
    
5270
    qemu_put_betls(f, &env->cr[0]);
5271
    qemu_put_betls(f, &env->cr[2]);
5272
    qemu_put_betls(f, &env->cr[3]);
5273
    qemu_put_betls(f, &env->cr[4]);
5274
    
5275
    for(i = 0; i < 8; i++)
5276
        qemu_put_betls(f, &env->dr[i]);
5277

    
5278
    /* MMU */
5279
    qemu_put_be32s(f, &env->a20_mask);
5280

    
5281
    /* XMM */
5282
    qemu_put_be32s(f, &env->mxcsr);
5283
    for(i = 0; i < CPU_NB_REGS; i++) {
5284
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5285
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5286
    }
5287

    
5288
#ifdef TARGET_X86_64
5289
    qemu_put_be64s(f, &env->efer);
5290
    qemu_put_be64s(f, &env->star);
5291
    qemu_put_be64s(f, &env->lstar);
5292
    qemu_put_be64s(f, &env->cstar);
5293
    qemu_put_be64s(f, &env->fmask);
5294
    qemu_put_be64s(f, &env->kernelgsbase);
5295
#endif
5296
    qemu_put_be32s(f, &env->smbase);
5297
}
5298

    
5299
#ifdef USE_X86LDOUBLE
5300
/* XXX: add that in a FPU generic layer */
5301
union x86_longdouble {
5302
    uint64_t mant;
5303
    uint16_t exp;
5304
};
5305

    
5306
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5307
#define EXPBIAS1 1023
5308
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5309
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5310

    
5311
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5312
{
5313
    int e;
5314
    /* mantissa */
5315
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5316
    /* exponent + sign */
5317
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5318
    e |= SIGND1(temp) >> 16;
5319
    p->exp = e;
5320
}
5321
#endif
5322

    
5323
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5324
{
5325
    CPUState *env = opaque;
5326
    int i, guess_mmx;
5327
    uint32_t hflags;
5328
    uint16_t fpus, fpuc, fptag, fpregs_format;
5329

    
5330
    if (version_id != 3 && version_id != 4)
5331
        return -EINVAL;
5332
    for(i = 0; i < CPU_NB_REGS; i++)
5333
        qemu_get_betls(f, &env->regs[i]);
5334
    qemu_get_betls(f, &env->eip);
5335
    qemu_get_betls(f, &env->eflags);
5336
    qemu_get_be32s(f, &hflags);
5337

    
5338
    qemu_get_be16s(f, &fpuc);
5339
    qemu_get_be16s(f, &fpus);
5340
    qemu_get_be16s(f, &fptag);
5341
    qemu_get_be16s(f, &fpregs_format);
5342
    
5343
    /* NOTE: we cannot always restore the FPU state if the image come
5344
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5345
       if we are in an MMX state to restore correctly in that case. */
5346
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5347
    for(i = 0; i < 8; i++) {
5348
        uint64_t mant;
5349
        uint16_t exp;
5350
        
5351
        switch(fpregs_format) {
5352
        case 0:
5353
            mant = qemu_get_be64(f);
5354
            exp = qemu_get_be16(f);
5355
#ifdef USE_X86LDOUBLE
5356
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5357
#else
5358
            /* difficult case */
5359
            if (guess_mmx)
5360
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5361
            else
5362
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5363
#endif
5364
            break;
5365
        case 1:
5366
            mant = qemu_get_be64(f);
5367
#ifdef USE_X86LDOUBLE
5368
            {
5369
                union x86_longdouble *p;
5370
                /* difficult case */
5371
                p = (void *)&env->fpregs[i];
5372
                if (guess_mmx) {
5373
                    p->mant = mant;
5374
                    p->exp = 0xffff;
5375
                } else {
5376
                    fp64_to_fp80(p, mant);
5377
                }
5378
            }
5379
#else
5380
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5381
#endif            
5382
            break;
5383
        default:
5384
            return -EINVAL;
5385
        }
5386
    }
5387

    
5388
    env->fpuc = fpuc;
5389
    /* XXX: restore FPU round state */
5390
    env->fpstt = (fpus >> 11) & 7;
5391
    env->fpus = fpus & ~0x3800;
5392
    fptag ^= 0xff;
5393
    for(i = 0; i < 8; i++) {
5394
        env->fptags[i] = (fptag >> i) & 1;
5395
    }
5396
    
5397
    for(i = 0; i < 6; i++)
5398
        cpu_get_seg(f, &env->segs[i]);
5399
    cpu_get_seg(f, &env->ldt);
5400
    cpu_get_seg(f, &env->tr);
5401
    cpu_get_seg(f, &env->gdt);
5402
    cpu_get_seg(f, &env->idt);
5403
    
5404
    qemu_get_be32s(f, &env->sysenter_cs);
5405
    qemu_get_be32s(f, &env->sysenter_esp);
5406
    qemu_get_be32s(f, &env->sysenter_eip);
5407
    
5408
    qemu_get_betls(f, &env->cr[0]);
5409
    qemu_get_betls(f, &env->cr[2]);
5410
    qemu_get_betls(f, &env->cr[3]);
5411
    qemu_get_betls(f, &env->cr[4]);
5412
    
5413
    for(i = 0; i < 8; i++)
5414
        qemu_get_betls(f, &env->dr[i]);
5415

    
5416
    /* MMU */
5417
    qemu_get_be32s(f, &env->a20_mask);
5418

    
5419
    qemu_get_be32s(f, &env->mxcsr);
5420
    for(i = 0; i < CPU_NB_REGS; i++) {
5421
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5422
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5423
    }
5424

    
5425
#ifdef TARGET_X86_64
5426
    qemu_get_be64s(f, &env->efer);
5427
    qemu_get_be64s(f, &env->star);
5428
    qemu_get_be64s(f, &env->lstar);
5429
    qemu_get_be64s(f, &env->cstar);
5430
    qemu_get_be64s(f, &env->fmask);
5431
    qemu_get_be64s(f, &env->kernelgsbase);
5432
#endif
5433
    if (version_id >= 4) 
5434
        qemu_get_be32s(f, &env->smbase);
5435

    
5436
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5437
    env->hflags = hflags;
5438
    tlb_flush(env, 1);
5439
    return 0;
5440
}
5441

    
5442
#elif defined(TARGET_PPC)
5443
void cpu_save(QEMUFile *f, void *opaque)
5444
{
5445
}
5446

    
5447
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5448
{
5449
    return 0;
5450
}
5451

    
5452
#elif defined(TARGET_MIPS)
5453
void cpu_save(QEMUFile *f, void *opaque)
5454
{
5455
}
5456

    
5457
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5458
{
5459
    return 0;
5460
}
5461

    
5462
#elif defined(TARGET_SPARC)
5463
void cpu_save(QEMUFile *f, void *opaque)
5464
{
5465
    CPUState *env = opaque;
5466
    int i;
5467
    uint32_t tmp;
5468

    
5469
    for(i = 0; i < 8; i++)
5470
        qemu_put_betls(f, &env->gregs[i]);
5471
    for(i = 0; i < NWINDOWS * 16; i++)
5472
        qemu_put_betls(f, &env->regbase[i]);
5473

    
5474
    /* FPU */
5475
    for(i = 0; i < TARGET_FPREGS; i++) {
5476
        union {
5477
            float32 f;
5478
            uint32_t i;
5479
        } u;
5480
        u.f = env->fpr[i];
5481
        qemu_put_be32(f, u.i);
5482
    }
5483

    
5484
    qemu_put_betls(f, &env->pc);
5485
    qemu_put_betls(f, &env->npc);
5486
    qemu_put_betls(f, &env->y);
5487
    tmp = GET_PSR(env);
5488
    qemu_put_be32(f, tmp);
5489
    qemu_put_betls(f, &env->fsr);
5490
    qemu_put_betls(f, &env->tbr);
5491
#ifndef TARGET_SPARC64
5492
    qemu_put_be32s(f, &env->wim);
5493
    /* MMU */
5494
    for(i = 0; i < 16; i++)
5495
        qemu_put_be32s(f, &env->mmuregs[i]);
5496
#endif
5497
}
5498

    
5499
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5500
{
5501
    CPUState *env = opaque;
5502
    int i;
5503
    uint32_t tmp;
5504

    
5505
    for(i = 0; i < 8; i++)
5506
        qemu_get_betls(f, &env->gregs[i]);
5507
    for(i = 0; i < NWINDOWS * 16; i++)
5508
        qemu_get_betls(f, &env->regbase[i]);
5509

    
5510
    /* FPU */
5511
    for(i = 0; i < TARGET_FPREGS; i++) {
5512
        union {
5513
            float32 f;
5514
            uint32_t i;
5515
        } u;
5516
        u.i = qemu_get_be32(f);
5517
        env->fpr[i] = u.f;
5518
    }
5519

    
5520
    qemu_get_betls(f, &env->pc);
5521
    qemu_get_betls(f, &env->npc);
5522
    qemu_get_betls(f, &env->y);
5523
    tmp = qemu_get_be32(f);
5524
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5525
                     correctly updated */
5526
    PUT_PSR(env, tmp);
5527
    qemu_get_betls(f, &env->fsr);
5528
    qemu_get_betls(f, &env->tbr);
5529
#ifndef TARGET_SPARC64
5530
    qemu_get_be32s(f, &env->wim);
5531
    /* MMU */
5532
    for(i = 0; i < 16; i++)
5533
        qemu_get_be32s(f, &env->mmuregs[i]);
5534
#endif
5535
    tlb_flush(env, 1);
5536
    return 0;
5537
}
5538

    
5539
#elif defined(TARGET_ARM)
5540

    
5541
/* ??? Need to implement these.  */
5542
void cpu_save(QEMUFile *f, void *opaque)
5543
{
5544
}
5545

    
5546
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5547
{
5548
    return 0;
5549
}
5550

    
5551
#else
5552

    
5553
#warning No CPU save/restore functions
5554

    
5555
#endif
5556

    
5557
/***********************************************************/
5558
/* ram save/restore */
5559

    
5560
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5561
{
5562
    int v;
5563

    
5564
    v = qemu_get_byte(f);
5565
    switch(v) {
5566
    case 0:
5567
        if (qemu_get_buffer(f, buf, len) != len)
5568
            return -EIO;
5569
        break;
5570
    case 1:
5571
        v = qemu_get_byte(f);
5572
        memset(buf, v, len);
5573
        break;
5574
    default:
5575
        return -EINVAL;
5576
    }
5577
    return 0;
5578
}
5579

    
5580
static int ram_load_v1(QEMUFile *f, void *opaque)
5581
{
5582
    int i, ret;
5583

    
5584
    if (qemu_get_be32(f) != phys_ram_size)
5585
        return -EINVAL;
5586
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5587
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5588
        if (ret)
5589
            return ret;
5590
    }
5591
    return 0;
5592
}
5593

    
5594
#define BDRV_HASH_BLOCK_SIZE 1024
5595
#define IOBUF_SIZE 4096
5596
#define RAM_CBLOCK_MAGIC 0xfabe
5597

    
5598
typedef struct RamCompressState {
5599
    z_stream zstream;
5600
    QEMUFile *f;
5601
    uint8_t buf[IOBUF_SIZE];
5602
} RamCompressState;
5603

    
5604
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5605
{
5606
    int ret;
5607
    memset(s, 0, sizeof(*s));
5608
    s->f = f;
5609
    ret = deflateInit2(&s->zstream, 1,
5610
                       Z_DEFLATED, 15, 
5611
                       9, Z_DEFAULT_STRATEGY);
5612
    if (ret != Z_OK)
5613
        return -1;
5614
    s->zstream.avail_out = IOBUF_SIZE;
5615
    s->zstream.next_out = s->buf;
5616
    return 0;
5617
}
5618

    
5619
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5620
{
5621
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5622
    qemu_put_be16(s->f, len);
5623
    qemu_put_buffer(s->f, buf, len);
5624
}
5625

    
5626
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5627
{
5628
    int ret;
5629

    
5630
    s->zstream.avail_in = len;
5631
    s->zstream.next_in = (uint8_t *)buf;
5632
    while (s->zstream.avail_in > 0) {
5633
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5634
        if (ret != Z_OK)
5635
            return -1;
5636
        if (s->zstream.avail_out == 0) {
5637
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5638
            s->zstream.avail_out = IOBUF_SIZE;
5639
            s->zstream.next_out = s->buf;
5640
        }
5641
    }
5642
    return 0;
5643
}
5644

    
5645
static void ram_compress_close(RamCompressState *s)
5646
{
5647
    int len, ret;
5648

    
5649
    /* compress last bytes */
5650
    for(;;) {
5651
        ret = deflate(&s->zstream, Z_FINISH);
5652
        if (ret == Z_OK || ret == Z_STREAM_END) {
5653
            len = IOBUF_SIZE - s->zstream.avail_out;
5654
            if (len > 0) {
5655
                ram_put_cblock(s, s->buf, len);
5656
            }
5657
            s->zstream.avail_out = IOBUF_SIZE;
5658
            s->zstream.next_out = s->buf;
5659
            if (ret == Z_STREAM_END)
5660
                break;
5661
        } else {
5662
            goto fail;
5663
        }
5664
    }
5665
fail:
5666
    deflateEnd(&s->zstream);
5667
}
5668

    
5669
typedef struct RamDecompressState {
5670
    z_stream zstream;
5671
    QEMUFile *f;
5672
    uint8_t buf[IOBUF_SIZE];
5673
} RamDecompressState;
5674

    
5675
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5676
{
5677
    int ret;
5678
    memset(s, 0, sizeof(*s));
5679
    s->f = f;
5680
    ret = inflateInit(&s->zstream);
5681
    if (ret != Z_OK)
5682
        return -1;
5683
    return 0;
5684
}
5685

    
5686
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5687
{
5688
    int ret, clen;
5689

    
5690
    s->zstream.avail_out = len;
5691
    s->zstream.next_out = buf;
5692
    while (s->zstream.avail_out > 0) {
5693
        if (s->zstream.avail_in == 0) {
5694
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5695
                return -1;
5696
            clen = qemu_get_be16(s->f);
5697
            if (clen > IOBUF_SIZE)
5698
                return -1;
5699
            qemu_get_buffer(s->f, s->buf, clen);
5700
            s->zstream.avail_in = clen;
5701
            s->zstream.next_in = s->buf;
5702
        }
5703
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5704
        if (ret != Z_OK && ret != Z_STREAM_END) {
5705
            return -1;
5706
        }
5707
    }
5708
    return 0;
5709
}
5710

    
5711
static void ram_decompress_close(RamDecompressState *s)
5712
{
5713
    inflateEnd(&s->zstream);
5714
}
5715

    
5716
static void ram_save(QEMUFile *f, void *opaque)
5717
{
5718
    int i;
5719
    RamCompressState s1, *s = &s1;
5720
    uint8_t buf[10];
5721
    
5722
    qemu_put_be32(f, phys_ram_size);
5723
    if (ram_compress_open(s, f) < 0)
5724
        return;
5725
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5726
#if 0
5727
        if (tight_savevm_enabled) {
5728
            int64_t sector_num;
5729
            int j;
5730

5731
            /* find if the memory block is available on a virtual
5732
               block device */
5733
            sector_num = -1;
5734
            for(j = 0; j < MAX_DISKS; j++) {
5735
                if (bs_table[j]) {
5736
                    sector_num = bdrv_hash_find(bs_table[j], 
5737
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5738
                    if (sector_num >= 0)
5739
                        break;
5740
                }
5741
            }
5742
            if (j == MAX_DISKS)
5743
                goto normal_compress;
5744
            buf[0] = 1;
5745
            buf[1] = j;
5746
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5747
            ram_compress_buf(s, buf, 10);
5748
        } else 
5749
#endif
5750
        {
5751
            //        normal_compress:
5752
            buf[0] = 0;
5753
            ram_compress_buf(s, buf, 1);
5754
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5755
        }
5756
    }
5757
    ram_compress_close(s);
5758
}
5759

    
5760
static int ram_load(QEMUFile *f, void *opaque, int version_id)
5761
{
5762
    RamDecompressState s1, *s = &s1;
5763
    uint8_t buf[10];
5764
    int i;
5765

    
5766
    if (version_id == 1)
5767
        return ram_load_v1(f, opaque);
5768
    if (version_id != 2)
5769
        return -EINVAL;
5770
    if (qemu_get_be32(f) != phys_ram_size)
5771
        return -EINVAL;
5772
    if (ram_decompress_open(s, f) < 0)
5773
        return -EINVAL;
5774
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5775
        if (ram_decompress_buf(s, buf, 1) < 0) {
5776
            fprintf(stderr, "Error while reading ram block header\n");
5777
            goto error;
5778
        }
5779
        if (buf[0] == 0) {
5780
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5781
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5782
                goto error;
5783
            }
5784
        } else 
5785
#if 0
5786
        if (buf[0] == 1) {
5787
            int bs_index;
5788
            int64_t sector_num;
5789

5790
            ram_decompress_buf(s, buf + 1, 9);
5791
            bs_index = buf[1];
5792
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5793
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5794
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
5795
                goto error;
5796
            }
5797
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5798
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5799
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5800
                        bs_index, sector_num);
5801
                goto error;
5802
            }
5803
        } else 
5804
#endif
5805
        {
5806
        error:
5807
            printf("Error block header\n");
5808
            return -EINVAL;
5809
        }
5810
    }
5811
    ram_decompress_close(s);
5812
    return 0;
5813
}
5814

    
5815
/***********************************************************/
5816
/* bottom halves (can be seen as timers which expire ASAP) */
5817

    
5818
struct QEMUBH {
5819
    QEMUBHFunc *cb;
5820
    void *opaque;
5821
    int scheduled;
5822
    QEMUBH *next;
5823
};
5824

    
5825
static QEMUBH *first_bh = NULL;
5826

    
5827
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5828
{
5829
    QEMUBH *bh;
5830
    bh = qemu_mallocz(sizeof(QEMUBH));
5831
    if (!bh)
5832
        return NULL;
5833
    bh->cb = cb;
5834
    bh->opaque = opaque;
5835
    return bh;
5836
}
5837

    
5838
int qemu_bh_poll(void)
5839
{
5840
    QEMUBH *bh, **pbh;
5841
    int ret;
5842

    
5843
    ret = 0;
5844
    for(;;) {
5845
        pbh = &first_bh;
5846
        bh = *pbh;
5847
        if (!bh)
5848
            break;
5849
        ret = 1;
5850
        *pbh = bh->next;
5851
        bh->scheduled = 0;
5852
        bh->cb(bh->opaque);
5853
    }
5854
    return ret;
5855
}
5856

    
5857
void qemu_bh_schedule(QEMUBH *bh)
5858
{
5859
    CPUState *env = cpu_single_env;
5860
    if (bh->scheduled)
5861
        return;
5862
    bh->scheduled = 1;
5863
    bh->next = first_bh;
5864
    first_bh = bh;
5865

    
5866
    /* stop the currently executing CPU to execute the BH ASAP */
5867
    if (env) {
5868
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5869
    }
5870
}
5871

    
5872
void qemu_bh_cancel(QEMUBH *bh)
5873
{
5874
    QEMUBH **pbh;
5875
    if (bh->scheduled) {
5876
        pbh = &first_bh;
5877
        while (*pbh != bh)
5878
            pbh = &(*pbh)->next;
5879
        *pbh = bh->next;
5880
        bh->scheduled = 0;
5881
    }
5882
}
5883

    
5884
void qemu_bh_delete(QEMUBH *bh)
5885
{
5886
    qemu_bh_cancel(bh);
5887
    qemu_free(bh);
5888
}
5889

    
5890
/***********************************************************/
5891
/* machine registration */
5892

    
5893
QEMUMachine *first_machine = NULL;
5894

    
5895
int qemu_register_machine(QEMUMachine *m)
5896
{
5897
    QEMUMachine **pm;
5898
    pm = &first_machine;
5899
    while (*pm != NULL)
5900
        pm = &(*pm)->next;
5901
    m->next = NULL;
5902
    *pm = m;
5903
    return 0;
5904
}
5905

    
5906
QEMUMachine *find_machine(const char *name)
5907
{
5908
    QEMUMachine *m;
5909

    
5910
    for(m = first_machine; m != NULL; m = m->next) {
5911
        if (!strcmp(m->name, name))
5912
            return m;
5913
    }
5914
    return NULL;
5915
}
5916

    
5917
/***********************************************************/
5918
/* main execution loop */
5919

    
5920
void gui_update(void *opaque)
5921
{
5922
    display_state.dpy_refresh(&display_state);
5923
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5924
}
5925

    
5926
struct vm_change_state_entry {
5927
    VMChangeStateHandler *cb;
5928
    void *opaque;
5929
    LIST_ENTRY (vm_change_state_entry) entries;
5930
};
5931

    
5932
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5933

    
5934
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5935
                                                     void *opaque)
5936
{
5937
    VMChangeStateEntry *e;
5938

    
5939
    e = qemu_mallocz(sizeof (*e));
5940
    if (!e)
5941
        return NULL;
5942

    
5943
    e->cb = cb;
5944
    e->opaque = opaque;
5945
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5946
    return e;
5947
}
5948

    
5949
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5950
{
5951
    LIST_REMOVE (e, entries);
5952
    qemu_free (e);
5953
}
5954

    
5955
static void vm_state_notify(int running)
5956
{
5957
    VMChangeStateEntry *e;
5958

    
5959
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5960
        e->cb(e->opaque, running);
5961
    }
5962
}
5963

    
5964
/* XXX: support several handlers */
5965
static VMStopHandler *vm_stop_cb;
5966
static void *vm_stop_opaque;
5967

    
5968
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5969
{
5970
    vm_stop_cb = cb;
5971
    vm_stop_opaque = opaque;
5972
    return 0;
5973
}
5974

    
5975
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5976
{
5977
    vm_stop_cb = NULL;
5978
}
5979

    
5980
void vm_start(void)
5981
{
5982
    if (!vm_running) {
5983
        cpu_enable_ticks();
5984
        vm_running = 1;
5985
        vm_state_notify(1);
5986
    }
5987
}
5988

    
5989
void vm_stop(int reason) 
5990
{
5991
    if (vm_running) {
5992
        cpu_disable_ticks();
5993
        vm_running = 0;
5994
        if (reason != 0) {
5995
            if (vm_stop_cb) {
5996
                vm_stop_cb(vm_stop_opaque, reason);
5997
            }
5998
        }
5999
        vm_state_notify(0);
6000
    }
6001
}
6002

    
6003
/* reset/shutdown handler */
6004

    
6005
typedef struct QEMUResetEntry {
6006
    QEMUResetHandler *func;
6007
    void *opaque;
6008
    struct QEMUResetEntry *next;
6009
} QEMUResetEntry;
6010

    
6011
static QEMUResetEntry *first_reset_entry;
6012
static int reset_requested;
6013
static int shutdown_requested;
6014
static int powerdown_requested;
6015

    
6016
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6017
{
6018
    QEMUResetEntry **pre, *re;
6019

    
6020
    pre = &first_reset_entry;
6021
    while (*pre != NULL)
6022
        pre = &(*pre)->next;
6023
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6024
    re->func = func;
6025
    re->opaque = opaque;
6026
    re->next = NULL;
6027
    *pre = re;
6028
}
6029

    
6030
static void qemu_system_reset(void)
6031
{
6032
    QEMUResetEntry *re;
6033

    
6034
    /* reset all devices */
6035
    for(re = first_reset_entry; re != NULL; re = re->next) {
6036
        re->func(re->opaque);
6037
    }
6038
}
6039

    
6040
void qemu_system_reset_request(void)
6041
{
6042
    if (no_reboot) {
6043
        shutdown_requested = 1;
6044
    } else {
6045
        reset_requested = 1;
6046
    }
6047
    if (cpu_single_env)
6048
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6049
}
6050

    
6051
void qemu_system_shutdown_request(void)
6052
{
6053
    shutdown_requested = 1;
6054
    if (cpu_single_env)
6055
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6056
}
6057

    
6058
void qemu_system_powerdown_request(void)
6059
{
6060
    powerdown_requested = 1;
6061
    if (cpu_single_env)
6062
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6063
}
6064

    
6065
void main_loop_wait(int timeout)
6066
{
6067
    IOHandlerRecord *ioh, *ioh_next;
6068
    fd_set rfds, wfds, xfds;
6069
    int ret, nfds;
6070
    struct timeval tv;
6071
    PollingEntry *pe;
6072

    
6073

    
6074
    /* XXX: need to suppress polling by better using win32 events */
6075
    ret = 0;
6076
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6077
        ret |= pe->func(pe->opaque);
6078
    }
6079
#ifdef _WIN32
6080
    if (ret == 0 && timeout > 0) {
6081
        int err;
6082
        WaitObjects *w = &wait_objects;
6083
        
6084
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6085
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6086
            if (w->func[ret - WAIT_OBJECT_0])
6087
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6088
        } else if (ret == WAIT_TIMEOUT) {
6089
        } else {
6090
            err = GetLastError();
6091
            fprintf(stderr, "Wait error %d %d\n", ret, err);
6092
        }
6093
    }
6094
#endif
6095
    /* poll any events */
6096
    /* XXX: separate device handlers from system ones */
6097
    nfds = -1;
6098
    FD_ZERO(&rfds);
6099
    FD_ZERO(&wfds);
6100
    FD_ZERO(&xfds);
6101
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6102
        if (ioh->fd_read &&
6103
            (!ioh->fd_read_poll ||
6104
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6105
            FD_SET(ioh->fd, &rfds);
6106
            if (ioh->fd > nfds)
6107
                nfds = ioh->fd;
6108
        }
6109
        if (ioh->fd_write) {
6110
            FD_SET(ioh->fd, &wfds);
6111
            if (ioh->fd > nfds)
6112
                nfds = ioh->fd;
6113
        }
6114
    }
6115
    
6116
    tv.tv_sec = 0;
6117
#ifdef _WIN32
6118
    tv.tv_usec = 0;
6119
#else
6120
    tv.tv_usec = timeout * 1000;
6121
#endif
6122
#if defined(CONFIG_SLIRP)
6123
    if (slirp_inited) {
6124
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6125
    }
6126
#endif
6127
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6128
    if (ret > 0) {
6129
        /* XXX: better handling of removal */
6130
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
6131
            ioh_next = ioh->next;
6132
            if (FD_ISSET(ioh->fd, &rfds)) {
6133
                ioh->fd_read(ioh->opaque);
6134
            }
6135
            if (FD_ISSET(ioh->fd, &wfds)) {
6136
                ioh->fd_write(ioh->opaque);
6137
            }
6138
        }
6139
    }
6140
#if defined(CONFIG_SLIRP)
6141
    if (slirp_inited) {
6142
        if (ret < 0) {
6143
            FD_ZERO(&rfds);
6144
            FD_ZERO(&wfds);
6145
            FD_ZERO(&xfds);
6146
        }
6147
        slirp_select_poll(&rfds, &wfds, &xfds);
6148
    }
6149
#endif
6150
    qemu_aio_poll();
6151
    qemu_bh_poll();
6152

    
6153
    if (vm_running) {
6154
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
6155
                        qemu_get_clock(vm_clock));
6156
        /* run dma transfers, if any */
6157
        DMA_run();
6158
    }
6159
    
6160
    /* real time timers */
6161
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
6162
                    qemu_get_clock(rt_clock));
6163
}
6164

    
6165
static CPUState *cur_cpu;
6166

    
6167
int main_loop(void)
6168
{
6169
    int ret, timeout;
6170
#ifdef CONFIG_PROFILER
6171
    int64_t ti;
6172
#endif
6173
    CPUState *env;
6174

    
6175
    cur_cpu = first_cpu;
6176
    for(;;) {
6177
        if (vm_running) {
6178

    
6179
            env = cur_cpu;
6180
            for(;;) {
6181
                /* get next cpu */
6182
                env = env->next_cpu;
6183
                if (!env)
6184
                    env = first_cpu;
6185
#ifdef CONFIG_PROFILER
6186
                ti = profile_getclock();
6187
#endif
6188
                ret = cpu_exec(env);
6189
#ifdef CONFIG_PROFILER
6190
                qemu_time += profile_getclock() - ti;
6191
#endif
6192
                if (ret != EXCP_HALTED)
6193
                    break;
6194
                /* all CPUs are halted ? */
6195
                if (env == cur_cpu) {
6196
                    ret = EXCP_HLT;
6197
                    break;
6198
                }
6199
            }
6200
            cur_cpu = env;
6201

    
6202
            if (shutdown_requested) {
6203
                ret = EXCP_INTERRUPT;
6204
                break;
6205
            }
6206
            if (reset_requested) {
6207
                reset_requested = 0;
6208
                qemu_system_reset();
6209
                ret = EXCP_INTERRUPT;
6210
            }
6211
            if (powerdown_requested) {
6212
                powerdown_requested = 0;
6213
                qemu_system_powerdown();
6214
                ret = EXCP_INTERRUPT;
6215
            }
6216
            if (ret == EXCP_DEBUG) {
6217
                vm_stop(EXCP_DEBUG);
6218
            }
6219
            /* if hlt instruction, we wait until the next IRQ */
6220
            /* XXX: use timeout computed from timers */
6221
            if (ret == EXCP_HLT)
6222
                timeout = 10;
6223
            else
6224
                timeout = 0;
6225
        } else {
6226
            timeout = 10;
6227
        }
6228
#ifdef CONFIG_PROFILER
6229
        ti = profile_getclock();
6230
#endif
6231
        main_loop_wait(timeout);
6232
#ifdef CONFIG_PROFILER
6233
        dev_time += profile_getclock() - ti;
6234
#endif
6235
    }
6236
    cpu_disable_ticks();
6237
    return ret;
6238
}
6239

    
6240
void help(void)
6241
{
6242
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6243
           "usage: %s [options] [disk_image]\n"
6244
           "\n"
6245
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6246
           "\n"
6247
           "Standard options:\n"
6248
           "-M machine      select emulated machine (-M ? for list)\n"
6249
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6250
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6251
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6252
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6253
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6254
           "-snapshot       write to temporary files instead of disk image files\n"
6255
#ifdef CONFIG_SDL
6256
           "-no-quit        disable SDL window close capability\n"
6257
#endif
6258
#ifdef TARGET_I386
6259
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6260
#endif
6261
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6262
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
6263
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
6264
#ifndef _WIN32
6265
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
6266
#endif
6267
#ifdef HAS_AUDIO
6268
           "-audio-help     print list of audio drivers and their options\n"
6269
           "-soundhw c1,... enable audio support\n"
6270
           "                and only specified sound cards (comma separated list)\n"
6271
           "                use -soundhw ? to get the list of supported cards\n"
6272
           "                use -soundhw all to enable all of them\n"
6273
#endif
6274
           "-localtime      set the real time clock to local time [default=utc]\n"
6275
           "-full-screen    start in full screen\n"
6276
#ifdef TARGET_I386
6277
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6278
#endif
6279
           "-usb            enable the USB driver (will be the default soon)\n"
6280
           "-usbdevice name add the host or guest USB device 'name'\n"
6281
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6282
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6283
#endif
6284
           "\n"
6285
           "Network options:\n"
6286
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6287
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6288
#ifdef CONFIG_SLIRP
6289
           "-net user[,vlan=n][,hostname=host]\n"
6290
           "                connect the user mode network stack to VLAN 'n' and send\n"
6291
           "                hostname 'host' to DHCP clients\n"
6292
#endif
6293
#ifdef _WIN32
6294
           "-net tap[,vlan=n],ifname=name\n"
6295
           "                connect the host TAP network interface to VLAN 'n'\n"
6296
#else
6297
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6298
           "                connect the host TAP network interface to VLAN 'n' and use\n"
6299
           "                the network script 'file' (default=%s);\n"
6300
           "                use 'script=no' to disable script execution;\n"
6301
           "                use 'fd=h' to connect to an already opened TAP interface\n"
6302
#endif
6303
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6304
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
6305
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6306
           "                connect the vlan 'n' to multicast maddr and port\n"
6307
           "-net none       use it alone to have zero network devices; if no -net option\n"
6308
           "                is provided, the default is '-net nic -net user'\n"
6309
           "\n"
6310
#ifdef CONFIG_SLIRP
6311
           "-tftp prefix    allow tftp access to files starting with prefix [-net user]\n"
6312
#ifndef _WIN32
6313
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6314
#endif
6315
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6316
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
6317
#endif
6318
           "\n"
6319
           "Linux boot specific:\n"
6320
           "-kernel bzImage use 'bzImage' as kernel image\n"
6321
           "-append cmdline use 'cmdline' as kernel command line\n"
6322
           "-initrd file    use 'file' as initial ram disk\n"
6323
           "\n"
6324
           "Debug/Expert options:\n"
6325
           "-monitor dev    redirect the monitor to char device 'dev'\n"
6326
           "-serial dev     redirect the serial port to char device 'dev'\n"
6327
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
6328
           "-pidfile file   Write PID to 'file'\n"
6329
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
6330
           "-s              wait gdb connection to port %d\n"
6331
           "-p port         change gdb connection port\n"
6332
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6333
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6334
           "                translation (t=none or lba) (usually qemu can guess them)\n"
6335
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6336
#ifdef USE_KQEMU
6337
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6338
           "-no-kqemu       disable KQEMU kernel module usage\n"
6339
#endif
6340
#ifdef USE_CODE_COPY
6341
           "-no-code-copy   disable code copy acceleration\n"
6342
#endif
6343
#ifdef TARGET_I386
6344
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6345
           "                (default is CL-GD5446 PCI VGA)\n"
6346
           "-no-acpi        disable ACPI\n"
6347
#endif
6348
           "-no-reboot      exit instead of rebooting\n"
6349
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6350
           "-vnc display    start a VNC server on display\n"
6351
#ifndef _WIN32
6352
           "-daemonize      daemonize QEMU after initializing\n"
6353
#endif
6354
           "-option-rom rom load a file, rom, into the option ROM space\n"
6355
           "\n"
6356
           "During emulation, the following keys are useful:\n"
6357
           "ctrl-alt-f      toggle full screen\n"
6358
           "ctrl-alt-n      switch to virtual console 'n'\n"
6359
           "ctrl-alt        toggle mouse and keyboard grab\n"
6360
           "\n"
6361
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
6362
           ,
6363
           "qemu",
6364
           DEFAULT_RAM_SIZE,
6365
#ifndef _WIN32
6366
           DEFAULT_NETWORK_SCRIPT,
6367
#endif
6368
           DEFAULT_GDBSTUB_PORT,
6369
           "/tmp/qemu.log");
6370
    exit(1);
6371
}
6372

    
6373
#define HAS_ARG 0x0001
6374

    
6375
enum {
6376
    QEMU_OPTION_h,
6377

    
6378
    QEMU_OPTION_M,
6379
    QEMU_OPTION_fda,
6380
    QEMU_OPTION_fdb,
6381
    QEMU_OPTION_hda,
6382
    QEMU_OPTION_hdb,
6383
    QEMU_OPTION_hdc,
6384
    QEMU_OPTION_hdd,
6385
    QEMU_OPTION_cdrom,
6386
    QEMU_OPTION_boot,
6387
    QEMU_OPTION_snapshot,
6388
#ifdef TARGET_I386
6389
    QEMU_OPTION_no_fd_bootchk,
6390
#endif
6391
    QEMU_OPTION_m,
6392
    QEMU_OPTION_nographic,
6393
#ifdef HAS_AUDIO
6394
    QEMU_OPTION_audio_help,
6395
    QEMU_OPTION_soundhw,
6396
#endif
6397

    
6398
    QEMU_OPTION_net,
6399
    QEMU_OPTION_tftp,
6400
    QEMU_OPTION_smb,
6401
    QEMU_OPTION_redir,
6402

    
6403
    QEMU_OPTION_kernel,
6404
    QEMU_OPTION_append,
6405
    QEMU_OPTION_initrd,
6406

    
6407
    QEMU_OPTION_S,
6408
    QEMU_OPTION_s,
6409
    QEMU_OPTION_p,
6410
    QEMU_OPTION_d,
6411
    QEMU_OPTION_hdachs,
6412
    QEMU_OPTION_L,
6413
    QEMU_OPTION_no_code_copy,
6414
    QEMU_OPTION_k,
6415
    QEMU_OPTION_localtime,
6416
    QEMU_OPTION_cirrusvga,
6417
    QEMU_OPTION_g,
6418
    QEMU_OPTION_std_vga,
6419
    QEMU_OPTION_monitor,
6420
    QEMU_OPTION_serial,
6421
    QEMU_OPTION_parallel,
6422
    QEMU_OPTION_loadvm,
6423
    QEMU_OPTION_full_screen,
6424
    QEMU_OPTION_no_quit,
6425
    QEMU_OPTION_pidfile,
6426
    QEMU_OPTION_no_kqemu,
6427
    QEMU_OPTION_kernel_kqemu,
6428
    QEMU_OPTION_win2k_hack,
6429
    QEMU_OPTION_usb,
6430
    QEMU_OPTION_usbdevice,
6431
    QEMU_OPTION_smp,
6432
    QEMU_OPTION_vnc,
6433
    QEMU_OPTION_no_acpi,
6434
    QEMU_OPTION_no_reboot,
6435
    QEMU_OPTION_daemonize,
6436
    QEMU_OPTION_option_rom,
6437
    QEMU_OPTION_semihosting
6438
};
6439

    
6440
typedef struct QEMUOption {
6441
    const char *name;
6442
    int flags;
6443
    int index;
6444
} QEMUOption;
6445

    
6446
const QEMUOption qemu_options[] = {
6447
    { "h", 0, QEMU_OPTION_h },
6448
    { "help", 0, QEMU_OPTION_h },
6449

    
6450
    { "M", HAS_ARG, QEMU_OPTION_M },
6451
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6452
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6453
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6454
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6455
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6456
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6457
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6458
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6459
    { "snapshot", 0, QEMU_OPTION_snapshot },
6460
#ifdef TARGET_I386
6461
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6462
#endif
6463
    { "m", HAS_ARG, QEMU_OPTION_m },
6464
    { "nographic", 0, QEMU_OPTION_nographic },
6465
    { "k", HAS_ARG, QEMU_OPTION_k },
6466
#ifdef HAS_AUDIO
6467
    { "audio-help", 0, QEMU_OPTION_audio_help },
6468
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6469
#endif
6470

    
6471
    { "net", HAS_ARG, QEMU_OPTION_net},
6472
#ifdef CONFIG_SLIRP
6473
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6474
#ifndef _WIN32
6475
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6476
#endif
6477
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6478
#endif
6479

    
6480
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6481
    { "append", HAS_ARG, QEMU_OPTION_append },
6482
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6483

    
6484
    { "S", 0, QEMU_OPTION_S },
6485
    { "s", 0, QEMU_OPTION_s },
6486
    { "p", HAS_ARG, QEMU_OPTION_p },
6487
    { "d", HAS_ARG, QEMU_OPTION_d },
6488
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6489
    { "L", HAS_ARG, QEMU_OPTION_L },
6490
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6491
#ifdef USE_KQEMU
6492
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6493
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6494
#endif
6495
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6496
    { "g", 1, QEMU_OPTION_g },
6497
#endif
6498
    { "localtime", 0, QEMU_OPTION_localtime },
6499
    { "std-vga", 0, QEMU_OPTION_std_vga },
6500
    { "monitor", 1, QEMU_OPTION_monitor },
6501
    { "serial", 1, QEMU_OPTION_serial },
6502
    { "parallel", 1, QEMU_OPTION_parallel },
6503
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6504
    { "full-screen", 0, QEMU_OPTION_full_screen },
6505
#ifdef CONFIG_SDL
6506
    { "no-quit", 0, QEMU_OPTION_no_quit },
6507
#endif
6508
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6509
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6510
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6511
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6512
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6513

    
6514
    /* temporary options */
6515
    { "usb", 0, QEMU_OPTION_usb },
6516
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6517
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6518
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
6519
    { "daemonize", 0, QEMU_OPTION_daemonize },
6520
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6521
#if defined(TARGET_ARM)
6522
    { "semihosting", 0, QEMU_OPTION_semihosting },
6523
#endif
6524
    { NULL },
6525
};
6526

    
6527
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6528

    
6529
/* this stack is only used during signal handling */
6530
#define SIGNAL_STACK_SIZE 32768
6531

    
6532
static uint8_t *signal_stack;
6533

    
6534
#endif
6535

    
6536
/* password input */
6537

    
6538
static BlockDriverState *get_bdrv(int index)
6539
{
6540
    BlockDriverState *bs;
6541

    
6542
    if (index < 4) {
6543
        bs = bs_table[index];
6544
    } else if (index < 6) {
6545
        bs = fd_table[index - 4];
6546
    } else {
6547
        bs = NULL;
6548
    }
6549
    return bs;
6550
}
6551

    
6552
static void read_passwords(void)
6553
{
6554
    BlockDriverState *bs;
6555
    int i, j;
6556
    char password[256];
6557

    
6558
    for(i = 0; i < 6; i++) {
6559
        bs = get_bdrv(i);
6560
        if (bs && bdrv_is_encrypted(bs)) {
6561
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6562
            for(j = 0; j < 3; j++) {
6563
                monitor_readline("Password: ", 
6564
                                 1, password, sizeof(password));
6565
                if (bdrv_set_key(bs, password) == 0)
6566
                    break;
6567
                term_printf("invalid password\n");
6568
            }
6569
        }
6570
    }
6571
}
6572

    
6573
/* XXX: currently we cannot use simultaneously different CPUs */
6574
void register_machines(void)
6575
{
6576
#if defined(TARGET_I386)
6577
    qemu_register_machine(&pc_machine);
6578
    qemu_register_machine(&isapc_machine);
6579
#elif defined(TARGET_PPC)
6580
    qemu_register_machine(&heathrow_machine);
6581
    qemu_register_machine(&core99_machine);
6582
    qemu_register_machine(&prep_machine);
6583
#elif defined(TARGET_MIPS)
6584
    qemu_register_machine(&mips_machine);
6585
    qemu_register_machine(&mips_malta_machine);
6586
#elif defined(TARGET_SPARC)
6587
#ifdef TARGET_SPARC64
6588
    qemu_register_machine(&sun4u_machine);
6589
#else
6590
    qemu_register_machine(&sun4m_machine);
6591
#endif
6592
#elif defined(TARGET_ARM)
6593
    qemu_register_machine(&integratorcp926_machine);
6594
    qemu_register_machine(&integratorcp1026_machine);
6595
    qemu_register_machine(&versatilepb_machine);
6596
    qemu_register_machine(&versatileab_machine);
6597
    qemu_register_machine(&realview_machine);
6598
#elif defined(TARGET_SH4)
6599
    qemu_register_machine(&shix_machine);
6600
#else
6601
#error unsupported CPU
6602
#endif
6603
}
6604

    
6605
#ifdef HAS_AUDIO
6606
struct soundhw soundhw[] = {
6607
#ifdef TARGET_I386
6608
    {
6609
        "pcspk",
6610
        "PC speaker",
6611
        0,
6612
        1,
6613
        { .init_isa = pcspk_audio_init }
6614
    },
6615
#endif
6616
    {
6617
        "sb16",
6618
        "Creative Sound Blaster 16",
6619
        0,
6620
        1,
6621
        { .init_isa = SB16_init }
6622
    },
6623

    
6624
#ifdef CONFIG_ADLIB
6625
    {
6626
        "adlib",
6627
#ifdef HAS_YMF262
6628
        "Yamaha YMF262 (OPL3)",
6629
#else
6630
        "Yamaha YM3812 (OPL2)",
6631
#endif
6632
        0,
6633
        1,
6634
        { .init_isa = Adlib_init }
6635
    },
6636
#endif
6637

    
6638
#ifdef CONFIG_GUS
6639
    {
6640
        "gus",
6641
        "Gravis Ultrasound GF1",
6642
        0,
6643
        1,
6644
        { .init_isa = GUS_init }
6645
    },
6646
#endif
6647

    
6648
    {
6649
        "es1370",
6650
        "ENSONIQ AudioPCI ES1370",
6651
        0,
6652
        0,
6653
        { .init_pci = es1370_init }
6654
    },
6655

    
6656
    { NULL, NULL, 0, 0, { NULL } }
6657
};
6658

    
6659
static void select_soundhw (const char *optarg)
6660
{
6661
    struct soundhw *c;
6662

    
6663
    if (*optarg == '?') {
6664
    show_valid_cards:
6665

    
6666
        printf ("Valid sound card names (comma separated):\n");
6667
        for (c = soundhw; c->name; ++c) {
6668
            printf ("%-11s %s\n", c->name, c->descr);
6669
        }
6670
        printf ("\n-soundhw all will enable all of the above\n");
6671
        exit (*optarg != '?');
6672
    }
6673
    else {
6674
        size_t l;
6675
        const char *p;
6676
        char *e;
6677
        int bad_card = 0;
6678

    
6679
        if (!strcmp (optarg, "all")) {
6680
            for (c = soundhw; c->name; ++c) {
6681
                c->enabled = 1;
6682
            }
6683
            return;
6684
        }
6685

    
6686
        p = optarg;
6687
        while (*p) {
6688
            e = strchr (p, ',');
6689
            l = !e ? strlen (p) : (size_t) (e - p);
6690

    
6691
            for (c = soundhw; c->name; ++c) {
6692
                if (!strncmp (c->name, p, l)) {
6693
                    c->enabled = 1;
6694
                    break;
6695
                }
6696
            }
6697

    
6698
            if (!c->name) {
6699
                if (l > 80) {
6700
                    fprintf (stderr,
6701
                             "Unknown sound card name (too big to show)\n");
6702
                }
6703
                else {
6704
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
6705
                             (int) l, p);
6706
                }
6707
                bad_card = 1;
6708
            }
6709
            p += l + (e != NULL);
6710
        }
6711

    
6712
        if (bad_card)
6713
            goto show_valid_cards;
6714
    }
6715
}
6716
#endif
6717

    
6718
#ifdef _WIN32
6719
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6720
{
6721
    exit(STATUS_CONTROL_C_EXIT);
6722
    return TRUE;
6723
}
6724
#endif
6725

    
6726
#define MAX_NET_CLIENTS 32
6727

    
6728
int main(int argc, char **argv)
6729
{
6730
#ifdef CONFIG_GDBSTUB
6731
    int use_gdbstub, gdbstub_port;
6732
#endif
6733
    int i, cdrom_index;
6734
    int snapshot, linux_boot;
6735
    const char *initrd_filename;
6736
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6737
    const char *kernel_filename, *kernel_cmdline;
6738
    DisplayState *ds = &display_state;
6739
    int cyls, heads, secs, translation;
6740
    char net_clients[MAX_NET_CLIENTS][256];
6741
    int nb_net_clients;
6742
    int optind;
6743
    const char *r, *optarg;
6744
    CharDriverState *monitor_hd;
6745
    char monitor_device[128];
6746
    char serial_devices[MAX_SERIAL_PORTS][128];
6747
    int serial_device_index;
6748
    char parallel_devices[MAX_PARALLEL_PORTS][128];
6749
    int parallel_device_index;
6750
    const char *loadvm = NULL;
6751
    QEMUMachine *machine;
6752
    char usb_devices[MAX_USB_CMDLINE][128];
6753
    int usb_devices_index;
6754
    int fds[2];
6755

    
6756
    LIST_INIT (&vm_change_state_head);
6757
#ifndef _WIN32
6758
    {
6759
        struct sigaction act;
6760
        sigfillset(&act.sa_mask);
6761
        act.sa_flags = 0;
6762
        act.sa_handler = SIG_IGN;
6763
        sigaction(SIGPIPE, &act, NULL);
6764
    }
6765
#else
6766
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6767
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
6768
       QEMU to run on a single CPU */
6769
    {
6770
        HANDLE h;
6771
        DWORD mask, smask;
6772
        int i;
6773
        h = GetCurrentProcess();
6774
        if (GetProcessAffinityMask(h, &mask, &smask)) {
6775
            for(i = 0; i < 32; i++) {
6776
                if (mask & (1 << i))
6777
                    break;
6778
            }
6779
            if (i != 32) {
6780
                mask = 1 << i;
6781
                SetProcessAffinityMask(h, mask);
6782
            }
6783
        }
6784
    }
6785
#endif
6786

    
6787
    register_machines();
6788
    machine = first_machine;
6789
    initrd_filename = NULL;
6790
    for(i = 0; i < MAX_FD; i++)
6791
        fd_filename[i] = NULL;
6792
    for(i = 0; i < MAX_DISKS; i++)
6793
        hd_filename[i] = NULL;
6794
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6795
    vga_ram_size = VGA_RAM_SIZE;
6796
#ifdef CONFIG_GDBSTUB
6797
    use_gdbstub = 0;
6798
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
6799
#endif
6800
    snapshot = 0;
6801
    nographic = 0;
6802
    kernel_filename = NULL;
6803
    kernel_cmdline = "";
6804
#ifdef TARGET_PPC
6805
    cdrom_index = 1;
6806
#else
6807
    cdrom_index = 2;
6808
#endif
6809
    cyls = heads = secs = 0;
6810
    translation = BIOS_ATA_TRANSLATION_AUTO;
6811
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6812

    
6813
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6814
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
6815
        serial_devices[i][0] = '\0';
6816
    serial_device_index = 0;
6817
    
6818
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6819
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6820
        parallel_devices[i][0] = '\0';
6821
    parallel_device_index = 0;
6822
    
6823
    usb_devices_index = 0;
6824
    
6825
    nb_net_clients = 0;
6826

    
6827
    nb_nics = 0;
6828
    /* default mac address of the first network interface */
6829
    
6830
    optind = 1;
6831
    for(;;) {
6832
        if (optind >= argc)
6833
            break;
6834
        r = argv[optind];
6835
        if (r[0] != '-') {
6836
            hd_filename[0] = argv[optind++];
6837
        } else {
6838
            const QEMUOption *popt;
6839

    
6840
            optind++;
6841
            /* Treat --foo the same as -foo.  */
6842
            if (r[1] == '-')
6843
                r++;
6844
            popt = qemu_options;
6845
            for(;;) {
6846
                if (!popt->name) {
6847
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
6848
                            argv[0], r);
6849
                    exit(1);
6850
                }
6851
                if (!strcmp(popt->name, r + 1))
6852
                    break;
6853
                popt++;
6854
            }
6855
            if (popt->flags & HAS_ARG) {
6856
                if (optind >= argc) {
6857
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
6858
                            argv[0], r);
6859
                    exit(1);
6860
                }
6861
                optarg = argv[optind++];
6862
            } else {
6863
                optarg = NULL;
6864
            }
6865

    
6866
            switch(popt->index) {
6867
            case QEMU_OPTION_M:
6868
                machine = find_machine(optarg);
6869
                if (!machine) {
6870
                    QEMUMachine *m;
6871
                    printf("Supported machines are:\n");
6872
                    for(m = first_machine; m != NULL; m = m->next) {
6873
                        printf("%-10s %s%s\n",
6874
                               m->name, m->desc, 
6875
                               m == first_machine ? " (default)" : "");
6876
                    }
6877
                    exit(1);
6878
                }
6879
                break;
6880
            case QEMU_OPTION_initrd:
6881
                initrd_filename = optarg;
6882
                break;
6883
            case QEMU_OPTION_hda:
6884
            case QEMU_OPTION_hdb:
6885
            case QEMU_OPTION_hdc:
6886
            case QEMU_OPTION_hdd:
6887
                {
6888
                    int hd_index;
6889
                    hd_index = popt->index - QEMU_OPTION_hda;
6890
                    hd_filename[hd_index] = optarg;
6891
                    if (hd_index == cdrom_index)
6892
                        cdrom_index = -1;
6893
                }
6894
                break;
6895
            case QEMU_OPTION_snapshot:
6896
                snapshot = 1;
6897
                break;
6898
            case QEMU_OPTION_hdachs:
6899
                {
6900
                    const char *p;
6901
                    p = optarg;
6902
                    cyls = strtol(p, (char **)&p, 0);
6903
                    if (cyls < 1 || cyls > 16383)
6904
                        goto chs_fail;
6905
                    if (*p != ',')
6906
                        goto chs_fail;
6907
                    p++;
6908
                    heads = strtol(p, (char **)&p, 0);
6909
                    if (heads < 1 || heads > 16)
6910
                        goto chs_fail;
6911
                    if (*p != ',')
6912
                        goto chs_fail;
6913
                    p++;
6914
                    secs = strtol(p, (char **)&p, 0);
6915
                    if (secs < 1 || secs > 63)
6916
                        goto chs_fail;
6917
                    if (*p == ',') {
6918
                        p++;
6919
                        if (!strcmp(p, "none"))
6920
                            translation = BIOS_ATA_TRANSLATION_NONE;
6921
                        else if (!strcmp(p, "lba"))
6922
                            translation = BIOS_ATA_TRANSLATION_LBA;
6923
                        else if (!strcmp(p, "auto"))
6924
                            translation = BIOS_ATA_TRANSLATION_AUTO;
6925
                        else
6926
                            goto chs_fail;
6927
                    } else if (*p != '\0') {
6928
                    chs_fail:
6929
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
6930
                        exit(1);
6931
                    }
6932
                }
6933
                break;
6934
            case QEMU_OPTION_nographic:
6935
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6936
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6937
                nographic = 1;
6938
                break;
6939
            case QEMU_OPTION_kernel:
6940
                kernel_filename = optarg;
6941
                break;
6942
            case QEMU_OPTION_append:
6943
                kernel_cmdline = optarg;
6944
                break;
6945
            case QEMU_OPTION_cdrom:
6946
                if (cdrom_index >= 0) {
6947
                    hd_filename[cdrom_index] = optarg;
6948
                }
6949
                break;
6950
            case QEMU_OPTION_boot:
6951
                boot_device = optarg[0];
6952
                if (boot_device != 'a' && 
6953
#if defined(TARGET_SPARC) || defined(TARGET_I386)
6954
                    // Network boot
6955
                    boot_device != 'n' &&
6956
#endif
6957
                    boot_device != 'c' && boot_device != 'd') {
6958
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6959
                    exit(1);
6960
                }
6961
                break;
6962
            case QEMU_OPTION_fda:
6963
                fd_filename[0] = optarg;
6964
                break;
6965
            case QEMU_OPTION_fdb:
6966
                fd_filename[1] = optarg;
6967
                break;
6968
#ifdef TARGET_I386
6969
            case QEMU_OPTION_no_fd_bootchk:
6970
                fd_bootchk = 0;
6971
                break;
6972
#endif
6973
            case QEMU_OPTION_no_code_copy:
6974
                code_copy_enabled = 0;
6975
                break;
6976
            case QEMU_OPTION_net:
6977
                if (nb_net_clients >= MAX_NET_CLIENTS) {
6978
                    fprintf(stderr, "qemu: too many network clients\n");
6979
                    exit(1);
6980
                }
6981
                pstrcpy(net_clients[nb_net_clients],
6982
                        sizeof(net_clients[0]),
6983
                        optarg);
6984
                nb_net_clients++;
6985
                break;
6986
#ifdef CONFIG_SLIRP
6987
            case QEMU_OPTION_tftp:
6988
                tftp_prefix = optarg;
6989
                break;
6990
#ifndef _WIN32
6991
            case QEMU_OPTION_smb:
6992
                net_slirp_smb(optarg);
6993
                break;
6994
#endif
6995
            case QEMU_OPTION_redir:
6996
                net_slirp_redir(optarg);                
6997
                break;
6998
#endif
6999
#ifdef HAS_AUDIO
7000
            case QEMU_OPTION_audio_help:
7001
                AUD_help ();
7002
                exit (0);
7003
                break;
7004
            case QEMU_OPTION_soundhw:
7005
                select_soundhw (optarg);
7006
                break;
7007
#endif
7008
            case QEMU_OPTION_h:
7009
                help();
7010
                break;
7011
            case QEMU_OPTION_m:
7012
                ram_size = atoi(optarg) * 1024 * 1024;
7013
                if (ram_size <= 0)
7014
                    help();
7015
                if (ram_size > PHYS_RAM_MAX_SIZE) {
7016
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7017
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
7018
                    exit(1);
7019
                }
7020
                break;
7021
            case QEMU_OPTION_d:
7022
                {
7023
                    int mask;
7024
                    CPULogItem *item;
7025
                    
7026
                    mask = cpu_str_to_log_mask(optarg);
7027
                    if (!mask) {
7028
                        printf("Log items (comma separated):\n");
7029
                    for(item = cpu_log_items; item->mask != 0; item++) {
7030
                        printf("%-10s %s\n", item->name, item->help);
7031
                    }
7032
                    exit(1);
7033
                    }
7034
                    cpu_set_log(mask);
7035
                }
7036
                break;
7037
#ifdef CONFIG_GDBSTUB
7038
            case QEMU_OPTION_s:
7039
                use_gdbstub = 1;
7040
                break;
7041
            case QEMU_OPTION_p:
7042
                gdbstub_port = atoi(optarg);
7043
                break;
7044
#endif
7045
            case QEMU_OPTION_L:
7046
                bios_dir = optarg;
7047
                break;
7048
            case QEMU_OPTION_S:
7049
                autostart = 0;
7050
                break;
7051
            case QEMU_OPTION_k:
7052
                keyboard_layout = optarg;
7053
                break;
7054
            case QEMU_OPTION_localtime:
7055
                rtc_utc = 0;
7056
                break;
7057
            case QEMU_OPTION_cirrusvga:
7058
                cirrus_vga_enabled = 1;
7059
                break;
7060
            case QEMU_OPTION_std_vga:
7061
                cirrus_vga_enabled = 0;
7062
                break;
7063
            case QEMU_OPTION_g:
7064
                {
7065
                    const char *p;
7066
                    int w, h, depth;
7067
                    p = optarg;
7068
                    w = strtol(p, (char **)&p, 10);
7069
                    if (w <= 0) {
7070
                    graphic_error:
7071
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
7072
                        exit(1);
7073
                    }
7074
                    if (*p != 'x')
7075
                        goto graphic_error;
7076
                    p++;
7077
                    h = strtol(p, (char **)&p, 10);
7078
                    if (h <= 0)
7079
                        goto graphic_error;
7080
                    if (*p == 'x') {
7081
                        p++;
7082
                        depth = strtol(p, (char **)&p, 10);
7083
                        if (depth != 8 && depth != 15 && depth != 16 && 
7084
                            depth != 24 && depth != 32)
7085
                            goto graphic_error;
7086
                    } else if (*p == '\0') {
7087
                        depth = graphic_depth;
7088
                    } else {
7089
                        goto graphic_error;
7090
                    }
7091
                    
7092
                    graphic_width = w;
7093
                    graphic_height = h;
7094
                    graphic_depth = depth;
7095
                }
7096
                break;
7097
            case QEMU_OPTION_monitor:
7098
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7099
                break;
7100
            case QEMU_OPTION_serial:
7101
                if (serial_device_index >= MAX_SERIAL_PORTS) {
7102
                    fprintf(stderr, "qemu: too many serial ports\n");
7103
                    exit(1);
7104
                }
7105
                pstrcpy(serial_devices[serial_device_index], 
7106
                        sizeof(serial_devices[0]), optarg);
7107
                serial_device_index++;
7108
                break;
7109
            case QEMU_OPTION_parallel:
7110
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7111
                    fprintf(stderr, "qemu: too many parallel ports\n");
7112
                    exit(1);
7113
                }
7114
                pstrcpy(parallel_devices[parallel_device_index], 
7115
                        sizeof(parallel_devices[0]), optarg);
7116
                parallel_device_index++;
7117
                break;
7118
            case QEMU_OPTION_loadvm:
7119
                loadvm = optarg;
7120
                break;
7121
            case QEMU_OPTION_full_screen:
7122
                full_screen = 1;
7123
                break;
7124
#ifdef CONFIG_SDL
7125
            case QEMU_OPTION_no_quit:
7126
                no_quit = 1;
7127
                break;
7128
#endif
7129
            case QEMU_OPTION_pidfile:
7130
                create_pidfile(optarg);
7131
                break;
7132
#ifdef TARGET_I386
7133
            case QEMU_OPTION_win2k_hack:
7134
                win2k_install_hack = 1;
7135
                break;
7136
#endif
7137
#ifdef USE_KQEMU
7138
            case QEMU_OPTION_no_kqemu:
7139
                kqemu_allowed = 0;
7140
                break;
7141
            case QEMU_OPTION_kernel_kqemu:
7142
                kqemu_allowed = 2;
7143
                break;
7144
#endif
7145
            case QEMU_OPTION_usb:
7146
                usb_enabled = 1;
7147
                break;
7148
            case QEMU_OPTION_usbdevice:
7149
                usb_enabled = 1;
7150
                if (usb_devices_index >= MAX_USB_CMDLINE) {
7151
                    fprintf(stderr, "Too many USB devices\n");
7152
                    exit(1);
7153
                }
7154
                pstrcpy(usb_devices[usb_devices_index],
7155
                        sizeof(usb_devices[usb_devices_index]),
7156
                        optarg);
7157
                usb_devices_index++;
7158
                break;
7159
            case QEMU_OPTION_smp:
7160
                smp_cpus = atoi(optarg);
7161
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7162
                    fprintf(stderr, "Invalid number of CPUs\n");
7163
                    exit(1);
7164
                }
7165
                break;
7166
            case QEMU_OPTION_vnc:
7167
                vnc_display = optarg;
7168
                break;
7169
            case QEMU_OPTION_no_acpi:
7170
                acpi_enabled = 0;
7171
                break;
7172
            case QEMU_OPTION_no_reboot:
7173
                no_reboot = 1;
7174
                break;
7175
            case QEMU_OPTION_daemonize:
7176
                daemonize = 1;
7177
                break;
7178
            case QEMU_OPTION_option_rom:
7179
                if (nb_option_roms >= MAX_OPTION_ROMS) {
7180
                    fprintf(stderr, "Too many option ROMs\n");
7181
                    exit(1);
7182
                }
7183
                option_rom[nb_option_roms] = optarg;
7184
                nb_option_roms++;
7185
                break;
7186
            case QEMU_OPTION_semihosting:
7187
                semihosting_enabled = 1;
7188
                break;
7189
            }
7190
        }
7191
    }
7192

    
7193
#ifndef _WIN32
7194
    if (daemonize && !nographic && vnc_display == NULL) {
7195
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7196
        daemonize = 0;
7197
    }
7198

    
7199
    if (daemonize) {
7200
        pid_t pid;
7201

    
7202
        if (pipe(fds) == -1)
7203
            exit(1);
7204

    
7205
        pid = fork();
7206
        if (pid > 0) {
7207
            uint8_t status;
7208
            ssize_t len;
7209

    
7210
            close(fds[1]);
7211

    
7212
        again:
7213
            len = read(fds[0], &status, 1);
7214
            if (len == -1 && (errno == EINTR))
7215
                goto again;
7216
            
7217
            if (len != 1 || status != 0)
7218
                exit(1);
7219
            else
7220
                exit(0);
7221
        } else if (pid < 0)
7222
            exit(1);
7223

    
7224
        setsid();
7225

    
7226
        pid = fork();
7227
        if (pid > 0)
7228
            exit(0);
7229
        else if (pid < 0)
7230
            exit(1);
7231

    
7232
        umask(027);
7233
        chdir("/");
7234

    
7235
        signal(SIGTSTP, SIG_IGN);
7236
        signal(SIGTTOU, SIG_IGN);
7237
        signal(SIGTTIN, SIG_IGN);
7238
    }
7239
#endif
7240

    
7241
#ifdef USE_KQEMU
7242
    if (smp_cpus > 1)
7243
        kqemu_allowed = 0;
7244
#endif
7245
    linux_boot = (kernel_filename != NULL);
7246

    
7247
    if (!linux_boot &&
7248
        hd_filename[0] == '\0' && 
7249
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7250
        fd_filename[0] == '\0')
7251
        help();
7252

    
7253
    /* boot to floppy or the default cd if no hard disk defined yet */
7254
    if (hd_filename[0] == '\0' && boot_device == 'c') {
7255
        if (fd_filename[0] != '\0')
7256
            boot_device = 'a';
7257
        else
7258
            boot_device = 'd';
7259
    }
7260

    
7261
    setvbuf(stdout, NULL, _IOLBF, 0);
7262
    
7263
    init_timers();
7264
    init_timer_alarm();
7265
    qemu_aio_init();
7266

    
7267
#ifdef _WIN32
7268
    socket_init();
7269
#endif
7270

    
7271
    /* init network clients */
7272
    if (nb_net_clients == 0) {
7273
        /* if no clients, we use a default config */
7274
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
7275
                "nic");
7276
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
7277
                "user");
7278
        nb_net_clients = 2;
7279
    }
7280

    
7281
    for(i = 0;i < nb_net_clients; i++) {
7282
        if (net_client_init(net_clients[i]) < 0)
7283
            exit(1);
7284
    }
7285

    
7286
#ifdef TARGET_I386
7287
    if (boot_device == 'n') {
7288
        for (i = 0; i < nb_nics; i++) {
7289
            const char *model = nd_table[i].model;
7290
            char buf[1024];
7291
            if (model == NULL)
7292
                model = "ne2k_pci";
7293
            snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7294
            if (get_image_size(buf) > 0) {
7295
                option_rom[nb_option_roms] = strdup(buf);
7296
                nb_option_roms++;
7297
                break;
7298
            }
7299
        }
7300
        if (i == nb_nics) {
7301
            fprintf(stderr, "No valid PXE rom found for network device\n");
7302
            exit(1);
7303
        }
7304
        boot_device = 'c'; /* to prevent confusion by the BIOS */
7305
    }
7306
#endif
7307

    
7308
    /* init the memory */
7309
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7310

    
7311
    phys_ram_base = qemu_vmalloc(phys_ram_size);
7312
    if (!phys_ram_base) {
7313
        fprintf(stderr, "Could not allocate physical memory\n");
7314
        exit(1);
7315
    }
7316

    
7317
    /* we always create the cdrom drive, even if no disk is there */
7318
    bdrv_init();
7319
    if (cdrom_index >= 0) {
7320
        bs_table[cdrom_index] = bdrv_new("cdrom");
7321
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7322
    }
7323

    
7324
    /* open the virtual block devices */
7325
    for(i = 0; i < MAX_DISKS; i++) {
7326
        if (hd_filename[i]) {
7327
            if (!bs_table[i]) {
7328
                char buf[64];
7329
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7330
                bs_table[i] = bdrv_new(buf);
7331
            }
7332
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7333
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7334
                        hd_filename[i]);
7335
                exit(1);
7336
            }
7337
            if (i == 0 && cyls != 0) {
7338
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7339
                bdrv_set_translation_hint(bs_table[i], translation);
7340
            }
7341
        }
7342
    }
7343

    
7344
    /* we always create at least one floppy disk */
7345
    fd_table[0] = bdrv_new("fda");
7346
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7347

    
7348
    for(i = 0; i < MAX_FD; i++) {
7349
        if (fd_filename[i]) {
7350
            if (!fd_table[i]) {
7351
                char buf[64];
7352
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7353
                fd_table[i] = bdrv_new(buf);
7354
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7355
            }
7356
            if (fd_filename[i] != '\0') {
7357
                if (bdrv_open(fd_table[i], fd_filename[i],
7358
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7359
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7360
                            fd_filename[i]);
7361
                    exit(1);
7362
                }
7363
            }
7364
        }
7365
    }
7366

    
7367
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7368
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7369

    
7370
    init_ioports();
7371

    
7372
    /* terminal init */
7373
    if (nographic) {
7374
        dumb_display_init(ds);
7375
    } else if (vnc_display != NULL) {
7376
        vnc_display_init(ds, vnc_display);
7377
    } else {
7378
#if defined(CONFIG_SDL)
7379
        sdl_display_init(ds, full_screen);
7380
#elif defined(CONFIG_COCOA)
7381
        cocoa_display_init(ds, full_screen);
7382
#else
7383
        dumb_display_init(ds);
7384
#endif
7385
    }
7386

    
7387
    monitor_hd = qemu_chr_open(monitor_device);
7388
    if (!monitor_hd) {
7389
        fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7390
        exit(1);
7391
    }
7392
    monitor_init(monitor_hd, !nographic);
7393

    
7394
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7395
        const char *devname = serial_devices[i];
7396
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7397
            serial_hds[i] = qemu_chr_open(devname);
7398
            if (!serial_hds[i]) {
7399
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7400
                        devname);
7401
                exit(1);
7402
            }
7403
            if (!strcmp(devname, "vc"))
7404
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7405
        }
7406
    }
7407

    
7408
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7409
        const char *devname = parallel_devices[i];
7410
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7411
            parallel_hds[i] = qemu_chr_open(devname);
7412
            if (!parallel_hds[i]) {
7413
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7414
                        devname);
7415
                exit(1);
7416
            }
7417
            if (!strcmp(devname, "vc"))
7418
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7419
        }
7420
    }
7421

    
7422
    machine->init(ram_size, vga_ram_size, boot_device,
7423
                  ds, fd_filename, snapshot,
7424
                  kernel_filename, kernel_cmdline, initrd_filename);
7425

    
7426
    /* init USB devices */
7427
    if (usb_enabled) {
7428
        for(i = 0; i < usb_devices_index; i++) {
7429
            if (usb_device_add(usb_devices[i]) < 0) {
7430
                fprintf(stderr, "Warning: could not add USB device %s\n",
7431
                        usb_devices[i]);
7432
            }
7433
        }
7434
    }
7435

    
7436
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7437
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7438

    
7439
#ifdef CONFIG_GDBSTUB
7440
    if (use_gdbstub) {
7441
        /* XXX: use standard host:port notation and modify options
7442
           accordingly. */
7443
        if (gdbserver_start_port(gdbstub_port) < 0) {
7444
            fprintf(stderr, "qemu: could not open gdbstub device on port '%d'\n",
7445
                    gdbstub_port);
7446
            exit(1);
7447
        }
7448
    } else 
7449
#endif
7450
    if (loadvm)
7451
        do_loadvm(loadvm);
7452

    
7453
    {
7454
        /* XXX: simplify init */
7455
        read_passwords();
7456
        if (autostart) {
7457
            vm_start();
7458
        }
7459
    }
7460

    
7461
    if (daemonize) {
7462
        uint8_t status = 0;
7463
        ssize_t len;
7464
        int fd;
7465

    
7466
    again1:
7467
        len = write(fds[1], &status, 1);
7468
        if (len == -1 && (errno == EINTR))
7469
            goto again1;
7470

    
7471
        if (len != 1)
7472
            exit(1);
7473

    
7474
        fd = open("/dev/null", O_RDWR);
7475
        if (fd == -1)
7476
            exit(1);
7477

    
7478
        dup2(fd, 0);
7479
        dup2(fd, 1);
7480
        dup2(fd, 2);
7481

    
7482
        close(fd);
7483
    }
7484

    
7485
    main_loop();
7486
    quit_timers();
7487
    return 0;
7488
}