4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
32 /* Needed early for CONFIG_BSD etc. */
33 #include "config-host.h"
38 #include <sys/times.h>
42 #include <sys/ioctl.h>
43 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
47 #include <arpa/inet.h>
50 #include <sys/select.h>
53 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
62 #include <linux/rtc.h>
63 #include <sys/prctl.h>
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> */
70 #include <linux/ppdev.h>
71 #include <linux/parport.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>
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);
94 #if defined(__OpenBSD__)
98 #if defined(CONFIG_VDE)
99 #include <libvdeplug.h>
104 #include <mmsystem.h>
108 #if defined(__APPLE__) || defined(main)
110 int qemu_main(int argc
, char **argv
, char **envp
);
111 int main(int argc
, char **argv
)
113 return qemu_main(argc
, argv
, NULL
);
116 #define main qemu_main
118 #endif /* CONFIG_SDL */
122 #define main qemu_main
123 #endif /* CONFIG_COCOA */
126 #include "hw/boards.h"
128 #include "hw/pcmcia.h"
130 #include "hw/audiodev.h"
134 #include "hw/watchdog.h"
135 #include "hw/smbios.h"
138 #include "hw/loader.h"
141 #include "net/slirp.h"
146 #include "qemu-timer.h"
147 #include "qemu-char.h"
148 #include "cache-utils.h"
150 #include "block_int.h"
151 #include "block-migration.h"
153 #include "audio/audio.h"
154 #include "migration.h"
157 #include "qemu-option.h"
158 #include "qemu-config.h"
159 #include "qemu-objects.h"
160 #include "qemu-kvm.h"
161 #include "hw/device-assignment.h"
165 #include "exec-all.h"
167 #include "qemu_socket.h"
169 #include "slirp/libslirp.h"
171 #include "qemu-queue.h"
174 //#define DEBUG_SLIRP
176 #define DEFAULT_RAM_SIZE 128
178 #define MAX_VIRTIO_CONSOLES 1
180 static const char *data_dir
;
181 const char *bios_name
= NULL
;
182 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
183 to store the VM snapshots */
184 struct drivelist drives
= QTAILQ_HEAD_INITIALIZER(drives
);
185 struct driveoptlist driveopts
= QTAILQ_HEAD_INITIALIZER(driveopts
);
186 DriveInfo
*extboot_drive
= NULL
;
187 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
188 static DisplayState
*display_state
;
189 DisplayType display_type
= DT_DEFAULT
;
190 const char* keyboard_layout
= NULL
;
193 NICInfo nd_table
[MAX_NICS
];
196 static int rtc_utc
= 1;
197 static int rtc_date_offset
= -1; /* -1 means no change */
198 QEMUClock
*rtc_clock
;
199 int vga_interface_type
= VGA_NONE
;
201 int graphic_width
= 1024;
202 int graphic_height
= 768;
203 int graphic_depth
= 8;
205 int graphic_width
= 800;
206 int graphic_height
= 600;
207 int graphic_depth
= 15;
209 static int full_screen
= 0;
211 static int no_frame
= 0;
214 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
215 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
216 CharDriverState
*virtcon_hds
[MAX_VIRTIO_CONSOLES
];
218 int win2k_install_hack
= 0;
223 const char *assigned_devices
[MAX_DEV_ASSIGN_CMDLINE
];
224 int assigned_devices_index
;
229 const char *vnc_display
;
230 int acpi_enabled
= 1;
238 int graphic_rotate
= 0;
239 uint8_t irq0override
= 1;
243 const char *watchdog
;
244 const char *option_rom
[MAX_OPTION_ROMS
];
246 int semihosting_enabled
= 0;
247 int time_drift_fix
= 0;
248 unsigned int kvm_shadow_memory
= 0;
249 const char *mem_path
= NULL
;
251 int mem_prealloc
= 1; /* force preallocation of physical target memory */
256 const char *qemu_name
;
259 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
260 unsigned int nb_prom_envs
= 0;
261 const char *prom_envs
[MAX_PROM_ENVS
];
263 const char *nvram
= NULL
;
267 uint64_t node_mem
[MAX_NODES
];
268 uint64_t node_cpumask
[MAX_NODES
];
270 static CPUState
*cur_cpu
;
271 static CPUState
*next_cpu
;
272 static int timer_alarm_pending
= 1;
273 /* Conversion factor from emulated instructions to virtual clock ticks. */
274 static int icount_time_shift
;
275 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
276 #define MAX_ICOUNT_SHIFT 10
277 /* Compensate for varying guest execution speed. */
278 static int64_t qemu_icount_bias
;
279 static QEMUTimer
*icount_rt_timer
;
280 static QEMUTimer
*icount_vm_timer
;
281 static QEMUTimer
*nographic_timer
;
283 uint8_t qemu_uuid
[16];
285 static QEMUBootSetHandler
*boot_set_handler
;
286 static void *boot_set_opaque
;
288 static int default_serial
= 1;
289 static int default_parallel
= 1;
290 static int default_virtcon
= 1;
291 static int default_monitor
= 1;
292 static int default_vga
= 1;
293 static int default_floppy
= 1;
294 static int default_cdrom
= 1;
295 static int default_sdcard
= 1;
301 { .driver
= "isa-serial", .flag
= &default_serial
},
302 { .driver
= "isa-parallel", .flag
= &default_parallel
},
303 { .driver
= "isa-fdc", .flag
= &default_floppy
},
304 { .driver
= "ide-drive", .flag
= &default_cdrom
},
305 { .driver
= "virtio-serial-pci", .flag
= &default_virtcon
},
306 { .driver
= "virtio-serial-s390", .flag
= &default_virtcon
},
307 { .driver
= "virtio-serial", .flag
= &default_virtcon
},
308 { .driver
= "VGA", .flag
= &default_vga
},
309 { .driver
= "cirrus-vga", .flag
= &default_vga
},
310 { .driver
= "vmware-svga", .flag
= &default_vga
},
313 static int default_driver_check(QemuOpts
*opts
, void *opaque
)
315 const char *driver
= qemu_opt_get(opts
, "driver");
320 for (i
= 0; i
< ARRAY_SIZE(default_list
); i
++) {
321 if (strcmp(default_list
[i
].driver
, driver
) != 0)
323 *(default_list
[i
].flag
) = 0;
328 /***********************************************************/
329 /* x86 ISA bus support */
331 target_phys_addr_t isa_mem_base
= 0;
334 /***********************************************************/
335 void hw_error(const char *fmt
, ...)
341 fprintf(stderr
, "qemu: hardware error: ");
342 vfprintf(stderr
, fmt
, ap
);
343 fprintf(stderr
, "\n");
344 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
345 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
347 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
349 cpu_dump_state(env
, stderr
, fprintf
, 0);
356 static void set_proc_name(const char *s
)
358 #if defined(__linux__) && defined(PR_SET_NAME)
362 name
[sizeof(name
) - 1] = 0;
363 strncpy(name
, s
, sizeof(name
));
364 /* Could rewrite argv[0] too, but that's a bit more complicated.
365 This simple way is enough for `top'. */
366 prctl(PR_SET_NAME
, name
);
373 static QEMUBalloonEvent
*qemu_balloon_event
;
374 void *qemu_balloon_event_opaque
;
376 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
378 qemu_balloon_event
= func
;
379 qemu_balloon_event_opaque
= opaque
;
382 int qemu_balloon(ram_addr_t target
, MonitorCompletion cb
, void *opaque
)
384 if (qemu_balloon_event
) {
385 qemu_balloon_event(qemu_balloon_event_opaque
, target
, cb
, opaque
);
392 int qemu_balloon_status(MonitorCompletion cb
, void *opaque
)
394 if (qemu_balloon_event
) {
395 qemu_balloon_event(qemu_balloon_event_opaque
, 0, cb
, opaque
);
403 /***********************************************************/
404 /* real time host monotonic timer */
406 /* compute with 96 bit intermediate result: (a*b)/c */
407 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
412 #ifdef HOST_WORDS_BIGENDIAN
422 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
423 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
426 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
430 static int64_t get_clock_realtime(void)
434 gettimeofday(&tv
, NULL
);
435 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
440 static int64_t clock_freq
;
442 static void init_get_clock(void)
446 ret
= QueryPerformanceFrequency(&freq
);
448 fprintf(stderr
, "Could not calibrate ticks\n");
451 clock_freq
= freq
.QuadPart
;
454 static int64_t get_clock(void)
457 QueryPerformanceCounter(&ti
);
458 return muldiv64(ti
.QuadPart
, get_ticks_per_sec(), clock_freq
);
463 static int use_rt_clock
;
465 static void init_get_clock(void)
468 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
469 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
472 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
479 static int64_t get_clock(void)
481 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
482 || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
485 clock_gettime(CLOCK_MONOTONIC
, &ts
);
486 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
490 /* XXX: using gettimeofday leads to problems if the date
491 changes, so it should be avoided. */
492 return get_clock_realtime();
497 /* Return the virtual CPU time, based on the instruction counter. */
498 static int64_t cpu_get_icount(void)
501 CPUState
*env
= cpu_single_env
;;
502 icount
= qemu_icount
;
505 fprintf(stderr
, "Bad clock read\n");
506 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
508 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
511 /***********************************************************/
512 /* guest cycle counter */
514 typedef struct TimersState
{
515 int64_t cpu_ticks_prev
;
516 int64_t cpu_ticks_offset
;
517 int64_t cpu_clock_offset
;
518 int32_t cpu_ticks_enabled
;
522 TimersState timers_state
;
524 /* return the host CPU cycle counter and handle stop/restart */
525 int64_t cpu_get_ticks(void)
528 return cpu_get_icount();
530 if (!timers_state
.cpu_ticks_enabled
) {
531 return timers_state
.cpu_ticks_offset
;
534 ticks
= cpu_get_real_ticks();
535 if (timers_state
.cpu_ticks_prev
> ticks
) {
536 /* Note: non increasing ticks may happen if the host uses
538 timers_state
.cpu_ticks_offset
+= timers_state
.cpu_ticks_prev
- ticks
;
540 timers_state
.cpu_ticks_prev
= ticks
;
541 return ticks
+ timers_state
.cpu_ticks_offset
;
545 /* return the host CPU monotonic timer and handle stop/restart */
546 static int64_t cpu_get_clock(void)
549 if (!timers_state
.cpu_ticks_enabled
) {
550 return timers_state
.cpu_clock_offset
;
553 return ti
+ timers_state
.cpu_clock_offset
;
557 /* enable cpu_get_ticks() */
558 void cpu_enable_ticks(void)
560 if (!timers_state
.cpu_ticks_enabled
) {
561 timers_state
.cpu_ticks_offset
-= cpu_get_real_ticks();
562 timers_state
.cpu_clock_offset
-= get_clock();
563 timers_state
.cpu_ticks_enabled
= 1;
567 /* disable cpu_get_ticks() : the clock is stopped. You must not call
568 cpu_get_ticks() after that. */
569 void cpu_disable_ticks(void)
571 if (timers_state
.cpu_ticks_enabled
) {
572 timers_state
.cpu_ticks_offset
= cpu_get_ticks();
573 timers_state
.cpu_clock_offset
= cpu_get_clock();
574 timers_state
.cpu_ticks_enabled
= 0;
578 /***********************************************************/
581 #define QEMU_CLOCK_REALTIME 0
582 #define QEMU_CLOCK_VIRTUAL 1
583 #define QEMU_CLOCK_HOST 2
587 /* XXX: add frequency */
595 struct QEMUTimer
*next
;
598 struct qemu_alarm_timer
{
602 int (*start
)(struct qemu_alarm_timer
*t
);
603 void (*stop
)(struct qemu_alarm_timer
*t
);
604 void (*rearm
)(struct qemu_alarm_timer
*t
);
608 #define ALARM_FLAG_DYNTICKS 0x1
609 #define ALARM_FLAG_EXPIRED 0x2
611 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
613 return t
&& (t
->flags
& ALARM_FLAG_DYNTICKS
);
616 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
618 if (!alarm_has_dynticks(t
))
624 /* TODO: MIN_TIMER_REARM_US should be optimized */
625 #define MIN_TIMER_REARM_US 250
627 static struct qemu_alarm_timer
*alarm_timer
;
631 struct qemu_alarm_win32
{
634 } alarm_win32_data
= {0, -1};
636 static int win32_start_timer(struct qemu_alarm_timer
*t
);
637 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
638 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
642 static int unix_start_timer(struct qemu_alarm_timer
*t
);
643 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
647 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
648 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
649 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
651 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
652 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
654 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
655 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
657 #endif /* __linux__ */
661 /* Correlation between real and virtual time is always going to be
662 fairly approximate, so ignore small variation.
663 When the guest is idle real and virtual time will be aligned in
665 #define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
667 static void icount_adjust(void)
672 static int64_t last_delta
;
673 /* If the VM is not running, then do nothing. */
677 cur_time
= cpu_get_clock();
678 cur_icount
= qemu_get_clock(vm_clock
);
679 delta
= cur_icount
- cur_time
;
680 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
682 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
683 && icount_time_shift
> 0) {
684 /* The guest is getting too far ahead. Slow time down. */
688 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
689 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
690 /* The guest is getting too far behind. Speed time up. */
694 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
697 static void icount_adjust_rt(void * opaque
)
699 qemu_mod_timer(icount_rt_timer
,
700 qemu_get_clock(rt_clock
) + 1000);
704 static void icount_adjust_vm(void * opaque
)
706 qemu_mod_timer(icount_vm_timer
,
707 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
711 static void init_icount_adjust(void)
713 /* Have both realtime and virtual time triggers for speed adjustment.
714 The realtime trigger catches emulated time passing too slowly,
715 the virtual time trigger catches emulated time passing too fast.
716 Realtime triggers occur even when idle, so use them less frequently
718 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
719 qemu_mod_timer(icount_rt_timer
,
720 qemu_get_clock(rt_clock
) + 1000);
721 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
722 qemu_mod_timer(icount_vm_timer
,
723 qemu_get_clock(vm_clock
) + get_ticks_per_sec() / 10);
726 static struct qemu_alarm_timer alarm_timers
[] = {
729 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
730 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
731 /* HPET - if available - is preferred */
732 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
733 /* ...otherwise try RTC */
734 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
736 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
738 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
739 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
740 {"win32", 0, win32_start_timer
,
741 win32_stop_timer
, NULL
, &alarm_win32_data
},
746 static void show_available_alarms(void)
750 printf("Available alarm timers, in order of precedence:\n");
751 for (i
= 0; alarm_timers
[i
].name
; i
++)
752 printf("%s\n", alarm_timers
[i
].name
);
755 static void configure_alarms(char const *opt
)
759 int count
= ARRAY_SIZE(alarm_timers
) - 1;
762 struct qemu_alarm_timer tmp
;
764 if (!strcmp(opt
, "?")) {
765 show_available_alarms();
769 arg
= qemu_strdup(opt
);
771 /* Reorder the array */
772 name
= strtok(arg
, ",");
774 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
775 if (!strcmp(alarm_timers
[i
].name
, name
))
780 fprintf(stderr
, "Unknown clock %s\n", name
);
789 tmp
= alarm_timers
[i
];
790 alarm_timers
[i
] = alarm_timers
[cur
];
791 alarm_timers
[cur
] = tmp
;
795 name
= strtok(NULL
, ",");
801 /* Disable remaining timers */
802 for (i
= cur
; i
< count
; i
++)
803 alarm_timers
[i
].name
= NULL
;
805 show_available_alarms();
810 #define QEMU_NUM_CLOCKS 3
814 QEMUClock
*host_clock
;
816 static QEMUTimer
*active_timers
[QEMU_NUM_CLOCKS
];
818 static QEMUClock
*qemu_new_clock(int type
)
821 clock
= qemu_mallocz(sizeof(QEMUClock
));
826 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
830 ts
= qemu_mallocz(sizeof(QEMUTimer
));
837 void qemu_free_timer(QEMUTimer
*ts
)
842 /* stop a timer, but do not dealloc it */
843 void qemu_del_timer(QEMUTimer
*ts
)
847 /* NOTE: this code must be signal safe because
848 qemu_timer_expired() can be called from a signal. */
849 pt
= &active_timers
[ts
->clock
->type
];
862 /* modify the current timer so that it will be fired when current_time
863 >= expire_time. The corresponding callback will be called. */
864 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
870 /* add the timer in the sorted list */
871 /* NOTE: this code must be signal safe because
872 qemu_timer_expired() can be called from a signal. */
873 pt
= &active_timers
[ts
->clock
->type
];
878 if (t
->expire_time
> expire_time
)
882 ts
->expire_time
= expire_time
;
886 /* Rearm if necessary */
887 if (pt
== &active_timers
[ts
->clock
->type
]) {
888 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
889 qemu_rearm_alarm_timer(alarm_timer
);
891 /* Interrupt execution to force deadline recalculation. */
897 int qemu_timer_pending(QEMUTimer
*ts
)
900 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
907 int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
911 return (timer_head
->expire_time
<= current_time
);
914 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
920 if (!ts
|| ts
->expire_time
> current_time
)
922 /* remove timer from the list before calling the callback */
923 *ptimer_head
= ts
->next
;
926 /* run the callback (the timer list can be modified) */
931 int64_t qemu_get_clock(QEMUClock
*clock
)
933 switch(clock
->type
) {
934 case QEMU_CLOCK_REALTIME
:
935 return get_clock() / 1000000;
937 case QEMU_CLOCK_VIRTUAL
:
939 return cpu_get_icount();
941 return cpu_get_clock();
943 case QEMU_CLOCK_HOST
:
944 return get_clock_realtime();
948 static void init_clocks(void)
951 rt_clock
= qemu_new_clock(QEMU_CLOCK_REALTIME
);
952 vm_clock
= qemu_new_clock(QEMU_CLOCK_VIRTUAL
);
953 host_clock
= qemu_new_clock(QEMU_CLOCK_HOST
);
955 rtc_clock
= host_clock
;
959 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
961 uint64_t expire_time
;
963 if (qemu_timer_pending(ts
)) {
964 expire_time
= ts
->expire_time
;
968 qemu_put_be64(f
, expire_time
);
971 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
973 uint64_t expire_time
;
975 expire_time
= qemu_get_be64(f
);
976 if (expire_time
!= -1) {
977 qemu_mod_timer(ts
, expire_time
);
983 static const VMStateDescription vmstate_timers
= {
986 .minimum_version_id
= 1,
987 .minimum_version_id_old
= 1,
988 .fields
= (VMStateField
[]) {
989 VMSTATE_INT64(cpu_ticks_offset
, TimersState
),
990 VMSTATE_INT64(dummy
, TimersState
),
991 VMSTATE_INT64_V(cpu_clock_offset
, TimersState
, 2),
992 VMSTATE_END_OF_LIST()
996 static void qemu_event_increment(void);
999 static void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1000 DWORD_PTR dwUser
, DWORD_PTR dw1
,
1003 static void host_alarm_handler(int host_signum
)
1007 #define DISP_FREQ 1000
1009 static int64_t delta_min
= INT64_MAX
;
1010 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1012 ti
= qemu_get_clock(vm_clock
);
1013 if (last_clock
!= 0) {
1014 delta
= ti
- last_clock
;
1015 if (delta
< delta_min
)
1017 if (delta
> delta_max
)
1020 if (++count
== DISP_FREQ
) {
1021 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1022 muldiv64(delta_min
, 1000000, get_ticks_per_sec()),
1023 muldiv64(delta_max
, 1000000, get_ticks_per_sec()),
1024 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, get_ticks_per_sec()),
1025 (double)get_ticks_per_sec() / ((double)delta_cum
/ DISP_FREQ
));
1027 delta_min
= INT64_MAX
;
1035 if (alarm_has_dynticks(alarm_timer
) ||
1037 qemu_timer_expired(active_timers
[QEMU_CLOCK_VIRTUAL
],
1038 qemu_get_clock(vm_clock
))) ||
1039 qemu_timer_expired(active_timers
[QEMU_CLOCK_REALTIME
],
1040 qemu_get_clock(rt_clock
)) ||
1041 qemu_timer_expired(active_timers
[QEMU_CLOCK_HOST
],
1042 qemu_get_clock(host_clock
))) {
1043 qemu_event_increment();
1044 if (alarm_timer
) alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1046 #ifndef CONFIG_IOTHREAD
1048 /* stop the currently executing cpu because a timer occured */
1052 timer_alarm_pending
= 1;
1053 qemu_notify_event();
1057 static int64_t qemu_next_deadline(void)
1059 /* To avoid problems with overflow limit this to 2^32. */
1060 int64_t delta
= INT32_MAX
;
1062 if (active_timers
[QEMU_CLOCK_VIRTUAL
]) {
1063 delta
= active_timers
[QEMU_CLOCK_VIRTUAL
]->expire_time
-
1064 qemu_get_clock(vm_clock
);
1066 if (active_timers
[QEMU_CLOCK_HOST
]) {
1067 int64_t hdelta
= active_timers
[QEMU_CLOCK_HOST
]->expire_time
-
1068 qemu_get_clock(host_clock
);
1079 #if defined(__linux__)
1080 static uint64_t qemu_next_deadline_dyntick(void)
1088 delta
= (qemu_next_deadline() + 999) / 1000;
1090 if (active_timers
[QEMU_CLOCK_REALTIME
]) {
1091 rtdelta
= (active_timers
[QEMU_CLOCK_REALTIME
]->expire_time
-
1092 qemu_get_clock(rt_clock
))*1000;
1093 if (rtdelta
< delta
)
1097 if (delta
< MIN_TIMER_REARM_US
)
1098 delta
= MIN_TIMER_REARM_US
;
1106 /* Sets a specific flag */
1107 static int fcntl_setfl(int fd
, int flag
)
1111 flags
= fcntl(fd
, F_GETFL
);
1115 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1)
1121 #if defined(__linux__)
1123 #define RTC_FREQ 1024
1125 static void enable_sigio_timer(int fd
)
1127 struct sigaction act
;
1130 sigfillset(&act
.sa_mask
);
1132 act
.sa_handler
= host_alarm_handler
;
1134 sigaction(SIGIO
, &act
, NULL
);
1135 fcntl_setfl(fd
, O_ASYNC
);
1136 fcntl(fd
, F_SETOWN
, getpid());
1139 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1141 struct hpet_info info
;
1144 fd
= qemu_open("/dev/hpet", O_RDONLY
);
1149 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1151 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1152 "error, but for better emulation accuracy type:\n"
1153 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1157 /* Check capabilities */
1158 r
= ioctl(fd
, HPET_INFO
, &info
);
1162 /* Enable periodic mode */
1163 r
= ioctl(fd
, HPET_EPI
, 0);
1164 if (info
.hi_flags
&& (r
< 0))
1167 /* Enable interrupt */
1168 r
= ioctl(fd
, HPET_IE_ON
, 0);
1172 enable_sigio_timer(fd
);
1173 t
->priv
= (void *)(long)fd
;
1181 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1183 int fd
= (long)t
->priv
;
1188 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1191 unsigned long current_rtc_freq
= 0;
1193 TFR(rtc_fd
= qemu_open("/dev/rtc", O_RDONLY
));
1196 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1197 if (current_rtc_freq
!= RTC_FREQ
&&
1198 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1199 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1200 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1201 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1204 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1210 enable_sigio_timer(rtc_fd
);
1212 t
->priv
= (void *)(long)rtc_fd
;
1217 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1219 int rtc_fd
= (long)t
->priv
;
1224 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1228 struct sigaction act
;
1230 sigfillset(&act
.sa_mask
);
1232 act
.sa_handler
= host_alarm_handler
;
1234 sigaction(SIGALRM
, &act
, NULL
);
1237 * Initialize ev struct to 0 to avoid valgrind complaining
1238 * about uninitialized data in timer_create call
1240 memset(&ev
, 0, sizeof(ev
));
1241 ev
.sigev_value
.sival_int
= 0;
1242 ev
.sigev_notify
= SIGEV_SIGNAL
;
1243 ev
.sigev_signo
= SIGALRM
;
1245 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1246 perror("timer_create");
1248 /* disable dynticks */
1249 fprintf(stderr
, "Dynamic Ticks disabled\n");
1254 t
->priv
= (void *)(long)host_timer
;
1259 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1261 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1263 timer_delete(host_timer
);
1266 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1268 timer_t host_timer
= (timer_t
)(long)t
->priv
;
1269 struct itimerspec timeout
;
1270 int64_t nearest_delta_us
= INT64_MAX
;
1273 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1274 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1275 !active_timers
[QEMU_CLOCK_HOST
])
1278 nearest_delta_us
= qemu_next_deadline_dyntick();
1280 /* check whether a timer is already running */
1281 if (timer_gettime(host_timer
, &timeout
)) {
1283 fprintf(stderr
, "Internal timer error: aborting\n");
1286 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1287 if (current_us
&& current_us
<= nearest_delta_us
)
1290 timeout
.it_interval
.tv_sec
= 0;
1291 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1292 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1293 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1294 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1296 fprintf(stderr
, "Internal timer error: aborting\n");
1301 #endif /* defined(__linux__) */
1303 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1305 struct sigaction act
;
1306 struct itimerval itv
;
1310 sigfillset(&act
.sa_mask
);
1312 act
.sa_handler
= host_alarm_handler
;
1314 sigaction(SIGALRM
, &act
, NULL
);
1316 itv
.it_interval
.tv_sec
= 0;
1317 /* for i386 kernel 2.6 to get 1 ms */
1318 itv
.it_interval
.tv_usec
= 999;
1319 itv
.it_value
.tv_sec
= 0;
1320 itv
.it_value
.tv_usec
= 10 * 1000;
1322 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1329 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1331 struct itimerval itv
;
1333 memset(&itv
, 0, sizeof(itv
));
1334 setitimer(ITIMER_REAL
, &itv
, NULL
);
1337 #endif /* !defined(_WIN32) */
1342 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1345 struct qemu_alarm_win32
*data
= t
->priv
;
1348 memset(&tc
, 0, sizeof(tc
));
1349 timeGetDevCaps(&tc
, sizeof(tc
));
1351 if (data
->period
< tc
.wPeriodMin
)
1352 data
->period
= tc
.wPeriodMin
;
1354 timeBeginPeriod(data
->period
);
1356 flags
= TIME_CALLBACK_FUNCTION
;
1357 if (alarm_has_dynticks(t
))
1358 flags
|= TIME_ONESHOT
;
1360 flags
|= TIME_PERIODIC
;
1362 data
->timerId
= timeSetEvent(1, // interval (ms)
1363 data
->period
, // resolution
1364 host_alarm_handler
, // function
1365 (DWORD
)t
, // parameter
1368 if (!data
->timerId
) {
1369 fprintf(stderr
, "Failed to initialize win32 alarm timer: %ld\n",
1371 timeEndPeriod(data
->period
);
1378 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1380 struct qemu_alarm_win32
*data
= t
->priv
;
1382 timeKillEvent(data
->timerId
);
1383 timeEndPeriod(data
->period
);
1386 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1388 struct qemu_alarm_win32
*data
= t
->priv
;
1390 if (!active_timers
[QEMU_CLOCK_REALTIME
] &&
1391 !active_timers
[QEMU_CLOCK_VIRTUAL
] &&
1392 !active_timers
[QEMU_CLOCK_HOST
])
1395 timeKillEvent(data
->timerId
);
1397 data
->timerId
= timeSetEvent(1,
1401 TIME_ONESHOT
| TIME_PERIODIC
);
1403 if (!data
->timerId
) {
1404 fprintf(stderr
, "Failed to re-arm win32 alarm timer %ld\n",
1407 timeEndPeriod(data
->period
);
1414 static int init_timer_alarm(void)
1416 struct qemu_alarm_timer
*t
= NULL
;
1419 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1420 t
= &alarm_timers
[i
];
1440 static void quit_timers(void)
1442 alarm_timer
->stop(alarm_timer
);
1446 /***********************************************************/
1447 /* host time/date access */
1448 void qemu_get_timedate(struct tm
*tm
, int offset
)
1455 if (rtc_date_offset
== -1) {
1459 ret
= localtime(&ti
);
1461 ti
-= rtc_date_offset
;
1465 memcpy(tm
, ret
, sizeof(struct tm
));
1468 int qemu_timedate_diff(struct tm
*tm
)
1472 if (rtc_date_offset
== -1)
1474 seconds
= mktimegm(tm
);
1476 seconds
= mktime(tm
);
1478 seconds
= mktimegm(tm
) + rtc_date_offset
;
1480 return seconds
- time(NULL
);
1483 static void configure_rtc_date_offset(const char *startdate
, int legacy
)
1485 time_t rtc_start_date
;
1488 if (!strcmp(startdate
, "now") && legacy
) {
1489 rtc_date_offset
= -1;
1491 if (sscanf(startdate
, "%d-%d-%dT%d:%d:%d",
1499 } else if (sscanf(startdate
, "%d-%d-%d",
1502 &tm
.tm_mday
) == 3) {
1511 rtc_start_date
= mktimegm(&tm
);
1512 if (rtc_start_date
== -1) {
1514 fprintf(stderr
, "Invalid date format. Valid formats are:\n"
1515 "'2006-06-17T16:01:21' or '2006-06-17'\n");
1518 rtc_date_offset
= time(NULL
) - rtc_start_date
;
1522 static void configure_rtc(QemuOpts
*opts
)
1526 value
= qemu_opt_get(opts
, "base");
1528 if (!strcmp(value
, "utc")) {
1530 } else if (!strcmp(value
, "localtime")) {
1533 configure_rtc_date_offset(value
, 0);
1536 value
= qemu_opt_get(opts
, "clock");
1538 if (!strcmp(value
, "host")) {
1539 rtc_clock
= host_clock
;
1540 } else if (!strcmp(value
, "vm")) {
1541 rtc_clock
= vm_clock
;
1543 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1547 #ifdef CONFIG_TARGET_I386
1548 value
= qemu_opt_get(opts
, "driftfix");
1550 if (!strcmp(buf
, "slew")) {
1552 } else if (!strcmp(buf
, "none")) {
1555 fprintf(stderr
, "qemu: invalid option value '%s'\n", value
);
1563 static void socket_cleanup(void)
1568 static int socket_init(void)
1573 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1575 err
= WSAGetLastError();
1576 fprintf(stderr
, "WSAStartup: %d\n", err
);
1579 atexit(socket_cleanup
);
1584 /***********************************************************/
1585 /* Bluetooth support */
1588 static struct HCIInfo
*hci_table
[MAX_NICS
];
1590 static struct bt_vlan_s
{
1591 struct bt_scatternet_s net
;
1593 struct bt_vlan_s
*next
;
1596 /* find or alloc a new bluetooth "VLAN" */
1597 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
1599 struct bt_vlan_s
**pvlan
, *vlan
;
1600 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
1604 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
1606 pvlan
= &first_bt_vlan
;
1607 while (*pvlan
!= NULL
)
1608 pvlan
= &(*pvlan
)->next
;
1613 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
1617 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
1622 static struct HCIInfo null_hci
= {
1623 .cmd_send
= null_hci_send
,
1624 .sco_send
= null_hci_send
,
1625 .acl_send
= null_hci_send
,
1626 .bdaddr_set
= null_hci_addr_set
,
1629 struct HCIInfo
*qemu_next_hci(void)
1631 if (cur_hci
== nb_hcis
)
1634 return hci_table
[cur_hci
++];
1637 static struct HCIInfo
*hci_init(const char *str
)
1640 struct bt_scatternet_s
*vlan
= 0;
1642 if (!strcmp(str
, "null"))
1645 else if (!strncmp(str
, "host", 4) && (str
[4] == '\0' || str
[4] == ':'))
1647 return bt_host_hci(str
[4] ? str
+ 5 : "hci0");
1648 else if (!strncmp(str
, "hci", 3)) {
1651 if (!strncmp(str
+ 3, ",vlan=", 6)) {
1652 vlan
= qemu_find_bt_vlan(strtol(str
+ 9, &endp
, 0));
1657 vlan
= qemu_find_bt_vlan(0);
1659 return bt_new_hci(vlan
);
1662 fprintf(stderr
, "qemu: Unknown bluetooth HCI `%s'.\n", str
);
1667 static int bt_hci_parse(const char *str
)
1669 struct HCIInfo
*hci
;
1672 if (nb_hcis
>= MAX_NICS
) {
1673 fprintf(stderr
, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS
);
1677 hci
= hci_init(str
);
1686 bdaddr
.b
[5] = 0x56 + nb_hcis
;
1687 hci
->bdaddr_set(hci
, bdaddr
.b
);
1689 hci_table
[nb_hcis
++] = hci
;
1694 static void bt_vhci_add(int vlan_id
)
1696 struct bt_scatternet_s
*vlan
= qemu_find_bt_vlan(vlan_id
);
1699 fprintf(stderr
, "qemu: warning: adding a VHCI to "
1700 "an empty scatternet %i\n", vlan_id
);
1702 bt_vhci_init(bt_new_hci(vlan
));
1705 static struct bt_device_s
*bt_device_add(const char *opt
)
1707 struct bt_scatternet_s
*vlan
;
1709 char *endp
= strstr(opt
, ",vlan=");
1710 int len
= (endp
? endp
- opt
: strlen(opt
)) + 1;
1713 pstrcpy(devname
, MIN(sizeof(devname
), len
), opt
);
1716 vlan_id
= strtol(endp
+ 6, &endp
, 0);
1718 fprintf(stderr
, "qemu: unrecognised bluetooth vlan Id\n");
1723 vlan
= qemu_find_bt_vlan(vlan_id
);
1726 fprintf(stderr
, "qemu: warning: adding a slave device to "
1727 "an empty scatternet %i\n", vlan_id
);
1729 if (!strcmp(devname
, "keyboard"))
1730 return bt_keyboard_init(vlan
);
1732 fprintf(stderr
, "qemu: unsupported bluetooth device `%s'\n", devname
);
1736 static int bt_parse(const char *opt
)
1738 const char *endp
, *p
;
1741 if (strstart(opt
, "hci", &endp
)) {
1742 if (!*endp
|| *endp
== ',') {
1744 if (!strstart(endp
, ",vlan=", 0))
1747 return bt_hci_parse(opt
);
1749 } else if (strstart(opt
, "vhci", &endp
)) {
1750 if (!*endp
|| *endp
== ',') {
1752 if (strstart(endp
, ",vlan=", &p
)) {
1753 vlan
= strtol(p
, (char **) &endp
, 0);
1755 fprintf(stderr
, "qemu: bad scatternet '%s'\n", p
);
1759 fprintf(stderr
, "qemu: bad parameter '%s'\n", endp
+ 1);
1768 } else if (strstart(opt
, "device:", &endp
))
1769 return !bt_device_add(endp
);
1771 fprintf(stderr
, "qemu: bad bluetooth parameter '%s'\n", opt
);
1775 /***********************************************************/
1776 /* QEMU Block devices */
1778 #define HD_ALIAS "index=%d,media=disk"
1779 #define CDROM_ALIAS "index=2,media=cdrom"
1780 #define FD_ALIAS "index=%d,if=floppy"
1781 #define PFLASH_ALIAS "if=pflash"
1782 #define MTD_ALIAS "if=mtd"
1783 #define SD_ALIAS "index=0,if=sd"
1785 QemuOpts
*drive_add(const char *file
, const char *fmt
, ...)
1792 vsnprintf(optstr
, sizeof(optstr
), fmt
, ap
);
1795 opts
= qemu_opts_parse(&qemu_drive_opts
, optstr
, NULL
);
1797 fprintf(stderr
, "%s: huh? duplicate? (%s)\n",
1798 __FUNCTION__
, optstr
);
1802 qemu_opt_set(opts
, "file", file
);
1806 DriveInfo
*drive_get(BlockInterfaceType type
, int bus
, int unit
)
1810 /* seek interface, bus and unit */
1812 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1813 if (dinfo
->type
== type
&&
1814 dinfo
->bus
== bus
&&
1815 dinfo
->unit
== unit
)
1822 DriveInfo
*drive_get_by_id(const char *id
)
1826 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1827 if (strcmp(id
, dinfo
->id
))
1834 int drive_get_max_bus(BlockInterfaceType type
)
1840 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1841 if(dinfo
->type
== type
&&
1842 dinfo
->bus
> max_bus
)
1843 max_bus
= dinfo
->bus
;
1848 const char *drive_get_serial(BlockDriverState
*bdrv
)
1852 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1853 if (dinfo
->bdrv
== bdrv
)
1854 return dinfo
->serial
;
1860 BlockInterfaceErrorAction
drive_get_on_error(
1861 BlockDriverState
*bdrv
, int is_read
)
1865 QTAILQ_FOREACH(dinfo
, &drives
, next
) {
1866 if (dinfo
->bdrv
== bdrv
)
1867 return is_read
? dinfo
->on_read_error
: dinfo
->on_write_error
;
1870 return is_read
? BLOCK_ERR_REPORT
: BLOCK_ERR_STOP_ENOSPC
;
1873 static void bdrv_format_print(void *opaque
, const char *name
)
1875 fprintf(stderr
, " %s", name
);
1878 void drive_uninit(DriveInfo
*dinfo
)
1880 qemu_opts_del(dinfo
->opts
);
1881 bdrv_delete(dinfo
->bdrv
);
1882 QTAILQ_REMOVE(&drives
, dinfo
, next
);
1886 static int parse_block_error_action(const char *buf
, int is_read
)
1888 if (!strcmp(buf
, "ignore")) {
1889 return BLOCK_ERR_IGNORE
;
1890 } else if (!is_read
&& !strcmp(buf
, "enospc")) {
1891 return BLOCK_ERR_STOP_ENOSPC
;
1892 } else if (!strcmp(buf
, "stop")) {
1893 return BLOCK_ERR_STOP_ANY
;
1894 } else if (!strcmp(buf
, "report")) {
1895 return BLOCK_ERR_REPORT
;
1897 fprintf(stderr
, "qemu: '%s' invalid %s error action\n",
1898 buf
, is_read
? "read" : "write");
1903 DriveInfo
*drive_init(QemuOpts
*opts
, void *opaque
,
1907 const char *file
= NULL
;
1910 const char *mediastr
= "";
1911 BlockInterfaceType type
;
1912 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
1913 int bus_id
, unit_id
;
1914 int cyls
, heads
, secs
, translation
;
1915 BlockDriver
*drv
= NULL
;
1916 QEMUMachine
*machine
= opaque
;
1923 int on_read_error
, on_write_error
;
1924 const char *devaddr
;
1931 translation
= BIOS_ATA_TRANSLATION_AUTO
;
1934 if (machine
&& machine
->use_scsi
) {
1936 max_devs
= MAX_SCSI_DEVS
;
1937 pstrcpy(devname
, sizeof(devname
), "scsi");
1940 max_devs
= MAX_IDE_DEVS
;
1941 pstrcpy(devname
, sizeof(devname
), "ide");
1945 /* extract parameters */
1946 bus_id
= qemu_opt_get_number(opts
, "bus", 0);
1947 unit_id
= qemu_opt_get_number(opts
, "unit", -1);
1948 index
= qemu_opt_get_number(opts
, "index", -1);
1950 cyls
= qemu_opt_get_number(opts
, "cyls", 0);
1951 heads
= qemu_opt_get_number(opts
, "heads", 0);
1952 secs
= qemu_opt_get_number(opts
, "secs", 0);
1954 snapshot
= qemu_opt_get_bool(opts
, "snapshot", 0);
1955 ro
= qemu_opt_get_bool(opts
, "readonly", 0);
1957 file
= qemu_opt_get(opts
, "file");
1958 serial
= qemu_opt_get(opts
, "serial");
1960 if ((buf
= qemu_opt_get(opts
, "if")) != NULL
) {
1961 pstrcpy(devname
, sizeof(devname
), buf
);
1962 if (!strcmp(buf
, "ide")) {
1964 max_devs
= MAX_IDE_DEVS
;
1965 } else if (!strcmp(buf
, "scsi")) {
1967 max_devs
= MAX_SCSI_DEVS
;
1968 } else if (!strcmp(buf
, "floppy")) {
1971 } else if (!strcmp(buf
, "pflash")) {
1974 } else if (!strcmp(buf
, "mtd")) {
1977 } else if (!strcmp(buf
, "sd")) {
1980 } else if (!strcmp(buf
, "virtio")) {
1983 } else if (!strcmp(buf
, "xen")) {
1986 } else if (!strcmp(buf
, "none")) {
1990 fprintf(stderr
, "qemu: unsupported bus type '%s'\n", buf
);
1995 if (cyls
|| heads
|| secs
) {
1996 if (cyls
< 1 || (type
== IF_IDE
&& cyls
> 16383)) {
1997 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", buf
);
2000 if (heads
< 1 || (type
== IF_IDE
&& heads
> 16)) {
2001 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", buf
);
2004 if (secs
< 1 || (type
== IF_IDE
&& secs
> 63)) {
2005 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", buf
);
2010 if ((buf
= qemu_opt_get(opts
, "trans")) != NULL
) {
2013 "qemu: '%s' trans must be used with cyls,heads and secs\n",
2017 if (!strcmp(buf
, "none"))
2018 translation
= BIOS_ATA_TRANSLATION_NONE
;
2019 else if (!strcmp(buf
, "lba"))
2020 translation
= BIOS_ATA_TRANSLATION_LBA
;
2021 else if (!strcmp(buf
, "auto"))
2022 translation
= BIOS_ATA_TRANSLATION_AUTO
;
2024 fprintf(stderr
, "qemu: '%s' invalid translation type\n", buf
);
2029 if ((buf
= qemu_opt_get(opts
, "media")) != NULL
) {
2030 if (!strcmp(buf
, "disk")) {
2032 } else if (!strcmp(buf
, "cdrom")) {
2033 if (cyls
|| secs
|| heads
) {
2035 "qemu: '%s' invalid physical CHS format\n", buf
);
2038 media
= MEDIA_CDROM
;
2040 fprintf(stderr
, "qemu: '%s' invalid media\n", buf
);
2045 if ((buf
= qemu_opt_get(opts
, "cache")) != NULL
) {
2046 if (!strcmp(buf
, "off") || !strcmp(buf
, "none"))
2048 else if (!strcmp(buf
, "writethrough"))
2050 else if (!strcmp(buf
, "writeback"))
2053 fprintf(stderr
, "qemu: invalid cache option\n");
2058 #ifdef CONFIG_LINUX_AIO
2059 if ((buf
= qemu_opt_get(opts
, "aio")) != NULL
) {
2060 if (!strcmp(buf
, "threads"))
2062 else if (!strcmp(buf
, "native"))
2065 fprintf(stderr
, "qemu: invalid aio option\n");
2071 if ((buf
= qemu_opt_get(opts
, "format")) != NULL
) {
2072 if (strcmp(buf
, "?") == 0) {
2073 fprintf(stderr
, "qemu: Supported formats:");
2074 bdrv_iterate_format(bdrv_format_print
, NULL
);
2075 fprintf(stderr
, "\n");
2078 drv
= bdrv_find_whitelisted_format(buf
);
2080 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
2085 is_extboot
= qemu_opt_get_bool(opts
, "boot", 0);
2086 if (is_extboot
&& extboot_drive
) {
2087 fprintf(stderr
, "qemu: two bootable drives specified\n");
2091 on_write_error
= BLOCK_ERR_STOP_ENOSPC
;
2092 if ((buf
= qemu_opt_get(opts
, "werror")) != NULL
) {
2093 if (type
!= IF_IDE
&& type
!= IF_SCSI
&& type
!= IF_VIRTIO
) {
2094 fprintf(stderr
, "werror is no supported by this format\n");
2098 on_write_error
= parse_block_error_action(buf
, 0);
2099 if (on_write_error
< 0) {
2104 on_read_error
= BLOCK_ERR_REPORT
;
2105 if ((buf
= qemu_opt_get(opts
, "rerror")) != NULL
) {
2106 if (type
!= IF_IDE
&& type
!= IF_VIRTIO
) {
2107 fprintf(stderr
, "rerror is no supported by this format\n");
2111 on_read_error
= parse_block_error_action(buf
, 1);
2112 if (on_read_error
< 0) {
2117 if ((devaddr
= qemu_opt_get(opts
, "addr")) != NULL
) {
2118 if (type
!= IF_VIRTIO
) {
2119 fprintf(stderr
, "addr is not supported\n");
2124 /* compute bus and unit according index */
2127 if (bus_id
!= 0 || unit_id
!= -1) {
2129 "qemu: index cannot be used with bus and unit\n");
2137 unit_id
= index
% max_devs
;
2138 bus_id
= index
/ max_devs
;
2142 /* if user doesn't specify a unit_id,
2143 * try to find the first free
2146 if (unit_id
== -1) {
2148 while (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2150 if (max_devs
&& unit_id
>= max_devs
) {
2151 unit_id
-= max_devs
;
2159 if (max_devs
&& unit_id
>= max_devs
) {
2160 fprintf(stderr
, "qemu: unit %d too big (max is %d)\n",
2161 unit_id
, max_devs
- 1);
2166 * ignore multiple definitions
2169 if (drive_get(type
, bus_id
, unit_id
) != NULL
) {
2176 dinfo
= qemu_mallocz(sizeof(*dinfo
));
2177 if ((buf
= qemu_opts_id(opts
)) != NULL
) {
2178 dinfo
->id
= qemu_strdup(buf
);
2180 /* no id supplied -> create one */
2181 dinfo
->id
= qemu_mallocz(32);
2182 if (type
== IF_IDE
|| type
== IF_SCSI
)
2183 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
2185 snprintf(dinfo
->id
, 32, "%s%i%s%i",
2186 devname
, bus_id
, mediastr
, unit_id
);
2188 snprintf(dinfo
->id
, 32, "%s%s%i",
2189 devname
, mediastr
, unit_id
);
2191 dinfo
->bdrv
= bdrv_new(dinfo
->id
);
2192 dinfo
->devaddr
= devaddr
;
2194 dinfo
->bus
= bus_id
;
2195 dinfo
->unit
= unit_id
;
2196 dinfo
->on_read_error
= on_read_error
;
2197 dinfo
->on_write_error
= on_write_error
;
2200 strncpy(dinfo
->serial
, serial
, sizeof(serial
));
2201 QTAILQ_INSERT_TAIL(&drives
, dinfo
, next
);
2203 extboot_drive
= dinfo
;
2214 bdrv_set_geometry_hint(dinfo
->bdrv
, cyls
, heads
, secs
);
2215 bdrv_set_translation_hint(dinfo
->bdrv
, translation
);
2219 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_CDROM
);
2224 /* FIXME: This isn't really a floppy, but it's a reasonable
2227 bdrv_set_type_hint(dinfo
->bdrv
, BDRV_TYPE_FLOPPY
);
2233 /* add virtio block device */
2234 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
2235 qemu_opt_set(opts
, "driver", "virtio-blk-pci");
2236 qemu_opt_set(opts
, "drive", dinfo
->id
);
2238 qemu_opt_set(opts
, "addr", devaddr
);
2249 bdrv_flags
|= BDRV_O_SNAPSHOT
;
2250 cache
= 2; /* always use write-back with snapshot */
2252 if (cache
== 0) /* no caching */
2253 bdrv_flags
|= BDRV_O_NOCACHE
;
2254 else if (cache
== 2) /* write-back */
2255 bdrv_flags
|= BDRV_O_CACHE_WB
;
2258 bdrv_flags
|= BDRV_O_NATIVE_AIO
;
2260 bdrv_flags
&= ~BDRV_O_NATIVE_AIO
;
2264 if (type
!= IF_SCSI
&& type
!= IF_VIRTIO
&& type
!= IF_FLOPPY
) {
2265 fprintf(stderr
, "qemu: readonly flag not supported for drive with this interface\n");
2270 * cdrom is read-only. Set it now, after above interface checking
2271 * since readonly attribute not explicitly required, so no error.
2273 if (media
== MEDIA_CDROM
) {
2276 bdrv_flags
|= ro
? 0 : BDRV_O_RDWR
;
2278 if (bdrv_open2(dinfo
->bdrv
, file
, bdrv_flags
, drv
) < 0) {
2279 fprintf(stderr
, "qemu: could not open disk image %s: %s\n",
2280 file
, strerror(errno
));
2284 if (bdrv_key_required(dinfo
->bdrv
))
2290 static int drive_init_func(QemuOpts
*opts
, void *opaque
)
2292 QEMUMachine
*machine
= opaque
;
2293 int fatal_error
= 0;
2295 if (drive_init(opts
, machine
, &fatal_error
) == NULL
) {
2302 static int drive_enable_snapshot(QemuOpts
*opts
, void *opaque
)
2304 if (NULL
== qemu_opt_get(opts
, "snapshot")) {
2305 qemu_opt_set(opts
, "snapshot", "on");
2310 void qemu_register_boot_set(QEMUBootSetHandler
*func
, void *opaque
)
2312 boot_set_handler
= func
;
2313 boot_set_opaque
= opaque
;
2316 int qemu_boot_set(const char *boot_devices
)
2318 if (!boot_set_handler
) {
2321 return boot_set_handler(boot_set_opaque
, boot_devices
);
2324 static int parse_bootdevices(char *devices
)
2326 /* We just do some generic consistency checks */
2330 for (p
= devices
; *p
!= '\0'; p
++) {
2331 /* Allowed boot devices are:
2332 * a-b: floppy disk drives
2333 * c-f: IDE disk drives
2334 * g-m: machine implementation dependant drives
2335 * n-p: network devices
2336 * It's up to each machine implementation to check if the given boot
2337 * devices match the actual hardware implementation and firmware
2340 if (*p
< 'a' || *p
> 'p') {
2341 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
2344 if (bitmap
& (1 << (*p
- 'a'))) {
2345 fprintf(stderr
, "Boot device '%c' was given twice\n", *p
);
2348 bitmap
|= 1 << (*p
- 'a');
2353 static void restore_boot_devices(void *opaque
)
2355 char *standard_boot_devices
= opaque
;
2357 qemu_boot_set(standard_boot_devices
);
2359 qemu_unregister_reset(restore_boot_devices
, standard_boot_devices
);
2360 qemu_free(standard_boot_devices
);
2363 static void numa_add(const char *optarg
)
2367 unsigned long long value
, endvalue
;
2370 optarg
= get_opt_name(option
, 128, optarg
, ',') + 1;
2371 if (!strcmp(option
, "node")) {
2372 if (get_param_value(option
, 128, "nodeid", optarg
) == 0) {
2373 nodenr
= nb_numa_nodes
;
2375 nodenr
= strtoull(option
, NULL
, 10);
2378 if (get_param_value(option
, 128, "mem", optarg
) == 0) {
2379 node_mem
[nodenr
] = 0;
2381 value
= strtoull(option
, &endptr
, 0);
2383 case 0: case 'M': case 'm':
2390 node_mem
[nodenr
] = value
;
2392 if (get_param_value(option
, 128, "cpus", optarg
) == 0) {
2393 node_cpumask
[nodenr
] = 0;
2395 value
= strtoull(option
, &endptr
, 10);
2398 fprintf(stderr
, "only 64 CPUs in NUMA mode supported.\n");
2400 if (*endptr
== '-') {
2401 endvalue
= strtoull(endptr
+1, &endptr
, 10);
2402 if (endvalue
>= 63) {
2405 "only 63 CPUs in NUMA mode supported.\n");
2407 value
= (2ULL << endvalue
) - (1ULL << value
);
2409 value
= 1ULL << value
;
2412 node_cpumask
[nodenr
] = value
;
2419 static void smp_parse(const char *optarg
)
2421 int smp
, sockets
= 0, threads
= 0, cores
= 0;
2425 smp
= strtoul(optarg
, &endptr
, 10);
2426 if (endptr
!= optarg
) {
2427 if (*endptr
== ',') {
2431 if (get_param_value(option
, 128, "sockets", endptr
) != 0)
2432 sockets
= strtoull(option
, NULL
, 10);
2433 if (get_param_value(option
, 128, "cores", endptr
) != 0)
2434 cores
= strtoull(option
, NULL
, 10);
2435 if (get_param_value(option
, 128, "threads", endptr
) != 0)
2436 threads
= strtoull(option
, NULL
, 10);
2437 if (get_param_value(option
, 128, "maxcpus", endptr
) != 0)
2438 max_cpus
= strtoull(option
, NULL
, 10);
2440 /* compute missing values, prefer sockets over cores over threads */
2441 if (smp
== 0 || sockets
== 0) {
2442 sockets
= sockets
> 0 ? sockets
: 1;
2443 cores
= cores
> 0 ? cores
: 1;
2444 threads
= threads
> 0 ? threads
: 1;
2446 smp
= cores
* threads
* sockets
;
2450 threads
= threads
> 0 ? threads
: 1;
2451 cores
= smp
/ (sockets
* threads
);
2454 threads
= smp
/ (cores
* sockets
);
2459 smp_cores
= cores
> 0 ? cores
: 1;
2460 smp_threads
= threads
> 0 ? threads
: 1;
2462 max_cpus
= smp_cpus
;
2465 /***********************************************************/
2468 static int usb_device_add(const char *devname
, int is_hotplug
)
2471 USBDevice
*dev
= NULL
;
2476 /* drivers with .usbdevice_name entry in USBDeviceInfo */
2477 dev
= usbdevice_create(devname
);
2481 /* the other ones */
2482 if (strstart(devname
, "host:", &p
)) {
2483 dev
= usb_host_device_open(p
);
2484 } else if (!strcmp(devname
, "bt") || strstart(devname
, "bt:", &p
)) {
2485 dev
= usb_bt_init(devname
[2] ? hci_init(p
) :
2486 bt_new_hci(qemu_find_bt_vlan(0)));
2497 static int usb_device_del(const char *devname
)
2502 if (strstart(devname
, "host:", &p
))
2503 return usb_host_device_close(p
);
2508 p
= strchr(devname
, '.');
2511 bus_num
= strtoul(devname
, NULL
, 0);
2512 addr
= strtoul(p
+ 1, NULL
, 0);
2514 return usb_device_delete_addr(bus_num
, addr
);
2517 static int usb_parse(const char *cmdline
)
2520 r
= usb_device_add(cmdline
, 0);
2522 fprintf(stderr
, "qemu: could not add USB device '%s'\n", cmdline
);
2527 void do_usb_add(Monitor
*mon
, const QDict
*qdict
)
2529 const char *devname
= qdict_get_str(qdict
, "devname");
2530 if (usb_device_add(devname
, 1) < 0) {
2531 qemu_error("could not add USB device '%s'\n", devname
);
2535 void do_usb_del(Monitor
*mon
, const QDict
*qdict
)
2537 const char *devname
= qdict_get_str(qdict
, "devname");
2538 if (usb_device_del(devname
) < 0) {
2539 qemu_error("could not delete USB device '%s'\n", devname
);
2543 /***********************************************************/
2544 /* PCMCIA/Cardbus */
2546 static struct pcmcia_socket_entry_s
{
2547 PCMCIASocket
*socket
;
2548 struct pcmcia_socket_entry_s
*next
;
2549 } *pcmcia_sockets
= 0;
2551 void pcmcia_socket_register(PCMCIASocket
*socket
)
2553 struct pcmcia_socket_entry_s
*entry
;
2555 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
2556 entry
->socket
= socket
;
2557 entry
->next
= pcmcia_sockets
;
2558 pcmcia_sockets
= entry
;
2561 void pcmcia_socket_unregister(PCMCIASocket
*socket
)
2563 struct pcmcia_socket_entry_s
*entry
, **ptr
;
2565 ptr
= &pcmcia_sockets
;
2566 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
2567 if (entry
->socket
== socket
) {
2573 void pcmcia_info(Monitor
*mon
)
2575 struct pcmcia_socket_entry_s
*iter
;
2577 if (!pcmcia_sockets
)
2578 monitor_printf(mon
, "No PCMCIA sockets\n");
2580 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
2581 monitor_printf(mon
, "%s: %s\n", iter
->socket
->slot_string
,
2582 iter
->socket
->attached
? iter
->socket
->card_string
:
2586 /***********************************************************/
2587 /* register display */
2589 struct DisplayAllocator default_allocator
= {
2590 defaultallocator_create_displaysurface
,
2591 defaultallocator_resize_displaysurface
,
2592 defaultallocator_free_displaysurface
2595 void register_displaystate(DisplayState
*ds
)
2605 DisplayState
*get_displaystate(void)
2607 return display_state
;
2610 DisplayAllocator
*register_displayallocator(DisplayState
*ds
, DisplayAllocator
*da
)
2612 if(ds
->allocator
== &default_allocator
) ds
->allocator
= da
;
2613 return ds
->allocator
;
2618 static void dumb_display_init(void)
2620 DisplayState
*ds
= qemu_mallocz(sizeof(DisplayState
));
2621 ds
->allocator
= &default_allocator
;
2622 ds
->surface
= qemu_create_displaysurface(ds
, 640, 480);
2623 register_displaystate(ds
);
2626 /***********************************************************/
2629 typedef struct IOHandlerRecord
{
2631 IOCanRWHandler
*fd_read_poll
;
2633 IOHandler
*fd_write
;
2636 /* temporary data */
2638 struct IOHandlerRecord
*next
;
2641 static IOHandlerRecord
*first_io_handler
;
2643 /* XXX: fd_read_poll should be suppressed, but an API change is
2644 necessary in the character devices to suppress fd_can_read(). */
2645 int qemu_set_fd_handler2(int fd
,
2646 IOCanRWHandler
*fd_read_poll
,
2648 IOHandler
*fd_write
,
2651 IOHandlerRecord
**pioh
, *ioh
;
2653 if (!fd_read
&& !fd_write
) {
2654 pioh
= &first_io_handler
;
2659 if (ioh
->fd
== fd
) {
2666 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
2670 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
2671 ioh
->next
= first_io_handler
;
2672 first_io_handler
= ioh
;
2675 ioh
->fd_read_poll
= fd_read_poll
;
2676 ioh
->fd_read
= fd_read
;
2677 ioh
->fd_write
= fd_write
;
2678 ioh
->opaque
= opaque
;
2681 qemu_notify_event();
2685 int qemu_set_fd_handler(int fd
,
2687 IOHandler
*fd_write
,
2690 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
2694 /***********************************************************/
2695 /* Polling handling */
2697 typedef struct PollingEntry
{
2700 struct PollingEntry
*next
;
2703 static PollingEntry
*first_polling_entry
;
2705 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
2707 PollingEntry
**ppe
, *pe
;
2708 pe
= qemu_mallocz(sizeof(PollingEntry
));
2710 pe
->opaque
= opaque
;
2711 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
2716 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
2718 PollingEntry
**ppe
, *pe
;
2719 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
2721 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
2729 /***********************************************************/
2730 /* Wait objects support */
2731 typedef struct WaitObjects
{
2733 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
2734 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
2735 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
2738 static WaitObjects wait_objects
= {0};
2740 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2742 WaitObjects
*w
= &wait_objects
;
2744 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
2746 w
->events
[w
->num
] = handle
;
2747 w
->func
[w
->num
] = func
;
2748 w
->opaque
[w
->num
] = opaque
;
2753 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
2756 WaitObjects
*w
= &wait_objects
;
2759 for (i
= 0; i
< w
->num
; i
++) {
2760 if (w
->events
[i
] == handle
)
2763 w
->events
[i
] = w
->events
[i
+ 1];
2764 w
->func
[i
] = w
->func
[i
+ 1];
2765 w
->opaque
[i
] = w
->opaque
[i
+ 1];
2773 /***********************************************************/
2774 /* ram save/restore */
2776 #define RAM_SAVE_FLAG_FULL 0x01 /* Obsolete, not used anymore */
2777 #define RAM_SAVE_FLAG_COMPRESS 0x02
2778 #define RAM_SAVE_FLAG_MEM_SIZE 0x04
2779 #define RAM_SAVE_FLAG_PAGE 0x08
2780 #define RAM_SAVE_FLAG_EOS 0x10
2782 static int is_dup_page(uint8_t *page
, uint8_t ch
)
2784 uint32_t val
= ch
<< 24 | ch
<< 16 | ch
<< 8 | ch
;
2785 uint32_t *array
= (uint32_t *)page
;
2788 for (i
= 0; i
< (TARGET_PAGE_SIZE
/ 4); i
++) {
2789 if (array
[i
] != val
)
2796 static int ram_save_block(QEMUFile
*f
)
2798 static ram_addr_t current_addr
= 0;
2799 ram_addr_t saved_addr
= current_addr
;
2800 ram_addr_t addr
= 0;
2803 while (addr
< last_ram_offset
) {
2804 if (kvm_enabled() && current_addr
== 0) {
2806 r
= kvm_update_dirty_pages_log();
2808 fprintf(stderr
, "%s: update dirty pages log failed %d\n", __FUNCTION__
, r
);
2809 qemu_file_set_error(f
);
2813 if (cpu_physical_memory_get_dirty(current_addr
, MIGRATION_DIRTY_FLAG
)) {
2816 cpu_physical_memory_reset_dirty(current_addr
,
2817 current_addr
+ TARGET_PAGE_SIZE
,
2818 MIGRATION_DIRTY_FLAG
);
2820 p
= qemu_get_ram_ptr(current_addr
);
2822 if (is_dup_page(p
, *p
)) {
2823 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_COMPRESS
);
2824 qemu_put_byte(f
, *p
);
2826 qemu_put_be64(f
, current_addr
| RAM_SAVE_FLAG_PAGE
);
2827 qemu_put_buffer(f
, p
, TARGET_PAGE_SIZE
);
2833 addr
+= TARGET_PAGE_SIZE
;
2834 current_addr
= (saved_addr
+ addr
) % last_ram_offset
;
2840 static uint64_t bytes_transferred
;
2842 static ram_addr_t
ram_save_remaining(void)
2845 ram_addr_t count
= 0;
2847 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2848 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2855 uint64_t ram_bytes_remaining(void)
2857 return ram_save_remaining() * TARGET_PAGE_SIZE
;
2860 uint64_t ram_bytes_transferred(void)
2862 return bytes_transferred
;
2865 uint64_t ram_bytes_total(void)
2867 return last_ram_offset
;
2870 static int ram_save_live(Monitor
*mon
, QEMUFile
*f
, int stage
, void *opaque
)
2873 uint64_t bytes_transferred_last
;
2875 uint64_t expected_time
= 0;
2878 cpu_physical_memory_set_dirty_tracking(0);
2882 if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX
) != 0) {
2883 qemu_file_set_error(f
);
2888 bytes_transferred
= 0;
2890 /* Make sure all dirty bits are set */
2891 for (addr
= 0; addr
< last_ram_offset
; addr
+= TARGET_PAGE_SIZE
) {
2892 if (!cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
))
2893 cpu_physical_memory_set_dirty(addr
);
2896 /* Enable dirty memory tracking */
2897 cpu_physical_memory_set_dirty_tracking(1);
2899 qemu_put_be64(f
, last_ram_offset
| RAM_SAVE_FLAG_MEM_SIZE
);
2902 bytes_transferred_last
= bytes_transferred
;
2903 bwidth
= get_clock();
2905 while (!qemu_file_rate_limit(f
)) {
2908 ret
= ram_save_block(f
);
2909 bytes_transferred
+= ret
* TARGET_PAGE_SIZE
;
2910 if (ret
== 0) /* no more blocks */
2914 bwidth
= get_clock() - bwidth
;
2915 bwidth
= (bytes_transferred
- bytes_transferred_last
) / bwidth
;
2917 /* if we haven't transferred anything this round, force expected_time to a
2918 * a very high value, but without crashing */
2922 /* try transferring iterative blocks of memory */
2924 /* flush all remaining blocks regardless of rate limiting */
2925 while (ram_save_block(f
) != 0) {
2926 bytes_transferred
+= TARGET_PAGE_SIZE
;
2928 cpu_physical_memory_set_dirty_tracking(0);
2931 qemu_put_be64(f
, RAM_SAVE_FLAG_EOS
);
2933 expected_time
= ram_save_remaining() * TARGET_PAGE_SIZE
/ bwidth
;
2935 return (stage
== 2) && (expected_time
<= migrate_max_downtime());
2938 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
2943 if (version_id
!= 3)
2947 addr
= qemu_get_be64(f
);
2949 flags
= addr
& ~TARGET_PAGE_MASK
;
2950 addr
&= TARGET_PAGE_MASK
;
2952 if (flags
& RAM_SAVE_FLAG_MEM_SIZE
) {
2953 if (addr
!= last_ram_offset
)
2957 if (flags
& RAM_SAVE_FLAG_COMPRESS
) {
2958 uint8_t ch
= qemu_get_byte(f
);
2959 memset(qemu_get_ram_ptr(addr
), ch
, TARGET_PAGE_SIZE
);
2962 (!kvm_enabled() || kvm_has_sync_mmu())) {
2963 madvise(qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
, MADV_DONTNEED
);
2966 } else if (flags
& RAM_SAVE_FLAG_PAGE
) {
2967 qemu_get_buffer(f
, qemu_get_ram_ptr(addr
), TARGET_PAGE_SIZE
);
2969 if (qemu_file_has_error(f
)) {
2972 } while (!(flags
& RAM_SAVE_FLAG_EOS
));
2977 void qemu_service_io(void)
2979 qemu_notify_event();
2982 /***********************************************************/
2983 /* machine registration */
2985 static QEMUMachine
*first_machine
= NULL
;
2986 QEMUMachine
*current_machine
= NULL
;
2988 int qemu_register_machine(QEMUMachine
*m
)
2991 pm
= &first_machine
;
2999 static QEMUMachine
*find_machine(const char *name
)
3003 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3004 if (!strcmp(m
->name
, name
))
3006 if (m
->alias
&& !strcmp(m
->alias
, name
))
3012 static QEMUMachine
*find_default_machine(void)
3016 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
3017 if (m
->is_default
) {
3024 /***********************************************************/
3025 /* main execution loop */
3027 static void gui_update(void *opaque
)
3029 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3030 DisplayState
*ds
= opaque
;
3031 DisplayChangeListener
*dcl
= ds
->listeners
;
3033 qemu_flush_coalesced_mmio_buffer();
3036 while (dcl
!= NULL
) {
3037 if (dcl
->gui_timer_interval
&&
3038 dcl
->gui_timer_interval
< interval
)
3039 interval
= dcl
->gui_timer_interval
;
3042 qemu_mod_timer(ds
->gui_timer
, interval
+ qemu_get_clock(rt_clock
));
3045 static void nographic_update(void *opaque
)
3047 uint64_t interval
= GUI_REFRESH_INTERVAL
;
3049 qemu_flush_coalesced_mmio_buffer();
3050 qemu_mod_timer(nographic_timer
, interval
+ qemu_get_clock(rt_clock
));
3053 struct vm_change_state_entry
{
3054 VMChangeStateHandler
*cb
;
3056 QLIST_ENTRY (vm_change_state_entry
) entries
;
3059 static QLIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
3061 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
3064 VMChangeStateEntry
*e
;
3066 e
= qemu_mallocz(sizeof (*e
));
3070 QLIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
3074 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
3076 QLIST_REMOVE (e
, entries
);
3080 static void vm_state_notify(int running
, int reason
)
3082 VMChangeStateEntry
*e
;
3084 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
3085 e
->cb(e
->opaque
, running
, reason
);
3089 static void resume_all_vcpus(void);
3090 static void pause_all_vcpus(void);
3097 vm_state_notify(1, 0);
3098 qemu_rearm_alarm_timer(alarm_timer
);
3103 /* reset/shutdown handler */
3105 typedef struct QEMUResetEntry
{
3106 QTAILQ_ENTRY(QEMUResetEntry
) entry
;
3107 QEMUResetHandler
*func
;
3111 static QTAILQ_HEAD(reset_handlers
, QEMUResetEntry
) reset_handlers
=
3112 QTAILQ_HEAD_INITIALIZER(reset_handlers
);
3113 static int reset_requested
;
3114 static int shutdown_requested
;
3115 static int powerdown_requested
;
3116 static int debug_requested
;
3117 static int vmstop_requested
;
3119 int qemu_no_shutdown(void)
3121 int r
= no_shutdown
;
3126 int qemu_shutdown_requested(void)
3128 int r
= shutdown_requested
;
3129 shutdown_requested
= 0;
3133 int qemu_reset_requested(void)
3135 int r
= reset_requested
;
3136 reset_requested
= 0;
3140 int qemu_powerdown_requested(void)
3142 int r
= powerdown_requested
;
3143 powerdown_requested
= 0;
3147 static int qemu_debug_requested(void)
3149 int r
= debug_requested
;
3150 debug_requested
= 0;
3154 static int qemu_vmstop_requested(void)
3156 int r
= vmstop_requested
;
3157 vmstop_requested
= 0;
3161 static void do_vm_stop(int reason
)
3164 cpu_disable_ticks();
3167 vm_state_notify(0, reason
);
3171 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
3173 QEMUResetEntry
*re
= qemu_mallocz(sizeof(QEMUResetEntry
));
3176 re
->opaque
= opaque
;
3177 QTAILQ_INSERT_TAIL(&reset_handlers
, re
, entry
);
3180 void qemu_unregister_reset(QEMUResetHandler
*func
, void *opaque
)
3184 QTAILQ_FOREACH(re
, &reset_handlers
, entry
) {
3185 if (re
->func
== func
&& re
->opaque
== opaque
) {
3186 QTAILQ_REMOVE(&reset_handlers
, re
, entry
);
3193 void qemu_system_reset(void)
3195 QEMUResetEntry
*re
, *nre
;
3197 /* reset all devices */
3198 QTAILQ_FOREACH_SAFE(re
, &reset_handlers
, entry
, nre
) {
3199 re
->func(re
->opaque
);
3203 void qemu_system_reset_request(void)
3206 shutdown_requested
= 1;
3208 reset_requested
= 1;
3210 if (cpu_single_env
) {
3211 cpu_single_env
->stopped
= 1;
3213 qemu_notify_event();
3216 void qemu_system_shutdown_request(void)
3218 shutdown_requested
= 1;
3219 qemu_notify_event();
3222 void qemu_system_powerdown_request(void)
3224 powerdown_requested
= 1;
3225 qemu_notify_event();
3228 #ifdef CONFIG_IOTHREAD
3229 static void qemu_system_vmstop_request(int reason
)
3231 vmstop_requested
= reason
;
3232 qemu_notify_event();
3237 static int io_thread_fd
= -1;
3239 static void qemu_event_increment(void)
3241 static const char byte
= 0;
3244 if (io_thread_fd
== -1)
3247 ret
= write(io_thread_fd
, &byte
, sizeof(byte
));
3248 if (ret
< 0 && (errno
!= EINTR
&& errno
!= EAGAIN
)) {
3249 fprintf(stderr
, "qemu_event_increment: write() filed: %s\n",
3255 static void qemu_event_read(void *opaque
)
3257 int fd
= (unsigned long)opaque
;
3260 /* Drain the notify pipe */
3263 len
= read(fd
, buffer
, sizeof(buffer
));
3264 } while ((len
== -1 && errno
== EINTR
) || len
> 0);
3267 static int qemu_event_init(void)
3272 err
= qemu_pipe(fds
);
3276 err
= fcntl_setfl(fds
[0], O_NONBLOCK
);
3280 err
= fcntl_setfl(fds
[1], O_NONBLOCK
);
3284 qemu_set_fd_handler2(fds
[0], NULL
, qemu_event_read
, NULL
,
3285 (void *)(unsigned long)fds
[0]);
3287 io_thread_fd
= fds
[1];
3296 HANDLE qemu_event_handle
;
3298 static void dummy_event_handler(void *opaque
)
3302 static int qemu_event_init(void)
3304 qemu_event_handle
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
3305 if (!qemu_event_handle
) {
3306 fprintf(stderr
, "Failed CreateEvent: %ld\n", GetLastError());
3309 qemu_add_wait_object(qemu_event_handle
, dummy_event_handler
, NULL
);
3313 static void qemu_event_increment(void)
3315 if (!SetEvent(qemu_event_handle
)) {
3316 fprintf(stderr
, "qemu_event_increment: SetEvent failed: %ld\n",
3323 static int cpu_can_run(CPUState
*env
)
3334 #ifndef CONFIG_IOTHREAD
3335 static int qemu_init_main_loop(void)
3337 return qemu_event_init();
3340 void qemu_init_vcpu(void *_env
)
3342 CPUState
*env
= _env
;
3344 env
->nr_cores
= smp_cores
;
3345 env
->nr_threads
= smp_threads
;
3351 int qemu_cpu_self(void *env
)
3356 static void resume_all_vcpus(void)
3360 static void pause_all_vcpus(void)
3364 void qemu_cpu_kick(void *env
)
3369 void qemu_notify_event(void)
3371 CPUState
*env
= cpu_single_env
;
3373 if (kvm_enabled()) {
3374 qemu_kvm_notify_work();
3382 #if defined(KVM_UPSTREAM) || !defined(CONFIG_KVM)
3383 void qemu_mutex_lock_iothread(void) {}
3384 void qemu_mutex_unlock_iothread(void) {}
3387 void vm_stop(int reason
)
3392 #else /* CONFIG_IOTHREAD */
3394 #include "qemu-thread.h"
3396 QemuMutex qemu_global_mutex
;
3397 static QemuMutex qemu_fair_mutex
;
3399 static QemuThread io_thread
;
3401 static QemuThread
*tcg_cpu_thread
;
3402 static QemuCond
*tcg_halt_cond
;
3404 static int qemu_system_ready
;
3406 static QemuCond qemu_cpu_cond
;
3408 static QemuCond qemu_system_cond
;
3409 static QemuCond qemu_pause_cond
;
3411 static void block_io_signals(void);
3412 static void unblock_io_signals(void);
3413 static int tcg_has_work(void);
3415 static int qemu_init_main_loop(void)
3419 ret
= qemu_event_init();
3423 qemu_cond_init(&qemu_pause_cond
);
3424 qemu_mutex_init(&qemu_fair_mutex
);
3425 qemu_mutex_init(&qemu_global_mutex
);
3426 qemu_mutex_lock(&qemu_global_mutex
);
3428 unblock_io_signals();
3429 qemu_thread_self(&io_thread
);
3434 static void qemu_wait_io_event(CPUState
*env
)
3436 while (!tcg_has_work())
3437 qemu_cond_timedwait(env
->halt_cond
, &qemu_global_mutex
, 1000);
3439 qemu_mutex_unlock(&qemu_global_mutex
);
3442 * Users of qemu_global_mutex can be starved, having no chance
3443 * to acquire it since this path will get to it first.
3444 * So use another lock to provide fairness.
3446 qemu_mutex_lock(&qemu_fair_mutex
);
3447 qemu_mutex_unlock(&qemu_fair_mutex
);
3449 qemu_mutex_lock(&qemu_global_mutex
);
3453 qemu_cond_signal(&qemu_pause_cond
);
3457 static int qemu_cpu_exec(CPUState
*env
);
3459 static void *kvm_cpu_thread_fn(void *arg
)
3461 CPUState
*env
= arg
;
3464 qemu_thread_self(env
->thread
);
3468 /* signal CPU creation */
3469 qemu_mutex_lock(&qemu_global_mutex
);
3471 qemu_cond_signal(&qemu_cpu_cond
);
3473 /* and wait for machine initialization */
3474 while (!qemu_system_ready
)
3475 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3478 if (cpu_can_run(env
))
3480 qemu_wait_io_event(env
);
3486 static void tcg_cpu_exec(void);
3488 static void *tcg_cpu_thread_fn(void *arg
)
3490 CPUState
*env
= arg
;
3493 qemu_thread_self(env
->thread
);
3495 /* signal CPU creation */
3496 qemu_mutex_lock(&qemu_global_mutex
);
3497 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3499 qemu_cond_signal(&qemu_cpu_cond
);
3501 /* and wait for machine initialization */
3502 while (!qemu_system_ready
)
3503 qemu_cond_timedwait(&qemu_system_cond
, &qemu_global_mutex
, 100);
3507 qemu_wait_io_event(cur_cpu
);
3513 void qemu_cpu_kick(void *_env
)
3515 CPUState
*env
= _env
;
3516 qemu_cond_broadcast(env
->halt_cond
);
3518 qemu_thread_signal(env
->thread
, SIGUSR1
);
3521 int qemu_cpu_self(void *_env
)
3523 CPUState
*env
= _env
;
3526 qemu_thread_self(&this);
3528 return qemu_thread_equal(&this, env
->thread
);
3531 static void cpu_signal(int sig
)
3534 cpu_exit(cpu_single_env
);
3537 static void block_io_signals(void)
3540 struct sigaction sigact
;
3543 sigaddset(&set
, SIGUSR2
);
3544 sigaddset(&set
, SIGIO
);
3545 sigaddset(&set
, SIGALRM
);
3546 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3549 sigaddset(&set
, SIGUSR1
);
3550 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3552 memset(&sigact
, 0, sizeof(sigact
));
3553 sigact
.sa_handler
= cpu_signal
;
3554 sigaction(SIGUSR1
, &sigact
, NULL
);
3557 static void unblock_io_signals(void)
3562 sigaddset(&set
, SIGUSR2
);
3563 sigaddset(&set
, SIGIO
);
3564 sigaddset(&set
, SIGALRM
);
3565 pthread_sigmask(SIG_UNBLOCK
, &set
, NULL
);
3568 sigaddset(&set
, SIGUSR1
);
3569 pthread_sigmask(SIG_BLOCK
, &set
, NULL
);
3572 static void qemu_signal_lock(unsigned int msecs
)
3574 qemu_mutex_lock(&qemu_fair_mutex
);
3576 while (qemu_mutex_trylock(&qemu_global_mutex
)) {
3577 qemu_thread_signal(tcg_cpu_thread
, SIGUSR1
);
3578 if (!qemu_mutex_timedlock(&qemu_global_mutex
, msecs
))
3581 qemu_mutex_unlock(&qemu_fair_mutex
);
3584 void qemu_mutex_lock_iothread(void)
3586 if (kvm_enabled()) {
3587 qemu_mutex_lock(&qemu_fair_mutex
);
3588 qemu_mutex_lock(&qemu_global_mutex
);
3589 qemu_mutex_unlock(&qemu_fair_mutex
);
3591 qemu_signal_lock(100);
3594 void qemu_mutex_unlock_iothread(void)
3596 qemu_mutex_unlock(&qemu_global_mutex
);
3599 static int all_vcpus_paused(void)
3601 CPUState
*penv
= first_cpu
;
3606 penv
= (CPUState
*)penv
->next_cpu
;
3612 static void pause_all_vcpus(void)
3614 CPUState
*penv
= first_cpu
;
3618 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3619 qemu_cpu_kick(penv
);
3620 penv
= (CPUState
*)penv
->next_cpu
;
3623 while (!all_vcpus_paused()) {
3624 qemu_cond_timedwait(&qemu_pause_cond
, &qemu_global_mutex
, 100);
3627 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3628 penv
= (CPUState
*)penv
->next_cpu
;
3633 static void resume_all_vcpus(void)
3635 CPUState
*penv
= first_cpu
;
3640 qemu_thread_signal(penv
->thread
, SIGUSR1
);
3641 qemu_cpu_kick(penv
);
3642 penv
= (CPUState
*)penv
->next_cpu
;
3646 static void tcg_init_vcpu(void *_env
)
3648 CPUState
*env
= _env
;
3649 /* share a single thread for all cpus with TCG */
3650 if (!tcg_cpu_thread
) {
3651 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3652 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3653 qemu_cond_init(env
->halt_cond
);
3654 qemu_thread_create(env
->thread
, tcg_cpu_thread_fn
, env
);
3655 while (env
->created
== 0)
3656 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3657 tcg_cpu_thread
= env
->thread
;
3658 tcg_halt_cond
= env
->halt_cond
;
3660 env
->thread
= tcg_cpu_thread
;
3661 env
->halt_cond
= tcg_halt_cond
;
3665 static void kvm_start_vcpu(CPUState
*env
)
3667 env
->thread
= qemu_mallocz(sizeof(QemuThread
));
3668 env
->halt_cond
= qemu_mallocz(sizeof(QemuCond
));
3669 qemu_cond_init(env
->halt_cond
);
3670 qemu_thread_create(env
->thread
, kvm_cpu_thread_fn
, env
);
3671 while (env
->created
== 0)
3672 qemu_cond_timedwait(&qemu_cpu_cond
, &qemu_global_mutex
, 100);
3675 void qemu_init_vcpu(void *_env
)
3677 CPUState
*env
= _env
;
3679 env
->nr_cores
= smp_cores
;
3680 env
->nr_threads
= smp_threads
;
3682 kvm_start_vcpu(env
);
3687 void qemu_notify_event(void)
3689 qemu_event_increment();
3692 void vm_stop(int reason
)
3695 qemu_thread_self(&me
);
3697 if (!qemu_thread_equal(&me
, &io_thread
)) {
3698 qemu_system_vmstop_request(reason
);
3700 * FIXME: should not return to device code in case
3701 * vm_stop() has been requested.
3703 if (cpu_single_env
) {
3704 cpu_exit(cpu_single_env
);
3705 cpu_single_env
->stop
= 1;
3716 static void host_main_loop_wait(int *timeout
)
3722 /* XXX: need to suppress polling by better using win32 events */
3724 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
3725 ret
|= pe
->func(pe
->opaque
);
3729 WaitObjects
*w
= &wait_objects
;
3731 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, *timeout
);
3732 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
3733 if (w
->func
[ret
- WAIT_OBJECT_0
])
3734 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
3736 /* Check for additional signaled events */
3737 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
3739 /* Check if event is signaled */
3740 ret2
= WaitForSingleObject(w
->events
[i
], 0);
3741 if(ret2
== WAIT_OBJECT_0
) {
3743 w
->func
[i
](w
->opaque
[i
]);
3744 } else if (ret2
== WAIT_TIMEOUT
) {
3746 err
= GetLastError();
3747 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
3750 } else if (ret
== WAIT_TIMEOUT
) {
3752 err
= GetLastError();
3753 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
3760 static void host_main_loop_wait(int *timeout
)
3765 void main_loop_wait(int timeout
)
3767 IOHandlerRecord
*ioh
;
3768 fd_set rfds
, wfds
, xfds
;
3772 qemu_bh_update_timeout(&timeout
);
3774 host_main_loop_wait(&timeout
);
3776 /* poll any events */
3777 /* XXX: separate device handlers from system ones */
3782 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3786 (!ioh
->fd_read_poll
||
3787 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
3788 FD_SET(ioh
->fd
, &rfds
);
3792 if (ioh
->fd_write
) {
3793 FD_SET(ioh
->fd
, &wfds
);
3799 tv
.tv_sec
= timeout
/ 1000;
3800 tv
.tv_usec
= (timeout
% 1000) * 1000;
3802 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
3804 qemu_mutex_unlock_iothread();
3805 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
3806 qemu_mutex_lock_iothread();
3808 IOHandlerRecord
**pioh
;
3810 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
3811 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
3812 ioh
->fd_read(ioh
->opaque
);
3813 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
3814 FD_CLR(ioh
->fd
, &rfds
);
3816 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
3817 ioh
->fd_write(ioh
->opaque
);
3821 /* remove deleted IO handlers */
3822 pioh
= &first_io_handler
;
3833 slirp_select_poll(&rfds
, &wfds
, &xfds
, (ret
< 0));
3835 /* rearm timer, if not periodic */
3836 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
3837 alarm_timer
->flags
&= ~ALARM_FLAG_EXPIRED
;
3838 qemu_rearm_alarm_timer(alarm_timer
);
3841 /* vm time timers */
3843 if (!cur_cpu
|| likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
3844 qemu_run_timers(&active_timers
[QEMU_CLOCK_VIRTUAL
],
3845 qemu_get_clock(vm_clock
));
3848 /* real time timers */
3849 qemu_run_timers(&active_timers
[QEMU_CLOCK_REALTIME
],
3850 qemu_get_clock(rt_clock
));
3852 qemu_run_timers(&active_timers
[QEMU_CLOCK_HOST
],
3853 qemu_get_clock(host_clock
));
3855 /* Check bottom-halves last in case any of the earlier events triggered
3861 static int qemu_cpu_exec(CPUState
*env
)
3864 #ifdef CONFIG_PROFILER
3868 #ifdef CONFIG_PROFILER
3869 ti
= profile_getclock();
3874 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
3875 env
->icount_decr
.u16
.low
= 0;
3876 env
->icount_extra
= 0;
3877 count
= qemu_next_deadline();
3878 count
= (count
+ (1 << icount_time_shift
) - 1)
3879 >> icount_time_shift
;
3880 qemu_icount
+= count
;
3881 decr
= (count
> 0xffff) ? 0xffff : count
;
3883 env
->icount_decr
.u16
.low
= decr
;
3884 env
->icount_extra
= count
;
3886 ret
= cpu_exec(env
);
3887 #ifdef CONFIG_PROFILER
3888 qemu_time
+= profile_getclock() - ti
;
3891 /* Fold pending instructions back into the
3892 instruction counter, and clear the interrupt flag. */
3893 qemu_icount
-= (env
->icount_decr
.u16
.low
3894 + env
->icount_extra
);
3895 env
->icount_decr
.u32
= 0;
3896 env
->icount_extra
= 0;
3901 static void tcg_cpu_exec(void)
3905 if (next_cpu
== NULL
)
3906 next_cpu
= first_cpu
;
3907 for (; next_cpu
!= NULL
; next_cpu
= next_cpu
->next_cpu
) {
3908 CPUState
*env
= cur_cpu
= next_cpu
;
3912 if (timer_alarm_pending
) {
3913 timer_alarm_pending
= 0;
3916 if (cpu_can_run(env
))
3917 ret
= qemu_cpu_exec(env
);
3918 if (ret
== EXCP_DEBUG
) {
3919 gdb_set_stop_cpu(env
);
3920 debug_requested
= 1;
3926 static int cpu_has_work(CPUState
*env
)
3934 if (qemu_cpu_has_work(env
))
3939 static int tcg_has_work(void)
3943 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
)
3944 if (cpu_has_work(env
))
3949 static int qemu_calculate_timeout(void)
3951 #ifndef CONFIG_IOTHREAD
3956 else if (tcg_has_work())
3958 else if (!use_icount
)
3961 /* XXX: use timeout computed from timers */
3964 /* Advance virtual time to the next event. */
3965 if (use_icount
== 1) {
3966 /* When not using an adaptive execution frequency
3967 we tend to get badly out of sync with real time,
3968 so just delay for a reasonable amount of time. */
3971 delta
= cpu_get_icount() - cpu_get_clock();
3974 /* If virtual time is ahead of real time then just
3976 timeout
= (delta
/ 1000000) + 1;
3978 /* Wait for either IO to occur or the next
3980 add
= qemu_next_deadline();
3981 /* We advance the timer before checking for IO.
3982 Limit the amount we advance so that early IO
3983 activity won't get the guest too far ahead. */
3987 add
= (add
+ (1 << icount_time_shift
) - 1)
3988 >> icount_time_shift
;
3990 timeout
= delta
/ 1000000;
3997 #else /* CONFIG_IOTHREAD */
4002 static int vm_can_run(void)
4004 if (powerdown_requested
)
4006 if (reset_requested
)
4008 if (shutdown_requested
)
4010 if (debug_requested
)
4015 qemu_irq qemu_system_powerdown
;
4017 static void main_loop(void)
4021 if (kvm_enabled()) {
4023 cpu_disable_ticks();
4027 #ifdef CONFIG_IOTHREAD
4028 qemu_system_ready
= 1;
4029 qemu_cond_broadcast(&qemu_system_cond
);
4034 #ifdef CONFIG_PROFILER
4037 #ifndef CONFIG_IOTHREAD
4040 #ifdef CONFIG_PROFILER
4041 ti
= profile_getclock();
4043 main_loop_wait(qemu_calculate_timeout());
4044 #ifdef CONFIG_PROFILER
4045 dev_time
+= profile_getclock() - ti
;
4047 } while (vm_can_run());
4049 if (qemu_debug_requested()) {
4050 monitor_protocol_event(QEVENT_DEBUG
, NULL
);
4051 vm_stop(EXCP_DEBUG
);
4053 if (qemu_shutdown_requested()) {
4054 monitor_protocol_event(QEVENT_SHUTDOWN
, NULL
);
4061 if (qemu_reset_requested()) {
4062 monitor_protocol_event(QEVENT_RESET
, NULL
);
4064 qemu_system_reset();
4067 if (qemu_powerdown_requested()) {
4068 monitor_protocol_event(QEVENT_POWERDOWN
, NULL
);
4069 qemu_irq_raise(qemu_system_powerdown
);
4071 if ((r
= qemu_vmstop_requested())) {
4072 monitor_protocol_event(QEVENT_STOP
, NULL
);
4079 static void version(void)
4081 printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n");
4084 static void help(int exitcode
)
4086 const char *options_help
=
4087 #define DEF(option, opt_arg, opt_enum, opt_help) \
4089 #define DEFHEADING(text) stringify(text) "\n"
4090 #include "qemu-options.h"
4096 printf("usage: %s [options] [disk_image]\n"
4098 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4101 "During emulation, the following keys are useful:\n"
4102 "ctrl-alt-f toggle full screen\n"
4103 "ctrl-alt-n switch to virtual console 'n'\n"
4104 "ctrl-alt toggle mouse and keyboard grab\n"
4106 "When using -nographic, press 'ctrl-a h' to get some help.\n",
4112 #define HAS_ARG 0x0001
4115 #define DEF(option, opt_arg, opt_enum, opt_help) \
4117 #define DEFHEADING(text)
4118 #include "qemu-options.h"
4124 typedef struct QEMUOption
{
4130 static const QEMUOption qemu_options
[] = {
4131 { "h", 0, QEMU_OPTION_h
},
4132 #define DEF(option, opt_arg, opt_enum, opt_help) \
4133 { option, opt_arg, opt_enum },
4134 #define DEFHEADING(text)
4135 #include "qemu-options.h"
4143 struct soundhw soundhw
[] = {
4144 #ifdef HAS_AUDIO_CHOICE
4145 #if defined(TARGET_I386) || defined(TARGET_MIPS)
4151 { .init_isa
= pcspk_audio_init
}
4158 "Creative Sound Blaster 16",
4161 { .init_isa
= SB16_init
}
4165 #ifdef CONFIG_CS4231A
4171 { .init_isa
= cs4231a_init
}
4179 "Yamaha YMF262 (OPL3)",
4181 "Yamaha YM3812 (OPL2)",
4185 { .init_isa
= Adlib_init
}
4192 "Gravis Ultrasound GF1",
4195 { .init_isa
= GUS_init
}
4202 "Intel 82801AA AC97 Audio",
4205 { .init_pci
= ac97_init
}
4209 #ifdef CONFIG_ES1370
4212 "ENSONIQ AudioPCI ES1370",
4215 { .init_pci
= es1370_init
}
4219 #endif /* HAS_AUDIO_CHOICE */
4221 { NULL
, NULL
, 0, 0, { NULL
} }
4224 static void select_soundhw (const char *optarg
)
4228 if (*optarg
== '?') {
4231 printf ("Valid sound card names (comma separated):\n");
4232 for (c
= soundhw
; c
->name
; ++c
) {
4233 printf ("%-11s %s\n", c
->name
, c
->descr
);
4235 printf ("\n-soundhw all will enable all of the above\n");
4236 exit (*optarg
!= '?');
4244 if (!strcmp (optarg
, "all")) {
4245 for (c
= soundhw
; c
->name
; ++c
) {
4253 e
= strchr (p
, ',');
4254 l
= !e
? strlen (p
) : (size_t) (e
- p
);
4256 for (c
= soundhw
; c
->name
; ++c
) {
4257 if (!strncmp (c
->name
, p
, l
) && !c
->name
[l
]) {
4266 "Unknown sound card name (too big to show)\n");
4269 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
4274 p
+= l
+ (e
!= NULL
);
4278 goto show_valid_cards
;
4283 static void select_vgahw (const char *p
)
4288 vga_interface_type
= VGA_NONE
;
4289 if (strstart(p
, "std", &opts
)) {
4290 vga_interface_type
= VGA_STD
;
4291 } else if (strstart(p
, "cirrus", &opts
)) {
4292 vga_interface_type
= VGA_CIRRUS
;
4293 } else if (strstart(p
, "vmware", &opts
)) {
4294 vga_interface_type
= VGA_VMWARE
;
4295 } else if (strstart(p
, "xenfb", &opts
)) {
4296 vga_interface_type
= VGA_XENFB
;
4297 } else if (!strstart(p
, "none", &opts
)) {
4299 fprintf(stderr
, "Unknown vga type: %s\n", p
);
4303 const char *nextopt
;
4305 if (strstart(opts
, ",retrace=", &nextopt
)) {
4307 if (strstart(opts
, "dumb", &nextopt
))
4308 vga_retrace_method
= VGA_RETRACE_DUMB
;
4309 else if (strstart(opts
, "precise", &nextopt
))
4310 vga_retrace_method
= VGA_RETRACE_PRECISE
;
4311 else goto invalid_vga
;
4312 } else goto invalid_vga
;
4318 static int balloon_parse(const char *arg
)
4322 if (strcmp(arg
, "none") == 0) {
4326 if (!strncmp(arg
, "virtio", 6)) {
4327 if (arg
[6] == ',') {
4328 /* have params -> parse them */
4329 opts
= qemu_opts_parse(&qemu_device_opts
, arg
+7, NULL
);
4333 /* create empty opts */
4334 opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4336 qemu_opt_set(opts
, "driver", "virtio-balloon-pci");
4345 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
4347 exit(STATUS_CONTROL_C_EXIT
);
4352 int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
4356 if(strlen(str
) != 36)
4359 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
4360 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
4361 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
4367 smbios_add_field(1, offsetof(struct smbios_type_1
, uuid
), 16, uuid
);
4375 static void termsig_handler(int signal
)
4377 qemu_system_shutdown_request();
4380 static void sigchld_handler(int signal
)
4382 waitpid(-1, NULL
, WNOHANG
);
4385 static void sighandler_setup(void)
4387 struct sigaction act
;
4389 memset(&act
, 0, sizeof(act
));
4390 act
.sa_handler
= termsig_handler
;
4391 sigaction(SIGINT
, &act
, NULL
);
4392 sigaction(SIGHUP
, &act
, NULL
);
4393 sigaction(SIGTERM
, &act
, NULL
);
4395 act
.sa_handler
= sigchld_handler
;
4396 act
.sa_flags
= SA_NOCLDSTOP
;
4397 sigaction(SIGCHLD
, &act
, NULL
);
4403 /* Look for support files in the same directory as the executable. */
4404 static char *find_datadir(const char *argv0
)
4410 len
= GetModuleFileName(NULL
, buf
, sizeof(buf
) - 1);
4417 while (p
!= buf
&& *p
!= '\\')
4420 if (access(buf
, R_OK
) == 0) {
4421 return qemu_strdup(buf
);
4427 /* Find a likely location for support files using the location of the binary.
4428 For installed binaries this will be "$bindir/../share/qemu". When
4429 running from the build tree this will be "$bindir/../pc-bios". */
4430 #define SHARE_SUFFIX "/share/qemu"
4431 #define BUILD_SUFFIX "/pc-bios"
4432 static char *find_datadir(const char *argv0
)
4440 #if defined(__linux__)
4443 len
= readlink("/proc/self/exe", buf
, sizeof(buf
) - 1);
4449 #elif defined(__FreeBSD__)
4452 len
= readlink("/proc/curproc/file", buf
, sizeof(buf
) - 1);
4459 /* If we don't have any way of figuring out the actual executable
4460 location then try argv[0]. */
4462 p
= realpath(argv0
, buf
);
4470 max_len
= strlen(dir
) +
4471 MAX(strlen(SHARE_SUFFIX
), strlen(BUILD_SUFFIX
)) + 1;
4472 res
= qemu_mallocz(max_len
);
4473 snprintf(res
, max_len
, "%s%s", dir
, SHARE_SUFFIX
);
4474 if (access(res
, R_OK
)) {
4475 snprintf(res
, max_len
, "%s%s", dir
, BUILD_SUFFIX
);
4476 if (access(res
, R_OK
)) {
4488 char *qemu_find_file(int type
, const char *name
)
4494 /* If name contains path separators then try it as a straight path. */
4495 if ((strchr(name
, '/') || strchr(name
, '\\'))
4496 && access(name
, R_OK
) == 0) {
4497 return qemu_strdup(name
);
4500 case QEMU_FILE_TYPE_BIOS
:
4503 case QEMU_FILE_TYPE_KEYMAP
:
4504 subdir
= "keymaps/";
4509 len
= strlen(data_dir
) + strlen(name
) + strlen(subdir
) + 2;
4510 buf
= qemu_mallocz(len
);
4511 snprintf(buf
, len
, "%s/%s%s", data_dir
, subdir
, name
);
4512 if (access(buf
, R_OK
)) {
4519 static int device_help_func(QemuOpts
*opts
, void *opaque
)
4521 return qdev_device_help(opts
);
4524 static int device_init_func(QemuOpts
*opts
, void *opaque
)
4528 dev
= qdev_device_add(opts
);
4534 static int chardev_init_func(QemuOpts
*opts
, void *opaque
)
4536 CharDriverState
*chr
;
4538 chr
= qemu_chr_open_opts(opts
, NULL
);
4544 static int mon_init_func(QemuOpts
*opts
, void *opaque
)
4546 CharDriverState
*chr
;
4547 const char *chardev
;
4551 mode
= qemu_opt_get(opts
, "mode");
4555 if (strcmp(mode
, "readline") == 0) {
4556 flags
= MONITOR_USE_READLINE
;
4557 } else if (strcmp(mode
, "control") == 0) {
4558 flags
= MONITOR_USE_CONTROL
;
4560 fprintf(stderr
, "unknown monitor mode \"%s\"\n", mode
);
4564 if (qemu_opt_get_bool(opts
, "default", 0))
4565 flags
|= MONITOR_IS_DEFAULT
;
4567 chardev
= qemu_opt_get(opts
, "chardev");
4568 chr
= qemu_chr_find(chardev
);
4570 fprintf(stderr
, "chardev \"%s\" not found\n", chardev
);
4574 monitor_init(chr
, flags
);
4578 static void monitor_parse(const char *optarg
, const char *mode
)
4580 static int monitor_device_index
= 0;
4586 if (strstart(optarg
, "chardev:", &p
)) {
4587 snprintf(label
, sizeof(label
), "%s", p
);
4589 if (monitor_device_index
) {
4590 snprintf(label
, sizeof(label
), "monitor%d",
4591 monitor_device_index
);
4593 snprintf(label
, sizeof(label
), "monitor");
4596 opts
= qemu_chr_parse_compat(label
, optarg
);
4598 fprintf(stderr
, "parse error: %s\n", optarg
);
4603 opts
= qemu_opts_create(&qemu_mon_opts
, label
, 1);
4605 fprintf(stderr
, "duplicate chardev: %s\n", label
);
4608 qemu_opt_set(opts
, "mode", mode
);
4609 qemu_opt_set(opts
, "chardev", label
);
4611 qemu_opt_set(opts
, "default", "on");
4612 monitor_device_index
++;
4615 struct device_config
{
4617 DEV_USB
, /* -usbdevice */
4619 DEV_SERIAL
, /* -serial */
4620 DEV_PARALLEL
, /* -parallel */
4621 DEV_VIRTCON
, /* -virtioconsole */
4622 DEV_DEBUGCON
, /* -debugcon */
4624 const char *cmdline
;
4625 QTAILQ_ENTRY(device_config
) next
;
4627 QTAILQ_HEAD(, device_config
) device_configs
= QTAILQ_HEAD_INITIALIZER(device_configs
);
4629 static void add_device_config(int type
, const char *cmdline
)
4631 struct device_config
*conf
;
4633 conf
= qemu_mallocz(sizeof(*conf
));
4635 conf
->cmdline
= cmdline
;
4636 QTAILQ_INSERT_TAIL(&device_configs
, conf
, next
);
4639 static int foreach_device_config(int type
, int (*func
)(const char *cmdline
))
4641 struct device_config
*conf
;
4644 QTAILQ_FOREACH(conf
, &device_configs
, next
) {
4645 if (conf
->type
!= type
)
4647 rc
= func(conf
->cmdline
);
4654 static int serial_parse(const char *devname
)
4656 static int index
= 0;
4659 if (strcmp(devname
, "none") == 0)
4661 if (index
== MAX_SERIAL_PORTS
) {
4662 fprintf(stderr
, "qemu: too many serial ports\n");
4665 snprintf(label
, sizeof(label
), "serial%d", index
);
4666 serial_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4667 if (!serial_hds
[index
]) {
4668 fprintf(stderr
, "qemu: could not open serial device '%s': %s\n",
4669 devname
, strerror(errno
));
4676 static int parallel_parse(const char *devname
)
4678 static int index
= 0;
4681 if (strcmp(devname
, "none") == 0)
4683 if (index
== MAX_PARALLEL_PORTS
) {
4684 fprintf(stderr
, "qemu: too many parallel ports\n");
4687 snprintf(label
, sizeof(label
), "parallel%d", index
);
4688 parallel_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4689 if (!parallel_hds
[index
]) {
4690 fprintf(stderr
, "qemu: could not open parallel device '%s': %s\n",
4691 devname
, strerror(errno
));
4698 static int virtcon_parse(const char *devname
)
4700 static int index
= 0;
4702 QemuOpts
*bus_opts
, *dev_opts
;
4704 if (strcmp(devname
, "none") == 0)
4706 if (index
== MAX_VIRTIO_CONSOLES
) {
4707 fprintf(stderr
, "qemu: too many virtio consoles\n");
4711 bus_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4712 qemu_opt_set(bus_opts
, "driver", "virtio-serial");
4714 dev_opts
= qemu_opts_create(&qemu_device_opts
, NULL
, 0);
4715 qemu_opt_set(dev_opts
, "driver", "virtconsole");
4717 snprintf(label
, sizeof(label
), "virtcon%d", index
);
4718 virtcon_hds
[index
] = qemu_chr_open(label
, devname
, NULL
);
4719 if (!virtcon_hds
[index
]) {
4720 fprintf(stderr
, "qemu: could not open virtio console '%s': %s\n",
4721 devname
, strerror(errno
));
4724 qemu_opt_set(dev_opts
, "chardev", label
);
4730 static int debugcon_parse(const char *devname
)
4734 if (!qemu_chr_open("debugcon", devname
, NULL
)) {
4737 opts
= qemu_opts_create(&qemu_device_opts
, "debugcon", 1);
4739 fprintf(stderr
, "qemu: already have a debugcon device\n");
4742 qemu_opt_set(opts
, "driver", "isa-debugcon");
4743 qemu_opt_set(opts
, "chardev", "debugcon");
4747 static const QEMUOption
*lookup_opt(int argc
, char **argv
,
4748 const char **poptarg
, int *poptind
)
4750 const QEMUOption
*popt
;
4751 int optind
= *poptind
;
4752 char *r
= argv
[optind
];
4756 /* Treat --foo the same as -foo. */
4759 popt
= qemu_options
;
4762 fprintf(stderr
, "%s: invalid option -- '%s'\n",
4766 if (!strcmp(popt
->name
, r
+ 1))
4770 if (popt
->flags
& HAS_ARG
) {
4771 if (optind
>= argc
) {
4772 fprintf(stderr
, "%s: option '%s' requires an argument\n",
4776 optarg
= argv
[optind
++];
4787 int main(int argc
, char **argv
, char **envp
)
4789 const char *gdbstub_dev
= NULL
;
4790 uint32_t boot_devices_bitmap
= 0;
4792 int snapshot
, linux_boot
, net_boot
;
4793 const char *initrd_filename
;
4794 const char *kernel_filename
, *kernel_cmdline
;
4795 char boot_devices
[33] = "cad"; /* default to HD->floppy->CD-ROM */
4797 DisplayChangeListener
*dcl
;
4798 int cyls
, heads
, secs
, translation
;
4799 QemuOpts
*hda_opts
= NULL
, *opts
;
4802 const char *loadvm
= NULL
;
4803 QEMUMachine
*machine
;
4804 const char *cpu_model
;
4809 const char *pid_file
= NULL
;
4810 const char *incoming
= NULL
;
4813 struct passwd
*pwd
= NULL
;
4814 const char *chroot_dir
= NULL
;
4815 const char *run_as
= NULL
;
4818 int show_vnc_port
= 0;
4823 qemu_errors_to_file(stderr
);
4824 qemu_cache_utils_init(envp
);
4826 QLIST_INIT (&vm_change_state_head
);
4829 struct sigaction act
;
4830 sigfillset(&act
.sa_mask
);
4832 act
.sa_handler
= SIG_IGN
;
4833 sigaction(SIGPIPE
, &act
, NULL
);
4836 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
4837 /* Note: cpu_interrupt() is currently not SMP safe, so we force
4838 QEMU to run on a single CPU */
4843 h
= GetCurrentProcess();
4844 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
4845 for(i
= 0; i
< 32; i
++) {
4846 if (mask
& (1 << i
))
4851 SetProcessAffinityMask(h
, mask
);
4857 module_call_init(MODULE_INIT_MACHINE
);
4858 machine
= find_default_machine();
4860 initrd_filename
= NULL
;
4863 kernel_filename
= NULL
;
4864 kernel_cmdline
= "";
4865 cyls
= heads
= secs
= 0;
4866 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4868 for (i
= 0; i
< MAX_NODES
; i
++) {
4870 node_cpumask
[i
] = 0;
4873 assigned_devices_index
= 0;
4881 /* first pass of option parsing */
4883 while (optind
< argc
) {
4884 if (argv
[optind
][0] != '-') {
4889 const QEMUOption
*popt
;
4891 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4892 switch (popt
->index
) {
4893 case QEMU_OPTION_nodefconfig
:
4902 fp
= fopen(CONFIG_QEMU_CONFDIR
"/qemu.conf", "r");
4904 if (qemu_config_parse(fp
) != 0) {
4910 fp
= fopen(CONFIG_QEMU_CONFDIR
"/target-" TARGET_ARCH
".conf", "r");
4912 if (qemu_config_parse(fp
) != 0) {
4919 /* second pass of option parsing */
4924 if (argv
[optind
][0] != '-') {
4925 hda_opts
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
4927 const QEMUOption
*popt
;
4929 popt
= lookup_opt(argc
, argv
, &optarg
, &optind
);
4930 switch(popt
->index
) {
4932 machine
= find_machine(optarg
);
4935 printf("Supported machines are:\n");
4936 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4938 printf("%-10s %s (alias of %s)\n",
4939 m
->alias
, m
->desc
, m
->name
);
4940 printf("%-10s %s%s\n",
4942 m
->is_default
? " (default)" : "");
4944 exit(*optarg
!= '?');
4947 case QEMU_OPTION_cpu
:
4948 /* hw initialization will check this */
4949 if (*optarg
== '?') {
4950 /* XXX: implement xxx_cpu_list for targets that still miss it */
4951 #if defined(cpu_list)
4952 cpu_list(stdout
, &fprintf
);
4959 case QEMU_OPTION_initrd
:
4960 initrd_filename
= optarg
;
4962 case QEMU_OPTION_hda
:
4964 hda_opts
= drive_add(optarg
, HD_ALIAS
, 0);
4966 hda_opts
= drive_add(optarg
, HD_ALIAS
4967 ",cyls=%d,heads=%d,secs=%d%s",
4968 0, cyls
, heads
, secs
,
4969 translation
== BIOS_ATA_TRANSLATION_LBA
?
4971 translation
== BIOS_ATA_TRANSLATION_NONE
?
4972 ",trans=none" : "");
4974 case QEMU_OPTION_hdb
:
4975 case QEMU_OPTION_hdc
:
4976 case QEMU_OPTION_hdd
:
4977 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
4979 case QEMU_OPTION_drive
:
4980 drive_add(NULL
, "%s", optarg
);
4982 case QEMU_OPTION_set
:
4983 if (qemu_set_option(optarg
) != 0)
4986 case QEMU_OPTION_global
:
4987 if (qemu_global_option(optarg
) != 0)
4990 case QEMU_OPTION_mtdblock
:
4991 drive_add(optarg
, MTD_ALIAS
);
4993 case QEMU_OPTION_sd
:
4994 drive_add(optarg
, SD_ALIAS
);
4996 case QEMU_OPTION_pflash
:
4997 drive_add(optarg
, PFLASH_ALIAS
);
4999 case QEMU_OPTION_snapshot
:
5002 case QEMU_OPTION_hdachs
:
5006 cyls
= strtol(p
, (char **)&p
, 0);
5007 if (cyls
< 1 || cyls
> 16383)
5012 heads
= strtol(p
, (char **)&p
, 0);
5013 if (heads
< 1 || heads
> 16)
5018 secs
= strtol(p
, (char **)&p
, 0);
5019 if (secs
< 1 || secs
> 63)
5023 if (!strcmp(p
, "none"))
5024 translation
= BIOS_ATA_TRANSLATION_NONE
;
5025 else if (!strcmp(p
, "lba"))
5026 translation
= BIOS_ATA_TRANSLATION_LBA
;
5027 else if (!strcmp(p
, "auto"))
5028 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5031 } else if (*p
!= '\0') {
5033 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5036 if (hda_opts
!= NULL
) {
5038 snprintf(num
, sizeof(num
), "%d", cyls
);
5039 qemu_opt_set(hda_opts
, "cyls", num
);
5040 snprintf(num
, sizeof(num
), "%d", heads
);
5041 qemu_opt_set(hda_opts
, "heads", num
);
5042 snprintf(num
, sizeof(num
), "%d", secs
);
5043 qemu_opt_set(hda_opts
, "secs", num
);
5044 if (translation
== BIOS_ATA_TRANSLATION_LBA
)
5045 qemu_opt_set(hda_opts
, "trans", "lba");
5046 if (translation
== BIOS_ATA_TRANSLATION_NONE
)
5047 qemu_opt_set(hda_opts
, "trans", "none");
5051 case QEMU_OPTION_numa
:
5052 if (nb_numa_nodes
>= MAX_NODES
) {
5053 fprintf(stderr
, "qemu: too many NUMA nodes\n");
5058 case QEMU_OPTION_nographic
:
5059 display_type
= DT_NOGRAPHIC
;
5061 #ifdef CONFIG_CURSES
5062 case QEMU_OPTION_curses
:
5063 display_type
= DT_CURSES
;
5066 case QEMU_OPTION_portrait
:
5069 case QEMU_OPTION_kernel
:
5070 kernel_filename
= optarg
;
5072 case QEMU_OPTION_append
:
5073 kernel_cmdline
= optarg
;
5075 case QEMU_OPTION_cdrom
:
5076 drive_add(optarg
, CDROM_ALIAS
);
5078 case QEMU_OPTION_boot
:
5080 static const char * const params
[] = {
5081 "order", "once", "menu", NULL
5083 char buf
[sizeof(boot_devices
)];
5084 char *standard_boot_devices
;
5087 if (!strchr(optarg
, '=')) {
5089 pstrcpy(buf
, sizeof(buf
), optarg
);
5090 } else if (check_params(buf
, sizeof(buf
), params
, optarg
) < 0) {
5092 "qemu: unknown boot parameter '%s' in '%s'\n",
5098 get_param_value(buf
, sizeof(buf
), "order", optarg
)) {
5099 boot_devices_bitmap
= parse_bootdevices(buf
);
5100 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5103 if (get_param_value(buf
, sizeof(buf
),
5105 boot_devices_bitmap
|= parse_bootdevices(buf
);
5106 standard_boot_devices
= qemu_strdup(boot_devices
);
5107 pstrcpy(boot_devices
, sizeof(boot_devices
), buf
);
5108 qemu_register_reset(restore_boot_devices
,
5109 standard_boot_devices
);
5111 if (get_param_value(buf
, sizeof(buf
),
5113 if (!strcmp(buf
, "on")) {
5115 } else if (!strcmp(buf
, "off")) {
5119 "qemu: invalid option value '%s'\n",
5127 case QEMU_OPTION_fda
:
5128 case QEMU_OPTION_fdb
:
5129 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
5132 case QEMU_OPTION_no_fd_bootchk
:
5136 case QEMU_OPTION_netdev
:
5137 if (net_client_parse(&qemu_netdev_opts
, optarg
) == -1) {
5141 case QEMU_OPTION_net
:
5142 if (net_client_parse(&qemu_net_opts
, optarg
) == -1) {
5147 case QEMU_OPTION_tftp
:
5148 legacy_tftp_prefix
= optarg
;
5150 case QEMU_OPTION_bootp
:
5151 legacy_bootp_filename
= optarg
;
5154 case QEMU_OPTION_smb
:
5155 if (net_slirp_smb(optarg
) < 0)
5159 case QEMU_OPTION_redir
:
5160 if (net_slirp_redir(optarg
) < 0)
5164 case QEMU_OPTION_bt
:
5165 add_device_config(DEV_BT
, optarg
);
5168 case QEMU_OPTION_audio_help
:
5172 case QEMU_OPTION_soundhw
:
5173 select_soundhw (optarg
);
5179 case QEMU_OPTION_version
:
5183 case QEMU_OPTION_m
: {
5187 value
= strtoul(optarg
, &ptr
, 10);
5189 case 0: case 'M': case 'm':
5196 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
5200 /* On 32-bit hosts, QEMU is limited by virtual address space */
5201 if (value
> (2047 << 20) && HOST_LONG_BITS
== 32) {
5202 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
5205 if (value
!= (uint64_t)(ram_addr_t
)value
) {
5206 fprintf(stderr
, "qemu: ram size too large\n");
5215 const CPULogItem
*item
;
5217 mask
= cpu_str_to_log_mask(optarg
);
5219 printf("Log items (comma separated):\n");
5220 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
5221 printf("%-10s %s\n", item
->name
, item
->help
);
5229 gdbstub_dev
= "tcp::" DEFAULT_GDBSTUB_PORT
;
5231 case QEMU_OPTION_gdb
:
5232 gdbstub_dev
= optarg
;
5237 case QEMU_OPTION_bios
:
5240 case QEMU_OPTION_singlestep
:
5247 keyboard_layout
= optarg
;
5249 case QEMU_OPTION_localtime
:
5252 case QEMU_OPTION_vga
:
5253 select_vgahw (optarg
);
5255 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5261 w
= strtol(p
, (char **)&p
, 10);
5264 fprintf(stderr
, "qemu: invalid resolution or depth\n");
5270 h
= strtol(p
, (char **)&p
, 10);
5275 depth
= strtol(p
, (char **)&p
, 10);
5276 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
5277 depth
!= 24 && depth
!= 32)
5279 } else if (*p
== '\0') {
5280 depth
= graphic_depth
;
5287 graphic_depth
= depth
;
5291 case QEMU_OPTION_echr
:
5294 term_escape_char
= strtol(optarg
, &r
, 0);
5296 printf("Bad argument to echr\n");
5299 case QEMU_OPTION_monitor
:
5300 monitor_parse(optarg
, "readline");
5301 default_monitor
= 0;
5303 case QEMU_OPTION_qmp
:
5304 monitor_parse(optarg
, "control");
5305 default_monitor
= 0;
5307 case QEMU_OPTION_mon
:
5308 opts
= qemu_opts_parse(&qemu_mon_opts
, optarg
, "chardev");
5310 fprintf(stderr
, "parse error: %s\n", optarg
);
5313 default_monitor
= 0;
5315 case QEMU_OPTION_chardev
:
5316 opts
= qemu_opts_parse(&qemu_chardev_opts
, optarg
, "backend");
5318 fprintf(stderr
, "parse error: %s\n", optarg
);
5322 case QEMU_OPTION_serial
:
5323 add_device_config(DEV_SERIAL
, optarg
);
5326 case QEMU_OPTION_watchdog
:
5329 "qemu: only one watchdog option may be given\n");
5334 case QEMU_OPTION_watchdog_action
:
5335 if (select_watchdog_action(optarg
) == -1) {
5336 fprintf(stderr
, "Unknown -watchdog-action parameter\n");
5340 case QEMU_OPTION_virtiocon
:
5341 add_device_config(DEV_VIRTCON
, optarg
);
5342 default_virtcon
= 0;
5344 case QEMU_OPTION_parallel
:
5345 add_device_config(DEV_PARALLEL
, optarg
);
5346 default_parallel
= 0;
5348 case QEMU_OPTION_debugcon
:
5349 add_device_config(DEV_DEBUGCON
, optarg
);
5351 case QEMU_OPTION_loadvm
:
5354 case QEMU_OPTION_full_screen
:
5358 case QEMU_OPTION_no_frame
:
5361 case QEMU_OPTION_alt_grab
:
5364 case QEMU_OPTION_ctrl_grab
:
5367 case QEMU_OPTION_no_quit
:
5370 case QEMU_OPTION_sdl
:
5371 display_type
= DT_SDL
;
5374 case QEMU_OPTION_pidfile
:
5378 case QEMU_OPTION_win2k_hack
:
5379 win2k_install_hack
= 1;
5381 case QEMU_OPTION_rtc_td_hack
:
5384 case QEMU_OPTION_acpitable
:
5385 if(acpi_table_add(optarg
) < 0) {
5386 fprintf(stderr
, "Wrong acpi table provided\n");
5390 case QEMU_OPTION_smbios
:
5391 if(smbios_entry_add(optarg
) < 0) {
5392 fprintf(stderr
, "Wrong smbios provided\n");
5399 case QEMU_OPTION_enable_kvm
:
5403 case QEMU_OPTION_no_kvm
:
5406 case QEMU_OPTION_no_kvm_irqchip
: {
5411 case QEMU_OPTION_no_kvm_pit
: {
5415 case QEMU_OPTION_no_kvm_pit_reinjection
: {
5416 kvm_pit_reinject
= 0;
5419 case QEMU_OPTION_enable_nesting
: {
5423 #if defined(TARGET_I386) || defined(TARGET_X86_64) || defined(TARGET_IA64) || defined(__linux__)
5424 case QEMU_OPTION_pcidevice
:
5425 if (assigned_devices_index
>= MAX_DEV_ASSIGN_CMDLINE
) {
5426 fprintf(stderr
, "Too many assigned devices\n");
5429 assigned_devices
[assigned_devices_index
] = optarg
;
5430 assigned_devices_index
++;
5434 case QEMU_OPTION_usb
:
5437 case QEMU_OPTION_usbdevice
:
5439 add_device_config(DEV_USB
, optarg
);
5441 case QEMU_OPTION_device
:
5442 if (!qemu_opts_parse(&qemu_device_opts
, optarg
, "driver")) {
5446 case QEMU_OPTION_smp
:
5449 fprintf(stderr
, "Invalid number of CPUs\n");
5452 if (max_cpus
< smp_cpus
) {
5453 fprintf(stderr
, "maxcpus must be equal to or greater than "
5457 if (max_cpus
> 255) {
5458 fprintf(stderr
, "Unsupported number of maxcpus\n");
5462 case QEMU_OPTION_vnc
:
5463 display_type
= DT_VNC
;
5464 vnc_display
= optarg
;
5467 case QEMU_OPTION_no_acpi
:
5470 case QEMU_OPTION_no_hpet
:
5473 case QEMU_OPTION_balloon
:
5474 if (balloon_parse(optarg
) < 0) {
5475 fprintf(stderr
, "Unknown -balloon argument %s\n", optarg
);
5480 case QEMU_OPTION_no_reboot
:
5483 case QEMU_OPTION_no_shutdown
:
5486 case QEMU_OPTION_show_cursor
:
5489 case QEMU_OPTION_uuid
:
5490 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
5491 fprintf(stderr
, "Fail to parse UUID string."
5492 " Wrong format.\n");
5497 case QEMU_OPTION_daemonize
:
5501 case QEMU_OPTION_option_rom
:
5502 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
5503 fprintf(stderr
, "Too many option ROMs\n");
5506 option_rom
[nb_option_roms
] = optarg
;
5509 #if defined(TARGET_ARM) || defined(TARGET_M68K)
5510 case QEMU_OPTION_semihosting
:
5511 semihosting_enabled
= 1;
5514 case QEMU_OPTION_tdf
:
5517 case QEMU_OPTION_kvm_shadow_memory
:
5518 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
5520 case QEMU_OPTION_mempath
:
5524 case QEMU_OPTION_mem_prealloc
:
5525 mem_prealloc
= !mem_prealloc
;
5528 case QEMU_OPTION_name
:
5529 qemu_name
= qemu_strdup(optarg
);
5531 char *p
= strchr(qemu_name
, ',');
5534 if (strncmp(p
, "process=", 8)) {
5535 fprintf(stderr
, "Unknown subargument %s to -name", p
);
5543 #if defined(TARGET_SPARC) || defined(TARGET_PPC)
5544 case QEMU_OPTION_prom_env
:
5545 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
5546 fprintf(stderr
, "Too many prom variables\n");
5549 prom_envs
[nb_prom_envs
] = optarg
;
5554 case QEMU_OPTION_old_param
:
5558 case QEMU_OPTION_clock
:
5559 configure_alarms(optarg
);
5561 case QEMU_OPTION_startdate
:
5562 configure_rtc_date_offset(optarg
, 1);
5564 case QEMU_OPTION_rtc
:
5565 opts
= qemu_opts_parse(&qemu_rtc_opts
, optarg
, NULL
);
5567 fprintf(stderr
, "parse error: %s\n", optarg
);
5570 configure_rtc(opts
);
5572 case QEMU_OPTION_tb_size
:
5573 tb_size
= strtol(optarg
, NULL
, 0);
5577 case QEMU_OPTION_icount
:
5579 if (strcmp(optarg
, "auto") == 0) {
5580 icount_time_shift
= -1;
5582 icount_time_shift
= strtol(optarg
, NULL
, 0);
5585 case QEMU_OPTION_incoming
:
5588 case QEMU_OPTION_nodefaults
:
5590 default_parallel
= 0;
5591 default_virtcon
= 0;
5592 default_monitor
= 0;
5600 case QEMU_OPTION_chroot
:
5601 chroot_dir
= optarg
;
5603 case QEMU_OPTION_runas
:
5606 case QEMU_OPTION_nvram
:
5611 case QEMU_OPTION_xen_domid
:
5612 xen_domid
= atoi(optarg
);
5614 case QEMU_OPTION_xen_create
:
5615 xen_mode
= XEN_CREATE
;
5617 case QEMU_OPTION_xen_attach
:
5618 xen_mode
= XEN_ATTACH
;
5621 case QEMU_OPTION_readconfig
:
5624 fp
= fopen(optarg
, "r");
5626 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5629 if (qemu_config_parse(fp
) != 0) {
5635 case QEMU_OPTION_writeconfig
:
5638 if (strcmp(optarg
, "-") == 0) {
5641 fp
= fopen(optarg
, "w");
5643 fprintf(stderr
, "open %s: %s\n", optarg
, strerror(errno
));
5647 qemu_config_write(fp
);
5655 /* If no data_dir is specified then try to find it relative to the
5658 data_dir
= find_datadir(argv
[0]);
5660 /* If all else fails use the install patch specified when building. */
5662 data_dir
= CONFIG_QEMU_SHAREDIR
;
5666 * Default to max_cpus = smp_cpus, in case the user doesn't
5667 * specify a max_cpus value.
5670 max_cpus
= smp_cpus
;
5672 machine
->max_cpus
= machine
->max_cpus
?: 1; /* Default to UP */
5673 if (smp_cpus
> machine
->max_cpus
) {
5674 fprintf(stderr
, "Number of SMP cpus requested (%d), exceeds max cpus "
5675 "supported by machine `%s' (%d)\n", smp_cpus
, machine
->name
,
5680 qemu_opts_foreach(&qemu_device_opts
, default_driver_check
, NULL
, 0);
5681 qemu_opts_foreach(&qemu_global_opts
, default_driver_check
, NULL
, 0);
5683 if (machine
->no_serial
) {
5686 if (machine
->no_parallel
) {
5687 default_parallel
= 0;
5689 if (!machine
->use_virtcon
) {
5690 default_virtcon
= 0;
5692 if (machine
->no_vga
) {
5695 if (machine
->no_floppy
) {
5698 if (machine
->no_cdrom
) {
5701 if (machine
->no_sdcard
) {
5705 if (display_type
== DT_NOGRAPHIC
) {
5706 if (default_parallel
)
5707 add_device_config(DEV_PARALLEL
, "null");
5708 if (default_serial
&& default_monitor
) {
5709 add_device_config(DEV_SERIAL
, "mon:stdio");
5710 } else if (default_virtcon
&& default_monitor
) {
5711 add_device_config(DEV_VIRTCON
, "mon:stdio");
5714 add_device_config(DEV_SERIAL
, "stdio");
5715 if (default_virtcon
)
5716 add_device_config(DEV_VIRTCON
, "stdio");
5717 if (default_monitor
)
5718 monitor_parse("stdio", "readline");
5722 add_device_config(DEV_SERIAL
, "vc:80Cx24C");
5723 if (default_parallel
)
5724 add_device_config(DEV_PARALLEL
, "vc:80Cx24C");
5725 if (default_monitor
)
5726 monitor_parse("vc:80Cx24C", "readline");
5727 if (default_virtcon
)
5728 add_device_config(DEV_VIRTCON
, "vc:80Cx24C");
5731 vga_interface_type
= VGA_CIRRUS
;
5733 if (qemu_opts_foreach(&qemu_chardev_opts
, chardev_init_func
, NULL
, 1) != 0)
5740 if (pipe(fds
) == -1)
5751 len
= read(fds
[0], &status
, 1);
5752 if (len
== -1 && (errno
== EINTR
))
5757 else if (status
== 1) {
5758 fprintf(stderr
, "Could not acquire pidfile: %s\n", strerror(errno
));
5766 qemu_set_cloexec(fds
[1]);
5778 signal(SIGTSTP
, SIG_IGN
);
5779 signal(SIGTTOU
, SIG_IGN
);
5780 signal(SIGTTIN
, SIG_IGN
);
5784 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
5788 if (write(fds
[1], &status
, 1) != 1) {
5789 perror("daemonize. Writing to pipe\n");
5793 fprintf(stderr
, "Could not acquire pid file: %s\n", strerror(errno
));
5797 if (kvm_enabled()) {
5800 ret
= kvm_init(smp_cpus
);
5802 #if defined(KVM_UPSTREAM) || defined(CONFIG_NO_CPU_EMULATION)
5803 fprintf(stderr
, "failed to initialize KVM\n");
5806 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
5811 if (qemu_init_main_loop()) {
5812 fprintf(stderr
, "qemu_init_main_loop failed\n");
5815 linux_boot
= (kernel_filename
!= NULL
);
5817 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
5818 fprintf(stderr
, "-append only allowed with -kernel option\n");
5822 if (!linux_boot
&& initrd_filename
!= NULL
) {
5823 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
5828 /* Win32 doesn't support line-buffering and requires size >= 2 */
5829 setvbuf(stdout
, NULL
, _IOLBF
, 0);
5832 if (init_timer_alarm() < 0) {
5833 fprintf(stderr
, "could not initialize alarm timer\n");
5836 if (use_icount
&& icount_time_shift
< 0) {
5838 /* 125MIPS seems a reasonable initial guess at the guest speed.
5839 It will be corrected fairly quickly anyway. */
5840 icount_time_shift
= 3;
5841 init_icount_adjust();
5848 if (net_init_clients() < 0) {
5852 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
5853 net_set_boot_mask(net_boot
);
5855 /* init the bluetooth world */
5856 if (foreach_device_config(DEV_BT
, bt_parse
))
5859 /* init the memory */
5861 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5863 /* init the dynamic translator */
5864 cpu_exec_init_all(tb_size
* 1024 * 1024);
5866 bdrv_init_with_whitelist();
5870 if (default_cdrom
) {
5871 /* we always create the cdrom drive, even if no disk is there */
5872 drive_add(NULL
, CDROM_ALIAS
);
5875 if (default_floppy
) {
5876 /* we always create at least one floppy */
5877 drive_add(NULL
, FD_ALIAS
, 0);
5880 if (default_sdcard
) {
5881 /* we always create one sd slot, even if no card is in it */
5882 drive_add(NULL
, SD_ALIAS
);
5885 /* open the virtual block devices */
5887 qemu_opts_foreach(&qemu_drive_opts
, drive_enable_snapshot
, NULL
, 0);
5888 if (qemu_opts_foreach(&qemu_drive_opts
, drive_init_func
, machine
, 1) != 0)
5891 vmstate_register(0, &vmstate_timers
,&timers_state
);
5892 register_savevm_live("ram", 0, 3, NULL
, ram_save_live
, NULL
,
5895 if (nb_numa_nodes
> 0) {
5898 if (nb_numa_nodes
> smp_cpus
) {
5899 nb_numa_nodes
= smp_cpus
;
5902 /* If no memory size if given for any node, assume the default case
5903 * and distribute the available memory equally across all nodes
5905 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5906 if (node_mem
[i
] != 0)
5909 if (i
== nb_numa_nodes
) {
5910 uint64_t usedmem
= 0;
5912 /* On Linux, the each node's border has to be 8MB aligned,
5913 * the final node gets the rest.
5915 for (i
= 0; i
< nb_numa_nodes
- 1; i
++) {
5916 node_mem
[i
] = (ram_size
/ nb_numa_nodes
) & ~((1 << 23UL) - 1);
5917 usedmem
+= node_mem
[i
];
5919 node_mem
[i
] = ram_size
- usedmem
;
5922 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5923 if (node_cpumask
[i
] != 0)
5926 /* assigning the VCPUs round-robin is easier to implement, guest OSes
5927 * must cope with this anyway, because there are BIOSes out there in
5928 * real machines which also use this scheme.
5930 if (i
== nb_numa_nodes
) {
5931 for (i
= 0; i
< smp_cpus
; i
++) {
5932 node_cpumask
[i
% nb_numa_nodes
] |= 1 << i
;
5937 if (foreach_device_config(DEV_SERIAL
, serial_parse
) < 0)
5939 if (foreach_device_config(DEV_PARALLEL
, parallel_parse
) < 0)
5941 if (foreach_device_config(DEV_VIRTCON
, virtcon_parse
) < 0)
5943 if (foreach_device_config(DEV_DEBUGCON
, debugcon_parse
) < 0)
5946 module_call_init(MODULE_INIT_DEVICE
);
5948 if (qemu_opts_foreach(&qemu_device_opts
, device_help_func
, NULL
, 0) != 0)
5952 i
= select_watchdog(watchdog
);
5954 exit (i
== 1 ? 1 : 0);
5957 if (machine
->compat_props
) {
5958 qdev_prop_register_global_list(machine
->compat_props
);
5962 machine
->init(ram_size
, boot_devices
,
5963 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
5967 /* must be after terminal init, SDL library changes signal handlers */
5971 for (env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
5972 for (i
= 0; i
< nb_numa_nodes
; i
++) {
5973 if (node_cpumask
[i
] & (1 << env
->cpu_index
)) {
5979 current_machine
= machine
;
5981 /* init USB devices */
5983 if (foreach_device_config(DEV_USB
, usb_parse
) < 0)
5987 /* init generic devices */
5988 if (qemu_opts_foreach(&qemu_device_opts
, device_init_func
, NULL
, 1) != 0)
5992 dumb_display_init();
5993 /* just use the first displaystate for the moment */
5996 if (display_type
== DT_DEFAULT
) {
5997 #if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5998 display_type
= DT_SDL
;
6000 display_type
= DT_VNC
;
6001 vnc_display
= "localhost:0,to=99";
6007 switch (display_type
) {
6010 #if defined(CONFIG_CURSES)
6012 curses_display_init(ds
, full_screen
);
6015 #if defined(CONFIG_SDL)
6017 sdl_display_init(ds
, full_screen
, no_frame
);
6019 #elif defined(CONFIG_COCOA)
6021 cocoa_display_init(ds
, full_screen
);
6025 vnc_display_init(ds
);
6026 if (vnc_display_open(ds
, vnc_display
) < 0)
6029 if (show_vnc_port
) {
6030 printf("VNC server running on `%s'\n", vnc_display_local_addr(ds
));
6038 dcl
= ds
->listeners
;
6039 while (dcl
!= NULL
) {
6040 if (dcl
->dpy_refresh
!= NULL
) {
6041 ds
->gui_timer
= qemu_new_timer(rt_clock
, gui_update
, ds
);
6042 qemu_mod_timer(ds
->gui_timer
, qemu_get_clock(rt_clock
));
6047 if (display_type
== DT_NOGRAPHIC
|| display_type
== DT_VNC
) {
6048 nographic_timer
= qemu_new_timer(rt_clock
, nographic_update
, NULL
);
6049 qemu_mod_timer(nographic_timer
, qemu_get_clock(rt_clock
));
6052 text_consoles_set_display(display_state
);
6054 if (qemu_opts_foreach(&qemu_mon_opts
, mon_init_func
, NULL
, 1) != 0)
6057 if (gdbstub_dev
&& gdbserver_start(gdbstub_dev
) < 0) {
6058 fprintf(stderr
, "qemu: could not open gdbserver on device '%s'\n",
6063 qdev_machine_creation_done();
6065 if (rom_load_all() != 0) {
6066 fprintf(stderr
, "rom loading failed\n");
6070 qemu_system_reset();
6072 if (load_vmstate(cur_mon
, loadvm
) < 0) {
6078 qemu_start_incoming_migration(incoming
);
6079 } else if (autostart
) {
6089 len
= write(fds
[1], &status
, 1);
6090 if (len
== -1 && (errno
== EINTR
))
6097 perror("not able to chdir to /");
6100 TFR(fd
= qemu_open("/dev/null", O_RDWR
));
6106 pwd
= getpwnam(run_as
);
6108 fprintf(stderr
, "User \"%s\" doesn't exist\n", run_as
);
6114 if (chroot(chroot_dir
) < 0) {
6115 fprintf(stderr
, "chroot failed\n");
6119 perror("not able to chdir to /");
6125 if (setgid(pwd
->pw_gid
) < 0) {
6126 fprintf(stderr
, "Failed to setgid(%d)\n", pwd
->pw_gid
);
6129 if (setuid(pwd
->pw_uid
) < 0) {
6130 fprintf(stderr
, "Failed to setuid(%d)\n", pwd
->pw_uid
);
6133 if (setuid(0) != -1) {
6134 fprintf(stderr
, "Dropping privileges failed\n");