Statistics
| Branch: | Revision:

root / vl.c @ d0309311

History | View | Annotate | Download (102.7 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 <ctype.h>
29
#include <getopt.h>
30
#include <inttypes.h>
31
#include <unistd.h>
32
#include <sys/mman.h>
33
#include <fcntl.h>
34
#include <signal.h>
35
#include <time.h>
36
#include <sys/time.h>
37
#include <malloc.h>
38
#include <termios.h>
39
#include <sys/poll.h>
40
#include <errno.h>
41
#include <sys/wait.h>
42

    
43
#include <sys/ioctl.h>
44
#include <sys/socket.h>
45
#include <linux/if.h>
46
#include <linux/if_tun.h>
47

    
48
#include "cpu.h"
49
#include "disas.h"
50
#include "thunk.h"
51

    
52
#include "vl.h"
53

    
54
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
55
#define BIOS_FILENAME "bios.bin"
56
#define VGABIOS_FILENAME "vgabios.bin"
57

    
58
//#define DEBUG_UNUSED_IOPORT
59

    
60
//#define DEBUG_IRQ_LATENCY
61

    
62
/* output Bochs bios info messages */
63
//#define DEBUG_BIOS
64

    
65
//#define DEBUG_CMOS
66

    
67
/* debug PIC */
68
//#define DEBUG_PIC
69

    
70
/* debug NE2000 card */
71
//#define DEBUG_NE2000
72

    
73
/* debug PC keyboard */
74
//#define DEBUG_KBD
75

    
76
/* debug PC keyboard : only mouse */
77
//#define DEBUG_MOUSE
78

    
79
//#define DEBUG_SERIAL
80

    
81
#define PHYS_RAM_BASE     0xac000000
82
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
83

    
84
#if defined (TARGET_I386)
85
#define KERNEL_LOAD_ADDR   0x00100000
86
#elif defined (TARGET_PPC)
87
//#define USE_OPEN_FIRMWARE
88
#if defined (USE_OPEN_FIRMWARE)
89
#define KERNEL_LOAD_ADDR    0x01000000
90
#define KERNEL_STACK_ADDR   0x01200000
91
#else
92
#define KERNEL_LOAD_ADDR    0x00000000
93
#define KERNEL_STACK_ADDR   0x00400000
94
#endif
95
#endif
96
#define INITRD_LOAD_ADDR   0x00400000
97
#define KERNEL_PARAMS_ADDR 0x00090000
98

    
99
#define GUI_REFRESH_INTERVAL 30 
100

    
101
/* from plex86 (BSD license) */
102
struct  __attribute__ ((packed)) linux_params {
103
  // For 0x00..0x3f, see 'struct screen_info' in linux/include/linux/tty.h.
104
  // I just padded out the VESA parts, rather than define them.
105

    
106
  /* 0x000 */ uint8_t   orig_x;
107
  /* 0x001 */ uint8_t   orig_y;
108
  /* 0x002 */ uint16_t  ext_mem_k;
109
  /* 0x004 */ uint16_t  orig_video_page;
110
  /* 0x006 */ uint8_t   orig_video_mode;
111
  /* 0x007 */ uint8_t   orig_video_cols;
112
  /* 0x008 */ uint16_t  unused1;
113
  /* 0x00a */ uint16_t  orig_video_ega_bx;
114
  /* 0x00c */ uint16_t  unused2;
115
  /* 0x00e */ uint8_t   orig_video_lines;
116
  /* 0x00f */ uint8_t   orig_video_isVGA;
117
  /* 0x010 */ uint16_t  orig_video_points;
118
  /* 0x012 */ uint8_t   pad0[0x20 - 0x12]; // VESA info.
119
  /* 0x020 */ uint16_t  cl_magic;  // Commandline magic number (0xA33F)
120
  /* 0x022 */ uint16_t  cl_offset; // Commandline offset.  Address of commandline
121
                                 // is calculated as 0x90000 + cl_offset, bu
122
                                 // only if cl_magic == 0xA33F.
123
  /* 0x024 */ uint8_t   pad1[0x40 - 0x24]; // VESA info.
124

    
125
  /* 0x040 */ uint8_t   apm_bios_info[20]; // struct apm_bios_info
126
  /* 0x054 */ uint8_t   pad2[0x80 - 0x54];
127

    
128
  // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.
129
  // Might be truncated?
130
  /* 0x080 */ uint8_t   hd0_info[16]; // hd0-disk-parameter from intvector 0x41
131
  /* 0x090 */ uint8_t   hd1_info[16]; // hd1-disk-parameter from intvector 0x46
132

    
133
  // System description table truncated to 16 bytes
134
  // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.
135
  /* 0x0a0 */ uint16_t  sys_description_len;
136
  /* 0x0a2 */ uint8_t   sys_description_table[14];
137
                        // [0] machine id
138
                        // [1] machine submodel id
139
                        // [2] BIOS revision
140
                        // [3] bit1: MCA bus
141

    
142
  /* 0x0b0 */ uint8_t   pad3[0x1e0 - 0xb0];
143
  /* 0x1e0 */ uint32_t  alt_mem_k;
144
  /* 0x1e4 */ uint8_t   pad4[4];
145
  /* 0x1e8 */ uint8_t   e820map_entries;
146
  /* 0x1e9 */ uint8_t   eddbuf_entries; // EDD_NR
147
  /* 0x1ea */ uint8_t   pad5[0x1f1 - 0x1ea];
148
  /* 0x1f1 */ uint8_t   setup_sects; // size of setup.S, number of sectors
149
  /* 0x1f2 */ uint16_t  mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)
150
  /* 0x1f4 */ uint16_t  sys_size; // size of compressed kernel-part in the
151
                                // (b)zImage-file (in 16 byte units, rounded up)
152
  /* 0x1f6 */ uint16_t  swap_dev; // (unused AFAIK)
153
  /* 0x1f8 */ uint16_t  ramdisk_flags;
154
  /* 0x1fa */ uint16_t  vga_mode; // (old one)
155
  /* 0x1fc */ uint16_t  orig_root_dev; // (high=Major, low=minor)
156
  /* 0x1fe */ uint8_t   pad6[1];
157
  /* 0x1ff */ uint8_t   aux_device_info;
158
  /* 0x200 */ uint16_t  jump_setup; // Jump to start of setup code,
159
                                  // aka "reserved" field.
160
  /* 0x202 */ uint8_t   setup_signature[4]; // Signature for SETUP-header, ="HdrS"
161
  /* 0x206 */ uint16_t  header_format_version; // Version number of header format;
162
  /* 0x208 */ uint8_t   setup_S_temp0[8]; // Used by setup.S for communication with
163
                                        // boot loaders, look there.
164
  /* 0x210 */ uint8_t   loader_type;
165
                        // 0 for old one.
166
                        // else 0xTV:
167
                        //   T=0: LILO
168
                        //   T=1: Loadlin
169
                        //   T=2: bootsect-loader
170
                        //   T=3: SYSLINUX
171
                        //   T=4: ETHERBOOT
172
                        //   V=version
173
  /* 0x211 */ uint8_t   loadflags;
174
                        // bit0 = 1: kernel is loaded high (bzImage)
175
                        // bit7 = 1: Heap and pointer (see below) set by boot
176
                        //   loader.
177
  /* 0x212 */ uint16_t  setup_S_temp1;
178
  /* 0x214 */ uint32_t  kernel_start;
179
  /* 0x218 */ uint32_t  initrd_start;
180
  /* 0x21c */ uint32_t  initrd_size;
181
  /* 0x220 */ uint8_t   setup_S_temp2[4];
182
  /* 0x224 */ uint16_t  setup_S_heap_end_pointer;
183
  /* 0x226 */ uint8_t   pad7[0x2d0 - 0x226];
184

    
185
  /* 0x2d0 : Int 15, ax=e820 memory map. */
186
  // (linux/include/asm-i386/e820.h, 'struct e820entry')
187
#define E820MAX  32
188
#define E820_RAM  1
189
#define E820_RESERVED 2
190
#define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */
191
#define E820_NVS  4
192
  struct {
193
    uint64_t addr;
194
    uint64_t size;
195
    uint32_t type;
196
    } e820map[E820MAX];
197

    
198
  /* 0x550 */ uint8_t   pad8[0x600 - 0x550];
199

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

    
205
  /* 0x7d4 */ uint8_t   pad9[0x800 - 0x7d4];
206
  /* 0x800 */ uint8_t   commandline[0x800];
207

    
208
  /* 0x1000 */
209
  uint64_t gdt_table[256];
210
  uint64_t idt_table[48];
211
};
212

    
213
#define KERNEL_CS     0x10
214
#define KERNEL_DS     0x18
215

    
216
/* XXX: use a two level table to limit memory usage */
217
#define MAX_IOPORTS 65536
218

    
219
static const char *bios_dir = CONFIG_QEMU_SHAREDIR;
220
char phys_ram_file[1024];
221
CPUState *global_env;
222
CPUState *cpu_single_env;
223
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
224
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
225
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
226
int vga_ram_size;
227
static DisplayState display_state;
228
int nographic;
229
int term_inited;
230
int64_t ticks_per_sec;
231
int boot_device = 'c';
232

    
233
/***********************************************************/
234
/* x86 io ports */
235

    
236
uint32_t default_ioport_readb(CPUState *env, uint32_t address)
237
{
238
#ifdef DEBUG_UNUSED_IOPORT
239
    fprintf(stderr, "inb: port=0x%04x\n", address);
240
#endif
241
    return 0xff;
242
}
243

    
244
void default_ioport_writeb(CPUState *env, uint32_t address, uint32_t data)
245
{
246
#ifdef DEBUG_UNUSED_IOPORT
247
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
248
#endif
249
}
250

    
251
/* default is to make two byte accesses */
252
uint32_t default_ioport_readw(CPUState *env, uint32_t address)
253
{
254
    uint32_t data;
255
    data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](env, address);
256
    data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1) << 8;
257
    return data;
258
}
259

    
260
void default_ioport_writew(CPUState *env, uint32_t address, uint32_t data)
261
{
262
    ioport_write_table[0][address & (MAX_IOPORTS - 1)](env, address, data & 0xff);
263
    ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1, (data >> 8) & 0xff);
264
}
265

    
266
uint32_t default_ioport_readl(CPUState *env, uint32_t address)
267
{
268
#ifdef DEBUG_UNUSED_IOPORT
269
    fprintf(stderr, "inl: port=0x%04x\n", address);
270
#endif
271
    return 0xffffffff;
272
}
273

    
274
void default_ioport_writel(CPUState *env, uint32_t address, uint32_t data)
275
{
276
#ifdef DEBUG_UNUSED_IOPORT
277
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
278
#endif
279
}
280

    
281
void init_ioports(void)
282
{
283
    int i;
284

    
285
    for(i = 0; i < MAX_IOPORTS; i++) {
286
        ioport_read_table[0][i] = default_ioport_readb;
287
        ioport_write_table[0][i] = default_ioport_writeb;
288
        ioport_read_table[1][i] = default_ioport_readw;
289
        ioport_write_table[1][i] = default_ioport_writew;
290
        ioport_read_table[2][i] = default_ioport_readl;
291
        ioport_write_table[2][i] = default_ioport_writel;
292
    }
293
}
294

    
295
/* size is the word size in byte */
296
int register_ioport_read(int start, int length, IOPortReadFunc *func, int size)
297
{
298
    int i, bsize;
299

    
300
    if (size == 1)
301
        bsize = 0;
302
    else if (size == 2)
303
        bsize = 1;
304
    else if (size == 4)
305
        bsize = 2;
306
    else
307
        return -1;
308
    for(i = start; i < start + length; i += size)
309
        ioport_read_table[bsize][i] = func;
310
    return 0;
311
}
312

    
313
/* size is the word size in byte */
314
int register_ioport_write(int start, int length, IOPortWriteFunc *func, int size)
315
{
316
    int i, bsize;
317

    
318
    if (size == 1)
319
        bsize = 0;
320
    else if (size == 2)
321
        bsize = 1;
322
    else if (size == 4)
323
        bsize = 2;
324
    else
325
        return -1;
326
    for(i = start; i < start + length; i += size)
327
        ioport_write_table[bsize][i] = func;
328
    return 0;
329
}
330

    
331
void pstrcpy(char *buf, int buf_size, const char *str)
332
{
333
    int c;
334
    char *q = buf;
335

    
336
    if (buf_size <= 0)
337
        return;
338

    
339
    for(;;) {
340
        c = *str++;
341
        if (c == 0 || q >= buf + buf_size - 1)
342
            break;
343
        *q++ = c;
344
    }
345
    *q = '\0';
346
}
347

    
348
/* strcat and truncate. */
349
char *pstrcat(char *buf, int buf_size, const char *s)
350
{
351
    int len;
352
    len = strlen(buf);
353
    if (len < buf_size) 
354
        pstrcpy(buf + len, buf_size - len, s);
355
    return buf;
356
}
357

    
358
int load_kernel(const char *filename, uint8_t *addr)
359
{
360
    int fd, size;
361
#if defined (TARGET_I386)
362
    int setup_sects;
363
    uint8_t bootsect[512];
364
#endif
365

    
366
    printf("Load kernel at %p (0x%08x)\n", addr,
367
           (uint32_t)addr - (uint32_t)phys_ram_base);
368
    fd = open(filename, O_RDONLY);
369
    if (fd < 0)
370
        return -1;
371
#if defined (TARGET_I386)
372
    if (read(fd, bootsect, 512) != 512)
373
        goto fail;
374
    setup_sects = bootsect[0x1F1];
375
    if (!setup_sects)
376
        setup_sects = 4;
377
    /* skip 16 bit setup code */
378
    lseek(fd, (setup_sects + 1) * 512, SEEK_SET);
379
#endif
380
    size = read(fd, addr, 16 * 1024 * 1024);
381
    if (size < 0)
382
        goto fail;
383
    close(fd);
384
    return size;
385
 fail:
386
    close(fd);
387
    return -1;
388
}
389

    
390
/* return the size or -1 if error */
391
int load_image(const char *filename, uint8_t *addr)
392
{
393
    int fd, size;
394
    fd = open(filename, O_RDONLY);
395
    if (fd < 0)
396
        return -1;
397
    size = lseek(fd, 0, SEEK_END);
398
    lseek(fd, 0, SEEK_SET);
399
    if (read(fd, addr, size) != size) {
400
        close(fd);
401
        return -1;
402
    }
403
    close(fd);
404
    return size;
405
}
406

    
407
void cpu_outb(CPUState *env, int addr, int val)
408
{
409
    ioport_write_table[0][addr & (MAX_IOPORTS - 1)](env, addr, val);
410
}
411

    
412
void cpu_outw(CPUState *env, int addr, int val)
413
{
414
    ioport_write_table[1][addr & (MAX_IOPORTS - 1)](env, addr, val);
415
}
416

    
417
void cpu_outl(CPUState *env, int addr, int val)
418
{
419
    ioport_write_table[2][addr & (MAX_IOPORTS - 1)](env, addr, val);
420
}
421

    
422
int cpu_inb(CPUState *env, int addr)
423
{
424
    return ioport_read_table[0][addr & (MAX_IOPORTS - 1)](env, addr);
425
}
426

    
427
int cpu_inw(CPUState *env, int addr)
428
{
429
    return ioport_read_table[1][addr & (MAX_IOPORTS - 1)](env, addr);
430
}
431

    
432
int cpu_inl(CPUState *env, int addr)
433
{
434
    return ioport_read_table[2][addr & (MAX_IOPORTS - 1)](env, addr);
435
}
436

    
437
/***********************************************************/
438
void ioport80_write(CPUState *env, uint32_t addr, uint32_t data)
439
{
440
}
441

    
442
void hw_error(const char *fmt, ...)
443
{
444
    va_list ap;
445

    
446
    va_start(ap, fmt);
447
    fprintf(stderr, "qemu: hardware error: ");
448
    vfprintf(stderr, fmt, ap);
449
    fprintf(stderr, "\n");
450
#ifdef TARGET_I386
451
    cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
452
#else
453
    cpu_dump_state(global_env, stderr, 0);
454
#endif
455
    va_end(ap);
456
    abort();
457
}
458

    
459
/***********************************************************/
460
/* cmos emulation */
461

    
462
#if defined (TARGET_I386)
463
#define RTC_SECONDS             0
464
#define RTC_SECONDS_ALARM       1
465
#define RTC_MINUTES             2
466
#define RTC_MINUTES_ALARM       3
467
#define RTC_HOURS               4
468
#define RTC_HOURS_ALARM         5
469
#define RTC_ALARM_DONT_CARE    0xC0
470

    
471
#define RTC_DAY_OF_WEEK         6
472
#define RTC_DAY_OF_MONTH        7
473
#define RTC_MONTH               8
474
#define RTC_YEAR                9
475

    
476
#define RTC_REG_A               10
477
#define RTC_REG_B               11
478
#define RTC_REG_C               12
479
#define RTC_REG_D               13
480

    
481
/* PC cmos mappings */
482
#define REG_EQUIPMENT_BYTE          0x14
483
#define REG_IBM_CENTURY_BYTE        0x32
484

    
485
uint8_t cmos_data[128];
486
uint8_t cmos_index;
487

    
488
void cmos_ioport_write(CPUState *env, uint32_t addr, uint32_t data)
489
{
490
    if (addr == 0x70) {
491
        cmos_index = data & 0x7f;
492
    } else {
493
#ifdef DEBUG_CMOS
494
        printf("cmos: write index=0x%02x val=0x%02x\n",
495
               cmos_index, data);
496
#endif        
497
        switch(addr) {
498
        case RTC_SECONDS_ALARM:
499
        case RTC_MINUTES_ALARM:
500
        case RTC_HOURS_ALARM:
501
            /* XXX: not supported */
502
            cmos_data[cmos_index] = data;
503
            break;
504
        case RTC_SECONDS:
505
        case RTC_MINUTES:
506
        case RTC_HOURS:
507
        case RTC_DAY_OF_WEEK:
508
        case RTC_DAY_OF_MONTH:
509
        case RTC_MONTH:
510
        case RTC_YEAR:
511
            cmos_data[cmos_index] = data;
512
            break;
513
        case RTC_REG_A:
514
        case RTC_REG_B:
515
            cmos_data[cmos_index] = data;
516
            break;
517
        case RTC_REG_C:
518
        case RTC_REG_D:
519
            /* cannot write to them */
520
            break;
521
        default:
522
            cmos_data[cmos_index] = data;
523
            break;
524
        }
525
    }
526
}
527

    
528
static inline int to_bcd(int a)
529
{
530
    return ((a / 10) << 4) | (a % 10);
531
}
532

    
533
static void cmos_update_time(void)
534
{
535
    struct tm *tm;
536
    time_t ti;
537

    
538
    ti = time(NULL);
539
    tm = gmtime(&ti);
540
    cmos_data[RTC_SECONDS] = to_bcd(tm->tm_sec);
541
    cmos_data[RTC_MINUTES] = to_bcd(tm->tm_min);
542
    cmos_data[RTC_HOURS] = to_bcd(tm->tm_hour);
543
    cmos_data[RTC_DAY_OF_WEEK] = to_bcd(tm->tm_wday);
544
    cmos_data[RTC_DAY_OF_MONTH] = to_bcd(tm->tm_mday);
545
    cmos_data[RTC_MONTH] = to_bcd(tm->tm_mon + 1);
546
    cmos_data[RTC_YEAR] = to_bcd(tm->tm_year % 100);
547
    cmos_data[REG_IBM_CENTURY_BYTE] = to_bcd((tm->tm_year / 100) + 19);
548
}
549

    
550
uint32_t cmos_ioport_read(CPUState *env, uint32_t addr)
551
{
552
    int ret;
553

    
554
    if (addr == 0x70) {
555
        return 0xff;
556
    } else {
557
        switch(cmos_index) {
558
        case RTC_SECONDS:
559
        case RTC_MINUTES:
560
        case RTC_HOURS:
561
        case RTC_DAY_OF_WEEK:
562
        case RTC_DAY_OF_MONTH:
563
        case RTC_MONTH:
564
        case RTC_YEAR:
565
        case REG_IBM_CENTURY_BYTE:
566
            cmos_update_time();
567
            ret = cmos_data[cmos_index];
568
            break;
569
        case RTC_REG_A:
570
            ret = cmos_data[cmos_index];
571
            /* toggle update-in-progress bit for Linux (same hack as
572
               plex86) */
573
            cmos_data[RTC_REG_A] ^= 0x80; 
574
            break;
575
        case RTC_REG_C:
576
            ret = cmos_data[cmos_index];
577
            pic_set_irq(8, 0);
578
            cmos_data[RTC_REG_C] = 0x00; 
579
            break;
580
        default:
581
            ret = cmos_data[cmos_index];
582
            break;
583
        }
584
#ifdef DEBUG_CMOS
585
        printf("cmos: read index=0x%02x val=0x%02x\n",
586
               cmos_index, ret);
587
#endif
588
        return ret;
589
    }
590
}
591

    
592
void cmos_init(void)
593
{
594
    int val;
595

    
596
    cmos_update_time();
597

    
598
    cmos_data[RTC_REG_A] = 0x26;
599
    cmos_data[RTC_REG_B] = 0x02;
600
    cmos_data[RTC_REG_C] = 0x00;
601
    cmos_data[RTC_REG_D] = 0x80;
602

    
603
    /* various important CMOS locations needed by PC/Bochs bios */
604

    
605
    cmos_data[REG_EQUIPMENT_BYTE] = 0x02; /* FPU is there */
606
    cmos_data[REG_EQUIPMENT_BYTE] |= 0x04; /* PS/2 mouse installed */
607

    
608
    /* memory size */
609
    val = (phys_ram_size / 1024) - 1024;
610
    if (val > 65535)
611
        val = 65535;
612
    cmos_data[0x17] = val;
613
    cmos_data[0x18] = val >> 8;
614
    cmos_data[0x30] = val;
615
    cmos_data[0x31] = val >> 8;
616

    
617
    val = (phys_ram_size / 65536) - ((16 * 1024 * 1024) / 65536);
618
    if (val > 65535)
619
        val = 65535;
620
    cmos_data[0x34] = val;
621
    cmos_data[0x35] = val >> 8;
622
    
623
    switch(boot_device) {
624
    case 'a':
625
    case 'b':
626
        cmos_data[0x3d] = 0x01; /* floppy boot */
627
        break;
628
    default:
629
    case 'c':
630
        cmos_data[0x3d] = 0x02; /* hard drive boot */
631
        break;
632
    case 'd':
633
        cmos_data[0x3d] = 0x03; /* CD-ROM boot */
634
        break;
635
    }
636

    
637
    register_ioport_write(0x70, 2, cmos_ioport_write, 1);
638
    register_ioport_read(0x70, 2, cmos_ioport_read, 1);
639
}
640

    
641
void cmos_register_fd (uint8_t fd0, uint8_t fd1)
642
{
643
    int nb = 0;
644

    
645
    cmos_data[0x10] = 0;
646
    switch (fd0) {
647
    case 0:
648
        /* 1.44 Mb 3"5 drive */
649
        cmos_data[0x10] |= 0x40;
650
        break;
651
    case 1:
652
        /* 2.88 Mb 3"5 drive */
653
        cmos_data[0x10] |= 0x60;
654
        break;
655
    case 2:
656
        /* 1.2 Mb 5"5 drive */
657
        cmos_data[0x10] |= 0x20;
658
        break;
659
    }
660
    switch (fd1) {
661
    case 0:
662
        /* 1.44 Mb 3"5 drive */
663
        cmos_data[0x10] |= 0x04;
664
        break;
665
    case 1:
666
        /* 2.88 Mb 3"5 drive */
667
        cmos_data[0x10] |= 0x06;
668
        break;
669
    case 2:
670
        /* 1.2 Mb 5"5 drive */
671
        cmos_data[0x10] |= 0x02;
672
        break;
673
    }
674
    if (fd0 < 3)
675
        nb++;
676
    if (fd1 < 3)
677
        nb++;
678
    switch (nb) {
679
    case 0:
680
        break;
681
    case 1:
682
        cmos_data[REG_EQUIPMENT_BYTE] |= 0x01; /* 1 drive, ready for boot */
683
        break;
684
    case 2:
685
        cmos_data[REG_EQUIPMENT_BYTE] |= 0x41; /* 2 drives, ready for boot */
686
        break;
687
    }
688
}
689
#endif /* TARGET_I386 */
690

    
691
/***********************************************************/
692
/* 8259 pic emulation */
693

    
694
typedef struct PicState {
695
    uint8_t last_irr; /* edge detection */
696
    uint8_t irr; /* interrupt request register */
697
    uint8_t imr; /* interrupt mask register */
698
    uint8_t isr; /* interrupt service register */
699
    uint8_t priority_add; /* highest irq priority */
700
    uint8_t irq_base;
701
    uint8_t read_reg_select;
702
    uint8_t poll;
703
    uint8_t special_mask;
704
    uint8_t init_state;
705
    uint8_t auto_eoi;
706
    uint8_t rotate_on_auto_eoi;
707
    uint8_t special_fully_nested_mode;
708
    uint8_t init4; /* true if 4 byte init */
709
} PicState;
710

    
711
/* 0 is master pic, 1 is slave pic */
712
PicState pics[2];
713
int pic_irq_requested;
714

    
715
/* set irq level. If an edge is detected, then the IRR is set to 1 */
716
static inline void pic_set_irq1(PicState *s, int irq, int level)
717
{
718
    int mask;
719
    mask = 1 << irq;
720
    if (level) {
721
        if ((s->last_irr & mask) == 0)
722
            s->irr |= mask;
723
        s->last_irr |= mask;
724
    } else {
725
        s->last_irr &= ~mask;
726
    }
727
}
728

    
729
/* return the highest priority found in mask (highest = smallest
730
   number). Return 8 if no irq */
731
static inline int get_priority(PicState *s, int mask)
732
{
733
    int priority;
734
    if (mask == 0)
735
        return 8;
736
    priority = 0;
737
    while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)
738
        priority++;
739
    return priority;
740
}
741

    
742
/* return the pic wanted interrupt. return -1 if none */
743
static int pic_get_irq(PicState *s)
744
{
745
    int mask, cur_priority, priority;
746

    
747
    mask = s->irr & ~s->imr;
748
    priority = get_priority(s, mask);
749
    if (priority == 8)
750
        return -1;
751
    /* compute current priority. If special fully nested mode on the
752
       master, the IRQ coming from the slave is not taken into account
753
       for the priority computation. */
754
    mask = s->isr;
755
    if (s->special_fully_nested_mode && s == &pics[0])
756
        mask &= ~(1 << 2);
757
    cur_priority = get_priority(s, mask);
758
    if (priority < cur_priority) {
759
        /* higher priority found: an irq should be generated */
760
        return (priority + s->priority_add) & 7;
761
    } else {
762
        return -1;
763
    }
764
}
765

    
766
/* raise irq to CPU if necessary. must be called every time the active
767
   irq may change */
768
void pic_update_irq(void)
769
{
770
    int irq2, irq;
771

    
772
    /* first look at slave pic */
773
    irq2 = pic_get_irq(&pics[1]);
774
    if (irq2 >= 0) {
775
        /* if irq request by slave pic, signal master PIC */
776
        pic_set_irq1(&pics[0], 2, 1);
777
        pic_set_irq1(&pics[0], 2, 0);
778
    }
779
    /* look at requested irq */
780
    irq = pic_get_irq(&pics[0]);
781
    if (irq >= 0) {
782
        if (irq == 2) {
783
            /* from slave pic */
784
            pic_irq_requested = 8 + irq2;
785
        } else {
786
            /* from master pic */
787
            pic_irq_requested = irq;
788
        }
789
#if defined(DEBUG_PIC)
790
        {
791
            int i;
792
            for(i = 0; i < 2; i++) {
793
                printf("pic%d: imr=%x irr=%x padd=%d\n", 
794
                       i, pics[i].imr, pics[i].irr, pics[i].priority_add);
795
                
796
            }
797
        }
798
        printf("pic: cpu_interrupt req=%d\n", pic_irq_requested);
799
#endif
800
        cpu_interrupt(global_env, CPU_INTERRUPT_HARD);
801
    }
802
}
803

    
804
#ifdef DEBUG_IRQ_LATENCY
805
int64_t irq_time[16];
806
int64_t cpu_get_ticks(void);
807
#endif
808
#if defined(DEBUG_PIC)
809
int irq_level[16];
810
#endif
811

    
812
void pic_set_irq(int irq, int level)
813
{
814
#if defined(DEBUG_PIC)
815
    if (level != irq_level[irq]) {
816
        printf("pic_set_irq: irq=%d level=%d\n", irq, level);
817
        irq_level[irq] = level;
818
    }
819
#endif
820
#ifdef DEBUG_IRQ_LATENCY
821
    if (level) {
822
        irq_time[irq] = cpu_get_ticks();
823
    }
824
#endif
825
    pic_set_irq1(&pics[irq >> 3], irq & 7, level);
826
    pic_update_irq();
827
}
828

    
829
/* acknowledge interrupt 'irq' */
830
static inline void pic_intack(PicState *s, int irq)
831
{
832
    if (s->auto_eoi) {
833
        if (s->rotate_on_auto_eoi)
834
            s->priority_add = (irq + 1) & 7;
835
    } else {
836
        s->isr |= (1 << irq);
837
    }
838
    s->irr &= ~(1 << irq);
839
}
840

    
841
int cpu_x86_get_pic_interrupt(CPUState *env)
842
{
843
    int irq, irq2, intno;
844

    
845
    /* signal the pic that the irq was acked by the CPU */
846
    irq = pic_irq_requested;
847
#ifdef DEBUG_IRQ_LATENCY
848
    printf("IRQ%d latency=%0.3fus\n", 
849
           irq, 
850
           (double)(cpu_get_ticks() - irq_time[irq]) * 1000000.0 / ticks_per_sec);
851
#endif
852
#if defined(DEBUG_PIC)
853
    printf("pic_interrupt: irq=%d\n", irq);
854
#endif
855

    
856
    if (irq >= 8) {
857
        irq2 = irq & 7;
858
        pic_intack(&pics[1], irq2);
859
        irq = 2;
860
        intno = pics[1].irq_base + irq2;
861
    } else {
862
        intno = pics[0].irq_base + irq;
863
    }
864
    pic_intack(&pics[0], irq);
865
    return intno;
866
}
867

    
868
void pic_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
869
{
870
    PicState *s;
871
    int priority, cmd, irq;
872

    
873
#ifdef DEBUG_PIC
874
    printf("pic_write: addr=0x%02x val=0x%02x\n", addr, val);
875
#endif
876
    s = &pics[addr >> 7];
877
    addr &= 1;
878
    if (addr == 0) {
879
        if (val & 0x10) {
880
            /* init */
881
            memset(s, 0, sizeof(PicState));
882
            s->init_state = 1;
883
            s->init4 = val & 1;
884
            if (val & 0x02)
885
                hw_error("single mode not supported");
886
            if (val & 0x08)
887
                hw_error("level sensitive irq not supported");
888
        } else if (val & 0x08) {
889
            if (val & 0x04)
890
                s->poll = 1;
891
            if (val & 0x02)
892
                s->read_reg_select = val & 1;
893
            if (val & 0x40)
894
                s->special_mask = (val >> 5) & 1;
895
        } else {
896
            cmd = val >> 5;
897
            switch(cmd) {
898
            case 0:
899
            case 4:
900
                s->rotate_on_auto_eoi = cmd >> 2;
901
                break;
902
            case 1: /* end of interrupt */
903
            case 5:
904
                priority = get_priority(s, s->isr);
905
                if (priority != 8) {
906
                    irq = (priority + s->priority_add) & 7;
907
                    s->isr &= ~(1 << irq);
908
                    if (cmd == 5)
909
                        s->priority_add = (irq + 1) & 7;
910
                    pic_update_irq();
911
                }
912
                break;
913
            case 3:
914
                irq = val & 7;
915
                s->isr &= ~(1 << irq);
916
                pic_update_irq();
917
                break;
918
            case 6:
919
                s->priority_add = (val + 1) & 7;
920
                pic_update_irq();
921
                break;
922
            case 7:
923
                irq = val & 7;
924
                s->isr &= ~(1 << irq);
925
                s->priority_add = (irq + 1) & 7;
926
                pic_update_irq();
927
                break;
928
            default:
929
                /* no operation */
930
                break;
931
            }
932
        }
933
    } else {
934
        switch(s->init_state) {
935
        case 0:
936
            /* normal mode */
937
            s->imr = val;
938
            pic_update_irq();
939
            break;
940
        case 1:
941
            s->irq_base = val & 0xf8;
942
            s->init_state = 2;
943
            break;
944
        case 2:
945
            if (s->init4) {
946
                s->init_state = 3;
947
            } else {
948
                s->init_state = 0;
949
            }
950
            break;
951
        case 3:
952
            s->special_fully_nested_mode = (val >> 4) & 1;
953
            s->auto_eoi = (val >> 1) & 1;
954
            s->init_state = 0;
955
            break;
956
        }
957
    }
958
}
959

    
960
static uint32_t pic_poll_read (PicState *s, uint32_t addr1)
961
{
962
    int ret;
963

    
964
    ret = pic_get_irq(s);
965
    if (ret >= 0) {
966
        if (addr1 >> 7) {
967
            pics[0].isr &= ~(1 << 2);
968
            pics[0].irr &= ~(1 << 2);
969
        }
970
        s->irr &= ~(1 << ret);
971
        s->isr &= ~(1 << ret);
972
        if (addr1 >> 7 || ret != 2)
973
            pic_update_irq();
974
    } else {
975
        ret = 0x07;
976
        pic_update_irq();
977
    }
978

    
979
    return ret;
980
}
981

    
982
uint32_t pic_ioport_read(CPUState *env, uint32_t addr1)
983
{
984
    PicState *s;
985
    unsigned int addr;
986
    int ret;
987

    
988
    addr = addr1;
989
    s = &pics[addr >> 7];
990
    addr &= 1;
991
    if (s->poll) {
992
        ret = pic_poll_read(s, addr1);
993
        s->poll = 0;
994
    } else {
995
        if (addr == 0) {
996
            if (s->read_reg_select)
997
                ret = s->isr;
998
            else
999
                ret = s->irr;
1000
        } else {
1001
            ret = s->imr;
1002
        }
1003
    }
1004
#ifdef DEBUG_PIC
1005
    printf("pic_read: addr=0x%02x val=0x%02x\n", addr1, ret);
1006
#endif
1007
    return ret;
1008
}
1009

    
1010
/* memory mapped interrupt status */
1011
uint32_t pic_intack_read(CPUState *env)
1012
{
1013
    int ret;
1014

    
1015
    ret = pic_poll_read(&pics[0], 0x00);
1016
    if (ret == 2)
1017
        ret = pic_poll_read(&pics[1], 0x80) + 8;
1018
    /* Prepare for ISR read */
1019
    pics[0].read_reg_select = 1;
1020
    
1021
    return ret;
1022
}
1023

    
1024
void pic_init(void)
1025
{
1026
#if defined (TARGET_I386) || defined (TARGET_PPC)
1027
    register_ioport_write(0x20, 2, pic_ioport_write, 1);
1028
    register_ioport_read(0x20, 2, pic_ioport_read, 1);
1029
    register_ioport_write(0xa0, 2, pic_ioport_write, 1);
1030
    register_ioport_read(0xa0, 2, pic_ioport_read, 1);
1031
#endif
1032
}
1033

    
1034
/***********************************************************/
1035
/* 8253 PIT emulation */
1036

    
1037
#define PIT_FREQ 1193182
1038

    
1039
#define RW_STATE_LSB 0
1040
#define RW_STATE_MSB 1
1041
#define RW_STATE_WORD0 2
1042
#define RW_STATE_WORD1 3
1043
#define RW_STATE_LATCHED_WORD0 4
1044
#define RW_STATE_LATCHED_WORD1 5
1045

    
1046
typedef struct PITChannelState {
1047
    int count; /* can be 65536 */
1048
    uint16_t latched_count;
1049
    uint8_t rw_state;
1050
    uint8_t mode;
1051
    uint8_t bcd; /* not supported */
1052
    uint8_t gate; /* timer start */
1053
    int64_t count_load_time;
1054
    int64_t count_last_edge_check_time;
1055
} PITChannelState;
1056

    
1057
PITChannelState pit_channels[3];
1058
int speaker_data_on;
1059
int dummy_refresh_clock;
1060
int pit_min_timer_count = 0;
1061

    
1062

    
1063
#if defined(__powerpc__)
1064

    
1065
static inline uint32_t get_tbl(void) 
1066
{
1067
    uint32_t tbl;
1068
    asm volatile("mftb %0" : "=r" (tbl));
1069
    return tbl;
1070
}
1071

    
1072
static inline uint32_t get_tbu(void) 
1073
{
1074
        uint32_t tbl;
1075
        asm volatile("mftbu %0" : "=r" (tbl));
1076
        return tbl;
1077
}
1078

    
1079
int64_t cpu_get_real_ticks(void)
1080
{
1081
    uint32_t l, h, h1;
1082
    /* NOTE: we test if wrapping has occurred */
1083
    do {
1084
        h = get_tbu();
1085
        l = get_tbl();
1086
        h1 = get_tbu();
1087
    } while (h != h1);
1088
    return ((int64_t)h << 32) | l;
1089
}
1090

    
1091
#elif defined(__i386__)
1092

    
1093
int64_t cpu_get_real_ticks(void)
1094
{
1095
    int64_t val;
1096
    asm("rdtsc" : "=A" (val));
1097
    return val;
1098
}
1099

    
1100
#else
1101
#error unsupported CPU
1102
#endif
1103

    
1104
static int64_t cpu_ticks_offset;
1105
static int64_t cpu_ticks_last;
1106

    
1107
int64_t cpu_get_ticks(void)
1108
{
1109
    return cpu_get_real_ticks() + cpu_ticks_offset;
1110
}
1111

    
1112
/* enable cpu_get_ticks() */
1113
void cpu_enable_ticks(void)
1114
{
1115
    cpu_ticks_offset = cpu_ticks_last - cpu_get_real_ticks();
1116
}
1117

    
1118
/* disable cpu_get_ticks() : the clock is stopped. You must not call
1119
   cpu_get_ticks() after that.  */
1120
void cpu_disable_ticks(void)
1121
{
1122
    cpu_ticks_last = cpu_get_ticks();
1123
}
1124

    
1125
int64_t get_clock(void)
1126
{
1127
    struct timeval tv;
1128
    gettimeofday(&tv, NULL);
1129
    return tv.tv_sec * 1000000LL + tv.tv_usec;
1130
}
1131

    
1132
void cpu_calibrate_ticks(void)
1133
{
1134
    int64_t usec, ticks;
1135

    
1136
    usec = get_clock();
1137
    ticks = cpu_get_ticks();
1138
    usleep(50 * 1000);
1139
    usec = get_clock() - usec;
1140
    ticks = cpu_get_ticks() - ticks;
1141
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
1142
}
1143

    
1144
/* compute with 96 bit intermediate result: (a*b)/c */
1145
static uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
1146
{
1147
    union {
1148
        uint64_t ll;
1149
        struct {
1150
#ifdef WORDS_BIGENDIAN
1151
            uint32_t high, low;
1152
#else
1153
            uint32_t low, high;
1154
#endif            
1155
        } l;
1156
    } u, res;
1157
    uint64_t rl, rh;
1158

    
1159
    u.ll = a;
1160
    rl = (uint64_t)u.l.low * (uint64_t)b;
1161
    rh = (uint64_t)u.l.high * (uint64_t)b;
1162
    rh += (rl >> 32);
1163
    res.l.high = rh / c;
1164
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
1165
    return res.ll;
1166
}
1167

    
1168
static int pit_get_count(PITChannelState *s)
1169
{
1170
    uint64_t d;
1171
    int counter;
1172

    
1173
    d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
1174
    switch(s->mode) {
1175
    case 0:
1176
    case 1:
1177
    case 4:
1178
    case 5:
1179
        counter = (s->count - d) & 0xffff;
1180
        break;
1181
    case 3:
1182
        /* XXX: may be incorrect for odd counts */
1183
        counter = s->count - ((2 * d) % s->count);
1184
        break;
1185
    default:
1186
        counter = s->count - (d % s->count);
1187
        break;
1188
    }
1189
    return counter;
1190
}
1191

    
1192
/* get pit output bit */
1193
static int pit_get_out(PITChannelState *s)
1194
{
1195
    uint64_t d;
1196
    int out;
1197

    
1198
    d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
1199
    switch(s->mode) {
1200
    default:
1201
    case 0:
1202
        out = (d >= s->count);
1203
        break;
1204
    case 1:
1205
        out = (d < s->count);
1206
        break;
1207
    case 2:
1208
        if ((d % s->count) == 0 && d != 0)
1209
            out = 1;
1210
        else
1211
            out = 0;
1212
        break;
1213
    case 3:
1214
        out = (d % s->count) < ((s->count + 1) >> 1);
1215
        break;
1216
    case 4:
1217
    case 5:
1218
        out = (d == s->count);
1219
        break;
1220
    }
1221
    return out;
1222
}
1223

    
1224
/* get the number of 0 to 1 transitions we had since we call this
1225
   function */
1226
/* XXX: maybe better to use ticks precision to avoid getting edges
1227
   twice if checks are done at very small intervals */
1228
static int pit_get_out_edges(PITChannelState *s)
1229
{
1230
    uint64_t d1, d2;
1231
    int64_t ticks;
1232
    int ret, v;
1233

    
1234
    ticks = cpu_get_ticks();
1235
    d1 = muldiv64(s->count_last_edge_check_time - s->count_load_time, 
1236
                 PIT_FREQ, ticks_per_sec);
1237
    d2 = muldiv64(ticks - s->count_load_time, 
1238
                  PIT_FREQ, ticks_per_sec);
1239
    s->count_last_edge_check_time = ticks;
1240
    switch(s->mode) {
1241
    default:
1242
    case 0:
1243
        if (d1 < s->count && d2 >= s->count)
1244
            ret = 1;
1245
        else
1246
            ret = 0;
1247
        break;
1248
    case 1:
1249
        ret = 0;
1250
        break;
1251
    case 2:
1252
        d1 /= s->count;
1253
        d2 /= s->count;
1254
        ret = d2 - d1;
1255
        break;
1256
    case 3:
1257
        v = s->count - ((s->count + 1) >> 1);
1258
        d1 = (d1 + v) / s->count;
1259
        d2 = (d2 + v) / s->count;
1260
        ret = d2 - d1;
1261
        break;
1262
    case 4:
1263
    case 5:
1264
        if (d1 < s->count && d2 >= s->count)
1265
            ret = 1;
1266
        else
1267
            ret = 0;
1268
        break;
1269
    }
1270
    return ret;
1271
}
1272

    
1273
/* val must be 0 or 1 */
1274
static inline void pit_set_gate(PITChannelState *s, int val)
1275
{
1276
    switch(s->mode) {
1277
    default:
1278
    case 0:
1279
    case 4:
1280
        /* XXX: just disable/enable counting */
1281
        break;
1282
    case 1:
1283
    case 5:
1284
        if (s->gate < val) {
1285
            /* restart counting on rising edge */
1286
            s->count_load_time = cpu_get_ticks();
1287
            s->count_last_edge_check_time = s->count_load_time;
1288
        }
1289
        break;
1290
    case 2:
1291
    case 3:
1292
        if (s->gate < val) {
1293
            /* restart counting on rising edge */
1294
            s->count_load_time = cpu_get_ticks();
1295
            s->count_last_edge_check_time = s->count_load_time;
1296
        }
1297
        /* XXX: disable/enable counting */
1298
        break;
1299
    }
1300
    s->gate = val;
1301
}
1302

    
1303
static inline void pit_load_count(PITChannelState *s, int val)
1304
{
1305
    if (val == 0)
1306
        val = 0x10000;
1307
    s->count_load_time = cpu_get_ticks();
1308
    s->count_last_edge_check_time = s->count_load_time;
1309
    s->count = val;
1310
    if (s == &pit_channels[0] && val <= pit_min_timer_count) {
1311
        fprintf(stderr, 
1312
                "\nWARNING: qemu: on your system, accurate timer emulation is impossible if its frequency is more than %d Hz. If using a 2.5.xx Linux kernel, you must patch asm/param.h to change HZ from 1000 to 100.\n\n", 
1313
                PIT_FREQ / pit_min_timer_count);
1314
    }
1315
}
1316

    
1317
void pit_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
1318
{
1319
    int channel, access;
1320
    PITChannelState *s;
1321

    
1322
    addr &= 3;
1323
    if (addr == 3) {
1324
        channel = val >> 6;
1325
        if (channel == 3)
1326
            return;
1327
        s = &pit_channels[channel];
1328
        access = (val >> 4) & 3;
1329
        switch(access) {
1330
        case 0:
1331
            s->latched_count = pit_get_count(s);
1332
            s->rw_state = RW_STATE_LATCHED_WORD0;
1333
            break;
1334
        default:
1335
            s->mode = (val >> 1) & 7;
1336
            s->bcd = val & 1;
1337
            s->rw_state = access - 1 +  RW_STATE_LSB;
1338
            break;
1339
        }
1340
    } else {
1341
        s = &pit_channels[addr];
1342
        switch(s->rw_state) {
1343
        case RW_STATE_LSB:
1344
            pit_load_count(s, val);
1345
            break;
1346
        case RW_STATE_MSB:
1347
            pit_load_count(s, val << 8);
1348
            break;
1349
        case RW_STATE_WORD0:
1350
        case RW_STATE_WORD1:
1351
            if (s->rw_state & 1) {
1352
                pit_load_count(s, (s->latched_count & 0xff) | (val << 8));
1353
            } else {
1354
                s->latched_count = val;
1355
            }
1356
            s->rw_state ^= 1;
1357
            break;
1358
        }
1359
    }
1360
}
1361

    
1362
uint32_t pit_ioport_read(CPUState *env, uint32_t addr)
1363
{
1364
    int ret, count;
1365
    PITChannelState *s;
1366
    
1367
    addr &= 3;
1368
    s = &pit_channels[addr];
1369
    switch(s->rw_state) {
1370
    case RW_STATE_LSB:
1371
    case RW_STATE_MSB:
1372
    case RW_STATE_WORD0:
1373
    case RW_STATE_WORD1:
1374
        count = pit_get_count(s);
1375
        if (s->rw_state & 1)
1376
            ret = (count >> 8) & 0xff;
1377
        else
1378
            ret = count & 0xff;
1379
        if (s->rw_state & 2)
1380
            s->rw_state ^= 1;
1381
        break;
1382
    default:
1383
    case RW_STATE_LATCHED_WORD0:
1384
    case RW_STATE_LATCHED_WORD1:
1385
        if (s->rw_state & 1)
1386
            ret = s->latched_count >> 8;
1387
        else
1388
            ret = s->latched_count & 0xff;
1389
        s->rw_state ^= 1;
1390
        break;
1391
    }
1392
    return ret;
1393
}
1394

    
1395
#if defined (TARGET_I386)
1396
void speaker_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
1397
{
1398
    speaker_data_on = (val >> 1) & 1;
1399
    pit_set_gate(&pit_channels[2], val & 1);
1400
}
1401

    
1402
uint32_t speaker_ioport_read(CPUState *env, uint32_t addr)
1403
{
1404
    int out;
1405
    out = pit_get_out(&pit_channels[2]);
1406
    dummy_refresh_clock ^= 1;
1407
    return (speaker_data_on << 1) | pit_channels[2].gate | (out << 5) |
1408
      (dummy_refresh_clock << 4);
1409
}
1410
#endif
1411

    
1412
void pit_init(void)
1413
{
1414
    PITChannelState *s;
1415
    int i;
1416

    
1417
    cpu_calibrate_ticks();
1418

    
1419
    for(i = 0;i < 3; i++) {
1420
        s = &pit_channels[i];
1421
        s->mode = 3;
1422
        s->gate = (i != 2);
1423
        pit_load_count(s, 0);
1424
    }
1425

    
1426
    register_ioport_write(0x40, 4, pit_ioport_write, 1);
1427
    register_ioport_read(0x40, 3, pit_ioport_read, 1);
1428

    
1429
#if defined (TARGET_I386)
1430
    register_ioport_read(0x61, 1, speaker_ioport_read, 1);
1431
    register_ioport_write(0x61, 1, speaker_ioport_write, 1);
1432
#endif
1433
}
1434

    
1435
/***********************************************************/
1436
/* serial port emulation */
1437

    
1438
#define UART_IRQ        4
1439

    
1440
#define UART_LCR_DLAB        0x80        /* Divisor latch access bit */
1441

    
1442
#define UART_IER_MSI        0x08        /* Enable Modem status interrupt */
1443
#define UART_IER_RLSI        0x04        /* Enable receiver line status interrupt */
1444
#define UART_IER_THRI        0x02        /* Enable Transmitter holding register int. */
1445
#define UART_IER_RDI        0x01        /* Enable receiver data interrupt */
1446

    
1447
#define UART_IIR_NO_INT        0x01        /* No interrupts pending */
1448
#define UART_IIR_ID        0x06        /* Mask for the interrupt ID */
1449

    
1450
#define UART_IIR_MSI        0x00        /* Modem status interrupt */
1451
#define UART_IIR_THRI        0x02        /* Transmitter holding register empty */
1452
#define UART_IIR_RDI        0x04        /* Receiver data interrupt */
1453
#define UART_IIR_RLSI        0x06        /* Receiver line status interrupt */
1454

    
1455
/*
1456
 * These are the definitions for the Modem Control Register
1457
 */
1458
#define UART_MCR_LOOP        0x10        /* Enable loopback test mode */
1459
#define UART_MCR_OUT2        0x08        /* Out2 complement */
1460
#define UART_MCR_OUT1        0x04        /* Out1 complement */
1461
#define UART_MCR_RTS        0x02        /* RTS complement */
1462
#define UART_MCR_DTR        0x01        /* DTR complement */
1463

    
1464
/*
1465
 * These are the definitions for the Modem Status Register
1466
 */
1467
#define UART_MSR_DCD        0x80        /* Data Carrier Detect */
1468
#define UART_MSR_RI        0x40        /* Ring Indicator */
1469
#define UART_MSR_DSR        0x20        /* Data Set Ready */
1470
#define UART_MSR_CTS        0x10        /* Clear to Send */
1471
#define UART_MSR_DDCD        0x08        /* Delta DCD */
1472
#define UART_MSR_TERI        0x04        /* Trailing edge ring indicator */
1473
#define UART_MSR_DDSR        0x02        /* Delta DSR */
1474
#define UART_MSR_DCTS        0x01        /* Delta CTS */
1475
#define UART_MSR_ANY_DELTA 0x0F        /* Any of the delta bits! */
1476

    
1477
#define UART_LSR_TEMT        0x40        /* Transmitter empty */
1478
#define UART_LSR_THRE        0x20        /* Transmit-hold-register empty */
1479
#define UART_LSR_BI        0x10        /* Break interrupt indicator */
1480
#define UART_LSR_FE        0x08        /* Frame error indicator */
1481
#define UART_LSR_PE        0x04        /* Parity error indicator */
1482
#define UART_LSR_OE        0x02        /* Overrun error indicator */
1483
#define UART_LSR_DR        0x01        /* Receiver data ready */
1484

    
1485
typedef struct SerialState {
1486
    uint8_t divider;
1487
    uint8_t rbr; /* receive register */
1488
    uint8_t ier;
1489
    uint8_t iir; /* read only */
1490
    uint8_t lcr;
1491
    uint8_t mcr;
1492
    uint8_t lsr; /* read only */
1493
    uint8_t msr;
1494
    uint8_t scr;
1495
    /* NOTE: this hidden state is necessary for tx irq generation as
1496
       it can be reset while reading iir */
1497
    int thr_ipending;
1498
} SerialState;
1499

    
1500
SerialState serial_ports[1];
1501

    
1502
void serial_update_irq(void)
1503
{
1504
    SerialState *s = &serial_ports[0];
1505

    
1506
    if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {
1507
        s->iir = UART_IIR_RDI;
1508
    } else if (s->thr_ipending && (s->ier & UART_IER_THRI)) {
1509
        s->iir = UART_IIR_THRI;
1510
    } else {
1511
        s->iir = UART_IIR_NO_INT;
1512
    }
1513
    if (s->iir != UART_IIR_NO_INT) {
1514
        pic_set_irq(UART_IRQ, 1);
1515
    } else {
1516
        pic_set_irq(UART_IRQ, 0);
1517
    }
1518
}
1519

    
1520
void serial_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
1521
{
1522
    SerialState *s = &serial_ports[0];
1523
    unsigned char ch;
1524
    int ret;
1525
    
1526
    addr &= 7;
1527
#ifdef DEBUG_SERIAL
1528
    printf("serial: write addr=0x%02x val=0x%02x\n", addr, val);
1529
#endif
1530
    switch(addr) {
1531
    default:
1532
    case 0:
1533
        if (s->lcr & UART_LCR_DLAB) {
1534
            s->divider = (s->divider & 0xff00) | val;
1535
        } else {
1536
            s->thr_ipending = 0;
1537
            s->lsr &= ~UART_LSR_THRE;
1538
            serial_update_irq();
1539

    
1540
            ch = val;
1541
            do {
1542
                ret = write(1, &ch, 1);
1543
            } while (ret != 1);
1544
            s->thr_ipending = 1;
1545
            s->lsr |= UART_LSR_THRE;
1546
            s->lsr |= UART_LSR_TEMT;
1547
            serial_update_irq();
1548
        }
1549
        break;
1550
    case 1:
1551
        if (s->lcr & UART_LCR_DLAB) {
1552
            s->divider = (s->divider & 0x00ff) | (val << 8);
1553
        } else {
1554
            s->ier = val;
1555
            serial_update_irq();
1556
        }
1557
        break;
1558
    case 2:
1559
        break;
1560
    case 3:
1561
        s->lcr = val;
1562
        break;
1563
    case 4:
1564
        s->mcr = val;
1565
        break;
1566
    case 5:
1567
        break;
1568
    case 6:
1569
        s->msr = val;
1570
        break;
1571
    case 7:
1572
        s->scr = val;
1573
        break;
1574
    }
1575
}
1576

    
1577
uint32_t serial_ioport_read(CPUState *env, uint32_t addr)
1578
{
1579
    SerialState *s = &serial_ports[0];
1580
    uint32_t ret;
1581

    
1582
    addr &= 7;
1583
    switch(addr) {
1584
    default:
1585
    case 0:
1586
        if (s->lcr & UART_LCR_DLAB) {
1587
            ret = s->divider & 0xff; 
1588
        } else {
1589
            ret = s->rbr;
1590
            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
1591
            serial_update_irq();
1592
        }
1593
        break;
1594
    case 1:
1595
        if (s->lcr & UART_LCR_DLAB) {
1596
            ret = (s->divider >> 8) & 0xff;
1597
        } else {
1598
            ret = s->ier;
1599
        }
1600
        break;
1601
    case 2:
1602
        ret = s->iir;
1603
        /* reset THR pending bit */
1604
        if ((ret & 0x7) == UART_IIR_THRI)
1605
            s->thr_ipending = 0;
1606
        serial_update_irq();
1607
        break;
1608
    case 3:
1609
        ret = s->lcr;
1610
        break;
1611
    case 4:
1612
        ret = s->mcr;
1613
        break;
1614
    case 5:
1615
        ret = s->lsr;
1616
        break;
1617
    case 6:
1618
        if (s->mcr & UART_MCR_LOOP) {
1619
            /* in loopback, the modem output pins are connected to the
1620
               inputs */
1621
            ret = (s->mcr & 0x0c) << 4;
1622
            ret |= (s->mcr & 0x02) << 3;
1623
            ret |= (s->mcr & 0x01) << 5;
1624
        } else {
1625
            ret = s->msr;
1626
        }
1627
        break;
1628
    case 7:
1629
        ret = s->scr;
1630
        break;
1631
    }
1632
#ifdef DEBUG_SERIAL
1633
    printf("serial: read addr=0x%02x val=0x%02x\n", addr, ret);
1634
#endif
1635
    return ret;
1636
}
1637

    
1638
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1639
static int term_got_escape, term_command;
1640
static unsigned char term_cmd_buf[128];
1641

    
1642
typedef struct term_cmd_t {
1643
    const unsigned char *name;
1644
    void (*handler)(unsigned char *params);
1645
} term_cmd_t;
1646

    
1647
static void do_change_cdrom (unsigned char *params);
1648
static void do_change_fd0 (unsigned char *params);
1649
static void do_change_fd1 (unsigned char *params);
1650

    
1651
static term_cmd_t term_cmds[] = {
1652
    { "changecd", &do_change_cdrom, },
1653
    { "changefd0", &do_change_fd0, },
1654
    { "changefd1", &do_change_fd1, },
1655
    { NULL, NULL, },
1656
};
1657

    
1658
void term_print_help(void)
1659
{
1660
    printf("\n"
1661
           "C-a h    print this help\n"
1662
           "C-a x    exit emulatior\n"
1663
           "C-a d    switch on/off debug log\n"
1664
           "C-a s    save disk data back to file (if -snapshot)\n"
1665
           "C-a b    send break (magic sysrq)\n"
1666
           "C-a c    send qemu internal command\n"
1667
           "C-a C-a  send C-a\n"
1668
           );
1669
}
1670

    
1671
static void do_change_cdrom (unsigned char *params)
1672
{
1673
    /* Dunno how to do it... */
1674
}
1675

    
1676
static void do_change_fd (int fd, unsigned char *params)
1677
{
1678
    unsigned char *name_start, *name_end, *ros;
1679
    int ro;
1680

    
1681
    for (name_start = params;
1682
         isspace(*name_start); name_start++)
1683
        continue;
1684
    if (*name_start == '\0')
1685
        return;
1686
    for (name_end = name_start;
1687
         !isspace(*name_end) && *name_end != '\0'; name_end++)
1688
        continue;
1689
    for (ros = name_end + 1; isspace(*ros); ros++)
1690
        continue;
1691
    if (ros[0] == 'r' && ros[1] == 'o')
1692
        ro = 1;
1693
    else
1694
        ro = 0;
1695
    *name_end = '\0';
1696
    printf("Change fd %d to %s (%s)\n", fd, name_start, params);
1697
    fdctrl_disk_change(fd, name_start, ro);
1698
}
1699

    
1700
static void do_change_fd0 (unsigned char *params)
1701
{
1702
    do_change_fd(0, params);
1703
}
1704

    
1705
static void do_change_fd1 (unsigned char *params)
1706
{
1707
    do_change_fd(1, params);
1708
}
1709

    
1710
static void serial_treat_command ()
1711
{
1712
    unsigned char *cmd_start, *cmd_end;
1713
    int i;
1714

    
1715
    for (cmd_start = term_cmd_buf; isspace(*cmd_start); cmd_start++)
1716
        continue;
1717
    for (cmd_end = cmd_start;
1718
         !isspace(*cmd_end) && *cmd_end != '\0'; cmd_end++)
1719
        continue;
1720
    for (i = 0; term_cmds[i].name != NULL; i++) {
1721
        if (strlen(term_cmds[i].name) == (cmd_end - cmd_start) &&
1722
            memcmp(term_cmds[i].name, cmd_start, cmd_end - cmd_start) == 0) {
1723
            (*term_cmds[i].handler)(cmd_end + 1);
1724
            return;
1725
        }
1726
    }
1727
    *cmd_end = '\0';
1728
    printf("Unknown term command: %s\n", cmd_start);
1729
}
1730

    
1731
extern FILE *logfile;
1732

    
1733
/* called when a char is received */
1734
void serial_received_byte(SerialState *s, int ch)
1735
{
1736
    if (term_command) {
1737
        if (ch == '\n' || ch == '\r' || term_command == 127) {
1738
            printf("\n");
1739
            serial_treat_command();
1740
            term_command = 0;
1741
        } else {
1742
            if (ch == 0x7F || ch == 0x08) {
1743
                if (term_command > 1) {
1744
                    term_cmd_buf[--term_command - 1] = '\0';
1745
                    printf("\r                                               "
1746
                           "                               ");
1747
                    printf("\r> %s", term_cmd_buf);
1748
                }
1749
            } else if (ch > 0x1f) {
1750
                term_cmd_buf[term_command++ - 1] = ch;
1751
                term_cmd_buf[term_command - 1] = '\0';
1752
                printf("\r> %s", term_cmd_buf);
1753
            }
1754
            fflush(stdout);
1755
        }
1756
    } else if (term_got_escape) {
1757
        term_got_escape = 0;
1758
        switch(ch) {
1759
        case 'h':
1760
            term_print_help();
1761
            break;
1762
        case 'x':
1763
            exit(0);
1764
            break;
1765
        case 's': 
1766
            {
1767
                int i;
1768
                for (i = 0; i < MAX_DISKS; i++) {
1769
                    if (bs_table[i])
1770
                        bdrv_commit(bs_table[i]);
1771
                }
1772
            }
1773
            break;
1774
        case 'b':
1775
            /* send break */
1776
            s->rbr = 0;
1777
            s->lsr |= UART_LSR_BI | UART_LSR_DR;
1778
            serial_update_irq();
1779
            break;
1780
        case 'c':
1781
            printf("> ");
1782
            fflush(stdout);
1783
            term_command = 1;
1784
            break;
1785
        case 'd':
1786
            cpu_set_log(CPU_LOG_ALL);
1787
            break;
1788
        case TERM_ESCAPE:
1789
            goto send_char;
1790
        }
1791
    } else if (ch == TERM_ESCAPE) {
1792
        term_got_escape = 1;
1793
    } else {
1794
    send_char:
1795
        s->rbr = ch;
1796
        s->lsr |= UART_LSR_DR;
1797
        serial_update_irq();
1798
    }
1799
}
1800

    
1801
void serial_init(void)
1802
{
1803
    SerialState *s = &serial_ports[0];
1804

    
1805
    s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
1806
    s->iir = UART_IIR_NO_INT;
1807
    
1808
#if defined(TARGET_I386) || defined (TARGET_PPC)
1809
    register_ioport_write(0x3f8, 8, serial_ioport_write, 1);
1810
    register_ioport_read(0x3f8, 8, serial_ioport_read, 1);
1811
#endif
1812
}
1813

    
1814
/***********************************************************/
1815
/* ne2000 emulation */
1816

    
1817
#if defined (TARGET_I386)
1818
#define NE2000_IOPORT   0x300
1819
#define NE2000_IRQ      9
1820

    
1821
#define MAX_ETH_FRAME_SIZE 1514
1822

    
1823
#define E8390_CMD        0x00  /* The command register (for all pages) */
1824
/* Page 0 register offsets. */
1825
#define EN0_CLDALO        0x01        /* Low byte of current local dma addr  RD */
1826
#define EN0_STARTPG        0x01        /* Starting page of ring bfr WR */
1827
#define EN0_CLDAHI        0x02        /* High byte of current local dma addr  RD */
1828
#define EN0_STOPPG        0x02        /* Ending page +1 of ring bfr WR */
1829
#define EN0_BOUNDARY        0x03        /* Boundary page of ring bfr RD WR */
1830
#define EN0_TSR                0x04        /* Transmit status reg RD */
1831
#define EN0_TPSR        0x04        /* Transmit starting page WR */
1832
#define EN0_NCR                0x05        /* Number of collision reg RD */
1833
#define EN0_TCNTLO        0x05        /* Low  byte of tx byte count WR */
1834
#define EN0_FIFO        0x06        /* FIFO RD */
1835
#define EN0_TCNTHI        0x06        /* High byte of tx byte count WR */
1836
#define EN0_ISR                0x07        /* Interrupt status reg RD WR */
1837
#define EN0_CRDALO        0x08        /* low byte of current remote dma address RD */
1838
#define EN0_RSARLO        0x08        /* Remote start address reg 0 */
1839
#define EN0_CRDAHI        0x09        /* high byte, current remote dma address RD */
1840
#define EN0_RSARHI        0x09        /* Remote start address reg 1 */
1841
#define EN0_RCNTLO        0x0a        /* Remote byte count reg WR */
1842
#define EN0_RCNTHI        0x0b        /* Remote byte count reg WR */
1843
#define EN0_RSR                0x0c        /* rx status reg RD */
1844
#define EN0_RXCR        0x0c        /* RX configuration reg WR */
1845
#define EN0_TXCR        0x0d        /* TX configuration reg WR */
1846
#define EN0_COUNTER0        0x0d        /* Rcv alignment error counter RD */
1847
#define EN0_DCFG        0x0e        /* Data configuration reg WR */
1848
#define EN0_COUNTER1        0x0e        /* Rcv CRC error counter RD */
1849
#define EN0_IMR                0x0f        /* Interrupt mask reg WR */
1850
#define EN0_COUNTER2        0x0f        /* Rcv missed frame error counter RD */
1851

    
1852
#define EN1_PHYS        0x11
1853
#define EN1_CURPAG      0x17
1854
#define EN1_MULT        0x18
1855

    
1856
/*  Register accessed at EN_CMD, the 8390 base addr.  */
1857
#define E8390_STOP        0x01        /* Stop and reset the chip */
1858
#define E8390_START        0x02        /* Start the chip, clear reset */
1859
#define E8390_TRANS        0x04        /* Transmit a frame */
1860
#define E8390_RREAD        0x08        /* Remote read */
1861
#define E8390_RWRITE        0x10        /* Remote write  */
1862
#define E8390_NODMA        0x20        /* Remote DMA */
1863
#define E8390_PAGE0        0x00        /* Select page chip registers */
1864
#define E8390_PAGE1        0x40        /* using the two high-order bits */
1865
#define E8390_PAGE2        0x80        /* Page 3 is invalid. */
1866

    
1867
/* Bits in EN0_ISR - Interrupt status register */
1868
#define ENISR_RX        0x01        /* Receiver, no error */
1869
#define ENISR_TX        0x02        /* Transmitter, no error */
1870
#define ENISR_RX_ERR        0x04        /* Receiver, with error */
1871
#define ENISR_TX_ERR        0x08        /* Transmitter, with error */
1872
#define ENISR_OVER        0x10        /* Receiver overwrote the ring */
1873
#define ENISR_COUNTERS        0x20        /* Counters need emptying */
1874
#define ENISR_RDC        0x40        /* remote dma complete */
1875
#define ENISR_RESET        0x80        /* Reset completed */
1876
#define ENISR_ALL        0x3f        /* Interrupts we will enable */
1877

    
1878
/* Bits in received packet status byte and EN0_RSR*/
1879
#define ENRSR_RXOK        0x01        /* Received a good packet */
1880
#define ENRSR_CRC        0x02        /* CRC error */
1881
#define ENRSR_FAE        0x04        /* frame alignment error */
1882
#define ENRSR_FO        0x08        /* FIFO overrun */
1883
#define ENRSR_MPA        0x10        /* missed pkt */
1884
#define ENRSR_PHY        0x20        /* physical/multicast address */
1885
#define ENRSR_DIS        0x40        /* receiver disable. set in monitor mode */
1886
#define ENRSR_DEF        0x80        /* deferring */
1887

    
1888
/* Transmitted packet status, EN0_TSR. */
1889
#define ENTSR_PTX 0x01        /* Packet transmitted without error */
1890
#define ENTSR_ND  0x02        /* The transmit wasn't deferred. */
1891
#define ENTSR_COL 0x04        /* The transmit collided at least once. */
1892
#define ENTSR_ABT 0x08  /* The transmit collided 16 times, and was deferred. */
1893
#define ENTSR_CRS 0x10        /* The carrier sense was lost. */
1894
#define ENTSR_FU  0x20  /* A "FIFO underrun" occurred during transmit. */
1895
#define ENTSR_CDH 0x40        /* The collision detect "heartbeat" signal was lost. */
1896
#define ENTSR_OWC 0x80  /* There was an out-of-window collision. */
1897

    
1898
#define NE2000_MEM_SIZE 32768
1899

    
1900
typedef struct NE2000State {
1901
    uint8_t cmd;
1902
    uint32_t start;
1903
    uint32_t stop;
1904
    uint8_t boundary;
1905
    uint8_t tsr;
1906
    uint8_t tpsr;
1907
    uint16_t tcnt;
1908
    uint16_t rcnt;
1909
    uint32_t rsar;
1910
    uint8_t isr;
1911
    uint8_t dcfg;
1912
    uint8_t imr;
1913
    uint8_t phys[6]; /* mac address */
1914
    uint8_t curpag;
1915
    uint8_t mult[8]; /* multicast mask array */
1916
    uint8_t mem[NE2000_MEM_SIZE];
1917
} NE2000State;
1918

    
1919
NE2000State ne2000_state;
1920
int net_fd = -1;
1921
char network_script[1024];
1922

    
1923
void ne2000_reset(void)
1924
{
1925
    NE2000State *s = &ne2000_state;
1926
    int i;
1927

    
1928
    s->isr = ENISR_RESET;
1929
    s->mem[0] = 0x52;
1930
    s->mem[1] = 0x54;
1931
    s->mem[2] = 0x00;
1932
    s->mem[3] = 0x12;
1933
    s->mem[4] = 0x34;
1934
    s->mem[5] = 0x56;
1935
    s->mem[14] = 0x57;
1936
    s->mem[15] = 0x57;
1937

    
1938
    /* duplicate prom data */
1939
    for(i = 15;i >= 0; i--) {
1940
        s->mem[2 * i] = s->mem[i];
1941
        s->mem[2 * i + 1] = s->mem[i];
1942
    }
1943
}
1944

    
1945
void ne2000_update_irq(NE2000State *s)
1946
{
1947
    int isr;
1948
    isr = s->isr & s->imr;
1949
    if (isr)
1950
        pic_set_irq(NE2000_IRQ, 1);
1951
    else
1952
        pic_set_irq(NE2000_IRQ, 0);
1953
}
1954

    
1955
int net_init(void)
1956
{
1957
    struct ifreq ifr;
1958
    int fd, ret, pid, status;
1959
    
1960
    fd = open("/dev/net/tun", O_RDWR);
1961
    if (fd < 0) {
1962
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1963
        return -1;
1964
    }
1965
    memset(&ifr, 0, sizeof(ifr));
1966
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1967
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1968
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1969
    if (ret != 0) {
1970
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1971
        close(fd);
1972
        return -1;
1973
    }
1974
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
1975
    fcntl(fd, F_SETFL, O_NONBLOCK);
1976
    net_fd = fd;
1977

    
1978
    /* try to launch network init script */
1979
    pid = fork();
1980
    if (pid >= 0) {
1981
        if (pid == 0) {
1982
            execl(network_script, network_script, ifr.ifr_name, NULL);
1983
            exit(1);
1984
        }
1985
        while (waitpid(pid, &status, 0) != pid);
1986
        if (!WIFEXITED(status) ||
1987
            WEXITSTATUS(status) != 0) {
1988
            fprintf(stderr, "%s: could not launch network script for '%s'\n",
1989
                    network_script, ifr.ifr_name);
1990
        }
1991
    }
1992
    return 0;
1993
}
1994

    
1995
void net_send_packet(NE2000State *s, const uint8_t *buf, int size)
1996
{
1997
#ifdef DEBUG_NE2000
1998
    printf("NE2000: sending packet size=%d\n", size);
1999
#endif
2000
    write(net_fd, buf, size);
2001
}
2002

    
2003
/* return true if the NE2000 can receive more data */
2004
int ne2000_can_receive(NE2000State *s)
2005
{
2006
    int avail, index, boundary;
2007
    
2008
    if (s->cmd & E8390_STOP)
2009
        return 0;
2010
    index = s->curpag << 8;
2011
    boundary = s->boundary << 8;
2012
    if (index < boundary)
2013
        avail = boundary - index;
2014
    else
2015
        avail = (s->stop - s->start) - (index - boundary);
2016
    if (avail < (MAX_ETH_FRAME_SIZE + 4))
2017
        return 0;
2018
    return 1;
2019
}
2020

    
2021
void ne2000_receive(NE2000State *s, uint8_t *buf, int size)
2022
{
2023
    uint8_t *p;
2024
    int total_len, next, avail, len, index;
2025

    
2026
#if defined(DEBUG_NE2000)
2027
    printf("NE2000: received len=%d\n", size);
2028
#endif
2029

    
2030
    index = s->curpag << 8;
2031
    /* 4 bytes for header */
2032
    total_len = size + 4;
2033
    /* address for next packet (4 bytes for CRC) */
2034
    next = index + ((total_len + 4 + 255) & ~0xff);
2035
    if (next >= s->stop)
2036
        next -= (s->stop - s->start);
2037
    /* prepare packet header */
2038
    p = s->mem + index;
2039
    p[0] = ENRSR_RXOK; /* receive status */
2040
    p[1] = next >> 8;
2041
    p[2] = total_len;
2042
    p[3] = total_len >> 8;
2043
    index += 4;
2044

    
2045
    /* write packet data */
2046
    while (size > 0) {
2047
        avail = s->stop - index;
2048
        len = size;
2049
        if (len > avail)
2050
            len = avail;
2051
        memcpy(s->mem + index, buf, len);
2052
        buf += len;
2053
        index += len;
2054
        if (index == s->stop)
2055
            index = s->start;
2056
        size -= len;
2057
    }
2058
    s->curpag = next >> 8;
2059
    
2060
    /* now we can signal we have receive something */
2061
    s->isr |= ENISR_RX;
2062
    ne2000_update_irq(s);
2063
}
2064

    
2065
void ne2000_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
2066
{
2067
    NE2000State *s = &ne2000_state;
2068
    int offset, page;
2069

    
2070
    addr &= 0xf;
2071
#ifdef DEBUG_NE2000
2072
    printf("NE2000: write addr=0x%x val=0x%02x\n", addr, val);
2073
#endif
2074
    if (addr == E8390_CMD) {
2075
        /* control register */
2076
        s->cmd = val;
2077
        if (val & E8390_START) {
2078
            /* test specific case: zero length transfert */
2079
            if ((val & (E8390_RREAD | E8390_RWRITE)) &&
2080
                s->rcnt == 0) {
2081
                s->isr |= ENISR_RDC;
2082
                ne2000_update_irq(s);
2083
            }
2084
            if (val & E8390_TRANS) {
2085
                net_send_packet(s, s->mem + (s->tpsr << 8), s->tcnt);
2086
                /* signal end of transfert */
2087
                s->tsr = ENTSR_PTX;
2088
                s->isr |= ENISR_TX;
2089
                ne2000_update_irq(s);
2090
            }
2091
        }
2092
    } else {
2093
        page = s->cmd >> 6;
2094
        offset = addr | (page << 4);
2095
        switch(offset) {
2096
        case EN0_STARTPG:
2097
            s->start = val << 8;
2098
            break;
2099
        case EN0_STOPPG:
2100
            s->stop = val << 8;
2101
            break;
2102
        case EN0_BOUNDARY:
2103
            s->boundary = val;
2104
            break;
2105
        case EN0_IMR:
2106
            s->imr = val;
2107
            ne2000_update_irq(s);
2108
            break;
2109
        case EN0_TPSR:
2110
            s->tpsr = val;
2111
            break;
2112
        case EN0_TCNTLO:
2113
            s->tcnt = (s->tcnt & 0xff00) | val;
2114
            break;
2115
        case EN0_TCNTHI:
2116
            s->tcnt = (s->tcnt & 0x00ff) | (val << 8);
2117
            break;
2118
        case EN0_RSARLO:
2119
            s->rsar = (s->rsar & 0xff00) | val;
2120
            break;
2121
        case EN0_RSARHI:
2122
            s->rsar = (s->rsar & 0x00ff) | (val << 8);
2123
            break;
2124
        case EN0_RCNTLO:
2125
            s->rcnt = (s->rcnt & 0xff00) | val;
2126
            break;
2127
        case EN0_RCNTHI:
2128
            s->rcnt = (s->rcnt & 0x00ff) | (val << 8);
2129
            break;
2130
        case EN0_DCFG:
2131
            s->dcfg = val;
2132
            break;
2133
        case EN0_ISR:
2134
            s->isr &= ~val;
2135
            ne2000_update_irq(s);
2136
            break;
2137
        case EN1_PHYS ... EN1_PHYS + 5:
2138
            s->phys[offset - EN1_PHYS] = val;
2139
            break;
2140
        case EN1_CURPAG:
2141
            s->curpag = val;
2142
            break;
2143
        case EN1_MULT ... EN1_MULT + 7:
2144
            s->mult[offset - EN1_MULT] = val;
2145
            break;
2146
        }
2147
    }
2148
}
2149

    
2150
uint32_t ne2000_ioport_read(CPUState *env, uint32_t addr)
2151
{
2152
    NE2000State *s = &ne2000_state;
2153
    int offset, page, ret;
2154

    
2155
    addr &= 0xf;
2156
    if (addr == E8390_CMD) {
2157
        ret = s->cmd;
2158
    } else {
2159
        page = s->cmd >> 6;
2160
        offset = addr | (page << 4);
2161
        switch(offset) {
2162
        case EN0_TSR:
2163
            ret = s->tsr;
2164
            break;
2165
        case EN0_BOUNDARY:
2166
            ret = s->boundary;
2167
            break;
2168
        case EN0_ISR:
2169
            ret = s->isr;
2170
            break;
2171
        case EN1_PHYS ... EN1_PHYS + 5:
2172
            ret = s->phys[offset - EN1_PHYS];
2173
            break;
2174
        case EN1_CURPAG:
2175
            ret = s->curpag;
2176
            break;
2177
        case EN1_MULT ... EN1_MULT + 7:
2178
            ret = s->mult[offset - EN1_MULT];
2179
            break;
2180
        default:
2181
            ret = 0x00;
2182
            break;
2183
        }
2184
    }
2185
#ifdef DEBUG_NE2000
2186
    printf("NE2000: read addr=0x%x val=%02x\n", addr, ret);
2187
#endif
2188
    return ret;
2189
}
2190

    
2191
void ne2000_asic_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
2192
{
2193
    NE2000State *s = &ne2000_state;
2194
    uint8_t *p;
2195

    
2196
#ifdef DEBUG_NE2000
2197
    printf("NE2000: asic write val=0x%04x\n", val);
2198
#endif
2199
    p = s->mem + s->rsar;
2200
    if (s->dcfg & 0x01) {
2201
        /* 16 bit access */
2202
        p[0] = val;
2203
        p[1] = val >> 8;
2204
        s->rsar += 2;
2205
        s->rcnt -= 2;
2206
    } else {
2207
        /* 8 bit access */
2208
        p[0] = val;
2209
        s->rsar++;
2210
        s->rcnt--;
2211
    }
2212
    /* wrap */
2213
    if (s->rsar == s->stop)
2214
        s->rsar = s->start;
2215
    if (s->rcnt == 0) {
2216
        /* signal end of transfert */
2217
        s->isr |= ENISR_RDC;
2218
        ne2000_update_irq(s);
2219
    }
2220
}
2221

    
2222
uint32_t ne2000_asic_ioport_read(CPUState *env, uint32_t addr)
2223
{
2224
    NE2000State *s = &ne2000_state;
2225
    uint8_t *p;
2226
    int ret;
2227

    
2228
    p = s->mem + s->rsar;
2229
    if (s->dcfg & 0x01) {
2230
        /* 16 bit access */
2231
        ret = p[0] | (p[1] << 8);
2232
        s->rsar += 2;
2233
        s->rcnt -= 2;
2234
    } else {
2235
        /* 8 bit access */
2236
        ret = p[0];
2237
        s->rsar++;
2238
        s->rcnt--;
2239
    }
2240
    /* wrap */
2241
    if (s->rsar == s->stop)
2242
        s->rsar = s->start;
2243
    if (s->rcnt == 0) {
2244
        /* signal end of transfert */
2245
        s->isr |= ENISR_RDC;
2246
        ne2000_update_irq(s);
2247
    }
2248
#ifdef DEBUG_NE2000
2249
    printf("NE2000: asic read val=0x%04x\n", ret);
2250
#endif
2251
    return ret;
2252
}
2253

    
2254
void ne2000_reset_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
2255
{
2256
    /* nothing to do (end of reset pulse) */
2257
}
2258

    
2259
uint32_t ne2000_reset_ioport_read(CPUState *env, uint32_t addr)
2260
{
2261
    ne2000_reset();
2262
    return 0;
2263
}
2264

    
2265
void ne2000_init(void)
2266
{
2267
    register_ioport_write(NE2000_IOPORT, 16, ne2000_ioport_write, 1);
2268
    register_ioport_read(NE2000_IOPORT, 16, ne2000_ioport_read, 1);
2269

    
2270
    register_ioport_write(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_write, 1);
2271
    register_ioport_read(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_read, 1);
2272
    register_ioport_write(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_write, 2);
2273
    register_ioport_read(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_read, 2);
2274

    
2275
    register_ioport_write(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_write, 1);
2276
    register_ioport_read(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_read, 1);
2277
    ne2000_reset();
2278
}
2279
#endif
2280

    
2281
/***********************************************************/
2282
/* PC floppy disk controler emulation glue */
2283
#define PC_FDC_DMA  0x2
2284
#define PC_FDC_IRQ  0x6
2285
#define PC_FDC_BASE 0x3F0
2286

    
2287
static void fdctrl_register (unsigned char **disknames, int ro,
2288
                             char boot_device)
2289
{
2290
    int i;
2291

    
2292
    fdctrl_init(PC_FDC_IRQ, PC_FDC_DMA, 0, PC_FDC_BASE, boot_device);
2293
    for (i = 0; i < MAX_FD; i++) {
2294
        if (disknames[i] != NULL)
2295
            fdctrl_disk_change(i, disknames[i], ro);
2296
    }
2297
}
2298

    
2299
/***********************************************************/
2300
/* keyboard emulation */
2301

    
2302
/*        Keyboard Controller Commands */
2303
#define KBD_CCMD_READ_MODE        0x20        /* Read mode bits */
2304
#define KBD_CCMD_WRITE_MODE        0x60        /* Write mode bits */
2305
#define KBD_CCMD_GET_VERSION        0xA1        /* Get controller version */
2306
#define KBD_CCMD_MOUSE_DISABLE        0xA7        /* Disable mouse interface */
2307
#define KBD_CCMD_MOUSE_ENABLE        0xA8        /* Enable mouse interface */
2308
#define KBD_CCMD_TEST_MOUSE        0xA9        /* Mouse interface test */
2309
#define KBD_CCMD_SELF_TEST        0xAA        /* Controller self test */
2310
#define KBD_CCMD_KBD_TEST        0xAB        /* Keyboard interface test */
2311
#define KBD_CCMD_KBD_DISABLE        0xAD        /* Keyboard interface disable */
2312
#define KBD_CCMD_KBD_ENABLE        0xAE        /* Keyboard interface enable */
2313
#define KBD_CCMD_READ_INPORT    0xC0    /* read input port */
2314
#define KBD_CCMD_READ_OUTPORT        0xD0    /* read output port */
2315
#define KBD_CCMD_WRITE_OUTPORT        0xD1    /* write output port */
2316
#define KBD_CCMD_WRITE_OBUF        0xD2
2317
#define KBD_CCMD_WRITE_AUX_OBUF        0xD3    /* Write to output buffer as if
2318
                                           initiated by the auxiliary device */
2319
#define KBD_CCMD_WRITE_MOUSE        0xD4        /* Write the following byte to the mouse */
2320
#define KBD_CCMD_DISABLE_A20    0xDD    /* HP vectra only ? */
2321
#define KBD_CCMD_ENABLE_A20     0xDF    /* HP vectra only ? */
2322
#define KBD_CCMD_RESET                0xFE
2323

    
2324
/* Keyboard Commands */
2325
#define KBD_CMD_SET_LEDS        0xED        /* Set keyboard leds */
2326
#define KBD_CMD_ECHO             0xEE
2327
#define KBD_CMD_GET_ID                 0xF2        /* get keyboard ID */
2328
#define KBD_CMD_SET_RATE        0xF3        /* Set typematic rate */
2329
#define KBD_CMD_ENABLE                0xF4        /* Enable scanning */
2330
#define KBD_CMD_RESET_DISABLE        0xF5        /* reset and disable scanning */
2331
#define KBD_CMD_RESET_ENABLE           0xF6    /* reset and enable scanning */
2332
#define KBD_CMD_RESET                0xFF        /* Reset */
2333

    
2334
/* Keyboard Replies */
2335
#define KBD_REPLY_POR                0xAA        /* Power on reset */
2336
#define KBD_REPLY_ACK                0xFA        /* Command ACK */
2337
#define KBD_REPLY_RESEND        0xFE        /* Command NACK, send the cmd again */
2338

    
2339
/* Status Register Bits */
2340
#define KBD_STAT_OBF                 0x01        /* Keyboard output buffer full */
2341
#define KBD_STAT_IBF                 0x02        /* Keyboard input buffer full */
2342
#define KBD_STAT_SELFTEST        0x04        /* Self test successful */
2343
#define KBD_STAT_CMD                0x08        /* Last write was a command write (0=data) */
2344
#define KBD_STAT_UNLOCKED        0x10        /* Zero if keyboard locked */
2345
#define KBD_STAT_MOUSE_OBF        0x20        /* Mouse output buffer full */
2346
#define KBD_STAT_GTO                 0x40        /* General receive/xmit timeout */
2347
#define KBD_STAT_PERR                 0x80        /* Parity error */
2348

    
2349
/* Controller Mode Register Bits */
2350
#define KBD_MODE_KBD_INT        0x01        /* Keyboard data generate IRQ1 */
2351
#define KBD_MODE_MOUSE_INT        0x02        /* Mouse data generate IRQ12 */
2352
#define KBD_MODE_SYS                 0x04        /* The system flag (?) */
2353
#define KBD_MODE_NO_KEYLOCK        0x08        /* The keylock doesn't affect the keyboard if set */
2354
#define KBD_MODE_DISABLE_KBD        0x10        /* Disable keyboard interface */
2355
#define KBD_MODE_DISABLE_MOUSE        0x20        /* Disable mouse interface */
2356
#define KBD_MODE_KCC                 0x40        /* Scan code conversion to PC format */
2357
#define KBD_MODE_RFU                0x80
2358

    
2359
/* Mouse Commands */
2360
#define AUX_SET_SCALE11                0xE6        /* Set 1:1 scaling */
2361
#define AUX_SET_SCALE21                0xE7        /* Set 2:1 scaling */
2362
#define AUX_SET_RES                0xE8        /* Set resolution */
2363
#define AUX_GET_SCALE                0xE9        /* Get scaling factor */
2364
#define AUX_SET_STREAM                0xEA        /* Set stream mode */
2365
#define AUX_POLL                0xEB        /* Poll */
2366
#define AUX_RESET_WRAP                0xEC        /* Reset wrap mode */
2367
#define AUX_SET_WRAP                0xEE        /* Set wrap mode */
2368
#define AUX_SET_REMOTE                0xF0        /* Set remote mode */
2369
#define AUX_GET_TYPE                0xF2        /* Get type */
2370
#define AUX_SET_SAMPLE                0xF3        /* Set sample rate */
2371
#define AUX_ENABLE_DEV                0xF4        /* Enable aux device */
2372
#define AUX_DISABLE_DEV                0xF5        /* Disable aux device */
2373
#define AUX_SET_DEFAULT                0xF6
2374
#define AUX_RESET                0xFF        /* Reset aux device */
2375
#define AUX_ACK                        0xFA        /* Command byte ACK. */
2376

    
2377
#define MOUSE_STATUS_REMOTE     0x40
2378
#define MOUSE_STATUS_ENABLED    0x20
2379
#define MOUSE_STATUS_SCALE21    0x10
2380

    
2381
#define KBD_QUEUE_SIZE 256
2382

    
2383
typedef struct {
2384
    uint8_t data[KBD_QUEUE_SIZE];
2385
    int rptr, wptr, count;
2386
} KBDQueue;
2387

    
2388
typedef struct KBDState {
2389
    KBDQueue queues[2];
2390
    uint8_t write_cmd; /* if non zero, write data to port 60 is expected */
2391
    uint8_t status;
2392
    uint8_t mode;
2393
    /* keyboard state */
2394
    int kbd_write_cmd;
2395
    int scan_enabled;
2396
    /* mouse state */
2397
    int mouse_write_cmd;
2398
    uint8_t mouse_status;
2399
    uint8_t mouse_resolution;
2400
    uint8_t mouse_sample_rate;
2401
    uint8_t mouse_wrap;
2402
    uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */
2403
    uint8_t mouse_detect_state;
2404
    int mouse_dx; /* current values, needed for 'poll' mode */
2405
    int mouse_dy;
2406
    int mouse_dz;
2407
    uint8_t mouse_buttons;
2408
} KBDState;
2409

    
2410
KBDState kbd_state;
2411
int reset_requested;
2412

    
2413
/* update irq and KBD_STAT_[MOUSE_]OBF */
2414
/* XXX: not generating the irqs if KBD_MODE_DISABLE_KBD is set may be
2415
   incorrect, but it avoids having to simulate exact delays */
2416
static void kbd_update_irq(KBDState *s)
2417
{
2418
    int irq12_level, irq1_level;
2419

    
2420
    irq1_level = 0;    
2421
    irq12_level = 0;    
2422
    s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);
2423
    if (s->queues[0].count != 0 ||
2424
        s->queues[1].count != 0) {
2425
        s->status |= KBD_STAT_OBF;
2426
        if (s->queues[1].count != 0) {
2427
            s->status |= KBD_STAT_MOUSE_OBF;
2428
            if (s->mode & KBD_MODE_MOUSE_INT)
2429
                irq12_level = 1;
2430
        } else {
2431
            if ((s->mode & KBD_MODE_KBD_INT) && 
2432
                !(s->mode & KBD_MODE_DISABLE_KBD))
2433
                irq1_level = 1;
2434
        }
2435
    }
2436
    pic_set_irq(1, irq1_level);
2437
    pic_set_irq(12, irq12_level);
2438
}
2439

    
2440
static void kbd_queue(KBDState *s, int b, int aux)
2441
{
2442
    KBDQueue *q = &kbd_state.queues[aux];
2443

    
2444
#if defined(DEBUG_MOUSE) || defined(DEBUG_KBD)
2445
    if (aux)
2446
        printf("mouse event: 0x%02x\n", b);
2447
#ifdef DEBUG_KBD
2448
    else
2449
        printf("kbd event: 0x%02x\n", b);
2450
#endif
2451
#endif
2452
    if (q->count >= KBD_QUEUE_SIZE)
2453
        return;
2454
    q->data[q->wptr] = b;
2455
    if (++q->wptr == KBD_QUEUE_SIZE)
2456
        q->wptr = 0;
2457
    q->count++;
2458
    kbd_update_irq(s);
2459
}
2460

    
2461
void kbd_put_keycode(int keycode)
2462
{
2463
    KBDState *s = &kbd_state;
2464
    kbd_queue(s, keycode, 0);
2465
}
2466

    
2467
uint32_t kbd_read_status(CPUState *env, uint32_t addr)
2468
{
2469
    KBDState *s = &kbd_state;
2470
    int val;
2471
    val = s->status;
2472
#if defined(DEBUG_KBD)
2473
    printf("kbd: read status=0x%02x\n", val);
2474
#endif
2475
    return val;
2476
}
2477

    
2478
void kbd_write_command(CPUState *env, uint32_t addr, uint32_t val)
2479
{
2480
    KBDState *s = &kbd_state;
2481

    
2482
#ifdef DEBUG_KBD
2483
    printf("kbd: write cmd=0x%02x\n", val);
2484
#endif
2485
    switch(val) {
2486
    case KBD_CCMD_READ_MODE:
2487
        kbd_queue(s, s->mode, 0);
2488
        break;
2489
    case KBD_CCMD_WRITE_MODE:
2490
    case KBD_CCMD_WRITE_OBUF:
2491
    case KBD_CCMD_WRITE_AUX_OBUF:
2492
    case KBD_CCMD_WRITE_MOUSE:
2493
    case KBD_CCMD_WRITE_OUTPORT:
2494
        s->write_cmd = val;
2495
        break;
2496
    case KBD_CCMD_MOUSE_DISABLE:
2497
        s->mode |= KBD_MODE_DISABLE_MOUSE;
2498
        break;
2499
    case KBD_CCMD_MOUSE_ENABLE:
2500
        s->mode &= ~KBD_MODE_DISABLE_MOUSE;
2501
        break;
2502
    case KBD_CCMD_TEST_MOUSE:
2503
        kbd_queue(s, 0x00, 0);
2504
        break;
2505
    case KBD_CCMD_SELF_TEST:
2506
        s->status |= KBD_STAT_SELFTEST;
2507
        kbd_queue(s, 0x55, 0);
2508
        break;
2509
    case KBD_CCMD_KBD_TEST:
2510
        kbd_queue(s, 0x00, 0);
2511
        break;
2512
    case KBD_CCMD_KBD_DISABLE:
2513
        s->mode |= KBD_MODE_DISABLE_KBD;
2514
        kbd_update_irq(s);
2515
        break;
2516
    case KBD_CCMD_KBD_ENABLE:
2517
        s->mode &= ~KBD_MODE_DISABLE_KBD;
2518
        kbd_update_irq(s);
2519
        break;
2520
    case KBD_CCMD_READ_INPORT:
2521
        kbd_queue(s, 0x00, 0);
2522
        break;
2523
    case KBD_CCMD_READ_OUTPORT:
2524
        /* XXX: check that */
2525
#ifdef TARGET_I386
2526
        val = 0x01 | (a20_enabled << 1);
2527
#else
2528
        val = 0x01;
2529
#endif
2530
        if (s->status & KBD_STAT_OBF)
2531
            val |= 0x10;
2532
        if (s->status & KBD_STAT_MOUSE_OBF)
2533
            val |= 0x20;
2534
        kbd_queue(s, val, 0);
2535
        break;
2536
#ifdef TARGET_I386
2537
    case KBD_CCMD_ENABLE_A20:
2538
        cpu_x86_set_a20(env, 1);
2539
        break;
2540
    case KBD_CCMD_DISABLE_A20:
2541
        cpu_x86_set_a20(env, 0);
2542
        break;
2543
#endif
2544
    case KBD_CCMD_RESET:
2545
        reset_requested = 1;
2546
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
2547
        break;
2548
    case 0xff:
2549
        /* ignore that - I don't know what is its use */
2550
        break;
2551
    default:
2552
        fprintf(stderr, "qemu: unsupported keyboard cmd=0x%02x\n", val);
2553
        break;
2554
    }
2555
}
2556

    
2557
uint32_t kbd_read_data(CPUState *env, uint32_t addr)
2558
{
2559
    KBDState *s = &kbd_state;
2560
    KBDQueue *q;
2561
    int val, index;
2562
    
2563
    q = &s->queues[0]; /* first check KBD data */
2564
    if (q->count == 0)
2565
        q = &s->queues[1]; /* then check AUX data */
2566
    if (q->count == 0) {
2567
        /* NOTE: if no data left, we return the last keyboard one
2568
           (needed for EMM386) */
2569
        /* XXX: need a timer to do things correctly */
2570
        q = &s->queues[0];
2571
        index = q->rptr - 1;
2572
        if (index < 0)
2573
            index = KBD_QUEUE_SIZE - 1;
2574
        val = q->data[index];
2575
    } else {
2576
        val = q->data[q->rptr];
2577
        if (++q->rptr == KBD_QUEUE_SIZE)
2578
            q->rptr = 0;
2579
        q->count--;
2580
        /* reading deasserts IRQ */
2581
        if (q == &s->queues[0])
2582
            pic_set_irq(1, 0);
2583
        else
2584
            pic_set_irq(12, 0);
2585
    }
2586
    /* reassert IRQs if data left */
2587
    kbd_update_irq(s);
2588
#ifdef DEBUG_KBD
2589
    printf("kbd: read data=0x%02x\n", val);
2590
#endif
2591
    return val;
2592
}
2593

    
2594
static void kbd_reset_keyboard(KBDState *s)
2595
{
2596
    s->scan_enabled = 1;
2597
}
2598

    
2599
static void kbd_write_keyboard(KBDState *s, int val)
2600
{
2601
    switch(s->kbd_write_cmd) {
2602
    default:
2603
    case -1:
2604
        switch(val) {
2605
        case 0x00:
2606
            kbd_queue(s, KBD_REPLY_ACK, 0);
2607
            break;
2608
        case 0x05:
2609
            kbd_queue(s, KBD_REPLY_RESEND, 0);
2610
            break;
2611
        case KBD_CMD_GET_ID:
2612
            kbd_queue(s, KBD_REPLY_ACK, 0);
2613
            kbd_queue(s, 0xab, 0);
2614
            kbd_queue(s, 0x83, 0);
2615
            break;
2616
        case KBD_CMD_ECHO:
2617
            kbd_queue(s, KBD_CMD_ECHO, 0);
2618
            break;
2619
        case KBD_CMD_ENABLE:
2620
            s->scan_enabled = 1;
2621
            kbd_queue(s, KBD_REPLY_ACK, 0);
2622
            break;
2623
        case KBD_CMD_SET_LEDS:
2624
        case KBD_CMD_SET_RATE:
2625
            s->kbd_write_cmd = val;
2626
            kbd_queue(s, KBD_REPLY_ACK, 0);
2627
            break;
2628
        case KBD_CMD_RESET_DISABLE:
2629
            kbd_reset_keyboard(s);
2630
            s->scan_enabled = 0;
2631
            kbd_queue(s, KBD_REPLY_ACK, 0);
2632
            break;
2633
        case KBD_CMD_RESET_ENABLE:
2634
            kbd_reset_keyboard(s);
2635
            s->scan_enabled = 1;
2636
            kbd_queue(s, KBD_REPLY_ACK, 0);
2637
            break;
2638
        case KBD_CMD_RESET:
2639
            kbd_reset_keyboard(s);
2640
            kbd_queue(s, KBD_REPLY_ACK, 0);
2641
            kbd_queue(s, KBD_REPLY_POR, 0);
2642
            break;
2643
        default:
2644
            kbd_queue(s, KBD_REPLY_ACK, 0);
2645
            break;
2646
        }
2647
        break;
2648
    case KBD_CMD_SET_LEDS:
2649
        kbd_queue(s, KBD_REPLY_ACK, 0);
2650
        s->kbd_write_cmd = -1;
2651
        break;
2652
    case KBD_CMD_SET_RATE:
2653
        kbd_queue(s, KBD_REPLY_ACK, 0);
2654
        s->kbd_write_cmd = -1;
2655
        break;
2656
    }
2657
}
2658

    
2659
static void kbd_mouse_send_packet(KBDState *s)
2660
{
2661
    unsigned int b;
2662
    int dx1, dy1, dz1;
2663

    
2664
    dx1 = s->mouse_dx;
2665
    dy1 = s->mouse_dy;
2666
    dz1 = s->mouse_dz;
2667
    /* XXX: increase range to 8 bits ? */
2668
    if (dx1 > 127)
2669
        dx1 = 127;
2670
    else if (dx1 < -127)
2671
        dx1 = -127;
2672
    if (dy1 > 127)
2673
        dy1 = 127;
2674
    else if (dy1 < -127)
2675
        dy1 = -127;
2676
    b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);
2677
    kbd_queue(s, b, 1);
2678
    kbd_queue(s, dx1 & 0xff, 1);
2679
    kbd_queue(s, dy1 & 0xff, 1);
2680
    /* extra byte for IMPS/2 or IMEX */
2681
    switch(s->mouse_type) {
2682
    default:
2683
        break;
2684
    case 3:
2685
        if (dz1 > 127)
2686
            dz1 = 127;
2687
        else if (dz1 < -127)
2688
                dz1 = -127;
2689
        kbd_queue(s, dz1 & 0xff, 1);
2690
        break;
2691
    case 4:
2692
        if (dz1 > 7)
2693
            dz1 = 7;
2694
        else if (dz1 < -7)
2695
            dz1 = -7;
2696
        b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);
2697
        kbd_queue(s, b, 1);
2698
        break;
2699
    }
2700

    
2701
    /* update deltas */
2702
    s->mouse_dx -= dx1;
2703
    s->mouse_dy -= dy1;
2704
    s->mouse_dz -= dz1;
2705
}
2706

    
2707
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
2708
{
2709
    KBDState *s = &kbd_state;
2710

    
2711
    /* check if deltas are recorded when disabled */
2712
    if (!(s->mouse_status & MOUSE_STATUS_ENABLED))
2713
        return;
2714

    
2715
    s->mouse_dx += dx;
2716
    s->mouse_dy -= dy;
2717
    s->mouse_dz += dz;
2718
    s->mouse_buttons = buttons_state;
2719
    
2720
    if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&
2721
        (s->queues[1].count < (KBD_QUEUE_SIZE - 16))) {
2722
        for(;;) {
2723
            /* if not remote, send event. Multiple events are sent if
2724
               too big deltas */
2725
            kbd_mouse_send_packet(s);
2726
            if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)
2727
                break;
2728
        }
2729
    }
2730
}
2731

    
2732
static void kbd_write_mouse(KBDState *s, int val)
2733
{
2734
#ifdef DEBUG_MOUSE
2735
    printf("kbd: write mouse 0x%02x\n", val);
2736
#endif
2737
    switch(s->mouse_write_cmd) {
2738
    default:
2739
    case -1:
2740
        /* mouse command */
2741
        if (s->mouse_wrap) {
2742
            if (val == AUX_RESET_WRAP) {
2743
                s->mouse_wrap = 0;
2744
                kbd_queue(s, AUX_ACK, 1);
2745
                return;
2746
            } else if (val != AUX_RESET) {
2747
                kbd_queue(s, val, 1);
2748
                return;
2749
            }
2750
        }
2751
        switch(val) {
2752
        case AUX_SET_SCALE11:
2753
            s->mouse_status &= ~MOUSE_STATUS_SCALE21;
2754
            kbd_queue(s, AUX_ACK, 1);
2755
            break;
2756
        case AUX_SET_SCALE21:
2757
            s->mouse_status |= MOUSE_STATUS_SCALE21;
2758
            kbd_queue(s, AUX_ACK, 1);
2759
            break;
2760
        case AUX_SET_STREAM:
2761
            s->mouse_status &= ~MOUSE_STATUS_REMOTE;
2762
            kbd_queue(s, AUX_ACK, 1);
2763
            break;
2764
        case AUX_SET_WRAP:
2765
            s->mouse_wrap = 1;
2766
            kbd_queue(s, AUX_ACK, 1);
2767
            break;
2768
        case AUX_SET_REMOTE:
2769
            s->mouse_status |= MOUSE_STATUS_REMOTE;
2770
            kbd_queue(s, AUX_ACK, 1);
2771
            break;
2772
        case AUX_GET_TYPE:
2773
            kbd_queue(s, AUX_ACK, 1);
2774
            kbd_queue(s, s->mouse_type, 1);
2775
            break;
2776
        case AUX_SET_RES:
2777
        case AUX_SET_SAMPLE:
2778
            s->mouse_write_cmd = val;
2779
            kbd_queue(s, AUX_ACK, 1);
2780
            break;
2781
        case AUX_GET_SCALE:
2782
            kbd_queue(s, AUX_ACK, 1);
2783
            kbd_queue(s, s->mouse_status, 1);
2784
            kbd_queue(s, s->mouse_resolution, 1);
2785
            kbd_queue(s, s->mouse_sample_rate, 1);
2786
            break;
2787
        case AUX_POLL:
2788
            kbd_queue(s, AUX_ACK, 1);
2789
            kbd_mouse_send_packet(s);
2790
            break;
2791
        case AUX_ENABLE_DEV:
2792
            s->mouse_status |= MOUSE_STATUS_ENABLED;
2793
            kbd_queue(s, AUX_ACK, 1);
2794
            break;
2795
        case AUX_DISABLE_DEV:
2796
            s->mouse_status &= ~MOUSE_STATUS_ENABLED;
2797
            kbd_queue(s, AUX_ACK, 1);
2798
            break;
2799
        case AUX_SET_DEFAULT:
2800
            s->mouse_sample_rate = 100;
2801
            s->mouse_resolution = 2;
2802
            s->mouse_status = 0;
2803
            kbd_queue(s, AUX_ACK, 1);
2804
            break;
2805
        case AUX_RESET:
2806
            s->mouse_sample_rate = 100;
2807
            s->mouse_resolution = 2;
2808
            s->mouse_status = 0;
2809
            kbd_queue(s, AUX_ACK, 1);
2810
            kbd_queue(s, 0xaa, 1);
2811
            kbd_queue(s, s->mouse_type, 1);
2812
            break;
2813
        default:
2814
            break;
2815
        }
2816
        break;
2817
    case AUX_SET_SAMPLE:
2818
        s->mouse_sample_rate = val;
2819
#if 0
2820
        /* detect IMPS/2 or IMEX */
2821
        switch(s->mouse_detect_state) {
2822
        default:
2823
        case 0:
2824
            if (val == 200)
2825
                s->mouse_detect_state = 1;
2826
            break;
2827
        case 1:
2828
            if (val == 100)
2829
                s->mouse_detect_state = 2;
2830
            else if (val == 200)
2831
                s->mouse_detect_state = 3;
2832
            else
2833
                s->mouse_detect_state = 0;
2834
            break;
2835
        case 2:
2836
            if (val == 80) 
2837
                s->mouse_type = 3; /* IMPS/2 */
2838
            s->mouse_detect_state = 0;
2839
            break;
2840
        case 3:
2841
            if (val == 80) 
2842
                s->mouse_type = 4; /* IMEX */
2843
            s->mouse_detect_state = 0;
2844
            break;
2845
        }
2846
#endif
2847
        kbd_queue(s, AUX_ACK, 1);
2848
        s->mouse_write_cmd = -1;
2849
        break;
2850
    case AUX_SET_RES:
2851
        s->mouse_resolution = val;
2852
        kbd_queue(s, AUX_ACK, 1);
2853
        s->mouse_write_cmd = -1;
2854
        break;
2855
    }
2856
}
2857

    
2858
void kbd_write_data(CPUState *env, uint32_t addr, uint32_t val)
2859
{
2860
    KBDState *s = &kbd_state;
2861

    
2862
#ifdef DEBUG_KBD
2863
    printf("kbd: write data=0x%02x\n", val);
2864
#endif
2865

    
2866
    switch(s->write_cmd) {
2867
    case 0:
2868
        kbd_write_keyboard(s, val);
2869
        break;
2870
    case KBD_CCMD_WRITE_MODE:
2871
        s->mode = val;
2872
        kbd_update_irq(s);
2873
        break;
2874
    case KBD_CCMD_WRITE_OBUF:
2875
        kbd_queue(s, val, 0);
2876
        break;
2877
    case KBD_CCMD_WRITE_AUX_OBUF:
2878
        kbd_queue(s, val, 1);
2879
        break;
2880
    case KBD_CCMD_WRITE_OUTPORT:
2881
#ifdef TARGET_I386
2882
        cpu_x86_set_a20(env, (val >> 1) & 1);
2883
#endif
2884
        if (!(val & 1)) {
2885
            reset_requested = 1;
2886
            cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
2887
        }
2888
        break;
2889
    case KBD_CCMD_WRITE_MOUSE:
2890
        kbd_write_mouse(s, val);
2891
        break;
2892
    default:
2893
        break;
2894
    }
2895
    s->write_cmd = 0;
2896
}
2897

    
2898
void kbd_reset(KBDState *s)
2899
{
2900
    KBDQueue *q;
2901
    int i;
2902

    
2903
    s->kbd_write_cmd = -1;
2904
    s->mouse_write_cmd = -1;
2905
    s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;
2906
    s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;
2907
    for(i = 0; i < 2; i++) {
2908
        q = &s->queues[i];
2909
        q->rptr = 0;
2910
        q->wptr = 0;
2911
        q->count = 0;
2912
    }
2913
}
2914

    
2915
void kbd_init(void)
2916
{
2917
    kbd_reset(&kbd_state);
2918
#if defined (TARGET_I386) || defined (TARGET_PPC)
2919
    register_ioport_read(0x60, 1, kbd_read_data, 1);
2920
    register_ioport_write(0x60, 1, kbd_write_data, 1);
2921
    register_ioport_read(0x64, 1, kbd_read_status, 1);
2922
    register_ioport_write(0x64, 1, kbd_write_command, 1);
2923
#endif
2924
}
2925

    
2926
/***********************************************************/
2927
/* Bochs BIOS debug ports */
2928
#ifdef TARGET_I386
2929
void bochs_bios_write(CPUX86State *env, uint32_t addr, uint32_t val)
2930
{
2931
    switch(addr) {
2932
        /* Bochs BIOS messages */
2933
    case 0x400:
2934
    case 0x401:
2935
        fprintf(stderr, "BIOS panic at rombios.c, line %d\n", val);
2936
        exit(1);
2937
    case 0x402:
2938
    case 0x403:
2939
#ifdef DEBUG_BIOS
2940
        fprintf(stderr, "%c", val);
2941
#endif
2942
        break;
2943

    
2944
        /* LGPL'ed VGA BIOS messages */
2945
    case 0x501:
2946
    case 0x502:
2947
        fprintf(stderr, "VGA BIOS panic, line %d\n", val);
2948
        exit(1);
2949
    case 0x500:
2950
    case 0x503:
2951
#ifdef DEBUG_BIOS
2952
        fprintf(stderr, "%c", val);
2953
#endif
2954
        break;
2955
    }
2956
}
2957

    
2958
void bochs_bios_init(void)
2959
{
2960
    register_ioport_write(0x400, 1, bochs_bios_write, 2);
2961
    register_ioport_write(0x401, 1, bochs_bios_write, 2);
2962
    register_ioport_write(0x402, 1, bochs_bios_write, 1);
2963
    register_ioport_write(0x403, 1, bochs_bios_write, 1);
2964

    
2965
    register_ioport_write(0x501, 1, bochs_bios_write, 2);
2966
    register_ioport_write(0x502, 1, bochs_bios_write, 2);
2967
    register_ioport_write(0x500, 1, bochs_bios_write, 1);
2968
    register_ioport_write(0x503, 1, bochs_bios_write, 1);
2969
}
2970
#endif
2971

    
2972
/***********************************************************/
2973
/* dumb display */
2974

    
2975
/* init terminal so that we can grab keys */
2976
static struct termios oldtty;
2977

    
2978
static void term_exit(void)
2979
{
2980
    tcsetattr (0, TCSANOW, &oldtty);
2981
}
2982

    
2983
static void term_init(void)
2984
{
2985
    struct termios tty;
2986

    
2987
    tcgetattr (0, &tty);
2988
    oldtty = tty;
2989

    
2990
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2991
                          |INLCR|IGNCR|ICRNL|IXON);
2992
    tty.c_oflag |= OPOST;
2993
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2994
    /* if graphical mode, we allow Ctrl-C handling */
2995
    if (nographic)
2996
        tty.c_lflag &= ~ISIG;
2997
    tty.c_cflag &= ~(CSIZE|PARENB);
2998
    tty.c_cflag |= CS8;
2999
    tty.c_cc[VMIN] = 1;
3000
    tty.c_cc[VTIME] = 0;
3001
    
3002
    tcsetattr (0, TCSANOW, &tty);
3003

    
3004
    atexit(term_exit);
3005

    
3006
    fcntl(0, F_SETFL, O_NONBLOCK);
3007
}
3008

    
3009
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3010
{
3011
}
3012

    
3013
static void dumb_resize(DisplayState *ds, int w, int h)
3014
{
3015
}
3016

    
3017
static void dumb_refresh(DisplayState *ds)
3018
{
3019
    vga_update_display();
3020
}
3021

    
3022
void dumb_display_init(DisplayState *ds)
3023
{
3024
    ds->data = NULL;
3025
    ds->linesize = 0;
3026
    ds->depth = 0;
3027
    ds->dpy_update = dumb_update;
3028
    ds->dpy_resize = dumb_resize;
3029
    ds->dpy_refresh = dumb_refresh;
3030
}
3031

    
3032
#if !defined(CONFIG_SOFTMMU)
3033
/***********************************************************/
3034
/* cpu signal handler */
3035
static void host_segv_handler(int host_signum, siginfo_t *info, 
3036
                              void *puc)
3037
{
3038
    if (cpu_signal_handler(host_signum, info, puc))
3039
        return;
3040
    term_exit();
3041
    abort();
3042
}
3043
#endif
3044

    
3045
static int timer_irq_pending;
3046
static int timer_irq_count;
3047

    
3048
static int timer_ms;
3049
static int gui_refresh_pending, gui_refresh_count;
3050

    
3051
static void host_alarm_handler(int host_signum, siginfo_t *info, 
3052
                               void *puc)
3053
{
3054
    /* NOTE: since usually the OS asks a 100 Hz clock, there can be
3055
       some drift between cpu_get_ticks() and the interrupt time. So
3056
       we queue some interrupts to avoid missing some */
3057
    timer_irq_count += pit_get_out_edges(&pit_channels[0]);
3058
    if (timer_irq_count) {
3059
        if (timer_irq_count > 2)
3060
            timer_irq_count = 2;
3061
        timer_irq_count--;
3062
        timer_irq_pending = 1;
3063
    }
3064
    gui_refresh_count += timer_ms;
3065
    if (gui_refresh_count >= GUI_REFRESH_INTERVAL) {
3066
        gui_refresh_count = 0;
3067
        gui_refresh_pending = 1;
3068
    }
3069

    
3070
    /* XXX: seems dangerous to run that here. */
3071
    DMA_run();
3072
    SB16_run();
3073

    
3074
    if (gui_refresh_pending || timer_irq_pending) {
3075
        /* just exit from the cpu to have a chance to handle timers */
3076
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
3077
    }
3078
}
3079

    
3080
#ifdef CONFIG_SOFTMMU
3081
void *get_mmap_addr(unsigned long size)
3082
{
3083
    return NULL;
3084
}
3085
#else
3086
unsigned long mmap_addr = PHYS_RAM_BASE;
3087

    
3088
void *get_mmap_addr(unsigned long size)
3089
{
3090
    unsigned long addr;
3091
    addr = mmap_addr;
3092
    mmap_addr += ((size + 4095) & ~4095) + 4096;
3093
    return (void *)addr;
3094
}
3095
#endif
3096

    
3097
/* main execution loop */
3098

    
3099
CPUState *cpu_gdbstub_get_env(void *opaque)
3100
{
3101
    return global_env;
3102
}
3103

    
3104
int main_loop(void *opaque)
3105
{
3106
    struct pollfd ufds[3], *pf, *serial_ufd, *gdb_ufd;
3107
#if defined (TARGET_I386)
3108
    struct pollfd *net_ufd;
3109
#endif
3110
    int ret, n, timeout, serial_ok;
3111
    uint8_t ch;
3112
    CPUState *env = global_env;
3113

    
3114
    if (!term_inited) {
3115
        /* initialize terminal only there so that the user has a
3116
           chance to stop QEMU with Ctrl-C before the gdb connection
3117
           is launched */
3118
        term_inited = 1;
3119
        term_init();
3120
    }
3121

    
3122
    serial_ok = 1;
3123
    cpu_enable_ticks();
3124
    for(;;) {
3125
#if defined (DO_TB_FLUSH)
3126
        tb_flush();
3127
#endif
3128
        ret = cpu_exec(env);
3129
        if (reset_requested) {
3130
            ret = EXCP_INTERRUPT; 
3131
            break;
3132
        }
3133
        if (ret == EXCP_DEBUG) {
3134
            ret = EXCP_DEBUG;
3135
            break;
3136
        }
3137
        /* if hlt instruction, we wait until the next IRQ */
3138
        if (ret == EXCP_HLT) 
3139
            timeout = 10;
3140
        else
3141
            timeout = 0;
3142
        /* poll any events */
3143
        serial_ufd = NULL;
3144
        pf = ufds;
3145
        if (serial_ok && !(serial_ports[0].lsr & UART_LSR_DR)) {
3146
            serial_ufd = pf;
3147
            pf->fd = 0;
3148
            pf->events = POLLIN;
3149
            pf++;
3150
        }
3151
#if defined (TARGET_I386)
3152
        net_ufd = NULL;
3153
        if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) {
3154
            net_ufd = pf;
3155
            pf->fd = net_fd;
3156
            pf->events = POLLIN;
3157
            pf++;
3158
        }
3159
#endif
3160
        gdb_ufd = NULL;
3161
        if (gdbstub_fd > 0) {
3162
            gdb_ufd = pf;
3163
            pf->fd = gdbstub_fd;
3164
            pf->events = POLLIN;
3165
            pf++;
3166
        }
3167

    
3168
        ret = poll(ufds, pf - ufds, timeout);
3169
        if (ret > 0) {
3170
            if (serial_ufd && (serial_ufd->revents & POLLIN)) {
3171
                n = read(0, &ch, 1);
3172
                if (n == 1) {
3173
                    serial_received_byte(&serial_ports[0], ch);
3174
                } else {
3175
                    /* Closed, stop polling. */
3176
                    serial_ok = 0;
3177
                }
3178
            }
3179
#if defined (TARGET_I386)
3180
            if (net_ufd && (net_ufd->revents & POLLIN)) {
3181
                uint8_t buf[MAX_ETH_FRAME_SIZE];
3182

    
3183
                n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);
3184
                if (n > 0) {
3185
                    if (n < 60) {
3186
                        memset(buf + n, 0, 60 - n);
3187
                        n = 60;
3188
                    }
3189
                    ne2000_receive(&ne2000_state, buf, n);
3190
                }
3191
            }
3192
#endif
3193
            if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {
3194
                uint8_t buf[1];
3195
                /* stop emulation if requested by gdb */
3196
                n = read(gdbstub_fd, buf, 1);
3197
                if (n == 1) {
3198
                    ret = EXCP_INTERRUPT; 
3199
                    break;
3200
                }
3201
            }
3202
        }
3203

    
3204
        /* timer IRQ */
3205
        if (timer_irq_pending) {
3206
#if defined (TARGET_I386)
3207
            pic_set_irq(0, 1);
3208
            pic_set_irq(0, 0);
3209
            timer_irq_pending = 0;
3210
            /* XXX: RTC test */
3211
            if (cmos_data[RTC_REG_B] & 0x50) {
3212
                pic_set_irq(8, 1);
3213
            }
3214
#endif
3215
        }
3216

    
3217
        /* VGA */
3218
        if (gui_refresh_pending) {
3219
            display_state.dpy_refresh(&display_state);
3220
            gui_refresh_pending = 0;
3221
        }
3222
    }
3223
    cpu_disable_ticks();
3224
    return ret;
3225
}
3226

    
3227
void help(void)
3228
{
3229
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
3230
           "usage: %s [options] [disk_image]\n"
3231
           "\n"
3232
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3233
           "\n"
3234
           "Standard options:\n"
3235
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
3236
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
3237
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
3238
           "-cdrom file     use 'file' as IDE cdrom 2 image\n"
3239
           "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
3240
           "-snapshot       write to temporary files instead of disk image files\n"
3241
           "-m megs         set virtual RAM size to megs MB\n"
3242
           "-n script       set network init script [default=%s]\n"
3243
           "-tun-fd fd      this fd talks to tap/tun, use it.\n"
3244
           "-nographic      disable graphical output\n"
3245
           "\n"
3246
           "Linux boot specific (does not require PC BIOS):\n"
3247
           "-kernel bzImage use 'bzImage' as kernel image\n"
3248
           "-append cmdline use 'cmdline' as kernel command line\n"
3249
           "-initrd file    use 'file' as initial ram disk\n"
3250
           "\n"
3251
           "Debug/Expert options:\n"
3252
           "-s              wait gdb connection to port %d\n"
3253
           "-p port         change gdb connection port\n"
3254
           "-d              output log to %s\n"
3255
           "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
3256
           "-L path         set the directory for the BIOS and VGA BIOS\n"
3257
           "\n"
3258
           "During emulation, use C-a h to get terminal commands:\n",
3259
#ifdef CONFIG_SOFTMMU
3260
           "qemu",
3261
#else
3262
           "qemu-fast",
3263
#endif
3264
           DEFAULT_NETWORK_SCRIPT, 
3265
           DEFAULT_GDBSTUB_PORT,
3266
           "/tmp/qemu.log");
3267
    term_print_help();
3268
#ifndef CONFIG_SOFTMMU
3269
    printf("\n"
3270
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
3271
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
3272
           "PC emulation.\n");
3273
#endif
3274
    exit(1);
3275
}
3276

    
3277
struct option long_options[] = {
3278
    { "initrd", 1, NULL, 0, },
3279
    { "hda", 1, NULL, 0, },
3280
    { "hdb", 1, NULL, 0, },
3281
    { "snapshot", 0, NULL, 0, },
3282
    { "hdachs", 1, NULL, 0, },
3283
    { "nographic", 0, NULL, 0, },
3284
    { "kernel", 1, NULL, 0, },
3285
    { "append", 1, NULL, 0, },
3286
    { "tun-fd", 1, NULL, 0, },
3287
    { "hdc", 1, NULL, 0, },
3288
    { "hdd", 1, NULL, 0, },
3289
    { "cdrom", 1, NULL, 0, },
3290
    { "boot", 1, NULL, 0, },
3291
    { "fda", 1, NULL, 0, },
3292
    { "fdb", 1, NULL, 0, },
3293
    { NULL, 0, NULL, 0 },
3294
};
3295

    
3296
#ifdef CONFIG_SDL
3297
/* SDL use the pthreads and they modify sigaction. We don't
3298
   want that. */
3299
#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)
3300
extern void __libc_sigaction();
3301
#define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
3302
#else
3303
extern void __sigaction();
3304
#define sigaction(sig, act, oact) __sigaction(sig, act, oact)
3305
#endif
3306
#endif /* CONFIG_SDL */
3307

    
3308
int main(int argc, char **argv)
3309
{
3310
    int c, ret, initrd_size, i, use_gdbstub, gdbstub_port, long_index;
3311
    int snapshot, linux_boot, total_ram_size;
3312
#if defined (TARGET_I386)
3313
    struct linux_params *params;
3314
#endif
3315
    struct sigaction act;
3316
    struct itimerval itv;
3317
    CPUState *env;
3318
    const char *initrd_filename;
3319
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
3320
    const char *kernel_filename, *kernel_cmdline;
3321
    DisplayState *ds = &display_state;
3322

    
3323
    /* we never want that malloc() uses mmap() */
3324
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
3325
    initrd_filename = NULL;
3326
    for(i = 0; i < MAX_FD; i++)
3327
        fd_filename[i] = NULL;
3328
    for(i = 0; i < MAX_DISKS; i++)
3329
        hd_filename[i] = NULL;
3330
    phys_ram_size = 32 * 1024 * 1024;
3331
    vga_ram_size = VGA_RAM_SIZE;
3332
#if defined (TARGET_I386)
3333
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
3334
#endif
3335
    use_gdbstub = 0;
3336
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
3337
    snapshot = 0;
3338
    nographic = 0;
3339
    kernel_filename = NULL;
3340
    kernel_cmdline = "";
3341
    for(;;) {
3342
        c = getopt_long_only(argc, argv, "hm:dn:sp:L:", long_options, &long_index);
3343
        if (c == -1)
3344
            break;
3345
        switch(c) {
3346
        case 0:
3347
            switch(long_index) {
3348
            case 0:
3349
                initrd_filename = optarg;
3350
                break;
3351
            case 1:
3352
                hd_filename[0] = optarg;
3353
                break;
3354
            case 2:
3355
                hd_filename[1] = optarg;
3356
                break;
3357
            case 3:
3358
                snapshot = 1;
3359
                break;
3360
            case 4:
3361
                {
3362
                    int cyls, heads, secs;
3363
                    const char *p;
3364
                    p = optarg;
3365
                    cyls = strtol(p, (char **)&p, 0);
3366
                    if (*p != ',')
3367
                        goto chs_fail;
3368
                    p++;
3369
                    heads = strtol(p, (char **)&p, 0);
3370
                    if (*p != ',')
3371
                        goto chs_fail;
3372
                    p++;
3373
                    secs = strtol(p, (char **)&p, 0);
3374
                    if (*p != '\0')
3375
                        goto chs_fail;
3376
                    ide_set_geometry(0, cyls, heads, secs);
3377
                chs_fail: ;
3378
                }
3379
                break;
3380
            case 5:
3381
                nographic = 1;
3382
                break;
3383
            case 6:
3384
                kernel_filename = optarg;
3385
                break;
3386
            case 7:
3387
                kernel_cmdline = optarg;
3388
                break;
3389
#if defined (TARGET_I386)
3390
            case 8:
3391
                net_fd = atoi(optarg);
3392
                break;
3393
#endif
3394
            case 9:
3395
                hd_filename[2] = optarg;
3396
                break;
3397
            case 10:
3398
                hd_filename[3] = optarg;
3399
                break;
3400
            case 11:
3401
                hd_filename[2] = optarg;
3402
                ide_set_cdrom(2, 1);
3403
                break;
3404
            case 12:
3405
                boot_device = optarg[0];
3406
                if (boot_device != 'a' && boot_device != 'b' &&
3407
                    boot_device != 'c' && boot_device != 'd') {
3408
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3409
                    exit(1);
3410
                }
3411
                break;
3412
            case 13:
3413
                fd_filename[0] = optarg;
3414
                break;
3415
            case 14:
3416
                fd_filename[1] = optarg;
3417
                break;
3418
            }
3419
            break;
3420
        case 'h':
3421
            help();
3422
            break;
3423
        case 'm':
3424
            phys_ram_size = atoi(optarg) * 1024 * 1024;
3425
            if (phys_ram_size <= 0)
3426
                help();
3427
            if (phys_ram_size > PHYS_RAM_MAX_SIZE) {
3428
                fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3429
                        PHYS_RAM_MAX_SIZE / (1024 * 1024));
3430
                exit(1);
3431
            }
3432
            break;
3433
        case 'd':
3434
            cpu_set_log(CPU_LOG_ALL);
3435
            break;
3436
#if defined (TARGET_I386)
3437
        case 'n':
3438
            pstrcpy(network_script, sizeof(network_script), optarg);
3439
            break;
3440
#endif
3441
        case 's':
3442
            use_gdbstub = 1;
3443
            break;
3444
        case 'p':
3445
            gdbstub_port = atoi(optarg);
3446
            break;
3447
        case 'L':
3448
            bios_dir = optarg;
3449
            break;
3450
        }
3451
    }
3452

    
3453
    if (optind < argc) {
3454
        hd_filename[0] = argv[optind++];
3455
    }
3456

    
3457
    linux_boot = (kernel_filename != NULL);
3458
        
3459
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
3460
        fd_filename[0] == '\0')
3461
        help();
3462
    
3463
    /* boot to cd by default if no hard disk */
3464
    if (hd_filename[0] == '\0' && boot_device == 'c') {
3465
        if (fd_filename[0] != '\0')
3466
            boot_device = 'a';
3467
        else
3468
            boot_device = 'd';
3469
    }
3470

    
3471
#if !defined(CONFIG_SOFTMMU)
3472
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3473
    {
3474
        static uint8_t stdout_buf[4096];
3475
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3476
    }
3477
#else
3478
    setvbuf(stdout, NULL, _IOLBF, 0);
3479
#endif
3480

    
3481
    /* init network tun interface */
3482
#if defined (TARGET_I386)
3483
    if (net_fd < 0)
3484
        net_init();
3485
#endif
3486

    
3487
    /* init the memory */
3488
    total_ram_size = phys_ram_size + vga_ram_size;
3489

    
3490
#ifdef CONFIG_SOFTMMU
3491
    phys_ram_base = malloc(total_ram_size);
3492
    if (!phys_ram_base) {
3493
        fprintf(stderr, "Could not allocate physical memory\n");
3494
        exit(1);
3495
    }
3496
#else
3497
    /* as we must map the same page at several addresses, we must use
3498
       a fd */
3499
    {
3500
        const char *tmpdir;
3501

    
3502
        tmpdir = getenv("QEMU_TMPDIR");
3503
        if (!tmpdir)
3504
            tmpdir = "/tmp";
3505
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3506
        if (mkstemp(phys_ram_file) < 0) {
3507
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
3508
                    phys_ram_file);
3509
            exit(1);
3510
        }
3511
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3512
        if (phys_ram_fd < 0) {
3513
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
3514
                    phys_ram_file);
3515
            exit(1);
3516
        }
3517
        ftruncate(phys_ram_fd, total_ram_size);
3518
        unlink(phys_ram_file);
3519
        phys_ram_base = mmap(get_mmap_addr(total_ram_size), 
3520
                             total_ram_size, 
3521
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
3522
                             phys_ram_fd, 0);
3523
        if (phys_ram_base == MAP_FAILED) {
3524
            fprintf(stderr, "Could not map physical memory\n");
3525
            exit(1);
3526
        }
3527
    }
3528
#endif
3529

    
3530
    /* open the virtual block devices */
3531
    for(i = 0; i < MAX_DISKS; i++) {
3532
        if (hd_filename[i]) {
3533
            bs_table[i] = bdrv_open(hd_filename[i], snapshot);
3534
            if (!bs_table[i]) {
3535
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
3536
                        hd_filename[i]);
3537
                exit(1);
3538
            }
3539
        }
3540
    }
3541

    
3542
    /* init CPU state */
3543
    env = cpu_init();
3544
    global_env = env;
3545
    cpu_single_env = env;
3546

    
3547
    init_ioports();
3548

    
3549
    /* allocate RAM */
3550
    cpu_register_physical_memory(0, phys_ram_size, 0);
3551

    
3552
    if (linux_boot) {
3553
        /* now we can load the kernel */
3554
        ret = load_kernel(kernel_filename, phys_ram_base + KERNEL_LOAD_ADDR);
3555
        if (ret < 0) {
3556
            fprintf(stderr, "qemu: could not load kernel '%s'\n", 
3557
                    kernel_filename);
3558
            exit(1);
3559
        }
3560
        
3561
        /* load initrd */
3562
        initrd_size = 0;
3563
        if (initrd_filename) {
3564
            initrd_size = load_image(initrd_filename, phys_ram_base + INITRD_LOAD_ADDR);
3565
            if (initrd_size < 0) {
3566
                fprintf(stderr, "qemu: could not load initial ram disk '%s'\n", 
3567
                        initrd_filename);
3568
                exit(1);
3569
            }
3570
        }
3571
        
3572
        /* init kernel params */
3573
#ifdef TARGET_I386
3574
        params = (void *)(phys_ram_base + KERNEL_PARAMS_ADDR);
3575
        memset(params, 0, sizeof(struct linux_params));
3576
        params->mount_root_rdonly = 0;
3577
        stw_raw(&params->cl_magic, 0xA33F);
3578
        stw_raw(&params->cl_offset, params->commandline - (uint8_t *)params);
3579
        stl_raw(&params->alt_mem_k, (phys_ram_size / 1024) - 1024);
3580
        pstrcat(params->commandline, sizeof(params->commandline), kernel_cmdline);
3581
        params->loader_type = 0x01;
3582
        if (initrd_size > 0) {
3583
            stl_raw(&params->initrd_start, INITRD_LOAD_ADDR);
3584
            stl_raw(&params->initrd_size, initrd_size);
3585
        }
3586
        params->orig_video_lines = 25;
3587
        params->orig_video_cols = 80;
3588

    
3589
        /* setup basic memory access */
3590
        env->cr[0] = 0x00000033;
3591
        env->hflags |= HF_PE_MASK;
3592
        cpu_x86_init_mmu(env);
3593
        
3594
        memset(params->idt_table, 0, sizeof(params->idt_table));
3595
        
3596
        stq_raw(&params->gdt_table[2], 0x00cf9a000000ffffLL); /* KERNEL_CS */
3597
        stq_raw(&params->gdt_table[3], 0x00cf92000000ffffLL); /* KERNEL_DS */
3598
        /* for newer kernels (2.6.0) CS/DS are at different addresses */
3599
        stq_raw(&params->gdt_table[12], 0x00cf9a000000ffffLL); /* KERNEL_CS */
3600
        stq_raw(&params->gdt_table[13], 0x00cf92000000ffffLL); /* KERNEL_DS */
3601
        
3602
        env->idt.base = (void *)((uint8_t *)params->idt_table - phys_ram_base);
3603
        env->idt.limit = sizeof(params->idt_table) - 1;
3604
        env->gdt.base = (void *)((uint8_t *)params->gdt_table - phys_ram_base);
3605
        env->gdt.limit = sizeof(params->gdt_table) - 1;
3606
        
3607
        cpu_x86_load_seg_cache(env, R_CS, KERNEL_CS, NULL, 0xffffffff, 0x00cf9a00);
3608
        cpu_x86_load_seg_cache(env, R_DS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3609
        cpu_x86_load_seg_cache(env, R_ES, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3610
        cpu_x86_load_seg_cache(env, R_SS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3611
        cpu_x86_load_seg_cache(env, R_FS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3612
        cpu_x86_load_seg_cache(env, R_GS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3613
        
3614
        env->eip = KERNEL_LOAD_ADDR;
3615
        env->regs[R_ESI] = KERNEL_PARAMS_ADDR;
3616
        env->eflags = 0x2;
3617
#elif defined (TARGET_PPC)
3618
        cpu_x86_init_mmu(env);
3619
        PPC_init_hw(env, phys_ram_size, KERNEL_LOAD_ADDR, ret,
3620
                    KERNEL_STACK_ADDR, boot_device);
3621
#endif
3622
    } else {
3623
        char buf[1024];
3624

    
3625
        /* RAW PC boot */
3626
#if defined(TARGET_I386)
3627
        /* BIOS load */
3628
        snprintf(buf, sizeof(buf), "%s/%s", bios_dir, BIOS_FILENAME);
3629
        ret = load_image(buf, phys_ram_base + 0x000f0000);
3630
        if (ret != 0x10000) {
3631
            fprintf(stderr, "qemu: could not load PC bios '%s'\n", buf);
3632
            exit(1);
3633
        }
3634

    
3635
        /* VGA BIOS load */
3636
        snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_FILENAME);
3637
        ret = load_image(buf, phys_ram_base + 0x000c0000);
3638

    
3639
        /* setup basic memory access */
3640
        env->cr[0] = 0x60000010;
3641
        cpu_x86_init_mmu(env);
3642
        
3643
        cpu_register_physical_memory(0xc0000, 0x10000, 0xc0000 | IO_MEM_ROM);
3644
        cpu_register_physical_memory(0xf0000, 0x10000, 0xf0000 | IO_MEM_ROM);
3645

    
3646
        env->idt.limit = 0xffff;
3647
        env->gdt.limit = 0xffff;
3648
        env->ldt.limit = 0xffff;
3649
        env->ldt.flags = DESC_P_MASK;
3650
        env->tr.limit = 0xffff;
3651
        env->tr.flags = DESC_P_MASK;
3652

    
3653
        /* not correct (CS base=0xffff0000) */
3654
        cpu_x86_load_seg_cache(env, R_CS, 0xf000, (uint8_t *)0x000f0000, 0xffff, 0); 
3655
        cpu_x86_load_seg_cache(env, R_DS, 0, NULL, 0xffff, 0);
3656
        cpu_x86_load_seg_cache(env, R_ES, 0, NULL, 0xffff, 0);
3657
        cpu_x86_load_seg_cache(env, R_SS, 0, NULL, 0xffff, 0);
3658
        cpu_x86_load_seg_cache(env, R_FS, 0, NULL, 0xffff, 0);
3659
        cpu_x86_load_seg_cache(env, R_GS, 0, NULL, 0xffff, 0);
3660

    
3661
        env->eip = 0xfff0;
3662
        env->regs[R_EDX] = 0x600; /* indicate P6 processor */
3663

    
3664
        env->eflags = 0x2;
3665

    
3666
        bochs_bios_init();
3667
#elif defined(TARGET_PPC)
3668
        cpu_x86_init_mmu(env);
3669
        /* allocate ROM */
3670
        //        snprintf(buf, sizeof(buf), "%s/%s", bios_dir, BIOS_FILENAME);
3671
        snprintf(buf, sizeof(buf), "%s", BIOS_FILENAME);
3672
        printf("load BIOS at %p\n", phys_ram_base + 0x000f0000);
3673
        ret = load_image(buf, phys_ram_base + 0x000f0000);
3674
        if (ret != 0x10000) {
3675
            fprintf(stderr, "qemu: could not load PPC bios '%s' (%d)\n%m\n",
3676
                    buf, ret);
3677
            exit(1);
3678
        }
3679
#endif
3680
    }
3681

    
3682
    /* terminal init */
3683
    if (nographic) {
3684
        dumb_display_init(ds);
3685
    } else {
3686
#ifdef CONFIG_SDL
3687
        sdl_display_init(ds);
3688
#else
3689
        dumb_display_init(ds);
3690
#endif
3691
    }
3692
    /* init basic PC hardware */
3693
    register_ioport_write(0x80, 1, ioport80_write, 1);
3694

    
3695
    vga_initialize(ds, phys_ram_base + phys_ram_size, phys_ram_size, 
3696
             vga_ram_size);
3697
#if defined (TARGET_I386)
3698
    cmos_init();
3699
#endif
3700
    pic_init();
3701
    pit_init();
3702
    serial_init();
3703
#if defined (TARGET_I386)
3704
    ne2000_init();
3705
#endif
3706
    ide_init();
3707
    kbd_init();
3708
    AUD_init();
3709
    DMA_init();
3710
#if defined (TARGET_I386)
3711
    SB16_init();
3712
#endif
3713
#if defined (TARGET_PPC)
3714
    PPC_end_init();
3715
#endif
3716
    fdctrl_register((unsigned char **)fd_filename, snapshot, boot_device);
3717
    /* setup cpu signal handlers for MMU / self modifying code handling */
3718
    sigfillset(&act.sa_mask);
3719
    act.sa_flags = SA_SIGINFO;
3720
#if !defined(CONFIG_SOFTMMU)
3721
    act.sa_sigaction = host_segv_handler;
3722
    sigaction(SIGSEGV, &act, NULL);
3723
    sigaction(SIGBUS, &act, NULL);
3724
#endif
3725

    
3726
    act.sa_sigaction = host_alarm_handler;
3727
    sigaction(SIGALRM, &act, NULL);
3728

    
3729
    itv.it_interval.tv_sec = 0;
3730
    itv.it_interval.tv_usec = 1000;
3731
    itv.it_value.tv_sec = 0;
3732
    itv.it_value.tv_usec = 10 * 1000;
3733
    setitimer(ITIMER_REAL, &itv, NULL);
3734
    /* we probe the tick duration of the kernel to inform the user if
3735
       the emulated kernel requested a too high timer frequency */
3736
    getitimer(ITIMER_REAL, &itv);
3737
    timer_ms = itv.it_interval.tv_usec / 1000;
3738
    pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) / 
3739
        1000000;
3740

    
3741
    if (use_gdbstub) {
3742
        cpu_gdbstub(NULL, main_loop, gdbstub_port);
3743
    } else {
3744
        main_loop(NULL);
3745
    }
3746
    return 0;
3747
}