added NE2000 emulation
[qemu] / vl.c
1 /*
2  * QEMU based User Mode Linux 
3  * 
4  * This file is part of proprietary software - it is published here
5  * only for demonstration and information purposes.
6  * 
7  * Copyright (c) 2003 Fabrice Bellard 
8  */
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <getopt.h>
13 #include <inttypes.h>
14 #include <unistd.h>
15 #include <sys/mman.h>
16 #include <fcntl.h>
17 #include <signal.h>
18 #include <time.h>
19 #include <sys/time.h>
20 #include <malloc.h>
21 #include <termios.h>
22 #include <sys/poll.h>
23 #include <errno.h>
24 #include <sys/wait.h>
25
26 #include <sys/ioctl.h>
27 #include <sys/socket.h>
28 #include <linux/if.h>
29 #include <linux/if_tun.h>
30
31 #include "cpu-i386.h"
32 #include "disas.h"
33
34 #define DEBUG_LOGFILE "/tmp/vl.log"
35 #define DEFAULT_NETWORK_SCRIPT "/etc/vl-ifup"
36
37 //#define DEBUG_UNUSED_IOPORT
38
39 #define PHYS_RAM_BASE 0xa8000000
40 #define KERNEL_LOAD_ADDR   0x00100000
41 #define INITRD_LOAD_ADDR   0x00400000
42 #define KERNEL_PARAMS_ADDR 0x00090000
43
44 /* from plex86 (BSD license) */
45 struct  __attribute__ ((packed)) linux_params {
46   // For 0x00..0x3f, see 'struct screen_info' in linux/include/linux/tty.h.
47   // I just padded out the VESA parts, rather than define them.
48
49   /* 0x000 */ uint8_t   orig_x;
50   /* 0x001 */ uint8_t   orig_y;
51   /* 0x002 */ uint16_t  ext_mem_k;
52   /* 0x004 */ uint16_t  orig_video_page;
53   /* 0x006 */ uint8_t   orig_video_mode;
54   /* 0x007 */ uint8_t   orig_video_cols;
55   /* 0x008 */ uint16_t  unused1;
56   /* 0x00a */ uint16_t  orig_video_ega_bx;
57   /* 0x00c */ uint16_t  unused2;
58   /* 0x00e */ uint8_t   orig_video_lines;
59   /* 0x00f */ uint8_t   orig_video_isVGA;
60   /* 0x010 */ uint16_t  orig_video_points;
61   /* 0x012 */ uint8_t   pad0[0x20 - 0x12]; // VESA info.
62   /* 0x020 */ uint16_t  cl_magic;  // Commandline magic number (0xA33F)
63   /* 0x022 */ uint16_t  cl_offset; // Commandline offset.  Address of commandline
64                                  // is calculated as 0x90000 + cl_offset, bu
65                                  // only if cl_magic == 0xA33F.
66   /* 0x024 */ uint8_t   pad1[0x40 - 0x24]; // VESA info.
67
68   /* 0x040 */ uint8_t   apm_bios_info[20]; // struct apm_bios_info
69   /* 0x054 */ uint8_t   pad2[0x80 - 0x54];
70
71   // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.
72   // Might be truncated?
73   /* 0x080 */ uint8_t   hd0_info[16]; // hd0-disk-parameter from intvector 0x41
74   /* 0x090 */ uint8_t   hd1_info[16]; // hd1-disk-parameter from intvector 0x46
75
76   // System description table truncated to 16 bytes
77   // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.
78   /* 0x0a0 */ uint16_t  sys_description_len;
79   /* 0x0a2 */ uint8_t   sys_description_table[14];
80                         // [0] machine id
81                         // [1] machine submodel id
82                         // [2] BIOS revision
83                         // [3] bit1: MCA bus
84
85   /* 0x0b0 */ uint8_t   pad3[0x1e0 - 0xb0];
86   /* 0x1e0 */ uint32_t  alt_mem_k;
87   /* 0x1e4 */ uint8_t   pad4[4];
88   /* 0x1e8 */ uint8_t   e820map_entries;
89   /* 0x1e9 */ uint8_t   eddbuf_entries; // EDD_NR
90   /* 0x1ea */ uint8_t   pad5[0x1f1 - 0x1ea];
91   /* 0x1f1 */ uint8_t   setup_sects; // size of setup.S, number of sectors
92   /* 0x1f2 */ uint16_t  mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)
93   /* 0x1f4 */ uint16_t  sys_size; // size of compressed kernel-part in the
94                                 // (b)zImage-file (in 16 byte units, rounded up)
95   /* 0x1f6 */ uint16_t  swap_dev; // (unused AFAIK)
96   /* 0x1f8 */ uint16_t  ramdisk_flags;
97   /* 0x1fa */ uint16_t  vga_mode; // (old one)
98   /* 0x1fc */ uint16_t  orig_root_dev; // (high=Major, low=minor)
99   /* 0x1fe */ uint8_t   pad6[1];
100   /* 0x1ff */ uint8_t   aux_device_info;
101   /* 0x200 */ uint16_t  jump_setup; // Jump to start of setup code,
102                                   // aka "reserved" field.
103   /* 0x202 */ uint8_t   setup_signature[4]; // Signature for SETUP-header, ="HdrS"
104   /* 0x206 */ uint16_t  header_format_version; // Version number of header format;
105   /* 0x208 */ uint8_t   setup_S_temp0[8]; // Used by setup.S for communication with
106                                         // boot loaders, look there.
107   /* 0x210 */ uint8_t   loader_type;
108                         // 0 for old one.
109                         // else 0xTV:
110                         //   T=0: LILO
111                         //   T=1: Loadlin
112                         //   T=2: bootsect-loader
113                         //   T=3: SYSLINUX
114                         //   T=4: ETHERBOOT
115                         //   V=version
116   /* 0x211 */ uint8_t   loadflags;
117                         // bit0 = 1: kernel is loaded high (bzImage)
118                         // bit7 = 1: Heap and pointer (see below) set by boot
119                         //   loader.
120   /* 0x212 */ uint16_t  setup_S_temp1;
121   /* 0x214 */ uint32_t  kernel_start;
122   /* 0x218 */ uint32_t  initrd_start;
123   /* 0x21c */ uint32_t  initrd_size;
124   /* 0x220 */ uint8_t   setup_S_temp2[4];
125   /* 0x224 */ uint16_t  setup_S_heap_end_pointer;
126   /* 0x226 */ uint8_t   pad7[0x2d0 - 0x226];
127
128   /* 0x2d0 : Int 15, ax=e820 memory map. */
129   // (linux/include/asm-i386/e820.h, 'struct e820entry')
130 #define E820MAX  32
131 #define E820_RAM  1
132 #define E820_RESERVED 2
133 #define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */
134 #define E820_NVS  4
135   struct {
136     uint64_t addr;
137     uint64_t size;
138     uint32_t type;
139     } e820map[E820MAX];
140
141   /* 0x550 */ uint8_t   pad8[0x600 - 0x550];
142
143   // BIOS Enhanced Disk Drive Services.
144   // (From linux/include/asm-i386/edd.h, 'struct edd_info')
145   // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.
146   /* 0x600 */ uint8_t   eddbuf[0x7d4 - 0x600];
147
148   /* 0x7d4 */ uint8_t   pad9[0x800 - 0x7d4];
149   /* 0x800 */ uint8_t   commandline[0x800];
150
151   /* 0x1000 */
152   uint64_t gdt_table[256];
153   uint64_t idt_table[48];
154 };
155
156 #define KERNEL_CS     0x10
157 #define KERNEL_DS     0x18
158
159 typedef void (IOPortWriteFunc)(CPUX86State *env, uint32_t address, uint32_t data);
160 typedef uint32_t (IOPortReadFunc)(CPUX86State *env, uint32_t address);
161
162 #define MAX_IOPORTS 1024
163
164 char phys_ram_file[1024];
165 CPUX86State *global_env;
166 FILE *logfile = NULL;
167 int loglevel;
168 IOPortReadFunc *ioport_readb_table[MAX_IOPORTS];
169 IOPortWriteFunc *ioport_writeb_table[MAX_IOPORTS];
170 IOPortReadFunc *ioport_readw_table[MAX_IOPORTS];
171 IOPortWriteFunc *ioport_writew_table[MAX_IOPORTS];
172
173 /***********************************************************/
174 /* x86 io ports */
175
176 uint32_t default_ioport_readb(CPUX86State *env, uint32_t address)
177 {
178 #ifdef DEBUG_UNUSED_IOPORT
179     fprintf(stderr, "inb: port=0x%04x\n", address);
180 #endif
181     return 0;
182 }
183
184 void default_ioport_writeb(CPUX86State *env, uint32_t address, uint32_t data)
185 {
186 #ifdef DEBUG_UNUSED_IOPORT
187     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
188 #endif
189 }
190
191 /* default is to make two byte accesses */
192 uint32_t default_ioport_readw(CPUX86State *env, uint32_t address)
193 {
194     uint32_t data;
195     data = ioport_readb_table[address](env, address);
196     data |= ioport_readb_table[address + 1](env, address + 1) << 8;
197     return data;
198 }
199
200 void default_ioport_writew(CPUX86State *env, uint32_t address, uint32_t data)
201 {
202     ioport_writeb_table[address](env, address, data & 0xff);
203     ioport_writeb_table[address + 1](env, address + 1, (data >> 8) & 0xff);
204 }
205
206 void init_ioports(void)
207 {
208     int i;
209
210     for(i = 0; i < MAX_IOPORTS; i++) {
211         ioport_readb_table[i] = default_ioport_readb;
212         ioport_writeb_table[i] = default_ioport_writeb;
213         ioport_readw_table[i] = default_ioport_readw;
214         ioport_writew_table[i] = default_ioport_writew;
215     }
216 }
217
218 int register_ioport_readb(int start, int length, IOPortReadFunc *func)
219 {
220     int i;
221
222     for(i = start; i < start + length; i++)
223         ioport_readb_table[i] = func;
224     return 0;
225 }
226
227 int register_ioport_writeb(int start, int length, IOPortWriteFunc *func)
228 {
229     int i;
230
231     for(i = start; i < start + length; i++)
232         ioport_writeb_table[i] = func;
233     return 0;
234 }
235
236 int register_ioport_readw(int start, int length, IOPortReadFunc *func)
237 {
238     int i;
239
240     for(i = start; i < start + length; i += 2)
241         ioport_readw_table[i] = func;
242     return 0;
243 }
244
245 int register_ioport_writew(int start, int length, IOPortWriteFunc *func)
246 {
247     int i;
248
249     for(i = start; i < start + length; i += 2)
250         ioport_writew_table[i] = func;
251     return 0;
252 }
253
254 void pstrcpy(char *buf, int buf_size, const char *str)
255 {
256     int c;
257     char *q = buf;
258
259     if (buf_size <= 0)
260         return;
261
262     for(;;) {
263         c = *str++;
264         if (c == 0 || q >= buf + buf_size - 1)
265             break;
266         *q++ = c;
267     }
268     *q = '\0';
269 }
270
271 /* strcat and truncate. */
272 char *pstrcat(char *buf, int buf_size, const char *s)
273 {
274     int len;
275     len = strlen(buf);
276     if (len < buf_size) 
277         pstrcpy(buf + len, buf_size - len, s);
278     return buf;
279 }
280
281 int load_kernel(const char *filename, uint8_t *addr)
282 {
283     int fd, size, setup_sects;
284     uint8_t bootsect[512];
285
286     fd = open(filename, O_RDONLY);
287     if (fd < 0)
288         return -1;
289     if (read(fd, bootsect, 512) != 512)
290         goto fail;
291     setup_sects = bootsect[0x1F1];
292     if (!setup_sects)
293         setup_sects = 4;
294     /* skip 16 bit setup code */
295     lseek(fd, (setup_sects + 1) * 512, SEEK_SET);
296     size = read(fd, addr, 16 * 1024 * 1024);
297     if (size < 0)
298         goto fail;
299     close(fd);
300     return size;
301  fail:
302     close(fd);
303     return -1;
304 }
305
306 /* return the size or -1 if error */
307 int load_image(const char *filename, uint8_t *addr)
308 {
309     int fd, size;
310     fd = open(filename, O_RDONLY);
311     if (fd < 0)
312         return -1;
313     size = lseek(fd, 0, SEEK_END);
314     lseek(fd, 0, SEEK_SET);
315     if (read(fd, addr, size) != size) {
316         close(fd);
317         return -1;
318     }
319     close(fd);
320     return size;
321 }
322
323 void cpu_x86_outb(CPUX86State *env, int addr, int val)
324 {
325     ioport_writeb_table[addr & (MAX_IOPORTS - 1)](env, addr, val);
326 }
327
328 void cpu_x86_outw(CPUX86State *env, int addr, int val)
329 {
330     ioport_writew_table[addr & (MAX_IOPORTS - 1)](env, addr, val);
331 }
332
333 void cpu_x86_outl(CPUX86State *env, int addr, int val)
334 {
335     fprintf(stderr, "outl: port=0x%04x, data=%08x\n", addr, val);
336 }
337
338 int cpu_x86_inb(CPUX86State *env, int addr)
339 {
340     return ioport_readb_table[addr & (MAX_IOPORTS - 1)](env, addr);
341 }
342
343 int cpu_x86_inw(CPUX86State *env, int addr)
344 {
345     return ioport_readw_table[addr & (MAX_IOPORTS - 1)](env, addr);
346 }
347
348 int cpu_x86_inl(CPUX86State *env, int addr)
349 {
350     fprintf(stderr, "inl: port=0x%04x\n", addr);
351     return 0;
352 }
353
354 /***********************************************************/
355 void ioport80_write(CPUX86State *env, uint32_t addr, uint32_t data)
356 {
357 }
358
359 void hw_error(const char *fmt, ...)
360 {
361     va_list ap;
362
363     va_start(ap, fmt);
364     fprintf(stderr, "qemu: hardware error: ");
365     vfprintf(stderr, fmt, ap);
366     fprintf(stderr, "\n");
367 #ifdef TARGET_I386
368     cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
369 #endif
370     va_end(ap);
371     abort();
372 }
373
374 /***********************************************************/
375 /* vga emulation */
376 static uint8_t vga_index;
377 static uint8_t vga_regs[256];
378 static int last_cursor_pos;
379
380 void update_console_messages(void)
381 {
382     int c, i, cursor_pos, eol;
383
384     cursor_pos = vga_regs[0x0f] | (vga_regs[0x0e] << 8);
385     eol = 0;
386     for(i = last_cursor_pos; i < cursor_pos; i++) {
387         c = phys_ram_base[0xb8000 + (i) * 2];
388         if (c >= ' ') {
389             putchar(c);
390             eol = 0;
391         } else {
392             if (!eol)
393                 putchar('\n');
394             eol = 1;
395         }
396     }
397     fflush(stdout);
398     last_cursor_pos = cursor_pos;
399 }
400
401 /* just to see first Linux console messages, we intercept cursor position */
402 void vga_ioport_write(CPUX86State *env, uint32_t addr, uint32_t data)
403 {
404     switch(addr) {
405     case 0x3d4:
406         vga_index = data;
407         break;
408     case 0x3d5:
409         vga_regs[vga_index] = data;
410         if (vga_index == 0x0f)
411             update_console_messages();
412         break;
413     }
414             
415 }
416
417 /***********************************************************/
418 /* cmos emulation */
419
420 #define RTC_SECONDS             0
421 #define RTC_SECONDS_ALARM       1
422 #define RTC_MINUTES             2
423 #define RTC_MINUTES_ALARM       3
424 #define RTC_HOURS               4
425 #define RTC_HOURS_ALARM         5
426 #define RTC_ALARM_DONT_CARE    0xC0
427
428 #define RTC_DAY_OF_WEEK         6
429 #define RTC_DAY_OF_MONTH        7
430 #define RTC_MONTH               8
431 #define RTC_YEAR                9
432
433 #define RTC_REG_A               10
434 #define RTC_REG_B               11
435 #define RTC_REG_C               12
436 #define RTC_REG_D               13
437
438 /* PC cmos mappings */
439 #define REG_EQUIPMENT_BYTE          0x14
440
441 uint8_t cmos_data[128];
442 uint8_t cmos_index;
443
444 void cmos_ioport_write(CPUX86State *env, uint32_t addr, uint32_t data)
445 {
446     if (addr == 0x70) {
447         cmos_index = data & 0x7f;
448     }
449 }
450
451 uint32_t cmos_ioport_read(CPUX86State *env, uint32_t addr)
452 {
453     int ret;
454
455     if (addr == 0x70) {
456         return 0xff;
457     } else {
458         /* toggle update-in-progress bit for Linux (same hack as
459            plex86) */
460         ret = cmos_data[cmos_index];
461         if (cmos_index == RTC_REG_A)
462             cmos_data[RTC_REG_A] ^= 0x80; 
463         else if (cmos_index == RTC_REG_C)
464             cmos_data[RTC_REG_C] = 0x00; 
465         return ret;
466     }
467 }
468
469
470 static inline int to_bcd(int a)
471 {
472     return ((a / 10) << 4) | (a % 10);
473 }
474
475 void cmos_init(void)
476 {
477     struct tm *tm;
478     time_t ti;
479
480     ti = time(NULL);
481     tm = gmtime(&ti);
482     cmos_data[RTC_SECONDS] = to_bcd(tm->tm_sec);
483     cmos_data[RTC_MINUTES] = to_bcd(tm->tm_min);
484     cmos_data[RTC_HOURS] = to_bcd(tm->tm_hour);
485     cmos_data[RTC_DAY_OF_WEEK] = to_bcd(tm->tm_wday);
486     cmos_data[RTC_DAY_OF_MONTH] = to_bcd(tm->tm_mday);
487     cmos_data[RTC_MONTH] = to_bcd(tm->tm_mon);
488     cmos_data[RTC_YEAR] = to_bcd(tm->tm_year % 100);
489
490     cmos_data[RTC_REG_A] = 0x26;
491     cmos_data[RTC_REG_B] = 0x02;
492     cmos_data[RTC_REG_C] = 0x00;
493     cmos_data[RTC_REG_D] = 0x80;
494
495     cmos_data[REG_EQUIPMENT_BYTE] = 0x02; /* FPU is there */
496
497     register_ioport_writeb(0x70, 2, cmos_ioport_write);
498     register_ioport_readb(0x70, 2, cmos_ioport_read);
499 }
500
501 /***********************************************************/
502 /* 8259 pic emulation */
503
504 typedef struct PicState {
505     uint8_t last_irr; /* edge detection */
506     uint8_t irr; /* interrupt request register */
507     uint8_t imr; /* interrupt mask register */
508     uint8_t isr; /* interrupt service register */
509     uint8_t priority_add; /* used to compute irq priority */
510     uint8_t irq_base;
511     uint8_t read_reg_select;
512     uint8_t special_mask;
513     uint8_t init_state;
514     uint8_t auto_eoi;
515     uint8_t rotate_on_autoeoi;
516     uint8_t init4; /* true if 4 byte init */
517 } PicState;
518
519 /* 0 is master pic, 1 is slave pic */
520 PicState pics[2];
521 int pic_irq_requested;
522
523 /* set irq level. If an edge is detected, then the IRR is set to 1 */
524 static inline void pic_set_irq1(PicState *s, int irq, int level)
525 {
526     int mask;
527     mask = 1 << irq;
528     if (level) {
529         if ((s->last_irr & mask) == 0)
530             s->irr |= mask;
531         s->last_irr |= mask;
532     } else {
533         s->last_irr &= ~mask;
534     }
535 }
536
537 static inline int get_priority(PicState *s, int mask)
538 {
539     int priority;
540     if (mask == 0)
541         return -1;
542     priority = 7;
543     while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)
544         priority--;
545     return priority;
546 }
547
548 /* return the pic wanted interrupt. return -1 if none */
549 static int pic_get_irq(PicState *s)
550 {
551     int mask, cur_priority, priority;
552
553     mask = s->irr & ~s->imr;
554     priority = get_priority(s, mask);
555     if (priority < 0)
556         return -1;
557     /* compute current priority */
558     cur_priority = get_priority(s, s->isr);
559     if (priority > cur_priority) {
560         /* higher priority found: an irq should be generated */
561         return priority;
562     } else {
563         return -1;
564     }
565 }
566
567 void pic_set_irq(int irq, int level)
568 {
569     pic_set_irq1(&pics[irq >> 3], irq & 7, level);
570 }
571
572 /* can be called at any time outside cpu_exec() to raise irqs if
573    necessary */
574 void pic_handle_irq(void)
575 {
576     int irq2, irq;
577
578     /* first look at slave pic */
579     irq2 = pic_get_irq(&pics[1]);
580     if (irq2 >= 0) {
581         /* if irq request by slave pic, signal master PIC */
582         pic_set_irq1(&pics[0], 2, 1);
583         pic_set_irq1(&pics[0], 2, 0);
584     }
585     /* look at requested irq */
586     irq = pic_get_irq(&pics[0]);
587     if (irq >= 0) {
588         if (irq == 2) {
589             /* from slave pic */
590             pic_irq_requested = 8 + irq2;
591         } else {
592             /* from master pic */
593             pic_irq_requested = irq;
594         }
595         global_env->hard_interrupt_request = 1;
596     }
597 }
598
599 int cpu_x86_get_pic_interrupt(CPUX86State *env)
600 {
601     int irq, irq2, intno;
602
603     /* signal the pic that the irq was acked by the CPU */
604     irq = pic_irq_requested;
605     if (irq >= 8) {
606         irq2 = irq & 7;
607         pics[1].isr |= (1 << irq2);
608         pics[1].irr &= ~(1 << irq2);
609         irq = 2;
610         intno = pics[1].irq_base + irq2;
611     } else {
612         intno = pics[0].irq_base + irq;
613     }
614     pics[0].isr |= (1 << irq);
615     pics[0].irr &= ~(1 << irq);
616     return intno;
617 }
618
619 void pic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
620 {
621     PicState *s;
622     int priority;
623
624     s = &pics[addr >> 7];
625     addr &= 1;
626     if (addr == 0) {
627         if (val & 0x10) {
628             /* init */
629             memset(s, 0, sizeof(PicState));
630             s->init_state = 1;
631             s->init4 = val & 1;
632             if (val & 0x02)
633                 hw_error("single mode not supported");
634             if (val & 0x08)
635                 hw_error("level sensitive irq not supported");
636         } else if (val & 0x08) {
637             if (val & 0x02)
638                 s->read_reg_select = val & 1;
639             if (val & 0x40)
640                 s->special_mask = (val >> 5) & 1;
641         } else {
642             switch(val) {
643             case 0x00:
644             case 0x80:
645                 s->rotate_on_autoeoi = val >> 7;
646                 break;
647             case 0x20: /* end of interrupt */
648             case 0xa0:
649                 priority = get_priority(s, s->isr);
650                 if (priority >= 0) {
651                     s->isr &= ~(1 << ((priority + s->priority_add) & 7));
652                 }
653                 if (val == 0xa0)
654                     s->priority_add = (s->priority_add + 1) & 7;
655                 break;
656             case 0x60 ... 0x67:
657                 priority = val & 7;
658                 s->isr &= ~(1 << priority);
659                 break;
660             case 0xc0 ... 0xc7:
661                 s->priority_add = (val + 1) & 7;
662                 break;
663             case 0xe0 ... 0xe7:
664                 priority = val & 7;
665                 s->isr &= ~(1 << priority);
666                 s->priority_add = (priority + 1) & 7;
667                 break;
668             }
669         }
670     } else {
671         switch(s->init_state) {
672         case 0:
673             /* normal mode */
674             s->imr = val;
675             break;
676         case 1:
677             s->irq_base = val & 0xf8;
678             s->init_state = 2;
679             break;
680         case 2:
681             if (s->init4) {
682                 s->init_state = 3;
683             } else {
684                 s->init_state = 0;
685             }
686             break;
687         case 3:
688             s->auto_eoi = (val >> 1) & 1;
689             s->init_state = 0;
690             break;
691         }
692     }
693 }
694
695 uint32_t pic_ioport_read(CPUX86State *env, uint32_t addr)
696 {
697     PicState *s;
698     s = &pics[addr >> 7];
699     addr &= 1;
700     if (addr == 0) {
701         if (s->read_reg_select)
702             return s->isr;
703         else
704             return s->irr;
705     } else {
706         return s->imr;
707     }
708 }
709
710 void pic_init(void)
711 {
712     register_ioport_writeb(0x20, 2, pic_ioport_write);
713     register_ioport_readb(0x20, 2, pic_ioport_read);
714     register_ioport_writeb(0xa0, 2, pic_ioport_write);
715     register_ioport_readb(0xa0, 2, pic_ioport_read);
716 }
717
718 /***********************************************************/
719 /* 8253 PIT emulation */
720
721 #define PIT_FREQ 1193182
722
723 #define RW_STATE_LSB 0
724 #define RW_STATE_MSB 1
725 #define RW_STATE_WORD0 2
726 #define RW_STATE_WORD1 3
727 #define RW_STATE_LATCHED_WORD0 4
728 #define RW_STATE_LATCHED_WORD1 5
729
730 typedef struct PITChannelState {
731     uint16_t count;
732     uint16_t latched_count;
733     uint8_t rw_state;
734     uint8_t mode;
735     uint8_t bcd; /* not supported */
736     uint8_t gate; /* timer start */
737     int64_t count_load_time;
738 } PITChannelState;
739
740 PITChannelState pit_channels[3];
741 int speaker_data_on;
742
743 int64_t ticks_per_sec;
744
745 int64_t get_clock(void)
746 {
747     struct timeval tv;
748     gettimeofday(&tv, NULL);
749     return tv.tv_sec * 1000000LL + tv.tv_usec;
750 }
751
752 int64_t cpu_get_ticks(void)
753 {
754     int64_t val;
755     asm("rdtsc" : "=A" (val));
756     return val;
757 }
758
759 void cpu_calibrate_ticks(void)
760 {
761     int64_t usec, ticks;
762
763     usec = get_clock();
764     ticks = cpu_get_ticks();
765     usleep(50 * 1000);
766     usec = get_clock() - usec;
767     ticks = cpu_get_ticks() - ticks;
768     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
769 }
770
771 static int pit_get_count(PITChannelState *s)
772 {
773     int64_t d;
774     int counter;
775
776     d = ((cpu_get_ticks() - s->count_load_time) * PIT_FREQ) / 
777         ticks_per_sec;
778     switch(s->mode) {
779     case 0:
780     case 1:
781     case 4:
782     case 5:
783         counter = (s->count - d) & 0xffff;
784         break;
785     default:
786         counter = s->count - (d % s->count);
787         break;
788     }
789     return counter;
790 }
791
792 /* get pit output bit */
793 static int pit_get_out(PITChannelState *s)
794 {
795     int64_t d;
796     int out;
797
798     d = ((cpu_get_ticks() - s->count_load_time) * PIT_FREQ) / 
799         ticks_per_sec;
800     switch(s->mode) {
801     default:
802     case 0:
803         out = (d >= s->count);
804         break;
805     case 1:
806         out = (d < s->count);
807         break;
808     case 2:
809         if ((d % s->count) == 0 && d != 0)
810             out = 1;
811         else
812             out = 0;
813         break;
814     case 3:
815         out = (d % s->count) < (s->count >> 1);
816         break;
817     case 4:
818     case 5:
819         out = (d == s->count);
820         break;
821     }
822     return out;
823 }
824
825 void pit_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
826 {
827     int channel, access;
828     PITChannelState *s;
829     
830     addr &= 3;
831     if (addr == 3) {
832         channel = val >> 6;
833         if (channel == 3)
834             return;
835         s = &pit_channels[channel];
836         access = (val >> 4) & 3;
837         switch(access) {
838         case 0:
839             s->latched_count = pit_get_count(s);
840             s->rw_state = RW_STATE_LATCHED_WORD0;
841             break;
842         default:
843             s->rw_state = access - 1 +  RW_STATE_LSB;
844             break;
845         }
846         s->mode = (val >> 1) & 7;
847         s->bcd = val & 1;
848     } else {
849         s = &pit_channels[addr];
850         switch(s->rw_state) {
851         case RW_STATE_LSB:
852             s->count_load_time = cpu_get_ticks();
853             s->count = val;
854             break;
855         case RW_STATE_MSB:
856             s->count_load_time = cpu_get_ticks();
857             s->count = (val << 8);
858             break;
859         case RW_STATE_WORD0:
860         case RW_STATE_WORD1:
861             if (s->rw_state & 1) {
862                 s->count_load_time = cpu_get_ticks();
863                 s->count = (s->latched_count & 0xff) | (val << 8);
864             } else {
865                 s->latched_count = val;
866             }
867             s->rw_state ^= 1;
868             break;
869         }
870     }
871 }
872
873 uint32_t pit_ioport_read(CPUX86State *env, uint32_t addr)
874 {
875     int ret, count;
876     PITChannelState *s;
877     
878     addr &= 3;
879     s = &pit_channels[addr];
880     switch(s->rw_state) {
881     case RW_STATE_LSB:
882     case RW_STATE_MSB:
883     case RW_STATE_WORD0:
884     case RW_STATE_WORD1:
885         count = pit_get_count(s);
886         if (s->rw_state & 1)
887             ret = (count >> 8) & 0xff;
888         else
889             ret = count & 0xff;
890         if (s->rw_state & 2)
891             s->rw_state ^= 1;
892         break;
893     default:
894     case RW_STATE_LATCHED_WORD0:
895     case RW_STATE_LATCHED_WORD1:
896         if (s->rw_state & 1)
897             ret = s->latched_count >> 8;
898         else
899             ret = s->latched_count & 0xff;
900         s->rw_state ^= 1;
901         break;
902     }
903     return ret;
904 }
905
906 void speaker_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
907 {
908     speaker_data_on = (val >> 1) & 1;
909     pit_channels[2].gate = val & 1;
910 }
911
912 uint32_t speaker_ioport_read(CPUX86State *env, uint32_t addr)
913 {
914     int out;
915     out = pit_get_out(&pit_channels[2]);
916     return (speaker_data_on << 1) | pit_channels[2].gate | (out << 5);
917 }
918
919 void pit_init(void)
920 {
921     pit_channels[0].gate = 1;
922     pit_channels[1].gate = 1;
923     pit_channels[2].gate = 0;
924     
925     register_ioport_writeb(0x40, 4, pit_ioport_write);
926     register_ioport_readb(0x40, 3, pit_ioport_read);
927
928     register_ioport_readb(0x61, 1, speaker_ioport_read);
929     register_ioport_writeb(0x61, 1, speaker_ioport_write);
930     cpu_calibrate_ticks();
931 }
932
933 /***********************************************************/
934 /* serial port emulation */
935
936 #define UART_IRQ        4
937
938 #define UART_LCR_DLAB   0x80    /* Divisor latch access bit */
939
940 #define UART_IER_MSI    0x08    /* Enable Modem status interrupt */
941 #define UART_IER_RLSI   0x04    /* Enable receiver line status interrupt */
942 #define UART_IER_THRI   0x02    /* Enable Transmitter holding register int. */
943 #define UART_IER_RDI    0x01    /* Enable receiver data interrupt */
944
945 #define UART_IIR_NO_INT 0x01    /* No interrupts pending */
946 #define UART_IIR_ID     0x06    /* Mask for the interrupt ID */
947
948 #define UART_IIR_MSI    0x00    /* Modem status interrupt */
949 #define UART_IIR_THRI   0x02    /* Transmitter holding register empty */
950 #define UART_IIR_RDI    0x04    /* Receiver data interrupt */
951 #define UART_IIR_RLSI   0x06    /* Receiver line status interrupt */
952
953 #define UART_LSR_TEMT   0x40    /* Transmitter empty */
954 #define UART_LSR_THRE   0x20    /* Transmit-hold-register empty */
955 #define UART_LSR_BI     0x10    /* Break interrupt indicator */
956 #define UART_LSR_FE     0x08    /* Frame error indicator */
957 #define UART_LSR_PE     0x04    /* Parity error indicator */
958 #define UART_LSR_OE     0x02    /* Overrun error indicator */
959 #define UART_LSR_DR     0x01    /* Receiver data ready */
960
961 typedef struct SerialState {
962     uint8_t divider;
963     uint8_t rbr; /* receive register */
964     uint8_t ier;
965     uint8_t iir; /* read only */
966     uint8_t lcr;
967     uint8_t mcr;
968     uint8_t lsr; /* read only */
969     uint8_t msr;
970     uint8_t scr;
971 } SerialState;
972
973 SerialState serial_ports[1];
974
975 void serial_update_irq(void)
976 {
977     SerialState *s = &serial_ports[0];
978
979     if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {
980         s->iir = UART_IIR_RDI;
981     } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {
982         s->iir = UART_IIR_THRI;
983     } else {
984         s->iir = UART_IIR_NO_INT;
985     }
986     if (s->iir != UART_IIR_NO_INT) {
987         pic_set_irq(UART_IRQ, 1);
988     } else {
989         pic_set_irq(UART_IRQ, 0);
990     }
991 }
992
993 void serial_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
994 {
995     SerialState *s = &serial_ports[0];
996     unsigned char ch;
997     int ret;
998     
999     addr &= 7;
1000     switch(addr) {
1001     default:
1002     case 0:
1003         if (s->lcr & UART_LCR_DLAB) {
1004             s->divider = (s->divider & 0xff00) | val;
1005         } else {
1006             s->lsr &= ~UART_LSR_THRE;
1007             serial_update_irq();
1008
1009             ch = val;
1010             do {
1011                 ret = write(1, &ch, 1);
1012             } while (ret != 1);
1013             s->lsr |= UART_LSR_THRE;
1014             s->lsr |= UART_LSR_TEMT;
1015             serial_update_irq();
1016         }
1017         break;
1018     case 1:
1019         if (s->lcr & UART_LCR_DLAB) {
1020             s->divider = (s->divider & 0x00ff) | (val << 8);
1021         } else {
1022             s->ier = val;
1023             serial_update_irq();
1024         }
1025         break;
1026     case 2:
1027         break;
1028     case 3:
1029         s->lcr = val;
1030         break;
1031     case 4:
1032         s->mcr = val;
1033         break;
1034     case 5:
1035         break;
1036     case 6:
1037         s->msr = val;
1038         break;
1039     case 7:
1040         s->scr = val;
1041         break;
1042     }
1043 }
1044
1045 uint32_t serial_ioport_read(CPUX86State *env, uint32_t addr)
1046 {
1047     SerialState *s = &serial_ports[0];
1048     uint32_t ret;
1049
1050     addr &= 7;
1051     switch(addr) {
1052     default:
1053     case 0:
1054         if (s->lcr & UART_LCR_DLAB) {
1055             ret = s->divider & 0xff; 
1056         } else {
1057             ret = s->rbr;
1058             s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
1059             serial_update_irq();
1060         }
1061         break;
1062     case 1:
1063         if (s->lcr & UART_LCR_DLAB) {
1064             ret = (s->divider >> 8) & 0xff;
1065         } else {
1066             ret = s->ier;
1067         }
1068         break;
1069     case 2:
1070         ret = s->iir;
1071         break;
1072     case 3:
1073         ret = s->lcr;
1074         break;
1075     case 4:
1076         ret = s->mcr;
1077         break;
1078     case 5:
1079         ret = s->lsr;
1080         break;
1081     case 6:
1082         ret = s->msr;
1083         break;
1084     case 7:
1085         ret = s->scr;
1086         break;
1087     }
1088     return ret;
1089 }
1090
1091 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1092 static int term_got_escape;
1093
1094 void term_print_help(void)
1095 {
1096     printf("\n"
1097            "C-a h    print this help\n"
1098            "C-a x    exit emulatior\n"
1099            "C-a b    send break (magic sysrq)\n"
1100            "C-a C-a  send C-a\n"
1101            );
1102 }
1103
1104 /* called when a char is received */
1105 void serial_received_byte(SerialState *s, int ch)
1106 {
1107     if (term_got_escape) {
1108         term_got_escape = 0;
1109         switch(ch) {
1110         case 'h':
1111             term_print_help();
1112             break;
1113         case 'x':
1114             exit(0);
1115             break;
1116         case 'b':
1117             /* send break */
1118             s->rbr = 0;
1119             s->lsr |= UART_LSR_BI | UART_LSR_DR;
1120             serial_update_irq();
1121             break;
1122         case TERM_ESCAPE:
1123             goto send_char;
1124         }
1125     } else if (ch == TERM_ESCAPE) {
1126         term_got_escape = 1;
1127     } else {
1128     send_char:
1129         s->rbr = ch;
1130         s->lsr |= UART_LSR_DR;
1131         serial_update_irq();
1132     }
1133 }
1134
1135 /* init terminal so that we can grab keys */
1136 static struct termios oldtty;
1137
1138 static void term_exit(void)
1139 {
1140     tcsetattr (0, TCSANOW, &oldtty);
1141 }
1142
1143 static void term_init(void)
1144 {
1145     struct termios tty;
1146
1147     tcgetattr (0, &tty);
1148     oldtty = tty;
1149
1150     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1151                           |INLCR|IGNCR|ICRNL|IXON);
1152     tty.c_oflag |= OPOST;
1153     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1154     tty.c_cflag &= ~(CSIZE|PARENB);
1155     tty.c_cflag |= CS8;
1156     tty.c_cc[VMIN] = 1;
1157     tty.c_cc[VTIME] = 0;
1158     
1159     tcsetattr (0, TCSANOW, &tty);
1160
1161     atexit(term_exit);
1162
1163     fcntl(0, F_SETFL, O_NONBLOCK);
1164 }
1165
1166 void serial_init(void)
1167 {
1168     SerialState *s = &serial_ports[0];
1169
1170     s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
1171
1172     register_ioport_writeb(0x3f8, 8, serial_ioport_write);
1173     register_ioport_readb(0x3f8, 8, serial_ioport_read);
1174
1175     term_init();
1176 }
1177
1178 /***********************************************************/
1179 /* ne2000 emulation */
1180
1181 //#define DEBUG_NE2000
1182
1183 #define NE2000_IOPORT   0x300
1184 #define NE2000_IRQ      9
1185
1186 #define MAX_ETH_FRAME_SIZE 1514
1187
1188 #define E8390_CMD       0x00  /* The command register (for all pages) */
1189 /* Page 0 register offsets. */
1190 #define EN0_CLDALO      0x01    /* Low byte of current local dma addr  RD */
1191 #define EN0_STARTPG     0x01    /* Starting page of ring bfr WR */
1192 #define EN0_CLDAHI      0x02    /* High byte of current local dma addr  RD */
1193 #define EN0_STOPPG      0x02    /* Ending page +1 of ring bfr WR */
1194 #define EN0_BOUNDARY    0x03    /* Boundary page of ring bfr RD WR */
1195 #define EN0_TSR         0x04    /* Transmit status reg RD */
1196 #define EN0_TPSR        0x04    /* Transmit starting page WR */
1197 #define EN0_NCR         0x05    /* Number of collision reg RD */
1198 #define EN0_TCNTLO      0x05    /* Low  byte of tx byte count WR */
1199 #define EN0_FIFO        0x06    /* FIFO RD */
1200 #define EN0_TCNTHI      0x06    /* High byte of tx byte count WR */
1201 #define EN0_ISR         0x07    /* Interrupt status reg RD WR */
1202 #define EN0_CRDALO      0x08    /* low byte of current remote dma address RD */
1203 #define EN0_RSARLO      0x08    /* Remote start address reg 0 */
1204 #define EN0_CRDAHI      0x09    /* high byte, current remote dma address RD */
1205 #define EN0_RSARHI      0x09    /* Remote start address reg 1 */
1206 #define EN0_RCNTLO      0x0a    /* Remote byte count reg WR */
1207 #define EN0_RCNTHI      0x0b    /* Remote byte count reg WR */
1208 #define EN0_RSR         0x0c    /* rx status reg RD */
1209 #define EN0_RXCR        0x0c    /* RX configuration reg WR */
1210 #define EN0_TXCR        0x0d    /* TX configuration reg WR */
1211 #define EN0_COUNTER0    0x0d    /* Rcv alignment error counter RD */
1212 #define EN0_DCFG        0x0e    /* Data configuration reg WR */
1213 #define EN0_COUNTER1    0x0e    /* Rcv CRC error counter RD */
1214 #define EN0_IMR         0x0f    /* Interrupt mask reg WR */
1215 #define EN0_COUNTER2    0x0f    /* Rcv missed frame error counter RD */
1216
1217 #define EN1_PHYS        0x11
1218 #define EN1_CURPAG      0x17
1219 #define EN1_MULT        0x18
1220
1221 /*  Register accessed at EN_CMD, the 8390 base addr.  */
1222 #define E8390_STOP      0x01    /* Stop and reset the chip */
1223 #define E8390_START     0x02    /* Start the chip, clear reset */
1224 #define E8390_TRANS     0x04    /* Transmit a frame */
1225 #define E8390_RREAD     0x08    /* Remote read */
1226 #define E8390_RWRITE    0x10    /* Remote write  */
1227 #define E8390_NODMA     0x20    /* Remote DMA */
1228 #define E8390_PAGE0     0x00    /* Select page chip registers */
1229 #define E8390_PAGE1     0x40    /* using the two high-order bits */
1230 #define E8390_PAGE2     0x80    /* Page 3 is invalid. */
1231
1232 /* Bits in EN0_ISR - Interrupt status register */
1233 #define ENISR_RX        0x01    /* Receiver, no error */
1234 #define ENISR_TX        0x02    /* Transmitter, no error */
1235 #define ENISR_RX_ERR    0x04    /* Receiver, with error */
1236 #define ENISR_TX_ERR    0x08    /* Transmitter, with error */
1237 #define ENISR_OVER      0x10    /* Receiver overwrote the ring */
1238 #define ENISR_COUNTERS  0x20    /* Counters need emptying */
1239 #define ENISR_RDC       0x40    /* remote dma complete */
1240 #define ENISR_RESET     0x80    /* Reset completed */
1241 #define ENISR_ALL       0x3f    /* Interrupts we will enable */
1242
1243 /* Bits in received packet status byte and EN0_RSR*/
1244 #define ENRSR_RXOK      0x01    /* Received a good packet */
1245 #define ENRSR_CRC       0x02    /* CRC error */
1246 #define ENRSR_FAE       0x04    /* frame alignment error */
1247 #define ENRSR_FO        0x08    /* FIFO overrun */
1248 #define ENRSR_MPA       0x10    /* missed pkt */
1249 #define ENRSR_PHY       0x20    /* physical/multicast address */
1250 #define ENRSR_DIS       0x40    /* receiver disable. set in monitor mode */
1251 #define ENRSR_DEF       0x80    /* deferring */
1252
1253 /* Transmitted packet status, EN0_TSR. */
1254 #define ENTSR_PTX 0x01  /* Packet transmitted without error */
1255 #define ENTSR_ND  0x02  /* The transmit wasn't deferred. */
1256 #define ENTSR_COL 0x04  /* The transmit collided at least once. */
1257 #define ENTSR_ABT 0x08  /* The transmit collided 16 times, and was deferred. */
1258 #define ENTSR_CRS 0x10  /* The carrier sense was lost. */
1259 #define ENTSR_FU  0x20  /* A "FIFO underrun" occurred during transmit. */
1260 #define ENTSR_CDH 0x40  /* The collision detect "heartbeat" signal was lost. */
1261 #define ENTSR_OWC 0x80  /* There was an out-of-window collision. */
1262
1263 #define NE2000_MEM_SIZE 32768
1264
1265 typedef struct NE2000State {
1266     uint8_t cmd;
1267     uint32_t start;
1268     uint32_t stop;
1269     uint8_t boundary;
1270     uint8_t tsr;
1271     uint8_t tpsr;
1272     uint16_t tcnt;
1273     uint16_t rcnt;
1274     uint32_t rsar;
1275     uint8_t isr;
1276     uint8_t dcfg;
1277     uint8_t imr;
1278     uint8_t phys[6]; /* mac address */
1279     uint8_t curpag;
1280     uint8_t mult[8]; /* multicast mask array */
1281     uint8_t mem[NE2000_MEM_SIZE];
1282 } NE2000State;
1283
1284 NE2000State ne2000_state;
1285 int net_fd = -1;
1286 char network_script[1024];
1287
1288 void ne2000_reset(void)
1289 {
1290     NE2000State *s = &ne2000_state;
1291     int i;
1292
1293     s->isr = ENISR_RESET;
1294     s->mem[0] = 0x52;
1295     s->mem[1] = 0x54;
1296     s->mem[2] = 0x00;
1297     s->mem[3] = 0x12;
1298     s->mem[4] = 0x34;
1299     s->mem[5] = 0x56;
1300     s->mem[14] = 0x57;
1301     s->mem[15] = 0x57;
1302
1303     /* duplicate prom data */
1304     for(i = 15;i >= 0; i--) {
1305         s->mem[2 * i] = s->mem[i];
1306         s->mem[2 * i + 1] = s->mem[i];
1307     }
1308 }
1309
1310 void ne2000_update_irq(NE2000State *s)
1311 {
1312     int isr;
1313     isr = s->isr & s->imr;
1314     if (isr)
1315         pic_set_irq(NE2000_IRQ, 1);
1316     else
1317         pic_set_irq(NE2000_IRQ, 0);
1318 }
1319
1320 int net_init(void)
1321 {
1322     struct ifreq ifr;
1323     int fd, ret, pid, status;
1324     
1325     fd = open("/dev/net/tun", O_RDWR);
1326     if (fd < 0) {
1327         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1328         return -1;
1329     }
1330     memset(&ifr, 0, sizeof(ifr));
1331     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1332     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1333     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1334     if (ret != 0) {
1335         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1336         close(fd);
1337         return -1;
1338     }
1339     printf("connected to host network interface: %s\n", ifr.ifr_name);
1340     fcntl(fd, F_SETFL, O_NONBLOCK);
1341     net_fd = fd;
1342
1343     /* try to launch network init script */
1344     pid = fork();
1345     if (pid >= 0) {
1346         if (pid == 0) {
1347             execl(network_script, network_script, ifr.ifr_name, NULL);
1348             exit(1);
1349         }
1350         while (waitpid(pid, &status, 0) != pid);
1351         if (!WIFEXITED(status) ||
1352             WEXITSTATUS(status) != 0) {
1353             fprintf(stderr, "%s: could not launch network script for '%s'\n",
1354                     network_script, ifr.ifr_name);
1355         }
1356     }
1357     return 0;
1358 }
1359
1360 void net_send_packet(NE2000State *s, const uint8_t *buf, int size)
1361 {
1362 #ifdef DEBUG_NE2000
1363     printf("NE2000: sending packet size=%d\n", size);
1364 #endif
1365     write(net_fd, buf, size);
1366 }
1367
1368 /* return true if the NE2000 can receive more data */
1369 int ne2000_can_receive(NE2000State *s)
1370 {
1371     int avail, index, boundary;
1372     
1373     if (s->cmd & E8390_STOP)
1374         return 0;
1375     index = s->curpag << 8;
1376     boundary = s->boundary << 8;
1377     if (index < boundary)
1378         avail = boundary - index;
1379     else
1380         avail = (s->stop - s->start) - (index - boundary);
1381     if (avail < (MAX_ETH_FRAME_SIZE + 4))
1382         return 0;
1383     return 1;
1384 }
1385
1386 void ne2000_receive(NE2000State *s, uint8_t *buf, int size)
1387 {
1388     uint8_t *p;
1389     int total_len, next, avail, len, index;
1390
1391 #if defined(DEBUG_NE2000)
1392     printf("NE2000: received len=%d\n", size);
1393 #endif
1394
1395     index = s->curpag << 8;
1396     /* 4 bytes for header */
1397     total_len = size + 4;
1398     /* address for next packet (4 bytes for CRC) */
1399     next = index + ((total_len + 4 + 255) & ~0xff);
1400     if (next >= s->stop)
1401         next -= (s->stop - s->start);
1402     /* prepare packet header */
1403     p = s->mem + index;
1404     p[0] = ENRSR_RXOK; /* receive status */
1405     p[1] = next >> 8;
1406     p[2] = total_len;
1407     p[3] = total_len >> 8;
1408     index += 4;
1409
1410     /* write packet data */
1411     while (size > 0) {
1412         avail = s->stop - index;
1413         len = size;
1414         if (len > avail)
1415             len = avail;
1416         memcpy(s->mem + index, buf, len);
1417         buf += len;
1418         index += len;
1419         if (index == s->stop)
1420             index = s->start;
1421         size -= len;
1422     }
1423     s->curpag = next >> 8;
1424     
1425     /* now we can signal we have receive something */
1426     s->isr |= ENISR_RX;
1427     ne2000_update_irq(s);
1428 }
1429
1430 void ne2000_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1431 {
1432     NE2000State *s = &ne2000_state;
1433     int offset, page;
1434
1435     addr &= 0xf;
1436 #ifdef DEBUG_NE2000
1437     printf("NE2000: write addr=0x%x val=0x%02x\n", addr, val);
1438 #endif
1439     if (addr == E8390_CMD) {
1440         /* control register */
1441         s->cmd = val;
1442         if (val & E8390_START) {
1443             /* test specific case: zero length transfert */
1444             if ((val & (E8390_RREAD | E8390_RWRITE)) &&
1445                 s->rcnt == 0) {
1446                 s->isr |= ENISR_RDC;
1447                 ne2000_update_irq(s);
1448             }
1449             if (val & E8390_TRANS) {
1450                 net_send_packet(s, s->mem + (s->tpsr << 8), s->tcnt);
1451                 /* signal end of transfert */
1452                 s->tsr = ENTSR_PTX;
1453                 s->isr |= ENISR_TX;
1454                 ne2000_update_irq(s);
1455             }
1456         }
1457     } else {
1458         page = s->cmd >> 6;
1459         offset = addr | (page << 4);
1460         switch(offset) {
1461         case EN0_STARTPG:
1462             s->start = val << 8;
1463             break;
1464         case EN0_STOPPG:
1465             s->stop = val << 8;
1466             break;
1467         case EN0_BOUNDARY:
1468             s->boundary = val;
1469             break;
1470         case EN0_IMR:
1471             s->imr = val;
1472             ne2000_update_irq(s);
1473             break;
1474         case EN0_TPSR:
1475             s->tpsr = val;
1476             break;
1477         case EN0_TCNTLO:
1478             s->tcnt = (s->tcnt & 0xff00) | val;
1479             break;
1480         case EN0_TCNTHI:
1481             s->tcnt = (s->tcnt & 0x00ff) | (val << 8);
1482             break;
1483         case EN0_RSARLO:
1484             s->rsar = (s->rsar & 0xff00) | val;
1485             break;
1486         case EN0_RSARHI:
1487             s->rsar = (s->rsar & 0x00ff) | (val << 8);
1488             break;
1489         case EN0_RCNTLO:
1490             s->rcnt = (s->rcnt & 0xff00) | val;
1491             break;
1492         case EN0_RCNTHI:
1493             s->rcnt = (s->rcnt & 0x00ff) | (val << 8);
1494             break;
1495         case EN0_DCFG:
1496             s->dcfg = val;
1497             break;
1498         case EN0_ISR:
1499             s->isr &= ~val;
1500             ne2000_update_irq(s);
1501             break;
1502         case EN1_PHYS ... EN1_PHYS + 5:
1503             s->phys[offset - EN1_PHYS] = val;
1504             break;
1505         case EN1_CURPAG:
1506             s->curpag = val;
1507             break;
1508         case EN1_MULT ... EN1_MULT + 7:
1509             s->mult[offset - EN1_MULT] = val;
1510             break;
1511         }
1512     }
1513 }
1514
1515 uint32_t ne2000_ioport_read(CPUX86State *env, uint32_t addr)
1516 {
1517     NE2000State *s = &ne2000_state;
1518     int offset, page, ret;
1519
1520     addr &= 0xf;
1521     if (addr == E8390_CMD) {
1522         ret = s->cmd;
1523     } else {
1524         page = s->cmd >> 6;
1525         offset = addr | (page << 4);
1526         switch(offset) {
1527         case EN0_TSR:
1528             ret = s->tsr;
1529             break;
1530         case EN0_BOUNDARY:
1531             ret = s->boundary;
1532             break;
1533         case EN0_ISR:
1534             ret = s->isr;
1535             break;
1536         case EN1_PHYS ... EN1_PHYS + 5:
1537             ret = s->phys[offset - EN1_PHYS];
1538             break;
1539         case EN1_CURPAG:
1540             ret = s->curpag;
1541             break;
1542         case EN1_MULT ... EN1_MULT + 7:
1543             ret = s->mult[offset - EN1_MULT];
1544             break;
1545         default:
1546             ret = 0x00;
1547             break;
1548         }
1549     }
1550 #ifdef DEBUG_NE2000
1551     printf("NE2000: read addr=0x%x val=%02x\n", addr, ret);
1552 #endif
1553     return ret;
1554 }
1555
1556 void ne2000_asic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1557 {
1558     NE2000State *s = &ne2000_state;
1559     uint8_t *p;
1560
1561 #ifdef DEBUG_NE2000
1562     printf("NE2000: asic write val=0x%04x\n", val);
1563 #endif
1564     p = s->mem + s->rsar;
1565     if (s->dcfg & 0x01) {
1566         /* 16 bit access */
1567         p[0] = val;
1568         p[1] = val >> 8;
1569         s->rsar += 2;
1570         s->rcnt -= 2;
1571     } else {
1572         /* 8 bit access */
1573         p[0] = val;
1574         s->rsar++;
1575         s->rcnt--;
1576     }
1577     /* wrap */
1578     if (s->rsar == s->stop)
1579         s->rsar = s->start;
1580     if (s->rcnt == 0) {
1581         /* signal end of transfert */
1582         s->isr |= ENISR_RDC;
1583         ne2000_update_irq(s);
1584     }
1585 }
1586
1587 uint32_t ne2000_asic_ioport_read(CPUX86State *env, uint32_t addr)
1588 {
1589     NE2000State *s = &ne2000_state;
1590     uint8_t *p;
1591     int ret;
1592
1593     p = s->mem + s->rsar;
1594     if (s->dcfg & 0x01) {
1595         /* 16 bit access */
1596         ret = p[0] | (p[1] << 8);
1597         s->rsar += 2;
1598         s->rcnt -= 2;
1599     } else {
1600         /* 8 bit access */
1601         ret = p[0];
1602         s->rsar++;
1603         s->rcnt--;
1604     }
1605     /* wrap */
1606     if (s->rsar == s->stop)
1607         s->rsar = s->start;
1608     if (s->rcnt == 0) {
1609         /* signal end of transfert */
1610         s->isr |= ENISR_RDC;
1611         ne2000_update_irq(s);
1612     }
1613 #ifdef DEBUG_NE2000
1614     printf("NE2000: asic read val=0x%04x\n", ret);
1615 #endif
1616     return ret;
1617 }
1618
1619 void ne2000_reset_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1620 {
1621     /* nothing to do (end of reset pulse) */
1622 }
1623
1624 uint32_t ne2000_reset_ioport_read(CPUX86State *env, uint32_t addr)
1625 {
1626     ne2000_reset();
1627     return 0;
1628 }
1629
1630 void ne2000_init(void)
1631 {
1632     register_ioport_writeb(NE2000_IOPORT, 16, ne2000_ioport_write);
1633     register_ioport_readb(NE2000_IOPORT, 16, ne2000_ioport_read);
1634
1635     register_ioport_writeb(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_write);
1636     register_ioport_readb(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_read);
1637     register_ioport_writew(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_write);
1638     register_ioport_readw(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_read);
1639
1640     register_ioport_writeb(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_write);
1641     register_ioport_readb(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_read);
1642     ne2000_reset();
1643 }
1644
1645 /***********************************************************/
1646 /* cpu signal handler */
1647 static void host_segv_handler(int host_signum, siginfo_t *info, 
1648                               void *puc)
1649 {
1650     if (cpu_signal_handler(host_signum, info, puc))
1651         return;
1652     term_exit();
1653     abort();
1654 }
1655
1656 static int timer_irq_pending;
1657
1658 static void host_alarm_handler(int host_signum, siginfo_t *info, 
1659                                void *puc)
1660 {
1661     /* just exit from the cpu to have a change to handle timers */
1662     cpu_x86_interrupt(global_env);
1663     timer_irq_pending = 1;
1664 }
1665
1666 void help(void)
1667 {
1668     printf("Virtual Linux version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
1669            "usage: vl [-h] bzImage initrd [kernel parameters...]\n"
1670            "\n"
1671            "'bzImage' is a Linux kernel image (PAGE_OFFSET must be defined\n"
1672            "to 0x90000000 in asm/page.h and arch/i386/vmlinux.lds)\n"
1673            "'initrd' is an initrd image\n"
1674            "-m megs   set virtual RAM size to megs MB\n"
1675            "-n script set network init script [default=%s]\n"
1676            "-d        output log in /tmp/vl.log\n"
1677            "\n"
1678            "During emulation, use C-a h to get terminal commands:\n",
1679            DEFAULT_NETWORK_SCRIPT);
1680     term_print_help();
1681     exit(1);
1682 }
1683
1684 int main(int argc, char **argv)
1685 {
1686     int c, ret, initrd_size, i;
1687     struct linux_params *params;
1688     struct sigaction act;
1689     struct itimerval itv;
1690     CPUX86State *env;
1691
1692     /* we never want that malloc() uses mmap() */
1693     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
1694     
1695     phys_ram_size = 32 * 1024 * 1024;
1696     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
1697     for(;;) {
1698         c = getopt(argc, argv, "hm:dn:");
1699         if (c == -1)
1700             break;
1701         switch(c) {
1702         case 'h':
1703             help();
1704             break;
1705         case 'm':
1706             phys_ram_size = atoi(optarg) * 1024 * 1024;
1707             if (phys_ram_size <= 0)
1708                 help();
1709             break;
1710         case 'd':
1711             loglevel = 1;
1712             break;
1713         case 'n':
1714             pstrcpy(network_script, sizeof(network_script), optarg);
1715             break;
1716         }
1717     }
1718     if (optind + 1 >= argc)
1719         help();
1720
1721     /* init debug */
1722     if (loglevel) {
1723         logfile = fopen(DEBUG_LOGFILE, "w");
1724         if (!logfile) {
1725             perror(DEBUG_LOGFILE);
1726             _exit(1);
1727         }
1728         setvbuf(logfile, NULL, _IOLBF, 0);
1729     }
1730
1731     /* init network tun interface */
1732     net_init();
1733
1734     /* init the memory */
1735     strcpy(phys_ram_file, "/tmp/vlXXXXXX");
1736     if (mkstemp(phys_ram_file) < 0) {
1737         fprintf(stderr, "Could not create temporary memory file\n");
1738         exit(1);
1739     }
1740     phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
1741     if (phys_ram_fd < 0) {
1742         fprintf(stderr, "Could not open temporary memory file\n");
1743         exit(1);
1744     }
1745     ftruncate(phys_ram_fd, phys_ram_size);
1746     unlink(phys_ram_file);
1747     phys_ram_base = mmap((void *)PHYS_RAM_BASE, phys_ram_size, 
1748                          PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
1749                          phys_ram_fd, 0);
1750     if (phys_ram_base == MAP_FAILED) {
1751         fprintf(stderr, "Could not map physical memory\n");
1752         exit(1);
1753     }
1754
1755     /* now we can load the kernel */
1756     ret = load_kernel(argv[optind], phys_ram_base + KERNEL_LOAD_ADDR);
1757     if (ret < 0) {
1758         fprintf(stderr, "%s: could not load kernel\n", argv[optind]);
1759         exit(1);
1760     }
1761
1762     /* load initrd */
1763     initrd_size = load_image(argv[optind + 1], phys_ram_base + INITRD_LOAD_ADDR);
1764     if (initrd_size < 0) {
1765         fprintf(stderr, "%s: could not load initrd\n", argv[optind + 1]);
1766         exit(1);
1767     }
1768
1769     /* init kernel params */
1770     params = (void *)(phys_ram_base + KERNEL_PARAMS_ADDR);
1771     memset(params, 0, sizeof(struct linux_params));
1772     params->mount_root_rdonly = 0;
1773     params->cl_magic = 0xA33F;
1774     params->cl_offset = params->commandline - (uint8_t *)params;
1775     params->ext_mem_k = (phys_ram_size / 1024) - 1024;
1776     for(i = optind + 2; i < argc; i++) {
1777         if (i != optind + 2)
1778             pstrcat(params->commandline, sizeof(params->commandline), " ");
1779         pstrcat(params->commandline, sizeof(params->commandline), argv[i]);
1780     }
1781     params->loader_type = 0x01;
1782     if (initrd_size > 0) {
1783         params->initrd_start = INITRD_LOAD_ADDR;
1784         params->initrd_size = initrd_size;
1785     }
1786     params->orig_video_lines = 25;
1787     params->orig_video_cols = 80;
1788
1789     /* init basic PC hardware */
1790     init_ioports();
1791     register_ioport_writeb(0x80, 1, ioport80_write);
1792
1793     register_ioport_writeb(0x3d4, 2, vga_ioport_write);
1794
1795     cmos_init();
1796     pic_init();
1797     pit_init();
1798     serial_init();
1799     ne2000_init();
1800
1801     /* setup cpu signal handlers for MMU / self modifying code handling */
1802     sigfillset(&act.sa_mask);
1803     act.sa_flags = SA_SIGINFO;
1804     act.sa_sigaction = host_segv_handler;
1805     sigaction(SIGSEGV, &act, NULL);
1806     sigaction(SIGBUS, &act, NULL);
1807
1808     act.sa_sigaction = host_alarm_handler;
1809     sigaction(SIGALRM, &act, NULL);
1810
1811     /* init CPU state */
1812     env = cpu_init();
1813     global_env = env;
1814
1815     /* setup basic memory access */
1816     env->cr[0] = 0x00000033;
1817     cpu_x86_init_mmu(env);
1818     
1819     memset(params->idt_table, 0, sizeof(params->idt_table));
1820
1821     params->gdt_table[2] = 0x00cf9a000000ffffLL; /* KERNEL_CS */
1822     params->gdt_table[3] = 0x00cf92000000ffffLL; /* KERNEL_DS */
1823     
1824     env->idt.base = (void *)params->idt_table;
1825     env->idt.limit = sizeof(params->idt_table) - 1;
1826     env->gdt.base = (void *)params->gdt_table;
1827     env->gdt.limit = sizeof(params->gdt_table) - 1;
1828
1829     cpu_x86_load_seg(env, R_CS, KERNEL_CS);
1830     cpu_x86_load_seg(env, R_DS, KERNEL_DS);
1831     cpu_x86_load_seg(env, R_ES, KERNEL_DS);
1832     cpu_x86_load_seg(env, R_SS, KERNEL_DS);
1833     cpu_x86_load_seg(env, R_FS, KERNEL_DS);
1834     cpu_x86_load_seg(env, R_GS, KERNEL_DS);
1835     
1836     env->eip = KERNEL_LOAD_ADDR;
1837     env->regs[R_ESI] = KERNEL_PARAMS_ADDR;
1838     env->eflags = 0x2;
1839
1840     itv.it_interval.tv_sec = 0;
1841     itv.it_interval.tv_usec = 10 * 1000;
1842     itv.it_value.tv_sec = 0;
1843     itv.it_value.tv_usec = 10 * 1000;
1844     setitimer(ITIMER_REAL, &itv, NULL);
1845
1846     for(;;) {
1847         struct pollfd ufds[2], *pf, *serial_ufd, *net_ufd;
1848         int ret, n, timeout;
1849         uint8_t ch;
1850
1851         ret = cpu_x86_exec(env);
1852
1853         /* if hlt instruction, we wait until the next IRQ */
1854         if (ret == EXCP_HLT) 
1855             timeout = 10;
1856         else
1857             timeout = 0;
1858         /* poll any events */
1859         serial_ufd = NULL;
1860         net_ufd = NULL;
1861         pf = ufds;
1862         if (!(serial_ports[0].lsr & UART_LSR_DR)) {
1863             serial_ufd = pf;
1864             pf->fd = 0;
1865             pf->events = POLLIN;
1866             pf++;
1867         }
1868         if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) {
1869             net_ufd = pf;
1870             pf->fd = net_fd;
1871             pf->events = POLLIN;
1872             pf++;
1873         }
1874         ret = poll(ufds, pf - ufds, timeout);
1875         if (ret > 0) {
1876             if (serial_ufd && (serial_ufd->revents & POLLIN)) {
1877                 n = read(0, &ch, 1);
1878                 if (n == 1) {
1879                     serial_received_byte(&serial_ports[0], ch);
1880                 }
1881             }
1882             if (net_ufd && (net_ufd->revents & POLLIN)) {
1883                 uint8_t buf[MAX_ETH_FRAME_SIZE];
1884
1885                 n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);
1886                 if (n > 0) {
1887                     if (n < 60) {
1888                         memset(buf + n, 0, 60 - n);
1889                         n = 60;
1890                     }
1891                     ne2000_receive(&ne2000_state, buf, n);
1892                 }
1893             }
1894         }
1895
1896         /* just for testing */
1897         if (timer_irq_pending) {
1898             pic_set_irq(0, 1);
1899             pic_set_irq(0, 0);
1900             timer_irq_pending = 0;
1901         }
1902
1903         pic_handle_irq();
1904     }
1905
1906     return 0;
1907 }