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