Statistics
| Branch: | Revision:

root / vl.c @ 98b50080

History | View | Annotate | Download (153.9 kB)

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

    
32
/* Needed early for CONFIG_BSD etc. */
33
#include "config-host.h"
34

    
35
#ifndef _WIN32
36
#include <libgen.h>
37
#include <pwd.h>
38
#include <sys/times.h>
39
#include <sys/wait.h>
40
#include <termios.h>
41
#include <sys/mman.h>
42
#include <sys/ioctl.h>
43
#include <sys/resource.h>
44
#include <sys/socket.h>
45
#include <netinet/in.h>
46
#include <net/if.h>
47
#include <arpa/inet.h>
48
#include <dirent.h>
49
#include <netdb.h>
50
#include <sys/select.h>
51
#ifdef CONFIG_BSD
52
#include <sys/stat.h>
53
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54
#include <libutil.h>
55
#else
56
#include <util.h>
57
#endif
58
#else
59
#ifdef __linux__
60
#include <pty.h>
61
#include <malloc.h>
62
#include <linux/rtc.h>
63
#include <sys/prctl.h>
64

    
65
/* For the benefit of older linux systems which don't supply it,
66
   we use a local copy of hpet.h. */
67
/* #include <linux/hpet.h> */
68
#include "hpet.h"
69

    
70
#include <linux/ppdev.h>
71
#include <linux/parport.h>
72
#endif
73
#ifdef __sun__
74
#include <sys/stat.h>
75
#include <sys/ethernet.h>
76
#include <sys/sockio.h>
77
#include <netinet/arp.h>
78
#include <netinet/in.h>
79
#include <netinet/in_systm.h>
80
#include <netinet/ip.h>
81
#include <netinet/ip_icmp.h> // must come after ip.h
82
#include <netinet/udp.h>
83
#include <netinet/tcp.h>
84
#include <net/if.h>
85
#include <syslog.h>
86
#include <stropts.h>
87
/* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88
   discussion about Solaris header problems */
89
extern int madvise(caddr_t, size_t, int);
90
#endif
91
#endif
92
#endif
93

    
94
#if defined(__OpenBSD__)
95
#include <util.h>
96
#endif
97

    
98
#if defined(CONFIG_VDE)
99
#include <libvdeplug.h>
100
#endif
101

    
102
#ifdef _WIN32
103
#include <windows.h>
104
#include <mmsystem.h>
105
#endif
106

    
107
#ifdef CONFIG_SDL
108
#if defined(__APPLE__) || defined(main)
109
#include <SDL.h>
110
int qemu_main(int argc, char **argv, char **envp);
111
int main(int argc, char **argv)
112
{
113
    return qemu_main(argc, argv, NULL);
114
}
115
#undef main
116
#define main qemu_main
117
#endif
118
#endif /* CONFIG_SDL */
119

    
120
#ifdef CONFIG_COCOA
121
#undef main
122
#define main qemu_main
123
#endif /* CONFIG_COCOA */
124

    
125
#include "hw/hw.h"
126
#include "hw/boards.h"
127
#include "hw/usb.h"
128
#include "hw/pcmcia.h"
129
#include "hw/pc.h"
130
#include "hw/audiodev.h"
131
#include "hw/isa.h"
132
#include "hw/baum.h"
133
#include "hw/bt.h"
134
#include "hw/watchdog.h"
135
#include "hw/smbios.h"
136
#include "hw/xen.h"
137
#include "hw/qdev.h"
138
#include "hw/loader.h"
139
#include "bt-host.h"
140
#include "net.h"
141
#include "net/slirp.h"
142
#include "monitor.h"
143
#include "console.h"
144
#include "sysemu.h"
145
#include "gdbstub.h"
146
#include "qemu-timer.h"
147
#include "qemu-char.h"
148
#include "cache-utils.h"
149
#include "block.h"
150
#include "block_int.h"
151
#include "block-migration.h"
152
#include "dma.h"
153
#include "audio/audio.h"
154
#include "migration.h"
155
#include "kvm.h"
156
#include "balloon.h"
157
#include "qemu-option.h"
158
#include "qemu-config.h"
159
#include "qemu-objects.h"
160

    
161
#include "disas.h"
162

    
163
#include "exec-all.h"
164

    
165
#include "qemu_socket.h"
166

    
167
#include "slirp/libslirp.h"
168

    
169
#include "qemu-queue.h"
170

    
171
//#define DEBUG_NET
172
//#define DEBUG_SLIRP
173

    
174
#define DEFAULT_RAM_SIZE 128
175

    
176
#define MAX_VIRTIO_CONSOLES 1
177

    
178
static const char *data_dir;
179
const char *bios_name = NULL;
180
/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181
   to store the VM snapshots */
182
struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
183
struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
184
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
185
DisplayType display_type = DT_DEFAULT;
186
const char* keyboard_layout = NULL;
187
ram_addr_t ram_size;
188
int nb_nics;
189
NICInfo nd_table[MAX_NICS];
190
int vm_running;
191
int autostart;
192
static int rtc_utc = 1;
193
static int rtc_date_offset = -1; /* -1 means no change */
194
QEMUClock *rtc_clock;
195
int vga_interface_type = VGA_NONE;
196
#ifdef TARGET_SPARC
197
int graphic_width = 1024;
198
int graphic_height = 768;
199
int graphic_depth = 8;
200
#else
201
int graphic_width = 800;
202
int graphic_height = 600;
203
int graphic_depth = 15;
204
#endif
205
static int full_screen = 0;
206
#ifdef CONFIG_SDL
207
static int no_frame = 0;
208
#endif
209
int no_quit = 0;
210
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
211
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
212
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
213
#ifdef TARGET_I386
214
int win2k_install_hack = 0;
215
int rtc_td_hack = 0;
216
#endif
217
int usb_enabled = 0;
218
int singlestep = 0;
219
int smp_cpus = 1;
220
int max_cpus = 0;
221
int smp_cores = 1;
222
int smp_threads = 1;
223
const char *vnc_display;
224
int acpi_enabled = 1;
225
int no_hpet = 0;
226
int fd_bootchk = 1;
227
int no_reboot = 0;
228
int no_shutdown = 0;
229
int cursor_hide = 1;
230
int graphic_rotate = 0;
231
uint8_t irq0override = 1;
232
#ifndef _WIN32
233
int daemonize = 0;
234
#endif
235
const char *watchdog;
236
const char *option_rom[MAX_OPTION_ROMS];
237
int nb_option_roms;
238
int semihosting_enabled = 0;
239
#ifdef TARGET_ARM
240
int old_param = 0;
241
#endif
242
const char *qemu_name;
243
int alt_grab = 0;
244
int ctrl_grab = 0;
245
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
246
unsigned int nb_prom_envs = 0;
247
const char *prom_envs[MAX_PROM_ENVS];
248
#endif
249
int boot_menu;
250

    
251
int nb_numa_nodes;
252
uint64_t node_mem[MAX_NODES];
253
uint64_t node_cpumask[MAX_NODES];
254

    
255
static CPUState *cur_cpu;
256
static CPUState *next_cpu;
257
static int timer_alarm_pending = 1;
258
/* Conversion factor from emulated instructions to virtual clock ticks.  */
259
static int icount_time_shift;
260
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
261
#define MAX_ICOUNT_SHIFT 10
262
/* Compensate for varying guest execution speed.  */
263
static int64_t qemu_icount_bias;
264
static QEMUTimer *icount_rt_timer;
265
static QEMUTimer *icount_vm_timer;
266
static QEMUTimer *nographic_timer;
267

    
268
uint8_t qemu_uuid[16];
269

    
270
static QEMUBootSetHandler *boot_set_handler;
271
static void *boot_set_opaque;
272

    
273
static int default_serial = 1;
274
static int default_parallel = 1;
275
static int default_virtcon = 1;
276
static int default_monitor = 1;
277
static int default_vga = 1;
278
static int default_floppy = 1;
279
static int default_cdrom = 1;
280
static int default_sdcard = 1;
281

    
282
static struct {
283
    const char *driver;
284
    int *flag;
285
} default_list[] = {
286
    { .driver = "isa-serial",           .flag = &default_serial    },
287
    { .driver = "isa-parallel",         .flag = &default_parallel  },
288
    { .driver = "isa-fdc",              .flag = &default_floppy    },
289
    { .driver = "ide-drive",            .flag = &default_cdrom     },
290
    { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
291
    { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
292
    { .driver = "virtio-serial",        .flag = &default_virtcon   },
293
    { .driver = "VGA",                  .flag = &default_vga       },
294
    { .driver = "cirrus-vga",           .flag = &default_vga       },
295
    { .driver = "vmware-svga",          .flag = &default_vga       },
296
};
297

    
298
static int default_driver_check(QemuOpts *opts, void *opaque)
299
{
300
    const char *driver = qemu_opt_get(opts, "driver");
301
    int i;
302

    
303
    if (!driver)
304
        return 0;
305
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
306
        if (strcmp(default_list[i].driver, driver) != 0)
307
            continue;
308
        *(default_list[i].flag) = 0;
309
    }
310
    return 0;
311
}
312

    
313
/***********************************************************/
314
/* x86 ISA bus support */
315

    
316
target_phys_addr_t isa_mem_base = 0;
317
PicState2 *isa_pic;
318

    
319
/***********************************************************/
320
void hw_error(const char *fmt, ...)
321
{
322
    va_list ap;
323
    CPUState *env;
324

    
325
    va_start(ap, fmt);
326
    fprintf(stderr, "qemu: hardware error: ");
327
    vfprintf(stderr, fmt, ap);
328
    fprintf(stderr, "\n");
329
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
330
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
331
#ifdef TARGET_I386
332
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
333
#else
334
        cpu_dump_state(env, stderr, fprintf, 0);
335
#endif
336
    }
337
    va_end(ap);
338
    abort();
339
}
340

    
341
static void set_proc_name(const char *s)
342
{
343
#if defined(__linux__) && defined(PR_SET_NAME)
344
    char name[16];
345
    if (!s)
346
        return;
347
    name[sizeof(name) - 1] = 0;
348
    strncpy(name, s, sizeof(name));
349
    /* Could rewrite argv[0] too, but that's a bit more complicated.
350
       This simple way is enough for `top'. */
351
    prctl(PR_SET_NAME, name);
352
#endif            
353
}
354
 
355
/***************/
356
/* ballooning */
357

    
358
static QEMUBalloonEvent *qemu_balloon_event;
359
void *qemu_balloon_event_opaque;
360

    
361
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
362
{
363
    qemu_balloon_event = func;
364
    qemu_balloon_event_opaque = opaque;
365
}
366

    
367
int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
368
{
369
    if (qemu_balloon_event) {
370
        qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
371
        return 1;
372
    } else {
373
        return 0;
374
    }
375
}
376

    
377
int qemu_balloon_status(MonitorCompletion cb, void *opaque)
378
{
379
    if (qemu_balloon_event) {
380
        qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
381
        return 1;
382
    } else {
383
        return 0;
384
    }
385
}
386

    
387

    
388
/***********************************************************/
389
/* real time host monotonic timer */
390

    
391
/* compute with 96 bit intermediate result: (a*b)/c */
392
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
393
{
394
    union {
395
        uint64_t ll;
396
        struct {
397
#ifdef HOST_WORDS_BIGENDIAN
398
            uint32_t high, low;
399
#else
400
            uint32_t low, high;
401
#endif
402
        } l;
403
    } u, res;
404
    uint64_t rl, rh;
405

    
406
    u.ll = a;
407
    rl = (uint64_t)u.l.low * (uint64_t)b;
408
    rh = (uint64_t)u.l.high * (uint64_t)b;
409
    rh += (rl >> 32);
410
    res.l.high = rh / c;
411
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
412
    return res.ll;
413
}
414

    
415
static int64_t get_clock_realtime(void)
416
{
417
    struct timeval tv;
418

    
419
    gettimeofday(&tv, NULL);
420
    return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
421
}
422

    
423
#ifdef WIN32
424

    
425
static int64_t clock_freq;
426

    
427
static void init_get_clock(void)
428
{
429
    LARGE_INTEGER freq;
430
    int ret;
431
    ret = QueryPerformanceFrequency(&freq);
432
    if (ret == 0) {
433
        fprintf(stderr, "Could not calibrate ticks\n");
434
        exit(1);
435
    }
436
    clock_freq = freq.QuadPart;
437
}
438

    
439
static int64_t get_clock(void)
440
{
441
    LARGE_INTEGER ti;
442
    QueryPerformanceCounter(&ti);
443
    return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
444
}
445

    
446
#else
447

    
448
static int use_rt_clock;
449

    
450
static void init_get_clock(void)
451
{
452
    use_rt_clock = 0;
453
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
454
    || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
455
    {
456
        struct timespec ts;
457
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
458
            use_rt_clock = 1;
459
        }
460
    }
461
#endif
462
}
463

    
464
static int64_t get_clock(void)
465
{
466
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
467
        || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
468
    if (use_rt_clock) {
469
        struct timespec ts;
470
        clock_gettime(CLOCK_MONOTONIC, &ts);
471
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
472
    } else
473
#endif
474
    {
475
        /* XXX: using gettimeofday leads to problems if the date
476
           changes, so it should be avoided. */
477
        return get_clock_realtime();
478
    }
479
}
480
#endif
481

    
482
/* Return the virtual CPU time, based on the instruction counter.  */
483
static int64_t cpu_get_icount(void)
484
{
485
    int64_t icount;
486
    CPUState *env = cpu_single_env;;
487
    icount = qemu_icount;
488
    if (env) {
489
        if (!can_do_io(env))
490
            fprintf(stderr, "Bad clock read\n");
491
        icount -= (env->icount_decr.u16.low + env->icount_extra);
492
    }
493
    return qemu_icount_bias + (icount << icount_time_shift);
494
}
495

    
496
/***********************************************************/
497
/* guest cycle counter */
498

    
499
typedef struct TimersState {
500
    int64_t cpu_ticks_prev;
501
    int64_t cpu_ticks_offset;
502
    int64_t cpu_clock_offset;
503
    int32_t cpu_ticks_enabled;
504
    int64_t dummy;
505
} TimersState;
506

    
507
TimersState timers_state;
508

    
509
/* return the host CPU cycle counter and handle stop/restart */
510
int64_t cpu_get_ticks(void)
511
{
512
    if (use_icount) {
513
        return cpu_get_icount();
514
    }
515
    if (!timers_state.cpu_ticks_enabled) {
516
        return timers_state.cpu_ticks_offset;
517
    } else {
518
        int64_t ticks;
519
        ticks = cpu_get_real_ticks();
520
        if (timers_state.cpu_ticks_prev > ticks) {
521
            /* Note: non increasing ticks may happen if the host uses
522
               software suspend */
523
            timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
524
        }
525
        timers_state.cpu_ticks_prev = ticks;
526
        return ticks + timers_state.cpu_ticks_offset;
527
    }
528
}
529

    
530
/* return the host CPU monotonic timer and handle stop/restart */
531
static int64_t cpu_get_clock(void)
532
{
533
    int64_t ti;
534
    if (!timers_state.cpu_ticks_enabled) {
535
        return timers_state.cpu_clock_offset;
536
    } else {
537
        ti = get_clock();
538
        return ti + timers_state.cpu_clock_offset;
539
    }
540
}
541

    
542
/* enable cpu_get_ticks() */
543
void cpu_enable_ticks(void)
544
{
545
    if (!timers_state.cpu_ticks_enabled) {
546
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
547
        timers_state.cpu_clock_offset -= get_clock();
548
        timers_state.cpu_ticks_enabled = 1;
549
    }
550
}
551

    
552
/* disable cpu_get_ticks() : the clock is stopped. You must not call
553
   cpu_get_ticks() after that.  */
554
void cpu_disable_ticks(void)
555
{
556
    if (timers_state.cpu_ticks_enabled) {
557
        timers_state.cpu_ticks_offset = cpu_get_ticks();
558
        timers_state.cpu_clock_offset = cpu_get_clock();
559
        timers_state.cpu_ticks_enabled = 0;
560
    }
561
}
562

    
563
/***********************************************************/
564
/* timers */
565

    
566
#define QEMU_CLOCK_REALTIME 0
567
#define QEMU_CLOCK_VIRTUAL  1
568
#define QEMU_CLOCK_HOST     2
569

    
570
struct QEMUClock {
571
    int type;
572
    /* XXX: add frequency */
573
};
574

    
575
struct QEMUTimer {
576
    QEMUClock *clock;
577
    int64_t expire_time;
578
    QEMUTimerCB *cb;
579
    void *opaque;
580
    struct QEMUTimer *next;
581
};
582

    
583
struct qemu_alarm_timer {
584
    char const *name;
585
    unsigned int flags;
586

    
587
    int (*start)(struct qemu_alarm_timer *t);
588
    void (*stop)(struct qemu_alarm_timer *t);
589
    void (*rearm)(struct qemu_alarm_timer *t);
590
    void *priv;
591
};
592

    
593
#define ALARM_FLAG_DYNTICKS  0x1
594
#define ALARM_FLAG_EXPIRED   0x2
595

    
596
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
597
{
598
    return t && (t->flags & ALARM_FLAG_DYNTICKS);
599
}
600

    
601
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
602
{
603
    if (!alarm_has_dynticks(t))
604
        return;
605

    
606
    t->rearm(t);
607
}
608

    
609
/* TODO: MIN_TIMER_REARM_US should be optimized */
610
#define MIN_TIMER_REARM_US 250
611

    
612
static struct qemu_alarm_timer *alarm_timer;
613

    
614
#ifdef _WIN32
615

    
616
struct qemu_alarm_win32 {
617
    MMRESULT timerId;
618
    unsigned int period;
619
} alarm_win32_data = {0, -1};
620

    
621
static int win32_start_timer(struct qemu_alarm_timer *t);
622
static void win32_stop_timer(struct qemu_alarm_timer *t);
623
static void win32_rearm_timer(struct qemu_alarm_timer *t);
624

    
625
#else
626

    
627
static int unix_start_timer(struct qemu_alarm_timer *t);
628
static void unix_stop_timer(struct qemu_alarm_timer *t);
629

    
630
#ifdef __linux__
631

    
632
static int dynticks_start_timer(struct qemu_alarm_timer *t);
633
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
634
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
635

    
636
static int hpet_start_timer(struct qemu_alarm_timer *t);
637
static void hpet_stop_timer(struct qemu_alarm_timer *t);
638

    
639
static int rtc_start_timer(struct qemu_alarm_timer *t);
640
static void rtc_stop_timer(struct qemu_alarm_timer *t);
641

    
642
#endif /* __linux__ */
643

    
644
#endif /* _WIN32 */
645

    
646
/* Correlation between real and virtual time is always going to be
647
   fairly approximate, so ignore small variation.
648
   When the guest is idle real and virtual time will be aligned in
649
   the IO wait loop.  */
650
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
651

    
652
static void icount_adjust(void)
653
{
654
    int64_t cur_time;
655
    int64_t cur_icount;
656
    int64_t delta;
657
    static int64_t last_delta;
658
    /* If the VM is not running, then do nothing.  */
659
    if (!vm_running)
660
        return;
661

    
662
    cur_time = cpu_get_clock();
663
    cur_icount = qemu_get_clock(vm_clock);
664
    delta = cur_icount - cur_time;
665
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
666
    if (delta > 0
667
        && last_delta + ICOUNT_WOBBLE < delta * 2
668
        && icount_time_shift > 0) {
669
        /* The guest is getting too far ahead.  Slow time down.  */
670
        icount_time_shift--;
671
    }
672
    if (delta < 0
673
        && last_delta - ICOUNT_WOBBLE > delta * 2
674
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
675
        /* The guest is getting too far behind.  Speed time up.  */
676
        icount_time_shift++;
677
    }
678
    last_delta = delta;
679
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
680
}
681

    
682
static void icount_adjust_rt(void * opaque)
683
{
684
    qemu_mod_timer(icount_rt_timer,
685
                   qemu_get_clock(rt_clock) + 1000);
686
    icount_adjust();
687
}
688

    
689
static void icount_adjust_vm(void * opaque)
690
{
691
    qemu_mod_timer(icount_vm_timer,
692
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
693
    icount_adjust();
694
}
695

    
696
static void init_icount_adjust(void)
697
{
698
    /* Have both realtime and virtual time triggers for speed adjustment.
699
       The realtime trigger catches emulated time passing too slowly,
700
       the virtual time trigger catches emulated time passing too fast.
701
       Realtime triggers occur even when idle, so use them less frequently
702
       than VM triggers.  */
703
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
704
    qemu_mod_timer(icount_rt_timer,
705
                   qemu_get_clock(rt_clock) + 1000);
706
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
707
    qemu_mod_timer(icount_vm_timer,
708
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
709
}
710

    
711
static struct qemu_alarm_timer alarm_timers[] = {
712
#ifndef _WIN32
713
#ifdef __linux__
714
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
715
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
716
    /* HPET - if available - is preferred */
717
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
718
    /* ...otherwise try RTC */
719
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
720
#endif
721
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
722
#else
723
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
724
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
725
    {"win32", 0, win32_start_timer,
726
     win32_stop_timer, NULL, &alarm_win32_data},
727
#endif
728
    {NULL, }
729
};
730

    
731
static void show_available_alarms(void)
732
{
733
    int i;
734

    
735
    printf("Available alarm timers, in order of precedence:\n");
736
    for (i = 0; alarm_timers[i].name; i++)
737
        printf("%s\n", alarm_timers[i].name);
738
}
739

    
740
static void configure_alarms(char const *opt)
741
{
742
    int i;
743
    int cur = 0;
744
    int count = ARRAY_SIZE(alarm_timers) - 1;
745
    char *arg;
746
    char *name;
747
    struct qemu_alarm_timer tmp;
748

    
749
    if (!strcmp(opt, "?")) {
750
        show_available_alarms();
751
        exit(0);
752
    }
753

    
754
    arg = qemu_strdup(opt);
755

    
756
    /* Reorder the array */
757
    name = strtok(arg, ",");
758
    while (name) {
759
        for (i = 0; i < count && alarm_timers[i].name; i++) {
760
            if (!strcmp(alarm_timers[i].name, name))
761
                break;
762
        }
763

    
764
        if (i == count) {
765
            fprintf(stderr, "Unknown clock %s\n", name);
766
            goto next;
767
        }
768

    
769
        if (i < cur)
770
            /* Ignore */
771
            goto next;
772

    
773
        /* Swap */
774
        tmp = alarm_timers[i];
775
        alarm_timers[i] = alarm_timers[cur];
776
        alarm_timers[cur] = tmp;
777

    
778
        cur++;
779
next:
780
        name = strtok(NULL, ",");
781
    }
782

    
783
    qemu_free(arg);
784

    
785
    if (cur) {
786
        /* Disable remaining timers */
787
        for (i = cur; i < count; i++)
788
            alarm_timers[i].name = NULL;
789
    } else {
790
        show_available_alarms();
791
        exit(1);
792
    }
793
}
794

    
795
#define QEMU_NUM_CLOCKS 3
796

    
797
QEMUClock *rt_clock;
798
QEMUClock *vm_clock;
799
QEMUClock *host_clock;
800

    
801
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
802

    
803
static QEMUClock *qemu_new_clock(int type)
804
{
805
    QEMUClock *clock;
806
    clock = qemu_mallocz(sizeof(QEMUClock));
807
    clock->type = type;
808
    return clock;
809
}
810

    
811
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
812
{
813
    QEMUTimer *ts;
814

    
815
    ts = qemu_mallocz(sizeof(QEMUTimer));
816
    ts->clock = clock;
817
    ts->cb = cb;
818
    ts->opaque = opaque;
819
    return ts;
820
}
821

    
822
void qemu_free_timer(QEMUTimer *ts)
823
{
824
    qemu_free(ts);
825
}
826

    
827
/* stop a timer, but do not dealloc it */
828
void qemu_del_timer(QEMUTimer *ts)
829
{
830
    QEMUTimer **pt, *t;
831

    
832
    /* NOTE: this code must be signal safe because
833
       qemu_timer_expired() can be called from a signal. */
834
    pt = &active_timers[ts->clock->type];
835
    for(;;) {
836
        t = *pt;
837
        if (!t)
838
            break;
839
        if (t == ts) {
840
            *pt = t->next;
841
            break;
842
        }
843
        pt = &t->next;
844
    }
845
}
846

    
847
/* modify the current timer so that it will be fired when current_time
848
   >= expire_time. The corresponding callback will be called. */
849
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
850
{
851
    QEMUTimer **pt, *t;
852

    
853
    qemu_del_timer(ts);
854

    
855
    /* add the timer in the sorted list */
856
    /* NOTE: this code must be signal safe because
857
       qemu_timer_expired() can be called from a signal. */
858
    pt = &active_timers[ts->clock->type];
859
    for(;;) {
860
        t = *pt;
861
        if (!t)
862
            break;
863
        if (t->expire_time > expire_time)
864
            break;
865
        pt = &t->next;
866
    }
867
    ts->expire_time = expire_time;
868
    ts->next = *pt;
869
    *pt = ts;
870

    
871
    /* Rearm if necessary  */
872
    if (pt == &active_timers[ts->clock->type]) {
873
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
874
            qemu_rearm_alarm_timer(alarm_timer);
875
        }
876
        /* Interrupt execution to force deadline recalculation.  */
877
        if (use_icount)
878
            qemu_notify_event();
879
    }
880
}
881

    
882
int qemu_timer_pending(QEMUTimer *ts)
883
{
884
    QEMUTimer *t;
885
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
886
        if (t == ts)
887
            return 1;
888
    }
889
    return 0;
890
}
891

    
892
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
893
{
894
    if (!timer_head)
895
        return 0;
896
    return (timer_head->expire_time <= current_time);
897
}
898

    
899
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
900
{
901
    QEMUTimer *ts;
902

    
903
    for(;;) {
904
        ts = *ptimer_head;
905
        if (!ts || ts->expire_time > current_time)
906
            break;
907
        /* remove timer from the list before calling the callback */
908
        *ptimer_head = ts->next;
909
        ts->next = NULL;
910

    
911
        /* run the callback (the timer list can be modified) */
912
        ts->cb(ts->opaque);
913
    }
914
}
915

    
916
int64_t qemu_get_clock(QEMUClock *clock)
917
{
918
    switch(clock->type) {
919
    case QEMU_CLOCK_REALTIME:
920
        return get_clock() / 1000000;
921
    default:
922
    case QEMU_CLOCK_VIRTUAL:
923
        if (use_icount) {
924
            return cpu_get_icount();
925
        } else {
926
            return cpu_get_clock();
927
        }
928
    case QEMU_CLOCK_HOST:
929
        return get_clock_realtime();
930
    }
931
}
932

    
933
int64_t qemu_get_clock_ns(QEMUClock *clock)
934
{
935
    switch(clock->type) {
936
    case QEMU_CLOCK_REALTIME:
937
        return get_clock();
938
    default:
939
    case QEMU_CLOCK_VIRTUAL:
940
        if (use_icount) {
941
            return cpu_get_icount();
942
        } else {
943
            return cpu_get_clock();
944
        }
945
    case QEMU_CLOCK_HOST:
946
        return get_clock_realtime();
947
    }
948
}
949

    
950
static void init_clocks(void)
951
{
952
    init_get_clock();
953
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
954
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
955
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
956

    
957
    rtc_clock = host_clock;
958
}
959

    
960
/* save a timer */
961
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
962
{
963
    uint64_t expire_time;
964

    
965
    if (qemu_timer_pending(ts)) {
966
        expire_time = ts->expire_time;
967
    } else {
968
        expire_time = -1;
969
    }
970
    qemu_put_be64(f, expire_time);
971
}
972

    
973
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
974
{
975
    uint64_t expire_time;
976

    
977
    expire_time = qemu_get_be64(f);
978
    if (expire_time != -1) {
979
        qemu_mod_timer(ts, expire_time);
980
    } else {
981
        qemu_del_timer(ts);
982
    }
983
}
984

    
985
static const VMStateDescription vmstate_timers = {
986
    .name = "timer",
987
    .version_id = 2,
988
    .minimum_version_id = 1,
989
    .minimum_version_id_old = 1,
990
    .fields      = (VMStateField []) {
991
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
992
        VMSTATE_INT64(dummy, TimersState),
993
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
994
        VMSTATE_END_OF_LIST()
995
    }
996
};
997

    
998
static void qemu_event_increment(void);
999

    
1000
#ifdef _WIN32
1001
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1002
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
1003
                                        DWORD_PTR dw2)
1004
#else
1005
static void host_alarm_handler(int host_signum)
1006
#endif
1007
{
1008
#if 0
1009
#define DISP_FREQ 1000
1010
    {
1011
        static int64_t delta_min = INT64_MAX;
1012
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1013
        static int count;
1014
        ti = qemu_get_clock(vm_clock);
1015
        if (last_clock != 0) {
1016
            delta = ti - last_clock;
1017
            if (delta < delta_min)
1018
                delta_min = delta;
1019
            if (delta > delta_max)
1020
                delta_max = delta;
1021
            delta_cum += delta;
1022
            if (++count == DISP_FREQ) {
1023
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1024
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1025
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1026
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1027
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1028
                count = 0;
1029
                delta_min = INT64_MAX;
1030
                delta_max = 0;
1031
                delta_cum = 0;
1032
            }
1033
        }
1034
        last_clock = ti;
1035
    }
1036
#endif
1037
    if (alarm_has_dynticks(alarm_timer) ||
1038
        (!use_icount &&
1039
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1040
                               qemu_get_clock(vm_clock))) ||
1041
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1042
                           qemu_get_clock(rt_clock)) ||
1043
        qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1044
                           qemu_get_clock(host_clock))) {
1045
        qemu_event_increment();
1046
        if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1047

    
1048
#ifndef CONFIG_IOTHREAD
1049
        if (next_cpu) {
1050
            /* stop the currently executing cpu because a timer occured */
1051
            cpu_exit(next_cpu);
1052
        }
1053
#endif
1054
        timer_alarm_pending = 1;
1055
        qemu_notify_event();
1056
    }
1057
}
1058

    
1059
static int64_t qemu_next_deadline(void)
1060
{
1061
    /* To avoid problems with overflow limit this to 2^32.  */
1062
    int64_t delta = INT32_MAX;
1063

    
1064
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1065
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1066
                     qemu_get_clock(vm_clock);
1067
    }
1068
    if (active_timers[QEMU_CLOCK_HOST]) {
1069
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1070
                 qemu_get_clock(host_clock);
1071
        if (hdelta < delta)
1072
            delta = hdelta;
1073
    }
1074

    
1075
    if (delta < 0)
1076
        delta = 0;
1077

    
1078
    return delta;
1079
}
1080

    
1081
#if defined(__linux__)
1082
static uint64_t qemu_next_deadline_dyntick(void)
1083
{
1084
    int64_t delta;
1085
    int64_t rtdelta;
1086

    
1087
    if (use_icount)
1088
        delta = INT32_MAX;
1089
    else
1090
        delta = (qemu_next_deadline() + 999) / 1000;
1091

    
1092
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1093
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1094
                 qemu_get_clock(rt_clock))*1000;
1095
        if (rtdelta < delta)
1096
            delta = rtdelta;
1097
    }
1098

    
1099
    if (delta < MIN_TIMER_REARM_US)
1100
        delta = MIN_TIMER_REARM_US;
1101

    
1102
    return delta;
1103
}
1104
#endif
1105

    
1106
#ifndef _WIN32
1107

    
1108
/* Sets a specific flag */
1109
static int fcntl_setfl(int fd, int flag)
1110
{
1111
    int flags;
1112

    
1113
    flags = fcntl(fd, F_GETFL);
1114
    if (flags == -1)
1115
        return -errno;
1116

    
1117
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1118
        return -errno;
1119

    
1120
    return 0;
1121
}
1122

    
1123
#if defined(__linux__)
1124

    
1125
#define RTC_FREQ 1024
1126

    
1127
static void enable_sigio_timer(int fd)
1128
{
1129
    struct sigaction act;
1130

    
1131
    /* timer signal */
1132
    sigfillset(&act.sa_mask);
1133
    act.sa_flags = 0;
1134
    act.sa_handler = host_alarm_handler;
1135

    
1136
    sigaction(SIGIO, &act, NULL);
1137
    fcntl_setfl(fd, O_ASYNC);
1138
    fcntl(fd, F_SETOWN, getpid());
1139
}
1140

    
1141
static int hpet_start_timer(struct qemu_alarm_timer *t)
1142
{
1143
    struct hpet_info info;
1144
    int r, fd;
1145

    
1146
    fd = qemu_open("/dev/hpet", O_RDONLY);
1147
    if (fd < 0)
1148
        return -1;
1149

    
1150
    /* Set frequency */
1151
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1152
    if (r < 0) {
1153
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1154
                "error, but for better emulation accuracy type:\n"
1155
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1156
        goto fail;
1157
    }
1158

    
1159
    /* Check capabilities */
1160
    r = ioctl(fd, HPET_INFO, &info);
1161
    if (r < 0)
1162
        goto fail;
1163

    
1164
    /* Enable periodic mode */
1165
    r = ioctl(fd, HPET_EPI, 0);
1166
    if (info.hi_flags && (r < 0))
1167
        goto fail;
1168

    
1169
    /* Enable interrupt */
1170
    r = ioctl(fd, HPET_IE_ON, 0);
1171
    if (r < 0)
1172
        goto fail;
1173

    
1174
    enable_sigio_timer(fd);
1175
    t->priv = (void *)(long)fd;
1176

    
1177
    return 0;
1178
fail:
1179
    close(fd);
1180
    return -1;
1181
}
1182

    
1183
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1184
{
1185
    int fd = (long)t->priv;
1186

    
1187
    close(fd);
1188
}
1189

    
1190
static int rtc_start_timer(struct qemu_alarm_timer *t)
1191
{
1192
    int rtc_fd;
1193
    unsigned long current_rtc_freq = 0;
1194

    
1195
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1196
    if (rtc_fd < 0)
1197
        return -1;
1198
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1199
    if (current_rtc_freq != RTC_FREQ &&
1200
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1201
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1202
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1203
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1204
        goto fail;
1205
    }
1206
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1207
    fail:
1208
        close(rtc_fd);
1209
        return -1;
1210
    }
1211

    
1212
    enable_sigio_timer(rtc_fd);
1213

    
1214
    t->priv = (void *)(long)rtc_fd;
1215

    
1216
    return 0;
1217
}
1218

    
1219
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1220
{
1221
    int rtc_fd = (long)t->priv;
1222

    
1223
    close(rtc_fd);
1224
}
1225

    
1226
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1227
{
1228
    struct sigevent ev;
1229
    timer_t host_timer;
1230
    struct sigaction act;
1231

    
1232
    sigfillset(&act.sa_mask);
1233
    act.sa_flags = 0;
1234
    act.sa_handler = host_alarm_handler;
1235

    
1236
    sigaction(SIGALRM, &act, NULL);
1237

    
1238
    /* 
1239
     * Initialize ev struct to 0 to avoid valgrind complaining
1240
     * about uninitialized data in timer_create call
1241
     */
1242
    memset(&ev, 0, sizeof(ev));
1243
    ev.sigev_value.sival_int = 0;
1244
    ev.sigev_notify = SIGEV_SIGNAL;
1245
    ev.sigev_signo = SIGALRM;
1246

    
1247
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1248
        perror("timer_create");
1249

    
1250
        /* disable dynticks */
1251
        fprintf(stderr, "Dynamic Ticks disabled\n");
1252

    
1253
        return -1;
1254
    }
1255

    
1256
    t->priv = (void *)(long)host_timer;
1257

    
1258
    return 0;
1259
}
1260

    
1261
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1262
{
1263
    timer_t host_timer = (timer_t)(long)t->priv;
1264

    
1265
    timer_delete(host_timer);
1266
}
1267

    
1268
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1269
{
1270
    timer_t host_timer = (timer_t)(long)t->priv;
1271
    struct itimerspec timeout;
1272
    int64_t nearest_delta_us = INT64_MAX;
1273
    int64_t current_us;
1274

    
1275
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1276
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1277
        !active_timers[QEMU_CLOCK_HOST])
1278
        return;
1279

    
1280
    nearest_delta_us = qemu_next_deadline_dyntick();
1281

    
1282
    /* check whether a timer is already running */
1283
    if (timer_gettime(host_timer, &timeout)) {
1284
        perror("gettime");
1285
        fprintf(stderr, "Internal timer error: aborting\n");
1286
        exit(1);
1287
    }
1288
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1289
    if (current_us && current_us <= nearest_delta_us)
1290
        return;
1291

    
1292
    timeout.it_interval.tv_sec = 0;
1293
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1294
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1295
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1296
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1297
        perror("settime");
1298
        fprintf(stderr, "Internal timer error: aborting\n");
1299
        exit(1);
1300
    }
1301
}
1302

    
1303
#endif /* defined(__linux__) */
1304

    
1305
static int unix_start_timer(struct qemu_alarm_timer *t)
1306
{
1307
    struct sigaction act;
1308
    struct itimerval itv;
1309
    int err;
1310

    
1311
    /* timer signal */
1312
    sigfillset(&act.sa_mask);
1313
    act.sa_flags = 0;
1314
    act.sa_handler = host_alarm_handler;
1315

    
1316
    sigaction(SIGALRM, &act, NULL);
1317

    
1318
    itv.it_interval.tv_sec = 0;
1319
    /* for i386 kernel 2.6 to get 1 ms */
1320
    itv.it_interval.tv_usec = 999;
1321
    itv.it_value.tv_sec = 0;
1322
    itv.it_value.tv_usec = 10 * 1000;
1323

    
1324
    err = setitimer(ITIMER_REAL, &itv, NULL);
1325
    if (err)
1326
        return -1;
1327

    
1328
    return 0;
1329
}
1330

    
1331
static void unix_stop_timer(struct qemu_alarm_timer *t)
1332
{
1333
    struct itimerval itv;
1334

    
1335
    memset(&itv, 0, sizeof(itv));
1336
    setitimer(ITIMER_REAL, &itv, NULL);
1337
}
1338

    
1339
#endif /* !defined(_WIN32) */
1340

    
1341

    
1342
#ifdef _WIN32
1343

    
1344
static int win32_start_timer(struct qemu_alarm_timer *t)
1345
{
1346
    TIMECAPS tc;
1347
    struct qemu_alarm_win32 *data = t->priv;
1348
    UINT flags;
1349

    
1350
    memset(&tc, 0, sizeof(tc));
1351
    timeGetDevCaps(&tc, sizeof(tc));
1352

    
1353
    if (data->period < tc.wPeriodMin)
1354
        data->period = tc.wPeriodMin;
1355

    
1356
    timeBeginPeriod(data->period);
1357

    
1358
    flags = TIME_CALLBACK_FUNCTION;
1359
    if (alarm_has_dynticks(t))
1360
        flags |= TIME_ONESHOT;
1361
    else
1362
        flags |= TIME_PERIODIC;
1363

    
1364
    data->timerId = timeSetEvent(1,         // interval (ms)
1365
                        data->period,       // resolution
1366
                        host_alarm_handler, // function
1367
                        (DWORD)t,           // parameter
1368
                        flags);
1369

    
1370
    if (!data->timerId) {
1371
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1372
                GetLastError());
1373
        timeEndPeriod(data->period);
1374
        return -1;
1375
    }
1376

    
1377
    return 0;
1378
}
1379

    
1380
static void win32_stop_timer(struct qemu_alarm_timer *t)
1381
{
1382
    struct qemu_alarm_win32 *data = t->priv;
1383

    
1384
    timeKillEvent(data->timerId);
1385
    timeEndPeriod(data->period);
1386
}
1387

    
1388
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1389
{
1390
    struct qemu_alarm_win32 *data = t->priv;
1391

    
1392
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1393
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1394
        !active_timers[QEMU_CLOCK_HOST])
1395
        return;
1396

    
1397
    timeKillEvent(data->timerId);
1398

    
1399
    data->timerId = timeSetEvent(1,
1400
                        data->period,
1401
                        host_alarm_handler,
1402
                        (DWORD)t,
1403
                        TIME_ONESHOT | TIME_PERIODIC);
1404

    
1405
    if (!data->timerId) {
1406
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1407
                GetLastError());
1408

    
1409
        timeEndPeriod(data->period);
1410
        exit(1);
1411
    }
1412
}
1413

    
1414
#endif /* _WIN32 */
1415

    
1416
static int init_timer_alarm(void)
1417
{
1418
    struct qemu_alarm_timer *t = NULL;
1419
    int i, err = -1;
1420

    
1421
    for (i = 0; alarm_timers[i].name; i++) {
1422
        t = &alarm_timers[i];
1423

    
1424
        err = t->start(t);
1425
        if (!err)
1426
            break;
1427
    }
1428

    
1429
    if (err) {
1430
        err = -ENOENT;
1431
        goto fail;
1432
    }
1433

    
1434
    alarm_timer = t;
1435

    
1436
    return 0;
1437

    
1438
fail:
1439
    return err;
1440
}
1441

    
1442
static void quit_timers(void)
1443
{
1444
    alarm_timer->stop(alarm_timer);
1445
    alarm_timer = NULL;
1446
}
1447

    
1448
/***********************************************************/
1449
/* host time/date access */
1450
void qemu_get_timedate(struct tm *tm, int offset)
1451
{
1452
    time_t ti;
1453
    struct tm *ret;
1454

    
1455
    time(&ti);
1456
    ti += offset;
1457
    if (rtc_date_offset == -1) {
1458
        if (rtc_utc)
1459
            ret = gmtime(&ti);
1460
        else
1461
            ret = localtime(&ti);
1462
    } else {
1463
        ti -= rtc_date_offset;
1464
        ret = gmtime(&ti);
1465
    }
1466

    
1467
    memcpy(tm, ret, sizeof(struct tm));
1468
}
1469

    
1470
int qemu_timedate_diff(struct tm *tm)
1471
{
1472
    time_t seconds;
1473

    
1474
    if (rtc_date_offset == -1)
1475
        if (rtc_utc)
1476
            seconds = mktimegm(tm);
1477
        else
1478
            seconds = mktime(tm);
1479
    else
1480
        seconds = mktimegm(tm) + rtc_date_offset;
1481

    
1482
    return seconds - time(NULL);
1483
}
1484

    
1485
static void configure_rtc_date_offset(const char *startdate, int legacy)
1486
{
1487
    time_t rtc_start_date;
1488
    struct tm tm;
1489

    
1490
    if (!strcmp(startdate, "now") && legacy) {
1491
        rtc_date_offset = -1;
1492
    } else {
1493
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1494
                   &tm.tm_year,
1495
                   &tm.tm_mon,
1496
                   &tm.tm_mday,
1497
                   &tm.tm_hour,
1498
                   &tm.tm_min,
1499
                   &tm.tm_sec) == 6) {
1500
            /* OK */
1501
        } else if (sscanf(startdate, "%d-%d-%d",
1502
                          &tm.tm_year,
1503
                          &tm.tm_mon,
1504
                          &tm.tm_mday) == 3) {
1505
            tm.tm_hour = 0;
1506
            tm.tm_min = 0;
1507
            tm.tm_sec = 0;
1508
        } else {
1509
            goto date_fail;
1510
        }
1511
        tm.tm_year -= 1900;
1512
        tm.tm_mon--;
1513
        rtc_start_date = mktimegm(&tm);
1514
        if (rtc_start_date == -1) {
1515
        date_fail:
1516
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
1517
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
1518
            exit(1);
1519
        }
1520
        rtc_date_offset = time(NULL) - rtc_start_date;
1521
    }
1522
}
1523

    
1524
static void configure_rtc(QemuOpts *opts)
1525
{
1526
    const char *value;
1527

    
1528
    value = qemu_opt_get(opts, "base");
1529
    if (value) {
1530
        if (!strcmp(value, "utc")) {
1531
            rtc_utc = 1;
1532
        } else if (!strcmp(value, "localtime")) {
1533
            rtc_utc = 0;
1534
        } else {
1535
            configure_rtc_date_offset(value, 0);
1536
        }
1537
    }
1538
    value = qemu_opt_get(opts, "clock");
1539
    if (value) {
1540
        if (!strcmp(value, "host")) {
1541
            rtc_clock = host_clock;
1542
        } else if (!strcmp(value, "vm")) {
1543
            rtc_clock = vm_clock;
1544
        } else {
1545
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1546
            exit(1);
1547
        }
1548
    }
1549
#ifdef CONFIG_TARGET_I386
1550
    value = qemu_opt_get(opts, "driftfix");
1551
    if (value) {
1552
        if (!strcmp(buf, "slew")) {
1553
            rtc_td_hack = 1;
1554
        } else if (!strcmp(buf, "none")) {
1555
            rtc_td_hack = 0;
1556
        } else {
1557
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1558
            exit(1);
1559
        }
1560
    }
1561
#endif
1562
}
1563

    
1564
#ifdef _WIN32
1565
static void socket_cleanup(void)
1566
{
1567
    WSACleanup();
1568
}
1569

    
1570
static int socket_init(void)
1571
{
1572
    WSADATA Data;
1573
    int ret, err;
1574

    
1575
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1576
    if (ret != 0) {
1577
        err = WSAGetLastError();
1578
        fprintf(stderr, "WSAStartup: %d\n", err);
1579
        return -1;
1580
    }
1581
    atexit(socket_cleanup);
1582
    return 0;
1583
}
1584
#endif
1585

    
1586
/***********************************************************/
1587
/* Bluetooth support */
1588
static int nb_hcis;
1589
static int cur_hci;
1590
static struct HCIInfo *hci_table[MAX_NICS];
1591

    
1592
static struct bt_vlan_s {
1593
    struct bt_scatternet_s net;
1594
    int id;
1595
    struct bt_vlan_s *next;
1596
} *first_bt_vlan;
1597

    
1598
/* find or alloc a new bluetooth "VLAN" */
1599
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1600
{
1601
    struct bt_vlan_s **pvlan, *vlan;
1602
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1603
        if (vlan->id == id)
1604
            return &vlan->net;
1605
    }
1606
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1607
    vlan->id = id;
1608
    pvlan = &first_bt_vlan;
1609
    while (*pvlan != NULL)
1610
        pvlan = &(*pvlan)->next;
1611
    *pvlan = vlan;
1612
    return &vlan->net;
1613
}
1614

    
1615
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1616
{
1617
}
1618

    
1619
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1620
{
1621
    return -ENOTSUP;
1622
}
1623

    
1624
static struct HCIInfo null_hci = {
1625
    .cmd_send = null_hci_send,
1626
    .sco_send = null_hci_send,
1627
    .acl_send = null_hci_send,
1628
    .bdaddr_set = null_hci_addr_set,
1629
};
1630

    
1631
struct HCIInfo *qemu_next_hci(void)
1632
{
1633
    if (cur_hci == nb_hcis)
1634
        return &null_hci;
1635

    
1636
    return hci_table[cur_hci++];
1637
}
1638

    
1639
static struct HCIInfo *hci_init(const char *str)
1640
{
1641
    char *endp;
1642
    struct bt_scatternet_s *vlan = 0;
1643

    
1644
    if (!strcmp(str, "null"))
1645
        /* null */
1646
        return &null_hci;
1647
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1648
        /* host[:hciN] */
1649
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1650
    else if (!strncmp(str, "hci", 3)) {
1651
        /* hci[,vlan=n] */
1652
        if (str[3]) {
1653
            if (!strncmp(str + 3, ",vlan=", 6)) {
1654
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1655
                if (*endp)
1656
                    vlan = 0;
1657
            }
1658
        } else
1659
            vlan = qemu_find_bt_vlan(0);
1660
        if (vlan)
1661
           return bt_new_hci(vlan);
1662
    }
1663

    
1664
    fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1665

    
1666
    return 0;
1667
}
1668

    
1669
static int bt_hci_parse(const char *str)
1670
{
1671
    struct HCIInfo *hci;
1672
    bdaddr_t bdaddr;
1673

    
1674
    if (nb_hcis >= MAX_NICS) {
1675
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1676
        return -1;
1677
    }
1678

    
1679
    hci = hci_init(str);
1680
    if (!hci)
1681
        return -1;
1682

    
1683
    bdaddr.b[0] = 0x52;
1684
    bdaddr.b[1] = 0x54;
1685
    bdaddr.b[2] = 0x00;
1686
    bdaddr.b[3] = 0x12;
1687
    bdaddr.b[4] = 0x34;
1688
    bdaddr.b[5] = 0x56 + nb_hcis;
1689
    hci->bdaddr_set(hci, bdaddr.b);
1690

    
1691
    hci_table[nb_hcis++] = hci;
1692

    
1693
    return 0;
1694
}
1695

    
1696
static void bt_vhci_add(int vlan_id)
1697
{
1698
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1699

    
1700
    if (!vlan->slave)
1701
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1702
                        "an empty scatternet %i\n", vlan_id);
1703

    
1704
    bt_vhci_init(bt_new_hci(vlan));
1705
}
1706

    
1707
static struct bt_device_s *bt_device_add(const char *opt)
1708
{
1709
    struct bt_scatternet_s *vlan;
1710
    int vlan_id = 0;
1711
    char *endp = strstr(opt, ",vlan=");
1712
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1713
    char devname[10];
1714

    
1715
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1716

    
1717
    if (endp) {
1718
        vlan_id = strtol(endp + 6, &endp, 0);
1719
        if (*endp) {
1720
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1721
            return 0;
1722
        }
1723
    }
1724

    
1725
    vlan = qemu_find_bt_vlan(vlan_id);
1726

    
1727
    if (!vlan->slave)
1728
        fprintf(stderr, "qemu: warning: adding a slave device to "
1729
                        "an empty scatternet %i\n", vlan_id);
1730

    
1731
    if (!strcmp(devname, "keyboard"))
1732
        return bt_keyboard_init(vlan);
1733

    
1734
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1735
    return 0;
1736
}
1737

    
1738
static int bt_parse(const char *opt)
1739
{
1740
    const char *endp, *p;
1741
    int vlan;
1742

    
1743
    if (strstart(opt, "hci", &endp)) {
1744
        if (!*endp || *endp == ',') {
1745
            if (*endp)
1746
                if (!strstart(endp, ",vlan=", 0))
1747
                    opt = endp + 1;
1748

    
1749
            return bt_hci_parse(opt);
1750
       }
1751
    } else if (strstart(opt, "vhci", &endp)) {
1752
        if (!*endp || *endp == ',') {
1753
            if (*endp) {
1754
                if (strstart(endp, ",vlan=", &p)) {
1755
                    vlan = strtol(p, (char **) &endp, 0);
1756
                    if (*endp) {
1757
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1758
                        return 1;
1759
                    }
1760
                } else {
1761
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1762
                    return 1;
1763
                }
1764
            } else
1765
                vlan = 0;
1766

    
1767
            bt_vhci_add(vlan);
1768
            return 0;
1769
        }
1770
    } else if (strstart(opt, "device:", &endp))
1771
        return !bt_device_add(endp);
1772

    
1773
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1774
    return 1;
1775
}
1776

    
1777
/***********************************************************/
1778
/* QEMU Block devices */
1779

    
1780
#define HD_ALIAS "index=%d,media=disk"
1781
#define CDROM_ALIAS "index=2,media=cdrom"
1782
#define FD_ALIAS "index=%d,if=floppy"
1783
#define PFLASH_ALIAS "if=pflash"
1784
#define MTD_ALIAS "if=mtd"
1785
#define SD_ALIAS "index=0,if=sd"
1786

    
1787
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1788
{
1789
    va_list ap;
1790
    char optstr[1024];
1791
    QemuOpts *opts;
1792

    
1793
    va_start(ap, fmt);
1794
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1795
    va_end(ap);
1796

    
1797
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1798
    if (!opts) {
1799
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1800
                __FUNCTION__, optstr);
1801
        return NULL;
1802
    }
1803
    if (file)
1804
        qemu_opt_set(opts, "file", file);
1805
    return opts;
1806
}
1807

    
1808
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1809
{
1810
    DriveInfo *dinfo;
1811

    
1812
    /* seek interface, bus and unit */
1813

    
1814
    QTAILQ_FOREACH(dinfo, &drives, next) {
1815
        if (dinfo->type == type &&
1816
            dinfo->bus == bus &&
1817
            dinfo->unit == unit)
1818
            return dinfo;
1819
    }
1820

    
1821
    return NULL;
1822
}
1823

    
1824
DriveInfo *drive_get_by_id(const char *id)
1825
{
1826
    DriveInfo *dinfo;
1827

    
1828
    QTAILQ_FOREACH(dinfo, &drives, next) {
1829
        if (strcmp(id, dinfo->id))
1830
            continue;
1831
        return dinfo;
1832
    }
1833
    return NULL;
1834
}
1835

    
1836
int drive_get_max_bus(BlockInterfaceType type)
1837
{
1838
    int max_bus;
1839
    DriveInfo *dinfo;
1840

    
1841
    max_bus = -1;
1842
    QTAILQ_FOREACH(dinfo, &drives, next) {
1843
        if(dinfo->type == type &&
1844
           dinfo->bus > max_bus)
1845
            max_bus = dinfo->bus;
1846
    }
1847
    return max_bus;
1848
}
1849

    
1850
const char *drive_get_serial(BlockDriverState *bdrv)
1851
{
1852
    DriveInfo *dinfo;
1853

    
1854
    QTAILQ_FOREACH(dinfo, &drives, next) {
1855
        if (dinfo->bdrv == bdrv)
1856
            return dinfo->serial;
1857
    }
1858

    
1859
    return "\0";
1860
}
1861

    
1862
BlockInterfaceErrorAction drive_get_on_error(
1863
    BlockDriverState *bdrv, int is_read)
1864
{
1865
    DriveInfo *dinfo;
1866

    
1867
    QTAILQ_FOREACH(dinfo, &drives, next) {
1868
        if (dinfo->bdrv == bdrv)
1869
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1870
    }
1871

    
1872
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1873
}
1874

    
1875
static void bdrv_format_print(void *opaque, const char *name)
1876
{
1877
    fprintf(stderr, " %s", name);
1878
}
1879

    
1880
void drive_uninit(DriveInfo *dinfo)
1881
{
1882
    qemu_opts_del(dinfo->opts);
1883
    bdrv_delete(dinfo->bdrv);
1884
    QTAILQ_REMOVE(&drives, dinfo, next);
1885
    qemu_free(dinfo);
1886
}
1887

    
1888
static int parse_block_error_action(const char *buf, int is_read)
1889
{
1890
    if (!strcmp(buf, "ignore")) {
1891
        return BLOCK_ERR_IGNORE;
1892
    } else if (!is_read && !strcmp(buf, "enospc")) {
1893
        return BLOCK_ERR_STOP_ENOSPC;
1894
    } else if (!strcmp(buf, "stop")) {
1895
        return BLOCK_ERR_STOP_ANY;
1896
    } else if (!strcmp(buf, "report")) {
1897
        return BLOCK_ERR_REPORT;
1898
    } else {
1899
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1900
            buf, is_read ? "read" : "write");
1901
        return -1;
1902
    }
1903
}
1904

    
1905
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1906
                      int *fatal_error)
1907
{
1908
    const char *buf;
1909
    const char *file = NULL;
1910
    char devname[128];
1911
    const char *serial;
1912
    const char *mediastr = "";
1913
    BlockInterfaceType type;
1914
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1915
    int bus_id, unit_id;
1916
    int cyls, heads, secs, translation;
1917
    BlockDriver *drv = NULL;
1918
    QEMUMachine *machine = opaque;
1919
    int max_devs;
1920
    int index;
1921
    int cache;
1922
    int aio = 0;
1923
    int ro = 0;
1924
    int bdrv_flags;
1925
    int on_read_error, on_write_error;
1926
    const char *devaddr;
1927
    DriveInfo *dinfo;
1928
    int snapshot = 0;
1929

    
1930
    *fatal_error = 1;
1931

    
1932
    translation = BIOS_ATA_TRANSLATION_AUTO;
1933
    cache = 1;
1934

    
1935
    if (machine && machine->use_scsi) {
1936
        type = IF_SCSI;
1937
        max_devs = MAX_SCSI_DEVS;
1938
        pstrcpy(devname, sizeof(devname), "scsi");
1939
    } else {
1940
        type = IF_IDE;
1941
        max_devs = MAX_IDE_DEVS;
1942
        pstrcpy(devname, sizeof(devname), "ide");
1943
    }
1944
    media = MEDIA_DISK;
1945

    
1946
    /* extract parameters */
1947
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
1948
    unit_id = qemu_opt_get_number(opts, "unit", -1);
1949
    index   = qemu_opt_get_number(opts, "index", -1);
1950

    
1951
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
1952
    heads = qemu_opt_get_number(opts, "heads", 0);
1953
    secs  = qemu_opt_get_number(opts, "secs", 0);
1954

    
1955
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1956
    ro = qemu_opt_get_bool(opts, "readonly", 0);
1957

    
1958
    file = qemu_opt_get(opts, "file");
1959
    serial = qemu_opt_get(opts, "serial");
1960

    
1961
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1962
        pstrcpy(devname, sizeof(devname), buf);
1963
        if (!strcmp(buf, "ide")) {
1964
            type = IF_IDE;
1965
            max_devs = MAX_IDE_DEVS;
1966
        } else if (!strcmp(buf, "scsi")) {
1967
            type = IF_SCSI;
1968
            max_devs = MAX_SCSI_DEVS;
1969
        } else if (!strcmp(buf, "floppy")) {
1970
            type = IF_FLOPPY;
1971
            max_devs = 0;
1972
        } else if (!strcmp(buf, "pflash")) {
1973
            type = IF_PFLASH;
1974
            max_devs = 0;
1975
        } else if (!strcmp(buf, "mtd")) {
1976
            type = IF_MTD;
1977
            max_devs = 0;
1978
        } else if (!strcmp(buf, "sd")) {
1979
            type = IF_SD;
1980
            max_devs = 0;
1981
        } else if (!strcmp(buf, "virtio")) {
1982
            type = IF_VIRTIO;
1983
            max_devs = 0;
1984
        } else if (!strcmp(buf, "xen")) {
1985
            type = IF_XEN;
1986
            max_devs = 0;
1987
        } else if (!strcmp(buf, "none")) {
1988
            type = IF_NONE;
1989
            max_devs = 0;
1990
        } else {
1991
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1992
            return NULL;
1993
        }
1994
    }
1995

    
1996
    if (cyls || heads || secs) {
1997
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1998
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1999
            return NULL;
2000
        }
2001
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
2002
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2003
            return NULL;
2004
        }
2005
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
2006
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2007
            return NULL;
2008
        }
2009
    }
2010

    
2011
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2012
        if (!cyls) {
2013
            fprintf(stderr,
2014
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2015
                    buf);
2016
            return NULL;
2017
        }
2018
        if (!strcmp(buf, "none"))
2019
            translation = BIOS_ATA_TRANSLATION_NONE;
2020
        else if (!strcmp(buf, "lba"))
2021
            translation = BIOS_ATA_TRANSLATION_LBA;
2022
        else if (!strcmp(buf, "auto"))
2023
            translation = BIOS_ATA_TRANSLATION_AUTO;
2024
        else {
2025
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2026
            return NULL;
2027
        }
2028
    }
2029

    
2030
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2031
        if (!strcmp(buf, "disk")) {
2032
            media = MEDIA_DISK;
2033
        } else if (!strcmp(buf, "cdrom")) {
2034
            if (cyls || secs || heads) {
2035
                fprintf(stderr,
2036
                        "qemu: '%s' invalid physical CHS format\n", buf);
2037
                return NULL;
2038
            }
2039
            media = MEDIA_CDROM;
2040
        } else {
2041
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2042
            return NULL;
2043
        }
2044
    }
2045

    
2046
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2047
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2048
            cache = 0;
2049
        else if (!strcmp(buf, "writethrough"))
2050
            cache = 1;
2051
        else if (!strcmp(buf, "writeback"))
2052
            cache = 2;
2053
        else {
2054
           fprintf(stderr, "qemu: invalid cache option\n");
2055
           return NULL;
2056
        }
2057
    }
2058

    
2059
#ifdef CONFIG_LINUX_AIO
2060
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2061
        if (!strcmp(buf, "threads"))
2062
            aio = 0;
2063
        else if (!strcmp(buf, "native"))
2064
            aio = 1;
2065
        else {
2066
           fprintf(stderr, "qemu: invalid aio option\n");
2067
           return NULL;
2068
        }
2069
    }
2070
#endif
2071

    
2072
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2073
       if (strcmp(buf, "?") == 0) {
2074
            fprintf(stderr, "qemu: Supported formats:");
2075
            bdrv_iterate_format(bdrv_format_print, NULL);
2076
            fprintf(stderr, "\n");
2077
            return NULL;
2078
        }
2079
        drv = bdrv_find_whitelisted_format(buf);
2080
        if (!drv) {
2081
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2082
            return NULL;
2083
        }
2084
    }
2085

    
2086
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2087
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2088
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2089
            fprintf(stderr, "werror is no supported by this format\n");
2090
            return NULL;
2091
        }
2092

    
2093
        on_write_error = parse_block_error_action(buf, 0);
2094
        if (on_write_error < 0) {
2095
            return NULL;
2096
        }
2097
    }
2098

    
2099
    on_read_error = BLOCK_ERR_REPORT;
2100
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2101
        if (type != IF_IDE && type != IF_VIRTIO) {
2102
            fprintf(stderr, "rerror is no supported by this format\n");
2103
            return NULL;
2104
        }
2105

    
2106
        on_read_error = parse_block_error_action(buf, 1);
2107
        if (on_read_error < 0) {
2108
            return NULL;
2109
        }
2110
    }
2111

    
2112
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2113
        if (type != IF_VIRTIO) {
2114
            fprintf(stderr, "addr is not supported\n");
2115
            return NULL;
2116
        }
2117
    }
2118

    
2119
    /* compute bus and unit according index */
2120

    
2121
    if (index != -1) {
2122
        if (bus_id != 0 || unit_id != -1) {
2123
            fprintf(stderr,
2124
                    "qemu: index cannot be used with bus and unit\n");
2125
            return NULL;
2126
        }
2127
        if (max_devs == 0)
2128
        {
2129
            unit_id = index;
2130
            bus_id = 0;
2131
        } else {
2132
            unit_id = index % max_devs;
2133
            bus_id = index / max_devs;
2134
        }
2135
    }
2136

    
2137
    /* if user doesn't specify a unit_id,
2138
     * try to find the first free
2139
     */
2140

    
2141
    if (unit_id == -1) {
2142
       unit_id = 0;
2143
       while (drive_get(type, bus_id, unit_id) != NULL) {
2144
           unit_id++;
2145
           if (max_devs && unit_id >= max_devs) {
2146
               unit_id -= max_devs;
2147
               bus_id++;
2148
           }
2149
       }
2150
    }
2151

    
2152
    /* check unit id */
2153

    
2154
    if (max_devs && unit_id >= max_devs) {
2155
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2156
                unit_id, max_devs - 1);
2157
        return NULL;
2158
    }
2159

    
2160
    /*
2161
     * ignore multiple definitions
2162
     */
2163

    
2164
    if (drive_get(type, bus_id, unit_id) != NULL) {
2165
        *fatal_error = 0;
2166
        return NULL;
2167
    }
2168

    
2169
    /* init */
2170

    
2171
    dinfo = qemu_mallocz(sizeof(*dinfo));
2172
    if ((buf = qemu_opts_id(opts)) != NULL) {
2173
        dinfo->id = qemu_strdup(buf);
2174
    } else {
2175
        /* no id supplied -> create one */
2176
        dinfo->id = qemu_mallocz(32);
2177
        if (type == IF_IDE || type == IF_SCSI)
2178
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2179
        if (max_devs)
2180
            snprintf(dinfo->id, 32, "%s%i%s%i",
2181
                     devname, bus_id, mediastr, unit_id);
2182
        else
2183
            snprintf(dinfo->id, 32, "%s%s%i",
2184
                     devname, mediastr, unit_id);
2185
    }
2186
    dinfo->bdrv = bdrv_new(dinfo->id);
2187
    dinfo->devaddr = devaddr;
2188
    dinfo->type = type;
2189
    dinfo->bus = bus_id;
2190
    dinfo->unit = unit_id;
2191
    dinfo->on_read_error = on_read_error;
2192
    dinfo->on_write_error = on_write_error;
2193
    dinfo->opts = opts;
2194
    if (serial)
2195
        strncpy(dinfo->serial, serial, sizeof(serial));
2196
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2197

    
2198
    switch(type) {
2199
    case IF_IDE:
2200
    case IF_SCSI:
2201
    case IF_XEN:
2202
    case IF_NONE:
2203
        switch(media) {
2204
        case MEDIA_DISK:
2205
            if (cyls != 0) {
2206
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2207
                bdrv_set_translation_hint(dinfo->bdrv, translation);
2208
            }
2209
            break;
2210
        case MEDIA_CDROM:
2211
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2212
            break;
2213
        }
2214
        break;
2215
    case IF_SD:
2216
        /* FIXME: This isn't really a floppy, but it's a reasonable
2217
           approximation.  */
2218
    case IF_FLOPPY:
2219
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2220
        break;
2221
    case IF_PFLASH:
2222
    case IF_MTD:
2223
        break;
2224
    case IF_VIRTIO:
2225
        /* add virtio block device */
2226
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2227
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
2228
        qemu_opt_set(opts, "drive", dinfo->id);
2229
        if (devaddr)
2230
            qemu_opt_set(opts, "addr", devaddr);
2231
        break;
2232
    case IF_COUNT:
2233
        abort();
2234
    }
2235
    if (!file) {
2236
        *fatal_error = 0;
2237
        return NULL;
2238
    }
2239
    bdrv_flags = 0;
2240
    if (snapshot) {
2241
        bdrv_flags |= BDRV_O_SNAPSHOT;
2242
        cache = 2; /* always use write-back with snapshot */
2243
    }
2244
    if (cache == 0) /* no caching */
2245
        bdrv_flags |= BDRV_O_NOCACHE;
2246
    else if (cache == 2) /* write-back */
2247
        bdrv_flags |= BDRV_O_CACHE_WB;
2248

    
2249
    if (aio == 1) {
2250
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2251
    } else {
2252
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2253
    }
2254

    
2255
    if (ro == 1) {
2256
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2257
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2258
            return NULL;
2259
        }
2260
    }
2261
    /* 
2262
     * cdrom is read-only. Set it now, after above interface checking
2263
     * since readonly attribute not explicitly required, so no error.
2264
     */
2265
    if (media == MEDIA_CDROM) {
2266
        ro = 1;
2267
    }
2268
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2269

    
2270
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2271
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2272
                        file, strerror(errno));
2273
        return NULL;
2274
    }
2275

    
2276
    if (bdrv_key_required(dinfo->bdrv))
2277
        autostart = 0;
2278
    *fatal_error = 0;
2279
    return dinfo;
2280
}
2281

    
2282
static int drive_init_func(QemuOpts *opts, void *opaque)
2283
{
2284
    QEMUMachine *machine = opaque;
2285
    int fatal_error = 0;
2286

    
2287
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2288
        if (fatal_error)
2289
            return 1;
2290
    }
2291
    return 0;
2292
}
2293

    
2294
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2295
{
2296
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2297
        qemu_opt_set(opts, "snapshot", "on");
2298
    }
2299
    return 0;
2300
}
2301

    
2302
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2303
{
2304
    boot_set_handler = func;
2305
    boot_set_opaque = opaque;
2306
}
2307

    
2308
int qemu_boot_set(const char *boot_devices)
2309
{
2310
    if (!boot_set_handler) {
2311
        return -EINVAL;
2312
    }
2313
    return boot_set_handler(boot_set_opaque, boot_devices);
2314
}
2315

    
2316
static int parse_bootdevices(char *devices)
2317
{
2318
    /* We just do some generic consistency checks */
2319
    const char *p;
2320
    int bitmap = 0;
2321

    
2322
    for (p = devices; *p != '\0'; p++) {
2323
        /* Allowed boot devices are:
2324
         * a-b: floppy disk drives
2325
         * c-f: IDE disk drives
2326
         * g-m: machine implementation dependant drives
2327
         * n-p: network devices
2328
         * It's up to each machine implementation to check if the given boot
2329
         * devices match the actual hardware implementation and firmware
2330
         * features.
2331
         */
2332
        if (*p < 'a' || *p > 'p') {
2333
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2334
            exit(1);
2335
        }
2336
        if (bitmap & (1 << (*p - 'a'))) {
2337
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2338
            exit(1);
2339
        }
2340
        bitmap |= 1 << (*p - 'a');
2341
    }
2342
    return bitmap;
2343
}
2344

    
2345
static void restore_boot_devices(void *opaque)
2346
{
2347
    char *standard_boot_devices = opaque;
2348

    
2349
    qemu_boot_set(standard_boot_devices);
2350

    
2351
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2352
    qemu_free(standard_boot_devices);
2353
}
2354

    
2355
static void numa_add(const char *optarg)
2356
{
2357
    char option[128];
2358
    char *endptr;
2359
    unsigned long long value, endvalue;
2360
    int nodenr;
2361

    
2362
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2363
    if (!strcmp(option, "node")) {
2364
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2365
            nodenr = nb_numa_nodes;
2366
        } else {
2367
            nodenr = strtoull(option, NULL, 10);
2368
        }
2369

    
2370
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2371
            node_mem[nodenr] = 0;
2372
        } else {
2373
            value = strtoull(option, &endptr, 0);
2374
            switch (*endptr) {
2375
            case 0: case 'M': case 'm':
2376
                value <<= 20;
2377
                break;
2378
            case 'G': case 'g':
2379
                value <<= 30;
2380
                break;
2381
            }
2382
            node_mem[nodenr] = value;
2383
        }
2384
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2385
            node_cpumask[nodenr] = 0;
2386
        } else {
2387
            value = strtoull(option, &endptr, 10);
2388
            if (value >= 64) {
2389
                value = 63;
2390
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2391
            } else {
2392
                if (*endptr == '-') {
2393
                    endvalue = strtoull(endptr+1, &endptr, 10);
2394
                    if (endvalue >= 63) {
2395
                        endvalue = 62;
2396
                        fprintf(stderr,
2397
                            "only 63 CPUs in NUMA mode supported.\n");
2398
                    }
2399
                    value = (2ULL << endvalue) - (1ULL << value);
2400
                } else {
2401
                    value = 1ULL << value;
2402
                }
2403
            }
2404
            node_cpumask[nodenr] = value;
2405
        }
2406
        nb_numa_nodes++;
2407
    }
2408
    return;
2409
}
2410

    
2411
static void smp_parse(const char *optarg)
2412
{
2413
    int smp, sockets = 0, threads = 0, cores = 0;
2414
    char *endptr;
2415
    char option[128];
2416

    
2417
    smp = strtoul(optarg, &endptr, 10);
2418
    if (endptr != optarg) {
2419
        if (*endptr == ',') {
2420
            endptr++;
2421
        }
2422
    }
2423
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2424
        sockets = strtoull(option, NULL, 10);
2425
    if (get_param_value(option, 128, "cores", endptr) != 0)
2426
        cores = strtoull(option, NULL, 10);
2427
    if (get_param_value(option, 128, "threads", endptr) != 0)
2428
        threads = strtoull(option, NULL, 10);
2429
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2430
        max_cpus = strtoull(option, NULL, 10);
2431

    
2432
    /* compute missing values, prefer sockets over cores over threads */
2433
    if (smp == 0 || sockets == 0) {
2434
        sockets = sockets > 0 ? sockets : 1;
2435
        cores = cores > 0 ? cores : 1;
2436
        threads = threads > 0 ? threads : 1;
2437
        if (smp == 0) {
2438
            smp = cores * threads * sockets;
2439
        }
2440
    } else {
2441
        if (cores == 0) {
2442
            threads = threads > 0 ? threads : 1;
2443
            cores = smp / (sockets * threads);
2444
        } else {
2445
            if (sockets) {
2446
                threads = smp / (cores * sockets);
2447
            }
2448
        }
2449
    }
2450
    smp_cpus = smp;
2451
    smp_cores = cores > 0 ? cores : 1;
2452
    smp_threads = threads > 0 ? threads : 1;
2453
    if (max_cpus == 0)
2454
        max_cpus = smp_cpus;
2455
}
2456

    
2457
/***********************************************************/
2458
/* USB devices */
2459

    
2460
static int usb_device_add(const char *devname, int is_hotplug)
2461
{
2462
    const char *p;
2463
    USBDevice *dev = NULL;
2464

    
2465
    if (!usb_enabled)
2466
        return -1;
2467

    
2468
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2469
    dev = usbdevice_create(devname);
2470
    if (dev)
2471
        goto done;
2472

    
2473
    /* the other ones */
2474
    if (strstart(devname, "host:", &p)) {
2475
        dev = usb_host_device_open(p);
2476
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2477
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2478
                        bt_new_hci(qemu_find_bt_vlan(0)));
2479
    } else {
2480
        return -1;
2481
    }
2482
    if (!dev)
2483
        return -1;
2484

    
2485
done:
2486
    return 0;
2487
}
2488

    
2489
static int usb_device_del(const char *devname)
2490
{
2491
    int bus_num, addr;
2492
    const char *p;
2493

    
2494
    if (strstart(devname, "host:", &p))
2495
        return usb_host_device_close(p);
2496

    
2497
    if (!usb_enabled)
2498
        return -1;
2499

    
2500
    p = strchr(devname, '.');
2501
    if (!p)
2502
        return -1;
2503
    bus_num = strtoul(devname, NULL, 0);
2504
    addr = strtoul(p + 1, NULL, 0);
2505

    
2506
    return usb_device_delete_addr(bus_num, addr);
2507
}
2508

    
2509
static int usb_parse(const char *cmdline)
2510
{
2511
    int r;
2512
    r = usb_device_add(cmdline, 0);
2513
    if (r < 0) {
2514
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2515
    }
2516
    return r;
2517
}
2518

    
2519
void do_usb_add(Monitor *mon, const QDict *qdict)
2520
{
2521
    const char *devname = qdict_get_str(qdict, "devname");
2522
    if (usb_device_add(devname, 1) < 0) {
2523
        qemu_error("could not add USB device '%s'\n", devname);
2524
    }
2525
}
2526

    
2527
void do_usb_del(Monitor *mon, const QDict *qdict)
2528
{
2529
    const char *devname = qdict_get_str(qdict, "devname");
2530
    if (usb_device_del(devname) < 0) {
2531
        qemu_error("could not delete USB device '%s'\n", devname);
2532
    }
2533
}
2534

    
2535
/***********************************************************/
2536
/* PCMCIA/Cardbus */
2537

    
2538
static struct pcmcia_socket_entry_s {
2539
    PCMCIASocket *socket;
2540
    struct pcmcia_socket_entry_s *next;
2541
} *pcmcia_sockets = 0;
2542

    
2543
void pcmcia_socket_register(PCMCIASocket *socket)
2544
{
2545
    struct pcmcia_socket_entry_s *entry;
2546

    
2547
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2548
    entry->socket = socket;
2549
    entry->next = pcmcia_sockets;
2550
    pcmcia_sockets = entry;
2551
}
2552

    
2553
void pcmcia_socket_unregister(PCMCIASocket *socket)
2554
{
2555
    struct pcmcia_socket_entry_s *entry, **ptr;
2556

    
2557
    ptr = &pcmcia_sockets;
2558
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2559
        if (entry->socket == socket) {
2560
            *ptr = entry->next;
2561
            qemu_free(entry);
2562
        }
2563
}
2564

    
2565
void pcmcia_info(Monitor *mon)
2566
{
2567
    struct pcmcia_socket_entry_s *iter;
2568

    
2569
    if (!pcmcia_sockets)
2570
        monitor_printf(mon, "No PCMCIA sockets\n");
2571

    
2572
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2573
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2574
                       iter->socket->attached ? iter->socket->card_string :
2575
                       "Empty");
2576
}
2577

    
2578
/***********************************************************/
2579
/* I/O handling */
2580

    
2581
typedef struct IOHandlerRecord {
2582
    int fd;
2583
    IOCanRWHandler *fd_read_poll;
2584
    IOHandler *fd_read;
2585
    IOHandler *fd_write;
2586
    int deleted;
2587
    void *opaque;
2588
    /* temporary data */
2589
    struct pollfd *ufd;
2590
    struct IOHandlerRecord *next;
2591
} IOHandlerRecord;
2592

    
2593
static IOHandlerRecord *first_io_handler;
2594

    
2595
/* XXX: fd_read_poll should be suppressed, but an API change is
2596
   necessary in the character devices to suppress fd_can_read(). */
2597
int qemu_set_fd_handler2(int fd,
2598
                         IOCanRWHandler *fd_read_poll,
2599
                         IOHandler *fd_read,
2600
                         IOHandler *fd_write,
2601
                         void *opaque)
2602
{
2603
    IOHandlerRecord **pioh, *ioh;
2604

    
2605
    if (!fd_read && !fd_write) {
2606
        pioh = &first_io_handler;
2607
        for(;;) {
2608
            ioh = *pioh;
2609
            if (ioh == NULL)
2610
                break;
2611
            if (ioh->fd == fd) {
2612
                ioh->deleted = 1;
2613
                break;
2614
            }
2615
            pioh = &ioh->next;
2616
        }
2617
    } else {
2618
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2619
            if (ioh->fd == fd)
2620
                goto found;
2621
        }
2622
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2623
        ioh->next = first_io_handler;
2624
        first_io_handler = ioh;
2625
    found:
2626
        ioh->fd = fd;
2627
        ioh->fd_read_poll = fd_read_poll;
2628
        ioh->fd_read = fd_read;
2629
        ioh->fd_write = fd_write;
2630
        ioh->opaque = opaque;
2631
        ioh->deleted = 0;
2632
    }
2633
    return 0;
2634
}
2635

    
2636
int qemu_set_fd_handler(int fd,
2637
                        IOHandler *fd_read,
2638
                        IOHandler *fd_write,
2639
                        void *opaque)
2640
{
2641
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2642
}
2643

    
2644
#ifdef _WIN32
2645
/***********************************************************/
2646
/* Polling handling */
2647

    
2648
typedef struct PollingEntry {
2649
    PollingFunc *func;
2650
    void *opaque;
2651
    struct PollingEntry *next;
2652
} PollingEntry;
2653

    
2654
static PollingEntry *first_polling_entry;
2655

    
2656
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2657
{
2658
    PollingEntry **ppe, *pe;
2659
    pe = qemu_mallocz(sizeof(PollingEntry));
2660
    pe->func = func;
2661
    pe->opaque = opaque;
2662
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2663
    *ppe = pe;
2664
    return 0;
2665
}
2666

    
2667
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2668
{
2669
    PollingEntry **ppe, *pe;
2670
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2671
        pe = *ppe;
2672
        if (pe->func == func && pe->opaque == opaque) {
2673
            *ppe = pe->next;
2674
            qemu_free(pe);
2675
            break;
2676
        }
2677
    }
2678
}
2679

    
2680
/***********************************************************/
2681
/* Wait objects support */
2682
typedef struct WaitObjects {
2683
    int num;
2684
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2685
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2686
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2687
} WaitObjects;
2688

    
2689
static WaitObjects wait_objects = {0};
2690

    
2691
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2692
{
2693
    WaitObjects *w = &wait_objects;
2694

    
2695
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2696
        return -1;
2697
    w->events[w->num] = handle;
2698
    w->func[w->num] = func;
2699
    w->opaque[w->num] = opaque;
2700
    w->num++;
2701
    return 0;
2702
}
2703

    
2704
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2705
{
2706
    int i, found;
2707
    WaitObjects *w = &wait_objects;
2708

    
2709
    found = 0;
2710
    for (i = 0; i < w->num; i++) {
2711
        if (w->events[i] == handle)
2712
            found = 1;
2713
        if (found) {
2714
            w->events[i] = w->events[i + 1];
2715
            w->func[i] = w->func[i + 1];
2716
            w->opaque[i] = w->opaque[i + 1];
2717
        }
2718
    }
2719
    if (found)
2720
        w->num--;
2721
}
2722
#endif
2723

    
2724
/***********************************************************/
2725
/* ram save/restore */
2726

    
2727
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2728
#define RAM_SAVE_FLAG_COMPRESS        0x02
2729
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2730
#define RAM_SAVE_FLAG_PAGE        0x08
2731
#define RAM_SAVE_FLAG_EOS        0x10
2732

    
2733
static int is_dup_page(uint8_t *page, uint8_t ch)
2734
{
2735
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2736
    uint32_t *array = (uint32_t *)page;
2737
    int i;
2738

    
2739
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2740
        if (array[i] != val)
2741
            return 0;
2742
    }
2743

    
2744
    return 1;
2745
}
2746

    
2747
static int ram_save_block(QEMUFile *f)
2748
{
2749
    static ram_addr_t current_addr = 0;
2750
    ram_addr_t saved_addr = current_addr;
2751
    ram_addr_t addr = 0;
2752
    int found = 0;
2753

    
2754
    while (addr < last_ram_offset) {
2755
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2756
            uint8_t *p;
2757

    
2758
            cpu_physical_memory_reset_dirty(current_addr,
2759
                                            current_addr + TARGET_PAGE_SIZE,
2760
                                            MIGRATION_DIRTY_FLAG);
2761

    
2762
            p = qemu_get_ram_ptr(current_addr);
2763

    
2764
            if (is_dup_page(p, *p)) {
2765
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2766
                qemu_put_byte(f, *p);
2767
            } else {
2768
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2769
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2770
            }
2771

    
2772
            found = 1;
2773
            break;
2774
        }
2775
        addr += TARGET_PAGE_SIZE;
2776
        current_addr = (saved_addr + addr) % last_ram_offset;
2777
    }
2778

    
2779
    return found;
2780
}
2781

    
2782
static uint64_t bytes_transferred;
2783

    
2784
static ram_addr_t ram_save_remaining(void)
2785
{
2786
    ram_addr_t addr;
2787
    ram_addr_t count = 0;
2788

    
2789
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2790
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2791
            count++;
2792
    }
2793

    
2794
    return count;
2795
}
2796

    
2797
uint64_t ram_bytes_remaining(void)
2798
{
2799
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2800
}
2801

    
2802
uint64_t ram_bytes_transferred(void)
2803
{
2804
    return bytes_transferred;
2805
}
2806

    
2807
uint64_t ram_bytes_total(void)
2808
{
2809
    return last_ram_offset;
2810
}
2811

    
2812
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2813
{
2814
    ram_addr_t addr;
2815
    uint64_t bytes_transferred_last;
2816
    double bwidth = 0;
2817
    uint64_t expected_time = 0;
2818

    
2819
    if (stage < 0) {
2820
        cpu_physical_memory_set_dirty_tracking(0);
2821
        return 0;
2822
    }
2823

    
2824
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2825
        qemu_file_set_error(f);
2826
        return 0;
2827
    }
2828

    
2829
    if (stage == 1) {
2830
        bytes_transferred = 0;
2831

    
2832
        /* Make sure all dirty bits are set */
2833
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2834
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2835
                cpu_physical_memory_set_dirty(addr);
2836
        }
2837

    
2838
        /* Enable dirty memory tracking */
2839
        cpu_physical_memory_set_dirty_tracking(1);
2840

    
2841
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2842
    }
2843

    
2844
    bytes_transferred_last = bytes_transferred;
2845
    bwidth = qemu_get_clock_ns(rt_clock);
2846

    
2847
    while (!qemu_file_rate_limit(f)) {
2848
        int ret;
2849

    
2850
        ret = ram_save_block(f);
2851
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2852
        if (ret == 0) /* no more blocks */
2853
            break;
2854
    }
2855

    
2856
    bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2857
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2858

    
2859
    /* if we haven't transferred anything this round, force expected_time to a
2860
     * a very high value, but without crashing */
2861
    if (bwidth == 0)
2862
        bwidth = 0.000001;
2863

    
2864
    /* try transferring iterative blocks of memory */
2865
    if (stage == 3) {
2866
        /* flush all remaining blocks regardless of rate limiting */
2867
        while (ram_save_block(f) != 0) {
2868
            bytes_transferred += TARGET_PAGE_SIZE;
2869
        }
2870
        cpu_physical_memory_set_dirty_tracking(0);
2871
    }
2872

    
2873
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2874

    
2875
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2876

    
2877
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2878
}
2879

    
2880
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2881
{
2882
    ram_addr_t addr;
2883
    int flags;
2884

    
2885
    if (version_id != 3)
2886
        return -EINVAL;
2887

    
2888
    do {
2889
        addr = qemu_get_be64(f);
2890

    
2891
        flags = addr & ~TARGET_PAGE_MASK;
2892
        addr &= TARGET_PAGE_MASK;
2893

    
2894
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2895
            if (addr != last_ram_offset)
2896
                return -EINVAL;
2897
        }
2898

    
2899
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
2900
            uint8_t ch = qemu_get_byte(f);
2901
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2902
#ifndef _WIN32
2903
            if (ch == 0 &&
2904
                (!kvm_enabled() || kvm_has_sync_mmu())) {
2905
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2906
            }
2907
#endif
2908
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
2909
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2910
        }
2911
        if (qemu_file_has_error(f)) {
2912
            return -EIO;
2913
        }
2914
    } while (!(flags & RAM_SAVE_FLAG_EOS));
2915

    
2916
    return 0;
2917
}
2918

    
2919
void qemu_service_io(void)
2920
{
2921
    qemu_notify_event();
2922
}
2923

    
2924
/***********************************************************/
2925
/* machine registration */
2926

    
2927
static QEMUMachine *first_machine = NULL;
2928
QEMUMachine *current_machine = NULL;
2929

    
2930
int qemu_register_machine(QEMUMachine *m)
2931
{
2932
    QEMUMachine **pm;
2933
    pm = &first_machine;
2934
    while (*pm != NULL)
2935
        pm = &(*pm)->next;
2936
    m->next = NULL;
2937
    *pm = m;
2938
    return 0;
2939
}
2940

    
2941
static QEMUMachine *find_machine(const char *name)
2942
{
2943
    QEMUMachine *m;
2944

    
2945
    for(m = first_machine; m != NULL; m = m->next) {
2946
        if (!strcmp(m->name, name))
2947
            return m;
2948
        if (m->alias && !strcmp(m->alias, name))
2949
            return m;
2950
    }
2951
    return NULL;
2952
}
2953

    
2954
static QEMUMachine *find_default_machine(void)
2955
{
2956
    QEMUMachine *m;
2957

    
2958
    for(m = first_machine; m != NULL; m = m->next) {
2959
        if (m->is_default) {
2960
            return m;
2961
        }
2962
    }
2963
    return NULL;
2964
}
2965

    
2966
/***********************************************************/
2967
/* main execution loop */
2968

    
2969
static void gui_update(void *opaque)
2970
{
2971
    uint64_t interval = GUI_REFRESH_INTERVAL;
2972
    DisplayState *ds = opaque;
2973
    DisplayChangeListener *dcl = ds->listeners;
2974

    
2975
    qemu_flush_coalesced_mmio_buffer();
2976
    dpy_refresh(ds);
2977

    
2978
    while (dcl != NULL) {
2979
        if (dcl->gui_timer_interval &&
2980
            dcl->gui_timer_interval < interval)
2981
            interval = dcl->gui_timer_interval;
2982
        dcl = dcl->next;
2983
    }
2984
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
2985
}
2986

    
2987
static void nographic_update(void *opaque)
2988
{
2989
    uint64_t interval = GUI_REFRESH_INTERVAL;
2990

    
2991
    qemu_flush_coalesced_mmio_buffer();
2992
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
2993
}
2994

    
2995
struct vm_change_state_entry {
2996
    VMChangeStateHandler *cb;
2997
    void *opaque;
2998
    QLIST_ENTRY (vm_change_state_entry) entries;
2999
};
3000

    
3001
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3002

    
3003
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3004
                                                     void *opaque)
3005
{
3006
    VMChangeStateEntry *e;
3007

    
3008
    e = qemu_mallocz(sizeof (*e));
3009

    
3010
    e->cb = cb;
3011
    e->opaque = opaque;
3012
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3013
    return e;
3014
}
3015

    
3016
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3017
{
3018
    QLIST_REMOVE (e, entries);
3019
    qemu_free (e);
3020
}
3021

    
3022
static void vm_state_notify(int running, int reason)
3023
{
3024
    VMChangeStateEntry *e;
3025

    
3026
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3027
        e->cb(e->opaque, running, reason);
3028
    }
3029
}
3030

    
3031
static void resume_all_vcpus(void);
3032
static void pause_all_vcpus(void);
3033

    
3034
void vm_start(void)
3035
{
3036
    if (!vm_running) {
3037
        cpu_enable_ticks();
3038
        vm_running = 1;
3039
        vm_state_notify(1, 0);
3040
        qemu_rearm_alarm_timer(alarm_timer);
3041
        resume_all_vcpus();
3042
    }
3043
}
3044

    
3045
/* reset/shutdown handler */
3046

    
3047
typedef struct QEMUResetEntry {
3048
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3049
    QEMUResetHandler *func;
3050
    void *opaque;
3051
} QEMUResetEntry;
3052

    
3053
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3054
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3055
static int reset_requested;
3056
static int shutdown_requested;
3057
static int powerdown_requested;
3058
static int debug_requested;
3059
static int vmstop_requested;
3060

    
3061
int qemu_shutdown_requested(void)
3062
{
3063
    int r = shutdown_requested;
3064
    shutdown_requested = 0;
3065
    return r;
3066
}
3067

    
3068
int qemu_reset_requested(void)
3069
{
3070
    int r = reset_requested;
3071
    reset_requested = 0;
3072
    return r;
3073
}
3074

    
3075
int qemu_powerdown_requested(void)
3076
{
3077
    int r = powerdown_requested;
3078
    powerdown_requested = 0;
3079
    return r;
3080
}
3081

    
3082
static int qemu_debug_requested(void)
3083
{
3084
    int r = debug_requested;
3085
    debug_requested = 0;
3086
    return r;
3087
}
3088

    
3089
static int qemu_vmstop_requested(void)
3090
{
3091
    int r = vmstop_requested;
3092
    vmstop_requested = 0;
3093
    return r;
3094
}
3095

    
3096
static void do_vm_stop(int reason)
3097
{
3098
    if (vm_running) {
3099
        cpu_disable_ticks();
3100
        vm_running = 0;
3101
        pause_all_vcpus();
3102
        vm_state_notify(0, reason);
3103
    }
3104
}
3105

    
3106
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3107
{
3108
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3109

    
3110
    re->func = func;
3111
    re->opaque = opaque;
3112
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3113
}
3114

    
3115
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3116
{
3117
    QEMUResetEntry *re;
3118

    
3119
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3120
        if (re->func == func && re->opaque == opaque) {
3121
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3122
            qemu_free(re);
3123
            return;
3124
        }
3125
    }
3126
}
3127

    
3128
void qemu_system_reset(void)
3129
{
3130
    QEMUResetEntry *re, *nre;
3131

    
3132
    /* reset all devices */
3133
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3134
        re->func(re->opaque);
3135
    }
3136
}
3137

    
3138
void qemu_system_reset_request(void)
3139
{
3140
    if (no_reboot) {
3141
        shutdown_requested = 1;
3142
    } else {
3143
        reset_requested = 1;
3144
    }
3145
    qemu_notify_event();
3146
}
3147

    
3148
void qemu_system_shutdown_request(void)
3149
{
3150
    shutdown_requested = 1;
3151
    qemu_notify_event();
3152
}
3153

    
3154
void qemu_system_powerdown_request(void)
3155
{
3156
    powerdown_requested = 1;
3157
    qemu_notify_event();
3158
}
3159

    
3160
#ifdef CONFIG_IOTHREAD
3161
static void qemu_system_vmstop_request(int reason)
3162
{
3163
    vmstop_requested = reason;
3164
    qemu_notify_event();
3165
}
3166
#endif
3167

    
3168
#ifndef _WIN32
3169
static int io_thread_fd = -1;
3170

    
3171
static void qemu_event_increment(void)
3172
{
3173
    static const char byte = 0;
3174
    ssize_t ret;
3175

    
3176
    if (io_thread_fd == -1)
3177
        return;
3178

    
3179
    do {
3180
        ret = write(io_thread_fd, &byte, sizeof(byte));
3181
    } while (ret < 0 && errno == EINTR);
3182

    
3183
    /* EAGAIN is fine, a read must be pending.  */
3184
    if (ret < 0 && errno != EAGAIN) {
3185
        fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3186
                strerror(errno));
3187
        exit (1);
3188
    }
3189
}
3190

    
3191
static void qemu_event_read(void *opaque)
3192
{
3193
    int fd = (unsigned long)opaque;
3194
    ssize_t len;
3195
    char buffer[512];
3196

    
3197
    /* Drain the notify pipe */
3198
    do {
3199
        len = read(fd, buffer, sizeof(buffer));
3200
    } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3201
}
3202

    
3203
static int qemu_event_init(void)
3204
{
3205
    int err;
3206
    int fds[2];
3207

    
3208
    err = qemu_pipe(fds);
3209
    if (err == -1)
3210
        return -errno;
3211

    
3212
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3213
    if (err < 0)
3214
        goto fail;
3215

    
3216
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3217
    if (err < 0)
3218
        goto fail;
3219

    
3220
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3221
                         (void *)(unsigned long)fds[0]);
3222

    
3223
    io_thread_fd = fds[1];
3224
    return 0;
3225

    
3226
fail:
3227
    close(fds[0]);
3228
    close(fds[1]);
3229
    return err;
3230
}
3231
#else
3232
HANDLE qemu_event_handle;
3233

    
3234
static void dummy_event_handler(void *opaque)
3235
{
3236
}
3237

    
3238
static int qemu_event_init(void)
3239
{
3240
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3241
    if (!qemu_event_handle) {
3242
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3243
        return -1;
3244
    }
3245
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3246
    return 0;
3247
}
3248

    
3249
static void qemu_event_increment(void)
3250
{
3251
    if (!SetEvent(qemu_event_handle)) {
3252
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3253
                GetLastError());
3254
        exit (1);
3255
    }
3256
}
3257
#endif
3258

    
3259
static int cpu_can_run(CPUState *env)
3260
{
3261
    if (env->stop)
3262
        return 0;
3263
    if (env->stopped)
3264
        return 0;
3265
    if (!vm_running)
3266
        return 0;
3267
    return 1;
3268
}
3269

    
3270
#ifndef CONFIG_IOTHREAD
3271
static int qemu_init_main_loop(void)
3272
{
3273
    return qemu_event_init();
3274
}
3275

    
3276
void qemu_init_vcpu(void *_env)
3277
{
3278
    CPUState *env = _env;
3279

    
3280
    env->nr_cores = smp_cores;
3281
    env->nr_threads = smp_threads;
3282
    if (kvm_enabled())
3283
        kvm_init_vcpu(env);
3284
    return;
3285
}
3286

    
3287
int qemu_cpu_self(void *env)
3288
{
3289
    return 1;
3290
}
3291

    
3292
static void resume_all_vcpus(void)
3293
{
3294
}
3295

    
3296
static void pause_all_vcpus(void)
3297
{
3298
}
3299

    
3300
void qemu_cpu_kick(void *env)
3301
{
3302
    return;
3303
}
3304

    
3305
void qemu_notify_event(void)
3306
{
3307
    CPUState *env = cpu_single_env;
3308

    
3309
    if (env) {
3310
        cpu_exit(env);
3311
    }
3312
}
3313

    
3314
void qemu_mutex_lock_iothread(void) {}
3315
void qemu_mutex_unlock_iothread(void) {}
3316

    
3317
void vm_stop(int reason)
3318
{
3319
    do_vm_stop(reason);
3320
}
3321

    
3322
#else /* CONFIG_IOTHREAD */
3323

    
3324
#include "qemu-thread.h"
3325

    
3326
QemuMutex qemu_global_mutex;
3327
static QemuMutex qemu_fair_mutex;
3328

    
3329
static QemuThread io_thread;
3330

    
3331
static QemuThread *tcg_cpu_thread;
3332
static QemuCond *tcg_halt_cond;
3333

    
3334
static int qemu_system_ready;
3335
/* cpu creation */
3336
static QemuCond qemu_cpu_cond;
3337
/* system init */
3338
static QemuCond qemu_system_cond;
3339
static QemuCond qemu_pause_cond;
3340

    
3341
static void block_io_signals(void);
3342
static void unblock_io_signals(void);
3343
static int tcg_has_work(void);
3344

    
3345
static int qemu_init_main_loop(void)
3346
{
3347
    int ret;
3348

    
3349
    ret = qemu_event_init();
3350
    if (ret)
3351
        return ret;
3352

    
3353
    qemu_cond_init(&qemu_pause_cond);
3354
    qemu_mutex_init(&qemu_fair_mutex);
3355
    qemu_mutex_init(&qemu_global_mutex);
3356
    qemu_mutex_lock(&qemu_global_mutex);
3357

    
3358
    unblock_io_signals();
3359
    qemu_thread_self(&io_thread);
3360

    
3361
    return 0;
3362
}
3363

    
3364
static void qemu_wait_io_event(CPUState *env)
3365
{
3366
    while (!tcg_has_work())
3367
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3368

    
3369
    qemu_mutex_unlock(&qemu_global_mutex);
3370

    
3371
    /*
3372
     * Users of qemu_global_mutex can be starved, having no chance
3373
     * to acquire it since this path will get to it first.
3374
     * So use another lock to provide fairness.
3375
     */
3376
    qemu_mutex_lock(&qemu_fair_mutex);
3377
    qemu_mutex_unlock(&qemu_fair_mutex);
3378

    
3379
    qemu_mutex_lock(&qemu_global_mutex);
3380
    if (env->stop) {
3381
        env->stop = 0;
3382
        env->stopped = 1;
3383
        qemu_cond_signal(&qemu_pause_cond);
3384
    }
3385
}
3386

    
3387
static int qemu_cpu_exec(CPUState *env);
3388

    
3389
static void *kvm_cpu_thread_fn(void *arg)
3390
{
3391
    CPUState *env = arg;
3392

    
3393
    block_io_signals();
3394
    qemu_thread_self(env->thread);
3395
    if (kvm_enabled())
3396
        kvm_init_vcpu(env);
3397

    
3398
    /* signal CPU creation */
3399
    qemu_mutex_lock(&qemu_global_mutex);
3400
    env->created = 1;
3401
    qemu_cond_signal(&qemu_cpu_cond);
3402

    
3403
    /* and wait for machine initialization */
3404
    while (!qemu_system_ready)
3405
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3406

    
3407
    while (1) {
3408
        if (cpu_can_run(env))
3409
            qemu_cpu_exec(env);
3410
        qemu_wait_io_event(env);
3411
    }
3412

    
3413
    return NULL;
3414
}
3415

    
3416
static void tcg_cpu_exec(void);
3417

    
3418
static void *tcg_cpu_thread_fn(void *arg)
3419
{
3420
    CPUState *env = arg;
3421

    
3422
    block_io_signals();
3423
    qemu_thread_self(env->thread);
3424

    
3425
    /* signal CPU creation */
3426
    qemu_mutex_lock(&qemu_global_mutex);
3427
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3428
        env->created = 1;
3429
    qemu_cond_signal(&qemu_cpu_cond);
3430

    
3431
    /* and wait for machine initialization */
3432
    while (!qemu_system_ready)
3433
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3434

    
3435
    while (1) {
3436
        tcg_cpu_exec();
3437
        qemu_wait_io_event(cur_cpu);
3438
    }
3439

    
3440
    return NULL;
3441
}
3442

    
3443
void qemu_cpu_kick(void *_env)
3444
{
3445
    CPUState *env = _env;
3446
    qemu_cond_broadcast(env->halt_cond);
3447
    if (kvm_enabled())
3448
        qemu_thread_signal(env->thread, SIGUSR1);
3449
}
3450

    
3451
int qemu_cpu_self(void *_env)
3452
{
3453
    CPUState *env = _env;
3454
    QemuThread this;
3455
 
3456
    qemu_thread_self(&this);
3457
 
3458
    return qemu_thread_equal(&this, env->thread);
3459
}
3460

    
3461
static void cpu_signal(int sig)
3462
{
3463
    if (cpu_single_env)
3464
        cpu_exit(cpu_single_env);
3465
}
3466

    
3467
static void block_io_signals(void)
3468
{
3469
    sigset_t set;
3470
    struct sigaction sigact;
3471

    
3472
    sigemptyset(&set);
3473
    sigaddset(&set, SIGUSR2);
3474
    sigaddset(&set, SIGIO);
3475
    sigaddset(&set, SIGALRM);
3476
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3477

    
3478
    sigemptyset(&set);
3479
    sigaddset(&set, SIGUSR1);
3480
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3481

    
3482
    memset(&sigact, 0, sizeof(sigact));
3483
    sigact.sa_handler = cpu_signal;
3484
    sigaction(SIGUSR1, &sigact, NULL);
3485
}
3486

    
3487
static void unblock_io_signals(void)
3488
{
3489
    sigset_t set;
3490

    
3491
    sigemptyset(&set);
3492
    sigaddset(&set, SIGUSR2);
3493
    sigaddset(&set, SIGIO);
3494
    sigaddset(&set, SIGALRM);
3495
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3496

    
3497
    sigemptyset(&set);
3498
    sigaddset(&set, SIGUSR1);
3499
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3500
}
3501

    
3502
static void qemu_signal_lock(unsigned int msecs)
3503
{
3504
    qemu_mutex_lock(&qemu_fair_mutex);
3505

    
3506
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3507
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3508
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3509
            break;
3510
    }
3511
    qemu_mutex_unlock(&qemu_fair_mutex);
3512
}
3513

    
3514
void qemu_mutex_lock_iothread(void)
3515
{
3516
    if (kvm_enabled()) {
3517
        qemu_mutex_lock(&qemu_fair_mutex);
3518
        qemu_mutex_lock(&qemu_global_mutex);
3519
        qemu_mutex_unlock(&qemu_fair_mutex);
3520
    } else
3521
        qemu_signal_lock(100);
3522
}
3523

    
3524
void qemu_mutex_unlock_iothread(void)
3525
{
3526
    qemu_mutex_unlock(&qemu_global_mutex);
3527
}
3528

    
3529
static int all_vcpus_paused(void)
3530
{
3531
    CPUState *penv = first_cpu;
3532

    
3533
    while (penv) {
3534
        if (!penv->stopped)
3535
            return 0;
3536
        penv = (CPUState *)penv->next_cpu;
3537
    }
3538

    
3539
    return 1;
3540
}
3541

    
3542
static void pause_all_vcpus(void)
3543
{
3544
    CPUState *penv = first_cpu;
3545

    
3546
    while (penv) {
3547
        penv->stop = 1;
3548
        qemu_thread_signal(penv->thread, SIGUSR1);
3549
        qemu_cpu_kick(penv);
3550
        penv = (CPUState *)penv->next_cpu;
3551
    }
3552

    
3553
    while (!all_vcpus_paused()) {
3554
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3555
        penv = first_cpu;
3556
        while (penv) {
3557
            qemu_thread_signal(penv->thread, SIGUSR1);
3558
            penv = (CPUState *)penv->next_cpu;
3559
        }
3560
    }
3561
}
3562

    
3563
static void resume_all_vcpus(void)
3564
{
3565
    CPUState *penv = first_cpu;
3566

    
3567
    while (penv) {
3568
        penv->stop = 0;
3569
        penv->stopped = 0;
3570
        qemu_thread_signal(penv->thread, SIGUSR1);
3571
        qemu_cpu_kick(penv);
3572
        penv = (CPUState *)penv->next_cpu;
3573
    }
3574
}
3575

    
3576
static void tcg_init_vcpu(void *_env)
3577
{
3578
    CPUState *env = _env;
3579
    /* share a single thread for all cpus with TCG */
3580
    if (!tcg_cpu_thread) {
3581
        env->thread = qemu_mallocz(sizeof(QemuThread));
3582
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3583
        qemu_cond_init(env->halt_cond);
3584
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3585
        while (env->created == 0)
3586
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3587
        tcg_cpu_thread = env->thread;
3588
        tcg_halt_cond = env->halt_cond;
3589
    } else {
3590
        env->thread = tcg_cpu_thread;
3591
        env->halt_cond = tcg_halt_cond;
3592
    }
3593
}
3594

    
3595
static void kvm_start_vcpu(CPUState *env)
3596
{
3597
    env->thread = qemu_mallocz(sizeof(QemuThread));
3598
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3599
    qemu_cond_init(env->halt_cond);
3600
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3601
    while (env->created == 0)
3602
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3603
}
3604

    
3605
void qemu_init_vcpu(void *_env)
3606
{
3607
    CPUState *env = _env;
3608

    
3609
    env->nr_cores = smp_cores;
3610
    env->nr_threads = smp_threads;
3611
    if (kvm_enabled())
3612
        kvm_start_vcpu(env);
3613
    else
3614
        tcg_init_vcpu(env);
3615
}
3616

    
3617
void qemu_notify_event(void)
3618
{
3619
    qemu_event_increment();
3620
}
3621

    
3622
void vm_stop(int reason)
3623
{
3624
    QemuThread me;
3625
    qemu_thread_self(&me);
3626

    
3627
    if (!qemu_thread_equal(&me, &io_thread)) {
3628
        qemu_system_vmstop_request(reason);
3629
        /*
3630
         * FIXME: should not return to device code in case
3631
         * vm_stop() has been requested.
3632
         */
3633
        if (cpu_single_env) {
3634
            cpu_exit(cpu_single_env);
3635
            cpu_single_env->stop = 1;
3636
        }
3637
        return;
3638
    }
3639
    do_vm_stop(reason);
3640
}
3641

    
3642
#endif
3643

    
3644

    
3645
#ifdef _WIN32
3646
static void host_main_loop_wait(int *timeout)
3647
{
3648
    int ret, ret2, i;
3649
    PollingEntry *pe;
3650

    
3651

    
3652
    /* XXX: need to suppress polling by better using win32 events */
3653
    ret = 0;
3654
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3655
        ret |= pe->func(pe->opaque);
3656
    }
3657
    if (ret == 0) {
3658
        int err;
3659
        WaitObjects *w = &wait_objects;
3660

    
3661
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3662
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3663
            if (w->func[ret - WAIT_OBJECT_0])
3664
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3665

    
3666
            /* Check for additional signaled events */
3667
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3668

    
3669
                /* Check if event is signaled */
3670
                ret2 = WaitForSingleObject(w->events[i], 0);
3671
                if(ret2 == WAIT_OBJECT_0) {
3672
                    if (w->func[i])
3673
                        w->func[i](w->opaque[i]);
3674
                } else if (ret2 == WAIT_TIMEOUT) {
3675
                } else {
3676
                    err = GetLastError();
3677
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3678
                }
3679
            }
3680
        } else if (ret == WAIT_TIMEOUT) {
3681
        } else {
3682
            err = GetLastError();
3683
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3684
        }
3685
    }
3686

    
3687
    *timeout = 0;
3688
}
3689
#else
3690
static void host_main_loop_wait(int *timeout)
3691
{
3692
}
3693
#endif
3694

    
3695
void main_loop_wait(int timeout)
3696
{
3697
    IOHandlerRecord *ioh;
3698
    fd_set rfds, wfds, xfds;
3699
    int ret, nfds;
3700
    struct timeval tv;
3701

    
3702
    qemu_bh_update_timeout(&timeout);
3703

    
3704
    host_main_loop_wait(&timeout);
3705

    
3706
    /* poll any events */
3707
    /* XXX: separate device handlers from system ones */
3708
    nfds = -1;
3709
    FD_ZERO(&rfds);
3710
    FD_ZERO(&wfds);
3711
    FD_ZERO(&xfds);
3712
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3713
        if (ioh->deleted)
3714
            continue;
3715
        if (ioh->fd_read &&
3716
            (!ioh->fd_read_poll ||
3717
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3718
            FD_SET(ioh->fd, &rfds);
3719
            if (ioh->fd > nfds)
3720
                nfds = ioh->fd;
3721
        }
3722
        if (ioh->fd_write) {
3723
            FD_SET(ioh->fd, &wfds);
3724
            if (ioh->fd > nfds)
3725
                nfds = ioh->fd;
3726
        }
3727
    }
3728

    
3729
    tv.tv_sec = timeout / 1000;
3730
    tv.tv_usec = (timeout % 1000) * 1000;
3731

    
3732
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3733

    
3734
    qemu_mutex_unlock_iothread();
3735
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3736
    qemu_mutex_lock_iothread();
3737
    if (ret > 0) {
3738
        IOHandlerRecord **pioh;
3739

    
3740
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3741
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3742
                ioh->fd_read(ioh->opaque);
3743
            }
3744
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3745
                ioh->fd_write(ioh->opaque);
3746
            }
3747
        }
3748

    
3749
        /* remove deleted IO handlers */
3750
        pioh = &first_io_handler;
3751
        while (*pioh) {
3752
            ioh = *pioh;
3753
            if (ioh->deleted) {
3754
                *pioh = ioh->next;
3755
                qemu_free(ioh);
3756
            } else
3757
                pioh = &ioh->next;
3758
        }
3759
    }
3760

    
3761
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3762

    
3763
    /* rearm timer, if not periodic */
3764
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3765
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3766
        qemu_rearm_alarm_timer(alarm_timer);
3767
    }
3768

    
3769
    /* vm time timers */
3770
    if (vm_running) {
3771
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3772
            qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3773
                            qemu_get_clock(vm_clock));
3774
    }
3775

    
3776
    /* real time timers */
3777
    qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3778
                    qemu_get_clock(rt_clock));
3779

    
3780
    qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3781
                    qemu_get_clock(host_clock));
3782

    
3783
    /* Check bottom-halves last in case any of the earlier events triggered
3784
       them.  */
3785
    qemu_bh_poll();
3786

    
3787
}
3788

    
3789
static int qemu_cpu_exec(CPUState *env)
3790
{
3791
    int ret;
3792
#ifdef CONFIG_PROFILER
3793
    int64_t ti;
3794
#endif
3795

    
3796
#ifdef CONFIG_PROFILER
3797
    ti = profile_getclock();
3798
#endif
3799
    if (use_icount) {
3800
        int64_t count;
3801
        int decr;
3802
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3803
        env->icount_decr.u16.low = 0;
3804
        env->icount_extra = 0;
3805
        count = qemu_next_deadline();
3806
        count = (count + (1 << icount_time_shift) - 1)
3807
                >> icount_time_shift;
3808
        qemu_icount += count;
3809
        decr = (count > 0xffff) ? 0xffff : count;
3810
        count -= decr;
3811
        env->icount_decr.u16.low = decr;
3812
        env->icount_extra = count;
3813
    }
3814
    ret = cpu_exec(env);
3815
#ifdef CONFIG_PROFILER
3816
    qemu_time += profile_getclock() - ti;
3817
#endif
3818
    if (use_icount) {
3819
        /* Fold pending instructions back into the
3820
           instruction counter, and clear the interrupt flag.  */
3821
        qemu_icount -= (env->icount_decr.u16.low
3822
                        + env->icount_extra);
3823
        env->icount_decr.u32 = 0;
3824
        env->icount_extra = 0;
3825
    }
3826
    return ret;
3827
}
3828

    
3829
static void tcg_cpu_exec(void)
3830
{
3831
    int ret = 0;
3832

    
3833
    if (next_cpu == NULL)
3834
        next_cpu = first_cpu;
3835
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3836
        CPUState *env = cur_cpu = next_cpu;
3837

    
3838
        if (timer_alarm_pending) {
3839
            timer_alarm_pending = 0;
3840
            break;
3841
        }
3842
        if (cpu_can_run(env))
3843
            ret = qemu_cpu_exec(env);
3844
        else if (env->stop)
3845
            break;
3846

    
3847
        if (ret == EXCP_DEBUG) {
3848
            gdb_set_stop_cpu(env);
3849
            debug_requested = 1;
3850
            break;
3851
        }
3852
    }
3853
}
3854

    
3855
static int cpu_has_work(CPUState *env)
3856
{
3857
    if (env->stop)
3858
        return 1;
3859
    if (env->stopped)
3860
        return 0;
3861
    if (!env->halted)
3862
        return 1;
3863
    if (qemu_cpu_has_work(env))
3864
        return 1;
3865
    return 0;
3866
}
3867

    
3868
static int tcg_has_work(void)
3869
{
3870
    CPUState *env;
3871

    
3872
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3873
        if (cpu_has_work(env))
3874
            return 1;
3875
    return 0;
3876
}
3877

    
3878
static int qemu_calculate_timeout(void)
3879
{
3880
#ifndef CONFIG_IOTHREAD
3881
    int timeout;
3882

    
3883
    if (!vm_running)
3884
        timeout = 5000;
3885
    else if (tcg_has_work())
3886
        timeout = 0;
3887
    else if (!use_icount)
3888
        timeout = 5000;
3889
    else {
3890
     /* XXX: use timeout computed from timers */
3891
        int64_t add;
3892
        int64_t delta;
3893
        /* Advance virtual time to the next event.  */
3894
        if (use_icount == 1) {
3895
            /* When not using an adaptive execution frequency
3896
               we tend to get badly out of sync with real time,
3897
               so just delay for a reasonable amount of time.  */
3898
            delta = 0;
3899
        } else {
3900
            delta = cpu_get_icount() - cpu_get_clock();
3901
        }
3902
        if (delta > 0) {
3903
            /* If virtual time is ahead of real time then just
3904
               wait for IO.  */
3905
            timeout = (delta / 1000000) + 1;
3906
        } else {
3907
            /* Wait for either IO to occur or the next
3908
               timer event.  */
3909
            add = qemu_next_deadline();
3910
            /* We advance the timer before checking for IO.
3911
               Limit the amount we advance so that early IO
3912
               activity won't get the guest too far ahead.  */
3913
            if (add > 10000000)
3914
                add = 10000000;
3915
            delta += add;
3916
            add = (add + (1 << icount_time_shift) - 1)
3917
                  >> icount_time_shift;
3918
            qemu_icount += add;
3919
            timeout = delta / 1000000;
3920
            if (timeout < 0)
3921
                timeout = 0;
3922
        }
3923
    }
3924

    
3925
    return timeout;
3926
#else /* CONFIG_IOTHREAD */
3927
    return 1000;
3928
#endif
3929
}
3930

    
3931
static int vm_can_run(void)
3932
{
3933
    if (powerdown_requested)
3934
        return 0;
3935
    if (reset_requested)
3936
        return 0;
3937
    if (shutdown_requested)
3938
        return 0;
3939
    if (debug_requested)
3940
        return 0;
3941
    return 1;
3942
}
3943

    
3944
qemu_irq qemu_system_powerdown;
3945

    
3946
static void main_loop(void)
3947
{
3948
    int r;
3949

    
3950
#ifdef CONFIG_IOTHREAD
3951
    qemu_system_ready = 1;
3952
    qemu_cond_broadcast(&qemu_system_cond);
3953
#endif
3954

    
3955
    for (;;) {
3956
        do {
3957
#ifdef CONFIG_PROFILER
3958
            int64_t ti;
3959
#endif
3960
#ifndef CONFIG_IOTHREAD
3961
            tcg_cpu_exec();
3962
#endif
3963
#ifdef CONFIG_PROFILER
3964
            ti = profile_getclock();
3965
#endif
3966
            main_loop_wait(qemu_calculate_timeout());
3967
#ifdef CONFIG_PROFILER
3968
            dev_time += profile_getclock() - ti;
3969
#endif
3970
        } while (vm_can_run());
3971

    
3972
        if (qemu_debug_requested()) {
3973
            monitor_protocol_event(QEVENT_DEBUG, NULL);
3974
            vm_stop(EXCP_DEBUG);
3975
        }
3976
        if (qemu_shutdown_requested()) {
3977
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3978
            if (no_shutdown) {
3979
                vm_stop(0);
3980
                no_shutdown = 0;
3981
            } else
3982
                break;
3983
        }
3984
        if (qemu_reset_requested()) {
3985
            monitor_protocol_event(QEVENT_RESET, NULL);
3986
            pause_all_vcpus();
3987
            qemu_system_reset();
3988
            resume_all_vcpus();
3989
        }
3990
        if (qemu_powerdown_requested()) {
3991
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3992
            qemu_irq_raise(qemu_system_powerdown);
3993
        }
3994
        if ((r = qemu_vmstop_requested())) {
3995
            monitor_protocol_event(QEVENT_STOP, NULL);
3996
            vm_stop(r);
3997
        }
3998
    }
3999
    pause_all_vcpus();
4000
}
4001

    
4002
static void version(void)
4003
{
4004
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4005
}
4006

    
4007
static void help(int exitcode)
4008
{
4009
    const char *options_help =
4010
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4011
           opt_help
4012
#define DEFHEADING(text) stringify(text) "\n"
4013
#include "qemu-options.h"
4014
#undef DEF
4015
#undef DEFHEADING
4016
#undef GEN_DOCS
4017
        ;
4018
    version();
4019
    printf("usage: %s [options] [disk_image]\n"
4020
           "\n"
4021
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4022
           "\n"
4023
           "%s\n"
4024
           "During emulation, the following keys are useful:\n"
4025
           "ctrl-alt-f      toggle full screen\n"
4026
           "ctrl-alt-n      switch to virtual console 'n'\n"
4027
           "ctrl-alt        toggle mouse and keyboard grab\n"
4028
           "\n"
4029
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
4030
           "qemu",
4031
           options_help);
4032
    exit(exitcode);
4033
}
4034

    
4035
#define HAS_ARG 0x0001
4036

    
4037
enum {
4038
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4039
    opt_enum,
4040
#define DEFHEADING(text)
4041
#include "qemu-options.h"
4042
#undef DEF
4043
#undef DEFHEADING
4044
#undef GEN_DOCS
4045
};
4046

    
4047
typedef struct QEMUOption {
4048
    const char *name;
4049
    int flags;
4050
    int index;
4051
} QEMUOption;
4052

    
4053
static const QEMUOption qemu_options[] = {
4054
    { "h", 0, QEMU_OPTION_h },
4055
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4056
    { option, opt_arg, opt_enum },
4057
#define DEFHEADING(text)
4058
#include "qemu-options.h"
4059
#undef DEF
4060
#undef DEFHEADING
4061
#undef GEN_DOCS
4062
    { NULL },
4063
};
4064

    
4065
#ifdef HAS_AUDIO
4066
struct soundhw soundhw[] = {
4067
#ifdef HAS_AUDIO_CHOICE
4068
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4069
    {
4070
        "pcspk",
4071
        "PC speaker",
4072
        0,
4073
        1,
4074
        { .init_isa = pcspk_audio_init }
4075
    },
4076
#endif
4077

    
4078
#ifdef CONFIG_SB16
4079
    {
4080
        "sb16",
4081
        "Creative Sound Blaster 16",
4082
        0,
4083
        1,
4084
        { .init_isa = SB16_init }
4085
    },
4086
#endif
4087

    
4088
#ifdef CONFIG_CS4231A
4089
    {
4090
        "cs4231a",
4091
        "CS4231A",
4092
        0,
4093
        1,
4094
        { .init_isa = cs4231a_init }
4095
    },
4096
#endif
4097

    
4098
#ifdef CONFIG_ADLIB
4099
    {
4100
        "adlib",
4101
#ifdef HAS_YMF262
4102
        "Yamaha YMF262 (OPL3)",
4103
#else
4104
        "Yamaha YM3812 (OPL2)",
4105
#endif
4106
        0,
4107
        1,
4108
        { .init_isa = Adlib_init }
4109
    },
4110
#endif
4111

    
4112
#ifdef CONFIG_GUS
4113
    {
4114
        "gus",
4115
        "Gravis Ultrasound GF1",
4116
        0,
4117
        1,
4118
        { .init_isa = GUS_init }
4119
    },
4120
#endif
4121

    
4122
#ifdef CONFIG_AC97
4123
    {
4124
        "ac97",
4125
        "Intel 82801AA AC97 Audio",
4126
        0,
4127
        0,
4128
        { .init_pci = ac97_init }
4129
    },
4130
#endif
4131

    
4132
#ifdef CONFIG_ES1370
4133
    {
4134
        "es1370",
4135
        "ENSONIQ AudioPCI ES1370",
4136
        0,
4137
        0,
4138
        { .init_pci = es1370_init }
4139
    },
4140
#endif
4141

    
4142
#endif /* HAS_AUDIO_CHOICE */
4143

    
4144
    { NULL, NULL, 0, 0, { NULL } }
4145
};
4146

    
4147
static void select_soundhw (const char *optarg)
4148
{
4149
    struct soundhw *c;
4150

    
4151
    if (*optarg == '?') {
4152
    show_valid_cards:
4153

    
4154
        printf ("Valid sound card names (comma separated):\n");
4155
        for (c = soundhw; c->name; ++c) {
4156
            printf ("%-11s %s\n", c->name, c->descr);
4157
        }
4158
        printf ("\n-soundhw all will enable all of the above\n");
4159
        exit (*optarg != '?');
4160
    }
4161
    else {
4162
        size_t l;
4163
        const char *p;
4164
        char *e;
4165
        int bad_card = 0;
4166

    
4167
        if (!strcmp (optarg, "all")) {
4168
            for (c = soundhw; c->name; ++c) {
4169
                c->enabled = 1;
4170
            }
4171
            return;
4172
        }
4173

    
4174
        p = optarg;
4175
        while (*p) {
4176
            e = strchr (p, ',');
4177
            l = !e ? strlen (p) : (size_t) (e - p);
4178

    
4179
            for (c = soundhw; c->name; ++c) {
4180
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4181
                    c->enabled = 1;
4182
                    break;
4183
                }
4184
            }
4185

    
4186
            if (!c->name) {
4187
                if (l > 80) {
4188
                    fprintf (stderr,
4189
                             "Unknown sound card name (too big to show)\n");
4190
                }
4191
                else {
4192
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4193
                             (int) l, p);
4194
                }
4195
                bad_card = 1;
4196
            }
4197
            p += l + (e != NULL);
4198
        }
4199

    
4200
        if (bad_card)
4201
            goto show_valid_cards;
4202
    }
4203
}
4204
#endif
4205

    
4206
static void select_vgahw (const char *p)
4207
{
4208
    const char *opts;
4209

    
4210
    default_vga = 0;
4211
    vga_interface_type = VGA_NONE;
4212
    if (strstart(p, "std", &opts)) {
4213
        vga_interface_type = VGA_STD;
4214
    } else if (strstart(p, "cirrus", &opts)) {
4215
        vga_interface_type = VGA_CIRRUS;
4216
    } else if (strstart(p, "vmware", &opts)) {
4217
        vga_interface_type = VGA_VMWARE;
4218
    } else if (strstart(p, "xenfb", &opts)) {
4219
        vga_interface_type = VGA_XENFB;
4220
    } else if (!strstart(p, "none", &opts)) {
4221
    invalid_vga:
4222
        fprintf(stderr, "Unknown vga type: %s\n", p);
4223
        exit(1);
4224
    }
4225
    while (*opts) {
4226
        const char *nextopt;
4227

    
4228
        if (strstart(opts, ",retrace=", &nextopt)) {
4229
            opts = nextopt;
4230
            if (strstart(opts, "dumb", &nextopt))
4231
                vga_retrace_method = VGA_RETRACE_DUMB;
4232
            else if (strstart(opts, "precise", &nextopt))
4233
                vga_retrace_method = VGA_RETRACE_PRECISE;
4234
            else goto invalid_vga;
4235
        } else goto invalid_vga;
4236
        opts = nextopt;
4237
    }
4238
}
4239

    
4240
#ifdef TARGET_I386
4241
static int balloon_parse(const char *arg)
4242
{
4243
    QemuOpts *opts;
4244

    
4245
    if (strcmp(arg, "none") == 0) {
4246
        return 0;
4247
    }
4248

    
4249
    if (!strncmp(arg, "virtio", 6)) {
4250
        if (arg[6] == ',') {
4251
            /* have params -> parse them */
4252
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4253
            if (!opts)
4254
                return  -1;
4255
        } else {
4256
            /* create empty opts */
4257
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4258
        }
4259
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4260
        return 0;
4261
    }
4262

    
4263
    return -1;
4264
}
4265
#endif
4266

    
4267
#ifdef _WIN32
4268
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4269
{
4270
    exit(STATUS_CONTROL_C_EXIT);
4271
    return TRUE;
4272
}
4273
#endif
4274

    
4275
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4276
{
4277
    int ret;
4278

    
4279
    if(strlen(str) != 36)
4280
        return -1;
4281

    
4282
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4283
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4284
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4285

    
4286
    if(ret != 16)
4287
        return -1;
4288

    
4289
#ifdef TARGET_I386
4290
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4291
#endif
4292

    
4293
    return 0;
4294
}
4295

    
4296
#ifndef _WIN32
4297

    
4298
static void termsig_handler(int signal)
4299
{
4300
    qemu_system_shutdown_request();
4301
}
4302

    
4303
static void sigchld_handler(int signal)
4304
{
4305
    waitpid(-1, NULL, WNOHANG);
4306
}
4307

    
4308
static void sighandler_setup(void)
4309
{
4310
    struct sigaction act;
4311

    
4312
    memset(&act, 0, sizeof(act));
4313
    act.sa_handler = termsig_handler;
4314
    sigaction(SIGINT,  &act, NULL);
4315
    sigaction(SIGHUP,  &act, NULL);
4316
    sigaction(SIGTERM, &act, NULL);
4317

    
4318
    act.sa_handler = sigchld_handler;
4319
    act.sa_flags = SA_NOCLDSTOP;
4320
    sigaction(SIGCHLD, &act, NULL);
4321
}
4322

    
4323
#endif
4324

    
4325
#ifdef _WIN32
4326
/* Look for support files in the same directory as the executable.  */
4327
static char *find_datadir(const char *argv0)
4328
{
4329
    char *p;
4330
    char buf[MAX_PATH];
4331
    DWORD len;
4332

    
4333
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4334
    if (len == 0) {
4335
        return NULL;
4336
    }
4337

    
4338
    buf[len] = 0;
4339
    p = buf + len - 1;
4340
    while (p != buf && *p != '\\')
4341
        p--;
4342
    *p = 0;
4343
    if (access(buf, R_OK) == 0) {
4344
        return qemu_strdup(buf);
4345
    }
4346
    return NULL;
4347
}
4348
#else /* !_WIN32 */
4349

    
4350
/* Find a likely location for support files using the location of the binary.
4351
   For installed binaries this will be "$bindir/../share/qemu".  When
4352
   running from the build tree this will be "$bindir/../pc-bios".  */
4353
#define SHARE_SUFFIX "/share/qemu"
4354
#define BUILD_SUFFIX "/pc-bios"
4355
static char *find_datadir(const char *argv0)
4356
{
4357
    char *dir;
4358
    char *p = NULL;
4359
    char *res;
4360
    char buf[PATH_MAX];
4361
    size_t max_len;
4362

    
4363
#if defined(__linux__)
4364
    {
4365
        int len;
4366
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4367
        if (len > 0) {
4368
            buf[len] = 0;
4369
            p = buf;
4370
        }
4371
    }
4372
#elif defined(__FreeBSD__)
4373
    {
4374
        int len;
4375
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4376
        if (len > 0) {
4377
            buf[len] = 0;
4378
            p = buf;
4379
        }
4380
    }
4381
#endif
4382
    /* If we don't have any way of figuring out the actual executable
4383
       location then try argv[0].  */
4384
    if (!p) {
4385
        p = realpath(argv0, buf);
4386
        if (!p) {
4387
            return NULL;
4388
        }
4389
    }
4390
    dir = dirname(p);
4391
    dir = dirname(dir);
4392

    
4393
    max_len = strlen(dir) +
4394
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4395
    res = qemu_mallocz(max_len);
4396
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4397
    if (access(res, R_OK)) {
4398
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4399
        if (access(res, R_OK)) {
4400
            qemu_free(res);
4401
            res = NULL;
4402
        }
4403
    }
4404

    
4405
    return res;
4406
}
4407
#undef SHARE_SUFFIX
4408
#undef BUILD_SUFFIX
4409
#endif
4410

    
4411
char *qemu_find_file(int type, const char *name)
4412
{
4413
    int len;
4414
    const char *subdir;
4415
    char *buf;
4416

    
4417
    /* If name contains path separators then try it as a straight path.  */
4418
    if ((strchr(name, '/') || strchr(name, '\\'))
4419
        && access(name, R_OK) == 0) {
4420
        return qemu_strdup(name);
4421
    }
4422
    switch (type) {
4423
    case QEMU_FILE_TYPE_BIOS:
4424
        subdir = "";
4425
        break;
4426
    case QEMU_FILE_TYPE_KEYMAP:
4427
        subdir = "keymaps/";
4428
        break;
4429
    default:
4430
        abort();
4431
    }
4432
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4433
    buf = qemu_mallocz(len);
4434
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4435
    if (access(buf, R_OK)) {
4436
        qemu_free(buf);
4437
        return NULL;
4438
    }
4439
    return buf;
4440
}
4441

    
4442
static int device_help_func(QemuOpts *opts, void *opaque)
4443
{
4444
    return qdev_device_help(opts);
4445
}
4446

    
4447
static int device_init_func(QemuOpts *opts, void *opaque)
4448
{
4449
    DeviceState *dev;
4450

    
4451
    dev = qdev_device_add(opts);
4452
    if (!dev)
4453
        return -1;
4454
    return 0;
4455
}
4456

    
4457
static int chardev_init_func(QemuOpts *opts, void *opaque)
4458
{
4459
    CharDriverState *chr;
4460

    
4461
    chr = qemu_chr_open_opts(opts, NULL);
4462
    if (!chr)
4463
        return -1;
4464
    return 0;
4465
}
4466

    
4467
static int mon_init_func(QemuOpts *opts, void *opaque)
4468
{
4469
    CharDriverState *chr;
4470
    const char *chardev;
4471
    const char *mode;
4472
    int flags;
4473

    
4474
    mode = qemu_opt_get(opts, "mode");
4475
    if (mode == NULL) {
4476
        mode = "readline";
4477
    }
4478
    if (strcmp(mode, "readline") == 0) {
4479
        flags = MONITOR_USE_READLINE;
4480
    } else if (strcmp(mode, "control") == 0) {
4481
        flags = MONITOR_USE_CONTROL;
4482
    } else {
4483
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4484
        exit(1);
4485
    }
4486

    
4487
    if (qemu_opt_get_bool(opts, "default", 0))
4488
        flags |= MONITOR_IS_DEFAULT;
4489

    
4490
    chardev = qemu_opt_get(opts, "chardev");
4491
    chr = qemu_chr_find(chardev);
4492
    if (chr == NULL) {
4493
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4494
        exit(1);
4495
    }
4496

    
4497
    monitor_init(chr, flags);
4498
    return 0;
4499
}
4500

    
4501
static void monitor_parse(const char *optarg, const char *mode)
4502
{
4503
    static int monitor_device_index = 0;
4504
    QemuOpts *opts;
4505
    const char *p;
4506
    char label[32];
4507
    int def = 0;
4508

    
4509
    if (strstart(optarg, "chardev:", &p)) {
4510
        snprintf(label, sizeof(label), "%s", p);
4511
    } else {
4512
        if (monitor_device_index) {
4513
            snprintf(label, sizeof(label), "monitor%d",
4514
                     monitor_device_index);
4515
        } else {
4516
            snprintf(label, sizeof(label), "monitor");
4517
            def = 1;
4518
        }
4519
        opts = qemu_chr_parse_compat(label, optarg);
4520
        if (!opts) {
4521
            fprintf(stderr, "parse error: %s\n", optarg);
4522
            exit(1);
4523
        }
4524
    }
4525

    
4526
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4527
    if (!opts) {
4528
        fprintf(stderr, "duplicate chardev: %s\n", label);
4529
        exit(1);
4530
    }
4531
    qemu_opt_set(opts, "mode", mode);
4532
    qemu_opt_set(opts, "chardev", label);
4533
    if (def)
4534
        qemu_opt_set(opts, "default", "on");
4535
    monitor_device_index++;
4536
}
4537

    
4538
struct device_config {
4539
    enum {
4540
        DEV_USB,       /* -usbdevice     */
4541
        DEV_BT,        /* -bt            */
4542
        DEV_SERIAL,    /* -serial        */
4543
        DEV_PARALLEL,  /* -parallel      */
4544
        DEV_VIRTCON,   /* -virtioconsole */
4545
        DEV_DEBUGCON,  /* -debugcon */
4546
    } type;
4547
    const char *cmdline;
4548
    QTAILQ_ENTRY(device_config) next;
4549
};
4550
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4551

    
4552
static void add_device_config(int type, const char *cmdline)
4553
{
4554
    struct device_config *conf;
4555

    
4556
    conf = qemu_mallocz(sizeof(*conf));
4557
    conf->type = type;
4558
    conf->cmdline = cmdline;
4559
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4560
}
4561

    
4562
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4563
{
4564
    struct device_config *conf;
4565
    int rc;
4566

    
4567
    QTAILQ_FOREACH(conf, &device_configs, next) {
4568
        if (conf->type != type)
4569
            continue;
4570
        rc = func(conf->cmdline);
4571
        if (0 != rc)
4572
            return rc;
4573
    }
4574
    return 0;
4575
}
4576

    
4577
static int serial_parse(const char *devname)
4578
{
4579
    static int index = 0;
4580
    char label[32];
4581

    
4582
    if (strcmp(devname, "none") == 0)
4583
        return 0;
4584
    if (index == MAX_SERIAL_PORTS) {
4585
        fprintf(stderr, "qemu: too many serial ports\n");
4586
        exit(1);
4587
    }
4588
    snprintf(label, sizeof(label), "serial%d", index);
4589
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
4590
    if (!serial_hds[index]) {
4591
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4592
                devname, strerror(errno));
4593
        return -1;
4594
    }
4595
    index++;
4596
    return 0;
4597
}
4598

    
4599
static int parallel_parse(const char *devname)
4600
{
4601
    static int index = 0;
4602
    char label[32];
4603

    
4604
    if (strcmp(devname, "none") == 0)
4605
        return 0;
4606
    if (index == MAX_PARALLEL_PORTS) {
4607
        fprintf(stderr, "qemu: too many parallel ports\n");
4608
        exit(1);
4609
    }
4610
    snprintf(label, sizeof(label), "parallel%d", index);
4611
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4612
    if (!parallel_hds[index]) {
4613
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4614
                devname, strerror(errno));
4615
        return -1;
4616
    }
4617
    index++;
4618
    return 0;
4619
}
4620

    
4621
static int virtcon_parse(const char *devname)
4622
{
4623
    static int index = 0;
4624
    char label[32];
4625
    QemuOpts *bus_opts, *dev_opts;
4626

    
4627
    if (strcmp(devname, "none") == 0)
4628
        return 0;
4629
    if (index == MAX_VIRTIO_CONSOLES) {
4630
        fprintf(stderr, "qemu: too many virtio consoles\n");
4631
        exit(1);
4632
    }
4633

    
4634
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4635
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
4636

    
4637
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4638
    qemu_opt_set(dev_opts, "driver", "virtconsole");
4639

    
4640
    snprintf(label, sizeof(label), "virtcon%d", index);
4641
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4642
    if (!virtcon_hds[index]) {
4643
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4644
                devname, strerror(errno));
4645
        return -1;
4646
    }
4647
    qemu_opt_set(dev_opts, "chardev", label);
4648

    
4649
    index++;
4650
    return 0;
4651
}
4652

    
4653
static int debugcon_parse(const char *devname)
4654
{   
4655
    QemuOpts *opts;
4656

    
4657
    if (!qemu_chr_open("debugcon", devname, NULL)) {
4658
        exit(1);
4659
    }
4660
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4661
    if (!opts) {
4662
        fprintf(stderr, "qemu: already have a debugcon device\n");
4663
        exit(1);
4664
    }
4665
    qemu_opt_set(opts, "driver", "isa-debugcon");
4666
    qemu_opt_set(opts, "chardev", "debugcon");
4667
    return 0;
4668
}
4669

    
4670
static const QEMUOption *lookup_opt(int argc, char **argv,
4671
                                    const char **poptarg, int *poptind)
4672
{
4673
    const QEMUOption *popt;
4674
    int optind = *poptind;
4675
    char *r = argv[optind];
4676
    const char *optarg;
4677

    
4678
    optind++;
4679
    /* Treat --foo the same as -foo.  */
4680
    if (r[1] == '-')
4681
        r++;
4682
    popt = qemu_options;
4683
    for(;;) {
4684
        if (!popt->name) {
4685
            fprintf(stderr, "%s: invalid option -- '%s'\n",
4686
                    argv[0], r);
4687
            exit(1);
4688
        }
4689
        if (!strcmp(popt->name, r + 1))
4690
            break;
4691
        popt++;
4692
    }
4693
    if (popt->flags & HAS_ARG) {
4694
        if (optind >= argc) {
4695
            fprintf(stderr, "%s: option '%s' requires an argument\n",
4696
                    argv[0], r);
4697
            exit(1);
4698
        }
4699
        optarg = argv[optind++];
4700
    } else {
4701
        optarg = NULL;
4702
    }
4703

    
4704
    *poptarg = optarg;
4705
    *poptind = optind;
4706

    
4707
    return popt;
4708
}
4709

    
4710
int main(int argc, char **argv, char **envp)
4711
{
4712
    const char *gdbstub_dev = NULL;
4713
    uint32_t boot_devices_bitmap = 0;
4714
    int i;
4715
    int snapshot, linux_boot, net_boot;
4716
    const char *initrd_filename;
4717
    const char *kernel_filename, *kernel_cmdline;
4718
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4719
    DisplayState *ds;
4720
    DisplayChangeListener *dcl;
4721
    int cyls, heads, secs, translation;
4722
    QemuOpts *hda_opts = NULL, *opts;
4723
    int optind;
4724
    const char *optarg;
4725
    const char *loadvm = NULL;
4726
    QEMUMachine *machine;
4727
    const char *cpu_model;
4728
#ifndef _WIN32
4729
    int fds[2];
4730
#endif
4731
    int tb_size;
4732
    const char *pid_file = NULL;
4733
    const char *incoming = NULL;
4734
#ifndef _WIN32
4735
    int fd = 0;
4736
    struct passwd *pwd = NULL;
4737
    const char *chroot_dir = NULL;
4738
    const char *run_as = NULL;
4739
#endif
4740
    CPUState *env;
4741
    int show_vnc_port = 0;
4742
    int defconfig = 1;
4743

    
4744
    init_clocks();
4745

    
4746
    qemu_errors_to_file(stderr);
4747
    qemu_cache_utils_init(envp);
4748

    
4749
    QLIST_INIT (&vm_change_state_head);
4750
#ifndef _WIN32
4751
    {
4752
        struct sigaction act;
4753
        sigfillset(&act.sa_mask);
4754
        act.sa_flags = 0;
4755
        act.sa_handler = SIG_IGN;
4756
        sigaction(SIGPIPE, &act, NULL);
4757
    }
4758
#else
4759
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4760
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4761
       QEMU to run on a single CPU */
4762
    {
4763
        HANDLE h;
4764
        DWORD mask, smask;
4765
        int i;
4766
        h = GetCurrentProcess();
4767
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4768
            for(i = 0; i < 32; i++) {
4769
                if (mask & (1 << i))
4770
                    break;
4771
            }
4772
            if (i != 32) {
4773
                mask = 1 << i;
4774
                SetProcessAffinityMask(h, mask);
4775
            }
4776
        }
4777
    }
4778
#endif
4779

    
4780
    module_call_init(MODULE_INIT_MACHINE);
4781
    machine = find_default_machine();
4782
    cpu_model = NULL;
4783
    initrd_filename = NULL;
4784
    ram_size = 0;
4785
    snapshot = 0;
4786
    kernel_filename = NULL;
4787
    kernel_cmdline = "";
4788
    cyls = heads = secs = 0;
4789
    translation = BIOS_ATA_TRANSLATION_AUTO;
4790

    
4791
    for (i = 0; i < MAX_NODES; i++) {
4792
        node_mem[i] = 0;
4793
        node_cpumask[i] = 0;
4794
    }
4795

    
4796
    nb_numa_nodes = 0;
4797
    nb_nics = 0;
4798

    
4799
    tb_size = 0;
4800
    autostart= 1;
4801

    
4802
    /* first pass of option parsing */
4803
    optind = 1;
4804
    while (optind < argc) {
4805
        if (argv[optind][0] != '-') {
4806
            /* disk image */
4807
            optind++;
4808
            continue;
4809
        } else {
4810
            const QEMUOption *popt;
4811

    
4812
            popt = lookup_opt(argc, argv, &optarg, &optind);
4813
            switch (popt->index) {
4814
            case QEMU_OPTION_nodefconfig:
4815
                defconfig=0;
4816
                break;
4817
            }
4818
        }
4819
    }
4820

    
4821
    if (defconfig) {
4822
        FILE *fp;
4823
        fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4824
        if (fp) {
4825
            if (qemu_config_parse(fp) != 0) {
4826
                exit(1);
4827
            }
4828
            fclose(fp);
4829
        }
4830

    
4831
        fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4832
        if (fp) {
4833
            if (qemu_config_parse(fp) != 0) {
4834
                exit(1);
4835
            }
4836
            fclose(fp);
4837
        }
4838
    }
4839

    
4840
    /* second pass of option parsing */
4841
    optind = 1;
4842
    for(;;) {
4843
        if (optind >= argc)
4844
            break;
4845
        if (argv[optind][0] != '-') {
4846
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4847
        } else {
4848
            const QEMUOption *popt;
4849

    
4850
            popt = lookup_opt(argc, argv, &optarg, &optind);
4851
            switch(popt->index) {
4852
            case QEMU_OPTION_M:
4853
                machine = find_machine(optarg);
4854
                if (!machine) {
4855
                    QEMUMachine *m;
4856
                    printf("Supported machines are:\n");
4857
                    for(m = first_machine; m != NULL; m = m->next) {
4858
                        if (m->alias)
4859
                            printf("%-10s %s (alias of %s)\n",
4860
                                   m->alias, m->desc, m->name);
4861
                        printf("%-10s %s%s\n",
4862
                               m->name, m->desc,
4863
                               m->is_default ? " (default)" : "");
4864
                    }
4865
                    exit(*optarg != '?');
4866
                }
4867
                break;
4868
            case QEMU_OPTION_cpu:
4869
                /* hw initialization will check this */
4870
                if (*optarg == '?') {
4871
/* XXX: implement xxx_cpu_list for targets that still miss it */
4872
#if defined(cpu_list)
4873
                    cpu_list(stdout, &fprintf);
4874
#endif
4875
                    exit(0);
4876
                } else {
4877
                    cpu_model = optarg;
4878
                }
4879
                break;
4880
            case QEMU_OPTION_initrd:
4881
                initrd_filename = optarg;
4882
                break;
4883
            case QEMU_OPTION_hda:
4884
                if (cyls == 0)
4885
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
4886
                else
4887
                    hda_opts = drive_add(optarg, HD_ALIAS
4888
                             ",cyls=%d,heads=%d,secs=%d%s",
4889
                             0, cyls, heads, secs,
4890
                             translation == BIOS_ATA_TRANSLATION_LBA ?
4891
                                 ",trans=lba" :
4892
                             translation == BIOS_ATA_TRANSLATION_NONE ?
4893
                                 ",trans=none" : "");
4894
                 break;
4895
            case QEMU_OPTION_hdb:
4896
            case QEMU_OPTION_hdc:
4897
            case QEMU_OPTION_hdd:
4898
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4899
                break;
4900
            case QEMU_OPTION_drive:
4901
                drive_add(NULL, "%s", optarg);
4902
                break;
4903
            case QEMU_OPTION_set:
4904
                if (qemu_set_option(optarg) != 0)
4905
                    exit(1);
4906
                break;
4907
            case QEMU_OPTION_global:
4908
                if (qemu_global_option(optarg) != 0)
4909
                    exit(1);
4910
                break;
4911
            case QEMU_OPTION_mtdblock:
4912
                drive_add(optarg, MTD_ALIAS);
4913
                break;
4914
            case QEMU_OPTION_sd:
4915
                drive_add(optarg, SD_ALIAS);
4916
                break;
4917
            case QEMU_OPTION_pflash:
4918
                drive_add(optarg, PFLASH_ALIAS);
4919
                break;
4920
            case QEMU_OPTION_snapshot:
4921
                snapshot = 1;
4922
                break;
4923
            case QEMU_OPTION_hdachs:
4924
                {
4925
                    const char *p;
4926
                    p = optarg;
4927
                    cyls = strtol(p, (char **)&p, 0);
4928
                    if (cyls < 1 || cyls > 16383)
4929
                        goto chs_fail;
4930
                    if (*p != ',')
4931
                        goto chs_fail;
4932
                    p++;
4933
                    heads = strtol(p, (char **)&p, 0);
4934
                    if (heads < 1 || heads > 16)
4935
                        goto chs_fail;
4936
                    if (*p != ',')
4937
                        goto chs_fail;
4938
                    p++;
4939
                    secs = strtol(p, (char **)&p, 0);
4940
                    if (secs < 1 || secs > 63)
4941
                        goto chs_fail;
4942
                    if (*p == ',') {
4943
                        p++;
4944
                        if (!strcmp(p, "none"))
4945
                            translation = BIOS_ATA_TRANSLATION_NONE;
4946
                        else if (!strcmp(p, "lba"))
4947
                            translation = BIOS_ATA_TRANSLATION_LBA;
4948
                        else if (!strcmp(p, "auto"))
4949
                            translation = BIOS_ATA_TRANSLATION_AUTO;
4950
                        else
4951
                            goto chs_fail;
4952
                    } else if (*p != '\0') {
4953
                    chs_fail:
4954
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
4955
                        exit(1);
4956
                    }
4957
                    if (hda_opts != NULL) {
4958
                        char num[16];
4959
                        snprintf(num, sizeof(num), "%d", cyls);
4960
                        qemu_opt_set(hda_opts, "cyls", num);
4961
                        snprintf(num, sizeof(num), "%d", heads);
4962
                        qemu_opt_set(hda_opts, "heads", num);
4963
                        snprintf(num, sizeof(num), "%d", secs);
4964
                        qemu_opt_set(hda_opts, "secs", num);
4965
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
4966
                            qemu_opt_set(hda_opts, "trans", "lba");
4967
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
4968
                            qemu_opt_set(hda_opts, "trans", "none");
4969
                    }
4970
                }
4971
                break;
4972
            case QEMU_OPTION_numa:
4973
                if (nb_numa_nodes >= MAX_NODES) {
4974
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
4975
                    exit(1);
4976
                }
4977
                numa_add(optarg);
4978
                break;
4979
            case QEMU_OPTION_nographic:
4980
                display_type = DT_NOGRAPHIC;
4981
                break;
4982
#ifdef CONFIG_CURSES
4983
            case QEMU_OPTION_curses:
4984
                display_type = DT_CURSES;
4985
                break;
4986
#endif
4987
            case QEMU_OPTION_portrait:
4988
                graphic_rotate = 1;
4989
                break;
4990
            case QEMU_OPTION_kernel:
4991
                kernel_filename = optarg;
4992
                break;
4993
            case QEMU_OPTION_append:
4994
                kernel_cmdline = optarg;
4995
                break;
4996
            case QEMU_OPTION_cdrom:
4997
                drive_add(optarg, CDROM_ALIAS);
4998
                break;
4999
            case QEMU_OPTION_boot:
5000
                {
5001
                    static const char * const params[] = {
5002
                        "order", "once", "menu", NULL
5003
                    };
5004
                    char buf[sizeof(boot_devices)];
5005
                    char *standard_boot_devices;
5006
                    int legacy = 0;
5007

    
5008
                    if (!strchr(optarg, '=')) {
5009
                        legacy = 1;
5010
                        pstrcpy(buf, sizeof(buf), optarg);
5011
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5012
                        fprintf(stderr,
5013
                                "qemu: unknown boot parameter '%s' in '%s'\n",
5014
                                buf, optarg);
5015
                        exit(1);
5016
                    }
5017

    
5018
                    if (legacy ||
5019
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
5020
                        boot_devices_bitmap = parse_bootdevices(buf);
5021
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
5022
                    }
5023
                    if (!legacy) {
5024
                        if (get_param_value(buf, sizeof(buf),
5025
                                            "once", optarg)) {
5026
                            boot_devices_bitmap |= parse_bootdevices(buf);
5027
                            standard_boot_devices = qemu_strdup(boot_devices);
5028
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
5029
                            qemu_register_reset(restore_boot_devices,
5030
                                                standard_boot_devices);
5031
                        }
5032
                        if (get_param_value(buf, sizeof(buf),
5033
                                            "menu", optarg)) {
5034
                            if (!strcmp(buf, "on")) {
5035
                                boot_menu = 1;
5036
                            } else if (!strcmp(buf, "off")) {
5037
                                boot_menu = 0;
5038
                            } else {
5039
                                fprintf(stderr,
5040
                                        "qemu: invalid option value '%s'\n",
5041
                                        buf);
5042
                                exit(1);
5043
                            }
5044
                        }
5045
                    }
5046
                }
5047
                break;
5048
            case QEMU_OPTION_fda:
5049
            case QEMU_OPTION_fdb:
5050
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5051
                break;
5052
#ifdef TARGET_I386
5053
            case QEMU_OPTION_no_fd_bootchk:
5054
                fd_bootchk = 0;
5055
                break;
5056
#endif
5057
            case QEMU_OPTION_netdev:
5058
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5059
                    exit(1);
5060
                }
5061
                break;
5062
            case QEMU_OPTION_net:
5063
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5064
                    exit(1);
5065
                }
5066
                break;
5067
#ifdef CONFIG_SLIRP
5068
            case QEMU_OPTION_tftp:
5069
                legacy_tftp_prefix = optarg;
5070
                break;
5071
            case QEMU_OPTION_bootp:
5072
                legacy_bootp_filename = optarg;
5073
                break;
5074
#ifndef _WIN32
5075
            case QEMU_OPTION_smb:
5076
                if (net_slirp_smb(optarg) < 0)
5077
                    exit(1);
5078
                break;
5079
#endif
5080
            case QEMU_OPTION_redir:
5081
                if (net_slirp_redir(optarg) < 0)
5082
                    exit(1);
5083
                break;
5084
#endif
5085
            case QEMU_OPTION_bt:
5086
                add_device_config(DEV_BT, optarg);
5087
                break;
5088
#ifdef HAS_AUDIO
5089
            case QEMU_OPTION_audio_help:
5090
                AUD_help ();
5091
                exit (0);
5092
                break;
5093
            case QEMU_OPTION_soundhw:
5094
                select_soundhw (optarg);
5095
                break;
5096
#endif
5097
            case QEMU_OPTION_h:
5098
                help(0);
5099
                break;
5100
            case QEMU_OPTION_version:
5101
                version();
5102
                exit(0);
5103
                break;
5104
            case QEMU_OPTION_m: {
5105
                uint64_t value;
5106
                char *ptr;
5107

    
5108
                value = strtoul(optarg, &ptr, 10);
5109
                switch (*ptr) {
5110
                case 0: case 'M': case 'm':
5111
                    value <<= 20;
5112
                    break;
5113
                case 'G': case 'g':
5114
                    value <<= 30;
5115
                    break;
5116
                default:
5117
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5118
                    exit(1);
5119
                }
5120

    
5121
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5122
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5123
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5124
                    exit(1);
5125
                }
5126
                if (value != (uint64_t)(ram_addr_t)value) {
5127
                    fprintf(stderr, "qemu: ram size too large\n");
5128
                    exit(1);
5129
                }
5130
                ram_size = value;
5131
                break;
5132
            }
5133
            case QEMU_OPTION_d:
5134
                {
5135
                    int mask;
5136
                    const CPULogItem *item;
5137

    
5138
                    mask = cpu_str_to_log_mask(optarg);
5139
                    if (!mask) {
5140
                        printf("Log items (comma separated):\n");
5141
                    for(item = cpu_log_items; item->mask != 0; item++) {
5142
                        printf("%-10s %s\n", item->name, item->help);
5143
                    }
5144
                    exit(1);
5145
                    }
5146
                    cpu_set_log(mask);
5147
                }
5148
                break;
5149
            case QEMU_OPTION_s:
5150
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5151
                break;
5152
            case QEMU_OPTION_gdb:
5153
                gdbstub_dev = optarg;
5154
                break;
5155
            case QEMU_OPTION_L:
5156
                data_dir = optarg;
5157
                break;
5158
            case QEMU_OPTION_bios:
5159
                bios_name = optarg;
5160
                break;
5161
            case QEMU_OPTION_singlestep:
5162
                singlestep = 1;
5163
                break;
5164
            case QEMU_OPTION_S:
5165
                autostart = 0;
5166
                break;
5167
            case QEMU_OPTION_k:
5168
                keyboard_layout = optarg;
5169
                break;
5170
            case QEMU_OPTION_localtime:
5171
                rtc_utc = 0;
5172
                break;
5173
            case QEMU_OPTION_vga:
5174
                select_vgahw (optarg);
5175
                break;
5176
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
5177
            case QEMU_OPTION_g:
5178
                {
5179
                    const char *p;
5180
                    int w, h, depth;
5181
                    p = optarg;
5182
                    w = strtol(p, (char **)&p, 10);
5183
                    if (w <= 0) {
5184
                    graphic_error:
5185
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5186
                        exit(1);
5187
                    }
5188
                    if (*p != 'x')
5189
                        goto graphic_error;
5190
                    p++;
5191
                    h = strtol(p, (char **)&p, 10);
5192
                    if (h <= 0)
5193
                        goto graphic_error;
5194
                    if (*p == 'x') {
5195
                        p++;
5196
                        depth = strtol(p, (char **)&p, 10);
5197
                        if (depth != 8 && depth != 15 && depth != 16 &&
5198
                            depth != 24 && depth != 32)
5199
                            goto graphic_error;
5200
                    } else if (*p == '\0') {
5201
                        depth = graphic_depth;
5202
                    } else {
5203
                        goto graphic_error;
5204
                    }
5205

    
5206
                    graphic_width = w;
5207
                    graphic_height = h;
5208
                    graphic_depth = depth;
5209
                }
5210
                break;
5211
#endif
5212
            case QEMU_OPTION_echr:
5213
                {
5214
                    char *r;
5215
                    term_escape_char = strtol(optarg, &r, 0);
5216
                    if (r == optarg)
5217
                        printf("Bad argument to echr\n");
5218
                    break;
5219
                }
5220
            case QEMU_OPTION_monitor:
5221
                monitor_parse(optarg, "readline");
5222
                default_monitor = 0;
5223
                break;
5224
            case QEMU_OPTION_qmp:
5225
                monitor_parse(optarg, "control");
5226
                default_monitor = 0;
5227
                break;
5228
            case QEMU_OPTION_mon:
5229
                opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5230
                if (!opts) {
5231
                    fprintf(stderr, "parse error: %s\n", optarg);
5232
                    exit(1);
5233
                }
5234
                default_monitor = 0;
5235
                break;
5236
            case QEMU_OPTION_chardev:
5237
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5238
                if (!opts) {
5239
                    fprintf(stderr, "parse error: %s\n", optarg);
5240
                    exit(1);
5241
                }
5242
                break;
5243
            case QEMU_OPTION_serial:
5244
                add_device_config(DEV_SERIAL, optarg);
5245
                default_serial = 0;
5246
                break;
5247
            case QEMU_OPTION_watchdog:
5248
                if (watchdog) {
5249
                    fprintf(stderr,
5250
                            "qemu: only one watchdog option may be given\n");
5251
                    return 1;
5252
                }
5253
                watchdog = optarg;
5254
                break;
5255
            case QEMU_OPTION_watchdog_action:
5256
                if (select_watchdog_action(optarg) == -1) {
5257
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
5258
                    exit(1);
5259
                }
5260
                break;
5261
            case QEMU_OPTION_virtiocon:
5262
                add_device_config(DEV_VIRTCON, optarg);
5263
                default_virtcon = 0;
5264
                break;
5265
            case QEMU_OPTION_parallel:
5266
                add_device_config(DEV_PARALLEL, optarg);
5267
                default_parallel = 0;
5268
                break;
5269
            case QEMU_OPTION_debugcon:
5270
                add_device_config(DEV_DEBUGCON, optarg);
5271
                break;
5272
            case QEMU_OPTION_loadvm:
5273
                loadvm = optarg;
5274
                break;
5275
            case QEMU_OPTION_full_screen:
5276
                full_screen = 1;
5277
                break;
5278
#ifdef CONFIG_SDL
5279
            case QEMU_OPTION_no_frame:
5280
                no_frame = 1;
5281
                break;
5282
            case QEMU_OPTION_alt_grab:
5283
                alt_grab = 1;
5284
                break;
5285
            case QEMU_OPTION_ctrl_grab:
5286
                ctrl_grab = 1;
5287
                break;
5288
            case QEMU_OPTION_no_quit:
5289
                no_quit = 1;
5290
                break;
5291
            case QEMU_OPTION_sdl:
5292
                display_type = DT_SDL;
5293
                break;
5294
#endif
5295
            case QEMU_OPTION_pidfile:
5296
                pid_file = optarg;
5297
                break;
5298
#ifdef TARGET_I386
5299
            case QEMU_OPTION_win2k_hack:
5300
                win2k_install_hack = 1;
5301
                break;
5302
            case QEMU_OPTION_rtc_td_hack:
5303
                rtc_td_hack = 1;
5304
                break;
5305
            case QEMU_OPTION_acpitable:
5306
                if(acpi_table_add(optarg) < 0) {
5307
                    fprintf(stderr, "Wrong acpi table provided\n");
5308
                    exit(1);
5309
                }
5310
                break;
5311
            case QEMU_OPTION_smbios:
5312
                if(smbios_entry_add(optarg) < 0) {
5313
                    fprintf(stderr, "Wrong smbios provided\n");
5314
                    exit(1);
5315
                }
5316
                break;
5317
#endif
5318
#ifdef CONFIG_KVM
5319
            case QEMU_OPTION_enable_kvm:
5320
                kvm_allowed = 1;
5321
                break;
5322
#endif
5323
            case QEMU_OPTION_usb:
5324
                usb_enabled = 1;
5325
                break;
5326
            case QEMU_OPTION_usbdevice:
5327
                usb_enabled = 1;
5328
                add_device_config(DEV_USB, optarg);
5329
                break;
5330
            case QEMU_OPTION_device:
5331
                if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5332
                    exit(1);
5333
                }
5334
                break;
5335
            case QEMU_OPTION_smp:
5336
                smp_parse(optarg);
5337
                if (smp_cpus < 1) {
5338
                    fprintf(stderr, "Invalid number of CPUs\n");
5339
                    exit(1);
5340
                }
5341
                if (max_cpus < smp_cpus) {
5342
                    fprintf(stderr, "maxcpus must be equal to or greater than "
5343
                            "smp\n");
5344
                    exit(1);
5345
                }
5346
                if (max_cpus > 255) {
5347
                    fprintf(stderr, "Unsupported number of maxcpus\n");
5348
                    exit(1);
5349
                }
5350
                break;
5351
            case QEMU_OPTION_vnc:
5352
                display_type = DT_VNC;
5353
                vnc_display = optarg;
5354
                break;
5355
#ifdef TARGET_I386
5356
            case QEMU_OPTION_no_acpi:
5357
                acpi_enabled = 0;
5358
                break;
5359
            case QEMU_OPTION_no_hpet:
5360
                no_hpet = 1;
5361
                break;
5362
            case QEMU_OPTION_balloon:
5363
                if (balloon_parse(optarg) < 0) {
5364
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5365
                    exit(1);
5366
                }
5367
                break;
5368
#endif
5369
            case QEMU_OPTION_no_reboot:
5370
                no_reboot = 1;
5371
                break;
5372
            case QEMU_OPTION_no_shutdown:
5373
                no_shutdown = 1;
5374
                break;
5375
            case QEMU_OPTION_show_cursor:
5376
                cursor_hide = 0;
5377
                break;
5378
            case QEMU_OPTION_uuid:
5379
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5380
                    fprintf(stderr, "Fail to parse UUID string."
5381
                            " Wrong format.\n");
5382
                    exit(1);
5383
                }
5384
                break;
5385
#ifndef _WIN32
5386
            case QEMU_OPTION_daemonize:
5387
                daemonize = 1;
5388
                break;
5389
#endif
5390
            case QEMU_OPTION_option_rom:
5391
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5392
                    fprintf(stderr, "Too many option ROMs\n");
5393
                    exit(1);
5394
                }
5395
                option_rom[nb_option_roms] = optarg;
5396
                nb_option_roms++;
5397
                break;
5398
#if defined(TARGET_ARM) || defined(TARGET_M68K)
5399
            case QEMU_OPTION_semihosting:
5400
                semihosting_enabled = 1;
5401
                break;
5402
#endif
5403
            case QEMU_OPTION_name:
5404
                qemu_name = qemu_strdup(optarg);
5405
                 {
5406
                     char *p = strchr(qemu_name, ',');
5407
                     if (p != NULL) {
5408
                        *p++ = 0;
5409
                        if (strncmp(p, "process=", 8)) {
5410
                            fprintf(stderr, "Unknown subargument %s to -name", p);
5411
                            exit(1);
5412
                        }
5413
                        p += 8;
5414
                        set_proc_name(p);
5415
                     }        
5416
                 }        
5417
                break;
5418
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
5419
            case QEMU_OPTION_prom_env:
5420
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5421
                    fprintf(stderr, "Too many prom variables\n");
5422
                    exit(1);
5423
                }
5424
                prom_envs[nb_prom_envs] = optarg;
5425
                nb_prom_envs++;
5426
                break;
5427
#endif
5428
#ifdef TARGET_ARM
5429
            case QEMU_OPTION_old_param:
5430
                old_param = 1;
5431
                break;
5432
#endif
5433
            case QEMU_OPTION_clock:
5434
                configure_alarms(optarg);
5435
                break;
5436
            case QEMU_OPTION_startdate:
5437
                configure_rtc_date_offset(optarg, 1);
5438
                break;
5439
            case QEMU_OPTION_rtc:
5440
                opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5441
                if (!opts) {
5442
                    fprintf(stderr, "parse error: %s\n", optarg);
5443
                    exit(1);
5444
                }
5445
                configure_rtc(opts);
5446
                break;
5447
            case QEMU_OPTION_tb_size:
5448
                tb_size = strtol(optarg, NULL, 0);
5449
                if (tb_size < 0)
5450
                    tb_size = 0;
5451
                break;
5452
            case QEMU_OPTION_icount:
5453
                use_icount = 1;
5454
                if (strcmp(optarg, "auto") == 0) {
5455
                    icount_time_shift = -1;
5456
                } else {
5457
                    icount_time_shift = strtol(optarg, NULL, 0);
5458
                }
5459
                break;
5460
            case QEMU_OPTION_incoming:
5461
                incoming = optarg;
5462
                break;
5463
            case QEMU_OPTION_nodefaults:
5464
                default_serial = 0;
5465
                default_parallel = 0;
5466
                default_virtcon = 0;
5467
                default_monitor = 0;
5468
                default_vga = 0;
5469
                default_net = 0;
5470
                default_floppy = 0;
5471
                default_cdrom = 0;
5472
                default_sdcard = 0;
5473
                break;
5474
#ifndef _WIN32
5475
            case QEMU_OPTION_chroot:
5476
                chroot_dir = optarg;
5477
                break;
5478
            case QEMU_OPTION_runas:
5479
                run_as = optarg;
5480
                break;
5481
#endif
5482
#ifdef CONFIG_XEN
5483
            case QEMU_OPTION_xen_domid:
5484
                xen_domid = atoi(optarg);
5485
                break;
5486
            case QEMU_OPTION_xen_create:
5487
                xen_mode = XEN_CREATE;
5488
                break;
5489
            case QEMU_OPTION_xen_attach:
5490
                xen_mode = XEN_ATTACH;
5491
                break;
5492
#endif
5493
            case QEMU_OPTION_readconfig:
5494
                {
5495
                    FILE *fp;
5496
                    fp = fopen(optarg, "r");
5497
                    if (fp == NULL) {
5498
                        fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5499
                        exit(1);
5500
                    }
5501
                    if (qemu_config_parse(fp) != 0) {
5502
                        exit(1);
5503
                    }
5504
                    fclose(fp);
5505
                    break;
5506
                }
5507
            case QEMU_OPTION_writeconfig:
5508
                {
5509
                    FILE *fp;
5510
                    if (strcmp(optarg, "-") == 0) {
5511
                        fp = stdout;
5512
                    } else {
5513
                        fp = fopen(optarg, "w");
5514
                        if (fp == NULL) {
5515
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5516
                            exit(1);
5517
                        }
5518
                    }
5519
                    qemu_config_write(fp);
5520
                    fclose(fp);
5521
                    break;
5522
                }
5523
            }
5524
        }
5525
    }
5526

    
5527
    /* If no data_dir is specified then try to find it relative to the
5528
       executable path.  */
5529
    if (!data_dir) {
5530
        data_dir = find_datadir(argv[0]);
5531
    }
5532
    /* If all else fails use the install patch specified when building.  */
5533
    if (!data_dir) {
5534
        data_dir = CONFIG_QEMU_SHAREDIR;
5535
    }
5536

    
5537
    /*
5538
     * Default to max_cpus = smp_cpus, in case the user doesn't
5539
     * specify a max_cpus value.
5540
     */
5541
    if (!max_cpus)
5542
        max_cpus = smp_cpus;
5543

    
5544
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5545
    if (smp_cpus > machine->max_cpus) {
5546
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5547
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5548
                machine->max_cpus);
5549
        exit(1);
5550
    }
5551

    
5552
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5553
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5554

    
5555
    if (machine->no_serial) {
5556
        default_serial = 0;
5557
    }
5558
    if (machine->no_parallel) {
5559
        default_parallel = 0;
5560
    }
5561
    if (!machine->use_virtcon) {
5562
        default_virtcon = 0;
5563
    }
5564
    if (machine->no_vga) {
5565
        default_vga = 0;
5566
    }
5567
    if (machine->no_floppy) {
5568
        default_floppy = 0;
5569
    }
5570
    if (machine->no_cdrom) {
5571
        default_cdrom = 0;
5572
    }
5573
    if (machine->no_sdcard) {
5574
        default_sdcard = 0;
5575
    }
5576

    
5577
    if (display_type == DT_NOGRAPHIC) {
5578
        if (default_parallel)
5579
            add_device_config(DEV_PARALLEL, "null");
5580
        if (default_serial && default_monitor) {
5581
            add_device_config(DEV_SERIAL, "mon:stdio");
5582
        } else if (default_virtcon && default_monitor) {
5583
            add_device_config(DEV_VIRTCON, "mon:stdio");
5584
        } else {
5585
            if (default_serial)
5586
                add_device_config(DEV_SERIAL, "stdio");
5587
            if (default_virtcon)
5588
                add_device_config(DEV_VIRTCON, "stdio");
5589
            if (default_monitor)
5590
                monitor_parse("stdio", "readline");
5591
        }
5592
    } else {
5593
        if (default_serial)
5594
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
5595
        if (default_parallel)
5596
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5597
        if (default_monitor)
5598
            monitor_parse("vc:80Cx24C", "readline");
5599
        if (default_virtcon)
5600
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5601
    }
5602
    if (default_vga)
5603
        vga_interface_type = VGA_CIRRUS;
5604

    
5605
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5606
        exit(1);
5607

    
5608
#ifndef _WIN32
5609
    if (daemonize) {
5610
        pid_t pid;
5611

    
5612
        if (pipe(fds) == -1)
5613
            exit(1);
5614

    
5615
        pid = fork();
5616
        if (pid > 0) {
5617
            uint8_t status;
5618
            ssize_t len;
5619

    
5620
            close(fds[1]);
5621

    
5622
        again:
5623
            len = read(fds[0], &status, 1);
5624
            if (len == -1 && (errno == EINTR))
5625
                goto again;
5626

    
5627
            if (len != 1)
5628
                exit(1);
5629
            else if (status == 1) {
5630
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5631
                exit(1);
5632
            } else
5633
                exit(0);
5634
        } else if (pid < 0)
5635
            exit(1);
5636

    
5637
        close(fds[0]);
5638
        qemu_set_cloexec(fds[1]);
5639

    
5640
        setsid();
5641

    
5642
        pid = fork();
5643
        if (pid > 0)
5644
            exit(0);
5645
        else if (pid < 0)
5646
            exit(1);
5647

    
5648
        umask(027);
5649

    
5650
        signal(SIGTSTP, SIG_IGN);
5651
        signal(SIGTTOU, SIG_IGN);
5652
        signal(SIGTTIN, SIG_IGN);
5653
    }
5654
#endif
5655

    
5656
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5657
#ifndef _WIN32
5658
        if (daemonize) {
5659
            uint8_t status = 1;
5660
            if (write(fds[1], &status, 1) != 1) {
5661
                perror("daemonize. Writing to pipe\n");
5662
            }
5663
        } else
5664
#endif
5665
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5666
        exit(1);
5667
    }
5668

    
5669
    if (kvm_enabled()) {
5670
        int ret;
5671

    
5672
        ret = kvm_init(smp_cpus);
5673
        if (ret < 0) {
5674
            fprintf(stderr, "failed to initialize KVM\n");
5675
            exit(1);
5676
        }
5677
    }
5678

    
5679
    if (qemu_init_main_loop()) {
5680
        fprintf(stderr, "qemu_init_main_loop failed\n");
5681
        exit(1);
5682
    }
5683
    linux_boot = (kernel_filename != NULL);
5684

    
5685
    if (!linux_boot && *kernel_cmdline != '\0') {
5686
        fprintf(stderr, "-append only allowed with -kernel option\n");
5687
        exit(1);
5688
    }
5689

    
5690
    if (!linux_boot && initrd_filename != NULL) {
5691
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5692
        exit(1);
5693
    }
5694

    
5695
#ifndef _WIN32
5696
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5697
    setvbuf(stdout, NULL, _IOLBF, 0);
5698
#endif
5699

    
5700
    if (init_timer_alarm() < 0) {
5701
        fprintf(stderr, "could not initialize alarm timer\n");
5702
        exit(1);
5703
    }
5704
    if (use_icount && icount_time_shift < 0) {
5705
        use_icount = 2;
5706
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5707
           It will be corrected fairly quickly anyway.  */
5708
        icount_time_shift = 3;
5709
        init_icount_adjust();
5710
    }
5711

    
5712
#ifdef _WIN32
5713
    socket_init();
5714
#endif
5715

    
5716
    if (net_init_clients() < 0) {
5717
        exit(1);
5718
    }
5719

    
5720
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5721
    net_set_boot_mask(net_boot);
5722

    
5723
    /* init the bluetooth world */
5724
    if (foreach_device_config(DEV_BT, bt_parse))
5725
        exit(1);
5726

    
5727
    /* init the memory */
5728
    if (ram_size == 0)
5729
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5730

    
5731
    /* init the dynamic translator */
5732
    cpu_exec_init_all(tb_size * 1024 * 1024);
5733

    
5734
    bdrv_init_with_whitelist();
5735

    
5736
    blk_mig_init();
5737

    
5738
    if (default_cdrom) {
5739
        /* we always create the cdrom drive, even if no disk is there */
5740
        drive_add(NULL, CDROM_ALIAS);
5741
    }
5742

    
5743
    if (default_floppy) {
5744
        /* we always create at least one floppy */
5745
        drive_add(NULL, FD_ALIAS, 0);
5746
    }
5747

    
5748
    if (default_sdcard) {
5749
        /* we always create one sd slot, even if no card is in it */
5750
        drive_add(NULL, SD_ALIAS);
5751
    }
5752

    
5753
    /* open the virtual block devices */
5754
    if (snapshot)
5755
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5756
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5757
        exit(1);
5758

    
5759
    vmstate_register(0, &vmstate_timers ,&timers_state);
5760
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
5761
                         ram_load, NULL);
5762

    
5763
    if (nb_numa_nodes > 0) {
5764
        int i;
5765

    
5766
        if (nb_numa_nodes > smp_cpus) {
5767
            nb_numa_nodes = smp_cpus;
5768
        }
5769

    
5770
        /* If no memory size if given for any node, assume the default case
5771
         * and distribute the available memory equally across all nodes
5772
         */
5773
        for (i = 0; i < nb_numa_nodes; i++) {
5774
            if (node_mem[i] != 0)
5775
                break;
5776
        }
5777
        if (i == nb_numa_nodes) {
5778
            uint64_t usedmem = 0;
5779

    
5780
            /* On Linux, the each node's border has to be 8MB aligned,
5781
             * the final node gets the rest.
5782
             */
5783
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5784
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5785
                usedmem += node_mem[i];
5786
            }
5787
            node_mem[i] = ram_size - usedmem;
5788
        }
5789

    
5790
        for (i = 0; i < nb_numa_nodes; i++) {
5791
            if (node_cpumask[i] != 0)
5792
                break;
5793
        }
5794
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5795
         * must cope with this anyway, because there are BIOSes out there in
5796
         * real machines which also use this scheme.
5797
         */
5798
        if (i == nb_numa_nodes) {
5799
            for (i = 0; i < smp_cpus; i++) {
5800
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5801
            }
5802
        }
5803
    }
5804

    
5805
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5806
        exit(1);
5807
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5808
        exit(1);
5809
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5810
        exit(1);
5811
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5812
        exit(1);
5813

    
5814
    module_call_init(MODULE_INIT_DEVICE);
5815

    
5816
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5817
        exit(0);
5818

    
5819
    if (watchdog) {
5820
        i = select_watchdog(watchdog);
5821
        if (i > 0)
5822
            exit (i == 1 ? 1 : 0);
5823
    }
5824

    
5825
    if (machine->compat_props) {
5826
        qdev_prop_register_global_list(machine->compat_props);
5827
    }
5828
    qemu_add_globals();
5829

    
5830
    machine->init(ram_size, boot_devices,
5831
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5832

    
5833

    
5834
#ifndef _WIN32
5835
    /* must be after terminal init, SDL library changes signal handlers */
5836
    sighandler_setup();
5837
#endif
5838

    
5839
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5840
        for (i = 0; i < nb_numa_nodes; i++) {
5841
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5842
                env->numa_node = i;
5843
            }
5844
        }
5845
    }
5846

    
5847
    current_machine = machine;
5848

    
5849
    /* init USB devices */
5850
    if (usb_enabled) {
5851
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
5852
            exit(1);
5853
    }
5854

    
5855
    /* init generic devices */
5856
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5857
        exit(1);
5858

    
5859
    net_check_clients();
5860

    
5861
    /* just use the first displaystate for the moment */
5862
    ds = get_displaystate();
5863

    
5864
    if (display_type == DT_DEFAULT) {
5865
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5866
        display_type = DT_SDL;
5867
#else
5868
        display_type = DT_VNC;
5869
        vnc_display = "localhost:0,to=99";
5870
        show_vnc_port = 1;
5871
#endif
5872
    }
5873
        
5874

    
5875
    switch (display_type) {
5876
    case DT_NOGRAPHIC:
5877
        break;
5878
#if defined(CONFIG_CURSES)
5879
    case DT_CURSES:
5880
        curses_display_init(ds, full_screen);
5881
        break;
5882
#endif
5883
#if defined(CONFIG_SDL)
5884
    case DT_SDL:
5885
        sdl_display_init(ds, full_screen, no_frame);
5886
        break;
5887
#elif defined(CONFIG_COCOA)
5888
    case DT_SDL:
5889
        cocoa_display_init(ds, full_screen);
5890
        break;
5891
#endif
5892
    case DT_VNC:
5893
        vnc_display_init(ds);
5894
        if (vnc_display_open(ds, vnc_display) < 0)
5895
            exit(1);
5896

    
5897
        if (show_vnc_port) {
5898
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5899
        }
5900
        break;
5901
    default:
5902
        break;
5903
    }
5904
    dpy_resize(ds);
5905

    
5906
    dcl = ds->listeners;
5907
    while (dcl != NULL) {
5908
        if (dcl->dpy_refresh != NULL) {
5909
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5910
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5911
        }
5912
        dcl = dcl->next;
5913
    }
5914

    
5915
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5916
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5917
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5918
    }
5919

    
5920
    text_consoles_set_display(ds);
5921

    
5922
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5923
        exit(1);
5924

    
5925
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5926
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5927
                gdbstub_dev);
5928
        exit(1);
5929
    }
5930

    
5931
    qdev_machine_creation_done();
5932

    
5933
    if (rom_load_all() != 0) {
5934
        fprintf(stderr, "rom loading failed\n");
5935
        exit(1);
5936
    }
5937

    
5938
    qemu_system_reset();
5939
    if (loadvm) {
5940
        if (load_vmstate(cur_mon, loadvm) < 0) {
5941
            autostart = 0;
5942
        }
5943
    }
5944

    
5945
    if (incoming) {
5946
        qemu_start_incoming_migration(incoming);
5947
    } else if (autostart) {
5948
        vm_start();
5949
    }
5950

    
5951
#ifndef _WIN32
5952
    if (daemonize) {
5953
        uint8_t status = 0;
5954
        ssize_t len;
5955

    
5956
    again1:
5957
        len = write(fds[1], &status, 1);
5958
        if (len == -1 && (errno == EINTR))
5959
            goto again1;
5960

    
5961
        if (len != 1)
5962
            exit(1);
5963

    
5964
        if (chdir("/")) {
5965
            perror("not able to chdir to /");
5966
            exit(1);
5967
        }
5968
        TFR(fd = qemu_open("/dev/null", O_RDWR));
5969
        if (fd == -1)
5970
            exit(1);
5971
    }
5972

    
5973
    if (run_as) {
5974
        pwd = getpwnam(run_as);
5975
        if (!pwd) {
5976
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5977
            exit(1);
5978
        }
5979
    }
5980

    
5981
    if (chroot_dir) {
5982
        if (chroot(chroot_dir) < 0) {
5983
            fprintf(stderr, "chroot failed\n");
5984
            exit(1);
5985
        }
5986
        if (chdir("/")) {
5987
            perror("not able to chdir to /");
5988
            exit(1);
5989
        }
5990
    }
5991

    
5992
    if (run_as) {
5993
        if (setgid(pwd->pw_gid) < 0) {
5994
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5995
            exit(1);
5996
        }
5997
        if (setuid(pwd->pw_uid) < 0) {
5998
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5999
            exit(1);
6000
        }
6001
        if (setuid(0) != -1) {
6002
            fprintf(stderr, "Dropping privileges failed\n");
6003
            exit(1);
6004
        }
6005
    }
6006

    
6007
    if (daemonize) {
6008
        dup2(fd, 0);
6009
        dup2(fd, 1);
6010
        dup2(fd, 2);
6011

    
6012
        close(fd);
6013
    }
6014
#endif
6015

    
6016
    main_loop();
6017
    quit_timers();
6018
    net_cleanup();
6019

    
6020
    return 0;
6021
}