]> git.proxmox.com Git - mirror_qemu.git/blob - vl.c
initial support for up to 255 CPUs
[mirror_qemu.git] / vl.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 Fabrice Bellard
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24 #include "vl.h"
25
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
32
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <dirent.h>
43 #include <netdb.h>
44 #ifdef _BSD
45 #include <sys/stat.h>
46 #ifndef __APPLE__
47 #include <libutil.h>
48 #endif
49 #else
50 #include <linux/if.h>
51 #include <linux/if_tun.h>
52 #include <pty.h>
53 #include <malloc.h>
54 #include <linux/rtc.h>
55 #include <linux/ppdev.h>
56 #endif
57 #endif
58
59 #if defined(CONFIG_SLIRP)
60 #include "libslirp.h"
61 #endif
62
63 #ifdef _WIN32
64 #include <malloc.h>
65 #include <sys/timeb.h>
66 #include <windows.h>
67 #define getopt_long_only getopt_long
68 #define memalign(align, size) malloc(size)
69 #endif
70
71 #ifdef CONFIG_SDL
72 #ifdef __APPLE__
73 #include <SDL/SDL.h>
74 #endif
75 #endif /* CONFIG_SDL */
76
77 #ifdef CONFIG_COCOA
78 #undef main
79 #define main qemu_main
80 #endif /* CONFIG_COCOA */
81
82 #include "disas.h"
83
84 #include "exec-all.h"
85
86 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
87
88 //#define DEBUG_UNUSED_IOPORT
89 //#define DEBUG_IOPORT
90
91 #if !defined(CONFIG_SOFTMMU)
92 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
93 #else
94 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
95 #endif
96
97 #ifdef TARGET_PPC
98 #define DEFAULT_RAM_SIZE 144
99 #else
100 #define DEFAULT_RAM_SIZE 128
101 #endif
102 /* in ms */
103 #define GUI_REFRESH_INTERVAL 30
104
105 /* XXX: use a two level table to limit memory usage */
106 #define MAX_IOPORTS 65536
107
108 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
109 char phys_ram_file[1024];
110 void *ioport_opaque[MAX_IOPORTS];
111 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
112 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
113 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
114 int vga_ram_size;
115 int bios_size;
116 static DisplayState display_state;
117 int nographic;
118 const char* keyboard_layout = NULL;
119 int64_t ticks_per_sec;
120 int boot_device = 'c';
121 int ram_size;
122 int pit_min_timer_count = 0;
123 int nb_nics;
124 NICInfo nd_table[MAX_NICS];
125 QEMUTimer *gui_timer;
126 int vm_running;
127 #ifdef HAS_AUDIO
128 int audio_enabled = 0;
129 int sb16_enabled = 0;
130 int adlib_enabled = 0;
131 int gus_enabled = 0;
132 int es1370_enabled = 0;
133 #endif
134 int rtc_utc = 1;
135 int cirrus_vga_enabled = 1;
136 #ifdef TARGET_SPARC
137 int graphic_width = 1024;
138 int graphic_height = 768;
139 #else
140 int graphic_width = 800;
141 int graphic_height = 600;
142 #endif
143 int graphic_depth = 15;
144 int full_screen = 0;
145 TextConsole *vga_console;
146 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
147 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
148 #ifdef TARGET_I386
149 int win2k_install_hack = 0;
150 #endif
151 int usb_enabled = 0;
152 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
153 USBDevice *vm_usb_hub;
154 static VLANState *first_vlan;
155 int smp_cpus = 1;
156 #if defined(TARGET_SPARC)
157 #define MAX_CPUS 16
158 #elif defined(TARGET_I386)
159 #define MAX_CPUS 255
160 #else
161 #define MAX_CPUS 1
162 #endif
163
164 /***********************************************************/
165 /* x86 ISA bus support */
166
167 target_phys_addr_t isa_mem_base = 0;
168 PicState2 *isa_pic;
169
170 uint32_t default_ioport_readb(void *opaque, uint32_t address)
171 {
172 #ifdef DEBUG_UNUSED_IOPORT
173 fprintf(stderr, "inb: port=0x%04x\n", address);
174 #endif
175 return 0xff;
176 }
177
178 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
179 {
180 #ifdef DEBUG_UNUSED_IOPORT
181 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
182 #endif
183 }
184
185 /* default is to make two byte accesses */
186 uint32_t default_ioport_readw(void *opaque, uint32_t address)
187 {
188 uint32_t data;
189 data = ioport_read_table[0][address](ioport_opaque[address], address);
190 address = (address + 1) & (MAX_IOPORTS - 1);
191 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
192 return data;
193 }
194
195 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
196 {
197 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
198 address = (address + 1) & (MAX_IOPORTS - 1);
199 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
200 }
201
202 uint32_t default_ioport_readl(void *opaque, uint32_t address)
203 {
204 #ifdef DEBUG_UNUSED_IOPORT
205 fprintf(stderr, "inl: port=0x%04x\n", address);
206 #endif
207 return 0xffffffff;
208 }
209
210 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
211 {
212 #ifdef DEBUG_UNUSED_IOPORT
213 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
214 #endif
215 }
216
217 void init_ioports(void)
218 {
219 int i;
220
221 for(i = 0; i < MAX_IOPORTS; i++) {
222 ioport_read_table[0][i] = default_ioport_readb;
223 ioport_write_table[0][i] = default_ioport_writeb;
224 ioport_read_table[1][i] = default_ioport_readw;
225 ioport_write_table[1][i] = default_ioport_writew;
226 ioport_read_table[2][i] = default_ioport_readl;
227 ioport_write_table[2][i] = default_ioport_writel;
228 }
229 }
230
231 /* size is the word size in byte */
232 int register_ioport_read(int start, int length, int size,
233 IOPortReadFunc *func, void *opaque)
234 {
235 int i, bsize;
236
237 if (size == 1) {
238 bsize = 0;
239 } else if (size == 2) {
240 bsize = 1;
241 } else if (size == 4) {
242 bsize = 2;
243 } else {
244 hw_error("register_ioport_read: invalid size");
245 return -1;
246 }
247 for(i = start; i < start + length; i += size) {
248 ioport_read_table[bsize][i] = func;
249 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
250 hw_error("register_ioport_read: invalid opaque");
251 ioport_opaque[i] = opaque;
252 }
253 return 0;
254 }
255
256 /* size is the word size in byte */
257 int register_ioport_write(int start, int length, int size,
258 IOPortWriteFunc *func, void *opaque)
259 {
260 int i, bsize;
261
262 if (size == 1) {
263 bsize = 0;
264 } else if (size == 2) {
265 bsize = 1;
266 } else if (size == 4) {
267 bsize = 2;
268 } else {
269 hw_error("register_ioport_write: invalid size");
270 return -1;
271 }
272 for(i = start; i < start + length; i += size) {
273 ioport_write_table[bsize][i] = func;
274 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
275 hw_error("register_ioport_read: invalid opaque");
276 ioport_opaque[i] = opaque;
277 }
278 return 0;
279 }
280
281 void isa_unassign_ioport(int start, int length)
282 {
283 int i;
284
285 for(i = start; i < start + length; i++) {
286 ioport_read_table[0][i] = default_ioport_readb;
287 ioport_read_table[1][i] = default_ioport_readw;
288 ioport_read_table[2][i] = default_ioport_readl;
289
290 ioport_write_table[0][i] = default_ioport_writeb;
291 ioport_write_table[1][i] = default_ioport_writew;
292 ioport_write_table[2][i] = default_ioport_writel;
293 }
294 }
295
296 /***********************************************************/
297
298 void pstrcpy(char *buf, int buf_size, const char *str)
299 {
300 int c;
301 char *q = buf;
302
303 if (buf_size <= 0)
304 return;
305
306 for(;;) {
307 c = *str++;
308 if (c == 0 || q >= buf + buf_size - 1)
309 break;
310 *q++ = c;
311 }
312 *q = '\0';
313 }
314
315 /* strcat and truncate. */
316 char *pstrcat(char *buf, int buf_size, const char *s)
317 {
318 int len;
319 len = strlen(buf);
320 if (len < buf_size)
321 pstrcpy(buf + len, buf_size - len, s);
322 return buf;
323 }
324
325 int strstart(const char *str, const char *val, const char **ptr)
326 {
327 const char *p, *q;
328 p = str;
329 q = val;
330 while (*q != '\0') {
331 if (*p != *q)
332 return 0;
333 p++;
334 q++;
335 }
336 if (ptr)
337 *ptr = p;
338 return 1;
339 }
340
341 /* return the size or -1 if error */
342 int get_image_size(const char *filename)
343 {
344 int fd, size;
345 fd = open(filename, O_RDONLY | O_BINARY);
346 if (fd < 0)
347 return -1;
348 size = lseek(fd, 0, SEEK_END);
349 close(fd);
350 return size;
351 }
352
353 /* return the size or -1 if error */
354 int load_image(const char *filename, uint8_t *addr)
355 {
356 int fd, size;
357 fd = open(filename, O_RDONLY | O_BINARY);
358 if (fd < 0)
359 return -1;
360 size = lseek(fd, 0, SEEK_END);
361 lseek(fd, 0, SEEK_SET);
362 if (read(fd, addr, size) != size) {
363 close(fd);
364 return -1;
365 }
366 close(fd);
367 return size;
368 }
369
370 void cpu_outb(CPUState *env, int addr, int val)
371 {
372 #ifdef DEBUG_IOPORT
373 if (loglevel & CPU_LOG_IOPORT)
374 fprintf(logfile, "outb: %04x %02x\n", addr, val);
375 #endif
376 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
377 }
378
379 void cpu_outw(CPUState *env, int addr, int val)
380 {
381 #ifdef DEBUG_IOPORT
382 if (loglevel & CPU_LOG_IOPORT)
383 fprintf(logfile, "outw: %04x %04x\n", addr, val);
384 #endif
385 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
386 }
387
388 void cpu_outl(CPUState *env, int addr, int val)
389 {
390 #ifdef DEBUG_IOPORT
391 if (loglevel & CPU_LOG_IOPORT)
392 fprintf(logfile, "outl: %04x %08x\n", addr, val);
393 #endif
394 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
395 }
396
397 int cpu_inb(CPUState *env, int addr)
398 {
399 int val;
400 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
401 #ifdef DEBUG_IOPORT
402 if (loglevel & CPU_LOG_IOPORT)
403 fprintf(logfile, "inb : %04x %02x\n", addr, val);
404 #endif
405 return val;
406 }
407
408 int cpu_inw(CPUState *env, int addr)
409 {
410 int val;
411 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
412 #ifdef DEBUG_IOPORT
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "inw : %04x %04x\n", addr, val);
415 #endif
416 return val;
417 }
418
419 int cpu_inl(CPUState *env, int addr)
420 {
421 int val;
422 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
423 #ifdef DEBUG_IOPORT
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inl : %04x %08x\n", addr, val);
426 #endif
427 return val;
428 }
429
430 /***********************************************************/
431 void hw_error(const char *fmt, ...)
432 {
433 va_list ap;
434 CPUState *env;
435
436 va_start(ap, fmt);
437 fprintf(stderr, "qemu: hardware error: ");
438 vfprintf(stderr, fmt, ap);
439 fprintf(stderr, "\n");
440 for(env = first_cpu; env != NULL; env = env->next_cpu) {
441 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
442 #ifdef TARGET_I386
443 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
444 #else
445 cpu_dump_state(env, stderr, fprintf, 0);
446 #endif
447 }
448 va_end(ap);
449 abort();
450 }
451
452 /***********************************************************/
453 /* keyboard/mouse */
454
455 static QEMUPutKBDEvent *qemu_put_kbd_event;
456 static void *qemu_put_kbd_event_opaque;
457 static QEMUPutMouseEvent *qemu_put_mouse_event;
458 static void *qemu_put_mouse_event_opaque;
459
460 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
461 {
462 qemu_put_kbd_event_opaque = opaque;
463 qemu_put_kbd_event = func;
464 }
465
466 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque)
467 {
468 qemu_put_mouse_event_opaque = opaque;
469 qemu_put_mouse_event = func;
470 }
471
472 void kbd_put_keycode(int keycode)
473 {
474 if (qemu_put_kbd_event) {
475 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
476 }
477 }
478
479 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
480 {
481 if (qemu_put_mouse_event) {
482 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
483 dx, dy, dz, buttons_state);
484 }
485 }
486
487 /***********************************************************/
488 /* timers */
489
490 #if defined(__powerpc__)
491
492 static inline uint32_t get_tbl(void)
493 {
494 uint32_t tbl;
495 asm volatile("mftb %0" : "=r" (tbl));
496 return tbl;
497 }
498
499 static inline uint32_t get_tbu(void)
500 {
501 uint32_t tbl;
502 asm volatile("mftbu %0" : "=r" (tbl));
503 return tbl;
504 }
505
506 int64_t cpu_get_real_ticks(void)
507 {
508 uint32_t l, h, h1;
509 /* NOTE: we test if wrapping has occurred */
510 do {
511 h = get_tbu();
512 l = get_tbl();
513 h1 = get_tbu();
514 } while (h != h1);
515 return ((int64_t)h << 32) | l;
516 }
517
518 #elif defined(__i386__)
519
520 int64_t cpu_get_real_ticks(void)
521 {
522 int64_t val;
523 asm volatile ("rdtsc" : "=A" (val));
524 return val;
525 }
526
527 #elif defined(__x86_64__)
528
529 int64_t cpu_get_real_ticks(void)
530 {
531 uint32_t low,high;
532 int64_t val;
533 asm volatile("rdtsc" : "=a" (low), "=d" (high));
534 val = high;
535 val <<= 32;
536 val |= low;
537 return val;
538 }
539
540 #elif defined(__ia64)
541
542 int64_t cpu_get_real_ticks(void)
543 {
544 int64_t val;
545 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
546 return val;
547 }
548
549 #elif defined(__s390__)
550
551 int64_t cpu_get_real_ticks(void)
552 {
553 int64_t val;
554 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
555 return val;
556 }
557
558 #else
559 #error unsupported CPU
560 #endif
561
562 static int64_t cpu_ticks_offset;
563 static int cpu_ticks_enabled;
564
565 static inline int64_t cpu_get_ticks(void)
566 {
567 if (!cpu_ticks_enabled) {
568 return cpu_ticks_offset;
569 } else {
570 return cpu_get_real_ticks() + cpu_ticks_offset;
571 }
572 }
573
574 /* enable cpu_get_ticks() */
575 void cpu_enable_ticks(void)
576 {
577 if (!cpu_ticks_enabled) {
578 cpu_ticks_offset -= cpu_get_real_ticks();
579 cpu_ticks_enabled = 1;
580 }
581 }
582
583 /* disable cpu_get_ticks() : the clock is stopped. You must not call
584 cpu_get_ticks() after that. */
585 void cpu_disable_ticks(void)
586 {
587 if (cpu_ticks_enabled) {
588 cpu_ticks_offset = cpu_get_ticks();
589 cpu_ticks_enabled = 0;
590 }
591 }
592
593 static int64_t get_clock(void)
594 {
595 #ifdef _WIN32
596 struct _timeb tb;
597 _ftime(&tb);
598 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
599 #else
600 struct timeval tv;
601 gettimeofday(&tv, NULL);
602 return tv.tv_sec * 1000000LL + tv.tv_usec;
603 #endif
604 }
605
606 void cpu_calibrate_ticks(void)
607 {
608 int64_t usec, ticks;
609
610 usec = get_clock();
611 ticks = cpu_get_real_ticks();
612 #ifdef _WIN32
613 Sleep(50);
614 #else
615 usleep(50 * 1000);
616 #endif
617 usec = get_clock() - usec;
618 ticks = cpu_get_real_ticks() - ticks;
619 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
620 }
621
622 /* compute with 96 bit intermediate result: (a*b)/c */
623 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
624 {
625 union {
626 uint64_t ll;
627 struct {
628 #ifdef WORDS_BIGENDIAN
629 uint32_t high, low;
630 #else
631 uint32_t low, high;
632 #endif
633 } l;
634 } u, res;
635 uint64_t rl, rh;
636
637 u.ll = a;
638 rl = (uint64_t)u.l.low * (uint64_t)b;
639 rh = (uint64_t)u.l.high * (uint64_t)b;
640 rh += (rl >> 32);
641 res.l.high = rh / c;
642 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
643 return res.ll;
644 }
645
646 #define QEMU_TIMER_REALTIME 0
647 #define QEMU_TIMER_VIRTUAL 1
648
649 struct QEMUClock {
650 int type;
651 /* XXX: add frequency */
652 };
653
654 struct QEMUTimer {
655 QEMUClock *clock;
656 int64_t expire_time;
657 QEMUTimerCB *cb;
658 void *opaque;
659 struct QEMUTimer *next;
660 };
661
662 QEMUClock *rt_clock;
663 QEMUClock *vm_clock;
664
665 static QEMUTimer *active_timers[2];
666 #ifdef _WIN32
667 static MMRESULT timerID;
668 #else
669 /* frequency of the times() clock tick */
670 static int timer_freq;
671 #endif
672
673 QEMUClock *qemu_new_clock(int type)
674 {
675 QEMUClock *clock;
676 clock = qemu_mallocz(sizeof(QEMUClock));
677 if (!clock)
678 return NULL;
679 clock->type = type;
680 return clock;
681 }
682
683 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
684 {
685 QEMUTimer *ts;
686
687 ts = qemu_mallocz(sizeof(QEMUTimer));
688 ts->clock = clock;
689 ts->cb = cb;
690 ts->opaque = opaque;
691 return ts;
692 }
693
694 void qemu_free_timer(QEMUTimer *ts)
695 {
696 qemu_free(ts);
697 }
698
699 /* stop a timer, but do not dealloc it */
700 void qemu_del_timer(QEMUTimer *ts)
701 {
702 QEMUTimer **pt, *t;
703
704 /* NOTE: this code must be signal safe because
705 qemu_timer_expired() can be called from a signal. */
706 pt = &active_timers[ts->clock->type];
707 for(;;) {
708 t = *pt;
709 if (!t)
710 break;
711 if (t == ts) {
712 *pt = t->next;
713 break;
714 }
715 pt = &t->next;
716 }
717 }
718
719 /* modify the current timer so that it will be fired when current_time
720 >= expire_time. The corresponding callback will be called. */
721 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
722 {
723 QEMUTimer **pt, *t;
724
725 qemu_del_timer(ts);
726
727 /* add the timer in the sorted list */
728 /* NOTE: this code must be signal safe because
729 qemu_timer_expired() can be called from a signal. */
730 pt = &active_timers[ts->clock->type];
731 for(;;) {
732 t = *pt;
733 if (!t)
734 break;
735 if (t->expire_time > expire_time)
736 break;
737 pt = &t->next;
738 }
739 ts->expire_time = expire_time;
740 ts->next = *pt;
741 *pt = ts;
742 }
743
744 int qemu_timer_pending(QEMUTimer *ts)
745 {
746 QEMUTimer *t;
747 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
748 if (t == ts)
749 return 1;
750 }
751 return 0;
752 }
753
754 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
755 {
756 if (!timer_head)
757 return 0;
758 return (timer_head->expire_time <= current_time);
759 }
760
761 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
762 {
763 QEMUTimer *ts;
764
765 for(;;) {
766 ts = *ptimer_head;
767 if (!ts || ts->expire_time > current_time)
768 break;
769 /* remove timer from the list before calling the callback */
770 *ptimer_head = ts->next;
771 ts->next = NULL;
772
773 /* run the callback (the timer list can be modified) */
774 ts->cb(ts->opaque);
775 }
776 }
777
778 int64_t qemu_get_clock(QEMUClock *clock)
779 {
780 switch(clock->type) {
781 case QEMU_TIMER_REALTIME:
782 #ifdef _WIN32
783 return GetTickCount();
784 #else
785 {
786 struct tms tp;
787
788 /* Note that using gettimeofday() is not a good solution
789 for timers because its value change when the date is
790 modified. */
791 if (timer_freq == 100) {
792 return times(&tp) * 10;
793 } else {
794 return ((int64_t)times(&tp) * 1000) / timer_freq;
795 }
796 }
797 #endif
798 default:
799 case QEMU_TIMER_VIRTUAL:
800 return cpu_get_ticks();
801 }
802 }
803
804 /* save a timer */
805 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
806 {
807 uint64_t expire_time;
808
809 if (qemu_timer_pending(ts)) {
810 expire_time = ts->expire_time;
811 } else {
812 expire_time = -1;
813 }
814 qemu_put_be64(f, expire_time);
815 }
816
817 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
818 {
819 uint64_t expire_time;
820
821 expire_time = qemu_get_be64(f);
822 if (expire_time != -1) {
823 qemu_mod_timer(ts, expire_time);
824 } else {
825 qemu_del_timer(ts);
826 }
827 }
828
829 static void timer_save(QEMUFile *f, void *opaque)
830 {
831 if (cpu_ticks_enabled) {
832 hw_error("cannot save state if virtual timers are running");
833 }
834 qemu_put_be64s(f, &cpu_ticks_offset);
835 qemu_put_be64s(f, &ticks_per_sec);
836 }
837
838 static int timer_load(QEMUFile *f, void *opaque, int version_id)
839 {
840 if (version_id != 1)
841 return -EINVAL;
842 if (cpu_ticks_enabled) {
843 return -EINVAL;
844 }
845 qemu_get_be64s(f, &cpu_ticks_offset);
846 qemu_get_be64s(f, &ticks_per_sec);
847 return 0;
848 }
849
850 #ifdef _WIN32
851 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
852 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
853 #else
854 static void host_alarm_handler(int host_signum)
855 #endif
856 {
857 #if 0
858 #define DISP_FREQ 1000
859 {
860 static int64_t delta_min = INT64_MAX;
861 static int64_t delta_max, delta_cum, last_clock, delta, ti;
862 static int count;
863 ti = qemu_get_clock(vm_clock);
864 if (last_clock != 0) {
865 delta = ti - last_clock;
866 if (delta < delta_min)
867 delta_min = delta;
868 if (delta > delta_max)
869 delta_max = delta;
870 delta_cum += delta;
871 if (++count == DISP_FREQ) {
872 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
873 muldiv64(delta_min, 1000000, ticks_per_sec),
874 muldiv64(delta_max, 1000000, ticks_per_sec),
875 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
876 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
877 count = 0;
878 delta_min = INT64_MAX;
879 delta_max = 0;
880 delta_cum = 0;
881 }
882 }
883 last_clock = ti;
884 }
885 #endif
886 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
887 qemu_get_clock(vm_clock)) ||
888 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
889 qemu_get_clock(rt_clock))) {
890 CPUState *env = cpu_single_env;
891 if (env) {
892 /* stop the currently executing cpu because a timer occured */
893 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
894 #ifdef USE_KQEMU
895 if (env->kqemu_enabled) {
896 kqemu_cpu_interrupt(env);
897 }
898 #endif
899 }
900 }
901 }
902
903 #ifndef _WIN32
904
905 #if defined(__linux__)
906
907 #define RTC_FREQ 1024
908
909 static int rtc_fd;
910
911 static int start_rtc_timer(void)
912 {
913 rtc_fd = open("/dev/rtc", O_RDONLY);
914 if (rtc_fd < 0)
915 return -1;
916 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
917 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
918 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
919 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
920 goto fail;
921 }
922 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
923 fail:
924 close(rtc_fd);
925 return -1;
926 }
927 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
928 return 0;
929 }
930
931 #else
932
933 static int start_rtc_timer(void)
934 {
935 return -1;
936 }
937
938 #endif /* !defined(__linux__) */
939
940 #endif /* !defined(_WIN32) */
941
942 static void init_timers(void)
943 {
944 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
945 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
946
947 #ifdef _WIN32
948 {
949 int count=0;
950 timerID = timeSetEvent(1, // interval (ms)
951 0, // resolution
952 host_alarm_handler, // function
953 (DWORD)&count, // user parameter
954 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
955 if( !timerID ) {
956 perror("failed timer alarm");
957 exit(1);
958 }
959 }
960 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
961 #else
962 {
963 struct sigaction act;
964 struct itimerval itv;
965
966 /* get times() syscall frequency */
967 timer_freq = sysconf(_SC_CLK_TCK);
968
969 /* timer signal */
970 sigfillset(&act.sa_mask);
971 act.sa_flags = 0;
972 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
973 act.sa_flags |= SA_ONSTACK;
974 #endif
975 act.sa_handler = host_alarm_handler;
976 sigaction(SIGALRM, &act, NULL);
977
978 itv.it_interval.tv_sec = 0;
979 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
980 itv.it_value.tv_sec = 0;
981 itv.it_value.tv_usec = 10 * 1000;
982 setitimer(ITIMER_REAL, &itv, NULL);
983 /* we probe the tick duration of the kernel to inform the user if
984 the emulated kernel requested a too high timer frequency */
985 getitimer(ITIMER_REAL, &itv);
986
987 #if defined(__linux__)
988 if (itv.it_interval.tv_usec > 1000) {
989 /* try to use /dev/rtc to have a faster timer */
990 if (start_rtc_timer() < 0)
991 goto use_itimer;
992 /* disable itimer */
993 itv.it_interval.tv_sec = 0;
994 itv.it_interval.tv_usec = 0;
995 itv.it_value.tv_sec = 0;
996 itv.it_value.tv_usec = 0;
997 setitimer(ITIMER_REAL, &itv, NULL);
998
999 /* use the RTC */
1000 sigaction(SIGIO, &act, NULL);
1001 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1002 fcntl(rtc_fd, F_SETOWN, getpid());
1003 } else
1004 #endif /* defined(__linux__) */
1005 {
1006 use_itimer:
1007 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1008 PIT_FREQ) / 1000000;
1009 }
1010 }
1011 #endif
1012 }
1013
1014 void quit_timers(void)
1015 {
1016 #ifdef _WIN32
1017 timeKillEvent(timerID);
1018 #endif
1019 }
1020
1021 /***********************************************************/
1022 /* character device */
1023
1024 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1025 {
1026 return s->chr_write(s, buf, len);
1027 }
1028
1029 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1030 {
1031 if (!s->chr_ioctl)
1032 return -ENOTSUP;
1033 return s->chr_ioctl(s, cmd, arg);
1034 }
1035
1036 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1037 {
1038 char buf[4096];
1039 va_list ap;
1040 va_start(ap, fmt);
1041 vsnprintf(buf, sizeof(buf), fmt, ap);
1042 qemu_chr_write(s, buf, strlen(buf));
1043 va_end(ap);
1044 }
1045
1046 void qemu_chr_send_event(CharDriverState *s, int event)
1047 {
1048 if (s->chr_send_event)
1049 s->chr_send_event(s, event);
1050 }
1051
1052 void qemu_chr_add_read_handler(CharDriverState *s,
1053 IOCanRWHandler *fd_can_read,
1054 IOReadHandler *fd_read, void *opaque)
1055 {
1056 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1057 }
1058
1059 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1060 {
1061 s->chr_event = chr_event;
1062 }
1063
1064 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1065 {
1066 return len;
1067 }
1068
1069 static void null_chr_add_read_handler(CharDriverState *chr,
1070 IOCanRWHandler *fd_can_read,
1071 IOReadHandler *fd_read, void *opaque)
1072 {
1073 }
1074
1075 CharDriverState *qemu_chr_open_null(void)
1076 {
1077 CharDriverState *chr;
1078
1079 chr = qemu_mallocz(sizeof(CharDriverState));
1080 if (!chr)
1081 return NULL;
1082 chr->chr_write = null_chr_write;
1083 chr->chr_add_read_handler = null_chr_add_read_handler;
1084 return chr;
1085 }
1086
1087 #ifndef _WIN32
1088
1089 typedef struct {
1090 int fd_in, fd_out;
1091 IOCanRWHandler *fd_can_read;
1092 IOReadHandler *fd_read;
1093 void *fd_opaque;
1094 int max_size;
1095 } FDCharDriver;
1096
1097 #define STDIO_MAX_CLIENTS 2
1098
1099 static int stdio_nb_clients;
1100 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1101
1102 static int unix_write(int fd, const uint8_t *buf, int len1)
1103 {
1104 int ret, len;
1105
1106 len = len1;
1107 while (len > 0) {
1108 ret = write(fd, buf, len);
1109 if (ret < 0) {
1110 if (errno != EINTR && errno != EAGAIN)
1111 return -1;
1112 } else if (ret == 0) {
1113 break;
1114 } else {
1115 buf += ret;
1116 len -= ret;
1117 }
1118 }
1119 return len1 - len;
1120 }
1121
1122 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1123 {
1124 FDCharDriver *s = chr->opaque;
1125 return unix_write(s->fd_out, buf, len);
1126 }
1127
1128 static int fd_chr_read_poll(void *opaque)
1129 {
1130 CharDriverState *chr = opaque;
1131 FDCharDriver *s = chr->opaque;
1132
1133 s->max_size = s->fd_can_read(s->fd_opaque);
1134 return s->max_size;
1135 }
1136
1137 static void fd_chr_read(void *opaque)
1138 {
1139 CharDriverState *chr = opaque;
1140 FDCharDriver *s = chr->opaque;
1141 int size, len;
1142 uint8_t buf[1024];
1143
1144 len = sizeof(buf);
1145 if (len > s->max_size)
1146 len = s->max_size;
1147 if (len == 0)
1148 return;
1149 size = read(s->fd_in, buf, len);
1150 if (size > 0) {
1151 s->fd_read(s->fd_opaque, buf, size);
1152 }
1153 }
1154
1155 static void fd_chr_add_read_handler(CharDriverState *chr,
1156 IOCanRWHandler *fd_can_read,
1157 IOReadHandler *fd_read, void *opaque)
1158 {
1159 FDCharDriver *s = chr->opaque;
1160
1161 if (s->fd_in >= 0) {
1162 s->fd_can_read = fd_can_read;
1163 s->fd_read = fd_read;
1164 s->fd_opaque = opaque;
1165 if (nographic && s->fd_in == 0) {
1166 } else {
1167 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1168 fd_chr_read, NULL, chr);
1169 }
1170 }
1171 }
1172
1173 /* open a character device to a unix fd */
1174 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1175 {
1176 CharDriverState *chr;
1177 FDCharDriver *s;
1178
1179 chr = qemu_mallocz(sizeof(CharDriverState));
1180 if (!chr)
1181 return NULL;
1182 s = qemu_mallocz(sizeof(FDCharDriver));
1183 if (!s) {
1184 free(chr);
1185 return NULL;
1186 }
1187 s->fd_in = fd_in;
1188 s->fd_out = fd_out;
1189 chr->opaque = s;
1190 chr->chr_write = fd_chr_write;
1191 chr->chr_add_read_handler = fd_chr_add_read_handler;
1192 return chr;
1193 }
1194
1195 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1196 {
1197 int fd_out;
1198
1199 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY);
1200 if (fd_out < 0)
1201 return NULL;
1202 return qemu_chr_open_fd(-1, fd_out);
1203 }
1204
1205 CharDriverState *qemu_chr_open_pipe(const char *filename)
1206 {
1207 int fd;
1208
1209 fd = open(filename, O_RDWR | O_BINARY);
1210 if (fd < 0)
1211 return NULL;
1212 return qemu_chr_open_fd(fd, fd);
1213 }
1214
1215
1216 /* for STDIO, we handle the case where several clients use it
1217 (nographic mode) */
1218
1219 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1220
1221 #define TERM_FIFO_MAX_SIZE 1
1222
1223 static int term_got_escape, client_index;
1224 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1225 int term_fifo_size;
1226
1227 void term_print_help(void)
1228 {
1229 printf("\n"
1230 "C-a h print this help\n"
1231 "C-a x exit emulator\n"
1232 "C-a s save disk data back to file (if -snapshot)\n"
1233 "C-a b send break (magic sysrq)\n"
1234 "C-a c switch between console and monitor\n"
1235 "C-a C-a send C-a\n"
1236 );
1237 }
1238
1239 /* called when a char is received */
1240 static void stdio_received_byte(int ch)
1241 {
1242 if (term_got_escape) {
1243 term_got_escape = 0;
1244 switch(ch) {
1245 case 'h':
1246 term_print_help();
1247 break;
1248 case 'x':
1249 exit(0);
1250 break;
1251 case 's':
1252 {
1253 int i;
1254 for (i = 0; i < MAX_DISKS; i++) {
1255 if (bs_table[i])
1256 bdrv_commit(bs_table[i]);
1257 }
1258 }
1259 break;
1260 case 'b':
1261 if (client_index < stdio_nb_clients) {
1262 CharDriverState *chr;
1263 FDCharDriver *s;
1264
1265 chr = stdio_clients[client_index];
1266 s = chr->opaque;
1267 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1268 }
1269 break;
1270 case 'c':
1271 client_index++;
1272 if (client_index >= stdio_nb_clients)
1273 client_index = 0;
1274 if (client_index == 0) {
1275 /* send a new line in the monitor to get the prompt */
1276 ch = '\r';
1277 goto send_char;
1278 }
1279 break;
1280 case TERM_ESCAPE:
1281 goto send_char;
1282 }
1283 } else if (ch == TERM_ESCAPE) {
1284 term_got_escape = 1;
1285 } else {
1286 send_char:
1287 if (client_index < stdio_nb_clients) {
1288 uint8_t buf[1];
1289 CharDriverState *chr;
1290 FDCharDriver *s;
1291
1292 chr = stdio_clients[client_index];
1293 s = chr->opaque;
1294 if (s->fd_can_read(s->fd_opaque) > 0) {
1295 buf[0] = ch;
1296 s->fd_read(s->fd_opaque, buf, 1);
1297 } else if (term_fifo_size == 0) {
1298 term_fifo[term_fifo_size++] = ch;
1299 }
1300 }
1301 }
1302 }
1303
1304 static int stdio_read_poll(void *opaque)
1305 {
1306 CharDriverState *chr;
1307 FDCharDriver *s;
1308
1309 if (client_index < stdio_nb_clients) {
1310 chr = stdio_clients[client_index];
1311 s = chr->opaque;
1312 /* try to flush the queue if needed */
1313 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1314 s->fd_read(s->fd_opaque, term_fifo, 1);
1315 term_fifo_size = 0;
1316 }
1317 /* see if we can absorb more chars */
1318 if (term_fifo_size == 0)
1319 return 1;
1320 else
1321 return 0;
1322 } else {
1323 return 1;
1324 }
1325 }
1326
1327 static void stdio_read(void *opaque)
1328 {
1329 int size;
1330 uint8_t buf[1];
1331
1332 size = read(0, buf, 1);
1333 if (size > 0)
1334 stdio_received_byte(buf[0]);
1335 }
1336
1337 /* init terminal so that we can grab keys */
1338 static struct termios oldtty;
1339 static int old_fd0_flags;
1340
1341 static void term_exit(void)
1342 {
1343 tcsetattr (0, TCSANOW, &oldtty);
1344 fcntl(0, F_SETFL, old_fd0_flags);
1345 }
1346
1347 static void term_init(void)
1348 {
1349 struct termios tty;
1350
1351 tcgetattr (0, &tty);
1352 oldtty = tty;
1353 old_fd0_flags = fcntl(0, F_GETFL);
1354
1355 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1356 |INLCR|IGNCR|ICRNL|IXON);
1357 tty.c_oflag |= OPOST;
1358 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1359 /* if graphical mode, we allow Ctrl-C handling */
1360 if (nographic)
1361 tty.c_lflag &= ~ISIG;
1362 tty.c_cflag &= ~(CSIZE|PARENB);
1363 tty.c_cflag |= CS8;
1364 tty.c_cc[VMIN] = 1;
1365 tty.c_cc[VTIME] = 0;
1366
1367 tcsetattr (0, TCSANOW, &tty);
1368
1369 atexit(term_exit);
1370
1371 fcntl(0, F_SETFL, O_NONBLOCK);
1372 }
1373
1374 CharDriverState *qemu_chr_open_stdio(void)
1375 {
1376 CharDriverState *chr;
1377
1378 if (nographic) {
1379 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1380 return NULL;
1381 chr = qemu_chr_open_fd(0, 1);
1382 if (stdio_nb_clients == 0)
1383 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1384 client_index = stdio_nb_clients;
1385 } else {
1386 if (stdio_nb_clients != 0)
1387 return NULL;
1388 chr = qemu_chr_open_fd(0, 1);
1389 }
1390 stdio_clients[stdio_nb_clients++] = chr;
1391 if (stdio_nb_clients == 1) {
1392 /* set the terminal in raw mode */
1393 term_init();
1394 }
1395 return chr;
1396 }
1397
1398 #if defined(__linux__)
1399 CharDriverState *qemu_chr_open_pty(void)
1400 {
1401 char slave_name[1024];
1402 int master_fd, slave_fd;
1403
1404 /* Not satisfying */
1405 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1406 return NULL;
1407 }
1408 fprintf(stderr, "char device redirected to %s\n", slave_name);
1409 return qemu_chr_open_fd(master_fd, master_fd);
1410 }
1411
1412 static void tty_serial_init(int fd, int speed,
1413 int parity, int data_bits, int stop_bits)
1414 {
1415 struct termios tty;
1416 speed_t spd;
1417
1418 #if 0
1419 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1420 speed, parity, data_bits, stop_bits);
1421 #endif
1422 tcgetattr (fd, &tty);
1423
1424 switch(speed) {
1425 case 50:
1426 spd = B50;
1427 break;
1428 case 75:
1429 spd = B75;
1430 break;
1431 case 300:
1432 spd = B300;
1433 break;
1434 case 600:
1435 spd = B600;
1436 break;
1437 case 1200:
1438 spd = B1200;
1439 break;
1440 case 2400:
1441 spd = B2400;
1442 break;
1443 case 4800:
1444 spd = B4800;
1445 break;
1446 case 9600:
1447 spd = B9600;
1448 break;
1449 case 19200:
1450 spd = B19200;
1451 break;
1452 case 38400:
1453 spd = B38400;
1454 break;
1455 case 57600:
1456 spd = B57600;
1457 break;
1458 default:
1459 case 115200:
1460 spd = B115200;
1461 break;
1462 }
1463
1464 cfsetispeed(&tty, spd);
1465 cfsetospeed(&tty, spd);
1466
1467 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1468 |INLCR|IGNCR|ICRNL|IXON);
1469 tty.c_oflag |= OPOST;
1470 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1471 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1472 switch(data_bits) {
1473 default:
1474 case 8:
1475 tty.c_cflag |= CS8;
1476 break;
1477 case 7:
1478 tty.c_cflag |= CS7;
1479 break;
1480 case 6:
1481 tty.c_cflag |= CS6;
1482 break;
1483 case 5:
1484 tty.c_cflag |= CS5;
1485 break;
1486 }
1487 switch(parity) {
1488 default:
1489 case 'N':
1490 break;
1491 case 'E':
1492 tty.c_cflag |= PARENB;
1493 break;
1494 case 'O':
1495 tty.c_cflag |= PARENB | PARODD;
1496 break;
1497 }
1498
1499 tcsetattr (fd, TCSANOW, &tty);
1500 }
1501
1502 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1503 {
1504 FDCharDriver *s = chr->opaque;
1505
1506 switch(cmd) {
1507 case CHR_IOCTL_SERIAL_SET_PARAMS:
1508 {
1509 QEMUSerialSetParams *ssp = arg;
1510 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1511 ssp->data_bits, ssp->stop_bits);
1512 }
1513 break;
1514 case CHR_IOCTL_SERIAL_SET_BREAK:
1515 {
1516 int enable = *(int *)arg;
1517 if (enable)
1518 tcsendbreak(s->fd_in, 1);
1519 }
1520 break;
1521 default:
1522 return -ENOTSUP;
1523 }
1524 return 0;
1525 }
1526
1527 CharDriverState *qemu_chr_open_tty(const char *filename)
1528 {
1529 CharDriverState *chr;
1530 int fd;
1531
1532 fd = open(filename, O_RDWR | O_NONBLOCK);
1533 if (fd < 0)
1534 return NULL;
1535 fcntl(fd, F_SETFL, O_NONBLOCK);
1536 tty_serial_init(fd, 115200, 'N', 8, 1);
1537 chr = qemu_chr_open_fd(fd, fd);
1538 if (!chr)
1539 return NULL;
1540 chr->chr_ioctl = tty_serial_ioctl;
1541 return chr;
1542 }
1543
1544 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1545 {
1546 int fd = (int)chr->opaque;
1547 uint8_t b;
1548
1549 switch(cmd) {
1550 case CHR_IOCTL_PP_READ_DATA:
1551 if (ioctl(fd, PPRDATA, &b) < 0)
1552 return -ENOTSUP;
1553 *(uint8_t *)arg = b;
1554 break;
1555 case CHR_IOCTL_PP_WRITE_DATA:
1556 b = *(uint8_t *)arg;
1557 if (ioctl(fd, PPWDATA, &b) < 0)
1558 return -ENOTSUP;
1559 break;
1560 case CHR_IOCTL_PP_READ_CONTROL:
1561 if (ioctl(fd, PPRCONTROL, &b) < 0)
1562 return -ENOTSUP;
1563 *(uint8_t *)arg = b;
1564 break;
1565 case CHR_IOCTL_PP_WRITE_CONTROL:
1566 b = *(uint8_t *)arg;
1567 if (ioctl(fd, PPWCONTROL, &b) < 0)
1568 return -ENOTSUP;
1569 break;
1570 case CHR_IOCTL_PP_READ_STATUS:
1571 if (ioctl(fd, PPRSTATUS, &b) < 0)
1572 return -ENOTSUP;
1573 *(uint8_t *)arg = b;
1574 break;
1575 default:
1576 return -ENOTSUP;
1577 }
1578 return 0;
1579 }
1580
1581 CharDriverState *qemu_chr_open_pp(const char *filename)
1582 {
1583 CharDriverState *chr;
1584 int fd;
1585
1586 fd = open(filename, O_RDWR);
1587 if (fd < 0)
1588 return NULL;
1589
1590 if (ioctl(fd, PPCLAIM) < 0) {
1591 close(fd);
1592 return NULL;
1593 }
1594
1595 chr = qemu_mallocz(sizeof(CharDriverState));
1596 if (!chr) {
1597 close(fd);
1598 return NULL;
1599 }
1600 chr->opaque = (void *)fd;
1601 chr->chr_write = null_chr_write;
1602 chr->chr_add_read_handler = null_chr_add_read_handler;
1603 chr->chr_ioctl = pp_ioctl;
1604 return chr;
1605 }
1606
1607 #else
1608 CharDriverState *qemu_chr_open_pty(void)
1609 {
1610 return NULL;
1611 }
1612 #endif
1613
1614 #endif /* !defined(_WIN32) */
1615
1616 CharDriverState *qemu_chr_open(const char *filename)
1617 {
1618 const char *p;
1619 if (!strcmp(filename, "vc")) {
1620 return text_console_init(&display_state);
1621 } else if (!strcmp(filename, "null")) {
1622 return qemu_chr_open_null();
1623 } else
1624 #ifndef _WIN32
1625 if (strstart(filename, "file:", &p)) {
1626 return qemu_chr_open_file_out(p);
1627 } else if (strstart(filename, "pipe:", &p)) {
1628 return qemu_chr_open_pipe(p);
1629 } else if (!strcmp(filename, "pty")) {
1630 return qemu_chr_open_pty();
1631 } else if (!strcmp(filename, "stdio")) {
1632 return qemu_chr_open_stdio();
1633 } else
1634 #endif
1635 #if defined(__linux__)
1636 if (strstart(filename, "/dev/parport", NULL)) {
1637 return qemu_chr_open_pp(filename);
1638 } else
1639 if (strstart(filename, "/dev/", NULL)) {
1640 return qemu_chr_open_tty(filename);
1641 } else
1642 #endif
1643 {
1644 return NULL;
1645 }
1646 }
1647
1648 /***********************************************************/
1649 /* network device redirectors */
1650
1651 void hex_dump(FILE *f, const uint8_t *buf, int size)
1652 {
1653 int len, i, j, c;
1654
1655 for(i=0;i<size;i+=16) {
1656 len = size - i;
1657 if (len > 16)
1658 len = 16;
1659 fprintf(f, "%08x ", i);
1660 for(j=0;j<16;j++) {
1661 if (j < len)
1662 fprintf(f, " %02x", buf[i+j]);
1663 else
1664 fprintf(f, " ");
1665 }
1666 fprintf(f, " ");
1667 for(j=0;j<len;j++) {
1668 c = buf[i+j];
1669 if (c < ' ' || c > '~')
1670 c = '.';
1671 fprintf(f, "%c", c);
1672 }
1673 fprintf(f, "\n");
1674 }
1675 }
1676
1677 static int parse_macaddr(uint8_t *macaddr, const char *p)
1678 {
1679 int i;
1680 for(i = 0; i < 6; i++) {
1681 macaddr[i] = strtol(p, (char **)&p, 16);
1682 if (i == 5) {
1683 if (*p != '\0')
1684 return -1;
1685 } else {
1686 if (*p != ':')
1687 return -1;
1688 p++;
1689 }
1690 }
1691 return 0;
1692 }
1693
1694 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
1695 {
1696 const char *p, *p1;
1697 int len;
1698 p = *pp;
1699 p1 = strchr(p, sep);
1700 if (!p1)
1701 return -1;
1702 len = p1 - p;
1703 p1++;
1704 if (buf_size > 0) {
1705 if (len > buf_size - 1)
1706 len = buf_size - 1;
1707 memcpy(buf, p, len);
1708 buf[len] = '\0';
1709 }
1710 *pp = p1;
1711 return 0;
1712 }
1713
1714 int parse_host_port(struct sockaddr_in *saddr, const char *str)
1715 {
1716 char buf[512];
1717 struct hostent *he;
1718 const char *p, *r;
1719 int port;
1720
1721 p = str;
1722 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1723 return -1;
1724 saddr->sin_family = AF_INET;
1725 if (buf[0] == '\0') {
1726 saddr->sin_addr.s_addr = 0;
1727 } else {
1728 if (isdigit(buf[0])) {
1729 if (!inet_aton(buf, &saddr->sin_addr))
1730 return -1;
1731 } else {
1732 #ifdef _WIN32
1733 return -1;
1734 #else
1735 if ((he = gethostbyname(buf)) == NULL)
1736 return - 1;
1737 saddr->sin_addr = *(struct in_addr *)he->h_addr;
1738 #endif
1739 }
1740 }
1741 port = strtol(p, (char **)&r, 0);
1742 if (r == p)
1743 return -1;
1744 saddr->sin_port = htons(port);
1745 return 0;
1746 }
1747
1748 /* find or alloc a new VLAN */
1749 VLANState *qemu_find_vlan(int id)
1750 {
1751 VLANState **pvlan, *vlan;
1752 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
1753 if (vlan->id == id)
1754 return vlan;
1755 }
1756 vlan = qemu_mallocz(sizeof(VLANState));
1757 if (!vlan)
1758 return NULL;
1759 vlan->id = id;
1760 vlan->next = NULL;
1761 pvlan = &first_vlan;
1762 while (*pvlan != NULL)
1763 pvlan = &(*pvlan)->next;
1764 *pvlan = vlan;
1765 return vlan;
1766 }
1767
1768 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
1769 IOReadHandler *fd_read, void *opaque)
1770 {
1771 VLANClientState *vc, **pvc;
1772 vc = qemu_mallocz(sizeof(VLANClientState));
1773 if (!vc)
1774 return NULL;
1775 vc->fd_read = fd_read;
1776 vc->opaque = opaque;
1777 vc->vlan = vlan;
1778
1779 vc->next = NULL;
1780 pvc = &vlan->first_client;
1781 while (*pvc != NULL)
1782 pvc = &(*pvc)->next;
1783 *pvc = vc;
1784 return vc;
1785 }
1786
1787 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
1788 {
1789 VLANState *vlan = vc1->vlan;
1790 VLANClientState *vc;
1791
1792 #if 0
1793 printf("vlan %d send:\n", vlan->id);
1794 hex_dump(stdout, buf, size);
1795 #endif
1796 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
1797 if (vc != vc1) {
1798 vc->fd_read(vc->opaque, buf, size);
1799 }
1800 }
1801 }
1802
1803 #if defined(CONFIG_SLIRP)
1804
1805 /* slirp network adapter */
1806
1807 static int slirp_inited;
1808 static VLANClientState *slirp_vc;
1809
1810 int slirp_can_output(void)
1811 {
1812 return 1;
1813 }
1814
1815 void slirp_output(const uint8_t *pkt, int pkt_len)
1816 {
1817 #if 0
1818 printf("slirp output:\n");
1819 hex_dump(stdout, pkt, pkt_len);
1820 #endif
1821 qemu_send_packet(slirp_vc, pkt, pkt_len);
1822 }
1823
1824 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
1825 {
1826 #if 0
1827 printf("slirp input:\n");
1828 hex_dump(stdout, buf, size);
1829 #endif
1830 slirp_input(buf, size);
1831 }
1832
1833 static int net_slirp_init(VLANState *vlan)
1834 {
1835 if (!slirp_inited) {
1836 slirp_inited = 1;
1837 slirp_init();
1838 }
1839 slirp_vc = qemu_new_vlan_client(vlan,
1840 slirp_receive, NULL);
1841 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
1842 return 0;
1843 }
1844
1845 static void net_slirp_redir(const char *redir_str)
1846 {
1847 int is_udp;
1848 char buf[256], *r;
1849 const char *p;
1850 struct in_addr guest_addr;
1851 int host_port, guest_port;
1852
1853 if (!slirp_inited) {
1854 slirp_inited = 1;
1855 slirp_init();
1856 }
1857
1858 p = redir_str;
1859 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1860 goto fail;
1861 if (!strcmp(buf, "tcp")) {
1862 is_udp = 0;
1863 } else if (!strcmp(buf, "udp")) {
1864 is_udp = 1;
1865 } else {
1866 goto fail;
1867 }
1868
1869 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1870 goto fail;
1871 host_port = strtol(buf, &r, 0);
1872 if (r == buf)
1873 goto fail;
1874
1875 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
1876 goto fail;
1877 if (buf[0] == '\0') {
1878 pstrcpy(buf, sizeof(buf), "10.0.2.15");
1879 }
1880 if (!inet_aton(buf, &guest_addr))
1881 goto fail;
1882
1883 guest_port = strtol(p, &r, 0);
1884 if (r == p)
1885 goto fail;
1886
1887 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
1888 fprintf(stderr, "qemu: could not set up redirection\n");
1889 exit(1);
1890 }
1891 return;
1892 fail:
1893 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
1894 exit(1);
1895 }
1896
1897 #ifndef _WIN32
1898
1899 char smb_dir[1024];
1900
1901 static void smb_exit(void)
1902 {
1903 DIR *d;
1904 struct dirent *de;
1905 char filename[1024];
1906
1907 /* erase all the files in the directory */
1908 d = opendir(smb_dir);
1909 for(;;) {
1910 de = readdir(d);
1911 if (!de)
1912 break;
1913 if (strcmp(de->d_name, ".") != 0 &&
1914 strcmp(de->d_name, "..") != 0) {
1915 snprintf(filename, sizeof(filename), "%s/%s",
1916 smb_dir, de->d_name);
1917 unlink(filename);
1918 }
1919 }
1920 closedir(d);
1921 rmdir(smb_dir);
1922 }
1923
1924 /* automatic user mode samba server configuration */
1925 void net_slirp_smb(const char *exported_dir)
1926 {
1927 char smb_conf[1024];
1928 char smb_cmdline[1024];
1929 FILE *f;
1930
1931 if (!slirp_inited) {
1932 slirp_inited = 1;
1933 slirp_init();
1934 }
1935
1936 /* XXX: better tmp dir construction */
1937 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
1938 if (mkdir(smb_dir, 0700) < 0) {
1939 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
1940 exit(1);
1941 }
1942 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
1943
1944 f = fopen(smb_conf, "w");
1945 if (!f) {
1946 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
1947 exit(1);
1948 }
1949 fprintf(f,
1950 "[global]\n"
1951 "private dir=%s\n"
1952 "smb ports=0\n"
1953 "socket address=127.0.0.1\n"
1954 "pid directory=%s\n"
1955 "lock directory=%s\n"
1956 "log file=%s/log.smbd\n"
1957 "smb passwd file=%s/smbpasswd\n"
1958 "security = share\n"
1959 "[qemu]\n"
1960 "path=%s\n"
1961 "read only=no\n"
1962 "guest ok=yes\n",
1963 smb_dir,
1964 smb_dir,
1965 smb_dir,
1966 smb_dir,
1967 smb_dir,
1968 exported_dir
1969 );
1970 fclose(f);
1971 atexit(smb_exit);
1972
1973 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
1974 smb_conf);
1975
1976 slirp_add_exec(0, smb_cmdline, 4, 139);
1977 }
1978
1979 #endif /* !defined(_WIN32) */
1980
1981 #endif /* CONFIG_SLIRP */
1982
1983 #if !defined(_WIN32)
1984
1985 typedef struct TAPState {
1986 VLANClientState *vc;
1987 int fd;
1988 } TAPState;
1989
1990 static void tap_receive(void *opaque, const uint8_t *buf, int size)
1991 {
1992 TAPState *s = opaque;
1993 int ret;
1994 for(;;) {
1995 ret = write(s->fd, buf, size);
1996 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
1997 } else {
1998 break;
1999 }
2000 }
2001 }
2002
2003 static void tap_send(void *opaque)
2004 {
2005 TAPState *s = opaque;
2006 uint8_t buf[4096];
2007 int size;
2008
2009 size = read(s->fd, buf, sizeof(buf));
2010 if (size > 0) {
2011 qemu_send_packet(s->vc, buf, size);
2012 }
2013 }
2014
2015 /* fd support */
2016
2017 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2018 {
2019 TAPState *s;
2020
2021 s = qemu_mallocz(sizeof(TAPState));
2022 if (!s)
2023 return NULL;
2024 s->fd = fd;
2025 s->vc = qemu_new_vlan_client(vlan, tap_receive, s);
2026 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2027 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2028 return s;
2029 }
2030
2031 #ifdef _BSD
2032 static int tap_open(char *ifname, int ifname_size)
2033 {
2034 int fd;
2035 char *dev;
2036 struct stat s;
2037
2038 fd = open("/dev/tap", O_RDWR);
2039 if (fd < 0) {
2040 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2041 return -1;
2042 }
2043
2044 fstat(fd, &s);
2045 dev = devname(s.st_rdev, S_IFCHR);
2046 pstrcpy(ifname, ifname_size, dev);
2047
2048 fcntl(fd, F_SETFL, O_NONBLOCK);
2049 return fd;
2050 }
2051 #else
2052 static int tap_open(char *ifname, int ifname_size)
2053 {
2054 struct ifreq ifr;
2055 int fd, ret;
2056
2057 fd = open("/dev/net/tun", O_RDWR);
2058 if (fd < 0) {
2059 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2060 return -1;
2061 }
2062 memset(&ifr, 0, sizeof(ifr));
2063 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2064 if (ifname[0] != '\0')
2065 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2066 else
2067 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2068 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2069 if (ret != 0) {
2070 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2071 close(fd);
2072 return -1;
2073 }
2074 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2075 fcntl(fd, F_SETFL, O_NONBLOCK);
2076 return fd;
2077 }
2078 #endif
2079
2080 static int net_tap_init(VLANState *vlan, const char *ifname1,
2081 const char *setup_script)
2082 {
2083 TAPState *s;
2084 int pid, status, fd;
2085 char *args[3];
2086 char **parg;
2087 char ifname[128];
2088
2089 if (ifname1 != NULL)
2090 pstrcpy(ifname, sizeof(ifname), ifname1);
2091 else
2092 ifname[0] = '\0';
2093 fd = tap_open(ifname, sizeof(ifname));
2094 if (fd < 0)
2095 return -1;
2096
2097 if (!setup_script)
2098 setup_script = "";
2099 if (setup_script[0] != '\0') {
2100 /* try to launch network init script */
2101 pid = fork();
2102 if (pid >= 0) {
2103 if (pid == 0) {
2104 parg = args;
2105 *parg++ = (char *)setup_script;
2106 *parg++ = ifname;
2107 *parg++ = NULL;
2108 execv(setup_script, args);
2109 _exit(1);
2110 }
2111 while (waitpid(pid, &status, 0) != pid);
2112 if (!WIFEXITED(status) ||
2113 WEXITSTATUS(status) != 0) {
2114 fprintf(stderr, "%s: could not launch network script\n",
2115 setup_script);
2116 return -1;
2117 }
2118 }
2119 }
2120 s = net_tap_fd_init(vlan, fd);
2121 if (!s)
2122 return -1;
2123 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2124 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2125 return 0;
2126 }
2127
2128 /* network connection */
2129 typedef struct NetSocketState {
2130 VLANClientState *vc;
2131 int fd;
2132 int state; /* 0 = getting length, 1 = getting data */
2133 int index;
2134 int packet_len;
2135 uint8_t buf[4096];
2136 } NetSocketState;
2137
2138 typedef struct NetSocketListenState {
2139 VLANState *vlan;
2140 int fd;
2141 } NetSocketListenState;
2142
2143 /* XXX: we consider we can send the whole packet without blocking */
2144 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2145 {
2146 NetSocketState *s = opaque;
2147 uint32_t len;
2148 len = htonl(size);
2149
2150 unix_write(s->fd, (const uint8_t *)&len, sizeof(len));
2151 unix_write(s->fd, buf, size);
2152 }
2153
2154 static void net_socket_send(void *opaque)
2155 {
2156 NetSocketState *s = opaque;
2157 int l, size;
2158 uint8_t buf1[4096];
2159 const uint8_t *buf;
2160
2161 size = read(s->fd, buf1, sizeof(buf1));
2162 if (size < 0)
2163 return;
2164 if (size == 0) {
2165 /* end of connection */
2166 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2167 return;
2168 }
2169 buf = buf1;
2170 while (size > 0) {
2171 /* reassemble a packet from the network */
2172 switch(s->state) {
2173 case 0:
2174 l = 4 - s->index;
2175 if (l > size)
2176 l = size;
2177 memcpy(s->buf + s->index, buf, l);
2178 buf += l;
2179 size -= l;
2180 s->index += l;
2181 if (s->index == 4) {
2182 /* got length */
2183 s->packet_len = ntohl(*(uint32_t *)s->buf);
2184 s->index = 0;
2185 s->state = 1;
2186 }
2187 break;
2188 case 1:
2189 l = s->packet_len - s->index;
2190 if (l > size)
2191 l = size;
2192 memcpy(s->buf + s->index, buf, l);
2193 s->index += l;
2194 buf += l;
2195 size -= l;
2196 if (s->index >= s->packet_len) {
2197 qemu_send_packet(s->vc, s->buf, s->packet_len);
2198 s->index = 0;
2199 s->state = 0;
2200 }
2201 break;
2202 }
2203 }
2204 }
2205
2206 static void net_socket_connect(void *opaque)
2207 {
2208 NetSocketState *s = opaque;
2209 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2210 }
2211
2212 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2213 int is_connected)
2214 {
2215 NetSocketState *s;
2216 s = qemu_mallocz(sizeof(NetSocketState));
2217 if (!s)
2218 return NULL;
2219 s->fd = fd;
2220 s->vc = qemu_new_vlan_client(vlan,
2221 net_socket_receive, s);
2222 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2223 "socket: fd=%d", fd);
2224 if (is_connected) {
2225 net_socket_connect(s);
2226 } else {
2227 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2228 }
2229 return s;
2230 }
2231
2232 static void net_socket_accept(void *opaque)
2233 {
2234 NetSocketListenState *s = opaque;
2235 NetSocketState *s1;
2236 struct sockaddr_in saddr;
2237 socklen_t len;
2238 int fd;
2239
2240 for(;;) {
2241 len = sizeof(saddr);
2242 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2243 if (fd < 0 && errno != EINTR) {
2244 return;
2245 } else if (fd >= 0) {
2246 break;
2247 }
2248 }
2249 s1 = net_socket_fd_init(s->vlan, fd, 1);
2250 if (!s1) {
2251 close(fd);
2252 } else {
2253 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2254 "socket: connection from %s:%d",
2255 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2256 }
2257 }
2258
2259 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2260 {
2261 NetSocketListenState *s;
2262 int fd, val, ret;
2263 struct sockaddr_in saddr;
2264
2265 if (parse_host_port(&saddr, host_str) < 0)
2266 return -1;
2267
2268 s = qemu_mallocz(sizeof(NetSocketListenState));
2269 if (!s)
2270 return -1;
2271
2272 fd = socket(PF_INET, SOCK_STREAM, 0);
2273 if (fd < 0) {
2274 perror("socket");
2275 return -1;
2276 }
2277 fcntl(fd, F_SETFL, O_NONBLOCK);
2278
2279 /* allow fast reuse */
2280 val = 1;
2281 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2282
2283 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2284 if (ret < 0) {
2285 perror("bind");
2286 return -1;
2287 }
2288 ret = listen(fd, 0);
2289 if (ret < 0) {
2290 perror("listen");
2291 return -1;
2292 }
2293 s->vlan = vlan;
2294 s->fd = fd;
2295 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2296 return 0;
2297 }
2298
2299 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2300 {
2301 NetSocketState *s;
2302 int fd, connected, ret;
2303 struct sockaddr_in saddr;
2304
2305 if (parse_host_port(&saddr, host_str) < 0)
2306 return -1;
2307
2308 fd = socket(PF_INET, SOCK_STREAM, 0);
2309 if (fd < 0) {
2310 perror("socket");
2311 return -1;
2312 }
2313 fcntl(fd, F_SETFL, O_NONBLOCK);
2314
2315 connected = 0;
2316 for(;;) {
2317 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2318 if (ret < 0) {
2319 if (errno == EINTR || errno == EAGAIN) {
2320 } else if (errno == EINPROGRESS) {
2321 break;
2322 } else {
2323 perror("connect");
2324 close(fd);
2325 return -1;
2326 }
2327 } else {
2328 connected = 1;
2329 break;
2330 }
2331 }
2332 s = net_socket_fd_init(vlan, fd, connected);
2333 if (!s)
2334 return -1;
2335 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2336 "socket: connect to %s:%d",
2337 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2338 return 0;
2339 }
2340
2341 #endif /* !_WIN32 */
2342
2343 static int get_param_value(char *buf, int buf_size,
2344 const char *tag, const char *str)
2345 {
2346 const char *p;
2347 char *q;
2348 char option[128];
2349
2350 p = str;
2351 for(;;) {
2352 q = option;
2353 while (*p != '\0' && *p != '=') {
2354 if ((q - option) < sizeof(option) - 1)
2355 *q++ = *p;
2356 p++;
2357 }
2358 *q = '\0';
2359 if (*p != '=')
2360 break;
2361 p++;
2362 if (!strcmp(tag, option)) {
2363 q = buf;
2364 while (*p != '\0' && *p != ',') {
2365 if ((q - buf) < buf_size - 1)
2366 *q++ = *p;
2367 p++;
2368 }
2369 *q = '\0';
2370 return q - buf;
2371 } else {
2372 while (*p != '\0' && *p != ',') {
2373 p++;
2374 }
2375 }
2376 if (*p != ',')
2377 break;
2378 p++;
2379 }
2380 return 0;
2381 }
2382
2383 int net_client_init(const char *str)
2384 {
2385 const char *p;
2386 char *q;
2387 char device[64];
2388 char buf[1024];
2389 int vlan_id, ret;
2390 VLANState *vlan;
2391
2392 p = str;
2393 q = device;
2394 while (*p != '\0' && *p != ',') {
2395 if ((q - device) < sizeof(device) - 1)
2396 *q++ = *p;
2397 p++;
2398 }
2399 *q = '\0';
2400 if (*p == ',')
2401 p++;
2402 vlan_id = 0;
2403 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
2404 vlan_id = strtol(buf, NULL, 0);
2405 }
2406 vlan = qemu_find_vlan(vlan_id);
2407 if (!vlan) {
2408 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
2409 return -1;
2410 }
2411 if (!strcmp(device, "nic")) {
2412 NICInfo *nd;
2413 uint8_t *macaddr;
2414
2415 if (nb_nics >= MAX_NICS) {
2416 fprintf(stderr, "Too Many NICs\n");
2417 return -1;
2418 }
2419 nd = &nd_table[nb_nics];
2420 macaddr = nd->macaddr;
2421 macaddr[0] = 0x52;
2422 macaddr[1] = 0x54;
2423 macaddr[2] = 0x00;
2424 macaddr[3] = 0x12;
2425 macaddr[4] = 0x34;
2426 macaddr[5] = 0x56 + nb_nics;
2427
2428 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
2429 if (parse_macaddr(macaddr, buf) < 0) {
2430 fprintf(stderr, "invalid syntax for ethernet address\n");
2431 return -1;
2432 }
2433 }
2434 nd->vlan = vlan;
2435 nb_nics++;
2436 ret = 0;
2437 } else
2438 if (!strcmp(device, "none")) {
2439 /* does nothing. It is needed to signal that no network cards
2440 are wanted */
2441 ret = 0;
2442 } else
2443 #ifdef CONFIG_SLIRP
2444 if (!strcmp(device, "user")) {
2445 ret = net_slirp_init(vlan);
2446 } else
2447 #endif
2448 #ifndef _WIN32
2449 if (!strcmp(device, "tap")) {
2450 char ifname[64];
2451 char setup_script[1024];
2452 int fd;
2453 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2454 fd = strtol(buf, NULL, 0);
2455 ret = -1;
2456 if (net_tap_fd_init(vlan, fd))
2457 ret = 0;
2458 } else {
2459 get_param_value(ifname, sizeof(ifname), "ifname", p);
2460 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
2461 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
2462 }
2463 ret = net_tap_init(vlan, ifname, setup_script);
2464 }
2465 } else
2466 if (!strcmp(device, "socket")) {
2467 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
2468 int fd;
2469 fd = strtol(buf, NULL, 0);
2470 ret = -1;
2471 if (net_socket_fd_init(vlan, fd, 1))
2472 ret = 0;
2473 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
2474 ret = net_socket_listen_init(vlan, buf);
2475 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
2476 ret = net_socket_connect_init(vlan, buf);
2477 } else {
2478 fprintf(stderr, "Unknown socket options: %s\n", p);
2479 return -1;
2480 }
2481 } else
2482 #endif
2483 {
2484 fprintf(stderr, "Unknown network device: %s\n", device);
2485 return -1;
2486 }
2487 if (ret < 0) {
2488 fprintf(stderr, "Could not initialize device '%s'\n", device);
2489 }
2490
2491 return ret;
2492 }
2493
2494 void do_info_network(void)
2495 {
2496 VLANState *vlan;
2497 VLANClientState *vc;
2498
2499 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2500 term_printf("VLAN %d devices:\n", vlan->id);
2501 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
2502 term_printf(" %s\n", vc->info_str);
2503 }
2504 }
2505
2506 /***********************************************************/
2507 /* USB devices */
2508
2509 static int usb_device_add(const char *devname)
2510 {
2511 const char *p;
2512 USBDevice *dev;
2513 int i;
2514
2515 if (!vm_usb_hub)
2516 return -1;
2517 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2518 if (!vm_usb_ports[i]->dev)
2519 break;
2520 }
2521 if (i == MAX_VM_USB_PORTS)
2522 return -1;
2523
2524 if (strstart(devname, "host:", &p)) {
2525 dev = usb_host_device_open(p);
2526 if (!dev)
2527 return -1;
2528 } else if (!strcmp(devname, "mouse")) {
2529 dev = usb_mouse_init();
2530 if (!dev)
2531 return -1;
2532 } else {
2533 return -1;
2534 }
2535 usb_attach(vm_usb_ports[i], dev);
2536 return 0;
2537 }
2538
2539 static int usb_device_del(const char *devname)
2540 {
2541 USBDevice *dev;
2542 int bus_num, addr, i;
2543 const char *p;
2544
2545 if (!vm_usb_hub)
2546 return -1;
2547
2548 p = strchr(devname, '.');
2549 if (!p)
2550 return -1;
2551 bus_num = strtoul(devname, NULL, 0);
2552 addr = strtoul(p + 1, NULL, 0);
2553 if (bus_num != 0)
2554 return -1;
2555 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
2556 dev = vm_usb_ports[i]->dev;
2557 if (dev && dev->addr == addr)
2558 break;
2559 }
2560 if (i == MAX_VM_USB_PORTS)
2561 return -1;
2562 usb_attach(vm_usb_ports[i], NULL);
2563 return 0;
2564 }
2565
2566 void do_usb_add(const char *devname)
2567 {
2568 int ret;
2569 ret = usb_device_add(devname);
2570 if (ret < 0)
2571 term_printf("Could not add USB device '%s'\n", devname);
2572 }
2573
2574 void do_usb_del(const char *devname)
2575 {
2576 int ret;
2577 ret = usb_device_del(devname);
2578 if (ret < 0)
2579 term_printf("Could not remove USB device '%s'\n", devname);
2580 }
2581
2582 void usb_info(void)
2583 {
2584 USBDevice *dev;
2585 int i;
2586 const char *speed_str;
2587
2588 if (!vm_usb_hub) {
2589 term_printf("USB support not enabled\n");
2590 return;
2591 }
2592
2593 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
2594 dev = vm_usb_ports[i]->dev;
2595 if (dev) {
2596 term_printf("Hub port %d:\n", i);
2597 switch(dev->speed) {
2598 case USB_SPEED_LOW:
2599 speed_str = "1.5";
2600 break;
2601 case USB_SPEED_FULL:
2602 speed_str = "12";
2603 break;
2604 case USB_SPEED_HIGH:
2605 speed_str = "480";
2606 break;
2607 default:
2608 speed_str = "?";
2609 break;
2610 }
2611 term_printf(" Device %d.%d, speed %s Mb/s\n",
2612 0, dev->addr, speed_str);
2613 }
2614 }
2615 }
2616
2617 /***********************************************************/
2618 /* pid file */
2619
2620 static char *pid_filename;
2621
2622 /* Remove PID file. Called on normal exit */
2623
2624 static void remove_pidfile(void)
2625 {
2626 unlink (pid_filename);
2627 }
2628
2629 static void create_pidfile(const char *filename)
2630 {
2631 struct stat pidstat;
2632 FILE *f;
2633
2634 /* Try to write our PID to the named file */
2635 if (stat(filename, &pidstat) < 0) {
2636 if (errno == ENOENT) {
2637 if ((f = fopen (filename, "w")) == NULL) {
2638 perror("Opening pidfile");
2639 exit(1);
2640 }
2641 fprintf(f, "%d\n", getpid());
2642 fclose(f);
2643 pid_filename = qemu_strdup(filename);
2644 if (!pid_filename) {
2645 fprintf(stderr, "Could not save PID filename");
2646 exit(1);
2647 }
2648 atexit(remove_pidfile);
2649 }
2650 } else {
2651 fprintf(stderr, "%s already exists. Remove it and try again.\n",
2652 filename);
2653 exit(1);
2654 }
2655 }
2656
2657 /***********************************************************/
2658 /* dumb display */
2659
2660 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2661 {
2662 }
2663
2664 static void dumb_resize(DisplayState *ds, int w, int h)
2665 {
2666 }
2667
2668 static void dumb_refresh(DisplayState *ds)
2669 {
2670 vga_update_display();
2671 }
2672
2673 void dumb_display_init(DisplayState *ds)
2674 {
2675 ds->data = NULL;
2676 ds->linesize = 0;
2677 ds->depth = 0;
2678 ds->dpy_update = dumb_update;
2679 ds->dpy_resize = dumb_resize;
2680 ds->dpy_refresh = dumb_refresh;
2681 }
2682
2683 #if !defined(CONFIG_SOFTMMU)
2684 /***********************************************************/
2685 /* cpu signal handler */
2686 static void host_segv_handler(int host_signum, siginfo_t *info,
2687 void *puc)
2688 {
2689 if (cpu_signal_handler(host_signum, info, puc))
2690 return;
2691 if (stdio_nb_clients > 0)
2692 term_exit();
2693 abort();
2694 }
2695 #endif
2696
2697 /***********************************************************/
2698 /* I/O handling */
2699
2700 #define MAX_IO_HANDLERS 64
2701
2702 typedef struct IOHandlerRecord {
2703 int fd;
2704 IOCanRWHandler *fd_read_poll;
2705 IOHandler *fd_read;
2706 IOHandler *fd_write;
2707 void *opaque;
2708 /* temporary data */
2709 struct pollfd *ufd;
2710 struct IOHandlerRecord *next;
2711 } IOHandlerRecord;
2712
2713 static IOHandlerRecord *first_io_handler;
2714
2715 /* XXX: fd_read_poll should be suppressed, but an API change is
2716 necessary in the character devices to suppress fd_can_read(). */
2717 int qemu_set_fd_handler2(int fd,
2718 IOCanRWHandler *fd_read_poll,
2719 IOHandler *fd_read,
2720 IOHandler *fd_write,
2721 void *opaque)
2722 {
2723 IOHandlerRecord **pioh, *ioh;
2724
2725 if (!fd_read && !fd_write) {
2726 pioh = &first_io_handler;
2727 for(;;) {
2728 ioh = *pioh;
2729 if (ioh == NULL)
2730 break;
2731 if (ioh->fd == fd) {
2732 *pioh = ioh->next;
2733 break;
2734 }
2735 pioh = &ioh->next;
2736 }
2737 } else {
2738 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2739 if (ioh->fd == fd)
2740 goto found;
2741 }
2742 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2743 if (!ioh)
2744 return -1;
2745 ioh->next = first_io_handler;
2746 first_io_handler = ioh;
2747 found:
2748 ioh->fd = fd;
2749 ioh->fd_read_poll = fd_read_poll;
2750 ioh->fd_read = fd_read;
2751 ioh->fd_write = fd_write;
2752 ioh->opaque = opaque;
2753 }
2754 return 0;
2755 }
2756
2757 int qemu_set_fd_handler(int fd,
2758 IOHandler *fd_read,
2759 IOHandler *fd_write,
2760 void *opaque)
2761 {
2762 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2763 }
2764
2765 /***********************************************************/
2766 /* savevm/loadvm support */
2767
2768 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2769 {
2770 fwrite(buf, 1, size, f);
2771 }
2772
2773 void qemu_put_byte(QEMUFile *f, int v)
2774 {
2775 fputc(v, f);
2776 }
2777
2778 void qemu_put_be16(QEMUFile *f, unsigned int v)
2779 {
2780 qemu_put_byte(f, v >> 8);
2781 qemu_put_byte(f, v);
2782 }
2783
2784 void qemu_put_be32(QEMUFile *f, unsigned int v)
2785 {
2786 qemu_put_byte(f, v >> 24);
2787 qemu_put_byte(f, v >> 16);
2788 qemu_put_byte(f, v >> 8);
2789 qemu_put_byte(f, v);
2790 }
2791
2792 void qemu_put_be64(QEMUFile *f, uint64_t v)
2793 {
2794 qemu_put_be32(f, v >> 32);
2795 qemu_put_be32(f, v);
2796 }
2797
2798 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
2799 {
2800 return fread(buf, 1, size, f);
2801 }
2802
2803 int qemu_get_byte(QEMUFile *f)
2804 {
2805 int v;
2806 v = fgetc(f);
2807 if (v == EOF)
2808 return 0;
2809 else
2810 return v;
2811 }
2812
2813 unsigned int qemu_get_be16(QEMUFile *f)
2814 {
2815 unsigned int v;
2816 v = qemu_get_byte(f) << 8;
2817 v |= qemu_get_byte(f);
2818 return v;
2819 }
2820
2821 unsigned int qemu_get_be32(QEMUFile *f)
2822 {
2823 unsigned int v;
2824 v = qemu_get_byte(f) << 24;
2825 v |= qemu_get_byte(f) << 16;
2826 v |= qemu_get_byte(f) << 8;
2827 v |= qemu_get_byte(f);
2828 return v;
2829 }
2830
2831 uint64_t qemu_get_be64(QEMUFile *f)
2832 {
2833 uint64_t v;
2834 v = (uint64_t)qemu_get_be32(f) << 32;
2835 v |= qemu_get_be32(f);
2836 return v;
2837 }
2838
2839 int64_t qemu_ftell(QEMUFile *f)
2840 {
2841 return ftell(f);
2842 }
2843
2844 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
2845 {
2846 if (fseek(f, pos, whence) < 0)
2847 return -1;
2848 return ftell(f);
2849 }
2850
2851 typedef struct SaveStateEntry {
2852 char idstr[256];
2853 int instance_id;
2854 int version_id;
2855 SaveStateHandler *save_state;
2856 LoadStateHandler *load_state;
2857 void *opaque;
2858 struct SaveStateEntry *next;
2859 } SaveStateEntry;
2860
2861 static SaveStateEntry *first_se;
2862
2863 int register_savevm(const char *idstr,
2864 int instance_id,
2865 int version_id,
2866 SaveStateHandler *save_state,
2867 LoadStateHandler *load_state,
2868 void *opaque)
2869 {
2870 SaveStateEntry *se, **pse;
2871
2872 se = qemu_malloc(sizeof(SaveStateEntry));
2873 if (!se)
2874 return -1;
2875 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
2876 se->instance_id = instance_id;
2877 se->version_id = version_id;
2878 se->save_state = save_state;
2879 se->load_state = load_state;
2880 se->opaque = opaque;
2881 se->next = NULL;
2882
2883 /* add at the end of list */
2884 pse = &first_se;
2885 while (*pse != NULL)
2886 pse = &(*pse)->next;
2887 *pse = se;
2888 return 0;
2889 }
2890
2891 #define QEMU_VM_FILE_MAGIC 0x5145564d
2892 #define QEMU_VM_FILE_VERSION 0x00000001
2893
2894 int qemu_savevm(const char *filename)
2895 {
2896 SaveStateEntry *se;
2897 QEMUFile *f;
2898 int len, len_pos, cur_pos, saved_vm_running, ret;
2899
2900 saved_vm_running = vm_running;
2901 vm_stop(0);
2902
2903 f = fopen(filename, "wb");
2904 if (!f) {
2905 ret = -1;
2906 goto the_end;
2907 }
2908
2909 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
2910 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
2911
2912 for(se = first_se; se != NULL; se = se->next) {
2913 /* ID string */
2914 len = strlen(se->idstr);
2915 qemu_put_byte(f, len);
2916 qemu_put_buffer(f, se->idstr, len);
2917
2918 qemu_put_be32(f, se->instance_id);
2919 qemu_put_be32(f, se->version_id);
2920
2921 /* record size: filled later */
2922 len_pos = ftell(f);
2923 qemu_put_be32(f, 0);
2924
2925 se->save_state(f, se->opaque);
2926
2927 /* fill record size */
2928 cur_pos = ftell(f);
2929 len = ftell(f) - len_pos - 4;
2930 fseek(f, len_pos, SEEK_SET);
2931 qemu_put_be32(f, len);
2932 fseek(f, cur_pos, SEEK_SET);
2933 }
2934
2935 fclose(f);
2936 ret = 0;
2937 the_end:
2938 if (saved_vm_running)
2939 vm_start();
2940 return ret;
2941 }
2942
2943 static SaveStateEntry *find_se(const char *idstr, int instance_id)
2944 {
2945 SaveStateEntry *se;
2946
2947 for(se = first_se; se != NULL; se = se->next) {
2948 if (!strcmp(se->idstr, idstr) &&
2949 instance_id == se->instance_id)
2950 return se;
2951 }
2952 return NULL;
2953 }
2954
2955 int qemu_loadvm(const char *filename)
2956 {
2957 SaveStateEntry *se;
2958 QEMUFile *f;
2959 int len, cur_pos, ret, instance_id, record_len, version_id;
2960 int saved_vm_running;
2961 unsigned int v;
2962 char idstr[256];
2963
2964 saved_vm_running = vm_running;
2965 vm_stop(0);
2966
2967 f = fopen(filename, "rb");
2968 if (!f) {
2969 ret = -1;
2970 goto the_end;
2971 }
2972
2973 v = qemu_get_be32(f);
2974 if (v != QEMU_VM_FILE_MAGIC)
2975 goto fail;
2976 v = qemu_get_be32(f);
2977 if (v != QEMU_VM_FILE_VERSION) {
2978 fail:
2979 fclose(f);
2980 ret = -1;
2981 goto the_end;
2982 }
2983 for(;;) {
2984 len = qemu_get_byte(f);
2985 if (feof(f))
2986 break;
2987 qemu_get_buffer(f, idstr, len);
2988 idstr[len] = '\0';
2989 instance_id = qemu_get_be32(f);
2990 version_id = qemu_get_be32(f);
2991 record_len = qemu_get_be32(f);
2992 #if 0
2993 printf("idstr=%s instance=0x%x version=%d len=%d\n",
2994 idstr, instance_id, version_id, record_len);
2995 #endif
2996 cur_pos = ftell(f);
2997 se = find_se(idstr, instance_id);
2998 if (!se) {
2999 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3000 instance_id, idstr);
3001 } else {
3002 ret = se->load_state(f, se->opaque, version_id);
3003 if (ret < 0) {
3004 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3005 instance_id, idstr);
3006 }
3007 }
3008 /* always seek to exact end of record */
3009 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3010 }
3011 fclose(f);
3012 ret = 0;
3013 the_end:
3014 if (saved_vm_running)
3015 vm_start();
3016 return ret;
3017 }
3018
3019 /***********************************************************/
3020 /* cpu save/restore */
3021
3022 #if defined(TARGET_I386)
3023
3024 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3025 {
3026 qemu_put_be32(f, dt->selector);
3027 qemu_put_betl(f, dt->base);
3028 qemu_put_be32(f, dt->limit);
3029 qemu_put_be32(f, dt->flags);
3030 }
3031
3032 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3033 {
3034 dt->selector = qemu_get_be32(f);
3035 dt->base = qemu_get_betl(f);
3036 dt->limit = qemu_get_be32(f);
3037 dt->flags = qemu_get_be32(f);
3038 }
3039
3040 void cpu_save(QEMUFile *f, void *opaque)
3041 {
3042 CPUState *env = opaque;
3043 uint16_t fptag, fpus, fpuc, fpregs_format;
3044 uint32_t hflags;
3045 int i;
3046
3047 for(i = 0; i < CPU_NB_REGS; i++)
3048 qemu_put_betls(f, &env->regs[i]);
3049 qemu_put_betls(f, &env->eip);
3050 qemu_put_betls(f, &env->eflags);
3051 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3052 qemu_put_be32s(f, &hflags);
3053
3054 /* FPU */
3055 fpuc = env->fpuc;
3056 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3057 fptag = 0;
3058 for(i = 0; i < 8; i++) {
3059 fptag |= ((!env->fptags[i]) << i);
3060 }
3061
3062 qemu_put_be16s(f, &fpuc);
3063 qemu_put_be16s(f, &fpus);
3064 qemu_put_be16s(f, &fptag);
3065
3066 #ifdef USE_X86LDOUBLE
3067 fpregs_format = 0;
3068 #else
3069 fpregs_format = 1;
3070 #endif
3071 qemu_put_be16s(f, &fpregs_format);
3072
3073 for(i = 0; i < 8; i++) {
3074 #ifdef USE_X86LDOUBLE
3075 {
3076 uint64_t mant;
3077 uint16_t exp;
3078 /* we save the real CPU data (in case of MMX usage only 'mant'
3079 contains the MMX register */
3080 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3081 qemu_put_be64(f, mant);
3082 qemu_put_be16(f, exp);
3083 }
3084 #else
3085 /* if we use doubles for float emulation, we save the doubles to
3086 avoid losing information in case of MMX usage. It can give
3087 problems if the image is restored on a CPU where long
3088 doubles are used instead. */
3089 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3090 #endif
3091 }
3092
3093 for(i = 0; i < 6; i++)
3094 cpu_put_seg(f, &env->segs[i]);
3095 cpu_put_seg(f, &env->ldt);
3096 cpu_put_seg(f, &env->tr);
3097 cpu_put_seg(f, &env->gdt);
3098 cpu_put_seg(f, &env->idt);
3099
3100 qemu_put_be32s(f, &env->sysenter_cs);
3101 qemu_put_be32s(f, &env->sysenter_esp);
3102 qemu_put_be32s(f, &env->sysenter_eip);
3103
3104 qemu_put_betls(f, &env->cr[0]);
3105 qemu_put_betls(f, &env->cr[2]);
3106 qemu_put_betls(f, &env->cr[3]);
3107 qemu_put_betls(f, &env->cr[4]);
3108
3109 for(i = 0; i < 8; i++)
3110 qemu_put_betls(f, &env->dr[i]);
3111
3112 /* MMU */
3113 qemu_put_be32s(f, &env->a20_mask);
3114
3115 /* XMM */
3116 qemu_put_be32s(f, &env->mxcsr);
3117 for(i = 0; i < CPU_NB_REGS; i++) {
3118 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3119 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3120 }
3121
3122 #ifdef TARGET_X86_64
3123 qemu_put_be64s(f, &env->efer);
3124 qemu_put_be64s(f, &env->star);
3125 qemu_put_be64s(f, &env->lstar);
3126 qemu_put_be64s(f, &env->cstar);
3127 qemu_put_be64s(f, &env->fmask);
3128 qemu_put_be64s(f, &env->kernelgsbase);
3129 #endif
3130 }
3131
3132 #ifdef USE_X86LDOUBLE
3133 /* XXX: add that in a FPU generic layer */
3134 union x86_longdouble {
3135 uint64_t mant;
3136 uint16_t exp;
3137 };
3138
3139 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3140 #define EXPBIAS1 1023
3141 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3142 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3143
3144 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3145 {
3146 int e;
3147 /* mantissa */
3148 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3149 /* exponent + sign */
3150 e = EXPD1(temp) - EXPBIAS1 + 16383;
3151 e |= SIGND1(temp) >> 16;
3152 p->exp = e;
3153 }
3154 #endif
3155
3156 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3157 {
3158 CPUState *env = opaque;
3159 int i, guess_mmx;
3160 uint32_t hflags;
3161 uint16_t fpus, fpuc, fptag, fpregs_format;
3162
3163 if (version_id != 3)
3164 return -EINVAL;
3165 for(i = 0; i < CPU_NB_REGS; i++)
3166 qemu_get_betls(f, &env->regs[i]);
3167 qemu_get_betls(f, &env->eip);
3168 qemu_get_betls(f, &env->eflags);
3169 qemu_get_be32s(f, &hflags);
3170
3171 qemu_get_be16s(f, &fpuc);
3172 qemu_get_be16s(f, &fpus);
3173 qemu_get_be16s(f, &fptag);
3174 qemu_get_be16s(f, &fpregs_format);
3175
3176 /* NOTE: we cannot always restore the FPU state if the image come
3177 from a host with a different 'USE_X86LDOUBLE' define. We guess
3178 if we are in an MMX state to restore correctly in that case. */
3179 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3180 for(i = 0; i < 8; i++) {
3181 uint64_t mant;
3182 uint16_t exp;
3183
3184 switch(fpregs_format) {
3185 case 0:
3186 mant = qemu_get_be64(f);
3187 exp = qemu_get_be16(f);
3188 #ifdef USE_X86LDOUBLE
3189 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3190 #else
3191 /* difficult case */
3192 if (guess_mmx)
3193 env->fpregs[i].mmx.MMX_Q(0) = mant;
3194 else
3195 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3196 #endif
3197 break;
3198 case 1:
3199 mant = qemu_get_be64(f);
3200 #ifdef USE_X86LDOUBLE
3201 {
3202 union x86_longdouble *p;
3203 /* difficult case */
3204 p = (void *)&env->fpregs[i];
3205 if (guess_mmx) {
3206 p->mant = mant;
3207 p->exp = 0xffff;
3208 } else {
3209 fp64_to_fp80(p, mant);
3210 }
3211 }
3212 #else
3213 env->fpregs[i].mmx.MMX_Q(0) = mant;
3214 #endif
3215 break;
3216 default:
3217 return -EINVAL;
3218 }
3219 }
3220
3221 env->fpuc = fpuc;
3222 /* XXX: restore FPU round state */
3223 env->fpstt = (fpus >> 11) & 7;
3224 env->fpus = fpus & ~0x3800;
3225 fptag ^= 0xff;
3226 for(i = 0; i < 8; i++) {
3227 env->fptags[i] = (fptag >> i) & 1;
3228 }
3229
3230 for(i = 0; i < 6; i++)
3231 cpu_get_seg(f, &env->segs[i]);
3232 cpu_get_seg(f, &env->ldt);
3233 cpu_get_seg(f, &env->tr);
3234 cpu_get_seg(f, &env->gdt);
3235 cpu_get_seg(f, &env->idt);
3236
3237 qemu_get_be32s(f, &env->sysenter_cs);
3238 qemu_get_be32s(f, &env->sysenter_esp);
3239 qemu_get_be32s(f, &env->sysenter_eip);
3240
3241 qemu_get_betls(f, &env->cr[0]);
3242 qemu_get_betls(f, &env->cr[2]);
3243 qemu_get_betls(f, &env->cr[3]);
3244 qemu_get_betls(f, &env->cr[4]);
3245
3246 for(i = 0; i < 8; i++)
3247 qemu_get_betls(f, &env->dr[i]);
3248
3249 /* MMU */
3250 qemu_get_be32s(f, &env->a20_mask);
3251
3252 qemu_get_be32s(f, &env->mxcsr);
3253 for(i = 0; i < CPU_NB_REGS; i++) {
3254 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3255 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3256 }
3257
3258 #ifdef TARGET_X86_64
3259 qemu_get_be64s(f, &env->efer);
3260 qemu_get_be64s(f, &env->star);
3261 qemu_get_be64s(f, &env->lstar);
3262 qemu_get_be64s(f, &env->cstar);
3263 qemu_get_be64s(f, &env->fmask);
3264 qemu_get_be64s(f, &env->kernelgsbase);
3265 #endif
3266
3267 /* XXX: compute hflags from scratch, except for CPL and IIF */
3268 env->hflags = hflags;
3269 tlb_flush(env, 1);
3270 return 0;
3271 }
3272
3273 #elif defined(TARGET_PPC)
3274 void cpu_save(QEMUFile *f, void *opaque)
3275 {
3276 }
3277
3278 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3279 {
3280 return 0;
3281 }
3282
3283 #elif defined(TARGET_MIPS)
3284 void cpu_save(QEMUFile *f, void *opaque)
3285 {
3286 }
3287
3288 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3289 {
3290 return 0;
3291 }
3292
3293 #elif defined(TARGET_SPARC)
3294 void cpu_save(QEMUFile *f, void *opaque)
3295 {
3296 CPUState *env = opaque;
3297 int i;
3298 uint32_t tmp;
3299
3300 for(i = 0; i < 8; i++)
3301 qemu_put_betls(f, &env->gregs[i]);
3302 for(i = 0; i < NWINDOWS * 16; i++)
3303 qemu_put_betls(f, &env->regbase[i]);
3304
3305 /* FPU */
3306 for(i = 0; i < TARGET_FPREGS; i++) {
3307 union {
3308 TARGET_FPREG_T f;
3309 target_ulong i;
3310 } u;
3311 u.f = env->fpr[i];
3312 qemu_put_betl(f, u.i);
3313 }
3314
3315 qemu_put_betls(f, &env->pc);
3316 qemu_put_betls(f, &env->npc);
3317 qemu_put_betls(f, &env->y);
3318 tmp = GET_PSR(env);
3319 qemu_put_be32(f, tmp);
3320 qemu_put_betls(f, &env->fsr);
3321 qemu_put_betls(f, &env->tbr);
3322 #ifndef TARGET_SPARC64
3323 qemu_put_be32s(f, &env->wim);
3324 /* MMU */
3325 for(i = 0; i < 16; i++)
3326 qemu_put_be32s(f, &env->mmuregs[i]);
3327 #endif
3328 }
3329
3330 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3331 {
3332 CPUState *env = opaque;
3333 int i;
3334 uint32_t tmp;
3335
3336 for(i = 0; i < 8; i++)
3337 qemu_get_betls(f, &env->gregs[i]);
3338 for(i = 0; i < NWINDOWS * 16; i++)
3339 qemu_get_betls(f, &env->regbase[i]);
3340
3341 /* FPU */
3342 for(i = 0; i < TARGET_FPREGS; i++) {
3343 union {
3344 TARGET_FPREG_T f;
3345 target_ulong i;
3346 } u;
3347 u.i = qemu_get_betl(f);
3348 env->fpr[i] = u.f;
3349 }
3350
3351 qemu_get_betls(f, &env->pc);
3352 qemu_get_betls(f, &env->npc);
3353 qemu_get_betls(f, &env->y);
3354 tmp = qemu_get_be32(f);
3355 env->cwp = 0; /* needed to ensure that the wrapping registers are
3356 correctly updated */
3357 PUT_PSR(env, tmp);
3358 qemu_get_betls(f, &env->fsr);
3359 qemu_get_betls(f, &env->tbr);
3360 #ifndef TARGET_SPARC64
3361 qemu_get_be32s(f, &env->wim);
3362 /* MMU */
3363 for(i = 0; i < 16; i++)
3364 qemu_get_be32s(f, &env->mmuregs[i]);
3365 #endif
3366 tlb_flush(env, 1);
3367 return 0;
3368 }
3369
3370 #elif defined(TARGET_ARM)
3371
3372 /* ??? Need to implement these. */
3373 void cpu_save(QEMUFile *f, void *opaque)
3374 {
3375 }
3376
3377 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3378 {
3379 return 0;
3380 }
3381
3382 #else
3383
3384 #warning No CPU save/restore functions
3385
3386 #endif
3387
3388 /***********************************************************/
3389 /* ram save/restore */
3390
3391 /* we just avoid storing empty pages */
3392 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
3393 {
3394 int i, v;
3395
3396 v = buf[0];
3397 for(i = 1; i < len; i++) {
3398 if (buf[i] != v)
3399 goto normal_save;
3400 }
3401 qemu_put_byte(f, 1);
3402 qemu_put_byte(f, v);
3403 return;
3404 normal_save:
3405 qemu_put_byte(f, 0);
3406 qemu_put_buffer(f, buf, len);
3407 }
3408
3409 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3410 {
3411 int v;
3412
3413 v = qemu_get_byte(f);
3414 switch(v) {
3415 case 0:
3416 if (qemu_get_buffer(f, buf, len) != len)
3417 return -EIO;
3418 break;
3419 case 1:
3420 v = qemu_get_byte(f);
3421 memset(buf, v, len);
3422 break;
3423 default:
3424 return -EINVAL;
3425 }
3426 return 0;
3427 }
3428
3429 static void ram_save(QEMUFile *f, void *opaque)
3430 {
3431 int i;
3432 qemu_put_be32(f, phys_ram_size);
3433 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3434 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3435 }
3436 }
3437
3438 static int ram_load(QEMUFile *f, void *opaque, int version_id)
3439 {
3440 int i, ret;
3441
3442 if (version_id != 1)
3443 return -EINVAL;
3444 if (qemu_get_be32(f) != phys_ram_size)
3445 return -EINVAL;
3446 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3447 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3448 if (ret)
3449 return ret;
3450 }
3451 return 0;
3452 }
3453
3454 /***********************************************************/
3455 /* machine registration */
3456
3457 QEMUMachine *first_machine = NULL;
3458
3459 int qemu_register_machine(QEMUMachine *m)
3460 {
3461 QEMUMachine **pm;
3462 pm = &first_machine;
3463 while (*pm != NULL)
3464 pm = &(*pm)->next;
3465 m->next = NULL;
3466 *pm = m;
3467 return 0;
3468 }
3469
3470 QEMUMachine *find_machine(const char *name)
3471 {
3472 QEMUMachine *m;
3473
3474 for(m = first_machine; m != NULL; m = m->next) {
3475 if (!strcmp(m->name, name))
3476 return m;
3477 }
3478 return NULL;
3479 }
3480
3481 /***********************************************************/
3482 /* main execution loop */
3483
3484 void gui_update(void *opaque)
3485 {
3486 display_state.dpy_refresh(&display_state);
3487 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
3488 }
3489
3490 struct vm_change_state_entry {
3491 VMChangeStateHandler *cb;
3492 void *opaque;
3493 LIST_ENTRY (vm_change_state_entry) entries;
3494 };
3495
3496 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3497
3498 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3499 void *opaque)
3500 {
3501 VMChangeStateEntry *e;
3502
3503 e = qemu_mallocz(sizeof (*e));
3504 if (!e)
3505 return NULL;
3506
3507 e->cb = cb;
3508 e->opaque = opaque;
3509 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3510 return e;
3511 }
3512
3513 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3514 {
3515 LIST_REMOVE (e, entries);
3516 qemu_free (e);
3517 }
3518
3519 static void vm_state_notify(int running)
3520 {
3521 VMChangeStateEntry *e;
3522
3523 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3524 e->cb(e->opaque, running);
3525 }
3526 }
3527
3528 /* XXX: support several handlers */
3529 static VMStopHandler *vm_stop_cb;
3530 static void *vm_stop_opaque;
3531
3532 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3533 {
3534 vm_stop_cb = cb;
3535 vm_stop_opaque = opaque;
3536 return 0;
3537 }
3538
3539 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3540 {
3541 vm_stop_cb = NULL;
3542 }
3543
3544 void vm_start(void)
3545 {
3546 if (!vm_running) {
3547 cpu_enable_ticks();
3548 vm_running = 1;
3549 vm_state_notify(1);
3550 }
3551 }
3552
3553 void vm_stop(int reason)
3554 {
3555 if (vm_running) {
3556 cpu_disable_ticks();
3557 vm_running = 0;
3558 if (reason != 0) {
3559 if (vm_stop_cb) {
3560 vm_stop_cb(vm_stop_opaque, reason);
3561 }
3562 }
3563 vm_state_notify(0);
3564 }
3565 }
3566
3567 /* reset/shutdown handler */
3568
3569 typedef struct QEMUResetEntry {
3570 QEMUResetHandler *func;
3571 void *opaque;
3572 struct QEMUResetEntry *next;
3573 } QEMUResetEntry;
3574
3575 static QEMUResetEntry *first_reset_entry;
3576 static int reset_requested;
3577 static int shutdown_requested;
3578 static int powerdown_requested;
3579
3580 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3581 {
3582 QEMUResetEntry **pre, *re;
3583
3584 pre = &first_reset_entry;
3585 while (*pre != NULL)
3586 pre = &(*pre)->next;
3587 re = qemu_mallocz(sizeof(QEMUResetEntry));
3588 re->func = func;
3589 re->opaque = opaque;
3590 re->next = NULL;
3591 *pre = re;
3592 }
3593
3594 void qemu_system_reset(void)
3595 {
3596 QEMUResetEntry *re;
3597
3598 /* reset all devices */
3599 for(re = first_reset_entry; re != NULL; re = re->next) {
3600 re->func(re->opaque);
3601 }
3602 }
3603
3604 void qemu_system_reset_request(void)
3605 {
3606 reset_requested = 1;
3607 if (cpu_single_env)
3608 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3609 }
3610
3611 void qemu_system_shutdown_request(void)
3612 {
3613 shutdown_requested = 1;
3614 if (cpu_single_env)
3615 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3616 }
3617
3618 void qemu_system_powerdown_request(void)
3619 {
3620 powerdown_requested = 1;
3621 if (cpu_single_env)
3622 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3623 }
3624
3625 void main_loop_wait(int timeout)
3626 {
3627 #ifndef _WIN32
3628 struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
3629 IOHandlerRecord *ioh, *ioh_next;
3630 #endif
3631 int ret;
3632
3633 #ifdef _WIN32
3634 if (timeout > 0)
3635 Sleep(timeout);
3636 #else
3637 /* poll any events */
3638 /* XXX: separate device handlers from system ones */
3639 pf = ufds;
3640 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3641 pf->events = 0;
3642 pf->fd = ioh->fd;
3643 if (ioh->fd_read &&
3644 (!ioh->fd_read_poll ||
3645 ioh->fd_read_poll(ioh->opaque) != 0)) {
3646 pf->events |= POLLIN;
3647 }
3648 if (ioh->fd_write) {
3649 pf->events |= POLLOUT;
3650 }
3651 ioh->ufd = pf;
3652 pf++;
3653 }
3654
3655 ret = poll(ufds, pf - ufds, timeout);
3656 if (ret > 0) {
3657 /* XXX: better handling of removal */
3658 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
3659 ioh_next = ioh->next;
3660 pf = ioh->ufd;
3661 if (pf->revents & POLLIN) {
3662 ioh->fd_read(ioh->opaque);
3663 }
3664 if (pf->revents & POLLOUT) {
3665 ioh->fd_write(ioh->opaque);
3666 }
3667 }
3668 }
3669 #endif /* !defined(_WIN32) */
3670 #if defined(CONFIG_SLIRP)
3671 /* XXX: merge with poll() */
3672 if (slirp_inited) {
3673 fd_set rfds, wfds, xfds;
3674 int nfds;
3675 struct timeval tv;
3676
3677 nfds = -1;
3678 FD_ZERO(&rfds);
3679 FD_ZERO(&wfds);
3680 FD_ZERO(&xfds);
3681 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3682 tv.tv_sec = 0;
3683 tv.tv_usec = 0;
3684 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3685 if (ret >= 0) {
3686 slirp_select_poll(&rfds, &wfds, &xfds);
3687 }
3688 }
3689 #endif
3690
3691 if (vm_running) {
3692 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3693 qemu_get_clock(vm_clock));
3694 /* run dma transfers, if any */
3695 DMA_run();
3696 }
3697
3698 /* real time timers */
3699 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3700 qemu_get_clock(rt_clock));
3701 }
3702
3703 static CPUState *cur_cpu;
3704
3705 int main_loop(void)
3706 {
3707 int ret, timeout;
3708 CPUState *env;
3709
3710 cur_cpu = first_cpu;
3711 for(;;) {
3712 if (vm_running) {
3713
3714 env = cur_cpu;
3715 for(;;) {
3716 /* get next cpu */
3717 env = env->next_cpu;
3718 if (!env)
3719 env = first_cpu;
3720 ret = cpu_exec(env);
3721 if (ret != EXCP_HALTED)
3722 break;
3723 /* all CPUs are halted ? */
3724 if (env == cur_cpu) {
3725 ret = EXCP_HLT;
3726 break;
3727 }
3728 }
3729 cur_cpu = env;
3730
3731 if (shutdown_requested) {
3732 ret = EXCP_INTERRUPT;
3733 break;
3734 }
3735 if (reset_requested) {
3736 reset_requested = 0;
3737 qemu_system_reset();
3738 ret = EXCP_INTERRUPT;
3739 }
3740 if (powerdown_requested) {
3741 powerdown_requested = 0;
3742 qemu_system_powerdown();
3743 ret = EXCP_INTERRUPT;
3744 }
3745 if (ret == EXCP_DEBUG) {
3746 vm_stop(EXCP_DEBUG);
3747 }
3748 /* if hlt instruction, we wait until the next IRQ */
3749 /* XXX: use timeout computed from timers */
3750 if (ret == EXCP_HLT)
3751 timeout = 10;
3752 else
3753 timeout = 0;
3754 } else {
3755 timeout = 10;
3756 }
3757 main_loop_wait(timeout);
3758 }
3759 cpu_disable_ticks();
3760 return ret;
3761 }
3762
3763 void help(void)
3764 {
3765 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
3766 "usage: %s [options] [disk_image]\n"
3767 "\n"
3768 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3769 "\n"
3770 "Standard options:\n"
3771 "-M machine select emulated machine (-M ? for list)\n"
3772 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
3773 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
3774 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
3775 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3776 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
3777 "-snapshot write to temporary files instead of disk image files\n"
3778 "-m megs set virtual RAM size to megs MB [default=%d]\n"
3779 "-nographic disable graphical output and redirect serial I/Os to console\n"
3780 #ifndef _WIN32
3781 "-k language use keyboard layout (for example \"fr\" for French)\n"
3782 #endif
3783 #ifdef HAS_AUDIO
3784 "-enable-audio enable audio support, and all the sound cars\n"
3785 "-audio-help print list of audio drivers and their options\n"
3786 "-soundhw c1,... enable audio support\n"
3787 " and only specified sound cards (comma separated list)\n"
3788 " use -soundhw ? to get the list of supported cards\n"
3789 #endif
3790 "-localtime set the real time clock to local time [default=utc]\n"
3791 "-full-screen start in full screen\n"
3792 #ifdef TARGET_I386
3793 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
3794 #endif
3795 "-usb enable the USB driver (will be the default soon)\n"
3796 "-usbdevice name add the host or guest USB device 'name'\n"
3797 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3798 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
3799 #endif
3800 "\n"
3801 "Network options:\n"
3802 "-net nic[,vlan=n][,macaddr=addr]\n"
3803 " create a new Network Interface Card and connect it to VLAN 'n'\n"
3804 #ifdef CONFIG_SLIRP
3805 "-net user[,vlan=n]\n"
3806 " connect the user mode network stack to VLAN 'n'\n"
3807 #endif
3808 #ifndef _WIN32
3809 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
3810 " connect the host TAP network interface to VLAN 'n' and use\n"
3811 " the network script 'file' (default=%s);\n"
3812 " use 'fd=h' to connect to an already opened TAP interface\n"
3813 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3814 " connect the vlan 'n' to another VLAN using a socket connection\n"
3815 #endif
3816 "-net none use it alone to have zero network devices; if no -net option\n"
3817 " is provided, the default is '-net nic -net user'\n"
3818 "\n"
3819 #ifdef CONFIG_SLIRP
3820 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
3821 #ifndef _WIN32
3822 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
3823 #endif
3824 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3825 " redirect TCP or UDP connections from host to guest [-net user]\n"
3826 #endif
3827 "\n"
3828 "Linux boot specific:\n"
3829 "-kernel bzImage use 'bzImage' as kernel image\n"
3830 "-append cmdline use 'cmdline' as kernel command line\n"
3831 "-initrd file use 'file' as initial ram disk\n"
3832 "\n"
3833 "Debug/Expert options:\n"
3834 "-monitor dev redirect the monitor to char device 'dev'\n"
3835 "-serial dev redirect the serial port to char device 'dev'\n"
3836 "-parallel dev redirect the parallel port to char device 'dev'\n"
3837 "-pidfile file Write PID to 'file'\n"
3838 "-S freeze CPU at startup (use 'c' to start execution)\n"
3839 "-s wait gdb connection to port %d\n"
3840 "-p port change gdb connection port\n"
3841 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
3842 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
3843 " translation (t=none or lba) (usually qemu can guess them)\n"
3844 "-L path set the directory for the BIOS and VGA BIOS\n"
3845 #ifdef USE_KQEMU
3846 "-no-kqemu disable KQEMU kernel module usage\n"
3847 #endif
3848 #ifdef USE_CODE_COPY
3849 "-no-code-copy disable code copy acceleration\n"
3850 #endif
3851 #ifdef TARGET_I386
3852 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
3853 " (default is CL-GD5446 PCI VGA)\n"
3854 #endif
3855 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
3856 "\n"
3857 "During emulation, the following keys are useful:\n"
3858 "ctrl-alt-f toggle full screen\n"
3859 "ctrl-alt-n switch to virtual console 'n'\n"
3860 "ctrl-alt toggle mouse and keyboard grab\n"
3861 "\n"
3862 "When using -nographic, press 'ctrl-a h' to get some help.\n"
3863 ,
3864 #ifdef CONFIG_SOFTMMU
3865 "qemu",
3866 #else
3867 "qemu-fast",
3868 #endif
3869 DEFAULT_RAM_SIZE,
3870 #ifndef _WIN32
3871 DEFAULT_NETWORK_SCRIPT,
3872 #endif
3873 DEFAULT_GDBSTUB_PORT,
3874 "/tmp/qemu.log");
3875 #ifndef CONFIG_SOFTMMU
3876 printf("\n"
3877 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
3878 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
3879 "PC emulation.\n");
3880 #endif
3881 exit(1);
3882 }
3883
3884 #define HAS_ARG 0x0001
3885
3886 enum {
3887 QEMU_OPTION_h,
3888
3889 QEMU_OPTION_M,
3890 QEMU_OPTION_fda,
3891 QEMU_OPTION_fdb,
3892 QEMU_OPTION_hda,
3893 QEMU_OPTION_hdb,
3894 QEMU_OPTION_hdc,
3895 QEMU_OPTION_hdd,
3896 QEMU_OPTION_cdrom,
3897 QEMU_OPTION_boot,
3898 QEMU_OPTION_snapshot,
3899 QEMU_OPTION_m,
3900 QEMU_OPTION_nographic,
3901 #ifdef HAS_AUDIO
3902 QEMU_OPTION_enable_audio,
3903 QEMU_OPTION_audio_help,
3904 QEMU_OPTION_soundhw,
3905 #endif
3906
3907 QEMU_OPTION_net,
3908 QEMU_OPTION_tftp,
3909 QEMU_OPTION_smb,
3910 QEMU_OPTION_redir,
3911
3912 QEMU_OPTION_kernel,
3913 QEMU_OPTION_append,
3914 QEMU_OPTION_initrd,
3915
3916 QEMU_OPTION_S,
3917 QEMU_OPTION_s,
3918 QEMU_OPTION_p,
3919 QEMU_OPTION_d,
3920 QEMU_OPTION_hdachs,
3921 QEMU_OPTION_L,
3922 QEMU_OPTION_no_code_copy,
3923 QEMU_OPTION_k,
3924 QEMU_OPTION_localtime,
3925 QEMU_OPTION_cirrusvga,
3926 QEMU_OPTION_g,
3927 QEMU_OPTION_std_vga,
3928 QEMU_OPTION_monitor,
3929 QEMU_OPTION_serial,
3930 QEMU_OPTION_parallel,
3931 QEMU_OPTION_loadvm,
3932 QEMU_OPTION_full_screen,
3933 QEMU_OPTION_pidfile,
3934 QEMU_OPTION_no_kqemu,
3935 QEMU_OPTION_win2k_hack,
3936 QEMU_OPTION_usb,
3937 QEMU_OPTION_usbdevice,
3938 QEMU_OPTION_smp,
3939 };
3940
3941 typedef struct QEMUOption {
3942 const char *name;
3943 int flags;
3944 int index;
3945 } QEMUOption;
3946
3947 const QEMUOption qemu_options[] = {
3948 { "h", 0, QEMU_OPTION_h },
3949
3950 { "M", HAS_ARG, QEMU_OPTION_M },
3951 { "fda", HAS_ARG, QEMU_OPTION_fda },
3952 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
3953 { "hda", HAS_ARG, QEMU_OPTION_hda },
3954 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
3955 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
3956 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
3957 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
3958 { "boot", HAS_ARG, QEMU_OPTION_boot },
3959 { "snapshot", 0, QEMU_OPTION_snapshot },
3960 { "m", HAS_ARG, QEMU_OPTION_m },
3961 { "nographic", 0, QEMU_OPTION_nographic },
3962 { "k", HAS_ARG, QEMU_OPTION_k },
3963 #ifdef HAS_AUDIO
3964 { "enable-audio", 0, QEMU_OPTION_enable_audio },
3965 { "audio-help", 0, QEMU_OPTION_audio_help },
3966 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
3967 #endif
3968
3969 { "net", HAS_ARG, QEMU_OPTION_net},
3970 #ifdef CONFIG_SLIRP
3971 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
3972 #ifndef _WIN32
3973 { "smb", HAS_ARG, QEMU_OPTION_smb },
3974 #endif
3975 { "redir", HAS_ARG, QEMU_OPTION_redir },
3976 #endif
3977
3978 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
3979 { "append", HAS_ARG, QEMU_OPTION_append },
3980 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
3981
3982 { "S", 0, QEMU_OPTION_S },
3983 { "s", 0, QEMU_OPTION_s },
3984 { "p", HAS_ARG, QEMU_OPTION_p },
3985 { "d", HAS_ARG, QEMU_OPTION_d },
3986 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
3987 { "L", HAS_ARG, QEMU_OPTION_L },
3988 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
3989 #ifdef USE_KQEMU
3990 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
3991 #endif
3992 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
3993 { "g", 1, QEMU_OPTION_g },
3994 #endif
3995 { "localtime", 0, QEMU_OPTION_localtime },
3996 { "std-vga", 0, QEMU_OPTION_std_vga },
3997 { "monitor", 1, QEMU_OPTION_monitor },
3998 { "serial", 1, QEMU_OPTION_serial },
3999 { "parallel", 1, QEMU_OPTION_parallel },
4000 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4001 { "full-screen", 0, QEMU_OPTION_full_screen },
4002 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4003 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4004 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4005 { "smp", HAS_ARG, QEMU_OPTION_smp },
4006
4007 /* temporary options */
4008 { "usb", 0, QEMU_OPTION_usb },
4009 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4010 { NULL },
4011 };
4012
4013 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4014
4015 /* this stack is only used during signal handling */
4016 #define SIGNAL_STACK_SIZE 32768
4017
4018 static uint8_t *signal_stack;
4019
4020 #endif
4021
4022 /* password input */
4023
4024 static BlockDriverState *get_bdrv(int index)
4025 {
4026 BlockDriverState *bs;
4027
4028 if (index < 4) {
4029 bs = bs_table[index];
4030 } else if (index < 6) {
4031 bs = fd_table[index - 4];
4032 } else {
4033 bs = NULL;
4034 }
4035 return bs;
4036 }
4037
4038 static void read_passwords(void)
4039 {
4040 BlockDriverState *bs;
4041 int i, j;
4042 char password[256];
4043
4044 for(i = 0; i < 6; i++) {
4045 bs = get_bdrv(i);
4046 if (bs && bdrv_is_encrypted(bs)) {
4047 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4048 for(j = 0; j < 3; j++) {
4049 monitor_readline("Password: ",
4050 1, password, sizeof(password));
4051 if (bdrv_set_key(bs, password) == 0)
4052 break;
4053 term_printf("invalid password\n");
4054 }
4055 }
4056 }
4057 }
4058
4059 /* XXX: currently we cannot use simultaneously different CPUs */
4060 void register_machines(void)
4061 {
4062 #if defined(TARGET_I386)
4063 qemu_register_machine(&pc_machine);
4064 qemu_register_machine(&isapc_machine);
4065 #elif defined(TARGET_PPC)
4066 qemu_register_machine(&heathrow_machine);
4067 qemu_register_machine(&core99_machine);
4068 qemu_register_machine(&prep_machine);
4069 #elif defined(TARGET_MIPS)
4070 qemu_register_machine(&mips_machine);
4071 #elif defined(TARGET_SPARC)
4072 #ifdef TARGET_SPARC64
4073 qemu_register_machine(&sun4u_machine);
4074 #else
4075 qemu_register_machine(&sun4m_machine);
4076 #endif
4077 #elif defined(TARGET_ARM)
4078 qemu_register_machine(&integratorcp_machine);
4079 #else
4080 #error unsupported CPU
4081 #endif
4082 }
4083
4084 #ifdef HAS_AUDIO
4085 static void select_soundhw (const char *optarg)
4086 {
4087 if (*optarg == '?') {
4088 show_valid_cards:
4089 printf ("Valid sound card names (comma separated):\n");
4090 printf ("sb16 Creative Sound Blaster 16\n");
4091 #ifdef CONFIG_ADLIB
4092 #ifdef HAS_YMF262
4093 printf ("adlib Yamaha YMF262 (OPL3)\n");
4094 #else
4095 printf ("adlib Yamaha YM3812 (OPL2)\n");
4096 #endif
4097 #endif
4098 #ifdef CONFIG_GUS
4099 printf ("gus Gravis Ultrasound GF1\n");
4100 #endif
4101 printf ("es1370 ENSONIQ AudioPCI ES1370\n");
4102 exit (*optarg != '?');
4103 }
4104 else {
4105 struct {
4106 char *name;
4107 int *enabledp;
4108 } soundhw_tab[] = {
4109 { "sb16", &sb16_enabled },
4110 #ifdef CONFIG_ADLIB
4111 { "adlib", &adlib_enabled },
4112 #endif
4113 #ifdef CONFIG_GUS
4114 { "gus", &gus_enabled },
4115 #endif
4116 { "es1370", &es1370_enabled },
4117 };
4118 size_t tablen, l, i;
4119 const char *p;
4120 char *e;
4121 int bad_card = 0;
4122
4123 p = optarg;
4124 tablen = sizeof (soundhw_tab) / sizeof (soundhw_tab[0]);
4125
4126 while (*p) {
4127 e = strchr (p, ',');
4128 l = !e ? strlen (p) : (size_t) (e - p);
4129 for (i = 0; i < tablen; ++i) {
4130 if (!strncmp (soundhw_tab[i].name, p, l)) {
4131 audio_enabled = 1;
4132 *soundhw_tab[i].enabledp = 1;
4133 break;
4134 }
4135 }
4136 if (i == tablen) {
4137 if (l > 80) {
4138 fprintf (stderr,
4139 "Unknown sound card name (too big to show)\n");
4140 }
4141 else {
4142 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4143 (int) l, p);
4144 }
4145 bad_card = 1;
4146 }
4147 p += l + (e != NULL);
4148 }
4149
4150 if (bad_card)
4151 goto show_valid_cards;
4152 }
4153 }
4154 #endif
4155
4156 #define MAX_NET_CLIENTS 32
4157
4158 int main(int argc, char **argv)
4159 {
4160 #ifdef CONFIG_GDBSTUB
4161 int use_gdbstub, gdbstub_port;
4162 #endif
4163 int i, cdrom_index;
4164 int snapshot, linux_boot;
4165 const char *initrd_filename;
4166 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4167 const char *kernel_filename, *kernel_cmdline;
4168 DisplayState *ds = &display_state;
4169 int cyls, heads, secs, translation;
4170 int start_emulation = 1;
4171 char net_clients[MAX_NET_CLIENTS][256];
4172 int nb_net_clients;
4173 int optind;
4174 const char *r, *optarg;
4175 CharDriverState *monitor_hd;
4176 char monitor_device[128];
4177 char serial_devices[MAX_SERIAL_PORTS][128];
4178 int serial_device_index;
4179 char parallel_devices[MAX_PARALLEL_PORTS][128];
4180 int parallel_device_index;
4181 const char *loadvm = NULL;
4182 QEMUMachine *machine;
4183 char usb_devices[MAX_VM_USB_PORTS][128];
4184 int usb_devices_index;
4185
4186 LIST_INIT (&vm_change_state_head);
4187 #if !defined(CONFIG_SOFTMMU)
4188 /* we never want that malloc() uses mmap() */
4189 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4190 #endif
4191 register_machines();
4192 machine = first_machine;
4193 initrd_filename = NULL;
4194 for(i = 0; i < MAX_FD; i++)
4195 fd_filename[i] = NULL;
4196 for(i = 0; i < MAX_DISKS; i++)
4197 hd_filename[i] = NULL;
4198 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
4199 vga_ram_size = VGA_RAM_SIZE;
4200 bios_size = BIOS_SIZE;
4201 #ifdef CONFIG_GDBSTUB
4202 use_gdbstub = 0;
4203 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4204 #endif
4205 snapshot = 0;
4206 nographic = 0;
4207 kernel_filename = NULL;
4208 kernel_cmdline = "";
4209 #ifdef TARGET_PPC
4210 cdrom_index = 1;
4211 #else
4212 cdrom_index = 2;
4213 #endif
4214 cyls = heads = secs = 0;
4215 translation = BIOS_ATA_TRANSLATION_AUTO;
4216 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
4217
4218 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
4219 for(i = 1; i < MAX_SERIAL_PORTS; i++)
4220 serial_devices[i][0] = '\0';
4221 serial_device_index = 0;
4222
4223 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
4224 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4225 parallel_devices[i][0] = '\0';
4226 parallel_device_index = 0;
4227
4228 usb_devices_index = 0;
4229
4230 nb_net_clients = 0;
4231
4232 nb_nics = 0;
4233 /* default mac address of the first network interface */
4234
4235 optind = 1;
4236 for(;;) {
4237 if (optind >= argc)
4238 break;
4239 r = argv[optind];
4240 if (r[0] != '-') {
4241 hd_filename[0] = argv[optind++];
4242 } else {
4243 const QEMUOption *popt;
4244
4245 optind++;
4246 popt = qemu_options;
4247 for(;;) {
4248 if (!popt->name) {
4249 fprintf(stderr, "%s: invalid option -- '%s'\n",
4250 argv[0], r);
4251 exit(1);
4252 }
4253 if (!strcmp(popt->name, r + 1))
4254 break;
4255 popt++;
4256 }
4257 if (popt->flags & HAS_ARG) {
4258 if (optind >= argc) {
4259 fprintf(stderr, "%s: option '%s' requires an argument\n",
4260 argv[0], r);
4261 exit(1);
4262 }
4263 optarg = argv[optind++];
4264 } else {
4265 optarg = NULL;
4266 }
4267
4268 switch(popt->index) {
4269 case QEMU_OPTION_M:
4270 machine = find_machine(optarg);
4271 if (!machine) {
4272 QEMUMachine *m;
4273 printf("Supported machines are:\n");
4274 for(m = first_machine; m != NULL; m = m->next) {
4275 printf("%-10s %s%s\n",
4276 m->name, m->desc,
4277 m == first_machine ? " (default)" : "");
4278 }
4279 exit(1);
4280 }
4281 break;
4282 case QEMU_OPTION_initrd:
4283 initrd_filename = optarg;
4284 break;
4285 case QEMU_OPTION_hda:
4286 case QEMU_OPTION_hdb:
4287 case QEMU_OPTION_hdc:
4288 case QEMU_OPTION_hdd:
4289 {
4290 int hd_index;
4291 hd_index = popt->index - QEMU_OPTION_hda;
4292 hd_filename[hd_index] = optarg;
4293 if (hd_index == cdrom_index)
4294 cdrom_index = -1;
4295 }
4296 break;
4297 case QEMU_OPTION_snapshot:
4298 snapshot = 1;
4299 break;
4300 case QEMU_OPTION_hdachs:
4301 {
4302 const char *p;
4303 p = optarg;
4304 cyls = strtol(p, (char **)&p, 0);
4305 if (cyls < 1 || cyls > 16383)
4306 goto chs_fail;
4307 if (*p != ',')
4308 goto chs_fail;
4309 p++;
4310 heads = strtol(p, (char **)&p, 0);
4311 if (heads < 1 || heads > 16)
4312 goto chs_fail;
4313 if (*p != ',')
4314 goto chs_fail;
4315 p++;
4316 secs = strtol(p, (char **)&p, 0);
4317 if (secs < 1 || secs > 63)
4318 goto chs_fail;
4319 if (*p == ',') {
4320 p++;
4321 if (!strcmp(p, "none"))
4322 translation = BIOS_ATA_TRANSLATION_NONE;
4323 else if (!strcmp(p, "lba"))
4324 translation = BIOS_ATA_TRANSLATION_LBA;
4325 else if (!strcmp(p, "auto"))
4326 translation = BIOS_ATA_TRANSLATION_AUTO;
4327 else
4328 goto chs_fail;
4329 } else if (*p != '\0') {
4330 chs_fail:
4331 fprintf(stderr, "qemu: invalid physical CHS format\n");
4332 exit(1);
4333 }
4334 }
4335 break;
4336 case QEMU_OPTION_nographic:
4337 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
4338 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
4339 nographic = 1;
4340 break;
4341 case QEMU_OPTION_kernel:
4342 kernel_filename = optarg;
4343 break;
4344 case QEMU_OPTION_append:
4345 kernel_cmdline = optarg;
4346 break;
4347 case QEMU_OPTION_cdrom:
4348 if (cdrom_index >= 0) {
4349 hd_filename[cdrom_index] = optarg;
4350 }
4351 break;
4352 case QEMU_OPTION_boot:
4353 boot_device = optarg[0];
4354 if (boot_device != 'a' &&
4355 #ifdef TARGET_SPARC
4356 // Network boot
4357 boot_device != 'n' &&
4358 #endif
4359 boot_device != 'c' && boot_device != 'd') {
4360 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4361 exit(1);
4362 }
4363 break;
4364 case QEMU_OPTION_fda:
4365 fd_filename[0] = optarg;
4366 break;
4367 case QEMU_OPTION_fdb:
4368 fd_filename[1] = optarg;
4369 break;
4370 case QEMU_OPTION_no_code_copy:
4371 code_copy_enabled = 0;
4372 break;
4373 case QEMU_OPTION_net:
4374 if (nb_net_clients >= MAX_NET_CLIENTS) {
4375 fprintf(stderr, "qemu: too many network clients\n");
4376 exit(1);
4377 }
4378 pstrcpy(net_clients[nb_net_clients],
4379 sizeof(net_clients[0]),
4380 optarg);
4381 nb_net_clients++;
4382 break;
4383 #ifdef CONFIG_SLIRP
4384 case QEMU_OPTION_tftp:
4385 tftp_prefix = optarg;
4386 break;
4387 #ifndef _WIN32
4388 case QEMU_OPTION_smb:
4389 net_slirp_smb(optarg);
4390 break;
4391 #endif
4392 case QEMU_OPTION_redir:
4393 net_slirp_redir(optarg);
4394 break;
4395 #endif
4396 #ifdef HAS_AUDIO
4397 case QEMU_OPTION_enable_audio:
4398 audio_enabled = 1;
4399 sb16_enabled = 1;
4400 adlib_enabled = 1;
4401 gus_enabled = 1;
4402 es1370_enabled = 1;
4403 break;
4404 case QEMU_OPTION_audio_help:
4405 AUD_help ();
4406 exit (0);
4407 break;
4408 case QEMU_OPTION_soundhw:
4409 select_soundhw (optarg);
4410 break;
4411 #endif
4412 case QEMU_OPTION_h:
4413 help();
4414 break;
4415 case QEMU_OPTION_m:
4416 ram_size = atoi(optarg) * 1024 * 1024;
4417 if (ram_size <= 0)
4418 help();
4419 if (ram_size > PHYS_RAM_MAX_SIZE) {
4420 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4421 PHYS_RAM_MAX_SIZE / (1024 * 1024));
4422 exit(1);
4423 }
4424 break;
4425 case QEMU_OPTION_d:
4426 {
4427 int mask;
4428 CPULogItem *item;
4429
4430 mask = cpu_str_to_log_mask(optarg);
4431 if (!mask) {
4432 printf("Log items (comma separated):\n");
4433 for(item = cpu_log_items; item->mask != 0; item++) {
4434 printf("%-10s %s\n", item->name, item->help);
4435 }
4436 exit(1);
4437 }
4438 cpu_set_log(mask);
4439 }
4440 break;
4441 #ifdef CONFIG_GDBSTUB
4442 case QEMU_OPTION_s:
4443 use_gdbstub = 1;
4444 break;
4445 case QEMU_OPTION_p:
4446 gdbstub_port = atoi(optarg);
4447 break;
4448 #endif
4449 case QEMU_OPTION_L:
4450 bios_dir = optarg;
4451 break;
4452 case QEMU_OPTION_S:
4453 start_emulation = 0;
4454 break;
4455 case QEMU_OPTION_k:
4456 keyboard_layout = optarg;
4457 break;
4458 case QEMU_OPTION_localtime:
4459 rtc_utc = 0;
4460 break;
4461 case QEMU_OPTION_cirrusvga:
4462 cirrus_vga_enabled = 1;
4463 break;
4464 case QEMU_OPTION_std_vga:
4465 cirrus_vga_enabled = 0;
4466 break;
4467 case QEMU_OPTION_g:
4468 {
4469 const char *p;
4470 int w, h, depth;
4471 p = optarg;
4472 w = strtol(p, (char **)&p, 10);
4473 if (w <= 0) {
4474 graphic_error:
4475 fprintf(stderr, "qemu: invalid resolution or depth\n");
4476 exit(1);
4477 }
4478 if (*p != 'x')
4479 goto graphic_error;
4480 p++;
4481 h = strtol(p, (char **)&p, 10);
4482 if (h <= 0)
4483 goto graphic_error;
4484 if (*p == 'x') {
4485 p++;
4486 depth = strtol(p, (char **)&p, 10);
4487 if (depth != 8 && depth != 15 && depth != 16 &&
4488 depth != 24 && depth != 32)
4489 goto graphic_error;
4490 } else if (*p == '\0') {
4491 depth = graphic_depth;
4492 } else {
4493 goto graphic_error;
4494 }
4495
4496 graphic_width = w;
4497 graphic_height = h;
4498 graphic_depth = depth;
4499 }
4500 break;
4501 case QEMU_OPTION_monitor:
4502 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
4503 break;
4504 case QEMU_OPTION_serial:
4505 if (serial_device_index >= MAX_SERIAL_PORTS) {
4506 fprintf(stderr, "qemu: too many serial ports\n");
4507 exit(1);
4508 }
4509 pstrcpy(serial_devices[serial_device_index],
4510 sizeof(serial_devices[0]), optarg);
4511 serial_device_index++;
4512 break;
4513 case QEMU_OPTION_parallel:
4514 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4515 fprintf(stderr, "qemu: too many parallel ports\n");
4516 exit(1);
4517 }
4518 pstrcpy(parallel_devices[parallel_device_index],
4519 sizeof(parallel_devices[0]), optarg);
4520 parallel_device_index++;
4521 break;
4522 case QEMU_OPTION_loadvm:
4523 loadvm = optarg;
4524 break;
4525 case QEMU_OPTION_full_screen:
4526 full_screen = 1;
4527 break;
4528 case QEMU_OPTION_pidfile:
4529 create_pidfile(optarg);
4530 break;
4531 #ifdef TARGET_I386
4532 case QEMU_OPTION_win2k_hack:
4533 win2k_install_hack = 1;
4534 break;
4535 #endif
4536 #ifdef USE_KQEMU
4537 case QEMU_OPTION_no_kqemu:
4538 kqemu_allowed = 0;
4539 break;
4540 #endif
4541 case QEMU_OPTION_usb:
4542 usb_enabled = 1;
4543 break;
4544 case QEMU_OPTION_usbdevice:
4545 usb_enabled = 1;
4546 if (usb_devices_index >= MAX_VM_USB_PORTS) {
4547 fprintf(stderr, "Too many USB devices\n");
4548 exit(1);
4549 }
4550 pstrcpy(usb_devices[usb_devices_index],
4551 sizeof(usb_devices[usb_devices_index]),
4552 optarg);
4553 usb_devices_index++;
4554 break;
4555 case QEMU_OPTION_smp:
4556 smp_cpus = atoi(optarg);
4557 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
4558 fprintf(stderr, "Invalid number of CPUs\n");
4559 exit(1);
4560 }
4561 break;
4562 }
4563 }
4564 }
4565
4566 linux_boot = (kernel_filename != NULL);
4567
4568 if (!linux_boot &&
4569 hd_filename[0] == '\0' &&
4570 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
4571 fd_filename[0] == '\0')
4572 help();
4573
4574 /* boot to cd by default if no hard disk */
4575 if (hd_filename[0] == '\0' && boot_device == 'c') {
4576 if (fd_filename[0] != '\0')
4577 boot_device = 'a';
4578 else
4579 boot_device = 'd';
4580 }
4581
4582 #if !defined(CONFIG_SOFTMMU)
4583 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
4584 {
4585 static uint8_t stdout_buf[4096];
4586 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
4587 }
4588 #else
4589 setvbuf(stdout, NULL, _IOLBF, 0);
4590 #endif
4591
4592 /* init network clients */
4593 if (nb_net_clients == 0) {
4594 /* if no clients, we use a default config */
4595 pstrcpy(net_clients[0], sizeof(net_clients[0]),
4596 "nic");
4597 pstrcpy(net_clients[1], sizeof(net_clients[0]),
4598 "user");
4599 nb_net_clients = 2;
4600 }
4601
4602 for(i = 0;i < nb_net_clients; i++) {
4603 if (net_client_init(net_clients[i]) < 0)
4604 exit(1);
4605 }
4606
4607 /* init the memory */
4608 phys_ram_size = ram_size + vga_ram_size + bios_size;
4609
4610 #ifdef CONFIG_SOFTMMU
4611 phys_ram_base = qemu_vmalloc(phys_ram_size);
4612 if (!phys_ram_base) {
4613 fprintf(stderr, "Could not allocate physical memory\n");
4614 exit(1);
4615 }
4616 #else
4617 /* as we must map the same page at several addresses, we must use
4618 a fd */
4619 {
4620 const char *tmpdir;
4621
4622 tmpdir = getenv("QEMU_TMPDIR");
4623 if (!tmpdir)
4624 tmpdir = "/tmp";
4625 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4626 if (mkstemp(phys_ram_file) < 0) {
4627 fprintf(stderr, "Could not create temporary memory file '%s'\n",
4628 phys_ram_file);
4629 exit(1);
4630 }
4631 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4632 if (phys_ram_fd < 0) {
4633 fprintf(stderr, "Could not open temporary memory file '%s'\n",
4634 phys_ram_file);
4635 exit(1);
4636 }
4637 ftruncate(phys_ram_fd, phys_ram_size);
4638 unlink(phys_ram_file);
4639 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
4640 phys_ram_size,
4641 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
4642 phys_ram_fd, 0);
4643 if (phys_ram_base == MAP_FAILED) {
4644 fprintf(stderr, "Could not map physical memory\n");
4645 exit(1);
4646 }
4647 }
4648 #endif
4649
4650 /* we always create the cdrom drive, even if no disk is there */
4651 bdrv_init();
4652 if (cdrom_index >= 0) {
4653 bs_table[cdrom_index] = bdrv_new("cdrom");
4654 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
4655 }
4656
4657 /* open the virtual block devices */
4658 for(i = 0; i < MAX_DISKS; i++) {
4659 if (hd_filename[i]) {
4660 if (!bs_table[i]) {
4661 char buf[64];
4662 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
4663 bs_table[i] = bdrv_new(buf);
4664 }
4665 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
4666 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
4667 hd_filename[i]);
4668 exit(1);
4669 }
4670 if (i == 0 && cyls != 0) {
4671 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
4672 bdrv_set_translation_hint(bs_table[i], translation);
4673 }
4674 }
4675 }
4676
4677 /* we always create at least one floppy disk */
4678 fd_table[0] = bdrv_new("fda");
4679 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
4680
4681 for(i = 0; i < MAX_FD; i++) {
4682 if (fd_filename[i]) {
4683 if (!fd_table[i]) {
4684 char buf[64];
4685 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
4686 fd_table[i] = bdrv_new(buf);
4687 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
4688 }
4689 if (fd_filename[i] != '\0') {
4690 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
4691 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
4692 fd_filename[i]);
4693 exit(1);
4694 }
4695 }
4696 }
4697 }
4698
4699 /* init USB devices */
4700 if (usb_enabled) {
4701 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
4702 for(i = 0; i < usb_devices_index; i++) {
4703 if (usb_device_add(usb_devices[i]) < 0) {
4704 fprintf(stderr, "Warning: could not add USB device %s\n",
4705 usb_devices[i]);
4706 }
4707 }
4708 }
4709
4710 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
4711 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
4712
4713 init_ioports();
4714 cpu_calibrate_ticks();
4715
4716 /* terminal init */
4717 if (nographic) {
4718 dumb_display_init(ds);
4719 } else {
4720 #if defined(CONFIG_SDL)
4721 sdl_display_init(ds, full_screen);
4722 #elif defined(CONFIG_COCOA)
4723 cocoa_display_init(ds, full_screen);
4724 #else
4725 dumb_display_init(ds);
4726 #endif
4727 }
4728
4729 vga_console = graphic_console_init(ds);
4730
4731 monitor_hd = qemu_chr_open(monitor_device);
4732 if (!monitor_hd) {
4733 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
4734 exit(1);
4735 }
4736 monitor_init(monitor_hd, !nographic);
4737
4738 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
4739 if (serial_devices[i][0] != '\0') {
4740 serial_hds[i] = qemu_chr_open(serial_devices[i]);
4741 if (!serial_hds[i]) {
4742 fprintf(stderr, "qemu: could not open serial device '%s'\n",
4743 serial_devices[i]);
4744 exit(1);
4745 }
4746 if (!strcmp(serial_devices[i], "vc"))
4747 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
4748 }
4749 }
4750
4751 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
4752 if (parallel_devices[i][0] != '\0') {
4753 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
4754 if (!parallel_hds[i]) {
4755 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
4756 parallel_devices[i]);
4757 exit(1);
4758 }
4759 if (!strcmp(parallel_devices[i], "vc"))
4760 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
4761 }
4762 }
4763
4764 /* setup cpu signal handlers for MMU / self modifying code handling */
4765 #if !defined(CONFIG_SOFTMMU)
4766
4767 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4768 {
4769 stack_t stk;
4770 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
4771 stk.ss_sp = signal_stack;
4772 stk.ss_size = SIGNAL_STACK_SIZE;
4773 stk.ss_flags = 0;
4774
4775 if (sigaltstack(&stk, NULL) < 0) {
4776 perror("sigaltstack");
4777 exit(1);
4778 }
4779 }
4780 #endif
4781 {
4782 struct sigaction act;
4783
4784 sigfillset(&act.sa_mask);
4785 act.sa_flags = SA_SIGINFO;
4786 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4787 act.sa_flags |= SA_ONSTACK;
4788 #endif
4789 act.sa_sigaction = host_segv_handler;
4790 sigaction(SIGSEGV, &act, NULL);
4791 sigaction(SIGBUS, &act, NULL);
4792 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4793 sigaction(SIGFPE, &act, NULL);
4794 #endif
4795 }
4796 #endif
4797
4798 #ifndef _WIN32
4799 {
4800 struct sigaction act;
4801 sigfillset(&act.sa_mask);
4802 act.sa_flags = 0;
4803 act.sa_handler = SIG_IGN;
4804 sigaction(SIGPIPE, &act, NULL);
4805 }
4806 #endif
4807 init_timers();
4808
4809 machine->init(ram_size, vga_ram_size, boot_device,
4810 ds, fd_filename, snapshot,
4811 kernel_filename, kernel_cmdline, initrd_filename);
4812
4813 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
4814 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
4815
4816 #ifdef CONFIG_GDBSTUB
4817 if (use_gdbstub) {
4818 if (gdbserver_start(gdbstub_port) < 0) {
4819 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
4820 gdbstub_port);
4821 exit(1);
4822 } else {
4823 printf("Waiting gdb connection on port %d\n", gdbstub_port);
4824 }
4825 } else
4826 #endif
4827 if (loadvm)
4828 qemu_loadvm(loadvm);
4829
4830 {
4831 /* XXX: simplify init */
4832 read_passwords();
4833 if (start_emulation) {
4834 vm_start();
4835 }
4836 }
4837 main_loop();
4838 quit_timers();
4839 return 0;
4840 }