Dynamically allocate each drive_g with malloc_fseg().
[seabios.git] / src / ata.c
1 // Low level ATA disk access
2 //
3 // Copyright (C) 2008,2009  Kevin O'Connor <kevin@koconnor.net>
4 // Copyright (C) 2002  MandrakeSoft S.A.
5 //
6 // This file may be distributed under the terms of the GNU LGPLv3 license.
7
8 #include "types.h" // u8
9 #include "ioport.h" // inb
10 #include "util.h" // dprintf
11 #include "cmos.h" // inb_cmos
12 #include "pic.h" // enable_hwirq
13 #include "biosvar.h" // GET_EBDA
14 #include "pci.h" // foreachpci
15 #include "pci_ids.h" // PCI_CLASS_STORAGE_OTHER
16 #include "pci_regs.h" // PCI_INTERRUPT_LINE
17 #include "boot.h" // add_bcv_hd
18 #include "disk.h" // struct ata_s
19 #include "ata.h" // ATA_CB_STAT
20 #include "blockcmd.h" // CDB_CMD_READ_10
21
22 #define IDE_TIMEOUT 32000 //32 seconds max for IDE ops
23
24 struct ata_channel_s ATA_channels[CONFIG_MAX_ATA_INTERFACES] VAR16VISIBLE;
25
26
27 /****************************************************************
28  * Helper functions
29  ****************************************************************/
30
31 // Wait for the specified ide state
32 static inline int
33 await_ide(u8 mask, u8 flags, u16 base, u16 timeout)
34 {
35     u64 end = calc_future_tsc(timeout);
36     for (;;) {
37         u8 status = inb(base+ATA_CB_STAT);
38         if ((status & mask) == flags)
39             return status;
40         if (check_time(end)) {
41             warn_timeout();
42             return -1;
43         }
44         yield();
45     }
46 }
47
48 // Wait for the device to be not-busy.
49 static int
50 await_not_bsy(u16 base)
51 {
52     return await_ide(ATA_CB_STAT_BSY, 0, base, IDE_TIMEOUT);
53 }
54
55 // Wait for the device to be ready.
56 static int
57 await_rdy(u16 base)
58 {
59     return await_ide(ATA_CB_STAT_RDY, ATA_CB_STAT_RDY, base, IDE_TIMEOUT);
60 }
61
62 // Wait for ide state - pauses for one ata cycle first.
63 static inline int
64 pause_await_not_bsy(u16 iobase1, u16 iobase2)
65 {
66     // Wait one PIO transfer cycle.
67     inb(iobase2 + ATA_CB_ASTAT);
68
69     return await_not_bsy(iobase1);
70 }
71
72 // Wait for ide state - pause for 400ns first.
73 static inline int
74 ndelay_await_not_bsy(u16 iobase1)
75 {
76     ndelay(400);
77     return await_not_bsy(iobase1);
78 }
79
80 // Reset a drive
81 static void
82 ata_reset(struct drive_s *drive_g)
83 {
84     u8 ataid = GET_GLOBAL(drive_g->cntl_id);
85     u8 channel = ataid / 2;
86     u8 slave = ataid % 2;
87     u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
88     u16 iobase2 = GET_GLOBAL(ATA_channels[channel].iobase2);
89
90     dprintf(6, "ata_reset drive=%p\n", drive_g);
91     // Pulse SRST
92     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN | ATA_CB_DC_SRST, iobase2+ATA_CB_DC);
93     udelay(5);
94     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2+ATA_CB_DC);
95     msleep(2);
96
97     // wait for device to become not busy.
98     int status = await_not_bsy(iobase1);
99     if (status < 0)
100         goto done;
101     if (slave) {
102         // Change device.
103         u64 end = calc_future_tsc(IDE_TIMEOUT);
104         for (;;) {
105             outb(ATA_CB_DH_DEV1, iobase1 + ATA_CB_DH);
106             status = ndelay_await_not_bsy(iobase1);
107             if (status < 0)
108                 goto done;
109             if (inb(iobase1 + ATA_CB_DH) == ATA_CB_DH_DEV1)
110                 break;
111             // Change drive request failed to take effect - retry.
112             if (check_time(end)) {
113                 warn_timeout();
114                 goto done;
115             }
116         }
117     } else {
118         // QEMU doesn't reset dh on reset, so set it explicitly.
119         outb(ATA_CB_DH_DEV0, iobase1 + ATA_CB_DH);
120     }
121
122     // On a user-reset request, wait for RDY if it is an ATA device.
123     u8 type=GET_GLOBAL(drive_g->type);
124     if (type == DTYPE_ATA)
125         status = await_rdy(iobase1);
126
127 done:
128     // Enable interrupts
129     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
130
131     dprintf(6, "ata_reset exit status=%x\n", status);
132 }
133
134 // Check for drive RDY for 16bit interface command.
135 static int
136 isready(struct drive_s *drive_g)
137 {
138     // Read the status from controller
139     u8 ataid = GET_GLOBAL(drive_g->cntl_id);
140     u8 channel = ataid / 2;
141     u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
142     u8 status = inb(iobase1 + ATA_CB_STAT);
143     if ((status & (ATA_CB_STAT_BSY|ATA_CB_STAT_RDY)) == ATA_CB_STAT_RDY)
144         return DISK_RET_SUCCESS;
145     return DISK_RET_ENOTREADY;
146 }
147
148 // Default 16bit command demuxer for ATA and ATAPI devices.
149 static int
150 process_ata_misc_op(struct disk_op_s *op)
151 {
152     if (!CONFIG_ATA)
153         return 0;
154
155     switch (op->command) {
156     case CMD_RESET:
157         ata_reset(op->drive_g);
158         return DISK_RET_SUCCESS;
159     case CMD_ISREADY:
160         return isready(op->drive_g);
161     case CMD_FORMAT:
162     case CMD_VERIFY:
163     case CMD_SEEK:
164         return DISK_RET_SUCCESS;
165     default:
166         op->count = 0;
167         return DISK_RET_EPARAM;
168     }
169 }
170
171
172 /****************************************************************
173  * ATA send command
174  ****************************************************************/
175
176 struct ata_pio_command {
177     u8 feature;
178     u8 sector_count;
179     u8 lba_low;
180     u8 lba_mid;
181     u8 lba_high;
182     u8 device;
183     u8 command;
184
185     u8 feature2;
186     u8 sector_count2;
187     u8 lba_low2;
188     u8 lba_mid2;
189     u8 lba_high2;
190 };
191
192 // Send an ata command to the drive.
193 static int
194 send_cmd(struct drive_s *drive_g, struct ata_pio_command *cmd)
195 {
196     u8 ataid = GET_GLOBAL(drive_g->cntl_id);
197     u8 channel = ataid / 2;
198     u8 slave = ataid % 2;
199     u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
200
201     // Select device
202     int status = await_not_bsy(iobase1);
203     if (status < 0)
204         return status;
205     u8 newdh = ((cmd->device & ~ATA_CB_DH_DEV1)
206                 | (slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0));
207     u8 olddh = inb(iobase1 + ATA_CB_DH);
208     outb(newdh, iobase1 + ATA_CB_DH);
209     if ((olddh ^ newdh) & (1<<4)) {
210         // Was a device change - wait for device to become not busy.
211         status = ndelay_await_not_bsy(iobase1);
212         if (status < 0)
213             return status;
214     }
215
216     // Check for ATA_CMD_(READ|WRITE)_(SECTORS|DMA)_EXT commands.
217     if ((cmd->command & ~0x11) == ATA_CMD_READ_SECTORS_EXT) {
218         outb(cmd->feature2, iobase1 + ATA_CB_FR);
219         outb(cmd->sector_count2, iobase1 + ATA_CB_SC);
220         outb(cmd->lba_low2, iobase1 + ATA_CB_SN);
221         outb(cmd->lba_mid2, iobase1 + ATA_CB_CL);
222         outb(cmd->lba_high2, iobase1 + ATA_CB_CH);
223     }
224     outb(cmd->feature, iobase1 + ATA_CB_FR);
225     outb(cmd->sector_count, iobase1 + ATA_CB_SC);
226     outb(cmd->lba_low, iobase1 + ATA_CB_SN);
227     outb(cmd->lba_mid, iobase1 + ATA_CB_CL);
228     outb(cmd->lba_high, iobase1 + ATA_CB_CH);
229     outb(cmd->command, iobase1 + ATA_CB_CMD);
230
231     return 0;
232 }
233
234 // Wait for data after calling 'send_cmd'.
235 static int
236 ata_wait_data(u16 iobase1)
237 {
238     int status = ndelay_await_not_bsy(iobase1);
239     if (status < 0)
240         return status;
241
242     if (status & ATA_CB_STAT_ERR) {
243         dprintf(6, "send_cmd : read error (status=%02x err=%02x)\n"
244                 , status, inb(iobase1 + ATA_CB_ERR));
245         return -4;
246     }
247     if (!(status & ATA_CB_STAT_DRQ)) {
248         dprintf(6, "send_cmd : DRQ not set (status %02x)\n", status);
249         return -5;
250     }
251
252     return 0;
253 }
254
255 // Send an ata command that does not transfer any further data.
256 int
257 ata_cmd_nondata(struct drive_s *drive_g, struct ata_pio_command *cmd)
258 {
259     u8 ataid = GET_GLOBAL(drive_g->cntl_id);
260     u8 channel = ataid / 2;
261     u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
262     u16 iobase2 = GET_GLOBAL(ATA_channels[channel].iobase2);
263
264     // Disable interrupts
265     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
266
267     int ret = send_cmd(drive_g, cmd);
268     if (ret)
269         goto fail;
270     ret = ndelay_await_not_bsy(iobase1);
271     if (ret < 0)
272         goto fail;
273
274     if (ret & ATA_CB_STAT_ERR) {
275         dprintf(6, "nondata cmd : read error (status=%02x err=%02x)\n"
276                 , ret, inb(iobase1 + ATA_CB_ERR));
277         ret = -4;
278         goto fail;
279     }
280     if (ret & ATA_CB_STAT_DRQ) {
281         dprintf(6, "nondata cmd : DRQ set (status %02x)\n", ret);
282         ret = -5;
283         goto fail;
284     }
285
286 fail:
287     // Enable interrupts
288     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
289
290     return ret;
291 }
292
293
294 /****************************************************************
295  * ATA PIO transfers
296  ****************************************************************/
297
298 // Transfer 'op->count' blocks (of 'blocksize' bytes) to/from drive
299 // 'op->drive_g'.
300 static int
301 ata_pio_transfer(struct disk_op_s *op, int iswrite, int blocksize)
302 {
303     dprintf(16, "ata_pio_transfer id=%p write=%d count=%d bs=%d buf=%p\n"
304             , op->drive_g, iswrite, op->count, blocksize, op->buf_fl);
305
306     u8 ataid = GET_GLOBAL(op->drive_g->cntl_id);
307     u8 channel = ataid / 2;
308     u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
309     u16 iobase2 = GET_GLOBAL(ATA_channels[channel].iobase2);
310     int count = op->count;
311     void *buf_fl = op->buf_fl;
312     int status;
313     for (;;) {
314         if (iswrite) {
315             // Write data to controller
316             dprintf(16, "Write sector id=%p dest=%p\n", op->drive_g, buf_fl);
317             if (CONFIG_ATA_PIO32)
318                 outsl_fl(iobase1, buf_fl, blocksize / 4);
319             else
320                 outsw_fl(iobase1, buf_fl, blocksize / 2);
321         } else {
322             // Read data from controller
323             dprintf(16, "Read sector id=%p dest=%p\n", op->drive_g, buf_fl);
324             if (CONFIG_ATA_PIO32)
325                 insl_fl(iobase1, buf_fl, blocksize / 4);
326             else
327                 insw_fl(iobase1, buf_fl, blocksize / 2);
328         }
329         buf_fl += blocksize;
330
331         status = pause_await_not_bsy(iobase1, iobase2);
332         if (status < 0) {
333             // Error
334             op->count -= count;
335             return status;
336         }
337
338         count--;
339         if (!count)
340             break;
341         status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_DRQ | ATA_CB_STAT_ERR);
342         if (status != ATA_CB_STAT_DRQ) {
343             dprintf(6, "ata_pio_transfer : more sectors left (status %02x)\n"
344                     , status);
345             op->count -= count;
346             return -6;
347         }
348     }
349
350     status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_DF | ATA_CB_STAT_DRQ
351                | ATA_CB_STAT_ERR);
352     if (!iswrite)
353         status &= ~ATA_CB_STAT_DF;
354     if (status != 0) {
355         dprintf(6, "ata_pio_transfer : no sectors left (status %02x)\n", status);
356         return -7;
357     }
358
359     return 0;
360 }
361
362
363 /****************************************************************
364  * ATA DMA transfers
365  ****************************************************************/
366
367 #define BM_CMD    0
368 #define  BM_CMD_MEMWRITE  0x08
369 #define  BM_CMD_START     0x01
370 #define BM_STATUS 2
371 #define  BM_STATUS_IRQ    0x04
372 #define  BM_STATUS_ERROR  0x02
373 #define  BM_STATUS_ACTIVE 0x01
374 #define BM_TABLE  4
375
376 struct sff_dma_prd {
377     u32 buf_fl;
378     u32 count;
379 };
380
381 // Check if DMA available and setup transfer if so.
382 static int
383 ata_try_dma(struct disk_op_s *op, int iswrite, int blocksize)
384 {
385     if (! CONFIG_ATA_DMA)
386         return -1;
387     u32 dest = (u32)op->buf_fl;
388     if (dest & 1)
389         // Need minimum alignment of 1.
390         return -1;
391     u8 ataid = GET_GLOBAL(op->drive_g->cntl_id);
392     u8 channel = ataid / 2;
393     u16 iomaster = GET_GLOBAL(ATA_channels[channel].iomaster);
394     if (! iomaster)
395         return -1;
396     u32 bytes = op->count * blocksize;
397     if (! bytes)
398         return -1;
399
400     // Build PRD dma structure.
401     struct sff_dma_prd *dma = MAKE_FLATPTR(
402         get_ebda_seg()
403         , (void*)offsetof(struct extended_bios_data_area_s, extra_stack));
404     struct sff_dma_prd *origdma = dma;
405     while (bytes) {
406         if (dma >= &origdma[16])
407             // Too many descriptors..
408             return -1;
409         u32 count = bytes;
410         if (count > 0x10000)
411             count = 0x10000;
412         u32 max = 0x10000 - (dest & 0xffff);
413         if (count > max)
414             count = max;
415
416         SET_FLATPTR(dma->buf_fl, dest);
417         bytes -= count;
418         if (!bytes)
419             // Last descriptor.
420             count |= 1<<31;
421         dprintf(16, "dma@%p: %08x %08x\n", dma, dest, count);
422         dest += count;
423         SET_FLATPTR(dma->count, count);
424         dma++;
425     }
426
427     // Program bus-master controller.
428     outl((u32)origdma, iomaster + BM_TABLE);
429     u8 oldcmd = inb(iomaster + BM_CMD) & ~(BM_CMD_MEMWRITE|BM_CMD_START);
430     outb(oldcmd | (iswrite ? 0x00 : BM_CMD_MEMWRITE), iomaster + BM_CMD);
431     outb(BM_STATUS_ERROR|BM_STATUS_IRQ, iomaster + BM_STATUS);
432
433     return 0;
434 }
435
436 // Transfer data using DMA.
437 static int
438 ata_dma_transfer(struct disk_op_s *op)
439 {
440     if (! CONFIG_ATA_DMA)
441         return -1;
442     dprintf(16, "ata_dma_transfer id=%p buf=%p\n"
443             , op->drive_g, op->buf_fl);
444
445     u8 ataid = GET_GLOBAL(op->drive_g->cntl_id);
446     u8 channel = ataid / 2;
447     u16 iomaster = GET_GLOBAL(ATA_channels[channel].iomaster);
448
449     // Start bus-master controller.
450     u8 oldcmd = inb(iomaster + BM_CMD);
451     outb(oldcmd | BM_CMD_START, iomaster + BM_CMD);
452
453     u64 end = calc_future_tsc(IDE_TIMEOUT);
454     u8 status;
455     for (;;) {
456         status = inb(iomaster + BM_STATUS);
457         if (status & BM_STATUS_IRQ)
458             break;
459         // Transfer in progress
460         if (check_time(end)) {
461             // Timeout.
462             warn_timeout();
463             break;
464         }
465         yield();
466     }
467     outb(oldcmd & ~BM_CMD_START, iomaster + BM_CMD);
468
469     u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
470     u16 iobase2 = GET_GLOBAL(ATA_channels[channel].iobase2);
471     int idestatus = pause_await_not_bsy(iobase1, iobase2);
472
473     if ((status & (BM_STATUS_IRQ|BM_STATUS_ACTIVE)) == BM_STATUS_IRQ
474         && idestatus >= 0x00
475         && (idestatus & (ATA_CB_STAT_BSY | ATA_CB_STAT_DF | ATA_CB_STAT_DRQ
476                          | ATA_CB_STAT_ERR)) == 0x00)
477         // Success.
478         return 0;
479
480     dprintf(6, "IDE DMA error (dma=%x ide=%x/%x/%x)\n", status, idestatus
481             , inb(iobase2 + ATA_CB_ASTAT), inb(iobase1 + ATA_CB_ERR));
482     op->count = 0;
483     return -1;
484 }
485
486
487 /****************************************************************
488  * ATA hard drive functions
489  ****************************************************************/
490
491 // Transfer data to harddrive using PIO protocol.
492 static int
493 ata_pio_cmd_data(struct disk_op_s *op, int iswrite, struct ata_pio_command *cmd)
494 {
495     u8 ataid = GET_GLOBAL(op->drive_g->cntl_id);
496     u8 channel = ataid / 2;
497     u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
498     u16 iobase2 = GET_GLOBAL(ATA_channels[channel].iobase2);
499
500     // Disable interrupts
501     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
502
503     int ret = send_cmd(op->drive_g, cmd);
504     if (ret)
505         goto fail;
506     ret = ata_wait_data(iobase1);
507     if (ret)
508         goto fail;
509     ret = ata_pio_transfer(op, iswrite, DISK_SECTOR_SIZE);
510
511 fail:
512     // Enable interrupts
513     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
514     return ret;
515 }
516
517 // Transfer data to harddrive using DMA protocol.
518 static int
519 ata_dma_cmd_data(struct disk_op_s *op, struct ata_pio_command *cmd)
520 {
521     if (! CONFIG_ATA_DMA)
522         return -1;
523     int ret = send_cmd(op->drive_g, cmd);
524     if (ret)
525         return ret;
526     return ata_dma_transfer(op);
527 }
528
529 // Read/write count blocks from a harddrive.
530 static int
531 ata_readwrite(struct disk_op_s *op, int iswrite)
532 {
533     u64 lba = op->lba;
534
535     int usepio = ata_try_dma(op, iswrite, DISK_SECTOR_SIZE);
536
537     struct ata_pio_command cmd;
538     memset(&cmd, 0, sizeof(cmd));
539
540     if (op->count >= (1<<8) || lba + op->count >= (1<<28)) {
541         cmd.sector_count2 = op->count >> 8;
542         cmd.lba_low2 = lba >> 24;
543         cmd.lba_mid2 = lba >> 32;
544         cmd.lba_high2 = lba >> 40;
545         lba &= 0xffffff;
546
547         if (usepio)
548             cmd.command = (iswrite ? ATA_CMD_WRITE_SECTORS_EXT
549                            : ATA_CMD_READ_SECTORS_EXT);
550         else
551             cmd.command = (iswrite ? ATA_CMD_WRITE_DMA_EXT
552                            : ATA_CMD_READ_DMA_EXT);
553     } else {
554         if (usepio)
555             cmd.command = (iswrite ? ATA_CMD_WRITE_SECTORS
556                            : ATA_CMD_READ_SECTORS);
557         else
558             cmd.command = (iswrite ? ATA_CMD_WRITE_DMA
559                            : ATA_CMD_READ_DMA);
560     }
561
562     cmd.sector_count = op->count;
563     cmd.lba_low = lba;
564     cmd.lba_mid = lba >> 8;
565     cmd.lba_high = lba >> 16;
566     cmd.device = ((lba >> 24) & 0xf) | ATA_CB_DH_LBA;
567
568     int ret;
569     if (usepio)
570         ret = ata_pio_cmd_data(op, iswrite, &cmd);
571     else
572         ret = ata_dma_cmd_data(op, &cmd);
573     if (ret)
574         return DISK_RET_EBADTRACK;
575     return DISK_RET_SUCCESS;
576 }
577
578 // 16bit command demuxer for ATA harddrives.
579 int
580 process_ata_op(struct disk_op_s *op)
581 {
582     if (!CONFIG_ATA)
583         return 0;
584
585     switch (op->command) {
586     case CMD_READ:
587         return ata_readwrite(op, 0);
588     case CMD_WRITE:
589         return ata_readwrite(op, 1);
590     default:
591         return process_ata_misc_op(op);
592     }
593 }
594
595
596 /****************************************************************
597  * ATAPI functions
598  ****************************************************************/
599
600 #define CDROM_CDB_SIZE 12
601
602 // Low-level atapi command transmit function.
603 int
604 atapi_cmd_data(struct disk_op_s *op, void *cdbcmd, u16 blocksize)
605 {
606     u8 ataid = GET_GLOBAL(op->drive_g->cntl_id);
607     u8 channel = ataid / 2;
608     u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
609     u16 iobase2 = GET_GLOBAL(ATA_channels[channel].iobase2);
610
611     struct ata_pio_command cmd;
612     memset(&cmd, 0, sizeof(cmd));
613     cmd.lba_mid = blocksize;
614     cmd.lba_high = blocksize >> 8;
615     cmd.command = ATA_CMD_PACKET;
616
617     // Disable interrupts
618     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
619
620     int ret = send_cmd(op->drive_g, &cmd);
621     if (ret)
622         goto fail;
623     ret = ata_wait_data(iobase1);
624     if (ret)
625         goto fail;
626
627     // Send command to device
628     outsw_fl(iobase1, MAKE_FLATPTR(GET_SEG(SS), cdbcmd), CDROM_CDB_SIZE / 2);
629
630     int status = pause_await_not_bsy(iobase1, iobase2);
631     if (status < 0) {
632         ret = status;
633         goto fail;
634     }
635
636     if (status & ATA_CB_STAT_ERR) {
637         u8 err = inb(iobase1 + ATA_CB_ERR);
638         // skip "Not Ready"
639         if (err != 0x20)
640             dprintf(6, "send_atapi_cmd : read error (status=%02x err=%02x)\n"
641                     , status, err);
642         ret = -2;
643         goto fail;
644     }
645     if (!(status & ATA_CB_STAT_DRQ)) {
646         dprintf(6, "send_atapi_cmd : DRQ not set (status %02x)\n", status);
647         ret = -3;
648         goto fail;
649     }
650
651     ret = ata_pio_transfer(op, 0, blocksize);
652
653 fail:
654     // Enable interrupts
655     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
656     return ret;
657 }
658
659 // Read sectors from the cdrom.
660 int
661 cdrom_read(struct disk_op_s *op)
662 {
663     struct cdb_rwdata_10 cmd;
664     memset(&cmd, 0, sizeof(cmd));
665     cmd.command = CDB_CMD_READ_10;
666     cmd.lba = htonl(op->lba);
667     cmd.count = htons(op->count);
668     return atapi_cmd_data(op, &cmd, CDROM_SECTOR_SIZE);
669 }
670
671 // 16bit command demuxer for ATAPI cdroms.
672 int
673 process_atapi_op(struct disk_op_s *op)
674 {
675     int ret;
676     switch (op->command) {
677     case CMD_READ:
678         ret = cdrom_read(op);
679         if (ret)
680             return DISK_RET_EBADTRACK;
681         return DISK_RET_SUCCESS;
682     case CMD_FORMAT:
683     case CMD_WRITE:
684         return DISK_RET_EWRITEPROTECT;
685     default:
686         return process_ata_misc_op(op);
687     }
688 }
689
690
691 /****************************************************************
692  * ATA detect and init
693  ****************************************************************/
694
695 // Send an identify device or identify device packet command.
696 static int
697 send_ata_identity(struct drive_s *drive_g, u16 *buffer, int command)
698 {
699     memset(buffer, 0, DISK_SECTOR_SIZE);
700
701     struct disk_op_s dop;
702     memset(&dop, 0, sizeof(dop));
703     dop.drive_g = drive_g;
704     dop.count = 1;
705     dop.lba = 1;
706     dop.buf_fl = MAKE_FLATPTR(GET_SEG(SS), buffer);
707
708     struct ata_pio_command cmd;
709     memset(&cmd, 0, sizeof(cmd));
710     cmd.command = command;
711
712     return ata_pio_cmd_data(&dop, 0, &cmd);
713 }
714
715 // Extract the ATA/ATAPI version info.
716 static int
717 extract_version(u16 *buffer)
718 {
719     // Extract ATA/ATAPI version.
720     u16 ataversion = buffer[80];
721     u8 version;
722     for (version=15; version>0; version--)
723         if (ataversion & (1<<version))
724             break;
725     return version;
726 }
727
728 // Extract common information from IDENTIFY commands.
729 static void
730 extract_identify(struct drive_s *drive_g, u16 *buffer)
731 {
732     dprintf(3, "Identify w0=%x w2=%x\n", buffer[0], buffer[2]);
733
734     // Read model name
735     char *model = drive_g->model;
736     int maxsize = ARRAY_SIZE(drive_g->model);
737     int i;
738     for (i=0; i<maxsize/2; i++) {
739         u16 v = buffer[27+i];
740         model[i*2] = v >> 8;
741         model[i*2+1] = v & 0xff;
742     }
743     model[maxsize-1] = 0x00;
744
745     // Trim trailing spaces from model name.
746     for (i=maxsize-2; i>0 && model[i] == 0x20; i--)
747         model[i] = 0x00;
748
749     // Common flags.
750     SET_GLOBAL(drive_g->removable, (buffer[0] & 0x80) ? 1 : 0);
751     SET_GLOBAL(drive_g->cntl_info, extract_version(buffer));
752 }
753
754 // Print out a description of the given atapi drive.
755 void
756 describe_atapi(struct drive_s *drive_g)
757 {
758     u8 ataid = drive_g->cntl_id;
759     u8 channel = ataid / 2;
760     u8 slave = ataid % 2;
761     u8 version = drive_g->cntl_info;
762     int iscd = drive_g->floppy_type;
763     printf("ata%d-%d: %s ATAPI-%d %s", channel, slave
764            , drive_g->model, version
765            , (iscd ? "CD-Rom/DVD-Rom" : "Device"));
766 }
767
768 // Detect if the given drive is an atapi - initialize it if so.
769 static struct drive_s *
770 init_drive_atapi(struct drive_s *dummy, u16 *buffer)
771 {
772     // Send an IDENTIFY_DEVICE_PACKET command to device
773     int ret = send_ata_identity(dummy, buffer, ATA_CMD_IDENTIFY_PACKET_DEVICE);
774     if (ret)
775         return NULL;
776
777     // Success - setup as ATAPI.
778     struct drive_s *drive_g = malloc_fseg(sizeof(*drive_g));
779     if (! drive_g) {
780         warn_noalloc();
781         return NULL;
782     }
783     memset(drive_g, 0, sizeof(*drive_g));
784     SET_GLOBAL(drive_g->cntl_id, dummy->cntl_id);
785     extract_identify(drive_g, buffer);
786     SET_GLOBAL(drive_g->type, DTYPE_ATAPI);
787     SET_GLOBAL(drive_g->blksize, CDROM_SECTOR_SIZE);
788     SET_GLOBAL(drive_g->sectors, (u64)-1);
789     u8 iscd = ((buffer[0] >> 8) & 0x1f) == 0x05;
790     SET_GLOBAL(drive_g->floppy_type, iscd);
791
792     // fill cdidmap
793     if (iscd)
794         map_cd_drive(drive_g);
795
796     return drive_g;
797 }
798
799 // Print out a description of the given ata drive.
800 void
801 describe_ata(struct drive_s *drive_g)
802 {
803     u8 ataid = drive_g->cntl_id;
804     u8 channel = ataid / 2;
805     u8 slave = ataid % 2;
806     u64 sectors = drive_g->sectors;
807     u8 version = drive_g->cntl_info;
808     char *model = drive_g->model;
809     printf("ata%d-%d: %s ATA-%d Hard-Disk", channel, slave, model, version);
810     u64 sizeinmb = sectors >> 11;
811     if (sizeinmb < (1 << 16))
812         printf(" (%u MiBytes)", (u32)sizeinmb);
813     else
814         printf(" (%u GiBytes)", (u32)(sizeinmb >> 10));
815 }
816
817 // Detect if the given drive is a regular ata drive - initialize it if so.
818 static struct drive_s *
819 init_drive_ata(struct drive_s *dummy, u16 *buffer)
820 {
821     // Send an IDENTIFY_DEVICE command to device
822     int ret = send_ata_identity(dummy, buffer, ATA_CMD_IDENTIFY_DEVICE);
823     if (ret)
824         return NULL;
825
826     // Success - setup as ATA.
827     struct drive_s *drive_g = malloc_fseg(sizeof(*drive_g));
828     if (! drive_g) {
829         warn_noalloc();
830         return NULL;
831     }
832     memset(drive_g, 0, sizeof(*drive_g));
833     SET_GLOBAL(drive_g->cntl_id, dummy->cntl_id);
834     extract_identify(drive_g, buffer);
835     SET_GLOBAL(drive_g->type, DTYPE_ATA);
836     SET_GLOBAL(drive_g->blksize, DISK_SECTOR_SIZE);
837
838     SET_GLOBAL(drive_g->pchs.cylinders, buffer[1]);
839     SET_GLOBAL(drive_g->pchs.heads, buffer[3]);
840     SET_GLOBAL(drive_g->pchs.spt, buffer[6]);
841
842     u64 sectors;
843     if (buffer[83] & (1 << 10)) // word 83 - lba48 support
844         sectors = *(u64*)&buffer[100]; // word 100-103
845     else
846         sectors = *(u32*)&buffer[60]; // word 60 and word 61
847     SET_GLOBAL(drive_g->sectors, sectors);
848
849     // Setup disk geometry translation.
850     setup_translation(drive_g);
851
852     // Register with bcv system.
853     add_bcv_internal(drive_g);
854
855     return drive_g;
856 }
857
858 static u64 SpinupEnd;
859
860 // Wait for non-busy status and check for "floating bus" condition.
861 static int
862 powerup_await_non_bsy(u16 base)
863 {
864     u8 orstatus = 0;
865     u8 status;
866     for (;;) {
867         status = inb(base+ATA_CB_STAT);
868         if (!(status & ATA_CB_STAT_BSY))
869             break;
870         orstatus |= status;
871         if (orstatus == 0xff) {
872             dprintf(1, "powerup IDE floating\n");
873             return orstatus;
874         }
875         if (check_time(SpinupEnd)) {
876             warn_timeout();
877             return -1;
878         }
879         yield();
880     }
881     dprintf(6, "powerup iobase=%x st=%x\n", base, status);
882     return status;
883 }
884
885 // Detect any drives attached to a given controller.
886 static void
887 ata_detect(void *data)
888 {
889     struct ata_channel_s *atachannel = data;
890     int startid = (atachannel - ATA_channels) * 2;
891     struct drive_s dummy;
892     memset(&dummy, 0, sizeof(dummy));
893     // Device detection
894     int ataid, last_reset_ataid=-1;
895     for (ataid=startid; ataid<startid+2; ataid++) {
896         u8 channel = ataid / 2;
897         u8 slave = ataid % 2;
898
899         u16 iobase1 = GET_GLOBAL(ATA_channels[channel].iobase1);
900         if (!iobase1)
901             break;
902
903         // Wait for not-bsy.
904         int status = powerup_await_non_bsy(iobase1);
905         if (status < 0)
906             continue;
907         u8 newdh = slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0;
908         outb(newdh, iobase1+ATA_CB_DH);
909         ndelay(400);
910         status = powerup_await_non_bsy(iobase1);
911         if (status < 0)
912             continue;
913
914         // Check if ioport registers look valid.
915         outb(newdh, iobase1+ATA_CB_DH);
916         u8 dh = inb(iobase1+ATA_CB_DH);
917         outb(0x55, iobase1+ATA_CB_SC);
918         outb(0xaa, iobase1+ATA_CB_SN);
919         u8 sc = inb(iobase1+ATA_CB_SC);
920         u8 sn = inb(iobase1+ATA_CB_SN);
921         dprintf(6, "ata_detect ataid=%d sc=%x sn=%x dh=%x\n"
922                 , ataid, sc, sn, dh);
923         if (sc != 0x55 || sn != 0xaa || dh != newdh)
924             continue;
925
926         // Prepare new drive.
927         dummy.cntl_id = ataid;
928
929         // reset the channel
930         if (slave && ataid == last_reset_ataid + 1) {
931             // The drive was just reset - no need to reset it again.
932         } else {
933             ata_reset(&dummy);
934             last_reset_ataid = ataid;
935         }
936
937         // check for ATAPI
938         u16 buffer[256];
939         struct drive_s *drive_g = init_drive_atapi(&dummy, buffer);
940         if (!drive_g) {
941             // Didn't find an ATAPI drive - look for ATA drive.
942             u8 st = inb(iobase1+ATA_CB_STAT);
943             if (!st)
944                 // Status not set - can't be a valid drive.
945                 continue;
946
947             // Wait for RDY.
948             int ret = await_rdy(iobase1);
949             if (ret < 0)
950                 continue;
951
952             // check for ATA.
953             drive_g = init_drive_ata(&dummy, buffer);
954             if (!drive_g)
955                 // No ATA drive found
956                 continue;
957         }
958
959         u16 resetresult = buffer[93];
960         dprintf(6, "ata_detect resetresult=%04x\n", resetresult);
961         if (!slave && (resetresult & 0xdf61) == 0x4041)
962             // resetresult looks valid and device 0 is responding to
963             // device 1 requests - device 1 must not be present - skip
964             // detection.
965             ataid++;
966     }
967 }
968
969 // Initialize an ata controller and detect its drives.
970 static void
971 init_controller(struct ata_channel_s *atachannel
972                 , int bdf, int irq, u32 port1, u32 port2, u32 master)
973 {
974     SET_GLOBAL(atachannel->irq, irq);
975     SET_GLOBAL(atachannel->pci_bdf, bdf);
976     SET_GLOBAL(atachannel->iobase1, port1);
977     SET_GLOBAL(atachannel->iobase2, port2);
978     SET_GLOBAL(atachannel->iomaster, master);
979     dprintf(1, "ATA controller %d at %x/%x/%x (irq %d dev %x)\n"
980             , atachannel - ATA_channels, port1, port2, master, irq, bdf);
981     run_thread(ata_detect, atachannel);
982 }
983
984 #define IRQ_ATA1 14
985 #define IRQ_ATA2 15
986
987 // Locate and init ata controllers.
988 static void
989 ata_init(void)
990 {
991     // Scan PCI bus for ATA adapters
992     int count=0, pcicount=0;
993     int bdf, max;
994     foreachpci(bdf, max) {
995         pcicount++;
996         if (pci_config_readw(bdf, PCI_CLASS_DEVICE) != PCI_CLASS_STORAGE_IDE)
997             continue;
998         if (count >= ARRAY_SIZE(ATA_channels))
999             break;
1000
1001         u8 pciirq = pci_config_readb(bdf, PCI_INTERRUPT_LINE);
1002         u8 prog_if = pci_config_readb(bdf, PCI_CLASS_PROG);
1003         int master = 0;
1004         if (CONFIG_ATA_DMA && prog_if & 0x80) {
1005             // Check for bus-mastering.
1006             u32 bar = pci_config_readl(bdf, PCI_BASE_ADDRESS_4);
1007             if (bar & PCI_BASE_ADDRESS_SPACE_IO) {
1008                 master = bar & PCI_BASE_ADDRESS_IO_MASK;
1009                 pci_config_maskw(bdf, PCI_COMMAND, 0, PCI_COMMAND_MASTER);
1010             }
1011         }
1012
1013         u32 port1, port2, irq;
1014         if (prog_if & 1) {
1015             port1 = pci_config_readl(bdf, PCI_BASE_ADDRESS_0) & ~3;
1016             port2 = pci_config_readl(bdf, PCI_BASE_ADDRESS_1) & ~3;
1017             irq = pciirq;
1018         } else {
1019             port1 = PORT_ATA1_CMD_BASE;
1020             port2 = PORT_ATA1_CTRL_BASE;
1021             irq = IRQ_ATA1;
1022         }
1023         init_controller(&ATA_channels[count], bdf, irq, port1, port2, master);
1024         count++;
1025
1026         if (prog_if & 4) {
1027             port1 = pci_config_readl(bdf, PCI_BASE_ADDRESS_2) & ~3;
1028             port2 = pci_config_readl(bdf, PCI_BASE_ADDRESS_3) & ~3;
1029             irq = pciirq;
1030         } else {
1031             port1 = PORT_ATA2_CMD_BASE;
1032             port2 = PORT_ATA2_CTRL_BASE;
1033             irq = IRQ_ATA2;
1034         }
1035         init_controller(&ATA_channels[count], bdf, irq, port1, port2
1036                         , master ? master + 8 : 0);
1037         count++;
1038     }
1039
1040     if (!CONFIG_COREBOOT && !pcicount && ARRAY_SIZE(ATA_channels) >= 2) {
1041         // No PCI devices found - probably a QEMU "-M isapc" machine.
1042         // Try using ISA ports for ATA controllers.
1043         init_controller(&ATA_channels[0], -1, IRQ_ATA1
1044                         , PORT_ATA1_CMD_BASE, PORT_ATA1_CTRL_BASE, 0);
1045         init_controller(&ATA_channels[1], -1, IRQ_ATA2
1046                         , PORT_ATA2_CMD_BASE, PORT_ATA2_CTRL_BASE, 0);
1047     }
1048 }
1049
1050 void
1051 ata_setup(void)
1052 {
1053     ASSERT32FLAT();
1054     if (!CONFIG_ATA)
1055         return;
1056
1057     dprintf(3, "init hard drives\n");
1058
1059     SpinupEnd = calc_future_tsc(IDE_TIMEOUT);
1060     ata_init();
1061
1062     SET_BDA(disk_control_byte, 0xc0);
1063
1064     enable_hwirq(14, entry_76);
1065 }