Palacios Public Git Repository

To checkout Palacios execute

  git clone http://v3vee.org/palacios/palacios.web/palacios.git
This will give you the master branch. You probably want the devel branch or one of the release branches. To switch to the devel branch, simply execute
  cd palacios
  git checkout --track -b devel origin/devel
The other branches are similar.


updates to the PCI configuration for the southbridge and northbridge
[palacios.git] / palacios / src / devices / ide.c
1 /* 
2  * This file is part of the Palacios Virtual Machine Monitor developed
3  * by the V3VEE Project with funding from the United States National 
4  * Science Foundation and the Department of Energy.  
5  *
6  * The V3VEE Project is a joint project between Northwestern University
7  * and the University of New Mexico.  You can find out more at 
8  * http://www.v3vee.org
9  *
10  * Copyright (c) 2008, Jack Lange <jarusl@cs.northwestern.edu> 
11  * Copyright (c) 2008, The V3VEE Project <http://www.v3vee.org> 
12  * All rights reserved.
13  *
14  * Author: Jack Lange <jarusl@cs.northwestern.edu>
15  *
16  * This is free software.  You are permitted to use,
17  * redistribute, and modify it as specified in the file "V3VEE_LICENSE".
18  */
19
20 #include <palacios/vmm.h>
21 #include <palacios/vm_guest_mem.h>
22 #include <devices/ide.h>
23 #include <devices/pci.h>
24 #include <devices/southbridge.h>
25 #include "ide-types.h"
26 #include "atapi-types.h"
27
28 #ifndef DEBUG_IDE
29 #undef PrintDebug
30 #define PrintDebug(fmt, args...)
31 #endif
32
33 #define PRI_DEFAULT_IRQ 14
34 #define SEC_DEFAULT_IRQ 15
35
36
37 #define PRI_DATA_PORT         0x1f0
38 #define PRI_FEATURES_PORT     0x1f1
39 #define PRI_SECT_CNT_PORT     0x1f2
40 #define PRI_SECT_NUM_PORT     0x1f3
41 #define PRI_CYL_LOW_PORT      0x1f4
42 #define PRI_CYL_HIGH_PORT     0x1f5
43 #define PRI_DRV_SEL_PORT      0x1f6
44 #define PRI_CMD_PORT          0x1f7
45 #define PRI_CTRL_PORT         0x3f6
46 #define PRI_ADDR_REG_PORT     0x3f7
47
48 #define SEC_DATA_PORT         0x170
49 #define SEC_FEATURES_PORT     0x171
50 #define SEC_SECT_CNT_PORT     0x172
51 #define SEC_SECT_NUM_PORT     0x173
52 #define SEC_CYL_LOW_PORT      0x174
53 #define SEC_CYL_HIGH_PORT     0x175
54 #define SEC_DRV_SEL_PORT      0x176
55 #define SEC_CMD_PORT          0x177
56 #define SEC_CTRL_PORT         0x376
57 #define SEC_ADDR_REG_PORT     0x377
58
59
60 #define PRI_DEFAULT_DMA_PORT 0xc000
61 #define SEC_DEFAULT_DMA_PORT 0xc008
62
63 #define DATA_BUFFER_SIZE 2048
64
65 static const char * ide_pri_port_strs[] = {"PRI_DATA", "PRI_FEATURES", "PRI_SECT_CNT", "PRI_SECT_NUM", 
66                                           "PRI_CYL_LOW", "PRI_CYL_HIGH", "PRI_DRV_SEL", "PRI_CMD",
67                                            "PRI_CTRL", "PRI_ADDR_REG"};
68
69
70 static const char * ide_sec_port_strs[] = {"SEC_DATA", "SEC_FEATURES", "SEC_SECT_CNT", "SEC_SECT_NUM", 
71                                           "SEC_CYL_LOW", "SEC_CYL_HIGH", "SEC_DRV_SEL", "SEC_CMD",
72                                            "SEC_CTRL", "SEC_ADDR_REG"};
73
74 static const char * ide_dma_port_strs[] = {"DMA_CMD", NULL, "DMA_STATUS", NULL,
75                                            "DMA_PRD0", "DMA_PRD1", "DMA_PRD2", "DMA_PRD3"};
76
77
78
79 static inline const char * io_port_to_str(uint16_t port) {
80     if ((port >= PRI_DATA_PORT) && (port <= PRI_CMD_PORT)) {
81         return ide_pri_port_strs[port - PRI_DATA_PORT];
82     } else if ((port >= SEC_DATA_PORT) && (port <= SEC_CMD_PORT)) {
83         return ide_sec_port_strs[port - SEC_DATA_PORT];
84     } else if ((port == PRI_CTRL_PORT) || (port == PRI_ADDR_REG_PORT)) {
85         return ide_pri_port_strs[port - PRI_CTRL_PORT + 8];
86     } else if ((port == SEC_CTRL_PORT) || (port == SEC_ADDR_REG_PORT)) {
87         return ide_sec_port_strs[port - SEC_CTRL_PORT + 8];
88     } 
89     return NULL;
90 }
91
92
93 static inline const char * dma_port_to_str(uint16_t port) {
94     return ide_dma_port_strs[port & 0x7];
95 }
96
97
98 static const char * ide_dev_type_strs[] = {"NONE", "HARDDISK", "CDROM" };
99
100
101 static inline const char * device_type_to_str(v3_ide_dev_type_t type) {
102     if (type > 2) {
103         return NULL;
104     }
105
106     return ide_dev_type_strs[type];
107 }
108
109
110
111 struct ide_cd_state {
112     struct atapi_sense_data sense;
113
114     uint8_t atapi_cmd;
115     struct atapi_error_recovery err_recovery;
116 };
117
118 struct ide_hd_state {
119     int accessed;
120
121     /* this is the multiple sector transfer size as configured for read/write multiple sectors*/
122     uint_t mult_sector_num;
123
124     /* This is the current op sector size:
125      * for multiple sector ops this equals mult_sector_num
126      * for standard ops this equals 1
127      */
128     uint_t cur_sector_num;
129 };
130
131 struct ide_drive {
132     // Command Registers
133
134     v3_ide_dev_type_t drive_type;
135
136     union {
137         struct v3_ide_cd_ops * cd_ops;
138         struct v3_ide_hd_ops * hd_ops;
139     };
140
141
142     union {
143         struct ide_cd_state cd_state;
144         struct ide_hd_state hd_state;
145     };
146
147     char model[41];
148
149     // Where we are in the data transfer
150     uint_t transfer_index;
151
152     // the length of a transfer
153     // calculated for easy access
154     uint_t transfer_length;
155
156     uint64_t current_lba;
157
158     // We have a local data buffer that we use for IO port accesses
159     uint8_t data_buf[DATA_BUFFER_SIZE];
160
161
162     void * private_data;
163     
164     union {
165         uint8_t sector_count;             // 0x1f2,0x172
166         struct atapi_irq_flags irq_flags;
167     } __attribute__((packed));
168
169     union {
170         uint8_t sector_num;               // 0x1f3,0x173
171         uint8_t lba0;
172     } __attribute__((packed));
173
174     union {
175         uint16_t cylinder;
176         uint16_t lba12;
177         
178         struct {
179             uint8_t cylinder_low;       // 0x1f4,0x174
180             uint8_t cylinder_high;      // 0x1f5,0x175
181         } __attribute__((packed));
182         
183         struct {
184             uint8_t lba1;
185             uint8_t lba2;
186         } __attribute__((packed));
187         
188         
189         // The transfer length requested by the CPU 
190         uint16_t req_len;
191     } __attribute__((packed));
192
193 };
194
195
196
197 struct ide_channel {
198     struct ide_drive drives[2];
199
200     // Command Registers
201     struct ide_error_reg error_reg;     // [read] 0x1f1,0x171
202
203     struct ide_features_reg features;
204
205     struct ide_drive_head_reg drive_head; // 0x1f6,0x176
206
207     struct ide_status_reg status;       // [read] 0x1f7,0x177
208     uint8_t cmd_reg;                // [write] 0x1f7,0x177
209
210     int irq; // this is temporary until we add PCI support
211
212     // Control Registers
213     struct ide_ctrl_reg ctrl_reg; // [write] 0x3f6,0x376
214
215     struct ide_dma_cmd_reg dma_cmd;
216     struct ide_dma_status_reg dma_status;
217     uint32_t dma_prd_addr;
218     uint_t dma_tbl_index;
219 };
220
221
222
223 struct ide_internal {
224     struct ide_channel channels[2];
225
226     struct v3_southbridge * southbridge;
227     struct vm_device * pci_bus;
228
229     struct pci_device * ide_pci;
230 };
231
232
233
234
235
236 /* Utility functions */
237
238 static inline uint16_t be_to_le_16(const uint16_t val) {
239     uint8_t * buf = (uint8_t *)&val;
240     return (buf[0] << 8) | (buf[1]) ;
241 }
242
243 static inline uint16_t le_to_be_16(const uint16_t val) {
244     return be_to_le_16(val);
245 }
246
247
248 static inline uint32_t be_to_le_32(const uint32_t val) {
249     uint8_t * buf = (uint8_t *)&val;
250     return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
251 }
252
253 static inline uint32_t le_to_be_32(const uint32_t val) {
254     return be_to_le_32(val);
255 }
256
257
258 static inline int get_channel_index(ushort_t port) {
259     if (((port & 0xfff8) == 0x1f0) ||
260         ((port & 0xfffe) == 0x3f6) || 
261         ((port & 0xfff8) == 0xc000)) {
262         return 0;
263     } else if (((port & 0xfff8) == 0x170) ||
264                ((port & 0xfffe) == 0x376) ||
265                ((port & 0xfff8) == 0xc008)) {
266         return 1;
267     }
268
269     return -1;
270 }
271
272 static inline struct ide_channel * get_selected_channel(struct ide_internal * ide, ushort_t port) {
273     int channel_idx = get_channel_index(port);    
274     return &(ide->channels[channel_idx]);
275 }
276
277 static inline struct ide_drive * get_selected_drive(struct ide_channel * channel) {
278     return &(channel->drives[channel->drive_head.drive_sel]);
279 }
280
281
282 static inline int is_lba_enabled(struct ide_channel * channel) {
283     return channel->drive_head.lba_mode;
284 }
285
286
287 /* Drive Commands */
288 static void ide_raise_irq(struct vm_device * dev, struct ide_channel * channel) {
289     if (channel->ctrl_reg.irq_disable == 0) {
290         PrintDebug("Raising IDE Interrupt %d\n", channel->irq);
291         channel->dma_status.int_gen = 1;
292         v3_raise_irq(dev->vm, channel->irq);
293     }
294 }
295
296
297 static void drive_reset(struct ide_drive * drive) {
298     drive->sector_count = 0x01;
299     drive->sector_num = 0x01;
300
301     PrintDebug("Resetting drive %s\n", drive->model);
302     
303     if (drive->drive_type == IDE_CDROM) {
304         drive->cylinder = 0xeb14;
305     } else {
306         drive->cylinder = 0x0000;
307         //drive->hd_state.accessed = 0;
308     }
309
310
311     memset(drive->data_buf, 0, sizeof(drive->data_buf));
312     drive->transfer_index = 0;
313
314     // Send the reset signal to the connected device callbacks
315     //     channel->drives[0].reset();
316     //    channel->drives[1].reset();
317 }
318
319 static void channel_reset(struct ide_channel * channel) {
320     
321     // set busy and seek complete flags
322     channel->status.val = 0x90;
323
324     // Clear errors
325     channel->error_reg.val = 0x01;
326
327     // clear commands
328     channel->cmd_reg = 0x00;
329
330     channel->ctrl_reg.irq_disable = 0;
331 }
332
333 static void channel_reset_complete(struct ide_channel * channel) {
334     channel->status.busy = 0;
335     channel->status.ready = 1;
336
337     channel->drive_head.head_num = 0;    
338     
339     drive_reset(&(channel->drives[0]));
340     drive_reset(&(channel->drives[1]));
341 }
342
343
344 static void ide_abort_command(struct vm_device * dev, struct ide_channel * channel) {
345     channel->status.val = 0x41; // Error + ready
346     channel->error_reg.val = 0x04; // No idea...
347
348     ide_raise_irq(dev, channel);
349 }
350
351
352
353
354
355
356 /* ATAPI functions */
357 #include "atapi.h"
358
359 /* ATA functions */
360 #include "ata.h"
361
362
363
364 /* IO Operations */
365 static int dma_read(struct vm_device * dev, struct ide_channel * channel) {
366     struct ide_drive * drive = get_selected_drive(channel);
367     struct ide_dma_prd prd_entry;
368     uint32_t prd_entry_addr = channel->dma_prd_addr + (sizeof(struct ide_dma_prd) * channel->dma_tbl_index);
369     int ret;
370
371     PrintDebug("PRD table address = %x\n", channel->dma_prd_addr);
372
373     ret = read_guest_pa_memory(dev->vm, prd_entry_addr, sizeof(struct ide_dma_prd), (void *)&prd_entry);
374
375     if (ret != sizeof(struct ide_dma_prd)) {
376         PrintError("Could not read PRD\n");
377         return -1;
378     }
379
380     PrintDebug("PRD Addr: %x, PDR Len: %d, EOT: %d\n", prd_entry.base_addr, prd_entry.size, prd_entry.end_of_table);
381
382     ret = write_guest_pa_memory(dev->vm, prd_entry.base_addr, prd_entry.size, drive->data_buf); 
383
384     if (ret != prd_entry.size) {
385         PrintError("Failed to copy data into guest memory... (ret=%d)\n", ret);
386         return -1;
387     }
388
389
390
391     /*
392       drive->irq_flags.io_dir = 1;
393       drive->irq_flags.c_d = 1;
394       drive->irq_flags.rel = 0;
395     */
396
397
398     // set DMA status
399
400     if (prd_entry.end_of_table) {
401         channel->dma_status.active = 0;
402         channel->dma_status.err = 0;
403         channel->dma_status.int_gen = 1;
404
405         channel->status.busy = 0;
406         channel->status.ready = 1;
407         channel->status.data_req = 0;
408         channel->status.error = 0;
409         channel->status.seek_complete = 1;
410     }
411
412     ide_raise_irq(dev, channel);
413
414     return 0;
415 }
416
417
418 static int dma_write(struct vm_device * dev, struct ide_channel * channel) {
419     // unsupported
420     PrintError("DMA writes currently not supported\n");
421     return -1;
422 }
423
424
425
426 #define DMA_CMD_PORT      0x00
427 #define DMA_STATUS_PORT   0x02
428 #define DMA_PRD_PORT0     0x04
429 #define DMA_PRD_PORT1     0x05
430 #define DMA_PRD_PORT2     0x06
431 #define DMA_PRD_PORT3     0x07
432
433 #define DMA_CHANNEL_FLAG  0x08
434
435 static int write_dma_port(ushort_t port, void * src, uint_t length, struct vm_device * dev) {
436     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
437     uint16_t port_offset = port & (DMA_CHANNEL_FLAG - 1);
438     uint_t channel_flag = (port & DMA_CHANNEL_FLAG) >> 3;
439     struct ide_channel * channel = &(ide->channels[channel_flag]);
440
441     switch (port_offset) {
442         case DMA_CMD_PORT:
443             channel->dma_cmd.val = *(uint8_t *)src;
444
445             if (channel->dma_cmd.start == 0) {
446                 channel->dma_tbl_index = 0;
447             } else {
448                 channel->dma_status.active = 1;
449
450                 if (channel->dma_cmd.read == 1) {
451                     // DMA Read
452                     if (dma_read(dev, channel) == -1) {
453                         PrintError("Failed DMA Read\n");
454                         return -1;
455                     }
456                 } else {
457                     // DMA write
458                     if (dma_write(dev, channel) == -1) {
459                         PrintError("Failed DMA Write\n");
460                         return -1;
461                     }
462                 }
463
464                 channel->dma_cmd.val &= 0x09;
465             }
466
467             break;
468             
469         case DMA_STATUS_PORT:
470             if (length != 1) {
471                 PrintError("Invalid read length for DMA status port\n");
472                 return -1;
473             }
474
475             channel->dma_status.val = *(uint8_t *)src;
476             break;
477             
478         case DMA_PRD_PORT0:
479         case DMA_PRD_PORT1:
480         case DMA_PRD_PORT2:
481         case DMA_PRD_PORT3: {
482             uint_t addr_index = port_offset & 0x3;
483             uint8_t * addr_buf = (uint8_t *)&(channel->dma_prd_addr);
484             int i = 0;
485
486             if (addr_index + length > 4) {
487                 PrintError("DMA Port space overrun port=%x len=%d\n", port_offset, length);
488                 return -1;
489             }
490
491             for (i = 0; i < length; i++) {
492                 addr_buf[addr_index + i] = *((uint8_t *)src + i);
493             }
494
495             PrintDebug("Writing PRD Port %x (val=%x)\n", port_offset, channel->dma_prd_addr);
496
497             break;
498         }
499         default:
500             PrintError("IDE: Invalid DMA Port (%s)\n", dma_port_to_str(port_offset));
501             return -1;
502     }
503
504     return length;
505 }
506
507
508 static int read_dma_port(ushort_t port, void * dst, uint_t length, struct vm_device * dev) {
509     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
510     uint16_t port_offset = port & (DMA_CHANNEL_FLAG - 1);
511     uint_t channel_flag = (port & DMA_CHANNEL_FLAG) >> 3;
512     struct ide_channel * channel = &(ide->channels[channel_flag]);
513
514     switch (port_offset) {
515         case DMA_CMD_PORT:
516             *(uint8_t *)dst = channel->dma_cmd.val;
517             break;
518
519         case DMA_STATUS_PORT:
520             if (length != 1) {
521                 PrintError("Invalid read length for DMA status port\n");
522                 return -1;
523             }
524
525             *(uint8_t *)dst = channel->dma_status.val;
526             break;
527
528         case DMA_PRD_PORT0:
529         case DMA_PRD_PORT1:
530         case DMA_PRD_PORT2:
531         case DMA_PRD_PORT3: {
532             uint_t addr_index = port_offset & 0x3;
533             uint8_t * addr_buf = (uint8_t *)&(channel->dma_prd_addr);
534             int i = 0;
535
536             if (addr_index + length > 4) {
537                 PrintError("DMA Port space overrun port=%x len=%d\n", port_offset, length);
538                 return -1;
539             }
540
541             for (i = 0; i < length; i++) {
542                 *((uint8_t *)dst + i) = addr_buf[addr_index + i];
543             }
544
545             break;
546         }
547         default:
548             PrintError("IDE: Invalid DMA Port (%s)\n", dma_port_to_str(port_offset));
549             return -1;
550     }
551
552     PrintDebug("\tval=%x\n", *(uint32_t *)dst);
553
554     return length;
555 }
556
557
558
559 static int write_cmd_port(ushort_t port, void * src, uint_t length, struct vm_device * dev) {
560     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
561     struct ide_channel * channel = get_selected_channel(ide, port);
562     struct ide_drive * drive = get_selected_drive(channel);
563
564     if (length != 1) {
565         PrintError("Invalid Write Length on IDE command Port %x\n", port);
566         return -1;
567     }
568
569     PrintDebug("IDE: Writing Command Port %x (%s) (val=%x)\n", port, io_port_to_str(port), *(uint8_t *)src);
570     
571     channel->cmd_reg = *(uint8_t *)src;
572     
573     switch (channel->cmd_reg) {
574
575         case 0xa1: // ATAPI Identify Device Packet
576             if (drive->drive_type != IDE_CDROM) {
577                 drive_reset(drive);
578
579                 // JRL: Should we abort here?
580                 ide_abort_command(dev, channel);
581             } else {
582                 
583                 atapi_identify_device(drive);
584                 
585                 channel->error_reg.val = 0;
586                 channel->status.val = 0x58; // ready, data_req, seek_complete
587             
588                 ide_raise_irq(dev, channel);
589             }
590             break;
591         case 0xec: // Identify Device
592             if (drive->drive_type != IDE_DISK) {
593                 drive_reset(drive);
594
595                 // JRL: Should we abort here?
596                 ide_abort_command(dev, channel);
597             } else {
598                 ata_identify_device(drive);
599
600                 channel->error_reg.val = 0;
601                 channel->status.val = 0x58;
602
603                 ide_raise_irq(dev, channel);
604             }
605             break;
606
607         case 0xa0: // ATAPI Command Packet
608             if (drive->drive_type != IDE_CDROM) {
609                 ide_abort_command(dev, channel);
610             }
611             
612             drive->sector_count = 1;
613
614             channel->status.busy = 0;
615             channel->status.write_fault = 0;
616             channel->status.data_req = 1;
617             channel->status.error = 0;
618
619             // reset the data buffer...
620             drive->transfer_length = ATAPI_PACKET_SIZE;
621             drive->transfer_index = 0;
622
623             break;
624
625         case 0x20: // Read Sectors with Retry
626         case 0x21: // Read Sectors without Retry
627             drive->hd_state.cur_sector_num = 1;
628
629             if (ata_read_sectors(dev, channel) == -1) {
630                 PrintError("Error reading sectors\n");
631                 return -1;
632             }
633             break;
634
635         case 0x24: // Read Sectors Extended
636             drive->hd_state.cur_sector_num = 1;
637
638             if (ata_read_sectors_ext(dev, channel) == -1) {
639                 PrintError("Error reading extended sectors\n");
640                 return -1;
641             }
642             break;
643
644         case 0xc8: // Read DMA with retry
645         case 0xc9: // Read DMA
646             drive->hd_state.cur_sector_num = 1;
647
648             break;
649         case 0xef: // Set Features
650             // Prior to this the features register has been written to. 
651             // This command tells the drive to check if the new value is supported (the value is drive specific)
652             // Common is that bit0=DMA enable
653             // If valid the drive raises an interrupt, if not it aborts.
654
655             // Do some checking here...
656
657             channel->status.busy = 0;
658             channel->status.write_fault = 0;
659             channel->status.error = 0;
660             channel->status.ready = 1;
661             channel->status.seek_complete = 1;
662             
663             ide_raise_irq(dev, channel);
664             break;
665
666         case 0x91:  // Initialize Drive Parameters
667         case 0x10:  // recalibrate?
668             channel->status.error = 0;
669             channel->status.ready = 1;
670             channel->status.seek_complete = 1;
671             ide_raise_irq(dev, channel);
672             break;
673         case 0xc6: { // Set multiple mode (IDE Block mode) 
674             // This makes the drive transfer multiple sectors before generating an interrupt
675             uint32_t tmp_sect_num = drive->sector_num; // GCC SUCKS
676
677             if (tmp_sect_num > MAX_MULT_SECTORS) {
678                 ide_abort_command(dev, channel);
679                 break;
680             }
681
682             if (drive->sector_count == 0) {
683                 drive->hd_state.mult_sector_num= 1;
684             } else {
685                 drive->hd_state.mult_sector_num = drive->sector_count;
686             }
687
688             channel->status.ready = 1;
689             channel->status.error = 0;
690
691             ide_raise_irq(dev, channel);
692
693             break;
694         }
695         case 0xc4:  // read multiple sectors
696             drive->hd_state.cur_sector_num = drive->hd_state.mult_sector_num;
697         default:
698             PrintError("Unimplemented IDE command (%x)\n", channel->cmd_reg);
699             return -1;
700     }
701
702     return length;
703 }
704
705
706 static int write_data_port(ushort_t port, void * src, uint_t length, struct vm_device * dev) {
707     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
708     struct ide_channel * channel = get_selected_channel(ide, port);
709     struct ide_drive * drive = get_selected_drive(channel);
710
711     //    PrintDebug("IDE: Writing Data Port %x (val=%x, len=%d)\n", 
712     //         port, *(uint32_t *)src, length);
713     
714     memcpy(drive->data_buf + drive->transfer_index, src, length);    
715     drive->transfer_index += length;
716
717     // Transfer is complete, dispatch the command
718     if (drive->transfer_index >= drive->transfer_length) {
719         switch (channel->cmd_reg) {
720             case 0x30: // Write Sectors
721                 PrintError("Writing Data not yet implemented\n");
722                 return -1;
723                 
724             case 0xa0: // ATAPI packet command
725                 if (atapi_handle_packet(dev, channel) == -1) {
726                     PrintError("Error handling ATAPI packet\n");
727                     return -1;
728                 }
729                 break;
730             default:
731                 PrintError("Unhandld IDE Command %x\n", channel->cmd_reg);
732                 return -1;
733         }
734     }
735
736     return length;
737 }
738
739
740 static int read_hd_data(uint8_t * dst, uint_t length, struct vm_device * dev, struct ide_channel * channel) {
741     struct ide_drive * drive = get_selected_drive(channel);
742     int data_offset = drive->transfer_index % IDE_SECTOR_SIZE;
743
744
745
746     if (drive->transfer_index >= drive->transfer_length) {
747         PrintError("Buffer overrun... (xfer_len=%d) (cur_idx=%x) (post_idx=%d)\n",
748                    drive->transfer_length, drive->transfer_index,
749                    drive->transfer_index + length);
750         return -1;
751     }
752
753     
754     if ((data_offset == 0) && (drive->transfer_index > 0)) {
755         drive->current_lba++;
756
757         if (ata_read(dev, channel, drive->data_buf, 1) == -1) {
758             PrintError("Could not read next disk sector\n");
759             return -1;
760         }
761     }
762
763     /*
764       PrintDebug("Reading HD Data (Val=%x), (len=%d) (offset=%d)\n", 
765       *(uint32_t *)(drive->data_buf + data_offset), 
766       length, data_offset);
767     */
768     memcpy(dst, drive->data_buf + data_offset, length);
769
770     drive->transfer_index += length;
771
772
773     /* This is the trigger for interrupt injection.
774      * For read single sector commands we interrupt after every sector
775      * For multi sector reads we interrupt only at end of the cluster size (mult_sector_num)
776      * cur_sector_num is configured depending on the operation we are currently running
777      * We also trigger an interrupt if this is the last byte to transfer, regardless of sector count
778      */
779     if (((drive->transfer_index % (IDE_SECTOR_SIZE * drive->hd_state.cur_sector_num)) == 0) || 
780         (drive->transfer_index == drive->transfer_length)) {
781         if (drive->transfer_index < drive->transfer_length) {
782             // An increment is complete, but there is still more data to be transferred...
783             PrintDebug("Integral Complete, still transferring more sectors\n");
784             channel->status.data_req = 1;
785
786             drive->irq_flags.c_d = 0;
787         } else {
788             PrintDebug("Final Sector Transferred\n");
789             // This was the final read of the request
790             channel->status.data_req = 0;
791
792             
793             drive->irq_flags.c_d = 1;
794             drive->irq_flags.rel = 0;
795         }
796
797         channel->status.ready = 1;
798         drive->irq_flags.io_dir = 1;
799         channel->status.busy = 0;
800
801         ide_raise_irq(dev, channel);
802     }
803
804
805     return length;
806 }
807
808
809
810 static int read_cd_data(uint8_t * dst, uint_t length, struct vm_device * dev, struct ide_channel * channel) {
811     struct ide_drive * drive = get_selected_drive(channel);
812     int data_offset = drive->transfer_index % ATAPI_BLOCK_SIZE;
813     int req_offset = drive->transfer_index % drive->req_len;
814     
815     if (drive->cd_state.atapi_cmd != 0x28) {
816         PrintDebug("IDE: Reading CD Data (len=%d) (req_len=%d)\n", length, drive->req_len);
817     }
818
819     if (drive->transfer_index >= drive->transfer_length) {
820         PrintError("Buffer Overrun... (xfer_len=%d) (cur_idx=%d) (post_idx=%d)\n", 
821                    drive->transfer_length, drive->transfer_index, 
822                    drive->transfer_index + length);
823         return -1;
824     }
825
826
827
828     if ((data_offset == 0) && (drive->transfer_index > 0)) {
829         if (atapi_update_data_buf(dev, channel) == -1) {
830             PrintError("Could not update CDROM data buffer\n");
831             return -1;
832         }
833     }
834
835     memcpy(dst, drive->data_buf + data_offset, length);
836     
837     drive->transfer_index += length;
838
839
840     // Should the req_offset be recalculated here?????
841     if ((req_offset == 0) && (drive->transfer_index > 0)) {
842         if (drive->transfer_index < drive->transfer_length) {
843             // An increment is complete, but there is still more data to be transferred...
844             
845             channel->status.data_req = 1;
846
847             drive->irq_flags.c_d = 0;
848
849             // Update the request length in the cylinder regs
850             if (atapi_update_req_len(dev, channel, drive->transfer_length - drive->transfer_index) == -1) {
851                 PrintError("Could not update request length after completed increment\n");
852                 return -1;
853             }
854         } else {
855             // This was the final read of the request
856             channel->status.data_req = 0;
857             channel->status.ready = 1;
858             
859             drive->irq_flags.c_d = 1;
860             drive->irq_flags.rel = 0;
861         }
862
863         drive->irq_flags.io_dir = 1;
864         channel->status.busy = 0;
865
866         ide_raise_irq(dev, channel);
867     }
868
869     return length;
870 }
871
872
873 static int read_drive_id(uint8_t * dst, uint_t length, struct vm_device * dev, struct ide_channel * channel) {
874     struct ide_drive * drive = get_selected_drive(channel);
875
876     channel->status.busy = 0;
877     channel->status.ready = 1;
878     channel->status.write_fault = 0;
879     channel->status.seek_complete = 1;
880     channel->status.corrected = 0;
881     channel->status.error = 0;
882                 
883     
884     memcpy(dst, drive->data_buf + drive->transfer_index, length);
885     drive->transfer_index += length;
886     
887     if (drive->transfer_index >= drive->transfer_length) {
888         channel->status.data_req = 0;
889     }
890     
891     return length;
892 }
893
894
895 static int ide_read_data_port(ushort_t port, void * dst, uint_t length, struct vm_device * dev) {
896     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
897     struct ide_channel * channel = get_selected_channel(ide, port);
898     struct ide_drive * drive = get_selected_drive(channel);
899
900     //    PrintDebug("IDE: Reading Data Port %x (len=%d)\n", port, length);
901
902     if ((channel->cmd_reg == 0xec) ||
903         (channel->cmd_reg == 0xa1)) {
904         return read_drive_id((uint8_t *)dst, length, dev, channel);
905     }
906
907     if (drive->drive_type == IDE_CDROM) {
908         if (read_cd_data((uint8_t *)dst, length, dev, channel) == -1) {
909             PrintError("IDE: Could not read CD Data\n");
910             return -1;
911         }
912     } else if (drive->drive_type == IDE_DISK) {
913         if (read_hd_data((uint8_t *)dst, length, dev, channel) == -1) {
914             PrintError("IDE: Could not read HD Data\n");
915             return -1;
916         }
917     } else {
918         memset((uint8_t *)dst, 0, length);
919     }
920
921     return length;
922 }
923
924 static int write_port_std(ushort_t port, void * src, uint_t length, struct vm_device * dev) {
925     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
926     struct ide_channel * channel = get_selected_channel(ide, port);
927     struct ide_drive * drive = get_selected_drive(channel);
928             
929     if (length != 1) {
930         PrintError("Invalid Write length on IDE port %x\n", port);
931         return -1;
932     }
933
934     PrintDebug("IDE: Writing Standard Port %x (%s) (val=%x)\n", port, io_port_to_str(port), *(uint8_t *)src);
935
936     switch (port) {
937         // reset and interrupt enable
938         case PRI_CTRL_PORT:
939         case SEC_CTRL_PORT: {
940             struct ide_ctrl_reg * tmp_ctrl = (struct ide_ctrl_reg *)src;
941
942             // only reset channel on a 0->1 reset bit transition
943             if ((!channel->ctrl_reg.soft_reset) && (tmp_ctrl->soft_reset)) {
944                 channel_reset(channel);
945             } else if ((channel->ctrl_reg.soft_reset) && (!tmp_ctrl->soft_reset)) {
946                 channel_reset_complete(channel);
947             }
948
949             channel->ctrl_reg.val = tmp_ctrl->val;          
950             break;
951         }
952         case PRI_FEATURES_PORT:
953         case SEC_FEATURES_PORT:
954             channel->features.val = *(uint8_t *)src;
955             break;
956
957         case PRI_SECT_CNT_PORT:
958         case SEC_SECT_CNT_PORT:
959             channel->drives[0].sector_count = *(uint8_t *)src;
960             channel->drives[1].sector_count = *(uint8_t *)src;
961             break;
962
963         case PRI_SECT_NUM_PORT:
964         case SEC_SECT_NUM_PORT:
965             channel->drives[0].sector_num = *(uint8_t *)src;
966             channel->drives[1].sector_num = *(uint8_t *)src;
967             break;
968         case PRI_CYL_LOW_PORT:
969         case SEC_CYL_LOW_PORT:
970             channel->drives[0].cylinder_low = *(uint8_t *)src;
971             channel->drives[1].cylinder_low = *(uint8_t *)src;
972             break;
973
974         case PRI_CYL_HIGH_PORT:
975         case SEC_CYL_HIGH_PORT:
976             channel->drives[0].cylinder_high = *(uint8_t *)src;
977             channel->drives[1].cylinder_high = *(uint8_t *)src;
978             break;
979
980         case PRI_DRV_SEL_PORT:
981         case SEC_DRV_SEL_PORT: {
982             channel->drive_head.val = *(uint8_t *)src;
983             
984             // make sure the reserved bits are ok..
985             // JRL TODO: check with new ramdisk to make sure this is right...
986             channel->drive_head.val |= 0xa0;
987
988             drive = get_selected_drive(channel);
989
990             // Selecting a non-present device is a no-no
991             if (drive->drive_type == IDE_NONE) {
992                 PrintDebug("Attempting to select a non-present drive\n");
993                 channel->error_reg.abort = 1;
994                 channel->status.error = 1;
995             }
996
997             break;
998         }
999         default:
1000             PrintError("IDE: Write to unknown Port %x\n", port);
1001             return -1;
1002     }
1003     return length;
1004 }
1005
1006
1007 static int read_port_std(ushort_t port, void * dst, uint_t length, struct vm_device * dev) {
1008     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
1009     struct ide_channel * channel = get_selected_channel(ide, port);
1010     struct ide_drive * drive = get_selected_drive(channel);
1011     
1012     if (length != 1) {
1013         PrintError("Invalid Read length on IDE port %x\n", port);
1014         return -1;
1015     }
1016     
1017     PrintDebug("IDE: Reading Standard Port %x (%s)\n", port, io_port_to_str(port));
1018
1019     if ((port == PRI_ADDR_REG_PORT) ||
1020         (port == SEC_ADDR_REG_PORT)) {
1021         // unused, return 0xff
1022         *(uint8_t *)dst = 0xff;
1023         return length;
1024     }
1025
1026
1027     // if no drive is present just return 0 + reserved bits
1028     if (drive->drive_type == IDE_NONE) {
1029         if ((port == PRI_DRV_SEL_PORT) ||
1030             (port == SEC_DRV_SEL_PORT)) {
1031             *(uint8_t *)dst = 0xa0;
1032         } else {
1033             *(uint8_t *)dst = 0;
1034         }
1035
1036         return length;
1037     }
1038
1039     switch (port) {
1040
1041         // This is really the error register.
1042         case PRI_FEATURES_PORT:
1043         case SEC_FEATURES_PORT:
1044             *(uint8_t *)dst = channel->error_reg.val;
1045             break;
1046             
1047         case PRI_SECT_CNT_PORT:
1048         case SEC_SECT_CNT_PORT:
1049             *(uint8_t *)dst = drive->sector_count;
1050             break;
1051
1052         case PRI_SECT_NUM_PORT:
1053         case SEC_SECT_NUM_PORT:
1054             *(uint8_t *)dst = drive->sector_num;
1055             break;
1056
1057         case PRI_CYL_LOW_PORT:
1058         case SEC_CYL_LOW_PORT:
1059             *(uint8_t *)dst = drive->cylinder_low;
1060             break;
1061
1062
1063         case PRI_CYL_HIGH_PORT:
1064         case SEC_CYL_HIGH_PORT:
1065             *(uint8_t *)dst = drive->cylinder_high;
1066             break;
1067
1068         case PRI_DRV_SEL_PORT:
1069         case SEC_DRV_SEL_PORT:  // hard disk drive and head register 0x1f6
1070             *(uint8_t *)dst = channel->drive_head.val;
1071             break;
1072
1073         case PRI_CTRL_PORT:
1074         case SEC_CTRL_PORT:
1075         case PRI_CMD_PORT:
1076         case SEC_CMD_PORT:
1077             // Something about lowering interrupts here....
1078             *(uint8_t *)dst = channel->status.val;
1079             break;
1080
1081         default:
1082             PrintError("Invalid Port: %x\n", port);
1083             return -1;
1084     }
1085
1086     PrintDebug("\tVal=%x\n", *(uint8_t *)dst);
1087
1088     return length;
1089 }
1090
1091
1092
1093 static void init_drive(struct ide_drive * drive) {
1094
1095     drive->sector_count = 0x01;
1096     drive->sector_num = 0x01;
1097     drive->cylinder = 0x0000;
1098
1099     drive->drive_type = IDE_NONE;
1100
1101     memset(drive->model, 0, sizeof(drive->model));
1102
1103     drive->transfer_index = 0;
1104     drive->transfer_length = 0;
1105     memset(drive->data_buf, 0, sizeof(drive->data_buf));
1106
1107
1108     drive->private_data = NULL;
1109     drive->cd_ops = NULL;
1110 }
1111
1112 static void init_channel(struct ide_channel * channel) {
1113     int i = 0;
1114
1115     channel->error_reg.val = 0x01;
1116     channel->drive_head.val = 0x00;
1117     channel->status.val = 0x00;
1118     channel->cmd_reg = 0x00;
1119     channel->ctrl_reg.val = 0x08;
1120
1121
1122     channel->dma_cmd.val = 0;
1123     channel->dma_status.val = 0;
1124     channel->dma_prd_addr = 0;
1125     channel->dma_tbl_index = 0;
1126
1127     for (i = 0; i < 2; i++) {
1128         init_drive(&(channel->drives[i]));
1129     }
1130
1131 }
1132
1133
1134 static int pci_config_update(struct pci_device * pci_dev, uint_t reg_num, int length) {
1135     PrintDebug("PCI Config Update\n");
1136     PrintDebug("\t\tInterupt register (Dev=%s), irq=%d\n", pci_dev->name, pci_dev->config_header.intr_line);
1137
1138     return 0;
1139 }
1140
1141 static int init_ide_state(struct vm_device * dev) {
1142     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
1143     int i;
1144
1145     /* 
1146      * Check if the PIIX 3 actually represents both IDE channels in a single PCI entry 
1147      */
1148
1149     for (i = 0; i < 1; i++) {
1150         init_channel(&(ide->channels[i]));
1151
1152         // JRL: this is a terrible hack...
1153         ide->channels[i].irq = PRI_DEFAULT_IRQ + i;
1154     }
1155
1156
1157     return 0;
1158 }
1159
1160
1161
1162 static int init_ide(struct vm_device * dev) {
1163     struct ide_internal * ide = (struct ide_internal *)(dev->private_data);
1164
1165     PrintDebug("IDE: Initializing IDE\n");
1166
1167     if (init_ide_state(dev) == -1) {
1168         PrintError("Failed to initialize IDE state\n");
1169         return -1;
1170     }
1171
1172
1173     v3_dev_hook_io(dev, PRI_DATA_PORT, 
1174                    &ide_read_data_port, &write_data_port);
1175     v3_dev_hook_io(dev, PRI_FEATURES_PORT, 
1176                    &read_port_std, &write_port_std);
1177     v3_dev_hook_io(dev, PRI_SECT_CNT_PORT, 
1178                    &read_port_std, &write_port_std);
1179     v3_dev_hook_io(dev, PRI_SECT_NUM_PORT, 
1180                    &read_port_std, &write_port_std);
1181     v3_dev_hook_io(dev, PRI_CYL_LOW_PORT, 
1182                    &read_port_std, &write_port_std);
1183     v3_dev_hook_io(dev, PRI_CYL_HIGH_PORT, 
1184                    &read_port_std, &write_port_std);
1185     v3_dev_hook_io(dev, PRI_DRV_SEL_PORT, 
1186                    &read_port_std, &write_port_std);
1187     v3_dev_hook_io(dev, PRI_CMD_PORT, 
1188                    &read_port_std, &write_cmd_port);
1189
1190     v3_dev_hook_io(dev, SEC_DATA_PORT, 
1191                    &ide_read_data_port, &write_data_port);
1192     v3_dev_hook_io(dev, SEC_FEATURES_PORT, 
1193                    &read_port_std, &write_port_std);
1194     v3_dev_hook_io(dev, SEC_SECT_CNT_PORT, 
1195                    &read_port_std, &write_port_std);
1196     v3_dev_hook_io(dev, SEC_SECT_NUM_PORT, 
1197                    &read_port_std, &write_port_std);
1198     v3_dev_hook_io(dev, SEC_CYL_LOW_PORT, 
1199                    &read_port_std, &write_port_std);
1200     v3_dev_hook_io(dev, SEC_CYL_HIGH_PORT, 
1201                    &read_port_std, &write_port_std);
1202     v3_dev_hook_io(dev, SEC_DRV_SEL_PORT, 
1203                    &read_port_std, &write_port_std);
1204     v3_dev_hook_io(dev, SEC_CMD_PORT, 
1205                    &read_port_std, &write_cmd_port);
1206   
1207
1208     v3_dev_hook_io(dev, PRI_CTRL_PORT, 
1209                    &read_port_std, &write_port_std);
1210
1211     v3_dev_hook_io(dev, SEC_CTRL_PORT, 
1212                    &read_port_std, &write_port_std);
1213   
1214
1215     v3_dev_hook_io(dev, SEC_ADDR_REG_PORT, 
1216                    &read_port_std, &write_port_std);
1217
1218     v3_dev_hook_io(dev, PRI_ADDR_REG_PORT, 
1219                    &read_port_std, &write_port_std);
1220
1221
1222
1223
1224     if (ide->pci_bus) {
1225         struct v3_pci_bar bars[6];
1226         struct v3_southbridge * southbridge = (struct v3_southbridge *)(ide->southbridge);
1227         struct pci_device * sb_pci = (struct pci_device *)(southbridge->southbridge_pci);
1228         struct pci_device * pci_dev = NULL;
1229         int i;
1230
1231         for (i = 0; i < 6; i++) {
1232             bars[i].type = PCI_BAR_NONE;
1233         }
1234
1235         bars[4].type = PCI_BAR_IO;
1236         bars[4].default_base_port = PRI_DEFAULT_DMA_PORT;
1237         bars[4].num_ports = 16;
1238
1239         bars[4].io_read = read_dma_port;
1240         bars[4].io_write = write_dma_port;
1241         
1242         pci_dev = v3_pci_register_device(ide->pci_bus, PCI_STD_DEVICE, 0, sb_pci->dev_num, 1, 
1243                                          "PIIX3_IDE", bars,
1244                                          pci_config_update, NULL, NULL, dev);
1245
1246         if (pci_dev == NULL) {
1247             PrintError("Failed to register IDE BUS %d with PCI\n", i); 
1248             return -1;
1249         }
1250
1251         /* This is for CMD646 devices 
1252            pci_dev->config_header.vendor_id = 0x1095;
1253            pci_dev->config_header.device_id = 0x0646;
1254            pci_dev->config_header.revision = 0x8f07;
1255         */
1256
1257         pci_dev->config_header.vendor_id = 0x8086;
1258         pci_dev->config_header.device_id = 0x7010;
1259         pci_dev->config_header.revision = 0x8000;
1260
1261         pci_dev->config_header.subclass = 0x01;
1262         pci_dev->config_header.class = 0x01;
1263
1264         pci_dev->config_header.command = 0;
1265         pci_dev->config_header.status = 0x0280;
1266     }
1267
1268     return 0;
1269 }
1270
1271
1272 static int deinit_ide(struct vm_device * dev) {
1273     // unhook io ports....
1274     // deregister from PCI?
1275     return 0;
1276 }
1277
1278
1279 static struct vm_device_ops dev_ops = {
1280     .init = init_ide,
1281     .deinit = deinit_ide,
1282     .reset = NULL,
1283     .start = NULL,
1284     .stop = NULL,
1285 };
1286
1287
1288 struct vm_device *  v3_create_ide(struct vm_device * pci_bus, struct vm_device * southbridge_dev) {
1289     struct ide_internal * ide  = (struct ide_internal *)V3_Malloc(sizeof(struct ide_internal));  
1290     struct vm_device * device = v3_create_device("IDE", &dev_ops, ide);
1291
1292     ide->pci_bus = pci_bus;
1293     ide->southbridge = (struct v3_southbridge *)(southbridge_dev->private_data);
1294
1295     PrintDebug("IDE: Creating IDE bus x 2\n");
1296
1297     return device;
1298 }
1299
1300
1301
1302
1303
1304 int v3_ide_register_cdrom(struct vm_device * ide_dev, 
1305                           uint_t bus_num, 
1306                           uint_t drive_num,
1307                           char * dev_name, 
1308                           struct v3_ide_cd_ops * ops, 
1309                           void * private_data) {
1310
1311     struct ide_internal * ide  = (struct ide_internal *)(ide_dev->private_data);  
1312     struct ide_channel * channel = NULL;
1313     struct ide_drive * drive = NULL;
1314
1315     V3_ASSERT((bus_num >= 0) && (bus_num < 2));
1316     V3_ASSERT((drive_num >= 0) && (drive_num < 2));
1317
1318     channel = &(ide->channels[bus_num]);
1319     drive = &(channel->drives[drive_num]);
1320     
1321     if (drive->drive_type != IDE_NONE) {
1322         PrintError("Device slot (bus=%d, drive=%d) already occupied\n", bus_num, drive_num);
1323         return -1;
1324     }
1325
1326     strncpy(drive->model, dev_name, sizeof(drive->model) - 1);
1327
1328     while (strlen((char *)(drive->model)) < 40) {
1329         strcat((char*)(drive->model), " ");
1330     }
1331
1332
1333     drive->drive_type = IDE_CDROM;
1334
1335     drive->cd_ops = ops;
1336
1337     drive->private_data = private_data;
1338
1339     return 0;
1340 }
1341
1342
1343 int v3_ide_register_harddisk(struct vm_device * ide_dev, 
1344                              uint_t bus_num, 
1345                              uint_t drive_num, 
1346                              char * dev_name, 
1347                              struct v3_ide_hd_ops * ops, 
1348                              void * private_data) {
1349
1350     struct ide_internal * ide  = (struct ide_internal *)(ide_dev->private_data);  
1351     struct ide_channel * channel = NULL;
1352     struct ide_drive * drive = NULL;
1353
1354     V3_ASSERT((bus_num >= 0) && (bus_num < 2));
1355     V3_ASSERT((drive_num >= 0) && (drive_num < 2));
1356
1357     channel = &(ide->channels[bus_num]);
1358     drive = &(channel->drives[drive_num]);
1359     
1360     if (drive->drive_type != IDE_NONE) {
1361         PrintError("Device slot (bus=%d, drive=%d) already occupied\n", bus_num, drive_num);
1362         return -1;
1363     }
1364
1365     strncpy(drive->model, dev_name, sizeof(drive->model) - 1);
1366
1367     drive->drive_type = IDE_DISK;
1368
1369     drive->hd_state.accessed = 0;
1370     drive->hd_state.mult_sector_num = 1;
1371
1372     drive->hd_ops = ops;
1373
1374     drive->private_data = private_data;
1375
1376     return 0;
1377 }
1378
1379
1380