keyboard emulation - accepts to boot with Bochs BIOS and LGPL'ed VGA BIOS
[qemu] / vl.c
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include <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>
41
42 #include <sys/ioctl.h>
43 #include <sys/socket.h>
44 #include <linux/if.h>
45 #include <linux/if_tun.h>
46
47 #include "cpu-i386.h"
48 #include "disas.h"
49 #include "thunk.h"
50
51 #include "vl.h"
52
53 #define DEBUG_LOGFILE "/tmp/vl.log"
54 #define DEFAULT_NETWORK_SCRIPT "/etc/vl-ifup"
55 #define BIOS_FILENAME "bios.bin"
56 #define VGABIOS_FILENAME "vgabios.bin"
57
58 //#define DEBUG_UNUSED_IOPORT
59
60 //#define DEBUG_IRQ_LATENCY
61
62 /* output Bochs bios info messages */
63 //#define DEBUG_BIOS
64
65 /* debug IDE devices */
66 //#define DEBUG_IDE
67
68 /* debug PIC */
69 //#define DEBUG_PIC
70
71 /* debug NE2000 card */
72 //#define DEBUG_NE2000
73
74 /* debug PC keyboard */
75 //#define DEBUG_KBD
76
77 #define PHYS_RAM_BASE     0xac000000
78 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
79
80 #define KERNEL_LOAD_ADDR   0x00100000
81 #define INITRD_LOAD_ADDR   0x00400000
82 #define KERNEL_PARAMS_ADDR 0x00090000
83
84 #define MAX_DISKS 2
85
86 /* from plex86 (BSD license) */
87 struct  __attribute__ ((packed)) linux_params {
88   // For 0x00..0x3f, see 'struct screen_info' in linux/include/linux/tty.h.
89   // I just padded out the VESA parts, rather than define them.
90
91   /* 0x000 */ uint8_t   orig_x;
92   /* 0x001 */ uint8_t   orig_y;
93   /* 0x002 */ uint16_t  ext_mem_k;
94   /* 0x004 */ uint16_t  orig_video_page;
95   /* 0x006 */ uint8_t   orig_video_mode;
96   /* 0x007 */ uint8_t   orig_video_cols;
97   /* 0x008 */ uint16_t  unused1;
98   /* 0x00a */ uint16_t  orig_video_ega_bx;
99   /* 0x00c */ uint16_t  unused2;
100   /* 0x00e */ uint8_t   orig_video_lines;
101   /* 0x00f */ uint8_t   orig_video_isVGA;
102   /* 0x010 */ uint16_t  orig_video_points;
103   /* 0x012 */ uint8_t   pad0[0x20 - 0x12]; // VESA info.
104   /* 0x020 */ uint16_t  cl_magic;  // Commandline magic number (0xA33F)
105   /* 0x022 */ uint16_t  cl_offset; // Commandline offset.  Address of commandline
106                                  // is calculated as 0x90000 + cl_offset, bu
107                                  // only if cl_magic == 0xA33F.
108   /* 0x024 */ uint8_t   pad1[0x40 - 0x24]; // VESA info.
109
110   /* 0x040 */ uint8_t   apm_bios_info[20]; // struct apm_bios_info
111   /* 0x054 */ uint8_t   pad2[0x80 - 0x54];
112
113   // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.
114   // Might be truncated?
115   /* 0x080 */ uint8_t   hd0_info[16]; // hd0-disk-parameter from intvector 0x41
116   /* 0x090 */ uint8_t   hd1_info[16]; // hd1-disk-parameter from intvector 0x46
117
118   // System description table truncated to 16 bytes
119   // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.
120   /* 0x0a0 */ uint16_t  sys_description_len;
121   /* 0x0a2 */ uint8_t   sys_description_table[14];
122                         // [0] machine id
123                         // [1] machine submodel id
124                         // [2] BIOS revision
125                         // [3] bit1: MCA bus
126
127   /* 0x0b0 */ uint8_t   pad3[0x1e0 - 0xb0];
128   /* 0x1e0 */ uint32_t  alt_mem_k;
129   /* 0x1e4 */ uint8_t   pad4[4];
130   /* 0x1e8 */ uint8_t   e820map_entries;
131   /* 0x1e9 */ uint8_t   eddbuf_entries; // EDD_NR
132   /* 0x1ea */ uint8_t   pad5[0x1f1 - 0x1ea];
133   /* 0x1f1 */ uint8_t   setup_sects; // size of setup.S, number of sectors
134   /* 0x1f2 */ uint16_t  mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)
135   /* 0x1f4 */ uint16_t  sys_size; // size of compressed kernel-part in the
136                                 // (b)zImage-file (in 16 byte units, rounded up)
137   /* 0x1f6 */ uint16_t  swap_dev; // (unused AFAIK)
138   /* 0x1f8 */ uint16_t  ramdisk_flags;
139   /* 0x1fa */ uint16_t  vga_mode; // (old one)
140   /* 0x1fc */ uint16_t  orig_root_dev; // (high=Major, low=minor)
141   /* 0x1fe */ uint8_t   pad6[1];
142   /* 0x1ff */ uint8_t   aux_device_info;
143   /* 0x200 */ uint16_t  jump_setup; // Jump to start of setup code,
144                                   // aka "reserved" field.
145   /* 0x202 */ uint8_t   setup_signature[4]; // Signature for SETUP-header, ="HdrS"
146   /* 0x206 */ uint16_t  header_format_version; // Version number of header format;
147   /* 0x208 */ uint8_t   setup_S_temp0[8]; // Used by setup.S for communication with
148                                         // boot loaders, look there.
149   /* 0x210 */ uint8_t   loader_type;
150                         // 0 for old one.
151                         // else 0xTV:
152                         //   T=0: LILO
153                         //   T=1: Loadlin
154                         //   T=2: bootsect-loader
155                         //   T=3: SYSLINUX
156                         //   T=4: ETHERBOOT
157                         //   V=version
158   /* 0x211 */ uint8_t   loadflags;
159                         // bit0 = 1: kernel is loaded high (bzImage)
160                         // bit7 = 1: Heap and pointer (see below) set by boot
161                         //   loader.
162   /* 0x212 */ uint16_t  setup_S_temp1;
163   /* 0x214 */ uint32_t  kernel_start;
164   /* 0x218 */ uint32_t  initrd_start;
165   /* 0x21c */ uint32_t  initrd_size;
166   /* 0x220 */ uint8_t   setup_S_temp2[4];
167   /* 0x224 */ uint16_t  setup_S_heap_end_pointer;
168   /* 0x226 */ uint8_t   pad7[0x2d0 - 0x226];
169
170   /* 0x2d0 : Int 15, ax=e820 memory map. */
171   // (linux/include/asm-i386/e820.h, 'struct e820entry')
172 #define E820MAX  32
173 #define E820_RAM  1
174 #define E820_RESERVED 2
175 #define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */
176 #define E820_NVS  4
177   struct {
178     uint64_t addr;
179     uint64_t size;
180     uint32_t type;
181     } e820map[E820MAX];
182
183   /* 0x550 */ uint8_t   pad8[0x600 - 0x550];
184
185   // BIOS Enhanced Disk Drive Services.
186   // (From linux/include/asm-i386/edd.h, 'struct edd_info')
187   // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.
188   /* 0x600 */ uint8_t   eddbuf[0x7d4 - 0x600];
189
190   /* 0x7d4 */ uint8_t   pad9[0x800 - 0x7d4];
191   /* 0x800 */ uint8_t   commandline[0x800];
192
193   /* 0x1000 */
194   uint64_t gdt_table[256];
195   uint64_t idt_table[48];
196 };
197
198 #define KERNEL_CS     0x10
199 #define KERNEL_DS     0x18
200
201 typedef void (IOPortWriteFunc)(CPUX86State *env, uint32_t address, uint32_t data);
202 typedef uint32_t (IOPortReadFunc)(CPUX86State *env, uint32_t address);
203
204 #define MAX_IOPORTS 4096
205
206 static const char *interp_prefix = CONFIG_QEMU_PREFIX;
207 char phys_ram_file[1024];
208 CPUX86State *global_env;
209 CPUX86State *cpu_single_env;
210 FILE *logfile = NULL;
211 int loglevel;
212 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
213 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
214 BlockDriverState *bs_table[MAX_DISKS];
215
216 /***********************************************************/
217 /* x86 io ports */
218
219 uint32_t default_ioport_readb(CPUX86State *env, uint32_t address)
220 {
221 #ifdef DEBUG_UNUSED_IOPORT
222     fprintf(stderr, "inb: port=0x%04x\n", address);
223 #endif
224     return 0xff;
225 }
226
227 void default_ioport_writeb(CPUX86State *env, uint32_t address, uint32_t data)
228 {
229 #ifdef DEBUG_UNUSED_IOPORT
230     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
231 #endif
232 }
233
234 /* default is to make two byte accesses */
235 uint32_t default_ioport_readw(CPUX86State *env, uint32_t address)
236 {
237     uint32_t data;
238     data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](env, address);
239     data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1) << 8;
240     return data;
241 }
242
243 void default_ioport_writew(CPUX86State *env, uint32_t address, uint32_t data)
244 {
245     ioport_write_table[0][address & (MAX_IOPORTS - 1)](env, address, data & 0xff);
246     ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1, (data >> 8) & 0xff);
247 }
248
249 uint32_t default_ioport_readl(CPUX86State *env, uint32_t address)
250 {
251 #ifdef DEBUG_UNUSED_IOPORT
252     fprintf(stderr, "inl: port=0x%04x\n", address);
253 #endif
254     return 0xffffffff;
255 }
256
257 void default_ioport_writel(CPUX86State *env, uint32_t address, uint32_t data)
258 {
259 #ifdef DEBUG_UNUSED_IOPORT
260     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
261 #endif
262 }
263
264 void init_ioports(void)
265 {
266     int i;
267
268     for(i = 0; i < MAX_IOPORTS; i++) {
269         ioport_read_table[0][i] = default_ioport_readb;
270         ioport_write_table[0][i] = default_ioport_writeb;
271         ioport_read_table[1][i] = default_ioport_readw;
272         ioport_write_table[1][i] = default_ioport_writew;
273         ioport_read_table[2][i] = default_ioport_readl;
274         ioport_write_table[2][i] = default_ioport_writel;
275     }
276 }
277
278 /* size is the word size in byte */
279 int register_ioport_read(int start, int length, IOPortReadFunc *func, int size)
280 {
281     int i, bsize;
282
283     if (size == 1)
284         bsize = 0;
285     else if (size == 2)
286         bsize = 1;
287     else if (size == 4)
288         bsize = 2;
289     else
290         return -1;
291     for(i = start; i < start + length; i += size)
292         ioport_read_table[bsize][i] = func;
293     return 0;
294 }
295
296 /* size is the word size in byte */
297 int register_ioport_write(int start, int length, IOPortWriteFunc *func, int size)
298 {
299     int i, bsize;
300
301     if (size == 1)
302         bsize = 0;
303     else if (size == 2)
304         bsize = 1;
305     else if (size == 4)
306         bsize = 2;
307     else
308         return -1;
309     for(i = start; i < start + length; i += size)
310         ioport_write_table[bsize][i] = func;
311     return 0;
312 }
313
314 void pstrcpy(char *buf, int buf_size, const char *str)
315 {
316     int c;
317     char *q = buf;
318
319     if (buf_size <= 0)
320         return;
321
322     for(;;) {
323         c = *str++;
324         if (c == 0 || q >= buf + buf_size - 1)
325             break;
326         *q++ = c;
327     }
328     *q = '\0';
329 }
330
331 /* strcat and truncate. */
332 char *pstrcat(char *buf, int buf_size, const char *s)
333 {
334     int len;
335     len = strlen(buf);
336     if (len < buf_size) 
337         pstrcpy(buf + len, buf_size - len, s);
338     return buf;
339 }
340
341 int load_kernel(const char *filename, uint8_t *addr)
342 {
343     int fd, size, setup_sects;
344     uint8_t bootsect[512];
345
346     fd = open(filename, O_RDONLY);
347     if (fd < 0)
348         return -1;
349     if (read(fd, bootsect, 512) != 512)
350         goto fail;
351     setup_sects = bootsect[0x1F1];
352     if (!setup_sects)
353         setup_sects = 4;
354     /* skip 16 bit setup code */
355     lseek(fd, (setup_sects + 1) * 512, SEEK_SET);
356     size = read(fd, addr, 16 * 1024 * 1024);
357     if (size < 0)
358         goto fail;
359     close(fd);
360     return size;
361  fail:
362     close(fd);
363     return -1;
364 }
365
366 /* return the size or -1 if error */
367 int load_image(const char *filename, uint8_t *addr)
368 {
369     int fd, size;
370     fd = open(filename, O_RDONLY);
371     if (fd < 0)
372         return -1;
373     size = lseek(fd, 0, SEEK_END);
374     lseek(fd, 0, SEEK_SET);
375     if (read(fd, addr, size) != size) {
376         close(fd);
377         return -1;
378     }
379     close(fd);
380     return size;
381 }
382
383 void cpu_x86_outb(CPUX86State *env, int addr, int val)
384 {
385     ioport_write_table[0][addr & (MAX_IOPORTS - 1)](env, addr, val);
386 }
387
388 void cpu_x86_outw(CPUX86State *env, int addr, int val)
389 {
390     ioport_write_table[1][addr & (MAX_IOPORTS - 1)](env, addr, val);
391 }
392
393 void cpu_x86_outl(CPUX86State *env, int addr, int val)
394 {
395     ioport_write_table[2][addr & (MAX_IOPORTS - 1)](env, addr, val);
396 }
397
398 int cpu_x86_inb(CPUX86State *env, int addr)
399 {
400     return ioport_read_table[0][addr & (MAX_IOPORTS - 1)](env, addr);
401 }
402
403 int cpu_x86_inw(CPUX86State *env, int addr)
404 {
405     return ioport_read_table[1][addr & (MAX_IOPORTS - 1)](env, addr);
406 }
407
408 int cpu_x86_inl(CPUX86State *env, int addr)
409 {
410     return ioport_read_table[2][addr & (MAX_IOPORTS - 1)](env, addr);
411 }
412
413 /***********************************************************/
414 void ioport80_write(CPUX86State *env, uint32_t addr, uint32_t data)
415 {
416 }
417
418 void hw_error(const char *fmt, ...)
419 {
420     va_list ap;
421
422     va_start(ap, fmt);
423     fprintf(stderr, "qemu: hardware error: ");
424     vfprintf(stderr, fmt, ap);
425     fprintf(stderr, "\n");
426 #ifdef TARGET_I386
427     cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
428 #endif
429     va_end(ap);
430     abort();
431 }
432
433 /***********************************************************/
434 /* vga emulation */
435 static uint8_t vga_index;
436 static uint8_t vga_regs[256];
437 static int last_cursor_pos;
438
439 void update_console_messages(void)
440 {
441     int c, i, cursor_pos, eol;
442
443     cursor_pos = vga_regs[0x0f] | (vga_regs[0x0e] << 8);
444     eol = 0;
445     for(i = last_cursor_pos; i < cursor_pos; i++) {
446         c = phys_ram_base[0xb8000 + (i) * 2];
447         if (c >= ' ') {
448             putchar(c);
449             eol = 0;
450         } else {
451             if (!eol)
452                 putchar('\n');
453             eol = 1;
454         }
455     }
456     fflush(stdout);
457     last_cursor_pos = cursor_pos;
458 }
459
460 /* just to see first Linux console messages, we intercept cursor position */
461 void vga_ioport_write(CPUX86State *env, uint32_t addr, uint32_t data)
462 {
463     switch(addr) {
464     case 0x3d4:
465         vga_index = data;
466         break;
467     case 0x3d5:
468         vga_regs[vga_index] = data;
469         if (vga_index == 0x0f)
470             update_console_messages();
471         break;
472     }
473             
474 }
475
476 /***********************************************************/
477 /* cmos emulation */
478
479 #define RTC_SECONDS             0
480 #define RTC_SECONDS_ALARM       1
481 #define RTC_MINUTES             2
482 #define RTC_MINUTES_ALARM       3
483 #define RTC_HOURS               4
484 #define RTC_HOURS_ALARM         5
485 #define RTC_ALARM_DONT_CARE    0xC0
486
487 #define RTC_DAY_OF_WEEK         6
488 #define RTC_DAY_OF_MONTH        7
489 #define RTC_MONTH               8
490 #define RTC_YEAR                9
491
492 #define RTC_REG_A               10
493 #define RTC_REG_B               11
494 #define RTC_REG_C               12
495 #define RTC_REG_D               13
496
497 /* PC cmos mappings */
498 #define REG_EQUIPMENT_BYTE          0x14
499
500 uint8_t cmos_data[128];
501 uint8_t cmos_index;
502
503 void cmos_ioport_write(CPUX86State *env, uint32_t addr, uint32_t data)
504 {
505     if (addr == 0x70) {
506         cmos_index = data & 0x7f;
507     }
508 }
509
510 uint32_t cmos_ioport_read(CPUX86State *env, uint32_t addr)
511 {
512     int ret;
513
514     if (addr == 0x70) {
515         return 0xff;
516     } else {
517         /* toggle update-in-progress bit for Linux (same hack as
518            plex86) */
519         ret = cmos_data[cmos_index];
520         if (cmos_index == RTC_REG_A)
521             cmos_data[RTC_REG_A] ^= 0x80; 
522         else if (cmos_index == RTC_REG_C)
523             cmos_data[RTC_REG_C] = 0x00; 
524         return ret;
525     }
526 }
527
528
529 static inline int to_bcd(int a)
530 {
531     return ((a / 10) << 4) | (a % 10);
532 }
533
534 void cmos_init(void)
535 {
536     struct tm *tm;
537     time_t ti;
538     int val;
539
540     ti = time(NULL);
541     tm = gmtime(&ti);
542     cmos_data[RTC_SECONDS] = to_bcd(tm->tm_sec);
543     cmos_data[RTC_MINUTES] = to_bcd(tm->tm_min);
544     cmos_data[RTC_HOURS] = to_bcd(tm->tm_hour);
545     cmos_data[RTC_DAY_OF_WEEK] = to_bcd(tm->tm_wday);
546     cmos_data[RTC_DAY_OF_MONTH] = to_bcd(tm->tm_mday);
547     cmos_data[RTC_MONTH] = to_bcd(tm->tm_mon + 1);
548     cmos_data[RTC_YEAR] = to_bcd(tm->tm_year % 100);
549
550     cmos_data[RTC_REG_A] = 0x26;
551     cmos_data[RTC_REG_B] = 0x02;
552     cmos_data[RTC_REG_C] = 0x00;
553     cmos_data[RTC_REG_D] = 0x80;
554
555     /* various important CMOS locations needed by PC/Bochs bios */
556
557     cmos_data[REG_EQUIPMENT_BYTE] = 0x02; /* FPU is there */
558
559     /* memory size */
560     val = (phys_ram_size / 1024) - 1024;
561     if (val > 65535)
562         val = 65535;
563     cmos_data[0x17] = val;
564     cmos_data[0x18] = val >> 8;
565     cmos_data[0x30] = val;
566     cmos_data[0x31] = val >> 8;
567
568     val = (phys_ram_size / 65536) - ((16 * 1024 * 1024) / 65536);
569     if (val > 65535)
570         val = 65535;
571     cmos_data[0x34] = val;
572     cmos_data[0x35] = val >> 8;
573     
574     cmos_data[0x3d] = 0x02; /* hard drive boot */
575     
576     register_ioport_write(0x70, 2, cmos_ioport_write, 1);
577     register_ioport_read(0x70, 2, cmos_ioport_read, 1);
578 }
579
580 /***********************************************************/
581 /* 8259 pic emulation */
582
583 typedef struct PicState {
584     uint8_t last_irr; /* edge detection */
585     uint8_t irr; /* interrupt request register */
586     uint8_t imr; /* interrupt mask register */
587     uint8_t isr; /* interrupt service register */
588     uint8_t priority_add; /* used to compute irq priority */
589     uint8_t irq_base;
590     uint8_t read_reg_select;
591     uint8_t special_mask;
592     uint8_t init_state;
593     uint8_t auto_eoi;
594     uint8_t rotate_on_autoeoi;
595     uint8_t init4; /* true if 4 byte init */
596 } PicState;
597
598 /* 0 is master pic, 1 is slave pic */
599 PicState pics[2];
600 int pic_irq_requested;
601
602 /* set irq level. If an edge is detected, then the IRR is set to 1 */
603 static inline void pic_set_irq1(PicState *s, int irq, int level)
604 {
605     int mask;
606     mask = 1 << irq;
607     if (level) {
608         if ((s->last_irr & mask) == 0)
609             s->irr |= mask;
610         s->last_irr |= mask;
611     } else {
612         s->last_irr &= ~mask;
613     }
614 }
615
616 static inline int get_priority(PicState *s, int mask)
617 {
618     int priority;
619     if (mask == 0)
620         return -1;
621     priority = 7;
622     while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)
623         priority--;
624     return priority;
625 }
626
627 /* return the pic wanted interrupt. return -1 if none */
628 static int pic_get_irq(PicState *s)
629 {
630     int mask, cur_priority, priority;
631
632     mask = s->irr & ~s->imr;
633     priority = get_priority(s, mask);
634     if (priority < 0)
635         return -1;
636     /* compute current priority */
637     cur_priority = get_priority(s, s->isr);
638     if (priority > cur_priority) {
639         /* higher priority found: an irq should be generated */
640         return priority;
641     } else {
642         return -1;
643     }
644 }
645
646 /* raise irq to CPU if necessary. must be called every time the active
647    irq may change */
648 static void pic_update_irq(void)
649 {
650     int irq2, irq;
651
652     /* first look at slave pic */
653     irq2 = pic_get_irq(&pics[1]);
654     if (irq2 >= 0) {
655         /* if irq request by slave pic, signal master PIC */
656         pic_set_irq1(&pics[0], 2, 1);
657         pic_set_irq1(&pics[0], 2, 0);
658     }
659     /* look at requested irq */
660     irq = pic_get_irq(&pics[0]);
661     if (irq >= 0) {
662         if (irq == 2) {
663             /* from slave pic */
664             pic_irq_requested = 8 + irq2;
665         } else {
666             /* from master pic */
667             pic_irq_requested = irq;
668         }
669         cpu_x86_interrupt(global_env, CPU_INTERRUPT_HARD);
670     }
671 }
672
673 #ifdef DEBUG_IRQ_LATENCY
674 int64_t irq_time[16];
675 int64_t cpu_get_ticks(void);
676 #endif
677 #ifdef DEBUG_PIC
678 int irq_level[16];
679 #endif
680
681 void pic_set_irq(int irq, int level)
682 {
683 #ifdef DEBUG_PIC
684     if (level != irq_level[irq]) {
685         printf("pic_set_irq: irq=%d level=%d\n", irq, level);
686         irq_level[irq] = level;
687     }
688 #endif
689 #ifdef DEBUG_IRQ_LATENCY
690     if (level) {
691         irq_time[irq] = cpu_get_ticks();
692     }
693 #endif
694     pic_set_irq1(&pics[irq >> 3], irq & 7, level);
695     pic_update_irq();
696 }
697
698 int cpu_x86_get_pic_interrupt(CPUX86State *env)
699 {
700     int irq, irq2, intno;
701
702     /* signal the pic that the irq was acked by the CPU */
703     irq = pic_irq_requested;
704 #ifdef DEBUG_IRQ_LATENCY
705     printf("IRQ%d latency=%Ld\n", irq, cpu_get_ticks() - irq_time[irq]);
706 #endif
707 #ifdef DEBUG_PIC
708     printf("pic_interrupt: irq=%d\n", irq);
709 #endif
710
711     if (irq >= 8) {
712         irq2 = irq & 7;
713         pics[1].isr |= (1 << irq2);
714         pics[1].irr &= ~(1 << irq2);
715         irq = 2;
716         intno = pics[1].irq_base + irq2;
717     } else {
718         intno = pics[0].irq_base + irq;
719     }
720     pics[0].isr |= (1 << irq);
721     pics[0].irr &= ~(1 << irq);
722     return intno;
723 }
724
725 void pic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
726 {
727     PicState *s;
728     int priority;
729
730 #ifdef DEBUG_PIC
731     printf("pic_write: addr=0x%02x val=0x%02x\n", addr, val);
732 #endif
733     s = &pics[addr >> 7];
734     addr &= 1;
735     if (addr == 0) {
736         if (val & 0x10) {
737             /* init */
738             memset(s, 0, sizeof(PicState));
739             s->init_state = 1;
740             s->init4 = val & 1;
741             if (val & 0x02)
742                 hw_error("single mode not supported");
743             if (val & 0x08)
744                 hw_error("level sensitive irq not supported");
745         } else if (val & 0x08) {
746             if (val & 0x02)
747                 s->read_reg_select = val & 1;
748             if (val & 0x40)
749                 s->special_mask = (val >> 5) & 1;
750         } else {
751             switch(val) {
752             case 0x00:
753             case 0x80:
754                 s->rotate_on_autoeoi = val >> 7;
755                 break;
756             case 0x20: /* end of interrupt */
757             case 0xa0:
758                 priority = get_priority(s, s->isr);
759                 if (priority >= 0) {
760                     s->isr &= ~(1 << ((priority + s->priority_add) & 7));
761                 }
762                 if (val == 0xa0)
763                     s->priority_add = (s->priority_add + 1) & 7;
764                 break;
765             case 0x60 ... 0x67:
766                 priority = val & 7;
767                 s->isr &= ~(1 << priority);
768                 break;
769             case 0xc0 ... 0xc7:
770                 s->priority_add = (val + 1) & 7;
771                 break;
772             case 0xe0 ... 0xe7:
773                 priority = val & 7;
774                 s->isr &= ~(1 << priority);
775                 s->priority_add = (priority + 1) & 7;
776                 break;
777             }
778         }
779     } else {
780         switch(s->init_state) {
781         case 0:
782             /* normal mode */
783             s->imr = val;
784             pic_update_irq();
785             break;
786         case 1:
787             s->irq_base = val & 0xf8;
788             s->init_state = 2;
789             break;
790         case 2:
791             if (s->init4) {
792                 s->init_state = 3;
793             } else {
794                 s->init_state = 0;
795             }
796             break;
797         case 3:
798             s->auto_eoi = (val >> 1) & 1;
799             s->init_state = 0;
800             break;
801         }
802     }
803 }
804
805 uint32_t pic_ioport_read(CPUX86State *env, uint32_t addr1)
806 {
807     PicState *s;
808     unsigned int addr;
809     int ret;
810
811     addr = addr1;
812     s = &pics[addr >> 7];
813     addr &= 1;
814     if (addr == 0) {
815         if (s->read_reg_select)
816             ret = s->isr;
817         else
818             ret = s->irr;
819     } else {
820         ret = s->imr;
821     }
822 #ifdef DEBUG_PIC
823     printf("pic_read: addr=0x%02x val=0x%02x\n", addr1, ret);
824 #endif
825     return ret;
826 }
827
828 void pic_init(void)
829 {
830     register_ioport_write(0x20, 2, pic_ioport_write, 1);
831     register_ioport_read(0x20, 2, pic_ioport_read, 1);
832     register_ioport_write(0xa0, 2, pic_ioport_write, 1);
833     register_ioport_read(0xa0, 2, pic_ioport_read, 1);
834 }
835
836 /***********************************************************/
837 /* 8253 PIT emulation */
838
839 #define PIT_FREQ 1193182
840
841 #define RW_STATE_LSB 0
842 #define RW_STATE_MSB 1
843 #define RW_STATE_WORD0 2
844 #define RW_STATE_WORD1 3
845 #define RW_STATE_LATCHED_WORD0 4
846 #define RW_STATE_LATCHED_WORD1 5
847
848 typedef struct PITChannelState {
849     int count; /* can be 65536 */
850     uint16_t latched_count;
851     uint8_t rw_state;
852     uint8_t mode;
853     uint8_t bcd; /* not supported */
854     uint8_t gate; /* timer start */
855     int64_t count_load_time;
856     int64_t count_last_edge_check_time;
857 } PITChannelState;
858
859 PITChannelState pit_channels[3];
860 int speaker_data_on;
861 int pit_min_timer_count = 0;
862
863 int64_t ticks_per_sec;
864
865 int64_t get_clock(void)
866 {
867     struct timeval tv;
868     gettimeofday(&tv, NULL);
869     return tv.tv_sec * 1000000LL + tv.tv_usec;
870 }
871
872 int64_t cpu_get_ticks(void)
873 {
874     int64_t val;
875     asm("rdtsc" : "=A" (val));
876     return val;
877 }
878
879 void cpu_calibrate_ticks(void)
880 {
881     int64_t usec, ticks;
882
883     usec = get_clock();
884     ticks = cpu_get_ticks();
885     usleep(50 * 1000);
886     usec = get_clock() - usec;
887     ticks = cpu_get_ticks() - ticks;
888     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
889 }
890
891 /* compute with 96 bit intermediate result: (a*b)/c */
892 static uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
893 {
894     union {
895         uint64_t ll;
896         struct {
897 #ifdef WORDS_BIGENDIAN
898             uint32_t high, low;
899 #else
900             uint32_t low, high;
901 #endif            
902         } l;
903     } u, res;
904     uint64_t rl, rh;
905
906     u.ll = a;
907     rl = (uint64_t)u.l.low * (uint64_t)b;
908     rh = (uint64_t)u.l.high * (uint64_t)b;
909     rh += (rl >> 32);
910     res.l.high = rh / c;
911     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
912     return res.ll;
913 }
914
915 static int pit_get_count(PITChannelState *s)
916 {
917     uint64_t d;
918     int counter;
919
920     d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
921     switch(s->mode) {
922     case 0:
923     case 1:
924     case 4:
925     case 5:
926         counter = (s->count - d) & 0xffff;
927         break;
928     default:
929         counter = s->count - (d % s->count);
930         break;
931     }
932     return counter;
933 }
934
935 /* get pit output bit */
936 static int pit_get_out(PITChannelState *s)
937 {
938     uint64_t d;
939     int out;
940
941     d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
942     switch(s->mode) {
943     default:
944     case 0:
945         out = (d >= s->count);
946         break;
947     case 1:
948         out = (d < s->count);
949         break;
950     case 2:
951         if ((d % s->count) == 0 && d != 0)
952             out = 1;
953         else
954             out = 0;
955         break;
956     case 3:
957         out = (d % s->count) < (s->count >> 1);
958         break;
959     case 4:
960     case 5:
961         out = (d == s->count);
962         break;
963     }
964     return out;
965 }
966
967 /* get the number of 0 to 1 transitions we had since we call this
968    function */
969 /* XXX: maybe better to use ticks precision to avoid getting edges
970    twice if checks are done at very small intervals */
971 static int pit_get_out_edges(PITChannelState *s)
972 {
973     uint64_t d1, d2;
974     int64_t ticks;
975     int ret, v;
976
977     ticks = cpu_get_ticks();
978     d1 = muldiv64(s->count_last_edge_check_time - s->count_load_time, 
979                  PIT_FREQ, ticks_per_sec);
980     d2 = muldiv64(ticks - s->count_load_time, 
981                   PIT_FREQ, ticks_per_sec);
982     s->count_last_edge_check_time = ticks;
983     switch(s->mode) {
984     default:
985     case 0:
986         if (d1 < s->count && d2 >= s->count)
987             ret = 1;
988         else
989             ret = 0;
990         break;
991     case 1:
992         ret = 0;
993         break;
994     case 2:
995         d1 /= s->count;
996         d2 /= s->count;
997         ret = d2 - d1;
998         break;
999     case 3:
1000         v = s->count - (s->count >> 1);
1001         d1 = (d1 + v) / s->count;
1002         d2 = (d2 + v) / s->count;
1003         ret = d2 - d1;
1004         break;
1005     case 4:
1006     case 5:
1007         if (d1 < s->count && d2 >= s->count)
1008             ret = 1;
1009         else
1010             ret = 0;
1011         break;
1012     }
1013     return ret;
1014 }
1015
1016 static inline void pit_load_count(PITChannelState *s, int val)
1017 {
1018     if (val == 0)
1019         val = 0x10000;
1020     s->count_load_time = cpu_get_ticks();
1021     s->count_last_edge_check_time = s->count_load_time;
1022     s->count = val;
1023     if (s == &pit_channels[0] && val <= pit_min_timer_count) {
1024         fprintf(stderr, 
1025                 "\nWARNING: vl: 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", 
1026                 PIT_FREQ / pit_min_timer_count);
1027     }
1028 }
1029
1030 void pit_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1031 {
1032     int channel, access;
1033     PITChannelState *s;
1034
1035     addr &= 3;
1036     if (addr == 3) {
1037         channel = val >> 6;
1038         if (channel == 3)
1039             return;
1040         s = &pit_channels[channel];
1041         access = (val >> 4) & 3;
1042         switch(access) {
1043         case 0:
1044             s->latched_count = pit_get_count(s);
1045             s->rw_state = RW_STATE_LATCHED_WORD0;
1046             break;
1047         default:
1048             s->mode = (val >> 1) & 7;
1049             s->bcd = val & 1;
1050             s->rw_state = access - 1 +  RW_STATE_LSB;
1051             break;
1052         }
1053     } else {
1054         s = &pit_channels[addr];
1055         switch(s->rw_state) {
1056         case RW_STATE_LSB:
1057             pit_load_count(s, val);
1058             break;
1059         case RW_STATE_MSB:
1060             pit_load_count(s, val << 8);
1061             break;
1062         case RW_STATE_WORD0:
1063         case RW_STATE_WORD1:
1064             if (s->rw_state & 1) {
1065                 pit_load_count(s, (s->latched_count & 0xff) | (val << 8));
1066             } else {
1067                 s->latched_count = val;
1068             }
1069             s->rw_state ^= 1;
1070             break;
1071         }
1072     }
1073 }
1074
1075 uint32_t pit_ioport_read(CPUX86State *env, uint32_t addr)
1076 {
1077     int ret, count;
1078     PITChannelState *s;
1079     
1080     addr &= 3;
1081     s = &pit_channels[addr];
1082     switch(s->rw_state) {
1083     case RW_STATE_LSB:
1084     case RW_STATE_MSB:
1085     case RW_STATE_WORD0:
1086     case RW_STATE_WORD1:
1087         count = pit_get_count(s);
1088         if (s->rw_state & 1)
1089             ret = (count >> 8) & 0xff;
1090         else
1091             ret = count & 0xff;
1092         if (s->rw_state & 2)
1093             s->rw_state ^= 1;
1094         break;
1095     default:
1096     case RW_STATE_LATCHED_WORD0:
1097     case RW_STATE_LATCHED_WORD1:
1098         if (s->rw_state & 1)
1099             ret = s->latched_count >> 8;
1100         else
1101             ret = s->latched_count & 0xff;
1102         s->rw_state ^= 1;
1103         break;
1104     }
1105     return ret;
1106 }
1107
1108 void speaker_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1109 {
1110     speaker_data_on = (val >> 1) & 1;
1111     pit_channels[2].gate = val & 1;
1112 }
1113
1114 uint32_t speaker_ioport_read(CPUX86State *env, uint32_t addr)
1115 {
1116     int out;
1117     out = pit_get_out(&pit_channels[2]);
1118     return (speaker_data_on << 1) | pit_channels[2].gate | (out << 5);
1119 }
1120
1121 void pit_init(void)
1122 {
1123     PITChannelState *s;
1124     int i;
1125
1126     cpu_calibrate_ticks();
1127
1128     for(i = 0;i < 3; i++) {
1129         s = &pit_channels[i];
1130         s->mode = 3;
1131         s->gate = (i != 2);
1132         pit_load_count(s, 0);
1133     }
1134
1135     register_ioport_write(0x40, 4, pit_ioport_write, 1);
1136     register_ioport_read(0x40, 3, pit_ioport_read, 1);
1137
1138     register_ioport_read(0x61, 1, speaker_ioport_read, 1);
1139     register_ioport_write(0x61, 1, speaker_ioport_write, 1);
1140 }
1141
1142 /***********************************************************/
1143 /* serial port emulation */
1144
1145 #define UART_IRQ        4
1146
1147 #define UART_LCR_DLAB   0x80    /* Divisor latch access bit */
1148
1149 #define UART_IER_MSI    0x08    /* Enable Modem status interrupt */
1150 #define UART_IER_RLSI   0x04    /* Enable receiver line status interrupt */
1151 #define UART_IER_THRI   0x02    /* Enable Transmitter holding register int. */
1152 #define UART_IER_RDI    0x01    /* Enable receiver data interrupt */
1153
1154 #define UART_IIR_NO_INT 0x01    /* No interrupts pending */
1155 #define UART_IIR_ID     0x06    /* Mask for the interrupt ID */
1156
1157 #define UART_IIR_MSI    0x00    /* Modem status interrupt */
1158 #define UART_IIR_THRI   0x02    /* Transmitter holding register empty */
1159 #define UART_IIR_RDI    0x04    /* Receiver data interrupt */
1160 #define UART_IIR_RLSI   0x06    /* Receiver line status interrupt */
1161
1162 #define UART_LSR_TEMT   0x40    /* Transmitter empty */
1163 #define UART_LSR_THRE   0x20    /* Transmit-hold-register empty */
1164 #define UART_LSR_BI     0x10    /* Break interrupt indicator */
1165 #define UART_LSR_FE     0x08    /* Frame error indicator */
1166 #define UART_LSR_PE     0x04    /* Parity error indicator */
1167 #define UART_LSR_OE     0x02    /* Overrun error indicator */
1168 #define UART_LSR_DR     0x01    /* Receiver data ready */
1169
1170 typedef struct SerialState {
1171     uint8_t divider;
1172     uint8_t rbr; /* receive register */
1173     uint8_t ier;
1174     uint8_t iir; /* read only */
1175     uint8_t lcr;
1176     uint8_t mcr;
1177     uint8_t lsr; /* read only */
1178     uint8_t msr;
1179     uint8_t scr;
1180 } SerialState;
1181
1182 SerialState serial_ports[1];
1183
1184 void serial_update_irq(void)
1185 {
1186     SerialState *s = &serial_ports[0];
1187
1188     if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {
1189         s->iir = UART_IIR_RDI;
1190     } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {
1191         s->iir = UART_IIR_THRI;
1192     } else {
1193         s->iir = UART_IIR_NO_INT;
1194     }
1195     if (s->iir != UART_IIR_NO_INT) {
1196         pic_set_irq(UART_IRQ, 1);
1197     } else {
1198         pic_set_irq(UART_IRQ, 0);
1199     }
1200 }
1201
1202 void serial_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1203 {
1204     SerialState *s = &serial_ports[0];
1205     unsigned char ch;
1206     int ret;
1207     
1208     addr &= 7;
1209     switch(addr) {
1210     default:
1211     case 0:
1212         if (s->lcr & UART_LCR_DLAB) {
1213             s->divider = (s->divider & 0xff00) | val;
1214         } else {
1215             s->lsr &= ~UART_LSR_THRE;
1216             serial_update_irq();
1217
1218             ch = val;
1219             do {
1220                 ret = write(1, &ch, 1);
1221             } while (ret != 1);
1222             s->lsr |= UART_LSR_THRE;
1223             s->lsr |= UART_LSR_TEMT;
1224             serial_update_irq();
1225         }
1226         break;
1227     case 1:
1228         if (s->lcr & UART_LCR_DLAB) {
1229             s->divider = (s->divider & 0x00ff) | (val << 8);
1230         } else {
1231             s->ier = val;
1232             serial_update_irq();
1233         }
1234         break;
1235     case 2:
1236         break;
1237     case 3:
1238         s->lcr = val;
1239         break;
1240     case 4:
1241         s->mcr = val;
1242         break;
1243     case 5:
1244         break;
1245     case 6:
1246         s->msr = val;
1247         break;
1248     case 7:
1249         s->scr = val;
1250         break;
1251     }
1252 }
1253
1254 uint32_t serial_ioport_read(CPUX86State *env, uint32_t addr)
1255 {
1256     SerialState *s = &serial_ports[0];
1257     uint32_t ret;
1258
1259     addr &= 7;
1260     switch(addr) {
1261     default:
1262     case 0:
1263         if (s->lcr & UART_LCR_DLAB) {
1264             ret = s->divider & 0xff; 
1265         } else {
1266             ret = s->rbr;
1267             s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
1268             serial_update_irq();
1269         }
1270         break;
1271     case 1:
1272         if (s->lcr & UART_LCR_DLAB) {
1273             ret = (s->divider >> 8) & 0xff;
1274         } else {
1275             ret = s->ier;
1276         }
1277         break;
1278     case 2:
1279         ret = s->iir;
1280         break;
1281     case 3:
1282         ret = s->lcr;
1283         break;
1284     case 4:
1285         ret = s->mcr;
1286         break;
1287     case 5:
1288         ret = s->lsr;
1289         break;
1290     case 6:
1291         ret = s->msr;
1292         break;
1293     case 7:
1294         ret = s->scr;
1295         break;
1296     }
1297     return ret;
1298 }
1299
1300 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1301 static int term_got_escape;
1302
1303 void term_print_help(void)
1304 {
1305     printf("\n"
1306            "C-a h    print this help\n"
1307            "C-a x    exit emulatior\n"
1308            "C-a s    save disk data back to file (if -snapshot)\n"
1309            "C-a b    send break (magic sysrq)\n"
1310            "C-a C-a  send C-a\n"
1311            );
1312 }
1313
1314 /* called when a char is received */
1315 void serial_received_byte(SerialState *s, int ch)
1316 {
1317     if (term_got_escape) {
1318         term_got_escape = 0;
1319         switch(ch) {
1320         case 'h':
1321             term_print_help();
1322             break;
1323         case 'x':
1324             exit(0);
1325             break;
1326         case 's': 
1327             {
1328                 int i;
1329                 for (i = 0; i < MAX_DISKS; i++) {
1330                     if (bs_table[i])
1331                         bdrv_commit(bs_table[i]);
1332                 }
1333             }
1334             break;
1335         case 'b':
1336             /* send break */
1337             s->rbr = 0;
1338             s->lsr |= UART_LSR_BI | UART_LSR_DR;
1339             serial_update_irq();
1340             break;
1341         case TERM_ESCAPE:
1342             goto send_char;
1343         }
1344     } else if (ch == TERM_ESCAPE) {
1345         term_got_escape = 1;
1346     } else {
1347     send_char:
1348         s->rbr = ch;
1349         s->lsr |= UART_LSR_DR;
1350         serial_update_irq();
1351     }
1352 }
1353
1354 /* init terminal so that we can grab keys */
1355 static struct termios oldtty;
1356
1357 static void term_exit(void)
1358 {
1359     tcsetattr (0, TCSANOW, &oldtty);
1360 }
1361
1362 static void term_init(void)
1363 {
1364     struct termios tty;
1365
1366     tcgetattr (0, &tty);
1367     oldtty = tty;
1368
1369     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1370                           |INLCR|IGNCR|ICRNL|IXON);
1371     tty.c_oflag |= OPOST;
1372     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1373     tty.c_cflag &= ~(CSIZE|PARENB);
1374     tty.c_cflag |= CS8;
1375     tty.c_cc[VMIN] = 1;
1376     tty.c_cc[VTIME] = 0;
1377     
1378     tcsetattr (0, TCSANOW, &tty);
1379
1380     atexit(term_exit);
1381
1382     fcntl(0, F_SETFL, O_NONBLOCK);
1383 }
1384
1385 void serial_init(void)
1386 {
1387     SerialState *s = &serial_ports[0];
1388
1389     s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
1390
1391     register_ioport_write(0x3f8, 8, serial_ioport_write, 1);
1392     register_ioport_read(0x3f8, 8, serial_ioport_read, 1);
1393
1394     term_init();
1395 }
1396
1397 /***********************************************************/
1398 /* ne2000 emulation */
1399
1400 #define NE2000_IOPORT   0x300
1401 #define NE2000_IRQ      9
1402
1403 #define MAX_ETH_FRAME_SIZE 1514
1404
1405 #define E8390_CMD       0x00  /* The command register (for all pages) */
1406 /* Page 0 register offsets. */
1407 #define EN0_CLDALO      0x01    /* Low byte of current local dma addr  RD */
1408 #define EN0_STARTPG     0x01    /* Starting page of ring bfr WR */
1409 #define EN0_CLDAHI      0x02    /* High byte of current local dma addr  RD */
1410 #define EN0_STOPPG      0x02    /* Ending page +1 of ring bfr WR */
1411 #define EN0_BOUNDARY    0x03    /* Boundary page of ring bfr RD WR */
1412 #define EN0_TSR         0x04    /* Transmit status reg RD */
1413 #define EN0_TPSR        0x04    /* Transmit starting page WR */
1414 #define EN0_NCR         0x05    /* Number of collision reg RD */
1415 #define EN0_TCNTLO      0x05    /* Low  byte of tx byte count WR */
1416 #define EN0_FIFO        0x06    /* FIFO RD */
1417 #define EN0_TCNTHI      0x06    /* High byte of tx byte count WR */
1418 #define EN0_ISR         0x07    /* Interrupt status reg RD WR */
1419 #define EN0_CRDALO      0x08    /* low byte of current remote dma address RD */
1420 #define EN0_RSARLO      0x08    /* Remote start address reg 0 */
1421 #define EN0_CRDAHI      0x09    /* high byte, current remote dma address RD */
1422 #define EN0_RSARHI      0x09    /* Remote start address reg 1 */
1423 #define EN0_RCNTLO      0x0a    /* Remote byte count reg WR */
1424 #define EN0_RCNTHI      0x0b    /* Remote byte count reg WR */
1425 #define EN0_RSR         0x0c    /* rx status reg RD */
1426 #define EN0_RXCR        0x0c    /* RX configuration reg WR */
1427 #define EN0_TXCR        0x0d    /* TX configuration reg WR */
1428 #define EN0_COUNTER0    0x0d    /* Rcv alignment error counter RD */
1429 #define EN0_DCFG        0x0e    /* Data configuration reg WR */
1430 #define EN0_COUNTER1    0x0e    /* Rcv CRC error counter RD */
1431 #define EN0_IMR         0x0f    /* Interrupt mask reg WR */
1432 #define EN0_COUNTER2    0x0f    /* Rcv missed frame error counter RD */
1433
1434 #define EN1_PHYS        0x11
1435 #define EN1_CURPAG      0x17
1436 #define EN1_MULT        0x18
1437
1438 /*  Register accessed at EN_CMD, the 8390 base addr.  */
1439 #define E8390_STOP      0x01    /* Stop and reset the chip */
1440 #define E8390_START     0x02    /* Start the chip, clear reset */
1441 #define E8390_TRANS     0x04    /* Transmit a frame */
1442 #define E8390_RREAD     0x08    /* Remote read */
1443 #define E8390_RWRITE    0x10    /* Remote write  */
1444 #define E8390_NODMA     0x20    /* Remote DMA */
1445 #define E8390_PAGE0     0x00    /* Select page chip registers */
1446 #define E8390_PAGE1     0x40    /* using the two high-order bits */
1447 #define E8390_PAGE2     0x80    /* Page 3 is invalid. */
1448
1449 /* Bits in EN0_ISR - Interrupt status register */
1450 #define ENISR_RX        0x01    /* Receiver, no error */
1451 #define ENISR_TX        0x02    /* Transmitter, no error */
1452 #define ENISR_RX_ERR    0x04    /* Receiver, with error */
1453 #define ENISR_TX_ERR    0x08    /* Transmitter, with error */
1454 #define ENISR_OVER      0x10    /* Receiver overwrote the ring */
1455 #define ENISR_COUNTERS  0x20    /* Counters need emptying */
1456 #define ENISR_RDC       0x40    /* remote dma complete */
1457 #define ENISR_RESET     0x80    /* Reset completed */
1458 #define ENISR_ALL       0x3f    /* Interrupts we will enable */
1459
1460 /* Bits in received packet status byte and EN0_RSR*/
1461 #define ENRSR_RXOK      0x01    /* Received a good packet */
1462 #define ENRSR_CRC       0x02    /* CRC error */
1463 #define ENRSR_FAE       0x04    /* frame alignment error */
1464 #define ENRSR_FO        0x08    /* FIFO overrun */
1465 #define ENRSR_MPA       0x10    /* missed pkt */
1466 #define ENRSR_PHY       0x20    /* physical/multicast address */
1467 #define ENRSR_DIS       0x40    /* receiver disable. set in monitor mode */
1468 #define ENRSR_DEF       0x80    /* deferring */
1469
1470 /* Transmitted packet status, EN0_TSR. */
1471 #define ENTSR_PTX 0x01  /* Packet transmitted without error */
1472 #define ENTSR_ND  0x02  /* The transmit wasn't deferred. */
1473 #define ENTSR_COL 0x04  /* The transmit collided at least once. */
1474 #define ENTSR_ABT 0x08  /* The transmit collided 16 times, and was deferred. */
1475 #define ENTSR_CRS 0x10  /* The carrier sense was lost. */
1476 #define ENTSR_FU  0x20  /* A "FIFO underrun" occurred during transmit. */
1477 #define ENTSR_CDH 0x40  /* The collision detect "heartbeat" signal was lost. */
1478 #define ENTSR_OWC 0x80  /* There was an out-of-window collision. */
1479
1480 #define NE2000_MEM_SIZE 32768
1481
1482 typedef struct NE2000State {
1483     uint8_t cmd;
1484     uint32_t start;
1485     uint32_t stop;
1486     uint8_t boundary;
1487     uint8_t tsr;
1488     uint8_t tpsr;
1489     uint16_t tcnt;
1490     uint16_t rcnt;
1491     uint32_t rsar;
1492     uint8_t isr;
1493     uint8_t dcfg;
1494     uint8_t imr;
1495     uint8_t phys[6]; /* mac address */
1496     uint8_t curpag;
1497     uint8_t mult[8]; /* multicast mask array */
1498     uint8_t mem[NE2000_MEM_SIZE];
1499 } NE2000State;
1500
1501 NE2000State ne2000_state;
1502 int net_fd = -1;
1503 char network_script[1024];
1504
1505 void ne2000_reset(void)
1506 {
1507     NE2000State *s = &ne2000_state;
1508     int i;
1509
1510     s->isr = ENISR_RESET;
1511     s->mem[0] = 0x52;
1512     s->mem[1] = 0x54;
1513     s->mem[2] = 0x00;
1514     s->mem[3] = 0x12;
1515     s->mem[4] = 0x34;
1516     s->mem[5] = 0x56;
1517     s->mem[14] = 0x57;
1518     s->mem[15] = 0x57;
1519
1520     /* duplicate prom data */
1521     for(i = 15;i >= 0; i--) {
1522         s->mem[2 * i] = s->mem[i];
1523         s->mem[2 * i + 1] = s->mem[i];
1524     }
1525 }
1526
1527 void ne2000_update_irq(NE2000State *s)
1528 {
1529     int isr;
1530     isr = s->isr & s->imr;
1531     if (isr)
1532         pic_set_irq(NE2000_IRQ, 1);
1533     else
1534         pic_set_irq(NE2000_IRQ, 0);
1535 }
1536
1537 int net_init(void)
1538 {
1539     struct ifreq ifr;
1540     int fd, ret, pid, status;
1541     
1542     fd = open("/dev/net/tun", O_RDWR);
1543     if (fd < 0) {
1544         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1545         return -1;
1546     }
1547     memset(&ifr, 0, sizeof(ifr));
1548     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1549     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1550     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1551     if (ret != 0) {
1552         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1553         close(fd);
1554         return -1;
1555     }
1556     printf("Connected to host network interface: %s\n", ifr.ifr_name);
1557     fcntl(fd, F_SETFL, O_NONBLOCK);
1558     net_fd = fd;
1559
1560     /* try to launch network init script */
1561     pid = fork();
1562     if (pid >= 0) {
1563         if (pid == 0) {
1564             execl(network_script, network_script, ifr.ifr_name, NULL);
1565             exit(1);
1566         }
1567         while (waitpid(pid, &status, 0) != pid);
1568         if (!WIFEXITED(status) ||
1569             WEXITSTATUS(status) != 0) {
1570             fprintf(stderr, "%s: could not launch network script for '%s'\n",
1571                     network_script, ifr.ifr_name);
1572         }
1573     }
1574     return 0;
1575 }
1576
1577 void net_send_packet(NE2000State *s, const uint8_t *buf, int size)
1578 {
1579 #ifdef DEBUG_NE2000
1580     printf("NE2000: sending packet size=%d\n", size);
1581 #endif
1582     write(net_fd, buf, size);
1583 }
1584
1585 /* return true if the NE2000 can receive more data */
1586 int ne2000_can_receive(NE2000State *s)
1587 {
1588     int avail, index, boundary;
1589     
1590     if (s->cmd & E8390_STOP)
1591         return 0;
1592     index = s->curpag << 8;
1593     boundary = s->boundary << 8;
1594     if (index < boundary)
1595         avail = boundary - index;
1596     else
1597         avail = (s->stop - s->start) - (index - boundary);
1598     if (avail < (MAX_ETH_FRAME_SIZE + 4))
1599         return 0;
1600     return 1;
1601 }
1602
1603 void ne2000_receive(NE2000State *s, uint8_t *buf, int size)
1604 {
1605     uint8_t *p;
1606     int total_len, next, avail, len, index;
1607
1608 #if defined(DEBUG_NE2000)
1609     printf("NE2000: received len=%d\n", size);
1610 #endif
1611
1612     index = s->curpag << 8;
1613     /* 4 bytes for header */
1614     total_len = size + 4;
1615     /* address for next packet (4 bytes for CRC) */
1616     next = index + ((total_len + 4 + 255) & ~0xff);
1617     if (next >= s->stop)
1618         next -= (s->stop - s->start);
1619     /* prepare packet header */
1620     p = s->mem + index;
1621     p[0] = ENRSR_RXOK; /* receive status */
1622     p[1] = next >> 8;
1623     p[2] = total_len;
1624     p[3] = total_len >> 8;
1625     index += 4;
1626
1627     /* write packet data */
1628     while (size > 0) {
1629         avail = s->stop - index;
1630         len = size;
1631         if (len > avail)
1632             len = avail;
1633         memcpy(s->mem + index, buf, len);
1634         buf += len;
1635         index += len;
1636         if (index == s->stop)
1637             index = s->start;
1638         size -= len;
1639     }
1640     s->curpag = next >> 8;
1641     
1642     /* now we can signal we have receive something */
1643     s->isr |= ENISR_RX;
1644     ne2000_update_irq(s);
1645 }
1646
1647 void ne2000_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1648 {
1649     NE2000State *s = &ne2000_state;
1650     int offset, page;
1651
1652     addr &= 0xf;
1653 #ifdef DEBUG_NE2000
1654     printf("NE2000: write addr=0x%x val=0x%02x\n", addr, val);
1655 #endif
1656     if (addr == E8390_CMD) {
1657         /* control register */
1658         s->cmd = val;
1659         if (val & E8390_START) {
1660             /* test specific case: zero length transfert */
1661             if ((val & (E8390_RREAD | E8390_RWRITE)) &&
1662                 s->rcnt == 0) {
1663                 s->isr |= ENISR_RDC;
1664                 ne2000_update_irq(s);
1665             }
1666             if (val & E8390_TRANS) {
1667                 net_send_packet(s, s->mem + (s->tpsr << 8), s->tcnt);
1668                 /* signal end of transfert */
1669                 s->tsr = ENTSR_PTX;
1670                 s->isr |= ENISR_TX;
1671                 ne2000_update_irq(s);
1672             }
1673         }
1674     } else {
1675         page = s->cmd >> 6;
1676         offset = addr | (page << 4);
1677         switch(offset) {
1678         case EN0_STARTPG:
1679             s->start = val << 8;
1680             break;
1681         case EN0_STOPPG:
1682             s->stop = val << 8;
1683             break;
1684         case EN0_BOUNDARY:
1685             s->boundary = val;
1686             break;
1687         case EN0_IMR:
1688             s->imr = val;
1689             ne2000_update_irq(s);
1690             break;
1691         case EN0_TPSR:
1692             s->tpsr = val;
1693             break;
1694         case EN0_TCNTLO:
1695             s->tcnt = (s->tcnt & 0xff00) | val;
1696             break;
1697         case EN0_TCNTHI:
1698             s->tcnt = (s->tcnt & 0x00ff) | (val << 8);
1699             break;
1700         case EN0_RSARLO:
1701             s->rsar = (s->rsar & 0xff00) | val;
1702             break;
1703         case EN0_RSARHI:
1704             s->rsar = (s->rsar & 0x00ff) | (val << 8);
1705             break;
1706         case EN0_RCNTLO:
1707             s->rcnt = (s->rcnt & 0xff00) | val;
1708             break;
1709         case EN0_RCNTHI:
1710             s->rcnt = (s->rcnt & 0x00ff) | (val << 8);
1711             break;
1712         case EN0_DCFG:
1713             s->dcfg = val;
1714             break;
1715         case EN0_ISR:
1716             s->isr &= ~val;
1717             ne2000_update_irq(s);
1718             break;
1719         case EN1_PHYS ... EN1_PHYS + 5:
1720             s->phys[offset - EN1_PHYS] = val;
1721             break;
1722         case EN1_CURPAG:
1723             s->curpag = val;
1724             break;
1725         case EN1_MULT ... EN1_MULT + 7:
1726             s->mult[offset - EN1_MULT] = val;
1727             break;
1728         }
1729     }
1730 }
1731
1732 uint32_t ne2000_ioport_read(CPUX86State *env, uint32_t addr)
1733 {
1734     NE2000State *s = &ne2000_state;
1735     int offset, page, ret;
1736
1737     addr &= 0xf;
1738     if (addr == E8390_CMD) {
1739         ret = s->cmd;
1740     } else {
1741         page = s->cmd >> 6;
1742         offset = addr | (page << 4);
1743         switch(offset) {
1744         case EN0_TSR:
1745             ret = s->tsr;
1746             break;
1747         case EN0_BOUNDARY:
1748             ret = s->boundary;
1749             break;
1750         case EN0_ISR:
1751             ret = s->isr;
1752             break;
1753         case EN1_PHYS ... EN1_PHYS + 5:
1754             ret = s->phys[offset - EN1_PHYS];
1755             break;
1756         case EN1_CURPAG:
1757             ret = s->curpag;
1758             break;
1759         case EN1_MULT ... EN1_MULT + 7:
1760             ret = s->mult[offset - EN1_MULT];
1761             break;
1762         default:
1763             ret = 0x00;
1764             break;
1765         }
1766     }
1767 #ifdef DEBUG_NE2000
1768     printf("NE2000: read addr=0x%x val=%02x\n", addr, ret);
1769 #endif
1770     return ret;
1771 }
1772
1773 void ne2000_asic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1774 {
1775     NE2000State *s = &ne2000_state;
1776     uint8_t *p;
1777
1778 #ifdef DEBUG_NE2000
1779     printf("NE2000: asic write val=0x%04x\n", val);
1780 #endif
1781     p = s->mem + s->rsar;
1782     if (s->dcfg & 0x01) {
1783         /* 16 bit access */
1784         p[0] = val;
1785         p[1] = val >> 8;
1786         s->rsar += 2;
1787         s->rcnt -= 2;
1788     } else {
1789         /* 8 bit access */
1790         p[0] = val;
1791         s->rsar++;
1792         s->rcnt--;
1793     }
1794     /* wrap */
1795     if (s->rsar == s->stop)
1796         s->rsar = s->start;
1797     if (s->rcnt == 0) {
1798         /* signal end of transfert */
1799         s->isr |= ENISR_RDC;
1800         ne2000_update_irq(s);
1801     }
1802 }
1803
1804 uint32_t ne2000_asic_ioport_read(CPUX86State *env, uint32_t addr)
1805 {
1806     NE2000State *s = &ne2000_state;
1807     uint8_t *p;
1808     int ret;
1809
1810     p = s->mem + s->rsar;
1811     if (s->dcfg & 0x01) {
1812         /* 16 bit access */
1813         ret = p[0] | (p[1] << 8);
1814         s->rsar += 2;
1815         s->rcnt -= 2;
1816     } else {
1817         /* 8 bit access */
1818         ret = p[0];
1819         s->rsar++;
1820         s->rcnt--;
1821     }
1822     /* wrap */
1823     if (s->rsar == s->stop)
1824         s->rsar = s->start;
1825     if (s->rcnt == 0) {
1826         /* signal end of transfert */
1827         s->isr |= ENISR_RDC;
1828         ne2000_update_irq(s);
1829     }
1830 #ifdef DEBUG_NE2000
1831     printf("NE2000: asic read val=0x%04x\n", ret);
1832 #endif
1833     return ret;
1834 }
1835
1836 void ne2000_reset_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1837 {
1838     /* nothing to do (end of reset pulse) */
1839 }
1840
1841 uint32_t ne2000_reset_ioport_read(CPUX86State *env, uint32_t addr)
1842 {
1843     ne2000_reset();
1844     return 0;
1845 }
1846
1847 void ne2000_init(void)
1848 {
1849     register_ioport_write(NE2000_IOPORT, 16, ne2000_ioport_write, 1);
1850     register_ioport_read(NE2000_IOPORT, 16, ne2000_ioport_read, 1);
1851
1852     register_ioport_write(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_write, 1);
1853     register_ioport_read(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_read, 1);
1854     register_ioport_write(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_write, 2);
1855     register_ioport_read(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_read, 2);
1856
1857     register_ioport_write(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_write, 1);
1858     register_ioport_read(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_read, 1);
1859     ne2000_reset();
1860 }
1861
1862 /***********************************************************/
1863 /* ide emulation */
1864
1865 /* Bits of HD_STATUS */
1866 #define ERR_STAT                0x01
1867 #define INDEX_STAT              0x02
1868 #define ECC_STAT                0x04    /* Corrected error */
1869 #define DRQ_STAT                0x08
1870 #define SEEK_STAT               0x10
1871 #define SRV_STAT                0x10
1872 #define WRERR_STAT              0x20
1873 #define READY_STAT              0x40
1874 #define BUSY_STAT               0x80
1875
1876 /* Bits for HD_ERROR */
1877 #define MARK_ERR                0x01    /* Bad address mark */
1878 #define TRK0_ERR                0x02    /* couldn't find track 0 */
1879 #define ABRT_ERR                0x04    /* Command aborted */
1880 #define MCR_ERR                 0x08    /* media change request */
1881 #define ID_ERR                  0x10    /* ID field not found */
1882 #define MC_ERR                  0x20    /* media changed */
1883 #define ECC_ERR                 0x40    /* Uncorrectable ECC error */
1884 #define BBD_ERR                 0x80    /* pre-EIDE meaning:  block marked bad */
1885 #define ICRC_ERR                0x80    /* new meaning:  CRC error during transfer */
1886
1887 /* Bits of HD_NSECTOR */
1888 #define CD                      0x01
1889 #define IO                      0x02
1890 #define REL                     0x04
1891 #define TAG_MASK                0xf8
1892
1893 #define IDE_CMD_RESET           0x04
1894 #define IDE_CMD_DISABLE_IRQ     0x02
1895
1896 /* ATA/ATAPI Commands pre T13 Spec */
1897 #define WIN_NOP                         0x00
1898 /*
1899  *      0x01->0x02 Reserved
1900  */
1901 #define CFA_REQ_EXT_ERROR_CODE          0x03 /* CFA Request Extended Error Code */
1902 /*
1903  *      0x04->0x07 Reserved
1904  */
1905 #define WIN_SRST                        0x08 /* ATAPI soft reset command */
1906 #define WIN_DEVICE_RESET                0x08
1907 /*
1908  *      0x09->0x0F Reserved
1909  */
1910 #define WIN_RECAL                       0x10
1911 #define WIN_RESTORE                     WIN_RECAL
1912 /*
1913  *      0x10->0x1F Reserved
1914  */
1915 #define WIN_READ                        0x20 /* 28-Bit */
1916 #define WIN_READ_ONCE                   0x21 /* 28-Bit without retries */
1917 #define WIN_READ_LONG                   0x22 /* 28-Bit */
1918 #define WIN_READ_LONG_ONCE              0x23 /* 28-Bit without retries */
1919 #define WIN_READ_EXT                    0x24 /* 48-Bit */
1920 #define WIN_READDMA_EXT                 0x25 /* 48-Bit */
1921 #define WIN_READDMA_QUEUED_EXT          0x26 /* 48-Bit */
1922 #define WIN_READ_NATIVE_MAX_EXT         0x27 /* 48-Bit */
1923 /*
1924  *      0x28
1925  */
1926 #define WIN_MULTREAD_EXT                0x29 /* 48-Bit */
1927 /*
1928  *      0x2A->0x2F Reserved
1929  */
1930 #define WIN_WRITE                       0x30 /* 28-Bit */
1931 #define WIN_WRITE_ONCE                  0x31 /* 28-Bit without retries */
1932 #define WIN_WRITE_LONG                  0x32 /* 28-Bit */
1933 #define WIN_WRITE_LONG_ONCE             0x33 /* 28-Bit without retries */
1934 #define WIN_WRITE_EXT                   0x34 /* 48-Bit */
1935 #define WIN_WRITEDMA_EXT                0x35 /* 48-Bit */
1936 #define WIN_WRITEDMA_QUEUED_EXT         0x36 /* 48-Bit */
1937 #define WIN_SET_MAX_EXT                 0x37 /* 48-Bit */
1938 #define CFA_WRITE_SECT_WO_ERASE         0x38 /* CFA Write Sectors without erase */
1939 #define WIN_MULTWRITE_EXT               0x39 /* 48-Bit */
1940 /*
1941  *      0x3A->0x3B Reserved
1942  */
1943 #define WIN_WRITE_VERIFY                0x3C /* 28-Bit */
1944 /*
1945  *      0x3D->0x3F Reserved
1946  */
1947 #define WIN_VERIFY                      0x40 /* 28-Bit - Read Verify Sectors */
1948 #define WIN_VERIFY_ONCE                 0x41 /* 28-Bit - without retries */
1949 #define WIN_VERIFY_EXT                  0x42 /* 48-Bit */
1950 /*
1951  *      0x43->0x4F Reserved
1952  */
1953 #define WIN_FORMAT                      0x50
1954 /*
1955  *      0x51->0x5F Reserved
1956  */
1957 #define WIN_INIT                        0x60
1958 /*
1959  *      0x61->0x5F Reserved
1960  */
1961 #define WIN_SEEK                        0x70 /* 0x70-0x7F Reserved */
1962 #define CFA_TRANSLATE_SECTOR            0x87 /* CFA Translate Sector */
1963 #define WIN_DIAGNOSE                    0x90
1964 #define WIN_SPECIFY                     0x91 /* set drive geometry translation */
1965 #define WIN_DOWNLOAD_MICROCODE          0x92
1966 #define WIN_STANDBYNOW2                 0x94
1967 #define WIN_STANDBY2                    0x96
1968 #define WIN_SETIDLE2                    0x97
1969 #define WIN_CHECKPOWERMODE2             0x98
1970 #define WIN_SLEEPNOW2                   0x99
1971 /*
1972  *      0x9A VENDOR
1973  */
1974 #define WIN_PACKETCMD                   0xA0 /* Send a packet command. */
1975 #define WIN_PIDENTIFY                   0xA1 /* identify ATAPI device   */
1976 #define WIN_QUEUED_SERVICE              0xA2
1977 #define WIN_SMART                       0xB0 /* self-monitoring and reporting */
1978 #define CFA_ERASE_SECTORS               0xC0
1979 #define WIN_MULTREAD                    0xC4 /* read sectors using multiple mode*/
1980 #define WIN_MULTWRITE                   0xC5 /* write sectors using multiple mode */
1981 #define WIN_SETMULT                     0xC6 /* enable/disable multiple mode */
1982 #define WIN_READDMA_QUEUED              0xC7 /* read sectors using Queued DMA transfers */
1983 #define WIN_READDMA                     0xC8 /* read sectors using DMA transfers */
1984 #define WIN_READDMA_ONCE                0xC9 /* 28-Bit - without retries */
1985 #define WIN_WRITEDMA                    0xCA /* write sectors using DMA transfers */
1986 #define WIN_WRITEDMA_ONCE               0xCB /* 28-Bit - without retries */
1987 #define WIN_WRITEDMA_QUEUED             0xCC /* write sectors using Queued DMA transfers */
1988 #define CFA_WRITE_MULTI_WO_ERASE        0xCD /* CFA Write multiple without erase */
1989 #define WIN_GETMEDIASTATUS              0xDA    
1990 #define WIN_ACKMEDIACHANGE              0xDB /* ATA-1, ATA-2 vendor */
1991 #define WIN_POSTBOOT                    0xDC
1992 #define WIN_PREBOOT                     0xDD
1993 #define WIN_DOORLOCK                    0xDE /* lock door on removable drives */
1994 #define WIN_DOORUNLOCK                  0xDF /* unlock door on removable drives */
1995 #define WIN_STANDBYNOW1                 0xE0
1996 #define WIN_IDLEIMMEDIATE               0xE1 /* force drive to become "ready" */
1997 #define WIN_STANDBY                     0xE2 /* Set device in Standby Mode */
1998 #define WIN_SETIDLE1                    0xE3
1999 #define WIN_READ_BUFFER                 0xE4 /* force read only 1 sector */
2000 #define WIN_CHECKPOWERMODE1             0xE5
2001 #define WIN_SLEEPNOW1                   0xE6
2002 #define WIN_FLUSH_CACHE                 0xE7
2003 #define WIN_WRITE_BUFFER                0xE8 /* force write only 1 sector */
2004 #define WIN_WRITE_SAME                  0xE9 /* read ata-2 to use */
2005         /* SET_FEATURES 0x22 or 0xDD */
2006 #define WIN_FLUSH_CACHE_EXT             0xEA /* 48-Bit */
2007 #define WIN_IDENTIFY                    0xEC /* ask drive to identify itself    */
2008 #define WIN_MEDIAEJECT                  0xED
2009 #define WIN_IDENTIFY_DMA                0xEE /* same as WIN_IDENTIFY, but DMA */
2010 #define WIN_SETFEATURES                 0xEF /* set special drive features */
2011 #define EXABYTE_ENABLE_NEST             0xF0
2012 #define WIN_SECURITY_SET_PASS           0xF1
2013 #define WIN_SECURITY_UNLOCK             0xF2
2014 #define WIN_SECURITY_ERASE_PREPARE      0xF3
2015 #define WIN_SECURITY_ERASE_UNIT         0xF4
2016 #define WIN_SECURITY_FREEZE_LOCK        0xF5
2017 #define WIN_SECURITY_DISABLE            0xF6
2018 #define WIN_READ_NATIVE_MAX             0xF8 /* return the native maximum address */
2019 #define WIN_SET_MAX                     0xF9
2020 #define DISABLE_SEAGATE                 0xFB
2021
2022 /* set to 1 set disable mult support */
2023 #define MAX_MULT_SECTORS 8
2024
2025 struct IDEState;
2026
2027 typedef void EndTransferFunc(struct IDEState *);
2028
2029 typedef struct IDEState {
2030     /* ide config */
2031     int cylinders, heads, sectors;
2032     int64_t nb_sectors;
2033     int mult_sectors;
2034     int irq;
2035     /* ide regs */
2036     uint8_t feature;
2037     uint8_t error;
2038     uint16_t nsector; /* 0 is 256 to ease computations */
2039     uint8_t sector;
2040     uint8_t lcyl;
2041     uint8_t hcyl;
2042     uint8_t select;
2043     uint8_t status;
2044     /* 0x3f6 command, only meaningful for drive 0 */
2045     uint8_t cmd;
2046     /* depends on bit 4 in select, only meaningful for drive 0 */
2047     struct IDEState *cur_drive; 
2048     BlockDriverState *bs;
2049     int req_nb_sectors; /* number of sectors per interrupt */
2050     EndTransferFunc *end_transfer_func;
2051     uint8_t *data_ptr;
2052     uint8_t *data_end;
2053     uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4];
2054 } IDEState;
2055
2056 IDEState ide_state[MAX_DISKS];
2057
2058 static void padstr(char *str, const char *src, int len)
2059 {
2060     int i, v;
2061     for(i = 0; i < len; i++) {
2062         if (*src)
2063             v = *src++;
2064         else
2065             v = ' ';
2066         *(char *)((long)str ^ 1) = v;
2067         str++;
2068     }
2069 }
2070
2071 static void ide_identify(IDEState *s)
2072 {
2073     uint16_t *p;
2074     unsigned int oldsize;
2075
2076     memset(s->io_buffer, 0, 512);
2077     p = (uint16_t *)s->io_buffer;
2078     stw(p + 0, 0x0040);
2079     stw(p + 1, s->cylinders); 
2080     stw(p + 3, s->heads);
2081     stw(p + 4, 512 * s->sectors); /* sectors */
2082     stw(p + 5, 512); /* sector size */
2083     stw(p + 6, s->sectors); 
2084     stw(p + 20, 3); /* buffer type */
2085     stw(p + 21, 512); /* cache size in sectors */
2086     stw(p + 22, 4); /* ecc bytes */
2087     padstr((uint8_t *)(p + 27), "QEMU HARDDISK", 40);
2088 #if MAX_MULT_SECTORS > 1    
2089     stw(p + 47, MAX_MULT_SECTORS);
2090 #endif
2091     stw(p + 48, 1); /* dword I/O */
2092     stw(p + 49, 1 << 9); /* LBA supported, no DMA */
2093     stw(p + 51, 0x200); /* PIO transfer cycle */
2094     stw(p + 52, 0x200); /* DMA transfer cycle */
2095     stw(p + 54, s->cylinders);
2096     stw(p + 55, s->heads);
2097     stw(p + 56, s->sectors);
2098     oldsize = s->cylinders * s->heads * s->sectors;
2099     stw(p + 57, oldsize);
2100     stw(p + 58, oldsize >> 16);
2101     if (s->mult_sectors)
2102         stw(p + 59, 0x100 | s->mult_sectors);
2103     stw(p + 60, s->nb_sectors);
2104     stw(p + 61, s->nb_sectors >> 16);
2105     stw(p + 80, (1 << 1) | (1 << 2));
2106     stw(p + 82, (1 << 14));
2107     stw(p + 83, (1 << 14));
2108     stw(p + 84, (1 << 14));
2109     stw(p + 85, (1 << 14));
2110     stw(p + 86, 0);
2111     stw(p + 87, (1 << 14));
2112 }
2113
2114 static inline void ide_abort_command(IDEState *s)
2115 {
2116     s->status = READY_STAT | ERR_STAT;
2117     s->error = ABRT_ERR;
2118 }
2119
2120 static inline void ide_set_irq(IDEState *s)
2121 {
2122     if (!(ide_state[0].cmd & IDE_CMD_DISABLE_IRQ)) {
2123         pic_set_irq(s->irq, 1);
2124     }
2125 }
2126
2127 /* prepare data transfer and tell what to do after */
2128 static void ide_transfer_start(IDEState *s, int size, 
2129                                EndTransferFunc *end_transfer_func)
2130 {
2131     s->end_transfer_func = end_transfer_func;
2132     s->data_ptr = s->io_buffer;
2133     s->data_end = s->io_buffer + size;
2134     s->status |= DRQ_STAT;
2135 }
2136
2137 static void ide_transfer_stop(IDEState *s)
2138 {
2139     s->end_transfer_func = ide_transfer_stop;
2140     s->data_ptr = s->io_buffer;
2141     s->data_end = s->io_buffer;
2142     s->status &= ~DRQ_STAT;
2143 }
2144
2145 static int64_t ide_get_sector(IDEState *s)
2146 {
2147     int64_t sector_num;
2148     if (s->select & 0x40) {
2149         /* lba */
2150         sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) | 
2151             (s->lcyl << 8) | s->sector;
2152     } else {
2153         sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors +
2154             (s->select & 0x0f) * s->sectors + 
2155             (s->sector - 1);
2156     }
2157     return sector_num;
2158 }
2159
2160 static void ide_set_sector(IDEState *s, int64_t sector_num)
2161 {
2162     unsigned int cyl, r;
2163     if (s->select & 0x40) {
2164         s->select = (s->select & 0xf0) | (sector_num >> 24);
2165         s->hcyl = (sector_num >> 16);
2166         s->lcyl = (sector_num >> 8);
2167         s->sector = (sector_num);
2168     } else {
2169         cyl = sector_num / (s->heads * s->sectors);
2170         r = sector_num % (s->heads * s->sectors);
2171         s->hcyl = cyl >> 8;
2172         s->lcyl = cyl;
2173         s->select = (s->select & 0xf0) | (r / s->sectors);
2174         s->sector = (r % s->sectors) + 1;
2175     }
2176 }
2177
2178 static void ide_sector_read(IDEState *s)
2179 {
2180     int64_t sector_num;
2181     int ret, n;
2182
2183     s->status = READY_STAT | SEEK_STAT;
2184     sector_num = ide_get_sector(s);
2185     n = s->nsector;
2186     if (n == 0) {
2187         /* no more sector to read from disk */
2188         ide_transfer_stop(s);
2189     } else {
2190 #if defined(DEBUG_IDE)
2191         printf("read sector=%Ld\n", sector_num);
2192 #endif
2193         if (n > s->req_nb_sectors)
2194             n = s->req_nb_sectors;
2195         ret = bdrv_read(s->bs, sector_num, s->io_buffer, n);
2196         ide_transfer_start(s, 512 * n, ide_sector_read);
2197         ide_set_irq(s);
2198         ide_set_sector(s, sector_num + n);
2199         s->nsector -= n;
2200     }
2201 }
2202
2203 static void ide_sector_write(IDEState *s)
2204 {
2205     int64_t sector_num;
2206     int ret, n, n1;
2207
2208     s->status = READY_STAT | SEEK_STAT;
2209     sector_num = ide_get_sector(s);
2210 #if defined(DEBUG_IDE)
2211     printf("write sector=%Ld\n", sector_num);
2212 #endif
2213     n = s->nsector;
2214     if (n > s->req_nb_sectors)
2215         n = s->req_nb_sectors;
2216     ret = bdrv_write(s->bs, sector_num, s->io_buffer, n);
2217     s->nsector -= n;
2218     if (s->nsector == 0) {
2219         /* no more sector to write */
2220         ide_transfer_stop(s);
2221     } else {
2222         n1 = s->nsector;
2223         if (n1 > s->req_nb_sectors)
2224             n1 = s->req_nb_sectors;
2225         ide_transfer_start(s, 512 * n1, ide_sector_write);
2226     }
2227     ide_set_sector(s, sector_num + n);
2228     ide_set_irq(s);
2229 }
2230
2231 void ide_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
2232 {
2233     IDEState *s = ide_state[0].cur_drive;
2234     int unit, n;
2235
2236     addr &= 7;
2237 #ifdef DEBUG_IDE
2238     printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
2239 #endif
2240     switch(addr) {
2241     case 0:
2242         break;
2243     case 1:
2244         s->feature = val;
2245         break;
2246     case 2:
2247         if (val == 0)
2248             val = 256;
2249         s->nsector = val;
2250         break;
2251     case 3:
2252         s->sector = val;
2253         break;
2254     case 4:
2255         s->lcyl = val;
2256         break;
2257     case 5:
2258         s->hcyl = val;
2259         break;
2260     case 6:
2261         /* select drive */
2262         unit = (val >> 4) & 1;
2263         s = &ide_state[unit];
2264         ide_state[0].cur_drive = s;
2265         s->select = val;
2266         break;
2267     default:
2268     case 7:
2269         /* command */
2270 #if defined(DEBUG_IDE)
2271         printf("ide: CMD=%02x\n", val);
2272 #endif
2273         switch(val) {
2274         case WIN_PIDENTIFY:
2275         case WIN_IDENTIFY:
2276             if (s->bs) {
2277                 ide_identify(s);
2278                 s->status = READY_STAT;
2279                 ide_transfer_start(s, 512, ide_transfer_stop);
2280             } else {
2281                 ide_abort_command(s);
2282             }
2283             ide_set_irq(s);
2284             break;
2285         case WIN_SPECIFY:
2286         case WIN_RECAL:
2287             s->status = READY_STAT;
2288             ide_set_irq(s);
2289             break;
2290         case WIN_SETMULT:
2291             if (s->nsector > MAX_MULT_SECTORS || 
2292                 s->nsector == 0 ||
2293                 (s->nsector & (s->nsector - 1)) != 0) {
2294                 ide_abort_command(s);
2295             } else {
2296                 s->mult_sectors = s->nsector;
2297                 s->status = READY_STAT;
2298             }
2299             ide_set_irq(s);
2300             break;
2301         case WIN_READ:
2302         case WIN_READ_ONCE:
2303             s->req_nb_sectors = 1;
2304             ide_sector_read(s);
2305             break;
2306         case WIN_WRITE:
2307         case WIN_WRITE_ONCE:
2308             s->status = SEEK_STAT;
2309             s->req_nb_sectors = 1;
2310             ide_transfer_start(s, 512, ide_sector_write);
2311             break;
2312         case WIN_MULTREAD:
2313             if (!s->mult_sectors)
2314                 goto abort_cmd;
2315             s->req_nb_sectors = s->mult_sectors;
2316             ide_sector_read(s);
2317             break;
2318         case WIN_MULTWRITE:
2319             if (!s->mult_sectors)
2320                 goto abort_cmd;
2321             s->status = SEEK_STAT;
2322             s->req_nb_sectors = s->mult_sectors;
2323             n = s->nsector;
2324             if (n > s->req_nb_sectors)
2325                 n = s->req_nb_sectors;
2326             ide_transfer_start(s, 512 * n, ide_sector_write);
2327             break;
2328         case WIN_READ_NATIVE_MAX:
2329             ide_set_sector(s, s->nb_sectors - 1);
2330             s->status = READY_STAT;
2331             ide_set_irq(s);
2332             break;
2333         default:
2334         abort_cmd:
2335             ide_abort_command(s);
2336             ide_set_irq(s);
2337             break;
2338         }
2339     }
2340 }
2341
2342 uint32_t ide_ioport_read(CPUX86State *env, uint32_t addr)
2343 {
2344     IDEState *s = ide_state[0].cur_drive;
2345     int ret;
2346
2347     addr &= 7;
2348     switch(addr) {
2349     case 0:
2350         ret = 0xff;
2351         break;
2352     case 1:
2353         ret = s->error;
2354         break;
2355     case 2:
2356         ret = s->nsector & 0xff;
2357         break;
2358     case 3:
2359         ret = s->sector;
2360         break;
2361     case 4:
2362         ret = s->lcyl;
2363         break;
2364     case 5:
2365         ret = s->hcyl;
2366         break;
2367     case 6:
2368         ret = s->select;
2369         break;
2370     default:
2371     case 7:
2372         ret = s->status;
2373         pic_set_irq(s->irq, 0);
2374         break;
2375     }
2376 #ifdef DEBUG_IDE
2377     printf("ide: read addr=0x%x val=%02x\n", addr, ret);
2378 #endif
2379     return ret;
2380 }
2381
2382 uint32_t ide_status_read(CPUX86State *env, uint32_t addr)
2383 {
2384     IDEState *s = ide_state[0].cur_drive;
2385     int ret;
2386     ret = s->status;
2387 #ifdef DEBUG_IDE
2388     printf("ide: read status val=%02x\n", ret);
2389 #endif
2390     return ret;
2391 }
2392
2393 void ide_cmd_write(CPUX86State *env, uint32_t addr, uint32_t val)
2394 {
2395     IDEState *s;
2396     int i;
2397
2398 #ifdef DEBUG_IDE
2399     printf("ide: write control val=%02x\n", val);
2400 #endif
2401     /* common for both drives */
2402     if (!(ide_state[0].cmd & IDE_CMD_RESET) &&
2403         (val & IDE_CMD_RESET)) {
2404         /* reset low to high */
2405         for(i = 0;i < 2; i++) {
2406             s = &ide_state[i];
2407             s->status = BUSY_STAT | SEEK_STAT;
2408             s->error = 0x01;
2409         }
2410     } else if ((ide_state[0].cmd & IDE_CMD_RESET) &&
2411                !(val & IDE_CMD_RESET)) {
2412         /* high to low */
2413         for(i = 0;i < 2; i++) {
2414             s = &ide_state[i];
2415             s->status = READY_STAT;
2416             /* set hard disk drive ID */
2417             s->select &= 0xf0; /* clear head */
2418             s->nsector = 1;
2419             s->sector = 1;
2420             if (s->nb_sectors == 0) {
2421                 /* no disk present */
2422                 s->lcyl = 0x12;
2423                 s->hcyl = 0x34;
2424             } else {
2425                 s->lcyl = 0;
2426                 s->hcyl = 0;
2427             }
2428         }
2429     }
2430
2431     ide_state[0].cmd = val;
2432 }
2433
2434 void ide_data_writew(CPUX86State *env, uint32_t addr, uint32_t val)
2435 {
2436     IDEState *s = ide_state[0].cur_drive;
2437     uint8_t *p;
2438
2439     p = s->data_ptr;
2440     *(uint16_t *)p = tswap16(val);
2441     p += 2;
2442     s->data_ptr = p;
2443     if (p >= s->data_end)
2444         s->end_transfer_func(s);
2445 }
2446
2447 uint32_t ide_data_readw(CPUX86State *env, uint32_t addr)
2448 {
2449     IDEState *s = ide_state[0].cur_drive;
2450     uint8_t *p;
2451     int ret;
2452     
2453     p = s->data_ptr;
2454     ret = tswap16(*(uint16_t *)p);
2455     p += 2;
2456     s->data_ptr = p;
2457     if (p >= s->data_end)
2458         s->end_transfer_func(s);
2459     return ret;
2460 }
2461
2462 void ide_data_writel(CPUX86State *env, uint32_t addr, uint32_t val)
2463 {
2464     IDEState *s = ide_state[0].cur_drive;
2465     uint8_t *p;
2466
2467     p = s->data_ptr;
2468     *(uint32_t *)p = tswap32(val);
2469     p += 4;
2470     s->data_ptr = p;
2471     if (p >= s->data_end)
2472         s->end_transfer_func(s);
2473 }
2474
2475 uint32_t ide_data_readl(CPUX86State *env, uint32_t addr)
2476 {
2477     IDEState *s = ide_state[0].cur_drive;
2478     uint8_t *p;
2479     int ret;
2480     
2481     p = s->data_ptr;
2482     ret = tswap32(*(uint32_t *)p);
2483     p += 4;
2484     s->data_ptr = p;
2485     if (p >= s->data_end)
2486         s->end_transfer_func(s);
2487     return ret;
2488 }
2489
2490 void ide_reset(IDEState *s)
2491 {
2492     s->mult_sectors = MAX_MULT_SECTORS;
2493     s->status = READY_STAT;
2494     s->cur_drive = s;
2495     s->select = 0xa0;
2496 }
2497
2498 void ide_init(void)
2499 {
2500     IDEState *s;
2501     int i, cylinders;
2502     int64_t nb_sectors;
2503
2504     for(i = 0; i < MAX_DISKS; i++) {
2505         s = &ide_state[i];
2506         s->bs = bs_table[i];
2507         if (s->bs) {
2508             bdrv_get_geometry(s->bs, &nb_sectors);
2509             if (s->cylinders == 0) {
2510                 /* if no geometry, use a LBA compatible one */
2511                 cylinders = nb_sectors / (16 * 63);
2512                 if (cylinders > 16383)
2513                     cylinders = 16383;
2514                 else if (cylinders < 2)
2515                     cylinders = 2;
2516                 s->cylinders = cylinders;
2517                 s->heads = 16;
2518                 s->sectors = 63;
2519             }
2520             s->nb_sectors = nb_sectors;
2521         }
2522         s->irq = 14;
2523         ide_reset(s);
2524     }
2525     register_ioport_write(0x1f0, 8, ide_ioport_write, 1);
2526     register_ioport_read(0x1f0, 8, ide_ioport_read, 1);
2527     register_ioport_read(0x3f6, 1, ide_status_read, 1);
2528     register_ioport_write(0x3f6, 1, ide_cmd_write, 1);
2529
2530     /* data ports */
2531     register_ioport_write(0x1f0, 2, ide_data_writew, 2);
2532     register_ioport_read(0x1f0, 2, ide_data_readw, 2);
2533     register_ioport_write(0x1f0, 4, ide_data_writel, 4);
2534     register_ioport_read(0x1f0, 4, ide_data_readl, 4);
2535 }
2536
2537 /***********************************************************/
2538 /* keyboard emulation */
2539
2540 /*      Keyboard Controller Commands */
2541 #define KBD_CCMD_READ_MODE      0x20    /* Read mode bits */
2542 #define KBD_CCMD_WRITE_MODE     0x60    /* Write mode bits */
2543 #define KBD_CCMD_GET_VERSION    0xA1    /* Get controller version */
2544 #define KBD_CCMD_MOUSE_DISABLE  0xA7    /* Disable mouse interface */
2545 #define KBD_CCMD_MOUSE_ENABLE   0xA8    /* Enable mouse interface */
2546 #define KBD_CCMD_TEST_MOUSE     0xA9    /* Mouse interface test */
2547 #define KBD_CCMD_SELF_TEST      0xAA    /* Controller self test */
2548 #define KBD_CCMD_KBD_TEST       0xAB    /* Keyboard interface test */
2549 #define KBD_CCMD_KBD_DISABLE    0xAD    /* Keyboard interface disable */
2550 #define KBD_CCMD_KBD_ENABLE     0xAE    /* Keyboard interface enable */
2551 #define KBD_CCMD_READ_INPORT    0xC0    /* read input port */
2552 #define KBD_CCMD_READ_OUTPORT   0xD0    /* read output port */
2553 #define KBD_CCMD_WRITE_OUTPORT  0xD1    /* write output port */
2554 #define KBD_CCMD_WRITE_OBUF     0xD2
2555 #define KBD_CCMD_WRITE_AUX_OBUF 0xD3    /* Write to output buffer as if
2556                                            initiated by the auxiliary device */
2557 #define KBD_CCMD_WRITE_MOUSE    0xD4    /* Write the following byte to the mouse */
2558 #define KBD_CCMD_ENABLE_A20     0xDD
2559 #define KBD_CCMD_DISABLE_A20    0xDF
2560 #define KBD_CCMD_RESET          0xFE
2561
2562 /* Keyboard Commands */
2563 #define KBD_CMD_SET_LEDS        0xED    /* Set keyboard leds */
2564 #define KBD_CMD_ECHO            0xEE
2565 #define KBD_CMD_SET_RATE        0xF3    /* Set typematic rate */
2566 #define KBD_CMD_ENABLE          0xF4    /* Enable scanning */
2567 #define KBD_CMD_RESET_DISABLE   0xF5    /* reset and disable scanning */
2568 #define KBD_CMD_RESET_ENABLE    0xF6    /* reset and enable scanning */
2569 #define KBD_CMD_RESET           0xFF    /* Reset */
2570
2571 /* Keyboard Replies */
2572 #define KBD_REPLY_POR           0xAA    /* Power on reset */
2573 #define KBD_REPLY_ACK           0xFA    /* Command ACK */
2574 #define KBD_REPLY_RESEND        0xFE    /* Command NACK, send the cmd again */
2575
2576 /* Status Register Bits */
2577 #define KBD_STAT_OBF            0x01    /* Keyboard output buffer full */
2578 #define KBD_STAT_IBF            0x02    /* Keyboard input buffer full */
2579 #define KBD_STAT_SELFTEST       0x04    /* Self test successful */
2580 #define KBD_STAT_CMD            0x08    /* Last write was a command write (0=data) */
2581 #define KBD_STAT_UNLOCKED       0x10    /* Zero if keyboard locked */
2582 #define KBD_STAT_MOUSE_OBF      0x20    /* Mouse output buffer full */
2583 #define KBD_STAT_GTO            0x40    /* General receive/xmit timeout */
2584 #define KBD_STAT_PERR           0x80    /* Parity error */
2585
2586 /* Controller Mode Register Bits */
2587 #define KBD_MODE_KBD_INT        0x01    /* Keyboard data generate IRQ1 */
2588 #define KBD_MODE_MOUSE_INT      0x02    /* Mouse data generate IRQ12 */
2589 #define KBD_MODE_SYS            0x04    /* The system flag (?) */
2590 #define KBD_MODE_NO_KEYLOCK     0x08    /* The keylock doesn't affect the keyboard if set */
2591 #define KBD_MODE_DISABLE_KBD    0x10    /* Disable keyboard interface */
2592 #define KBD_MODE_DISABLE_MOUSE  0x20    /* Disable mouse interface */
2593 #define KBD_MODE_KCC            0x40    /* Scan code conversion to PC format */
2594 #define KBD_MODE_RFU            0x80
2595
2596 /* Mouse Commands */
2597 #define AUX_SET_RES             0xE8    /* Set resolution */
2598 #define AUX_SET_SCALE11         0xE6    /* Set 1:1 scaling */
2599 #define AUX_SET_SCALE21         0xE7    /* Set 2:1 scaling */
2600 #define AUX_GET_SCALE           0xE9    /* Get scaling factor */
2601 #define AUX_SET_STREAM          0xEA    /* Set stream mode */
2602 #define AUX_SET_SAMPLE          0xF3    /* Set sample rate */
2603 #define AUX_ENABLE_DEV          0xF4    /* Enable aux device */
2604 #define AUX_DISABLE_DEV         0xF5    /* Disable aux device */
2605 #define AUX_RESET               0xFF    /* Reset aux device */
2606 #define AUX_ACK                 0xFA    /* Command byte ACK. */
2607
2608 #define KBD_QUEUE_SIZE 64
2609
2610 typedef struct {
2611     uint8_t data[KBD_QUEUE_SIZE];
2612     int rptr, wptr, count;
2613 } KBDQueue;
2614
2615 enum KBDWriteState {
2616     KBD_STATE_CMD = 0,
2617     KBD_STATE_LED,
2618 };
2619
2620 typedef struct KBDState {
2621     KBDQueue queues[2];
2622     uint8_t write_cmd; /* if non zero, write data to port 60 is expected */
2623     uint8_t status;
2624     uint8_t mode;
2625     int kbd_write_cmd;
2626     int scan_enabled;
2627 } KBDState;
2628
2629 KBDState kbd_state;
2630 int reset_requested;
2631 int a20_enabled;
2632
2633 static void kbd_update_irq(KBDState *s)
2634 {
2635     int level;
2636     
2637     level = ((s->status & KBD_STAT_OBF) && (s->mode & KBD_MODE_KBD_INT));
2638     pic_set_irq(1, level);
2639     
2640     level = ((s->status & KBD_STAT_MOUSE_OBF) && (s->mode & KBD_MODE_MOUSE_INT));
2641     pic_set_irq(12, level);
2642 }
2643
2644 static void kbd_queue(KBDState *s, int b, int aux)
2645 {
2646     KBDQueue *q = &kbd_state.queues[aux];
2647
2648     if (q->count >= KBD_QUEUE_SIZE)
2649         return;
2650     q->data[q->wptr] = b;
2651     if (++q->wptr == KBD_QUEUE_SIZE)
2652         q->wptr = 0;
2653     q->count++;
2654     s->status |= KBD_STAT_OBF;
2655     if (aux)
2656         s->status |= KBD_STAT_MOUSE_OBF;
2657     kbd_update_irq(s);
2658 }
2659
2660 uint32_t kbd_read_status(CPUX86State *env, uint32_t addr)
2661 {
2662     KBDState *s = &kbd_state;
2663     int val;
2664     val = s->status;
2665 #if defined(DEBUG_KBD) && 0
2666     printf("kbd: read status=0x%02x\n", val);
2667 #endif
2668     return val;
2669 }
2670
2671 void kbd_write_command(CPUX86State *env, uint32_t addr, uint32_t val)
2672 {
2673     KBDState *s = &kbd_state;
2674
2675 #ifdef DEBUG_KBD
2676     printf("kbd: write cmd=0x%02x\n", val);
2677 #endif
2678     switch(val) {
2679     case KBD_CCMD_READ_MODE:
2680         kbd_queue(s, s->mode, 0);
2681         break;
2682     case KBD_CCMD_WRITE_MODE:
2683     case KBD_CCMD_WRITE_OBUF:
2684     case KBD_CCMD_WRITE_AUX_OBUF:
2685     case KBD_CCMD_WRITE_MOUSE:
2686     case KBD_CCMD_WRITE_OUTPORT:
2687         s->write_cmd = val;
2688         break;
2689     case KBD_CCMD_MOUSE_DISABLE:
2690         s->mode |= KBD_MODE_DISABLE_MOUSE;
2691         break;
2692     case KBD_CCMD_MOUSE_ENABLE:
2693         s->mode &= ~KBD_MODE_DISABLE_MOUSE;
2694         break;
2695     case KBD_CCMD_TEST_MOUSE:
2696         kbd_queue(s, 0x00, 0);
2697         break;
2698     case KBD_CCMD_SELF_TEST:
2699         s->status |= KBD_STAT_SELFTEST;
2700         kbd_queue(s, 0x55, 0);
2701         break;
2702     case KBD_CCMD_KBD_TEST:
2703         kbd_queue(s, 0x00, 0);
2704         break;
2705     case KBD_CCMD_KBD_DISABLE:
2706         s->mode |= KBD_MODE_DISABLE_KBD;
2707         break;
2708     case KBD_CCMD_KBD_ENABLE:
2709         s->mode &= ~KBD_MODE_DISABLE_KBD;
2710         break;
2711     case KBD_CCMD_READ_INPORT:
2712         kbd_queue(s, 0x00, 0);
2713         break;
2714     case KBD_CCMD_READ_OUTPORT:
2715         /* XXX: check that */
2716         val = 0x01 | (a20_enabled << 1);
2717         if (s->status & KBD_STAT_OBF)
2718             val |= 0x10;
2719         if (s->status & KBD_STAT_MOUSE_OBF)
2720             val |= 0x20;
2721         kbd_queue(s, val, 0);
2722         break;
2723     case KBD_CCMD_ENABLE_A20:
2724         a20_enabled = 1;
2725         break;
2726     case KBD_CCMD_DISABLE_A20:
2727         a20_enabled = 0;
2728         break;
2729     case KBD_CCMD_RESET:
2730         reset_requested = 1;
2731         cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
2732         break;
2733     default:
2734         fprintf(stderr, "vl: unsupported keyboard cmd=0x%02x\n", val);
2735         break;
2736     }
2737 }
2738
2739 uint32_t kbd_read_data(CPUX86State *env, uint32_t addr)
2740 {
2741     KBDState *s = &kbd_state;
2742     KBDQueue *q;
2743     int val;
2744     
2745     q = &s->queues[1]; /* first check AUX data */
2746     if (q->count == 0)
2747         q = &s->queues[0]; /* then check KBD data */
2748     if (q->count == 0) {
2749         /* XXX: return something else ? */
2750         val = 0;
2751     } else {
2752         val = q->data[q->rptr];
2753         if (++q->rptr == KBD_QUEUE_SIZE)
2754             q->rptr = 0;
2755         q->count--;
2756     }
2757     if (s->queues[1].count == 0) {
2758         s->status &= ~KBD_STAT_MOUSE_OBF;
2759         if (s->queues[0].count == 0)
2760             s->status &= ~KBD_STAT_OBF;
2761         kbd_update_irq(s);
2762     }
2763
2764 #ifdef DEBUG_KBD
2765     printf("kbd: read data=0x%02x\n", val);
2766 #endif
2767     return val;
2768 }
2769
2770 static void kbd_reset_keyboard(KBDState *s)
2771 {
2772     s->scan_enabled = 1;
2773 }
2774
2775 static void kbd_write_keyboard(KBDState *s, int val)
2776 {
2777     switch(s->kbd_write_cmd) {
2778     default:
2779     case -1:
2780         switch(val) {
2781         case 0x00:
2782             kbd_queue(s, KBD_REPLY_ACK, 0);
2783             break;
2784         case 0x05:
2785             kbd_queue(s, KBD_REPLY_RESEND, 0);
2786             break;
2787         case KBD_CMD_ECHO:
2788             kbd_queue(s, KBD_CMD_ECHO, 0);
2789             break;
2790         case KBD_CMD_ENABLE:
2791             s->scan_enabled = 1;
2792             kbd_queue(s, KBD_REPLY_ACK, 0);
2793             break;
2794         case KBD_CMD_SET_LEDS:
2795         case KBD_CMD_SET_RATE:
2796             s->kbd_write_cmd = val;
2797             break;
2798         case KBD_CMD_RESET_DISABLE:
2799             kbd_reset_keyboard(s);
2800             s->scan_enabled = 0;
2801             kbd_queue(s, KBD_REPLY_ACK, 0);
2802             break;
2803         case KBD_CMD_RESET_ENABLE:
2804             kbd_reset_keyboard(s);
2805             s->scan_enabled = 1;
2806             kbd_queue(s, KBD_REPLY_ACK, 0);
2807             break;
2808         case KBD_CMD_RESET:
2809             kbd_reset_keyboard(s);
2810             kbd_queue(s, KBD_REPLY_ACK, 0);
2811             kbd_queue(s, KBD_REPLY_POR, 0);
2812             break;
2813         default:
2814             kbd_queue(s, KBD_REPLY_ACK, 0);
2815             break;
2816         }
2817         break;
2818     case KBD_CMD_SET_LEDS:
2819         kbd_queue(s, KBD_REPLY_ACK, 0);
2820         break;
2821     case KBD_CMD_SET_RATE:
2822         kbd_queue(s, KBD_REPLY_ACK, 0);
2823         break;
2824     }
2825     s->kbd_write_cmd = -1;
2826 }
2827
2828 void kbd_write_data(CPUX86State *env, uint32_t addr, uint32_t val)
2829 {
2830     KBDState *s = &kbd_state;
2831
2832 #ifdef DEBUG_KBD
2833     printf("kbd: write data=0x%02x\n", val);
2834 #endif
2835
2836     switch(s->write_cmd) {
2837     case 0:
2838         kbd_write_keyboard(s, val);
2839         break;
2840     case KBD_CCMD_WRITE_MODE:
2841         s->mode = val;
2842         kbd_update_irq(s);
2843         break;
2844     case KBD_CCMD_WRITE_OBUF:
2845         kbd_queue(s, val, 0);
2846         break;
2847     case KBD_CCMD_WRITE_AUX_OBUF:
2848         kbd_queue(s, val, 1);
2849         break;
2850     case KBD_CCMD_WRITE_OUTPORT:
2851         a20_enabled = (val >> 1) & 1;
2852         if (!(val & 1)) {
2853             reset_requested = 1;
2854             cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
2855         }
2856         break;
2857     default:
2858         break;
2859     }
2860     s->write_cmd = 0;
2861 }
2862
2863 void kbd_reset(KBDState *s)
2864 {
2865     KBDQueue *q;
2866     int i;
2867
2868     s->kbd_write_cmd = -1;
2869     s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;
2870     s->status = KBD_MODE_SYS | KBD_MODE_NO_KEYLOCK;
2871     for(i = 0; i < 2; i++) {
2872         q = &s->queues[i];
2873         q->rptr = 0;
2874         q->wptr = 0;
2875         q->count = 0;
2876     }
2877 }
2878
2879 void kbd_init(void)
2880 {
2881     kbd_reset(&kbd_state);
2882     register_ioport_read(0x60, 1, kbd_read_data, 1);
2883     register_ioport_write(0x60, 1, kbd_write_data, 1);
2884     register_ioport_read(0x64, 1, kbd_read_status, 1);
2885     register_ioport_write(0x64, 1, kbd_write_command, 1);
2886 }
2887
2888 /***********************************************************/
2889 /* Bochs BIOS debug ports */
2890
2891 void bochs_bios_write(CPUX86State *env, uint32_t addr, uint32_t val)
2892 {
2893     switch(addr) {
2894         /* Bochs BIOS messages */
2895     case 0x400:
2896     case 0x401:
2897         fprintf(stderr, "BIOS panic at rombios.c, line %d\n", val);
2898         exit(1);
2899     case 0x402:
2900     case 0x403:
2901 #ifdef DEBUG_BIOS
2902         fprintf(stderr, "%c", val);
2903 #endif
2904         break;
2905
2906         /* LGPL'ed VGA BIOS messages */
2907     case 0x501:
2908     case 0x502:
2909         fprintf(stderr, "VGA BIOS panic, line %d\n", val);
2910         exit(1);
2911     case 0x500:
2912     case 0x503:
2913 #ifdef DEBUG_BIOS
2914         fprintf(stderr, "%c", val);
2915 #endif
2916         break;
2917     }
2918 }
2919
2920 void bochs_bios_init(void)
2921 {
2922     register_ioport_write(0x400, 1, bochs_bios_write, 2);
2923     register_ioport_write(0x401, 1, bochs_bios_write, 2);
2924     register_ioport_write(0x402, 1, bochs_bios_write, 1);
2925     register_ioport_write(0x403, 1, bochs_bios_write, 1);
2926
2927     register_ioport_write(0x501, 1, bochs_bios_write, 2);
2928     register_ioport_write(0x502, 1, bochs_bios_write, 2);
2929     register_ioport_write(0x500, 1, bochs_bios_write, 1);
2930     register_ioport_write(0x503, 1, bochs_bios_write, 1);
2931 }
2932
2933 /***********************************************************/
2934 /* cpu signal handler */
2935 static void host_segv_handler(int host_signum, siginfo_t *info, 
2936                               void *puc)
2937 {
2938     if (cpu_signal_handler(host_signum, info, puc))
2939         return;
2940     term_exit();
2941     abort();
2942 }
2943
2944 static int timer_irq_pending;
2945 static int timer_irq_count;
2946
2947 static void host_alarm_handler(int host_signum, siginfo_t *info, 
2948                                void *puc)
2949 {
2950     /* NOTE: since usually the OS asks a 100 Hz clock, there can be
2951        some drift between cpu_get_ticks() and the interrupt time. So
2952        we queue some interrupts to avoid missing some */
2953     timer_irq_count += pit_get_out_edges(&pit_channels[0]);
2954     if (timer_irq_count) {
2955         if (timer_irq_count > 2)
2956             timer_irq_count = 2;
2957         timer_irq_count--;
2958         /* just exit from the cpu to have a chance to handle timers */
2959         cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
2960         timer_irq_pending = 1;
2961     }
2962 }
2963
2964 unsigned long mmap_addr = PHYS_RAM_BASE;
2965
2966 void *get_mmap_addr(unsigned long size)
2967 {
2968     unsigned long addr;
2969     addr = mmap_addr;
2970     mmap_addr += ((size + 4095) & ~4095) + 4096;
2971     return (void *)addr;
2972 }
2973
2974 /* main execution loop */
2975
2976 CPUState *cpu_gdbstub_get_env(void *opaque)
2977 {
2978     return global_env;
2979 }
2980
2981 int main_loop(void *opaque)
2982 {
2983     struct pollfd ufds[2], *pf, *serial_ufd, *net_ufd, *gdb_ufd;
2984     int ret, n, timeout;
2985     uint8_t ch;
2986     CPUState *env = global_env;
2987
2988     for(;;) {
2989
2990         ret = cpu_x86_exec(env);
2991         if (reset_requested)
2992             break;
2993         if (ret == EXCP_DEBUG)
2994             return EXCP_DEBUG;
2995         /* if hlt instruction, we wait until the next IRQ */
2996         if (ret == EXCP_HLT) 
2997             timeout = 10;
2998         else
2999             timeout = 0;
3000         /* poll any events */
3001         serial_ufd = NULL;
3002         pf = ufds;
3003         if (!(serial_ports[0].lsr & UART_LSR_DR)) {
3004             serial_ufd = pf;
3005             pf->fd = 0;
3006             pf->events = POLLIN;
3007             pf++;
3008         }
3009         net_ufd = NULL;
3010         if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) {
3011             net_ufd = pf;
3012             pf->fd = net_fd;
3013             pf->events = POLLIN;
3014             pf++;
3015         }
3016         gdb_ufd = NULL;
3017         if (gdbstub_fd > 0) {
3018             gdb_ufd = pf;
3019             pf->fd = gdbstub_fd;
3020             pf->events = POLLIN;
3021             pf++;
3022         }
3023
3024         ret = poll(ufds, pf - ufds, timeout);
3025         if (ret > 0) {
3026             if (serial_ufd && (serial_ufd->revents & POLLIN)) {
3027                 n = read(0, &ch, 1);
3028                 if (n == 1) {
3029                     serial_received_byte(&serial_ports[0], ch);
3030                 }
3031             }
3032             if (net_ufd && (net_ufd->revents & POLLIN)) {
3033                 uint8_t buf[MAX_ETH_FRAME_SIZE];
3034
3035                 n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);
3036                 if (n > 0) {
3037                     if (n < 60) {
3038                         memset(buf + n, 0, 60 - n);
3039                         n = 60;
3040                     }
3041                     ne2000_receive(&ne2000_state, buf, n);
3042                 }
3043             }
3044             if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {
3045                 uint8_t buf[1];
3046                 /* stop emulation if requested by gdb */
3047                 n = read(gdbstub_fd, buf, 1);
3048                 if (n == 1)
3049                     break;
3050             }
3051         }
3052
3053         /* timer IRQ */
3054         if (timer_irq_pending) {
3055             pic_set_irq(0, 1);
3056             pic_set_irq(0, 0);
3057             timer_irq_pending = 0;
3058         }
3059     }
3060     return EXCP_INTERRUPT;
3061 }
3062
3063 void help(void)
3064 {
3065     printf("Virtual Linux version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
3066            "usage: vl [options] [bzImage [kernel parameters...]]\n"
3067            "\n"
3068            "'bzImage' is a Linux kernel image (PAGE_OFFSET must be defined\n"
3069            "to 0x90000000 in asm/page.h and arch/i386/vmlinux.lds)\n"
3070            "\n"
3071            "General options:\n"
3072            "-initrd file   use 'file' as initial ram disk\n"
3073            "-hda file      use 'file' as hard disk 0 image\n"
3074            "-hdb file      use 'file' as hard disk 1 image\n"
3075            "-snapshot      write to temporary files instead of disk image files\n"
3076            "-m megs        set virtual RAM size to megs MB\n"
3077            "-n script      set network init script [default=%s]\n"
3078            "\n"
3079            "Debug/Expert options:\n"
3080            "-s             wait gdb connection to port %d\n"
3081            "-p port        change gdb connection port\n"
3082            "-d             output log in /tmp/vl.log\n"
3083            "-hdachs c,h,s  force hard disk 0 geometry for non LBA disk images\n"
3084            "-L path        set the directory for the BIOS and VGA BIOS\n"
3085            "\n"
3086            "During emulation, use C-a h to get terminal commands:\n",
3087            DEFAULT_NETWORK_SCRIPT, DEFAULT_GDBSTUB_PORT);
3088     term_print_help();
3089     exit(1);
3090 }
3091
3092 struct option long_options[] = {
3093     { "initrd", 1, NULL, 0, },
3094     { "hda", 1, NULL, 0, },
3095     { "hdb", 1, NULL, 0, },
3096     { "snapshot", 0, NULL, 0, },
3097     { "hdachs", 1, NULL, 0, },
3098     { NULL, 0, NULL, 0 },
3099 };
3100
3101 int main(int argc, char **argv)
3102 {
3103     int c, ret, initrd_size, i, use_gdbstub, gdbstub_port, long_index;
3104     int snapshot, linux_boot;
3105     struct linux_params *params;
3106     struct sigaction act;
3107     struct itimerval itv;
3108     CPUX86State *env;
3109     const char *tmpdir, *initrd_filename;
3110     const char *hd_filename[MAX_DISKS];
3111     
3112     /* we never want that malloc() uses mmap() */
3113     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
3114     initrd_filename = NULL;
3115     for(i = 0; i < MAX_DISKS; i++)
3116         hd_filename[i] = NULL;
3117     phys_ram_size = 32 * 1024 * 1024;
3118     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
3119     use_gdbstub = 0;
3120     gdbstub_port = DEFAULT_GDBSTUB_PORT;
3121     snapshot = 0;
3122     linux_boot = 0;
3123     for(;;) {
3124         c = getopt_long_only(argc, argv, "hm:dn:sp:L:", long_options, &long_index);
3125         if (c == -1)
3126             break;
3127         switch(c) {
3128         case 0:
3129             switch(long_index) {
3130             case 0:
3131                 initrd_filename = optarg;
3132                 break;
3133             case 1:
3134                 hd_filename[0] = optarg;
3135                 break;
3136             case 2:
3137                 hd_filename[1] = optarg;
3138                 break;
3139             case 3:
3140                 snapshot = 1;
3141                 break;
3142             case 4:
3143                 {
3144                     int cyls, heads, secs;
3145                     const char *p;
3146                     p = optarg;
3147                     cyls = strtol(p, (char **)&p, 0);
3148                     if (*p != ',')
3149                         goto chs_fail;
3150                     p++;
3151                     heads = strtol(p, (char **)&p, 0);
3152                     if (*p != ',')
3153                         goto chs_fail;
3154                     p++;
3155                     secs = strtol(p, (char **)&p, 0);
3156                     if (*p != '\0')
3157                         goto chs_fail;
3158                     ide_state[0].cylinders = cyls;
3159                     ide_state[0].heads = heads;
3160                     ide_state[0].sectors = secs;
3161                 chs_fail: ;
3162                 }
3163                 break;
3164             }
3165             break;
3166         case 'h':
3167             help();
3168             break;
3169         case 'm':
3170             phys_ram_size = atoi(optarg) * 1024 * 1024;
3171             if (phys_ram_size <= 0)
3172                 help();
3173             if (phys_ram_size > PHYS_RAM_MAX_SIZE) {
3174                 fprintf(stderr, "vl: at most %d MB RAM can be simulated\n",
3175                         PHYS_RAM_MAX_SIZE / (1024 * 1024));
3176                 exit(1);
3177             }
3178             break;
3179         case 'd':
3180             loglevel = 1;
3181             break;
3182         case 'n':
3183             pstrcpy(network_script, sizeof(network_script), optarg);
3184             break;
3185         case 's':
3186             use_gdbstub = 1;
3187             break;
3188         case 'p':
3189             gdbstub_port = atoi(optarg);
3190             break;
3191         case 'L':
3192             interp_prefix = optarg;
3193             break;
3194         }
3195     }
3196
3197     linux_boot = (optind < argc);
3198         
3199     if (!linux_boot && hd_filename[0] == '\0')
3200         help();
3201
3202     /* init debug */
3203     setvbuf(stdout, NULL, _IOLBF, 0);
3204     if (loglevel) {
3205         logfile = fopen(DEBUG_LOGFILE, "w");
3206         if (!logfile) {
3207             perror(DEBUG_LOGFILE);
3208             _exit(1);
3209         }
3210         setvbuf(logfile, NULL, _IOLBF, 0);
3211     }
3212
3213     /* init network tun interface */
3214     net_init();
3215
3216     /* init the memory */
3217     tmpdir = getenv("VLTMPDIR");
3218     if (!tmpdir)
3219         tmpdir = "/tmp";
3220     snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3221     if (mkstemp(phys_ram_file) < 0) {
3222         fprintf(stderr, "Could not create temporary memory file '%s'\n", 
3223                 phys_ram_file);
3224         exit(1);
3225     }
3226     phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3227     if (phys_ram_fd < 0) {
3228         fprintf(stderr, "Could not open temporary memory file '%s'\n", 
3229                 phys_ram_file);
3230         exit(1);
3231     }
3232     ftruncate(phys_ram_fd, phys_ram_size);
3233     unlink(phys_ram_file);
3234     phys_ram_base = mmap(get_mmap_addr(phys_ram_size), phys_ram_size, 
3235                          PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
3236                          phys_ram_fd, 0);
3237     if (phys_ram_base == MAP_FAILED) {
3238         fprintf(stderr, "Could not map physical memory\n");
3239         exit(1);
3240     }
3241
3242     /* open the virtual block devices */
3243     for(i = 0; i < MAX_DISKS; i++) {
3244         if (hd_filename[i]) {
3245             bs_table[i] = bdrv_open(hd_filename[i], snapshot);
3246             if (!bs_table[i]) {
3247                 fprintf(stderr, "vl: could not open hard disk image '%s\n",
3248                         hd_filename[i]);
3249                 exit(1);
3250             }
3251         }
3252     }
3253
3254     /* init CPU state */
3255     env = cpu_init();
3256     global_env = env;
3257     cpu_single_env = env;
3258
3259     init_ioports();
3260
3261     if (linux_boot) {
3262         /* now we can load the kernel */
3263         ret = load_kernel(argv[optind], phys_ram_base + KERNEL_LOAD_ADDR);
3264         if (ret < 0) {
3265             fprintf(stderr, "vl: could not load kernel '%s'\n", argv[optind]);
3266             exit(1);
3267         }
3268         
3269         /* load initrd */
3270         initrd_size = 0;
3271         if (initrd_filename) {
3272             initrd_size = load_image(initrd_filename, phys_ram_base + INITRD_LOAD_ADDR);
3273             if (initrd_size < 0) {
3274                 fprintf(stderr, "vl: could not load initial ram disk '%s'\n", 
3275                         initrd_filename);
3276                 exit(1);
3277             }
3278         }
3279         
3280         /* init kernel params */
3281         params = (void *)(phys_ram_base + KERNEL_PARAMS_ADDR);
3282         memset(params, 0, sizeof(struct linux_params));
3283         params->mount_root_rdonly = 0;
3284         params->cl_magic = 0xA33F;
3285         params->cl_offset = params->commandline - (uint8_t *)params;
3286         params->alt_mem_k = (phys_ram_size / 1024) - 1024;
3287         for(i = optind + 1; i < argc; i++) {
3288             if (i != optind + 1)
3289                 pstrcat(params->commandline, sizeof(params->commandline), " ");
3290             pstrcat(params->commandline, sizeof(params->commandline), argv[i]);
3291         }
3292         params->loader_type = 0x01;
3293         if (initrd_size > 0) {
3294             params->initrd_start = INITRD_LOAD_ADDR;
3295             params->initrd_size = initrd_size;
3296         }
3297         params->orig_video_lines = 25;
3298         params->orig_video_cols = 80;
3299
3300         /* setup basic memory access */
3301         env->cr[0] = 0x00000033;
3302         cpu_x86_init_mmu(env);
3303         
3304         memset(params->idt_table, 0, sizeof(params->idt_table));
3305         
3306         params->gdt_table[2] = 0x00cf9a000000ffffLL; /* KERNEL_CS */
3307         params->gdt_table[3] = 0x00cf92000000ffffLL; /* KERNEL_DS */
3308         
3309         env->idt.base = (void *)params->idt_table;
3310         env->idt.limit = sizeof(params->idt_table) - 1;
3311         env->gdt.base = (void *)params->gdt_table;
3312         env->gdt.limit = sizeof(params->gdt_table) - 1;
3313         
3314         cpu_x86_load_seg(env, R_CS, KERNEL_CS);
3315         cpu_x86_load_seg(env, R_DS, KERNEL_DS);
3316         cpu_x86_load_seg(env, R_ES, KERNEL_DS);
3317         cpu_x86_load_seg(env, R_SS, KERNEL_DS);
3318         cpu_x86_load_seg(env, R_FS, KERNEL_DS);
3319         cpu_x86_load_seg(env, R_GS, KERNEL_DS);
3320         
3321         env->eip = KERNEL_LOAD_ADDR;
3322         env->regs[R_ESI] = KERNEL_PARAMS_ADDR;
3323         env->eflags = 0x2;
3324
3325     } else {
3326         char buf[1024];
3327         
3328         /* RAW PC boot */
3329
3330         /* BIOS load */
3331         snprintf(buf, sizeof(buf), "%s/%s", interp_prefix, BIOS_FILENAME);
3332         ret = load_image(buf, phys_ram_base + 0x000f0000);
3333         if (ret != 0x10000) {
3334             fprintf(stderr, "vl: could not load PC bios '%s'\n", BIOS_FILENAME);
3335             exit(1);
3336         }
3337
3338         /* VGA BIOS load */
3339         snprintf(buf, sizeof(buf), "%s/%s", interp_prefix, VGABIOS_FILENAME);
3340         ret = load_image(buf, phys_ram_base + 0x000c0000);
3341
3342         /* setup basic memory access */
3343         env->cr[0] = 0x60000010;
3344         cpu_x86_init_mmu(env);
3345         
3346         env->idt.limit = 0xffff;
3347         env->gdt.limit = 0xffff;
3348         env->ldt.limit = 0xffff;
3349
3350         /* not correct (CS base=0xffff0000) */
3351         cpu_x86_load_seg(env, R_CS, 0xf000); 
3352         cpu_x86_load_seg(env, R_DS, 0);
3353         cpu_x86_load_seg(env, R_ES, 0);
3354         cpu_x86_load_seg(env, R_SS, 0);
3355         cpu_x86_load_seg(env, R_FS, 0);
3356         cpu_x86_load_seg(env, R_GS, 0);
3357
3358         env->eip = 0xfff0;
3359         env->regs[R_EDX] = 0x600; /* indicate P6 processor */
3360
3361         env->eflags = 0x2;
3362
3363         bochs_bios_init();
3364     }
3365
3366     /* init basic PC hardware */
3367     register_ioport_write(0x80, 1, ioport80_write, 1);
3368
3369     register_ioport_write(0x3d4, 2, vga_ioport_write, 1);
3370
3371     cmos_init();
3372     pic_init();
3373     pit_init();
3374     serial_init();
3375     ne2000_init();
3376     ide_init();
3377     kbd_init();
3378
3379     /* setup cpu signal handlers for MMU / self modifying code handling */
3380     sigfillset(&act.sa_mask);
3381     act.sa_flags = SA_SIGINFO;
3382     act.sa_sigaction = host_segv_handler;
3383     sigaction(SIGSEGV, &act, NULL);
3384     sigaction(SIGBUS, &act, NULL);
3385
3386     act.sa_sigaction = host_alarm_handler;
3387     sigaction(SIGALRM, &act, NULL);
3388
3389     itv.it_interval.tv_sec = 0;
3390     itv.it_interval.tv_usec = 1000;
3391     itv.it_value.tv_sec = 0;
3392     itv.it_value.tv_usec = 10 * 1000;
3393     setitimer(ITIMER_REAL, &itv, NULL);
3394     /* we probe the tick duration of the kernel to inform the user if
3395        the emulated kernel requested a too high timer frequency */
3396     getitimer(ITIMER_REAL, &itv);
3397     pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) / 
3398         1000000;
3399     
3400     if (use_gdbstub) {
3401         cpu_gdbstub(NULL, main_loop, gdbstub_port);
3402     } else {
3403         main_loop(NULL);
3404     }
3405     return 0;
3406 }