hardware level IDE CD-ROM emulation - added second IDE interface for up to 4 IDE...
[qemu/qemu_0_9_1_stable.git] / vl.c
blob053f3e90f9ae22b94893c24ac70d1d35886afff3
1 /*
2 * QEMU PC System Emulator
3 *
4 * Copyright (c) 2003 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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <getopt.h>
29 #include <inttypes.h>
30 #include <unistd.h>
31 #include <sys/mman.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <time.h>
35 #include <sys/time.h>
36 #include <malloc.h>
37 #include <termios.h>
38 #include <sys/poll.h>
39 #include <errno.h>
40 #include <sys/wait.h>
42 #include <sys/ioctl.h>
43 #include <sys/socket.h>
44 #include <linux/if.h>
45 #include <linux/if_tun.h>
47 #include "cpu.h"
48 #include "disas.h"
49 #include "thunk.h"
51 #include "vl.h"
53 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
54 #define BIOS_FILENAME "bios.bin"
55 #define VGABIOS_FILENAME "vgabios.bin"
57 //#define DEBUG_UNUSED_IOPORT
59 //#define DEBUG_IRQ_LATENCY
61 /* output Bochs bios info messages */
62 //#define DEBUG_BIOS
64 /* debug IDE devices */
65 //#define DEBUG_IDE
66 //#define DEBUG_IDE_ATAPI
68 /* debug PIC */
69 //#define DEBUG_PIC
71 /* debug NE2000 card */
72 //#define DEBUG_NE2000
74 /* debug PC keyboard */
75 //#define DEBUG_KBD
77 /* debug PC keyboard : only mouse */
78 //#define DEBUG_MOUSE
80 #define PHYS_RAM_BASE 0xac000000
81 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
83 #define KERNEL_LOAD_ADDR 0x00100000
84 #define INITRD_LOAD_ADDR 0x00400000
85 #define KERNEL_PARAMS_ADDR 0x00090000
87 #define GUI_REFRESH_INTERVAL 30
89 #define MAX_DISKS 4
91 /* from plex86 (BSD license) */
92 struct __attribute__ ((packed)) linux_params {
93 // For 0x00..0x3f, see 'struct screen_info' in linux/include/linux/tty.h.
94 // I just padded out the VESA parts, rather than define them.
96 /* 0x000 */ uint8_t orig_x;
97 /* 0x001 */ uint8_t orig_y;
98 /* 0x002 */ uint16_t ext_mem_k;
99 /* 0x004 */ uint16_t orig_video_page;
100 /* 0x006 */ uint8_t orig_video_mode;
101 /* 0x007 */ uint8_t orig_video_cols;
102 /* 0x008 */ uint16_t unused1;
103 /* 0x00a */ uint16_t orig_video_ega_bx;
104 /* 0x00c */ uint16_t unused2;
105 /* 0x00e */ uint8_t orig_video_lines;
106 /* 0x00f */ uint8_t orig_video_isVGA;
107 /* 0x010 */ uint16_t orig_video_points;
108 /* 0x012 */ uint8_t pad0[0x20 - 0x12]; // VESA info.
109 /* 0x020 */ uint16_t cl_magic; // Commandline magic number (0xA33F)
110 /* 0x022 */ uint16_t cl_offset; // Commandline offset. Address of commandline
111 // is calculated as 0x90000 + cl_offset, bu
112 // only if cl_magic == 0xA33F.
113 /* 0x024 */ uint8_t pad1[0x40 - 0x24]; // VESA info.
115 /* 0x040 */ uint8_t apm_bios_info[20]; // struct apm_bios_info
116 /* 0x054 */ uint8_t pad2[0x80 - 0x54];
118 // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.
119 // Might be truncated?
120 /* 0x080 */ uint8_t hd0_info[16]; // hd0-disk-parameter from intvector 0x41
121 /* 0x090 */ uint8_t hd1_info[16]; // hd1-disk-parameter from intvector 0x46
123 // System description table truncated to 16 bytes
124 // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.
125 /* 0x0a0 */ uint16_t sys_description_len;
126 /* 0x0a2 */ uint8_t sys_description_table[14];
127 // [0] machine id
128 // [1] machine submodel id
129 // [2] BIOS revision
130 // [3] bit1: MCA bus
132 /* 0x0b0 */ uint8_t pad3[0x1e0 - 0xb0];
133 /* 0x1e0 */ uint32_t alt_mem_k;
134 /* 0x1e4 */ uint8_t pad4[4];
135 /* 0x1e8 */ uint8_t e820map_entries;
136 /* 0x1e9 */ uint8_t eddbuf_entries; // EDD_NR
137 /* 0x1ea */ uint8_t pad5[0x1f1 - 0x1ea];
138 /* 0x1f1 */ uint8_t setup_sects; // size of setup.S, number of sectors
139 /* 0x1f2 */ uint16_t mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)
140 /* 0x1f4 */ uint16_t sys_size; // size of compressed kernel-part in the
141 // (b)zImage-file (in 16 byte units, rounded up)
142 /* 0x1f6 */ uint16_t swap_dev; // (unused AFAIK)
143 /* 0x1f8 */ uint16_t ramdisk_flags;
144 /* 0x1fa */ uint16_t vga_mode; // (old one)
145 /* 0x1fc */ uint16_t orig_root_dev; // (high=Major, low=minor)
146 /* 0x1fe */ uint8_t pad6[1];
147 /* 0x1ff */ uint8_t aux_device_info;
148 /* 0x200 */ uint16_t jump_setup; // Jump to start of setup code,
149 // aka "reserved" field.
150 /* 0x202 */ uint8_t setup_signature[4]; // Signature for SETUP-header, ="HdrS"
151 /* 0x206 */ uint16_t header_format_version; // Version number of header format;
152 /* 0x208 */ uint8_t setup_S_temp0[8]; // Used by setup.S for communication with
153 // boot loaders, look there.
154 /* 0x210 */ uint8_t loader_type;
155 // 0 for old one.
156 // else 0xTV:
157 // T=0: LILO
158 // T=1: Loadlin
159 // T=2: bootsect-loader
160 // T=3: SYSLINUX
161 // T=4: ETHERBOOT
162 // V=version
163 /* 0x211 */ uint8_t loadflags;
164 // bit0 = 1: kernel is loaded high (bzImage)
165 // bit7 = 1: Heap and pointer (see below) set by boot
166 // loader.
167 /* 0x212 */ uint16_t setup_S_temp1;
168 /* 0x214 */ uint32_t kernel_start;
169 /* 0x218 */ uint32_t initrd_start;
170 /* 0x21c */ uint32_t initrd_size;
171 /* 0x220 */ uint8_t setup_S_temp2[4];
172 /* 0x224 */ uint16_t setup_S_heap_end_pointer;
173 /* 0x226 */ uint8_t pad7[0x2d0 - 0x226];
175 /* 0x2d0 : Int 15, ax=e820 memory map. */
176 // (linux/include/asm-i386/e820.h, 'struct e820entry')
177 #define E820MAX 32
178 #define E820_RAM 1
179 #define E820_RESERVED 2
180 #define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */
181 #define E820_NVS 4
182 struct {
183 uint64_t addr;
184 uint64_t size;
185 uint32_t type;
186 } e820map[E820MAX];
188 /* 0x550 */ uint8_t pad8[0x600 - 0x550];
190 // BIOS Enhanced Disk Drive Services.
191 // (From linux/include/asm-i386/edd.h, 'struct edd_info')
192 // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.
193 /* 0x600 */ uint8_t eddbuf[0x7d4 - 0x600];
195 /* 0x7d4 */ uint8_t pad9[0x800 - 0x7d4];
196 /* 0x800 */ uint8_t commandline[0x800];
198 /* 0x1000 */
199 uint64_t gdt_table[256];
200 uint64_t idt_table[48];
203 #define KERNEL_CS 0x10
204 #define KERNEL_DS 0x18
206 #define MAX_IOPORTS 4096
208 static const char *bios_dir = CONFIG_QEMU_SHAREDIR;
209 char phys_ram_file[1024];
210 CPUX86State *global_env;
211 CPUX86State *cpu_single_env;
212 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
213 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
214 BlockDriverState *bs_table[MAX_DISKS];
215 int vga_ram_size;
216 static DisplayState display_state;
217 int nographic;
218 int term_inited;
219 int64_t ticks_per_sec;
220 int boot_device = 'c';
222 /***********************************************************/
223 /* x86 io ports */
225 uint32_t default_ioport_readb(CPUX86State *env, uint32_t address)
227 #ifdef DEBUG_UNUSED_IOPORT
228 fprintf(stderr, "inb: port=0x%04x\n", address);
229 #endif
230 return 0xff;
233 void default_ioport_writeb(CPUX86State *env, uint32_t address, uint32_t data)
235 #ifdef DEBUG_UNUSED_IOPORT
236 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
237 #endif
240 /* default is to make two byte accesses */
241 uint32_t default_ioport_readw(CPUX86State *env, uint32_t address)
243 uint32_t data;
244 data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](env, address);
245 data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1) << 8;
246 return data;
249 void default_ioport_writew(CPUX86State *env, uint32_t address, uint32_t data)
251 ioport_write_table[0][address & (MAX_IOPORTS - 1)](env, address, data & 0xff);
252 ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1, (data >> 8) & 0xff);
255 uint32_t default_ioport_readl(CPUX86State *env, uint32_t address)
257 #ifdef DEBUG_UNUSED_IOPORT
258 fprintf(stderr, "inl: port=0x%04x\n", address);
259 #endif
260 return 0xffffffff;
263 void default_ioport_writel(CPUX86State *env, uint32_t address, uint32_t data)
265 #ifdef DEBUG_UNUSED_IOPORT
266 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
267 #endif
270 void init_ioports(void)
272 int i;
274 for(i = 0; i < MAX_IOPORTS; i++) {
275 ioport_read_table[0][i] = default_ioport_readb;
276 ioport_write_table[0][i] = default_ioport_writeb;
277 ioport_read_table[1][i] = default_ioport_readw;
278 ioport_write_table[1][i] = default_ioport_writew;
279 ioport_read_table[2][i] = default_ioport_readl;
280 ioport_write_table[2][i] = default_ioport_writel;
284 /* size is the word size in byte */
285 int register_ioport_read(int start, int length, IOPortReadFunc *func, int size)
287 int i, bsize;
289 if (size == 1)
290 bsize = 0;
291 else if (size == 2)
292 bsize = 1;
293 else if (size == 4)
294 bsize = 2;
295 else
296 return -1;
297 for(i = start; i < start + length; i += size)
298 ioport_read_table[bsize][i] = func;
299 return 0;
302 /* size is the word size in byte */
303 int register_ioport_write(int start, int length, IOPortWriteFunc *func, int size)
305 int i, bsize;
307 if (size == 1)
308 bsize = 0;
309 else if (size == 2)
310 bsize = 1;
311 else if (size == 4)
312 bsize = 2;
313 else
314 return -1;
315 for(i = start; i < start + length; i += size)
316 ioport_write_table[bsize][i] = func;
317 return 0;
320 void pstrcpy(char *buf, int buf_size, const char *str)
322 int c;
323 char *q = buf;
325 if (buf_size <= 0)
326 return;
328 for(;;) {
329 c = *str++;
330 if (c == 0 || q >= buf + buf_size - 1)
331 break;
332 *q++ = c;
334 *q = '\0';
337 /* strcat and truncate. */
338 char *pstrcat(char *buf, int buf_size, const char *s)
340 int len;
341 len = strlen(buf);
342 if (len < buf_size)
343 pstrcpy(buf + len, buf_size - len, s);
344 return buf;
347 int load_kernel(const char *filename, uint8_t *addr)
349 int fd, size, setup_sects;
350 uint8_t bootsect[512];
352 fd = open(filename, O_RDONLY);
353 if (fd < 0)
354 return -1;
355 if (read(fd, bootsect, 512) != 512)
356 goto fail;
357 setup_sects = bootsect[0x1F1];
358 if (!setup_sects)
359 setup_sects = 4;
360 /* skip 16 bit setup code */
361 lseek(fd, (setup_sects + 1) * 512, SEEK_SET);
362 size = read(fd, addr, 16 * 1024 * 1024);
363 if (size < 0)
364 goto fail;
365 close(fd);
366 return size;
367 fail:
368 close(fd);
369 return -1;
372 /* return the size or -1 if error */
373 int load_image(const char *filename, uint8_t *addr)
375 int fd, size;
376 fd = open(filename, O_RDONLY);
377 if (fd < 0)
378 return -1;
379 size = lseek(fd, 0, SEEK_END);
380 lseek(fd, 0, SEEK_SET);
381 if (read(fd, addr, size) != size) {
382 close(fd);
383 return -1;
385 close(fd);
386 return size;
389 void cpu_x86_outb(CPUX86State *env, int addr, int val)
391 ioport_write_table[0][addr & (MAX_IOPORTS - 1)](env, addr, val);
394 void cpu_x86_outw(CPUX86State *env, int addr, int val)
396 ioport_write_table[1][addr & (MAX_IOPORTS - 1)](env, addr, val);
399 void cpu_x86_outl(CPUX86State *env, int addr, int val)
401 ioport_write_table[2][addr & (MAX_IOPORTS - 1)](env, addr, val);
404 int cpu_x86_inb(CPUX86State *env, int addr)
406 return ioport_read_table[0][addr & (MAX_IOPORTS - 1)](env, addr);
409 int cpu_x86_inw(CPUX86State *env, int addr)
411 return ioport_read_table[1][addr & (MAX_IOPORTS - 1)](env, addr);
414 int cpu_x86_inl(CPUX86State *env, int addr)
416 return ioport_read_table[2][addr & (MAX_IOPORTS - 1)](env, addr);
419 /***********************************************************/
420 void ioport80_write(CPUX86State *env, uint32_t addr, uint32_t data)
424 void hw_error(const char *fmt, ...)
426 va_list ap;
428 va_start(ap, fmt);
429 fprintf(stderr, "qemu: hardware error: ");
430 vfprintf(stderr, fmt, ap);
431 fprintf(stderr, "\n");
432 #ifdef TARGET_I386
433 cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
434 #endif
435 va_end(ap);
436 abort();
439 /***********************************************************/
440 /* cmos emulation */
442 #define RTC_SECONDS 0
443 #define RTC_SECONDS_ALARM 1
444 #define RTC_MINUTES 2
445 #define RTC_MINUTES_ALARM 3
446 #define RTC_HOURS 4
447 #define RTC_HOURS_ALARM 5
448 #define RTC_ALARM_DONT_CARE 0xC0
450 #define RTC_DAY_OF_WEEK 6
451 #define RTC_DAY_OF_MONTH 7
452 #define RTC_MONTH 8
453 #define RTC_YEAR 9
455 #define RTC_REG_A 10
456 #define RTC_REG_B 11
457 #define RTC_REG_C 12
458 #define RTC_REG_D 13
460 /* PC cmos mappings */
461 #define REG_EQUIPMENT_BYTE 0x14
463 uint8_t cmos_data[128];
464 uint8_t cmos_index;
466 void cmos_ioport_write(CPUX86State *env, uint32_t addr, uint32_t data)
468 if (addr == 0x70) {
469 cmos_index = data & 0x7f;
473 uint32_t cmos_ioport_read(CPUX86State *env, uint32_t addr)
475 int ret;
477 if (addr == 0x70) {
478 return 0xff;
479 } else {
480 /* toggle update-in-progress bit for Linux (same hack as
481 plex86) */
482 ret = cmos_data[cmos_index];
483 if (cmos_index == RTC_REG_A)
484 cmos_data[RTC_REG_A] ^= 0x80;
485 else if (cmos_index == RTC_REG_C)
486 cmos_data[RTC_REG_C] = 0x00;
487 return ret;
492 static inline int to_bcd(int a)
494 return ((a / 10) << 4) | (a % 10);
497 void cmos_init(void)
499 struct tm *tm;
500 time_t ti;
501 int val;
503 ti = time(NULL);
504 tm = gmtime(&ti);
505 cmos_data[RTC_SECONDS] = to_bcd(tm->tm_sec);
506 cmos_data[RTC_MINUTES] = to_bcd(tm->tm_min);
507 cmos_data[RTC_HOURS] = to_bcd(tm->tm_hour);
508 cmos_data[RTC_DAY_OF_WEEK] = to_bcd(tm->tm_wday);
509 cmos_data[RTC_DAY_OF_MONTH] = to_bcd(tm->tm_mday);
510 cmos_data[RTC_MONTH] = to_bcd(tm->tm_mon + 1);
511 cmos_data[RTC_YEAR] = to_bcd(tm->tm_year % 100);
513 cmos_data[RTC_REG_A] = 0x26;
514 cmos_data[RTC_REG_B] = 0x02;
515 cmos_data[RTC_REG_C] = 0x00;
516 cmos_data[RTC_REG_D] = 0x80;
518 /* various important CMOS locations needed by PC/Bochs bios */
520 cmos_data[REG_EQUIPMENT_BYTE] = 0x02; /* FPU is there */
521 cmos_data[REG_EQUIPMENT_BYTE] |= 0x04; /* PS/2 mouse installed */
523 /* memory size */
524 val = (phys_ram_size / 1024) - 1024;
525 if (val > 65535)
526 val = 65535;
527 cmos_data[0x17] = val;
528 cmos_data[0x18] = val >> 8;
529 cmos_data[0x30] = val;
530 cmos_data[0x31] = val >> 8;
532 val = (phys_ram_size / 65536) - ((16 * 1024 * 1024) / 65536);
533 if (val > 65535)
534 val = 65535;
535 cmos_data[0x34] = val;
536 cmos_data[0x35] = val >> 8;
538 switch(boot_device) {
539 case 'a':
540 cmos_data[0x3d] = 0x01; /* floppy boot */
541 break;
542 default:
543 case 'c':
544 cmos_data[0x3d] = 0x02; /* hard drive boot */
545 break;
546 case 'd':
547 cmos_data[0x3d] = 0x03; /* CD-ROM boot */
548 break;
551 register_ioport_write(0x70, 2, cmos_ioport_write, 1);
552 register_ioport_read(0x70, 2, cmos_ioport_read, 1);
555 /***********************************************************/
556 /* 8259 pic emulation */
558 typedef struct PicState {
559 uint8_t last_irr; /* edge detection */
560 uint8_t irr; /* interrupt request register */
561 uint8_t imr; /* interrupt mask register */
562 uint8_t isr; /* interrupt service register */
563 uint8_t priority_add; /* used to compute irq priority */
564 uint8_t irq_base;
565 uint8_t read_reg_select;
566 uint8_t special_mask;
567 uint8_t init_state;
568 uint8_t auto_eoi;
569 uint8_t rotate_on_autoeoi;
570 uint8_t init4; /* true if 4 byte init */
571 } PicState;
573 /* 0 is master pic, 1 is slave pic */
574 PicState pics[2];
575 int pic_irq_requested;
577 /* set irq level. If an edge is detected, then the IRR is set to 1 */
578 static inline void pic_set_irq1(PicState *s, int irq, int level)
580 int mask;
581 mask = 1 << irq;
582 if (level) {
583 if ((s->last_irr & mask) == 0)
584 s->irr |= mask;
585 s->last_irr |= mask;
586 } else {
587 s->last_irr &= ~mask;
591 static inline int get_priority(PicState *s, int mask)
593 int priority;
594 if (mask == 0)
595 return -1;
596 priority = 7;
597 while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)
598 priority--;
599 return priority;
602 /* return the pic wanted interrupt. return -1 if none */
603 static int pic_get_irq(PicState *s)
605 int mask, cur_priority, priority;
607 mask = s->irr & ~s->imr;
608 priority = get_priority(s, mask);
609 if (priority < 0)
610 return -1;
611 /* compute current priority */
612 cur_priority = get_priority(s, s->isr);
613 if (priority > cur_priority) {
614 /* higher priority found: an irq should be generated */
615 return priority;
616 } else {
617 return -1;
621 /* raise irq to CPU if necessary. must be called every time the active
622 irq may change */
623 static void pic_update_irq(void)
625 int irq2, irq;
627 /* first look at slave pic */
628 irq2 = pic_get_irq(&pics[1]);
629 if (irq2 >= 0) {
630 /* if irq request by slave pic, signal master PIC */
631 pic_set_irq1(&pics[0], 2, 1);
632 pic_set_irq1(&pics[0], 2, 0);
634 /* look at requested irq */
635 irq = pic_get_irq(&pics[0]);
636 if (irq >= 0) {
637 if (irq == 2) {
638 /* from slave pic */
639 pic_irq_requested = 8 + irq2;
640 } else {
641 /* from master pic */
642 pic_irq_requested = irq;
644 cpu_x86_interrupt(global_env, CPU_INTERRUPT_HARD);
648 #ifdef DEBUG_IRQ_LATENCY
649 int64_t irq_time[16];
650 int64_t cpu_get_ticks(void);
651 #endif
652 #if defined(DEBUG_PIC)
653 int irq_level[16];
654 #endif
656 void pic_set_irq(int irq, int level)
658 #if defined(DEBUG_PIC)
659 if (level != irq_level[irq]) {
660 printf("pic_set_irq: irq=%d level=%d\n", irq, level);
661 irq_level[irq] = level;
663 #endif
664 #ifdef DEBUG_IRQ_LATENCY
665 if (level) {
666 irq_time[irq] = cpu_get_ticks();
668 #endif
669 pic_set_irq1(&pics[irq >> 3], irq & 7, level);
670 pic_update_irq();
673 int cpu_x86_get_pic_interrupt(CPUX86State *env)
675 int irq, irq2, intno;
677 /* signal the pic that the irq was acked by the CPU */
678 irq = pic_irq_requested;
679 #ifdef DEBUG_IRQ_LATENCY
680 printf("IRQ%d latency=%0.3fus\n",
681 irq,
682 (double)(cpu_get_ticks() - irq_time[irq]) * 1000000.0 / ticks_per_sec);
683 #endif
684 #ifdef DEBUG_PIC
685 printf("pic_interrupt: irq=%d\n", irq);
686 #endif
688 if (irq >= 8) {
689 irq2 = irq & 7;
690 pics[1].isr |= (1 << irq2);
691 pics[1].irr &= ~(1 << irq2);
692 irq = 2;
693 intno = pics[1].irq_base + irq2;
694 } else {
695 intno = pics[0].irq_base + irq;
697 pics[0].isr |= (1 << irq);
698 pics[0].irr &= ~(1 << irq);
699 return intno;
702 void pic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
704 PicState *s;
705 int priority;
707 #ifdef DEBUG_PIC
708 printf("pic_write: addr=0x%02x val=0x%02x\n", addr, val);
709 #endif
710 s = &pics[addr >> 7];
711 addr &= 1;
712 if (addr == 0) {
713 if (val & 0x10) {
714 /* init */
715 memset(s, 0, sizeof(PicState));
716 s->init_state = 1;
717 s->init4 = val & 1;
718 if (val & 0x02)
719 hw_error("single mode not supported");
720 if (val & 0x08)
721 hw_error("level sensitive irq not supported");
722 } else if (val & 0x08) {
723 if (val & 0x02)
724 s->read_reg_select = val & 1;
725 if (val & 0x40)
726 s->special_mask = (val >> 5) & 1;
727 } else {
728 switch(val) {
729 case 0x00:
730 case 0x80:
731 s->rotate_on_autoeoi = val >> 7;
732 break;
733 case 0x20: /* end of interrupt */
734 case 0xa0:
735 priority = get_priority(s, s->isr);
736 if (priority >= 0) {
737 s->isr &= ~(1 << ((priority + s->priority_add) & 7));
739 if (val == 0xa0)
740 s->priority_add = (s->priority_add + 1) & 7;
741 pic_update_irq();
742 break;
743 case 0x60 ... 0x67:
744 priority = val & 7;
745 s->isr &= ~(1 << priority);
746 pic_update_irq();
747 break;
748 case 0xc0 ... 0xc7:
749 s->priority_add = (val + 1) & 7;
750 pic_update_irq();
751 break;
752 case 0xe0 ... 0xe7:
753 priority = val & 7;
754 s->isr &= ~(1 << priority);
755 s->priority_add = (priority + 1) & 7;
756 pic_update_irq();
757 break;
760 } else {
761 switch(s->init_state) {
762 case 0:
763 /* normal mode */
764 s->imr = val;
765 pic_update_irq();
766 break;
767 case 1:
768 s->irq_base = val & 0xf8;
769 s->init_state = 2;
770 break;
771 case 2:
772 if (s->init4) {
773 s->init_state = 3;
774 } else {
775 s->init_state = 0;
777 break;
778 case 3:
779 s->auto_eoi = (val >> 1) & 1;
780 s->init_state = 0;
781 break;
786 uint32_t pic_ioport_read(CPUX86State *env, uint32_t addr1)
788 PicState *s;
789 unsigned int addr;
790 int ret;
792 addr = addr1;
793 s = &pics[addr >> 7];
794 addr &= 1;
795 if (addr == 0) {
796 if (s->read_reg_select)
797 ret = s->isr;
798 else
799 ret = s->irr;
800 } else {
801 ret = s->imr;
803 #ifdef DEBUG_PIC
804 printf("pic_read: addr=0x%02x val=0x%02x\n", addr1, ret);
805 #endif
806 return ret;
809 void pic_init(void)
811 register_ioport_write(0x20, 2, pic_ioport_write, 1);
812 register_ioport_read(0x20, 2, pic_ioport_read, 1);
813 register_ioport_write(0xa0, 2, pic_ioport_write, 1);
814 register_ioport_read(0xa0, 2, pic_ioport_read, 1);
817 /***********************************************************/
818 /* 8253 PIT emulation */
820 #define PIT_FREQ 1193182
822 #define RW_STATE_LSB 0
823 #define RW_STATE_MSB 1
824 #define RW_STATE_WORD0 2
825 #define RW_STATE_WORD1 3
826 #define RW_STATE_LATCHED_WORD0 4
827 #define RW_STATE_LATCHED_WORD1 5
829 typedef struct PITChannelState {
830 int count; /* can be 65536 */
831 uint16_t latched_count;
832 uint8_t rw_state;
833 uint8_t mode;
834 uint8_t bcd; /* not supported */
835 uint8_t gate; /* timer start */
836 int64_t count_load_time;
837 int64_t count_last_edge_check_time;
838 } PITChannelState;
840 PITChannelState pit_channels[3];
841 int speaker_data_on;
842 int dummy_refresh_clock;
843 int pit_min_timer_count = 0;
846 #if defined(__powerpc__)
848 static inline uint32_t get_tbl(void)
850 uint32_t tbl;
851 asm volatile("mftb %0" : "=r" (tbl));
852 return tbl;
855 static inline uint32_t get_tbu(void)
857 uint32_t tbl;
858 asm volatile("mftbu %0" : "=r" (tbl));
859 return tbl;
862 int64_t cpu_get_real_ticks(void)
864 uint32_t l, h, h1;
865 /* NOTE: we test if wrapping has occurred */
866 do {
867 h = get_tbu();
868 l = get_tbl();
869 h1 = get_tbu();
870 } while (h != h1);
871 return ((int64_t)h << 32) | l;
874 #elif defined(__i386__)
876 int64_t cpu_get_real_ticks(void)
878 int64_t val;
879 asm("rdtsc" : "=A" (val));
880 return val;
883 #else
884 #error unsupported CPU
885 #endif
887 static int64_t cpu_ticks_offset;
888 static int64_t cpu_ticks_last;
890 int64_t cpu_get_ticks(void)
892 return cpu_get_real_ticks() + cpu_ticks_offset;
895 /* enable cpu_get_ticks() */
896 void cpu_enable_ticks(void)
898 cpu_ticks_offset = cpu_ticks_last - cpu_get_real_ticks();
901 /* disable cpu_get_ticks() : the clock is stopped. You must not call
902 cpu_get_ticks() after that. */
903 void cpu_disable_ticks(void)
905 cpu_ticks_last = cpu_get_ticks();
908 int64_t get_clock(void)
910 struct timeval tv;
911 gettimeofday(&tv, NULL);
912 return tv.tv_sec * 1000000LL + tv.tv_usec;
915 void cpu_calibrate_ticks(void)
917 int64_t usec, ticks;
919 usec = get_clock();
920 ticks = cpu_get_ticks();
921 usleep(50 * 1000);
922 usec = get_clock() - usec;
923 ticks = cpu_get_ticks() - ticks;
924 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
927 /* compute with 96 bit intermediate result: (a*b)/c */
928 static uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
930 union {
931 uint64_t ll;
932 struct {
933 #ifdef WORDS_BIGENDIAN
934 uint32_t high, low;
935 #else
936 uint32_t low, high;
937 #endif
938 } l;
939 } u, res;
940 uint64_t rl, rh;
942 u.ll = a;
943 rl = (uint64_t)u.l.low * (uint64_t)b;
944 rh = (uint64_t)u.l.high * (uint64_t)b;
945 rh += (rl >> 32);
946 res.l.high = rh / c;
947 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
948 return res.ll;
951 static int pit_get_count(PITChannelState *s)
953 uint64_t d;
954 int counter;
956 d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
957 switch(s->mode) {
958 case 0:
959 case 1:
960 case 4:
961 case 5:
962 counter = (s->count - d) & 0xffff;
963 break;
964 default:
965 counter = s->count - (d % s->count);
966 break;
968 return counter;
971 /* get pit output bit */
972 static int pit_get_out(PITChannelState *s)
974 uint64_t d;
975 int out;
977 d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
978 switch(s->mode) {
979 default:
980 case 0:
981 out = (d >= s->count);
982 break;
983 case 1:
984 out = (d < s->count);
985 break;
986 case 2:
987 if ((d % s->count) == 0 && d != 0)
988 out = 1;
989 else
990 out = 0;
991 break;
992 case 3:
993 out = (d % s->count) < (s->count >> 1);
994 break;
995 case 4:
996 case 5:
997 out = (d == s->count);
998 break;
1000 return out;
1003 /* get the number of 0 to 1 transitions we had since we call this
1004 function */
1005 /* XXX: maybe better to use ticks precision to avoid getting edges
1006 twice if checks are done at very small intervals */
1007 static int pit_get_out_edges(PITChannelState *s)
1009 uint64_t d1, d2;
1010 int64_t ticks;
1011 int ret, v;
1013 ticks = cpu_get_ticks();
1014 d1 = muldiv64(s->count_last_edge_check_time - s->count_load_time,
1015 PIT_FREQ, ticks_per_sec);
1016 d2 = muldiv64(ticks - s->count_load_time,
1017 PIT_FREQ, ticks_per_sec);
1018 s->count_last_edge_check_time = ticks;
1019 switch(s->mode) {
1020 default:
1021 case 0:
1022 if (d1 < s->count && d2 >= s->count)
1023 ret = 1;
1024 else
1025 ret = 0;
1026 break;
1027 case 1:
1028 ret = 0;
1029 break;
1030 case 2:
1031 d1 /= s->count;
1032 d2 /= s->count;
1033 ret = d2 - d1;
1034 break;
1035 case 3:
1036 v = s->count - (s->count >> 1);
1037 d1 = (d1 + v) / s->count;
1038 d2 = (d2 + v) / s->count;
1039 ret = d2 - d1;
1040 break;
1041 case 4:
1042 case 5:
1043 if (d1 < s->count && d2 >= s->count)
1044 ret = 1;
1045 else
1046 ret = 0;
1047 break;
1049 return ret;
1052 static inline void pit_load_count(PITChannelState *s, int val)
1054 if (val == 0)
1055 val = 0x10000;
1056 s->count_load_time = cpu_get_ticks();
1057 s->count_last_edge_check_time = s->count_load_time;
1058 s->count = val;
1059 if (s == &pit_channels[0] && val <= pit_min_timer_count) {
1060 fprintf(stderr,
1061 "\nWARNING: qemu: on your system, accurate timer emulation is impossible if its frequency is more than %d Hz. If using a 2.5.xx Linux kernel, you must patch asm/param.h to change HZ from 1000 to 100.\n\n",
1062 PIT_FREQ / pit_min_timer_count);
1066 void pit_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1068 int channel, access;
1069 PITChannelState *s;
1071 addr &= 3;
1072 if (addr == 3) {
1073 channel = val >> 6;
1074 if (channel == 3)
1075 return;
1076 s = &pit_channels[channel];
1077 access = (val >> 4) & 3;
1078 switch(access) {
1079 case 0:
1080 s->latched_count = pit_get_count(s);
1081 s->rw_state = RW_STATE_LATCHED_WORD0;
1082 break;
1083 default:
1084 s->mode = (val >> 1) & 7;
1085 s->bcd = val & 1;
1086 s->rw_state = access - 1 + RW_STATE_LSB;
1087 break;
1089 } else {
1090 s = &pit_channels[addr];
1091 switch(s->rw_state) {
1092 case RW_STATE_LSB:
1093 pit_load_count(s, val);
1094 break;
1095 case RW_STATE_MSB:
1096 pit_load_count(s, val << 8);
1097 break;
1098 case RW_STATE_WORD0:
1099 case RW_STATE_WORD1:
1100 if (s->rw_state & 1) {
1101 pit_load_count(s, (s->latched_count & 0xff) | (val << 8));
1102 } else {
1103 s->latched_count = val;
1105 s->rw_state ^= 1;
1106 break;
1111 uint32_t pit_ioport_read(CPUX86State *env, uint32_t addr)
1113 int ret, count;
1114 PITChannelState *s;
1116 addr &= 3;
1117 s = &pit_channels[addr];
1118 switch(s->rw_state) {
1119 case RW_STATE_LSB:
1120 case RW_STATE_MSB:
1121 case RW_STATE_WORD0:
1122 case RW_STATE_WORD1:
1123 count = pit_get_count(s);
1124 if (s->rw_state & 1)
1125 ret = (count >> 8) & 0xff;
1126 else
1127 ret = count & 0xff;
1128 if (s->rw_state & 2)
1129 s->rw_state ^= 1;
1130 break;
1131 default:
1132 case RW_STATE_LATCHED_WORD0:
1133 case RW_STATE_LATCHED_WORD1:
1134 if (s->rw_state & 1)
1135 ret = s->latched_count >> 8;
1136 else
1137 ret = s->latched_count & 0xff;
1138 s->rw_state ^= 1;
1139 break;
1141 return ret;
1144 void speaker_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1146 speaker_data_on = (val >> 1) & 1;
1147 pit_channels[2].gate = val & 1;
1150 uint32_t speaker_ioport_read(CPUX86State *env, uint32_t addr)
1152 int out;
1153 out = pit_get_out(&pit_channels[2]);
1154 dummy_refresh_clock ^= 1;
1155 return (speaker_data_on << 1) | pit_channels[2].gate | (out << 5) |
1156 (dummy_refresh_clock << 4);
1159 void pit_init(void)
1161 PITChannelState *s;
1162 int i;
1164 cpu_calibrate_ticks();
1166 for(i = 0;i < 3; i++) {
1167 s = &pit_channels[i];
1168 s->mode = 3;
1169 s->gate = (i != 2);
1170 pit_load_count(s, 0);
1173 register_ioport_write(0x40, 4, pit_ioport_write, 1);
1174 register_ioport_read(0x40, 3, pit_ioport_read, 1);
1176 register_ioport_read(0x61, 1, speaker_ioport_read, 1);
1177 register_ioport_write(0x61, 1, speaker_ioport_write, 1);
1180 /***********************************************************/
1181 /* serial port emulation */
1183 #define UART_IRQ 4
1185 #define UART_LCR_DLAB 0x80 /* Divisor latch access bit */
1187 #define UART_IER_MSI 0x08 /* Enable Modem status interrupt */
1188 #define UART_IER_RLSI 0x04 /* Enable receiver line status interrupt */
1189 #define UART_IER_THRI 0x02 /* Enable Transmitter holding register int. */
1190 #define UART_IER_RDI 0x01 /* Enable receiver data interrupt */
1192 #define UART_IIR_NO_INT 0x01 /* No interrupts pending */
1193 #define UART_IIR_ID 0x06 /* Mask for the interrupt ID */
1195 #define UART_IIR_MSI 0x00 /* Modem status interrupt */
1196 #define UART_IIR_THRI 0x02 /* Transmitter holding register empty */
1197 #define UART_IIR_RDI 0x04 /* Receiver data interrupt */
1198 #define UART_IIR_RLSI 0x06 /* Receiver line status interrupt */
1200 #define UART_LSR_TEMT 0x40 /* Transmitter empty */
1201 #define UART_LSR_THRE 0x20 /* Transmit-hold-register empty */
1202 #define UART_LSR_BI 0x10 /* Break interrupt indicator */
1203 #define UART_LSR_FE 0x08 /* Frame error indicator */
1204 #define UART_LSR_PE 0x04 /* Parity error indicator */
1205 #define UART_LSR_OE 0x02 /* Overrun error indicator */
1206 #define UART_LSR_DR 0x01 /* Receiver data ready */
1208 typedef struct SerialState {
1209 uint8_t divider;
1210 uint8_t rbr; /* receive register */
1211 uint8_t ier;
1212 uint8_t iir; /* read only */
1213 uint8_t lcr;
1214 uint8_t mcr;
1215 uint8_t lsr; /* read only */
1216 uint8_t msr;
1217 uint8_t scr;
1218 } SerialState;
1220 SerialState serial_ports[1];
1222 void serial_update_irq(void)
1224 SerialState *s = &serial_ports[0];
1226 if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {
1227 s->iir = UART_IIR_RDI;
1228 } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {
1229 s->iir = UART_IIR_THRI;
1230 } else {
1231 s->iir = UART_IIR_NO_INT;
1233 if (s->iir != UART_IIR_NO_INT) {
1234 pic_set_irq(UART_IRQ, 1);
1235 } else {
1236 pic_set_irq(UART_IRQ, 0);
1240 void serial_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1242 SerialState *s = &serial_ports[0];
1243 unsigned char ch;
1244 int ret;
1246 addr &= 7;
1247 switch(addr) {
1248 default:
1249 case 0:
1250 if (s->lcr & UART_LCR_DLAB) {
1251 s->divider = (s->divider & 0xff00) | val;
1252 } else {
1253 s->lsr &= ~UART_LSR_THRE;
1254 serial_update_irq();
1256 ch = val;
1257 do {
1258 ret = write(1, &ch, 1);
1259 } while (ret != 1);
1260 s->lsr |= UART_LSR_THRE;
1261 s->lsr |= UART_LSR_TEMT;
1262 serial_update_irq();
1264 break;
1265 case 1:
1266 if (s->lcr & UART_LCR_DLAB) {
1267 s->divider = (s->divider & 0x00ff) | (val << 8);
1268 } else {
1269 s->ier = val;
1270 serial_update_irq();
1272 break;
1273 case 2:
1274 break;
1275 case 3:
1276 s->lcr = val;
1277 break;
1278 case 4:
1279 s->mcr = val;
1280 break;
1281 case 5:
1282 break;
1283 case 6:
1284 s->msr = val;
1285 break;
1286 case 7:
1287 s->scr = val;
1288 break;
1292 uint32_t serial_ioport_read(CPUX86State *env, uint32_t addr)
1294 SerialState *s = &serial_ports[0];
1295 uint32_t ret;
1297 addr &= 7;
1298 switch(addr) {
1299 default:
1300 case 0:
1301 if (s->lcr & UART_LCR_DLAB) {
1302 ret = s->divider & 0xff;
1303 } else {
1304 ret = s->rbr;
1305 s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
1306 serial_update_irq();
1308 break;
1309 case 1:
1310 if (s->lcr & UART_LCR_DLAB) {
1311 ret = (s->divider >> 8) & 0xff;
1312 } else {
1313 ret = s->ier;
1315 break;
1316 case 2:
1317 ret = s->iir;
1318 break;
1319 case 3:
1320 ret = s->lcr;
1321 break;
1322 case 4:
1323 ret = s->mcr;
1324 break;
1325 case 5:
1326 ret = s->lsr;
1327 break;
1328 case 6:
1329 ret = s->msr;
1330 break;
1331 case 7:
1332 ret = s->scr;
1333 break;
1335 return ret;
1338 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1339 static int term_got_escape;
1341 void term_print_help(void)
1343 printf("\n"
1344 "C-a h print this help\n"
1345 "C-a x exit emulatior\n"
1346 "C-a s save disk data back to file (if -snapshot)\n"
1347 "C-a b send break (magic sysrq)\n"
1348 "C-a C-a send C-a\n"
1352 /* called when a char is received */
1353 void serial_received_byte(SerialState *s, int ch)
1355 if (term_got_escape) {
1356 term_got_escape = 0;
1357 switch(ch) {
1358 case 'h':
1359 term_print_help();
1360 break;
1361 case 'x':
1362 exit(0);
1363 break;
1364 case 's':
1366 int i;
1367 for (i = 0; i < MAX_DISKS; i++) {
1368 if (bs_table[i])
1369 bdrv_commit(bs_table[i]);
1372 break;
1373 case 'b':
1374 /* send break */
1375 s->rbr = 0;
1376 s->lsr |= UART_LSR_BI | UART_LSR_DR;
1377 serial_update_irq();
1378 break;
1379 case TERM_ESCAPE:
1380 goto send_char;
1382 } else if (ch == TERM_ESCAPE) {
1383 term_got_escape = 1;
1384 } else {
1385 send_char:
1386 s->rbr = ch;
1387 s->lsr |= UART_LSR_DR;
1388 serial_update_irq();
1392 void serial_init(void)
1394 SerialState *s = &serial_ports[0];
1396 s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
1398 register_ioport_write(0x3f8, 8, serial_ioport_write, 1);
1399 register_ioport_read(0x3f8, 8, serial_ioport_read, 1);
1402 /***********************************************************/
1403 /* ne2000 emulation */
1405 #define NE2000_IOPORT 0x300
1406 #define NE2000_IRQ 9
1408 #define MAX_ETH_FRAME_SIZE 1514
1410 #define E8390_CMD 0x00 /* The command register (for all pages) */
1411 /* Page 0 register offsets. */
1412 #define EN0_CLDALO 0x01 /* Low byte of current local dma addr RD */
1413 #define EN0_STARTPG 0x01 /* Starting page of ring bfr WR */
1414 #define EN0_CLDAHI 0x02 /* High byte of current local dma addr RD */
1415 #define EN0_STOPPG 0x02 /* Ending page +1 of ring bfr WR */
1416 #define EN0_BOUNDARY 0x03 /* Boundary page of ring bfr RD WR */
1417 #define EN0_TSR 0x04 /* Transmit status reg RD */
1418 #define EN0_TPSR 0x04 /* Transmit starting page WR */
1419 #define EN0_NCR 0x05 /* Number of collision reg RD */
1420 #define EN0_TCNTLO 0x05 /* Low byte of tx byte count WR */
1421 #define EN0_FIFO 0x06 /* FIFO RD */
1422 #define EN0_TCNTHI 0x06 /* High byte of tx byte count WR */
1423 #define EN0_ISR 0x07 /* Interrupt status reg RD WR */
1424 #define EN0_CRDALO 0x08 /* low byte of current remote dma address RD */
1425 #define EN0_RSARLO 0x08 /* Remote start address reg 0 */
1426 #define EN0_CRDAHI 0x09 /* high byte, current remote dma address RD */
1427 #define EN0_RSARHI 0x09 /* Remote start address reg 1 */
1428 #define EN0_RCNTLO 0x0a /* Remote byte count reg WR */
1429 #define EN0_RCNTHI 0x0b /* Remote byte count reg WR */
1430 #define EN0_RSR 0x0c /* rx status reg RD */
1431 #define EN0_RXCR 0x0c /* RX configuration reg WR */
1432 #define EN0_TXCR 0x0d /* TX configuration reg WR */
1433 #define EN0_COUNTER0 0x0d /* Rcv alignment error counter RD */
1434 #define EN0_DCFG 0x0e /* Data configuration reg WR */
1435 #define EN0_COUNTER1 0x0e /* Rcv CRC error counter RD */
1436 #define EN0_IMR 0x0f /* Interrupt mask reg WR */
1437 #define EN0_COUNTER2 0x0f /* Rcv missed frame error counter RD */
1439 #define EN1_PHYS 0x11
1440 #define EN1_CURPAG 0x17
1441 #define EN1_MULT 0x18
1443 /* Register accessed at EN_CMD, the 8390 base addr. */
1444 #define E8390_STOP 0x01 /* Stop and reset the chip */
1445 #define E8390_START 0x02 /* Start the chip, clear reset */
1446 #define E8390_TRANS 0x04 /* Transmit a frame */
1447 #define E8390_RREAD 0x08 /* Remote read */
1448 #define E8390_RWRITE 0x10 /* Remote write */
1449 #define E8390_NODMA 0x20 /* Remote DMA */
1450 #define E8390_PAGE0 0x00 /* Select page chip registers */
1451 #define E8390_PAGE1 0x40 /* using the two high-order bits */
1452 #define E8390_PAGE2 0x80 /* Page 3 is invalid. */
1454 /* Bits in EN0_ISR - Interrupt status register */
1455 #define ENISR_RX 0x01 /* Receiver, no error */
1456 #define ENISR_TX 0x02 /* Transmitter, no error */
1457 #define ENISR_RX_ERR 0x04 /* Receiver, with error */
1458 #define ENISR_TX_ERR 0x08 /* Transmitter, with error */
1459 #define ENISR_OVER 0x10 /* Receiver overwrote the ring */
1460 #define ENISR_COUNTERS 0x20 /* Counters need emptying */
1461 #define ENISR_RDC 0x40 /* remote dma complete */
1462 #define ENISR_RESET 0x80 /* Reset completed */
1463 #define ENISR_ALL 0x3f /* Interrupts we will enable */
1465 /* Bits in received packet status byte and EN0_RSR*/
1466 #define ENRSR_RXOK 0x01 /* Received a good packet */
1467 #define ENRSR_CRC 0x02 /* CRC error */
1468 #define ENRSR_FAE 0x04 /* frame alignment error */
1469 #define ENRSR_FO 0x08 /* FIFO overrun */
1470 #define ENRSR_MPA 0x10 /* missed pkt */
1471 #define ENRSR_PHY 0x20 /* physical/multicast address */
1472 #define ENRSR_DIS 0x40 /* receiver disable. set in monitor mode */
1473 #define ENRSR_DEF 0x80 /* deferring */
1475 /* Transmitted packet status, EN0_TSR. */
1476 #define ENTSR_PTX 0x01 /* Packet transmitted without error */
1477 #define ENTSR_ND 0x02 /* The transmit wasn't deferred. */
1478 #define ENTSR_COL 0x04 /* The transmit collided at least once. */
1479 #define ENTSR_ABT 0x08 /* The transmit collided 16 times, and was deferred. */
1480 #define ENTSR_CRS 0x10 /* The carrier sense was lost. */
1481 #define ENTSR_FU 0x20 /* A "FIFO underrun" occurred during transmit. */
1482 #define ENTSR_CDH 0x40 /* The collision detect "heartbeat" signal was lost. */
1483 #define ENTSR_OWC 0x80 /* There was an out-of-window collision. */
1485 #define NE2000_MEM_SIZE 32768
1487 typedef struct NE2000State {
1488 uint8_t cmd;
1489 uint32_t start;
1490 uint32_t stop;
1491 uint8_t boundary;
1492 uint8_t tsr;
1493 uint8_t tpsr;
1494 uint16_t tcnt;
1495 uint16_t rcnt;
1496 uint32_t rsar;
1497 uint8_t isr;
1498 uint8_t dcfg;
1499 uint8_t imr;
1500 uint8_t phys[6]; /* mac address */
1501 uint8_t curpag;
1502 uint8_t mult[8]; /* multicast mask array */
1503 uint8_t mem[NE2000_MEM_SIZE];
1504 } NE2000State;
1506 NE2000State ne2000_state;
1507 int net_fd = -1;
1508 char network_script[1024];
1510 void ne2000_reset(void)
1512 NE2000State *s = &ne2000_state;
1513 int i;
1515 s->isr = ENISR_RESET;
1516 s->mem[0] = 0x52;
1517 s->mem[1] = 0x54;
1518 s->mem[2] = 0x00;
1519 s->mem[3] = 0x12;
1520 s->mem[4] = 0x34;
1521 s->mem[5] = 0x56;
1522 s->mem[14] = 0x57;
1523 s->mem[15] = 0x57;
1525 /* duplicate prom data */
1526 for(i = 15;i >= 0; i--) {
1527 s->mem[2 * i] = s->mem[i];
1528 s->mem[2 * i + 1] = s->mem[i];
1532 void ne2000_update_irq(NE2000State *s)
1534 int isr;
1535 isr = s->isr & s->imr;
1536 if (isr)
1537 pic_set_irq(NE2000_IRQ, 1);
1538 else
1539 pic_set_irq(NE2000_IRQ, 0);
1542 int net_init(void)
1544 struct ifreq ifr;
1545 int fd, ret, pid, status;
1547 fd = open("/dev/net/tun", O_RDWR);
1548 if (fd < 0) {
1549 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1550 return -1;
1552 memset(&ifr, 0, sizeof(ifr));
1553 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1554 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1555 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1556 if (ret != 0) {
1557 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1558 close(fd);
1559 return -1;
1561 printf("Connected to host network interface: %s\n", ifr.ifr_name);
1562 fcntl(fd, F_SETFL, O_NONBLOCK);
1563 net_fd = fd;
1565 /* try to launch network init script */
1566 pid = fork();
1567 if (pid >= 0) {
1568 if (pid == 0) {
1569 execl(network_script, network_script, ifr.ifr_name, NULL);
1570 exit(1);
1572 while (waitpid(pid, &status, 0) != pid);
1573 if (!WIFEXITED(status) ||
1574 WEXITSTATUS(status) != 0) {
1575 fprintf(stderr, "%s: could not launch network script for '%s'\n",
1576 network_script, ifr.ifr_name);
1579 return 0;
1582 void net_send_packet(NE2000State *s, const uint8_t *buf, int size)
1584 #ifdef DEBUG_NE2000
1585 printf("NE2000: sending packet size=%d\n", size);
1586 #endif
1587 write(net_fd, buf, size);
1590 /* return true if the NE2000 can receive more data */
1591 int ne2000_can_receive(NE2000State *s)
1593 int avail, index, boundary;
1595 if (s->cmd & E8390_STOP)
1596 return 0;
1597 index = s->curpag << 8;
1598 boundary = s->boundary << 8;
1599 if (index < boundary)
1600 avail = boundary - index;
1601 else
1602 avail = (s->stop - s->start) - (index - boundary);
1603 if (avail < (MAX_ETH_FRAME_SIZE + 4))
1604 return 0;
1605 return 1;
1608 void ne2000_receive(NE2000State *s, uint8_t *buf, int size)
1610 uint8_t *p;
1611 int total_len, next, avail, len, index;
1613 #if defined(DEBUG_NE2000)
1614 printf("NE2000: received len=%d\n", size);
1615 #endif
1617 index = s->curpag << 8;
1618 /* 4 bytes for header */
1619 total_len = size + 4;
1620 /* address for next packet (4 bytes for CRC) */
1621 next = index + ((total_len + 4 + 255) & ~0xff);
1622 if (next >= s->stop)
1623 next -= (s->stop - s->start);
1624 /* prepare packet header */
1625 p = s->mem + index;
1626 p[0] = ENRSR_RXOK; /* receive status */
1627 p[1] = next >> 8;
1628 p[2] = total_len;
1629 p[3] = total_len >> 8;
1630 index += 4;
1632 /* write packet data */
1633 while (size > 0) {
1634 avail = s->stop - index;
1635 len = size;
1636 if (len > avail)
1637 len = avail;
1638 memcpy(s->mem + index, buf, len);
1639 buf += len;
1640 index += len;
1641 if (index == s->stop)
1642 index = s->start;
1643 size -= len;
1645 s->curpag = next >> 8;
1647 /* now we can signal we have receive something */
1648 s->isr |= ENISR_RX;
1649 ne2000_update_irq(s);
1652 void ne2000_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1654 NE2000State *s = &ne2000_state;
1655 int offset, page;
1657 addr &= 0xf;
1658 #ifdef DEBUG_NE2000
1659 printf("NE2000: write addr=0x%x val=0x%02x\n", addr, val);
1660 #endif
1661 if (addr == E8390_CMD) {
1662 /* control register */
1663 s->cmd = val;
1664 if (val & E8390_START) {
1665 /* test specific case: zero length transfert */
1666 if ((val & (E8390_RREAD | E8390_RWRITE)) &&
1667 s->rcnt == 0) {
1668 s->isr |= ENISR_RDC;
1669 ne2000_update_irq(s);
1671 if (val & E8390_TRANS) {
1672 net_send_packet(s, s->mem + (s->tpsr << 8), s->tcnt);
1673 /* signal end of transfert */
1674 s->tsr = ENTSR_PTX;
1675 s->isr |= ENISR_TX;
1676 ne2000_update_irq(s);
1679 } else {
1680 page = s->cmd >> 6;
1681 offset = addr | (page << 4);
1682 switch(offset) {
1683 case EN0_STARTPG:
1684 s->start = val << 8;
1685 break;
1686 case EN0_STOPPG:
1687 s->stop = val << 8;
1688 break;
1689 case EN0_BOUNDARY:
1690 s->boundary = val;
1691 break;
1692 case EN0_IMR:
1693 s->imr = val;
1694 ne2000_update_irq(s);
1695 break;
1696 case EN0_TPSR:
1697 s->tpsr = val;
1698 break;
1699 case EN0_TCNTLO:
1700 s->tcnt = (s->tcnt & 0xff00) | val;
1701 break;
1702 case EN0_TCNTHI:
1703 s->tcnt = (s->tcnt & 0x00ff) | (val << 8);
1704 break;
1705 case EN0_RSARLO:
1706 s->rsar = (s->rsar & 0xff00) | val;
1707 break;
1708 case EN0_RSARHI:
1709 s->rsar = (s->rsar & 0x00ff) | (val << 8);
1710 break;
1711 case EN0_RCNTLO:
1712 s->rcnt = (s->rcnt & 0xff00) | val;
1713 break;
1714 case EN0_RCNTHI:
1715 s->rcnt = (s->rcnt & 0x00ff) | (val << 8);
1716 break;
1717 case EN0_DCFG:
1718 s->dcfg = val;
1719 break;
1720 case EN0_ISR:
1721 s->isr &= ~val;
1722 ne2000_update_irq(s);
1723 break;
1724 case EN1_PHYS ... EN1_PHYS + 5:
1725 s->phys[offset - EN1_PHYS] = val;
1726 break;
1727 case EN1_CURPAG:
1728 s->curpag = val;
1729 break;
1730 case EN1_MULT ... EN1_MULT + 7:
1731 s->mult[offset - EN1_MULT] = val;
1732 break;
1737 uint32_t ne2000_ioport_read(CPUX86State *env, uint32_t addr)
1739 NE2000State *s = &ne2000_state;
1740 int offset, page, ret;
1742 addr &= 0xf;
1743 if (addr == E8390_CMD) {
1744 ret = s->cmd;
1745 } else {
1746 page = s->cmd >> 6;
1747 offset = addr | (page << 4);
1748 switch(offset) {
1749 case EN0_TSR:
1750 ret = s->tsr;
1751 break;
1752 case EN0_BOUNDARY:
1753 ret = s->boundary;
1754 break;
1755 case EN0_ISR:
1756 ret = s->isr;
1757 break;
1758 case EN1_PHYS ... EN1_PHYS + 5:
1759 ret = s->phys[offset - EN1_PHYS];
1760 break;
1761 case EN1_CURPAG:
1762 ret = s->curpag;
1763 break;
1764 case EN1_MULT ... EN1_MULT + 7:
1765 ret = s->mult[offset - EN1_MULT];
1766 break;
1767 default:
1768 ret = 0x00;
1769 break;
1772 #ifdef DEBUG_NE2000
1773 printf("NE2000: read addr=0x%x val=%02x\n", addr, ret);
1774 #endif
1775 return ret;
1778 void ne2000_asic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1780 NE2000State *s = &ne2000_state;
1781 uint8_t *p;
1783 #ifdef DEBUG_NE2000
1784 printf("NE2000: asic write val=0x%04x\n", val);
1785 #endif
1786 p = s->mem + s->rsar;
1787 if (s->dcfg & 0x01) {
1788 /* 16 bit access */
1789 p[0] = val;
1790 p[1] = val >> 8;
1791 s->rsar += 2;
1792 s->rcnt -= 2;
1793 } else {
1794 /* 8 bit access */
1795 p[0] = val;
1796 s->rsar++;
1797 s->rcnt--;
1799 /* wrap */
1800 if (s->rsar == s->stop)
1801 s->rsar = s->start;
1802 if (s->rcnt == 0) {
1803 /* signal end of transfert */
1804 s->isr |= ENISR_RDC;
1805 ne2000_update_irq(s);
1809 uint32_t ne2000_asic_ioport_read(CPUX86State *env, uint32_t addr)
1811 NE2000State *s = &ne2000_state;
1812 uint8_t *p;
1813 int ret;
1815 p = s->mem + s->rsar;
1816 if (s->dcfg & 0x01) {
1817 /* 16 bit access */
1818 ret = p[0] | (p[1] << 8);
1819 s->rsar += 2;
1820 s->rcnt -= 2;
1821 } else {
1822 /* 8 bit access */
1823 ret = p[0];
1824 s->rsar++;
1825 s->rcnt--;
1827 /* wrap */
1828 if (s->rsar == s->stop)
1829 s->rsar = s->start;
1830 if (s->rcnt == 0) {
1831 /* signal end of transfert */
1832 s->isr |= ENISR_RDC;
1833 ne2000_update_irq(s);
1835 #ifdef DEBUG_NE2000
1836 printf("NE2000: asic read val=0x%04x\n", ret);
1837 #endif
1838 return ret;
1841 void ne2000_reset_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1843 /* nothing to do (end of reset pulse) */
1846 uint32_t ne2000_reset_ioport_read(CPUX86State *env, uint32_t addr)
1848 ne2000_reset();
1849 return 0;
1852 void ne2000_init(void)
1854 register_ioport_write(NE2000_IOPORT, 16, ne2000_ioport_write, 1);
1855 register_ioport_read(NE2000_IOPORT, 16, ne2000_ioport_read, 1);
1857 register_ioport_write(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_write, 1);
1858 register_ioport_read(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_read, 1);
1859 register_ioport_write(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_write, 2);
1860 register_ioport_read(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_read, 2);
1862 register_ioport_write(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_write, 1);
1863 register_ioport_read(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_read, 1);
1864 ne2000_reset();
1867 /***********************************************************/
1868 /* ide emulation */
1870 /* Bits of HD_STATUS */
1871 #define ERR_STAT 0x01
1872 #define INDEX_STAT 0x02
1873 #define ECC_STAT 0x04 /* Corrected error */
1874 #define DRQ_STAT 0x08
1875 #define SEEK_STAT 0x10
1876 #define SRV_STAT 0x10
1877 #define WRERR_STAT 0x20
1878 #define READY_STAT 0x40
1879 #define BUSY_STAT 0x80
1881 /* Bits for HD_ERROR */
1882 #define MARK_ERR 0x01 /* Bad address mark */
1883 #define TRK0_ERR 0x02 /* couldn't find track 0 */
1884 #define ABRT_ERR 0x04 /* Command aborted */
1885 #define MCR_ERR 0x08 /* media change request */
1886 #define ID_ERR 0x10 /* ID field not found */
1887 #define MC_ERR 0x20 /* media changed */
1888 #define ECC_ERR 0x40 /* Uncorrectable ECC error */
1889 #define BBD_ERR 0x80 /* pre-EIDE meaning: block marked bad */
1890 #define ICRC_ERR 0x80 /* new meaning: CRC error during transfer */
1892 /* Bits of HD_NSECTOR */
1893 #define CD 0x01
1894 #define IO 0x02
1895 #define REL 0x04
1896 #define TAG_MASK 0xf8
1898 #define IDE_CMD_RESET 0x04
1899 #define IDE_CMD_DISABLE_IRQ 0x02
1901 /* ATA/ATAPI Commands pre T13 Spec */
1902 #define WIN_NOP 0x00
1904 * 0x01->0x02 Reserved
1906 #define CFA_REQ_EXT_ERROR_CODE 0x03 /* CFA Request Extended Error Code */
1908 * 0x04->0x07 Reserved
1910 #define WIN_SRST 0x08 /* ATAPI soft reset command */
1911 #define WIN_DEVICE_RESET 0x08
1913 * 0x09->0x0F Reserved
1915 #define WIN_RECAL 0x10
1916 #define WIN_RESTORE WIN_RECAL
1918 * 0x10->0x1F Reserved
1920 #define WIN_READ 0x20 /* 28-Bit */
1921 #define WIN_READ_ONCE 0x21 /* 28-Bit without retries */
1922 #define WIN_READ_LONG 0x22 /* 28-Bit */
1923 #define WIN_READ_LONG_ONCE 0x23 /* 28-Bit without retries */
1924 #define WIN_READ_EXT 0x24 /* 48-Bit */
1925 #define WIN_READDMA_EXT 0x25 /* 48-Bit */
1926 #define WIN_READDMA_QUEUED_EXT 0x26 /* 48-Bit */
1927 #define WIN_READ_NATIVE_MAX_EXT 0x27 /* 48-Bit */
1929 * 0x28
1931 #define WIN_MULTREAD_EXT 0x29 /* 48-Bit */
1933 * 0x2A->0x2F Reserved
1935 #define WIN_WRITE 0x30 /* 28-Bit */
1936 #define WIN_WRITE_ONCE 0x31 /* 28-Bit without retries */
1937 #define WIN_WRITE_LONG 0x32 /* 28-Bit */
1938 #define WIN_WRITE_LONG_ONCE 0x33 /* 28-Bit without retries */
1939 #define WIN_WRITE_EXT 0x34 /* 48-Bit */
1940 #define WIN_WRITEDMA_EXT 0x35 /* 48-Bit */
1941 #define WIN_WRITEDMA_QUEUED_EXT 0x36 /* 48-Bit */
1942 #define WIN_SET_MAX_EXT 0x37 /* 48-Bit */
1943 #define CFA_WRITE_SECT_WO_ERASE 0x38 /* CFA Write Sectors without erase */
1944 #define WIN_MULTWRITE_EXT 0x39 /* 48-Bit */
1946 * 0x3A->0x3B Reserved
1948 #define WIN_WRITE_VERIFY 0x3C /* 28-Bit */
1950 * 0x3D->0x3F Reserved
1952 #define WIN_VERIFY 0x40 /* 28-Bit - Read Verify Sectors */
1953 #define WIN_VERIFY_ONCE 0x41 /* 28-Bit - without retries */
1954 #define WIN_VERIFY_EXT 0x42 /* 48-Bit */
1956 * 0x43->0x4F Reserved
1958 #define WIN_FORMAT 0x50
1960 * 0x51->0x5F Reserved
1962 #define WIN_INIT 0x60
1964 * 0x61->0x5F Reserved
1966 #define WIN_SEEK 0x70 /* 0x70-0x7F Reserved */
1967 #define CFA_TRANSLATE_SECTOR 0x87 /* CFA Translate Sector */
1968 #define WIN_DIAGNOSE 0x90
1969 #define WIN_SPECIFY 0x91 /* set drive geometry translation */
1970 #define WIN_DOWNLOAD_MICROCODE 0x92
1971 #define WIN_STANDBYNOW2 0x94
1972 #define WIN_STANDBY2 0x96
1973 #define WIN_SETIDLE2 0x97
1974 #define WIN_CHECKPOWERMODE2 0x98
1975 #define WIN_SLEEPNOW2 0x99
1977 * 0x9A VENDOR
1979 #define WIN_PACKETCMD 0xA0 /* Send a packet command. */
1980 #define WIN_PIDENTIFY 0xA1 /* identify ATAPI device */
1981 #define WIN_QUEUED_SERVICE 0xA2
1982 #define WIN_SMART 0xB0 /* self-monitoring and reporting */
1983 #define CFA_ERASE_SECTORS 0xC0
1984 #define WIN_MULTREAD 0xC4 /* read sectors using multiple mode*/
1985 #define WIN_MULTWRITE 0xC5 /* write sectors using multiple mode */
1986 #define WIN_SETMULT 0xC6 /* enable/disable multiple mode */
1987 #define WIN_READDMA_QUEUED 0xC7 /* read sectors using Queued DMA transfers */
1988 #define WIN_READDMA 0xC8 /* read sectors using DMA transfers */
1989 #define WIN_READDMA_ONCE 0xC9 /* 28-Bit - without retries */
1990 #define WIN_WRITEDMA 0xCA /* write sectors using DMA transfers */
1991 #define WIN_WRITEDMA_ONCE 0xCB /* 28-Bit - without retries */
1992 #define WIN_WRITEDMA_QUEUED 0xCC /* write sectors using Queued DMA transfers */
1993 #define CFA_WRITE_MULTI_WO_ERASE 0xCD /* CFA Write multiple without erase */
1994 #define WIN_GETMEDIASTATUS 0xDA
1995 #define WIN_ACKMEDIACHANGE 0xDB /* ATA-1, ATA-2 vendor */
1996 #define WIN_POSTBOOT 0xDC
1997 #define WIN_PREBOOT 0xDD
1998 #define WIN_DOORLOCK 0xDE /* lock door on removable drives */
1999 #define WIN_DOORUNLOCK 0xDF /* unlock door on removable drives */
2000 #define WIN_STANDBYNOW1 0xE0
2001 #define WIN_IDLEIMMEDIATE 0xE1 /* force drive to become "ready" */
2002 #define WIN_STANDBY 0xE2 /* Set device in Standby Mode */
2003 #define WIN_SETIDLE1 0xE3
2004 #define WIN_READ_BUFFER 0xE4 /* force read only 1 sector */
2005 #define WIN_CHECKPOWERMODE1 0xE5
2006 #define WIN_SLEEPNOW1 0xE6
2007 #define WIN_FLUSH_CACHE 0xE7
2008 #define WIN_WRITE_BUFFER 0xE8 /* force write only 1 sector */
2009 #define WIN_WRITE_SAME 0xE9 /* read ata-2 to use */
2010 /* SET_FEATURES 0x22 or 0xDD */
2011 #define WIN_FLUSH_CACHE_EXT 0xEA /* 48-Bit */
2012 #define WIN_IDENTIFY 0xEC /* ask drive to identify itself */
2013 #define WIN_MEDIAEJECT 0xED
2014 #define WIN_IDENTIFY_DMA 0xEE /* same as WIN_IDENTIFY, but DMA */
2015 #define WIN_SETFEATURES 0xEF /* set special drive features */
2016 #define EXABYTE_ENABLE_NEST 0xF0
2017 #define WIN_SECURITY_SET_PASS 0xF1
2018 #define WIN_SECURITY_UNLOCK 0xF2
2019 #define WIN_SECURITY_ERASE_PREPARE 0xF3
2020 #define WIN_SECURITY_ERASE_UNIT 0xF4
2021 #define WIN_SECURITY_FREEZE_LOCK 0xF5
2022 #define WIN_SECURITY_DISABLE 0xF6
2023 #define WIN_READ_NATIVE_MAX 0xF8 /* return the native maximum address */
2024 #define WIN_SET_MAX 0xF9
2025 #define DISABLE_SEAGATE 0xFB
2027 /* set to 1 set disable mult support */
2028 #define MAX_MULT_SECTORS 8
2030 /* ATAPI defines */
2032 #define ATAPI_PACKET_SIZE 12
2034 /* The generic packet command opcodes for CD/DVD Logical Units,
2035 * From Table 57 of the SFF8090 Ver. 3 (Mt. Fuji) draft standard. */
2036 #define GPCMD_BLANK 0xa1
2037 #define GPCMD_CLOSE_TRACK 0x5b
2038 #define GPCMD_FLUSH_CACHE 0x35
2039 #define GPCMD_FORMAT_UNIT 0x04
2040 #define GPCMD_GET_CONFIGURATION 0x46
2041 #define GPCMD_GET_EVENT_STATUS_NOTIFICATION 0x4a
2042 #define GPCMD_GET_PERFORMANCE 0xac
2043 #define GPCMD_INQUIRY 0x12
2044 #define GPCMD_LOAD_UNLOAD 0xa6
2045 #define GPCMD_MECHANISM_STATUS 0xbd
2046 #define GPCMD_MODE_SELECT_10 0x55
2047 #define GPCMD_MODE_SENSE_10 0x5a
2048 #define GPCMD_PAUSE_RESUME 0x4b
2049 #define GPCMD_PLAY_AUDIO_10 0x45
2050 #define GPCMD_PLAY_AUDIO_MSF 0x47
2051 #define GPCMD_PLAY_AUDIO_TI 0x48
2052 #define GPCMD_PLAY_CD 0xbc
2053 #define GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e
2054 #define GPCMD_READ_10 0x28
2055 #define GPCMD_READ_12 0xa8
2056 #define GPCMD_READ_CDVD_CAPACITY 0x25
2057 #define GPCMD_READ_CD 0xbe
2058 #define GPCMD_READ_CD_MSF 0xb9
2059 #define GPCMD_READ_DISC_INFO 0x51
2060 #define GPCMD_READ_DVD_STRUCTURE 0xad
2061 #define GPCMD_READ_FORMAT_CAPACITIES 0x23
2062 #define GPCMD_READ_HEADER 0x44
2063 #define GPCMD_READ_TRACK_RZONE_INFO 0x52
2064 #define GPCMD_READ_SUBCHANNEL 0x42
2065 #define GPCMD_READ_TOC_PMA_ATIP 0x43
2066 #define GPCMD_REPAIR_RZONE_TRACK 0x58
2067 #define GPCMD_REPORT_KEY 0xa4
2068 #define GPCMD_REQUEST_SENSE 0x03
2069 #define GPCMD_RESERVE_RZONE_TRACK 0x53
2070 #define GPCMD_SCAN 0xba
2071 #define GPCMD_SEEK 0x2b
2072 #define GPCMD_SEND_DVD_STRUCTURE 0xad
2073 #define GPCMD_SEND_EVENT 0xa2
2074 #define GPCMD_SEND_KEY 0xa3
2075 #define GPCMD_SEND_OPC 0x54
2076 #define GPCMD_SET_READ_AHEAD 0xa7
2077 #define GPCMD_SET_STREAMING 0xb6
2078 #define GPCMD_START_STOP_UNIT 0x1b
2079 #define GPCMD_STOP_PLAY_SCAN 0x4e
2080 #define GPCMD_TEST_UNIT_READY 0x00
2081 #define GPCMD_VERIFY_10 0x2f
2082 #define GPCMD_WRITE_10 0x2a
2083 #define GPCMD_WRITE_AND_VERIFY_10 0x2e
2084 /* This is listed as optional in ATAPI 2.6, but is (curiously)
2085 * missing from Mt. Fuji, Table 57. It _is_ mentioned in Mt. Fuji
2086 * Table 377 as an MMC command for SCSi devices though... Most ATAPI
2087 * drives support it. */
2088 #define GPCMD_SET_SPEED 0xbb
2089 /* This seems to be a SCSI specific CD-ROM opcode
2090 * to play data at track/index */
2091 #define GPCMD_PLAYAUDIO_TI 0x48
2093 * From MS Media Status Notification Support Specification. For
2094 * older drives only.
2096 #define GPCMD_GET_MEDIA_STATUS 0xda
2098 /* Mode page codes for mode sense/set */
2099 #define GPMODE_R_W_ERROR_PAGE 0x01
2100 #define GPMODE_WRITE_PARMS_PAGE 0x05
2101 #define GPMODE_AUDIO_CTL_PAGE 0x0e
2102 #define GPMODE_POWER_PAGE 0x1a
2103 #define GPMODE_FAULT_FAIL_PAGE 0x1c
2104 #define GPMODE_TO_PROTECT_PAGE 0x1d
2105 #define GPMODE_CAPABILITIES_PAGE 0x2a
2106 #define GPMODE_ALL_PAGES 0x3f
2107 /* Not in Mt. Fuji, but in ATAPI 2.6 -- depricated now in favor
2108 * of MODE_SENSE_POWER_PAGE */
2109 #define GPMODE_CDROM_PAGE 0x0d
2111 #define ATAPI_INT_REASON_CD 0x01 /* 0 = data transfer */
2112 #define ATAPI_INT_REASON_IO 0x02 /* 1 = transfer to the host */
2113 #define ATAPI_INT_REASON_REL 0x04
2114 #define ATAPI_INT_REASON_TAG 0xf8
2116 /* same constants as bochs */
2117 #define ASC_LOGICAL_BLOCK_OOR 0x21
2118 #define ASC_INV_FIELD_IN_CMD_PACKET 0x24
2119 #define ASC_MEDIUM_NOT_PRESENT 0x3a
2120 #define ASC_SAVING_PARAMETERS_NOT_SUPPORTED 0x39
2122 #define SENSE_NONE 0
2123 #define SENSE_NOT_READY 2
2124 #define SENSE_ILLEGAL_REQUEST 5
2125 #define SENSE_UNIT_ATTENTION 6
2127 struct IDEState;
2129 typedef void EndTransferFunc(struct IDEState *);
2131 typedef struct IDEState {
2132 /* ide config */
2133 int is_cdrom;
2134 int cdrom_locked;
2135 int cylinders, heads, sectors;
2136 int64_t nb_sectors;
2137 int mult_sectors;
2138 int irq;
2139 /* ide regs */
2140 uint8_t feature;
2141 uint8_t error;
2142 uint16_t nsector; /* 0 is 256 to ease computations */
2143 uint8_t sector;
2144 uint8_t lcyl;
2145 uint8_t hcyl;
2146 uint8_t select;
2147 uint8_t status;
2148 /* 0x3f6 command, only meaningful for drive 0 */
2149 uint8_t cmd;
2150 /* depends on bit 4 in select, only meaningful for drive 0 */
2151 struct IDEState *cur_drive;
2152 BlockDriverState *bs;
2153 /* ATAPI specific */
2154 uint8_t sense_key;
2155 uint8_t asc;
2156 int packet_transfer_size;
2157 int elementary_transfer_size;
2158 int io_buffer_index;
2159 int lba;
2160 /* transfer handling */
2161 int req_nb_sectors; /* number of sectors per interrupt */
2162 EndTransferFunc *end_transfer_func;
2163 uint8_t *data_ptr;
2164 uint8_t *data_end;
2165 uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4];
2166 } IDEState;
2168 IDEState ide_state[MAX_DISKS];
2169 IDEState *ide_table[0x400 >> 3];
2171 static inline IDEState *get_ide_interface(uint32_t addr)
2173 return ide_table[addr >> 3];
2176 static void padstr(char *str, const char *src, int len)
2178 int i, v;
2179 for(i = 0; i < len; i++) {
2180 if (*src)
2181 v = *src++;
2182 else
2183 v = ' ';
2184 *(char *)((long)str ^ 1) = v;
2185 str++;
2189 static void ide_identify(IDEState *s)
2191 uint16_t *p;
2192 unsigned int oldsize;
2194 memset(s->io_buffer, 0, 512);
2195 p = (uint16_t *)s->io_buffer;
2196 stw_raw(p + 0, 0x0040);
2197 stw_raw(p + 1, s->cylinders);
2198 stw_raw(p + 3, s->heads);
2199 stw_raw(p + 4, 512 * s->sectors); /* sectors */
2200 stw_raw(p + 5, 512); /* sector size */
2201 stw_raw(p + 6, s->sectors);
2202 padstr((uint8_t *)(p + 10), "QM00001", 20); /* serial number */
2203 stw_raw(p + 20, 3); /* buffer type */
2204 stw_raw(p + 21, 512); /* cache size in sectors */
2205 stw_raw(p + 22, 4); /* ecc bytes */
2206 padstr((uint8_t *)(p + 23), QEMU_VERSION, 8); /* firmware version */
2207 padstr((uint8_t *)(p + 27), "QEMU HARDDISK", 40); /* model */
2208 #if MAX_MULT_SECTORS > 1
2209 stw_raw(p + 47, MAX_MULT_SECTORS);
2210 #endif
2211 stw_raw(p + 48, 1); /* dword I/O */
2212 stw_raw(p + 49, 1 << 9); /* LBA supported, no DMA */
2213 stw_raw(p + 51, 0x200); /* PIO transfer cycle */
2214 stw_raw(p + 52, 0x200); /* DMA transfer cycle */
2215 stw_raw(p + 54, s->cylinders);
2216 stw_raw(p + 55, s->heads);
2217 stw_raw(p + 56, s->sectors);
2218 oldsize = s->cylinders * s->heads * s->sectors;
2219 stw_raw(p + 57, oldsize);
2220 stw_raw(p + 58, oldsize >> 16);
2221 if (s->mult_sectors)
2222 stw_raw(p + 59, 0x100 | s->mult_sectors);
2223 stw_raw(p + 60, s->nb_sectors);
2224 stw_raw(p + 61, s->nb_sectors >> 16);
2225 stw_raw(p + 80, (1 << 1) | (1 << 2));
2226 stw_raw(p + 82, (1 << 14));
2227 stw_raw(p + 83, (1 << 14));
2228 stw_raw(p + 84, (1 << 14));
2229 stw_raw(p + 85, (1 << 14));
2230 stw_raw(p + 86, 0);
2231 stw_raw(p + 87, (1 << 14));
2234 static void ide_atapi_identify(IDEState *s)
2236 uint16_t *p;
2238 memset(s->io_buffer, 0, 512);
2239 p = (uint16_t *)s->io_buffer;
2240 /* Removable CDROM, 50us response, 12 byte packets */
2241 stw_raw(p + 0, (2 << 14) | (5 << 8) | (1 << 7) | (2 << 5) | (0 << 0));
2242 stw_raw(p + 1, s->cylinders);
2243 stw_raw(p + 3, s->heads);
2244 stw_raw(p + 4, 512 * s->sectors); /* sectors */
2245 stw_raw(p + 5, 512); /* sector size */
2246 stw_raw(p + 6, s->sectors);
2247 padstr((uint8_t *)(p + 10), "QM00001", 20); /* serial number */
2248 stw_raw(p + 20, 3); /* buffer type */
2249 stw_raw(p + 21, 512); /* cache size in sectors */
2250 stw_raw(p + 22, 4); /* ecc bytes */
2251 padstr((uint8_t *)(p + 23), QEMU_VERSION, 8); /* firmware version */
2252 padstr((uint8_t *)(p + 27), "QEMU CD-ROM", 40); /* model */
2253 stw_raw(p + 48, 1); /* dword I/O (XXX: should not be set on CDROM) */
2254 stw_raw(p + 49, 1 << 9); /* LBA supported, no DMA */
2255 stw_raw(p + 53, 3); /* words 64-70, 54-58 valid */
2256 stw_raw(p + 63, 0x103); /* DMA modes XXX: may be incorrect */
2257 stw_raw(p + 64, 1); /* PIO modes */
2258 stw_raw(p + 65, 0xb4); /* minimum DMA multiword tx cycle time */
2259 stw_raw(p + 66, 0xb4); /* recommended DMA multiword tx cycle time */
2260 stw_raw(p + 67, 0x12c); /* minimum PIO cycle time without flow control */
2261 stw_raw(p + 68, 0xb4); /* minimum PIO cycle time with IORDY flow control */
2263 stw_raw(p + 71, 30); /* in ns */
2264 stw_raw(p + 72, 30); /* in ns */
2266 stw_raw(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */
2269 static void ide_set_signature(IDEState *s)
2271 s->select &= 0xf0; /* clear head */
2272 /* put signature */
2273 s->nsector = 1;
2274 s->sector = 1;
2275 if (s->is_cdrom) {
2276 s->lcyl = 0x14;
2277 s->hcyl = 0xeb;
2278 } else if (s->bs) {
2279 s->lcyl = 0;
2280 s->hcyl = 0;
2281 } else {
2282 s->lcyl = 0xff;
2283 s->hcyl = 0xff;
2287 static inline void ide_abort_command(IDEState *s)
2289 s->status = READY_STAT | ERR_STAT;
2290 s->error = ABRT_ERR;
2293 static inline void ide_set_irq(IDEState *s)
2295 if (!(s->cmd & IDE_CMD_DISABLE_IRQ)) {
2296 pic_set_irq(s->irq, 1);
2300 /* prepare data transfer and tell what to do after */
2301 static void ide_transfer_start(IDEState *s, uint8_t *buf, int size,
2302 EndTransferFunc *end_transfer_func)
2304 s->end_transfer_func = end_transfer_func;
2305 s->data_ptr = buf;
2306 s->data_end = buf + size;
2307 s->status |= DRQ_STAT;
2310 static void ide_transfer_stop(IDEState *s)
2312 s->end_transfer_func = ide_transfer_stop;
2313 s->data_ptr = s->io_buffer;
2314 s->data_end = s->io_buffer;
2315 s->status &= ~DRQ_STAT;
2318 static int64_t ide_get_sector(IDEState *s)
2320 int64_t sector_num;
2321 if (s->select & 0x40) {
2322 /* lba */
2323 sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) |
2324 (s->lcyl << 8) | s->sector;
2325 } else {
2326 sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors +
2327 (s->select & 0x0f) * s->sectors +
2328 (s->sector - 1);
2330 return sector_num;
2333 static void ide_set_sector(IDEState *s, int64_t sector_num)
2335 unsigned int cyl, r;
2336 if (s->select & 0x40) {
2337 s->select = (s->select & 0xf0) | (sector_num >> 24);
2338 s->hcyl = (sector_num >> 16);
2339 s->lcyl = (sector_num >> 8);
2340 s->sector = (sector_num);
2341 } else {
2342 cyl = sector_num / (s->heads * s->sectors);
2343 r = sector_num % (s->heads * s->sectors);
2344 s->hcyl = cyl >> 8;
2345 s->lcyl = cyl;
2346 s->select = (s->select & 0xf0) | (r / s->sectors);
2347 s->sector = (r % s->sectors) + 1;
2351 static void ide_sector_read(IDEState *s)
2353 int64_t sector_num;
2354 int ret, n;
2356 s->status = READY_STAT | SEEK_STAT;
2357 sector_num = ide_get_sector(s);
2358 n = s->nsector;
2359 if (n == 0) {
2360 /* no more sector to read from disk */
2361 ide_transfer_stop(s);
2362 } else {
2363 #if defined(DEBUG_IDE)
2364 printf("read sector=%Ld\n", sector_num);
2365 #endif
2366 if (n > s->req_nb_sectors)
2367 n = s->req_nb_sectors;
2368 ret = bdrv_read(s->bs, sector_num, s->io_buffer, n);
2369 ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_read);
2370 ide_set_irq(s);
2371 ide_set_sector(s, sector_num + n);
2372 s->nsector -= n;
2376 static void ide_sector_write(IDEState *s)
2378 int64_t sector_num;
2379 int ret, n, n1;
2381 s->status = READY_STAT | SEEK_STAT;
2382 sector_num = ide_get_sector(s);
2383 #if defined(DEBUG_IDE)
2384 printf("write sector=%Ld\n", sector_num);
2385 #endif
2386 n = s->nsector;
2387 if (n > s->req_nb_sectors)
2388 n = s->req_nb_sectors;
2389 ret = bdrv_write(s->bs, sector_num, s->io_buffer, n);
2390 s->nsector -= n;
2391 if (s->nsector == 0) {
2392 /* no more sector to write */
2393 ide_transfer_stop(s);
2394 } else {
2395 n1 = s->nsector;
2396 if (n1 > s->req_nb_sectors)
2397 n1 = s->req_nb_sectors;
2398 ide_transfer_start(s, s->io_buffer, 512 * n1, ide_sector_write);
2400 ide_set_sector(s, sector_num + n);
2401 ide_set_irq(s);
2404 static void ide_atapi_cmd_ok(IDEState *s)
2406 s->error = 0;
2407 s->status = READY_STAT;
2408 s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
2409 ide_set_irq(s);
2412 static void ide_atapi_cmd_error(IDEState *s, int sense_key, int asc)
2414 #ifdef DEBUG_IDE_ATAPI
2415 printf("atapi_cmd_error: sense=0x%x asc=0x%x\n", sense_key, asc);
2416 #endif
2417 s->error = sense_key << 4;
2418 s->status = READY_STAT | ERR_STAT;
2419 s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
2420 s->sense_key = sense_key;
2421 s->asc = asc;
2422 ide_set_irq(s);
2425 static inline void cpu_to_ube16(uint8_t *buf, int val)
2427 buf[0] = val >> 8;
2428 buf[1] = val;
2431 static inline void cpu_to_ube32(uint8_t *buf, unsigned int val)
2433 buf[0] = val >> 24;
2434 buf[1] = val >> 16;
2435 buf[2] = val >> 8;
2436 buf[3] = val;
2439 static inline int ube16_to_cpu(const uint8_t *buf)
2441 return (buf[0] << 8) | buf[1];
2444 static inline int ube32_to_cpu(const uint8_t *buf)
2446 return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
2449 /* The whole ATAPI transfer logic is handled in this function */
2450 static void ide_atapi_cmd_reply_end(IDEState *s)
2452 int byte_count_limit, size;
2453 #ifdef DEBUG_IDE_ATAPI
2454 printf("reply: tx_size=%d elem_tx_size=%d index=%d\n",
2455 s->packet_transfer_size,
2456 s->elementary_transfer_size,
2457 s->io_buffer_index);
2458 #endif
2459 if (s->packet_transfer_size <= 0) {
2460 /* end of transfer */
2461 ide_transfer_stop(s);
2462 s->status = READY_STAT;
2463 s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO | ATAPI_INT_REASON_CD;
2464 ide_set_irq(s);
2465 #ifdef DEBUG_IDE_ATAPI
2466 printf("status=0x%x\n", s->status);
2467 #endif
2468 } else {
2469 /* see if a new sector must be read */
2470 if (s->lba != -1 && s->io_buffer_index >= 2048) {
2471 bdrv_read(s->bs, (int64_t)s->lba << 2, s->io_buffer, 4);
2472 s->lba++;
2473 s->io_buffer_index = 0;
2475 if (s->elementary_transfer_size > 0) {
2476 /* there are some data left to transmit in this elementary
2477 transfer */
2478 size = 2048 - s->io_buffer_index;
2479 if (size > s->elementary_transfer_size)
2480 size = s->elementary_transfer_size;
2481 ide_transfer_start(s, s->io_buffer + s->io_buffer_index,
2482 size, ide_atapi_cmd_reply_end);
2483 s->packet_transfer_size -= size;
2484 s->elementary_transfer_size -= size;
2485 s->io_buffer_index += size;
2486 } else {
2487 /* a new transfer is needed */
2488 s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO;
2489 byte_count_limit = s->lcyl | (s->hcyl << 8);
2490 #ifdef DEBUG_IDE_ATAPI
2491 printf("byte_count_limit=%d\n", byte_count_limit);
2492 #endif
2493 if (byte_count_limit == 0xffff)
2494 byte_count_limit--;
2495 size = s->packet_transfer_size;
2496 if (size > byte_count_limit) {
2497 /* byte count limit must be even if this case */
2498 if (byte_count_limit & 1)
2499 byte_count_limit--;
2500 size = byte_count_limit;
2501 } else {
2502 s->lcyl = size;
2503 s->hcyl = size >> 8;
2505 s->elementary_transfer_size = size;
2506 /* we cannot transmit more than one sector at a time */
2507 if (s->lba != -1) {
2508 if (size > (2048 - s->io_buffer_index))
2509 size = (2048 - s->io_buffer_index);
2511 ide_transfer_start(s, s->io_buffer + s->io_buffer_index,
2512 size, ide_atapi_cmd_reply_end);
2513 s->packet_transfer_size -= size;
2514 s->elementary_transfer_size -= size;
2515 s->io_buffer_index += size;
2516 ide_set_irq(s);
2517 #ifdef DEBUG_IDE_ATAPI
2518 printf("status=0x%x\n", s->status);
2519 #endif
2524 /* send a reply of 'size' bytes in s->io_buffer to an ATAPI command */
2525 static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)
2527 if (size > max_size)
2528 size = max_size;
2529 s->lba = -1; /* no sector read */
2530 s->packet_transfer_size = size;
2531 s->elementary_transfer_size = 0;
2532 s->io_buffer_index = 0;
2534 s->status = READY_STAT;
2535 ide_atapi_cmd_reply_end(s);
2538 /* start a CD-CDROM read command */
2539 static void ide_atapi_cmd_read(IDEState *s, int lba, int nb_sectors)
2541 #ifdef DEBUG_IDE_ATAPI
2542 printf("read: LBA=%d nb_sectors=%d\n", lba, nb_sectors);
2543 #endif
2544 s->lba = lba;
2545 s->packet_transfer_size = nb_sectors * 2048;
2546 s->elementary_transfer_size = 0;
2547 s->io_buffer_index = 2048;
2549 s->status = READY_STAT;
2550 ide_atapi_cmd_reply_end(s);
2553 /* same toc as bochs. Return -1 if error or the toc length */
2554 static int cdrom_read_toc(IDEState *s, uint8_t *buf, int msf, int start_track)
2556 uint8_t *q;
2557 int nb_sectors, len;
2559 if (start_track > 1 && start_track != 0xaa)
2560 return -1;
2561 q = buf + 2;
2562 *q++ = 1;
2563 *q++ = 1;
2564 if (start_track <= 1) {
2565 *q++ = 0; /* reserved */
2566 *q++ = 0x14; /* ADR, control */
2567 *q++ = 1; /* track number */
2568 *q++ = 0; /* reserved */
2569 if (msf) {
2570 *q++ = 0; /* reserved */
2571 *q++ = 0; /* minute */
2572 *q++ = 2; /* second */
2573 *q++ = 0; /* frame */
2574 } else {
2575 /* sector 0 */
2576 cpu_to_ube32(q, 0);
2577 q += 4;
2580 /* lead out track */
2581 *q++ = 0; /* reserved */
2582 *q++ = 0x16; /* ADR, control */
2583 *q++ = 0xaa; /* track number */
2584 *q++ = 0; /* reserved */
2585 nb_sectors = s->nb_sectors >> 2;
2586 if (msf) {
2587 *q++ = 0; /* reserved */
2588 *q++ = ((nb_sectors + 150) / 75) / 60;
2589 *q++ = ((nb_sectors + 150) / 75) % 60;
2590 *q++ = (nb_sectors + 150) % 75;
2591 } else {
2592 cpu_to_ube32(q, nb_sectors);
2593 q += 4;
2595 len = q - buf;
2596 cpu_to_ube16(buf, len - 2);
2597 return len;
2600 static void ide_atapi_cmd(IDEState *s)
2602 const uint8_t *packet;
2603 uint8_t *buf;
2604 int max_len;
2606 packet = s->io_buffer;
2607 buf = s->io_buffer;
2608 #ifdef DEBUG_IDE_ATAPI
2610 int i;
2611 printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));
2612 for(i = 0; i < ATAPI_PACKET_SIZE; i++) {
2613 printf(" %02x", packet[i]);
2615 printf("\n");
2617 #endif
2618 switch(s->io_buffer[0]) {
2619 case GPCMD_TEST_UNIT_READY:
2620 if (s->bs) {
2621 ide_atapi_cmd_ok(s);
2622 } else {
2623 ide_atapi_cmd_error(s, SENSE_NOT_READY,
2624 ASC_MEDIUM_NOT_PRESENT);
2626 break;
2627 case GPCMD_MODE_SENSE_10:
2629 int action, code;
2630 max_len = ube16_to_cpu(packet + 7);
2631 action = packet[2] >> 6;
2632 code = packet[2] & 0x3f;
2633 switch(action) {
2634 case 0: /* current values */
2635 switch(code) {
2636 case 0x01: /* error recovery */
2637 cpu_to_ube16(&buf[0], 16 + 6);
2638 buf[2] = 0x70;
2639 buf[3] = 0;
2640 buf[4] = 0;
2641 buf[5] = 0;
2642 buf[6] = 0;
2643 buf[7] = 0;
2645 buf[8] = 0x01;
2646 buf[9] = 0x06;
2647 buf[10] = 0x00;
2648 buf[11] = 0x05;
2649 buf[12] = 0x00;
2650 buf[13] = 0x00;
2651 buf[14] = 0x00;
2652 buf[15] = 0x00;
2653 ide_atapi_cmd_reply(s, 16, max_len);
2654 break;
2655 case 0x2a:
2656 cpu_to_ube16(&buf[0], 28 + 6);
2657 buf[2] = 0x70;
2658 buf[3] = 0;
2659 buf[4] = 0;
2660 buf[5] = 0;
2661 buf[6] = 0;
2662 buf[7] = 0;
2664 buf[8] = 0x2a;
2665 buf[9] = 0x12;
2666 buf[10] = 0x00;
2667 buf[11] = 0x00;
2669 buf[12] = 0x70;
2670 buf[13] = 3 << 5;
2671 buf[14] = (1 << 0) | (1 << 3) | (1 << 5);
2672 if (s->cdrom_locked)
2673 buf[6] |= 1 << 1;
2674 buf[15] = 0x00;
2675 cpu_to_ube16(&buf[16], 706);
2676 buf[18] = 0;
2677 buf[19] = 2;
2678 cpu_to_ube16(&buf[20], 512);
2679 cpu_to_ube16(&buf[22], 706);
2680 buf[24] = 0;
2681 buf[25] = 0;
2682 buf[26] = 0;
2683 buf[27] = 0;
2684 ide_atapi_cmd_reply(s, 28, max_len);
2685 break;
2686 default:
2687 goto error_cmd;
2689 break;
2690 case 1: /* changeable values */
2691 goto error_cmd;
2692 case 2: /* default values */
2693 goto error_cmd;
2694 default:
2695 case 3: /* saved values */
2696 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2697 ASC_SAVING_PARAMETERS_NOT_SUPPORTED);
2698 break;
2701 break;
2702 case GPCMD_REQUEST_SENSE:
2703 max_len = packet[4];
2704 memset(buf, 0, 18);
2705 buf[0] = 0x70 | (1 << 7);
2706 buf[2] = s->sense_key;
2707 buf[7] = 10;
2708 buf[12] = s->asc;
2709 ide_atapi_cmd_reply(s, 18, max_len);
2710 break;
2711 case GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
2712 if (s->bs) {
2713 s->cdrom_locked = packet[4] & 1;
2714 ide_atapi_cmd_ok(s);
2715 } else {
2716 ide_atapi_cmd_error(s, SENSE_NOT_READY,
2717 ASC_MEDIUM_NOT_PRESENT);
2719 break;
2720 case GPCMD_READ_10:
2721 case GPCMD_READ_12:
2723 int nb_sectors, lba;
2725 if (!s->bs) {
2726 ide_atapi_cmd_error(s, SENSE_NOT_READY,
2727 ASC_MEDIUM_NOT_PRESENT);
2728 break;
2730 if (packet[0] == GPCMD_READ_10)
2731 nb_sectors = ube16_to_cpu(packet + 7);
2732 else
2733 nb_sectors = ube32_to_cpu(packet + 6);
2734 lba = ube32_to_cpu(packet + 2);
2735 if (nb_sectors == 0) {
2736 ide_atapi_cmd_ok(s);
2737 break;
2739 if (((int64_t)(lba + nb_sectors) << 2) > s->nb_sectors) {
2740 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2741 ASC_LOGICAL_BLOCK_OOR);
2742 break;
2744 ide_atapi_cmd_read(s, lba, nb_sectors);
2746 break;
2747 case GPCMD_SEEK:
2749 int lba;
2750 if (!s->bs) {
2751 ide_atapi_cmd_error(s, SENSE_NOT_READY,
2752 ASC_MEDIUM_NOT_PRESENT);
2753 break;
2755 lba = ube32_to_cpu(packet + 2);
2756 if (((int64_t)lba << 2) > s->nb_sectors) {
2757 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2758 ASC_LOGICAL_BLOCK_OOR);
2759 break;
2761 ide_atapi_cmd_ok(s);
2763 break;
2764 case GPCMD_START_STOP_UNIT:
2766 int start, eject;
2767 start = packet[4] & 1;
2768 eject = (packet[4] >> 1) & 1;
2770 /* XXX: currently none implemented */
2771 ide_atapi_cmd_ok(s);
2773 break;
2774 case GPCMD_MECHANISM_STATUS:
2776 max_len = ube16_to_cpu(packet + 8);
2777 cpu_to_ube16(buf, 0);
2778 /* no current LBA */
2779 buf[2] = 0;
2780 buf[3] = 0;
2781 buf[4] = 0;
2782 buf[5] = 1;
2783 cpu_to_ube16(buf + 6, 0);
2784 ide_atapi_cmd_reply(s, 8, max_len);
2786 break;
2787 case GPCMD_READ_TOC_PMA_ATIP:
2789 int format, msf, start_track, len;
2791 if (!s->bs) {
2792 ide_atapi_cmd_error(s, SENSE_NOT_READY,
2793 ASC_MEDIUM_NOT_PRESENT);
2794 break;
2796 max_len = ube16_to_cpu(packet + 7);
2797 format = packet[9] >> 6;
2798 msf = (packet[1] >> 1) & 1;
2799 start_track = packet[6];
2800 switch(format) {
2801 case 0:
2802 len = cdrom_read_toc(s, buf, msf, start_track);
2803 if (len < 0)
2804 goto error_cmd;
2805 ide_atapi_cmd_reply(s, len, max_len);
2806 break;
2807 case 1:
2808 /* multi session : only a single session defined */
2809 memset(buf, 0, 12);
2810 buf[1] = 0x0a;
2811 buf[2] = 0x01;
2812 buf[3] = 0x01;
2813 ide_atapi_cmd_reply(s, 12, max_len);
2814 break;
2815 default:
2816 goto error_cmd;
2819 break;
2820 case GPCMD_READ_CDVD_CAPACITY:
2821 if (!s->bs) {
2822 ide_atapi_cmd_error(s, SENSE_NOT_READY,
2823 ASC_MEDIUM_NOT_PRESENT);
2824 break;
2826 /* NOTE: it is really the number of sectors minus 1 */
2827 cpu_to_ube32(buf, (s->nb_sectors >> 2) - 1);
2828 cpu_to_ube32(buf + 4, 2048);
2829 ide_atapi_cmd_reply(s, 8, 8);
2830 break;
2831 default:
2832 error_cmd:
2833 ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,
2834 ASC_INV_FIELD_IN_CMD_PACKET);
2835 break;
2839 void ide_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
2841 IDEState *ide_if = get_ide_interface(addr);
2842 IDEState *s = ide_if->cur_drive;
2843 int unit, n;
2845 #ifdef DEBUG_IDE
2846 printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
2847 #endif
2848 addr &= 7;
2849 switch(addr) {
2850 case 0:
2851 break;
2852 case 1:
2853 s->feature = val;
2854 break;
2855 case 2:
2856 if (val == 0)
2857 val = 256;
2858 s->nsector = val;
2859 break;
2860 case 3:
2861 s->sector = val;
2862 break;
2863 case 4:
2864 s->lcyl = val;
2865 break;
2866 case 5:
2867 s->hcyl = val;
2868 break;
2869 case 6:
2870 /* select drive */
2871 unit = (val >> 4) & 1;
2872 s = ide_if + unit;
2873 ide_if->cur_drive = s;
2874 s->select = val;
2875 break;
2876 default:
2877 case 7:
2878 /* command */
2879 #if defined(DEBUG_IDE)
2880 printf("ide: CMD=%02x\n", val);
2881 #endif
2882 switch(val) {
2883 case WIN_IDENTIFY:
2884 if (s->bs && !s->is_cdrom) {
2885 ide_identify(s);
2886 s->status = READY_STAT;
2887 ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
2888 } else {
2889 if (s->is_cdrom) {
2890 ide_set_signature(s);
2892 ide_abort_command(s);
2894 ide_set_irq(s);
2895 break;
2896 case WIN_SPECIFY:
2897 case WIN_RECAL:
2898 s->status = READY_STAT;
2899 ide_set_irq(s);
2900 break;
2901 case WIN_SETMULT:
2902 if (s->nsector > MAX_MULT_SECTORS ||
2903 s->nsector == 0 ||
2904 (s->nsector & (s->nsector - 1)) != 0) {
2905 ide_abort_command(s);
2906 } else {
2907 s->mult_sectors = s->nsector;
2908 s->status = READY_STAT;
2910 ide_set_irq(s);
2911 break;
2912 case WIN_READ:
2913 case WIN_READ_ONCE:
2914 s->req_nb_sectors = 1;
2915 ide_sector_read(s);
2916 break;
2917 case WIN_WRITE:
2918 case WIN_WRITE_ONCE:
2919 s->status = SEEK_STAT;
2920 s->req_nb_sectors = 1;
2921 ide_transfer_start(s, s->io_buffer, 512, ide_sector_write);
2922 break;
2923 case WIN_MULTREAD:
2924 if (!s->mult_sectors)
2925 goto abort_cmd;
2926 s->req_nb_sectors = s->mult_sectors;
2927 ide_sector_read(s);
2928 break;
2929 case WIN_MULTWRITE:
2930 if (!s->mult_sectors)
2931 goto abort_cmd;
2932 s->status = SEEK_STAT;
2933 s->req_nb_sectors = s->mult_sectors;
2934 n = s->nsector;
2935 if (n > s->req_nb_sectors)
2936 n = s->req_nb_sectors;
2937 ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write);
2938 break;
2939 case WIN_READ_NATIVE_MAX:
2940 ide_set_sector(s, s->nb_sectors - 1);
2941 s->status = READY_STAT;
2942 ide_set_irq(s);
2943 break;
2945 /* ATAPI commands */
2946 case WIN_PIDENTIFY:
2947 if (s->is_cdrom) {
2948 ide_atapi_identify(s);
2949 s->status = READY_STAT;
2950 ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);
2951 } else {
2952 ide_abort_command(s);
2954 ide_set_irq(s);
2955 break;
2956 case WIN_SRST:
2957 if (!s->is_cdrom)
2958 goto abort_cmd;
2959 ide_set_signature(s);
2960 s->status = READY_STAT;
2961 s->error = 0x01;
2962 break;
2963 case WIN_PACKETCMD:
2964 if (!s->is_cdrom)
2965 goto abort_cmd;
2966 /* DMA or overlapping commands not supported */
2967 if ((s->feature & 0x03) != 0)
2968 goto abort_cmd;
2969 s->nsector = 1;
2970 ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE,
2971 ide_atapi_cmd);
2972 break;
2973 default:
2974 abort_cmd:
2975 ide_abort_command(s);
2976 ide_set_irq(s);
2977 break;
2982 uint32_t ide_ioport_read(CPUX86State *env, uint32_t addr1)
2984 IDEState *s = get_ide_interface(addr1)->cur_drive;
2985 uint32_t addr;
2986 int ret;
2988 addr = addr1 & 7;
2989 switch(addr) {
2990 case 0:
2991 ret = 0xff;
2992 break;
2993 case 1:
2994 ret = s->error;
2995 break;
2996 case 2:
2997 ret = s->nsector & 0xff;
2998 break;
2999 case 3:
3000 ret = s->sector;
3001 break;
3002 case 4:
3003 ret = s->lcyl;
3004 break;
3005 case 5:
3006 ret = s->hcyl;
3007 break;
3008 case 6:
3009 ret = s->select;
3010 break;
3011 default:
3012 case 7:
3013 ret = s->status;
3014 pic_set_irq(s->irq, 0);
3015 break;
3017 #ifdef DEBUG_IDE
3018 printf("ide: read addr=0x%x val=%02x\n", addr1, ret);
3019 #endif
3020 return ret;
3023 uint32_t ide_status_read(CPUX86State *env, uint32_t addr)
3025 IDEState *s = get_ide_interface(addr)->cur_drive;
3026 int ret;
3027 ret = s->status;
3028 #ifdef DEBUG_IDE
3029 printf("ide: read status addr=0x%x val=%02x\n", addr, ret);
3030 #endif
3031 return ret;
3034 void ide_cmd_write(CPUX86State *env, uint32_t addr, uint32_t val)
3036 IDEState *ide_if = get_ide_interface(addr);
3037 IDEState *s;
3038 int i;
3040 #ifdef DEBUG_IDE
3041 printf("ide: write control addr=0x%x val=%02x\n", addr, val);
3042 #endif
3043 /* common for both drives */
3044 if (!(ide_if[0].cmd & IDE_CMD_RESET) &&
3045 (val & IDE_CMD_RESET)) {
3046 /* reset low to high */
3047 for(i = 0;i < 2; i++) {
3048 s = &ide_if[i];
3049 s->status = BUSY_STAT | SEEK_STAT;
3050 s->error = 0x01;
3052 } else if ((ide_if[0].cmd & IDE_CMD_RESET) &&
3053 !(val & IDE_CMD_RESET)) {
3054 /* high to low */
3055 for(i = 0;i < 2; i++) {
3056 s = &ide_if[i];
3057 s->status = READY_STAT;
3058 ide_set_signature(s);
3062 ide_if[0].cmd = val;
3063 ide_if[1].cmd = val;
3066 void ide_data_writew(CPUX86State *env, uint32_t addr, uint32_t val)
3068 IDEState *s = get_ide_interface(addr)->cur_drive;
3069 uint8_t *p;
3071 p = s->data_ptr;
3072 *(uint16_t *)p = tswap16(val);
3073 p += 2;
3074 s->data_ptr = p;
3075 if (p >= s->data_end)
3076 s->end_transfer_func(s);
3079 uint32_t ide_data_readw(CPUX86State *env, uint32_t addr)
3081 IDEState *s = get_ide_interface(addr)->cur_drive;
3082 uint8_t *p;
3083 int ret;
3084 p = s->data_ptr;
3085 ret = tswap16(*(uint16_t *)p);
3086 p += 2;
3087 s->data_ptr = p;
3088 if (p >= s->data_end)
3089 s->end_transfer_func(s);
3090 return ret;
3093 void ide_data_writel(CPUX86State *env, uint32_t addr, uint32_t val)
3095 IDEState *s = get_ide_interface(addr)->cur_drive;
3096 uint8_t *p;
3098 p = s->data_ptr;
3099 *(uint32_t *)p = tswap32(val);
3100 p += 4;
3101 s->data_ptr = p;
3102 if (p >= s->data_end)
3103 s->end_transfer_func(s);
3106 uint32_t ide_data_readl(CPUX86State *env, uint32_t addr)
3108 IDEState *s = get_ide_interface(addr)->cur_drive;
3109 uint8_t *p;
3110 int ret;
3112 p = s->data_ptr;
3113 ret = tswap32(*(uint32_t *)p);
3114 p += 4;
3115 s->data_ptr = p;
3116 if (p >= s->data_end)
3117 s->end_transfer_func(s);
3118 return ret;
3121 void ide_reset(IDEState *s)
3123 s->mult_sectors = MAX_MULT_SECTORS;
3124 s->cur_drive = s;
3125 s->select = 0xa0;
3126 s->status = READY_STAT;
3127 ide_set_signature(s);
3130 struct partition {
3131 uint8_t boot_ind; /* 0x80 - active */
3132 uint8_t head; /* starting head */
3133 uint8_t sector; /* starting sector */
3134 uint8_t cyl; /* starting cylinder */
3135 uint8_t sys_ind; /* What partition type */
3136 uint8_t end_head; /* end head */
3137 uint8_t end_sector; /* end sector */
3138 uint8_t end_cyl; /* end cylinder */
3139 uint32_t start_sect; /* starting sector counting from 0 */
3140 uint32_t nr_sects; /* nr of sectors in partition */
3141 } __attribute__((packed));
3143 /* try to guess the IDE geometry from the MSDOS partition table */
3144 void ide_guess_geometry(IDEState *s)
3146 uint8_t buf[512];
3147 int ret, i;
3148 struct partition *p;
3149 uint32_t nr_sects;
3151 if (s->cylinders != 0)
3152 return;
3153 ret = bdrv_read(s->bs, 0, buf, 1);
3154 if (ret < 0)
3155 return;
3156 /* test msdos magic */
3157 if (buf[510] != 0x55 || buf[511] != 0xaa)
3158 return;
3159 for(i = 0; i < 4; i++) {
3160 p = ((struct partition *)(buf + 0x1be)) + i;
3161 nr_sects = tswap32(p->nr_sects);
3162 if (nr_sects && p->end_head) {
3163 /* We make the assumption that the partition terminates on
3164 a cylinder boundary */
3165 s->heads = p->end_head + 1;
3166 s->sectors = p->end_sector & 63;
3167 s->cylinders = s->nb_sectors / (s->heads * s->sectors);
3168 #if 0
3169 printf("guessed partition: CHS=%d %d %d\n",
3170 s->cylinders, s->heads, s->sectors);
3171 #endif
3176 void ide_init(void)
3178 IDEState *s;
3179 int i, cylinders, iobase, iobase2;
3180 int64_t nb_sectors;
3181 static const int ide_iobase[2] = { 0x1f0, 0x170 };
3182 static const int ide_iobase2[2] = { 0x3f6, 0x376 };
3183 static const int ide_irq[2] = { 14, 15 };
3185 for(i = 0; i < MAX_DISKS; i++) {
3186 s = &ide_state[i];
3187 s->bs = bs_table[i];
3188 if (s->bs) {
3189 bdrv_get_geometry(s->bs, &nb_sectors);
3190 s->nb_sectors = nb_sectors;
3191 ide_guess_geometry(s);
3192 if (s->cylinders == 0) {
3193 /* if no geometry, use a LBA compatible one */
3194 cylinders = nb_sectors / (16 * 63);
3195 if (cylinders > 16383)
3196 cylinders = 16383;
3197 else if (cylinders < 2)
3198 cylinders = 2;
3199 s->cylinders = cylinders;
3200 s->heads = 16;
3201 s->sectors = 63;
3204 s->irq = ide_irq[i >> 1];
3205 ide_reset(s);
3207 for(i = 0; i < (MAX_DISKS / 2); i++) {
3208 iobase = ide_iobase[i];
3209 iobase2 = ide_iobase2[i];
3210 ide_table[iobase >> 3] = &ide_state[2 * i];
3211 if (ide_iobase2[i])
3212 ide_table[iobase2 >> 3] = &ide_state[2 * i];
3213 register_ioport_write(iobase, 8, ide_ioport_write, 1);
3214 register_ioport_read(iobase, 8, ide_ioport_read, 1);
3215 register_ioport_read(iobase2, 1, ide_status_read, 1);
3216 register_ioport_write(iobase2, 1, ide_cmd_write, 1);
3218 /* data ports */
3219 register_ioport_write(iobase, 2, ide_data_writew, 2);
3220 register_ioport_read(iobase, 2, ide_data_readw, 2);
3221 register_ioport_write(iobase, 4, ide_data_writel, 4);
3222 register_ioport_read(iobase, 4, ide_data_readl, 4);
3226 /***********************************************************/
3227 /* keyboard emulation */
3229 /* Keyboard Controller Commands */
3230 #define KBD_CCMD_READ_MODE 0x20 /* Read mode bits */
3231 #define KBD_CCMD_WRITE_MODE 0x60 /* Write mode bits */
3232 #define KBD_CCMD_GET_VERSION 0xA1 /* Get controller version */
3233 #define KBD_CCMD_MOUSE_DISABLE 0xA7 /* Disable mouse interface */
3234 #define KBD_CCMD_MOUSE_ENABLE 0xA8 /* Enable mouse interface */
3235 #define KBD_CCMD_TEST_MOUSE 0xA9 /* Mouse interface test */
3236 #define KBD_CCMD_SELF_TEST 0xAA /* Controller self test */
3237 #define KBD_CCMD_KBD_TEST 0xAB /* Keyboard interface test */
3238 #define KBD_CCMD_KBD_DISABLE 0xAD /* Keyboard interface disable */
3239 #define KBD_CCMD_KBD_ENABLE 0xAE /* Keyboard interface enable */
3240 #define KBD_CCMD_READ_INPORT 0xC0 /* read input port */
3241 #define KBD_CCMD_READ_OUTPORT 0xD0 /* read output port */
3242 #define KBD_CCMD_WRITE_OUTPORT 0xD1 /* write output port */
3243 #define KBD_CCMD_WRITE_OBUF 0xD2
3244 #define KBD_CCMD_WRITE_AUX_OBUF 0xD3 /* Write to output buffer as if
3245 initiated by the auxiliary device */
3246 #define KBD_CCMD_WRITE_MOUSE 0xD4 /* Write the following byte to the mouse */
3247 #define KBD_CCMD_DISABLE_A20 0xDD /* HP vectra only ? */
3248 #define KBD_CCMD_ENABLE_A20 0xDF /* HP vectra only ? */
3249 #define KBD_CCMD_RESET 0xFE
3251 /* Keyboard Commands */
3252 #define KBD_CMD_SET_LEDS 0xED /* Set keyboard leds */
3253 #define KBD_CMD_ECHO 0xEE
3254 #define KBD_CMD_SET_RATE 0xF3 /* Set typematic rate */
3255 #define KBD_CMD_ENABLE 0xF4 /* Enable scanning */
3256 #define KBD_CMD_RESET_DISABLE 0xF5 /* reset and disable scanning */
3257 #define KBD_CMD_RESET_ENABLE 0xF6 /* reset and enable scanning */
3258 #define KBD_CMD_RESET 0xFF /* Reset */
3260 /* Keyboard Replies */
3261 #define KBD_REPLY_POR 0xAA /* Power on reset */
3262 #define KBD_REPLY_ACK 0xFA /* Command ACK */
3263 #define KBD_REPLY_RESEND 0xFE /* Command NACK, send the cmd again */
3265 /* Status Register Bits */
3266 #define KBD_STAT_OBF 0x01 /* Keyboard output buffer full */
3267 #define KBD_STAT_IBF 0x02 /* Keyboard input buffer full */
3268 #define KBD_STAT_SELFTEST 0x04 /* Self test successful */
3269 #define KBD_STAT_CMD 0x08 /* Last write was a command write (0=data) */
3270 #define KBD_STAT_UNLOCKED 0x10 /* Zero if keyboard locked */
3271 #define KBD_STAT_MOUSE_OBF 0x20 /* Mouse output buffer full */
3272 #define KBD_STAT_GTO 0x40 /* General receive/xmit timeout */
3273 #define KBD_STAT_PERR 0x80 /* Parity error */
3275 /* Controller Mode Register Bits */
3276 #define KBD_MODE_KBD_INT 0x01 /* Keyboard data generate IRQ1 */
3277 #define KBD_MODE_MOUSE_INT 0x02 /* Mouse data generate IRQ12 */
3278 #define KBD_MODE_SYS 0x04 /* The system flag (?) */
3279 #define KBD_MODE_NO_KEYLOCK 0x08 /* The keylock doesn't affect the keyboard if set */
3280 #define KBD_MODE_DISABLE_KBD 0x10 /* Disable keyboard interface */
3281 #define KBD_MODE_DISABLE_MOUSE 0x20 /* Disable mouse interface */
3282 #define KBD_MODE_KCC 0x40 /* Scan code conversion to PC format */
3283 #define KBD_MODE_RFU 0x80
3285 /* Mouse Commands */
3286 #define AUX_SET_SCALE11 0xE6 /* Set 1:1 scaling */
3287 #define AUX_SET_SCALE21 0xE7 /* Set 2:1 scaling */
3288 #define AUX_SET_RES 0xE8 /* Set resolution */
3289 #define AUX_GET_SCALE 0xE9 /* Get scaling factor */
3290 #define AUX_SET_STREAM 0xEA /* Set stream mode */
3291 #define AUX_POLL 0xEB /* Poll */
3292 #define AUX_RESET_WRAP 0xEC /* Reset wrap mode */
3293 #define AUX_SET_WRAP 0xEE /* Set wrap mode */
3294 #define AUX_SET_REMOTE 0xF0 /* Set remote mode */
3295 #define AUX_GET_TYPE 0xF2 /* Get type */
3296 #define AUX_SET_SAMPLE 0xF3 /* Set sample rate */
3297 #define AUX_ENABLE_DEV 0xF4 /* Enable aux device */
3298 #define AUX_DISABLE_DEV 0xF5 /* Disable aux device */
3299 #define AUX_SET_DEFAULT 0xF6
3300 #define AUX_RESET 0xFF /* Reset aux device */
3301 #define AUX_ACK 0xFA /* Command byte ACK. */
3303 #define MOUSE_STATUS_REMOTE 0x40
3304 #define MOUSE_STATUS_ENABLED 0x20
3305 #define MOUSE_STATUS_SCALE21 0x10
3307 #define KBD_QUEUE_SIZE 256
3309 typedef struct {
3310 uint8_t data[KBD_QUEUE_SIZE];
3311 int rptr, wptr, count;
3312 } KBDQueue;
3314 typedef struct KBDState {
3315 KBDQueue queues[2];
3316 uint8_t write_cmd; /* if non zero, write data to port 60 is expected */
3317 uint8_t status;
3318 uint8_t mode;
3319 /* keyboard state */
3320 int kbd_write_cmd;
3321 int scan_enabled;
3322 /* mouse state */
3323 int mouse_write_cmd;
3324 uint8_t mouse_status;
3325 uint8_t mouse_resolution;
3326 uint8_t mouse_sample_rate;
3327 uint8_t mouse_wrap;
3328 uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */
3329 uint8_t mouse_detect_state;
3330 int mouse_dx; /* current values, needed for 'poll' mode */
3331 int mouse_dy;
3332 int mouse_dz;
3333 uint8_t mouse_buttons;
3334 } KBDState;
3336 KBDState kbd_state;
3337 int reset_requested;
3339 /* update irq and KBD_STAT_[MOUSE_]OBF */
3340 static void kbd_update_irq(KBDState *s)
3342 int irq12_level, irq1_level;
3344 irq1_level = 0;
3345 irq12_level = 0;
3346 s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);
3347 if (s->queues[0].count != 0 ||
3348 s->queues[1].count != 0) {
3349 s->status |= KBD_STAT_OBF;
3350 if (s->queues[1].count != 0) {
3351 s->status |= KBD_STAT_MOUSE_OBF;
3352 if (s->mode & KBD_MODE_MOUSE_INT)
3353 irq12_level = 1;
3354 } else {
3355 if (s->mode & KBD_MODE_KBD_INT)
3356 irq1_level = 1;
3359 pic_set_irq(1, irq1_level);
3360 pic_set_irq(12, irq12_level);
3363 static void kbd_queue(KBDState *s, int b, int aux)
3365 KBDQueue *q = &kbd_state.queues[aux];
3367 #if defined(DEBUG_MOUSE) || defined(DEBUG_KBD)
3368 if (aux)
3369 printf("mouse event: 0x%02x\n", b);
3370 #ifdef DEBUG_KBD
3371 else
3372 printf("kbd event: 0x%02x\n", b);
3373 #endif
3374 #endif
3375 if (q->count >= KBD_QUEUE_SIZE)
3376 return;
3377 q->data[q->wptr] = b;
3378 if (++q->wptr == KBD_QUEUE_SIZE)
3379 q->wptr = 0;
3380 q->count++;
3381 kbd_update_irq(s);
3384 void kbd_put_keycode(int keycode)
3386 KBDState *s = &kbd_state;
3387 kbd_queue(s, keycode, 0);
3390 uint32_t kbd_read_status(CPUX86State *env, uint32_t addr)
3392 KBDState *s = &kbd_state;
3393 int val;
3394 val = s->status;
3395 #if defined(DEBUG_KBD) && 0
3396 printf("kbd: read status=0x%02x\n", val);
3397 #endif
3398 return val;
3401 void kbd_write_command(CPUX86State *env, uint32_t addr, uint32_t val)
3403 KBDState *s = &kbd_state;
3405 #ifdef DEBUG_KBD
3406 printf("kbd: write cmd=0x%02x\n", val);
3407 #endif
3408 switch(val) {
3409 case KBD_CCMD_READ_MODE:
3410 kbd_queue(s, s->mode, 0);
3411 break;
3412 case KBD_CCMD_WRITE_MODE:
3413 case KBD_CCMD_WRITE_OBUF:
3414 case KBD_CCMD_WRITE_AUX_OBUF:
3415 case KBD_CCMD_WRITE_MOUSE:
3416 case KBD_CCMD_WRITE_OUTPORT:
3417 s->write_cmd = val;
3418 break;
3419 case KBD_CCMD_MOUSE_DISABLE:
3420 s->mode |= KBD_MODE_DISABLE_MOUSE;
3421 break;
3422 case KBD_CCMD_MOUSE_ENABLE:
3423 s->mode &= ~KBD_MODE_DISABLE_MOUSE;
3424 break;
3425 case KBD_CCMD_TEST_MOUSE:
3426 kbd_queue(s, 0x00, 0);
3427 break;
3428 case KBD_CCMD_SELF_TEST:
3429 s->status |= KBD_STAT_SELFTEST;
3430 kbd_queue(s, 0x55, 0);
3431 break;
3432 case KBD_CCMD_KBD_TEST:
3433 kbd_queue(s, 0x00, 0);
3434 break;
3435 case KBD_CCMD_KBD_DISABLE:
3436 s->mode |= KBD_MODE_DISABLE_KBD;
3437 break;
3438 case KBD_CCMD_KBD_ENABLE:
3439 s->mode &= ~KBD_MODE_DISABLE_KBD;
3440 break;
3441 case KBD_CCMD_READ_INPORT:
3442 kbd_queue(s, 0x00, 0);
3443 break;
3444 case KBD_CCMD_READ_OUTPORT:
3445 /* XXX: check that */
3446 val = 0x01 | (a20_enabled << 1);
3447 if (s->status & KBD_STAT_OBF)
3448 val |= 0x10;
3449 if (s->status & KBD_STAT_MOUSE_OBF)
3450 val |= 0x20;
3451 kbd_queue(s, val, 0);
3452 break;
3453 case KBD_CCMD_ENABLE_A20:
3454 cpu_x86_set_a20(env, 1);
3455 break;
3456 case KBD_CCMD_DISABLE_A20:
3457 cpu_x86_set_a20(env, 0);
3458 break;
3459 case KBD_CCMD_RESET:
3460 reset_requested = 1;
3461 cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
3462 break;
3463 default:
3464 fprintf(stderr, "qemu: unsupported keyboard cmd=0x%02x\n", val);
3465 break;
3469 uint32_t kbd_read_data(CPUX86State *env, uint32_t addr)
3471 KBDState *s = &kbd_state;
3472 KBDQueue *q;
3473 int val;
3475 q = &s->queues[0]; /* first check KBD data */
3476 if (q->count == 0)
3477 q = &s->queues[1]; /* then check AUX data */
3478 if (q->count == 0) {
3479 /* XXX: return something else ? */
3480 val = 0;
3481 } else {
3482 val = q->data[q->rptr];
3483 if (++q->rptr == KBD_QUEUE_SIZE)
3484 q->rptr = 0;
3485 q->count--;
3486 /* reading deasserts IRQ */
3487 if (q == &s->queues[0])
3488 pic_set_irq(1, 0);
3489 else
3490 pic_set_irq(12, 0);
3492 /* reassert IRQs if data left */
3493 kbd_update_irq(s);
3494 #ifdef DEBUG_KBD
3495 printf("kbd: read data=0x%02x\n", val);
3496 #endif
3497 return val;
3500 static void kbd_reset_keyboard(KBDState *s)
3502 s->scan_enabled = 1;
3505 static void kbd_write_keyboard(KBDState *s, int val)
3507 switch(s->kbd_write_cmd) {
3508 default:
3509 case -1:
3510 switch(val) {
3511 case 0x00:
3512 kbd_queue(s, KBD_REPLY_ACK, 0);
3513 break;
3514 case 0x05:
3515 kbd_queue(s, KBD_REPLY_RESEND, 0);
3516 break;
3517 case KBD_CMD_ECHO:
3518 kbd_queue(s, KBD_CMD_ECHO, 0);
3519 break;
3520 case KBD_CMD_ENABLE:
3521 s->scan_enabled = 1;
3522 kbd_queue(s, KBD_REPLY_ACK, 0);
3523 break;
3524 case KBD_CMD_SET_LEDS:
3525 case KBD_CMD_SET_RATE:
3526 s->kbd_write_cmd = val;
3527 kbd_queue(s, KBD_REPLY_ACK, 0);
3528 break;
3529 case KBD_CMD_RESET_DISABLE:
3530 kbd_reset_keyboard(s);
3531 s->scan_enabled = 0;
3532 kbd_queue(s, KBD_REPLY_ACK, 0);
3533 break;
3534 case KBD_CMD_RESET_ENABLE:
3535 kbd_reset_keyboard(s);
3536 s->scan_enabled = 1;
3537 kbd_queue(s, KBD_REPLY_ACK, 0);
3538 break;
3539 case KBD_CMD_RESET:
3540 kbd_reset_keyboard(s);
3541 kbd_queue(s, KBD_REPLY_ACK, 0);
3542 kbd_queue(s, KBD_REPLY_POR, 0);
3543 break;
3544 default:
3545 kbd_queue(s, KBD_REPLY_ACK, 0);
3546 break;
3548 break;
3549 case KBD_CMD_SET_LEDS:
3550 kbd_queue(s, KBD_REPLY_ACK, 0);
3551 s->kbd_write_cmd = -1;
3552 break;
3553 case KBD_CMD_SET_RATE:
3554 kbd_queue(s, KBD_REPLY_ACK, 0);
3555 s->kbd_write_cmd = -1;
3556 break;
3560 static void kbd_mouse_send_packet(KBDState *s)
3562 unsigned int b;
3563 int dx1, dy1, dz1;
3565 dx1 = s->mouse_dx;
3566 dy1 = s->mouse_dy;
3567 dz1 = s->mouse_dz;
3568 /* XXX: increase range to 8 bits ? */
3569 if (dx1 > 127)
3570 dx1 = 127;
3571 else if (dx1 < -127)
3572 dx1 = -127;
3573 if (dy1 > 127)
3574 dy1 = 127;
3575 else if (dy1 < -127)
3576 dy1 = -127;
3577 b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);
3578 kbd_queue(s, b, 1);
3579 kbd_queue(s, dx1 & 0xff, 1);
3580 kbd_queue(s, dy1 & 0xff, 1);
3581 /* extra byte for IMPS/2 or IMEX */
3582 switch(s->mouse_type) {
3583 default:
3584 break;
3585 case 3:
3586 if (dz1 > 127)
3587 dz1 = 127;
3588 else if (dz1 < -127)
3589 dz1 = -127;
3590 kbd_queue(s, dz1 & 0xff, 1);
3591 break;
3592 case 4:
3593 if (dz1 > 7)
3594 dz1 = 7;
3595 else if (dz1 < -7)
3596 dz1 = -7;
3597 b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);
3598 kbd_queue(s, b, 1);
3599 break;
3602 /* update deltas */
3603 s->mouse_dx -= dx1;
3604 s->mouse_dy -= dy1;
3605 s->mouse_dz -= dz1;
3608 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
3610 KBDState *s = &kbd_state;
3612 /* check if deltas are recorded when disabled */
3613 if (!(s->mouse_status & MOUSE_STATUS_ENABLED))
3614 return;
3616 s->mouse_dx += dx;
3617 s->mouse_dy -= dy;
3618 s->mouse_dz += dz;
3619 s->mouse_buttons = buttons_state;
3621 if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&
3622 (s->queues[1].count < (KBD_QUEUE_SIZE - 16))) {
3623 for(;;) {
3624 /* if not remote, send event. Multiple events are sent if
3625 too big deltas */
3626 kbd_mouse_send_packet(s);
3627 if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)
3628 break;
3633 static void kbd_write_mouse(KBDState *s, int val)
3635 #ifdef DEBUG_MOUSE
3636 printf("kbd: write mouse 0x%02x\n", val);
3637 #endif
3638 switch(s->mouse_write_cmd) {
3639 default:
3640 case -1:
3641 /* mouse command */
3642 if (s->mouse_wrap) {
3643 if (val == AUX_RESET_WRAP) {
3644 s->mouse_wrap = 0;
3645 kbd_queue(s, AUX_ACK, 1);
3646 return;
3647 } else if (val != AUX_RESET) {
3648 kbd_queue(s, val, 1);
3649 return;
3652 switch(val) {
3653 case AUX_SET_SCALE11:
3654 s->mouse_status &= ~MOUSE_STATUS_SCALE21;
3655 kbd_queue(s, AUX_ACK, 1);
3656 break;
3657 case AUX_SET_SCALE21:
3658 s->mouse_status |= MOUSE_STATUS_SCALE21;
3659 kbd_queue(s, AUX_ACK, 1);
3660 break;
3661 case AUX_SET_STREAM:
3662 s->mouse_status &= ~MOUSE_STATUS_REMOTE;
3663 kbd_queue(s, AUX_ACK, 1);
3664 break;
3665 case AUX_SET_WRAP:
3666 s->mouse_wrap = 1;
3667 kbd_queue(s, AUX_ACK, 1);
3668 break;
3669 case AUX_SET_REMOTE:
3670 s->mouse_status |= MOUSE_STATUS_REMOTE;
3671 kbd_queue(s, AUX_ACK, 1);
3672 break;
3673 case AUX_GET_TYPE:
3674 kbd_queue(s, AUX_ACK, 1);
3675 kbd_queue(s, s->mouse_type, 1);
3676 break;
3677 case AUX_SET_RES:
3678 case AUX_SET_SAMPLE:
3679 s->mouse_write_cmd = val;
3680 kbd_queue(s, AUX_ACK, 1);
3681 break;
3682 case AUX_GET_SCALE:
3683 kbd_queue(s, AUX_ACK, 1);
3684 kbd_queue(s, s->mouse_status, 1);
3685 kbd_queue(s, s->mouse_resolution, 1);
3686 kbd_queue(s, s->mouse_sample_rate, 1);
3687 break;
3688 case AUX_POLL:
3689 kbd_queue(s, AUX_ACK, 1);
3690 kbd_mouse_send_packet(s);
3691 break;
3692 case AUX_ENABLE_DEV:
3693 s->mouse_status |= MOUSE_STATUS_ENABLED;
3694 kbd_queue(s, AUX_ACK, 1);
3695 break;
3696 case AUX_DISABLE_DEV:
3697 s->mouse_status &= ~MOUSE_STATUS_ENABLED;
3698 kbd_queue(s, AUX_ACK, 1);
3699 break;
3700 case AUX_SET_DEFAULT:
3701 s->mouse_sample_rate = 100;
3702 s->mouse_resolution = 2;
3703 s->mouse_status = 0;
3704 kbd_queue(s, AUX_ACK, 1);
3705 break;
3706 case AUX_RESET:
3707 s->mouse_sample_rate = 100;
3708 s->mouse_resolution = 2;
3709 s->mouse_status = 0;
3710 kbd_queue(s, AUX_ACK, 1);
3711 kbd_queue(s, 0xaa, 1);
3712 kbd_queue(s, s->mouse_type, 1);
3713 break;
3714 default:
3715 break;
3717 break;
3718 case AUX_SET_SAMPLE:
3719 s->mouse_sample_rate = val;
3720 #if 0
3721 /* detect IMPS/2 or IMEX */
3722 switch(s->mouse_detect_state) {
3723 default:
3724 case 0:
3725 if (val == 200)
3726 s->mouse_detect_state = 1;
3727 break;
3728 case 1:
3729 if (val == 100)
3730 s->mouse_detect_state = 2;
3731 else if (val == 200)
3732 s->mouse_detect_state = 3;
3733 else
3734 s->mouse_detect_state = 0;
3735 break;
3736 case 2:
3737 if (val == 80)
3738 s->mouse_type = 3; /* IMPS/2 */
3739 s->mouse_detect_state = 0;
3740 break;
3741 case 3:
3742 if (val == 80)
3743 s->mouse_type = 4; /* IMEX */
3744 s->mouse_detect_state = 0;
3745 break;
3747 #endif
3748 kbd_queue(s, AUX_ACK, 1);
3749 s->mouse_write_cmd = -1;
3750 break;
3751 case AUX_SET_RES:
3752 s->mouse_resolution = val;
3753 kbd_queue(s, AUX_ACK, 1);
3754 s->mouse_write_cmd = -1;
3755 break;
3759 void kbd_write_data(CPUX86State *env, uint32_t addr, uint32_t val)
3761 KBDState *s = &kbd_state;
3763 #ifdef DEBUG_KBD
3764 printf("kbd: write data=0x%02x\n", val);
3765 #endif
3767 switch(s->write_cmd) {
3768 case 0:
3769 kbd_write_keyboard(s, val);
3770 break;
3771 case KBD_CCMD_WRITE_MODE:
3772 s->mode = val;
3773 kbd_update_irq(s);
3774 break;
3775 case KBD_CCMD_WRITE_OBUF:
3776 kbd_queue(s, val, 0);
3777 break;
3778 case KBD_CCMD_WRITE_AUX_OBUF:
3779 kbd_queue(s, val, 1);
3780 break;
3781 case KBD_CCMD_WRITE_OUTPORT:
3782 cpu_x86_set_a20(env, (val >> 1) & 1);
3783 if (!(val & 1)) {
3784 reset_requested = 1;
3785 cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
3787 break;
3788 case KBD_CCMD_WRITE_MOUSE:
3789 kbd_write_mouse(s, val);
3790 break;
3791 default:
3792 break;
3794 s->write_cmd = 0;
3797 void kbd_reset(KBDState *s)
3799 KBDQueue *q;
3800 int i;
3802 s->kbd_write_cmd = -1;
3803 s->mouse_write_cmd = -1;
3804 s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;
3805 s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;
3806 for(i = 0; i < 2; i++) {
3807 q = &s->queues[i];
3808 q->rptr = 0;
3809 q->wptr = 0;
3810 q->count = 0;
3814 void kbd_init(void)
3816 kbd_reset(&kbd_state);
3817 register_ioport_read(0x60, 1, kbd_read_data, 1);
3818 register_ioport_write(0x60, 1, kbd_write_data, 1);
3819 register_ioport_read(0x64, 1, kbd_read_status, 1);
3820 register_ioport_write(0x64, 1, kbd_write_command, 1);
3823 /***********************************************************/
3824 /* Bochs BIOS debug ports */
3826 void bochs_bios_write(CPUX86State *env, uint32_t addr, uint32_t val)
3828 switch(addr) {
3829 /* Bochs BIOS messages */
3830 case 0x400:
3831 case 0x401:
3832 fprintf(stderr, "BIOS panic at rombios.c, line %d\n", val);
3833 exit(1);
3834 case 0x402:
3835 case 0x403:
3836 #ifdef DEBUG_BIOS
3837 fprintf(stderr, "%c", val);
3838 #endif
3839 break;
3841 /* LGPL'ed VGA BIOS messages */
3842 case 0x501:
3843 case 0x502:
3844 fprintf(stderr, "VGA BIOS panic, line %d\n", val);
3845 exit(1);
3846 case 0x500:
3847 case 0x503:
3848 #ifdef DEBUG_BIOS
3849 fprintf(stderr, "%c", val);
3850 #endif
3851 break;
3855 void bochs_bios_init(void)
3857 register_ioport_write(0x400, 1, bochs_bios_write, 2);
3858 register_ioport_write(0x401, 1, bochs_bios_write, 2);
3859 register_ioport_write(0x402, 1, bochs_bios_write, 1);
3860 register_ioport_write(0x403, 1, bochs_bios_write, 1);
3862 register_ioport_write(0x501, 1, bochs_bios_write, 2);
3863 register_ioport_write(0x502, 1, bochs_bios_write, 2);
3864 register_ioport_write(0x500, 1, bochs_bios_write, 1);
3865 register_ioport_write(0x503, 1, bochs_bios_write, 1);
3868 /***********************************************************/
3869 /* dumb display */
3871 /* init terminal so that we can grab keys */
3872 static struct termios oldtty;
3874 static void term_exit(void)
3876 tcsetattr (0, TCSANOW, &oldtty);
3879 static void term_init(void)
3881 struct termios tty;
3883 tcgetattr (0, &tty);
3884 oldtty = tty;
3886 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
3887 |INLCR|IGNCR|ICRNL|IXON);
3888 tty.c_oflag |= OPOST;
3889 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
3890 /* if graphical mode, we allow Ctrl-C handling */
3891 if (nographic)
3892 tty.c_lflag &= ~ISIG;
3893 tty.c_cflag &= ~(CSIZE|PARENB);
3894 tty.c_cflag |= CS8;
3895 tty.c_cc[VMIN] = 1;
3896 tty.c_cc[VTIME] = 0;
3898 tcsetattr (0, TCSANOW, &tty);
3900 atexit(term_exit);
3902 fcntl(0, F_SETFL, O_NONBLOCK);
3905 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3909 static void dumb_resize(DisplayState *ds, int w, int h)
3913 static void dumb_refresh(DisplayState *ds)
3915 vga_update_display();
3918 void dumb_display_init(DisplayState *ds)
3920 ds->data = NULL;
3921 ds->linesize = 0;
3922 ds->depth = 0;
3923 ds->dpy_update = dumb_update;
3924 ds->dpy_resize = dumb_resize;
3925 ds->dpy_refresh = dumb_refresh;
3928 #if !defined(CONFIG_SOFTMMU)
3929 /***********************************************************/
3930 /* cpu signal handler */
3931 static void host_segv_handler(int host_signum, siginfo_t *info,
3932 void *puc)
3934 if (cpu_signal_handler(host_signum, info, puc))
3935 return;
3936 term_exit();
3937 abort();
3939 #endif
3941 static int timer_irq_pending;
3942 static int timer_irq_count;
3944 static int timer_ms;
3945 static int gui_refresh_pending, gui_refresh_count;
3947 static void host_alarm_handler(int host_signum, siginfo_t *info,
3948 void *puc)
3950 /* NOTE: since usually the OS asks a 100 Hz clock, there can be
3951 some drift between cpu_get_ticks() and the interrupt time. So
3952 we queue some interrupts to avoid missing some */
3953 timer_irq_count += pit_get_out_edges(&pit_channels[0]);
3954 if (timer_irq_count) {
3955 if (timer_irq_count > 2)
3956 timer_irq_count = 2;
3957 timer_irq_count--;
3958 timer_irq_pending = 1;
3960 gui_refresh_count += timer_ms;
3961 if (gui_refresh_count >= GUI_REFRESH_INTERVAL) {
3962 gui_refresh_count = 0;
3963 gui_refresh_pending = 1;
3966 if (gui_refresh_pending || timer_irq_pending) {
3967 /* just exit from the cpu to have a chance to handle timers */
3968 cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
3972 #ifdef CONFIG_SOFTMMU
3973 void *get_mmap_addr(unsigned long size)
3975 return NULL;
3977 #else
3978 unsigned long mmap_addr = PHYS_RAM_BASE;
3980 void *get_mmap_addr(unsigned long size)
3982 unsigned long addr;
3983 addr = mmap_addr;
3984 mmap_addr += ((size + 4095) & ~4095) + 4096;
3985 return (void *)addr;
3987 #endif
3989 /* main execution loop */
3991 CPUState *cpu_gdbstub_get_env(void *opaque)
3993 return global_env;
3996 int main_loop(void *opaque)
3998 struct pollfd ufds[3], *pf, *serial_ufd, *net_ufd, *gdb_ufd;
3999 int ret, n, timeout, serial_ok;
4000 uint8_t ch;
4001 CPUState *env = global_env;
4003 if (!term_inited) {
4004 /* initialize terminal only there so that the user has a
4005 chance to stop QEMU with Ctrl-C before the gdb connection
4006 is launched */
4007 term_inited = 1;
4008 term_init();
4011 serial_ok = 1;
4012 cpu_enable_ticks();
4013 for(;;) {
4014 ret = cpu_x86_exec(env);
4015 if (reset_requested) {
4016 ret = EXCP_INTERRUPT;
4017 break;
4019 if (ret == EXCP_DEBUG) {
4020 ret = EXCP_DEBUG;
4021 break;
4023 /* if hlt instruction, we wait until the next IRQ */
4024 if (ret == EXCP_HLT)
4025 timeout = 10;
4026 else
4027 timeout = 0;
4028 /* poll any events */
4029 serial_ufd = NULL;
4030 pf = ufds;
4031 if (serial_ok && !(serial_ports[0].lsr & UART_LSR_DR)) {
4032 serial_ufd = pf;
4033 pf->fd = 0;
4034 pf->events = POLLIN;
4035 pf++;
4037 net_ufd = NULL;
4038 if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) {
4039 net_ufd = pf;
4040 pf->fd = net_fd;
4041 pf->events = POLLIN;
4042 pf++;
4044 gdb_ufd = NULL;
4045 if (gdbstub_fd > 0) {
4046 gdb_ufd = pf;
4047 pf->fd = gdbstub_fd;
4048 pf->events = POLLIN;
4049 pf++;
4052 ret = poll(ufds, pf - ufds, timeout);
4053 if (ret > 0) {
4054 if (serial_ufd && (serial_ufd->revents & POLLIN)) {
4055 n = read(0, &ch, 1);
4056 if (n == 1) {
4057 serial_received_byte(&serial_ports[0], ch);
4058 } else {
4059 /* Closed, stop polling. */
4060 serial_ok = 0;
4063 if (net_ufd && (net_ufd->revents & POLLIN)) {
4064 uint8_t buf[MAX_ETH_FRAME_SIZE];
4066 n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);
4067 if (n > 0) {
4068 if (n < 60) {
4069 memset(buf + n, 0, 60 - n);
4070 n = 60;
4072 ne2000_receive(&ne2000_state, buf, n);
4075 if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {
4076 uint8_t buf[1];
4077 /* stop emulation if requested by gdb */
4078 n = read(gdbstub_fd, buf, 1);
4079 if (n == 1) {
4080 ret = EXCP_INTERRUPT;
4081 break;
4086 /* timer IRQ */
4087 if (timer_irq_pending) {
4088 pic_set_irq(0, 1);
4089 pic_set_irq(0, 0);
4090 timer_irq_pending = 0;
4093 /* VGA */
4094 if (gui_refresh_pending) {
4095 display_state.dpy_refresh(&display_state);
4096 gui_refresh_pending = 0;
4099 cpu_disable_ticks();
4100 return ret;
4103 void help(void)
4105 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
4106 "usage: %s [options] [disk_image]\n"
4107 "\n"
4108 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4109 "\n"
4110 "Standard options:\n"
4111 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4112 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4113 "-cdrom file use 'file' as IDE cdrom 2 image\n"
4114 "-boot [c|d] boot on hard disk or CD-ROM\n"
4115 "-snapshot write to temporary files instead of disk image files\n"
4116 "-m megs set virtual RAM size to megs MB\n"
4117 "-n script set network init script [default=%s]\n"
4118 "-tun-fd fd this fd talks to tap/tun, use it.\n"
4119 "-nographic disable graphical output\n"
4120 "\n"
4121 "Linux boot specific (does not require PC BIOS):\n"
4122 "-kernel bzImage use 'bzImage' as kernel image\n"
4123 "-append cmdline use 'cmdline' as kernel command line\n"
4124 "-initrd file use 'file' as initial ram disk\n"
4125 "\n"
4126 "Debug/Expert options:\n"
4127 "-s wait gdb connection to port %d\n"
4128 "-p port change gdb connection port\n"
4129 "-d output log in /tmp/vl.log\n"
4130 "-hdachs c,h,s force hard disk 0 geometry (usually qemu can guess it)\n"
4131 "-L path set the directory for the BIOS and VGA BIOS\n"
4132 "\n"
4133 "During emulation, use C-a h to get terminal commands:\n",
4134 #ifdef CONFIG_SOFTMMU
4135 "qemu",
4136 #else
4137 "qemu-fast",
4138 #endif
4139 DEFAULT_NETWORK_SCRIPT,
4140 DEFAULT_GDBSTUB_PORT);
4141 term_print_help();
4142 #ifndef CONFIG_SOFTMMU
4143 printf("\n"
4144 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4145 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4146 "PC emulation.\n");
4147 #endif
4148 exit(1);
4151 struct option long_options[] = {
4152 { "initrd", 1, NULL, 0, },
4153 { "hda", 1, NULL, 0, },
4154 { "hdb", 1, NULL, 0, },
4155 { "snapshot", 0, NULL, 0, },
4156 { "hdachs", 1, NULL, 0, },
4157 { "nographic", 0, NULL, 0, },
4158 { "kernel", 1, NULL, 0, },
4159 { "append", 1, NULL, 0, },
4160 { "tun-fd", 1, NULL, 0, },
4161 { "hdc", 1, NULL, 0, },
4162 { "hdd", 1, NULL, 0, },
4163 { "cdrom", 1, NULL, 0, },
4164 { "boot", 1, NULL, 0, },
4165 { NULL, 0, NULL, 0 },
4168 #ifdef CONFIG_SDL
4169 /* SDL use the pthreads and they modify sigaction. We don't
4170 want that. */
4171 #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)
4172 extern void __libc_sigaction();
4173 #define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
4174 #else
4175 extern void __sigaction();
4176 #define sigaction(sig, act, oact) __sigaction(sig, act, oact)
4177 #endif
4178 #endif /* CONFIG_SDL */
4180 int main(int argc, char **argv)
4182 int c, ret, initrd_size, i, use_gdbstub, gdbstub_port, long_index;
4183 int snapshot, linux_boot, total_ram_size;
4184 struct linux_params *params;
4185 struct sigaction act;
4186 struct itimerval itv;
4187 CPUX86State *env;
4188 const char *initrd_filename;
4189 const char *hd_filename[MAX_DISKS];
4190 const char *kernel_filename, *kernel_cmdline;
4191 DisplayState *ds = &display_state;
4193 /* we never want that malloc() uses mmap() */
4194 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
4195 initrd_filename = NULL;
4196 for(i = 0; i < MAX_DISKS; i++)
4197 hd_filename[i] = NULL;
4198 phys_ram_size = 32 * 1024 * 1024;
4199 vga_ram_size = VGA_RAM_SIZE;
4200 pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
4201 use_gdbstub = 0;
4202 gdbstub_port = DEFAULT_GDBSTUB_PORT;
4203 snapshot = 0;
4204 nographic = 0;
4205 kernel_filename = NULL;
4206 kernel_cmdline = "";
4207 for(;;) {
4208 c = getopt_long_only(argc, argv, "hm:dn:sp:L:", long_options, &long_index);
4209 if (c == -1)
4210 break;
4211 switch(c) {
4212 case 0:
4213 switch(long_index) {
4214 case 0:
4215 initrd_filename = optarg;
4216 break;
4217 case 1:
4218 hd_filename[0] = optarg;
4219 break;
4220 case 2:
4221 hd_filename[1] = optarg;
4222 break;
4223 case 3:
4224 snapshot = 1;
4225 break;
4226 case 4:
4228 int cyls, heads, secs;
4229 const char *p;
4230 p = optarg;
4231 cyls = strtol(p, (char **)&p, 0);
4232 if (*p != ',')
4233 goto chs_fail;
4234 p++;
4235 heads = strtol(p, (char **)&p, 0);
4236 if (*p != ',')
4237 goto chs_fail;
4238 p++;
4239 secs = strtol(p, (char **)&p, 0);
4240 if (*p != '\0')
4241 goto chs_fail;
4242 ide_state[0].cylinders = cyls;
4243 ide_state[0].heads = heads;
4244 ide_state[0].sectors = secs;
4245 chs_fail: ;
4247 break;
4248 case 5:
4249 nographic = 1;
4250 break;
4251 case 6:
4252 kernel_filename = optarg;
4253 break;
4254 case 7:
4255 kernel_cmdline = optarg;
4256 break;
4257 case 8:
4258 net_fd = atoi(optarg);
4259 break;
4260 case 9:
4261 hd_filename[2] = optarg;
4262 break;
4263 case 10:
4264 hd_filename[3] = optarg;
4265 break;
4266 case 11:
4267 hd_filename[2] = optarg;
4268 ide_state[2].is_cdrom = 1;
4269 break;
4270 case 12:
4271 boot_device = optarg[0];
4272 if (boot_device != 'c' && boot_device != 'd') {
4273 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
4274 exit(1);
4276 break;
4278 break;
4279 case 'h':
4280 help();
4281 break;
4282 case 'm':
4283 phys_ram_size = atoi(optarg) * 1024 * 1024;
4284 if (phys_ram_size <= 0)
4285 help();
4286 if (phys_ram_size > PHYS_RAM_MAX_SIZE) {
4287 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
4288 PHYS_RAM_MAX_SIZE / (1024 * 1024));
4289 exit(1);
4291 break;
4292 case 'd':
4293 cpu_set_log(CPU_LOG_ALL);
4294 break;
4295 case 'n':
4296 pstrcpy(network_script, sizeof(network_script), optarg);
4297 break;
4298 case 's':
4299 use_gdbstub = 1;
4300 break;
4301 case 'p':
4302 gdbstub_port = atoi(optarg);
4303 break;
4304 case 'L':
4305 bios_dir = optarg;
4306 break;
4310 if (optind < argc) {
4311 hd_filename[0] = argv[optind++];
4314 linux_boot = (kernel_filename != NULL);
4316 if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0')
4317 help();
4319 /* init debug */
4320 setvbuf(stdout, NULL, _IOLBF, 0);
4322 /* init network tun interface */
4323 if (net_fd < 0)
4324 net_init();
4326 /* init the memory */
4327 total_ram_size = phys_ram_size + vga_ram_size;
4329 #ifdef CONFIG_SOFTMMU
4330 phys_ram_base = malloc(total_ram_size);
4331 if (!phys_ram_base) {
4332 fprintf(stderr, "Could not allocate physical memory\n");
4333 exit(1);
4335 #else
4336 /* as we must map the same page at several addresses, we must use
4337 a fd */
4339 const char *tmpdir;
4341 tmpdir = getenv("QEMU_TMPDIR");
4342 if (!tmpdir)
4343 tmpdir = "/tmp";
4344 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
4345 if (mkstemp(phys_ram_file) < 0) {
4346 fprintf(stderr, "Could not create temporary memory file '%s'\n",
4347 phys_ram_file);
4348 exit(1);
4350 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
4351 if (phys_ram_fd < 0) {
4352 fprintf(stderr, "Could not open temporary memory file '%s'\n",
4353 phys_ram_file);
4354 exit(1);
4356 ftruncate(phys_ram_fd, total_ram_size);
4357 unlink(phys_ram_file);
4358 phys_ram_base = mmap(get_mmap_addr(total_ram_size),
4359 total_ram_size,
4360 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
4361 phys_ram_fd, 0);
4362 if (phys_ram_base == MAP_FAILED) {
4363 fprintf(stderr, "Could not map physical memory\n");
4364 exit(1);
4367 #endif
4369 /* open the virtual block devices */
4370 for(i = 0; i < MAX_DISKS; i++) {
4371 if (hd_filename[i]) {
4372 bs_table[i] = bdrv_open(hd_filename[i], snapshot);
4373 if (!bs_table[i]) {
4374 fprintf(stderr, "qemu: could not open hard disk image '%s\n",
4375 hd_filename[i]);
4376 exit(1);
4381 /* init CPU state */
4382 env = cpu_init();
4383 global_env = env;
4384 cpu_single_env = env;
4386 init_ioports();
4388 /* allocate RAM */
4389 cpu_register_physical_memory(0, phys_ram_size, 0);
4391 if (linux_boot) {
4392 /* now we can load the kernel */
4393 ret = load_kernel(kernel_filename, phys_ram_base + KERNEL_LOAD_ADDR);
4394 if (ret < 0) {
4395 fprintf(stderr, "qemu: could not load kernel '%s'\n",
4396 kernel_filename);
4397 exit(1);
4400 /* load initrd */
4401 initrd_size = 0;
4402 if (initrd_filename) {
4403 initrd_size = load_image(initrd_filename, phys_ram_base + INITRD_LOAD_ADDR);
4404 if (initrd_size < 0) {
4405 fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
4406 initrd_filename);
4407 exit(1);
4411 /* init kernel params */
4412 params = (void *)(phys_ram_base + KERNEL_PARAMS_ADDR);
4413 memset(params, 0, sizeof(struct linux_params));
4414 params->mount_root_rdonly = 0;
4415 stw_raw(&params->cl_magic, 0xA33F);
4416 stw_raw(&params->cl_offset, params->commandline - (uint8_t *)params);
4417 stl_raw(&params->alt_mem_k, (phys_ram_size / 1024) - 1024);
4418 pstrcat(params->commandline, sizeof(params->commandline), kernel_cmdline);
4419 params->loader_type = 0x01;
4420 if (initrd_size > 0) {
4421 stl_raw(&params->initrd_start, INITRD_LOAD_ADDR);
4422 stl_raw(&params->initrd_size, initrd_size);
4424 params->orig_video_lines = 25;
4425 params->orig_video_cols = 80;
4427 /* setup basic memory access */
4428 env->cr[0] = 0x00000033;
4429 cpu_x86_init_mmu(env);
4431 memset(params->idt_table, 0, sizeof(params->idt_table));
4433 stq_raw(&params->gdt_table[2], 0x00cf9a000000ffffLL); /* KERNEL_CS */
4434 stq_raw(&params->gdt_table[3], 0x00cf92000000ffffLL); /* KERNEL_DS */
4435 /* for newer kernels (2.6.0) CS/DS are at different addresses */
4436 stq_raw(&params->gdt_table[12], 0x00cf9a000000ffffLL); /* KERNEL_CS */
4437 stq_raw(&params->gdt_table[13], 0x00cf92000000ffffLL); /* KERNEL_DS */
4439 env->idt.base = (void *)((uint8_t *)params->idt_table - phys_ram_base);
4440 env->idt.limit = sizeof(params->idt_table) - 1;
4441 env->gdt.base = (void *)((uint8_t *)params->gdt_table - phys_ram_base);
4442 env->gdt.limit = sizeof(params->gdt_table) - 1;
4444 cpu_x86_load_seg_cache(env, R_CS, KERNEL_CS, NULL, 0xffffffff, 0x00cf9a00);
4445 cpu_x86_load_seg_cache(env, R_DS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
4446 cpu_x86_load_seg_cache(env, R_ES, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
4447 cpu_x86_load_seg_cache(env, R_SS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
4448 cpu_x86_load_seg_cache(env, R_FS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
4449 cpu_x86_load_seg_cache(env, R_GS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
4451 env->eip = KERNEL_LOAD_ADDR;
4452 env->regs[R_ESI] = KERNEL_PARAMS_ADDR;
4453 env->eflags = 0x2;
4455 } else {
4456 char buf[1024];
4458 /* RAW PC boot */
4460 /* BIOS load */
4461 snprintf(buf, sizeof(buf), "%s/%s", bios_dir, BIOS_FILENAME);
4462 ret = load_image(buf, phys_ram_base + 0x000f0000);
4463 if (ret != 0x10000) {
4464 fprintf(stderr, "qemu: could not load PC bios '%s'\n", buf);
4465 exit(1);
4468 /* VGA BIOS load */
4469 snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_FILENAME);
4470 ret = load_image(buf, phys_ram_base + 0x000c0000);
4472 /* setup basic memory access */
4473 env->cr[0] = 0x60000010;
4474 cpu_x86_init_mmu(env);
4476 env->idt.limit = 0xffff;
4477 env->gdt.limit = 0xffff;
4478 env->ldt.limit = 0xffff;
4480 /* not correct (CS base=0xffff0000) */
4481 cpu_x86_load_seg_cache(env, R_CS, 0xf000, (uint8_t *)0x000f0000, 0xffff, 0);
4482 cpu_x86_load_seg_cache(env, R_DS, 0, NULL, 0xffff, 0);
4483 cpu_x86_load_seg_cache(env, R_ES, 0, NULL, 0xffff, 0);
4484 cpu_x86_load_seg_cache(env, R_SS, 0, NULL, 0xffff, 0);
4485 cpu_x86_load_seg_cache(env, R_FS, 0, NULL, 0xffff, 0);
4486 cpu_x86_load_seg_cache(env, R_GS, 0, NULL, 0xffff, 0);
4488 env->eip = 0xfff0;
4489 env->regs[R_EDX] = 0x600; /* indicate P6 processor */
4491 env->eflags = 0x2;
4493 bochs_bios_init();
4496 /* terminal init */
4497 if (nographic) {
4498 dumb_display_init(ds);
4499 } else {
4500 #ifdef CONFIG_SDL
4501 sdl_display_init(ds);
4502 #else
4503 dumb_display_init(ds);
4504 #endif
4506 /* init basic PC hardware */
4507 register_ioport_write(0x80, 1, ioport80_write, 1);
4509 vga_init(ds, phys_ram_base + phys_ram_size, phys_ram_size,
4510 vga_ram_size);
4511 cmos_init();
4512 pic_init();
4513 pit_init();
4514 serial_init();
4515 ne2000_init();
4516 ide_init();
4517 kbd_init();
4519 /* setup cpu signal handlers for MMU / self modifying code handling */
4520 sigfillset(&act.sa_mask);
4521 act.sa_flags = SA_SIGINFO;
4522 #if !defined(CONFIG_SOFTMMU)
4523 act.sa_sigaction = host_segv_handler;
4524 sigaction(SIGSEGV, &act, NULL);
4525 sigaction(SIGBUS, &act, NULL);
4526 #endif
4528 act.sa_sigaction = host_alarm_handler;
4529 sigaction(SIGALRM, &act, NULL);
4531 itv.it_interval.tv_sec = 0;
4532 itv.it_interval.tv_usec = 1000;
4533 itv.it_value.tv_sec = 0;
4534 itv.it_value.tv_usec = 10 * 1000;
4535 setitimer(ITIMER_REAL, &itv, NULL);
4536 /* we probe the tick duration of the kernel to inform the user if
4537 the emulated kernel requested a too high timer frequency */
4538 getitimer(ITIMER_REAL, &itv);
4539 timer_ms = itv.it_interval.tv_usec / 1000;
4540 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) /
4541 1000000;
4543 if (use_gdbstub) {
4544 cpu_gdbstub(NULL, main_loop, gdbstub_port);
4545 } else {
4546 main_loop(NULL);
4548 return 0;