Statistics
| Branch: | Revision:

root / vl.c @ abd0aaff

History | View | Annotate | Download (76.2 kB)

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

    
56
//#define DEBUG_UNUSED_IOPORT
57
//#define DEBUG_IRQ_LATENCY
58

    
59
#define PHYS_RAM_BASE 0xa8000000
60
#define KERNEL_LOAD_ADDR   0x00100000
61
#define INITRD_LOAD_ADDR   0x00400000
62
#define KERNEL_PARAMS_ADDR 0x00090000
63

    
64
/* from plex86 (BSD license) */
65
struct  __attribute__ ((packed)) linux_params {
66
  // For 0x00..0x3f, see 'struct screen_info' in linux/include/linux/tty.h.
67
  // I just padded out the VESA parts, rather than define them.
68

    
69
  /* 0x000 */ uint8_t   orig_x;
70
  /* 0x001 */ uint8_t   orig_y;
71
  /* 0x002 */ uint16_t  ext_mem_k;
72
  /* 0x004 */ uint16_t  orig_video_page;
73
  /* 0x006 */ uint8_t   orig_video_mode;
74
  /* 0x007 */ uint8_t   orig_video_cols;
75
  /* 0x008 */ uint16_t  unused1;
76
  /* 0x00a */ uint16_t  orig_video_ega_bx;
77
  /* 0x00c */ uint16_t  unused2;
78
  /* 0x00e */ uint8_t   orig_video_lines;
79
  /* 0x00f */ uint8_t   orig_video_isVGA;
80
  /* 0x010 */ uint16_t  orig_video_points;
81
  /* 0x012 */ uint8_t   pad0[0x20 - 0x12]; // VESA info.
82
  /* 0x020 */ uint16_t  cl_magic;  // Commandline magic number (0xA33F)
83
  /* 0x022 */ uint16_t  cl_offset; // Commandline offset.  Address of commandline
84
                                 // is calculated as 0x90000 + cl_offset, bu
85
                                 // only if cl_magic == 0xA33F.
86
  /* 0x024 */ uint8_t   pad1[0x40 - 0x24]; // VESA info.
87

    
88
  /* 0x040 */ uint8_t   apm_bios_info[20]; // struct apm_bios_info
89
  /* 0x054 */ uint8_t   pad2[0x80 - 0x54];
90

    
91
  // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.
92
  // Might be truncated?
93
  /* 0x080 */ uint8_t   hd0_info[16]; // hd0-disk-parameter from intvector 0x41
94
  /* 0x090 */ uint8_t   hd1_info[16]; // hd1-disk-parameter from intvector 0x46
95

    
96
  // System description table truncated to 16 bytes
97
  // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.
98
  /* 0x0a0 */ uint16_t  sys_description_len;
99
  /* 0x0a2 */ uint8_t   sys_description_table[14];
100
                        // [0] machine id
101
                        // [1] machine submodel id
102
                        // [2] BIOS revision
103
                        // [3] bit1: MCA bus
104

    
105
  /* 0x0b0 */ uint8_t   pad3[0x1e0 - 0xb0];
106
  /* 0x1e0 */ uint32_t  alt_mem_k;
107
  /* 0x1e4 */ uint8_t   pad4[4];
108
  /* 0x1e8 */ uint8_t   e820map_entries;
109
  /* 0x1e9 */ uint8_t   eddbuf_entries; // EDD_NR
110
  /* 0x1ea */ uint8_t   pad5[0x1f1 - 0x1ea];
111
  /* 0x1f1 */ uint8_t   setup_sects; // size of setup.S, number of sectors
112
  /* 0x1f2 */ uint16_t  mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)
113
  /* 0x1f4 */ uint16_t  sys_size; // size of compressed kernel-part in the
114
                                // (b)zImage-file (in 16 byte units, rounded up)
115
  /* 0x1f6 */ uint16_t  swap_dev; // (unused AFAIK)
116
  /* 0x1f8 */ uint16_t  ramdisk_flags;
117
  /* 0x1fa */ uint16_t  vga_mode; // (old one)
118
  /* 0x1fc */ uint16_t  orig_root_dev; // (high=Major, low=minor)
119
  /* 0x1fe */ uint8_t   pad6[1];
120
  /* 0x1ff */ uint8_t   aux_device_info;
121
  /* 0x200 */ uint16_t  jump_setup; // Jump to start of setup code,
122
                                  // aka "reserved" field.
123
  /* 0x202 */ uint8_t   setup_signature[4]; // Signature for SETUP-header, ="HdrS"
124
  /* 0x206 */ uint16_t  header_format_version; // Version number of header format;
125
  /* 0x208 */ uint8_t   setup_S_temp0[8]; // Used by setup.S for communication with
126
                                        // boot loaders, look there.
127
  /* 0x210 */ uint8_t   loader_type;
128
                        // 0 for old one.
129
                        // else 0xTV:
130
                        //   T=0: LILO
131
                        //   T=1: Loadlin
132
                        //   T=2: bootsect-loader
133
                        //   T=3: SYSLINUX
134
                        //   T=4: ETHERBOOT
135
                        //   V=version
136
  /* 0x211 */ uint8_t   loadflags;
137
                        // bit0 = 1: kernel is loaded high (bzImage)
138
                        // bit7 = 1: Heap and pointer (see below) set by boot
139
                        //   loader.
140
  /* 0x212 */ uint16_t  setup_S_temp1;
141
  /* 0x214 */ uint32_t  kernel_start;
142
  /* 0x218 */ uint32_t  initrd_start;
143
  /* 0x21c */ uint32_t  initrd_size;
144
  /* 0x220 */ uint8_t   setup_S_temp2[4];
145
  /* 0x224 */ uint16_t  setup_S_heap_end_pointer;
146
  /* 0x226 */ uint8_t   pad7[0x2d0 - 0x226];
147

    
148
  /* 0x2d0 : Int 15, ax=e820 memory map. */
149
  // (linux/include/asm-i386/e820.h, 'struct e820entry')
150
#define E820MAX  32
151
#define E820_RAM  1
152
#define E820_RESERVED 2
153
#define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */
154
#define E820_NVS  4
155
  struct {
156
    uint64_t addr;
157
    uint64_t size;
158
    uint32_t type;
159
    } e820map[E820MAX];
160

    
161
  /* 0x550 */ uint8_t   pad8[0x600 - 0x550];
162

    
163
  // BIOS Enhanced Disk Drive Services.
164
  // (From linux/include/asm-i386/edd.h, 'struct edd_info')
165
  // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.
166
  /* 0x600 */ uint8_t   eddbuf[0x7d4 - 0x600];
167

    
168
  /* 0x7d4 */ uint8_t   pad9[0x800 - 0x7d4];
169
  /* 0x800 */ uint8_t   commandline[0x800];
170

    
171
  /* 0x1000 */
172
  uint64_t gdt_table[256];
173
  uint64_t idt_table[48];
174
};
175

    
176
#define KERNEL_CS     0x10
177
#define KERNEL_DS     0x18
178

    
179
typedef void (IOPortWriteFunc)(CPUX86State *env, uint32_t address, uint32_t data);
180
typedef uint32_t (IOPortReadFunc)(CPUX86State *env, uint32_t address);
181

    
182
#define MAX_IOPORTS 4096
183

    
184
char phys_ram_file[1024];
185
CPUX86State *global_env;
186
CPUX86State *cpu_single_env;
187
FILE *logfile = NULL;
188
int loglevel;
189
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
190
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
191

    
192
/***********************************************************/
193
/* x86 io ports */
194

    
195
uint32_t default_ioport_readb(CPUX86State *env, uint32_t address)
196
{
197
#ifdef DEBUG_UNUSED_IOPORT
198
    fprintf(stderr, "inb: port=0x%04x\n", address);
199
#endif
200
    return 0xff;
201
}
202

    
203
void default_ioport_writeb(CPUX86State *env, uint32_t address, uint32_t data)
204
{
205
#ifdef DEBUG_UNUSED_IOPORT
206
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
207
#endif
208
}
209

    
210
/* default is to make two byte accesses */
211
uint32_t default_ioport_readw(CPUX86State *env, uint32_t address)
212
{
213
    uint32_t data;
214
    data = ioport_read_table[0][address](env, address);
215
    data |= ioport_read_table[0][address + 1](env, address + 1) << 8;
216
    return data;
217
}
218

    
219
void default_ioport_writew(CPUX86State *env, uint32_t address, uint32_t data)
220
{
221
    ioport_write_table[0][address](env, address, data & 0xff);
222
    ioport_write_table[0][address + 1](env, address + 1, (data >> 8) & 0xff);
223
}
224

    
225
uint32_t default_ioport_readl(CPUX86State *env, uint32_t address)
226
{
227
#ifdef DEBUG_UNUSED_IOPORT
228
    fprintf(stderr, "inl: port=0x%04x\n", address);
229
#endif
230
    return 0xffffffff;
231
}
232

    
233
void default_ioport_writel(CPUX86State *env, uint32_t address, uint32_t data)
234
{
235
#ifdef DEBUG_UNUSED_IOPORT
236
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
237
#endif
238
}
239

    
240
void init_ioports(void)
241
{
242
    int i;
243

    
244
    for(i = 0; i < MAX_IOPORTS; i++) {
245
        ioport_read_table[0][i] = default_ioport_readb;
246
        ioport_write_table[0][i] = default_ioport_writeb;
247
        ioport_read_table[1][i] = default_ioport_readw;
248
        ioport_write_table[1][i] = default_ioport_writew;
249
        ioport_read_table[2][i] = default_ioport_readl;
250
        ioport_write_table[2][i] = default_ioport_writel;
251
    }
252
}
253

    
254
/* size is the word size in byte */
255
int register_ioport_read(int start, int length, IOPortReadFunc *func, int size)
256
{
257
    int i, bsize;
258

    
259
    if (size == 1)
260
        bsize = 0;
261
    else if (size == 2)
262
        bsize = 1;
263
    else if (size == 4)
264
        bsize = 2;
265
    else
266
        return -1;
267
    for(i = start; i < start + length; i += size)
268
        ioport_read_table[bsize][i] = func;
269
    return 0;
270
}
271

    
272
/* size is the word size in byte */
273
int register_ioport_write(int start, int length, IOPortWriteFunc *func, int size)
274
{
275
    int i, bsize;
276

    
277
    if (size == 1)
278
        bsize = 0;
279
    else if (size == 2)
280
        bsize = 1;
281
    else if (size == 4)
282
        bsize = 2;
283
    else
284
        return -1;
285
    for(i = start; i < start + length; i += size)
286
        ioport_write_table[bsize][i] = func;
287
    return 0;
288
}
289

    
290
void pstrcpy(char *buf, int buf_size, const char *str)
291
{
292
    int c;
293
    char *q = buf;
294

    
295
    if (buf_size <= 0)
296
        return;
297

    
298
    for(;;) {
299
        c = *str++;
300
        if (c == 0 || q >= buf + buf_size - 1)
301
            break;
302
        *q++ = c;
303
    }
304
    *q = '\0';
305
}
306

    
307
/* strcat and truncate. */
308
char *pstrcat(char *buf, int buf_size, const char *s)
309
{
310
    int len;
311
    len = strlen(buf);
312
    if (len < buf_size) 
313
        pstrcpy(buf + len, buf_size - len, s);
314
    return buf;
315
}
316

    
317
int load_kernel(const char *filename, uint8_t *addr)
318
{
319
    int fd, size, setup_sects;
320
    uint8_t bootsect[512];
321

    
322
    fd = open(filename, O_RDONLY);
323
    if (fd < 0)
324
        return -1;
325
    if (read(fd, bootsect, 512) != 512)
326
        goto fail;
327
    setup_sects = bootsect[0x1F1];
328
    if (!setup_sects)
329
        setup_sects = 4;
330
    /* skip 16 bit setup code */
331
    lseek(fd, (setup_sects + 1) * 512, SEEK_SET);
332
    size = read(fd, addr, 16 * 1024 * 1024);
333
    if (size < 0)
334
        goto fail;
335
    close(fd);
336
    return size;
337
 fail:
338
    close(fd);
339
    return -1;
340
}
341

    
342
/* return the size or -1 if error */
343
int load_image(const char *filename, uint8_t *addr)
344
{
345
    int fd, size;
346
    fd = open(filename, O_RDONLY);
347
    if (fd < 0)
348
        return -1;
349
    size = lseek(fd, 0, SEEK_END);
350
    lseek(fd, 0, SEEK_SET);
351
    if (read(fd, addr, size) != size) {
352
        close(fd);
353
        return -1;
354
    }
355
    close(fd);
356
    return size;
357
}
358

    
359
void cpu_x86_outb(CPUX86State *env, int addr, int val)
360
{
361
    ioport_write_table[0][addr & (MAX_IOPORTS - 1)](env, addr, val);
362
}
363

    
364
void cpu_x86_outw(CPUX86State *env, int addr, int val)
365
{
366
    ioport_write_table[1][addr & (MAX_IOPORTS - 1)](env, addr, val);
367
}
368

    
369
void cpu_x86_outl(CPUX86State *env, int addr, int val)
370
{
371
    ioport_write_table[2][addr & (MAX_IOPORTS - 1)](env, addr, val);
372
}
373

    
374
int cpu_x86_inb(CPUX86State *env, int addr)
375
{
376
    return ioport_read_table[0][addr & (MAX_IOPORTS - 1)](env, addr);
377
}
378

    
379
int cpu_x86_inw(CPUX86State *env, int addr)
380
{
381
    return ioport_read_table[1][addr & (MAX_IOPORTS - 1)](env, addr);
382
}
383

    
384
int cpu_x86_inl(CPUX86State *env, int addr)
385
{
386
    return ioport_read_table[2][addr & (MAX_IOPORTS - 1)](env, addr);
387
}
388

    
389
/***********************************************************/
390
void ioport80_write(CPUX86State *env, uint32_t addr, uint32_t data)
391
{
392
}
393

    
394
void hw_error(const char *fmt, ...)
395
{
396
    va_list ap;
397

    
398
    va_start(ap, fmt);
399
    fprintf(stderr, "qemu: hardware error: ");
400
    vfprintf(stderr, fmt, ap);
401
    fprintf(stderr, "\n");
402
#ifdef TARGET_I386
403
    cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
404
#endif
405
    va_end(ap);
406
    abort();
407
}
408

    
409
/***********************************************************/
410
/* vga emulation */
411
static uint8_t vga_index;
412
static uint8_t vga_regs[256];
413
static int last_cursor_pos;
414

    
415
void update_console_messages(void)
416
{
417
    int c, i, cursor_pos, eol;
418

    
419
    cursor_pos = vga_regs[0x0f] | (vga_regs[0x0e] << 8);
420
    eol = 0;
421
    for(i = last_cursor_pos; i < cursor_pos; i++) {
422
        c = phys_ram_base[0xb8000 + (i) * 2];
423
        if (c >= ' ') {
424
            putchar(c);
425
            eol = 0;
426
        } else {
427
            if (!eol)
428
                putchar('\n');
429
            eol = 1;
430
        }
431
    }
432
    fflush(stdout);
433
    last_cursor_pos = cursor_pos;
434
}
435

    
436
/* just to see first Linux console messages, we intercept cursor position */
437
void vga_ioport_write(CPUX86State *env, uint32_t addr, uint32_t data)
438
{
439
    switch(addr) {
440
    case 0x3d4:
441
        vga_index = data;
442
        break;
443
    case 0x3d5:
444
        vga_regs[vga_index] = data;
445
        if (vga_index == 0x0f)
446
            update_console_messages();
447
        break;
448
    }
449
            
450
}
451

    
452
/***********************************************************/
453
/* cmos emulation */
454

    
455
#define RTC_SECONDS             0
456
#define RTC_SECONDS_ALARM       1
457
#define RTC_MINUTES             2
458
#define RTC_MINUTES_ALARM       3
459
#define RTC_HOURS               4
460
#define RTC_HOURS_ALARM         5
461
#define RTC_ALARM_DONT_CARE    0xC0
462

    
463
#define RTC_DAY_OF_WEEK         6
464
#define RTC_DAY_OF_MONTH        7
465
#define RTC_MONTH               8
466
#define RTC_YEAR                9
467

    
468
#define RTC_REG_A               10
469
#define RTC_REG_B               11
470
#define RTC_REG_C               12
471
#define RTC_REG_D               13
472

    
473
/* PC cmos mappings */
474
#define REG_EQUIPMENT_BYTE          0x14
475

    
476
uint8_t cmos_data[128];
477
uint8_t cmos_index;
478

    
479
void cmos_ioport_write(CPUX86State *env, uint32_t addr, uint32_t data)
480
{
481
    if (addr == 0x70) {
482
        cmos_index = data & 0x7f;
483
    }
484
}
485

    
486
uint32_t cmos_ioport_read(CPUX86State *env, uint32_t addr)
487
{
488
    int ret;
489

    
490
    if (addr == 0x70) {
491
        return 0xff;
492
    } else {
493
        /* toggle update-in-progress bit for Linux (same hack as
494
           plex86) */
495
        ret = cmos_data[cmos_index];
496
        if (cmos_index == RTC_REG_A)
497
            cmos_data[RTC_REG_A] ^= 0x80; 
498
        else if (cmos_index == RTC_REG_C)
499
            cmos_data[RTC_REG_C] = 0x00; 
500
        return ret;
501
    }
502
}
503

    
504

    
505
static inline int to_bcd(int a)
506
{
507
    return ((a / 10) << 4) | (a % 10);
508
}
509

    
510
void cmos_init(void)
511
{
512
    struct tm *tm;
513
    time_t ti;
514

    
515
    ti = time(NULL);
516
    tm = gmtime(&ti);
517
    cmos_data[RTC_SECONDS] = to_bcd(tm->tm_sec);
518
    cmos_data[RTC_MINUTES] = to_bcd(tm->tm_min);
519
    cmos_data[RTC_HOURS] = to_bcd(tm->tm_hour);
520
    cmos_data[RTC_DAY_OF_WEEK] = to_bcd(tm->tm_wday);
521
    cmos_data[RTC_DAY_OF_MONTH] = to_bcd(tm->tm_mday);
522
    cmos_data[RTC_MONTH] = to_bcd(tm->tm_mon + 1);
523
    cmos_data[RTC_YEAR] = to_bcd(tm->tm_year % 100);
524

    
525
    cmos_data[RTC_REG_A] = 0x26;
526
    cmos_data[RTC_REG_B] = 0x02;
527
    cmos_data[RTC_REG_C] = 0x00;
528
    cmos_data[RTC_REG_D] = 0x80;
529

    
530
    cmos_data[REG_EQUIPMENT_BYTE] = 0x02; /* FPU is there */
531

    
532
    register_ioport_write(0x70, 2, cmos_ioport_write, 1);
533
    register_ioport_read(0x70, 2, cmos_ioport_read, 1);
534
}
535

    
536
/***********************************************************/
537
/* 8259 pic emulation */
538

    
539
//#define DEBUG_PIC
540

    
541
typedef struct PicState {
542
    uint8_t last_irr; /* edge detection */
543
    uint8_t irr; /* interrupt request register */
544
    uint8_t imr; /* interrupt mask register */
545
    uint8_t isr; /* interrupt service register */
546
    uint8_t priority_add; /* used to compute irq priority */
547
    uint8_t irq_base;
548
    uint8_t read_reg_select;
549
    uint8_t special_mask;
550
    uint8_t init_state;
551
    uint8_t auto_eoi;
552
    uint8_t rotate_on_autoeoi;
553
    uint8_t init4; /* true if 4 byte init */
554
} PicState;
555

    
556
/* 0 is master pic, 1 is slave pic */
557
PicState pics[2];
558
int pic_irq_requested;
559

    
560
/* set irq level. If an edge is detected, then the IRR is set to 1 */
561
static inline void pic_set_irq1(PicState *s, int irq, int level)
562
{
563
    int mask;
564
    mask = 1 << irq;
565
    if (level) {
566
        if ((s->last_irr & mask) == 0)
567
            s->irr |= mask;
568
        s->last_irr |= mask;
569
    } else {
570
        s->last_irr &= ~mask;
571
    }
572
}
573

    
574
static inline int get_priority(PicState *s, int mask)
575
{
576
    int priority;
577
    if (mask == 0)
578
        return -1;
579
    priority = 7;
580
    while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)
581
        priority--;
582
    return priority;
583
}
584

    
585
/* return the pic wanted interrupt. return -1 if none */
586
static int pic_get_irq(PicState *s)
587
{
588
    int mask, cur_priority, priority;
589

    
590
    mask = s->irr & ~s->imr;
591
    priority = get_priority(s, mask);
592
    if (priority < 0)
593
        return -1;
594
    /* compute current priority */
595
    cur_priority = get_priority(s, s->isr);
596
    if (priority > cur_priority) {
597
        /* higher priority found: an irq should be generated */
598
        return priority;
599
    } else {
600
        return -1;
601
    }
602
}
603

    
604
/* raise irq to CPU if necessary. must be called every time the active
605
   irq may change */
606
static void pic_update_irq(void)
607
{
608
    int irq2, irq;
609

    
610
    /* first look at slave pic */
611
    irq2 = pic_get_irq(&pics[1]);
612
    if (irq2 >= 0) {
613
        /* if irq request by slave pic, signal master PIC */
614
        pic_set_irq1(&pics[0], 2, 1);
615
        pic_set_irq1(&pics[0], 2, 0);
616
    }
617
    /* look at requested irq */
618
    irq = pic_get_irq(&pics[0]);
619
    if (irq >= 0) {
620
        if (irq == 2) {
621
            /* from slave pic */
622
            pic_irq_requested = 8 + irq2;
623
        } else {
624
            /* from master pic */
625
            pic_irq_requested = irq;
626
        }
627
        cpu_x86_interrupt(global_env, CPU_INTERRUPT_HARD);
628
    }
629
}
630

    
631
#ifdef DEBUG_IRQ_LATENCY
632
int64_t irq_time[16];
633
int64_t cpu_get_ticks(void);
634
#endif
635
#ifdef DEBUG_PIC
636
int irq_level[16];
637
#endif
638

    
639
void pic_set_irq(int irq, int level)
640
{
641
#ifdef DEBUG_PIC
642
    if (level != irq_level[irq]) {
643
        printf("pic_set_irq: irq=%d level=%d\n", irq, level);
644
        irq_level[irq] = level;
645
    }
646
#endif
647
#ifdef DEBUG_IRQ_LATENCY
648
    if (level) {
649
        irq_time[irq] = cpu_get_ticks();
650
    }
651
#endif
652
    pic_set_irq1(&pics[irq >> 3], irq & 7, level);
653
    pic_update_irq();
654
}
655

    
656
int cpu_x86_get_pic_interrupt(CPUX86State *env)
657
{
658
    int irq, irq2, intno;
659

    
660
    /* signal the pic that the irq was acked by the CPU */
661
    irq = pic_irq_requested;
662
#ifdef DEBUG_IRQ_LATENCY
663
    printf("IRQ%d latency=%Ld\n", irq, cpu_get_ticks() - irq_time[irq]);
664
#endif
665
#ifdef DEBUG_PIC
666
    printf("pic_interrupt: irq=%d\n", irq);
667
#endif
668

    
669
    if (irq >= 8) {
670
        irq2 = irq & 7;
671
        pics[1].isr |= (1 << irq2);
672
        pics[1].irr &= ~(1 << irq2);
673
        irq = 2;
674
        intno = pics[1].irq_base + irq2;
675
    } else {
676
        intno = pics[0].irq_base + irq;
677
    }
678
    pics[0].isr |= (1 << irq);
679
    pics[0].irr &= ~(1 << irq);
680
    return intno;
681
}
682

    
683
void pic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
684
{
685
    PicState *s;
686
    int priority;
687

    
688
#ifdef DEBUG_PIC
689
    printf("pic_write: addr=0x%02x val=0x%02x\n", addr, val);
690
#endif
691
    s = &pics[addr >> 7];
692
    addr &= 1;
693
    if (addr == 0) {
694
        if (val & 0x10) {
695
            /* init */
696
            memset(s, 0, sizeof(PicState));
697
            s->init_state = 1;
698
            s->init4 = val & 1;
699
            if (val & 0x02)
700
                hw_error("single mode not supported");
701
            if (val & 0x08)
702
                hw_error("level sensitive irq not supported");
703
        } else if (val & 0x08) {
704
            if (val & 0x02)
705
                s->read_reg_select = val & 1;
706
            if (val & 0x40)
707
                s->special_mask = (val >> 5) & 1;
708
        } else {
709
            switch(val) {
710
            case 0x00:
711
            case 0x80:
712
                s->rotate_on_autoeoi = val >> 7;
713
                break;
714
            case 0x20: /* end of interrupt */
715
            case 0xa0:
716
                priority = get_priority(s, s->isr);
717
                if (priority >= 0) {
718
                    s->isr &= ~(1 << ((priority + s->priority_add) & 7));
719
                }
720
                if (val == 0xa0)
721
                    s->priority_add = (s->priority_add + 1) & 7;
722
                break;
723
            case 0x60 ... 0x67:
724
                priority = val & 7;
725
                s->isr &= ~(1 << priority);
726
                break;
727
            case 0xc0 ... 0xc7:
728
                s->priority_add = (val + 1) & 7;
729
                break;
730
            case 0xe0 ... 0xe7:
731
                priority = val & 7;
732
                s->isr &= ~(1 << priority);
733
                s->priority_add = (priority + 1) & 7;
734
                break;
735
            }
736
        }
737
    } else {
738
        switch(s->init_state) {
739
        case 0:
740
            /* normal mode */
741
            s->imr = val;
742
            pic_update_irq();
743
            break;
744
        case 1:
745
            s->irq_base = val & 0xf8;
746
            s->init_state = 2;
747
            break;
748
        case 2:
749
            if (s->init4) {
750
                s->init_state = 3;
751
            } else {
752
                s->init_state = 0;
753
            }
754
            break;
755
        case 3:
756
            s->auto_eoi = (val >> 1) & 1;
757
            s->init_state = 0;
758
            break;
759
        }
760
    }
761
}
762

    
763
uint32_t pic_ioport_read(CPUX86State *env, uint32_t addr1)
764
{
765
    PicState *s;
766
    unsigned int addr;
767
    int ret;
768

    
769
    addr = addr1;
770
    s = &pics[addr >> 7];
771
    addr &= 1;
772
    if (addr == 0) {
773
        if (s->read_reg_select)
774
            ret = s->isr;
775
        else
776
            ret = s->irr;
777
    } else {
778
        ret = s->imr;
779
    }
780
#ifdef DEBUG_PIC
781
    printf("pic_read: addr=0x%02x val=0x%02x\n", addr1, ret);
782
#endif
783
    return ret;
784
}
785

    
786
void pic_init(void)
787
{
788
    register_ioport_write(0x20, 2, pic_ioport_write, 1);
789
    register_ioport_read(0x20, 2, pic_ioport_read, 1);
790
    register_ioport_write(0xa0, 2, pic_ioport_write, 1);
791
    register_ioport_read(0xa0, 2, pic_ioport_read, 1);
792
}
793

    
794
/***********************************************************/
795
/* 8253 PIT emulation */
796

    
797
#define PIT_FREQ 1193182
798

    
799
#define RW_STATE_LSB 0
800
#define RW_STATE_MSB 1
801
#define RW_STATE_WORD0 2
802
#define RW_STATE_WORD1 3
803
#define RW_STATE_LATCHED_WORD0 4
804
#define RW_STATE_LATCHED_WORD1 5
805

    
806
typedef struct PITChannelState {
807
    int count; /* can be 65536 */
808
    uint16_t latched_count;
809
    uint8_t rw_state;
810
    uint8_t mode;
811
    uint8_t bcd; /* not supported */
812
    uint8_t gate; /* timer start */
813
    int64_t count_load_time;
814
    int64_t count_last_edge_check_time;
815
} PITChannelState;
816

    
817
PITChannelState pit_channels[3];
818
int speaker_data_on;
819
int pit_min_timer_count = 0;
820

    
821
int64_t ticks_per_sec;
822

    
823
int64_t get_clock(void)
824
{
825
    struct timeval tv;
826
    gettimeofday(&tv, NULL);
827
    return tv.tv_sec * 1000000LL + tv.tv_usec;
828
}
829

    
830
int64_t cpu_get_ticks(void)
831
{
832
    int64_t val;
833
    asm("rdtsc" : "=A" (val));
834
    return val;
835
}
836

    
837
void cpu_calibrate_ticks(void)
838
{
839
    int64_t usec, ticks;
840

    
841
    usec = get_clock();
842
    ticks = cpu_get_ticks();
843
    usleep(50 * 1000);
844
    usec = get_clock() - usec;
845
    ticks = cpu_get_ticks() - ticks;
846
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
847
}
848

    
849
/* compute with 96 bit intermediate result: (a*b)/c */
850
static uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
851
{
852
    union {
853
        uint64_t ll;
854
        struct {
855
#ifdef WORDS_BIGENDIAN
856
            uint32_t high, low;
857
#else
858
            uint32_t low, high;
859
#endif            
860
        } l;
861
    } u, res;
862
    uint64_t rl, rh;
863

    
864
    u.ll = a;
865
    rl = (uint64_t)u.l.low * (uint64_t)b;
866
    rh = (uint64_t)u.l.high * (uint64_t)b;
867
    rh += (rl >> 32);
868
    res.l.high = rh / c;
869
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
870
    return res.ll;
871
}
872

    
873
static int pit_get_count(PITChannelState *s)
874
{
875
    uint64_t d;
876
    int counter;
877

    
878
    d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
879
    switch(s->mode) {
880
    case 0:
881
    case 1:
882
    case 4:
883
    case 5:
884
        counter = (s->count - d) & 0xffff;
885
        break;
886
    default:
887
        counter = s->count - (d % s->count);
888
        break;
889
    }
890
    return counter;
891
}
892

    
893
/* get pit output bit */
894
static int pit_get_out(PITChannelState *s)
895
{
896
    uint64_t d;
897
    int out;
898

    
899
    d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
900
    switch(s->mode) {
901
    default:
902
    case 0:
903
        out = (d >= s->count);
904
        break;
905
    case 1:
906
        out = (d < s->count);
907
        break;
908
    case 2:
909
        if ((d % s->count) == 0 && d != 0)
910
            out = 1;
911
        else
912
            out = 0;
913
        break;
914
    case 3:
915
        out = (d % s->count) < (s->count >> 1);
916
        break;
917
    case 4:
918
    case 5:
919
        out = (d == s->count);
920
        break;
921
    }
922
    return out;
923
}
924

    
925
/* get the number of 0 to 1 transitions we had since we call this
926
   function */
927
/* XXX: maybe better to use ticks precision to avoid getting edges
928
   twice if checks are done at very small intervals */
929
static int pit_get_out_edges(PITChannelState *s)
930
{
931
    uint64_t d1, d2;
932
    int64_t ticks;
933
    int ret, v;
934

    
935
    ticks = cpu_get_ticks();
936
    d1 = muldiv64(s->count_last_edge_check_time - s->count_load_time, 
937
                 PIT_FREQ, ticks_per_sec);
938
    d2 = muldiv64(ticks - s->count_load_time, 
939
                  PIT_FREQ, ticks_per_sec);
940
    s->count_last_edge_check_time = ticks;
941
    switch(s->mode) {
942
    default:
943
    case 0:
944
        if (d1 < s->count && d2 >= s->count)
945
            ret = 1;
946
        else
947
            ret = 0;
948
        break;
949
    case 1:
950
        ret = 0;
951
        break;
952
    case 2:
953
        d1 /= s->count;
954
        d2 /= s->count;
955
        ret = d2 - d1;
956
        break;
957
    case 3:
958
        v = s->count - (s->count >> 1);
959
        d1 = (d1 + v) / s->count;
960
        d2 = (d2 + v) / s->count;
961
        ret = d2 - d1;
962
        break;
963
    case 4:
964
    case 5:
965
        if (d1 < s->count && d2 >= s->count)
966
            ret = 1;
967
        else
968
            ret = 0;
969
        break;
970
    }
971
    return ret;
972
}
973

    
974
static inline void pit_load_count(PITChannelState *s, int val)
975
{
976
    if (val == 0)
977
        val = 0x10000;
978
    s->count_load_time = cpu_get_ticks();
979
    s->count_last_edge_check_time = s->count_load_time;
980
    s->count = val;
981
    if (s == &pit_channels[0] && val <= pit_min_timer_count) {
982
        fprintf(stderr, 
983
                "\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", 
984
                PIT_FREQ / pit_min_timer_count);
985
    }
986
}
987

    
988
void pit_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
989
{
990
    int channel, access;
991
    PITChannelState *s;
992

    
993
    addr &= 3;
994
    if (addr == 3) {
995
        channel = val >> 6;
996
        if (channel == 3)
997
            return;
998
        s = &pit_channels[channel];
999
        access = (val >> 4) & 3;
1000
        switch(access) {
1001
        case 0:
1002
            s->latched_count = pit_get_count(s);
1003
            s->rw_state = RW_STATE_LATCHED_WORD0;
1004
            break;
1005
        default:
1006
            s->mode = (val >> 1) & 7;
1007
            s->bcd = val & 1;
1008
            s->rw_state = access - 1 +  RW_STATE_LSB;
1009
            break;
1010
        }
1011
    } else {
1012
        s = &pit_channels[addr];
1013
        switch(s->rw_state) {
1014
        case RW_STATE_LSB:
1015
            pit_load_count(s, val);
1016
            break;
1017
        case RW_STATE_MSB:
1018
            pit_load_count(s, val << 8);
1019
            break;
1020
        case RW_STATE_WORD0:
1021
        case RW_STATE_WORD1:
1022
            if (s->rw_state & 1) {
1023
                pit_load_count(s, (s->latched_count & 0xff) | (val << 8));
1024
            } else {
1025
                s->latched_count = val;
1026
            }
1027
            s->rw_state ^= 1;
1028
            break;
1029
        }
1030
    }
1031
}
1032

    
1033
uint32_t pit_ioport_read(CPUX86State *env, uint32_t addr)
1034
{
1035
    int ret, count;
1036
    PITChannelState *s;
1037
    
1038
    addr &= 3;
1039
    s = &pit_channels[addr];
1040
    switch(s->rw_state) {
1041
    case RW_STATE_LSB:
1042
    case RW_STATE_MSB:
1043
    case RW_STATE_WORD0:
1044
    case RW_STATE_WORD1:
1045
        count = pit_get_count(s);
1046
        if (s->rw_state & 1)
1047
            ret = (count >> 8) & 0xff;
1048
        else
1049
            ret = count & 0xff;
1050
        if (s->rw_state & 2)
1051
            s->rw_state ^= 1;
1052
        break;
1053
    default:
1054
    case RW_STATE_LATCHED_WORD0:
1055
    case RW_STATE_LATCHED_WORD1:
1056
        if (s->rw_state & 1)
1057
            ret = s->latched_count >> 8;
1058
        else
1059
            ret = s->latched_count & 0xff;
1060
        s->rw_state ^= 1;
1061
        break;
1062
    }
1063
    return ret;
1064
}
1065

    
1066
void speaker_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1067
{
1068
    speaker_data_on = (val >> 1) & 1;
1069
    pit_channels[2].gate = val & 1;
1070
}
1071

    
1072
uint32_t speaker_ioport_read(CPUX86State *env, uint32_t addr)
1073
{
1074
    int out;
1075
    out = pit_get_out(&pit_channels[2]);
1076
    return (speaker_data_on << 1) | pit_channels[2].gate | (out << 5);
1077
}
1078

    
1079
void pit_init(void)
1080
{
1081
    PITChannelState *s;
1082
    int i;
1083

    
1084
    cpu_calibrate_ticks();
1085

    
1086
    for(i = 0;i < 3; i++) {
1087
        s = &pit_channels[i];
1088
        s->mode = 3;
1089
        s->gate = (i != 2);
1090
        pit_load_count(s, 0);
1091
    }
1092

    
1093
    register_ioport_write(0x40, 4, pit_ioport_write, 1);
1094
    register_ioport_read(0x40, 3, pit_ioport_read, 1);
1095

    
1096
    register_ioport_read(0x61, 1, speaker_ioport_read, 1);
1097
    register_ioport_write(0x61, 1, speaker_ioport_write, 1);
1098
}
1099

    
1100
/***********************************************************/
1101
/* serial port emulation */
1102

    
1103
#define UART_IRQ        4
1104

    
1105
#define UART_LCR_DLAB        0x80        /* Divisor latch access bit */
1106

    
1107
#define UART_IER_MSI        0x08        /* Enable Modem status interrupt */
1108
#define UART_IER_RLSI        0x04        /* Enable receiver line status interrupt */
1109
#define UART_IER_THRI        0x02        /* Enable Transmitter holding register int. */
1110
#define UART_IER_RDI        0x01        /* Enable receiver data interrupt */
1111

    
1112
#define UART_IIR_NO_INT        0x01        /* No interrupts pending */
1113
#define UART_IIR_ID        0x06        /* Mask for the interrupt ID */
1114

    
1115
#define UART_IIR_MSI        0x00        /* Modem status interrupt */
1116
#define UART_IIR_THRI        0x02        /* Transmitter holding register empty */
1117
#define UART_IIR_RDI        0x04        /* Receiver data interrupt */
1118
#define UART_IIR_RLSI        0x06        /* Receiver line status interrupt */
1119

    
1120
#define UART_LSR_TEMT        0x40        /* Transmitter empty */
1121
#define UART_LSR_THRE        0x20        /* Transmit-hold-register empty */
1122
#define UART_LSR_BI        0x10        /* Break interrupt indicator */
1123
#define UART_LSR_FE        0x08        /* Frame error indicator */
1124
#define UART_LSR_PE        0x04        /* Parity error indicator */
1125
#define UART_LSR_OE        0x02        /* Overrun error indicator */
1126
#define UART_LSR_DR        0x01        /* Receiver data ready */
1127

    
1128
typedef struct SerialState {
1129
    uint8_t divider;
1130
    uint8_t rbr; /* receive register */
1131
    uint8_t ier;
1132
    uint8_t iir; /* read only */
1133
    uint8_t lcr;
1134
    uint8_t mcr;
1135
    uint8_t lsr; /* read only */
1136
    uint8_t msr;
1137
    uint8_t scr;
1138
} SerialState;
1139

    
1140
SerialState serial_ports[1];
1141

    
1142
void serial_update_irq(void)
1143
{
1144
    SerialState *s = &serial_ports[0];
1145

    
1146
    if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {
1147
        s->iir = UART_IIR_RDI;
1148
    } else if ((s->lsr & UART_LSR_THRE) && (s->ier & UART_IER_THRI)) {
1149
        s->iir = UART_IIR_THRI;
1150
    } else {
1151
        s->iir = UART_IIR_NO_INT;
1152
    }
1153
    if (s->iir != UART_IIR_NO_INT) {
1154
        pic_set_irq(UART_IRQ, 1);
1155
    } else {
1156
        pic_set_irq(UART_IRQ, 0);
1157
    }
1158
}
1159

    
1160
void serial_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1161
{
1162
    SerialState *s = &serial_ports[0];
1163
    unsigned char ch;
1164
    int ret;
1165
    
1166
    addr &= 7;
1167
    switch(addr) {
1168
    default:
1169
    case 0:
1170
        if (s->lcr & UART_LCR_DLAB) {
1171
            s->divider = (s->divider & 0xff00) | val;
1172
        } else {
1173
            s->lsr &= ~UART_LSR_THRE;
1174
            serial_update_irq();
1175

    
1176
            ch = val;
1177
            do {
1178
                ret = write(1, &ch, 1);
1179
            } while (ret != 1);
1180
            s->lsr |= UART_LSR_THRE;
1181
            s->lsr |= UART_LSR_TEMT;
1182
            serial_update_irq();
1183
        }
1184
        break;
1185
    case 1:
1186
        if (s->lcr & UART_LCR_DLAB) {
1187
            s->divider = (s->divider & 0x00ff) | (val << 8);
1188
        } else {
1189
            s->ier = val;
1190
            serial_update_irq();
1191
        }
1192
        break;
1193
    case 2:
1194
        break;
1195
    case 3:
1196
        s->lcr = val;
1197
        break;
1198
    case 4:
1199
        s->mcr = val;
1200
        break;
1201
    case 5:
1202
        break;
1203
    case 6:
1204
        s->msr = val;
1205
        break;
1206
    case 7:
1207
        s->scr = val;
1208
        break;
1209
    }
1210
}
1211

    
1212
uint32_t serial_ioport_read(CPUX86State *env, uint32_t addr)
1213
{
1214
    SerialState *s = &serial_ports[0];
1215
    uint32_t ret;
1216

    
1217
    addr &= 7;
1218
    switch(addr) {
1219
    default:
1220
    case 0:
1221
        if (s->lcr & UART_LCR_DLAB) {
1222
            ret = s->divider & 0xff; 
1223
        } else {
1224
            ret = s->rbr;
1225
            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
1226
            serial_update_irq();
1227
        }
1228
        break;
1229
    case 1:
1230
        if (s->lcr & UART_LCR_DLAB) {
1231
            ret = (s->divider >> 8) & 0xff;
1232
        } else {
1233
            ret = s->ier;
1234
        }
1235
        break;
1236
    case 2:
1237
        ret = s->iir;
1238
        break;
1239
    case 3:
1240
        ret = s->lcr;
1241
        break;
1242
    case 4:
1243
        ret = s->mcr;
1244
        break;
1245
    case 5:
1246
        ret = s->lsr;
1247
        break;
1248
    case 6:
1249
        ret = s->msr;
1250
        break;
1251
    case 7:
1252
        ret = s->scr;
1253
        break;
1254
    }
1255
    return ret;
1256
}
1257

    
1258
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1259
static int term_got_escape;
1260

    
1261
void term_print_help(void)
1262
{
1263
    printf("\n"
1264
           "C-a h    print this help\n"
1265
           "C-a x    exit emulatior\n"
1266
           "C-a b    send break (magic sysrq)\n"
1267
           "C-a C-a  send C-a\n"
1268
           );
1269
}
1270

    
1271
/* called when a char is received */
1272
void serial_received_byte(SerialState *s, int ch)
1273
{
1274
    if (term_got_escape) {
1275
        term_got_escape = 0;
1276
        switch(ch) {
1277
        case 'h':
1278
            term_print_help();
1279
            break;
1280
        case 'x':
1281
            exit(0);
1282
            break;
1283
        case 'b':
1284
            /* send break */
1285
            s->rbr = 0;
1286
            s->lsr |= UART_LSR_BI | UART_LSR_DR;
1287
            serial_update_irq();
1288
            break;
1289
        case TERM_ESCAPE:
1290
            goto send_char;
1291
        }
1292
    } else if (ch == TERM_ESCAPE) {
1293
        term_got_escape = 1;
1294
    } else {
1295
    send_char:
1296
        s->rbr = ch;
1297
        s->lsr |= UART_LSR_DR;
1298
        serial_update_irq();
1299
    }
1300
}
1301

    
1302
/* init terminal so that we can grab keys */
1303
static struct termios oldtty;
1304

    
1305
static void term_exit(void)
1306
{
1307
    tcsetattr (0, TCSANOW, &oldtty);
1308
}
1309

    
1310
static void term_init(void)
1311
{
1312
    struct termios tty;
1313

    
1314
    tcgetattr (0, &tty);
1315
    oldtty = tty;
1316

    
1317
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1318
                          |INLCR|IGNCR|ICRNL|IXON);
1319
    tty.c_oflag |= OPOST;
1320
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1321
    tty.c_cflag &= ~(CSIZE|PARENB);
1322
    tty.c_cflag |= CS8;
1323
    tty.c_cc[VMIN] = 1;
1324
    tty.c_cc[VTIME] = 0;
1325
    
1326
    tcsetattr (0, TCSANOW, &tty);
1327

    
1328
    atexit(term_exit);
1329

    
1330
    fcntl(0, F_SETFL, O_NONBLOCK);
1331
}
1332

    
1333
void serial_init(void)
1334
{
1335
    SerialState *s = &serial_ports[0];
1336

    
1337
    s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
1338

    
1339
    register_ioport_write(0x3f8, 8, serial_ioport_write, 1);
1340
    register_ioport_read(0x3f8, 8, serial_ioport_read, 1);
1341

    
1342
    term_init();
1343
}
1344

    
1345
/***********************************************************/
1346
/* ne2000 emulation */
1347

    
1348
//#define DEBUG_NE2000
1349

    
1350
#define NE2000_IOPORT   0x300
1351
#define NE2000_IRQ      9
1352

    
1353
#define MAX_ETH_FRAME_SIZE 1514
1354

    
1355
#define E8390_CMD        0x00  /* The command register (for all pages) */
1356
/* Page 0 register offsets. */
1357
#define EN0_CLDALO        0x01        /* Low byte of current local dma addr  RD */
1358
#define EN0_STARTPG        0x01        /* Starting page of ring bfr WR */
1359
#define EN0_CLDAHI        0x02        /* High byte of current local dma addr  RD */
1360
#define EN0_STOPPG        0x02        /* Ending page +1 of ring bfr WR */
1361
#define EN0_BOUNDARY        0x03        /* Boundary page of ring bfr RD WR */
1362
#define EN0_TSR                0x04        /* Transmit status reg RD */
1363
#define EN0_TPSR        0x04        /* Transmit starting page WR */
1364
#define EN0_NCR                0x05        /* Number of collision reg RD */
1365
#define EN0_TCNTLO        0x05        /* Low  byte of tx byte count WR */
1366
#define EN0_FIFO        0x06        /* FIFO RD */
1367
#define EN0_TCNTHI        0x06        /* High byte of tx byte count WR */
1368
#define EN0_ISR                0x07        /* Interrupt status reg RD WR */
1369
#define EN0_CRDALO        0x08        /* low byte of current remote dma address RD */
1370
#define EN0_RSARLO        0x08        /* Remote start address reg 0 */
1371
#define EN0_CRDAHI        0x09        /* high byte, current remote dma address RD */
1372
#define EN0_RSARHI        0x09        /* Remote start address reg 1 */
1373
#define EN0_RCNTLO        0x0a        /* Remote byte count reg WR */
1374
#define EN0_RCNTHI        0x0b        /* Remote byte count reg WR */
1375
#define EN0_RSR                0x0c        /* rx status reg RD */
1376
#define EN0_RXCR        0x0c        /* RX configuration reg WR */
1377
#define EN0_TXCR        0x0d        /* TX configuration reg WR */
1378
#define EN0_COUNTER0        0x0d        /* Rcv alignment error counter RD */
1379
#define EN0_DCFG        0x0e        /* Data configuration reg WR */
1380
#define EN0_COUNTER1        0x0e        /* Rcv CRC error counter RD */
1381
#define EN0_IMR                0x0f        /* Interrupt mask reg WR */
1382
#define EN0_COUNTER2        0x0f        /* Rcv missed frame error counter RD */
1383

    
1384
#define EN1_PHYS        0x11
1385
#define EN1_CURPAG      0x17
1386
#define EN1_MULT        0x18
1387

    
1388
/*  Register accessed at EN_CMD, the 8390 base addr.  */
1389
#define E8390_STOP        0x01        /* Stop and reset the chip */
1390
#define E8390_START        0x02        /* Start the chip, clear reset */
1391
#define E8390_TRANS        0x04        /* Transmit a frame */
1392
#define E8390_RREAD        0x08        /* Remote read */
1393
#define E8390_RWRITE        0x10        /* Remote write  */
1394
#define E8390_NODMA        0x20        /* Remote DMA */
1395
#define E8390_PAGE0        0x00        /* Select page chip registers */
1396
#define E8390_PAGE1        0x40        /* using the two high-order bits */
1397
#define E8390_PAGE2        0x80        /* Page 3 is invalid. */
1398

    
1399
/* Bits in EN0_ISR - Interrupt status register */
1400
#define ENISR_RX        0x01        /* Receiver, no error */
1401
#define ENISR_TX        0x02        /* Transmitter, no error */
1402
#define ENISR_RX_ERR        0x04        /* Receiver, with error */
1403
#define ENISR_TX_ERR        0x08        /* Transmitter, with error */
1404
#define ENISR_OVER        0x10        /* Receiver overwrote the ring */
1405
#define ENISR_COUNTERS        0x20        /* Counters need emptying */
1406
#define ENISR_RDC        0x40        /* remote dma complete */
1407
#define ENISR_RESET        0x80        /* Reset completed */
1408
#define ENISR_ALL        0x3f        /* Interrupts we will enable */
1409

    
1410
/* Bits in received packet status byte and EN0_RSR*/
1411
#define ENRSR_RXOK        0x01        /* Received a good packet */
1412
#define ENRSR_CRC        0x02        /* CRC error */
1413
#define ENRSR_FAE        0x04        /* frame alignment error */
1414
#define ENRSR_FO        0x08        /* FIFO overrun */
1415
#define ENRSR_MPA        0x10        /* missed pkt */
1416
#define ENRSR_PHY        0x20        /* physical/multicast address */
1417
#define ENRSR_DIS        0x40        /* receiver disable. set in monitor mode */
1418
#define ENRSR_DEF        0x80        /* deferring */
1419

    
1420
/* Transmitted packet status, EN0_TSR. */
1421
#define ENTSR_PTX 0x01        /* Packet transmitted without error */
1422
#define ENTSR_ND  0x02        /* The transmit wasn't deferred. */
1423
#define ENTSR_COL 0x04        /* The transmit collided at least once. */
1424
#define ENTSR_ABT 0x08  /* The transmit collided 16 times, and was deferred. */
1425
#define ENTSR_CRS 0x10        /* The carrier sense was lost. */
1426
#define ENTSR_FU  0x20  /* A "FIFO underrun" occurred during transmit. */
1427
#define ENTSR_CDH 0x40        /* The collision detect "heartbeat" signal was lost. */
1428
#define ENTSR_OWC 0x80  /* There was an out-of-window collision. */
1429

    
1430
#define NE2000_MEM_SIZE 32768
1431

    
1432
typedef struct NE2000State {
1433
    uint8_t cmd;
1434
    uint32_t start;
1435
    uint32_t stop;
1436
    uint8_t boundary;
1437
    uint8_t tsr;
1438
    uint8_t tpsr;
1439
    uint16_t tcnt;
1440
    uint16_t rcnt;
1441
    uint32_t rsar;
1442
    uint8_t isr;
1443
    uint8_t dcfg;
1444
    uint8_t imr;
1445
    uint8_t phys[6]; /* mac address */
1446
    uint8_t curpag;
1447
    uint8_t mult[8]; /* multicast mask array */
1448
    uint8_t mem[NE2000_MEM_SIZE];
1449
} NE2000State;
1450

    
1451
NE2000State ne2000_state;
1452
int net_fd = -1;
1453
char network_script[1024];
1454

    
1455
void ne2000_reset(void)
1456
{
1457
    NE2000State *s = &ne2000_state;
1458
    int i;
1459

    
1460
    s->isr = ENISR_RESET;
1461
    s->mem[0] = 0x52;
1462
    s->mem[1] = 0x54;
1463
    s->mem[2] = 0x00;
1464
    s->mem[3] = 0x12;
1465
    s->mem[4] = 0x34;
1466
    s->mem[5] = 0x56;
1467
    s->mem[14] = 0x57;
1468
    s->mem[15] = 0x57;
1469

    
1470
    /* duplicate prom data */
1471
    for(i = 15;i >= 0; i--) {
1472
        s->mem[2 * i] = s->mem[i];
1473
        s->mem[2 * i + 1] = s->mem[i];
1474
    }
1475
}
1476

    
1477
void ne2000_update_irq(NE2000State *s)
1478
{
1479
    int isr;
1480
    isr = s->isr & s->imr;
1481
    if (isr)
1482
        pic_set_irq(NE2000_IRQ, 1);
1483
    else
1484
        pic_set_irq(NE2000_IRQ, 0);
1485
}
1486

    
1487
int net_init(void)
1488
{
1489
    struct ifreq ifr;
1490
    int fd, ret, pid, status;
1491
    
1492
    fd = open("/dev/net/tun", O_RDWR);
1493
    if (fd < 0) {
1494
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1495
        return -1;
1496
    }
1497
    memset(&ifr, 0, sizeof(ifr));
1498
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1499
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1500
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1501
    if (ret != 0) {
1502
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1503
        close(fd);
1504
        return -1;
1505
    }
1506
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
1507
    fcntl(fd, F_SETFL, O_NONBLOCK);
1508
    net_fd = fd;
1509

    
1510
    /* try to launch network init script */
1511
    pid = fork();
1512
    if (pid >= 0) {
1513
        if (pid == 0) {
1514
            execl(network_script, network_script, ifr.ifr_name, NULL);
1515
            exit(1);
1516
        }
1517
        while (waitpid(pid, &status, 0) != pid);
1518
        if (!WIFEXITED(status) ||
1519
            WEXITSTATUS(status) != 0) {
1520
            fprintf(stderr, "%s: could not launch network script for '%s'\n",
1521
                    network_script, ifr.ifr_name);
1522
        }
1523
    }
1524
    return 0;
1525
}
1526

    
1527
void net_send_packet(NE2000State *s, const uint8_t *buf, int size)
1528
{
1529
#ifdef DEBUG_NE2000
1530
    printf("NE2000: sending packet size=%d\n", size);
1531
#endif
1532
    write(net_fd, buf, size);
1533
}
1534

    
1535
/* return true if the NE2000 can receive more data */
1536
int ne2000_can_receive(NE2000State *s)
1537
{
1538
    int avail, index, boundary;
1539
    
1540
    if (s->cmd & E8390_STOP)
1541
        return 0;
1542
    index = s->curpag << 8;
1543
    boundary = s->boundary << 8;
1544
    if (index < boundary)
1545
        avail = boundary - index;
1546
    else
1547
        avail = (s->stop - s->start) - (index - boundary);
1548
    if (avail < (MAX_ETH_FRAME_SIZE + 4))
1549
        return 0;
1550
    return 1;
1551
}
1552

    
1553
void ne2000_receive(NE2000State *s, uint8_t *buf, int size)
1554
{
1555
    uint8_t *p;
1556
    int total_len, next, avail, len, index;
1557

    
1558
#if defined(DEBUG_NE2000)
1559
    printf("NE2000: received len=%d\n", size);
1560
#endif
1561

    
1562
    index = s->curpag << 8;
1563
    /* 4 bytes for header */
1564
    total_len = size + 4;
1565
    /* address for next packet (4 bytes for CRC) */
1566
    next = index + ((total_len + 4 + 255) & ~0xff);
1567
    if (next >= s->stop)
1568
        next -= (s->stop - s->start);
1569
    /* prepare packet header */
1570
    p = s->mem + index;
1571
    p[0] = ENRSR_RXOK; /* receive status */
1572
    p[1] = next >> 8;
1573
    p[2] = total_len;
1574
    p[3] = total_len >> 8;
1575
    index += 4;
1576

    
1577
    /* write packet data */
1578
    while (size > 0) {
1579
        avail = s->stop - index;
1580
        len = size;
1581
        if (len > avail)
1582
            len = avail;
1583
        memcpy(s->mem + index, buf, len);
1584
        buf += len;
1585
        index += len;
1586
        if (index == s->stop)
1587
            index = s->start;
1588
        size -= len;
1589
    }
1590
    s->curpag = next >> 8;
1591
    
1592
    /* now we can signal we have receive something */
1593
    s->isr |= ENISR_RX;
1594
    ne2000_update_irq(s);
1595
}
1596

    
1597
void ne2000_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1598
{
1599
    NE2000State *s = &ne2000_state;
1600
    int offset, page;
1601

    
1602
    addr &= 0xf;
1603
#ifdef DEBUG_NE2000
1604
    printf("NE2000: write addr=0x%x val=0x%02x\n", addr, val);
1605
#endif
1606
    if (addr == E8390_CMD) {
1607
        /* control register */
1608
        s->cmd = val;
1609
        if (val & E8390_START) {
1610
            /* test specific case: zero length transfert */
1611
            if ((val & (E8390_RREAD | E8390_RWRITE)) &&
1612
                s->rcnt == 0) {
1613
                s->isr |= ENISR_RDC;
1614
                ne2000_update_irq(s);
1615
            }
1616
            if (val & E8390_TRANS) {
1617
                net_send_packet(s, s->mem + (s->tpsr << 8), s->tcnt);
1618
                /* signal end of transfert */
1619
                s->tsr = ENTSR_PTX;
1620
                s->isr |= ENISR_TX;
1621
                ne2000_update_irq(s);
1622
            }
1623
        }
1624
    } else {
1625
        page = s->cmd >> 6;
1626
        offset = addr | (page << 4);
1627
        switch(offset) {
1628
        case EN0_STARTPG:
1629
            s->start = val << 8;
1630
            break;
1631
        case EN0_STOPPG:
1632
            s->stop = val << 8;
1633
            break;
1634
        case EN0_BOUNDARY:
1635
            s->boundary = val;
1636
            break;
1637
        case EN0_IMR:
1638
            s->imr = val;
1639
            ne2000_update_irq(s);
1640
            break;
1641
        case EN0_TPSR:
1642
            s->tpsr = val;
1643
            break;
1644
        case EN0_TCNTLO:
1645
            s->tcnt = (s->tcnt & 0xff00) | val;
1646
            break;
1647
        case EN0_TCNTHI:
1648
            s->tcnt = (s->tcnt & 0x00ff) | (val << 8);
1649
            break;
1650
        case EN0_RSARLO:
1651
            s->rsar = (s->rsar & 0xff00) | val;
1652
            break;
1653
        case EN0_RSARHI:
1654
            s->rsar = (s->rsar & 0x00ff) | (val << 8);
1655
            break;
1656
        case EN0_RCNTLO:
1657
            s->rcnt = (s->rcnt & 0xff00) | val;
1658
            break;
1659
        case EN0_RCNTHI:
1660
            s->rcnt = (s->rcnt & 0x00ff) | (val << 8);
1661
            break;
1662
        case EN0_DCFG:
1663
            s->dcfg = val;
1664
            break;
1665
        case EN0_ISR:
1666
            s->isr &= ~val;
1667
            ne2000_update_irq(s);
1668
            break;
1669
        case EN1_PHYS ... EN1_PHYS + 5:
1670
            s->phys[offset - EN1_PHYS] = val;
1671
            break;
1672
        case EN1_CURPAG:
1673
            s->curpag = val;
1674
            break;
1675
        case EN1_MULT ... EN1_MULT + 7:
1676
            s->mult[offset - EN1_MULT] = val;
1677
            break;
1678
        }
1679
    }
1680
}
1681

    
1682
uint32_t ne2000_ioport_read(CPUX86State *env, uint32_t addr)
1683
{
1684
    NE2000State *s = &ne2000_state;
1685
    int offset, page, ret;
1686

    
1687
    addr &= 0xf;
1688
    if (addr == E8390_CMD) {
1689
        ret = s->cmd;
1690
    } else {
1691
        page = s->cmd >> 6;
1692
        offset = addr | (page << 4);
1693
        switch(offset) {
1694
        case EN0_TSR:
1695
            ret = s->tsr;
1696
            break;
1697
        case EN0_BOUNDARY:
1698
            ret = s->boundary;
1699
            break;
1700
        case EN0_ISR:
1701
            ret = s->isr;
1702
            break;
1703
        case EN1_PHYS ... EN1_PHYS + 5:
1704
            ret = s->phys[offset - EN1_PHYS];
1705
            break;
1706
        case EN1_CURPAG:
1707
            ret = s->curpag;
1708
            break;
1709
        case EN1_MULT ... EN1_MULT + 7:
1710
            ret = s->mult[offset - EN1_MULT];
1711
            break;
1712
        default:
1713
            ret = 0x00;
1714
            break;
1715
        }
1716
    }
1717
#ifdef DEBUG_NE2000
1718
    printf("NE2000: read addr=0x%x val=%02x\n", addr, ret);
1719
#endif
1720
    return ret;
1721
}
1722

    
1723
void ne2000_asic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1724
{
1725
    NE2000State *s = &ne2000_state;
1726
    uint8_t *p;
1727

    
1728
#ifdef DEBUG_NE2000
1729
    printf("NE2000: asic write val=0x%04x\n", val);
1730
#endif
1731
    p = s->mem + s->rsar;
1732
    if (s->dcfg & 0x01) {
1733
        /* 16 bit access */
1734
        p[0] = val;
1735
        p[1] = val >> 8;
1736
        s->rsar += 2;
1737
        s->rcnt -= 2;
1738
    } else {
1739
        /* 8 bit access */
1740
        p[0] = val;
1741
        s->rsar++;
1742
        s->rcnt--;
1743
    }
1744
    /* wrap */
1745
    if (s->rsar == s->stop)
1746
        s->rsar = s->start;
1747
    if (s->rcnt == 0) {
1748
        /* signal end of transfert */
1749
        s->isr |= ENISR_RDC;
1750
        ne2000_update_irq(s);
1751
    }
1752
}
1753

    
1754
uint32_t ne2000_asic_ioport_read(CPUX86State *env, uint32_t addr)
1755
{
1756
    NE2000State *s = &ne2000_state;
1757
    uint8_t *p;
1758
    int ret;
1759

    
1760
    p = s->mem + s->rsar;
1761
    if (s->dcfg & 0x01) {
1762
        /* 16 bit access */
1763
        ret = p[0] | (p[1] << 8);
1764
        s->rsar += 2;
1765
        s->rcnt -= 2;
1766
    } else {
1767
        /* 8 bit access */
1768
        ret = p[0];
1769
        s->rsar++;
1770
        s->rcnt--;
1771
    }
1772
    /* wrap */
1773
    if (s->rsar == s->stop)
1774
        s->rsar = s->start;
1775
    if (s->rcnt == 0) {
1776
        /* signal end of transfert */
1777
        s->isr |= ENISR_RDC;
1778
        ne2000_update_irq(s);
1779
    }
1780
#ifdef DEBUG_NE2000
1781
    printf("NE2000: asic read val=0x%04x\n", ret);
1782
#endif
1783
    return ret;
1784
}
1785

    
1786
void ne2000_reset_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1787
{
1788
    /* nothing to do (end of reset pulse) */
1789
}
1790

    
1791
uint32_t ne2000_reset_ioport_read(CPUX86State *env, uint32_t addr)
1792
{
1793
    ne2000_reset();
1794
    return 0;
1795
}
1796

    
1797
void ne2000_init(void)
1798
{
1799
    register_ioport_write(NE2000_IOPORT, 16, ne2000_ioport_write, 1);
1800
    register_ioport_read(NE2000_IOPORT, 16, ne2000_ioport_read, 1);
1801

    
1802
    register_ioport_write(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_write, 1);
1803
    register_ioport_read(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_read, 1);
1804
    register_ioport_write(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_write, 2);
1805
    register_ioport_read(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_read, 2);
1806

    
1807
    register_ioport_write(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_write, 1);
1808
    register_ioport_read(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_read, 1);
1809
    ne2000_reset();
1810
}
1811

    
1812
/***********************************************************/
1813
/* ide emulation */
1814

    
1815
//#define DEBUG_IDE
1816

    
1817
/* Bits of HD_STATUS */
1818
#define ERR_STAT                0x01
1819
#define INDEX_STAT                0x02
1820
#define ECC_STAT                0x04        /* Corrected error */
1821
#define DRQ_STAT                0x08
1822
#define SEEK_STAT                0x10
1823
#define SRV_STAT                0x10
1824
#define WRERR_STAT                0x20
1825
#define READY_STAT                0x40
1826
#define BUSY_STAT                0x80
1827

    
1828
/* Bits for HD_ERROR */
1829
#define MARK_ERR                0x01        /* Bad address mark */
1830
#define TRK0_ERR                0x02        /* couldn't find track 0 */
1831
#define ABRT_ERR                0x04        /* Command aborted */
1832
#define MCR_ERR                        0x08        /* media change request */
1833
#define ID_ERR                        0x10        /* ID field not found */
1834
#define MC_ERR                        0x20        /* media changed */
1835
#define ECC_ERR                        0x40        /* Uncorrectable ECC error */
1836
#define BBD_ERR                        0x80        /* pre-EIDE meaning:  block marked bad */
1837
#define ICRC_ERR                0x80        /* new meaning:  CRC error during transfer */
1838

    
1839
/* Bits of HD_NSECTOR */
1840
#define CD                        0x01
1841
#define IO                        0x02
1842
#define REL                        0x04
1843
#define TAG_MASK                0xf8
1844

    
1845
#define IDE_CMD_RESET           0x04
1846
#define IDE_CMD_DISABLE_IRQ     0x02
1847

    
1848
/* ATA/ATAPI Commands pre T13 Spec */
1849
#define WIN_NOP                                0x00
1850
/*
1851
 *        0x01->0x02 Reserved
1852
 */
1853
#define CFA_REQ_EXT_ERROR_CODE                0x03 /* CFA Request Extended Error Code */
1854
/*
1855
 *        0x04->0x07 Reserved
1856
 */
1857
#define WIN_SRST                        0x08 /* ATAPI soft reset command */
1858
#define WIN_DEVICE_RESET                0x08
1859
/*
1860
 *        0x09->0x0F Reserved
1861
 */
1862
#define WIN_RECAL                        0x10
1863
#define WIN_RESTORE                        WIN_RECAL
1864
/*
1865
 *        0x10->0x1F Reserved
1866
 */
1867
#define WIN_READ                        0x20 /* 28-Bit */
1868
#define WIN_READ_ONCE                        0x21 /* 28-Bit without retries */
1869
#define WIN_READ_LONG                        0x22 /* 28-Bit */
1870
#define WIN_READ_LONG_ONCE                0x23 /* 28-Bit without retries */
1871
#define WIN_READ_EXT                        0x24 /* 48-Bit */
1872
#define WIN_READDMA_EXT                        0x25 /* 48-Bit */
1873
#define WIN_READDMA_QUEUED_EXT                0x26 /* 48-Bit */
1874
#define WIN_READ_NATIVE_MAX_EXT                0x27 /* 48-Bit */
1875
/*
1876
 *        0x28
1877
 */
1878
#define WIN_MULTREAD_EXT                0x29 /* 48-Bit */
1879
/*
1880
 *        0x2A->0x2F Reserved
1881
 */
1882
#define WIN_WRITE                        0x30 /* 28-Bit */
1883
#define WIN_WRITE_ONCE                        0x31 /* 28-Bit without retries */
1884
#define WIN_WRITE_LONG                        0x32 /* 28-Bit */
1885
#define WIN_WRITE_LONG_ONCE                0x33 /* 28-Bit without retries */
1886
#define WIN_WRITE_EXT                        0x34 /* 48-Bit */
1887
#define WIN_WRITEDMA_EXT                0x35 /* 48-Bit */
1888
#define WIN_WRITEDMA_QUEUED_EXT                0x36 /* 48-Bit */
1889
#define WIN_SET_MAX_EXT                        0x37 /* 48-Bit */
1890
#define CFA_WRITE_SECT_WO_ERASE                0x38 /* CFA Write Sectors without erase */
1891
#define WIN_MULTWRITE_EXT                0x39 /* 48-Bit */
1892
/*
1893
 *        0x3A->0x3B Reserved
1894
 */
1895
#define WIN_WRITE_VERIFY                0x3C /* 28-Bit */
1896
/*
1897
 *        0x3D->0x3F Reserved
1898
 */
1899
#define WIN_VERIFY                        0x40 /* 28-Bit - Read Verify Sectors */
1900
#define WIN_VERIFY_ONCE                        0x41 /* 28-Bit - without retries */
1901
#define WIN_VERIFY_EXT                        0x42 /* 48-Bit */
1902
/*
1903
 *        0x43->0x4F Reserved
1904
 */
1905
#define WIN_FORMAT                        0x50
1906
/*
1907
 *        0x51->0x5F Reserved
1908
 */
1909
#define WIN_INIT                        0x60
1910
/*
1911
 *        0x61->0x5F Reserved
1912
 */
1913
#define WIN_SEEK                        0x70 /* 0x70-0x7F Reserved */
1914
#define CFA_TRANSLATE_SECTOR                0x87 /* CFA Translate Sector */
1915
#define WIN_DIAGNOSE                        0x90
1916
#define WIN_SPECIFY                        0x91 /* set drive geometry translation */
1917
#define WIN_DOWNLOAD_MICROCODE                0x92
1918
#define WIN_STANDBYNOW2                        0x94
1919
#define WIN_STANDBY2                        0x96
1920
#define WIN_SETIDLE2                        0x97
1921
#define WIN_CHECKPOWERMODE2                0x98
1922
#define WIN_SLEEPNOW2                        0x99
1923
/*
1924
 *        0x9A VENDOR
1925
 */
1926
#define WIN_PACKETCMD                        0xA0 /* Send a packet command. */
1927
#define WIN_PIDENTIFY                        0xA1 /* identify ATAPI device        */
1928
#define WIN_QUEUED_SERVICE                0xA2
1929
#define WIN_SMART                        0xB0 /* self-monitoring and reporting */
1930
#define CFA_ERASE_SECTORS               0xC0
1931
#define WIN_MULTREAD                        0xC4 /* read sectors using multiple mode*/
1932
#define WIN_MULTWRITE                        0xC5 /* write sectors using multiple mode */
1933
#define WIN_SETMULT                        0xC6 /* enable/disable multiple mode */
1934
#define WIN_READDMA_QUEUED                0xC7 /* read sectors using Queued DMA transfers */
1935
#define WIN_READDMA                        0xC8 /* read sectors using DMA transfers */
1936
#define WIN_READDMA_ONCE                0xC9 /* 28-Bit - without retries */
1937
#define WIN_WRITEDMA                        0xCA /* write sectors using DMA transfers */
1938
#define WIN_WRITEDMA_ONCE                0xCB /* 28-Bit - without retries */
1939
#define WIN_WRITEDMA_QUEUED                0xCC /* write sectors using Queued DMA transfers */
1940
#define CFA_WRITE_MULTI_WO_ERASE        0xCD /* CFA Write multiple without erase */
1941
#define WIN_GETMEDIASTATUS                0xDA        
1942
#define WIN_ACKMEDIACHANGE                0xDB /* ATA-1, ATA-2 vendor */
1943
#define WIN_POSTBOOT                        0xDC
1944
#define WIN_PREBOOT                        0xDD
1945
#define WIN_DOORLOCK                        0xDE /* lock door on removable drives */
1946
#define WIN_DOORUNLOCK                        0xDF /* unlock door on removable drives */
1947
#define WIN_STANDBYNOW1                        0xE0
1948
#define WIN_IDLEIMMEDIATE                0xE1 /* force drive to become "ready" */
1949
#define WIN_STANDBY                     0xE2 /* Set device in Standby Mode */
1950
#define WIN_SETIDLE1                        0xE3
1951
#define WIN_READ_BUFFER                        0xE4 /* force read only 1 sector */
1952
#define WIN_CHECKPOWERMODE1                0xE5
1953
#define WIN_SLEEPNOW1                        0xE6
1954
#define WIN_FLUSH_CACHE                        0xE7
1955
#define WIN_WRITE_BUFFER                0xE8 /* force write only 1 sector */
1956
#define WIN_WRITE_SAME                        0xE9 /* read ata-2 to use */
1957
        /* SET_FEATURES 0x22 or 0xDD */
1958
#define WIN_FLUSH_CACHE_EXT                0xEA /* 48-Bit */
1959
#define WIN_IDENTIFY                        0xEC /* ask drive to identify itself        */
1960
#define WIN_MEDIAEJECT                        0xED
1961
#define WIN_IDENTIFY_DMA                0xEE /* same as WIN_IDENTIFY, but DMA */
1962
#define WIN_SETFEATURES                        0xEF /* set special drive features */
1963
#define EXABYTE_ENABLE_NEST                0xF0
1964
#define WIN_SECURITY_SET_PASS                0xF1
1965
#define WIN_SECURITY_UNLOCK                0xF2
1966
#define WIN_SECURITY_ERASE_PREPARE        0xF3
1967
#define WIN_SECURITY_ERASE_UNIT                0xF4
1968
#define WIN_SECURITY_FREEZE_LOCK        0xF5
1969
#define WIN_SECURITY_DISABLE                0xF6
1970
#define WIN_READ_NATIVE_MAX                0xF8 /* return the native maximum address */
1971
#define WIN_SET_MAX                        0xF9
1972
#define DISABLE_SEAGATE                        0xFB
1973

    
1974
/* set to 1 set disable mult support */
1975
#define MAX_MULT_SECTORS 8
1976

    
1977
#define MAX_DISKS 2
1978

    
1979
struct IDEState;
1980

    
1981
typedef void EndTransferFunc(struct IDEState *);
1982

    
1983
typedef struct IDEState {
1984
    /* ide config */
1985
    int cylinders, heads, sectors;
1986
    int64_t nb_sectors;
1987
    int mult_sectors;
1988
    int irq;
1989
    /* ide regs */
1990
    uint8_t feature;
1991
    uint8_t error;
1992
    uint16_t nsector; /* 0 is 256 to ease computations */
1993
    uint8_t sector;
1994
    uint8_t lcyl;
1995
    uint8_t hcyl;
1996
    uint8_t select;
1997
    uint8_t status;
1998
    /* 0x3f6 command, only meaningful for drive 0 */
1999
    uint8_t cmd;
2000
    /* depends on bit 4 in select, only meaningful for drive 0 */
2001
    struct IDEState *cur_drive; 
2002
    BlockDriverState *bs;
2003
    int req_nb_sectors; /* number of sectors per interrupt */
2004
    EndTransferFunc *end_transfer_func;
2005
    uint8_t *data_ptr;
2006
    uint8_t *data_end;
2007
    uint8_t io_buffer[MAX_MULT_SECTORS*512 + 4];
2008
} IDEState;
2009

    
2010
BlockDriverState *bs_table[MAX_DISKS];
2011
IDEState ide_state[MAX_DISKS];
2012

    
2013
static void padstr(char *str, const char *src, int len)
2014
{
2015
    int i, v;
2016
    for(i = 0; i < len; i++) {
2017
        if (*src)
2018
            v = *src++;
2019
        else
2020
            v = ' ';
2021
        *(char *)((long)str ^ 1) = v;
2022
        str++;
2023
    }
2024
}
2025

    
2026
static void ide_identify(IDEState *s)
2027
{
2028
    uint16_t *p;
2029
    unsigned int oldsize;
2030

    
2031
    memset(s->io_buffer, 0, 512);
2032
    p = (uint16_t *)s->io_buffer;
2033
    stw(p + 0, 0x0040);
2034
    stw(p + 1, s->cylinders); 
2035
    stw(p + 3, s->heads);
2036
    stw(p + 4, 512 * s->sectors); /* sectors */
2037
    stw(p + 5, 512); /* sector size */
2038
    stw(p + 6, s->sectors); 
2039
    stw(p + 20, 3); /* buffer type */
2040
    stw(p + 21, 512); /* cache size in sectors */
2041
    stw(p + 22, 4); /* ecc bytes */
2042
    padstr((uint8_t *)(p + 27), "QEMU HARDDISK", 40);
2043
#if MAX_MULT_SECTORS > 1    
2044
    stw(p + 47, MAX_MULT_SECTORS);
2045
#endif
2046
    stw(p + 48, 1); /* dword I/O */
2047
    stw(p + 49, 1 << 9); /* LBA supported, no DMA */
2048
    stw(p + 51, 0x200); /* PIO transfer cycle */
2049
    stw(p + 52, 0x200); /* DMA transfer cycle */
2050
    stw(p + 54, s->cylinders);
2051
    stw(p + 55, s->heads);
2052
    stw(p + 56, s->sectors);
2053
    oldsize = s->cylinders * s->heads * s->sectors;
2054
    stw(p + 57, oldsize);
2055
    stw(p + 58, oldsize >> 16);
2056
    if (s->mult_sectors)
2057
        stw(p + 59, 0x100 | s->mult_sectors);
2058
    stw(p + 60, s->nb_sectors);
2059
    stw(p + 61, s->nb_sectors >> 16);
2060
    stw(p + 80, (1 << 1) | (1 << 2));
2061
    stw(p + 82, (1 << 14));
2062
    stw(p + 83, (1 << 14));
2063
    stw(p + 84, (1 << 14));
2064
    stw(p + 85, (1 << 14));
2065
    stw(p + 86, 0);
2066
    stw(p + 87, (1 << 14));
2067
}
2068

    
2069
static inline void ide_abort_command(IDEState *s)
2070
{
2071
    s->status = READY_STAT | ERR_STAT;
2072
    s->error = ABRT_ERR;
2073
}
2074

    
2075
static inline void ide_set_irq(IDEState *s)
2076
{
2077
    if (!(ide_state[0].cmd & IDE_CMD_DISABLE_IRQ)) {
2078
        pic_set_irq(s->irq, 1);
2079
    }
2080
}
2081

    
2082
/* prepare data transfer and tell what to do after */
2083
static void ide_transfer_start(IDEState *s, int size, 
2084
                               EndTransferFunc *end_transfer_func)
2085
{
2086
    s->end_transfer_func = end_transfer_func;
2087
    s->data_ptr = s->io_buffer;
2088
    s->data_end = s->io_buffer + size;
2089
    s->status |= DRQ_STAT;
2090
}
2091

    
2092
static void ide_transfer_stop(IDEState *s)
2093
{
2094
    s->end_transfer_func = ide_transfer_stop;
2095
    s->data_ptr = s->io_buffer;
2096
    s->data_end = s->io_buffer;
2097
    s->status &= ~DRQ_STAT;
2098
}
2099

    
2100
static int64_t ide_get_sector(IDEState *s)
2101
{
2102
    int64_t sector_num;
2103
    if (s->select & 0x40) {
2104
        /* lba */
2105
        sector_num = ((s->select & 0x0f) << 24) | (s->hcyl << 16) | 
2106
            (s->lcyl << 8) | s->sector;
2107
    } else {
2108
        sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors +
2109
            (s->select & 0x0f) * s->sectors + 
2110
            (s->sector - 1);
2111
    }
2112
    return sector_num;
2113
}
2114

    
2115
static void ide_set_sector(IDEState *s, int64_t sector_num)
2116
{
2117
    unsigned int cyl, r;
2118
    if (s->select & 0x40) {
2119
        s->select = (s->select & 0xf0) | (sector_num >> 24);
2120
        s->hcyl = (sector_num >> 16);
2121
        s->lcyl = (sector_num >> 8);
2122
        s->sector = (sector_num);
2123
    } else {
2124
        cyl = sector_num / (s->heads * s->sectors);
2125
        r = sector_num % (s->heads * s->sectors);
2126
        s->hcyl = cyl >> 8;
2127
        s->lcyl = cyl;
2128
        s->select = (s->select & 0xf0) | (r / s->sectors);
2129
        s->sector = (r % s->sectors) + 1;
2130
    }
2131
}
2132

    
2133
static void ide_sector_read(IDEState *s)
2134
{
2135
    int64_t sector_num;
2136
    int ret, n;
2137

    
2138
    s->status = READY_STAT | SEEK_STAT;
2139
    sector_num = ide_get_sector(s);
2140
    n = s->nsector;
2141
    if (n == 0) {
2142
        /* no more sector to read from disk */
2143
        ide_transfer_stop(s);
2144
    } else {
2145
#if defined(DEBUG_IDE)
2146
        printf("read sector=%Ld\n", sector_num);
2147
#endif
2148
        if (n > s->req_nb_sectors)
2149
            n = s->req_nb_sectors;
2150
        ret = bdrv_read(s->bs, sector_num, s->io_buffer, n);
2151
        ide_transfer_start(s, 512 * n, ide_sector_read);
2152
        ide_set_irq(s);
2153
        ide_set_sector(s, sector_num + n);
2154
        s->nsector -= n;
2155
    }
2156
}
2157

    
2158
static void ide_sector_write(IDEState *s)
2159
{
2160
    int64_t sector_num;
2161
    int ret, n, n1;
2162

    
2163
    s->status = READY_STAT | SEEK_STAT;
2164
    sector_num = ide_get_sector(s);
2165
#if defined(DEBUG_IDE)
2166
    printf("write sector=%Ld\n", sector_num);
2167
#endif
2168
    n = s->nsector;
2169
    if (n > s->req_nb_sectors)
2170
        n = s->req_nb_sectors;
2171
    ret = bdrv_write(s->bs, sector_num, s->io_buffer, n);
2172
    s->nsector -= n;
2173
    if (s->nsector == 0) {
2174
        /* no more sector to write */
2175
        ide_transfer_stop(s);
2176
    } else {
2177
        n1 = s->nsector;
2178
        if (n1 > s->req_nb_sectors)
2179
            n1 = s->req_nb_sectors;
2180
        ide_transfer_start(s, 512 * n1, ide_sector_write);
2181
    }
2182
    ide_set_sector(s, sector_num + n);
2183
    ide_set_irq(s);
2184
}
2185

    
2186
void ide_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
2187
{
2188
    IDEState *s = ide_state[0].cur_drive;
2189
    int unit, n;
2190

    
2191
    addr &= 7;
2192
#ifdef DEBUG_IDE
2193
    printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);
2194
#endif
2195
    switch(addr) {
2196
    case 0:
2197
        break;
2198
    case 1:
2199
        s->feature = val;
2200
        break;
2201
    case 2:
2202
        if (val == 0)
2203
            val = 256;
2204
        s->nsector = val;
2205
        break;
2206
    case 3:
2207
        s->sector = val;
2208
        break;
2209
    case 4:
2210
        s->lcyl = val;
2211
        break;
2212
    case 5:
2213
        s->hcyl = val;
2214
        break;
2215
    case 6:
2216
        /* select drive */
2217
        unit = (val >> 4) & 1;
2218
        s = &ide_state[unit];
2219
        ide_state[0].cur_drive = s;
2220
        s->select = val;
2221
        break;
2222
    default:
2223
    case 7:
2224
        /* command */
2225
#if defined(DEBUG_IDE)
2226
        printf("ide: CMD=%02x\n", val);
2227
#endif
2228
        switch(val) {
2229
        case WIN_PIDENTIFY:
2230
        case WIN_IDENTIFY:
2231
            if (s->bs) {
2232
                ide_identify(s);
2233
                s->status = READY_STAT;
2234
                ide_transfer_start(s, 512, ide_transfer_stop);
2235
            } else {
2236
                ide_abort_command(s);
2237
            }
2238
            ide_set_irq(s);
2239
            break;
2240
        case WIN_SPECIFY:
2241
        case WIN_RECAL:
2242
            s->status = READY_STAT;
2243
            ide_set_irq(s);
2244
            break;
2245
        case WIN_SETMULT:
2246
            if (s->nsector > MAX_MULT_SECTORS || 
2247
                s->nsector == 0 ||
2248
                (s->nsector & (s->nsector - 1)) != 0) {
2249
                ide_abort_command(s);
2250
            } else {
2251
                s->mult_sectors = s->nsector;
2252
                s->status = READY_STAT;
2253
            }
2254
            ide_set_irq(s);
2255
            break;
2256
        case WIN_READ:
2257
        case WIN_READ_ONCE:
2258
            s->req_nb_sectors = 1;
2259
            ide_sector_read(s);
2260
            break;
2261
        case WIN_WRITE:
2262
        case WIN_WRITE_ONCE:
2263
            s->status = SEEK_STAT;
2264
            s->req_nb_sectors = 1;
2265
            ide_transfer_start(s, 512, ide_sector_write);
2266
            break;
2267
        case WIN_MULTREAD:
2268
            if (!s->mult_sectors)
2269
                goto abort_cmd;
2270
            s->req_nb_sectors = s->mult_sectors;
2271
            ide_sector_read(s);
2272
            break;
2273
        case WIN_MULTWRITE:
2274
            if (!s->mult_sectors)
2275
                goto abort_cmd;
2276
            s->status = SEEK_STAT;
2277
            s->req_nb_sectors = s->mult_sectors;
2278
            n = s->nsector;
2279
            if (n > s->req_nb_sectors)
2280
                n = s->req_nb_sectors;
2281
            ide_transfer_start(s, 512 * n, ide_sector_write);
2282
            break;
2283
        default:
2284
        abort_cmd:
2285
            ide_abort_command(s);
2286
            ide_set_irq(s);
2287
            break;
2288
        }
2289
    }
2290
}
2291

    
2292
uint32_t ide_ioport_read(CPUX86State *env, uint32_t addr)
2293
{
2294
    IDEState *s = ide_state[0].cur_drive;
2295
    int ret;
2296

    
2297
    addr &= 7;
2298
    switch(addr) {
2299
    case 0:
2300
        ret = 0xff;
2301
        break;
2302
    case 1:
2303
        ret = s->error;
2304
        break;
2305
    case 2:
2306
        ret = s->nsector & 0xff;
2307
        break;
2308
    case 3:
2309
        ret = s->sector;
2310
        break;
2311
    case 4:
2312
        ret = s->lcyl;
2313
        break;
2314
    case 5:
2315
        ret = s->hcyl;
2316
        break;
2317
    case 6:
2318
        ret = s->select;
2319
        break;
2320
    default:
2321
    case 7:
2322
        ret = s->status;
2323
        pic_set_irq(s->irq, 0);
2324
        break;
2325
    }
2326
#ifdef DEBUG_IDE
2327
    printf("ide: read addr=0x%x val=%02x\n", addr, ret);
2328
#endif
2329
    return ret;
2330
}
2331

    
2332
uint32_t ide_status_read(CPUX86State *env, uint32_t addr)
2333
{
2334
    IDEState *s = ide_state[0].cur_drive;
2335
    int ret;
2336
    ret = s->status;
2337
#ifdef DEBUG_IDE
2338
    printf("ide: read addr=0x%x val=%02x\n", addr, ret);
2339
#endif
2340
    return ret;
2341
}
2342

    
2343
void ide_cmd_write(CPUX86State *env, uint32_t addr, uint32_t val)
2344
{
2345
    IDEState *s = &ide_state[0];
2346
    /* common for both drives */
2347
    s->cmd = val;
2348
}
2349

    
2350
void ide_data_writew(CPUX86State *env, uint32_t addr, uint32_t val)
2351
{
2352
    IDEState *s = ide_state[0].cur_drive;
2353
    uint8_t *p;
2354

    
2355
    p = s->data_ptr;
2356
    *(uint16_t *)p = tswap16(val);
2357
    p += 2;
2358
    s->data_ptr = p;
2359
    if (p >= s->data_end)
2360
        s->end_transfer_func(s);
2361
}
2362

    
2363
uint32_t ide_data_readw(CPUX86State *env, uint32_t addr)
2364
{
2365
    IDEState *s = ide_state[0].cur_drive;
2366
    uint8_t *p;
2367
    int ret;
2368
    
2369
    p = s->data_ptr;
2370
    ret = tswap16(*(uint16_t *)p);
2371
    p += 2;
2372
    s->data_ptr = p;
2373
    if (p >= s->data_end)
2374
        s->end_transfer_func(s);
2375
    return ret;
2376
}
2377

    
2378
void ide_data_writel(CPUX86State *env, uint32_t addr, uint32_t val)
2379
{
2380
    IDEState *s = ide_state[0].cur_drive;
2381
    uint8_t *p;
2382

    
2383
    p = s->data_ptr;
2384
    *(uint32_t *)p = tswap32(val);
2385
    p += 4;
2386
    s->data_ptr = p;
2387
    if (p >= s->data_end)
2388
        s->end_transfer_func(s);
2389
}
2390

    
2391
uint32_t ide_data_readl(CPUX86State *env, uint32_t addr)
2392
{
2393
    IDEState *s = ide_state[0].cur_drive;
2394
    uint8_t *p;
2395
    int ret;
2396
    
2397
    p = s->data_ptr;
2398
    ret = tswap32(*(uint32_t *)p);
2399
    p += 4;
2400
    s->data_ptr = p;
2401
    if (p >= s->data_end)
2402
        s->end_transfer_func(s);
2403
    return ret;
2404
}
2405

    
2406
void ide_reset(IDEState *s)
2407
{
2408
    s->mult_sectors = MAX_MULT_SECTORS;
2409
    s->status = READY_STAT;
2410
    s->cur_drive = s;
2411
    s->select = 0xa0;
2412
}
2413

    
2414
void ide_init(void)
2415
{
2416
    IDEState *s;
2417
    int i, cylinders;
2418
    int64_t nb_sectors;
2419

    
2420
    for(i = 0; i < MAX_DISKS; i++) {
2421
        s = &ide_state[i];
2422
        s->bs = bs_table[i];
2423
        if (s->bs) {
2424
            bdrv_get_geometry(s->bs, &nb_sectors);
2425
            cylinders = nb_sectors / (16 * 63);
2426
            if (cylinders > 16383)
2427
                cylinders = 16383;
2428
            else if (cylinders < 2)
2429
                cylinders = 2;
2430
            s->cylinders = cylinders;
2431
            s->heads = 16;
2432
            s->sectors = 63;
2433
            s->nb_sectors = nb_sectors;
2434
        }
2435
        s->irq = 14;
2436
        ide_reset(s);
2437
    }
2438
    register_ioport_write(0x1f0, 8, ide_ioport_write, 1);
2439
    register_ioport_read(0x1f0, 8, ide_ioport_read, 1);
2440
    register_ioport_read(0x3f6, 1, ide_status_read, 1);
2441
    register_ioport_write(0x3f6, 1, ide_cmd_write, 1);
2442

    
2443
    /* data ports */
2444
    register_ioport_write(0x1f0, 2, ide_data_writew, 2);
2445
    register_ioport_read(0x1f0, 2, ide_data_readw, 2);
2446
    register_ioport_write(0x1f0, 4, ide_data_writel, 4);
2447
    register_ioport_read(0x1f0, 4, ide_data_readl, 4);
2448
}
2449

    
2450
/***********************************************************/
2451
/* cpu signal handler */
2452
static void host_segv_handler(int host_signum, siginfo_t *info, 
2453
                              void *puc)
2454
{
2455
    if (cpu_signal_handler(host_signum, info, puc))
2456
        return;
2457
    term_exit();
2458
    abort();
2459
}
2460

    
2461
static int timer_irq_pending;
2462
static int timer_irq_count;
2463

    
2464
static void host_alarm_handler(int host_signum, siginfo_t *info, 
2465
                               void *puc)
2466
{
2467
    /* NOTE: since usually the OS asks a 100 Hz clock, there can be
2468
       some drift between cpu_get_ticks() and the interrupt time. So
2469
       we queue some interrupts to avoid missing some */
2470
    timer_irq_count += pit_get_out_edges(&pit_channels[0]);
2471
    if (timer_irq_count) {
2472
        if (timer_irq_count > 2)
2473
            timer_irq_count = 2;
2474
        timer_irq_count--;
2475
        /* just exit from the cpu to have a chance to handle timers */
2476
        cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
2477
        timer_irq_pending = 1;
2478
    }
2479
}
2480

    
2481
/* main execution loop */
2482

    
2483
CPUState *cpu_gdbstub_get_env(void *opaque)
2484
{
2485
    return global_env;
2486
}
2487

    
2488
void main_loop(void *opaque)
2489
{
2490
    struct pollfd ufds[2], *pf, *serial_ufd, *net_ufd, *gdb_ufd;
2491
    int ret, n, timeout;
2492
    uint8_t ch;
2493
    CPUState *env = global_env;
2494

    
2495
    for(;;) {
2496

    
2497
        ret = cpu_x86_exec(env);
2498

    
2499
        /* if hlt instruction, we wait until the next IRQ */
2500
        if (ret == EXCP_HLT) 
2501
            timeout = 10;
2502
        else
2503
            timeout = 0;
2504
        /* poll any events */
2505
        serial_ufd = NULL;
2506
        pf = ufds;
2507
        if (!(serial_ports[0].lsr & UART_LSR_DR)) {
2508
            serial_ufd = pf;
2509
            pf->fd = 0;
2510
            pf->events = POLLIN;
2511
            pf++;
2512
        }
2513
        net_ufd = NULL;
2514
        if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) {
2515
            net_ufd = pf;
2516
            pf->fd = net_fd;
2517
            pf->events = POLLIN;
2518
            pf++;
2519
        }
2520
        gdb_ufd = NULL;
2521
        if (gdbstub_fd > 0) {
2522
            gdb_ufd = pf;
2523
            pf->fd = gdbstub_fd;
2524
            pf->events = POLLIN;
2525
            pf++;
2526
        }
2527

    
2528
        ret = poll(ufds, pf - ufds, timeout);
2529
        if (ret > 0) {
2530
            if (serial_ufd && (serial_ufd->revents & POLLIN)) {
2531
                n = read(0, &ch, 1);
2532
                if (n == 1) {
2533
                    serial_received_byte(&serial_ports[0], ch);
2534
                }
2535
            }
2536
            if (net_ufd && (net_ufd->revents & POLLIN)) {
2537
                uint8_t buf[MAX_ETH_FRAME_SIZE];
2538

    
2539
                n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);
2540
                if (n > 0) {
2541
                    if (n < 60) {
2542
                        memset(buf + n, 0, 60 - n);
2543
                        n = 60;
2544
                    }
2545
                    ne2000_receive(&ne2000_state, buf, n);
2546
                }
2547
            }
2548
            if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {
2549
                uint8_t buf[1];
2550
                /* stop emulation if requested by gdb */
2551
                n = read(gdbstub_fd, buf, 1);
2552
                if (n == 1)
2553
                    break;
2554
            }
2555
        }
2556

    
2557
        /* timer IRQ */
2558
        if (timer_irq_pending) {
2559
            pic_set_irq(0, 1);
2560
            pic_set_irq(0, 0);
2561
            timer_irq_pending = 0;
2562
        }
2563
    }
2564
}
2565

    
2566
void help(void)
2567
{
2568
    printf("Virtual Linux version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
2569
           "usage: vl [options] bzImage [kernel parameters...]\n"
2570
           "\n"
2571
           "'bzImage' is a Linux kernel image (PAGE_OFFSET must be defined\n"
2572
           "to 0x90000000 in asm/page.h and arch/i386/vmlinux.lds)\n"
2573
           "\n"
2574
           "General options:\n"
2575
           "-initrd file   use 'file' as initial ram disk\n"
2576
           "-hda file      use 'file' as hard disk 0 image\n"
2577
           "-hdb file      use 'file' as hard disk 1 image\n"
2578
           "-m megs        set virtual RAM size to megs MB\n"
2579
           "-n script      set network init script [default=%s]\n"
2580
           "\n"
2581
           "Debug options:\n"
2582
           "-s             wait gdb connection to port %d\n"
2583
           "-p port        change gdb connection port\n"
2584
           "-d             output log in /tmp/vl.log\n"
2585
           "\n"
2586
           "During emulation, use C-a h to get terminal commands:\n",
2587
           DEFAULT_NETWORK_SCRIPT, DEFAULT_GDBSTUB_PORT);
2588
    term_print_help();
2589
    exit(1);
2590
}
2591

    
2592
struct option long_options[] = {
2593
    { "initrd", 1, NULL, 0, },
2594
    { "hda", 1, NULL, 0, },
2595
    { "hdb", 1, NULL, 0, },
2596
    { NULL, 0, NULL, 0 },
2597
};
2598

    
2599
int main(int argc, char **argv)
2600
{
2601
    int c, ret, initrd_size, i, use_gdbstub, gdbstub_port, long_index;
2602
    struct linux_params *params;
2603
    struct sigaction act;
2604
    struct itimerval itv;
2605
    CPUX86State *env;
2606
    const char *tmpdir, *initrd_filename;
2607
    const char *hd_filename[MAX_DISKS];
2608
    
2609
    /* we never want that malloc() uses mmap() */
2610
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2611
    initrd_filename = NULL;
2612
    for(i = 0; i < MAX_DISKS; i++)
2613
        hd_filename[i] = NULL;
2614
    phys_ram_size = 32 * 1024 * 1024;
2615
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2616
    use_gdbstub = 0;
2617
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
2618
    for(;;) {
2619
        c = getopt_long_only(argc, argv, "hm:dn:sp:", long_options, &long_index);
2620
        if (c == -1)
2621
            break;
2622
        switch(c) {
2623
        case 0:
2624
            switch(long_index) {
2625
            case 0:
2626
                initrd_filename = optarg;
2627
                break;
2628
            case 1:
2629
                hd_filename[0] = optarg;
2630
                break;
2631
            case 2:
2632
                hd_filename[1] = optarg;
2633
                break;
2634
            }
2635
            break;
2636
        case 'h':
2637
            help();
2638
            break;
2639
        case 'm':
2640
            phys_ram_size = atoi(optarg) * 1024 * 1024;
2641
            if (phys_ram_size <= 0)
2642
                help();
2643
            break;
2644
        case 'd':
2645
            loglevel = 1;
2646
            break;
2647
        case 'n':
2648
            pstrcpy(network_script, sizeof(network_script), optarg);
2649
            break;
2650
        case 's':
2651
            use_gdbstub = 1;
2652
            break;
2653
        case 'p':
2654
            gdbstub_port = atoi(optarg);
2655
            break;
2656
        }
2657
    }
2658
    if (optind >= argc)
2659
        help();
2660

    
2661
    /* init debug */
2662
    setvbuf(stdout, NULL, _IOLBF, 0);
2663
    if (loglevel) {
2664
        logfile = fopen(DEBUG_LOGFILE, "w");
2665
        if (!logfile) {
2666
            perror(DEBUG_LOGFILE);
2667
            _exit(1);
2668
        }
2669
        setvbuf(logfile, NULL, _IOLBF, 0);
2670
    }
2671

    
2672
    /* open the virtual block devices */
2673
    for(i = 0; i < MAX_DISKS; i++) {
2674
        if (hd_filename[i]) {
2675
            bs_table[i] = bdrv_open(hd_filename[i]);
2676
            if (!bs_table[i]) {
2677
                fprintf(stderr, "vl: could not open hard disk image '%s\n",
2678
                        hd_filename[i]);
2679
                exit(1);
2680
            }
2681
        }
2682
    }
2683

    
2684
    /* init network tun interface */
2685
    net_init();
2686

    
2687
    /* init the memory */
2688
    tmpdir = getenv("VLTMPDIR");
2689
    if (!tmpdir)
2690
        tmpdir = "/tmp";
2691
    snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2692
    if (mkstemp(phys_ram_file) < 0) {
2693
        fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2694
                phys_ram_file);
2695
        exit(1);
2696
    }
2697
    phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2698
    if (phys_ram_fd < 0) {
2699
        fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2700
                phys_ram_file);
2701
        exit(1);
2702
    }
2703
    ftruncate(phys_ram_fd, phys_ram_size);
2704
    unlink(phys_ram_file);
2705
    phys_ram_base = mmap((void *)PHYS_RAM_BASE, phys_ram_size, 
2706
                         PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2707
                         phys_ram_fd, 0);
2708
    if (phys_ram_base == MAP_FAILED) {
2709
        fprintf(stderr, "Could not map physical memory\n");
2710
        exit(1);
2711
    }
2712

    
2713
    /* now we can load the kernel */
2714
    ret = load_kernel(argv[optind], phys_ram_base + KERNEL_LOAD_ADDR);
2715
    if (ret < 0) {
2716
        fprintf(stderr, "vl: could not load kernel '%s'\n", argv[optind]);
2717
        exit(1);
2718
    }
2719

    
2720
    /* load initrd */
2721
    initrd_size = 0;
2722
    if (initrd_filename) {
2723
        initrd_size = load_image(initrd_filename, phys_ram_base + INITRD_LOAD_ADDR);
2724
        if (initrd_size < 0) {
2725
            fprintf(stderr, "vl: could not load initial ram disk '%s'\n", 
2726
                    initrd_filename);
2727
            exit(1);
2728
        }
2729
    }
2730

    
2731
    /* init kernel params */
2732
    params = (void *)(phys_ram_base + KERNEL_PARAMS_ADDR);
2733
    memset(params, 0, sizeof(struct linux_params));
2734
    params->mount_root_rdonly = 0;
2735
    params->cl_magic = 0xA33F;
2736
    params->cl_offset = params->commandline - (uint8_t *)params;
2737
    params->ext_mem_k = (phys_ram_size / 1024) - 1024;
2738
    for(i = optind + 1; i < argc; i++) {
2739
        if (i != optind + 1)
2740
            pstrcat(params->commandline, sizeof(params->commandline), " ");
2741
        pstrcat(params->commandline, sizeof(params->commandline), argv[i]);
2742
    }
2743
    params->loader_type = 0x01;
2744
    if (initrd_size > 0) {
2745
        params->initrd_start = INITRD_LOAD_ADDR;
2746
        params->initrd_size = initrd_size;
2747
    }
2748
    params->orig_video_lines = 25;
2749
    params->orig_video_cols = 80;
2750

    
2751
    /* init basic PC hardware */
2752
    init_ioports();
2753
    register_ioport_write(0x80, 1, ioport80_write, 1);
2754

    
2755
    register_ioport_write(0x3d4, 2, vga_ioport_write, 1);
2756

    
2757
    cmos_init();
2758
    pic_init();
2759
    pit_init();
2760
    serial_init();
2761
    ne2000_init();
2762
    ide_init();
2763

    
2764
    /* setup cpu signal handlers for MMU / self modifying code handling */
2765
    sigfillset(&act.sa_mask);
2766
    act.sa_flags = SA_SIGINFO;
2767
    act.sa_sigaction = host_segv_handler;
2768
    sigaction(SIGSEGV, &act, NULL);
2769
    sigaction(SIGBUS, &act, NULL);
2770

    
2771
    act.sa_sigaction = host_alarm_handler;
2772
    sigaction(SIGALRM, &act, NULL);
2773

    
2774
    /* init CPU state */
2775
    env = cpu_init();
2776
    global_env = env;
2777
    cpu_single_env = env;
2778

    
2779
    /* setup basic memory access */
2780
    env->cr[0] = 0x00000033;
2781
    cpu_x86_init_mmu(env);
2782
    
2783
    memset(params->idt_table, 0, sizeof(params->idt_table));
2784

    
2785
    params->gdt_table[2] = 0x00cf9a000000ffffLL; /* KERNEL_CS */
2786
    params->gdt_table[3] = 0x00cf92000000ffffLL; /* KERNEL_DS */
2787
    
2788
    env->idt.base = (void *)params->idt_table;
2789
    env->idt.limit = sizeof(params->idt_table) - 1;
2790
    env->gdt.base = (void *)params->gdt_table;
2791
    env->gdt.limit = sizeof(params->gdt_table) - 1;
2792

    
2793
    cpu_x86_load_seg(env, R_CS, KERNEL_CS);
2794
    cpu_x86_load_seg(env, R_DS, KERNEL_DS);
2795
    cpu_x86_load_seg(env, R_ES, KERNEL_DS);
2796
    cpu_x86_load_seg(env, R_SS, KERNEL_DS);
2797
    cpu_x86_load_seg(env, R_FS, KERNEL_DS);
2798
    cpu_x86_load_seg(env, R_GS, KERNEL_DS);
2799
    
2800
    env->eip = KERNEL_LOAD_ADDR;
2801
    env->regs[R_ESI] = KERNEL_PARAMS_ADDR;
2802
    env->eflags = 0x2;
2803

    
2804
    itv.it_interval.tv_sec = 0;
2805
    itv.it_interval.tv_usec = 1000;
2806
    itv.it_value.tv_sec = 0;
2807
    itv.it_value.tv_usec = 10 * 1000;
2808
    setitimer(ITIMER_REAL, &itv, NULL);
2809
    /* we probe the tick duration of the kernel to inform the user if
2810
       the emulated kernel requested a too high timer frequency */
2811
    getitimer(ITIMER_REAL, &itv);
2812
    pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) / 
2813
        1000000;
2814
    
2815
    if (use_gdbstub) {
2816
        cpu_gdbstub(NULL, main_loop, gdbstub_port);
2817
    } else {
2818
        main_loop(NULL);
2819
    }
2820
    return 0;
2821
}